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