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