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