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