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