]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/block/nbd.c
978d2d2d08d6549b85f7233407cfd5d71d06acf6
[linux.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/sched/mm.h>
22 #include <linux/fs.h>
23 #include <linux/bio.h>
24 #include <linux/stat.h>
25 #include <linux/errno.h>
26 #include <linux/file.h>
27 #include <linux/ioctl.h>
28 #include <linux/mutex.h>
29 #include <linux/compiler.h>
30 #include <linux/err.h>
31 #include <linux/kernel.h>
32 #include <linux/slab.h>
33 #include <net/sock.h>
34 #include <linux/net.h>
35 #include <linux/kthread.h>
36 #include <linux/types.h>
37 #include <linux/debugfs.h>
38 #include <linux/blk-mq.h>
39
40 #include <linux/uaccess.h>
41 #include <asm/types.h>
42
43 #include <linux/nbd.h>
44 #include <linux/nbd-netlink.h>
45 #include <net/genetlink.h>
46
47 static DEFINE_IDR(nbd_index_idr);
48 static DEFINE_MUTEX(nbd_index_mutex);
49 static int nbd_total_devices = 0;
50
51 struct nbd_sock {
52         struct socket *sock;
53         struct mutex tx_lock;
54         struct request *pending;
55         int sent;
56         bool dead;
57         int fallback_index;
58         int cookie;
59 };
60
61 struct recv_thread_args {
62         struct work_struct work;
63         struct nbd_device *nbd;
64         int index;
65 };
66
67 struct link_dead_args {
68         struct work_struct work;
69         int index;
70 };
71
72 #define NBD_TIMEDOUT                    0
73 #define NBD_DISCONNECT_REQUESTED        1
74 #define NBD_DISCONNECTED                2
75 #define NBD_HAS_PID_FILE                3
76 #define NBD_HAS_CONFIG_REF              4
77 #define NBD_BOUND                       5
78 #define NBD_DESTROY_ON_DISCONNECT       6
79
80 struct nbd_config {
81         u32 flags;
82         unsigned long runtime_flags;
83         u64 dead_conn_timeout;
84
85         struct nbd_sock **socks;
86         int num_connections;
87         atomic_t live_connections;
88         wait_queue_head_t conn_wait;
89
90         atomic_t recv_threads;
91         wait_queue_head_t recv_wq;
92         loff_t blksize;
93         loff_t bytesize;
94 #if IS_ENABLED(CONFIG_DEBUG_FS)
95         struct dentry *dbg_dir;
96 #endif
97 };
98
99 struct nbd_device {
100         struct blk_mq_tag_set tag_set;
101
102         int index;
103         refcount_t config_refs;
104         refcount_t refs;
105         struct nbd_config *config;
106         struct mutex config_lock;
107         struct gendisk *disk;
108
109         struct list_head list;
110         struct task_struct *task_recv;
111         struct task_struct *task_setup;
112 };
113
114 struct nbd_cmd {
115         struct nbd_device *nbd;
116         int index;
117         int cookie;
118         struct completion send_complete;
119         blk_status_t status;
120 };
121
122 #if IS_ENABLED(CONFIG_DEBUG_FS)
123 static struct dentry *nbd_dbg_dir;
124 #endif
125
126 #define nbd_name(nbd) ((nbd)->disk->disk_name)
127
128 #define NBD_MAGIC 0x68797548
129
130 static unsigned int nbds_max = 16;
131 static int max_part;
132 static struct workqueue_struct *recv_workqueue;
133 static int part_shift;
134
135 static int nbd_dev_dbg_init(struct nbd_device *nbd);
136 static void nbd_dev_dbg_close(struct nbd_device *nbd);
137 static void nbd_config_put(struct nbd_device *nbd);
138 static void nbd_connect_reply(struct genl_info *info, int index);
139 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
140 static void nbd_dead_link_work(struct work_struct *work);
141
142 static inline struct device *nbd_to_dev(struct nbd_device *nbd)
143 {
144         return disk_to_dev(nbd->disk);
145 }
146
147 static const char *nbdcmd_to_ascii(int cmd)
148 {
149         switch (cmd) {
150         case  NBD_CMD_READ: return "read";
151         case NBD_CMD_WRITE: return "write";
152         case  NBD_CMD_DISC: return "disconnect";
153         case NBD_CMD_FLUSH: return "flush";
154         case  NBD_CMD_TRIM: return "trim/discard";
155         }
156         return "invalid";
157 }
158
159 static ssize_t pid_show(struct device *dev,
160                         struct device_attribute *attr, char *buf)
161 {
162         struct gendisk *disk = dev_to_disk(dev);
163         struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
164
165         return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
166 }
167
168 static struct device_attribute pid_attr = {
169         .attr = { .name = "pid", .mode = S_IRUGO},
170         .show = pid_show,
171 };
172
173 static void nbd_dev_remove(struct nbd_device *nbd)
174 {
175         struct gendisk *disk = nbd->disk;
176         if (disk) {
177                 del_gendisk(disk);
178                 blk_cleanup_queue(disk->queue);
179                 blk_mq_free_tag_set(&nbd->tag_set);
180                 disk->private_data = NULL;
181                 put_disk(disk);
182         }
183         kfree(nbd);
184 }
185
186 static void nbd_put(struct nbd_device *nbd)
187 {
188         if (refcount_dec_and_mutex_lock(&nbd->refs,
189                                         &nbd_index_mutex)) {
190                 idr_remove(&nbd_index_idr, nbd->index);
191                 mutex_unlock(&nbd_index_mutex);
192                 nbd_dev_remove(nbd);
193         }
194 }
195
196 static int nbd_disconnected(struct nbd_config *config)
197 {
198         return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
199                 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
200 }
201
202 static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
203                                 int notify)
204 {
205         if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
206                 struct link_dead_args *args;
207                 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
208                 if (args) {
209                         INIT_WORK(&args->work, nbd_dead_link_work);
210                         args->index = nbd->index;
211                         queue_work(system_wq, &args->work);
212                 }
213         }
214         if (!nsock->dead) {
215                 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
216                 atomic_dec(&nbd->config->live_connections);
217         }
218         nsock->dead = true;
219         nsock->pending = NULL;
220         nsock->sent = 0;
221 }
222
223 static void nbd_size_clear(struct nbd_device *nbd)
224 {
225         if (nbd->config->bytesize) {
226                 set_capacity(nbd->disk, 0);
227                 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
228         }
229 }
230
231 static void nbd_size_update(struct nbd_device *nbd)
232 {
233         struct nbd_config *config = nbd->config;
234         blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
235         blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
236         set_capacity(nbd->disk, config->bytesize >> 9);
237         kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
238 }
239
240 static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
241                          loff_t nr_blocks)
242 {
243         struct nbd_config *config = nbd->config;
244         config->blksize = blocksize;
245         config->bytesize = blocksize * nr_blocks;
246         nbd_size_update(nbd);
247 }
248
249 static void nbd_complete_rq(struct request *req)
250 {
251         struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
252
253         dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", cmd,
254                 cmd->status ? "failed" : "done");
255
256         blk_mq_end_request(req, cmd->status);
257 }
258
259 /*
260  * Forcibly shutdown the socket causing all listeners to error
261  */
262 static void sock_shutdown(struct nbd_device *nbd)
263 {
264         struct nbd_config *config = nbd->config;
265         int i;
266
267         if (config->num_connections == 0)
268                 return;
269         if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
270                 return;
271
272         for (i = 0; i < config->num_connections; i++) {
273                 struct nbd_sock *nsock = config->socks[i];
274                 mutex_lock(&nsock->tx_lock);
275                 nbd_mark_nsock_dead(nbd, nsock, 0);
276                 mutex_unlock(&nsock->tx_lock);
277         }
278         dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
279 }
280
281 static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
282                                                  bool reserved)
283 {
284         struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
285         struct nbd_device *nbd = cmd->nbd;
286         struct nbd_config *config;
287
288         if (!refcount_inc_not_zero(&nbd->config_refs)) {
289                 cmd->status = BLK_STS_TIMEOUT;
290                 return BLK_EH_HANDLED;
291         }
292
293         /* If we are waiting on our dead timer then we could get timeout
294          * callbacks for our request.  For this we just want to reset the timer
295          * and let the queue side take care of everything.
296          */
297         if (!completion_done(&cmd->send_complete)) {
298                 nbd_config_put(nbd);
299                 return BLK_EH_RESET_TIMER;
300         }
301         config = nbd->config;
302
303         if (config->num_connections > 1) {
304                 dev_err_ratelimited(nbd_to_dev(nbd),
305                                     "Connection timed out, retrying\n");
306                 /*
307                  * Hooray we have more connections, requeue this IO, the submit
308                  * path will put it on a real connection.
309                  */
310                 if (config->socks && config->num_connections > 1) {
311                         if (cmd->index < config->num_connections) {
312                                 struct nbd_sock *nsock =
313                                         config->socks[cmd->index];
314                                 mutex_lock(&nsock->tx_lock);
315                                 /* We can have multiple outstanding requests, so
316                                  * we don't want to mark the nsock dead if we've
317                                  * already reconnected with a new socket, so
318                                  * only mark it dead if its the same socket we
319                                  * were sent out on.
320                                  */
321                                 if (cmd->cookie == nsock->cookie)
322                                         nbd_mark_nsock_dead(nbd, nsock, 1);
323                                 mutex_unlock(&nsock->tx_lock);
324                         }
325                         blk_mq_requeue_request(req, true);
326                         nbd_config_put(nbd);
327                         return BLK_EH_NOT_HANDLED;
328                 }
329         } else {
330                 dev_err_ratelimited(nbd_to_dev(nbd),
331                                     "Connection timed out\n");
332         }
333         set_bit(NBD_TIMEDOUT, &config->runtime_flags);
334         cmd->status = BLK_STS_IOERR;
335         sock_shutdown(nbd);
336         nbd_config_put(nbd);
337
338         return BLK_EH_HANDLED;
339 }
340
341 /*
342  *  Send or receive packet.
343  */
344 static int sock_xmit(struct nbd_device *nbd, int index, int send,
345                      struct iov_iter *iter, int msg_flags, int *sent)
346 {
347         struct nbd_config *config = nbd->config;
348         struct socket *sock = config->socks[index]->sock;
349         int result;
350         struct msghdr msg;
351         unsigned int noreclaim_flag;
352
353         if (unlikely(!sock)) {
354                 dev_err_ratelimited(disk_to_dev(nbd->disk),
355                         "Attempted %s on closed socket in sock_xmit\n",
356                         (send ? "send" : "recv"));
357                 return -EINVAL;
358         }
359
360         msg.msg_iter = *iter;
361
362         noreclaim_flag = memalloc_noreclaim_save();
363         do {
364                 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
365                 msg.msg_name = NULL;
366                 msg.msg_namelen = 0;
367                 msg.msg_control = NULL;
368                 msg.msg_controllen = 0;
369                 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
370
371                 if (send)
372                         result = sock_sendmsg(sock, &msg);
373                 else
374                         result = sock_recvmsg(sock, &msg, msg.msg_flags);
375
376                 if (result <= 0) {
377                         if (result == 0)
378                                 result = -EPIPE; /* short read */
379                         break;
380                 }
381                 if (sent)
382                         *sent += result;
383         } while (msg_data_left(&msg));
384
385         memalloc_noreclaim_restore(noreclaim_flag);
386
387         return result;
388 }
389
390 /* always call with the tx_lock held */
391 static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
392 {
393         struct request *req = blk_mq_rq_from_pdu(cmd);
394         struct nbd_config *config = nbd->config;
395         struct nbd_sock *nsock = config->socks[index];
396         int result;
397         struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
398         struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
399         struct iov_iter from;
400         unsigned long size = blk_rq_bytes(req);
401         struct bio *bio;
402         u32 type;
403         u32 nbd_cmd_flags = 0;
404         u32 tag = blk_mq_unique_tag(req);
405         int sent = nsock->sent, skip = 0;
406
407         iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
408
409         switch (req_op(req)) {
410         case REQ_OP_DISCARD:
411                 type = NBD_CMD_TRIM;
412                 break;
413         case REQ_OP_FLUSH:
414                 type = NBD_CMD_FLUSH;
415                 break;
416         case REQ_OP_WRITE:
417                 type = NBD_CMD_WRITE;
418                 break;
419         case REQ_OP_READ:
420                 type = NBD_CMD_READ;
421                 break;
422         default:
423                 return -EIO;
424         }
425
426         if (rq_data_dir(req) == WRITE &&
427             (config->flags & NBD_FLAG_READ_ONLY)) {
428                 dev_err_ratelimited(disk_to_dev(nbd->disk),
429                                     "Write on read-only\n");
430                 return -EIO;
431         }
432
433         if (req->cmd_flags & REQ_FUA)
434                 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
435
436         /* We did a partial send previously, and we at least sent the whole
437          * request struct, so just go and send the rest of the pages in the
438          * request.
439          */
440         if (sent) {
441                 if (sent >= sizeof(request)) {
442                         skip = sent - sizeof(request);
443                         goto send_pages;
444                 }
445                 iov_iter_advance(&from, sent);
446         }
447         cmd->index = index;
448         cmd->cookie = nsock->cookie;
449         request.type = htonl(type | nbd_cmd_flags);
450         if (type != NBD_CMD_FLUSH) {
451                 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
452                 request.len = htonl(size);
453         }
454         memcpy(request.handle, &tag, sizeof(tag));
455
456         dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
457                 cmd, nbdcmd_to_ascii(type),
458                 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
459         result = sock_xmit(nbd, index, 1, &from,
460                         (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
461         if (result <= 0) {
462                 if (result == -ERESTARTSYS) {
463                         /* If we havne't sent anything we can just return BUSY,
464                          * however if we have sent something we need to make
465                          * sure we only allow this req to be sent until we are
466                          * completely done.
467                          */
468                         if (sent) {
469                                 nsock->pending = req;
470                                 nsock->sent = sent;
471                         }
472                         return BLK_MQ_RQ_QUEUE_BUSY;
473                 }
474                 dev_err_ratelimited(disk_to_dev(nbd->disk),
475                         "Send control failed (result %d)\n", result);
476                 return -EAGAIN;
477         }
478 send_pages:
479         if (type != NBD_CMD_WRITE)
480                 goto out;
481
482         bio = req->bio;
483         while (bio) {
484                 struct bio *next = bio->bi_next;
485                 struct bvec_iter iter;
486                 struct bio_vec bvec;
487
488                 bio_for_each_segment(bvec, bio, iter) {
489                         bool is_last = !next && bio_iter_last(bvec, iter);
490                         int flags = is_last ? 0 : MSG_MORE;
491
492                         dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
493                                 cmd, bvec.bv_len);
494                         iov_iter_bvec(&from, ITER_BVEC | WRITE,
495                                       &bvec, 1, bvec.bv_len);
496                         if (skip) {
497                                 if (skip >= iov_iter_count(&from)) {
498                                         skip -= iov_iter_count(&from);
499                                         continue;
500                                 }
501                                 iov_iter_advance(&from, skip);
502                                 skip = 0;
503                         }
504                         result = sock_xmit(nbd, index, 1, &from, flags, &sent);
505                         if (result <= 0) {
506                                 if (result == -ERESTARTSYS) {
507                                         /* We've already sent the header, we
508                                          * have no choice but to set pending and
509                                          * return BUSY.
510                                          */
511                                         nsock->pending = req;
512                                         nsock->sent = sent;
513                                         return BLK_MQ_RQ_QUEUE_BUSY;
514                                 }
515                                 dev_err(disk_to_dev(nbd->disk),
516                                         "Send data failed (result %d)\n",
517                                         result);
518                                 return -EAGAIN;
519                         }
520                         /*
521                          * The completion might already have come in,
522                          * so break for the last one instead of letting
523                          * the iterator do it. This prevents use-after-free
524                          * of the bio.
525                          */
526                         if (is_last)
527                                 break;
528                 }
529                 bio = next;
530         }
531 out:
532         nsock->pending = NULL;
533         nsock->sent = 0;
534         return 0;
535 }
536
537 /* NULL returned = something went wrong, inform userspace */
538 static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
539 {
540         struct nbd_config *config = nbd->config;
541         int result;
542         struct nbd_reply reply;
543         struct nbd_cmd *cmd;
544         struct request *req = NULL;
545         u16 hwq;
546         u32 tag;
547         struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
548         struct iov_iter to;
549
550         reply.magic = 0;
551         iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
552         result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
553         if (result <= 0) {
554                 if (!nbd_disconnected(config))
555                         dev_err(disk_to_dev(nbd->disk),
556                                 "Receive control failed (result %d)\n", result);
557                 return ERR_PTR(result);
558         }
559
560         if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
561                 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
562                                 (unsigned long)ntohl(reply.magic));
563                 return ERR_PTR(-EPROTO);
564         }
565
566         memcpy(&tag, reply.handle, sizeof(u32));
567
568         hwq = blk_mq_unique_tag_to_hwq(tag);
569         if (hwq < nbd->tag_set.nr_hw_queues)
570                 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
571                                        blk_mq_unique_tag_to_tag(tag));
572         if (!req || !blk_mq_request_started(req)) {
573                 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
574                         tag, req);
575                 return ERR_PTR(-ENOENT);
576         }
577         cmd = blk_mq_rq_to_pdu(req);
578         if (ntohl(reply.error)) {
579                 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
580                         ntohl(reply.error));
581                 cmd->status = BLK_STS_IOERR;
582                 return cmd;
583         }
584
585         dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", cmd);
586         if (rq_data_dir(req) != WRITE) {
587                 struct req_iterator iter;
588                 struct bio_vec bvec;
589
590                 rq_for_each_segment(bvec, req, iter) {
591                         iov_iter_bvec(&to, ITER_BVEC | READ,
592                                       &bvec, 1, bvec.bv_len);
593                         result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
594                         if (result <= 0) {
595                                 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
596                                         result);
597                                 /*
598                                  * If we've disconnected or we only have 1
599                                  * connection then we need to make sure we
600                                  * complete this request, otherwise error out
601                                  * and let the timeout stuff handle resubmitting
602                                  * this request onto another connection.
603                                  */
604                                 if (nbd_disconnected(config) ||
605                                     config->num_connections <= 1) {
606                                         cmd->status = BLK_STS_IOERR;
607                                         return cmd;
608                                 }
609                                 return ERR_PTR(-EIO);
610                         }
611                         dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
612                                 cmd, bvec.bv_len);
613                 }
614         } else {
615                 /* See the comment in nbd_queue_rq. */
616                 wait_for_completion(&cmd->send_complete);
617         }
618         return cmd;
619 }
620
621 static void recv_work(struct work_struct *work)
622 {
623         struct recv_thread_args *args = container_of(work,
624                                                      struct recv_thread_args,
625                                                      work);
626         struct nbd_device *nbd = args->nbd;
627         struct nbd_config *config = nbd->config;
628         struct nbd_cmd *cmd;
629         int ret = 0;
630
631         while (1) {
632                 cmd = nbd_read_stat(nbd, args->index);
633                 if (IS_ERR(cmd)) {
634                         struct nbd_sock *nsock = config->socks[args->index];
635
636                         mutex_lock(&nsock->tx_lock);
637                         nbd_mark_nsock_dead(nbd, nsock, 1);
638                         mutex_unlock(&nsock->tx_lock);
639                         ret = PTR_ERR(cmd);
640                         break;
641                 }
642
643                 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
644         }
645         atomic_dec(&config->recv_threads);
646         wake_up(&config->recv_wq);
647         nbd_config_put(nbd);
648         kfree(args);
649 }
650
651 static void nbd_clear_req(struct request *req, void *data, bool reserved)
652 {
653         struct nbd_cmd *cmd;
654
655         if (!blk_mq_request_started(req))
656                 return;
657         cmd = blk_mq_rq_to_pdu(req);
658         cmd->status = BLK_STS_IOERR;
659         blk_mq_complete_request(req);
660 }
661
662 static void nbd_clear_que(struct nbd_device *nbd)
663 {
664         blk_mq_stop_hw_queues(nbd->disk->queue);
665         blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
666         blk_mq_start_hw_queues(nbd->disk->queue);
667         dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
668 }
669
670 static int find_fallback(struct nbd_device *nbd, int index)
671 {
672         struct nbd_config *config = nbd->config;
673         int new_index = -1;
674         struct nbd_sock *nsock = config->socks[index];
675         int fallback = nsock->fallback_index;
676
677         if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
678                 return new_index;
679
680         if (config->num_connections <= 1) {
681                 dev_err_ratelimited(disk_to_dev(nbd->disk),
682                                     "Attempted send on invalid socket\n");
683                 return new_index;
684         }
685
686         if (fallback >= 0 && fallback < config->num_connections &&
687             !config->socks[fallback]->dead)
688                 return fallback;
689
690         if (nsock->fallback_index < 0 ||
691             nsock->fallback_index >= config->num_connections ||
692             config->socks[nsock->fallback_index]->dead) {
693                 int i;
694                 for (i = 0; i < config->num_connections; i++) {
695                         if (i == index)
696                                 continue;
697                         if (!config->socks[i]->dead) {
698                                 new_index = i;
699                                 break;
700                         }
701                 }
702                 nsock->fallback_index = new_index;
703                 if (new_index < 0) {
704                         dev_err_ratelimited(disk_to_dev(nbd->disk),
705                                             "Dead connection, failed to find a fallback\n");
706                         return new_index;
707                 }
708         }
709         new_index = nsock->fallback_index;
710         return new_index;
711 }
712
713 static int wait_for_reconnect(struct nbd_device *nbd)
714 {
715         struct nbd_config *config = nbd->config;
716         if (!config->dead_conn_timeout)
717                 return 0;
718         if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
719                 return 0;
720         wait_event_interruptible_timeout(config->conn_wait,
721                                          atomic_read(&config->live_connections),
722                                          config->dead_conn_timeout);
723         return atomic_read(&config->live_connections);
724 }
725
726 static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
727 {
728         struct request *req = blk_mq_rq_from_pdu(cmd);
729         struct nbd_device *nbd = cmd->nbd;
730         struct nbd_config *config;
731         struct nbd_sock *nsock;
732         int ret;
733
734         if (!refcount_inc_not_zero(&nbd->config_refs)) {
735                 dev_err_ratelimited(disk_to_dev(nbd->disk),
736                                     "Socks array is empty\n");
737                 return -EINVAL;
738         }
739         config = nbd->config;
740
741         if (index >= config->num_connections) {
742                 dev_err_ratelimited(disk_to_dev(nbd->disk),
743                                     "Attempted send on invalid socket\n");
744                 nbd_config_put(nbd);
745                 return -EINVAL;
746         }
747         cmd->status = BLK_STS_OK;
748 again:
749         nsock = config->socks[index];
750         mutex_lock(&nsock->tx_lock);
751         if (nsock->dead) {
752                 int old_index = index;
753                 index = find_fallback(nbd, index);
754                 mutex_unlock(&nsock->tx_lock);
755                 if (index < 0) {
756                         if (wait_for_reconnect(nbd)) {
757                                 index = old_index;
758                                 goto again;
759                         }
760                         /* All the sockets should already be down at this point,
761                          * we just want to make sure that DISCONNECTED is set so
762                          * any requests that come in that were queue'ed waiting
763                          * for the reconnect timer don't trigger the timer again
764                          * and instead just error out.
765                          */
766                         sock_shutdown(nbd);
767                         nbd_config_put(nbd);
768                         return -EIO;
769                 }
770                 goto again;
771         }
772
773         /* Handle the case that we have a pending request that was partially
774          * transmitted that _has_ to be serviced first.  We need to call requeue
775          * here so that it gets put _after_ the request that is already on the
776          * dispatch list.
777          */
778         if (unlikely(nsock->pending && nsock->pending != req)) {
779                 blk_mq_requeue_request(req, true);
780                 ret = 0;
781                 goto out;
782         }
783         /*
784          * Some failures are related to the link going down, so anything that
785          * returns EAGAIN can be retried on a different socket.
786          */
787         ret = nbd_send_cmd(nbd, cmd, index);
788         if (ret == -EAGAIN) {
789                 dev_err_ratelimited(disk_to_dev(nbd->disk),
790                                     "Request send failed trying another connection\n");
791                 nbd_mark_nsock_dead(nbd, nsock, 1);
792                 mutex_unlock(&nsock->tx_lock);
793                 goto again;
794         }
795 out:
796         mutex_unlock(&nsock->tx_lock);
797         nbd_config_put(nbd);
798         return ret;
799 }
800
801 static int nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
802                         const struct blk_mq_queue_data *bd)
803 {
804         struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
805         int ret;
806
807         /*
808          * Since we look at the bio's to send the request over the network we
809          * need to make sure the completion work doesn't mark this request done
810          * before we are done doing our send.  This keeps us from dereferencing
811          * freed data if we have particularly fast completions (ie we get the
812          * completion before we exit sock_xmit on the last bvec) or in the case
813          * that the server is misbehaving (or there was an error) before we're
814          * done sending everything over the wire.
815          */
816         init_completion(&cmd->send_complete);
817         blk_mq_start_request(bd->rq);
818
819         /* We can be called directly from the user space process, which means we
820          * could possibly have signals pending so our sendmsg will fail.  In
821          * this case we need to return that we are busy, otherwise error out as
822          * appropriate.
823          */
824         ret = nbd_handle_cmd(cmd, hctx->queue_num);
825         if (ret < 0)
826                 ret = BLK_MQ_RQ_QUEUE_ERROR;
827         if (!ret)
828                 ret = BLK_MQ_RQ_QUEUE_OK;
829         complete(&cmd->send_complete);
830
831         return ret;
832 }
833
834 static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
835                           bool netlink)
836 {
837         struct nbd_config *config = nbd->config;
838         struct socket *sock;
839         struct nbd_sock **socks;
840         struct nbd_sock *nsock;
841         int err;
842
843         sock = sockfd_lookup(arg, &err);
844         if (!sock)
845                 return err;
846
847         if (!netlink && !nbd->task_setup &&
848             !test_bit(NBD_BOUND, &config->runtime_flags))
849                 nbd->task_setup = current;
850
851         if (!netlink &&
852             (nbd->task_setup != current ||
853              test_bit(NBD_BOUND, &config->runtime_flags))) {
854                 dev_err(disk_to_dev(nbd->disk),
855                         "Device being setup by another task");
856                 sockfd_put(sock);
857                 return -EBUSY;
858         }
859
860         socks = krealloc(config->socks, (config->num_connections + 1) *
861                          sizeof(struct nbd_sock *), GFP_KERNEL);
862         if (!socks) {
863                 sockfd_put(sock);
864                 return -ENOMEM;
865         }
866         nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
867         if (!nsock) {
868                 sockfd_put(sock);
869                 return -ENOMEM;
870         }
871
872         config->socks = socks;
873
874         nsock->fallback_index = -1;
875         nsock->dead = false;
876         mutex_init(&nsock->tx_lock);
877         nsock->sock = sock;
878         nsock->pending = NULL;
879         nsock->sent = 0;
880         nsock->cookie = 0;
881         socks[config->num_connections++] = nsock;
882         atomic_inc(&config->live_connections);
883
884         return 0;
885 }
886
887 static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
888 {
889         struct nbd_config *config = nbd->config;
890         struct socket *sock, *old;
891         struct recv_thread_args *args;
892         int i;
893         int err;
894
895         sock = sockfd_lookup(arg, &err);
896         if (!sock)
897                 return err;
898
899         args = kzalloc(sizeof(*args), GFP_KERNEL);
900         if (!args) {
901                 sockfd_put(sock);
902                 return -ENOMEM;
903         }
904
905         for (i = 0; i < config->num_connections; i++) {
906                 struct nbd_sock *nsock = config->socks[i];
907
908                 if (!nsock->dead)
909                         continue;
910
911                 mutex_lock(&nsock->tx_lock);
912                 if (!nsock->dead) {
913                         mutex_unlock(&nsock->tx_lock);
914                         continue;
915                 }
916                 sk_set_memalloc(sock->sk);
917                 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
918                 atomic_inc(&config->recv_threads);
919                 refcount_inc(&nbd->config_refs);
920                 old = nsock->sock;
921                 nsock->fallback_index = -1;
922                 nsock->sock = sock;
923                 nsock->dead = false;
924                 INIT_WORK(&args->work, recv_work);
925                 args->index = i;
926                 args->nbd = nbd;
927                 nsock->cookie++;
928                 mutex_unlock(&nsock->tx_lock);
929                 sockfd_put(old);
930
931                 /* We take the tx_mutex in an error path in the recv_work, so we
932                  * need to queue_work outside of the tx_mutex.
933                  */
934                 queue_work(recv_workqueue, &args->work);
935
936                 atomic_inc(&config->live_connections);
937                 wake_up(&config->conn_wait);
938                 return 0;
939         }
940         sockfd_put(sock);
941         kfree(args);
942         return -ENOSPC;
943 }
944
945 /* Reset all properties of an NBD device */
946 static void nbd_reset(struct nbd_device *nbd)
947 {
948         nbd->config = NULL;
949         nbd->tag_set.timeout = 0;
950         queue_flag_clear_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
951 }
952
953 static void nbd_bdev_reset(struct block_device *bdev)
954 {
955         if (bdev->bd_openers > 1)
956                 return;
957         bd_set_size(bdev, 0);
958         if (max_part > 0) {
959                 blkdev_reread_part(bdev);
960                 bdev->bd_invalidated = 1;
961         }
962 }
963
964 static void nbd_parse_flags(struct nbd_device *nbd)
965 {
966         struct nbd_config *config = nbd->config;
967         if (config->flags & NBD_FLAG_READ_ONLY)
968                 set_disk_ro(nbd->disk, true);
969         else
970                 set_disk_ro(nbd->disk, false);
971         if (config->flags & NBD_FLAG_SEND_TRIM)
972                 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, nbd->disk->queue);
973         if (config->flags & NBD_FLAG_SEND_FLUSH) {
974                 if (config->flags & NBD_FLAG_SEND_FUA)
975                         blk_queue_write_cache(nbd->disk->queue, true, true);
976                 else
977                         blk_queue_write_cache(nbd->disk->queue, true, false);
978         }
979         else
980                 blk_queue_write_cache(nbd->disk->queue, false, false);
981 }
982
983 static void send_disconnects(struct nbd_device *nbd)
984 {
985         struct nbd_config *config = nbd->config;
986         struct nbd_request request = {
987                 .magic = htonl(NBD_REQUEST_MAGIC),
988                 .type = htonl(NBD_CMD_DISC),
989         };
990         struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
991         struct iov_iter from;
992         int i, ret;
993
994         for (i = 0; i < config->num_connections; i++) {
995                 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
996                 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
997                 if (ret <= 0)
998                         dev_err(disk_to_dev(nbd->disk),
999                                 "Send disconnect failed %d\n", ret);
1000         }
1001 }
1002
1003 static int nbd_disconnect(struct nbd_device *nbd)
1004 {
1005         struct nbd_config *config = nbd->config;
1006
1007         dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
1008         if (!test_and_set_bit(NBD_DISCONNECT_REQUESTED,
1009                               &config->runtime_flags))
1010                 send_disconnects(nbd);
1011         return 0;
1012 }
1013
1014 static void nbd_clear_sock(struct nbd_device *nbd)
1015 {
1016         sock_shutdown(nbd);
1017         nbd_clear_que(nbd);
1018         nbd->task_setup = NULL;
1019 }
1020
1021 static void nbd_config_put(struct nbd_device *nbd)
1022 {
1023         if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1024                                         &nbd->config_lock)) {
1025                 struct nbd_config *config = nbd->config;
1026                 nbd_dev_dbg_close(nbd);
1027                 nbd_size_clear(nbd);
1028                 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1029                                        &config->runtime_flags))
1030                         device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1031                 nbd->task_recv = NULL;
1032                 nbd_clear_sock(nbd);
1033                 if (config->num_connections) {
1034                         int i;
1035                         for (i = 0; i < config->num_connections; i++) {
1036                                 sockfd_put(config->socks[i]->sock);
1037                                 kfree(config->socks[i]);
1038                         }
1039                         kfree(config->socks);
1040                 }
1041                 nbd_reset(nbd);
1042
1043                 mutex_unlock(&nbd->config_lock);
1044                 nbd_put(nbd);
1045                 module_put(THIS_MODULE);
1046         }
1047 }
1048
1049 static int nbd_start_device(struct nbd_device *nbd)
1050 {
1051         struct nbd_config *config = nbd->config;
1052         int num_connections = config->num_connections;
1053         int error = 0, i;
1054
1055         if (nbd->task_recv)
1056                 return -EBUSY;
1057         if (!config->socks)
1058                 return -EINVAL;
1059         if (num_connections > 1 &&
1060             !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
1061                 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
1062                 return -EINVAL;
1063         }
1064
1065         blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
1066         nbd->task_recv = current;
1067
1068         nbd_parse_flags(nbd);
1069
1070         error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1071         if (error) {
1072                 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
1073                 return error;
1074         }
1075         set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
1076
1077         nbd_dev_dbg_init(nbd);
1078         for (i = 0; i < num_connections; i++) {
1079                 struct recv_thread_args *args;
1080
1081                 args = kzalloc(sizeof(*args), GFP_KERNEL);
1082                 if (!args) {
1083                         sock_shutdown(nbd);
1084                         return -ENOMEM;
1085                 }
1086                 sk_set_memalloc(config->socks[i]->sock->sk);
1087                 config->socks[i]->sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
1088                 atomic_inc(&config->recv_threads);
1089                 refcount_inc(&nbd->config_refs);
1090                 INIT_WORK(&args->work, recv_work);
1091                 args->nbd = nbd;
1092                 args->index = i;
1093                 queue_work(recv_workqueue, &args->work);
1094         }
1095         return error;
1096 }
1097
1098 static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1099 {
1100         struct nbd_config *config = nbd->config;
1101         int ret;
1102
1103         ret = nbd_start_device(nbd);
1104         if (ret)
1105                 return ret;
1106
1107         bd_set_size(bdev, config->bytesize);
1108         if (max_part)
1109                 bdev->bd_invalidated = 1;
1110         mutex_unlock(&nbd->config_lock);
1111         ret = wait_event_interruptible(config->recv_wq,
1112                                          atomic_read(&config->recv_threads) == 0);
1113         if (ret)
1114                 sock_shutdown(nbd);
1115         mutex_lock(&nbd->config_lock);
1116         bd_set_size(bdev, 0);
1117         /* user requested, ignore socket errors */
1118         if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1119                 ret = 0;
1120         if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1121                 ret = -ETIMEDOUT;
1122         return ret;
1123 }
1124
1125 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1126                                  struct block_device *bdev)
1127 {
1128         sock_shutdown(nbd);
1129         kill_bdev(bdev);
1130         nbd_bdev_reset(bdev);
1131         if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1132                                &nbd->config->runtime_flags))
1133                 nbd_config_put(nbd);
1134 }
1135
1136 /* Must be called with config_lock held */
1137 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1138                        unsigned int cmd, unsigned long arg)
1139 {
1140         struct nbd_config *config = nbd->config;
1141
1142         switch (cmd) {
1143         case NBD_DISCONNECT:
1144                 return nbd_disconnect(nbd);
1145         case NBD_CLEAR_SOCK:
1146                 nbd_clear_sock_ioctl(nbd, bdev);
1147                 return 0;
1148         case NBD_SET_SOCK:
1149                 return nbd_add_socket(nbd, arg, false);
1150         case NBD_SET_BLKSIZE:
1151                 nbd_size_set(nbd, arg,
1152                              div_s64(config->bytesize, arg));
1153                 return 0;
1154         case NBD_SET_SIZE:
1155                 nbd_size_set(nbd, config->blksize,
1156                              div_s64(arg, config->blksize));
1157                 return 0;
1158         case NBD_SET_SIZE_BLOCKS:
1159                 nbd_size_set(nbd, config->blksize, arg);
1160                 return 0;
1161         case NBD_SET_TIMEOUT:
1162                 if (arg) {
1163                         nbd->tag_set.timeout = arg * HZ;
1164                         blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1165                 }
1166                 return 0;
1167
1168         case NBD_SET_FLAGS:
1169                 config->flags = arg;
1170                 return 0;
1171         case NBD_DO_IT:
1172                 return nbd_start_device_ioctl(nbd, bdev);
1173         case NBD_CLEAR_QUE:
1174                 /*
1175                  * This is for compatibility only.  The queue is always cleared
1176                  * by NBD_DO_IT or NBD_CLEAR_SOCK.
1177                  */
1178                 return 0;
1179         case NBD_PRINT_DEBUG:
1180                 /*
1181                  * For compatibility only, we no longer keep a list of
1182                  * outstanding requests.
1183                  */
1184                 return 0;
1185         }
1186         return -ENOTTY;
1187 }
1188
1189 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1190                      unsigned int cmd, unsigned long arg)
1191 {
1192         struct nbd_device *nbd = bdev->bd_disk->private_data;
1193         struct nbd_config *config = nbd->config;
1194         int error = -EINVAL;
1195
1196         if (!capable(CAP_SYS_ADMIN))
1197                 return -EPERM;
1198
1199         mutex_lock(&nbd->config_lock);
1200
1201         /* Don't allow ioctl operations on a nbd device that was created with
1202          * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1203          */
1204         if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1205             (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1206                 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1207         else
1208                 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1209         mutex_unlock(&nbd->config_lock);
1210         return error;
1211 }
1212
1213 static struct nbd_config *nbd_alloc_config(void)
1214 {
1215         struct nbd_config *config;
1216
1217         config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1218         if (!config)
1219                 return NULL;
1220         atomic_set(&config->recv_threads, 0);
1221         init_waitqueue_head(&config->recv_wq);
1222         init_waitqueue_head(&config->conn_wait);
1223         config->blksize = 1024;
1224         atomic_set(&config->live_connections, 0);
1225         try_module_get(THIS_MODULE);
1226         return config;
1227 }
1228
1229 static int nbd_open(struct block_device *bdev, fmode_t mode)
1230 {
1231         struct nbd_device *nbd;
1232         int ret = 0;
1233
1234         mutex_lock(&nbd_index_mutex);
1235         nbd = bdev->bd_disk->private_data;
1236         if (!nbd) {
1237                 ret = -ENXIO;
1238                 goto out;
1239         }
1240         if (!refcount_inc_not_zero(&nbd->refs)) {
1241                 ret = -ENXIO;
1242                 goto out;
1243         }
1244         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1245                 struct nbd_config *config;
1246
1247                 mutex_lock(&nbd->config_lock);
1248                 if (refcount_inc_not_zero(&nbd->config_refs)) {
1249                         mutex_unlock(&nbd->config_lock);
1250                         goto out;
1251                 }
1252                 config = nbd->config = nbd_alloc_config();
1253                 if (!config) {
1254                         ret = -ENOMEM;
1255                         mutex_unlock(&nbd->config_lock);
1256                         goto out;
1257                 }
1258                 refcount_set(&nbd->config_refs, 1);
1259                 refcount_inc(&nbd->refs);
1260                 mutex_unlock(&nbd->config_lock);
1261         }
1262 out:
1263         mutex_unlock(&nbd_index_mutex);
1264         return ret;
1265 }
1266
1267 static void nbd_release(struct gendisk *disk, fmode_t mode)
1268 {
1269         struct nbd_device *nbd = disk->private_data;
1270         nbd_config_put(nbd);
1271         nbd_put(nbd);
1272 }
1273
1274 static const struct block_device_operations nbd_fops =
1275 {
1276         .owner =        THIS_MODULE,
1277         .open =         nbd_open,
1278         .release =      nbd_release,
1279         .ioctl =        nbd_ioctl,
1280         .compat_ioctl = nbd_ioctl,
1281 };
1282
1283 #if IS_ENABLED(CONFIG_DEBUG_FS)
1284
1285 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1286 {
1287         struct nbd_device *nbd = s->private;
1288
1289         if (nbd->task_recv)
1290                 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1291
1292         return 0;
1293 }
1294
1295 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1296 {
1297         return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1298 }
1299
1300 static const struct file_operations nbd_dbg_tasks_ops = {
1301         .open = nbd_dbg_tasks_open,
1302         .read = seq_read,
1303         .llseek = seq_lseek,
1304         .release = single_release,
1305 };
1306
1307 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1308 {
1309         struct nbd_device *nbd = s->private;
1310         u32 flags = nbd->config->flags;
1311
1312         seq_printf(s, "Hex: 0x%08x\n\n", flags);
1313
1314         seq_puts(s, "Known flags:\n");
1315
1316         if (flags & NBD_FLAG_HAS_FLAGS)
1317                 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1318         if (flags & NBD_FLAG_READ_ONLY)
1319                 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1320         if (flags & NBD_FLAG_SEND_FLUSH)
1321                 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1322         if (flags & NBD_FLAG_SEND_FUA)
1323                 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1324         if (flags & NBD_FLAG_SEND_TRIM)
1325                 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1326
1327         return 0;
1328 }
1329
1330 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1331 {
1332         return single_open(file, nbd_dbg_flags_show, inode->i_private);
1333 }
1334
1335 static const struct file_operations nbd_dbg_flags_ops = {
1336         .open = nbd_dbg_flags_open,
1337         .read = seq_read,
1338         .llseek = seq_lseek,
1339         .release = single_release,
1340 };
1341
1342 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1343 {
1344         struct dentry *dir;
1345         struct nbd_config *config = nbd->config;
1346
1347         if (!nbd_dbg_dir)
1348                 return -EIO;
1349
1350         dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1351         if (!dir) {
1352                 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1353                         nbd_name(nbd));
1354                 return -EIO;
1355         }
1356         config->dbg_dir = dir;
1357
1358         debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1359         debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1360         debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1361         debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1362         debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1363
1364         return 0;
1365 }
1366
1367 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1368 {
1369         debugfs_remove_recursive(nbd->config->dbg_dir);
1370 }
1371
1372 static int nbd_dbg_init(void)
1373 {
1374         struct dentry *dbg_dir;
1375
1376         dbg_dir = debugfs_create_dir("nbd", NULL);
1377         if (!dbg_dir)
1378                 return -EIO;
1379
1380         nbd_dbg_dir = dbg_dir;
1381
1382         return 0;
1383 }
1384
1385 static void nbd_dbg_close(void)
1386 {
1387         debugfs_remove_recursive(nbd_dbg_dir);
1388 }
1389
1390 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
1391
1392 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1393 {
1394         return 0;
1395 }
1396
1397 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1398 {
1399 }
1400
1401 static int nbd_dbg_init(void)
1402 {
1403         return 0;
1404 }
1405
1406 static void nbd_dbg_close(void)
1407 {
1408 }
1409
1410 #endif
1411
1412 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1413                             unsigned int hctx_idx, unsigned int numa_node)
1414 {
1415         struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1416         cmd->nbd = set->driver_data;
1417         return 0;
1418 }
1419
1420 static const struct blk_mq_ops nbd_mq_ops = {
1421         .queue_rq       = nbd_queue_rq,
1422         .complete       = nbd_complete_rq,
1423         .init_request   = nbd_init_request,
1424         .timeout        = nbd_xmit_timeout,
1425 };
1426
1427 static int nbd_dev_add(int index)
1428 {
1429         struct nbd_device *nbd;
1430         struct gendisk *disk;
1431         struct request_queue *q;
1432         int err = -ENOMEM;
1433
1434         nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1435         if (!nbd)
1436                 goto out;
1437
1438         disk = alloc_disk(1 << part_shift);
1439         if (!disk)
1440                 goto out_free_nbd;
1441
1442         if (index >= 0) {
1443                 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1444                                 GFP_KERNEL);
1445                 if (err == -ENOSPC)
1446                         err = -EEXIST;
1447         } else {
1448                 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1449                 if (err >= 0)
1450                         index = err;
1451         }
1452         if (err < 0)
1453                 goto out_free_disk;
1454
1455         nbd->index = index;
1456         nbd->disk = disk;
1457         nbd->tag_set.ops = &nbd_mq_ops;
1458         nbd->tag_set.nr_hw_queues = 1;
1459         nbd->tag_set.queue_depth = 128;
1460         nbd->tag_set.numa_node = NUMA_NO_NODE;
1461         nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1462         nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1463                 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1464         nbd->tag_set.driver_data = nbd;
1465
1466         err = blk_mq_alloc_tag_set(&nbd->tag_set);
1467         if (err)
1468                 goto out_free_idr;
1469
1470         q = blk_mq_init_queue(&nbd->tag_set);
1471         if (IS_ERR(q)) {
1472                 err = PTR_ERR(q);
1473                 goto out_free_tags;
1474         }
1475         disk->queue = q;
1476
1477         /*
1478          * Tell the block layer that we are not a rotational device
1479          */
1480         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1481         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1482         disk->queue->limits.discard_granularity = 512;
1483         blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1484         blk_queue_max_segment_size(disk->queue, UINT_MAX);
1485         blk_queue_max_segments(disk->queue, USHRT_MAX);
1486         blk_queue_max_hw_sectors(disk->queue, 65536);
1487         disk->queue->limits.max_sectors = 256;
1488
1489         mutex_init(&nbd->config_lock);
1490         refcount_set(&nbd->config_refs, 0);
1491         refcount_set(&nbd->refs, 1);
1492         INIT_LIST_HEAD(&nbd->list);
1493         disk->major = NBD_MAJOR;
1494         disk->first_minor = index << part_shift;
1495         disk->fops = &nbd_fops;
1496         disk->private_data = nbd;
1497         sprintf(disk->disk_name, "nbd%d", index);
1498         nbd_reset(nbd);
1499         add_disk(disk);
1500         nbd_total_devices++;
1501         return index;
1502
1503 out_free_tags:
1504         blk_mq_free_tag_set(&nbd->tag_set);
1505 out_free_idr:
1506         idr_remove(&nbd_index_idr, index);
1507 out_free_disk:
1508         put_disk(disk);
1509 out_free_nbd:
1510         kfree(nbd);
1511 out:
1512         return err;
1513 }
1514
1515 static int find_free_cb(int id, void *ptr, void *data)
1516 {
1517         struct nbd_device *nbd = ptr;
1518         struct nbd_device **found = data;
1519
1520         if (!refcount_read(&nbd->config_refs)) {
1521                 *found = nbd;
1522                 return 1;
1523         }
1524         return 0;
1525 }
1526
1527 /* Netlink interface. */
1528 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1529         [NBD_ATTR_INDEX]                =       { .type = NLA_U32 },
1530         [NBD_ATTR_SIZE_BYTES]           =       { .type = NLA_U64 },
1531         [NBD_ATTR_BLOCK_SIZE_BYTES]     =       { .type = NLA_U64 },
1532         [NBD_ATTR_TIMEOUT]              =       { .type = NLA_U64 },
1533         [NBD_ATTR_SERVER_FLAGS]         =       { .type = NLA_U64 },
1534         [NBD_ATTR_CLIENT_FLAGS]         =       { .type = NLA_U64 },
1535         [NBD_ATTR_SOCKETS]              =       { .type = NLA_NESTED},
1536         [NBD_ATTR_DEAD_CONN_TIMEOUT]    =       { .type = NLA_U64 },
1537         [NBD_ATTR_DEVICE_LIST]          =       { .type = NLA_NESTED},
1538 };
1539
1540 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1541         [NBD_SOCK_FD]                   =       { .type = NLA_U32 },
1542 };
1543
1544 /* We don't use this right now since we don't parse the incoming list, but we
1545  * still want it here so userspace knows what to expect.
1546  */
1547 static struct nla_policy __attribute__((unused))
1548 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1549         [NBD_DEVICE_INDEX]              =       { .type = NLA_U32 },
1550         [NBD_DEVICE_CONNECTED]          =       { .type = NLA_U8 },
1551 };
1552
1553 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1554 {
1555         struct nbd_device *nbd = NULL;
1556         struct nbd_config *config;
1557         int index = -1;
1558         int ret;
1559         bool put_dev = false;
1560
1561         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1562                 return -EPERM;
1563
1564         if (info->attrs[NBD_ATTR_INDEX])
1565                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1566         if (!info->attrs[NBD_ATTR_SOCKETS]) {
1567                 printk(KERN_ERR "nbd: must specify at least one socket\n");
1568                 return -EINVAL;
1569         }
1570         if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1571                 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1572                 return -EINVAL;
1573         }
1574 again:
1575         mutex_lock(&nbd_index_mutex);
1576         if (index == -1) {
1577                 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1578                 if (ret == 0) {
1579                         int new_index;
1580                         new_index = nbd_dev_add(-1);
1581                         if (new_index < 0) {
1582                                 mutex_unlock(&nbd_index_mutex);
1583                                 printk(KERN_ERR "nbd: failed to add new device\n");
1584                                 return ret;
1585                         }
1586                         nbd = idr_find(&nbd_index_idr, new_index);
1587                 }
1588         } else {
1589                 nbd = idr_find(&nbd_index_idr, index);
1590         }
1591         if (!nbd) {
1592                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1593                        index);
1594                 mutex_unlock(&nbd_index_mutex);
1595                 return -EINVAL;
1596         }
1597         if (!refcount_inc_not_zero(&nbd->refs)) {
1598                 mutex_unlock(&nbd_index_mutex);
1599                 if (index == -1)
1600                         goto again;
1601                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1602                        index);
1603                 return -EINVAL;
1604         }
1605         mutex_unlock(&nbd_index_mutex);
1606
1607         mutex_lock(&nbd->config_lock);
1608         if (refcount_read(&nbd->config_refs)) {
1609                 mutex_unlock(&nbd->config_lock);
1610                 nbd_put(nbd);
1611                 if (index == -1)
1612                         goto again;
1613                 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1614                 return -EBUSY;
1615         }
1616         if (WARN_ON(nbd->config)) {
1617                 mutex_unlock(&nbd->config_lock);
1618                 nbd_put(nbd);
1619                 return -EINVAL;
1620         }
1621         config = nbd->config = nbd_alloc_config();
1622         if (!nbd->config) {
1623                 mutex_unlock(&nbd->config_lock);
1624                 nbd_put(nbd);
1625                 printk(KERN_ERR "nbd: couldn't allocate config\n");
1626                 return -ENOMEM;
1627         }
1628         refcount_set(&nbd->config_refs, 1);
1629         set_bit(NBD_BOUND, &config->runtime_flags);
1630
1631         if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1632                 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1633                 nbd_size_set(nbd, config->blksize,
1634                              div64_u64(bytes, config->blksize));
1635         }
1636         if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1637                 u64 bsize =
1638                         nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1639                 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1640         }
1641         if (info->attrs[NBD_ATTR_TIMEOUT]) {
1642                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1643                 nbd->tag_set.timeout = timeout * HZ;
1644                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1645         }
1646         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1647                 config->dead_conn_timeout =
1648                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1649                 config->dead_conn_timeout *= HZ;
1650         }
1651         if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1652                 config->flags =
1653                         nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1654         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1655                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1656                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1657                         set_bit(NBD_DESTROY_ON_DISCONNECT,
1658                                 &config->runtime_flags);
1659                         put_dev = true;
1660                 }
1661         }
1662
1663         if (info->attrs[NBD_ATTR_SOCKETS]) {
1664                 struct nlattr *attr;
1665                 int rem, fd;
1666
1667                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1668                                     rem) {
1669                         struct nlattr *socks[NBD_SOCK_MAX+1];
1670
1671                         if (nla_type(attr) != NBD_SOCK_ITEM) {
1672                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1673                                 ret = -EINVAL;
1674                                 goto out;
1675                         }
1676                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1677                                                nbd_sock_policy, info->extack);
1678                         if (ret != 0) {
1679                                 printk(KERN_ERR "nbd: error processing sock list\n");
1680                                 ret = -EINVAL;
1681                                 goto out;
1682                         }
1683                         if (!socks[NBD_SOCK_FD])
1684                                 continue;
1685                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1686                         ret = nbd_add_socket(nbd, fd, true);
1687                         if (ret)
1688                                 goto out;
1689                 }
1690         }
1691         ret = nbd_start_device(nbd);
1692 out:
1693         mutex_unlock(&nbd->config_lock);
1694         if (!ret) {
1695                 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1696                 refcount_inc(&nbd->config_refs);
1697                 nbd_connect_reply(info, nbd->index);
1698         }
1699         nbd_config_put(nbd);
1700         if (put_dev)
1701                 nbd_put(nbd);
1702         return ret;
1703 }
1704
1705 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1706 {
1707         struct nbd_device *nbd;
1708         int index;
1709
1710         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1711                 return -EPERM;
1712
1713         if (!info->attrs[NBD_ATTR_INDEX]) {
1714                 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1715                 return -EINVAL;
1716         }
1717         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1718         mutex_lock(&nbd_index_mutex);
1719         nbd = idr_find(&nbd_index_idr, index);
1720         if (!nbd) {
1721                 mutex_unlock(&nbd_index_mutex);
1722                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1723                        index);
1724                 return -EINVAL;
1725         }
1726         if (!refcount_inc_not_zero(&nbd->refs)) {
1727                 mutex_unlock(&nbd_index_mutex);
1728                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1729                        index);
1730                 return -EINVAL;
1731         }
1732         mutex_unlock(&nbd_index_mutex);
1733         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1734                 nbd_put(nbd);
1735                 return 0;
1736         }
1737         mutex_lock(&nbd->config_lock);
1738         nbd_disconnect(nbd);
1739         mutex_unlock(&nbd->config_lock);
1740         if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1741                                &nbd->config->runtime_flags))
1742                 nbd_config_put(nbd);
1743         nbd_config_put(nbd);
1744         nbd_put(nbd);
1745         return 0;
1746 }
1747
1748 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1749 {
1750         struct nbd_device *nbd = NULL;
1751         struct nbd_config *config;
1752         int index;
1753         int ret = -EINVAL;
1754         bool put_dev = false;
1755
1756         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1757                 return -EPERM;
1758
1759         if (!info->attrs[NBD_ATTR_INDEX]) {
1760                 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1761                 return -EINVAL;
1762         }
1763         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1764         mutex_lock(&nbd_index_mutex);
1765         nbd = idr_find(&nbd_index_idr, index);
1766         if (!nbd) {
1767                 mutex_unlock(&nbd_index_mutex);
1768                 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1769                        index);
1770                 return -EINVAL;
1771         }
1772         if (!refcount_inc_not_zero(&nbd->refs)) {
1773                 mutex_unlock(&nbd_index_mutex);
1774                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1775                        index);
1776                 return -EINVAL;
1777         }
1778         mutex_unlock(&nbd_index_mutex);
1779
1780         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1781                 dev_err(nbd_to_dev(nbd),
1782                         "not configured, cannot reconfigure\n");
1783                 nbd_put(nbd);
1784                 return -EINVAL;
1785         }
1786
1787         mutex_lock(&nbd->config_lock);
1788         config = nbd->config;
1789         if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1790             !nbd->task_recv) {
1791                 dev_err(nbd_to_dev(nbd),
1792                         "not configured, cannot reconfigure\n");
1793                 goto out;
1794         }
1795
1796         if (info->attrs[NBD_ATTR_TIMEOUT]) {
1797                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1798                 nbd->tag_set.timeout = timeout * HZ;
1799                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1800         }
1801         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1802                 config->dead_conn_timeout =
1803                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1804                 config->dead_conn_timeout *= HZ;
1805         }
1806         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1807                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1808                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1809                         if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1810                                               &config->runtime_flags))
1811                                 put_dev = true;
1812                 } else {
1813                         if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1814                                                &config->runtime_flags))
1815                                 refcount_inc(&nbd->refs);
1816                 }
1817         }
1818
1819         if (info->attrs[NBD_ATTR_SOCKETS]) {
1820                 struct nlattr *attr;
1821                 int rem, fd;
1822
1823                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1824                                     rem) {
1825                         struct nlattr *socks[NBD_SOCK_MAX+1];
1826
1827                         if (nla_type(attr) != NBD_SOCK_ITEM) {
1828                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1829                                 ret = -EINVAL;
1830                                 goto out;
1831                         }
1832                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1833                                                nbd_sock_policy, info->extack);
1834                         if (ret != 0) {
1835                                 printk(KERN_ERR "nbd: error processing sock list\n");
1836                                 ret = -EINVAL;
1837                                 goto out;
1838                         }
1839                         if (!socks[NBD_SOCK_FD])
1840                                 continue;
1841                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1842                         ret = nbd_reconnect_socket(nbd, fd);
1843                         if (ret) {
1844                                 if (ret == -ENOSPC)
1845                                         ret = 0;
1846                                 goto out;
1847                         }
1848                         dev_info(nbd_to_dev(nbd), "reconnected socket\n");
1849                 }
1850         }
1851 out:
1852         mutex_unlock(&nbd->config_lock);
1853         nbd_config_put(nbd);
1854         nbd_put(nbd);
1855         if (put_dev)
1856                 nbd_put(nbd);
1857         return ret;
1858 }
1859
1860 static const struct genl_ops nbd_connect_genl_ops[] = {
1861         {
1862                 .cmd    = NBD_CMD_CONNECT,
1863                 .policy = nbd_attr_policy,
1864                 .doit   = nbd_genl_connect,
1865         },
1866         {
1867                 .cmd    = NBD_CMD_DISCONNECT,
1868                 .policy = nbd_attr_policy,
1869                 .doit   = nbd_genl_disconnect,
1870         },
1871         {
1872                 .cmd    = NBD_CMD_RECONFIGURE,
1873                 .policy = nbd_attr_policy,
1874                 .doit   = nbd_genl_reconfigure,
1875         },
1876         {
1877                 .cmd    = NBD_CMD_STATUS,
1878                 .policy = nbd_attr_policy,
1879                 .doit   = nbd_genl_status,
1880         },
1881 };
1882
1883 static const struct genl_multicast_group nbd_mcast_grps[] = {
1884         { .name = NBD_GENL_MCAST_GROUP_NAME, },
1885 };
1886
1887 static struct genl_family nbd_genl_family __ro_after_init = {
1888         .hdrsize        = 0,
1889         .name           = NBD_GENL_FAMILY_NAME,
1890         .version        = NBD_GENL_VERSION,
1891         .module         = THIS_MODULE,
1892         .ops            = nbd_connect_genl_ops,
1893         .n_ops          = ARRAY_SIZE(nbd_connect_genl_ops),
1894         .maxattr        = NBD_ATTR_MAX,
1895         .mcgrps         = nbd_mcast_grps,
1896         .n_mcgrps       = ARRAY_SIZE(nbd_mcast_grps),
1897 };
1898
1899 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
1900 {
1901         struct nlattr *dev_opt;
1902         u8 connected = 0;
1903         int ret;
1904
1905         /* This is a little racey, but for status it's ok.  The
1906          * reason we don't take a ref here is because we can't
1907          * take a ref in the index == -1 case as we would need
1908          * to put under the nbd_index_mutex, which could
1909          * deadlock if we are configured to remove ourselves
1910          * once we're disconnected.
1911          */
1912         if (refcount_read(&nbd->config_refs))
1913                 connected = 1;
1914         dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
1915         if (!dev_opt)
1916                 return -EMSGSIZE;
1917         ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
1918         if (ret)
1919                 return -EMSGSIZE;
1920         ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
1921                          connected);
1922         if (ret)
1923                 return -EMSGSIZE;
1924         nla_nest_end(reply, dev_opt);
1925         return 0;
1926 }
1927
1928 static int status_cb(int id, void *ptr, void *data)
1929 {
1930         struct nbd_device *nbd = ptr;
1931         return populate_nbd_status(nbd, (struct sk_buff *)data);
1932 }
1933
1934 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
1935 {
1936         struct nlattr *dev_list;
1937         struct sk_buff *reply;
1938         void *reply_head;
1939         size_t msg_size;
1940         int index = -1;
1941         int ret = -ENOMEM;
1942
1943         if (info->attrs[NBD_ATTR_INDEX])
1944                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1945
1946         mutex_lock(&nbd_index_mutex);
1947
1948         msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
1949                                   nla_attr_size(sizeof(u8)));
1950         msg_size *= (index == -1) ? nbd_total_devices : 1;
1951
1952         reply = genlmsg_new(msg_size, GFP_KERNEL);
1953         if (!reply)
1954                 goto out;
1955         reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
1956                                        NBD_CMD_STATUS);
1957         if (!reply_head) {
1958                 nlmsg_free(reply);
1959                 goto out;
1960         }
1961
1962         dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
1963         if (index == -1) {
1964                 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
1965                 if (ret) {
1966                         nlmsg_free(reply);
1967                         goto out;
1968                 }
1969         } else {
1970                 struct nbd_device *nbd;
1971                 nbd = idr_find(&nbd_index_idr, index);
1972                 if (nbd) {
1973                         ret = populate_nbd_status(nbd, reply);
1974                         if (ret) {
1975                                 nlmsg_free(reply);
1976                                 goto out;
1977                         }
1978                 }
1979         }
1980         nla_nest_end(reply, dev_list);
1981         genlmsg_end(reply, reply_head);
1982         genlmsg_reply(reply, info);
1983         ret = 0;
1984 out:
1985         mutex_unlock(&nbd_index_mutex);
1986         return ret;
1987 }
1988
1989 static void nbd_connect_reply(struct genl_info *info, int index)
1990 {
1991         struct sk_buff *skb;
1992         void *msg_head;
1993         int ret;
1994
1995         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
1996         if (!skb)
1997                 return;
1998         msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
1999                                      NBD_CMD_CONNECT);
2000         if (!msg_head) {
2001                 nlmsg_free(skb);
2002                 return;
2003         }
2004         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2005         if (ret) {
2006                 nlmsg_free(skb);
2007                 return;
2008         }
2009         genlmsg_end(skb, msg_head);
2010         genlmsg_reply(skb, info);
2011 }
2012
2013 static void nbd_mcast_index(int index)
2014 {
2015         struct sk_buff *skb;
2016         void *msg_head;
2017         int ret;
2018
2019         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2020         if (!skb)
2021                 return;
2022         msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2023                                      NBD_CMD_LINK_DEAD);
2024         if (!msg_head) {
2025                 nlmsg_free(skb);
2026                 return;
2027         }
2028         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2029         if (ret) {
2030                 nlmsg_free(skb);
2031                 return;
2032         }
2033         genlmsg_end(skb, msg_head);
2034         genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2035 }
2036
2037 static void nbd_dead_link_work(struct work_struct *work)
2038 {
2039         struct link_dead_args *args = container_of(work, struct link_dead_args,
2040                                                    work);
2041         nbd_mcast_index(args->index);
2042         kfree(args);
2043 }
2044
2045 static int __init nbd_init(void)
2046 {
2047         int i;
2048
2049         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2050
2051         if (max_part < 0) {
2052                 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2053                 return -EINVAL;
2054         }
2055
2056         part_shift = 0;
2057         if (max_part > 0) {
2058                 part_shift = fls(max_part);
2059
2060                 /*
2061                  * Adjust max_part according to part_shift as it is exported
2062                  * to user space so that user can know the max number of
2063                  * partition kernel should be able to manage.
2064                  *
2065                  * Note that -1 is required because partition 0 is reserved
2066                  * for the whole disk.
2067                  */
2068                 max_part = (1UL << part_shift) - 1;
2069         }
2070
2071         if ((1UL << part_shift) > DISK_MAX_PARTS)
2072                 return -EINVAL;
2073
2074         if (nbds_max > 1UL << (MINORBITS - part_shift))
2075                 return -EINVAL;
2076         recv_workqueue = alloc_workqueue("knbd-recv",
2077                                          WQ_MEM_RECLAIM | WQ_HIGHPRI, 0);
2078         if (!recv_workqueue)
2079                 return -ENOMEM;
2080
2081         if (register_blkdev(NBD_MAJOR, "nbd")) {
2082                 destroy_workqueue(recv_workqueue);
2083                 return -EIO;
2084         }
2085
2086         if (genl_register_family(&nbd_genl_family)) {
2087                 unregister_blkdev(NBD_MAJOR, "nbd");
2088                 destroy_workqueue(recv_workqueue);
2089                 return -EINVAL;
2090         }
2091         nbd_dbg_init();
2092
2093         mutex_lock(&nbd_index_mutex);
2094         for (i = 0; i < nbds_max; i++)
2095                 nbd_dev_add(i);
2096         mutex_unlock(&nbd_index_mutex);
2097         return 0;
2098 }
2099
2100 static int nbd_exit_cb(int id, void *ptr, void *data)
2101 {
2102         struct list_head *list = (struct list_head *)data;
2103         struct nbd_device *nbd = ptr;
2104
2105         list_add_tail(&nbd->list, list);
2106         return 0;
2107 }
2108
2109 static void __exit nbd_cleanup(void)
2110 {
2111         struct nbd_device *nbd;
2112         LIST_HEAD(del_list);
2113
2114         nbd_dbg_close();
2115
2116         mutex_lock(&nbd_index_mutex);
2117         idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2118         mutex_unlock(&nbd_index_mutex);
2119
2120         while (!list_empty(&del_list)) {
2121                 nbd = list_first_entry(&del_list, struct nbd_device, list);
2122                 list_del_init(&nbd->list);
2123                 if (refcount_read(&nbd->refs) != 1)
2124                         printk(KERN_ERR "nbd: possibly leaking a device\n");
2125                 nbd_put(nbd);
2126         }
2127
2128         idr_destroy(&nbd_index_idr);
2129         genl_unregister_family(&nbd_genl_family);
2130         destroy_workqueue(recv_workqueue);
2131         unregister_blkdev(NBD_MAJOR, "nbd");
2132 }
2133
2134 module_init(nbd_init);
2135 module_exit(nbd_cleanup);
2136
2137 MODULE_DESCRIPTION("Network Block Device");
2138 MODULE_LICENSE("GPL");
2139
2140 module_param(nbds_max, int, 0444);
2141 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2142 module_param(max_part, int, 0444);
2143 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 0)");