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