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