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