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