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