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