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