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