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