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