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