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