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