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