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