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