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