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