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