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