GNU Linux-libre 4.14.313-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 (!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 (!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, 0, GFP_KERNEL);
1634                 if (err >= 0)
1635                         index = err;
1636         }
1637         if (err < 0)
1638                 goto out_free_disk;
1639
1640         nbd->index = index;
1641         nbd->disk = disk;
1642         nbd->tag_set.ops = &nbd_mq_ops;
1643         nbd->tag_set.nr_hw_queues = 1;
1644         nbd->tag_set.queue_depth = 128;
1645         nbd->tag_set.numa_node = NUMA_NO_NODE;
1646         nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1647         nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1648                 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1649         nbd->tag_set.driver_data = nbd;
1650
1651         err = blk_mq_alloc_tag_set(&nbd->tag_set);
1652         if (err)
1653                 goto out_free_idr;
1654
1655         q = blk_mq_init_queue(&nbd->tag_set);
1656         if (IS_ERR(q)) {
1657                 err = PTR_ERR(q);
1658                 goto out_free_tags;
1659         }
1660         disk->queue = q;
1661
1662         /*
1663          * Tell the block layer that we are not a rotational device
1664          */
1665         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, disk->queue);
1666         queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, disk->queue);
1667         disk->queue->limits.discard_granularity = 512;
1668         blk_queue_max_discard_sectors(disk->queue, UINT_MAX);
1669         blk_queue_max_segment_size(disk->queue, UINT_MAX);
1670         blk_queue_max_segments(disk->queue, USHRT_MAX);
1671         blk_queue_max_hw_sectors(disk->queue, 65536);
1672         disk->queue->limits.max_sectors = 256;
1673
1674         mutex_init(&nbd->config_lock);
1675         refcount_set(&nbd->config_refs, 0);
1676         refcount_set(&nbd->refs, 1);
1677         INIT_LIST_HEAD(&nbd->list);
1678         disk->major = NBD_MAJOR;
1679         disk->first_minor = index << part_shift;
1680         disk->fops = &nbd_fops;
1681         disk->private_data = nbd;
1682         sprintf(disk->disk_name, "nbd%d", index);
1683         add_disk(disk);
1684         nbd_total_devices++;
1685         return index;
1686
1687 out_free_tags:
1688         blk_mq_free_tag_set(&nbd->tag_set);
1689 out_free_idr:
1690         idr_remove(&nbd_index_idr, index);
1691 out_free_disk:
1692         put_disk(disk);
1693 out_free_nbd:
1694         kfree(nbd);
1695 out:
1696         return err;
1697 }
1698
1699 static int find_free_cb(int id, void *ptr, void *data)
1700 {
1701         struct nbd_device *nbd = ptr;
1702         struct nbd_device **found = data;
1703
1704         if (!refcount_read(&nbd->config_refs)) {
1705                 *found = nbd;
1706                 return 1;
1707         }
1708         return 0;
1709 }
1710
1711 /* Netlink interface. */
1712 static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1713         [NBD_ATTR_INDEX]                =       { .type = NLA_U32 },
1714         [NBD_ATTR_SIZE_BYTES]           =       { .type = NLA_U64 },
1715         [NBD_ATTR_BLOCK_SIZE_BYTES]     =       { .type = NLA_U64 },
1716         [NBD_ATTR_TIMEOUT]              =       { .type = NLA_U64 },
1717         [NBD_ATTR_SERVER_FLAGS]         =       { .type = NLA_U64 },
1718         [NBD_ATTR_CLIENT_FLAGS]         =       { .type = NLA_U64 },
1719         [NBD_ATTR_SOCKETS]              =       { .type = NLA_NESTED},
1720         [NBD_ATTR_DEAD_CONN_TIMEOUT]    =       { .type = NLA_U64 },
1721         [NBD_ATTR_DEVICE_LIST]          =       { .type = NLA_NESTED},
1722 };
1723
1724 static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1725         [NBD_SOCK_FD]                   =       { .type = NLA_U32 },
1726 };
1727
1728 /* We don't use this right now since we don't parse the incoming list, but we
1729  * still want it here so userspace knows what to expect.
1730  */
1731 static struct nla_policy __attribute__((unused))
1732 nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1733         [NBD_DEVICE_INDEX]              =       { .type = NLA_U32 },
1734         [NBD_DEVICE_CONNECTED]          =       { .type = NLA_U8 },
1735 };
1736
1737 static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1738 {
1739         struct nbd_device *nbd = NULL;
1740         struct nbd_config *config;
1741         int index = -1;
1742         int ret;
1743         bool put_dev = false;
1744
1745         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1746                 return -EPERM;
1747
1748         if (info->attrs[NBD_ATTR_INDEX])
1749                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1750         if (!info->attrs[NBD_ATTR_SOCKETS]) {
1751                 printk(KERN_ERR "nbd: must specify at least one socket\n");
1752                 return -EINVAL;
1753         }
1754         if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1755                 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1756                 return -EINVAL;
1757         }
1758 again:
1759         mutex_lock(&nbd_index_mutex);
1760         if (index == -1) {
1761                 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1762                 if (ret == 0) {
1763                         int new_index;
1764                         new_index = nbd_dev_add(-1);
1765                         if (new_index < 0) {
1766                                 mutex_unlock(&nbd_index_mutex);
1767                                 printk(KERN_ERR "nbd: failed to add new device\n");
1768                                 return new_index;
1769                         }
1770                         nbd = idr_find(&nbd_index_idr, new_index);
1771                 }
1772         } else {
1773                 nbd = idr_find(&nbd_index_idr, index);
1774                 if (!nbd) {
1775                         ret = nbd_dev_add(index);
1776                         if (ret < 0) {
1777                                 mutex_unlock(&nbd_index_mutex);
1778                                 printk(KERN_ERR "nbd: failed to add new device\n");
1779                                 return ret;
1780                         }
1781                         nbd = idr_find(&nbd_index_idr, index);
1782                 }
1783         }
1784         if (!nbd) {
1785                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1786                        index);
1787                 mutex_unlock(&nbd_index_mutex);
1788                 return -EINVAL;
1789         }
1790         if (!refcount_inc_not_zero(&nbd->refs)) {
1791                 mutex_unlock(&nbd_index_mutex);
1792                 if (index == -1)
1793                         goto again;
1794                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1795                        index);
1796                 return -EINVAL;
1797         }
1798         mutex_unlock(&nbd_index_mutex);
1799
1800         mutex_lock(&nbd->config_lock);
1801         if (refcount_read(&nbd->config_refs)) {
1802                 mutex_unlock(&nbd->config_lock);
1803                 nbd_put(nbd);
1804                 if (index == -1)
1805                         goto again;
1806                 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1807                 return -EBUSY;
1808         }
1809         if (WARN_ON(nbd->config)) {
1810                 mutex_unlock(&nbd->config_lock);
1811                 nbd_put(nbd);
1812                 return -EINVAL;
1813         }
1814         config = nbd_alloc_config();
1815         if (IS_ERR(config)) {
1816                 mutex_unlock(&nbd->config_lock);
1817                 nbd_put(nbd);
1818                 printk(KERN_ERR "nbd: couldn't allocate config\n");
1819                 return PTR_ERR(config);
1820         }
1821         nbd->config = config;
1822         refcount_set(&nbd->config_refs, 1);
1823         set_bit(NBD_BOUND, &config->runtime_flags);
1824
1825         if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1826                 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1827                 nbd_size_set(nbd, config->blksize,
1828                              div64_u64(bytes, config->blksize));
1829         }
1830         if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1831                 u64 bsize =
1832                         nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1833                 if (!bsize)
1834                         bsize = NBD_DEF_BLKSIZE;
1835                 if (!nbd_is_valid_blksize(bsize)) {
1836                         ret = -EINVAL;
1837                         goto out;
1838                 }
1839                 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1840         }
1841         if (info->attrs[NBD_ATTR_TIMEOUT]) {
1842                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1843                 nbd->tag_set.timeout = timeout * HZ;
1844                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1845         }
1846         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1847                 config->dead_conn_timeout =
1848                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1849                 config->dead_conn_timeout *= HZ;
1850         }
1851         if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1852                 config->flags =
1853                         nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
1854         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1855                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1856                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1857                         set_bit(NBD_DESTROY_ON_DISCONNECT,
1858                                 &config->runtime_flags);
1859                         put_dev = true;
1860                 }
1861                 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
1862                         set_bit(NBD_DISCONNECT_ON_CLOSE,
1863                                 &config->runtime_flags);
1864                 }
1865         }
1866
1867         if (info->attrs[NBD_ATTR_SOCKETS]) {
1868                 struct nlattr *attr;
1869                 int rem, fd;
1870
1871                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1872                                     rem) {
1873                         struct nlattr *socks[NBD_SOCK_MAX+1];
1874
1875                         if (nla_type(attr) != NBD_SOCK_ITEM) {
1876                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1877                                 ret = -EINVAL;
1878                                 goto out;
1879                         }
1880                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
1881                                                nbd_sock_policy, info->extack);
1882                         if (ret != 0) {
1883                                 printk(KERN_ERR "nbd: error processing sock list\n");
1884                                 ret = -EINVAL;
1885                                 goto out;
1886                         }
1887                         if (!socks[NBD_SOCK_FD])
1888                                 continue;
1889                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1890                         ret = nbd_add_socket(nbd, fd, true);
1891                         if (ret)
1892                                 goto out;
1893                 }
1894         }
1895         ret = nbd_start_device(nbd);
1896 out:
1897         mutex_unlock(&nbd->config_lock);
1898         if (!ret) {
1899                 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1900                 refcount_inc(&nbd->config_refs);
1901                 nbd_connect_reply(info, nbd->index);
1902         }
1903         nbd_config_put(nbd);
1904         if (put_dev)
1905                 nbd_put(nbd);
1906         return ret;
1907 }
1908
1909 static void nbd_disconnect_and_put(struct nbd_device *nbd)
1910 {
1911         mutex_lock(&nbd->config_lock);
1912         nbd_disconnect(nbd);
1913         mutex_unlock(&nbd->config_lock);
1914         /*
1915          * Make sure recv thread has finished, so it does not drop the last
1916          * config ref and try to destroy the workqueue from inside the work
1917          * queue.
1918          */
1919         flush_workqueue(nbd->recv_workq);
1920         if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1921                                &nbd->config->runtime_flags))
1922                 nbd_config_put(nbd);
1923 }
1924
1925 static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1926 {
1927         struct nbd_device *nbd;
1928         int index;
1929
1930         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1931                 return -EPERM;
1932
1933         if (!info->attrs[NBD_ATTR_INDEX]) {
1934                 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1935                 return -EINVAL;
1936         }
1937         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1938         mutex_lock(&nbd_index_mutex);
1939         nbd = idr_find(&nbd_index_idr, index);
1940         if (!nbd) {
1941                 mutex_unlock(&nbd_index_mutex);
1942                 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1943                        index);
1944                 return -EINVAL;
1945         }
1946         if (!refcount_inc_not_zero(&nbd->refs)) {
1947                 mutex_unlock(&nbd_index_mutex);
1948                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1949                        index);
1950                 return -EINVAL;
1951         }
1952         mutex_unlock(&nbd_index_mutex);
1953         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1954                 nbd_put(nbd);
1955                 return 0;
1956         }
1957         nbd_disconnect_and_put(nbd);
1958         nbd_config_put(nbd);
1959         nbd_put(nbd);
1960         return 0;
1961 }
1962
1963 static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1964 {
1965         struct nbd_device *nbd = NULL;
1966         struct nbd_config *config;
1967         int index;
1968         int ret = 0;
1969         bool put_dev = false;
1970
1971         if (!netlink_capable(skb, CAP_SYS_ADMIN))
1972                 return -EPERM;
1973
1974         if (!info->attrs[NBD_ATTR_INDEX]) {
1975                 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1976                 return -EINVAL;
1977         }
1978         index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1979         mutex_lock(&nbd_index_mutex);
1980         nbd = idr_find(&nbd_index_idr, index);
1981         if (!nbd) {
1982                 mutex_unlock(&nbd_index_mutex);
1983                 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1984                        index);
1985                 return -EINVAL;
1986         }
1987         if (!refcount_inc_not_zero(&nbd->refs)) {
1988                 mutex_unlock(&nbd_index_mutex);
1989                 printk(KERN_ERR "nbd: device at index %d is going down\n",
1990                        index);
1991                 return -EINVAL;
1992         }
1993         mutex_unlock(&nbd_index_mutex);
1994
1995         if (!refcount_inc_not_zero(&nbd->config_refs)) {
1996                 dev_err(nbd_to_dev(nbd),
1997                         "not configured, cannot reconfigure\n");
1998                 nbd_put(nbd);
1999                 return -EINVAL;
2000         }
2001
2002         mutex_lock(&nbd->config_lock);
2003         config = nbd->config;
2004         if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
2005             !nbd->task_recv) {
2006                 dev_err(nbd_to_dev(nbd),
2007                         "not configured, cannot reconfigure\n");
2008                 ret = -EINVAL;
2009                 goto out;
2010         }
2011
2012         if (info->attrs[NBD_ATTR_TIMEOUT]) {
2013                 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
2014                 nbd->tag_set.timeout = timeout * HZ;
2015                 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
2016         }
2017         if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
2018                 config->dead_conn_timeout =
2019                         nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
2020                 config->dead_conn_timeout *= HZ;
2021         }
2022         if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
2023                 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
2024                 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
2025                         if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
2026                                               &config->runtime_flags))
2027                                 put_dev = true;
2028                 } else {
2029                         if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
2030                                                &config->runtime_flags))
2031                                 refcount_inc(&nbd->refs);
2032                 }
2033
2034                 if (flags & NBD_CFLAG_DISCONNECT_ON_CLOSE) {
2035                         set_bit(NBD_DISCONNECT_ON_CLOSE,
2036                                         &config->runtime_flags);
2037                 } else {
2038                         clear_bit(NBD_DISCONNECT_ON_CLOSE,
2039                                         &config->runtime_flags);
2040                 }
2041         }
2042
2043         if (info->attrs[NBD_ATTR_SOCKETS]) {
2044                 struct nlattr *attr;
2045                 int rem, fd;
2046
2047                 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
2048                                     rem) {
2049                         struct nlattr *socks[NBD_SOCK_MAX+1];
2050
2051                         if (nla_type(attr) != NBD_SOCK_ITEM) {
2052                                 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
2053                                 ret = -EINVAL;
2054                                 goto out;
2055                         }
2056                         ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
2057                                                nbd_sock_policy, info->extack);
2058                         if (ret != 0) {
2059                                 printk(KERN_ERR "nbd: error processing sock list\n");
2060                                 ret = -EINVAL;
2061                                 goto out;
2062                         }
2063                         if (!socks[NBD_SOCK_FD])
2064                                 continue;
2065                         fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
2066                         ret = nbd_reconnect_socket(nbd, fd);
2067                         if (ret) {
2068                                 if (ret == -ENOSPC)
2069                                         ret = 0;
2070                                 goto out;
2071                         }
2072                         dev_info(nbd_to_dev(nbd), "reconnected socket\n");
2073                 }
2074         }
2075 out:
2076         mutex_unlock(&nbd->config_lock);
2077         nbd_config_put(nbd);
2078         nbd_put(nbd);
2079         if (put_dev)
2080                 nbd_put(nbd);
2081         return ret;
2082 }
2083
2084 static const struct genl_ops nbd_connect_genl_ops[] = {
2085         {
2086                 .cmd    = NBD_CMD_CONNECT,
2087                 .policy = nbd_attr_policy,
2088                 .doit   = nbd_genl_connect,
2089         },
2090         {
2091                 .cmd    = NBD_CMD_DISCONNECT,
2092                 .policy = nbd_attr_policy,
2093                 .doit   = nbd_genl_disconnect,
2094         },
2095         {
2096                 .cmd    = NBD_CMD_RECONFIGURE,
2097                 .policy = nbd_attr_policy,
2098                 .doit   = nbd_genl_reconfigure,
2099         },
2100         {
2101                 .cmd    = NBD_CMD_STATUS,
2102                 .policy = nbd_attr_policy,
2103                 .doit   = nbd_genl_status,
2104         },
2105 };
2106
2107 static const struct genl_multicast_group nbd_mcast_grps[] = {
2108         { .name = NBD_GENL_MCAST_GROUP_NAME, },
2109 };
2110
2111 static struct genl_family nbd_genl_family __ro_after_init = {
2112         .hdrsize        = 0,
2113         .name           = NBD_GENL_FAMILY_NAME,
2114         .version        = NBD_GENL_VERSION,
2115         .module         = THIS_MODULE,
2116         .ops            = nbd_connect_genl_ops,
2117         .n_ops          = ARRAY_SIZE(nbd_connect_genl_ops),
2118         .maxattr        = NBD_ATTR_MAX,
2119         .mcgrps         = nbd_mcast_grps,
2120         .n_mcgrps       = ARRAY_SIZE(nbd_mcast_grps),
2121 };
2122
2123 static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
2124 {
2125         struct nlattr *dev_opt;
2126         u8 connected = 0;
2127         int ret;
2128
2129         /* This is a little racey, but for status it's ok.  The
2130          * reason we don't take a ref here is because we can't
2131          * take a ref in the index == -1 case as we would need
2132          * to put under the nbd_index_mutex, which could
2133          * deadlock if we are configured to remove ourselves
2134          * once we're disconnected.
2135          */
2136         if (refcount_read(&nbd->config_refs))
2137                 connected = 1;
2138         dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
2139         if (!dev_opt)
2140                 return -EMSGSIZE;
2141         ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
2142         if (ret)
2143                 return -EMSGSIZE;
2144         ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
2145                          connected);
2146         if (ret)
2147                 return -EMSGSIZE;
2148         nla_nest_end(reply, dev_opt);
2149         return 0;
2150 }
2151
2152 static int status_cb(int id, void *ptr, void *data)
2153 {
2154         struct nbd_device *nbd = ptr;
2155         return populate_nbd_status(nbd, (struct sk_buff *)data);
2156 }
2157
2158 static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
2159 {
2160         struct nlattr *dev_list;
2161         struct sk_buff *reply;
2162         void *reply_head;
2163         size_t msg_size;
2164         int index = -1;
2165         int ret = -ENOMEM;
2166
2167         if (info->attrs[NBD_ATTR_INDEX])
2168                 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
2169
2170         mutex_lock(&nbd_index_mutex);
2171
2172         msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
2173                                   nla_attr_size(sizeof(u8)));
2174         msg_size *= (index == -1) ? nbd_total_devices : 1;
2175
2176         reply = genlmsg_new(msg_size, GFP_KERNEL);
2177         if (!reply)
2178                 goto out;
2179         reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
2180                                        NBD_CMD_STATUS);
2181         if (!reply_head) {
2182                 nlmsg_free(reply);
2183                 goto out;
2184         }
2185
2186         dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2187         if (index == -1) {
2188                 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2189                 if (ret) {
2190                         nlmsg_free(reply);
2191                         goto out;
2192                 }
2193         } else {
2194                 struct nbd_device *nbd;
2195                 nbd = idr_find(&nbd_index_idr, index);
2196                 if (nbd) {
2197                         ret = populate_nbd_status(nbd, reply);
2198                         if (ret) {
2199                                 nlmsg_free(reply);
2200                                 goto out;
2201                         }
2202                 }
2203         }
2204         nla_nest_end(reply, dev_list);
2205         genlmsg_end(reply, reply_head);
2206         genlmsg_reply(reply, info);
2207         ret = 0;
2208 out:
2209         mutex_unlock(&nbd_index_mutex);
2210         return ret;
2211 }
2212
2213 static void nbd_connect_reply(struct genl_info *info, int index)
2214 {
2215         struct sk_buff *skb;
2216         void *msg_head;
2217         int ret;
2218
2219         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2220         if (!skb)
2221                 return;
2222         msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2223                                      NBD_CMD_CONNECT);
2224         if (!msg_head) {
2225                 nlmsg_free(skb);
2226                 return;
2227         }
2228         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2229         if (ret) {
2230                 nlmsg_free(skb);
2231                 return;
2232         }
2233         genlmsg_end(skb, msg_head);
2234         genlmsg_reply(skb, info);
2235 }
2236
2237 static void nbd_mcast_index(int index)
2238 {
2239         struct sk_buff *skb;
2240         void *msg_head;
2241         int ret;
2242
2243         skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2244         if (!skb)
2245                 return;
2246         msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2247                                      NBD_CMD_LINK_DEAD);
2248         if (!msg_head) {
2249                 nlmsg_free(skb);
2250                 return;
2251         }
2252         ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2253         if (ret) {
2254                 nlmsg_free(skb);
2255                 return;
2256         }
2257         genlmsg_end(skb, msg_head);
2258         genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2259 }
2260
2261 static void nbd_dead_link_work(struct work_struct *work)
2262 {
2263         struct link_dead_args *args = container_of(work, struct link_dead_args,
2264                                                    work);
2265         nbd_mcast_index(args->index);
2266         kfree(args);
2267 }
2268
2269 static int __init nbd_init(void)
2270 {
2271         int i;
2272
2273         BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
2274
2275         if (max_part < 0) {
2276                 printk(KERN_ERR "nbd: max_part must be >= 0\n");
2277                 return -EINVAL;
2278         }
2279
2280         part_shift = 0;
2281         if (max_part > 0) {
2282                 part_shift = fls(max_part);
2283
2284                 /*
2285                  * Adjust max_part according to part_shift as it is exported
2286                  * to user space so that user can know the max number of
2287                  * partition kernel should be able to manage.
2288                  *
2289                  * Note that -1 is required because partition 0 is reserved
2290                  * for the whole disk.
2291                  */
2292                 max_part = (1UL << part_shift) - 1;
2293         }
2294
2295         if ((1UL << part_shift) > DISK_MAX_PARTS)
2296                 return -EINVAL;
2297
2298         if (nbds_max > 1UL << (MINORBITS - part_shift))
2299                 return -EINVAL;
2300
2301         if (register_blkdev(NBD_MAJOR, "nbd"))
2302                 return -EIO;
2303
2304         if (genl_register_family(&nbd_genl_family)) {
2305                 unregister_blkdev(NBD_MAJOR, "nbd");
2306                 return -EINVAL;
2307         }
2308         nbd_dbg_init();
2309
2310         mutex_lock(&nbd_index_mutex);
2311         for (i = 0; i < nbds_max; i++)
2312                 nbd_dev_add(i);
2313         mutex_unlock(&nbd_index_mutex);
2314         return 0;
2315 }
2316
2317 static int nbd_exit_cb(int id, void *ptr, void *data)
2318 {
2319         struct list_head *list = (struct list_head *)data;
2320         struct nbd_device *nbd = ptr;
2321
2322         list_add_tail(&nbd->list, list);
2323         return 0;
2324 }
2325
2326 static void __exit nbd_cleanup(void)
2327 {
2328         struct nbd_device *nbd;
2329         LIST_HEAD(del_list);
2330
2331         /*
2332          * Unregister netlink interface prior to waiting
2333          * for the completion of netlink commands.
2334          */
2335         genl_unregister_family(&nbd_genl_family);
2336
2337         nbd_dbg_close();
2338
2339         mutex_lock(&nbd_index_mutex);
2340         idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2341         mutex_unlock(&nbd_index_mutex);
2342
2343         while (!list_empty(&del_list)) {
2344                 nbd = list_first_entry(&del_list, struct nbd_device, list);
2345                 list_del_init(&nbd->list);
2346                 if (refcount_read(&nbd->config_refs))
2347                         printk(KERN_ERR "nbd: possibly leaking nbd_config (ref %d)\n",
2348                                         refcount_read(&nbd->config_refs));
2349                 if (refcount_read(&nbd->refs) != 1)
2350                         printk(KERN_ERR "nbd: possibly leaking a device\n");
2351                 nbd_put(nbd);
2352         }
2353
2354         idr_destroy(&nbd_index_idr);
2355         unregister_blkdev(NBD_MAJOR, "nbd");
2356 }
2357
2358 module_init(nbd_init);
2359 module_exit(nbd_cleanup);
2360
2361 MODULE_DESCRIPTION("Network Block Device");
2362 MODULE_LICENSE("GPL");
2363
2364 module_param(nbds_max, int, 0444);
2365 MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2366 module_param(max_part, int, 0444);
2367 MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");