]> git.proxmox.com Git - mirror_ubuntu-jammy-kernel.git/blame - drivers/block/nbd.c
blk-mq: Remove generation seqeunce
[mirror_ubuntu-jammy-kernel.git] / drivers / block / nbd.c
CommitLineData
1da177e4
LT
1/*
2 * Network block device - make block devices work over TCP
3 *
4 * Note that you can not swap over this thing, yet. Seems to work but
5 * deadlocks sometimes - you can not swap over TCP in general.
6 *
a2531293 7 * Copyright 1997-2000, 2008 Pavel Machek <pavel@ucw.cz>
1da177e4
LT
8 * Parts copyright 2001 Steven Whitehouse <steve@chygwyn.com>
9 *
dbf492d6 10 * This file is released under GPLv2 or later.
1da177e4 11 *
dbf492d6 12 * (part of code stolen from loop.c)
1da177e4
LT
13 */
14
15#include <linux/major.h>
16
17#include <linux/blkdev.h>
18#include <linux/module.h>
19#include <linux/init.h>
20#include <linux/sched.h>
f1083048 21#include <linux/sched/mm.h>
1da177e4
LT
22#include <linux/fs.h>
23#include <linux/bio.h>
24#include <linux/stat.h>
25#include <linux/errno.h>
26#include <linux/file.h>
27#include <linux/ioctl.h>
2a48fc0a 28#include <linux/mutex.h>
4b2f0260
HX
29#include <linux/compiler.h>
30#include <linux/err.h>
31#include <linux/kernel.h>
5a0e3ad6 32#include <linux/slab.h>
1da177e4 33#include <net/sock.h>
91cf45f0 34#include <linux/net.h>
48cf6061 35#include <linux/kthread.h>
b9c495bb 36#include <linux/types.h>
30d53d9c 37#include <linux/debugfs.h>
fd8383fd 38#include <linux/blk-mq.h>
1da177e4 39
7c0f6ba6 40#include <linux/uaccess.h>
1da177e4
LT
41#include <asm/types.h>
42
43#include <linux/nbd.h>
e46c7287
JB
44#include <linux/nbd-netlink.h>
45#include <net/genetlink.h>
1da177e4 46
b0d9111a
JB
47static DEFINE_IDR(nbd_index_idr);
48static DEFINE_MUTEX(nbd_index_mutex);
47d902b9 49static int nbd_total_devices = 0;
b0d9111a 50
9561a7ad
JB
51struct nbd_sock {
52 struct socket *sock;
53 struct mutex tx_lock;
9dd5d3ab
JB
54 struct request *pending;
55 int sent;
f3733247
JB
56 bool dead;
57 int fallback_index;
799f9a38 58 int cookie;
9561a7ad
JB
59};
60
5ea8d108
JB
61struct recv_thread_args {
62 struct work_struct work;
63 struct nbd_device *nbd;
64 int index;
65};
66
799f9a38
JB
67struct link_dead_args {
68 struct work_struct work;
69 int index;
70};
71
9b4a6ba9
JB
72#define NBD_TIMEDOUT 0
73#define NBD_DISCONNECT_REQUESTED 1
9561a7ad 74#define NBD_DISCONNECTED 2
5ea8d108 75#define NBD_HAS_PID_FILE 3
e46c7287
JB
76#define NBD_HAS_CONFIG_REF 4
77#define NBD_BOUND 5
a2c97909 78#define NBD_DESTROY_ON_DISCONNECT 6
9b4a6ba9 79
5ea8d108 80struct nbd_config {
22d109c1 81 u32 flags;
9b4a6ba9 82 unsigned long runtime_flags;
560bc4b3 83 u64 dead_conn_timeout;
13e71d69 84
5ea8d108 85 struct nbd_sock **socks;
9561a7ad 86 int num_connections;
560bc4b3
JB
87 atomic_t live_connections;
88 wait_queue_head_t conn_wait;
5ea8d108 89
9561a7ad
JB
90 atomic_t recv_threads;
91 wait_queue_head_t recv_wq;
ef77b515 92 loff_t blksize;
b9c495bb 93 loff_t bytesize;
30d53d9c
MP
94#if IS_ENABLED(CONFIG_DEBUG_FS)
95 struct dentry *dbg_dir;
96#endif
13e71d69
MP
97};
98
5ea8d108
JB
99struct nbd_device {
100 struct blk_mq_tag_set tag_set;
101
e46c7287 102 int index;
5ea8d108 103 refcount_t config_refs;
c6a4759e 104 refcount_t refs;
5ea8d108
JB
105 struct nbd_config *config;
106 struct mutex config_lock;
107 struct gendisk *disk;
108
c6a4759e 109 struct list_head list;
5ea8d108
JB
110 struct task_struct *task_recv;
111 struct task_struct *task_setup;
112};
113
fd8383fd
JB
114struct nbd_cmd {
115 struct nbd_device *nbd;
f3733247 116 int index;
799f9a38 117 int cookie;
9561a7ad 118 struct completion send_complete;
2a842aca 119 blk_status_t status;
fd8383fd
JB
120};
121
30d53d9c
MP
122#if IS_ENABLED(CONFIG_DEBUG_FS)
123static struct dentry *nbd_dbg_dir;
124#endif
125
126#define nbd_name(nbd) ((nbd)->disk->disk_name)
127
f4507164 128#define NBD_MAGIC 0x68797548
1da177e4 129
9c7a4169 130static unsigned int nbds_max = 16;
7a8362a0 131static int max_part = 16;
124d6db0 132static struct workqueue_struct *recv_workqueue;
b0d9111a 133static int part_shift;
1da177e4 134
9442b739
JB
135static int nbd_dev_dbg_init(struct nbd_device *nbd);
136static void nbd_dev_dbg_close(struct nbd_device *nbd);
5ea8d108 137static void nbd_config_put(struct nbd_device *nbd);
e46c7287 138static void nbd_connect_reply(struct genl_info *info, int index);
47d902b9 139static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info);
799f9a38 140static void nbd_dead_link_work(struct work_struct *work);
9442b739 141
d18509f5 142static inline struct device *nbd_to_dev(struct nbd_device *nbd)
1da177e4 143{
d18509f5 144 return disk_to_dev(nbd->disk);
1da177e4
LT
145}
146
147static const char *nbdcmd_to_ascii(int cmd)
148{
149 switch (cmd) {
150 case NBD_CMD_READ: return "read";
151 case NBD_CMD_WRITE: return "write";
152 case NBD_CMD_DISC: return "disconnect";
75f187ab 153 case NBD_CMD_FLUSH: return "flush";
a336d298 154 case NBD_CMD_TRIM: return "trim/discard";
1da177e4
LT
155 }
156 return "invalid";
157}
1da177e4 158
5ea8d108
JB
159static ssize_t pid_show(struct device *dev,
160 struct device_attribute *attr, char *buf)
161{
162 struct gendisk *disk = dev_to_disk(dev);
163 struct nbd_device *nbd = (struct nbd_device *)disk->private_data;
164
165 return sprintf(buf, "%d\n", task_pid_nr(nbd->task_recv));
166}
167
dfbde552 168static const struct device_attribute pid_attr = {
5657a819 169 .attr = { .name = "pid", .mode = 0444},
5ea8d108
JB
170 .show = pid_show,
171};
172
c6a4759e
JB
173static void nbd_dev_remove(struct nbd_device *nbd)
174{
175 struct gendisk *disk = nbd->disk;
8364da47
JB
176 struct request_queue *q;
177
c6a4759e 178 if (disk) {
8364da47 179 q = disk->queue;
c6a4759e 180 del_gendisk(disk);
8364da47 181 blk_cleanup_queue(q);
c6a4759e 182 blk_mq_free_tag_set(&nbd->tag_set);
a2c97909 183 disk->private_data = NULL;
c6a4759e
JB
184 put_disk(disk);
185 }
186 kfree(nbd);
187}
188
189static void nbd_put(struct nbd_device *nbd)
190{
191 if (refcount_dec_and_mutex_lock(&nbd->refs,
192 &nbd_index_mutex)) {
193 idr_remove(&nbd_index_idr, nbd->index);
194 mutex_unlock(&nbd_index_mutex);
195 nbd_dev_remove(nbd);
196 }
197}
198
799f9a38
JB
199static int nbd_disconnected(struct nbd_config *config)
200{
201 return test_bit(NBD_DISCONNECTED, &config->runtime_flags) ||
202 test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
203}
204
205static void nbd_mark_nsock_dead(struct nbd_device *nbd, struct nbd_sock *nsock,
206 int notify)
f3733247 207{
799f9a38
JB
208 if (!nsock->dead && notify && !nbd_disconnected(nbd->config)) {
209 struct link_dead_args *args;
210 args = kmalloc(sizeof(struct link_dead_args), GFP_NOIO);
211 if (args) {
212 INIT_WORK(&args->work, nbd_dead_link_work);
213 args->index = nbd->index;
214 queue_work(system_wq, &args->work);
215 }
216 }
560bc4b3 217 if (!nsock->dead) {
f3733247 218 kernel_sock_shutdown(nsock->sock, SHUT_RDWR);
560bc4b3
JB
219 atomic_dec(&nbd->config->live_connections);
220 }
f3733247
JB
221 nsock->dead = true;
222 nsock->pending = NULL;
223 nsock->sent = 0;
224}
225
29eaadc0 226static void nbd_size_clear(struct nbd_device *nbd)
37091fdd 227{
5ea8d108 228 if (nbd->config->bytesize) {
5ea8d108
JB
229 set_capacity(nbd->disk, 0);
230 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
231 }
37091fdd
MP
232}
233
29eaadc0 234static void nbd_size_update(struct nbd_device *nbd)
37091fdd 235{
5ea8d108 236 struct nbd_config *config = nbd->config;
9e2b1967
JB
237 struct block_device *bdev = bdget_disk(nbd->disk, 0);
238
6df133a1
JB
239 if (config->flags & NBD_FLAG_SEND_TRIM) {
240 nbd->disk->queue->limits.discard_granularity = config->blksize;
241 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
242 }
5ea8d108
JB
243 blk_queue_logical_block_size(nbd->disk->queue, config->blksize);
244 blk_queue_physical_block_size(nbd->disk->queue, config->blksize);
5ea8d108 245 set_capacity(nbd->disk, config->bytesize >> 9);
9e2b1967
JB
246 if (bdev) {
247 if (bdev->bd_disk)
248 bd_set_size(bdev, config->bytesize);
249 else
250 bdev->bd_invalidated = 1;
251 bdput(bdev);
252 }
37091fdd
MP
253 kobject_uevent(&nbd_to_dev(nbd)->kobj, KOBJ_CHANGE);
254}
255
29eaadc0
JB
256static void nbd_size_set(struct nbd_device *nbd, loff_t blocksize,
257 loff_t nr_blocks)
37091fdd 258{
5ea8d108
JB
259 struct nbd_config *config = nbd->config;
260 config->blksize = blocksize;
261 config->bytesize = blocksize * nr_blocks;
c3f7c939
JB
262 if (nbd->task_recv != NULL)
263 nbd_size_update(nbd);
37091fdd
MP
264}
265
1e388ae0 266static void nbd_complete_rq(struct request *req)
1da177e4 267{
1e388ae0 268 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
1da177e4 269
1e388ae0
CH
270 dev_dbg(nbd_to_dev(cmd->nbd), "request %p: %s\n", cmd,
271 cmd->status ? "failed" : "done");
1da177e4 272
1e388ae0 273 blk_mq_end_request(req, cmd->status);
1da177e4
LT
274}
275
e018e757
MP
276/*
277 * Forcibly shutdown the socket causing all listeners to error
278 */
36e47bee 279static void sock_shutdown(struct nbd_device *nbd)
7fdfd406 280{
5ea8d108 281 struct nbd_config *config = nbd->config;
9561a7ad 282 int i;
23272a67 283
5ea8d108 284 if (config->num_connections == 0)
9561a7ad 285 return;
5ea8d108 286 if (test_and_set_bit(NBD_DISCONNECTED, &config->runtime_flags))
260bbce4 287 return;
23272a67 288
5ea8d108
JB
289 for (i = 0; i < config->num_connections; i++) {
290 struct nbd_sock *nsock = config->socks[i];
9561a7ad 291 mutex_lock(&nsock->tx_lock);
799f9a38 292 nbd_mark_nsock_dead(nbd, nsock, 0);
9561a7ad
JB
293 mutex_unlock(&nsock->tx_lock);
294 }
295 dev_warn(disk_to_dev(nbd->disk), "shutting down sockets\n");
7fdfd406
PC
296}
297
0eadf37a
JB
298static enum blk_eh_timer_return nbd_xmit_timeout(struct request *req,
299 bool reserved)
7fdfd406 300{
0eadf37a
JB
301 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(req);
302 struct nbd_device *nbd = cmd->nbd;
5ea8d108
JB
303 struct nbd_config *config;
304
305 if (!refcount_inc_not_zero(&nbd->config_refs)) {
2a842aca 306 cmd->status = BLK_STS_TIMEOUT;
5ea8d108
JB
307 return BLK_EH_HANDLED;
308 }
5ea8d108 309 config = nbd->config;
dcc909d9 310
5ea8d108 311 if (config->num_connections > 1) {
f3733247
JB
312 dev_err_ratelimited(nbd_to_dev(nbd),
313 "Connection timed out, retrying\n");
f3733247
JB
314 /*
315 * Hooray we have more connections, requeue this IO, the submit
316 * path will put it on a real connection.
317 */
5ea8d108
JB
318 if (config->socks && config->num_connections > 1) {
319 if (cmd->index < config->num_connections) {
f3733247 320 struct nbd_sock *nsock =
5ea8d108 321 config->socks[cmd->index];
f3733247 322 mutex_lock(&nsock->tx_lock);
799f9a38
JB
323 /* We can have multiple outstanding requests, so
324 * we don't want to mark the nsock dead if we've
325 * already reconnected with a new socket, so
326 * only mark it dead if its the same socket we
327 * were sent out on.
328 */
329 if (cmd->cookie == nsock->cookie)
330 nbd_mark_nsock_dead(nbd, nsock, 1);
f3733247
JB
331 mutex_unlock(&nsock->tx_lock);
332 }
f3733247 333 blk_mq_requeue_request(req, true);
5ea8d108 334 nbd_config_put(nbd);
f3733247
JB
335 return BLK_EH_NOT_HANDLED;
336 }
f3733247
JB
337 } else {
338 dev_err_ratelimited(nbd_to_dev(nbd),
339 "Connection timed out\n");
340 }
5ea8d108 341 set_bit(NBD_TIMEDOUT, &config->runtime_flags);
2a842aca 342 cmd->status = BLK_STS_IOERR;
9561a7ad 343 sock_shutdown(nbd);
5ea8d108
JB
344 nbd_config_put(nbd);
345
0eadf37a 346 return BLK_EH_HANDLED;
7fdfd406
PC
347}
348
1da177e4
LT
349/*
350 * Send or receive packet.
351 */
c9f2b6ae 352static int sock_xmit(struct nbd_device *nbd, int index, int send,
9dd5d3ab 353 struct iov_iter *iter, int msg_flags, int *sent)
1da177e4 354{
5ea8d108
JB
355 struct nbd_config *config = nbd->config;
356 struct socket *sock = config->socks[index]->sock;
1da177e4
LT
357 int result;
358 struct msghdr msg;
f1083048 359 unsigned int noreclaim_flag;
1da177e4 360
ffc41cf8 361 if (unlikely(!sock)) {
a897b666 362 dev_err_ratelimited(disk_to_dev(nbd->disk),
7f1b90f9
WC
363 "Attempted %s on closed socket in sock_xmit\n",
364 (send ? "send" : "recv"));
ffc41cf8
MS
365 return -EINVAL;
366 }
367
c9f2b6ae 368 msg.msg_iter = *iter;
c1696cab 369
f1083048 370 noreclaim_flag = memalloc_noreclaim_save();
1da177e4 371 do {
7f338fe4 372 sock->sk->sk_allocation = GFP_NOIO | __GFP_MEMALLOC;
1da177e4
LT
373 msg.msg_name = NULL;
374 msg.msg_namelen = 0;
375 msg.msg_control = NULL;
376 msg.msg_controllen = 0;
1da177e4
LT
377 msg.msg_flags = msg_flags | MSG_NOSIGNAL;
378
7e2893a1 379 if (send)
c1696cab 380 result = sock_sendmsg(sock, &msg);
7e2893a1 381 else
c1696cab 382 result = sock_recvmsg(sock, &msg, msg.msg_flags);
1da177e4 383
1da177e4
LT
384 if (result <= 0) {
385 if (result == 0)
386 result = -EPIPE; /* short read */
387 break;
388 }
9dd5d3ab
JB
389 if (sent)
390 *sent += result;
c1696cab 391 } while (msg_data_left(&msg));
1da177e4 392
f1083048 393 memalloc_noreclaim_restore(noreclaim_flag);
1da177e4
LT
394
395 return result;
396}
397
32e67a3a
JB
398/*
399 * Different settings for sk->sk_sndtimeo can result in different return values
400 * if there is a signal pending when we enter sendmsg, because reasons?
401 */
402static inline int was_interrupted(int result)
403{
404 return result == -ERESTARTSYS || result == -EINTR;
405}
406
7fdfd406 407/* always call with the tx_lock held */
9561a7ad 408static int nbd_send_cmd(struct nbd_device *nbd, struct nbd_cmd *cmd, int index)
1da177e4 409{
fd8383fd 410 struct request *req = blk_mq_rq_from_pdu(cmd);
5ea8d108
JB
411 struct nbd_config *config = nbd->config;
412 struct nbd_sock *nsock = config->socks[index];
d61b7f97 413 int result;
c9f2b6ae
AV
414 struct nbd_request request = {.magic = htonl(NBD_REQUEST_MAGIC)};
415 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
416 struct iov_iter from;
1011c1b9 417 unsigned long size = blk_rq_bytes(req);
429a787b 418 struct bio *bio;
9dc6c806 419 u32 type;
685c9b24 420 u32 nbd_cmd_flags = 0;
9561a7ad 421 u32 tag = blk_mq_unique_tag(req);
9dd5d3ab 422 int sent = nsock->sent, skip = 0;
9dc6c806 423
c9f2b6ae
AV
424 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
425
aebf526b
CH
426 switch (req_op(req)) {
427 case REQ_OP_DISCARD:
9dc6c806 428 type = NBD_CMD_TRIM;
aebf526b
CH
429 break;
430 case REQ_OP_FLUSH:
9dc6c806 431 type = NBD_CMD_FLUSH;
aebf526b
CH
432 break;
433 case REQ_OP_WRITE:
9dc6c806 434 type = NBD_CMD_WRITE;
aebf526b
CH
435 break;
436 case REQ_OP_READ:
9dc6c806 437 type = NBD_CMD_READ;
aebf526b
CH
438 break;
439 default:
440 return -EIO;
441 }
1da177e4 442
09fc54cc 443 if (rq_data_dir(req) == WRITE &&
5ea8d108 444 (config->flags & NBD_FLAG_READ_ONLY)) {
09fc54cc
CH
445 dev_err_ratelimited(disk_to_dev(nbd->disk),
446 "Write on read-only\n");
447 return -EIO;
448 }
449
685c9b24
SM
450 if (req->cmd_flags & REQ_FUA)
451 nbd_cmd_flags |= NBD_CMD_FLAG_FUA;
452
9dd5d3ab
JB
453 /* We did a partial send previously, and we at least sent the whole
454 * request struct, so just go and send the rest of the pages in the
455 * request.
456 */
457 if (sent) {
458 if (sent >= sizeof(request)) {
459 skip = sent - sizeof(request);
460 goto send_pages;
461 }
462 iov_iter_advance(&from, sent);
463 }
f3733247 464 cmd->index = index;
799f9a38 465 cmd->cookie = nsock->cookie;
685c9b24 466 request.type = htonl(type | nbd_cmd_flags);
9561a7ad 467 if (type != NBD_CMD_FLUSH) {
75f187ab
AB
468 request.from = cpu_to_be64((u64)blk_rq_pos(req) << 9);
469 request.len = htonl(size);
470 }
9561a7ad 471 memcpy(request.handle, &tag, sizeof(tag));
1da177e4 472
d18509f5 473 dev_dbg(nbd_to_dev(nbd), "request %p: sending control (%s@%llu,%uB)\n",
fd8383fd 474 cmd, nbdcmd_to_ascii(type),
d18509f5 475 (unsigned long long)blk_rq_pos(req) << 9, blk_rq_bytes(req));
c9f2b6ae 476 result = sock_xmit(nbd, index, 1, &from,
9dd5d3ab 477 (type == NBD_CMD_WRITE) ? MSG_MORE : 0, &sent);
1da177e4 478 if (result <= 0) {
32e67a3a 479 if (was_interrupted(result)) {
9dd5d3ab
JB
480 /* If we havne't sent anything we can just return BUSY,
481 * however if we have sent something we need to make
482 * sure we only allow this req to be sent until we are
483 * completely done.
484 */
485 if (sent) {
486 nsock->pending = req;
487 nsock->sent = sent;
488 }
fc17b653 489 return BLK_STS_RESOURCE;
9dd5d3ab 490 }
a897b666 491 dev_err_ratelimited(disk_to_dev(nbd->disk),
7f1b90f9 492 "Send control failed (result %d)\n", result);
f3733247 493 return -EAGAIN;
1da177e4 494 }
9dd5d3ab 495send_pages:
429a787b 496 if (type != NBD_CMD_WRITE)
9dd5d3ab 497 goto out;
429a787b 498
429a787b
JA
499 bio = req->bio;
500 while (bio) {
501 struct bio *next = bio->bi_next;
502 struct bvec_iter iter;
7988613b 503 struct bio_vec bvec;
429a787b
JA
504
505 bio_for_each_segment(bvec, bio, iter) {
506 bool is_last = !next && bio_iter_last(bvec, iter);
d61b7f97 507 int flags = is_last ? 0 : MSG_MORE;
429a787b 508
d18509f5 509 dev_dbg(nbd_to_dev(nbd), "request %p: sending %d bytes data\n",
fd8383fd 510 cmd, bvec.bv_len);
c9f2b6ae
AV
511 iov_iter_bvec(&from, ITER_BVEC | WRITE,
512 &bvec, 1, bvec.bv_len);
9dd5d3ab
JB
513 if (skip) {
514 if (skip >= iov_iter_count(&from)) {
515 skip -= iov_iter_count(&from);
516 continue;
517 }
518 iov_iter_advance(&from, skip);
519 skip = 0;
520 }
521 result = sock_xmit(nbd, index, 1, &from, flags, &sent);
6c92e699 522 if (result <= 0) {
32e67a3a 523 if (was_interrupted(result)) {
9dd5d3ab
JB
524 /* We've already sent the header, we
525 * have no choice but to set pending and
526 * return BUSY.
527 */
528 nsock->pending = req;
529 nsock->sent = sent;
fc17b653 530 return BLK_STS_RESOURCE;
9dd5d3ab 531 }
f4507164 532 dev_err(disk_to_dev(nbd->disk),
7f1b90f9
WC
533 "Send data failed (result %d)\n",
534 result);
f3733247 535 return -EAGAIN;
6c92e699 536 }
429a787b
JA
537 /*
538 * The completion might already have come in,
539 * so break for the last one instead of letting
540 * the iterator do it. This prevents use-after-free
541 * of the bio.
542 */
543 if (is_last)
544 break;
1da177e4 545 }
429a787b 546 bio = next;
1da177e4 547 }
9dd5d3ab
JB
548out:
549 nsock->pending = NULL;
550 nsock->sent = 0;
1da177e4 551 return 0;
1da177e4
LT
552}
553
1da177e4 554/* NULL returned = something went wrong, inform userspace */
9561a7ad 555static struct nbd_cmd *nbd_read_stat(struct nbd_device *nbd, int index)
1da177e4 556{
5ea8d108 557 struct nbd_config *config = nbd->config;
1da177e4
LT
558 int result;
559 struct nbd_reply reply;
fd8383fd
JB
560 struct nbd_cmd *cmd;
561 struct request *req = NULL;
562 u16 hwq;
9561a7ad 563 u32 tag;
c9f2b6ae
AV
564 struct kvec iov = {.iov_base = &reply, .iov_len = sizeof(reply)};
565 struct iov_iter to;
1da177e4
LT
566
567 reply.magic = 0;
c9f2b6ae 568 iov_iter_kvec(&to, READ | ITER_KVEC, &iov, 1, sizeof(reply));
9dd5d3ab 569 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
1da177e4 570 if (result <= 0) {
5ea8d108 571 if (!nbd_disconnected(config))
9561a7ad
JB
572 dev_err(disk_to_dev(nbd->disk),
573 "Receive control failed (result %d)\n", result);
19391830 574 return ERR_PTR(result);
1da177e4 575 }
e4b57e08
MF
576
577 if (ntohl(reply.magic) != NBD_REPLY_MAGIC) {
f4507164 578 dev_err(disk_to_dev(nbd->disk), "Wrong magic (0x%lx)\n",
e4b57e08 579 (unsigned long)ntohl(reply.magic));
19391830 580 return ERR_PTR(-EPROTO);
e4b57e08
MF
581 }
582
9561a7ad 583 memcpy(&tag, reply.handle, sizeof(u32));
4b2f0260 584
fd8383fd
JB
585 hwq = blk_mq_unique_tag_to_hwq(tag);
586 if (hwq < nbd->tag_set.nr_hw_queues)
587 req = blk_mq_tag_to_rq(nbd->tag_set.tags[hwq],
588 blk_mq_unique_tag_to_tag(tag));
589 if (!req || !blk_mq_request_started(req)) {
590 dev_err(disk_to_dev(nbd->disk), "Unexpected reply (%d) %p\n",
591 tag, req);
592 return ERR_PTR(-ENOENT);
1da177e4 593 }
fd8383fd 594 cmd = blk_mq_rq_to_pdu(req);
1da177e4 595 if (ntohl(reply.error)) {
f4507164 596 dev_err(disk_to_dev(nbd->disk), "Other side returned error (%d)\n",
7f1b90f9 597 ntohl(reply.error));
2a842aca 598 cmd->status = BLK_STS_IOERR;
fd8383fd 599 return cmd;
1da177e4
LT
600 }
601
fd8383fd 602 dev_dbg(nbd_to_dev(nbd), "request %p: got reply\n", cmd);
9dc6c806 603 if (rq_data_dir(req) != WRITE) {
5705f702 604 struct req_iterator iter;
7988613b 605 struct bio_vec bvec;
5705f702
N
606
607 rq_for_each_segment(bvec, req, iter) {
c9f2b6ae
AV
608 iov_iter_bvec(&to, ITER_BVEC | READ,
609 &bvec, 1, bvec.bv_len);
9dd5d3ab 610 result = sock_xmit(nbd, index, 0, &to, MSG_WAITALL, NULL);
6c92e699 611 if (result <= 0) {
f4507164 612 dev_err(disk_to_dev(nbd->disk), "Receive data failed (result %d)\n",
7f1b90f9 613 result);
f3733247
JB
614 /*
615 * If we've disconnected or we only have 1
616 * connection then we need to make sure we
617 * complete this request, otherwise error out
618 * and let the timeout stuff handle resubmitting
619 * this request onto another connection.
620 */
5ea8d108
JB
621 if (nbd_disconnected(config) ||
622 config->num_connections <= 1) {
2a842aca 623 cmd->status = BLK_STS_IOERR;
f3733247
JB
624 return cmd;
625 }
626 return ERR_PTR(-EIO);
6c92e699 627 }
d18509f5 628 dev_dbg(nbd_to_dev(nbd), "request %p: got %d bytes data\n",
fd8383fd 629 cmd, bvec.bv_len);
1da177e4 630 }
9561a7ad
JB
631 } else {
632 /* See the comment in nbd_queue_rq. */
633 wait_for_completion(&cmd->send_complete);
1da177e4 634 }
fd8383fd 635 return cmd;
1da177e4
LT
636}
637
9561a7ad 638static void recv_work(struct work_struct *work)
1da177e4 639{
9561a7ad
JB
640 struct recv_thread_args *args = container_of(work,
641 struct recv_thread_args,
642 work);
643 struct nbd_device *nbd = args->nbd;
5ea8d108 644 struct nbd_config *config = nbd->config;
fd8383fd 645 struct nbd_cmd *cmd;
1da177e4 646
19391830 647 while (1) {
9561a7ad 648 cmd = nbd_read_stat(nbd, args->index);
fd8383fd 649 if (IS_ERR(cmd)) {
5ea8d108 650 struct nbd_sock *nsock = config->socks[args->index];
f3733247
JB
651
652 mutex_lock(&nsock->tx_lock);
799f9a38 653 nbd_mark_nsock_dead(nbd, nsock, 1);
f3733247 654 mutex_unlock(&nsock->tx_lock);
19391830
MP
655 break;
656 }
657
08e0029a 658 blk_mq_complete_request(blk_mq_rq_from_pdu(cmd));
19391830 659 }
5ea8d108
JB
660 atomic_dec(&config->recv_threads);
661 wake_up(&config->recv_wq);
662 nbd_config_put(nbd);
663 kfree(args);
1da177e4
LT
664}
665
fd8383fd 666static void nbd_clear_req(struct request *req, void *data, bool reserved)
1da177e4 667{
fd8383fd 668 struct nbd_cmd *cmd;
1da177e4 669
fd8383fd
JB
670 if (!blk_mq_request_started(req))
671 return;
672 cmd = blk_mq_rq_to_pdu(req);
2a842aca 673 cmd->status = BLK_STS_IOERR;
08e0029a 674 blk_mq_complete_request(req);
fd8383fd
JB
675}
676
677static void nbd_clear_que(struct nbd_device *nbd)
678{
b52c2e92 679 blk_mq_quiesce_queue(nbd->disk->queue);
fd8383fd 680 blk_mq_tagset_busy_iter(&nbd->tag_set, nbd_clear_req, NULL);
b52c2e92 681 blk_mq_unquiesce_queue(nbd->disk->queue);
e78273c8 682 dev_dbg(disk_to_dev(nbd->disk), "queue cleared\n");
1da177e4
LT
683}
684
f3733247
JB
685static int find_fallback(struct nbd_device *nbd, int index)
686{
5ea8d108 687 struct nbd_config *config = nbd->config;
f3733247 688 int new_index = -1;
5ea8d108 689 struct nbd_sock *nsock = config->socks[index];
f3733247
JB
690 int fallback = nsock->fallback_index;
691
5ea8d108 692 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
f3733247
JB
693 return new_index;
694
5ea8d108 695 if (config->num_connections <= 1) {
f3733247
JB
696 dev_err_ratelimited(disk_to_dev(nbd->disk),
697 "Attempted send on invalid socket\n");
698 return new_index;
699 }
700
5ea8d108
JB
701 if (fallback >= 0 && fallback < config->num_connections &&
702 !config->socks[fallback]->dead)
f3733247
JB
703 return fallback;
704
705 if (nsock->fallback_index < 0 ||
5ea8d108
JB
706 nsock->fallback_index >= config->num_connections ||
707 config->socks[nsock->fallback_index]->dead) {
f3733247 708 int i;
5ea8d108 709 for (i = 0; i < config->num_connections; i++) {
f3733247
JB
710 if (i == index)
711 continue;
5ea8d108 712 if (!config->socks[i]->dead) {
f3733247
JB
713 new_index = i;
714 break;
715 }
716 }
717 nsock->fallback_index = new_index;
718 if (new_index < 0) {
719 dev_err_ratelimited(disk_to_dev(nbd->disk),
720 "Dead connection, failed to find a fallback\n");
721 return new_index;
722 }
723 }
724 new_index = nsock->fallback_index;
725 return new_index;
726}
7fdfd406 727
560bc4b3
JB
728static int wait_for_reconnect(struct nbd_device *nbd)
729{
730 struct nbd_config *config = nbd->config;
731 if (!config->dead_conn_timeout)
732 return 0;
733 if (test_bit(NBD_DISCONNECTED, &config->runtime_flags))
734 return 0;
ff57dc94
JB
735 wait_event_timeout(config->conn_wait,
736 atomic_read(&config->live_connections),
737 config->dead_conn_timeout);
560bc4b3
JB
738 return atomic_read(&config->live_connections);
739}
740
9dd5d3ab 741static int nbd_handle_cmd(struct nbd_cmd *cmd, int index)
48cf6061 742{
fd8383fd
JB
743 struct request *req = blk_mq_rq_from_pdu(cmd);
744 struct nbd_device *nbd = cmd->nbd;
5ea8d108 745 struct nbd_config *config;
9561a7ad 746 struct nbd_sock *nsock;
9dd5d3ab 747 int ret;
fd8383fd 748
5ea8d108
JB
749 if (!refcount_inc_not_zero(&nbd->config_refs)) {
750 dev_err_ratelimited(disk_to_dev(nbd->disk),
751 "Socks array is empty\n");
6a468d59 752 blk_mq_start_request(req);
5ea8d108
JB
753 return -EINVAL;
754 }
755 config = nbd->config;
756
757 if (index >= config->num_connections) {
a897b666
JB
758 dev_err_ratelimited(disk_to_dev(nbd->disk),
759 "Attempted send on invalid socket\n");
5ea8d108 760 nbd_config_put(nbd);
6a468d59 761 blk_mq_start_request(req);
9dd5d3ab 762 return -EINVAL;
9561a7ad 763 }
2a842aca 764 cmd->status = BLK_STS_OK;
f3733247 765again:
5ea8d108 766 nsock = config->socks[index];
9561a7ad 767 mutex_lock(&nsock->tx_lock);
f3733247 768 if (nsock->dead) {
560bc4b3 769 int old_index = index;
f3733247 770 index = find_fallback(nbd, index);
560bc4b3 771 mutex_unlock(&nsock->tx_lock);
5ea8d108 772 if (index < 0) {
560bc4b3
JB
773 if (wait_for_reconnect(nbd)) {
774 index = old_index;
775 goto again;
776 }
777 /* All the sockets should already be down at this point,
778 * we just want to make sure that DISCONNECTED is set so
779 * any requests that come in that were queue'ed waiting
780 * for the reconnect timer don't trigger the timer again
781 * and instead just error out.
782 */
783 sock_shutdown(nbd);
784 nbd_config_put(nbd);
6a468d59 785 blk_mq_start_request(req);
560bc4b3 786 return -EIO;
5ea8d108 787 }
f3733247 788 goto again;
48cf6061
LV
789 }
790
9dd5d3ab
JB
791 /* Handle the case that we have a pending request that was partially
792 * transmitted that _has_ to be serviced first. We need to call requeue
793 * here so that it gets put _after_ the request that is already on the
794 * dispatch list.
795 */
6a468d59 796 blk_mq_start_request(req);
9dd5d3ab
JB
797 if (unlikely(nsock->pending && nsock->pending != req)) {
798 blk_mq_requeue_request(req, true);
799 ret = 0;
800 goto out;
48cf6061 801 }
f3733247
JB
802 /*
803 * Some failures are related to the link going down, so anything that
804 * returns EAGAIN can be retried on a different socket.
805 */
9dd5d3ab 806 ret = nbd_send_cmd(nbd, cmd, index);
f3733247
JB
807 if (ret == -EAGAIN) {
808 dev_err_ratelimited(disk_to_dev(nbd->disk),
6a468d59 809 "Request send failed, requeueing\n");
799f9a38 810 nbd_mark_nsock_dead(nbd, nsock, 1);
6a468d59
JB
811 blk_mq_requeue_request(req, true);
812 ret = 0;
f3733247 813 }
9dd5d3ab 814out:
9561a7ad 815 mutex_unlock(&nsock->tx_lock);
5ea8d108 816 nbd_config_put(nbd);
9dd5d3ab 817 return ret;
48cf6061
LV
818}
819
fc17b653 820static blk_status_t nbd_queue_rq(struct blk_mq_hw_ctx *hctx,
fd8383fd 821 const struct blk_mq_queue_data *bd)
1da177e4 822{
fd8383fd 823 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(bd->rq);
9dd5d3ab 824 int ret;
1da177e4 825
9561a7ad
JB
826 /*
827 * Since we look at the bio's to send the request over the network we
828 * need to make sure the completion work doesn't mark this request done
829 * before we are done doing our send. This keeps us from dereferencing
830 * freed data if we have particularly fast completions (ie we get the
831 * completion before we exit sock_xmit on the last bvec) or in the case
832 * that the server is misbehaving (or there was an error) before we're
833 * done sending everything over the wire.
834 */
835 init_completion(&cmd->send_complete);
9dd5d3ab
JB
836
837 /* We can be called directly from the user space process, which means we
838 * could possibly have signals pending so our sendmsg will fail. In
839 * this case we need to return that we are busy, otherwise error out as
840 * appropriate.
841 */
842 ret = nbd_handle_cmd(cmd, hctx->queue_num);
6e60a3bb
JB
843 if (ret < 0)
844 ret = BLK_STS_IOERR;
845 else if (!ret)
846 ret = BLK_STS_OK;
9561a7ad
JB
847 complete(&cmd->send_complete);
848
6e60a3bb 849 return ret;
1da177e4
LT
850}
851
e46c7287
JB
852static int nbd_add_socket(struct nbd_device *nbd, unsigned long arg,
853 bool netlink)
23272a67 854{
5ea8d108 855 struct nbd_config *config = nbd->config;
9442b739 856 struct socket *sock;
9561a7ad
JB
857 struct nbd_sock **socks;
858 struct nbd_sock *nsock;
9442b739
JB
859 int err;
860
861 sock = sockfd_lookup(arg, &err);
862 if (!sock)
863 return err;
23272a67 864
e46c7287
JB
865 if (!netlink && !nbd->task_setup &&
866 !test_bit(NBD_BOUND, &config->runtime_flags))
9561a7ad 867 nbd->task_setup = current;
e46c7287
JB
868
869 if (!netlink &&
870 (nbd->task_setup != current ||
871 test_bit(NBD_BOUND, &config->runtime_flags))) {
9561a7ad
JB
872 dev_err(disk_to_dev(nbd->disk),
873 "Device being setup by another task");
9b1355d5 874 sockfd_put(sock);
e46c7287 875 return -EBUSY;
23272a67
MP
876 }
877
5ea8d108 878 socks = krealloc(config->socks, (config->num_connections + 1) *
9561a7ad 879 sizeof(struct nbd_sock *), GFP_KERNEL);
9b1355d5
JB
880 if (!socks) {
881 sockfd_put(sock);
9561a7ad 882 return -ENOMEM;
9b1355d5 883 }
9561a7ad 884 nsock = kzalloc(sizeof(struct nbd_sock), GFP_KERNEL);
9b1355d5
JB
885 if (!nsock) {
886 sockfd_put(sock);
9561a7ad 887 return -ENOMEM;
9b1355d5 888 }
9561a7ad 889
5ea8d108 890 config->socks = socks;
23272a67 891
f3733247
JB
892 nsock->fallback_index = -1;
893 nsock->dead = false;
9561a7ad
JB
894 mutex_init(&nsock->tx_lock);
895 nsock->sock = sock;
9dd5d3ab
JB
896 nsock->pending = NULL;
897 nsock->sent = 0;
799f9a38 898 nsock->cookie = 0;
5ea8d108 899 socks[config->num_connections++] = nsock;
560bc4b3 900 atomic_inc(&config->live_connections);
23272a67 901
9561a7ad 902 return 0;
23272a67
MP
903}
904
b7aa3d39
JB
905static int nbd_reconnect_socket(struct nbd_device *nbd, unsigned long arg)
906{
907 struct nbd_config *config = nbd->config;
908 struct socket *sock, *old;
909 struct recv_thread_args *args;
910 int i;
911 int err;
912
913 sock = sockfd_lookup(arg, &err);
914 if (!sock)
915 return err;
916
917 args = kzalloc(sizeof(*args), GFP_KERNEL);
918 if (!args) {
919 sockfd_put(sock);
920 return -ENOMEM;
921 }
922
923 for (i = 0; i < config->num_connections; i++) {
924 struct nbd_sock *nsock = config->socks[i];
925
926 if (!nsock->dead)
927 continue;
928
929 mutex_lock(&nsock->tx_lock);
930 if (!nsock->dead) {
931 mutex_unlock(&nsock->tx_lock);
932 continue;
933 }
934 sk_set_memalloc(sock->sk);
a7ee8cf1
JB
935 if (nbd->tag_set.timeout)
936 sock->sk->sk_sndtimeo = nbd->tag_set.timeout;
b7aa3d39
JB
937 atomic_inc(&config->recv_threads);
938 refcount_inc(&nbd->config_refs);
939 old = nsock->sock;
940 nsock->fallback_index = -1;
941 nsock->sock = sock;
942 nsock->dead = false;
943 INIT_WORK(&args->work, recv_work);
944 args->index = i;
945 args->nbd = nbd;
799f9a38 946 nsock->cookie++;
b7aa3d39
JB
947 mutex_unlock(&nsock->tx_lock);
948 sockfd_put(old);
949
7a362ea9
JB
950 clear_bit(NBD_DISCONNECTED, &config->runtime_flags);
951
b7aa3d39
JB
952 /* We take the tx_mutex in an error path in the recv_work, so we
953 * need to queue_work outside of the tx_mutex.
954 */
955 queue_work(recv_workqueue, &args->work);
560bc4b3
JB
956
957 atomic_inc(&config->live_connections);
958 wake_up(&config->conn_wait);
b7aa3d39
JB
959 return 0;
960 }
961 sockfd_put(sock);
962 kfree(args);
963 return -ENOSPC;
964}
965
0e4f0f6f
MP
966static void nbd_bdev_reset(struct block_device *bdev)
967{
abbbdf12
RMB
968 if (bdev->bd_openers > 1)
969 return;
29eaadc0 970 bd_set_size(bdev, 0);
0e4f0f6f
MP
971}
972
29eaadc0 973static void nbd_parse_flags(struct nbd_device *nbd)
d02cf531 974{
5ea8d108
JB
975 struct nbd_config *config = nbd->config;
976 if (config->flags & NBD_FLAG_READ_ONLY)
29eaadc0
JB
977 set_disk_ro(nbd->disk, true);
978 else
979 set_disk_ro(nbd->disk, false);
5ea8d108 980 if (config->flags & NBD_FLAG_SEND_TRIM)
8b904b5b 981 blk_queue_flag_set(QUEUE_FLAG_DISCARD, nbd->disk->queue);
685c9b24
SM
982 if (config->flags & NBD_FLAG_SEND_FLUSH) {
983 if (config->flags & NBD_FLAG_SEND_FUA)
984 blk_queue_write_cache(nbd->disk->queue, true, true);
985 else
986 blk_queue_write_cache(nbd->disk->queue, true, false);
987 }
d02cf531 988 else
aafb1eec 989 blk_queue_write_cache(nbd->disk->queue, false, false);
d02cf531
MP
990}
991
9561a7ad
JB
992static void send_disconnects(struct nbd_device *nbd)
993{
5ea8d108 994 struct nbd_config *config = nbd->config;
c9f2b6ae
AV
995 struct nbd_request request = {
996 .magic = htonl(NBD_REQUEST_MAGIC),
997 .type = htonl(NBD_CMD_DISC),
998 };
999 struct kvec iov = {.iov_base = &request, .iov_len = sizeof(request)};
1000 struct iov_iter from;
9561a7ad
JB
1001 int i, ret;
1002
5ea8d108 1003 for (i = 0; i < config->num_connections; i++) {
b4b2aecc
JB
1004 struct nbd_sock *nsock = config->socks[i];
1005
c9f2b6ae 1006 iov_iter_kvec(&from, WRITE | ITER_KVEC, &iov, 1, sizeof(request));
b4b2aecc 1007 mutex_lock(&nsock->tx_lock);
9dd5d3ab 1008 ret = sock_xmit(nbd, i, 1, &from, 0, NULL);
9561a7ad
JB
1009 if (ret <= 0)
1010 dev_err(disk_to_dev(nbd->disk),
1011 "Send disconnect failed %d\n", ret);
b4b2aecc 1012 mutex_unlock(&nsock->tx_lock);
9561a7ad
JB
1013 }
1014}
1015
29eaadc0 1016static int nbd_disconnect(struct nbd_device *nbd)
9442b739 1017{
5ea8d108 1018 struct nbd_config *config = nbd->config;
30d53d9c 1019
5ea8d108 1020 dev_info(disk_to_dev(nbd->disk), "NBD_DISCONNECT\n");
2e13456f
JB
1021 set_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags);
1022 send_disconnects(nbd);
9442b739
JB
1023 return 0;
1024}
1025
29eaadc0 1026static void nbd_clear_sock(struct nbd_device *nbd)
1a2ad211 1027{
9442b739
JB
1028 sock_shutdown(nbd);
1029 nbd_clear_que(nbd);
5ea8d108 1030 nbd->task_setup = NULL;
5ea8d108
JB
1031}
1032
1033static void nbd_config_put(struct nbd_device *nbd)
1034{
1035 if (refcount_dec_and_mutex_lock(&nbd->config_refs,
1036 &nbd->config_lock)) {
5ea8d108 1037 struct nbd_config *config = nbd->config;
5ea8d108 1038 nbd_dev_dbg_close(nbd);
29eaadc0 1039 nbd_size_clear(nbd);
5ea8d108
JB
1040 if (test_and_clear_bit(NBD_HAS_PID_FILE,
1041 &config->runtime_flags))
1042 device_remove_file(disk_to_dev(nbd->disk), &pid_attr);
1043 nbd->task_recv = NULL;
29eaadc0 1044 nbd_clear_sock(nbd);
5ea8d108
JB
1045 if (config->num_connections) {
1046 int i;
1047 for (i = 0; i < config->num_connections; i++) {
1048 sockfd_put(config->socks[i]->sock);
1049 kfree(config->socks[i]);
1050 }
1051 kfree(config->socks);
1052 }
fa976532 1053 kfree(nbd->config);
af622b86
ID
1054 nbd->config = NULL;
1055
1056 nbd->tag_set.timeout = 0;
6df133a1
JB
1057 nbd->disk->queue->limits.discard_granularity = 0;
1058 blk_queue_max_discard_sectors(nbd->disk->queue, UINT_MAX);
8b904b5b 1059 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, nbd->disk->queue);
a2c97909 1060
5ea8d108 1061 mutex_unlock(&nbd->config_lock);
c6a4759e 1062 nbd_put(nbd);
5ea8d108
JB
1063 module_put(THIS_MODULE);
1064 }
9442b739
JB
1065}
1066
e46c7287 1067static int nbd_start_device(struct nbd_device *nbd)
9442b739 1068{
5ea8d108
JB
1069 struct nbd_config *config = nbd->config;
1070 int num_connections = config->num_connections;
9442b739 1071 int error = 0, i;
1a2ad211 1072
9442b739
JB
1073 if (nbd->task_recv)
1074 return -EBUSY;
5ea8d108 1075 if (!config->socks)
9442b739
JB
1076 return -EINVAL;
1077 if (num_connections > 1 &&
5ea8d108 1078 !(config->flags & NBD_FLAG_CAN_MULTI_CONN)) {
9442b739 1079 dev_err(disk_to_dev(nbd->disk), "server does not support multiple connections per device.\n");
5ea8d108 1080 return -EINVAL;
9442b739 1081 }
23272a67 1082
5ea8d108 1083 blk_mq_update_nr_hw_queues(&nbd->tag_set, config->num_connections);
9442b739 1084 nbd->task_recv = current;
23272a67 1085
29eaadc0 1086 nbd_parse_flags(nbd);
23272a67 1087
9442b739
JB
1088 error = device_create_file(disk_to_dev(nbd->disk), &pid_attr);
1089 if (error) {
1090 dev_err(disk_to_dev(nbd->disk), "device_create_file failed!\n");
5ea8d108 1091 return error;
1a2ad211 1092 }
29eaadc0 1093 set_bit(NBD_HAS_PID_FILE, &config->runtime_flags);
37091fdd 1094
9442b739
JB
1095 nbd_dev_dbg_init(nbd);
1096 for (i = 0; i < num_connections; i++) {
5ea8d108
JB
1097 struct recv_thread_args *args;
1098
1099 args = kzalloc(sizeof(*args), GFP_KERNEL);
1100 if (!args) {
1101 sock_shutdown(nbd);
1102 return -ENOMEM;
1103 }
1104 sk_set_memalloc(config->socks[i]->sock->sk);
a7ee8cf1
JB
1105 if (nbd->tag_set.timeout)
1106 config->socks[i]->sock->sk->sk_sndtimeo =
1107 nbd->tag_set.timeout;
5ea8d108
JB
1108 atomic_inc(&config->recv_threads);
1109 refcount_inc(&nbd->config_refs);
1110 INIT_WORK(&args->work, recv_work);
1111 args->nbd = nbd;
1112 args->index = i;
1113 queue_work(recv_workqueue, &args->work);
37091fdd 1114 }
639812a1 1115 nbd_size_update(nbd);
e46c7287
JB
1116 return error;
1117}
1118
1119static int nbd_start_device_ioctl(struct nbd_device *nbd, struct block_device *bdev)
1120{
1121 struct nbd_config *config = nbd->config;
1122 int ret;
1123
1124 ret = nbd_start_device(nbd);
1125 if (ret)
1126 return ret;
1127
e46c7287
JB
1128 if (max_part)
1129 bdev->bd_invalidated = 1;
1130 mutex_unlock(&nbd->config_lock);
1131 ret = wait_event_interruptible(config->recv_wq,
5ea8d108 1132 atomic_read(&config->recv_threads) == 0);
e46c7287 1133 if (ret)
5ea8d108 1134 sock_shutdown(nbd);
9442b739 1135 mutex_lock(&nbd->config_lock);
76aa1d34 1136 nbd_bdev_reset(bdev);
9442b739 1137 /* user requested, ignore socket errors */
5ea8d108 1138 if (test_bit(NBD_DISCONNECT_REQUESTED, &config->runtime_flags))
e46c7287 1139 ret = 0;
5ea8d108 1140 if (test_bit(NBD_TIMEDOUT, &config->runtime_flags))
e46c7287
JB
1141 ret = -ETIMEDOUT;
1142 return ret;
9442b739
JB
1143}
1144
29eaadc0
JB
1145static void nbd_clear_sock_ioctl(struct nbd_device *nbd,
1146 struct block_device *bdev)
1147{
2516ab15 1148 sock_shutdown(nbd);
29eaadc0
JB
1149 kill_bdev(bdev);
1150 nbd_bdev_reset(bdev);
e46c7287
JB
1151 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1152 &nbd->config->runtime_flags))
1153 nbd_config_put(nbd);
29eaadc0
JB
1154}
1155
9442b739
JB
1156/* Must be called with config_lock held */
1157static int __nbd_ioctl(struct block_device *bdev, struct nbd_device *nbd,
1158 unsigned int cmd, unsigned long arg)
1159{
5ea8d108
JB
1160 struct nbd_config *config = nbd->config;
1161
9442b739
JB
1162 switch (cmd) {
1163 case NBD_DISCONNECT:
29eaadc0 1164 return nbd_disconnect(nbd);
9442b739 1165 case NBD_CLEAR_SOCK:
29eaadc0
JB
1166 nbd_clear_sock_ioctl(nbd, bdev);
1167 return 0;
9442b739 1168 case NBD_SET_SOCK:
e46c7287 1169 return nbd_add_socket(nbd, arg, false);
9442b739 1170 case NBD_SET_BLKSIZE:
29eaadc0 1171 nbd_size_set(nbd, arg,
5ea8d108 1172 div_s64(config->bytesize, arg));
e544541b 1173 return 0;
1da177e4 1174 case NBD_SET_SIZE:
29eaadc0 1175 nbd_size_set(nbd, config->blksize,
5ea8d108 1176 div_s64(arg, config->blksize));
e544541b 1177 return 0;
37091fdd 1178 case NBD_SET_SIZE_BLOCKS:
29eaadc0 1179 nbd_size_set(nbd, config->blksize, arg);
e544541b 1180 return 0;
7fdfd406 1181 case NBD_SET_TIMEOUT:
f8586855
JB
1182 if (arg) {
1183 nbd->tag_set.timeout = arg * HZ;
1184 blk_queue_rq_timeout(nbd->disk->queue, arg * HZ);
1185 }
7fdfd406 1186 return 0;
1a2ad211 1187
2f012508 1188 case NBD_SET_FLAGS:
5ea8d108 1189 config->flags = arg;
2f012508 1190 return 0;
9442b739 1191 case NBD_DO_IT:
e46c7287 1192 return nbd_start_device_ioctl(nbd, bdev);
1da177e4 1193 case NBD_CLEAR_QUE:
4b2f0260
HX
1194 /*
1195 * This is for compatibility only. The queue is always cleared
1196 * by NBD_DO_IT or NBD_CLEAR_SOCK.
1197 */
1da177e4
LT
1198 return 0;
1199 case NBD_PRINT_DEBUG:
fd8383fd
JB
1200 /*
1201 * For compatibility only, we no longer keep a list of
1202 * outstanding requests.
1203 */
1da177e4
LT
1204 return 0;
1205 }
1a2ad211
PM
1206 return -ENOTTY;
1207}
1208
1209static int nbd_ioctl(struct block_device *bdev, fmode_t mode,
1210 unsigned int cmd, unsigned long arg)
1211{
f4507164 1212 struct nbd_device *nbd = bdev->bd_disk->private_data;
e46c7287
JB
1213 struct nbd_config *config = nbd->config;
1214 int error = -EINVAL;
1a2ad211
PM
1215
1216 if (!capable(CAP_SYS_ADMIN))
1217 return -EPERM;
1218
1dae69be
JB
1219 /* The block layer will pass back some non-nbd ioctls in case we have
1220 * special handling for them, but we don't so just return an error.
1221 */
1222 if (_IOC_TYPE(cmd) != 0xab)
1223 return -EINVAL;
1224
9561a7ad 1225 mutex_lock(&nbd->config_lock);
e46c7287
JB
1226
1227 /* Don't allow ioctl operations on a nbd device that was created with
1228 * netlink, unless it's DISCONNECT or CLEAR_SOCK, which are fine.
1229 */
1230 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1231 (cmd == NBD_DISCONNECT || cmd == NBD_CLEAR_SOCK))
1232 error = __nbd_ioctl(bdev, nbd, cmd, arg);
1233 else
1234 dev_err(nbd_to_dev(nbd), "Cannot use ioctl interface on a netlink controlled device.\n");
9561a7ad 1235 mutex_unlock(&nbd->config_lock);
1a2ad211 1236 return error;
1da177e4
LT
1237}
1238
5ea8d108
JB
1239static struct nbd_config *nbd_alloc_config(void)
1240{
1241 struct nbd_config *config;
1242
1243 config = kzalloc(sizeof(struct nbd_config), GFP_NOFS);
1244 if (!config)
1245 return NULL;
1246 atomic_set(&config->recv_threads, 0);
1247 init_waitqueue_head(&config->recv_wq);
560bc4b3 1248 init_waitqueue_head(&config->conn_wait);
5ea8d108 1249 config->blksize = 1024;
560bc4b3 1250 atomic_set(&config->live_connections, 0);
5ea8d108
JB
1251 try_module_get(THIS_MODULE);
1252 return config;
1253}
1254
1255static int nbd_open(struct block_device *bdev, fmode_t mode)
1256{
1257 struct nbd_device *nbd;
1258 int ret = 0;
1259
1260 mutex_lock(&nbd_index_mutex);
1261 nbd = bdev->bd_disk->private_data;
1262 if (!nbd) {
1263 ret = -ENXIO;
1264 goto out;
1265 }
c6a4759e
JB
1266 if (!refcount_inc_not_zero(&nbd->refs)) {
1267 ret = -ENXIO;
1268 goto out;
1269 }
5ea8d108
JB
1270 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1271 struct nbd_config *config;
1272
1273 mutex_lock(&nbd->config_lock);
1274 if (refcount_inc_not_zero(&nbd->config_refs)) {
1275 mutex_unlock(&nbd->config_lock);
1276 goto out;
1277 }
1278 config = nbd->config = nbd_alloc_config();
1279 if (!config) {
1280 ret = -ENOMEM;
1281 mutex_unlock(&nbd->config_lock);
1282 goto out;
1283 }
1284 refcount_set(&nbd->config_refs, 1);
c6a4759e 1285 refcount_inc(&nbd->refs);
5ea8d108 1286 mutex_unlock(&nbd->config_lock);
fe1f9e66
JB
1287 bdev->bd_invalidated = 1;
1288 } else if (nbd_disconnected(nbd->config)) {
1289 bdev->bd_invalidated = 1;
5ea8d108
JB
1290 }
1291out:
1292 mutex_unlock(&nbd_index_mutex);
1293 return ret;
1294}
1295
1296static void nbd_release(struct gendisk *disk, fmode_t mode)
1297{
1298 struct nbd_device *nbd = disk->private_data;
1299 nbd_config_put(nbd);
c6a4759e 1300 nbd_put(nbd);
5ea8d108
JB
1301}
1302
83d5cde4 1303static const struct block_device_operations nbd_fops =
1da177e4
LT
1304{
1305 .owner = THIS_MODULE,
5ea8d108
JB
1306 .open = nbd_open,
1307 .release = nbd_release,
8a6cfeb6 1308 .ioctl = nbd_ioctl,
263a3df1 1309 .compat_ioctl = nbd_ioctl,
1da177e4
LT
1310};
1311
30d53d9c
MP
1312#if IS_ENABLED(CONFIG_DEBUG_FS)
1313
1314static int nbd_dbg_tasks_show(struct seq_file *s, void *unused)
1315{
1316 struct nbd_device *nbd = s->private;
1317
1318 if (nbd->task_recv)
1319 seq_printf(s, "recv: %d\n", task_pid_nr(nbd->task_recv));
30d53d9c
MP
1320
1321 return 0;
1322}
1323
1324static int nbd_dbg_tasks_open(struct inode *inode, struct file *file)
1325{
1326 return single_open(file, nbd_dbg_tasks_show, inode->i_private);
1327}
1328
1329static const struct file_operations nbd_dbg_tasks_ops = {
1330 .open = nbd_dbg_tasks_open,
1331 .read = seq_read,
1332 .llseek = seq_lseek,
1333 .release = single_release,
1334};
1335
1336static int nbd_dbg_flags_show(struct seq_file *s, void *unused)
1337{
1338 struct nbd_device *nbd = s->private;
5ea8d108 1339 u32 flags = nbd->config->flags;
30d53d9c
MP
1340
1341 seq_printf(s, "Hex: 0x%08x\n\n", flags);
1342
1343 seq_puts(s, "Known flags:\n");
1344
1345 if (flags & NBD_FLAG_HAS_FLAGS)
1346 seq_puts(s, "NBD_FLAG_HAS_FLAGS\n");
1347 if (flags & NBD_FLAG_READ_ONLY)
1348 seq_puts(s, "NBD_FLAG_READ_ONLY\n");
1349 if (flags & NBD_FLAG_SEND_FLUSH)
1350 seq_puts(s, "NBD_FLAG_SEND_FLUSH\n");
685c9b24
SM
1351 if (flags & NBD_FLAG_SEND_FUA)
1352 seq_puts(s, "NBD_FLAG_SEND_FUA\n");
30d53d9c
MP
1353 if (flags & NBD_FLAG_SEND_TRIM)
1354 seq_puts(s, "NBD_FLAG_SEND_TRIM\n");
1355
1356 return 0;
1357}
1358
1359static int nbd_dbg_flags_open(struct inode *inode, struct file *file)
1360{
1361 return single_open(file, nbd_dbg_flags_show, inode->i_private);
1362}
1363
1364static const struct file_operations nbd_dbg_flags_ops = {
1365 .open = nbd_dbg_flags_open,
1366 .read = seq_read,
1367 .llseek = seq_lseek,
1368 .release = single_release,
1369};
1370
1371static int nbd_dev_dbg_init(struct nbd_device *nbd)
1372{
1373 struct dentry *dir;
5ea8d108 1374 struct nbd_config *config = nbd->config;
27ea43fe
MP
1375
1376 if (!nbd_dbg_dir)
1377 return -EIO;
30d53d9c
MP
1378
1379 dir = debugfs_create_dir(nbd_name(nbd), nbd_dbg_dir);
27ea43fe
MP
1380 if (!dir) {
1381 dev_err(nbd_to_dev(nbd), "Failed to create debugfs dir for '%s'\n",
1382 nbd_name(nbd));
1383 return -EIO;
30d53d9c 1384 }
5ea8d108 1385 config->dbg_dir = dir;
30d53d9c 1386
27ea43fe 1387 debugfs_create_file("tasks", 0444, dir, nbd, &nbd_dbg_tasks_ops);
5ea8d108 1388 debugfs_create_u64("size_bytes", 0444, dir, &config->bytesize);
0eadf37a 1389 debugfs_create_u32("timeout", 0444, dir, &nbd->tag_set.timeout);
5ea8d108 1390 debugfs_create_u64("blocksize", 0444, dir, &config->blksize);
d366a0ff 1391 debugfs_create_file("flags", 0444, dir, nbd, &nbd_dbg_flags_ops);
30d53d9c
MP
1392
1393 return 0;
1394}
1395
1396static void nbd_dev_dbg_close(struct nbd_device *nbd)
1397{
5ea8d108 1398 debugfs_remove_recursive(nbd->config->dbg_dir);
30d53d9c
MP
1399}
1400
1401static int nbd_dbg_init(void)
1402{
1403 struct dentry *dbg_dir;
1404
1405 dbg_dir = debugfs_create_dir("nbd", NULL);
27ea43fe
MP
1406 if (!dbg_dir)
1407 return -EIO;
30d53d9c
MP
1408
1409 nbd_dbg_dir = dbg_dir;
1410
1411 return 0;
1412}
1413
1414static void nbd_dbg_close(void)
1415{
1416 debugfs_remove_recursive(nbd_dbg_dir);
1417}
1418
1419#else /* IS_ENABLED(CONFIG_DEBUG_FS) */
1420
1421static int nbd_dev_dbg_init(struct nbd_device *nbd)
1422{
1423 return 0;
1424}
1425
1426static void nbd_dev_dbg_close(struct nbd_device *nbd)
1427{
1428}
1429
1430static int nbd_dbg_init(void)
1431{
1432 return 0;
1433}
1434
1435static void nbd_dbg_close(void)
1436{
1437}
1438
1439#endif
1440
d6296d39
CH
1441static int nbd_init_request(struct blk_mq_tag_set *set, struct request *rq,
1442 unsigned int hctx_idx, unsigned int numa_node)
fd8383fd
JB
1443{
1444 struct nbd_cmd *cmd = blk_mq_rq_to_pdu(rq);
d6296d39 1445 cmd->nbd = set->driver_data;
fd8383fd
JB
1446 return 0;
1447}
1448
f363b089 1449static const struct blk_mq_ops nbd_mq_ops = {
fd8383fd 1450 .queue_rq = nbd_queue_rq,
1e388ae0 1451 .complete = nbd_complete_rq,
fd8383fd 1452 .init_request = nbd_init_request,
0eadf37a 1453 .timeout = nbd_xmit_timeout,
fd8383fd
JB
1454};
1455
b0d9111a
JB
1456static int nbd_dev_add(int index)
1457{
1458 struct nbd_device *nbd;
1459 struct gendisk *disk;
1460 struct request_queue *q;
1461 int err = -ENOMEM;
1462
1463 nbd = kzalloc(sizeof(struct nbd_device), GFP_KERNEL);
1464 if (!nbd)
1465 goto out;
1466
1467 disk = alloc_disk(1 << part_shift);
1468 if (!disk)
1469 goto out_free_nbd;
1470
1471 if (index >= 0) {
1472 err = idr_alloc(&nbd_index_idr, nbd, index, index + 1,
1473 GFP_KERNEL);
1474 if (err == -ENOSPC)
1475 err = -EEXIST;
1476 } else {
1477 err = idr_alloc(&nbd_index_idr, nbd, 0, 0, GFP_KERNEL);
1478 if (err >= 0)
1479 index = err;
1480 }
1481 if (err < 0)
1482 goto out_free_disk;
1483
e46c7287 1484 nbd->index = index;
b0d9111a
JB
1485 nbd->disk = disk;
1486 nbd->tag_set.ops = &nbd_mq_ops;
1487 nbd->tag_set.nr_hw_queues = 1;
1488 nbd->tag_set.queue_depth = 128;
1489 nbd->tag_set.numa_node = NUMA_NO_NODE;
1490 nbd->tag_set.cmd_size = sizeof(struct nbd_cmd);
1491 nbd->tag_set.flags = BLK_MQ_F_SHOULD_MERGE |
1492 BLK_MQ_F_SG_MERGE | BLK_MQ_F_BLOCKING;
1493 nbd->tag_set.driver_data = nbd;
1494
1495 err = blk_mq_alloc_tag_set(&nbd->tag_set);
1496 if (err)
1497 goto out_free_idr;
1498
1499 q = blk_mq_init_queue(&nbd->tag_set);
1500 if (IS_ERR(q)) {
1501 err = PTR_ERR(q);
1502 goto out_free_tags;
1503 }
1504 disk->queue = q;
1505
1506 /*
1507 * Tell the block layer that we are not a rotational device
1508 */
8b904b5b
BVA
1509 blk_queue_flag_set(QUEUE_FLAG_NONROT, disk->queue);
1510 blk_queue_flag_clear(QUEUE_FLAG_ADD_RANDOM, disk->queue);
6df133a1
JB
1511 disk->queue->limits.discard_granularity = 0;
1512 blk_queue_max_discard_sectors(disk->queue, 0);
ebb16d0d 1513 blk_queue_max_segment_size(disk->queue, UINT_MAX);
1cc1f17a 1514 blk_queue_max_segments(disk->queue, USHRT_MAX);
b0d9111a
JB
1515 blk_queue_max_hw_sectors(disk->queue, 65536);
1516 disk->queue->limits.max_sectors = 256;
1517
b0d9111a 1518 mutex_init(&nbd->config_lock);
5ea8d108 1519 refcount_set(&nbd->config_refs, 0);
c6a4759e
JB
1520 refcount_set(&nbd->refs, 1);
1521 INIT_LIST_HEAD(&nbd->list);
b0d9111a
JB
1522 disk->major = NBD_MAJOR;
1523 disk->first_minor = index << part_shift;
1524 disk->fops = &nbd_fops;
1525 disk->private_data = nbd;
1526 sprintf(disk->disk_name, "nbd%d", index);
b0d9111a 1527 add_disk(disk);
47d902b9 1528 nbd_total_devices++;
b0d9111a
JB
1529 return index;
1530
1531out_free_tags:
1532 blk_mq_free_tag_set(&nbd->tag_set);
1533out_free_idr:
1534 idr_remove(&nbd_index_idr, index);
1535out_free_disk:
1536 put_disk(disk);
1537out_free_nbd:
1538 kfree(nbd);
1539out:
1540 return err;
1541}
1542
e46c7287
JB
1543static int find_free_cb(int id, void *ptr, void *data)
1544{
1545 struct nbd_device *nbd = ptr;
1546 struct nbd_device **found = data;
1547
1548 if (!refcount_read(&nbd->config_refs)) {
1549 *found = nbd;
1550 return 1;
1551 }
1552 return 0;
1553}
1554
1555/* Netlink interface. */
1556static struct nla_policy nbd_attr_policy[NBD_ATTR_MAX + 1] = {
1557 [NBD_ATTR_INDEX] = { .type = NLA_U32 },
1558 [NBD_ATTR_SIZE_BYTES] = { .type = NLA_U64 },
1559 [NBD_ATTR_BLOCK_SIZE_BYTES] = { .type = NLA_U64 },
1560 [NBD_ATTR_TIMEOUT] = { .type = NLA_U64 },
1561 [NBD_ATTR_SERVER_FLAGS] = { .type = NLA_U64 },
1562 [NBD_ATTR_CLIENT_FLAGS] = { .type = NLA_U64 },
1563 [NBD_ATTR_SOCKETS] = { .type = NLA_NESTED},
560bc4b3 1564 [NBD_ATTR_DEAD_CONN_TIMEOUT] = { .type = NLA_U64 },
47d902b9 1565 [NBD_ATTR_DEVICE_LIST] = { .type = NLA_NESTED},
e46c7287
JB
1566};
1567
1568static struct nla_policy nbd_sock_policy[NBD_SOCK_MAX + 1] = {
1569 [NBD_SOCK_FD] = { .type = NLA_U32 },
1570};
1571
47d902b9
JB
1572/* We don't use this right now since we don't parse the incoming list, but we
1573 * still want it here so userspace knows what to expect.
1574 */
1575static struct nla_policy __attribute__((unused))
1576nbd_device_policy[NBD_DEVICE_ATTR_MAX + 1] = {
1577 [NBD_DEVICE_INDEX] = { .type = NLA_U32 },
1578 [NBD_DEVICE_CONNECTED] = { .type = NLA_U8 },
1579};
1580
e46c7287
JB
1581static int nbd_genl_connect(struct sk_buff *skb, struct genl_info *info)
1582{
1583 struct nbd_device *nbd = NULL;
1584 struct nbd_config *config;
1585 int index = -1;
1586 int ret;
a2c97909 1587 bool put_dev = false;
e46c7287
JB
1588
1589 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1590 return -EPERM;
1591
1592 if (info->attrs[NBD_ATTR_INDEX])
1593 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1594 if (!info->attrs[NBD_ATTR_SOCKETS]) {
1595 printk(KERN_ERR "nbd: must specify at least one socket\n");
1596 return -EINVAL;
1597 }
1598 if (!info->attrs[NBD_ATTR_SIZE_BYTES]) {
1599 printk(KERN_ERR "nbd: must specify a size in bytes for the device\n");
1600 return -EINVAL;
1601 }
1602again:
1603 mutex_lock(&nbd_index_mutex);
1604 if (index == -1) {
1605 ret = idr_for_each(&nbd_index_idr, &find_free_cb, &nbd);
1606 if (ret == 0) {
1607 int new_index;
1608 new_index = nbd_dev_add(-1);
1609 if (new_index < 0) {
1610 mutex_unlock(&nbd_index_mutex);
1611 printk(KERN_ERR "nbd: failed to add new device\n");
0979962f 1612 return new_index;
e46c7287
JB
1613 }
1614 nbd = idr_find(&nbd_index_idr, new_index);
1615 }
1616 } else {
1617 nbd = idr_find(&nbd_index_idr, index);
e6a76272
JB
1618 if (!nbd) {
1619 ret = nbd_dev_add(index);
1620 if (ret < 0) {
1621 mutex_unlock(&nbd_index_mutex);
1622 printk(KERN_ERR "nbd: failed to add new device\n");
1623 return ret;
1624 }
1625 nbd = idr_find(&nbd_index_idr, index);
1626 }
e46c7287 1627 }
e46c7287
JB
1628 if (!nbd) {
1629 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1630 index);
c6a4759e
JB
1631 mutex_unlock(&nbd_index_mutex);
1632 return -EINVAL;
1633 }
1634 if (!refcount_inc_not_zero(&nbd->refs)) {
1635 mutex_unlock(&nbd_index_mutex);
1636 if (index == -1)
1637 goto again;
1638 printk(KERN_ERR "nbd: device at index %d is going down\n",
1639 index);
e46c7287
JB
1640 return -EINVAL;
1641 }
c6a4759e 1642 mutex_unlock(&nbd_index_mutex);
e46c7287
JB
1643
1644 mutex_lock(&nbd->config_lock);
1645 if (refcount_read(&nbd->config_refs)) {
1646 mutex_unlock(&nbd->config_lock);
c6a4759e 1647 nbd_put(nbd);
e46c7287
JB
1648 if (index == -1)
1649 goto again;
1650 printk(KERN_ERR "nbd: nbd%d already in use\n", index);
1651 return -EBUSY;
1652 }
1653 if (WARN_ON(nbd->config)) {
1654 mutex_unlock(&nbd->config_lock);
c6a4759e 1655 nbd_put(nbd);
e46c7287
JB
1656 return -EINVAL;
1657 }
1658 config = nbd->config = nbd_alloc_config();
1659 if (!nbd->config) {
1660 mutex_unlock(&nbd->config_lock);
c6a4759e 1661 nbd_put(nbd);
e46c7287
JB
1662 printk(KERN_ERR "nbd: couldn't allocate config\n");
1663 return -ENOMEM;
1664 }
1665 refcount_set(&nbd->config_refs, 1);
1666 set_bit(NBD_BOUND, &config->runtime_flags);
1667
1668 if (info->attrs[NBD_ATTR_SIZE_BYTES]) {
1669 u64 bytes = nla_get_u64(info->attrs[NBD_ATTR_SIZE_BYTES]);
1670 nbd_size_set(nbd, config->blksize,
1671 div64_u64(bytes, config->blksize));
1672 }
1673 if (info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]) {
1674 u64 bsize =
1675 nla_get_u64(info->attrs[NBD_ATTR_BLOCK_SIZE_BYTES]);
1676 nbd_size_set(nbd, bsize, div64_u64(config->bytesize, bsize));
1677 }
1678 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1679 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1680 nbd->tag_set.timeout = timeout * HZ;
1681 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1682 }
560bc4b3
JB
1683 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1684 config->dead_conn_timeout =
1685 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1686 config->dead_conn_timeout *= HZ;
1687 }
e46c7287
JB
1688 if (info->attrs[NBD_ATTR_SERVER_FLAGS])
1689 config->flags =
1690 nla_get_u64(info->attrs[NBD_ATTR_SERVER_FLAGS]);
a2c97909
JB
1691 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1692 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1693 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1694 set_bit(NBD_DESTROY_ON_DISCONNECT,
1695 &config->runtime_flags);
1696 put_dev = true;
1697 }
1698 }
1699
e46c7287
JB
1700 if (info->attrs[NBD_ATTR_SOCKETS]) {
1701 struct nlattr *attr;
1702 int rem, fd;
1703
1704 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1705 rem) {
1706 struct nlattr *socks[NBD_SOCK_MAX+1];
1707
1708 if (nla_type(attr) != NBD_SOCK_ITEM) {
1709 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1710 ret = -EINVAL;
1711 goto out;
1712 }
1713 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
8d65b08d 1714 nbd_sock_policy, info->extack);
e46c7287
JB
1715 if (ret != 0) {
1716 printk(KERN_ERR "nbd: error processing sock list\n");
1717 ret = -EINVAL;
1718 goto out;
1719 }
1720 if (!socks[NBD_SOCK_FD])
1721 continue;
1722 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1723 ret = nbd_add_socket(nbd, fd, true);
1724 if (ret)
1725 goto out;
1726 }
1727 }
1728 ret = nbd_start_device(nbd);
1729out:
1730 mutex_unlock(&nbd->config_lock);
1731 if (!ret) {
1732 set_bit(NBD_HAS_CONFIG_REF, &config->runtime_flags);
1733 refcount_inc(&nbd->config_refs);
1734 nbd_connect_reply(info, nbd->index);
1735 }
1736 nbd_config_put(nbd);
a2c97909
JB
1737 if (put_dev)
1738 nbd_put(nbd);
e46c7287
JB
1739 return ret;
1740}
1741
1742static int nbd_genl_disconnect(struct sk_buff *skb, struct genl_info *info)
1743{
1744 struct nbd_device *nbd;
1745 int index;
1746
1747 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1748 return -EPERM;
1749
1750 if (!info->attrs[NBD_ATTR_INDEX]) {
1751 printk(KERN_ERR "nbd: must specify an index to disconnect\n");
1752 return -EINVAL;
1753 }
1754 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1755 mutex_lock(&nbd_index_mutex);
1756 nbd = idr_find(&nbd_index_idr, index);
e46c7287 1757 if (!nbd) {
c6a4759e 1758 mutex_unlock(&nbd_index_mutex);
e46c7287
JB
1759 printk(KERN_ERR "nbd: couldn't find device at index %d\n",
1760 index);
1761 return -EINVAL;
1762 }
c6a4759e
JB
1763 if (!refcount_inc_not_zero(&nbd->refs)) {
1764 mutex_unlock(&nbd_index_mutex);
1765 printk(KERN_ERR "nbd: device at index %d is going down\n",
1766 index);
1767 return -EINVAL;
1768 }
1769 mutex_unlock(&nbd_index_mutex);
1770 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1771 nbd_put(nbd);
e46c7287 1772 return 0;
c6a4759e 1773 }
e46c7287
JB
1774 mutex_lock(&nbd->config_lock);
1775 nbd_disconnect(nbd);
96d97e17 1776 nbd_clear_sock(nbd);
e46c7287
JB
1777 mutex_unlock(&nbd->config_lock);
1778 if (test_and_clear_bit(NBD_HAS_CONFIG_REF,
1779 &nbd->config->runtime_flags))
1780 nbd_config_put(nbd);
1781 nbd_config_put(nbd);
c6a4759e 1782 nbd_put(nbd);
e46c7287
JB
1783 return 0;
1784}
1785
b7aa3d39
JB
1786static int nbd_genl_reconfigure(struct sk_buff *skb, struct genl_info *info)
1787{
1788 struct nbd_device *nbd = NULL;
1789 struct nbd_config *config;
1790 int index;
1791 int ret = -EINVAL;
a2c97909 1792 bool put_dev = false;
b7aa3d39
JB
1793
1794 if (!netlink_capable(skb, CAP_SYS_ADMIN))
1795 return -EPERM;
1796
1797 if (!info->attrs[NBD_ATTR_INDEX]) {
1798 printk(KERN_ERR "nbd: must specify a device to reconfigure\n");
1799 return -EINVAL;
1800 }
1801 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1802 mutex_lock(&nbd_index_mutex);
1803 nbd = idr_find(&nbd_index_idr, index);
b7aa3d39 1804 if (!nbd) {
c6a4759e 1805 mutex_unlock(&nbd_index_mutex);
b7aa3d39
JB
1806 printk(KERN_ERR "nbd: couldn't find a device at index %d\n",
1807 index);
1808 return -EINVAL;
1809 }
c6a4759e
JB
1810 if (!refcount_inc_not_zero(&nbd->refs)) {
1811 mutex_unlock(&nbd_index_mutex);
1812 printk(KERN_ERR "nbd: device at index %d is going down\n",
1813 index);
1814 return -EINVAL;
1815 }
1816 mutex_unlock(&nbd_index_mutex);
b7aa3d39
JB
1817
1818 if (!refcount_inc_not_zero(&nbd->config_refs)) {
1819 dev_err(nbd_to_dev(nbd),
1820 "not configured, cannot reconfigure\n");
c6a4759e 1821 nbd_put(nbd);
b7aa3d39
JB
1822 return -EINVAL;
1823 }
1824
1825 mutex_lock(&nbd->config_lock);
1826 config = nbd->config;
1827 if (!test_bit(NBD_BOUND, &config->runtime_flags) ||
1828 !nbd->task_recv) {
1829 dev_err(nbd_to_dev(nbd),
1830 "not configured, cannot reconfigure\n");
1831 goto out;
1832 }
1833
1834 if (info->attrs[NBD_ATTR_TIMEOUT]) {
1835 u64 timeout = nla_get_u64(info->attrs[NBD_ATTR_TIMEOUT]);
1836 nbd->tag_set.timeout = timeout * HZ;
1837 blk_queue_rq_timeout(nbd->disk->queue, timeout * HZ);
1838 }
560bc4b3
JB
1839 if (info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]) {
1840 config->dead_conn_timeout =
1841 nla_get_u64(info->attrs[NBD_ATTR_DEAD_CONN_TIMEOUT]);
1842 config->dead_conn_timeout *= HZ;
1843 }
a2c97909
JB
1844 if (info->attrs[NBD_ATTR_CLIENT_FLAGS]) {
1845 u64 flags = nla_get_u64(info->attrs[NBD_ATTR_CLIENT_FLAGS]);
1846 if (flags & NBD_CFLAG_DESTROY_ON_DISCONNECT) {
1847 if (!test_and_set_bit(NBD_DESTROY_ON_DISCONNECT,
1848 &config->runtime_flags))
1849 put_dev = true;
1850 } else {
1851 if (test_and_clear_bit(NBD_DESTROY_ON_DISCONNECT,
1852 &config->runtime_flags))
1853 refcount_inc(&nbd->refs);
1854 }
1855 }
b7aa3d39
JB
1856
1857 if (info->attrs[NBD_ATTR_SOCKETS]) {
1858 struct nlattr *attr;
1859 int rem, fd;
1860
1861 nla_for_each_nested(attr, info->attrs[NBD_ATTR_SOCKETS],
1862 rem) {
1863 struct nlattr *socks[NBD_SOCK_MAX+1];
1864
1865 if (nla_type(attr) != NBD_SOCK_ITEM) {
1866 printk(KERN_ERR "nbd: socks must be embedded in a SOCK_ITEM attr\n");
1867 ret = -EINVAL;
1868 goto out;
1869 }
1870 ret = nla_parse_nested(socks, NBD_SOCK_MAX, attr,
8d65b08d 1871 nbd_sock_policy, info->extack);
b7aa3d39
JB
1872 if (ret != 0) {
1873 printk(KERN_ERR "nbd: error processing sock list\n");
1874 ret = -EINVAL;
1875 goto out;
1876 }
1877 if (!socks[NBD_SOCK_FD])
1878 continue;
1879 fd = (int)nla_get_u32(socks[NBD_SOCK_FD]);
1880 ret = nbd_reconnect_socket(nbd, fd);
1881 if (ret) {
1882 if (ret == -ENOSPC)
1883 ret = 0;
1884 goto out;
1885 }
1886 dev_info(nbd_to_dev(nbd), "reconnected socket\n");
1887 }
1888 }
1889out:
1890 mutex_unlock(&nbd->config_lock);
1891 nbd_config_put(nbd);
c6a4759e 1892 nbd_put(nbd);
a2c97909
JB
1893 if (put_dev)
1894 nbd_put(nbd);
b7aa3d39
JB
1895 return ret;
1896}
1897
e46c7287
JB
1898static const struct genl_ops nbd_connect_genl_ops[] = {
1899 {
1900 .cmd = NBD_CMD_CONNECT,
1901 .policy = nbd_attr_policy,
1902 .doit = nbd_genl_connect,
1903 },
1904 {
1905 .cmd = NBD_CMD_DISCONNECT,
1906 .policy = nbd_attr_policy,
1907 .doit = nbd_genl_disconnect,
1908 },
b7aa3d39
JB
1909 {
1910 .cmd = NBD_CMD_RECONFIGURE,
1911 .policy = nbd_attr_policy,
1912 .doit = nbd_genl_reconfigure,
1913 },
47d902b9
JB
1914 {
1915 .cmd = NBD_CMD_STATUS,
1916 .policy = nbd_attr_policy,
1917 .doit = nbd_genl_status,
1918 },
e46c7287
JB
1919};
1920
799f9a38
JB
1921static const struct genl_multicast_group nbd_mcast_grps[] = {
1922 { .name = NBD_GENL_MCAST_GROUP_NAME, },
1923};
1924
e46c7287
JB
1925static struct genl_family nbd_genl_family __ro_after_init = {
1926 .hdrsize = 0,
1927 .name = NBD_GENL_FAMILY_NAME,
1928 .version = NBD_GENL_VERSION,
1929 .module = THIS_MODULE,
1930 .ops = nbd_connect_genl_ops,
1931 .n_ops = ARRAY_SIZE(nbd_connect_genl_ops),
1932 .maxattr = NBD_ATTR_MAX,
799f9a38
JB
1933 .mcgrps = nbd_mcast_grps,
1934 .n_mcgrps = ARRAY_SIZE(nbd_mcast_grps),
e46c7287
JB
1935};
1936
47d902b9
JB
1937static int populate_nbd_status(struct nbd_device *nbd, struct sk_buff *reply)
1938{
1939 struct nlattr *dev_opt;
1940 u8 connected = 0;
1941 int ret;
1942
1943 /* This is a little racey, but for status it's ok. The
1944 * reason we don't take a ref here is because we can't
1945 * take a ref in the index == -1 case as we would need
1946 * to put under the nbd_index_mutex, which could
1947 * deadlock if we are configured to remove ourselves
1948 * once we're disconnected.
1949 */
1950 if (refcount_read(&nbd->config_refs))
1951 connected = 1;
1952 dev_opt = nla_nest_start(reply, NBD_DEVICE_ITEM);
1953 if (!dev_opt)
1954 return -EMSGSIZE;
1955 ret = nla_put_u32(reply, NBD_DEVICE_INDEX, nbd->index);
1956 if (ret)
1957 return -EMSGSIZE;
1958 ret = nla_put_u8(reply, NBD_DEVICE_CONNECTED,
1959 connected);
1960 if (ret)
1961 return -EMSGSIZE;
1962 nla_nest_end(reply, dev_opt);
1963 return 0;
1964}
1965
1966static int status_cb(int id, void *ptr, void *data)
1967{
1968 struct nbd_device *nbd = ptr;
1969 return populate_nbd_status(nbd, (struct sk_buff *)data);
1970}
1971
1972static int nbd_genl_status(struct sk_buff *skb, struct genl_info *info)
1973{
1974 struct nlattr *dev_list;
1975 struct sk_buff *reply;
1976 void *reply_head;
1977 size_t msg_size;
1978 int index = -1;
1979 int ret = -ENOMEM;
1980
1981 if (info->attrs[NBD_ATTR_INDEX])
1982 index = nla_get_u32(info->attrs[NBD_ATTR_INDEX]);
1983
1984 mutex_lock(&nbd_index_mutex);
1985
1986 msg_size = nla_total_size(nla_attr_size(sizeof(u32)) +
1987 nla_attr_size(sizeof(u8)));
1988 msg_size *= (index == -1) ? nbd_total_devices : 1;
1989
1990 reply = genlmsg_new(msg_size, GFP_KERNEL);
1991 if (!reply)
1992 goto out;
1993 reply_head = genlmsg_put_reply(reply, info, &nbd_genl_family, 0,
1994 NBD_CMD_STATUS);
1995 if (!reply_head) {
1996 nlmsg_free(reply);
1997 goto out;
1998 }
1999
2000 dev_list = nla_nest_start(reply, NBD_ATTR_DEVICE_LIST);
2001 if (index == -1) {
2002 ret = idr_for_each(&nbd_index_idr, &status_cb, reply);
2003 if (ret) {
2004 nlmsg_free(reply);
2005 goto out;
2006 }
2007 } else {
2008 struct nbd_device *nbd;
2009 nbd = idr_find(&nbd_index_idr, index);
2010 if (nbd) {
2011 ret = populate_nbd_status(nbd, reply);
2012 if (ret) {
2013 nlmsg_free(reply);
2014 goto out;
2015 }
2016 }
2017 }
2018 nla_nest_end(reply, dev_list);
2019 genlmsg_end(reply, reply_head);
2020 genlmsg_reply(reply, info);
2021 ret = 0;
2022out:
2023 mutex_unlock(&nbd_index_mutex);
2024 return ret;
2025}
2026
e46c7287
JB
2027static void nbd_connect_reply(struct genl_info *info, int index)
2028{
2029 struct sk_buff *skb;
2030 void *msg_head;
2031 int ret;
2032
2033 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2034 if (!skb)
2035 return;
2036 msg_head = genlmsg_put_reply(skb, info, &nbd_genl_family, 0,
2037 NBD_CMD_CONNECT);
2038 if (!msg_head) {
2039 nlmsg_free(skb);
2040 return;
2041 }
2042 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2043 if (ret) {
2044 nlmsg_free(skb);
2045 return;
2046 }
2047 genlmsg_end(skb, msg_head);
2048 genlmsg_reply(skb, info);
2049}
1da177e4 2050
799f9a38
JB
2051static void nbd_mcast_index(int index)
2052{
2053 struct sk_buff *skb;
2054 void *msg_head;
2055 int ret;
2056
2057 skb = genlmsg_new(nla_total_size(sizeof(u32)), GFP_KERNEL);
2058 if (!skb)
2059 return;
2060 msg_head = genlmsg_put(skb, 0, 0, &nbd_genl_family, 0,
2061 NBD_CMD_LINK_DEAD);
2062 if (!msg_head) {
2063 nlmsg_free(skb);
2064 return;
2065 }
2066 ret = nla_put_u32(skb, NBD_ATTR_INDEX, index);
2067 if (ret) {
2068 nlmsg_free(skb);
2069 return;
2070 }
2071 genlmsg_end(skb, msg_head);
2072 genlmsg_multicast(&nbd_genl_family, skb, 0, 0, GFP_KERNEL);
2073}
2074
2075static void nbd_dead_link_work(struct work_struct *work)
2076{
2077 struct link_dead_args *args = container_of(work, struct link_dead_args,
2078 work);
2079 nbd_mcast_index(args->index);
2080 kfree(args);
2081}
2082
1da177e4
LT
2083static int __init nbd_init(void)
2084{
1da177e4
LT
2085 int i;
2086
5b7b18cc 2087 BUILD_BUG_ON(sizeof(struct nbd_request) != 28);
1da177e4 2088
d71a6d73 2089 if (max_part < 0) {
7742ce4a 2090 printk(KERN_ERR "nbd: max_part must be >= 0\n");
d71a6d73
LV
2091 return -EINVAL;
2092 }
2093
2094 part_shift = 0;
5988ce23 2095 if (max_part > 0) {
d71a6d73
LV
2096 part_shift = fls(max_part);
2097
5988ce23
NK
2098 /*
2099 * Adjust max_part according to part_shift as it is exported
2100 * to user space so that user can know the max number of
2101 * partition kernel should be able to manage.
2102 *
2103 * Note that -1 is required because partition 0 is reserved
2104 * for the whole disk.
2105 */
2106 max_part = (1UL << part_shift) - 1;
2107 }
2108
3b271082
NK
2109 if ((1UL << part_shift) > DISK_MAX_PARTS)
2110 return -EINVAL;
2111
2112 if (nbds_max > 1UL << (MINORBITS - part_shift))
2113 return -EINVAL;
124d6db0 2114 recv_workqueue = alloc_workqueue("knbd-recv",
2189c97c
DM
2115 WQ_MEM_RECLAIM | WQ_HIGHPRI |
2116 WQ_UNBOUND, 0);
124d6db0
JB
2117 if (!recv_workqueue)
2118 return -ENOMEM;
3b271082 2119
6330a2d0
JB
2120 if (register_blkdev(NBD_MAJOR, "nbd")) {
2121 destroy_workqueue(recv_workqueue);
b0d9111a 2122 return -EIO;
6330a2d0 2123 }
1da177e4 2124
e46c7287
JB
2125 if (genl_register_family(&nbd_genl_family)) {
2126 unregister_blkdev(NBD_MAJOR, "nbd");
2127 destroy_workqueue(recv_workqueue);
2128 return -EINVAL;
2129 }
30d53d9c
MP
2130 nbd_dbg_init();
2131
b0d9111a
JB
2132 mutex_lock(&nbd_index_mutex);
2133 for (i = 0; i < nbds_max; i++)
2134 nbd_dev_add(i);
2135 mutex_unlock(&nbd_index_mutex);
2136 return 0;
2137}
1da177e4 2138
b0d9111a
JB
2139static int nbd_exit_cb(int id, void *ptr, void *data)
2140{
c6a4759e 2141 struct list_head *list = (struct list_head *)data;
b0d9111a 2142 struct nbd_device *nbd = ptr;
c6a4759e 2143
c6a4759e 2144 list_add_tail(&nbd->list, list);
1da177e4 2145 return 0;
1da177e4
LT
2146}
2147
2148static void __exit nbd_cleanup(void)
2149{
c6a4759e
JB
2150 struct nbd_device *nbd;
2151 LIST_HEAD(del_list);
2152
30d53d9c
MP
2153 nbd_dbg_close();
2154
c6a4759e
JB
2155 mutex_lock(&nbd_index_mutex);
2156 idr_for_each(&nbd_index_idr, &nbd_exit_cb, &del_list);
2157 mutex_unlock(&nbd_index_mutex);
2158
60ae36ad
JB
2159 while (!list_empty(&del_list)) {
2160 nbd = list_first_entry(&del_list, struct nbd_device, list);
2161 list_del_init(&nbd->list);
2162 if (refcount_read(&nbd->refs) != 1)
c6a4759e
JB
2163 printk(KERN_ERR "nbd: possibly leaking a device\n");
2164 nbd_put(nbd);
c6a4759e
JB
2165 }
2166
b0d9111a 2167 idr_destroy(&nbd_index_idr);
e46c7287 2168 genl_unregister_family(&nbd_genl_family);
124d6db0 2169 destroy_workqueue(recv_workqueue);
1da177e4 2170 unregister_blkdev(NBD_MAJOR, "nbd");
1da177e4
LT
2171}
2172
2173module_init(nbd_init);
2174module_exit(nbd_cleanup);
2175
2176MODULE_DESCRIPTION("Network Block Device");
2177MODULE_LICENSE("GPL");
2178
40be0c28 2179module_param(nbds_max, int, 0444);
d71a6d73
LV
2180MODULE_PARM_DESC(nbds_max, "number of network block devices to initialize (default: 16)");
2181module_param(max_part, int, 0444);
7a8362a0 2182MODULE_PARM_DESC(max_part, "number of partitions per device (default: 16)");