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