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