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