xref: /openbmc/linux/drivers/block/nbd.c (revision 3821a065)
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 
38 #include <asm/uaccess.h>
39 #include <asm/types.h>
40 
41 #include <linux/nbd.h>
42 
43 struct nbd_device {
44 	u32 flags;
45 	struct socket * sock;	/* If == NULL, device is not ready, yet	*/
46 	int magic;
47 
48 	spinlock_t queue_lock;
49 	struct list_head queue_head;	/* Requests waiting result */
50 	struct request *active_req;
51 	wait_queue_head_t active_wq;
52 	struct list_head waiting_queue;	/* Requests to be sent */
53 	wait_queue_head_t waiting_wq;
54 
55 	struct mutex tx_lock;
56 	struct gendisk *disk;
57 	int blksize;
58 	loff_t bytesize;
59 	int xmit_timeout;
60 	bool disconnect; /* a disconnect has been requested by user */
61 
62 	struct timer_list timeout_timer;
63 	struct task_struct *task_recv;
64 	struct task_struct *task_send;
65 
66 #if IS_ENABLED(CONFIG_DEBUG_FS)
67 	struct dentry *dbg_dir;
68 #endif
69 };
70 
71 #if IS_ENABLED(CONFIG_DEBUG_FS)
72 static struct dentry *nbd_dbg_dir;
73 #endif
74 
75 #define nbd_name(nbd) ((nbd)->disk->disk_name)
76 
77 #define NBD_MAGIC 0x68797548
78 
79 static unsigned int nbds_max = 16;
80 static struct nbd_device *nbd_dev;
81 static int max_part;
82 
83 /*
84  * Use just one lock (or at most 1 per NIC). Two arguments for this:
85  * 1. Each NIC is essentially a synchronization point for all servers
86  *    accessed through that NIC so there's no need to have more locks
87  *    than NICs anyway.
88  * 2. More locks lead to more "Dirty cache line bouncing" which will slow
89  *    down each lock to the point where they're actually slower than just
90  *    a single lock.
91  * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
92  */
93 static DEFINE_SPINLOCK(nbd_lock);
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 const char *nbdcmd_to_ascii(int cmd)
101 {
102 	switch (cmd) {
103 	case  NBD_CMD_READ: return "read";
104 	case NBD_CMD_WRITE: return "write";
105 	case  NBD_CMD_DISC: return "disconnect";
106 	case NBD_CMD_FLUSH: return "flush";
107 	case  NBD_CMD_TRIM: return "trim/discard";
108 	}
109 	return "invalid";
110 }
111 
112 static void nbd_end_request(struct nbd_device *nbd, struct request *req)
113 {
114 	int error = req->errors ? -EIO : 0;
115 	struct request_queue *q = req->q;
116 	unsigned long flags;
117 
118 	dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", req,
119 		error ? "failed" : "done");
120 
121 	spin_lock_irqsave(q->queue_lock, flags);
122 	__blk_end_request_all(req, error);
123 	spin_unlock_irqrestore(q->queue_lock, flags);
124 }
125 
126 /*
127  * Forcibly shutdown the socket causing all listeners to error
128  */
129 static void sock_shutdown(struct nbd_device *nbd)
130 {
131 	if (!nbd->sock)
132 		return;
133 
134 	dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
135 	kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
136 	nbd->sock = NULL;
137 	del_timer_sync(&nbd->timeout_timer);
138 }
139 
140 static void nbd_xmit_timeout(unsigned long arg)
141 {
142 	struct nbd_device *nbd = (struct nbd_device *)arg;
143 	struct task_struct *task;
144 
145 	if (list_empty(&nbd->queue_head))
146 		return;
147 
148 	nbd->disconnect = true;
149 
150 	task = READ_ONCE(nbd->task_recv);
151 	if (task)
152 		force_sig(SIGKILL, task);
153 
154 	task = READ_ONCE(nbd->task_send);
155 	if (task)
156 		force_sig(SIGKILL, nbd->task_send);
157 
158 	dev_err(nbd_to_dev(nbd), "Connection timed out, killed receiver and sender, shutting down connection\n");
159 }
160 
161 /*
162  *  Send or receive packet.
163  */
164 static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
165 		int msg_flags)
166 {
167 	struct socket *sock = nbd->sock;
168 	int result;
169 	struct msghdr msg;
170 	struct kvec iov;
171 	sigset_t blocked, oldset;
172 	unsigned long pflags = current->flags;
173 
174 	if (unlikely(!sock)) {
175 		dev_err(disk_to_dev(nbd->disk),
176 			"Attempted %s on closed socket in sock_xmit\n",
177 			(send ? "send" : "recv"));
178 		return -EINVAL;
179 	}
180 
181 	/* Allow interception of SIGKILL only
182 	 * Don't allow other signals to interrupt the transmission */
183 	siginitsetinv(&blocked, sigmask(SIGKILL));
184 	sigprocmask(SIG_SETMASK, &blocked, &oldset);
185 
186 	current->flags |= PF_MEMALLOC;
187 	do {
188 		sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
189 		iov.iov_base = buf;
190 		iov.iov_len = size;
191 		msg.msg_name = NULL;
192 		msg.msg_namelen = 0;
193 		msg.msg_control = NULL;
194 		msg.msg_controllen = 0;
195 		msg.msg_flags = msg_flags | MSG_NOSIGNAL;
196 
197 		if (send)
198 			result = kernel_sendmsg(sock, &msg, &iov, 1, size);
199 		else
200 			result = kernel_recvmsg(sock, &msg, &iov, 1, size,
201 						msg.msg_flags);
202 
203 		if (result <= 0) {
204 			if (result == 0)
205 				result = -EPIPE; /* short read */
206 			break;
207 		}
208 		size -= result;
209 		buf += result;
210 	} while (size > 0);
211 
212 	sigprocmask(SIG_SETMASK, &oldset, NULL);
213 	tsk_restore_flags(current, pflags, PF_MEMALLOC);
214 
215 	if (!send && nbd->xmit_timeout)
216 		mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
217 
218 	return result;
219 }
220 
221 static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
222 		int flags)
223 {
224 	int result;
225 	void *kaddr = kmap(bvec->bv_page);
226 	result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
227 			   bvec->bv_len, flags);
228 	kunmap(bvec->bv_page);
229 	return result;
230 }
231 
232 /* always call with the tx_lock held */
233 static int nbd_send_req(struct nbd_device *nbd, struct request *req)
234 {
235 	int result, flags;
236 	struct nbd_request request;
237 	unsigned long size = blk_rq_bytes(req);
238 	u32 type;
239 
240 	if (req->cmd_type == REQ_TYPE_DRV_PRIV)
241 		type = NBD_CMD_DISC;
242 	else if (req->cmd_flags & REQ_DISCARD)
243 		type = NBD_CMD_TRIM;
244 	else if (req->cmd_flags & REQ_FLUSH)
245 		type = NBD_CMD_FLUSH;
246 	else if (rq_data_dir(req) == WRITE)
247 		type = NBD_CMD_WRITE;
248 	else
249 		type = NBD_CMD_READ;
250 
251 	memset(&request, 0, sizeof(request));
252 	request.magic = htonl(NBD_REQUEST_MAGIC);
253 	request.type = htonl(type);
254 	if (type != NBD_CMD_FLUSH && type != NBD_CMD_DISC) {
255 		request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
256 		request.len = htonl(size);
257 	}
258 	memcpy(request.handle, &req, sizeof(req));
259 
260 	dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
261 		req, nbdcmd_to_ascii(type),
262 		(unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
263 	result = sock_xmit(nbd, 1, &request, sizeof(request),
264 			(type == NBD_CMD_WRITE) ? MSG_MORE : 0);
265 	if (result <= 0) {
266 		dev_err(disk_to_dev(nbd->disk),
267 			"Send control failed (result %d)\n", result);
268 		return -EIO;
269 	}
270 
271 	if (type == NBD_CMD_WRITE) {
272 		struct req_iterator iter;
273 		struct bio_vec bvec;
274 		/*
275 		 * we are really probing at internals to determine
276 		 * whether to set MSG_MORE or not...
277 		 */
278 		rq_for_each_segment(bvec, req, iter) {
279 			flags = 0;
280 			if (!rq_iter_last(bvec, iter))
281 				flags = MSG_MORE;
282 			dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
283 				req, bvec.bv_len);
284 			result = sock_send_bvec(nbd, &bvec, flags);
285 			if (result <= 0) {
286 				dev_err(disk_to_dev(nbd->disk),
287 					"Send data failed (result %d)\n",
288 					result);
289 				return -EIO;
290 			}
291 		}
292 	}
293 	return 0;
294 }
295 
296 static struct request *nbd_find_request(struct nbd_device *nbd,
297 					struct request *xreq)
298 {
299 	struct request *req, *tmp;
300 	int err;
301 
302 	err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
303 	if (unlikely(err))
304 		return ERR_PTR(err);
305 
306 	spin_lock(&nbd->queue_lock);
307 	list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
308 		if (req != xreq)
309 			continue;
310 		list_del_init(&req->queuelist);
311 		spin_unlock(&nbd->queue_lock);
312 		return req;
313 	}
314 	spin_unlock(&nbd->queue_lock);
315 
316 	return ERR_PTR(-ENOENT);
317 }
318 
319 static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
320 {
321 	int result;
322 	void *kaddr = kmap(bvec->bv_page);
323 	result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
324 			MSG_WAITALL);
325 	kunmap(bvec->bv_page);
326 	return result;
327 }
328 
329 /* NULL returned = something went wrong, inform userspace */
330 static struct request *nbd_read_stat(struct nbd_device *nbd)
331 {
332 	int result;
333 	struct nbd_reply reply;
334 	struct request *req;
335 
336 	reply.magic = 0;
337 	result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
338 	if (result <= 0) {
339 		dev_err(disk_to_dev(nbd->disk),
340 			"Receive control failed (result %d)\n", result);
341 		return ERR_PTR(result);
342 	}
343 
344 	if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
345 		dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
346 				(unsigned long)ntohl(reply.magic));
347 		return ERR_PTR(-EPROTO);
348 	}
349 
350 	req = nbd_find_request(nbd, *(struct request **)reply.handle);
351 	if (IS_ERR(req)) {
352 		result = PTR_ERR(req);
353 		if (result != -ENOENT)
354 			return ERR_PTR(result);
355 
356 		dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
357 			reply.handle);
358 		return ERR_PTR(-EBADR);
359 	}
360 
361 	if (ntohl(reply.error)) {
362 		dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
363 			ntohl(reply.error));
364 		req->errors++;
365 		return req;
366 	}
367 
368 	dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
369 	if (rq_data_dir(req) != WRITE) {
370 		struct req_iterator iter;
371 		struct bio_vec bvec;
372 
373 		rq_for_each_segment(bvec, req, iter) {
374 			result = sock_recv_bvec(nbd, &bvec);
375 			if (result <= 0) {
376 				dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
377 					result);
378 				req->errors++;
379 				return req;
380 			}
381 			dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
382 				req, bvec.bv_len);
383 		}
384 	}
385 	return req;
386 }
387 
388 static ssize_t pid_show(struct device *dev,
389 			struct device_attribute *attr, char *buf)
390 {
391 	struct gendisk *disk = dev_to_disk(dev);
392 	struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
393 
394 	return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
395 }
396 
397 static struct device_attribute pid_attr = {
398 	.attr = { .name = "pid", .mode = S_IRUGO},
399 	.show = pid_show,
400 };
401 
402 static int nbd_thread_recv(struct nbd_device *nbd)
403 {
404 	struct request *req;
405 	int ret;
406 
407 	BUG_ON(nbd->magic != NBD_MAGIC);
408 
409 	sk_set_memalloc(nbd->sock->sk);
410 
411 	nbd->task_recv = current;
412 
413 	ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
414 	if (ret) {
415 		dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
416 		nbd->task_recv = NULL;
417 		return ret;
418 	}
419 
420 	while (1) {
421 		req = nbd_read_stat(nbd);
422 		if (IS_ERR(req)) {
423 			ret = PTR_ERR(req);
424 			break;
425 		}
426 
427 		nbd_end_request(nbd, req);
428 	}
429 
430 	device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
431 
432 	nbd->task_recv = NULL;
433 
434 	if (signal_pending(current)) {
435 		siginfo_t info;
436 
437 		ret = dequeue_signal_lock(current, &current->blocked, &info);
438 		dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
439 			 task_pid_nr(current), current->comm, ret);
440 		mutex_lock(&nbd->tx_lock);
441 		sock_shutdown(nbd);
442 		mutex_unlock(&nbd->tx_lock);
443 		ret = -ETIMEDOUT;
444 	}
445 
446 	return ret;
447 }
448 
449 static void nbd_clear_que(struct nbd_device *nbd)
450 {
451 	struct request *req;
452 
453 	BUG_ON(nbd->magic != NBD_MAGIC);
454 
455 	/*
456 	 * Because we have set nbd->sock to NULL under the tx_lock, all
457 	 * modifications to the list must have completed by now.  For
458 	 * the same reason, the active_req must be NULL.
459 	 *
460 	 * As a consequence, we don't need to take the spin lock while
461 	 * purging the list here.
462 	 */
463 	BUG_ON(nbd->sock);
464 	BUG_ON(nbd->active_req);
465 
466 	while (!list_empty(&nbd->queue_head)) {
467 		req = list_entry(nbd->queue_head.next, struct request,
468 				 queuelist);
469 		list_del_init(&req->queuelist);
470 		req->errors++;
471 		nbd_end_request(nbd, req);
472 	}
473 
474 	while (!list_empty(&nbd->waiting_queue)) {
475 		req = list_entry(nbd->waiting_queue.next, struct request,
476 				 queuelist);
477 		list_del_init(&req->queuelist);
478 		req->errors++;
479 		nbd_end_request(nbd, req);
480 	}
481 	dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
482 }
483 
484 
485 static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
486 {
487 	if (req->cmd_type != REQ_TYPE_FS)
488 		goto error_out;
489 
490 	if (rq_data_dir(req) == WRITE &&
491 	    (nbd->flags & NBD_FLAG_READ_ONLY)) {
492 		dev_err(disk_to_dev(nbd->disk),
493 			"Write on read-only\n");
494 		goto error_out;
495 	}
496 
497 	req->errors = 0;
498 
499 	mutex_lock(&nbd->tx_lock);
500 	if (unlikely(!nbd->sock)) {
501 		mutex_unlock(&nbd->tx_lock);
502 		dev_err(disk_to_dev(nbd->disk),
503 			"Attempted send on closed socket\n");
504 		goto error_out;
505 	}
506 
507 	nbd->active_req = req;
508 
509 	if (nbd->xmit_timeout && list_empty_careful(&nbd->queue_head))
510 		mod_timer(&nbd->timeout_timer, jiffies + nbd->xmit_timeout);
511 
512 	if (nbd_send_req(nbd, req) != 0) {
513 		dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
514 		req->errors++;
515 		nbd_end_request(nbd, req);
516 	} else {
517 		spin_lock(&nbd->queue_lock);
518 		list_add_tail(&req->queuelist, &nbd->queue_head);
519 		spin_unlock(&nbd->queue_lock);
520 	}
521 
522 	nbd->active_req = NULL;
523 	mutex_unlock(&nbd->tx_lock);
524 	wake_up_all(&nbd->active_wq);
525 
526 	return;
527 
528 error_out:
529 	req->errors++;
530 	nbd_end_request(nbd, req);
531 }
532 
533 static int nbd_thread_send(void *data)
534 {
535 	struct nbd_device *nbd = data;
536 	struct request *req;
537 
538 	nbd->task_send = current;
539 
540 	set_user_nice(current, MIN_NICE);
541 	while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
542 		/* wait for something to do */
543 		wait_event_interruptible(nbd->waiting_wq,
544 					 kthread_should_stop() ||
545 					 !list_empty(&nbd->waiting_queue));
546 
547 		if (signal_pending(current)) {
548 			siginfo_t info;
549 			int ret;
550 
551 			ret = dequeue_signal_lock(current, &current->blocked,
552 						  &info);
553 			dev_warn(nbd_to_dev(nbd), "pid %d, %s, got signal %d\n",
554 				 task_pid_nr(current), current->comm, ret);
555 			mutex_lock(&nbd->tx_lock);
556 			sock_shutdown(nbd);
557 			mutex_unlock(&nbd->tx_lock);
558 			break;
559 		}
560 
561 		/* extract request */
562 		if (list_empty(&nbd->waiting_queue))
563 			continue;
564 
565 		spin_lock_irq(&nbd->queue_lock);
566 		req = list_entry(nbd->waiting_queue.next, struct request,
567 				 queuelist);
568 		list_del_init(&req->queuelist);
569 		spin_unlock_irq(&nbd->queue_lock);
570 
571 		/* handle request */
572 		nbd_handle_req(nbd, req);
573 	}
574 
575 	nbd->task_send = NULL;
576 
577 	return 0;
578 }
579 
580 /*
581  * We always wait for result of write, for now. It would be nice to make it optional
582  * in future
583  * if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
584  *   { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
585  */
586 
587 static void nbd_request_handler(struct request_queue *q)
588 		__releases(q->queue_lock) __acquires(q->queue_lock)
589 {
590 	struct request *req;
591 
592 	while ((req = blk_fetch_request(q)) != NULL) {
593 		struct nbd_device *nbd;
594 
595 		spin_unlock_irq(q->queue_lock);
596 
597 		nbd = req->rq_disk->private_data;
598 
599 		BUG_ON(nbd->magic != NBD_MAGIC);
600 
601 		dev_dbg(nbd_to_dev(nbd), "request %p: dequeued (flags=%x)\n",
602 			req, req->cmd_type);
603 
604 		if (unlikely(!nbd->sock)) {
605 			dev_err(disk_to_dev(nbd->disk),
606 				"Attempted send on closed socket\n");
607 			req->errors++;
608 			nbd_end_request(nbd, req);
609 			spin_lock_irq(q->queue_lock);
610 			continue;
611 		}
612 
613 		spin_lock_irq(&nbd->queue_lock);
614 		list_add_tail(&req->queuelist, &nbd->waiting_queue);
615 		spin_unlock_irq(&nbd->queue_lock);
616 
617 		wake_up(&nbd->waiting_wq);
618 
619 		spin_lock_irq(q->queue_lock);
620 	}
621 }
622 
623 static int nbd_dev_dbg_init(struct nbd_device *nbd);
624 static void nbd_dev_dbg_close(struct nbd_device *nbd);
625 
626 /* Must be called with tx_lock held */
627 
628 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
629 		       unsigned int cmd, unsigned long arg)
630 {
631 	switch (cmd) {
632 	case NBD_DISCONNECT: {
633 		struct request sreq;
634 
635 		dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
636 		if (!nbd->sock)
637 			return -EINVAL;
638 
639 		mutex_unlock(&nbd->tx_lock);
640 		fsync_bdev(bdev);
641 		mutex_lock(&nbd->tx_lock);
642 		blk_rq_init(NULL, &sreq);
643 		sreq.cmd_type = REQ_TYPE_DRV_PRIV;
644 
645 		/* Check again after getting mutex back.  */
646 		if (!nbd->sock)
647 			return -EINVAL;
648 
649 		nbd->disconnect = true;
650 
651 		nbd_send_req(nbd, &sreq);
652 		return 0;
653 	}
654 
655 	case NBD_CLEAR_SOCK: {
656 		struct socket *sock = nbd->sock;
657 		nbd->sock = NULL;
658 		nbd_clear_que(nbd);
659 		BUG_ON(!list_empty(&nbd->queue_head));
660 		BUG_ON(!list_empty(&nbd->waiting_queue));
661 		kill_bdev(bdev);
662 		if (sock)
663 			sockfd_put(sock);
664 		return 0;
665 	}
666 
667 	case NBD_SET_SOCK: {
668 		struct socket *sock;
669 		int err;
670 		if (nbd->sock)
671 			return -EBUSY;
672 		sock = sockfd_lookup(arg, &err);
673 		if (sock) {
674 			nbd->sock = sock;
675 			if (max_part > 0)
676 				bdev->bd_invalidated = 1;
677 			nbd->disconnect = false; /* we're connected now */
678 			return 0;
679 		}
680 		return -EINVAL;
681 	}
682 
683 	case NBD_SET_BLKSIZE:
684 		nbd->blksize = arg;
685 		nbd->bytesize &= ~(nbd->blksize-1);
686 		bdev->bd_inode->i_size = nbd->bytesize;
687 		set_blocksize(bdev, nbd->blksize);
688 		set_capacity(nbd->disk, nbd->bytesize >> 9);
689 		return 0;
690 
691 	case NBD_SET_SIZE:
692 		nbd->bytesize = arg & ~(nbd->blksize-1);
693 		bdev->bd_inode->i_size = nbd->bytesize;
694 		set_blocksize(bdev, nbd->blksize);
695 		set_capacity(nbd->disk, nbd->bytesize >> 9);
696 		return 0;
697 
698 	case NBD_SET_TIMEOUT:
699 		nbd->xmit_timeout = arg * HZ;
700 		if (arg)
701 			mod_timer(&nbd->timeout_timer,
702 				  jiffies + nbd->xmit_timeout);
703 		else
704 			del_timer_sync(&nbd->timeout_timer);
705 
706 		return 0;
707 
708 	case NBD_SET_FLAGS:
709 		nbd->flags = arg;
710 		return 0;
711 
712 	case NBD_SET_SIZE_BLOCKS:
713 		nbd->bytesize = ((u64) arg) * nbd->blksize;
714 		bdev->bd_inode->i_size = nbd->bytesize;
715 		set_blocksize(bdev, nbd->blksize);
716 		set_capacity(nbd->disk, nbd->bytesize >> 9);
717 		return 0;
718 
719 	case NBD_DO_IT: {
720 		struct task_struct *thread;
721 		struct socket *sock;
722 		int error;
723 
724 		if (nbd->task_recv)
725 			return -EBUSY;
726 		if (!nbd->sock)
727 			return -EINVAL;
728 
729 		mutex_unlock(&nbd->tx_lock);
730 
731 		if (nbd->flags & NBD_FLAG_READ_ONLY)
732 			set_device_ro(bdev, true);
733 		if (nbd->flags & NBD_FLAG_SEND_TRIM)
734 			queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
735 				nbd->disk->queue);
736 		if (nbd->flags & NBD_FLAG_SEND_FLUSH)
737 			blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
738 		else
739 			blk_queue_flush(nbd->disk->queue, 0);
740 
741 		thread = kthread_run(nbd_thread_send, nbd, "%s",
742 				     nbd_name(nbd));
743 		if (IS_ERR(thread)) {
744 			mutex_lock(&nbd->tx_lock);
745 			return PTR_ERR(thread);
746 		}
747 
748 		nbd_dev_dbg_init(nbd);
749 		error = nbd_thread_recv(nbd);
750 		nbd_dev_dbg_close(nbd);
751 		kthread_stop(thread);
752 
753 		mutex_lock(&nbd->tx_lock);
754 
755 		sock_shutdown(nbd);
756 		sock = nbd->sock;
757 		nbd->sock = NULL;
758 		nbd_clear_que(nbd);
759 		kill_bdev(bdev);
760 		queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
761 		set_device_ro(bdev, false);
762 		if (sock)
763 			sockfd_put(sock);
764 		nbd->flags = 0;
765 		nbd->bytesize = 0;
766 		bdev->bd_inode->i_size = 0;
767 		set_capacity(nbd->disk, 0);
768 		if (max_part > 0)
769 			blkdev_reread_part(bdev);
770 		if (nbd->disconnect) /* user requested, ignore socket errors */
771 			return 0;
772 		return error;
773 	}
774 
775 	case NBD_CLEAR_QUE:
776 		/*
777 		 * This is for compatibility only.  The queue is always cleared
778 		 * by NBD_DO_IT or NBD_CLEAR_SOCK.
779 		 */
780 		return 0;
781 
782 	case NBD_PRINT_DEBUG:
783 		dev_info(disk_to_dev(nbd->disk),
784 			"next = %p, prev = %p, head = %p\n",
785 			nbd->queue_head.next, nbd->queue_head.prev,
786 			&nbd->queue_head);
787 		return 0;
788 	}
789 	return -ENOTTY;
790 }
791 
792 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
793 		     unsigned int cmd, unsigned long arg)
794 {
795 	struct nbd_device *nbd = bdev->bd_disk->private_data;
796 	int error;
797 
798 	if (!capable(CAP_SYS_ADMIN))
799 		return -EPERM;
800 
801 	BUG_ON(nbd->magic != NBD_MAGIC);
802 
803 	mutex_lock(&nbd->tx_lock);
804 	error = __nbd_ioctl(bdev, nbd, cmd, arg);
805 	mutex_unlock(&nbd->tx_lock);
806 
807 	return error;
808 }
809 
810 static const struct block_device_operations nbd_fops =
811 {
812 	.owner =	THIS_MODULE,
813 	.ioctl =	nbd_ioctl,
814 };
815 
816 #if IS_ENABLED(CONFIG_DEBUG_FS)
817 
818 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
819 {
820 	struct nbd_device *nbd = s->private;
821 
822 	if (nbd->task_recv)
823 		seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
824 	if (nbd->task_send)
825 		seq_printf(s, "send: %d\n", task_pid_nr(nbd->task_send));
826 
827 	return 0;
828 }
829 
830 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
831 {
832 	return single_open(file, nbd_dbg_tasks_show, inode->i_private);
833 }
834 
835 static const struct file_operations nbd_dbg_tasks_ops = {
836 	.open = nbd_dbg_tasks_open,
837 	.read = seq_read,
838 	.llseek = seq_lseek,
839 	.release = single_release,
840 };
841 
842 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
843 {
844 	struct nbd_device *nbd = s->private;
845 	u32 flags = nbd->flags;
846 
847 	seq_printf(s, "Hex: 0x%08x\n\n", flags);
848 
849 	seq_puts(s, "Known flags:\n");
850 
851 	if (flags & NBD_FLAG_HAS_FLAGS)
852 		seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
853 	if (flags & NBD_FLAG_READ_ONLY)
854 		seq_puts(s, "NBD_FLAG_READ_ONLY\n");
855 	if (flags & NBD_FLAG_SEND_FLUSH)
856 		seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
857 	if (flags & NBD_FLAG_SEND_TRIM)
858 		seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
859 
860 	return 0;
861 }
862 
863 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
864 {
865 	return single_open(file, nbd_dbg_flags_show, inode->i_private);
866 }
867 
868 static const struct file_operations nbd_dbg_flags_ops = {
869 	.open = nbd_dbg_flags_open,
870 	.read = seq_read,
871 	.llseek = seq_lseek,
872 	.release = single_release,
873 };
874 
875 static int nbd_dev_dbg_init(struct nbd_device *nbd)
876 {
877 	struct dentry *dir;
878 	struct dentry *f;
879 
880 	dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
881 	if (IS_ERR_OR_NULL(dir)) {
882 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s' (%ld)\n",
883 			nbd_name(nbd), PTR_ERR(dir));
884 		return PTR_ERR(dir);
885 	}
886 	nbd->dbg_dir = dir;
887 
888 	f = debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
889 	if (IS_ERR_OR_NULL(f)) {
890 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs file 'tasks', %ld\n",
891 			PTR_ERR(f));
892 		return PTR_ERR(f);
893 	}
894 
895 	f = debugfs_create_u64("size_bytes", 0444, dir, &nbd->bytesize);
896 	if (IS_ERR_OR_NULL(f)) {
897 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs file 'size_bytes', %ld\n",
898 			PTR_ERR(f));
899 		return PTR_ERR(f);
900 	}
901 
902 	f = debugfs_create_u32("timeout", 0444, dir, &nbd->xmit_timeout);
903 	if (IS_ERR_OR_NULL(f)) {
904 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs file 'timeout', %ld\n",
905 			PTR_ERR(f));
906 		return PTR_ERR(f);
907 	}
908 
909 	f = debugfs_create_u32("blocksize", 0444, dir, &nbd->blksize);
910 	if (IS_ERR_OR_NULL(f)) {
911 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs file 'blocksize', %ld\n",
912 			PTR_ERR(f));
913 		return PTR_ERR(f);
914 	}
915 
916 	f = debugfs_create_file("flags", 0444, dir, &nbd, &nbd_dbg_flags_ops);
917 	if (IS_ERR_OR_NULL(f)) {
918 		dev_err(nbd_to_dev(nbd), "Failed to create debugfs file 'flags', %ld\n",
919 			PTR_ERR(f));
920 		return PTR_ERR(f);
921 	}
922 
923 	return 0;
924 }
925 
926 static void nbd_dev_dbg_close(struct nbd_device *nbd)
927 {
928 	debugfs_remove_recursive(nbd->dbg_dir);
929 }
930 
931 static int nbd_dbg_init(void)
932 {
933 	struct dentry *dbg_dir;
934 
935 	dbg_dir = debugfs_create_dir("nbd", NULL);
936 	if (IS_ERR(dbg_dir))
937 		return PTR_ERR(dbg_dir);
938 
939 	nbd_dbg_dir = dbg_dir;
940 
941 	return 0;
942 }
943 
944 static void nbd_dbg_close(void)
945 {
946 	debugfs_remove_recursive(nbd_dbg_dir);
947 }
948 
949 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
950 
951 static int nbd_dev_dbg_init(struct nbd_device *nbd)
952 {
953 	return 0;
954 }
955 
956 static void nbd_dev_dbg_close(struct nbd_device *nbd)
957 {
958 }
959 
960 static int nbd_dbg_init(void)
961 {
962 	return 0;
963 }
964 
965 static void nbd_dbg_close(void)
966 {
967 }
968 
969 #endif
970 
971 /*
972  * And here should be modules and kernel interface
973  *  (Just smiley confuses emacs :-)
974  */
975 
976 static int __init nbd_init(void)
977 {
978 	int err = -ENOMEM;
979 	int i;
980 	int part_shift;
981 
982 	BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
983 
984 	if (max_part < 0) {
985 		printk(KERN_ERR "nbd: max_part must be >= 0\n");
986 		return -EINVAL;
987 	}
988 
989 	part_shift = 0;
990 	if (max_part > 0) {
991 		part_shift = fls(max_part);
992 
993 		/*
994 		 * Adjust max_part according to part_shift as it is exported
995 		 * to user space so that user can know the max number of
996 		 * partition kernel should be able to manage.
997 		 *
998 		 * Note that -1 is required because partition 0 is reserved
999 		 * for the whole disk.
1000 		 */
1001 		max_part = (1UL << part_shift) - 1;
1002 	}
1003 
1004 	if ((1UL << part_shift) > DISK_MAX_PARTS)
1005 		return -EINVAL;
1006 
1007 	if (nbds_max > 1UL << (MINORBITS - part_shift))
1008 		return -EINVAL;
1009 
1010 	nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
1011 	if (!nbd_dev)
1012 		return -ENOMEM;
1013 
1014 	for (i = 0; i < nbds_max; i++) {
1015 		struct gendisk *disk = alloc_disk(1 << part_shift);
1016 		if (!disk)
1017 			goto out;
1018 		nbd_dev[i].disk = disk;
1019 		/*
1020 		 * The new linux 2.5 block layer implementation requires
1021 		 * every gendisk to have its very own request_queue struct.
1022 		 * These structs are big so we dynamically allocate them.
1023 		 */
1024 		disk->queue = blk_init_queue(nbd_request_handler, &nbd_lock);
1025 		if (!disk->queue) {
1026 			put_disk(disk);
1027 			goto out;
1028 		}
1029 		/*
1030 		 * Tell the block layer that we are not a rotational device
1031 		 */
1032 		queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1033 		queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1034 		disk->queue->limits.discard_granularity = 512;
1035 		blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1036 		disk->queue->limits.discard_zeroes_data = 0;
1037 		blk_queue_max_hw_sectors(disk->queue, 65536);
1038 		disk->queue->limits.max_sectors = 256;
1039 	}
1040 
1041 	if (register_blkdev(NBD_MAJOR, "nbd")) {
1042 		err = -EIO;
1043 		goto out;
1044 	}
1045 
1046 	printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
1047 
1048 	nbd_dbg_init();
1049 
1050 	for (i = 0; i < nbds_max; i++) {
1051 		struct gendisk *disk = nbd_dev[i].disk;
1052 		nbd_dev[i].magic = NBD_MAGIC;
1053 		INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
1054 		spin_lock_init(&nbd_dev[i].queue_lock);
1055 		INIT_LIST_HEAD(&nbd_dev[i].queue_head);
1056 		mutex_init(&nbd_dev[i].tx_lock);
1057 		init_timer(&nbd_dev[i].timeout_timer);
1058 		nbd_dev[i].timeout_timer.function = nbd_xmit_timeout;
1059 		nbd_dev[i].timeout_timer.data = (unsigned long)&nbd_dev[i];
1060 		init_waitqueue_head(&nbd_dev[i].active_wq);
1061 		init_waitqueue_head(&nbd_dev[i].waiting_wq);
1062 		nbd_dev[i].blksize = 1024;
1063 		nbd_dev[i].bytesize = 0;
1064 		disk->major = NBD_MAJOR;
1065 		disk->first_minor = i << part_shift;
1066 		disk->fops = &nbd_fops;
1067 		disk->private_data = &nbd_dev[i];
1068 		sprintf(disk->disk_name, "nbd%d", i);
1069 		set_capacity(disk, 0);
1070 		add_disk(disk);
1071 	}
1072 
1073 	return 0;
1074 out:
1075 	while (i--) {
1076 		blk_cleanup_queue(nbd_dev[i].disk->queue);
1077 		put_disk(nbd_dev[i].disk);
1078 	}
1079 	kfree(nbd_dev);
1080 	return err;
1081 }
1082 
1083 static void __exit nbd_cleanup(void)
1084 {
1085 	int i;
1086 
1087 	nbd_dbg_close();
1088 
1089 	for (i = 0; i < nbds_max; i++) {
1090 		struct gendisk *disk = nbd_dev[i].disk;
1091 		nbd_dev[i].magic = 0;
1092 		if (disk) {
1093 			del_gendisk(disk);
1094 			blk_cleanup_queue(disk->queue);
1095 			put_disk(disk);
1096 		}
1097 	}
1098 	unregister_blkdev(NBD_MAJOR, "nbd");
1099 	kfree(nbd_dev);
1100 	printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
1101 }
1102 
1103 module_init(nbd_init);
1104 module_exit(nbd_cleanup);
1105 
1106 MODULE_DESCRIPTION("Network Block Device");
1107 MODULE_LICENSE("GPL");
1108 
1109 module_param(nbds_max, int, 0444);
1110 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
1111 module_param(max_part, int, 0444);
1112 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
1113