xref: /openbmc/linux/drivers/block/nbd.c (revision e4781421e883340b796da5a724bda7226817990b)
1 /*
2  * Network block device - make block devices work over TCP
3  *
4  * Note that you can not swap over this thing, yet. Seems to work but
5  * deadlocks sometimes - you can not swap over TCP in general.
6  *
7  * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
8  * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
9  *
10  * This file is released under GPLv2 or later.
11  *
12  * (part of code stolen from loop.c)
13  */
14 
15 #include <linux/major.h>
16 
17 #include <linux/blkdev.h>
18 #include <linux/module.h>
19 #include <linux/init.h>
20 #include <linux/sched.h>
21 #include <linux/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/err.h>
30 #include <linux/kernel.h>
31 #include <linux/slab.h>
32 #include <net/sock.h>
33 #include <linux/net.h>
34 #include <linux/kthread.h>
35 #include <linux/types.h>
36 #include <linux/debugfs.h>
37 #include <linux/blk-mq.h>
38 
39 #include <linux/uaccess.h>
40 #include <asm/types.h>
41 
42 #include <linux/nbd.h>
43 
44 struct nbd_sock {
45 	struct socket *sock;
46 	struct mutex tx_lock;
47 };
48 
49 #define NBD_TIMEDOUT			0
50 #define NBD_DISCONNECT_REQUESTED	1
51 #define NBD_DISCONNECTED		2
52 #define NBD_RUNNING			3
53 
54 struct nbd_device {
55 	u32 flags;
56 	unsigned long runtime_flags;
57 	struct nbd_sock **socks;
58 	int magic;
59 
60 	struct blk_mq_tag_set tag_set;
61 
62 	struct mutex config_lock;
63 	struct gendisk *disk;
64 	int num_connections;
65 	atomic_t recv_threads;
66 	wait_queue_head_t recv_wq;
67 	loff_t blksize;
68 	loff_t bytesize;
69 
70 	struct task_struct *task_recv;
71 	struct task_struct *task_setup;
72 
73 #if IS_ENABLED(CONFIG_DEBUG_FS)
74 	struct dentry *dbg_dir;
75 #endif
76 };
77 
78 struct nbd_cmd {
79 	struct nbd_device *nbd;
80 	struct completion send_complete;
81 };
82 
83 #if IS_ENABLED(CONFIG_DEBUG_FS)
84 static struct dentry *nbd_dbg_dir;
85 #endif
86 
87 #define nbd_name(nbd) ((nbd)->disk->disk_name)
88 
89 #define NBD_MAGIC 0x68797548
90 
91 static unsigned int nbds_max = 16;
92 static struct nbd_device *nbd_dev;
93 static int max_part;
94 
95 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
96 {
97 	return disk_to_dev(nbd->disk);
98 }
99 
100 static bool nbd_is_connected(struct nbd_device *nbd)
101 {
102 	return !!nbd->task_recv;
103 }
104 
105 static const char *nbdcmd_to_ascii(int cmd)
106 {
107 	switch (cmd) {
108 	case  NBD_CMD_READ: return "read";
109 	case NBD_CMD_WRITE: return "write";
110 	case  NBD_CMD_DISC: return "disconnect";
111 	case NBD_CMD_FLUSH: return "flush";
112 	case  NBD_CMD_TRIM: return "trim/discard";
113 	}
114 	return "invalid";
115 }
116 
117 static int nbd_size_clear(struct nbd_device *nbd, struct block_device *bdev)
118 {
119 	bdev->bd_inode->i_size = 0;
120 	set_capacity(nbd->disk, 0);
121 	kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
122 
123 	return 0;
124 }
125 
126 static void nbd_size_update(struct nbd_device *nbd, struct block_device *bdev)
127 {
128 	if (!nbd_is_connected(nbd))
129 		return;
130 
131 	bdev->bd_inode->i_size = nbd->bytesize;
132 	set_capacity(nbd->disk, nbd->bytesize >> 9);
133 	kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
134 }
135 
136 static int nbd_size_set(struct nbd_device *nbd, struct block_device *bdev,
137 			loff_t blocksize, loff_t nr_blocks)
138 {
139 	int ret;
140 
141 	ret = set_blocksize(bdev, blocksize);
142 	if (ret)
143 		return ret;
144 
145 	nbd->blksize = blocksize;
146 	nbd->bytesize = blocksize * nr_blocks;
147 
148 	nbd_size_update(nbd, bdev);
149 
150 	return 0;
151 }
152 
153 static void nbd_end_request(struct nbd_cmd *cmd)
154 {
155 	struct nbd_device *nbd = cmd->nbd;
156 	struct request *req = blk_mq_rq_from_pdu(cmd);
157 	int error = req->errors ? -EIO : 0;
158 
159 	dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", cmd,
160 		error ? "failed" : "done");
161 
162 	blk_mq_complete_request(req, error);
163 }
164 
165 /*
166  * Forcibly shutdown the socket causing all listeners to error
167  */
168 static void sock_shutdown(struct nbd_device *nbd)
169 {
170 	int i;
171 
172 	if (nbd->num_connections == 0)
173 		return;
174 	if (test_and_set_bit(NBD_DISCONNECTED, &nbd->runtime_flags))
175 		return;
176 
177 	for (i = 0; i < nbd->num_connections; i++) {
178 		struct nbd_sock *nsock = nbd->socks[i];
179 		mutex_lock(&nsock->tx_lock);
180 		kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
181 		mutex_unlock(&nsock->tx_lock);
182 	}
183 	dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
184 }
185 
186 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
187 						 bool reserved)
188 {
189 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
190 	struct nbd_device *nbd = cmd->nbd;
191 
192 	dev_err(nbd_to_dev(nbd), "Connection timed out, shutting down connection\n");
193 	set_bit(NBD_TIMEDOUT, &nbd->runtime_flags);
194 	req->errors++;
195 
196 	/*
197 	 * If our disconnect packet times out then we're already holding the
198 	 * config_lock and could deadlock here, so just set an error and return,
199 	 * we'll handle shutting everything down later.
200 	 */
201 	if (req->cmd_type == REQ_TYPE_DRV_PRIV)
202 		return BLK_EH_HANDLED;
203 	mutex_lock(&nbd->config_lock);
204 	sock_shutdown(nbd);
205 	mutex_unlock(&nbd->config_lock);
206 	return BLK_EH_HANDLED;
207 }
208 
209 /*
210  *  Send or receive packet.
211  */
212 static int sock_xmit(struct nbd_device *nbd, int index, int send, void *buf,
213 		     int size, int msg_flags)
214 {
215 	struct socket *sock = nbd->socks[index]->sock;
216 	int result;
217 	struct msghdr msg;
218 	struct kvec iov;
219 	unsigned long pflags = current->flags;
220 
221 	if (unlikely(!sock)) {
222 		dev_err_ratelimited(disk_to_dev(nbd->disk),
223 			"Attempted %s on closed socket in sock_xmit\n",
224 			(send ? "send" : "recv"));
225 		return -EINVAL;
226 	}
227 
228 	current->flags |= PF_MEMALLOC;
229 	do {
230 		sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
231 		iov.iov_base = buf;
232 		iov.iov_len = size;
233 		msg.msg_name = NULL;
234 		msg.msg_namelen = 0;
235 		msg.msg_control = NULL;
236 		msg.msg_controllen = 0;
237 		msg.msg_flags = msg_flags | MSG_NOSIGNAL;
238 
239 		if (send)
240 			result = kernel_sendmsg(sock, &msg, &iov, 1, size);
241 		else
242 			result = kernel_recvmsg(sock, &msg, &iov, 1, size,
243 						msg.msg_flags);
244 
245 		if (result <= 0) {
246 			if (result == 0)
247 				result = -EPIPE; /* short read */
248 			break;
249 		}
250 		size -= result;
251 		buf += result;
252 	} while (size > 0);
253 
254 	tsk_restore_flags(current, pflags, PF_MEMALLOC);
255 
256 	return result;
257 }
258 
259 static inline int sock_send_bvec(struct nbd_device *nbd, int index,
260 				 struct bio_vec *bvec, int flags)
261 {
262 	int result;
263 	void *kaddr = kmap(bvec->bv_page);
264 	result = sock_xmit(nbd, index, 1, kaddr + bvec->bv_offset,
265 			   bvec->bv_len, flags);
266 	kunmap(bvec->bv_page);
267 	return result;
268 }
269 
270 /* always call with the tx_lock held */
271 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
272 {
273 	struct request *req = blk_mq_rq_from_pdu(cmd);
274 	int result, flags;
275 	struct nbd_request request;
276 	unsigned long size = blk_rq_bytes(req);
277 	struct bio *bio;
278 	u32 type;
279 	u32 tag = blk_mq_unique_tag(req);
280 
281 	if (req_op(req) == REQ_OP_DISCARD)
282 		type = NBD_CMD_TRIM;
283 	else if (req_op(req) == REQ_OP_FLUSH)
284 		type = NBD_CMD_FLUSH;
285 	else if (rq_data_dir(req) == WRITE)
286 		type = NBD_CMD_WRITE;
287 	else
288 		type = NBD_CMD_READ;
289 
290 	memset(&request, 0, sizeof(request));
291 	request.magic = htonl(NBD_REQUEST_MAGIC);
292 	request.type = htonl(type);
293 	if (type != NBD_CMD_FLUSH) {
294 		request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
295 		request.len = htonl(size);
296 	}
297 	memcpy(request.handle, &tag, sizeof(tag));
298 
299 	dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
300 		cmd, nbdcmd_to_ascii(type),
301 		(unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
302 	result = sock_xmit(nbd, index, 1, &request, sizeof(request),
303 			(type == NBD_CMD_WRITE) ? MSG_MORE : 0);
304 	if (result <= 0) {
305 		dev_err_ratelimited(disk_to_dev(nbd->disk),
306 			"Send control failed (result %d)\n", result);
307 		return -EIO;
308 	}
309 
310 	if (type != NBD_CMD_WRITE)
311 		return 0;
312 
313 	flags = 0;
314 	bio = req->bio;
315 	while (bio) {
316 		struct bio *next = bio->bi_next;
317 		struct bvec_iter iter;
318 		struct bio_vec bvec;
319 
320 		bio_for_each_segment(bvec, bio, iter) {
321 			bool is_last = !next && bio_iter_last(bvec, iter);
322 
323 			if (is_last)
324 				flags = MSG_MORE;
325 			dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
326 				cmd, bvec.bv_len);
327 			result = sock_send_bvec(nbd, index, &bvec, flags);
328 			if (result <= 0) {
329 				dev_err(disk_to_dev(nbd->disk),
330 					"Send data failed (result %d)\n",
331 					result);
332 				return -EIO;
333 			}
334 			/*
335 			 * The completion might already have come in,
336 			 * so break for the last one instead of letting
337 			 * the iterator do it. This prevents use-after-free
338 			 * of the bio.
339 			 */
340 			if (is_last)
341 				break;
342 		}
343 		bio = next;
344 	}
345 	return 0;
346 }
347 
348 static inline int sock_recv_bvec(struct nbd_device *nbd, int index,
349 				 struct bio_vec *bvec)
350 {
351 	int result;
352 	void *kaddr = kmap(bvec->bv_page);
353 	result = sock_xmit(nbd, index, 0, kaddr + bvec->bv_offset,
354 			   bvec->bv_len, MSG_WAITALL);
355 	kunmap(bvec->bv_page);
356 	return result;
357 }
358 
359 /* NULL returned = something went wrong, inform userspace */
360 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
361 {
362 	int result;
363 	struct nbd_reply reply;
364 	struct nbd_cmd *cmd;
365 	struct request *req = NULL;
366 	u16 hwq;
367 	u32 tag;
368 
369 	reply.magic = 0;
370 	result = sock_xmit(nbd, index, 0, &reply, sizeof(reply), MSG_WAITALL);
371 	if (result <= 0) {
372 		if (!test_bit(NBD_DISCONNECTED, &nbd->runtime_flags) &&
373 		    !test_bit(NBD_DISCONNECT_REQUESTED, &nbd->runtime_flags))
374 			dev_err(disk_to_dev(nbd->disk),
375 				"Receive control failed (result %d)\n", result);
376 		return ERR_PTR(result);
377 	}
378 
379 	if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
380 		dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
381 				(unsigned long)ntohl(reply.magic));
382 		return ERR_PTR(-EPROTO);
383 	}
384 
385 	memcpy(&tag, reply.handle, sizeof(u32));
386 
387 	hwq = blk_mq_unique_tag_to_hwq(tag);
388 	if (hwq < nbd->tag_set.nr_hw_queues)
389 		req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
390 				       blk_mq_unique_tag_to_tag(tag));
391 	if (!req || !blk_mq_request_started(req)) {
392 		dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
393 			tag, req);
394 		return ERR_PTR(-ENOENT);
395 	}
396 	cmd = blk_mq_rq_to_pdu(req);
397 	if (ntohl(reply.error)) {
398 		dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
399 			ntohl(reply.error));
400 		req->errors++;
401 		return cmd;
402 	}
403 
404 	dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", cmd);
405 	if (rq_data_dir(req) != WRITE) {
406 		struct req_iterator iter;
407 		struct bio_vec bvec;
408 
409 		rq_for_each_segment(bvec, req, iter) {
410 			result = sock_recv_bvec(nbd, index, &bvec);
411 			if (result <= 0) {
412 				dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
413 					result);
414 				req->errors++;
415 				return cmd;
416 			}
417 			dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
418 				cmd, bvec.bv_len);
419 		}
420 	} else {
421 		/* See the comment in nbd_queue_rq. */
422 		wait_for_completion(&cmd->send_complete);
423 	}
424 	return cmd;
425 }
426 
427 static ssize_t pid_show(struct device *dev,
428 			struct device_attribute *attr, char *buf)
429 {
430 	struct gendisk *disk = dev_to_disk(dev);
431 	struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
432 
433 	return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
434 }
435 
436 static struct device_attribute pid_attr = {
437 	.attr = { .name = "pid", .mode = S_IRUGO},
438 	.show = pid_show,
439 };
440 
441 struct recv_thread_args {
442 	struct work_struct work;
443 	struct nbd_device *nbd;
444 	int index;
445 };
446 
447 static void recv_work(struct work_struct *work)
448 {
449 	struct recv_thread_args *args = container_of(work,
450 						     struct recv_thread_args,
451 						     work);
452 	struct nbd_device *nbd = args->nbd;
453 	struct nbd_cmd *cmd;
454 	int ret = 0;
455 
456 	BUG_ON(nbd->magic != NBD_MAGIC);
457 	while (1) {
458 		cmd = nbd_read_stat(nbd, args->index);
459 		if (IS_ERR(cmd)) {
460 			ret = PTR_ERR(cmd);
461 			break;
462 		}
463 
464 		nbd_end_request(cmd);
465 	}
466 
467 	/*
468 	 * We got an error, shut everybody down if this wasn't the result of a
469 	 * disconnect request.
470 	 */
471 	if (ret && !test_bit(NBD_DISCONNECT_REQUESTED, &nbd->runtime_flags))
472 		sock_shutdown(nbd);
473 	atomic_dec(&nbd->recv_threads);
474 	wake_up(&nbd->recv_wq);
475 }
476 
477 static void nbd_clear_req(struct request *req, void *data, bool reserved)
478 {
479 	struct nbd_cmd *cmd;
480 
481 	if (!blk_mq_request_started(req))
482 		return;
483 	cmd = blk_mq_rq_to_pdu(req);
484 	req->errors++;
485 	nbd_end_request(cmd);
486 }
487 
488 static void nbd_clear_que(struct nbd_device *nbd)
489 {
490 	BUG_ON(nbd->magic != NBD_MAGIC);
491 
492 	blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
493 	dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
494 }
495 
496 
497 static void nbd_handle_cmd(struct nbd_cmd *cmd, int index)
498 {
499 	struct request *req = blk_mq_rq_from_pdu(cmd);
500 	struct nbd_device *nbd = cmd->nbd;
501 	struct nbd_sock *nsock;
502 
503 	if (index >= nbd->num_connections) {
504 		dev_err_ratelimited(disk_to_dev(nbd->disk),
505 				    "Attempted send on invalid socket\n");
506 		goto error_out;
507 	}
508 
509 	if (test_bit(NBD_DISCONNECTED, &nbd->runtime_flags)) {
510 		dev_err_ratelimited(disk_to_dev(nbd->disk),
511 				    "Attempted send on closed socket\n");
512 		goto error_out;
513 	}
514 
515 	if (req->cmd_type != REQ_TYPE_FS &&
516 	    req->cmd_type != REQ_TYPE_DRV_PRIV)
517 		goto error_out;
518 
519 	if (req->cmd_type == REQ_TYPE_FS &&
520 	    rq_data_dir(req) == WRITE &&
521 	    (nbd->flags & NBD_FLAG_READ_ONLY)) {
522 		dev_err_ratelimited(disk_to_dev(nbd->disk),
523 				    "Write on read-only\n");
524 		goto error_out;
525 	}
526 
527 	req->errors = 0;
528 
529 	nsock = nbd->socks[index];
530 	mutex_lock(&nsock->tx_lock);
531 	if (unlikely(!nsock->sock)) {
532 		mutex_unlock(&nsock->tx_lock);
533 		dev_err_ratelimited(disk_to_dev(nbd->disk),
534 				    "Attempted send on closed socket\n");
535 		goto error_out;
536 	}
537 
538 	if (nbd_send_cmd(nbd, cmd, index) != 0) {
539 		dev_err_ratelimited(disk_to_dev(nbd->disk),
540 				    "Request send failed\n");
541 		req->errors++;
542 		nbd_end_request(cmd);
543 	}
544 
545 	mutex_unlock(&nsock->tx_lock);
546 
547 	return;
548 
549 error_out:
550 	req->errors++;
551 	nbd_end_request(cmd);
552 }
553 
554 static int nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
555 			const struct blk_mq_queue_data *bd)
556 {
557 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
558 
559 	/*
560 	 * Since we look at the bio's to send the request over the network we
561 	 * need to make sure the completion work doesn't mark this request done
562 	 * before we are done doing our send.  This keeps us from dereferencing
563 	 * freed data if we have particularly fast completions (ie we get the
564 	 * completion before we exit sock_xmit on the last bvec) or in the case
565 	 * that the server is misbehaving (or there was an error) before we're
566 	 * done sending everything over the wire.
567 	 */
568 	init_completion(&cmd->send_complete);
569 	blk_mq_start_request(bd->rq);
570 	nbd_handle_cmd(cmd, hctx->queue_num);
571 	complete(&cmd->send_complete);
572 
573 	return BLK_MQ_RQ_QUEUE_OK;
574 }
575 
576 static int nbd_add_socket(struct nbd_device *nbd, struct socket *sock)
577 {
578 	struct nbd_sock **socks;
579 	struct nbd_sock *nsock;
580 
581 	if (!nbd->task_setup)
582 		nbd->task_setup = current;
583 	if (nbd->task_setup != current) {
584 		dev_err(disk_to_dev(nbd->disk),
585 			"Device being setup by another task");
586 		return -EINVAL;
587 	}
588 
589 	socks = krealloc(nbd->socks, (nbd->num_connections + 1) *
590 			 sizeof(struct nbd_sock *), GFP_KERNEL);
591 	if (!socks)
592 		return -ENOMEM;
593 	nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
594 	if (!nsock)
595 		return -ENOMEM;
596 
597 	nbd->socks = socks;
598 
599 	mutex_init(&nsock->tx_lock);
600 	nsock->sock = sock;
601 	socks[nbd->num_connections++] = nsock;
602 
603 	return 0;
604 }
605 
606 /* Reset all properties of an NBD device */
607 static void nbd_reset(struct nbd_device *nbd)
608 {
609 	int i;
610 
611 	for (i = 0; i < nbd->num_connections; i++)
612 		kfree(nbd->socks[i]);
613 	kfree(nbd->socks);
614 	nbd->socks = NULL;
615 	nbd->runtime_flags = 0;
616 	nbd->blksize = 1024;
617 	nbd->bytesize = 0;
618 	set_capacity(nbd->disk, 0);
619 	nbd->flags = 0;
620 	nbd->tag_set.timeout = 0;
621 	nbd->num_connections = 0;
622 	nbd->task_setup = NULL;
623 	queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
624 }
625 
626 static void nbd_bdev_reset(struct block_device *bdev)
627 {
628 	set_device_ro(bdev, false);
629 	bdev->bd_inode->i_size = 0;
630 	if (max_part > 0) {
631 		blkdev_reread_part(bdev);
632 		bdev->bd_invalidated = 1;
633 	}
634 }
635 
636 static void nbd_parse_flags(struct nbd_device *nbd, struct block_device *bdev)
637 {
638 	if (nbd->flags & NBD_FLAG_READ_ONLY)
639 		set_device_ro(bdev, true);
640 	if (nbd->flags & NBD_FLAG_SEND_TRIM)
641 		queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
642 	if (nbd->flags & NBD_FLAG_SEND_FLUSH)
643 		blk_queue_write_cache(nbd->disk->queue, true, false);
644 	else
645 		blk_queue_write_cache(nbd->disk->queue, false, false);
646 }
647 
648 static void send_disconnects(struct nbd_device *nbd)
649 {
650 	struct nbd_request request = {};
651 	int i, ret;
652 
653 	request.magic = htonl(NBD_REQUEST_MAGIC);
654 	request.type = htonl(NBD_CMD_DISC);
655 
656 	for (i = 0; i < nbd->num_connections; i++) {
657 		ret = sock_xmit(nbd, i, 1, &request, sizeof(request), 0);
658 		if (ret <= 0)
659 			dev_err(disk_to_dev(nbd->disk),
660 				"Send disconnect failed %d\n", ret);
661 	}
662 }
663 
664 static int nbd_dev_dbg_init(struct nbd_device *nbd);
665 static void nbd_dev_dbg_close(struct nbd_device *nbd);
666 
667 /* Must be called with config_lock held */
668 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
669 		       unsigned int cmd, unsigned long arg)
670 {
671 	switch (cmd) {
672 	case NBD_DISCONNECT: {
673 		dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
674 		if (!nbd->socks)
675 			return -EINVAL;
676 
677 		mutex_unlock(&nbd->config_lock);
678 		fsync_bdev(bdev);
679 		mutex_lock(&nbd->config_lock);
680 
681 		/* Check again after getting mutex back.  */
682 		if (!nbd->socks)
683 			return -EINVAL;
684 
685 		if (!test_and_set_bit(NBD_DISCONNECT_REQUESTED,
686 				      &nbd->runtime_flags))
687 			send_disconnects(nbd);
688 		return 0;
689 	}
690 
691 	case NBD_CLEAR_SOCK:
692 		sock_shutdown(nbd);
693 		nbd_clear_que(nbd);
694 		kill_bdev(bdev);
695 		nbd_bdev_reset(bdev);
696 		/*
697 		 * We want to give the run thread a chance to wait for everybody
698 		 * to clean up and then do it's own cleanup.
699 		 */
700 		if (!test_bit(NBD_RUNNING, &nbd->runtime_flags)) {
701 			int i;
702 
703 			for (i = 0; i < nbd->num_connections; i++)
704 				kfree(nbd->socks[i]);
705 			kfree(nbd->socks);
706 			nbd->socks = NULL;
707 			nbd->num_connections = 0;
708 			nbd->task_setup = NULL;
709 		}
710 		return 0;
711 
712 	case NBD_SET_SOCK: {
713 		int err;
714 		struct socket *sock = sockfd_lookup(arg, &err);
715 
716 		if (!sock)
717 			return err;
718 
719 		err = nbd_add_socket(nbd, sock);
720 		if (!err && max_part)
721 			bdev->bd_invalidated = 1;
722 
723 		return err;
724 	}
725 
726 	case NBD_SET_BLKSIZE: {
727 		loff_t bsize = div_s64(nbd->bytesize, arg);
728 
729 		return nbd_size_set(nbd, bdev, arg, bsize);
730 	}
731 
732 	case NBD_SET_SIZE:
733 		return nbd_size_set(nbd, bdev, nbd->blksize,
734 					div_s64(arg, nbd->blksize));
735 
736 	case NBD_SET_SIZE_BLOCKS:
737 		return nbd_size_set(nbd, bdev, nbd->blksize, arg);
738 
739 	case NBD_SET_TIMEOUT:
740 		nbd->tag_set.timeout = arg * HZ;
741 		return 0;
742 
743 	case NBD_SET_FLAGS:
744 		nbd->flags = arg;
745 		return 0;
746 
747 	case NBD_DO_IT: {
748 		struct recv_thread_args *args;
749 		int num_connections = nbd->num_connections;
750 		int error = 0, i;
751 
752 		if (nbd->task_recv)
753 			return -EBUSY;
754 		if (!nbd->socks)
755 			return -EINVAL;
756 		if (num_connections > 1 &&
757 		    !(nbd->flags & NBD_FLAG_CAN_MULTI_CONN)) {
758 			dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
759 			error = -EINVAL;
760 			goto out_err;
761 		}
762 
763 		set_bit(NBD_RUNNING, &nbd->runtime_flags);
764 		blk_mq_update_nr_hw_queues(&nbd->tag_set, nbd->num_connections);
765 		args = kcalloc(num_connections, sizeof(*args), GFP_KERNEL);
766 		if (!args) {
767 			error = -ENOMEM;
768 			goto out_err;
769 		}
770 		nbd->task_recv = current;
771 		mutex_unlock(&nbd->config_lock);
772 
773 		nbd_parse_flags(nbd, bdev);
774 
775 		error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
776 		if (error) {
777 			dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
778 			goto out_recv;
779 		}
780 
781 		nbd_size_update(nbd, bdev);
782 
783 		nbd_dev_dbg_init(nbd);
784 		for (i = 0; i < num_connections; i++) {
785 			sk_set_memalloc(nbd->socks[i]->sock->sk);
786 			atomic_inc(&nbd->recv_threads);
787 			INIT_WORK(&args[i].work, recv_work);
788 			args[i].nbd = nbd;
789 			args[i].index = i;
790 			queue_work(system_long_wq, &args[i].work);
791 		}
792 		wait_event_interruptible(nbd->recv_wq,
793 					 atomic_read(&nbd->recv_threads) == 0);
794 		for (i = 0; i < num_connections; i++)
795 			flush_work(&args[i].work);
796 		nbd_dev_dbg_close(nbd);
797 		nbd_size_clear(nbd, bdev);
798 		device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
799 out_recv:
800 		mutex_lock(&nbd->config_lock);
801 		nbd->task_recv = NULL;
802 out_err:
803 		sock_shutdown(nbd);
804 		nbd_clear_que(nbd);
805 		kill_bdev(bdev);
806 		nbd_bdev_reset(bdev);
807 
808 		/* user requested, ignore socket errors */
809 		if (test_bit(NBD_DISCONNECT_REQUESTED, &nbd->runtime_flags))
810 			error = 0;
811 		if (test_bit(NBD_TIMEDOUT, &nbd->runtime_flags))
812 			error = -ETIMEDOUT;
813 
814 		nbd_reset(nbd);
815 		return error;
816 	}
817 
818 	case NBD_CLEAR_QUE:
819 		/*
820 		 * This is for compatibility only.  The queue is always cleared
821 		 * by NBD_DO_IT or NBD_CLEAR_SOCK.
822 		 */
823 		return 0;
824 
825 	case NBD_PRINT_DEBUG:
826 		/*
827 		 * For compatibility only, we no longer keep a list of
828 		 * outstanding requests.
829 		 */
830 		return 0;
831 	}
832 	return -ENOTTY;
833 }
834 
835 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
836 		     unsigned int cmd, unsigned long arg)
837 {
838 	struct nbd_device *nbd = bdev->bd_disk->private_data;
839 	int error;
840 
841 	if (!capable(CAP_SYS_ADMIN))
842 		return -EPERM;
843 
844 	BUG_ON(nbd->magic != NBD_MAGIC);
845 
846 	mutex_lock(&nbd->config_lock);
847 	error = __nbd_ioctl(bdev, nbd, cmd, arg);
848 	mutex_unlock(&nbd->config_lock);
849 
850 	return error;
851 }
852 
853 static const struct block_device_operations nbd_fops =
854 {
855 	.owner =	THIS_MODULE,
856 	.ioctl =	nbd_ioctl,
857 	.compat_ioctl =	nbd_ioctl,
858 };
859 
860 #if IS_ENABLED(CONFIG_DEBUG_FS)
861 
862 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
863 {
864 	struct nbd_device *nbd = s->private;
865 
866 	if (nbd->task_recv)
867 		seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
868 
869 	return 0;
870 }
871 
872 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
873 {
874 	return single_open(file, nbd_dbg_tasks_show, inode->i_private);
875 }
876 
877 static const struct file_operations nbd_dbg_tasks_ops = {
878 	.open = nbd_dbg_tasks_open,
879 	.read = seq_read,
880 	.llseek = seq_lseek,
881 	.release = single_release,
882 };
883 
884 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
885 {
886 	struct nbd_device *nbd = s->private;
887 	u32 flags = nbd->flags;
888 
889 	seq_printf(s, "Hex: 0x%08x\n\n", flags);
890 
891 	seq_puts(s, "Known flags:\n");
892 
893 	if (flags & NBD_FLAG_HAS_FLAGS)
894 		seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
895 	if (flags & NBD_FLAG_READ_ONLY)
896 		seq_puts(s, "NBD_FLAG_READ_ONLY\n");
897 	if (flags & NBD_FLAG_SEND_FLUSH)
898 		seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
899 	if (flags & NBD_FLAG_SEND_TRIM)
900 		seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
901 
902 	return 0;
903 }
904 
905 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
906 {
907 	return single_open(file, nbd_dbg_flags_show, inode->i_private);
908 }
909 
910 static const struct file_operations nbd_dbg_flags_ops = {
911 	.open = nbd_dbg_flags_open,
912 	.read = seq_read,
913 	.llseek = seq_lseek,
914 	.release = single_release,
915 };
916 
917 static int nbd_dev_dbg_init(struct nbd_device *nbd)
918 {
919 	struct dentry *dir;
920 
921 	if (!nbd_dbg_dir)
922 		return -EIO;
923 
924 	dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
925 	if (!dir) {
926 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
927 			nbd_name(nbd));
928 		return -EIO;
929 	}
930 	nbd->dbg_dir = dir;
931 
932 	debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
933 	debugfs_create_u64("size_bytes", 0444, dir, &nbd->bytesize);
934 	debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
935 	debugfs_create_u64("blocksize", 0444, dir, &nbd->blksize);
936 	debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
937 
938 	return 0;
939 }
940 
941 static void nbd_dev_dbg_close(struct nbd_device *nbd)
942 {
943 	debugfs_remove_recursive(nbd->dbg_dir);
944 }
945 
946 static int nbd_dbg_init(void)
947 {
948 	struct dentry *dbg_dir;
949 
950 	dbg_dir = debugfs_create_dir("nbd", NULL);
951 	if (!dbg_dir)
952 		return -EIO;
953 
954 	nbd_dbg_dir = dbg_dir;
955 
956 	return 0;
957 }
958 
959 static void nbd_dbg_close(void)
960 {
961 	debugfs_remove_recursive(nbd_dbg_dir);
962 }
963 
964 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
965 
966 static int nbd_dev_dbg_init(struct nbd_device *nbd)
967 {
968 	return 0;
969 }
970 
971 static void nbd_dev_dbg_close(struct nbd_device *nbd)
972 {
973 }
974 
975 static int nbd_dbg_init(void)
976 {
977 	return 0;
978 }
979 
980 static void nbd_dbg_close(void)
981 {
982 }
983 
984 #endif
985 
986 static int nbd_init_request(void *data, struct request *rq,
987 			    unsigned int hctx_idx, unsigned int request_idx,
988 			    unsigned int numa_node)
989 {
990 	struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
991 	cmd->nbd = data;
992 	return 0;
993 }
994 
995 static struct blk_mq_ops nbd_mq_ops = {
996 	.queue_rq	= nbd_queue_rq,
997 	.init_request	= nbd_init_request,
998 	.timeout	= nbd_xmit_timeout,
999 };
1000 
1001 /*
1002  * And here should be modules and kernel interface
1003  *  (Just smiley confuses emacs :-)
1004  */
1005 
1006 static int __init nbd_init(void)
1007 {
1008 	int err = -ENOMEM;
1009 	int i;
1010 	int part_shift;
1011 
1012 	BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
1013 
1014 	if (max_part < 0) {
1015 		printk(KERN_ERR "nbd: max_part must be >= 0\n");
1016 		return -EINVAL;
1017 	}
1018 
1019 	part_shift = 0;
1020 	if (max_part > 0) {
1021 		part_shift = fls(max_part);
1022 
1023 		/*
1024 		 * Adjust max_part according to part_shift as it is exported
1025 		 * to user space so that user can know the max number of
1026 		 * partition kernel should be able to manage.
1027 		 *
1028 		 * Note that -1 is required because partition 0 is reserved
1029 		 * for the whole disk.
1030 		 */
1031 		max_part = (1UL << part_shift) - 1;
1032 	}
1033 
1034 	if ((1UL << part_shift) > DISK_MAX_PARTS)
1035 		return -EINVAL;
1036 
1037 	if (nbds_max > 1UL << (MINORBITS - part_shift))
1038 		return -EINVAL;
1039 
1040 	nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
1041 	if (!nbd_dev)
1042 		return -ENOMEM;
1043 
1044 	for (i = 0; i < nbds_max; i++) {
1045 		struct gendisk *disk = alloc_disk(1 << part_shift);
1046 		if (!disk)
1047 			goto out;
1048 		nbd_dev[i].disk = disk;
1049 
1050 		nbd_dev[i].tag_set.ops = &nbd_mq_ops;
1051 		nbd_dev[i].tag_set.nr_hw_queues = 1;
1052 		nbd_dev[i].tag_set.queue_depth = 128;
1053 		nbd_dev[i].tag_set.numa_node = NUMA_NO_NODE;
1054 		nbd_dev[i].tag_set.cmd_size = sizeof(struct nbd_cmd);
1055 		nbd_dev[i].tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1056 			BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1057 		nbd_dev[i].tag_set.driver_data = &nbd_dev[i];
1058 
1059 		err = blk_mq_alloc_tag_set(&nbd_dev[i].tag_set);
1060 		if (err) {
1061 			put_disk(disk);
1062 			goto out;
1063 		}
1064 
1065 		/*
1066 		 * The new linux 2.5 block layer implementation requires
1067 		 * every gendisk to have its very own request_queue struct.
1068 		 * These structs are big so we dynamically allocate them.
1069 		 */
1070 		disk->queue = blk_mq_init_queue(&nbd_dev[i].tag_set);
1071 		if (!disk->queue) {
1072 			blk_mq_free_tag_set(&nbd_dev[i].tag_set);
1073 			put_disk(disk);
1074 			goto out;
1075 		}
1076 
1077 		/*
1078 		 * Tell the block layer that we are not a rotational device
1079 		 */
1080 		queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1081 		queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1082 		disk->queue->limits.discard_granularity = 512;
1083 		blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1084 		disk->queue->limits.discard_zeroes_data = 0;
1085 		blk_queue_max_hw_sectors(disk->queue, 65536);
1086 		disk->queue->limits.max_sectors = 256;
1087 	}
1088 
1089 	if (register_blkdev(NBD_MAJOR, "nbd")) {
1090 		err = -EIO;
1091 		goto out;
1092 	}
1093 
1094 	printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
1095 
1096 	nbd_dbg_init();
1097 
1098 	for (i = 0; i < nbds_max; i++) {
1099 		struct gendisk *disk = nbd_dev[i].disk;
1100 		nbd_dev[i].magic = NBD_MAGIC;
1101 		mutex_init(&nbd_dev[i].config_lock);
1102 		disk->major = NBD_MAJOR;
1103 		disk->first_minor = i << part_shift;
1104 		disk->fops = &nbd_fops;
1105 		disk->private_data = &nbd_dev[i];
1106 		sprintf(disk->disk_name, "nbd%d", i);
1107 		init_waitqueue_head(&nbd_dev[i].recv_wq);
1108 		nbd_reset(&nbd_dev[i]);
1109 		add_disk(disk);
1110 	}
1111 
1112 	return 0;
1113 out:
1114 	while (i--) {
1115 		blk_mq_free_tag_set(&nbd_dev[i].tag_set);
1116 		blk_cleanup_queue(nbd_dev[i].disk->queue);
1117 		put_disk(nbd_dev[i].disk);
1118 	}
1119 	kfree(nbd_dev);
1120 	return err;
1121 }
1122 
1123 static void __exit nbd_cleanup(void)
1124 {
1125 	int i;
1126 
1127 	nbd_dbg_close();
1128 
1129 	for (i = 0; i < nbds_max; i++) {
1130 		struct gendisk *disk = nbd_dev[i].disk;
1131 		nbd_dev[i].magic = 0;
1132 		if (disk) {
1133 			del_gendisk(disk);
1134 			blk_cleanup_queue(disk->queue);
1135 			blk_mq_free_tag_set(&nbd_dev[i].tag_set);
1136 			put_disk(disk);
1137 		}
1138 	}
1139 	unregister_blkdev(NBD_MAJOR, "nbd");
1140 	kfree(nbd_dev);
1141 	printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
1142 }
1143 
1144 module_init(nbd_init);
1145 module_exit(nbd_cleanup);
1146 
1147 MODULE_DESCRIPTION("Network Block Device");
1148 MODULE_LICENSE("GPL");
1149 
1150 module_param(nbds_max, int, 0444);
1151 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
1152 module_param(max_part, int, 0444);
1153 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
1154