xref: /openbmc/linux/drivers/block/nbd.c (revision 50dc9a85)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * Network block device - make block devices work over TCP
4  *
5  * Note that you can not swap over this thing, yet. Seems to work but
6  * deadlocks sometimes - you can not swap over TCP in general.
7  *
8  * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
9  * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
10  *
11  * (part of code stolen from loop.c)
12  */
13 
14 #include <linux/major.h>
15 
16 #include <linux/blkdev.h>
17 #include <linux/module.h>
18 #include <linux/init.h>
19 #include <linux/sched.h>
20 #include <linux/sched/mm.h>
21 #include <linux/fs.h>
22 #include <linux/bio.h>
23 #include <linux/stat.h>
24 #include <linux/errno.h>
25 #include <linux/file.h>
26 #include <linux/ioctl.h>
27 #include <linux/mutex.h>
28 #include <linux/compiler.h>
29 #include <linux/completion.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <net/sock.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
39 
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
42 
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
46 
47 #define CREATE_TRACE_POINTS
48 #include <trace/events/nbd.h>
49 
50 static DEFINE_IDR(nbd_index_idr);
51 static DEFINE_MUTEX(nbd_index_mutex);
52 static struct workqueue_struct *nbd_del_wq;
53 static int nbd_total_devices = 0;
54 
55 struct nbd_sock {
56 	struct socket *sock;
57 	struct mutex tx_lock;
58 	struct request *pending;
59 	int sent;
60 	bool dead;
61 	int fallback_index;
62 	int cookie;
63 };
64 
65 struct recv_thread_args {
66 	struct work_struct work;
67 	struct nbd_device *nbd;
68 	int index;
69 };
70 
71 struct link_dead_args {
72 	struct work_struct work;
73 	int index;
74 };
75 
76 #define NBD_RT_TIMEDOUT			0
77 #define NBD_RT_DISCONNECT_REQUESTED	1
78 #define NBD_RT_DISCONNECTED		2
79 #define NBD_RT_HAS_PID_FILE		3
80 #define NBD_RT_HAS_CONFIG_REF		4
81 #define NBD_RT_BOUND			5
82 #define NBD_RT_DISCONNECT_ON_CLOSE	6
83 #define NBD_RT_HAS_BACKEND_FILE		7
84 
85 #define NBD_DESTROY_ON_DISCONNECT	0
86 #define NBD_DISCONNECT_REQUESTED	1
87 
88 struct nbd_config {
89 	u32 flags;
90 	unsigned long runtime_flags;
91 	u64 dead_conn_timeout;
92 
93 	struct nbd_sock **socks;
94 	int num_connections;
95 	atomic_t live_connections;
96 	wait_queue_head_t conn_wait;
97 
98 	atomic_t recv_threads;
99 	wait_queue_head_t recv_wq;
100 	unsigned int blksize_bits;
101 	loff_t bytesize;
102 #if IS_ENABLED(CONFIG_DEBUG_FS)
103 	struct dentry *dbg_dir;
104 #endif
105 };
106 
107 static inline unsigned int nbd_blksize(struct nbd_config *config)
108 {
109 	return 1u << config->blksize_bits;
110 }
111 
112 struct nbd_device {
113 	struct blk_mq_tag_set tag_set;
114 
115 	int index;
116 	refcount_t config_refs;
117 	refcount_t refs;
118 	struct nbd_config *config;
119 	struct mutex config_lock;
120 	struct gendisk *disk;
121 	struct workqueue_struct *recv_workq;
122 	struct work_struct remove_work;
123 
124 	struct list_head list;
125 	struct task_struct *task_recv;
126 	struct task_struct *task_setup;
127 
128 	unsigned long flags;
129 
130 	char *backend;
131 };
132 
133 #define NBD_CMD_REQUEUED	1
134 
135 struct nbd_cmd {
136 	struct nbd_device *nbd;
137 	struct mutex lock;
138 	int index;
139 	int cookie;
140 	int retries;
141 	blk_status_t status;
142 	unsigned long flags;
143 	u32 cmd_cookie;
144 };
145 
146 #if IS_ENABLED(CONFIG_DEBUG_FS)
147 static struct dentry *nbd_dbg_dir;
148 #endif
149 
150 #define nbd_name(nbd) ((nbd)->disk->disk_name)
151 
152 #define NBD_MAGIC 0x68797548
153 
154 #define NBD_DEF_BLKSIZE_BITS 10
155 
156 static unsigned int nbds_max = 16;
157 static int max_part = 16;
158 static int part_shift;
159 
160 static int nbd_dev_dbg_init(struct nbd_device *nbd);
161 static void nbd_dev_dbg_close(struct nbd_device *nbd);
162 static void nbd_config_put(struct nbd_device *nbd);
163 static void nbd_connect_reply(struct genl_info *info, int index);
164 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
165 static void nbd_dead_link_work(struct work_struct *work);
166 static void nbd_disconnect_and_put(struct nbd_device *nbd);
167 
168 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
169 {
170 	return disk_to_dev(nbd->disk);
171 }
172 
173 static void nbd_requeue_cmd(struct nbd_cmd *cmd)
174 {
175 	struct request *req = blk_mq_rq_from_pdu(cmd);
176 
177 	if (!test_and_set_bit(NBD_CMD_REQUEUED, &cmd->flags))
178 		blk_mq_requeue_request(req, true);
179 }
180 
181 #define NBD_COOKIE_BITS 32
182 
183 static u64 nbd_cmd_handle(struct nbd_cmd *cmd)
184 {
185 	struct request *req = blk_mq_rq_from_pdu(cmd);
186 	u32 tag = blk_mq_unique_tag(req);
187 	u64 cookie = cmd->cmd_cookie;
188 
189 	return (cookie << NBD_COOKIE_BITS) | tag;
190 }
191 
192 static u32 nbd_handle_to_tag(u64 handle)
193 {
194 	return (u32)handle;
195 }
196 
197 static u32 nbd_handle_to_cookie(u64 handle)
198 {
199 	return (u32)(handle >> NBD_COOKIE_BITS);
200 }
201 
202 static const char *nbdcmd_to_ascii(int cmd)
203 {
204 	switch (cmd) {
205 	case  NBD_CMD_READ: return "read";
206 	case NBD_CMD_WRITE: return "write";
207 	case  NBD_CMD_DISC: return "disconnect";
208 	case NBD_CMD_FLUSH: return "flush";
209 	case  NBD_CMD_TRIM: return "trim/discard";
210 	}
211 	return "invalid";
212 }
213 
214 static ssize_t pid_show(struct device *dev,
215 			struct device_attribute *attr, char *buf)
216 {
217 	struct gendisk *disk = dev_to_disk(dev);
218 	struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
219 
220 	return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
221 }
222 
223 static const struct device_attribute pid_attr = {
224 	.attr = { .name = "pid", .mode = 0444},
225 	.show = pid_show,
226 };
227 
228 static ssize_t backend_show(struct device *dev,
229 		struct device_attribute *attr, char *buf)
230 {
231 	struct gendisk *disk = dev_to_disk(dev);
232 	struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
233 
234 	return sprintf(buf, "%s\n", nbd->backend ?: "");
235 }
236 
237 static const struct device_attribute backend_attr = {
238 	.attr = { .name = "backend", .mode = 0444},
239 	.show = backend_show,
240 };
241 
242 static void nbd_dev_remove(struct nbd_device *nbd)
243 {
244 	struct gendisk *disk = nbd->disk;
245 
246 	del_gendisk(disk);
247 	blk_cleanup_disk(disk);
248 	blk_mq_free_tag_set(&nbd->tag_set);
249 
250 	/*
251 	 * Remove from idr after del_gendisk() completes, so if the same ID is
252 	 * reused, the following add_disk() will succeed.
253 	 */
254 	mutex_lock(&nbd_index_mutex);
255 	idr_remove(&nbd_index_idr, nbd->index);
256 	mutex_unlock(&nbd_index_mutex);
257 
258 	kfree(nbd);
259 }
260 
261 static void nbd_dev_remove_work(struct work_struct *work)
262 {
263 	nbd_dev_remove(container_of(work, struct nbd_device, remove_work));
264 }
265 
266 static void nbd_put(struct nbd_device *nbd)
267 {
268 	if (!refcount_dec_and_test(&nbd->refs))
269 		return;
270 
271 	/* Call del_gendisk() asynchrounously to prevent deadlock */
272 	if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
273 		queue_work(nbd_del_wq, &nbd->remove_work);
274 	else
275 		nbd_dev_remove(nbd);
276 }
277 
278 static int nbd_disconnected(struct nbd_config *config)
279 {
280 	return test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags) ||
281 		test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
282 }
283 
284 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
285 				int notify)
286 {
287 	if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
288 		struct link_dead_args *args;
289 		args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
290 		if (args) {
291 			INIT_WORK(&args->work, nbd_dead_link_work);
292 			args->index = nbd->index;
293 			queue_work(system_wq, &args->work);
294 		}
295 	}
296 	if (!nsock->dead) {
297 		kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
298 		if (atomic_dec_return(&nbd->config->live_connections) == 0) {
299 			if (test_and_clear_bit(NBD_RT_DISCONNECT_REQUESTED,
300 					       &nbd->config->runtime_flags)) {
301 				set_bit(NBD_RT_DISCONNECTED,
302 					&nbd->config->runtime_flags);
303 				dev_info(nbd_to_dev(nbd),
304 					"Disconnected due to user request.\n");
305 			}
306 		}
307 	}
308 	nsock->dead = true;
309 	nsock->pending = NULL;
310 	nsock->sent = 0;
311 }
312 
313 static void nbd_size_clear(struct nbd_device *nbd)
314 {
315 	if (nbd->config->bytesize) {
316 		set_capacity(nbd->disk, 0);
317 		kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
318 	}
319 }
320 
321 static int nbd_set_size(struct nbd_device *nbd, loff_t bytesize,
322 		loff_t blksize)
323 {
324 	if (!blksize)
325 		blksize = 1u << NBD_DEF_BLKSIZE_BITS;
326 	if (blksize < 512 || blksize > PAGE_SIZE || !is_power_of_2(blksize))
327 		return -EINVAL;
328 
329 	nbd->config->bytesize = bytesize;
330 	nbd->config->blksize_bits = __ffs(blksize);
331 
332 	if (!nbd->task_recv)
333 		return 0;
334 
335 	if (nbd->config->flags & NBD_FLAG_SEND_TRIM) {
336 		nbd->disk->queue->limits.discard_granularity = blksize;
337 		nbd->disk->queue->limits.discard_alignment = blksize;
338 		blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
339 	}
340 	blk_queue_logical_block_size(nbd->disk->queue, blksize);
341 	blk_queue_physical_block_size(nbd->disk->queue, blksize);
342 
343 	if (max_part)
344 		set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
345 	if (!set_capacity_and_notify(nbd->disk, bytesize >> 9))
346 		kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
347 	return 0;
348 }
349 
350 static void nbd_complete_rq(struct request *req)
351 {
352 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
353 
354 	dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", req,
355 		cmd->status ? "failed" : "done");
356 
357 	blk_mq_end_request(req, cmd->status);
358 }
359 
360 /*
361  * Forcibly shutdown the socket causing all listeners to error
362  */
363 static void sock_shutdown(struct nbd_device *nbd)
364 {
365 	struct nbd_config *config = nbd->config;
366 	int i;
367 
368 	if (config->num_connections == 0)
369 		return;
370 	if (test_and_set_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
371 		return;
372 
373 	for (i = 0; i < config->num_connections; i++) {
374 		struct nbd_sock *nsock = config->socks[i];
375 		mutex_lock(&nsock->tx_lock);
376 		nbd_mark_nsock_dead(nbd, nsock, 0);
377 		mutex_unlock(&nsock->tx_lock);
378 	}
379 	dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
380 }
381 
382 static u32 req_to_nbd_cmd_type(struct request *req)
383 {
384 	switch (req_op(req)) {
385 	case REQ_OP_DISCARD:
386 		return NBD_CMD_TRIM;
387 	case REQ_OP_FLUSH:
388 		return NBD_CMD_FLUSH;
389 	case REQ_OP_WRITE:
390 		return NBD_CMD_WRITE;
391 	case REQ_OP_READ:
392 		return NBD_CMD_READ;
393 	default:
394 		return U32_MAX;
395 	}
396 }
397 
398 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
399 						 bool reserved)
400 {
401 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
402 	struct nbd_device *nbd = cmd->nbd;
403 	struct nbd_config *config;
404 
405 	if (!mutex_trylock(&cmd->lock))
406 		return BLK_EH_RESET_TIMER;
407 
408 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
409 		cmd->status = BLK_STS_TIMEOUT;
410 		mutex_unlock(&cmd->lock);
411 		goto done;
412 	}
413 	config = nbd->config;
414 
415 	if (config->num_connections > 1 ||
416 	    (config->num_connections == 1 && nbd->tag_set.timeout)) {
417 		dev_err_ratelimited(nbd_to_dev(nbd),
418 				    "Connection timed out, retrying (%d/%d alive)\n",
419 				    atomic_read(&config->live_connections),
420 				    config->num_connections);
421 		/*
422 		 * Hooray we have more connections, requeue this IO, the submit
423 		 * path will put it on a real connection. Or if only one
424 		 * connection is configured, the submit path will wait util
425 		 * a new connection is reconfigured or util dead timeout.
426 		 */
427 		if (config->socks) {
428 			if (cmd->index < config->num_connections) {
429 				struct nbd_sock *nsock =
430 					config->socks[cmd->index];
431 				mutex_lock(&nsock->tx_lock);
432 				/* We can have multiple outstanding requests, so
433 				 * we don't want to mark the nsock dead if we've
434 				 * already reconnected with a new socket, so
435 				 * only mark it dead if its the same socket we
436 				 * were sent out on.
437 				 */
438 				if (cmd->cookie == nsock->cookie)
439 					nbd_mark_nsock_dead(nbd, nsock, 1);
440 				mutex_unlock(&nsock->tx_lock);
441 			}
442 			mutex_unlock(&cmd->lock);
443 			nbd_requeue_cmd(cmd);
444 			nbd_config_put(nbd);
445 			return BLK_EH_DONE;
446 		}
447 	}
448 
449 	if (!nbd->tag_set.timeout) {
450 		/*
451 		 * Userspace sets timeout=0 to disable socket disconnection,
452 		 * so just warn and reset the timer.
453 		 */
454 		struct nbd_sock *nsock = config->socks[cmd->index];
455 		cmd->retries++;
456 		dev_info(nbd_to_dev(nbd), "Possible stuck request %p: control (%s@%llu,%uB). Runtime %u seconds\n",
457 			req, nbdcmd_to_ascii(req_to_nbd_cmd_type(req)),
458 			(unsigned long long)blk_rq_pos(req) << 9,
459 			blk_rq_bytes(req), (req->timeout / HZ) * cmd->retries);
460 
461 		mutex_lock(&nsock->tx_lock);
462 		if (cmd->cookie != nsock->cookie) {
463 			nbd_requeue_cmd(cmd);
464 			mutex_unlock(&nsock->tx_lock);
465 			mutex_unlock(&cmd->lock);
466 			nbd_config_put(nbd);
467 			return BLK_EH_DONE;
468 		}
469 		mutex_unlock(&nsock->tx_lock);
470 		mutex_unlock(&cmd->lock);
471 		nbd_config_put(nbd);
472 		return BLK_EH_RESET_TIMER;
473 	}
474 
475 	dev_err_ratelimited(nbd_to_dev(nbd), "Connection timed out\n");
476 	set_bit(NBD_RT_TIMEDOUT, &config->runtime_flags);
477 	cmd->status = BLK_STS_IOERR;
478 	mutex_unlock(&cmd->lock);
479 	sock_shutdown(nbd);
480 	nbd_config_put(nbd);
481 done:
482 	blk_mq_complete_request(req);
483 	return BLK_EH_DONE;
484 }
485 
486 /*
487  *  Send or receive packet.
488  */
489 static int sock_xmit(struct nbd_device *nbd, int index, int send,
490 		     struct iov_iter *iter, int msg_flags, int *sent)
491 {
492 	struct nbd_config *config = nbd->config;
493 	struct socket *sock = config->socks[index]->sock;
494 	int result;
495 	struct msghdr msg;
496 	unsigned int noreclaim_flag;
497 
498 	if (unlikely(!sock)) {
499 		dev_err_ratelimited(disk_to_dev(nbd->disk),
500 			"Attempted %s on closed socket in sock_xmit\n",
501 			(send ? "send" : "recv"));
502 		return -EINVAL;
503 	}
504 
505 	msg.msg_iter = *iter;
506 
507 	noreclaim_flag = memalloc_noreclaim_save();
508 	do {
509 		sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
510 		msg.msg_name = NULL;
511 		msg.msg_namelen = 0;
512 		msg.msg_control = NULL;
513 		msg.msg_controllen = 0;
514 		msg.msg_flags = msg_flags | MSG_NOSIGNAL;
515 
516 		if (send)
517 			result = sock_sendmsg(sock, &msg);
518 		else
519 			result = sock_recvmsg(sock, &msg, msg.msg_flags);
520 
521 		if (result <= 0) {
522 			if (result == 0)
523 				result = -EPIPE; /* short read */
524 			break;
525 		}
526 		if (sent)
527 			*sent += result;
528 	} while (msg_data_left(&msg));
529 
530 	memalloc_noreclaim_restore(noreclaim_flag);
531 
532 	return result;
533 }
534 
535 /*
536  * Different settings for sk->sk_sndtimeo can result in different return values
537  * if there is a signal pending when we enter sendmsg, because reasons?
538  */
539 static inline int was_interrupted(int result)
540 {
541 	return result == -ERESTARTSYS || result == -EINTR;
542 }
543 
544 /* always call with the tx_lock held */
545 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
546 {
547 	struct request *req = blk_mq_rq_from_pdu(cmd);
548 	struct nbd_config *config = nbd->config;
549 	struct nbd_sock *nsock = config->socks[index];
550 	int result;
551 	struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
552 	struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
553 	struct iov_iter from;
554 	unsigned long size = blk_rq_bytes(req);
555 	struct bio *bio;
556 	u64 handle;
557 	u32 type;
558 	u32 nbd_cmd_flags = 0;
559 	int sent = nsock->sent, skip = 0;
560 
561 	iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
562 
563 	type = req_to_nbd_cmd_type(req);
564 	if (type == U32_MAX)
565 		return -EIO;
566 
567 	if (rq_data_dir(req) == WRITE &&
568 	    (config->flags & NBD_FLAG_READ_ONLY)) {
569 		dev_err_ratelimited(disk_to_dev(nbd->disk),
570 				    "Write on read-only\n");
571 		return -EIO;
572 	}
573 
574 	if (req->cmd_flags & REQ_FUA)
575 		nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
576 
577 	/* We did a partial send previously, and we at least sent the whole
578 	 * request struct, so just go and send the rest of the pages in the
579 	 * request.
580 	 */
581 	if (sent) {
582 		if (sent >= sizeof(request)) {
583 			skip = sent - sizeof(request);
584 
585 			/* initialize handle for tracing purposes */
586 			handle = nbd_cmd_handle(cmd);
587 
588 			goto send_pages;
589 		}
590 		iov_iter_advance(&from, sent);
591 	} else {
592 		cmd->cmd_cookie++;
593 	}
594 	cmd->index = index;
595 	cmd->cookie = nsock->cookie;
596 	cmd->retries = 0;
597 	request.type = htonl(type | nbd_cmd_flags);
598 	if (type != NBD_CMD_FLUSH) {
599 		request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
600 		request.len = htonl(size);
601 	}
602 	handle = nbd_cmd_handle(cmd);
603 	memcpy(request.handle, &handle, sizeof(handle));
604 
605 	trace_nbd_send_request(&request, nbd->index, blk_mq_rq_from_pdu(cmd));
606 
607 	dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
608 		req, nbdcmd_to_ascii(type),
609 		(unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
610 	result = sock_xmit(nbd, index, 1, &from,
611 			(type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
612 	trace_nbd_header_sent(req, handle);
613 	if (result <= 0) {
614 		if (was_interrupted(result)) {
615 			/* If we havne't sent anything we can just return BUSY,
616 			 * however if we have sent something we need to make
617 			 * sure we only allow this req to be sent until we are
618 			 * completely done.
619 			 */
620 			if (sent) {
621 				nsock->pending = req;
622 				nsock->sent = sent;
623 			}
624 			set_bit(NBD_CMD_REQUEUED, &cmd->flags);
625 			return BLK_STS_RESOURCE;
626 		}
627 		dev_err_ratelimited(disk_to_dev(nbd->disk),
628 			"Send control failed (result %d)\n", result);
629 		return -EAGAIN;
630 	}
631 send_pages:
632 	if (type != NBD_CMD_WRITE)
633 		goto out;
634 
635 	bio = req->bio;
636 	while (bio) {
637 		struct bio *next = bio->bi_next;
638 		struct bvec_iter iter;
639 		struct bio_vec bvec;
640 
641 		bio_for_each_segment(bvec, bio, iter) {
642 			bool is_last = !next && bio_iter_last(bvec, iter);
643 			int flags = is_last ? 0 : MSG_MORE;
644 
645 			dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
646 				req, bvec.bv_len);
647 			iov_iter_bvec(&from, WRITE, &bvec, 1, bvec.bv_len);
648 			if (skip) {
649 				if (skip >= iov_iter_count(&from)) {
650 					skip -= iov_iter_count(&from);
651 					continue;
652 				}
653 				iov_iter_advance(&from, skip);
654 				skip = 0;
655 			}
656 			result = sock_xmit(nbd, index, 1, &from, flags, &sent);
657 			if (result <= 0) {
658 				if (was_interrupted(result)) {
659 					/* We've already sent the header, we
660 					 * have no choice but to set pending and
661 					 * return BUSY.
662 					 */
663 					nsock->pending = req;
664 					nsock->sent = sent;
665 					set_bit(NBD_CMD_REQUEUED, &cmd->flags);
666 					return BLK_STS_RESOURCE;
667 				}
668 				dev_err(disk_to_dev(nbd->disk),
669 					"Send data failed (result %d)\n",
670 					result);
671 				return -EAGAIN;
672 			}
673 			/*
674 			 * The completion might already have come in,
675 			 * so break for the last one instead of letting
676 			 * the iterator do it. This prevents use-after-free
677 			 * of the bio.
678 			 */
679 			if (is_last)
680 				break;
681 		}
682 		bio = next;
683 	}
684 out:
685 	trace_nbd_payload_sent(req, handle);
686 	nsock->pending = NULL;
687 	nsock->sent = 0;
688 	return 0;
689 }
690 
691 /* NULL returned = something went wrong, inform userspace */
692 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
693 {
694 	struct nbd_config *config = nbd->config;
695 	int result;
696 	struct nbd_reply reply;
697 	struct nbd_cmd *cmd;
698 	struct request *req = NULL;
699 	u64 handle;
700 	u16 hwq;
701 	u32 tag;
702 	struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
703 	struct iov_iter to;
704 	int ret = 0;
705 
706 	reply.magic = 0;
707 	iov_iter_kvec(&to, READ, &iov, 1, sizeof(reply));
708 	result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
709 	if (result <= 0) {
710 		if (!nbd_disconnected(config))
711 			dev_err(disk_to_dev(nbd->disk),
712 				"Receive control failed (result %d)\n", result);
713 		return ERR_PTR(result);
714 	}
715 
716 	if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
717 		dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
718 				(unsigned long)ntohl(reply.magic));
719 		return ERR_PTR(-EPROTO);
720 	}
721 
722 	memcpy(&handle, reply.handle, sizeof(handle));
723 	tag = nbd_handle_to_tag(handle);
724 	hwq = blk_mq_unique_tag_to_hwq(tag);
725 	if (hwq < nbd->tag_set.nr_hw_queues)
726 		req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
727 				       blk_mq_unique_tag_to_tag(tag));
728 	if (!req || !blk_mq_request_started(req)) {
729 		dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
730 			tag, req);
731 		return ERR_PTR(-ENOENT);
732 	}
733 	trace_nbd_header_received(req, handle);
734 	cmd = blk_mq_rq_to_pdu(req);
735 
736 	mutex_lock(&cmd->lock);
737 	if (cmd->cmd_cookie != nbd_handle_to_cookie(handle)) {
738 		dev_err(disk_to_dev(nbd->disk), "Double reply on req %p, cmd_cookie %u, handle cookie %u\n",
739 			req, cmd->cmd_cookie, nbd_handle_to_cookie(handle));
740 		ret = -ENOENT;
741 		goto out;
742 	}
743 	if (cmd->status != BLK_STS_OK) {
744 		dev_err(disk_to_dev(nbd->disk), "Command already handled %p\n",
745 			req);
746 		ret = -ENOENT;
747 		goto out;
748 	}
749 	if (test_bit(NBD_CMD_REQUEUED, &cmd->flags)) {
750 		dev_err(disk_to_dev(nbd->disk), "Raced with timeout on req %p\n",
751 			req);
752 		ret = -ENOENT;
753 		goto out;
754 	}
755 	if (ntohl(reply.error)) {
756 		dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
757 			ntohl(reply.error));
758 		cmd->status = BLK_STS_IOERR;
759 		goto out;
760 	}
761 
762 	dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
763 	if (rq_data_dir(req) != WRITE) {
764 		struct req_iterator iter;
765 		struct bio_vec bvec;
766 
767 		rq_for_each_segment(bvec, req, iter) {
768 			iov_iter_bvec(&to, READ, &bvec, 1, bvec.bv_len);
769 			result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
770 			if (result <= 0) {
771 				dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
772 					result);
773 				/*
774 				 * If we've disconnected, we need to make sure we
775 				 * complete this request, otherwise error out
776 				 * and let the timeout stuff handle resubmitting
777 				 * this request onto another connection.
778 				 */
779 				if (nbd_disconnected(config)) {
780 					cmd->status = BLK_STS_IOERR;
781 					goto out;
782 				}
783 				ret = -EIO;
784 				goto out;
785 			}
786 			dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
787 				req, bvec.bv_len);
788 		}
789 	}
790 out:
791 	trace_nbd_payload_received(req, handle);
792 	mutex_unlock(&cmd->lock);
793 	return ret ? ERR_PTR(ret) : cmd;
794 }
795 
796 static void recv_work(struct work_struct *work)
797 {
798 	struct recv_thread_args *args = container_of(work,
799 						     struct recv_thread_args,
800 						     work);
801 	struct nbd_device *nbd = args->nbd;
802 	struct nbd_config *config = nbd->config;
803 	struct nbd_cmd *cmd;
804 	struct request *rq;
805 
806 	while (1) {
807 		cmd = nbd_read_stat(nbd, args->index);
808 		if (IS_ERR(cmd)) {
809 			struct nbd_sock *nsock = config->socks[args->index];
810 
811 			mutex_lock(&nsock->tx_lock);
812 			nbd_mark_nsock_dead(nbd, nsock, 1);
813 			mutex_unlock(&nsock->tx_lock);
814 			break;
815 		}
816 
817 		rq = blk_mq_rq_from_pdu(cmd);
818 		if (likely(!blk_should_fake_timeout(rq->q)))
819 			blk_mq_complete_request(rq);
820 	}
821 	nbd_config_put(nbd);
822 	atomic_dec(&config->recv_threads);
823 	wake_up(&config->recv_wq);
824 	kfree(args);
825 }
826 
827 static bool nbd_clear_req(struct request *req, void *data, bool reserved)
828 {
829 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
830 
831 	/* don't abort one completed request */
832 	if (blk_mq_request_completed(req))
833 		return true;
834 
835 	mutex_lock(&cmd->lock);
836 	cmd->status = BLK_STS_IOERR;
837 	mutex_unlock(&cmd->lock);
838 
839 	blk_mq_complete_request(req);
840 	return true;
841 }
842 
843 static void nbd_clear_que(struct nbd_device *nbd)
844 {
845 	blk_mq_quiesce_queue(nbd->disk->queue);
846 	blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
847 	blk_mq_unquiesce_queue(nbd->disk->queue);
848 	dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
849 }
850 
851 static int find_fallback(struct nbd_device *nbd, int index)
852 {
853 	struct nbd_config *config = nbd->config;
854 	int new_index = -1;
855 	struct nbd_sock *nsock = config->socks[index];
856 	int fallback = nsock->fallback_index;
857 
858 	if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
859 		return new_index;
860 
861 	if (config->num_connections <= 1) {
862 		dev_err_ratelimited(disk_to_dev(nbd->disk),
863 				    "Dead connection, failed to find a fallback\n");
864 		return new_index;
865 	}
866 
867 	if (fallback >= 0 && fallback < config->num_connections &&
868 	    !config->socks[fallback]->dead)
869 		return fallback;
870 
871 	if (nsock->fallback_index < 0 ||
872 	    nsock->fallback_index >= config->num_connections ||
873 	    config->socks[nsock->fallback_index]->dead) {
874 		int i;
875 		for (i = 0; i < config->num_connections; i++) {
876 			if (i == index)
877 				continue;
878 			if (!config->socks[i]->dead) {
879 				new_index = i;
880 				break;
881 			}
882 		}
883 		nsock->fallback_index = new_index;
884 		if (new_index < 0) {
885 			dev_err_ratelimited(disk_to_dev(nbd->disk),
886 					    "Dead connection, failed to find a fallback\n");
887 			return new_index;
888 		}
889 	}
890 	new_index = nsock->fallback_index;
891 	return new_index;
892 }
893 
894 static int wait_for_reconnect(struct nbd_device *nbd)
895 {
896 	struct nbd_config *config = nbd->config;
897 	if (!config->dead_conn_timeout)
898 		return 0;
899 	if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
900 		return 0;
901 	return wait_event_timeout(config->conn_wait,
902 				  atomic_read(&config->live_connections) > 0,
903 				  config->dead_conn_timeout) > 0;
904 }
905 
906 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
907 {
908 	struct request *req = blk_mq_rq_from_pdu(cmd);
909 	struct nbd_device *nbd = cmd->nbd;
910 	struct nbd_config *config;
911 	struct nbd_sock *nsock;
912 	int ret;
913 
914 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
915 		dev_err_ratelimited(disk_to_dev(nbd->disk),
916 				    "Socks array is empty\n");
917 		blk_mq_start_request(req);
918 		return -EINVAL;
919 	}
920 	config = nbd->config;
921 
922 	if (index >= config->num_connections) {
923 		dev_err_ratelimited(disk_to_dev(nbd->disk),
924 				    "Attempted send on invalid socket\n");
925 		nbd_config_put(nbd);
926 		blk_mq_start_request(req);
927 		return -EINVAL;
928 	}
929 	cmd->status = BLK_STS_OK;
930 again:
931 	nsock = config->socks[index];
932 	mutex_lock(&nsock->tx_lock);
933 	if (nsock->dead) {
934 		int old_index = index;
935 		index = find_fallback(nbd, index);
936 		mutex_unlock(&nsock->tx_lock);
937 		if (index < 0) {
938 			if (wait_for_reconnect(nbd)) {
939 				index = old_index;
940 				goto again;
941 			}
942 			/* All the sockets should already be down at this point,
943 			 * we just want to make sure that DISCONNECTED is set so
944 			 * any requests that come in that were queue'ed waiting
945 			 * for the reconnect timer don't trigger the timer again
946 			 * and instead just error out.
947 			 */
948 			sock_shutdown(nbd);
949 			nbd_config_put(nbd);
950 			blk_mq_start_request(req);
951 			return -EIO;
952 		}
953 		goto again;
954 	}
955 
956 	/* Handle the case that we have a pending request that was partially
957 	 * transmitted that _has_ to be serviced first.  We need to call requeue
958 	 * here so that it gets put _after_ the request that is already on the
959 	 * dispatch list.
960 	 */
961 	blk_mq_start_request(req);
962 	if (unlikely(nsock->pending && nsock->pending != req)) {
963 		nbd_requeue_cmd(cmd);
964 		ret = 0;
965 		goto out;
966 	}
967 	/*
968 	 * Some failures are related to the link going down, so anything that
969 	 * returns EAGAIN can be retried on a different socket.
970 	 */
971 	ret = nbd_send_cmd(nbd, cmd, index);
972 	if (ret == -EAGAIN) {
973 		dev_err_ratelimited(disk_to_dev(nbd->disk),
974 				    "Request send failed, requeueing\n");
975 		nbd_mark_nsock_dead(nbd, nsock, 1);
976 		nbd_requeue_cmd(cmd);
977 		ret = 0;
978 	}
979 out:
980 	mutex_unlock(&nsock->tx_lock);
981 	nbd_config_put(nbd);
982 	return ret;
983 }
984 
985 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
986 			const struct blk_mq_queue_data *bd)
987 {
988 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
989 	int ret;
990 
991 	/*
992 	 * Since we look at the bio's to send the request over the network we
993 	 * need to make sure the completion work doesn't mark this request done
994 	 * before we are done doing our send.  This keeps us from dereferencing
995 	 * freed data if we have particularly fast completions (ie we get the
996 	 * completion before we exit sock_xmit on the last bvec) or in the case
997 	 * that the server is misbehaving (or there was an error) before we're
998 	 * done sending everything over the wire.
999 	 */
1000 	mutex_lock(&cmd->lock);
1001 	clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1002 
1003 	/* We can be called directly from the user space process, which means we
1004 	 * could possibly have signals pending so our sendmsg will fail.  In
1005 	 * this case we need to return that we are busy, otherwise error out as
1006 	 * appropriate.
1007 	 */
1008 	ret = nbd_handle_cmd(cmd, hctx->queue_num);
1009 	if (ret < 0)
1010 		ret = BLK_STS_IOERR;
1011 	else if (!ret)
1012 		ret = BLK_STS_OK;
1013 	mutex_unlock(&cmd->lock);
1014 
1015 	return ret;
1016 }
1017 
1018 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1019 				     int *err)
1020 {
1021 	struct socket *sock;
1022 
1023 	*err = 0;
1024 	sock = sockfd_lookup(fd, err);
1025 	if (!sock)
1026 		return NULL;
1027 
1028 	if (sock->ops->shutdown == sock_no_shutdown) {
1029 		dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1030 		*err = -EINVAL;
1031 		sockfd_put(sock);
1032 		return NULL;
1033 	}
1034 
1035 	return sock;
1036 }
1037 
1038 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1039 			  bool netlink)
1040 {
1041 	struct nbd_config *config = nbd->config;
1042 	struct socket *sock;
1043 	struct nbd_sock **socks;
1044 	struct nbd_sock *nsock;
1045 	int err;
1046 
1047 	sock = nbd_get_socket(nbd, arg, &err);
1048 	if (!sock)
1049 		return err;
1050 
1051 	/*
1052 	 * We need to make sure we don't get any errant requests while we're
1053 	 * reallocating the ->socks array.
1054 	 */
1055 	blk_mq_freeze_queue(nbd->disk->queue);
1056 
1057 	if (!netlink && !nbd->task_setup &&
1058 	    !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1059 		nbd->task_setup = current;
1060 
1061 	if (!netlink &&
1062 	    (nbd->task_setup != current ||
1063 	     test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1064 		dev_err(disk_to_dev(nbd->disk),
1065 			"Device being setup by another task");
1066 		err = -EBUSY;
1067 		goto put_socket;
1068 	}
1069 
1070 	nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1071 	if (!nsock) {
1072 		err = -ENOMEM;
1073 		goto put_socket;
1074 	}
1075 
1076 	socks = krealloc(config->socks, (config->num_connections + 1) *
1077 			 sizeof(struct nbd_sock *), GFP_KERNEL);
1078 	if (!socks) {
1079 		kfree(nsock);
1080 		err = -ENOMEM;
1081 		goto put_socket;
1082 	}
1083 
1084 	config->socks = socks;
1085 
1086 	nsock->fallback_index = -1;
1087 	nsock->dead = false;
1088 	mutex_init(&nsock->tx_lock);
1089 	nsock->sock = sock;
1090 	nsock->pending = NULL;
1091 	nsock->sent = 0;
1092 	nsock->cookie = 0;
1093 	socks[config->num_connections++] = nsock;
1094 	atomic_inc(&config->live_connections);
1095 	blk_mq_unfreeze_queue(nbd->disk->queue);
1096 
1097 	return 0;
1098 
1099 put_socket:
1100 	blk_mq_unfreeze_queue(nbd->disk->queue);
1101 	sockfd_put(sock);
1102 	return err;
1103 }
1104 
1105 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1106 {
1107 	struct nbd_config *config = nbd->config;
1108 	struct socket *sock, *old;
1109 	struct recv_thread_args *args;
1110 	int i;
1111 	int err;
1112 
1113 	sock = nbd_get_socket(nbd, arg, &err);
1114 	if (!sock)
1115 		return err;
1116 
1117 	args = kzalloc(sizeof(*args), GFP_KERNEL);
1118 	if (!args) {
1119 		sockfd_put(sock);
1120 		return -ENOMEM;
1121 	}
1122 
1123 	for (i = 0; i < config->num_connections; i++) {
1124 		struct nbd_sock *nsock = config->socks[i];
1125 
1126 		if (!nsock->dead)
1127 			continue;
1128 
1129 		mutex_lock(&nsock->tx_lock);
1130 		if (!nsock->dead) {
1131 			mutex_unlock(&nsock->tx_lock);
1132 			continue;
1133 		}
1134 		sk_set_memalloc(sock->sk);
1135 		if (nbd->tag_set.timeout)
1136 			sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1137 		atomic_inc(&config->recv_threads);
1138 		refcount_inc(&nbd->config_refs);
1139 		old = nsock->sock;
1140 		nsock->fallback_index = -1;
1141 		nsock->sock = sock;
1142 		nsock->dead = false;
1143 		INIT_WORK(&args->work, recv_work);
1144 		args->index = i;
1145 		args->nbd = nbd;
1146 		nsock->cookie++;
1147 		mutex_unlock(&nsock->tx_lock);
1148 		sockfd_put(old);
1149 
1150 		clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1151 
1152 		/* We take the tx_mutex in an error path in the recv_work, so we
1153 		 * need to queue_work outside of the tx_mutex.
1154 		 */
1155 		queue_work(nbd->recv_workq, &args->work);
1156 
1157 		atomic_inc(&config->live_connections);
1158 		wake_up(&config->conn_wait);
1159 		return 0;
1160 	}
1161 	sockfd_put(sock);
1162 	kfree(args);
1163 	return -ENOSPC;
1164 }
1165 
1166 static void nbd_bdev_reset(struct block_device *bdev)
1167 {
1168 	if (bdev->bd_openers > 1)
1169 		return;
1170 	set_capacity(bdev->bd_disk, 0);
1171 }
1172 
1173 static void nbd_parse_flags(struct nbd_device *nbd)
1174 {
1175 	struct nbd_config *config = nbd->config;
1176 	if (config->flags & NBD_FLAG_READ_ONLY)
1177 		set_disk_ro(nbd->disk, true);
1178 	else
1179 		set_disk_ro(nbd->disk, false);
1180 	if (config->flags & NBD_FLAG_SEND_TRIM)
1181 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1182 	if (config->flags & NBD_FLAG_SEND_FLUSH) {
1183 		if (config->flags & NBD_FLAG_SEND_FUA)
1184 			blk_queue_write_cache(nbd->disk->queue, true, true);
1185 		else
1186 			blk_queue_write_cache(nbd->disk->queue, true, false);
1187 	}
1188 	else
1189 		blk_queue_write_cache(nbd->disk->queue, false, false);
1190 }
1191 
1192 static void send_disconnects(struct nbd_device *nbd)
1193 {
1194 	struct nbd_config *config = nbd->config;
1195 	struct nbd_request request = {
1196 		.magic = htonl(NBD_REQUEST_MAGIC),
1197 		.type = htonl(NBD_CMD_DISC),
1198 	};
1199 	struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1200 	struct iov_iter from;
1201 	int i, ret;
1202 
1203 	for (i = 0; i < config->num_connections; i++) {
1204 		struct nbd_sock *nsock = config->socks[i];
1205 
1206 		iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1207 		mutex_lock(&nsock->tx_lock);
1208 		ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1209 		if (ret <= 0)
1210 			dev_err(disk_to_dev(nbd->disk),
1211 				"Send disconnect failed %d\n", ret);
1212 		mutex_unlock(&nsock->tx_lock);
1213 	}
1214 }
1215 
1216 static int nbd_disconnect(struct nbd_device *nbd)
1217 {
1218 	struct nbd_config *config = nbd->config;
1219 
1220 	dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1221 	set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1222 	set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1223 	send_disconnects(nbd);
1224 	return 0;
1225 }
1226 
1227 static void nbd_clear_sock(struct nbd_device *nbd)
1228 {
1229 	sock_shutdown(nbd);
1230 	nbd_clear_que(nbd);
1231 	nbd->task_setup = NULL;
1232 }
1233 
1234 static void nbd_config_put(struct nbd_device *nbd)
1235 {
1236 	if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1237 					&nbd->config_lock)) {
1238 		struct nbd_config *config = nbd->config;
1239 		nbd_dev_dbg_close(nbd);
1240 		nbd_size_clear(nbd);
1241 		if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1242 				       &config->runtime_flags))
1243 			device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1244 		nbd->task_recv = NULL;
1245 		if (test_and_clear_bit(NBD_RT_HAS_BACKEND_FILE,
1246 				       &config->runtime_flags)) {
1247 			device_remove_file(disk_to_dev(nbd->disk), &backend_attr);
1248 			kfree(nbd->backend);
1249 			nbd->backend = NULL;
1250 		}
1251 		nbd_clear_sock(nbd);
1252 		if (config->num_connections) {
1253 			int i;
1254 			for (i = 0; i < config->num_connections; i++) {
1255 				sockfd_put(config->socks[i]->sock);
1256 				kfree(config->socks[i]);
1257 			}
1258 			kfree(config->socks);
1259 		}
1260 		kfree(nbd->config);
1261 		nbd->config = NULL;
1262 
1263 		if (nbd->recv_workq)
1264 			destroy_workqueue(nbd->recv_workq);
1265 		nbd->recv_workq = NULL;
1266 
1267 		nbd->tag_set.timeout = 0;
1268 		nbd->disk->queue->limits.discard_granularity = 0;
1269 		nbd->disk->queue->limits.discard_alignment = 0;
1270 		blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1271 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1272 
1273 		mutex_unlock(&nbd->config_lock);
1274 		nbd_put(nbd);
1275 		module_put(THIS_MODULE);
1276 	}
1277 }
1278 
1279 static int nbd_start_device(struct nbd_device *nbd)
1280 {
1281 	struct nbd_config *config = nbd->config;
1282 	int num_connections = config->num_connections;
1283 	int error = 0, i;
1284 
1285 	if (nbd->task_recv)
1286 		return -EBUSY;
1287 	if (!config->socks)
1288 		return -EINVAL;
1289 	if (num_connections > 1 &&
1290 	    !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1291 		dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1292 		return -EINVAL;
1293 	}
1294 
1295 	nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1296 					  WQ_MEM_RECLAIM | WQ_HIGHPRI |
1297 					  WQ_UNBOUND, 0, nbd->index);
1298 	if (!nbd->recv_workq) {
1299 		dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1300 		return -ENOMEM;
1301 	}
1302 
1303 	blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1304 	nbd->task_recv = current;
1305 
1306 	nbd_parse_flags(nbd);
1307 
1308 	error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1309 	if (error) {
1310 		dev_err(disk_to_dev(nbd->disk), "device_create_file failed for pid!\n");
1311 		return error;
1312 	}
1313 	set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1314 
1315 	nbd_dev_dbg_init(nbd);
1316 	for (i = 0; i < num_connections; i++) {
1317 		struct recv_thread_args *args;
1318 
1319 		args = kzalloc(sizeof(*args), GFP_KERNEL);
1320 		if (!args) {
1321 			sock_shutdown(nbd);
1322 			/*
1323 			 * If num_connections is m (2 < m),
1324 			 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1325 			 * But NO.(n + 1) failed. We still have n recv threads.
1326 			 * So, add flush_workqueue here to prevent recv threads
1327 			 * dropping the last config_refs and trying to destroy
1328 			 * the workqueue from inside the workqueue.
1329 			 */
1330 			if (i)
1331 				flush_workqueue(nbd->recv_workq);
1332 			return -ENOMEM;
1333 		}
1334 		sk_set_memalloc(config->socks[i]->sock->sk);
1335 		if (nbd->tag_set.timeout)
1336 			config->socks[i]->sock->sk->sk_sndtimeo =
1337 				nbd->tag_set.timeout;
1338 		atomic_inc(&config->recv_threads);
1339 		refcount_inc(&nbd->config_refs);
1340 		INIT_WORK(&args->work, recv_work);
1341 		args->nbd = nbd;
1342 		args->index = i;
1343 		queue_work(nbd->recv_workq, &args->work);
1344 	}
1345 	return nbd_set_size(nbd, config->bytesize, nbd_blksize(config));
1346 }
1347 
1348 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1349 {
1350 	struct nbd_config *config = nbd->config;
1351 	int ret;
1352 
1353 	ret = nbd_start_device(nbd);
1354 	if (ret)
1355 		return ret;
1356 
1357 	if (max_part)
1358 		set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1359 	mutex_unlock(&nbd->config_lock);
1360 	ret = wait_event_interruptible(config->recv_wq,
1361 					 atomic_read(&config->recv_threads) == 0);
1362 	if (ret)
1363 		sock_shutdown(nbd);
1364 	flush_workqueue(nbd->recv_workq);
1365 
1366 	mutex_lock(&nbd->config_lock);
1367 	nbd_bdev_reset(bdev);
1368 	/* user requested, ignore socket errors */
1369 	if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1370 		ret = 0;
1371 	if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1372 		ret = -ETIMEDOUT;
1373 	return ret;
1374 }
1375 
1376 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1377 				 struct block_device *bdev)
1378 {
1379 	sock_shutdown(nbd);
1380 	__invalidate_device(bdev, true);
1381 	nbd_bdev_reset(bdev);
1382 	if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1383 			       &nbd->config->runtime_flags))
1384 		nbd_config_put(nbd);
1385 }
1386 
1387 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1388 {
1389 	nbd->tag_set.timeout = timeout * HZ;
1390 	if (timeout)
1391 		blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1392 	else
1393 		blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1394 }
1395 
1396 /* Must be called with config_lock held */
1397 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1398 		       unsigned int cmd, unsigned long arg)
1399 {
1400 	struct nbd_config *config = nbd->config;
1401 	loff_t bytesize;
1402 
1403 	switch (cmd) {
1404 	case NBD_DISCONNECT:
1405 		return nbd_disconnect(nbd);
1406 	case NBD_CLEAR_SOCK:
1407 		nbd_clear_sock_ioctl(nbd, bdev);
1408 		return 0;
1409 	case NBD_SET_SOCK:
1410 		return nbd_add_socket(nbd, arg, false);
1411 	case NBD_SET_BLKSIZE:
1412 		return nbd_set_size(nbd, config->bytesize, arg);
1413 	case NBD_SET_SIZE:
1414 		return nbd_set_size(nbd, arg, nbd_blksize(config));
1415 	case NBD_SET_SIZE_BLOCKS:
1416 		if (check_shl_overflow(arg, config->blksize_bits, &bytesize))
1417 			return -EINVAL;
1418 		return nbd_set_size(nbd, bytesize, nbd_blksize(config));
1419 	case NBD_SET_TIMEOUT:
1420 		nbd_set_cmd_timeout(nbd, arg);
1421 		return 0;
1422 
1423 	case NBD_SET_FLAGS:
1424 		config->flags = arg;
1425 		return 0;
1426 	case NBD_DO_IT:
1427 		return nbd_start_device_ioctl(nbd, bdev);
1428 	case NBD_CLEAR_QUE:
1429 		/*
1430 		 * This is for compatibility only.  The queue is always cleared
1431 		 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1432 		 */
1433 		return 0;
1434 	case NBD_PRINT_DEBUG:
1435 		/*
1436 		 * For compatibility only, we no longer keep a list of
1437 		 * outstanding requests.
1438 		 */
1439 		return 0;
1440 	}
1441 	return -ENOTTY;
1442 }
1443 
1444 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1445 		     unsigned int cmd, unsigned long arg)
1446 {
1447 	struct nbd_device *nbd = bdev->bd_disk->private_data;
1448 	struct nbd_config *config = nbd->config;
1449 	int error = -EINVAL;
1450 
1451 	if (!capable(CAP_SYS_ADMIN))
1452 		return -EPERM;
1453 
1454 	/* The block layer will pass back some non-nbd ioctls in case we have
1455 	 * special handling for them, but we don't so just return an error.
1456 	 */
1457 	if (_IOC_TYPE(cmd) != 0xab)
1458 		return -EINVAL;
1459 
1460 	mutex_lock(&nbd->config_lock);
1461 
1462 	/* Don't allow ioctl operations on a nbd device that was created with
1463 	 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1464 	 */
1465 	if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1466 	    (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1467 		error = __nbd_ioctl(bdev, nbd, cmd, arg);
1468 	else
1469 		dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1470 	mutex_unlock(&nbd->config_lock);
1471 	return error;
1472 }
1473 
1474 static struct nbd_config *nbd_alloc_config(void)
1475 {
1476 	struct nbd_config *config;
1477 
1478 	config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1479 	if (!config)
1480 		return NULL;
1481 	atomic_set(&config->recv_threads, 0);
1482 	init_waitqueue_head(&config->recv_wq);
1483 	init_waitqueue_head(&config->conn_wait);
1484 	config->blksize_bits = NBD_DEF_BLKSIZE_BITS;
1485 	atomic_set(&config->live_connections, 0);
1486 	try_module_get(THIS_MODULE);
1487 	return config;
1488 }
1489 
1490 static int nbd_open(struct block_device *bdev, fmode_t mode)
1491 {
1492 	struct nbd_device *nbd;
1493 	int ret = 0;
1494 
1495 	mutex_lock(&nbd_index_mutex);
1496 	nbd = bdev->bd_disk->private_data;
1497 	if (!nbd) {
1498 		ret = -ENXIO;
1499 		goto out;
1500 	}
1501 	if (!refcount_inc_not_zero(&nbd->refs)) {
1502 		ret = -ENXIO;
1503 		goto out;
1504 	}
1505 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
1506 		struct nbd_config *config;
1507 
1508 		mutex_lock(&nbd->config_lock);
1509 		if (refcount_inc_not_zero(&nbd->config_refs)) {
1510 			mutex_unlock(&nbd->config_lock);
1511 			goto out;
1512 		}
1513 		config = nbd->config = nbd_alloc_config();
1514 		if (!config) {
1515 			ret = -ENOMEM;
1516 			mutex_unlock(&nbd->config_lock);
1517 			goto out;
1518 		}
1519 		refcount_set(&nbd->config_refs, 1);
1520 		refcount_inc(&nbd->refs);
1521 		mutex_unlock(&nbd->config_lock);
1522 		if (max_part)
1523 			set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1524 	} else if (nbd_disconnected(nbd->config)) {
1525 		if (max_part)
1526 			set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1527 	}
1528 out:
1529 	mutex_unlock(&nbd_index_mutex);
1530 	return ret;
1531 }
1532 
1533 static void nbd_release(struct gendisk *disk, fmode_t mode)
1534 {
1535 	struct nbd_device *nbd = disk->private_data;
1536 
1537 	if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1538 			disk->part0->bd_openers == 0)
1539 		nbd_disconnect_and_put(nbd);
1540 
1541 	nbd_config_put(nbd);
1542 	nbd_put(nbd);
1543 }
1544 
1545 static const struct block_device_operations nbd_fops =
1546 {
1547 	.owner =	THIS_MODULE,
1548 	.open =		nbd_open,
1549 	.release =	nbd_release,
1550 	.ioctl =	nbd_ioctl,
1551 	.compat_ioctl =	nbd_ioctl,
1552 };
1553 
1554 #if IS_ENABLED(CONFIG_DEBUG_FS)
1555 
1556 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1557 {
1558 	struct nbd_device *nbd = s->private;
1559 
1560 	if (nbd->task_recv)
1561 		seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1562 
1563 	return 0;
1564 }
1565 
1566 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_tasks);
1567 
1568 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1569 {
1570 	struct nbd_device *nbd = s->private;
1571 	u32 flags = nbd->config->flags;
1572 
1573 	seq_printf(s, "Hex: 0x%08x\n\n", flags);
1574 
1575 	seq_puts(s, "Known flags:\n");
1576 
1577 	if (flags & NBD_FLAG_HAS_FLAGS)
1578 		seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1579 	if (flags & NBD_FLAG_READ_ONLY)
1580 		seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1581 	if (flags & NBD_FLAG_SEND_FLUSH)
1582 		seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1583 	if (flags & NBD_FLAG_SEND_FUA)
1584 		seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1585 	if (flags & NBD_FLAG_SEND_TRIM)
1586 		seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1587 
1588 	return 0;
1589 }
1590 
1591 DEFINE_SHOW_ATTRIBUTE(nbd_dbg_flags);
1592 
1593 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1594 {
1595 	struct dentry *dir;
1596 	struct nbd_config *config = nbd->config;
1597 
1598 	if (!nbd_dbg_dir)
1599 		return -EIO;
1600 
1601 	dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1602 	if (!dir) {
1603 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1604 			nbd_name(nbd));
1605 		return -EIO;
1606 	}
1607 	config->dbg_dir = dir;
1608 
1609 	debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_fops);
1610 	debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1611 	debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1612 	debugfs_create_u32("blocksize_bits", 0444, dir, &config->blksize_bits);
1613 	debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_fops);
1614 
1615 	return 0;
1616 }
1617 
1618 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1619 {
1620 	debugfs_remove_recursive(nbd->config->dbg_dir);
1621 }
1622 
1623 static int nbd_dbg_init(void)
1624 {
1625 	struct dentry *dbg_dir;
1626 
1627 	dbg_dir = debugfs_create_dir("nbd", NULL);
1628 	if (!dbg_dir)
1629 		return -EIO;
1630 
1631 	nbd_dbg_dir = dbg_dir;
1632 
1633 	return 0;
1634 }
1635 
1636 static void nbd_dbg_close(void)
1637 {
1638 	debugfs_remove_recursive(nbd_dbg_dir);
1639 }
1640 
1641 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
1642 
1643 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1644 {
1645 	return 0;
1646 }
1647 
1648 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1649 {
1650 }
1651 
1652 static int nbd_dbg_init(void)
1653 {
1654 	return 0;
1655 }
1656 
1657 static void nbd_dbg_close(void)
1658 {
1659 }
1660 
1661 #endif
1662 
1663 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1664 			    unsigned int hctx_idx, unsigned int numa_node)
1665 {
1666 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1667 	cmd->nbd = set->driver_data;
1668 	cmd->flags = 0;
1669 	mutex_init(&cmd->lock);
1670 	return 0;
1671 }
1672 
1673 static const struct blk_mq_ops nbd_mq_ops = {
1674 	.queue_rq	= nbd_queue_rq,
1675 	.complete	= nbd_complete_rq,
1676 	.init_request	= nbd_init_request,
1677 	.timeout	= nbd_xmit_timeout,
1678 };
1679 
1680 static struct nbd_device *nbd_dev_add(int index, unsigned int refs)
1681 {
1682 	struct nbd_device *nbd;
1683 	struct gendisk *disk;
1684 	int err = -ENOMEM;
1685 
1686 	nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1687 	if (!nbd)
1688 		goto out;
1689 
1690 	nbd->tag_set.ops = &nbd_mq_ops;
1691 	nbd->tag_set.nr_hw_queues = 1;
1692 	nbd->tag_set.queue_depth = 128;
1693 	nbd->tag_set.numa_node = NUMA_NO_NODE;
1694 	nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1695 	nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1696 		BLK_MQ_F_BLOCKING;
1697 	nbd->tag_set.driver_data = nbd;
1698 	INIT_WORK(&nbd->remove_work, nbd_dev_remove_work);
1699 	nbd->backend = NULL;
1700 
1701 	err = blk_mq_alloc_tag_set(&nbd->tag_set);
1702 	if (err)
1703 		goto out_free_nbd;
1704 
1705 	mutex_lock(&nbd_index_mutex);
1706 	if (index >= 0) {
1707 		err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1708 				GFP_KERNEL);
1709 		if (err == -ENOSPC)
1710 			err = -EEXIST;
1711 	} else {
1712 		err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1713 		if (err >= 0)
1714 			index = err;
1715 	}
1716 	nbd->index = index;
1717 	mutex_unlock(&nbd_index_mutex);
1718 	if (err < 0)
1719 		goto out_free_tags;
1720 
1721 	disk = blk_mq_alloc_disk(&nbd->tag_set, NULL);
1722 	if (IS_ERR(disk)) {
1723 		err = PTR_ERR(disk);
1724 		goto out_free_idr;
1725 	}
1726 	nbd->disk = disk;
1727 
1728 	/*
1729 	 * Tell the block layer that we are not a rotational device
1730 	 */
1731 	blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1732 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1733 	disk->queue->limits.discard_granularity = 0;
1734 	disk->queue->limits.discard_alignment = 0;
1735 	blk_queue_max_discard_sectors(disk->queue, 0);
1736 	blk_queue_max_segment_size(disk->queue, UINT_MAX);
1737 	blk_queue_max_segments(disk->queue, USHRT_MAX);
1738 	blk_queue_max_hw_sectors(disk->queue, 65536);
1739 	disk->queue->limits.max_sectors = 256;
1740 
1741 	mutex_init(&nbd->config_lock);
1742 	refcount_set(&nbd->config_refs, 0);
1743 	/*
1744 	 * Start out with a zero references to keep other threads from using
1745 	 * this device until it is fully initialized.
1746 	 */
1747 	refcount_set(&nbd->refs, 0);
1748 	INIT_LIST_HEAD(&nbd->list);
1749 	disk->major = NBD_MAJOR;
1750 
1751 	/* Too big first_minor can cause duplicate creation of
1752 	 * sysfs files/links, since first_minor will be truncated to
1753 	 * byte in __device_add_disk().
1754 	 */
1755 	disk->first_minor = index << part_shift;
1756 	if (disk->first_minor > 0xff) {
1757 		err = -EINVAL;
1758 		goto out_free_idr;
1759 	}
1760 
1761 	disk->minors = 1 << part_shift;
1762 	disk->fops = &nbd_fops;
1763 	disk->private_data = nbd;
1764 	sprintf(disk->disk_name, "nbd%d", index);
1765 	add_disk(disk);
1766 
1767 	/*
1768 	 * Now publish the device.
1769 	 */
1770 	refcount_set(&nbd->refs, refs);
1771 	nbd_total_devices++;
1772 	return nbd;
1773 
1774 out_free_idr:
1775 	mutex_lock(&nbd_index_mutex);
1776 	idr_remove(&nbd_index_idr, index);
1777 	mutex_unlock(&nbd_index_mutex);
1778 out_free_tags:
1779 	blk_mq_free_tag_set(&nbd->tag_set);
1780 out_free_nbd:
1781 	kfree(nbd);
1782 out:
1783 	return ERR_PTR(err);
1784 }
1785 
1786 static struct nbd_device *nbd_find_get_unused(void)
1787 {
1788 	struct nbd_device *nbd;
1789 	int id;
1790 
1791 	lockdep_assert_held(&nbd_index_mutex);
1792 
1793 	idr_for_each_entry(&nbd_index_idr, nbd, id) {
1794 		if (refcount_read(&nbd->config_refs) ||
1795 		    test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags))
1796 			continue;
1797 		if (refcount_inc_not_zero(&nbd->refs))
1798 			return nbd;
1799 	}
1800 
1801 	return NULL;
1802 }
1803 
1804 /* Netlink interface. */
1805 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1806 	[NBD_ATTR_INDEX]		=	{ .type = NLA_U32 },
1807 	[NBD_ATTR_SIZE_BYTES]		=	{ .type = NLA_U64 },
1808 	[NBD_ATTR_BLOCK_SIZE_BYTES]	=	{ .type = NLA_U64 },
1809 	[NBD_ATTR_TIMEOUT]		=	{ .type = NLA_U64 },
1810 	[NBD_ATTR_SERVER_FLAGS]		=	{ .type = NLA_U64 },
1811 	[NBD_ATTR_CLIENT_FLAGS]		=	{ .type = NLA_U64 },
1812 	[NBD_ATTR_SOCKETS]		=	{ .type = NLA_NESTED},
1813 	[NBD_ATTR_DEAD_CONN_TIMEOUT]	=	{ .type = NLA_U64 },
1814 	[NBD_ATTR_DEVICE_LIST]		=	{ .type = NLA_NESTED},
1815 	[NBD_ATTR_BACKEND_IDENTIFIER]	=	{ .type = NLA_STRING},
1816 };
1817 
1818 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1819 	[NBD_SOCK_FD]			=	{ .type = NLA_U32 },
1820 };
1821 
1822 /* We don't use this right now since we don't parse the incoming list, but we
1823  * still want it here so userspace knows what to expect.
1824  */
1825 static const struct nla_policy __attribute__((unused))
1826 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1827 	[NBD_DEVICE_INDEX]		=	{ .type = NLA_U32 },
1828 	[NBD_DEVICE_CONNECTED]		=	{ .type = NLA_U8 },
1829 };
1830 
1831 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1832 {
1833 	struct nbd_config *config = nbd->config;
1834 	u64 bsize = nbd_blksize(config);
1835 	u64 bytes = config->bytesize;
1836 
1837 	if (info->attrs[NBD_ATTR_SIZE_BYTES])
1838 		bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1839 
1840 	if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES])
1841 		bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1842 
1843 	if (bytes != config->bytesize || bsize != nbd_blksize(config))
1844 		return nbd_set_size(nbd, bytes, bsize);
1845 	return 0;
1846 }
1847 
1848 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1849 {
1850 	struct nbd_device *nbd;
1851 	struct nbd_config *config;
1852 	int index = -1;
1853 	int ret;
1854 	bool put_dev = false;
1855 
1856 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
1857 		return -EPERM;
1858 
1859 	if (info->attrs[NBD_ATTR_INDEX])
1860 		index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1861 	if (!info->attrs[NBD_ATTR_SOCKETS]) {
1862 		printk(KERN_ERR "nbd: must specify at least one socket\n");
1863 		return -EINVAL;
1864 	}
1865 	if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1866 		printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1867 		return -EINVAL;
1868 	}
1869 again:
1870 	mutex_lock(&nbd_index_mutex);
1871 	if (index == -1) {
1872 		nbd = nbd_find_get_unused();
1873 	} else {
1874 		nbd = idr_find(&nbd_index_idr, index);
1875 		if (nbd) {
1876 			if ((test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1877 			     test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) ||
1878 			    !refcount_inc_not_zero(&nbd->refs)) {
1879 				mutex_unlock(&nbd_index_mutex);
1880 				pr_err("nbd: device at index %d is going down\n",
1881 					index);
1882 				return -EINVAL;
1883 			}
1884 		}
1885 	}
1886 	mutex_unlock(&nbd_index_mutex);
1887 
1888 	if (!nbd) {
1889 		nbd = nbd_dev_add(index, 2);
1890 		if (IS_ERR(nbd)) {
1891 			pr_err("nbd: failed to add new device\n");
1892 			return PTR_ERR(nbd);
1893 		}
1894 	}
1895 
1896 	mutex_lock(&nbd->config_lock);
1897 	if (refcount_read(&nbd->config_refs)) {
1898 		mutex_unlock(&nbd->config_lock);
1899 		nbd_put(nbd);
1900 		if (index == -1)
1901 			goto again;
1902 		printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1903 		return -EBUSY;
1904 	}
1905 	if (WARN_ON(nbd->config)) {
1906 		mutex_unlock(&nbd->config_lock);
1907 		nbd_put(nbd);
1908 		return -EINVAL;
1909 	}
1910 	config = nbd->config = nbd_alloc_config();
1911 	if (!nbd->config) {
1912 		mutex_unlock(&nbd->config_lock);
1913 		nbd_put(nbd);
1914 		printk(KERN_ERR "nbd: couldn't allocate config\n");
1915 		return -ENOMEM;
1916 	}
1917 	refcount_set(&nbd->config_refs, 1);
1918 	set_bit(NBD_RT_BOUND, &config->runtime_flags);
1919 
1920 	ret = nbd_genl_size_set(info, nbd);
1921 	if (ret)
1922 		goto out;
1923 
1924 	if (info->attrs[NBD_ATTR_TIMEOUT])
1925 		nbd_set_cmd_timeout(nbd,
1926 				    nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
1927 	if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1928 		config->dead_conn_timeout =
1929 			nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1930 		config->dead_conn_timeout *= HZ;
1931 	}
1932 	if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1933 		config->flags =
1934 			nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1935 	if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1936 		u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1937 		if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1938 			/*
1939 			 * We have 1 ref to keep the device around, and then 1
1940 			 * ref for our current operation here, which will be
1941 			 * inherited by the config.  If we already have
1942 			 * DESTROY_ON_DISCONNECT set then we know we don't have
1943 			 * that extra ref already held so we don't need the
1944 			 * put_dev.
1945 			 */
1946 			if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1947 					      &nbd->flags))
1948 				put_dev = true;
1949 		} else {
1950 			if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1951 					       &nbd->flags))
1952 				refcount_inc(&nbd->refs);
1953 		}
1954 		if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1955 			set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
1956 				&config->runtime_flags);
1957 		}
1958 	}
1959 
1960 	if (info->attrs[NBD_ATTR_SOCKETS]) {
1961 		struct nlattr *attr;
1962 		int rem, fd;
1963 
1964 		nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1965 				    rem) {
1966 			struct nlattr *socks[NBD_SOCK_MAX+1];
1967 
1968 			if (nla_type(attr) != NBD_SOCK_ITEM) {
1969 				printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1970 				ret = -EINVAL;
1971 				goto out;
1972 			}
1973 			ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
1974 							  attr,
1975 							  nbd_sock_policy,
1976 							  info->extack);
1977 			if (ret != 0) {
1978 				printk(KERN_ERR "nbd: error processing sock list\n");
1979 				ret = -EINVAL;
1980 				goto out;
1981 			}
1982 			if (!socks[NBD_SOCK_FD])
1983 				continue;
1984 			fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1985 			ret = nbd_add_socket(nbd, fd, true);
1986 			if (ret)
1987 				goto out;
1988 		}
1989 	}
1990 	ret = nbd_start_device(nbd);
1991 	if (ret)
1992 		goto out;
1993 	if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
1994 		nbd->backend = nla_strdup(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
1995 					  GFP_KERNEL);
1996 		if (!nbd->backend) {
1997 			ret = -ENOMEM;
1998 			goto out;
1999 		}
2000 	}
2001 	ret = device_create_file(disk_to_dev(nbd->disk), &backend_attr);
2002 	if (ret) {
2003 		dev_err(disk_to_dev(nbd->disk),
2004 			"device_create_file failed for backend!\n");
2005 		goto out;
2006 	}
2007 	set_bit(NBD_RT_HAS_BACKEND_FILE, &config->runtime_flags);
2008 out:
2009 	mutex_unlock(&nbd->config_lock);
2010 	if (!ret) {
2011 		set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2012 		refcount_inc(&nbd->config_refs);
2013 		nbd_connect_reply(info, nbd->index);
2014 	}
2015 	nbd_config_put(nbd);
2016 	if (put_dev)
2017 		nbd_put(nbd);
2018 	return ret;
2019 }
2020 
2021 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2022 {
2023 	mutex_lock(&nbd->config_lock);
2024 	nbd_disconnect(nbd);
2025 	sock_shutdown(nbd);
2026 	/*
2027 	 * Make sure recv thread has finished, so it does not drop the last
2028 	 * config ref and try to destroy the workqueue from inside the work
2029 	 * queue. And this also ensure that we can safely call nbd_clear_que()
2030 	 * to cancel the inflight I/Os.
2031 	 */
2032 	if (nbd->recv_workq)
2033 		flush_workqueue(nbd->recv_workq);
2034 	nbd_clear_que(nbd);
2035 	nbd->task_setup = NULL;
2036 	mutex_unlock(&nbd->config_lock);
2037 
2038 	if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2039 			       &nbd->config->runtime_flags))
2040 		nbd_config_put(nbd);
2041 }
2042 
2043 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2044 {
2045 	struct nbd_device *nbd;
2046 	int index;
2047 
2048 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
2049 		return -EPERM;
2050 
2051 	if (!info->attrs[NBD_ATTR_INDEX]) {
2052 		printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2053 		return -EINVAL;
2054 	}
2055 	index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2056 	mutex_lock(&nbd_index_mutex);
2057 	nbd = idr_find(&nbd_index_idr, index);
2058 	if (!nbd) {
2059 		mutex_unlock(&nbd_index_mutex);
2060 		printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2061 		       index);
2062 		return -EINVAL;
2063 	}
2064 	if (!refcount_inc_not_zero(&nbd->refs)) {
2065 		mutex_unlock(&nbd_index_mutex);
2066 		printk(KERN_ERR "nbd: device at index %d is going down\n",
2067 		       index);
2068 		return -EINVAL;
2069 	}
2070 	mutex_unlock(&nbd_index_mutex);
2071 	if (!refcount_inc_not_zero(&nbd->config_refs))
2072 		goto put_nbd;
2073 	nbd_disconnect_and_put(nbd);
2074 	nbd_config_put(nbd);
2075 put_nbd:
2076 	nbd_put(nbd);
2077 	return 0;
2078 }
2079 
2080 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2081 {
2082 	struct nbd_device *nbd = NULL;
2083 	struct nbd_config *config;
2084 	int index;
2085 	int ret = 0;
2086 	bool put_dev = false;
2087 
2088 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
2089 		return -EPERM;
2090 
2091 	if (!info->attrs[NBD_ATTR_INDEX]) {
2092 		printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2093 		return -EINVAL;
2094 	}
2095 	index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2096 	mutex_lock(&nbd_index_mutex);
2097 	nbd = idr_find(&nbd_index_idr, index);
2098 	if (!nbd) {
2099 		mutex_unlock(&nbd_index_mutex);
2100 		printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2101 		       index);
2102 		return -EINVAL;
2103 	}
2104 	if (nbd->backend) {
2105 		if (info->attrs[NBD_ATTR_BACKEND_IDENTIFIER]) {
2106 			if (nla_strcmp(info->attrs[NBD_ATTR_BACKEND_IDENTIFIER],
2107 				       nbd->backend)) {
2108 				mutex_unlock(&nbd_index_mutex);
2109 				dev_err(nbd_to_dev(nbd),
2110 					"backend image doesn't match with %s\n",
2111 					nbd->backend);
2112 				return -EINVAL;
2113 			}
2114 		} else {
2115 			mutex_unlock(&nbd_index_mutex);
2116 			dev_err(nbd_to_dev(nbd), "must specify backend\n");
2117 			return -EINVAL;
2118 		}
2119 	}
2120 	if (!refcount_inc_not_zero(&nbd->refs)) {
2121 		mutex_unlock(&nbd_index_mutex);
2122 		printk(KERN_ERR "nbd: device at index %d is going down\n",
2123 		       index);
2124 		return -EINVAL;
2125 	}
2126 	mutex_unlock(&nbd_index_mutex);
2127 
2128 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
2129 		dev_err(nbd_to_dev(nbd),
2130 			"not configured, cannot reconfigure\n");
2131 		nbd_put(nbd);
2132 		return -EINVAL;
2133 	}
2134 
2135 	mutex_lock(&nbd->config_lock);
2136 	config = nbd->config;
2137 	if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2138 	    !nbd->task_recv) {
2139 		dev_err(nbd_to_dev(nbd),
2140 			"not configured, cannot reconfigure\n");
2141 		ret = -EINVAL;
2142 		goto out;
2143 	}
2144 
2145 	ret = nbd_genl_size_set(info, nbd);
2146 	if (ret)
2147 		goto out;
2148 
2149 	if (info->attrs[NBD_ATTR_TIMEOUT])
2150 		nbd_set_cmd_timeout(nbd,
2151 				    nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2152 	if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2153 		config->dead_conn_timeout =
2154 			nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2155 		config->dead_conn_timeout *= HZ;
2156 	}
2157 	if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2158 		u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2159 		if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2160 			if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2161 					      &nbd->flags))
2162 				put_dev = true;
2163 		} else {
2164 			if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2165 					       &nbd->flags))
2166 				refcount_inc(&nbd->refs);
2167 		}
2168 
2169 		if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2170 			set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2171 					&config->runtime_flags);
2172 		} else {
2173 			clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2174 					&config->runtime_flags);
2175 		}
2176 	}
2177 
2178 	if (info->attrs[NBD_ATTR_SOCKETS]) {
2179 		struct nlattr *attr;
2180 		int rem, fd;
2181 
2182 		nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2183 				    rem) {
2184 			struct nlattr *socks[NBD_SOCK_MAX+1];
2185 
2186 			if (nla_type(attr) != NBD_SOCK_ITEM) {
2187 				printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2188 				ret = -EINVAL;
2189 				goto out;
2190 			}
2191 			ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2192 							  attr,
2193 							  nbd_sock_policy,
2194 							  info->extack);
2195 			if (ret != 0) {
2196 				printk(KERN_ERR "nbd: error processing sock list\n");
2197 				ret = -EINVAL;
2198 				goto out;
2199 			}
2200 			if (!socks[NBD_SOCK_FD])
2201 				continue;
2202 			fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2203 			ret = nbd_reconnect_socket(nbd, fd);
2204 			if (ret) {
2205 				if (ret == -ENOSPC)
2206 					ret = 0;
2207 				goto out;
2208 			}
2209 			dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2210 		}
2211 	}
2212 out:
2213 	mutex_unlock(&nbd->config_lock);
2214 	nbd_config_put(nbd);
2215 	nbd_put(nbd);
2216 	if (put_dev)
2217 		nbd_put(nbd);
2218 	return ret;
2219 }
2220 
2221 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2222 	{
2223 		.cmd	= NBD_CMD_CONNECT,
2224 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2225 		.doit	= nbd_genl_connect,
2226 	},
2227 	{
2228 		.cmd	= NBD_CMD_DISCONNECT,
2229 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2230 		.doit	= nbd_genl_disconnect,
2231 	},
2232 	{
2233 		.cmd	= NBD_CMD_RECONFIGURE,
2234 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2235 		.doit	= nbd_genl_reconfigure,
2236 	},
2237 	{
2238 		.cmd	= NBD_CMD_STATUS,
2239 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2240 		.doit	= nbd_genl_status,
2241 	},
2242 };
2243 
2244 static const struct genl_multicast_group nbd_mcast_grps[] = {
2245 	{ .name = NBD_GENL_MCAST_GROUP_NAME, },
2246 };
2247 
2248 static struct genl_family nbd_genl_family __ro_after_init = {
2249 	.hdrsize	= 0,
2250 	.name		= NBD_GENL_FAMILY_NAME,
2251 	.version	= NBD_GENL_VERSION,
2252 	.module		= THIS_MODULE,
2253 	.small_ops	= nbd_connect_genl_ops,
2254 	.n_small_ops	= ARRAY_SIZE(nbd_connect_genl_ops),
2255 	.maxattr	= NBD_ATTR_MAX,
2256 	.policy = nbd_attr_policy,
2257 	.mcgrps		= nbd_mcast_grps,
2258 	.n_mcgrps	= ARRAY_SIZE(nbd_mcast_grps),
2259 };
2260 
2261 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2262 {
2263 	struct nlattr *dev_opt;
2264 	u8 connected = 0;
2265 	int ret;
2266 
2267 	/* This is a little racey, but for status it's ok.  The
2268 	 * reason we don't take a ref here is because we can't
2269 	 * take a ref in the index == -1 case as we would need
2270 	 * to put under the nbd_index_mutex, which could
2271 	 * deadlock if we are configured to remove ourselves
2272 	 * once we're disconnected.
2273 	 */
2274 	if (refcount_read(&nbd->config_refs))
2275 		connected = 1;
2276 	dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2277 	if (!dev_opt)
2278 		return -EMSGSIZE;
2279 	ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2280 	if (ret)
2281 		return -EMSGSIZE;
2282 	ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2283 			 connected);
2284 	if (ret)
2285 		return -EMSGSIZE;
2286 	nla_nest_end(reply, dev_opt);
2287 	return 0;
2288 }
2289 
2290 static int status_cb(int id, void *ptr, void *data)
2291 {
2292 	struct nbd_device *nbd = ptr;
2293 	return populate_nbd_status(nbd, (struct sk_buff *)data);
2294 }
2295 
2296 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2297 {
2298 	struct nlattr *dev_list;
2299 	struct sk_buff *reply;
2300 	void *reply_head;
2301 	size_t msg_size;
2302 	int index = -1;
2303 	int ret = -ENOMEM;
2304 
2305 	if (info->attrs[NBD_ATTR_INDEX])
2306 		index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2307 
2308 	mutex_lock(&nbd_index_mutex);
2309 
2310 	msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2311 				  nla_attr_size(sizeof(u8)));
2312 	msg_size *= (index == -1) ? nbd_total_devices : 1;
2313 
2314 	reply = genlmsg_new(msg_size, GFP_KERNEL);
2315 	if (!reply)
2316 		goto out;
2317 	reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2318 				       NBD_CMD_STATUS);
2319 	if (!reply_head) {
2320 		nlmsg_free(reply);
2321 		goto out;
2322 	}
2323 
2324 	dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2325 	if (index == -1) {
2326 		ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2327 		if (ret) {
2328 			nlmsg_free(reply);
2329 			goto out;
2330 		}
2331 	} else {
2332 		struct nbd_device *nbd;
2333 		nbd = idr_find(&nbd_index_idr, index);
2334 		if (nbd) {
2335 			ret = populate_nbd_status(nbd, reply);
2336 			if (ret) {
2337 				nlmsg_free(reply);
2338 				goto out;
2339 			}
2340 		}
2341 	}
2342 	nla_nest_end(reply, dev_list);
2343 	genlmsg_end(reply, reply_head);
2344 	ret = genlmsg_reply(reply, info);
2345 out:
2346 	mutex_unlock(&nbd_index_mutex);
2347 	return ret;
2348 }
2349 
2350 static void nbd_connect_reply(struct genl_info *info, int index)
2351 {
2352 	struct sk_buff *skb;
2353 	void *msg_head;
2354 	int ret;
2355 
2356 	skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2357 	if (!skb)
2358 		return;
2359 	msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2360 				     NBD_CMD_CONNECT);
2361 	if (!msg_head) {
2362 		nlmsg_free(skb);
2363 		return;
2364 	}
2365 	ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2366 	if (ret) {
2367 		nlmsg_free(skb);
2368 		return;
2369 	}
2370 	genlmsg_end(skb, msg_head);
2371 	genlmsg_reply(skb, info);
2372 }
2373 
2374 static void nbd_mcast_index(int index)
2375 {
2376 	struct sk_buff *skb;
2377 	void *msg_head;
2378 	int ret;
2379 
2380 	skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2381 	if (!skb)
2382 		return;
2383 	msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2384 				     NBD_CMD_LINK_DEAD);
2385 	if (!msg_head) {
2386 		nlmsg_free(skb);
2387 		return;
2388 	}
2389 	ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2390 	if (ret) {
2391 		nlmsg_free(skb);
2392 		return;
2393 	}
2394 	genlmsg_end(skb, msg_head);
2395 	genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2396 }
2397 
2398 static void nbd_dead_link_work(struct work_struct *work)
2399 {
2400 	struct link_dead_args *args = container_of(work, struct link_dead_args,
2401 						   work);
2402 	nbd_mcast_index(args->index);
2403 	kfree(args);
2404 }
2405 
2406 static int __init nbd_init(void)
2407 {
2408 	int i;
2409 
2410 	BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2411 
2412 	if (max_part < 0) {
2413 		printk(KERN_ERR "nbd: max_part must be >= 0\n");
2414 		return -EINVAL;
2415 	}
2416 
2417 	part_shift = 0;
2418 	if (max_part > 0) {
2419 		part_shift = fls(max_part);
2420 
2421 		/*
2422 		 * Adjust max_part according to part_shift as it is exported
2423 		 * to user space so that user can know the max number of
2424 		 * partition kernel should be able to manage.
2425 		 *
2426 		 * Note that -1 is required because partition 0 is reserved
2427 		 * for the whole disk.
2428 		 */
2429 		max_part = (1UL << part_shift) - 1;
2430 	}
2431 
2432 	if ((1UL << part_shift) > DISK_MAX_PARTS)
2433 		return -EINVAL;
2434 
2435 	if (nbds_max > 1UL << (MINORBITS - part_shift))
2436 		return -EINVAL;
2437 
2438 	if (register_blkdev(NBD_MAJOR, "nbd"))
2439 		return -EIO;
2440 
2441 	nbd_del_wq = alloc_workqueue("nbd-del", WQ_UNBOUND, 0);
2442 	if (!nbd_del_wq) {
2443 		unregister_blkdev(NBD_MAJOR, "nbd");
2444 		return -ENOMEM;
2445 	}
2446 
2447 	if (genl_register_family(&nbd_genl_family)) {
2448 		destroy_workqueue(nbd_del_wq);
2449 		unregister_blkdev(NBD_MAJOR, "nbd");
2450 		return -EINVAL;
2451 	}
2452 	nbd_dbg_init();
2453 
2454 	for (i = 0; i < nbds_max; i++)
2455 		nbd_dev_add(i, 1);
2456 	return 0;
2457 }
2458 
2459 static int nbd_exit_cb(int id, void *ptr, void *data)
2460 {
2461 	struct list_head *list = (struct list_head *)data;
2462 	struct nbd_device *nbd = ptr;
2463 
2464 	/* Skip nbd that is being removed asynchronously */
2465 	if (refcount_read(&nbd->refs))
2466 		list_add_tail(&nbd->list, list);
2467 
2468 	return 0;
2469 }
2470 
2471 static void __exit nbd_cleanup(void)
2472 {
2473 	struct nbd_device *nbd;
2474 	LIST_HEAD(del_list);
2475 
2476 	nbd_dbg_close();
2477 
2478 	mutex_lock(&nbd_index_mutex);
2479 	idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2480 	mutex_unlock(&nbd_index_mutex);
2481 
2482 	while (!list_empty(&del_list)) {
2483 		nbd = list_first_entry(&del_list, struct nbd_device, list);
2484 		list_del_init(&nbd->list);
2485 		if (refcount_read(&nbd->refs) != 1)
2486 			printk(KERN_ERR "nbd: possibly leaking a device\n");
2487 		nbd_put(nbd);
2488 	}
2489 
2490 	/* Also wait for nbd_dev_remove_work() completes */
2491 	destroy_workqueue(nbd_del_wq);
2492 
2493 	idr_destroy(&nbd_index_idr);
2494 	genl_unregister_family(&nbd_genl_family);
2495 	unregister_blkdev(NBD_MAJOR, "nbd");
2496 }
2497 
2498 module_init(nbd_init);
2499 module_exit(nbd_cleanup);
2500 
2501 MODULE_DESCRIPTION("Network Block Device");
2502 MODULE_LICENSE("GPL");
2503 
2504 module_param(nbds_max, int, 0444);
2505 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2506 module_param(max_part, int, 0444);
2507 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");
2508