OSDN Git Service

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