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