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