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