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