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