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