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