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