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