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