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