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