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