xref: /linux/drivers/block/nbd.c (revision c0e297dc61f8d4453e07afbea1fa8d0e67cd4a34)
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 
37 #include <asm/uaccess.h>
38 #include <asm/types.h>
39 
40 #include <linux/nbd.h>
41 
42 struct nbd_device {
43 	int flags;
44 	int harderror;		/* Code of hard error			*/
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 	pid_t pid; /* pid of nbd-client, if attached */
60 	int xmit_timeout;
61 	int disconnect; /* a disconnect has been requested by user */
62 };
63 
64 #define NBD_MAGIC 0x68797548
65 
66 static unsigned int nbds_max = 16;
67 static struct nbd_device *nbd_dev;
68 static int max_part;
69 
70 /*
71  * Use just one lock (or at most 1 per NIC). Two arguments for this:
72  * 1. Each NIC is essentially a synchronization point for all servers
73  *    accessed through that NIC so there's no need to have more locks
74  *    than NICs anyway.
75  * 2. More locks lead to more "Dirty cache line bouncing" which will slow
76  *    down each lock to the point where they're actually slower than just
77  *    a single lock.
78  * Thanks go to Jens Axboe and Al Viro for their LKML emails explaining this!
79  */
80 static DEFINE_SPINLOCK(nbd_lock);
81 
82 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
83 {
84 	return disk_to_dev(nbd->disk);
85 }
86 
87 static const char *nbdcmd_to_ascii(int cmd)
88 {
89 	switch (cmd) {
90 	case  NBD_CMD_READ: return "read";
91 	case NBD_CMD_WRITE: return "write";
92 	case  NBD_CMD_DISC: return "disconnect";
93 	case NBD_CMD_FLUSH: return "flush";
94 	case  NBD_CMD_TRIM: return "trim/discard";
95 	}
96 	return "invalid";
97 }
98 
99 static void nbd_end_request(struct nbd_device *nbd, struct request *req)
100 {
101 	int error = req->errors ? -EIO : 0;
102 	struct request_queue *q = req->q;
103 	unsigned long flags;
104 
105 	dev_dbg(nbd_to_dev(nbd), "request %p: %s\n", req,
106 		error ? "failed" : "done");
107 
108 	spin_lock_irqsave(q->queue_lock, flags);
109 	__blk_end_request_all(req, error);
110 	spin_unlock_irqrestore(q->queue_lock, flags);
111 }
112 
113 /*
114  * Forcibly shutdown the socket causing all listeners to error
115  */
116 static void sock_shutdown(struct nbd_device *nbd, int lock)
117 {
118 	if (lock)
119 		mutex_lock(&nbd->tx_lock);
120 	if (nbd->sock) {
121 		dev_warn(disk_to_dev(nbd->disk), "shutting down socket\n");
122 		kernel_sock_shutdown(nbd->sock, SHUT_RDWR);
123 		nbd->sock = NULL;
124 	}
125 	if (lock)
126 		mutex_unlock(&nbd->tx_lock);
127 }
128 
129 static void nbd_xmit_timeout(unsigned long arg)
130 {
131 	struct task_struct *task = (struct task_struct *)arg;
132 
133 	printk(KERN_WARNING "nbd: killing hung xmit (%s, pid: %d)\n",
134 		task->comm, task->pid);
135 	force_sig(SIGKILL, task);
136 }
137 
138 /*
139  *  Send or receive packet.
140  */
141 static int sock_xmit(struct nbd_device *nbd, int send, void *buf, int size,
142 		int msg_flags)
143 {
144 	struct socket *sock = nbd->sock;
145 	int result;
146 	struct msghdr msg;
147 	struct kvec iov;
148 	sigset_t blocked, oldset;
149 	unsigned long pflags = current->flags;
150 
151 	if (unlikely(!sock)) {
152 		dev_err(disk_to_dev(nbd->disk),
153 			"Attempted %s on closed socket in sock_xmit\n",
154 			(send ? "send" : "recv"));
155 		return -EINVAL;
156 	}
157 
158 	/* Allow interception of SIGKILL only
159 	 * Don't allow other signals to interrupt the transmission */
160 	siginitsetinv(&blocked, sigmask(SIGKILL));
161 	sigprocmask(SIG_SETMASK, &blocked, &oldset);
162 
163 	current->flags |= PF_MEMALLOC;
164 	do {
165 		sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
166 		iov.iov_base = buf;
167 		iov.iov_len = size;
168 		msg.msg_name = NULL;
169 		msg.msg_namelen = 0;
170 		msg.msg_control = NULL;
171 		msg.msg_controllen = 0;
172 		msg.msg_flags = msg_flags | MSG_NOSIGNAL;
173 
174 		if (send) {
175 			struct timer_list ti;
176 
177 			if (nbd->xmit_timeout) {
178 				init_timer(&ti);
179 				ti.function = nbd_xmit_timeout;
180 				ti.data = (unsigned long)current;
181 				ti.expires = jiffies + nbd->xmit_timeout;
182 				add_timer(&ti);
183 			}
184 			result = kernel_sendmsg(sock, &msg, &iov, 1, size);
185 			if (nbd->xmit_timeout)
186 				del_timer_sync(&ti);
187 		} else
188 			result = kernel_recvmsg(sock, &msg, &iov, 1, size,
189 						msg.msg_flags);
190 
191 		if (signal_pending(current)) {
192 			siginfo_t info;
193 			printk(KERN_WARNING "nbd (pid %d: %s) got signal %d\n",
194 				task_pid_nr(current), current->comm,
195 				dequeue_signal_lock(current, &current->blocked, &info));
196 			result = -EINTR;
197 			sock_shutdown(nbd, !send);
198 			break;
199 		}
200 
201 		if (result <= 0) {
202 			if (result == 0)
203 				result = -EPIPE; /* short read */
204 			break;
205 		}
206 		size -= result;
207 		buf += result;
208 	} while (size > 0);
209 
210 	sigprocmask(SIG_SETMASK, &oldset, NULL);
211 	tsk_restore_flags(current, pflags, PF_MEMALLOC);
212 
213 	return result;
214 }
215 
216 static inline int sock_send_bvec(struct nbd_device *nbd, struct bio_vec *bvec,
217 		int flags)
218 {
219 	int result;
220 	void *kaddr = kmap(bvec->bv_page);
221 	result = sock_xmit(nbd, 1, kaddr + bvec->bv_offset,
222 			   bvec->bv_len, flags);
223 	kunmap(bvec->bv_page);
224 	return result;
225 }
226 
227 /* always call with the tx_lock held */
228 static int nbd_send_req(struct nbd_device *nbd, struct request *req)
229 {
230 	int result, flags;
231 	struct nbd_request request;
232 	unsigned long size = blk_rq_bytes(req);
233 	u32 type;
234 
235 	if (req->cmd_type == REQ_TYPE_DRV_PRIV)
236 		type = NBD_CMD_DISC;
237 	else if (req->cmd_flags & REQ_DISCARD)
238 		type = NBD_CMD_TRIM;
239 	else if (req->cmd_flags & REQ_FLUSH)
240 		type = NBD_CMD_FLUSH;
241 	else if (rq_data_dir(req) == WRITE)
242 		type = NBD_CMD_WRITE;
243 	else
244 		type = NBD_CMD_READ;
245 
246 	memset(&request, 0, sizeof(request));
247 	request.magic = htonl(NBD_REQUEST_MAGIC);
248 	request.type = htonl(type);
249 	if (type != NBD_CMD_FLUSH && type != NBD_CMD_DISC) {
250 		request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
251 		request.len = htonl(size);
252 	}
253 	memcpy(request.handle, &req, sizeof(req));
254 
255 	dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
256 		req, nbdcmd_to_ascii(type),
257 		(unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
258 	result = sock_xmit(nbd, 1, &request, sizeof(request),
259 			(type == NBD_CMD_WRITE) ? MSG_MORE : 0);
260 	if (result <= 0) {
261 		dev_err(disk_to_dev(nbd->disk),
262 			"Send control failed (result %d)\n", result);
263 		return -EIO;
264 	}
265 
266 	if (type == NBD_CMD_WRITE) {
267 		struct req_iterator iter;
268 		struct bio_vec bvec;
269 		/*
270 		 * we are really probing at internals to determine
271 		 * whether to set MSG_MORE or not...
272 		 */
273 		rq_for_each_segment(bvec, req, iter) {
274 			flags = 0;
275 			if (!rq_iter_last(bvec, iter))
276 				flags = MSG_MORE;
277 			dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
278 				req, bvec.bv_len);
279 			result = sock_send_bvec(nbd, &bvec, flags);
280 			if (result <= 0) {
281 				dev_err(disk_to_dev(nbd->disk),
282 					"Send data failed (result %d)\n",
283 					result);
284 				return -EIO;
285 			}
286 		}
287 	}
288 	return 0;
289 }
290 
291 static struct request *nbd_find_request(struct nbd_device *nbd,
292 					struct request *xreq)
293 {
294 	struct request *req, *tmp;
295 	int err;
296 
297 	err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
298 	if (unlikely(err))
299 		return ERR_PTR(err);
300 
301 	spin_lock(&nbd->queue_lock);
302 	list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
303 		if (req != xreq)
304 			continue;
305 		list_del_init(&req->queuelist);
306 		spin_unlock(&nbd->queue_lock);
307 		return req;
308 	}
309 	spin_unlock(&nbd->queue_lock);
310 
311 	return ERR_PTR(-ENOENT);
312 }
313 
314 static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
315 {
316 	int result;
317 	void *kaddr = kmap(bvec->bv_page);
318 	result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
319 			MSG_WAITALL);
320 	kunmap(bvec->bv_page);
321 	return result;
322 }
323 
324 /* NULL returned = something went wrong, inform userspace */
325 static struct request *nbd_read_stat(struct nbd_device *nbd)
326 {
327 	int result;
328 	struct nbd_reply reply;
329 	struct request *req;
330 
331 	reply.magic = 0;
332 	result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
333 	if (result <= 0) {
334 		dev_err(disk_to_dev(nbd->disk),
335 			"Receive control failed (result %d)\n", result);
336 		goto harderror;
337 	}
338 
339 	if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
340 		dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
341 				(unsigned long)ntohl(reply.magic));
342 		result = -EPROTO;
343 		goto harderror;
344 	}
345 
346 	req = nbd_find_request(nbd, *(struct request **)reply.handle);
347 	if (IS_ERR(req)) {
348 		result = PTR_ERR(req);
349 		if (result != -ENOENT)
350 			goto harderror;
351 
352 		dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
353 			reply.handle);
354 		result = -EBADR;
355 		goto harderror;
356 	}
357 
358 	if (ntohl(reply.error)) {
359 		dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
360 			ntohl(reply.error));
361 		req->errors++;
362 		return req;
363 	}
364 
365 	dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
366 	if (rq_data_dir(req) != WRITE) {
367 		struct req_iterator iter;
368 		struct bio_vec bvec;
369 
370 		rq_for_each_segment(bvec, req, iter) {
371 			result = sock_recv_bvec(nbd, &bvec);
372 			if (result <= 0) {
373 				dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
374 					result);
375 				req->errors++;
376 				return req;
377 			}
378 			dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
379 				req, bvec.bv_len);
380 		}
381 	}
382 	return req;
383 harderror:
384 	nbd->harderror = result;
385 	return NULL;
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 
393 	return sprintf(buf, "%ld\n",
394 		(long) ((struct nbd_device *)disk->private_data)->pid);
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_do_it(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 	nbd->pid = task_pid_nr(current);
411 	ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
412 	if (ret) {
413 		dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
414 		nbd->pid = 0;
415 		return ret;
416 	}
417 
418 	while ((req = nbd_read_stat(nbd)) != NULL)
419 		nbd_end_request(nbd, req);
420 
421 	device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
422 	nbd->pid = 0;
423 	return 0;
424 }
425 
426 static void nbd_clear_que(struct nbd_device *nbd)
427 {
428 	struct request *req;
429 
430 	BUG_ON(nbd->magic != NBD_MAGIC);
431 
432 	/*
433 	 * Because we have set nbd->sock to NULL under the tx_lock, all
434 	 * modifications to the list must have completed by now.  For
435 	 * the same reason, the active_req must be NULL.
436 	 *
437 	 * As a consequence, we don't need to take the spin lock while
438 	 * purging the list here.
439 	 */
440 	BUG_ON(nbd->sock);
441 	BUG_ON(nbd->active_req);
442 
443 	while (!list_empty(&nbd->queue_head)) {
444 		req = list_entry(nbd->queue_head.next, struct request,
445 				 queuelist);
446 		list_del_init(&req->queuelist);
447 		req->errors++;
448 		nbd_end_request(nbd, req);
449 	}
450 
451 	while (!list_empty(&nbd->waiting_queue)) {
452 		req = list_entry(nbd->waiting_queue.next, struct request,
453 				 queuelist);
454 		list_del_init(&req->queuelist);
455 		req->errors++;
456 		nbd_end_request(nbd, req);
457 	}
458 }
459 
460 
461 static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
462 {
463 	if (req->cmd_type != REQ_TYPE_FS)
464 		goto error_out;
465 
466 	if (rq_data_dir(req) == WRITE &&
467 	    (nbd->flags & NBD_FLAG_READ_ONLY)) {
468 		dev_err(disk_to_dev(nbd->disk),
469 			"Write on read-only\n");
470 		goto error_out;
471 	}
472 
473 	req->errors = 0;
474 
475 	mutex_lock(&nbd->tx_lock);
476 	if (unlikely(!nbd->sock)) {
477 		mutex_unlock(&nbd->tx_lock);
478 		dev_err(disk_to_dev(nbd->disk),
479 			"Attempted send on closed socket\n");
480 		goto error_out;
481 	}
482 
483 	nbd->active_req = req;
484 
485 	if (nbd_send_req(nbd, req) != 0) {
486 		dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
487 		req->errors++;
488 		nbd_end_request(nbd, req);
489 	} else {
490 		spin_lock(&nbd->queue_lock);
491 		list_add_tail(&req->queuelist, &nbd->queue_head);
492 		spin_unlock(&nbd->queue_lock);
493 	}
494 
495 	nbd->active_req = NULL;
496 	mutex_unlock(&nbd->tx_lock);
497 	wake_up_all(&nbd->active_wq);
498 
499 	return;
500 
501 error_out:
502 	req->errors++;
503 	nbd_end_request(nbd, req);
504 }
505 
506 static int nbd_thread(void *data)
507 {
508 	struct nbd_device *nbd = data;
509 	struct request *req;
510 
511 	set_user_nice(current, MIN_NICE);
512 	while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
513 		/* wait for something to do */
514 		wait_event_interruptible(nbd->waiting_wq,
515 					 kthread_should_stop() ||
516 					 !list_empty(&nbd->waiting_queue));
517 
518 		/* extract request */
519 		if (list_empty(&nbd->waiting_queue))
520 			continue;
521 
522 		spin_lock_irq(&nbd->queue_lock);
523 		req = list_entry(nbd->waiting_queue.next, struct request,
524 				 queuelist);
525 		list_del_init(&req->queuelist);
526 		spin_unlock_irq(&nbd->queue_lock);
527 
528 		/* handle request */
529 		nbd_handle_req(nbd, req);
530 	}
531 	return 0;
532 }
533 
534 /*
535  * We always wait for result of write, for now. It would be nice to make it optional
536  * in future
537  * if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
538  *   { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
539  */
540 
541 static void do_nbd_request(struct request_queue *q)
542 		__releases(q->queue_lock) __acquires(q->queue_lock)
543 {
544 	struct request *req;
545 
546 	while ((req = blk_fetch_request(q)) != NULL) {
547 		struct nbd_device *nbd;
548 
549 		spin_unlock_irq(q->queue_lock);
550 
551 		nbd = req->rq_disk->private_data;
552 
553 		BUG_ON(nbd->magic != NBD_MAGIC);
554 
555 		dev_dbg(nbd_to_dev(nbd), "request %p: dequeued (flags=%x)\n",
556 			req, req->cmd_type);
557 
558 		if (unlikely(!nbd->sock)) {
559 			dev_err(disk_to_dev(nbd->disk),
560 				"Attempted send on closed socket\n");
561 			req->errors++;
562 			nbd_end_request(nbd, req);
563 			spin_lock_irq(q->queue_lock);
564 			continue;
565 		}
566 
567 		spin_lock_irq(&nbd->queue_lock);
568 		list_add_tail(&req->queuelist, &nbd->waiting_queue);
569 		spin_unlock_irq(&nbd->queue_lock);
570 
571 		wake_up(&nbd->waiting_wq);
572 
573 		spin_lock_irq(q->queue_lock);
574 	}
575 }
576 
577 /* Must be called with tx_lock held */
578 
579 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
580 		       unsigned int cmd, unsigned long arg)
581 {
582 	switch (cmd) {
583 	case NBD_DISCONNECT: {
584 		struct request sreq;
585 
586 		dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
587 		if (!nbd->sock)
588 			return -EINVAL;
589 
590 		mutex_unlock(&nbd->tx_lock);
591 		fsync_bdev(bdev);
592 		mutex_lock(&nbd->tx_lock);
593 		blk_rq_init(NULL, &sreq);
594 		sreq.cmd_type = REQ_TYPE_DRV_PRIV;
595 
596 		/* Check again after getting mutex back.  */
597 		if (!nbd->sock)
598 			return -EINVAL;
599 
600 		nbd->disconnect = 1;
601 
602 		nbd_send_req(nbd, &sreq);
603 		return 0;
604 	}
605 
606 	case NBD_CLEAR_SOCK: {
607 		struct socket *sock = nbd->sock;
608 		nbd->sock = NULL;
609 		nbd_clear_que(nbd);
610 		BUG_ON(!list_empty(&nbd->queue_head));
611 		BUG_ON(!list_empty(&nbd->waiting_queue));
612 		kill_bdev(bdev);
613 		if (sock)
614 			sockfd_put(sock);
615 		return 0;
616 	}
617 
618 	case NBD_SET_SOCK: {
619 		struct socket *sock;
620 		int err;
621 		if (nbd->sock)
622 			return -EBUSY;
623 		sock = sockfd_lookup(arg, &err);
624 		if (sock) {
625 			nbd->sock = sock;
626 			if (max_part > 0)
627 				bdev->bd_invalidated = 1;
628 			nbd->disconnect = 0; /* we're connected now */
629 			return 0;
630 		}
631 		return -EINVAL;
632 	}
633 
634 	case NBD_SET_BLKSIZE:
635 		nbd->blksize = arg;
636 		nbd->bytesize &= ~(nbd->blksize-1);
637 		bdev->bd_inode->i_size = nbd->bytesize;
638 		set_blocksize(bdev, nbd->blksize);
639 		set_capacity(nbd->disk, nbd->bytesize >> 9);
640 		return 0;
641 
642 	case NBD_SET_SIZE:
643 		nbd->bytesize = arg & ~(nbd->blksize-1);
644 		bdev->bd_inode->i_size = nbd->bytesize;
645 		set_blocksize(bdev, nbd->blksize);
646 		set_capacity(nbd->disk, nbd->bytesize >> 9);
647 		return 0;
648 
649 	case NBD_SET_TIMEOUT:
650 		nbd->xmit_timeout = arg * HZ;
651 		return 0;
652 
653 	case NBD_SET_FLAGS:
654 		nbd->flags = arg;
655 		return 0;
656 
657 	case NBD_SET_SIZE_BLOCKS:
658 		nbd->bytesize = ((u64) arg) * nbd->blksize;
659 		bdev->bd_inode->i_size = nbd->bytesize;
660 		set_blocksize(bdev, nbd->blksize);
661 		set_capacity(nbd->disk, nbd->bytesize >> 9);
662 		return 0;
663 
664 	case NBD_DO_IT: {
665 		struct task_struct *thread;
666 		struct socket *sock;
667 		int error;
668 
669 		if (nbd->pid)
670 			return -EBUSY;
671 		if (!nbd->sock)
672 			return -EINVAL;
673 
674 		mutex_unlock(&nbd->tx_lock);
675 
676 		if (nbd->flags & NBD_FLAG_READ_ONLY)
677 			set_device_ro(bdev, true);
678 		if (nbd->flags & NBD_FLAG_SEND_TRIM)
679 			queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
680 				nbd->disk->queue);
681 		if (nbd->flags & NBD_FLAG_SEND_FLUSH)
682 			blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
683 		else
684 			blk_queue_flush(nbd->disk->queue, 0);
685 
686 		thread = kthread_run(nbd_thread, nbd, "%s",
687 				     nbd->disk->disk_name);
688 		if (IS_ERR(thread)) {
689 			mutex_lock(&nbd->tx_lock);
690 			return PTR_ERR(thread);
691 		}
692 
693 		error = nbd_do_it(nbd);
694 		kthread_stop(thread);
695 
696 		mutex_lock(&nbd->tx_lock);
697 		if (error)
698 			return error;
699 		sock_shutdown(nbd, 0);
700 		sock = nbd->sock;
701 		nbd->sock = NULL;
702 		nbd_clear_que(nbd);
703 		dev_warn(disk_to_dev(nbd->disk), "queue cleared\n");
704 		kill_bdev(bdev);
705 		queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
706 		set_device_ro(bdev, false);
707 		if (sock)
708 			sockfd_put(sock);
709 		nbd->flags = 0;
710 		nbd->bytesize = 0;
711 		bdev->bd_inode->i_size = 0;
712 		set_capacity(nbd->disk, 0);
713 		if (max_part > 0)
714 			blkdev_reread_part(bdev);
715 		if (nbd->disconnect) /* user requested, ignore socket errors */
716 			return 0;
717 		return nbd->harderror;
718 	}
719 
720 	case NBD_CLEAR_QUE:
721 		/*
722 		 * This is for compatibility only.  The queue is always cleared
723 		 * by NBD_DO_IT or NBD_CLEAR_SOCK.
724 		 */
725 		return 0;
726 
727 	case NBD_PRINT_DEBUG:
728 		dev_info(disk_to_dev(nbd->disk),
729 			"next = %p, prev = %p, head = %p\n",
730 			nbd->queue_head.next, nbd->queue_head.prev,
731 			&nbd->queue_head);
732 		return 0;
733 	}
734 	return -ENOTTY;
735 }
736 
737 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
738 		     unsigned int cmd, unsigned long arg)
739 {
740 	struct nbd_device *nbd = bdev->bd_disk->private_data;
741 	int error;
742 
743 	if (!capable(CAP_SYS_ADMIN))
744 		return -EPERM;
745 
746 	BUG_ON(nbd->magic != NBD_MAGIC);
747 
748 	mutex_lock(&nbd->tx_lock);
749 	error = __nbd_ioctl(bdev, nbd, cmd, arg);
750 	mutex_unlock(&nbd->tx_lock);
751 
752 	return error;
753 }
754 
755 static const struct block_device_operations nbd_fops =
756 {
757 	.owner =	THIS_MODULE,
758 	.ioctl =	nbd_ioctl,
759 };
760 
761 /*
762  * And here should be modules and kernel interface
763  *  (Just smiley confuses emacs :-)
764  */
765 
766 static int __init nbd_init(void)
767 {
768 	int err = -ENOMEM;
769 	int i;
770 	int part_shift;
771 
772 	BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
773 
774 	if (max_part < 0) {
775 		printk(KERN_ERR "nbd: max_part must be >= 0\n");
776 		return -EINVAL;
777 	}
778 
779 	part_shift = 0;
780 	if (max_part > 0) {
781 		part_shift = fls(max_part);
782 
783 		/*
784 		 * Adjust max_part according to part_shift as it is exported
785 		 * to user space so that user can know the max number of
786 		 * partition kernel should be able to manage.
787 		 *
788 		 * Note that -1 is required because partition 0 is reserved
789 		 * for the whole disk.
790 		 */
791 		max_part = (1UL << part_shift) - 1;
792 	}
793 
794 	if ((1UL << part_shift) > DISK_MAX_PARTS)
795 		return -EINVAL;
796 
797 	if (nbds_max > 1UL << (MINORBITS - part_shift))
798 		return -EINVAL;
799 
800 	nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
801 	if (!nbd_dev)
802 		return -ENOMEM;
803 
804 	for (i = 0; i < nbds_max; i++) {
805 		struct gendisk *disk = alloc_disk(1 << part_shift);
806 		if (!disk)
807 			goto out;
808 		nbd_dev[i].disk = disk;
809 		/*
810 		 * The new linux 2.5 block layer implementation requires
811 		 * every gendisk to have its very own request_queue struct.
812 		 * These structs are big so we dynamically allocate them.
813 		 */
814 		disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
815 		if (!disk->queue) {
816 			put_disk(disk);
817 			goto out;
818 		}
819 		/*
820 		 * Tell the block layer that we are not a rotational device
821 		 */
822 		queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
823 		queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
824 		disk->queue->limits.discard_granularity = 512;
825 		disk->queue->limits.max_discard_sectors = UINT_MAX;
826 		disk->queue->limits.discard_zeroes_data = 0;
827 		blk_queue_max_hw_sectors(disk->queue, 65536);
828 		disk->queue->limits.max_sectors = 256;
829 	}
830 
831 	if (register_blkdev(NBD_MAJOR, "nbd")) {
832 		err = -EIO;
833 		goto out;
834 	}
835 
836 	printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
837 
838 	for (i = 0; i < nbds_max; i++) {
839 		struct gendisk *disk = nbd_dev[i].disk;
840 		nbd_dev[i].magic = NBD_MAGIC;
841 		INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
842 		spin_lock_init(&nbd_dev[i].queue_lock);
843 		INIT_LIST_HEAD(&nbd_dev[i].queue_head);
844 		mutex_init(&nbd_dev[i].tx_lock);
845 		init_waitqueue_head(&nbd_dev[i].active_wq);
846 		init_waitqueue_head(&nbd_dev[i].waiting_wq);
847 		nbd_dev[i].blksize = 1024;
848 		nbd_dev[i].bytesize = 0;
849 		disk->major = NBD_MAJOR;
850 		disk->first_minor = i << part_shift;
851 		disk->fops = &nbd_fops;
852 		disk->private_data = &nbd_dev[i];
853 		sprintf(disk->disk_name, "nbd%d", i);
854 		set_capacity(disk, 0);
855 		add_disk(disk);
856 	}
857 
858 	return 0;
859 out:
860 	while (i--) {
861 		blk_cleanup_queue(nbd_dev[i].disk->queue);
862 		put_disk(nbd_dev[i].disk);
863 	}
864 	kfree(nbd_dev);
865 	return err;
866 }
867 
868 static void __exit nbd_cleanup(void)
869 {
870 	int i;
871 	for (i = 0; i < nbds_max; i++) {
872 		struct gendisk *disk = nbd_dev[i].disk;
873 		nbd_dev[i].magic = 0;
874 		if (disk) {
875 			del_gendisk(disk);
876 			blk_cleanup_queue(disk->queue);
877 			put_disk(disk);
878 		}
879 	}
880 	unregister_blkdev(NBD_MAJOR, "nbd");
881 	kfree(nbd_dev);
882 	printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
883 }
884 
885 module_init(nbd_init);
886 module_exit(nbd_cleanup);
887 
888 MODULE_DESCRIPTION("Network Block Device");
889 MODULE_LICENSE("GPL");
890 
891 module_param(nbds_max, int, 0444);
892 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
893 module_param(max_part, int, 0444);
894 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");
895