nbd: Remove fixme that was already fixed
[firefly-linux-kernel-4.4.55.git] / drivers / block / nbd.c
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
234         memset(&request, 0, sizeof(request));
235         request.magic = htonl(NBD_REQUEST_MAGIC);
236         request.type = htonl(nbd_cmd(req));
237
238         if (nbd_cmd(req) != NBD_CMD_FLUSH && nbd_cmd(req) != NBD_CMD_DISC) {
239                 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
240                 request.len = htonl(size);
241         }
242         memcpy(request.handle, &req, sizeof(req));
243
244         dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
245                 req, nbdcmd_to_ascii(nbd_cmd(req)),
246                 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
247         result = sock_xmit(nbd, 1, &request, sizeof(request),
248                         (nbd_cmd(req) == NBD_CMD_WRITE) ? MSG_MORE : 0);
249         if (result <= 0) {
250                 dev_err(disk_to_dev(nbd->disk),
251                         "Send control failed (result %d)\n", result);
252                 goto error_out;
253         }
254
255         if (nbd_cmd(req) == NBD_CMD_WRITE) {
256                 struct req_iterator iter;
257                 struct bio_vec bvec;
258                 /*
259                  * we are really probing at internals to determine
260                  * whether to set MSG_MORE or not...
261                  */
262                 rq_for_each_segment(bvec, req, iter) {
263                         flags = 0;
264                         if (!rq_iter_last(bvec, iter))
265                                 flags = MSG_MORE;
266                         dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
267                                 req, bvec.bv_len);
268                         result = sock_send_bvec(nbd, &bvec, flags);
269                         if (result <= 0) {
270                                 dev_err(disk_to_dev(nbd->disk),
271                                         "Send data failed (result %d)\n",
272                                         result);
273                                 goto error_out;
274                         }
275                 }
276         }
277         return 0;
278
279 error_out:
280         return -EIO;
281 }
282
283 static struct request *nbd_find_request(struct nbd_device *nbd,
284                                         struct request *xreq)
285 {
286         struct request *req, *tmp;
287         int err;
288
289         err = wait_event_interruptible(nbd->active_wq, nbd->active_req != xreq);
290         if (unlikely(err))
291                 goto out;
292
293         spin_lock(&nbd->queue_lock);
294         list_for_each_entry_safe(req, tmp, &nbd->queue_head, queuelist) {
295                 if (req != xreq)
296                         continue;
297                 list_del_init(&req->queuelist);
298                 spin_unlock(&nbd->queue_lock);
299                 return req;
300         }
301         spin_unlock(&nbd->queue_lock);
302
303         err = -ENOENT;
304
305 out:
306         return ERR_PTR(err);
307 }
308
309 static inline int sock_recv_bvec(struct nbd_device *nbd, struct bio_vec *bvec)
310 {
311         int result;
312         void *kaddr = kmap(bvec->bv_page);
313         result = sock_xmit(nbd, 0, kaddr + bvec->bv_offset, bvec->bv_len,
314                         MSG_WAITALL);
315         kunmap(bvec->bv_page);
316         return result;
317 }
318
319 /* NULL returned = something went wrong, inform userspace */
320 static struct request *nbd_read_stat(struct nbd_device *nbd)
321 {
322         int result;
323         struct nbd_reply reply;
324         struct request *req;
325
326         reply.magic = 0;
327         result = sock_xmit(nbd, 0, &reply, sizeof(reply), MSG_WAITALL);
328         if (result <= 0) {
329                 dev_err(disk_to_dev(nbd->disk),
330                         "Receive control failed (result %d)\n", result);
331                 goto harderror;
332         }
333
334         if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
335                 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
336                                 (unsigned long)ntohl(reply.magic));
337                 result = -EPROTO;
338                 goto harderror;
339         }
340
341         req = nbd_find_request(nbd, *(struct request **)reply.handle);
342         if (IS_ERR(req)) {
343                 result = PTR_ERR(req);
344                 if (result != -ENOENT)
345                         goto harderror;
346
347                 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%p)\n",
348                         reply.handle);
349                 result = -EBADR;
350                 goto harderror;
351         }
352
353         if (ntohl(reply.error)) {
354                 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
355                         ntohl(reply.error));
356                 req->errors++;
357                 return req;
358         }
359
360         dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", req);
361         if (nbd_cmd(req) == NBD_CMD_READ) {
362                 struct req_iterator iter;
363                 struct bio_vec bvec;
364
365                 rq_for_each_segment(bvec, req, iter) {
366                         result = sock_recv_bvec(nbd, &bvec);
367                         if (result <= 0) {
368                                 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
369                                         result);
370                                 req->errors++;
371                                 return req;
372                         }
373                         dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
374                                 req, bvec.bv_len);
375                 }
376         }
377         return req;
378 harderror:
379         nbd->harderror = result;
380         return NULL;
381 }
382
383 static ssize_t pid_show(struct device *dev,
384                         struct device_attribute *attr, char *buf)
385 {
386         struct gendisk *disk = dev_to_disk(dev);
387
388         return sprintf(buf, "%ld\n",
389                 (long) ((struct nbd_device *)disk->private_data)->pid);
390 }
391
392 static struct device_attribute pid_attr = {
393         .attr = { .name = "pid", .mode = S_IRUGO},
394         .show = pid_show,
395 };
396
397 static int nbd_do_it(struct nbd_device *nbd)
398 {
399         struct request *req;
400         int ret;
401
402         BUG_ON(nbd->magic != NBD_MAGIC);
403
404         sk_set_memalloc(nbd->sock->sk);
405         nbd->pid = task_pid_nr(current);
406         ret = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
407         if (ret) {
408                 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
409                 nbd->pid = 0;
410                 return ret;
411         }
412
413         while ((req = nbd_read_stat(nbd)) != NULL)
414                 nbd_end_request(nbd, req);
415
416         device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
417         nbd->pid = 0;
418         return 0;
419 }
420
421 static void nbd_clear_que(struct nbd_device *nbd)
422 {
423         struct request *req;
424
425         BUG_ON(nbd->magic != NBD_MAGIC);
426
427         /*
428          * Because we have set nbd->sock to NULL under the tx_lock, all
429          * modifications to the list must have completed by now.  For
430          * the same reason, the active_req must be NULL.
431          *
432          * As a consequence, we don't need to take the spin lock while
433          * purging the list here.
434          */
435         BUG_ON(nbd->sock);
436         BUG_ON(nbd->active_req);
437
438         while (!list_empty(&nbd->queue_head)) {
439                 req = list_entry(nbd->queue_head.next, struct request,
440                                  queuelist);
441                 list_del_init(&req->queuelist);
442                 req->errors++;
443                 nbd_end_request(nbd, req);
444         }
445
446         while (!list_empty(&nbd->waiting_queue)) {
447                 req = list_entry(nbd->waiting_queue.next, struct request,
448                                  queuelist);
449                 list_del_init(&req->queuelist);
450                 req->errors++;
451                 nbd_end_request(nbd, req);
452         }
453 }
454
455
456 static void nbd_handle_req(struct nbd_device *nbd, struct request *req)
457 {
458         if (req->cmd_type != REQ_TYPE_FS)
459                 goto error_out;
460
461         nbd_cmd(req) = NBD_CMD_READ;
462         if (rq_data_dir(req) == WRITE) {
463                 if ((req->cmd_flags & REQ_DISCARD)) {
464                         WARN_ON(!(nbd->flags & NBD_FLAG_SEND_TRIM));
465                         nbd_cmd(req) = NBD_CMD_TRIM;
466                 } else
467                         nbd_cmd(req) = NBD_CMD_WRITE;
468                 if (nbd->flags & NBD_FLAG_READ_ONLY) {
469                         dev_err(disk_to_dev(nbd->disk),
470                                 "Write on read-only\n");
471                         goto error_out;
472                 }
473         }
474
475         if (req->cmd_flags & REQ_FLUSH) {
476                 BUG_ON(unlikely(blk_rq_sectors(req)));
477                 nbd_cmd(req) = NBD_CMD_FLUSH;
478         }
479
480         req->errors = 0;
481
482         mutex_lock(&nbd->tx_lock);
483         if (unlikely(!nbd->sock)) {
484                 mutex_unlock(&nbd->tx_lock);
485                 dev_err(disk_to_dev(nbd->disk),
486                         "Attempted send on closed socket\n");
487                 goto error_out;
488         }
489
490         nbd->active_req = req;
491
492         if (nbd_send_req(nbd, req) != 0) {
493                 dev_err(disk_to_dev(nbd->disk), "Request send failed\n");
494                 req->errors++;
495                 nbd_end_request(nbd, req);
496         } else {
497                 spin_lock(&nbd->queue_lock);
498                 list_add_tail(&req->queuelist, &nbd->queue_head);
499                 spin_unlock(&nbd->queue_lock);
500         }
501
502         nbd->active_req = NULL;
503         mutex_unlock(&nbd->tx_lock);
504         wake_up_all(&nbd->active_wq);
505
506         return;
507
508 error_out:
509         req->errors++;
510         nbd_end_request(nbd, req);
511 }
512
513 static int nbd_thread(void *data)
514 {
515         struct nbd_device *nbd = data;
516         struct request *req;
517
518         set_user_nice(current, MIN_NICE);
519         while (!kthread_should_stop() || !list_empty(&nbd->waiting_queue)) {
520                 /* wait for something to do */
521                 wait_event_interruptible(nbd->waiting_wq,
522                                          kthread_should_stop() ||
523                                          !list_empty(&nbd->waiting_queue));
524
525                 /* extract request */
526                 if (list_empty(&nbd->waiting_queue))
527                         continue;
528
529                 spin_lock_irq(&nbd->queue_lock);
530                 req = list_entry(nbd->waiting_queue.next, struct request,
531                                  queuelist);
532                 list_del_init(&req->queuelist);
533                 spin_unlock_irq(&nbd->queue_lock);
534
535                 /* handle request */
536                 nbd_handle_req(nbd, req);
537         }
538         return 0;
539 }
540
541 /*
542  * We always wait for result of write, for now. It would be nice to make it optional
543  * in future
544  * if ((rq_data_dir(req) == WRITE) && (nbd->flags & NBD_WRITE_NOCHK))
545  *   { printk( "Warning: Ignoring result!\n"); nbd_end_request( req ); }
546  */
547
548 static void do_nbd_request(struct request_queue *q)
549                 __releases(q->queue_lock) __acquires(q->queue_lock)
550 {
551         struct request *req;
552         
553         while ((req = blk_fetch_request(q)) != NULL) {
554                 struct nbd_device *nbd;
555
556                 spin_unlock_irq(q->queue_lock);
557
558                 nbd = req->rq_disk->private_data;
559
560                 BUG_ON(nbd->magic != NBD_MAGIC);
561
562                 dev_dbg(nbd_to_dev(nbd), "request %p: dequeued (flags=%x)\n",
563                         req, req->cmd_type);
564
565                 if (unlikely(!nbd->sock)) {
566                         dev_err(disk_to_dev(nbd->disk),
567                                 "Attempted send on closed socket\n");
568                         req->errors++;
569                         nbd_end_request(nbd, req);
570                         spin_lock_irq(q->queue_lock);
571                         continue;
572                 }
573
574                 spin_lock_irq(&nbd->queue_lock);
575                 list_add_tail(&req->queuelist, &nbd->waiting_queue);
576                 spin_unlock_irq(&nbd->queue_lock);
577
578                 wake_up(&nbd->waiting_wq);
579
580                 spin_lock_irq(q->queue_lock);
581         }
582 }
583
584 /* Must be called with tx_lock held */
585
586 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
587                        unsigned int cmd, unsigned long arg)
588 {
589         switch (cmd) {
590         case NBD_DISCONNECT: {
591                 struct request sreq;
592
593                 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
594                 if (!nbd->sock)
595                         return -EINVAL;
596
597                 mutex_unlock(&nbd->tx_lock);
598                 fsync_bdev(bdev);
599                 mutex_lock(&nbd->tx_lock);
600                 blk_rq_init(NULL, &sreq);
601                 sreq.cmd_type = REQ_TYPE_SPECIAL;
602                 nbd_cmd(&sreq) = NBD_CMD_DISC;
603
604                 /* Check again after getting mutex back.  */
605                 if (!nbd->sock)
606                         return -EINVAL;
607
608                 nbd->disconnect = 1;
609
610                 nbd_send_req(nbd, &sreq);
611                 return 0;
612         }
613  
614         case NBD_CLEAR_SOCK: {
615                 struct socket *sock = nbd->sock;
616                 nbd->sock = NULL;
617                 nbd_clear_que(nbd);
618                 BUG_ON(!list_empty(&nbd->queue_head));
619                 BUG_ON(!list_empty(&nbd->waiting_queue));
620                 kill_bdev(bdev);
621                 if (sock)
622                         sockfd_put(sock);
623                 return 0;
624         }
625
626         case NBD_SET_SOCK: {
627                 struct socket *sock;
628                 int err;
629                 if (nbd->sock)
630                         return -EBUSY;
631                 sock = sockfd_lookup(arg, &err);
632                 if (sock) {
633                         nbd->sock = sock;
634                         if (max_part > 0)
635                                 bdev->bd_invalidated = 1;
636                         nbd->disconnect = 0; /* we're connected now */
637                         return 0;
638                 }
639                 return -EINVAL;
640         }
641
642         case NBD_SET_BLKSIZE:
643                 nbd->blksize = arg;
644                 nbd->bytesize &= ~(nbd->blksize-1);
645                 bdev->bd_inode->i_size = nbd->bytesize;
646                 set_blocksize(bdev, nbd->blksize);
647                 set_capacity(nbd->disk, nbd->bytesize >> 9);
648                 return 0;
649
650         case NBD_SET_SIZE:
651                 nbd->bytesize = arg & ~(nbd->blksize-1);
652                 bdev->bd_inode->i_size = nbd->bytesize;
653                 set_blocksize(bdev, nbd->blksize);
654                 set_capacity(nbd->disk, nbd->bytesize >> 9);
655                 return 0;
656
657         case NBD_SET_TIMEOUT:
658                 nbd->xmit_timeout = arg * HZ;
659                 return 0;
660
661         case NBD_SET_FLAGS:
662                 nbd->flags = arg;
663                 return 0;
664
665         case NBD_SET_SIZE_BLOCKS:
666                 nbd->bytesize = ((u64) arg) * nbd->blksize;
667                 bdev->bd_inode->i_size = nbd->bytesize;
668                 set_blocksize(bdev, nbd->blksize);
669                 set_capacity(nbd->disk, nbd->bytesize >> 9);
670                 return 0;
671
672         case NBD_DO_IT: {
673                 struct task_struct *thread;
674                 struct socket *sock;
675                 int error;
676
677                 if (nbd->pid)
678                         return -EBUSY;
679                 if (!nbd->sock)
680                         return -EINVAL;
681
682                 mutex_unlock(&nbd->tx_lock);
683
684                 if (nbd->flags & NBD_FLAG_READ_ONLY)
685                         set_device_ro(bdev, true);
686                 if (nbd->flags & NBD_FLAG_SEND_TRIM)
687                         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD,
688                                 nbd->disk->queue);
689                 if (nbd->flags & NBD_FLAG_SEND_FLUSH)
690                         blk_queue_flush(nbd->disk->queue, REQ_FLUSH);
691                 else
692                         blk_queue_flush(nbd->disk->queue, 0);
693
694                 thread = kthread_run(nbd_thread, nbd, "%s",
695                                      nbd->disk->disk_name);
696                 if (IS_ERR(thread)) {
697                         mutex_lock(&nbd->tx_lock);
698                         return PTR_ERR(thread);
699                 }
700
701                 error = nbd_do_it(nbd);
702                 kthread_stop(thread);
703
704                 mutex_lock(&nbd->tx_lock);
705                 if (error)
706                         return error;
707                 sock_shutdown(nbd, 0);
708                 sock = nbd->sock;
709                 nbd->sock = NULL;
710                 nbd_clear_que(nbd);
711                 dev_warn(disk_to_dev(nbd->disk), "queue cleared\n");
712                 kill_bdev(bdev);
713                 queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
714                 set_device_ro(bdev, false);
715                 if (sock)
716                         sockfd_put(sock);
717                 nbd->flags = 0;
718                 nbd->bytesize = 0;
719                 bdev->bd_inode->i_size = 0;
720                 set_capacity(nbd->disk, 0);
721                 if (max_part > 0)
722                         ioctl_by_bdev(bdev, BLKRRPART, 0);
723                 if (nbd->disconnect) /* user requested, ignore socket errors */
724                         return 0;
725                 return nbd->harderror;
726         }
727
728         case NBD_CLEAR_QUE:
729                 /*
730                  * This is for compatibility only.  The queue is always cleared
731                  * by NBD_DO_IT or NBD_CLEAR_SOCK.
732                  */
733                 return 0;
734
735         case NBD_PRINT_DEBUG:
736                 dev_info(disk_to_dev(nbd->disk),
737                         "next = %p, prev = %p, head = %p\n",
738                         nbd->queue_head.next, nbd->queue_head.prev,
739                         &nbd->queue_head);
740                 return 0;
741         }
742         return -ENOTTY;
743 }
744
745 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
746                      unsigned int cmd, unsigned long arg)
747 {
748         struct nbd_device *nbd = bdev->bd_disk->private_data;
749         int error;
750
751         if (!capable(CAP_SYS_ADMIN))
752                 return -EPERM;
753
754         BUG_ON(nbd->magic != NBD_MAGIC);
755
756         mutex_lock(&nbd->tx_lock);
757         error = __nbd_ioctl(bdev, nbd, cmd, arg);
758         mutex_unlock(&nbd->tx_lock);
759
760         return error;
761 }
762
763 static const struct block_device_operations nbd_fops =
764 {
765         .owner =        THIS_MODULE,
766         .ioctl =        nbd_ioctl,
767 };
768
769 /*
770  * And here should be modules and kernel interface 
771  *  (Just smiley confuses emacs :-)
772  */
773
774 static int __init nbd_init(void)
775 {
776         int err = -ENOMEM;
777         int i;
778         int part_shift;
779
780         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
781
782         if (max_part < 0) {
783                 printk(KERN_ERR "nbd: max_part must be >= 0\n");
784                 return -EINVAL;
785         }
786
787         part_shift = 0;
788         if (max_part > 0) {
789                 part_shift = fls(max_part);
790
791                 /*
792                  * Adjust max_part according to part_shift as it is exported
793                  * to user space so that user can know the max number of
794                  * partition kernel should be able to manage.
795                  *
796                  * Note that -1 is required because partition 0 is reserved
797                  * for the whole disk.
798                  */
799                 max_part = (1UL << part_shift) - 1;
800         }
801
802         if ((1UL << part_shift) > DISK_MAX_PARTS)
803                 return -EINVAL;
804
805         if (nbds_max > 1UL << (MINORBITS - part_shift))
806                 return -EINVAL;
807
808         nbd_dev = kcalloc(nbds_max, sizeof(*nbd_dev), GFP_KERNEL);
809         if (!nbd_dev)
810                 return -ENOMEM;
811
812         for (i = 0; i < nbds_max; i++) {
813                 struct gendisk *disk = alloc_disk(1 << part_shift);
814                 if (!disk)
815                         goto out;
816                 nbd_dev[i].disk = disk;
817                 /*
818                  * The new linux 2.5 block layer implementation requires
819                  * every gendisk to have its very own request_queue struct.
820                  * These structs are big so we dynamically allocate them.
821                  */
822                 disk->queue = blk_init_queue(do_nbd_request, &nbd_lock);
823                 if (!disk->queue) {
824                         put_disk(disk);
825                         goto out;
826                 }
827                 /*
828                  * Tell the block layer that we are not a rotational device
829                  */
830                 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
831                 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
832                 disk->queue->limits.discard_granularity = 512;
833                 disk->queue->limits.max_discard_sectors = UINT_MAX;
834                 disk->queue->limits.discard_zeroes_data = 0;
835                 blk_queue_max_hw_sectors(disk->queue, 65536);
836                 disk->queue->limits.max_sectors = 256;
837         }
838
839         if (register_blkdev(NBD_MAJOR, "nbd")) {
840                 err = -EIO;
841                 goto out;
842         }
843
844         printk(KERN_INFO "nbd: registered device at major %d\n", NBD_MAJOR);
845
846         for (i = 0; i < nbds_max; i++) {
847                 struct gendisk *disk = nbd_dev[i].disk;
848                 nbd_dev[i].magic = NBD_MAGIC;
849                 INIT_LIST_HEAD(&nbd_dev[i].waiting_queue);
850                 spin_lock_init(&nbd_dev[i].queue_lock);
851                 INIT_LIST_HEAD(&nbd_dev[i].queue_head);
852                 mutex_init(&nbd_dev[i].tx_lock);
853                 init_waitqueue_head(&nbd_dev[i].active_wq);
854                 init_waitqueue_head(&nbd_dev[i].waiting_wq);
855                 nbd_dev[i].blksize = 1024;
856                 nbd_dev[i].bytesize = 0;
857                 disk->major = NBD_MAJOR;
858                 disk->first_minor = i << part_shift;
859                 disk->fops = &nbd_fops;
860                 disk->private_data = &nbd_dev[i];
861                 sprintf(disk->disk_name, "nbd%d", i);
862                 set_capacity(disk, 0);
863                 add_disk(disk);
864         }
865
866         return 0;
867 out:
868         while (i--) {
869                 blk_cleanup_queue(nbd_dev[i].disk->queue);
870                 put_disk(nbd_dev[i].disk);
871         }
872         kfree(nbd_dev);
873         return err;
874 }
875
876 static void __exit nbd_cleanup(void)
877 {
878         int i;
879         for (i = 0; i < nbds_max; i++) {
880                 struct gendisk *disk = nbd_dev[i].disk;
881                 nbd_dev[i].magic = 0;
882                 if (disk) {
883                         del_gendisk(disk);
884                         blk_cleanup_queue(disk->queue);
885                         put_disk(disk);
886                 }
887         }
888         unregister_blkdev(NBD_MAJOR, "nbd");
889         kfree(nbd_dev);
890         printk(KERN_INFO "nbd: unregistered device at major %d\n", NBD_MAJOR);
891 }
892
893 module_init(nbd_init);
894 module_exit(nbd_cleanup);
895
896 MODULE_DESCRIPTION("Network Block Device");
897 MODULE_LICENSE("GPL");
898
899 module_param(nbds_max, int, 0444);
900 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
901 module_param(max_part, int, 0444);
902 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");