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