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