GNU Linux-libre 4.14.290-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         flush_workqueue(nbd->recv_workq);
1264
1265         mutex_lock(&nbd->config_lock);
1266         bd_set_size(bdev, 0);
1267         /* user requested, ignore socket errors */
1268         if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
1269                 ret = 0;
1270         if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
1271                 ret = -ETIMEDOUT;
1272         return ret;
1273 }
1274
1275 static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1276                                  struct block_device *bdev)
1277 {
1278         nbd_clear_sock(nbd);
1279         __invalidate_device(bdev, true);
1280         nbd_bdev_reset(bdev);
1281         if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1282                                &nbd->config->runtime_flags))
1283                 nbd_config_put(nbd);
1284 }
1285
1286 static bool nbd_is_valid_blksize(unsigned long blksize)
1287 {
1288         if (!blksize || !is_power_of_2(blksize) || blksize < 512 ||
1289             blksize > PAGE_SIZE)
1290                 return false;
1291         return true;
1292 }
1293
1294 /* Must be called with config_lock held */
1295 static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1296                        unsigned int cmd, unsigned long arg)
1297 {
1298         struct nbd_config *config = nbd->config;
1299
1300         switch (cmd) {
1301         case NBD_DISCONNECT:
1302                 return nbd_disconnect(nbd);
1303         case NBD_CLEAR_SOCK:
1304                 nbd_clear_sock_ioctl(nbd, bdev);
1305                 return 0;
1306         case NBD_SET_SOCK:
1307                 return nbd_add_socket(nbd, arg, false);
1308         case NBD_SET_BLKSIZE:
1309                 if (!arg)
1310                         arg = NBD_DEF_BLKSIZE;
1311                 if (!nbd_is_valid_blksize(arg))
1312                         return -EINVAL;
1313                 nbd_size_set(nbd, arg,
1314                              div_s64(config->bytesize, arg));
1315                 return 0;
1316         case NBD_SET_SIZE:
1317                 nbd_size_set(nbd, config->blksize,
1318                              div_s64(arg, config->blksize));
1319                 return 0;
1320         case NBD_SET_SIZE_BLOCKS:
1321                 nbd_size_set(nbd, config->blksize, arg);
1322                 return 0;
1323         case NBD_SET_TIMEOUT:
1324                 if (arg) {
1325                         nbd->tag_set.timeout = arg * HZ;
1326                         blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1327                 }
1328                 return 0;
1329
1330         case NBD_SET_FLAGS:
1331                 config->flags = arg;
1332                 return 0;
1333         case NBD_DO_IT:
1334                 return nbd_start_device_ioctl(nbd, bdev);
1335         case NBD_CLEAR_QUE:
1336                 /*
1337                  * This is for compatibility only.  The queue is always cleared
1338                  * by NBD_DO_IT or NBD_CLEAR_SOCK.
1339                  */
1340                 return 0;
1341         case NBD_PRINT_DEBUG:
1342                 /*
1343                  * For compatibility only, we no longer keep a list of
1344                  * outstanding requests.
1345                  */
1346                 return 0;
1347         }
1348         return -ENOTTY;
1349 }
1350
1351 static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1352                      unsigned int cmd, unsigned long arg)
1353 {
1354         struct nbd_device *nbd = bdev->bd_disk->private_data;
1355         struct nbd_config *config = nbd->config;
1356         int error = -EINVAL;
1357
1358         if (!capable(CAP_SYS_ADMIN))
1359                 return -EPERM;
1360
1361         /* The block layer will pass back some non-nbd ioctls in case we have
1362          * special handling for them, but we don't so just return an error.
1363          */
1364         if (_IOC_TYPE(cmd) != 0xab)
1365                 return -EINVAL;
1366
1367         mutex_lock(&nbd->config_lock);
1368
1369         /* Don't allow ioctl operations on a nbd device that was created with
1370          * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1371          */
1372         if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1373             (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1374                 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1375         else
1376                 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
1377         mutex_unlock(&nbd->config_lock);
1378         return error;
1379 }
1380
1381 static struct nbd_config *nbd_alloc_config(void)
1382 {
1383         struct nbd_config *config;
1384
1385         if (!try_module_get(THIS_MODULE))
1386                 return ERR_PTR(-ENODEV);
1387
1388         config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1389         if (!config) {
1390                 module_put(THIS_MODULE);
1391                 return ERR_PTR(-ENOMEM);
1392         }
1393
1394         atomic_set(&config->recv_threads, 0);
1395         init_waitqueue_head(&config->recv_wq);
1396         init_waitqueue_head(&config->conn_wait);
1397         config->blksize = NBD_DEF_BLKSIZE;
1398         atomic_set(&config->live_connections, 0);
1399         return config;
1400 }
1401
1402 static int nbd_open(struct block_device *bdev, fmode_t mode)
1403 {
1404         struct nbd_device *nbd;
1405         int ret = 0;
1406
1407         mutex_lock(&nbd_index_mutex);
1408         nbd = bdev->bd_disk->private_data;
1409         if (!nbd) {
1410                 ret = -ENXIO;
1411                 goto out;
1412         }
1413         if (!refcount_inc_not_zero(&nbd->refs)) {
1414                 ret = -ENXIO;
1415                 goto out;
1416         }
1417         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1418                 struct nbd_config *config;
1419
1420                 mutex_lock(&nbd->config_lock);
1421                 if (refcount_inc_not_zero(&nbd->config_refs)) {
1422                         mutex_unlock(&nbd->config_lock);
1423                         goto out;
1424                 }
1425                 config = nbd_alloc_config();
1426                 if (IS_ERR(config)) {
1427                         ret = PTR_ERR(config);
1428                         mutex_unlock(&nbd->config_lock);
1429                         goto out;
1430                 }
1431                 nbd->config = config;
1432                 refcount_set(&nbd->config_refs, 1);
1433                 refcount_inc(&nbd->refs);
1434                 mutex_unlock(&nbd->config_lock);
1435         }
1436 out:
1437         mutex_unlock(&nbd_index_mutex);
1438         return ret;
1439 }
1440
1441 static void nbd_release(struct gendisk *disk, fmode_t mode)
1442 {
1443         struct nbd_device *nbd = disk->private_data;
1444         struct block_device *bdev = bdget_disk(disk, 0);
1445
1446         if (test_bit(NBD_DISCONNECT_ON_CLOSE, &nbd->config->runtime_flags) &&
1447                         bdev->bd_openers == 0)
1448                 nbd_disconnect_and_put(nbd);
1449         bdput(bdev);
1450
1451         nbd_config_put(nbd);
1452         nbd_put(nbd);
1453 }
1454
1455 static const struct block_device_operations nbd_fops =
1456 {
1457         .owner =        THIS_MODULE,
1458         .open =         nbd_open,
1459         .release =      nbd_release,
1460         .ioctl =        nbd_ioctl,
1461         .compat_ioctl = nbd_ioctl,
1462 };
1463
1464 #if IS_ENABLED(CONFIG_DEBUG_FS)
1465
1466 static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1467 {
1468         struct nbd_device *nbd = s->private;
1469
1470         if (nbd->task_recv)
1471                 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
1472
1473         return 0;
1474 }
1475
1476 static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1477 {
1478         return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1479 }
1480
1481 static const struct file_operations nbd_dbg_tasks_ops = {
1482         .open = nbd_dbg_tasks_open,
1483         .read = seq_read,
1484         .llseek = seq_lseek,
1485         .release = single_release,
1486 };
1487
1488 static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1489 {
1490         struct nbd_device *nbd = s->private;
1491         u32 flags = nbd->config->flags;
1492
1493         seq_printf(s, "Hex: 0x%08x\n\n", flags);
1494
1495         seq_puts(s, "Known flags:\n");
1496
1497         if (flags & NBD_FLAG_HAS_FLAGS)
1498                 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1499         if (flags & NBD_FLAG_READ_ONLY)
1500                 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1501         if (flags & NBD_FLAG_SEND_FLUSH)
1502                 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
1503         if (flags & NBD_FLAG_SEND_FUA)
1504                 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
1505         if (flags & NBD_FLAG_SEND_TRIM)
1506                 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1507
1508         return 0;
1509 }
1510
1511 static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1512 {
1513         return single_open(file, nbd_dbg_flags_show, inode->i_private);
1514 }
1515
1516 static const struct file_operations nbd_dbg_flags_ops = {
1517         .open = nbd_dbg_flags_open,
1518         .read = seq_read,
1519         .llseek = seq_lseek,
1520         .release = single_release,
1521 };
1522
1523 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1524 {
1525         struct dentry *dir;
1526         struct nbd_config *config = nbd->config;
1527
1528         if (!nbd_dbg_dir)
1529                 return -EIO;
1530
1531         dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
1532         if (!dir) {
1533                 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1534                         nbd_name(nbd));
1535                 return -EIO;
1536         }
1537         config->dbg_dir = dir;
1538
1539         debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
1540         debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
1541         debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
1542         debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
1543         debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
1544
1545         return 0;
1546 }
1547
1548 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1549 {
1550         debugfs_remove_recursive(nbd->config->dbg_dir);
1551 }
1552
1553 static int nbd_dbg_init(void)
1554 {
1555         struct dentry *dbg_dir;
1556
1557         dbg_dir = debugfs_create_dir("nbd", NULL);
1558         if (!dbg_dir)
1559                 return -EIO;
1560
1561         nbd_dbg_dir = dbg_dir;
1562
1563         return 0;
1564 }
1565
1566 static void nbd_dbg_close(void)
1567 {
1568         debugfs_remove_recursive(nbd_dbg_dir);
1569 }
1570
1571 #else  /* IS_ENABLED(CONFIG_DEBUG_FS) */
1572
1573 static int nbd_dev_dbg_init(struct nbd_device *nbd)
1574 {
1575         return 0;
1576 }
1577
1578 static void nbd_dev_dbg_close(struct nbd_device *nbd)
1579 {
1580 }
1581
1582 static int nbd_dbg_init(void)
1583 {
1584         return 0;
1585 }
1586
1587 static void nbd_dbg_close(void)
1588 {
1589 }
1590
1591 #endif
1592
1593 static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1594                             unsigned int hctx_idx, unsigned int numa_node)
1595 {
1596         struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
1597         cmd->nbd = set->driver_data;
1598         cmd->flags = 0;
1599         mutex_init(&cmd->lock);
1600         return 0;
1601 }
1602
1603 static const struct blk_mq_ops nbd_mq_ops = {
1604         .queue_rq       = nbd_queue_rq,
1605         .complete       = nbd_complete_rq,
1606         .init_request   = nbd_init_request,
1607         .timeout        = nbd_xmit_timeout,
1608 };
1609
1610 static int nbd_dev_add(int index)
1611 {
1612         struct nbd_device *nbd;
1613         struct gendisk *disk;
1614         struct request_queue *q;
1615         int err = -ENOMEM;
1616
1617         nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1618         if (!nbd)
1619                 goto out;
1620
1621         disk = alloc_disk(1 << part_shift);
1622         if (!disk)
1623                 goto out_free_nbd;
1624
1625         if (index >= 0) {
1626                 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1627                                 GFP_KERNEL);
1628                 if (err == -ENOSPC)
1629                         err = -EEXIST;
1630         } else {
1631                 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1632                 if (err >= 0)
1633                         index = err;
1634         }
1635         if (err < 0)
1636                 goto out_free_disk;
1637
1638         nbd->index = index;
1639         nbd->disk = disk;
1640         nbd->tag_set.ops = &nbd_mq_ops;
1641         nbd->tag_set.nr_hw_queues = 1;
1642         nbd->tag_set.queue_depth = 128;
1643         nbd->tag_set.numa_node = NUMA_NO_NODE;
1644         nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1645         nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1646                 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1647         nbd->tag_set.driver_data = nbd;
1648
1649         err = blk_mq_alloc_tag_set(&nbd->tag_set);
1650         if (err)
1651                 goto out_free_idr;
1652
1653         q = blk_mq_init_queue(&nbd->tag_set);
1654         if (IS_ERR(q)) {
1655                 err = PTR_ERR(q);
1656                 goto out_free_tags;
1657         }
1658         disk->queue = q;
1659
1660         /*
1661          * Tell the block layer that we are not a rotational device
1662          */
1663         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1664         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1665         disk->queue->limits.discard_granularity = 512;
1666         blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1667         blk_queue_max_segment_size(disk->queue, UINT_MAX);
1668         blk_queue_max_segments(disk->queue, USHRT_MAX);
1669         blk_queue_max_hw_sectors(disk->queue, 65536);
1670         disk->queue->limits.max_sectors = 256;
1671
1672         mutex_init(&nbd->config_lock);
1673         refcount_set(&nbd->config_refs, 0);
1674         refcount_set(&nbd->refs, 1);
1675         INIT_LIST_HEAD(&nbd->list);
1676         disk->major = NBD_MAJOR;
1677         disk->first_minor = index << part_shift;
1678         disk->fops = &nbd_fops;
1679         disk->private_data = nbd;
1680         sprintf(disk->disk_name, "nbd%d", index);
1681         add_disk(disk);
1682         nbd_total_devices++;
1683         return index;
1684
1685 out_free_tags:
1686         blk_mq_free_tag_set(&nbd->tag_set);
1687 out_free_idr:
1688         idr_remove(&nbd_index_idr, index);
1689 out_free_disk:
1690         put_disk(disk);
1691 out_free_nbd:
1692         kfree(nbd);
1693 out:
1694         return err;
1695 }
1696
1697 static int find_free_cb(int id, void *ptr, void *data)
1698 {
1699         struct nbd_device *nbd = ptr;
1700         struct nbd_device **found = data;
1701
1702         if (!refcount_read(&nbd->config_refs)) {
1703                 *found = nbd;
1704                 return 1;
1705         }
1706         return 0;
1707 }
1708
1709 /* Netlink interface. */
1710 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1711         [NBD_ATTR_INDEX]                =       { .type = NLA_U32 },
1712         [NBD_ATTR_SIZE_BYTES]           =       { .type = NLA_U64 },
1713         [NBD_ATTR_BLOCK_SIZE_BYTES]     =       { .type = NLA_U64 },
1714         [NBD_ATTR_TIMEOUT]              =       { .type = NLA_U64 },
1715         [NBD_ATTR_SERVER_FLAGS]         =       { .type = NLA_U64 },
1716         [NBD_ATTR_CLIENT_FLAGS]         =       { .type = NLA_U64 },
1717         [NBD_ATTR_SOCKETS]              =       { .type = NLA_NESTED},
1718         [NBD_ATTR_DEAD_CONN_TIMEOUT]    =       { .type = NLA_U64 },
1719         [NBD_ATTR_DEVICE_LIST]          =       { .type = NLA_NESTED},
1720 };
1721
1722 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1723         [NBD_SOCK_FD]                   =       { .type = NLA_U32 },
1724 };
1725
1726 /* We don't use this right now since we don't parse the incoming list, but we
1727  * still want it here so userspace knows what to expect.
1728  */
1729 static struct nla_policy __attribute__((unused))
1730 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1731         [NBD_DEVICE_INDEX]              =       { .type = NLA_U32 },
1732         [NBD_DEVICE_CONNECTED]          =       { .type = NLA_U8 },
1733 };
1734
1735 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1736 {
1737         struct nbd_device *nbd = NULL;
1738         struct nbd_config *config;
1739         int index = -1;
1740         int ret;
1741         bool put_dev = false;
1742
1743         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1744                 return -EPERM;
1745
1746         if (info->attrs[NBD_ATTR_INDEX])
1747                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1748         if (!info->attrs[NBD_ATTR_SOCKETS]) {
1749                 printk(KERN_ERR "nbd: must specify at least one socket\n");
1750                 return -EINVAL;
1751         }
1752         if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1753                 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1754                 return -EINVAL;
1755         }
1756 again:
1757         mutex_lock(&nbd_index_mutex);
1758         if (index == -1) {
1759                 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1760                 if (ret == 0) {
1761                         int new_index;
1762                         new_index = nbd_dev_add(-1);
1763                         if (new_index < 0) {
1764                                 mutex_unlock(&nbd_index_mutex);
1765                                 printk(KERN_ERR "nbd: failed to add new device\n");
1766                                 return new_index;
1767                         }
1768                         nbd = idr_find(&nbd_index_idr, new_index);
1769                 }
1770         } else {
1771                 nbd = idr_find(&nbd_index_idr, index);
1772                 if (!nbd) {
1773                         ret = nbd_dev_add(index);
1774                         if (ret < 0) {
1775                                 mutex_unlock(&nbd_index_mutex);
1776                                 printk(KERN_ERR "nbd: failed to add new device\n");
1777                                 return ret;
1778                         }
1779                         nbd = idr_find(&nbd_index_idr, index);
1780                 }
1781         }
1782         if (!nbd) {
1783                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1784                        index);
1785                 mutex_unlock(&nbd_index_mutex);
1786                 return -EINVAL;
1787         }
1788         if (!refcount_inc_not_zero(&nbd->refs)) {
1789                 mutex_unlock(&nbd_index_mutex);
1790                 if (index == -1)
1791                         goto again;
1792                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1793                        index);
1794                 return -EINVAL;
1795         }
1796         mutex_unlock(&nbd_index_mutex);
1797
1798         mutex_lock(&nbd->config_lock);
1799         if (refcount_read(&nbd->config_refs)) {
1800                 mutex_unlock(&nbd->config_lock);
1801                 nbd_put(nbd);
1802                 if (index == -1)
1803                         goto again;
1804                 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1805                 return -EBUSY;
1806         }
1807         if (WARN_ON(nbd->config)) {
1808                 mutex_unlock(&nbd->config_lock);
1809                 nbd_put(nbd);
1810                 return -EINVAL;
1811         }
1812         config = nbd_alloc_config();
1813         if (IS_ERR(config)) {
1814                 mutex_unlock(&nbd->config_lock);
1815                 nbd_put(nbd);
1816                 printk(KERN_ERR "nbd: couldn't allocate config\n");
1817                 return PTR_ERR(config);
1818         }
1819         nbd->config = config;
1820         refcount_set(&nbd->config_refs, 1);
1821         set_bit(NBD_BOUND, &config->runtime_flags);
1822
1823         if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1824                 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1825                 nbd_size_set(nbd, config->blksize,
1826                              div64_u64(bytes, config->blksize));
1827         }
1828         if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1829                 u64 bsize =
1830                         nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1831                 if (!bsize)
1832                         bsize = NBD_DEF_BLKSIZE;
1833                 if (!nbd_is_valid_blksize(bsize)) {
1834                         ret = -EINVAL;
1835                         goto out;
1836                 }
1837                 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1838         }
1839         if (info->attrs[NBD_ATTR_TIMEOUT]) {
1840                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1841                 nbd->tag_set.timeout = timeout * HZ;
1842                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1843         }
1844         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1845                 config->dead_conn_timeout =
1846                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1847                 config->dead_conn_timeout *= HZ;
1848         }
1849         if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1850                 config->flags =
1851                         nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1852         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1853                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1854                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1855                         set_bit(NBD_DESTROY_ON_DISCONNECT,
1856                                 &config->runtime_flags);
1857                         put_dev = true;
1858                 }
1859                 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1860                         set_bit(NBD_DISCONNECT_ON_CLOSE,
1861                                 &config->runtime_flags);
1862                 }
1863         }
1864
1865         if (info->attrs[NBD_ATTR_SOCKETS]) {
1866                 struct nlattr *attr;
1867                 int rem, fd;
1868
1869                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1870                                     rem) {
1871                         struct nlattr *socks[NBD_SOCK_MAX+1];
1872
1873                         if (nla_type(attr) != NBD_SOCK_ITEM) {
1874                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1875                                 ret = -EINVAL;
1876                                 goto out;
1877                         }
1878                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1879                                                nbd_sock_policy, info->extack);
1880                         if (ret != 0) {
1881                                 printk(KERN_ERR "nbd: error processing sock list\n");
1882                                 ret = -EINVAL;
1883                                 goto out;
1884                         }
1885                         if (!socks[NBD_SOCK_FD])
1886                                 continue;
1887                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1888                         ret = nbd_add_socket(nbd, fd, true);
1889                         if (ret)
1890                                 goto out;
1891                 }
1892         }
1893         ret = nbd_start_device(nbd);
1894 out:
1895         mutex_unlock(&nbd->config_lock);
1896         if (!ret) {
1897                 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1898                 refcount_inc(&nbd->config_refs);
1899                 nbd_connect_reply(info, nbd->index);
1900         }
1901         nbd_config_put(nbd);
1902         if (put_dev)
1903                 nbd_put(nbd);
1904         return ret;
1905 }
1906
1907 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1908 {
1909         mutex_lock(&nbd->config_lock);
1910         nbd_disconnect(nbd);
1911         mutex_unlock(&nbd->config_lock);
1912         /*
1913          * Make sure recv thread has finished, so it does not drop the last
1914          * config ref and try to destroy the workqueue from inside the work
1915          * queue.
1916          */
1917         flush_workqueue(nbd->recv_workq);
1918         if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1919                                &nbd->config->runtime_flags))
1920                 nbd_config_put(nbd);
1921 }
1922
1923 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1924 {
1925         struct nbd_device *nbd;
1926         int index;
1927
1928         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1929                 return -EPERM;
1930
1931         if (!info->attrs[NBD_ATTR_INDEX]) {
1932                 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1933                 return -EINVAL;
1934         }
1935         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1936         mutex_lock(&nbd_index_mutex);
1937         nbd = idr_find(&nbd_index_idr, index);
1938         if (!nbd) {
1939                 mutex_unlock(&nbd_index_mutex);
1940                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1941                        index);
1942                 return -EINVAL;
1943         }
1944         if (!refcount_inc_not_zero(&nbd->refs)) {
1945                 mutex_unlock(&nbd_index_mutex);
1946                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1947                        index);
1948                 return -EINVAL;
1949         }
1950         mutex_unlock(&nbd_index_mutex);
1951         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1952                 nbd_put(nbd);
1953                 return 0;
1954         }
1955         nbd_disconnect_and_put(nbd);
1956         nbd_config_put(nbd);
1957         nbd_put(nbd);
1958         return 0;
1959 }
1960
1961 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1962 {
1963         struct nbd_device *nbd = NULL;
1964         struct nbd_config *config;
1965         int index;
1966         int ret = 0;
1967         bool put_dev = false;
1968
1969         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1970                 return -EPERM;
1971
1972         if (!info->attrs[NBD_ATTR_INDEX]) {
1973                 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1974                 return -EINVAL;
1975         }
1976         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1977         mutex_lock(&nbd_index_mutex);
1978         nbd = idr_find(&nbd_index_idr, index);
1979         if (!nbd) {
1980                 mutex_unlock(&nbd_index_mutex);
1981                 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1982                        index);
1983                 return -EINVAL;
1984         }
1985         if (!refcount_inc_not_zero(&nbd->refs)) {
1986                 mutex_unlock(&nbd_index_mutex);
1987                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1988                        index);
1989                 return -EINVAL;
1990         }
1991         mutex_unlock(&nbd_index_mutex);
1992
1993         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1994                 dev_err(nbd_to_dev(nbd),
1995                         "not configured, cannot reconfigure\n");
1996                 nbd_put(nbd);
1997                 return -EINVAL;
1998         }
1999
2000         mutex_lock(&nbd->config_lock);
2001         config = nbd->config;
2002         if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
2003             !nbd->task_recv) {
2004                 dev_err(nbd_to_dev(nbd),
2005                         "not configured, cannot reconfigure\n");
2006                 ret = -EINVAL;
2007                 goto out;
2008         }
2009
2010         if (info->attrs[NBD_ATTR_TIMEOUT]) {
2011                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
2012                 nbd->tag_set.timeout = timeout * HZ;
2013                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
2014         }
2015         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2016                 config->dead_conn_timeout =
2017                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2018                 config->dead_conn_timeout *= HZ;
2019         }
2020         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2021                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2022                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2023                         if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2024                                               &config->runtime_flags))
2025                                 put_dev = true;
2026                 } else {
2027                         if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2028                                                &config->runtime_flags))
2029                                 refcount_inc(&nbd->refs);
2030                 }
2031
2032                 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2033                         set_bit(NBD_DISCONNECT_ON_CLOSE,
2034                                         &config->runtime_flags);
2035                 } else {
2036                         clear_bit(NBD_DISCONNECT_ON_CLOSE,
2037                                         &config->runtime_flags);
2038                 }
2039         }
2040
2041         if (info->attrs[NBD_ATTR_SOCKETS]) {
2042                 struct nlattr *attr;
2043                 int rem, fd;
2044
2045                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2046                                     rem) {
2047                         struct nlattr *socks[NBD_SOCK_MAX+1];
2048
2049                         if (nla_type(attr) != NBD_SOCK_ITEM) {
2050                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2051                                 ret = -EINVAL;
2052                                 goto out;
2053                         }
2054                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
2055                                                nbd_sock_policy, info->extack);
2056                         if (ret != 0) {
2057                                 printk(KERN_ERR "nbd: error processing sock list\n");
2058                                 ret = -EINVAL;
2059                                 goto out;
2060                         }
2061                         if (!socks[NBD_SOCK_FD])
2062                                 continue;
2063                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2064                         ret = nbd_reconnect_socket(nbd, fd);
2065                         if (ret) {
2066                                 if (ret == -ENOSPC)
2067                                         ret = 0;
2068                                 goto out;
2069                         }
2070                         dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2071                 }
2072         }
2073 out:
2074         mutex_unlock(&nbd->config_lock);
2075         nbd_config_put(nbd);
2076         nbd_put(nbd);
2077         if (put_dev)
2078                 nbd_put(nbd);
2079         return ret;
2080 }
2081
2082 static const struct genl_ops nbd_connect_genl_ops[] = {
2083         {
2084                 .cmd    = NBD_CMD_CONNECT,
2085                 .policy = nbd_attr_policy,
2086                 .doit   = nbd_genl_connect,
2087         },
2088         {
2089                 .cmd    = NBD_CMD_DISCONNECT,
2090                 .policy = nbd_attr_policy,
2091                 .doit   = nbd_genl_disconnect,
2092         },
2093         {
2094                 .cmd    = NBD_CMD_RECONFIGURE,
2095                 .policy = nbd_attr_policy,
2096                 .doit   = nbd_genl_reconfigure,
2097         },
2098         {
2099                 .cmd    = NBD_CMD_STATUS,
2100                 .policy = nbd_attr_policy,
2101                 .doit   = nbd_genl_status,
2102         },
2103 };
2104
2105 static const struct genl_multicast_group nbd_mcast_grps[] = {
2106         { .name = NBD_GENL_MCAST_GROUP_NAME, },
2107 };
2108
2109 static struct genl_family nbd_genl_family __ro_after_init = {
2110         .hdrsize        = 0,
2111         .name           = NBD_GENL_FAMILY_NAME,
2112         .version        = NBD_GENL_VERSION,
2113         .module         = THIS_MODULE,
2114         .ops            = nbd_connect_genl_ops,
2115         .n_ops          = ARRAY_SIZE(nbd_connect_genl_ops),
2116         .maxattr        = NBD_ATTR_MAX,
2117         .mcgrps         = nbd_mcast_grps,
2118         .n_mcgrps       = ARRAY_SIZE(nbd_mcast_grps),
2119 };
2120
2121 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2122 {
2123         struct nlattr *dev_opt;
2124         u8 connected = 0;
2125         int ret;
2126
2127         /* This is a little racey, but for status it's ok.  The
2128          * reason we don't take a ref here is because we can't
2129          * take a ref in the index == -1 case as we would need
2130          * to put under the nbd_index_mutex, which could
2131          * deadlock if we are configured to remove ourselves
2132          * once we're disconnected.
2133          */
2134         if (refcount_read(&nbd->config_refs))
2135                 connected = 1;
2136         dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
2137         if (!dev_opt)
2138                 return -EMSGSIZE;
2139         ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2140         if (ret)
2141                 return -EMSGSIZE;
2142         ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2143                          connected);
2144         if (ret)
2145                 return -EMSGSIZE;
2146         nla_nest_end(reply, dev_opt);
2147         return 0;
2148 }
2149
2150 static int status_cb(int id, void *ptr, void *data)
2151 {
2152         struct nbd_device *nbd = ptr;
2153         return populate_nbd_status(nbd, (struct sk_buff *)data);
2154 }
2155
2156 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2157 {
2158         struct nlattr *dev_list;
2159         struct sk_buff *reply;
2160         void *reply_head;
2161         size_t msg_size;
2162         int index = -1;
2163         int ret = -ENOMEM;
2164
2165         if (info->attrs[NBD_ATTR_INDEX])
2166                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2167
2168         mutex_lock(&nbd_index_mutex);
2169
2170         msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2171                                   nla_attr_size(sizeof(u8)));
2172         msg_size *= (index == -1) ? nbd_total_devices : 1;
2173
2174         reply = genlmsg_new(msg_size, GFP_KERNEL);
2175         if (!reply)
2176                 goto out;
2177         reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2178                                        NBD_CMD_STATUS);
2179         if (!reply_head) {
2180                 nlmsg_free(reply);
2181                 goto out;
2182         }
2183
2184         dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2185         if (index == -1) {
2186                 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2187                 if (ret) {
2188                         nlmsg_free(reply);
2189                         goto out;
2190                 }
2191         } else {
2192                 struct nbd_device *nbd;
2193                 nbd = idr_find(&nbd_index_idr, index);
2194                 if (nbd) {
2195                         ret = populate_nbd_status(nbd, reply);
2196                         if (ret) {
2197                                 nlmsg_free(reply);
2198                                 goto out;
2199                         }
2200                 }
2201         }
2202         nla_nest_end(reply, dev_list);
2203         genlmsg_end(reply, reply_head);
2204         genlmsg_reply(reply, info);
2205         ret = 0;
2206 out:
2207         mutex_unlock(&nbd_index_mutex);
2208         return ret;
2209 }
2210
2211 static void nbd_connect_reply(struct genl_info *info, int index)
2212 {
2213         struct sk_buff *skb;
2214         void *msg_head;
2215         int ret;
2216
2217         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2218         if (!skb)
2219                 return;
2220         msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2221                                      NBD_CMD_CONNECT);
2222         if (!msg_head) {
2223                 nlmsg_free(skb);
2224                 return;
2225         }
2226         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2227         if (ret) {
2228                 nlmsg_free(skb);
2229                 return;
2230         }
2231         genlmsg_end(skb, msg_head);
2232         genlmsg_reply(skb, info);
2233 }
2234
2235 static void nbd_mcast_index(int index)
2236 {
2237         struct sk_buff *skb;
2238         void *msg_head;
2239         int ret;
2240
2241         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2242         if (!skb)
2243                 return;
2244         msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2245                                      NBD_CMD_LINK_DEAD);
2246         if (!msg_head) {
2247                 nlmsg_free(skb);
2248                 return;
2249         }
2250         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2251         if (ret) {
2252                 nlmsg_free(skb);
2253                 return;
2254         }
2255         genlmsg_end(skb, msg_head);
2256         genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2257 }
2258
2259 static void nbd_dead_link_work(struct work_struct *work)
2260 {
2261         struct link_dead_args *args = container_of(work, struct link_dead_args,
2262                                                    work);
2263         nbd_mcast_index(args->index);
2264         kfree(args);
2265 }
2266
2267 static int __init nbd_init(void)
2268 {
2269         int i;
2270
2271         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2272
2273         if (max_part < 0) {
2274                 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2275                 return -EINVAL;
2276         }
2277
2278         part_shift = 0;
2279         if (max_part > 0) {
2280                 part_shift = fls(max_part);
2281
2282                 /*
2283                  * Adjust max_part according to part_shift as it is exported
2284                  * to user space so that user can know the max number of
2285                  * partition kernel should be able to manage.
2286                  *
2287                  * Note that -1 is required because partition 0 is reserved
2288                  * for the whole disk.
2289                  */
2290                 max_part = (1UL << part_shift) - 1;
2291         }
2292
2293         if ((1UL << part_shift) > DISK_MAX_PARTS)
2294                 return -EINVAL;
2295
2296         if (nbds_max > 1UL << (MINORBITS - part_shift))
2297                 return -EINVAL;
2298
2299         if (register_blkdev(NBD_MAJOR, "nbd"))
2300                 return -EIO;
2301
2302         if (genl_register_family(&nbd_genl_family)) {
2303                 unregister_blkdev(NBD_MAJOR, "nbd");
2304                 return -EINVAL;
2305         }
2306         nbd_dbg_init();
2307
2308         mutex_lock(&nbd_index_mutex);
2309         for (i = 0; i < nbds_max; i++)
2310                 nbd_dev_add(i);
2311         mutex_unlock(&nbd_index_mutex);
2312         return 0;
2313 }
2314
2315 static int nbd_exit_cb(int id, void *ptr, void *data)
2316 {
2317         struct list_head *list = (struct list_head *)data;
2318         struct nbd_device *nbd = ptr;
2319
2320         list_add_tail(&nbd->list, list);
2321         return 0;
2322 }
2323
2324 static void __exit nbd_cleanup(void)
2325 {
2326         struct nbd_device *nbd;
2327         LIST_HEAD(del_list);
2328
2329         /*
2330          * Unregister netlink interface prior to waiting
2331          * for the completion of netlink commands.
2332          */
2333         genl_unregister_family(&nbd_genl_family);
2334
2335         nbd_dbg_close();
2336
2337         mutex_lock(&nbd_index_mutex);
2338         idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2339         mutex_unlock(&nbd_index_mutex);
2340
2341         while (!list_empty(&del_list)) {
2342                 nbd = list_first_entry(&del_list, struct nbd_device, list);
2343                 list_del_init(&nbd->list);
2344                 if (refcount_read(&nbd->config_refs))
2345                         printk(KERN_ERR "nbd: possibly leaking nbd_config (ref %d)\n",
2346                                         refcount_read(&nbd->config_refs));
2347                 if (refcount_read(&nbd->refs) != 1)
2348                         printk(KERN_ERR "nbd: possibly leaking a device\n");
2349                 nbd_put(nbd);
2350         }
2351
2352         idr_destroy(&nbd_index_idr);
2353         unregister_blkdev(NBD_MAJOR, "nbd");
2354 }
2355
2356 module_init(nbd_init);
2357 module_exit(nbd_cleanup);
2358
2359 MODULE_DESCRIPTION("Network Block Device");
2360 MODULE_LICENSE("GPL");
2361
2362 module_param(nbds_max, int, 0444);
2363 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2364 module_param(max_part, int, 0444);
2365 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");