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