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