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