• 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 	if (test_bit(NBD_RT_DISCONNECTED, &config->runtime_flags))
940 		return 0;
941 	return wait_event_timeout(config->conn_wait,
942 				  atomic_read(&config->live_connections) > 0,
943 				  config->dead_conn_timeout) > 0;
944 }
945 
nbd_handle_cmd(struct nbd_cmd * cmd,int index)946 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
947 {
948 	struct request *req = blk_mq_rq_from_pdu(cmd);
949 	struct nbd_device *nbd = cmd->nbd;
950 	struct nbd_config *config;
951 	struct nbd_sock *nsock;
952 	int ret;
953 
954 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
955 		dev_err_ratelimited(disk_to_dev(nbd->disk),
956 				    "Socks array is empty\n");
957 		return -EINVAL;
958 	}
959 	config = nbd->config;
960 
961 	if (index >= config->num_connections) {
962 		dev_err_ratelimited(disk_to_dev(nbd->disk),
963 				    "Attempted send on invalid socket\n");
964 		nbd_config_put(nbd);
965 		return -EINVAL;
966 	}
967 	cmd->status = BLK_STS_OK;
968 again:
969 	nsock = config->socks[index];
970 	mutex_lock(&nsock->tx_lock);
971 	if (nsock->dead) {
972 		int old_index = index;
973 		index = find_fallback(nbd, index);
974 		mutex_unlock(&nsock->tx_lock);
975 		if (index < 0) {
976 			if (wait_for_reconnect(nbd)) {
977 				index = old_index;
978 				goto again;
979 			}
980 			/* All the sockets should already be down at this point,
981 			 * we just want to make sure that DISCONNECTED is set so
982 			 * any requests that come in that were queue'ed waiting
983 			 * for the reconnect timer don't trigger the timer again
984 			 * and instead just error out.
985 			 */
986 			sock_shutdown(nbd);
987 			nbd_config_put(nbd);
988 			return -EIO;
989 		}
990 		goto again;
991 	}
992 
993 	/* Handle the case that we have a pending request that was partially
994 	 * transmitted that _has_ to be serviced first.  We need to call requeue
995 	 * here so that it gets put _after_ the request that is already on the
996 	 * dispatch list.
997 	 */
998 	blk_mq_start_request(req);
999 	if (unlikely(nsock->pending && nsock->pending != req)) {
1000 		nbd_requeue_cmd(cmd);
1001 		ret = 0;
1002 		goto out;
1003 	}
1004 	/*
1005 	 * Some failures are related to the link going down, so anything that
1006 	 * returns EAGAIN can be retried on a different socket.
1007 	 */
1008 	ret = nbd_send_cmd(nbd, cmd, index);
1009 	/*
1010 	 * Access to this flag is protected by cmd->lock, thus it's safe to set
1011 	 * the flag after nbd_send_cmd() succeed to send request to server.
1012 	 */
1013 	if (!ret)
1014 		__set_bit(NBD_CMD_INFLIGHT, &cmd->flags);
1015 	else if (ret == -EAGAIN) {
1016 		dev_err_ratelimited(disk_to_dev(nbd->disk),
1017 				    "Request send failed, requeueing\n");
1018 		nbd_mark_nsock_dead(nbd, nsock, 1);
1019 		nbd_requeue_cmd(cmd);
1020 		ret = 0;
1021 	}
1022 out:
1023 	mutex_unlock(&nsock->tx_lock);
1024 	nbd_config_put(nbd);
1025 	return ret;
1026 }
1027 
nbd_queue_rq(struct blk_mq_hw_ctx * hctx,const struct blk_mq_queue_data * bd)1028 static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
1029 			const struct blk_mq_queue_data *bd)
1030 {
1031 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
1032 	int ret;
1033 
1034 	/*
1035 	 * Since we look at the bio's to send the request over the network we
1036 	 * need to make sure the completion work doesn't mark this request done
1037 	 * before we are done doing our send.  This keeps us from dereferencing
1038 	 * freed data if we have particularly fast completions (ie we get the
1039 	 * completion before we exit sock_xmit on the last bvec) or in the case
1040 	 * that the server is misbehaving (or there was an error) before we're
1041 	 * done sending everything over the wire.
1042 	 */
1043 	mutex_lock(&cmd->lock);
1044 	clear_bit(NBD_CMD_REQUEUED, &cmd->flags);
1045 
1046 	/* We can be called directly from the user space process, which means we
1047 	 * could possibly have signals pending so our sendmsg will fail.  In
1048 	 * this case we need to return that we are busy, otherwise error out as
1049 	 * appropriate.
1050 	 */
1051 	ret = nbd_handle_cmd(cmd, hctx->queue_num);
1052 	if (ret < 0)
1053 		ret = BLK_STS_IOERR;
1054 	else if (!ret)
1055 		ret = BLK_STS_OK;
1056 	mutex_unlock(&cmd->lock);
1057 
1058 	return ret;
1059 }
1060 
nbd_get_socket(struct nbd_device * nbd,unsigned long fd,int * err)1061 static struct socket *nbd_get_socket(struct nbd_device *nbd, unsigned long fd,
1062 				     int *err)
1063 {
1064 	struct socket *sock;
1065 
1066 	*err = 0;
1067 	sock = sockfd_lookup(fd, err);
1068 	if (!sock)
1069 		return NULL;
1070 
1071 	if (sock->ops->shutdown == sock_no_shutdown) {
1072 		dev_err(disk_to_dev(nbd->disk), "Unsupported socket: shutdown callout must be supported.\n");
1073 		*err = -EINVAL;
1074 		sockfd_put(sock);
1075 		return NULL;
1076 	}
1077 
1078 	return sock;
1079 }
1080 
nbd_add_socket(struct nbd_device * nbd,unsigned long arg,bool netlink)1081 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
1082 			  bool netlink)
1083 {
1084 	struct nbd_config *config = nbd->config;
1085 	struct socket *sock;
1086 	struct nbd_sock **socks;
1087 	struct nbd_sock *nsock;
1088 	int err;
1089 
1090 	sock = nbd_get_socket(nbd, arg, &err);
1091 	if (!sock)
1092 		return err;
1093 
1094 	/*
1095 	 * We need to make sure we don't get any errant requests while we're
1096 	 * reallocating the ->socks array.
1097 	 */
1098 	blk_mq_freeze_queue(nbd->disk->queue);
1099 
1100 	if (!netlink && !nbd->task_setup &&
1101 	    !test_bit(NBD_RT_BOUND, &config->runtime_flags))
1102 		nbd->task_setup = current;
1103 
1104 	if (!netlink &&
1105 	    (nbd->task_setup != current ||
1106 	     test_bit(NBD_RT_BOUND, &config->runtime_flags))) {
1107 		dev_err(disk_to_dev(nbd->disk),
1108 			"Device being setup by another task");
1109 		err = -EBUSY;
1110 		goto put_socket;
1111 	}
1112 
1113 	nsock = kzalloc(sizeof(*nsock), GFP_KERNEL);
1114 	if (!nsock) {
1115 		err = -ENOMEM;
1116 		goto put_socket;
1117 	}
1118 
1119 	socks = krealloc(config->socks, (config->num_connections + 1) *
1120 			 sizeof(struct nbd_sock *), GFP_KERNEL);
1121 	if (!socks) {
1122 		kfree(nsock);
1123 		err = -ENOMEM;
1124 		goto put_socket;
1125 	}
1126 
1127 	config->socks = socks;
1128 
1129 	nsock->fallback_index = -1;
1130 	nsock->dead = false;
1131 	mutex_init(&nsock->tx_lock);
1132 	nsock->sock = sock;
1133 	nsock->pending = NULL;
1134 	nsock->sent = 0;
1135 	nsock->cookie = 0;
1136 	socks[config->num_connections++] = nsock;
1137 	atomic_inc(&config->live_connections);
1138 	blk_mq_unfreeze_queue(nbd->disk->queue);
1139 
1140 	return 0;
1141 
1142 put_socket:
1143 	blk_mq_unfreeze_queue(nbd->disk->queue);
1144 	sockfd_put(sock);
1145 	return err;
1146 }
1147 
nbd_reconnect_socket(struct nbd_device * nbd,unsigned long arg)1148 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
1149 {
1150 	struct nbd_config *config = nbd->config;
1151 	struct socket *sock, *old;
1152 	struct recv_thread_args *args;
1153 	int i;
1154 	int err;
1155 
1156 	sock = nbd_get_socket(nbd, arg, &err);
1157 	if (!sock)
1158 		return err;
1159 
1160 	args = kzalloc(sizeof(*args), GFP_KERNEL);
1161 	if (!args) {
1162 		sockfd_put(sock);
1163 		return -ENOMEM;
1164 	}
1165 
1166 	for (i = 0; i < config->num_connections; i++) {
1167 		struct nbd_sock *nsock = config->socks[i];
1168 
1169 		if (!nsock->dead)
1170 			continue;
1171 
1172 		mutex_lock(&nsock->tx_lock);
1173 		if (!nsock->dead) {
1174 			mutex_unlock(&nsock->tx_lock);
1175 			continue;
1176 		}
1177 		sk_set_memalloc(sock->sk);
1178 		if (nbd->tag_set.timeout)
1179 			sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1180 		atomic_inc(&config->recv_threads);
1181 		refcount_inc(&nbd->config_refs);
1182 		old = nsock->sock;
1183 		nsock->fallback_index = -1;
1184 		nsock->sock = sock;
1185 		nsock->dead = false;
1186 		INIT_WORK(&args->work, recv_work);
1187 		args->index = i;
1188 		args->nbd = nbd;
1189 		nsock->cookie++;
1190 		mutex_unlock(&nsock->tx_lock);
1191 		sockfd_put(old);
1192 
1193 		clear_bit(NBD_RT_DISCONNECTED, &config->runtime_flags);
1194 
1195 		/* We take the tx_mutex in an error path in the recv_work, so we
1196 		 * need to queue_work outside of the tx_mutex.
1197 		 */
1198 		queue_work(nbd->recv_workq, &args->work);
1199 
1200 		atomic_inc(&config->live_connections);
1201 		wake_up(&config->conn_wait);
1202 		return 0;
1203 	}
1204 	sockfd_put(sock);
1205 	kfree(args);
1206 	return -ENOSPC;
1207 }
1208 
nbd_bdev_reset(struct block_device * bdev)1209 static void nbd_bdev_reset(struct block_device *bdev)
1210 {
1211 	if (bdev->bd_openers > 1)
1212 		return;
1213 	bd_set_nr_sectors(bdev, 0);
1214 }
1215 
nbd_parse_flags(struct nbd_device * nbd)1216 static void nbd_parse_flags(struct nbd_device *nbd)
1217 {
1218 	struct nbd_config *config = nbd->config;
1219 	if (config->flags & NBD_FLAG_READ_ONLY)
1220 		set_disk_ro(nbd->disk, true);
1221 	else
1222 		set_disk_ro(nbd->disk, false);
1223 	if (config->flags & NBD_FLAG_SEND_TRIM)
1224 		blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1225 	if (config->flags & NBD_FLAG_SEND_FLUSH) {
1226 		if (config->flags & NBD_FLAG_SEND_FUA)
1227 			blk_queue_write_cache(nbd->disk->queue, true, true);
1228 		else
1229 			blk_queue_write_cache(nbd->disk->queue, true, false);
1230 	}
1231 	else
1232 		blk_queue_write_cache(nbd->disk->queue, false, false);
1233 }
1234 
send_disconnects(struct nbd_device * nbd)1235 static void send_disconnects(struct nbd_device *nbd)
1236 {
1237 	struct nbd_config *config = nbd->config;
1238 	struct nbd_request request = {
1239 		.magic = htonl(NBD_REQUEST_MAGIC),
1240 		.type = htonl(NBD_CMD_DISC),
1241 	};
1242 	struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1243 	struct iov_iter from;
1244 	int i, ret;
1245 
1246 	for (i = 0; i < config->num_connections; i++) {
1247 		struct nbd_sock *nsock = config->socks[i];
1248 
1249 		iov_iter_kvec(&from, WRITE, &iov, 1, sizeof(request));
1250 		mutex_lock(&nsock->tx_lock);
1251 		ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
1252 		if (ret < 0)
1253 			dev_err(disk_to_dev(nbd->disk),
1254 				"Send disconnect failed %d\n", ret);
1255 		mutex_unlock(&nsock->tx_lock);
1256 	}
1257 }
1258 
nbd_disconnect(struct nbd_device * nbd)1259 static int nbd_disconnect(struct nbd_device *nbd)
1260 {
1261 	struct nbd_config *config = nbd->config;
1262 
1263 	dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1264 	set_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags);
1265 	set_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags);
1266 	send_disconnects(nbd);
1267 	return 0;
1268 }
1269 
nbd_clear_sock(struct nbd_device * nbd)1270 static void nbd_clear_sock(struct nbd_device *nbd)
1271 {
1272 	sock_shutdown(nbd);
1273 	nbd_clear_que(nbd);
1274 	nbd->task_setup = NULL;
1275 }
1276 
nbd_config_put(struct nbd_device * nbd)1277 static void nbd_config_put(struct nbd_device *nbd)
1278 {
1279 	if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1280 					&nbd->config_lock)) {
1281 		struct nbd_config *config = nbd->config;
1282 		nbd_dev_dbg_close(nbd);
1283 		nbd_size_clear(nbd);
1284 		if (test_and_clear_bit(NBD_RT_HAS_PID_FILE,
1285 				       &config->runtime_flags))
1286 			device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1287 		nbd->pid = 0;
1288 		nbd_clear_sock(nbd);
1289 		if (config->num_connections) {
1290 			int i;
1291 			for (i = 0; i < config->num_connections; i++) {
1292 				sockfd_put(config->socks[i]->sock);
1293 				kfree(config->socks[i]);
1294 			}
1295 			kfree(config->socks);
1296 		}
1297 		kfree(nbd->config);
1298 		nbd->config = NULL;
1299 
1300 		if (nbd->recv_workq)
1301 			destroy_workqueue(nbd->recv_workq);
1302 		nbd->recv_workq = NULL;
1303 
1304 		nbd->tag_set.timeout = 0;
1305 		nbd->disk->queue->limits.discard_granularity = 0;
1306 		nbd->disk->queue->limits.discard_alignment = 0;
1307 		blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
1308 		blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
1309 
1310 		mutex_unlock(&nbd->config_lock);
1311 		nbd_put(nbd);
1312 		module_put(THIS_MODULE);
1313 	}
1314 }
1315 
nbd_start_device(struct nbd_device * nbd)1316 static int nbd_start_device(struct nbd_device *nbd)
1317 {
1318 	struct nbd_config *config = nbd->config;
1319 	int num_connections = config->num_connections;
1320 	int error = 0, i;
1321 
1322 	if (nbd->pid)
1323 		return -EBUSY;
1324 	if (!config->socks)
1325 		return -EINVAL;
1326 	if (num_connections > 1 &&
1327 	    !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1328 		dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1329 		return -EINVAL;
1330 	}
1331 
1332 	nbd->recv_workq = alloc_workqueue("knbd%d-recv",
1333 					  WQ_MEM_RECLAIM | WQ_HIGHPRI |
1334 					  WQ_UNBOUND, 0, nbd->index);
1335 	if (!nbd->recv_workq) {
1336 		dev_err(disk_to_dev(nbd->disk), "Could not allocate knbd recv work queue.\n");
1337 		return -ENOMEM;
1338 	}
1339 
1340 	blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1341 	nbd->pid = task_pid_nr(current);
1342 
1343 	nbd_parse_flags(nbd);
1344 
1345 	error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1346 	if (error) {
1347 		dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1348 		return error;
1349 	}
1350 	set_bit(NBD_RT_HAS_PID_FILE, &config->runtime_flags);
1351 
1352 	nbd_dev_dbg_init(nbd);
1353 	for (i = 0; i < num_connections; i++) {
1354 		struct recv_thread_args *args;
1355 
1356 		args = kzalloc(sizeof(*args), GFP_KERNEL);
1357 		if (!args) {
1358 			sock_shutdown(nbd);
1359 			/*
1360 			 * If num_connections is m (2 < m),
1361 			 * and NO.1 ~ NO.n(1 < n < m) kzallocs are successful.
1362 			 * But NO.(n + 1) failed. We still have n recv threads.
1363 			 * So, add flush_workqueue here to prevent recv threads
1364 			 * dropping the last config_refs and trying to destroy
1365 			 * the workqueue from inside the workqueue.
1366 			 */
1367 			if (i)
1368 				flush_workqueue(nbd->recv_workq);
1369 			return -ENOMEM;
1370 		}
1371 		sk_set_memalloc(config->socks[i]->sock->sk);
1372 		if (nbd->tag_set.timeout)
1373 			config->socks[i]->sock->sk->sk_sndtimeo =
1374 				nbd->tag_set.timeout;
1375 		atomic_inc(&config->recv_threads);
1376 		refcount_inc(&nbd->config_refs);
1377 		INIT_WORK(&args->work, recv_work);
1378 		args->nbd = nbd;
1379 		args->index = i;
1380 		queue_work(nbd->recv_workq, &args->work);
1381 	}
1382 	nbd_size_update(nbd, true);
1383 	return error;
1384 }
1385 
nbd_start_device_ioctl(struct nbd_device * nbd,struct block_device * bdev)1386 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1387 {
1388 	struct nbd_config *config = nbd->config;
1389 	int ret;
1390 
1391 	ret = nbd_start_device(nbd);
1392 	if (ret)
1393 		return ret;
1394 
1395 	if (max_part)
1396 		set_bit(GD_NEED_PART_SCAN, &nbd->disk->state);
1397 	mutex_unlock(&nbd->config_lock);
1398 	ret = wait_event_interruptible(config->recv_wq,
1399 					 atomic_read(&config->recv_threads) == 0);
1400 	if (ret)
1401 		sock_shutdown(nbd);
1402 	flush_workqueue(nbd->recv_workq);
1403 
1404 	mutex_lock(&nbd->config_lock);
1405 	nbd_bdev_reset(bdev);
1406 	/* user requested, ignore socket errors */
1407 	if (test_bit(NBD_RT_DISCONNECT_REQUESTED, &config->runtime_flags))
1408 		ret = 0;
1409 	if (test_bit(NBD_RT_TIMEDOUT, &config->runtime_flags))
1410 		ret = -ETIMEDOUT;
1411 	return ret;
1412 }
1413 
nbd_clear_sock_ioctl(struct nbd_device * nbd,struct block_device * bdev)1414 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1415 				 struct block_device *bdev)
1416 {
1417 	sock_shutdown(nbd);
1418 	__invalidate_device(bdev, true);
1419 	nbd_bdev_reset(bdev);
1420 	if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
1421 			       &nbd->config->runtime_flags))
1422 		nbd_config_put(nbd);
1423 }
1424 
nbd_is_valid_blksize(unsigned long blksize)1425 static bool nbd_is_valid_blksize(unsigned long blksize)
1426 {
1427 	if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1428 	    blksize > PAGE_SIZE)
1429 		return false;
1430 	return true;
1431 }
1432 
nbd_set_cmd_timeout(struct nbd_device * nbd,u64 timeout)1433 static void nbd_set_cmd_timeout(struct nbd_device *nbd, u64 timeout)
1434 {
1435 	nbd->tag_set.timeout = timeout * HZ;
1436 	if (timeout)
1437 		blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1438 	else
1439 		blk_queue_rq_timeout(nbd->disk->queue, 30 * HZ);
1440 }
1441 
1442 /* Must be called with config_lock held */
__nbd_ioctl(struct block_device * bdev,struct nbd_device * nbd,unsigned int cmd,unsigned long arg)1443 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1444 		       unsigned int cmd, unsigned long arg)
1445 {
1446 	struct nbd_config *config = nbd->config;
1447 	loff_t bytesize;
1448 
1449 	switch (cmd) {
1450 	case NBD_DISCONNECT:
1451 		return nbd_disconnect(nbd);
1452 	case NBD_CLEAR_SOCK:
1453 		nbd_clear_sock_ioctl(nbd, bdev);
1454 		return 0;
1455 	case NBD_SET_SOCK:
1456 		return nbd_add_socket(nbd, arg, false);
1457 	case NBD_SET_BLKSIZE:
1458 		if (!arg)
1459 			arg = NBD_DEF_BLKSIZE;
1460 		if (!nbd_is_valid_blksize(arg))
1461 			return -EINVAL;
1462 		nbd_size_set(nbd, arg,
1463 			     div_s64(config->bytesize, arg));
1464 		return 0;
1465 	case NBD_SET_SIZE:
1466 		nbd_size_set(nbd, config->blksize,
1467 			     div_s64(arg, config->blksize));
1468 		return 0;
1469 	case NBD_SET_SIZE_BLOCKS:
1470 		if (check_mul_overflow((loff_t)arg, config->blksize, &bytesize))
1471 			return -EINVAL;
1472 		nbd_size_set(nbd, config->blksize, arg);
1473 		return 0;
1474 	case NBD_SET_TIMEOUT:
1475 		nbd_set_cmd_timeout(nbd, arg);
1476 		return 0;
1477 
1478 	case NBD_SET_FLAGS:
1479 		config->flags = arg;
1480 		return 0;
1481 	case NBD_DO_IT:
1482 		return nbd_start_device_ioctl(nbd, bdev);
1483 	case NBD_CLEAR_QUE:
1484 		/*
1485 		 * This is for compatibility only.  The queue is always cleared
1486 		 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1487 		 */
1488 		return 0;
1489 	case NBD_PRINT_DEBUG:
1490 		/*
1491 		 * For compatibility only, we no longer keep a list of
1492 		 * outstanding requests.
1493 		 */
1494 		return 0;
1495 	}
1496 	return -ENOTTY;
1497 }
1498 
nbd_ioctl(struct block_device * bdev,fmode_t mode,unsigned int cmd,unsigned long arg)1499 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1500 		     unsigned int cmd, unsigned long arg)
1501 {
1502 	struct nbd_device *nbd = bdev->bd_disk->private_data;
1503 	struct nbd_config *config = nbd->config;
1504 	int error = -EINVAL;
1505 
1506 	if (!capable(CAP_SYS_ADMIN))
1507 		return -EPERM;
1508 
1509 	/* The block layer will pass back some non-nbd ioctls in case we have
1510 	 * special handling for them, but we don't so just return an error.
1511 	 */
1512 	if (_IOC_TYPE(cmd) != 0xab)
1513 		return -EINVAL;
1514 
1515 	mutex_lock(&nbd->config_lock);
1516 
1517 	/* Don't allow ioctl operations on a nbd device that was created with
1518 	 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1519 	 */
1520 	if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
1521 	    (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1522 		error = __nbd_ioctl(bdev, nbd, cmd, arg);
1523 	else
1524 		dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1525 	mutex_unlock(&nbd->config_lock);
1526 	return error;
1527 }
1528 
nbd_alloc_config(void)1529 static struct nbd_config *nbd_alloc_config(void)
1530 {
1531 	struct nbd_config *config;
1532 
1533 	config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1534 	if (!config)
1535 		return NULL;
1536 	atomic_set(&config->recv_threads, 0);
1537 	init_waitqueue_head(&config->recv_wq);
1538 	init_waitqueue_head(&config->conn_wait);
1539 	config->blksize = NBD_DEF_BLKSIZE;
1540 	atomic_set(&config->live_connections, 0);
1541 	try_module_get(THIS_MODULE);
1542 	return config;
1543 }
1544 
nbd_open(struct block_device * bdev,fmode_t mode)1545 static int nbd_open(struct block_device *bdev, fmode_t mode)
1546 {
1547 	struct nbd_device *nbd;
1548 	int ret = 0;
1549 
1550 	mutex_lock(&nbd_index_mutex);
1551 	nbd = bdev->bd_disk->private_data;
1552 	if (!nbd) {
1553 		ret = -ENXIO;
1554 		goto out;
1555 	}
1556 	if (!refcount_inc_not_zero(&nbd->refs)) {
1557 		ret = -ENXIO;
1558 		goto out;
1559 	}
1560 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
1561 		struct nbd_config *config;
1562 
1563 		mutex_lock(&nbd->config_lock);
1564 		if (refcount_inc_not_zero(&nbd->config_refs)) {
1565 			mutex_unlock(&nbd->config_lock);
1566 			goto out;
1567 		}
1568 		config = nbd->config = nbd_alloc_config();
1569 		if (!config) {
1570 			ret = -ENOMEM;
1571 			mutex_unlock(&nbd->config_lock);
1572 			goto out;
1573 		}
1574 		refcount_set(&nbd->config_refs, 1);
1575 		refcount_inc(&nbd->refs);
1576 		mutex_unlock(&nbd->config_lock);
1577 		set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1578 	} else if (nbd_disconnected(nbd->config)) {
1579 		set_bit(GD_NEED_PART_SCAN, &bdev->bd_disk->state);
1580 	}
1581 out:
1582 	mutex_unlock(&nbd_index_mutex);
1583 	return ret;
1584 }
1585 
nbd_release(struct gendisk * disk,fmode_t mode)1586 static void nbd_release(struct gendisk *disk, fmode_t mode)
1587 {
1588 	struct nbd_device *nbd = disk->private_data;
1589 	struct block_device *bdev = bdget_disk(disk, 0);
1590 
1591 	if (test_bit(NBD_RT_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1592 			bdev->bd_openers == 0)
1593 		nbd_disconnect_and_put(nbd);
1594 	bdput(bdev);
1595 
1596 	nbd_config_put(nbd);
1597 	nbd_put(nbd);
1598 }
1599 
1600 static const struct block_device_operations nbd_fops =
1601 {
1602 	.owner =	THIS_MODULE,
1603 	.open =		nbd_open,
1604 	.release =	nbd_release,
1605 	.ioctl =	nbd_ioctl,
1606 	.compat_ioctl =	nbd_ioctl,
1607 };
1608 
1609 #if IS_ENABLED(CONFIG_DEBUG_FS)
1610 
nbd_dbg_tasks_show(struct seq_file * s,void * unused)1611 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1612 {
1613 	struct nbd_device *nbd = s->private;
1614 
1615 	if (nbd->pid)
1616 		seq_printf(s, "recv: %d\n", nbd->pid);
1617 
1618 	return 0;
1619 }
1620 
nbd_dbg_tasks_open(struct inode * inode,struct file * file)1621 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1622 {
1623 	return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1624 }
1625 
1626 static const struct file_operations nbd_dbg_tasks_ops = {
1627 	.open = nbd_dbg_tasks_open,
1628 	.read = seq_read,
1629 	.llseek = seq_lseek,
1630 	.release = single_release,
1631 };
1632 
nbd_dbg_flags_show(struct seq_file * s,void * unused)1633 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1634 {
1635 	struct nbd_device *nbd = s->private;
1636 	u32 flags = nbd->config->flags;
1637 
1638 	seq_printf(s, "Hex: 0x%08x\n\n", flags);
1639 
1640 	seq_puts(s, "Known flags:\n");
1641 
1642 	if (flags & NBD_FLAG_HAS_FLAGS)
1643 		seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1644 	if (flags & NBD_FLAG_READ_ONLY)
1645 		seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1646 	if (flags & NBD_FLAG_SEND_FLUSH)
1647 		seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1648 	if (flags & NBD_FLAG_SEND_FUA)
1649 		seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1650 	if (flags & NBD_FLAG_SEND_TRIM)
1651 		seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1652 
1653 	return 0;
1654 }
1655 
nbd_dbg_flags_open(struct inode * inode,struct file * file)1656 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1657 {
1658 	return single_open(file, nbd_dbg_flags_show, inode->i_private);
1659 }
1660 
1661 static const struct file_operations nbd_dbg_flags_ops = {
1662 	.open = nbd_dbg_flags_open,
1663 	.read = seq_read,
1664 	.llseek = seq_lseek,
1665 	.release = single_release,
1666 };
1667 
nbd_dev_dbg_init(struct nbd_device * nbd)1668 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1669 {
1670 	struct dentry *dir;
1671 	struct nbd_config *config = nbd->config;
1672 
1673 	if (!nbd_dbg_dir)
1674 		return -EIO;
1675 
1676 	dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1677 	if (!dir) {
1678 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1679 			nbd_name(nbd));
1680 		return -EIO;
1681 	}
1682 	config->dbg_dir = dir;
1683 
1684 	debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1685 	debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1686 	debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1687 	debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1688 	debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1689 
1690 	return 0;
1691 }
1692 
nbd_dev_dbg_close(struct nbd_device * nbd)1693 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1694 {
1695 	debugfs_remove_recursive(nbd->config->dbg_dir);
1696 }
1697 
nbd_dbg_init(void)1698 static int nbd_dbg_init(void)
1699 {
1700 	struct dentry *dbg_dir;
1701 
1702 	dbg_dir = debugfs_create_dir("nbd", NULL);
1703 	if (!dbg_dir)
1704 		return -EIO;
1705 
1706 	nbd_dbg_dir = dbg_dir;
1707 
1708 	return 0;
1709 }
1710 
nbd_dbg_close(void)1711 static void nbd_dbg_close(void)
1712 {
1713 	debugfs_remove_recursive(nbd_dbg_dir);
1714 }
1715 
1716 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
1717 
nbd_dev_dbg_init(struct nbd_device * nbd)1718 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1719 {
1720 	return 0;
1721 }
1722 
nbd_dev_dbg_close(struct nbd_device * nbd)1723 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1724 {
1725 }
1726 
nbd_dbg_init(void)1727 static int nbd_dbg_init(void)
1728 {
1729 	return 0;
1730 }
1731 
nbd_dbg_close(void)1732 static void nbd_dbg_close(void)
1733 {
1734 }
1735 
1736 #endif
1737 
nbd_init_request(struct blk_mq_tag_set * set,struct request * rq,unsigned int hctx_idx,unsigned int numa_node)1738 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1739 			    unsigned int hctx_idx, unsigned int numa_node)
1740 {
1741 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1742 	cmd->nbd = set->driver_data;
1743 	cmd->flags = 0;
1744 	mutex_init(&cmd->lock);
1745 	return 0;
1746 }
1747 
1748 static const struct blk_mq_ops nbd_mq_ops = {
1749 	.queue_rq	= nbd_queue_rq,
1750 	.complete	= nbd_complete_rq,
1751 	.init_request	= nbd_init_request,
1752 	.timeout	= nbd_xmit_timeout,
1753 };
1754 
nbd_dev_add(int index)1755 static int nbd_dev_add(int index)
1756 {
1757 	struct nbd_device *nbd;
1758 	struct gendisk *disk;
1759 	struct request_queue *q;
1760 	int err = -ENOMEM;
1761 
1762 	nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1763 	if (!nbd)
1764 		goto out;
1765 
1766 	disk = alloc_disk(1 << part_shift);
1767 	if (!disk)
1768 		goto out_free_nbd;
1769 
1770 	if (index >= 0) {
1771 		err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1772 				GFP_KERNEL);
1773 		if (err == -ENOSPC)
1774 			err = -EEXIST;
1775 	} else {
1776 		err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1777 		if (err >= 0)
1778 			index = err;
1779 	}
1780 	if (err < 0)
1781 		goto out_free_disk;
1782 
1783 	nbd->index = index;
1784 	nbd->disk = disk;
1785 	nbd->tag_set.ops = &nbd_mq_ops;
1786 	nbd->tag_set.nr_hw_queues = 1;
1787 	nbd->tag_set.queue_depth = 128;
1788 	nbd->tag_set.numa_node = NUMA_NO_NODE;
1789 	nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1790 	nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1791 		BLK_MQ_F_BLOCKING;
1792 	nbd->tag_set.driver_data = nbd;
1793 	nbd->destroy_complete = NULL;
1794 
1795 	err = blk_mq_alloc_tag_set(&nbd->tag_set);
1796 	if (err)
1797 		goto out_free_idr;
1798 
1799 	q = blk_mq_init_queue(&nbd->tag_set);
1800 	if (IS_ERR(q)) {
1801 		err = PTR_ERR(q);
1802 		goto out_free_tags;
1803 	}
1804 	disk->queue = q;
1805 
1806 	/*
1807 	 * Tell the block layer that we are not a rotational device
1808 	 */
1809 	blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1810 	blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1811 	disk->queue->limits.discard_granularity = 0;
1812 	disk->queue->limits.discard_alignment = 0;
1813 	blk_queue_max_discard_sectors(disk->queue, 0);
1814 	blk_queue_max_segment_size(disk->queue, UINT_MAX);
1815 	blk_queue_max_segments(disk->queue, USHRT_MAX);
1816 	blk_queue_max_hw_sectors(disk->queue, 65536);
1817 	disk->queue->limits.max_sectors = 256;
1818 
1819 	mutex_init(&nbd->config_lock);
1820 	refcount_set(&nbd->config_refs, 0);
1821 	refcount_set(&nbd->refs, 1);
1822 	INIT_LIST_HEAD(&nbd->list);
1823 	disk->major = NBD_MAJOR;
1824 
1825 	/*
1826 	 * Too big index can cause duplicate creation of sysfs files/links,
1827 	 * because MKDEV() expect that the max first minor is MINORMASK, or
1828 	 * index << part_shift can overflow.
1829 	 */
1830 	disk->first_minor = index << part_shift;
1831 	if (disk->first_minor < index || disk->first_minor > MINORMASK) {
1832 		err = -EINVAL;
1833 		goto out_free_tags;
1834 	}
1835 
1836 	disk->fops = &nbd_fops;
1837 	disk->private_data = nbd;
1838 	sprintf(disk->disk_name, "nbd%d", index);
1839 	add_disk(disk);
1840 	nbd_total_devices++;
1841 	return index;
1842 
1843 out_free_tags:
1844 	blk_mq_free_tag_set(&nbd->tag_set);
1845 out_free_idr:
1846 	idr_remove(&nbd_index_idr, index);
1847 out_free_disk:
1848 	put_disk(disk);
1849 out_free_nbd:
1850 	kfree(nbd);
1851 out:
1852 	return err;
1853 }
1854 
find_free_cb(int id,void * ptr,void * data)1855 static int find_free_cb(int id, void *ptr, void *data)
1856 {
1857 	struct nbd_device *nbd = ptr;
1858 	struct nbd_device **found = data;
1859 
1860 	if (!refcount_read(&nbd->config_refs)) {
1861 		*found = nbd;
1862 		return 1;
1863 	}
1864 	return 0;
1865 }
1866 
1867 /* Netlink interface. */
1868 static const struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1869 	[NBD_ATTR_INDEX]		=	{ .type = NLA_U32 },
1870 	[NBD_ATTR_SIZE_BYTES]		=	{ .type = NLA_U64 },
1871 	[NBD_ATTR_BLOCK_SIZE_BYTES]	=	{ .type = NLA_U64 },
1872 	[NBD_ATTR_TIMEOUT]		=	{ .type = NLA_U64 },
1873 	[NBD_ATTR_SERVER_FLAGS]		=	{ .type = NLA_U64 },
1874 	[NBD_ATTR_CLIENT_FLAGS]		=	{ .type = NLA_U64 },
1875 	[NBD_ATTR_SOCKETS]		=	{ .type = NLA_NESTED},
1876 	[NBD_ATTR_DEAD_CONN_TIMEOUT]	=	{ .type = NLA_U64 },
1877 	[NBD_ATTR_DEVICE_LIST]		=	{ .type = NLA_NESTED},
1878 };
1879 
1880 static const struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1881 	[NBD_SOCK_FD]			=	{ .type = NLA_U32 },
1882 };
1883 
1884 /* We don't use this right now since we don't parse the incoming list, but we
1885  * still want it here so userspace knows what to expect.
1886  */
1887 static const struct nla_policy __attribute__((unused))
1888 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1889 	[NBD_DEVICE_INDEX]		=	{ .type = NLA_U32 },
1890 	[NBD_DEVICE_CONNECTED]		=	{ .type = NLA_U8 },
1891 };
1892 
nbd_genl_size_set(struct genl_info * info,struct nbd_device * nbd)1893 static int nbd_genl_size_set(struct genl_info *info, struct nbd_device *nbd)
1894 {
1895 	struct nbd_config *config = nbd->config;
1896 	u64 bsize = config->blksize;
1897 	u64 bytes = config->bytesize;
1898 
1899 	if (info->attrs[NBD_ATTR_SIZE_BYTES])
1900 		bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1901 
1902 	if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1903 		bsize = nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1904 		if (!bsize)
1905 			bsize = NBD_DEF_BLKSIZE;
1906 		if (!nbd_is_valid_blksize(bsize)) {
1907 			printk(KERN_ERR "Invalid block size %llu\n", bsize);
1908 			return -EINVAL;
1909 		}
1910 	}
1911 
1912 	if (bytes != config->bytesize || bsize != config->blksize)
1913 		nbd_size_set(nbd, bsize, div64_u64(bytes, bsize));
1914 	return 0;
1915 }
1916 
nbd_genl_connect(struct sk_buff * skb,struct genl_info * info)1917 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1918 {
1919 	DECLARE_COMPLETION_ONSTACK(destroy_complete);
1920 	struct nbd_device *nbd = NULL;
1921 	struct nbd_config *config;
1922 	int index = -1;
1923 	int ret;
1924 	bool put_dev = false;
1925 
1926 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
1927 		return -EPERM;
1928 
1929 	if (info->attrs[NBD_ATTR_INDEX])
1930 		index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1931 	if (!info->attrs[NBD_ATTR_SOCKETS]) {
1932 		printk(KERN_ERR "nbd: must specify at least one socket\n");
1933 		return -EINVAL;
1934 	}
1935 	if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1936 		printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1937 		return -EINVAL;
1938 	}
1939 again:
1940 	mutex_lock(&nbd_index_mutex);
1941 	if (index == -1) {
1942 		ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1943 		if (ret == 0) {
1944 			int new_index;
1945 			new_index = nbd_dev_add(-1);
1946 			if (new_index < 0) {
1947 				mutex_unlock(&nbd_index_mutex);
1948 				printk(KERN_ERR "nbd: failed to add new device\n");
1949 				return new_index;
1950 			}
1951 			nbd = idr_find(&nbd_index_idr, new_index);
1952 		}
1953 	} else {
1954 		nbd = idr_find(&nbd_index_idr, index);
1955 		if (!nbd) {
1956 			ret = nbd_dev_add(index);
1957 			if (ret < 0) {
1958 				mutex_unlock(&nbd_index_mutex);
1959 				printk(KERN_ERR "nbd: failed to add new device\n");
1960 				return ret;
1961 			}
1962 			nbd = idr_find(&nbd_index_idr, index);
1963 		}
1964 	}
1965 	if (!nbd) {
1966 		printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1967 		       index);
1968 		mutex_unlock(&nbd_index_mutex);
1969 		return -EINVAL;
1970 	}
1971 
1972 	if (test_bit(NBD_DESTROY_ON_DISCONNECT, &nbd->flags) &&
1973 	    test_bit(NBD_DISCONNECT_REQUESTED, &nbd->flags)) {
1974 		nbd->destroy_complete = &destroy_complete;
1975 		mutex_unlock(&nbd_index_mutex);
1976 
1977 		/* Wait untill the the nbd stuff is totally destroyed */
1978 		wait_for_completion(&destroy_complete);
1979 		goto again;
1980 	}
1981 
1982 	if (!refcount_inc_not_zero(&nbd->refs)) {
1983 		mutex_unlock(&nbd_index_mutex);
1984 		if (index == -1)
1985 			goto again;
1986 		printk(KERN_ERR "nbd: device at index %d is going down\n",
1987 		       index);
1988 		return -EINVAL;
1989 	}
1990 	mutex_unlock(&nbd_index_mutex);
1991 
1992 	mutex_lock(&nbd->config_lock);
1993 	if (refcount_read(&nbd->config_refs)) {
1994 		mutex_unlock(&nbd->config_lock);
1995 		nbd_put(nbd);
1996 		if (index == -1)
1997 			goto again;
1998 		printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1999 		return -EBUSY;
2000 	}
2001 	if (WARN_ON(nbd->config)) {
2002 		mutex_unlock(&nbd->config_lock);
2003 		nbd_put(nbd);
2004 		return -EINVAL;
2005 	}
2006 	config = nbd->config = nbd_alloc_config();
2007 	if (!nbd->config) {
2008 		mutex_unlock(&nbd->config_lock);
2009 		nbd_put(nbd);
2010 		printk(KERN_ERR "nbd: couldn't allocate config\n");
2011 		return -ENOMEM;
2012 	}
2013 	refcount_set(&nbd->config_refs, 1);
2014 	set_bit(NBD_RT_BOUND, &config->runtime_flags);
2015 
2016 	ret = nbd_genl_size_set(info, nbd);
2017 	if (ret)
2018 		goto out;
2019 
2020 	if (info->attrs[NBD_ATTR_TIMEOUT])
2021 		nbd_set_cmd_timeout(nbd,
2022 				    nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2023 	if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2024 		config->dead_conn_timeout =
2025 			nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2026 		config->dead_conn_timeout *= HZ;
2027 	}
2028 	if (info->attrs[NBD_ATTR_SERVER_FLAGS])
2029 		config->flags =
2030 			nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
2031 	if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2032 		u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2033 		if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2034 			/*
2035 			 * We have 1 ref to keep the device around, and then 1
2036 			 * ref for our current operation here, which will be
2037 			 * inherited by the config.  If we already have
2038 			 * DESTROY_ON_DISCONNECT set then we know we don't have
2039 			 * that extra ref already held so we don't need the
2040 			 * put_dev.
2041 			 */
2042 			if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2043 					      &nbd->flags))
2044 				put_dev = true;
2045 		} else {
2046 			if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2047 					       &nbd->flags))
2048 				refcount_inc(&nbd->refs);
2049 		}
2050 		if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2051 			set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2052 				&config->runtime_flags);
2053 		}
2054 	}
2055 
2056 	if (info->attrs[NBD_ATTR_SOCKETS]) {
2057 		struct nlattr *attr;
2058 		int rem, fd;
2059 
2060 		nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2061 				    rem) {
2062 			struct nlattr *socks[NBD_SOCK_MAX+1];
2063 
2064 			if (nla_type(attr) != NBD_SOCK_ITEM) {
2065 				printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2066 				ret = -EINVAL;
2067 				goto out;
2068 			}
2069 			ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2070 							  attr,
2071 							  nbd_sock_policy,
2072 							  info->extack);
2073 			if (ret != 0) {
2074 				printk(KERN_ERR "nbd: error processing sock list\n");
2075 				ret = -EINVAL;
2076 				goto out;
2077 			}
2078 			if (!socks[NBD_SOCK_FD])
2079 				continue;
2080 			fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2081 			ret = nbd_add_socket(nbd, fd, true);
2082 			if (ret)
2083 				goto out;
2084 		}
2085 	}
2086 	ret = nbd_start_device(nbd);
2087 out:
2088 	mutex_unlock(&nbd->config_lock);
2089 	if (!ret) {
2090 		set_bit(NBD_RT_HAS_CONFIG_REF, &config->runtime_flags);
2091 		refcount_inc(&nbd->config_refs);
2092 		nbd_connect_reply(info, nbd->index);
2093 	}
2094 	nbd_config_put(nbd);
2095 	if (put_dev)
2096 		nbd_put(nbd);
2097 	return ret;
2098 }
2099 
nbd_disconnect_and_put(struct nbd_device * nbd)2100 static void nbd_disconnect_and_put(struct nbd_device *nbd)
2101 {
2102 	mutex_lock(&nbd->config_lock);
2103 	nbd_disconnect(nbd);
2104 	sock_shutdown(nbd);
2105 	/*
2106 	 * Make sure recv thread has finished, so it does not drop the last
2107 	 * config ref and try to destroy the workqueue from inside the work
2108 	 * queue. And this also ensure that we can safely call nbd_clear_que()
2109 	 * to cancel the inflight I/Os.
2110 	 */
2111 	if (nbd->recv_workq)
2112 		flush_workqueue(nbd->recv_workq);
2113 	nbd_clear_que(nbd);
2114 	nbd->task_setup = NULL;
2115 	mutex_unlock(&nbd->config_lock);
2116 
2117 	if (test_and_clear_bit(NBD_RT_HAS_CONFIG_REF,
2118 			       &nbd->config->runtime_flags))
2119 		nbd_config_put(nbd);
2120 }
2121 
nbd_genl_disconnect(struct sk_buff * skb,struct genl_info * info)2122 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
2123 {
2124 	struct nbd_device *nbd;
2125 	int index;
2126 
2127 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
2128 		return -EPERM;
2129 
2130 	if (!info->attrs[NBD_ATTR_INDEX]) {
2131 		printk(KERN_ERR "nbd: must specify an index to disconnect\n");
2132 		return -EINVAL;
2133 	}
2134 	index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2135 	mutex_lock(&nbd_index_mutex);
2136 	nbd = idr_find(&nbd_index_idr, index);
2137 	if (!nbd) {
2138 		mutex_unlock(&nbd_index_mutex);
2139 		printk(KERN_ERR "nbd: couldn't find device at index %d\n",
2140 		       index);
2141 		return -EINVAL;
2142 	}
2143 	if (!refcount_inc_not_zero(&nbd->refs)) {
2144 		mutex_unlock(&nbd_index_mutex);
2145 		printk(KERN_ERR "nbd: device at index %d is going down\n",
2146 		       index);
2147 		return -EINVAL;
2148 	}
2149 	mutex_unlock(&nbd_index_mutex);
2150 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
2151 		nbd_put(nbd);
2152 		return 0;
2153 	}
2154 	nbd_disconnect_and_put(nbd);
2155 	nbd_config_put(nbd);
2156 	nbd_put(nbd);
2157 	return 0;
2158 }
2159 
nbd_genl_reconfigure(struct sk_buff * skb,struct genl_info * info)2160 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
2161 {
2162 	struct nbd_device *nbd = NULL;
2163 	struct nbd_config *config;
2164 	int index;
2165 	int ret = 0;
2166 	bool put_dev = false;
2167 
2168 	if (!netlink_capable(skb, CAP_SYS_ADMIN))
2169 		return -EPERM;
2170 
2171 	if (!info->attrs[NBD_ATTR_INDEX]) {
2172 		printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
2173 		return -EINVAL;
2174 	}
2175 	index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2176 	mutex_lock(&nbd_index_mutex);
2177 	nbd = idr_find(&nbd_index_idr, index);
2178 	if (!nbd) {
2179 		mutex_unlock(&nbd_index_mutex);
2180 		printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
2181 		       index);
2182 		return -EINVAL;
2183 	}
2184 	if (!refcount_inc_not_zero(&nbd->refs)) {
2185 		mutex_unlock(&nbd_index_mutex);
2186 		printk(KERN_ERR "nbd: device at index %d is going down\n",
2187 		       index);
2188 		return -EINVAL;
2189 	}
2190 	mutex_unlock(&nbd_index_mutex);
2191 
2192 	if (!refcount_inc_not_zero(&nbd->config_refs)) {
2193 		dev_err(nbd_to_dev(nbd),
2194 			"not configured, cannot reconfigure\n");
2195 		nbd_put(nbd);
2196 		return -EINVAL;
2197 	}
2198 
2199 	mutex_lock(&nbd->config_lock);
2200 	config = nbd->config;
2201 	if (!test_bit(NBD_RT_BOUND, &config->runtime_flags) ||
2202 	    !nbd->pid) {
2203 		dev_err(nbd_to_dev(nbd),
2204 			"not configured, cannot reconfigure\n");
2205 		ret = -EINVAL;
2206 		goto out;
2207 	}
2208 
2209 	ret = nbd_genl_size_set(info, nbd);
2210 	if (ret)
2211 		goto out;
2212 
2213 	if (info->attrs[NBD_ATTR_TIMEOUT])
2214 		nbd_set_cmd_timeout(nbd,
2215 				    nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]));
2216 	if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2217 		config->dead_conn_timeout =
2218 			nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2219 		config->dead_conn_timeout *= HZ;
2220 	}
2221 	if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2222 		u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2223 		if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2224 			if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2225 					      &nbd->flags))
2226 				put_dev = true;
2227 		} else {
2228 			if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2229 					       &nbd->flags))
2230 				refcount_inc(&nbd->refs);
2231 		}
2232 
2233 		if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2234 			set_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2235 					&config->runtime_flags);
2236 		} else {
2237 			clear_bit(NBD_RT_DISCONNECT_ON_CLOSE,
2238 					&config->runtime_flags);
2239 		}
2240 	}
2241 
2242 	if (info->attrs[NBD_ATTR_SOCKETS]) {
2243 		struct nlattr *attr;
2244 		int rem, fd;
2245 
2246 		nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2247 				    rem) {
2248 			struct nlattr *socks[NBD_SOCK_MAX+1];
2249 
2250 			if (nla_type(attr) != NBD_SOCK_ITEM) {
2251 				printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2252 				ret = -EINVAL;
2253 				goto out;
2254 			}
2255 			ret = nla_parse_nested_deprecated(socks, NBD_SOCK_MAX,
2256 							  attr,
2257 							  nbd_sock_policy,
2258 							  info->extack);
2259 			if (ret != 0) {
2260 				printk(KERN_ERR "nbd: error processing sock list\n");
2261 				ret = -EINVAL;
2262 				goto out;
2263 			}
2264 			if (!socks[NBD_SOCK_FD])
2265 				continue;
2266 			fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2267 			ret = nbd_reconnect_socket(nbd, fd);
2268 			if (ret) {
2269 				if (ret == -ENOSPC)
2270 					ret = 0;
2271 				goto out;
2272 			}
2273 			dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2274 		}
2275 	}
2276 out:
2277 	mutex_unlock(&nbd->config_lock);
2278 	nbd_config_put(nbd);
2279 	nbd_put(nbd);
2280 	if (put_dev)
2281 		nbd_put(nbd);
2282 	return ret;
2283 }
2284 
2285 static const struct genl_small_ops nbd_connect_genl_ops[] = {
2286 	{
2287 		.cmd	= NBD_CMD_CONNECT,
2288 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2289 		.doit	= nbd_genl_connect,
2290 	},
2291 	{
2292 		.cmd	= NBD_CMD_DISCONNECT,
2293 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2294 		.doit	= nbd_genl_disconnect,
2295 	},
2296 	{
2297 		.cmd	= NBD_CMD_RECONFIGURE,
2298 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2299 		.doit	= nbd_genl_reconfigure,
2300 	},
2301 	{
2302 		.cmd	= NBD_CMD_STATUS,
2303 		.validate = GENL_DONT_VALIDATE_STRICT | GENL_DONT_VALIDATE_DUMP,
2304 		.doit	= nbd_genl_status,
2305 	},
2306 };
2307 
2308 static const struct genl_multicast_group nbd_mcast_grps[] = {
2309 	{ .name = NBD_GENL_MCAST_GROUP_NAME, },
2310 };
2311 
2312 static struct genl_family nbd_genl_family __ro_after_init = {
2313 	.hdrsize	= 0,
2314 	.name		= NBD_GENL_FAMILY_NAME,
2315 	.version	= NBD_GENL_VERSION,
2316 	.module		= THIS_MODULE,
2317 	.small_ops	= nbd_connect_genl_ops,
2318 	.n_small_ops	= ARRAY_SIZE(nbd_connect_genl_ops),
2319 	.maxattr	= NBD_ATTR_MAX,
2320 	.policy = nbd_attr_policy,
2321 	.mcgrps		= nbd_mcast_grps,
2322 	.n_mcgrps	= ARRAY_SIZE(nbd_mcast_grps),
2323 };
2324 
populate_nbd_status(struct nbd_device * nbd,struct sk_buff * reply)2325 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2326 {
2327 	struct nlattr *dev_opt;
2328 	u8 connected = 0;
2329 	int ret;
2330 
2331 	/* This is a little racey, but for status it's ok.  The
2332 	 * reason we don't take a ref here is because we can't
2333 	 * take a ref in the index == -1 case as we would need
2334 	 * to put under the nbd_index_mutex, which could
2335 	 * deadlock if we are configured to remove ourselves
2336 	 * once we're disconnected.
2337 	 */
2338 	if (refcount_read(&nbd->config_refs))
2339 		connected = 1;
2340 	dev_opt = nla_nest_start_noflag(reply, NBD_DEVICE_ITEM);
2341 	if (!dev_opt)
2342 		return -EMSGSIZE;
2343 	ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2344 	if (ret)
2345 		return -EMSGSIZE;
2346 	ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2347 			 connected);
2348 	if (ret)
2349 		return -EMSGSIZE;
2350 	nla_nest_end(reply, dev_opt);
2351 	return 0;
2352 }
2353 
status_cb(int id,void * ptr,void * data)2354 static int status_cb(int id, void *ptr, void *data)
2355 {
2356 	struct nbd_device *nbd = ptr;
2357 	return populate_nbd_status(nbd, (struct sk_buff *)data);
2358 }
2359 
nbd_genl_status(struct sk_buff * skb,struct genl_info * info)2360 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2361 {
2362 	struct nlattr *dev_list;
2363 	struct sk_buff *reply;
2364 	void *reply_head;
2365 	size_t msg_size;
2366 	int index = -1;
2367 	int ret = -ENOMEM;
2368 
2369 	if (info->attrs[NBD_ATTR_INDEX])
2370 		index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2371 
2372 	mutex_lock(&nbd_index_mutex);
2373 
2374 	msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2375 				  nla_attr_size(sizeof(u8)));
2376 	msg_size *= (index == -1) ? nbd_total_devices : 1;
2377 
2378 	reply = genlmsg_new(msg_size, GFP_KERNEL);
2379 	if (!reply)
2380 		goto out;
2381 	reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2382 				       NBD_CMD_STATUS);
2383 	if (!reply_head) {
2384 		nlmsg_free(reply);
2385 		goto out;
2386 	}
2387 
2388 	dev_list = nla_nest_start_noflag(reply, NBD_ATTR_DEVICE_LIST);
2389 	if (!dev_list) {
2390 		nlmsg_free(reply);
2391 		ret = -EMSGSIZE;
2392 		goto out;
2393 	}
2394 
2395 	if (index == -1) {
2396 		ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2397 		if (ret) {
2398 			nlmsg_free(reply);
2399 			goto out;
2400 		}
2401 	} else {
2402 		struct nbd_device *nbd;
2403 		nbd = idr_find(&nbd_index_idr, index);
2404 		if (nbd) {
2405 			ret = populate_nbd_status(nbd, reply);
2406 			if (ret) {
2407 				nlmsg_free(reply);
2408 				goto out;
2409 			}
2410 		}
2411 	}
2412 	nla_nest_end(reply, dev_list);
2413 	genlmsg_end(reply, reply_head);
2414 	ret = genlmsg_reply(reply, info);
2415 out:
2416 	mutex_unlock(&nbd_index_mutex);
2417 	return ret;
2418 }
2419 
nbd_connect_reply(struct genl_info * info,int index)2420 static void nbd_connect_reply(struct genl_info *info, int index)
2421 {
2422 	struct sk_buff *skb;
2423 	void *msg_head;
2424 	int ret;
2425 
2426 	skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2427 	if (!skb)
2428 		return;
2429 	msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2430 				     NBD_CMD_CONNECT);
2431 	if (!msg_head) {
2432 		nlmsg_free(skb);
2433 		return;
2434 	}
2435 	ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2436 	if (ret) {
2437 		nlmsg_free(skb);
2438 		return;
2439 	}
2440 	genlmsg_end(skb, msg_head);
2441 	genlmsg_reply(skb, info);
2442 }
2443 
nbd_mcast_index(int index)2444 static void nbd_mcast_index(int index)
2445 {
2446 	struct sk_buff *skb;
2447 	void *msg_head;
2448 	int ret;
2449 
2450 	skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2451 	if (!skb)
2452 		return;
2453 	msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2454 				     NBD_CMD_LINK_DEAD);
2455 	if (!msg_head) {
2456 		nlmsg_free(skb);
2457 		return;
2458 	}
2459 	ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2460 	if (ret) {
2461 		nlmsg_free(skb);
2462 		return;
2463 	}
2464 	genlmsg_end(skb, msg_head);
2465 	genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2466 }
2467 
nbd_dead_link_work(struct work_struct * work)2468 static void nbd_dead_link_work(struct work_struct *work)
2469 {
2470 	struct link_dead_args *args = container_of(work, struct link_dead_args,
2471 						   work);
2472 	nbd_mcast_index(args->index);
2473 	kfree(args);
2474 }
2475 
nbd_init(void)2476 static int __init nbd_init(void)
2477 {
2478 	int i;
2479 
2480 	BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2481 
2482 	if (max_part < 0) {
2483 		printk(KERN_ERR "nbd: max_part must be >= 0\n");
2484 		return -EINVAL;
2485 	}
2486 
2487 	part_shift = 0;
2488 	if (max_part > 0) {
2489 		part_shift = fls(max_part);
2490 
2491 		/*
2492 		 * Adjust max_part according to part_shift as it is exported
2493 		 * to user space so that user can know the max number of
2494 		 * partition kernel should be able to manage.
2495 		 *
2496 		 * Note that -1 is required because partition 0 is reserved
2497 		 * for the whole disk.
2498 		 */
2499 		max_part = (1UL << part_shift) - 1;
2500 	}
2501 
2502 	if ((1UL << part_shift) > DISK_MAX_PARTS)
2503 		return -EINVAL;
2504 
2505 	if (nbds_max > 1UL << (MINORBITS - part_shift))
2506 		return -EINVAL;
2507 
2508 	if (register_blkdev(NBD_MAJOR, "nbd"))
2509 		return -EIO;
2510 
2511 	if (genl_register_family(&nbd_genl_family)) {
2512 		unregister_blkdev(NBD_MAJOR, "nbd");
2513 		return -EINVAL;
2514 	}
2515 	nbd_dbg_init();
2516 
2517 	mutex_lock(&nbd_index_mutex);
2518 	for (i = 0; i < nbds_max; i++)
2519 		nbd_dev_add(i);
2520 	mutex_unlock(&nbd_index_mutex);
2521 	return 0;
2522 }
2523 
nbd_exit_cb(int id,void * ptr,void * data)2524 static int nbd_exit_cb(int id, void *ptr, void *data)
2525 {
2526 	struct list_head *list = (struct list_head *)data;
2527 	struct nbd_device *nbd = ptr;
2528 
2529 	list_add_tail(&nbd->list, list);
2530 	return 0;
2531 }
2532 
nbd_cleanup(void)2533 static void __exit nbd_cleanup(void)
2534 {
2535 	struct nbd_device *nbd;
2536 	LIST_HEAD(del_list);
2537 
2538 	nbd_dbg_close();
2539 
2540 	mutex_lock(&nbd_index_mutex);
2541 	idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2542 	mutex_unlock(&nbd_index_mutex);
2543 
2544 	while (!list_empty(&del_list)) {
2545 		nbd = list_first_entry(&del_list, struct nbd_device, list);
2546 		list_del_init(&nbd->list);
2547 		if (refcount_read(&nbd->refs) != 1)
2548 			printk(KERN_ERR "nbd: possibly leaking a device\n");
2549 		nbd_put(nbd);
2550 	}
2551 
2552 	idr_destroy(&nbd_index_idr);
2553 	genl_unregister_family(&nbd_genl_family);
2554 	unregister_blkdev(NBD_MAJOR, "nbd");
2555 }
2556 
2557 module_init(nbd_init);
2558 module_exit(nbd_cleanup);
2559 
2560 MODULE_DESCRIPTION("Network Block Device");
2561 MODULE_LICENSE("GPL");
2562 
2563 module_param(nbds_max, int, 0444);
2564 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2565 module_param(max_part, int, 0444);
2566 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");
2567