1 // SPDX-License-Identifier: GPL-2.0 2 /* 3 * NVM Express device driver 4 * Copyright (c) 2011-2014, Intel Corporation. 5 */ 6 7 #include <linux/blkdev.h> 8 #include <linux/blk-mq.h> 9 #include <linux/compat.h> 10 #include <linux/delay.h> 11 #include <linux/errno.h> 12 #include <linux/hdreg.h> 13 #include <linux/kernel.h> 14 #include <linux/module.h> 15 #include <linux/backing-dev.h> 16 #include <linux/list_sort.h> 17 #include <linux/slab.h> 18 #include <linux/types.h> 19 #include <linux/pr.h> 20 #include <linux/ptrace.h> 21 #include <linux/nvme_ioctl.h> 22 #include <linux/pm_qos.h> 23 #include <asm/unaligned.h> 24 25 #include "nvme.h" 26 #include "fabrics.h" 27 28 #define CREATE_TRACE_POINTS 29 #include "trace.h" 30 31 #define NVME_MINORS (1U << MINORBITS) 32 33 unsigned int admin_timeout = 60; 34 module_param(admin_timeout, uint, 0644); 35 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands"); 36 EXPORT_SYMBOL_GPL(admin_timeout); 37 38 unsigned int nvme_io_timeout = 30; 39 module_param_named(io_timeout, nvme_io_timeout, uint, 0644); 40 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O"); 41 EXPORT_SYMBOL_GPL(nvme_io_timeout); 42 43 static unsigned char shutdown_timeout = 5; 44 module_param(shutdown_timeout, byte, 0644); 45 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown"); 46 47 static u8 nvme_max_retries = 5; 48 module_param_named(max_retries, nvme_max_retries, byte, 0644); 49 MODULE_PARM_DESC(max_retries, "max number of retries a command may have"); 50 51 static unsigned long default_ps_max_latency_us = 100000; 52 module_param(default_ps_max_latency_us, ulong, 0644); 53 MODULE_PARM_DESC(default_ps_max_latency_us, 54 "max power saving latency for new devices; use PM QOS to change per device"); 55 56 static bool force_apst; 57 module_param(force_apst, bool, 0644); 58 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off"); 59 60 static unsigned long apst_primary_timeout_ms = 100; 61 module_param(apst_primary_timeout_ms, ulong, 0644); 62 MODULE_PARM_DESC(apst_primary_timeout_ms, 63 "primary APST timeout in ms"); 64 65 static unsigned long apst_secondary_timeout_ms = 2000; 66 module_param(apst_secondary_timeout_ms, ulong, 0644); 67 MODULE_PARM_DESC(apst_secondary_timeout_ms, 68 "secondary APST timeout in ms"); 69 70 static unsigned long apst_primary_latency_tol_us = 15000; 71 module_param(apst_primary_latency_tol_us, ulong, 0644); 72 MODULE_PARM_DESC(apst_primary_latency_tol_us, 73 "primary APST latency tolerance in us"); 74 75 static unsigned long apst_secondary_latency_tol_us = 100000; 76 module_param(apst_secondary_latency_tol_us, ulong, 0644); 77 MODULE_PARM_DESC(apst_secondary_latency_tol_us, 78 "secondary APST latency tolerance in us"); 79 80 static bool streams; 81 module_param(streams, bool, 0644); 82 MODULE_PARM_DESC(streams, "turn on support for Streams write directives"); 83 84 /* 85 * nvme_wq - hosts nvme related works that are not reset or delete 86 * nvme_reset_wq - hosts nvme reset works 87 * nvme_delete_wq - hosts nvme delete works 88 * 89 * nvme_wq will host works such as scan, aen handling, fw activation, 90 * keep-alive, periodic reconnects etc. nvme_reset_wq 91 * runs reset works which also flush works hosted on nvme_wq for 92 * serialization purposes. nvme_delete_wq host controller deletion 93 * works which flush reset works for serialization. 94 */ 95 struct workqueue_struct *nvme_wq; 96 EXPORT_SYMBOL_GPL(nvme_wq); 97 98 struct workqueue_struct *nvme_reset_wq; 99 EXPORT_SYMBOL_GPL(nvme_reset_wq); 100 101 struct workqueue_struct *nvme_delete_wq; 102 EXPORT_SYMBOL_GPL(nvme_delete_wq); 103 104 static LIST_HEAD(nvme_subsystems); 105 static DEFINE_MUTEX(nvme_subsystems_lock); 106 107 static DEFINE_IDA(nvme_instance_ida); 108 static dev_t nvme_ctrl_base_chr_devt; 109 static struct class *nvme_class; 110 static struct class *nvme_subsys_class; 111 112 static DEFINE_IDA(nvme_ns_chr_minor_ida); 113 static dev_t nvme_ns_chr_devt; 114 static struct class *nvme_ns_chr_class; 115 116 static void nvme_put_subsystem(struct nvme_subsystem *subsys); 117 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl, 118 unsigned nsid); 119 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl, 120 struct nvme_command *cmd); 121 122 /* 123 * Prepare a queue for teardown. 124 * 125 * This must forcibly unquiesce queues to avoid blocking dispatch, and only set 126 * the capacity to 0 after that to avoid blocking dispatchers that may be 127 * holding bd_butex. This will end buffered writers dirtying pages that can't 128 * be synced. 129 */ 130 static void nvme_set_queue_dying(struct nvme_ns *ns) 131 { 132 if (test_and_set_bit(NVME_NS_DEAD, &ns->flags)) 133 return; 134 135 blk_set_queue_dying(ns->queue); 136 blk_mq_unquiesce_queue(ns->queue); 137 138 set_capacity_and_notify(ns->disk, 0); 139 } 140 141 void nvme_queue_scan(struct nvme_ctrl *ctrl) 142 { 143 /* 144 * Only new queue scan work when admin and IO queues are both alive 145 */ 146 if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset) 147 queue_work(nvme_wq, &ctrl->scan_work); 148 } 149 150 /* 151 * Use this function to proceed with scheduling reset_work for a controller 152 * that had previously been set to the resetting state. This is intended for 153 * code paths that can't be interrupted by other reset attempts. A hot removal 154 * may prevent this from succeeding. 155 */ 156 int nvme_try_sched_reset(struct nvme_ctrl *ctrl) 157 { 158 if (ctrl->state != NVME_CTRL_RESETTING) 159 return -EBUSY; 160 if (!queue_work(nvme_reset_wq, &ctrl->reset_work)) 161 return -EBUSY; 162 return 0; 163 } 164 EXPORT_SYMBOL_GPL(nvme_try_sched_reset); 165 166 static void nvme_failfast_work(struct work_struct *work) 167 { 168 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work), 169 struct nvme_ctrl, failfast_work); 170 171 if (ctrl->state != NVME_CTRL_CONNECTING) 172 return; 173 174 set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 175 dev_info(ctrl->device, "failfast expired\n"); 176 nvme_kick_requeue_lists(ctrl); 177 } 178 179 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl) 180 { 181 if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1) 182 return; 183 184 schedule_delayed_work(&ctrl->failfast_work, 185 ctrl->opts->fast_io_fail_tmo * HZ); 186 } 187 188 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl) 189 { 190 if (!ctrl->opts) 191 return; 192 193 cancel_delayed_work_sync(&ctrl->failfast_work); 194 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 195 } 196 197 198 int nvme_reset_ctrl(struct nvme_ctrl *ctrl) 199 { 200 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) 201 return -EBUSY; 202 if (!queue_work(nvme_reset_wq, &ctrl->reset_work)) 203 return -EBUSY; 204 return 0; 205 } 206 EXPORT_SYMBOL_GPL(nvme_reset_ctrl); 207 208 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl) 209 { 210 int ret; 211 212 ret = nvme_reset_ctrl(ctrl); 213 if (!ret) { 214 flush_work(&ctrl->reset_work); 215 if (ctrl->state != NVME_CTRL_LIVE) 216 ret = -ENETRESET; 217 } 218 219 return ret; 220 } 221 222 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl) 223 { 224 dev_info(ctrl->device, 225 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn); 226 227 flush_work(&ctrl->reset_work); 228 nvme_stop_ctrl(ctrl); 229 nvme_remove_namespaces(ctrl); 230 ctrl->ops->delete_ctrl(ctrl); 231 nvme_uninit_ctrl(ctrl); 232 } 233 234 static void nvme_delete_ctrl_work(struct work_struct *work) 235 { 236 struct nvme_ctrl *ctrl = 237 container_of(work, struct nvme_ctrl, delete_work); 238 239 nvme_do_delete_ctrl(ctrl); 240 } 241 242 int nvme_delete_ctrl(struct nvme_ctrl *ctrl) 243 { 244 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING)) 245 return -EBUSY; 246 if (!queue_work(nvme_delete_wq, &ctrl->delete_work)) 247 return -EBUSY; 248 return 0; 249 } 250 EXPORT_SYMBOL_GPL(nvme_delete_ctrl); 251 252 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl) 253 { 254 /* 255 * Keep a reference until nvme_do_delete_ctrl() complete, 256 * since ->delete_ctrl can free the controller. 257 */ 258 nvme_get_ctrl(ctrl); 259 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING)) 260 nvme_do_delete_ctrl(ctrl); 261 nvme_put_ctrl(ctrl); 262 } 263 264 static blk_status_t nvme_error_status(u16 status) 265 { 266 switch (status & 0x7ff) { 267 case NVME_SC_SUCCESS: 268 return BLK_STS_OK; 269 case NVME_SC_CAP_EXCEEDED: 270 return BLK_STS_NOSPC; 271 case NVME_SC_LBA_RANGE: 272 case NVME_SC_CMD_INTERRUPTED: 273 case NVME_SC_NS_NOT_READY: 274 return BLK_STS_TARGET; 275 case NVME_SC_BAD_ATTRIBUTES: 276 case NVME_SC_ONCS_NOT_SUPPORTED: 277 case NVME_SC_INVALID_OPCODE: 278 case NVME_SC_INVALID_FIELD: 279 case NVME_SC_INVALID_NS: 280 return BLK_STS_NOTSUPP; 281 case NVME_SC_WRITE_FAULT: 282 case NVME_SC_READ_ERROR: 283 case NVME_SC_UNWRITTEN_BLOCK: 284 case NVME_SC_ACCESS_DENIED: 285 case NVME_SC_READ_ONLY: 286 case NVME_SC_COMPARE_FAILED: 287 return BLK_STS_MEDIUM; 288 case NVME_SC_GUARD_CHECK: 289 case NVME_SC_APPTAG_CHECK: 290 case NVME_SC_REFTAG_CHECK: 291 case NVME_SC_INVALID_PI: 292 return BLK_STS_PROTECTION; 293 case NVME_SC_RESERVATION_CONFLICT: 294 return BLK_STS_NEXUS; 295 case NVME_SC_HOST_PATH_ERROR: 296 return BLK_STS_TRANSPORT; 297 case NVME_SC_ZONE_TOO_MANY_ACTIVE: 298 return BLK_STS_ZONE_ACTIVE_RESOURCE; 299 case NVME_SC_ZONE_TOO_MANY_OPEN: 300 return BLK_STS_ZONE_OPEN_RESOURCE; 301 default: 302 return BLK_STS_IOERR; 303 } 304 } 305 306 static void nvme_retry_req(struct request *req) 307 { 308 unsigned long delay = 0; 309 u16 crd; 310 311 /* The mask and shift result must be <= 3 */ 312 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11; 313 if (crd) 314 delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100; 315 316 nvme_req(req)->retries++; 317 blk_mq_requeue_request(req, false); 318 blk_mq_delay_kick_requeue_list(req->q, delay); 319 } 320 321 enum nvme_disposition { 322 COMPLETE, 323 RETRY, 324 FAILOVER, 325 }; 326 327 static inline enum nvme_disposition nvme_decide_disposition(struct request *req) 328 { 329 if (likely(nvme_req(req)->status == 0)) 330 return COMPLETE; 331 332 if (blk_noretry_request(req) || 333 (nvme_req(req)->status & NVME_SC_DNR) || 334 nvme_req(req)->retries >= nvme_max_retries) 335 return COMPLETE; 336 337 if (req->cmd_flags & REQ_NVME_MPATH) { 338 if (nvme_is_path_error(nvme_req(req)->status) || 339 blk_queue_dying(req->q)) 340 return FAILOVER; 341 } else { 342 if (blk_queue_dying(req->q)) 343 return COMPLETE; 344 } 345 346 return RETRY; 347 } 348 349 static inline void nvme_end_req(struct request *req) 350 { 351 blk_status_t status = nvme_error_status(nvme_req(req)->status); 352 353 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) && 354 req_op(req) == REQ_OP_ZONE_APPEND) 355 req->__sector = nvme_lba_to_sect(req->q->queuedata, 356 le64_to_cpu(nvme_req(req)->result.u64)); 357 358 nvme_trace_bio_complete(req); 359 blk_mq_end_request(req, status); 360 } 361 362 void nvme_complete_rq(struct request *req) 363 { 364 trace_nvme_complete_rq(req); 365 nvme_cleanup_cmd(req); 366 367 if (nvme_req(req)->ctrl->kas) 368 nvme_req(req)->ctrl->comp_seen = true; 369 370 switch (nvme_decide_disposition(req)) { 371 case COMPLETE: 372 nvme_end_req(req); 373 return; 374 case RETRY: 375 nvme_retry_req(req); 376 return; 377 case FAILOVER: 378 nvme_failover_req(req); 379 return; 380 } 381 } 382 EXPORT_SYMBOL_GPL(nvme_complete_rq); 383 384 /* 385 * Called to unwind from ->queue_rq on a failed command submission so that the 386 * multipathing code gets called to potentially failover to another path. 387 * The caller needs to unwind all transport specific resource allocations and 388 * must return propagate the return value. 389 */ 390 blk_status_t nvme_host_path_error(struct request *req) 391 { 392 nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR; 393 blk_mq_set_request_complete(req); 394 nvme_complete_rq(req); 395 return BLK_STS_OK; 396 } 397 EXPORT_SYMBOL_GPL(nvme_host_path_error); 398 399 bool nvme_cancel_request(struct request *req, void *data, bool reserved) 400 { 401 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device, 402 "Cancelling I/O %d", req->tag); 403 404 /* don't abort one completed request */ 405 if (blk_mq_request_completed(req)) 406 return true; 407 408 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD; 409 nvme_req(req)->flags |= NVME_REQ_CANCELLED; 410 blk_mq_complete_request(req); 411 return true; 412 } 413 EXPORT_SYMBOL_GPL(nvme_cancel_request); 414 415 void nvme_cancel_tagset(struct nvme_ctrl *ctrl) 416 { 417 if (ctrl->tagset) { 418 blk_mq_tagset_busy_iter(ctrl->tagset, 419 nvme_cancel_request, ctrl); 420 blk_mq_tagset_wait_completed_request(ctrl->tagset); 421 } 422 } 423 EXPORT_SYMBOL_GPL(nvme_cancel_tagset); 424 425 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl) 426 { 427 if (ctrl->admin_tagset) { 428 blk_mq_tagset_busy_iter(ctrl->admin_tagset, 429 nvme_cancel_request, ctrl); 430 blk_mq_tagset_wait_completed_request(ctrl->admin_tagset); 431 } 432 } 433 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset); 434 435 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl, 436 enum nvme_ctrl_state new_state) 437 { 438 enum nvme_ctrl_state old_state; 439 unsigned long flags; 440 bool changed = false; 441 442 spin_lock_irqsave(&ctrl->lock, flags); 443 444 old_state = ctrl->state; 445 switch (new_state) { 446 case NVME_CTRL_LIVE: 447 switch (old_state) { 448 case NVME_CTRL_NEW: 449 case NVME_CTRL_RESETTING: 450 case NVME_CTRL_CONNECTING: 451 changed = true; 452 fallthrough; 453 default: 454 break; 455 } 456 break; 457 case NVME_CTRL_RESETTING: 458 switch (old_state) { 459 case NVME_CTRL_NEW: 460 case NVME_CTRL_LIVE: 461 changed = true; 462 fallthrough; 463 default: 464 break; 465 } 466 break; 467 case NVME_CTRL_CONNECTING: 468 switch (old_state) { 469 case NVME_CTRL_NEW: 470 case NVME_CTRL_RESETTING: 471 changed = true; 472 fallthrough; 473 default: 474 break; 475 } 476 break; 477 case NVME_CTRL_DELETING: 478 switch (old_state) { 479 case NVME_CTRL_LIVE: 480 case NVME_CTRL_RESETTING: 481 case NVME_CTRL_CONNECTING: 482 changed = true; 483 fallthrough; 484 default: 485 break; 486 } 487 break; 488 case NVME_CTRL_DELETING_NOIO: 489 switch (old_state) { 490 case NVME_CTRL_DELETING: 491 case NVME_CTRL_DEAD: 492 changed = true; 493 fallthrough; 494 default: 495 break; 496 } 497 break; 498 case NVME_CTRL_DEAD: 499 switch (old_state) { 500 case NVME_CTRL_DELETING: 501 changed = true; 502 fallthrough; 503 default: 504 break; 505 } 506 break; 507 default: 508 break; 509 } 510 511 if (changed) { 512 ctrl->state = new_state; 513 wake_up_all(&ctrl->state_wq); 514 } 515 516 spin_unlock_irqrestore(&ctrl->lock, flags); 517 if (!changed) 518 return false; 519 520 if (ctrl->state == NVME_CTRL_LIVE) { 521 if (old_state == NVME_CTRL_CONNECTING) 522 nvme_stop_failfast_work(ctrl); 523 nvme_kick_requeue_lists(ctrl); 524 } else if (ctrl->state == NVME_CTRL_CONNECTING && 525 old_state == NVME_CTRL_RESETTING) { 526 nvme_start_failfast_work(ctrl); 527 } 528 return changed; 529 } 530 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state); 531 532 /* 533 * Returns true for sink states that can't ever transition back to live. 534 */ 535 static bool nvme_state_terminal(struct nvme_ctrl *ctrl) 536 { 537 switch (ctrl->state) { 538 case NVME_CTRL_NEW: 539 case NVME_CTRL_LIVE: 540 case NVME_CTRL_RESETTING: 541 case NVME_CTRL_CONNECTING: 542 return false; 543 case NVME_CTRL_DELETING: 544 case NVME_CTRL_DELETING_NOIO: 545 case NVME_CTRL_DEAD: 546 return true; 547 default: 548 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state); 549 return true; 550 } 551 } 552 553 /* 554 * Waits for the controller state to be resetting, or returns false if it is 555 * not possible to ever transition to that state. 556 */ 557 bool nvme_wait_reset(struct nvme_ctrl *ctrl) 558 { 559 wait_event(ctrl->state_wq, 560 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) || 561 nvme_state_terminal(ctrl)); 562 return ctrl->state == NVME_CTRL_RESETTING; 563 } 564 EXPORT_SYMBOL_GPL(nvme_wait_reset); 565 566 static void nvme_free_ns_head(struct kref *ref) 567 { 568 struct nvme_ns_head *head = 569 container_of(ref, struct nvme_ns_head, ref); 570 571 nvme_mpath_remove_disk(head); 572 ida_simple_remove(&head->subsys->ns_ida, head->instance); 573 cleanup_srcu_struct(&head->srcu); 574 nvme_put_subsystem(head->subsys); 575 kfree(head); 576 } 577 578 bool nvme_tryget_ns_head(struct nvme_ns_head *head) 579 { 580 return kref_get_unless_zero(&head->ref); 581 } 582 583 void nvme_put_ns_head(struct nvme_ns_head *head) 584 { 585 kref_put(&head->ref, nvme_free_ns_head); 586 } 587 588 static void nvme_free_ns(struct kref *kref) 589 { 590 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref); 591 592 put_disk(ns->disk); 593 nvme_put_ns_head(ns->head); 594 nvme_put_ctrl(ns->ctrl); 595 kfree(ns); 596 } 597 598 static inline bool nvme_get_ns(struct nvme_ns *ns) 599 { 600 return kref_get_unless_zero(&ns->kref); 601 } 602 603 void nvme_put_ns(struct nvme_ns *ns) 604 { 605 kref_put(&ns->kref, nvme_free_ns); 606 } 607 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU); 608 609 static inline void nvme_clear_nvme_request(struct request *req) 610 { 611 nvme_req(req)->status = 0; 612 nvme_req(req)->retries = 0; 613 nvme_req(req)->flags = 0; 614 req->rq_flags |= RQF_DONTPREP; 615 } 616 617 static inline unsigned int nvme_req_op(struct nvme_command *cmd) 618 { 619 return nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN; 620 } 621 622 static inline void nvme_init_request(struct request *req, 623 struct nvme_command *cmd) 624 { 625 if (req->q->queuedata) 626 req->timeout = NVME_IO_TIMEOUT; 627 else /* no queuedata implies admin queue */ 628 req->timeout = NVME_ADMIN_TIMEOUT; 629 630 /* passthru commands should let the driver set the SGL flags */ 631 cmd->common.flags &= ~NVME_CMD_SGL_ALL; 632 633 req->cmd_flags |= REQ_FAILFAST_DRIVER; 634 if (req->mq_hctx->type == HCTX_TYPE_POLL) 635 req->cmd_flags |= REQ_HIPRI; 636 nvme_clear_nvme_request(req); 637 memcpy(nvme_req(req)->cmd, cmd, sizeof(*cmd)); 638 } 639 640 struct request *nvme_alloc_request(struct request_queue *q, 641 struct nvme_command *cmd, blk_mq_req_flags_t flags) 642 { 643 struct request *req; 644 645 req = blk_mq_alloc_request(q, nvme_req_op(cmd), flags); 646 if (!IS_ERR(req)) 647 nvme_init_request(req, cmd); 648 return req; 649 } 650 EXPORT_SYMBOL_GPL(nvme_alloc_request); 651 652 static struct request *nvme_alloc_request_qid(struct request_queue *q, 653 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid) 654 { 655 struct request *req; 656 657 req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), flags, 658 qid ? qid - 1 : 0); 659 if (!IS_ERR(req)) 660 nvme_init_request(req, cmd); 661 return req; 662 } 663 664 /* 665 * For something we're not in a state to send to the device the default action 666 * is to busy it and retry it after the controller state is recovered. However, 667 * if the controller is deleting or if anything is marked for failfast or 668 * nvme multipath it is immediately failed. 669 * 670 * Note: commands used to initialize the controller will be marked for failfast. 671 * Note: nvme cli/ioctl commands are marked for failfast. 672 */ 673 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl, 674 struct request *rq) 675 { 676 if (ctrl->state != NVME_CTRL_DELETING_NOIO && 677 ctrl->state != NVME_CTRL_DEAD && 678 !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) && 679 !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH)) 680 return BLK_STS_RESOURCE; 681 return nvme_host_path_error(rq); 682 } 683 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command); 684 685 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq, 686 bool queue_live) 687 { 688 struct nvme_request *req = nvme_req(rq); 689 690 /* 691 * currently we have a problem sending passthru commands 692 * on the admin_q if the controller is not LIVE because we can't 693 * make sure that they are going out after the admin connect, 694 * controller enable and/or other commands in the initialization 695 * sequence. until the controller will be LIVE, fail with 696 * BLK_STS_RESOURCE so that they will be rescheduled. 697 */ 698 if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD)) 699 return false; 700 701 if (ctrl->ops->flags & NVME_F_FABRICS) { 702 /* 703 * Only allow commands on a live queue, except for the connect 704 * command, which is require to set the queue live in the 705 * appropinquate states. 706 */ 707 switch (ctrl->state) { 708 case NVME_CTRL_CONNECTING: 709 if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) && 710 req->cmd->fabrics.fctype == nvme_fabrics_type_connect) 711 return true; 712 break; 713 default: 714 break; 715 case NVME_CTRL_DEAD: 716 return false; 717 } 718 } 719 720 return queue_live; 721 } 722 EXPORT_SYMBOL_GPL(__nvme_check_ready); 723 724 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable) 725 { 726 struct nvme_command c = { }; 727 728 c.directive.opcode = nvme_admin_directive_send; 729 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL); 730 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE; 731 c.directive.dtype = NVME_DIR_IDENTIFY; 732 c.directive.tdtype = NVME_DIR_STREAMS; 733 c.directive.endir = enable ? NVME_DIR_ENDIR : 0; 734 735 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0); 736 } 737 738 static int nvme_disable_streams(struct nvme_ctrl *ctrl) 739 { 740 return nvme_toggle_streams(ctrl, false); 741 } 742 743 static int nvme_enable_streams(struct nvme_ctrl *ctrl) 744 { 745 return nvme_toggle_streams(ctrl, true); 746 } 747 748 static int nvme_get_stream_params(struct nvme_ctrl *ctrl, 749 struct streams_directive_params *s, u32 nsid) 750 { 751 struct nvme_command c = { }; 752 753 memset(s, 0, sizeof(*s)); 754 755 c.directive.opcode = nvme_admin_directive_recv; 756 c.directive.nsid = cpu_to_le32(nsid); 757 c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s))); 758 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM; 759 c.directive.dtype = NVME_DIR_STREAMS; 760 761 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s)); 762 } 763 764 static int nvme_configure_directives(struct nvme_ctrl *ctrl) 765 { 766 struct streams_directive_params s; 767 int ret; 768 769 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES)) 770 return 0; 771 if (!streams) 772 return 0; 773 774 ret = nvme_enable_streams(ctrl); 775 if (ret) 776 return ret; 777 778 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL); 779 if (ret) 780 goto out_disable_stream; 781 782 ctrl->nssa = le16_to_cpu(s.nssa); 783 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) { 784 dev_info(ctrl->device, "too few streams (%u) available\n", 785 ctrl->nssa); 786 goto out_disable_stream; 787 } 788 789 ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1); 790 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams); 791 return 0; 792 793 out_disable_stream: 794 nvme_disable_streams(ctrl); 795 return ret; 796 } 797 798 /* 799 * Check if 'req' has a write hint associated with it. If it does, assign 800 * a valid namespace stream to the write. 801 */ 802 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl, 803 struct request *req, u16 *control, 804 u32 *dsmgmt) 805 { 806 enum rw_hint streamid = req->write_hint; 807 808 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE) 809 streamid = 0; 810 else { 811 streamid--; 812 if (WARN_ON_ONCE(streamid > ctrl->nr_streams)) 813 return; 814 815 *control |= NVME_RW_DTYPE_STREAMS; 816 *dsmgmt |= streamid << 16; 817 } 818 819 if (streamid < ARRAY_SIZE(req->q->write_hints)) 820 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9; 821 } 822 823 static inline void nvme_setup_flush(struct nvme_ns *ns, 824 struct nvme_command *cmnd) 825 { 826 cmnd->common.opcode = nvme_cmd_flush; 827 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id); 828 } 829 830 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req, 831 struct nvme_command *cmnd) 832 { 833 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0; 834 struct nvme_dsm_range *range; 835 struct bio *bio; 836 837 /* 838 * Some devices do not consider the DSM 'Number of Ranges' field when 839 * determining how much data to DMA. Always allocate memory for maximum 840 * number of segments to prevent device reading beyond end of buffer. 841 */ 842 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES; 843 844 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN); 845 if (!range) { 846 /* 847 * If we fail allocation our range, fallback to the controller 848 * discard page. If that's also busy, it's safe to return 849 * busy, as we know we can make progress once that's freed. 850 */ 851 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy)) 852 return BLK_STS_RESOURCE; 853 854 range = page_address(ns->ctrl->discard_page); 855 } 856 857 __rq_for_each_bio(bio, req) { 858 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector); 859 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift; 860 861 if (n < segments) { 862 range[n].cattr = cpu_to_le32(0); 863 range[n].nlb = cpu_to_le32(nlb); 864 range[n].slba = cpu_to_le64(slba); 865 } 866 n++; 867 } 868 869 if (WARN_ON_ONCE(n != segments)) { 870 if (virt_to_page(range) == ns->ctrl->discard_page) 871 clear_bit_unlock(0, &ns->ctrl->discard_page_busy); 872 else 873 kfree(range); 874 return BLK_STS_IOERR; 875 } 876 877 cmnd->dsm.opcode = nvme_cmd_dsm; 878 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id); 879 cmnd->dsm.nr = cpu_to_le32(segments - 1); 880 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD); 881 882 req->special_vec.bv_page = virt_to_page(range); 883 req->special_vec.bv_offset = offset_in_page(range); 884 req->special_vec.bv_len = alloc_size; 885 req->rq_flags |= RQF_SPECIAL_PAYLOAD; 886 887 return BLK_STS_OK; 888 } 889 890 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns, 891 struct request *req, struct nvme_command *cmnd) 892 { 893 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) 894 return nvme_setup_discard(ns, req, cmnd); 895 896 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes; 897 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id); 898 cmnd->write_zeroes.slba = 899 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req))); 900 cmnd->write_zeroes.length = 901 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1); 902 if (nvme_ns_has_pi(ns)) 903 cmnd->write_zeroes.control = cpu_to_le16(NVME_RW_PRINFO_PRACT); 904 else 905 cmnd->write_zeroes.control = 0; 906 return BLK_STS_OK; 907 } 908 909 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns, 910 struct request *req, struct nvme_command *cmnd, 911 enum nvme_opcode op) 912 { 913 struct nvme_ctrl *ctrl = ns->ctrl; 914 u16 control = 0; 915 u32 dsmgmt = 0; 916 917 if (req->cmd_flags & REQ_FUA) 918 control |= NVME_RW_FUA; 919 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD)) 920 control |= NVME_RW_LR; 921 922 if (req->cmd_flags & REQ_RAHEAD) 923 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH; 924 925 cmnd->rw.opcode = op; 926 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id); 927 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req))); 928 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1); 929 930 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams) 931 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt); 932 933 if (ns->ms) { 934 /* 935 * If formated with metadata, the block layer always provides a 936 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else 937 * we enable the PRACT bit for protection information or set the 938 * namespace capacity to zero to prevent any I/O. 939 */ 940 if (!blk_integrity_rq(req)) { 941 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns))) 942 return BLK_STS_NOTSUPP; 943 control |= NVME_RW_PRINFO_PRACT; 944 } 945 946 switch (ns->pi_type) { 947 case NVME_NS_DPS_PI_TYPE3: 948 control |= NVME_RW_PRINFO_PRCHK_GUARD; 949 break; 950 case NVME_NS_DPS_PI_TYPE1: 951 case NVME_NS_DPS_PI_TYPE2: 952 control |= NVME_RW_PRINFO_PRCHK_GUARD | 953 NVME_RW_PRINFO_PRCHK_REF; 954 if (op == nvme_cmd_zone_append) 955 control |= NVME_RW_APPEND_PIREMAP; 956 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req)); 957 break; 958 } 959 } 960 961 cmnd->rw.control = cpu_to_le16(control); 962 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt); 963 return 0; 964 } 965 966 void nvme_cleanup_cmd(struct request *req) 967 { 968 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) { 969 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl; 970 971 if (req->special_vec.bv_page == ctrl->discard_page) 972 clear_bit_unlock(0, &ctrl->discard_page_busy); 973 else 974 kfree(bvec_virt(&req->special_vec)); 975 } 976 } 977 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd); 978 979 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req) 980 { 981 struct nvme_command *cmd = nvme_req(req)->cmd; 982 blk_status_t ret = BLK_STS_OK; 983 984 if (!(req->rq_flags & RQF_DONTPREP)) { 985 nvme_clear_nvme_request(req); 986 memset(cmd, 0, sizeof(*cmd)); 987 } 988 989 switch (req_op(req)) { 990 case REQ_OP_DRV_IN: 991 case REQ_OP_DRV_OUT: 992 /* these are setup prior to execution in nvme_init_request() */ 993 break; 994 case REQ_OP_FLUSH: 995 nvme_setup_flush(ns, cmd); 996 break; 997 case REQ_OP_ZONE_RESET_ALL: 998 case REQ_OP_ZONE_RESET: 999 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET); 1000 break; 1001 case REQ_OP_ZONE_OPEN: 1002 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN); 1003 break; 1004 case REQ_OP_ZONE_CLOSE: 1005 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE); 1006 break; 1007 case REQ_OP_ZONE_FINISH: 1008 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH); 1009 break; 1010 case REQ_OP_WRITE_ZEROES: 1011 ret = nvme_setup_write_zeroes(ns, req, cmd); 1012 break; 1013 case REQ_OP_DISCARD: 1014 ret = nvme_setup_discard(ns, req, cmd); 1015 break; 1016 case REQ_OP_READ: 1017 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read); 1018 break; 1019 case REQ_OP_WRITE: 1020 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write); 1021 break; 1022 case REQ_OP_ZONE_APPEND: 1023 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append); 1024 break; 1025 default: 1026 WARN_ON_ONCE(1); 1027 return BLK_STS_IOERR; 1028 } 1029 1030 nvme_req(req)->genctr++; 1031 cmd->common.command_id = nvme_cid(req); 1032 trace_nvme_setup_cmd(req, cmd); 1033 return ret; 1034 } 1035 EXPORT_SYMBOL_GPL(nvme_setup_cmd); 1036 1037 /* 1038 * Return values: 1039 * 0: success 1040 * >0: nvme controller's cqe status response 1041 * <0: kernel error in lieu of controller response 1042 */ 1043 static int nvme_execute_rq(struct gendisk *disk, struct request *rq, 1044 bool at_head) 1045 { 1046 blk_status_t status; 1047 1048 status = blk_execute_rq(disk, rq, at_head); 1049 if (nvme_req(rq)->flags & NVME_REQ_CANCELLED) 1050 return -EINTR; 1051 if (nvme_req(rq)->status) 1052 return nvme_req(rq)->status; 1053 return blk_status_to_errno(status); 1054 } 1055 1056 /* 1057 * Returns 0 on success. If the result is negative, it's a Linux error code; 1058 * if the result is positive, it's an NVM Express status code 1059 */ 1060 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 1061 union nvme_result *result, void *buffer, unsigned bufflen, 1062 unsigned timeout, int qid, int at_head, 1063 blk_mq_req_flags_t flags) 1064 { 1065 struct request *req; 1066 int ret; 1067 1068 if (qid == NVME_QID_ANY) 1069 req = nvme_alloc_request(q, cmd, flags); 1070 else 1071 req = nvme_alloc_request_qid(q, cmd, flags, qid); 1072 if (IS_ERR(req)) 1073 return PTR_ERR(req); 1074 1075 if (timeout) 1076 req->timeout = timeout; 1077 1078 if (buffer && bufflen) { 1079 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL); 1080 if (ret) 1081 goto out; 1082 } 1083 1084 ret = nvme_execute_rq(NULL, req, at_head); 1085 if (result && ret >= 0) 1086 *result = nvme_req(req)->result; 1087 out: 1088 blk_mq_free_request(req); 1089 return ret; 1090 } 1091 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd); 1092 1093 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 1094 void *buffer, unsigned bufflen) 1095 { 1096 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0, 1097 NVME_QID_ANY, 0, 0); 1098 } 1099 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd); 1100 1101 static u32 nvme_known_admin_effects(u8 opcode) 1102 { 1103 switch (opcode) { 1104 case nvme_admin_format_nvm: 1105 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_NCC | 1106 NVME_CMD_EFFECTS_CSE_MASK; 1107 case nvme_admin_sanitize_nvm: 1108 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK; 1109 default: 1110 break; 1111 } 1112 return 0; 1113 } 1114 1115 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode) 1116 { 1117 u32 effects = 0; 1118 1119 if (ns) { 1120 if (ns->head->effects) 1121 effects = le32_to_cpu(ns->head->effects->iocs[opcode]); 1122 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC)) 1123 dev_warn_once(ctrl->device, 1124 "IO command:%02x has unhandled effects:%08x\n", 1125 opcode, effects); 1126 return 0; 1127 } 1128 1129 if (ctrl->effects) 1130 effects = le32_to_cpu(ctrl->effects->acs[opcode]); 1131 effects |= nvme_known_admin_effects(opcode); 1132 1133 return effects; 1134 } 1135 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU); 1136 1137 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, 1138 u8 opcode) 1139 { 1140 u32 effects = nvme_command_effects(ctrl, ns, opcode); 1141 1142 /* 1143 * For simplicity, IO to all namespaces is quiesced even if the command 1144 * effects say only one namespace is affected. 1145 */ 1146 if (effects & NVME_CMD_EFFECTS_CSE_MASK) { 1147 mutex_lock(&ctrl->scan_lock); 1148 mutex_lock(&ctrl->subsys->lock); 1149 nvme_mpath_start_freeze(ctrl->subsys); 1150 nvme_mpath_wait_freeze(ctrl->subsys); 1151 nvme_start_freeze(ctrl); 1152 nvme_wait_freeze(ctrl); 1153 } 1154 return effects; 1155 } 1156 1157 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects, 1158 struct nvme_command *cmd, int status) 1159 { 1160 if (effects & NVME_CMD_EFFECTS_CSE_MASK) { 1161 nvme_unfreeze(ctrl); 1162 nvme_mpath_unfreeze(ctrl->subsys); 1163 mutex_unlock(&ctrl->subsys->lock); 1164 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL); 1165 mutex_unlock(&ctrl->scan_lock); 1166 } 1167 if (effects & NVME_CMD_EFFECTS_CCC) 1168 nvme_init_ctrl_finish(ctrl); 1169 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) { 1170 nvme_queue_scan(ctrl); 1171 flush_work(&ctrl->scan_work); 1172 } 1173 1174 switch (cmd->common.opcode) { 1175 case nvme_admin_set_features: 1176 switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) { 1177 case NVME_FEAT_KATO: 1178 /* 1179 * Keep alive commands interval on the host should be 1180 * updated when KATO is modified by Set Features 1181 * commands. 1182 */ 1183 if (!status) 1184 nvme_update_keep_alive(ctrl, cmd); 1185 break; 1186 default: 1187 break; 1188 } 1189 break; 1190 default: 1191 break; 1192 } 1193 } 1194 1195 int nvme_execute_passthru_rq(struct request *rq) 1196 { 1197 struct nvme_command *cmd = nvme_req(rq)->cmd; 1198 struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl; 1199 struct nvme_ns *ns = rq->q->queuedata; 1200 struct gendisk *disk = ns ? ns->disk : NULL; 1201 u32 effects; 1202 int ret; 1203 1204 effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode); 1205 ret = nvme_execute_rq(disk, rq, false); 1206 if (effects) /* nothing to be done for zero cmd effects */ 1207 nvme_passthru_end(ctrl, effects, cmd, ret); 1208 1209 return ret; 1210 } 1211 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU); 1212 1213 /* 1214 * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1: 1215 * 1216 * The host should send Keep Alive commands at half of the Keep Alive Timeout 1217 * accounting for transport roundtrip times [..]. 1218 */ 1219 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl) 1220 { 1221 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ / 2); 1222 } 1223 1224 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status) 1225 { 1226 struct nvme_ctrl *ctrl = rq->end_io_data; 1227 unsigned long flags; 1228 bool startka = false; 1229 1230 blk_mq_free_request(rq); 1231 1232 if (status) { 1233 dev_err(ctrl->device, 1234 "failed nvme_keep_alive_end_io error=%d\n", 1235 status); 1236 return; 1237 } 1238 1239 ctrl->comp_seen = false; 1240 spin_lock_irqsave(&ctrl->lock, flags); 1241 if (ctrl->state == NVME_CTRL_LIVE || 1242 ctrl->state == NVME_CTRL_CONNECTING) 1243 startka = true; 1244 spin_unlock_irqrestore(&ctrl->lock, flags); 1245 if (startka) 1246 nvme_queue_keep_alive_work(ctrl); 1247 } 1248 1249 static void nvme_keep_alive_work(struct work_struct *work) 1250 { 1251 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work), 1252 struct nvme_ctrl, ka_work); 1253 bool comp_seen = ctrl->comp_seen; 1254 struct request *rq; 1255 1256 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) { 1257 dev_dbg(ctrl->device, 1258 "reschedule traffic based keep-alive timer\n"); 1259 ctrl->comp_seen = false; 1260 nvme_queue_keep_alive_work(ctrl); 1261 return; 1262 } 1263 1264 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, 1265 BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT); 1266 if (IS_ERR(rq)) { 1267 /* allocation failure, reset the controller */ 1268 dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq)); 1269 nvme_reset_ctrl(ctrl); 1270 return; 1271 } 1272 1273 rq->timeout = ctrl->kato * HZ; 1274 rq->end_io_data = ctrl; 1275 blk_execute_rq_nowait(NULL, rq, 0, nvme_keep_alive_end_io); 1276 } 1277 1278 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl) 1279 { 1280 if (unlikely(ctrl->kato == 0)) 1281 return; 1282 1283 nvme_queue_keep_alive_work(ctrl); 1284 } 1285 1286 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl) 1287 { 1288 if (unlikely(ctrl->kato == 0)) 1289 return; 1290 1291 cancel_delayed_work_sync(&ctrl->ka_work); 1292 } 1293 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive); 1294 1295 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl, 1296 struct nvme_command *cmd) 1297 { 1298 unsigned int new_kato = 1299 DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000); 1300 1301 dev_info(ctrl->device, 1302 "keep alive interval updated from %u ms to %u ms\n", 1303 ctrl->kato * 1000 / 2, new_kato * 1000 / 2); 1304 1305 nvme_stop_keep_alive(ctrl); 1306 ctrl->kato = new_kato; 1307 nvme_start_keep_alive(ctrl); 1308 } 1309 1310 /* 1311 * In NVMe 1.0 the CNS field was just a binary controller or namespace 1312 * flag, thus sending any new CNS opcodes has a big chance of not working. 1313 * Qemu unfortunately had that bug after reporting a 1.1 version compliance 1314 * (but not for any later version). 1315 */ 1316 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl) 1317 { 1318 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS) 1319 return ctrl->vs < NVME_VS(1, 2, 0); 1320 return ctrl->vs < NVME_VS(1, 1, 0); 1321 } 1322 1323 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id) 1324 { 1325 struct nvme_command c = { }; 1326 int error; 1327 1328 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 1329 c.identify.opcode = nvme_admin_identify; 1330 c.identify.cns = NVME_ID_CNS_CTRL; 1331 1332 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL); 1333 if (!*id) 1334 return -ENOMEM; 1335 1336 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id, 1337 sizeof(struct nvme_id_ctrl)); 1338 if (error) 1339 kfree(*id); 1340 return error; 1341 } 1342 1343 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids, 1344 struct nvme_ns_id_desc *cur, bool *csi_seen) 1345 { 1346 const char *warn_str = "ctrl returned bogus length:"; 1347 void *data = cur; 1348 1349 switch (cur->nidt) { 1350 case NVME_NIDT_EUI64: 1351 if (cur->nidl != NVME_NIDT_EUI64_LEN) { 1352 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n", 1353 warn_str, cur->nidl); 1354 return -1; 1355 } 1356 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN); 1357 return NVME_NIDT_EUI64_LEN; 1358 case NVME_NIDT_NGUID: 1359 if (cur->nidl != NVME_NIDT_NGUID_LEN) { 1360 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n", 1361 warn_str, cur->nidl); 1362 return -1; 1363 } 1364 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN); 1365 return NVME_NIDT_NGUID_LEN; 1366 case NVME_NIDT_UUID: 1367 if (cur->nidl != NVME_NIDT_UUID_LEN) { 1368 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n", 1369 warn_str, cur->nidl); 1370 return -1; 1371 } 1372 uuid_copy(&ids->uuid, data + sizeof(*cur)); 1373 return NVME_NIDT_UUID_LEN; 1374 case NVME_NIDT_CSI: 1375 if (cur->nidl != NVME_NIDT_CSI_LEN) { 1376 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n", 1377 warn_str, cur->nidl); 1378 return -1; 1379 } 1380 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN); 1381 *csi_seen = true; 1382 return NVME_NIDT_CSI_LEN; 1383 default: 1384 /* Skip unknown types */ 1385 return cur->nidl; 1386 } 1387 } 1388 1389 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid, 1390 struct nvme_ns_ids *ids) 1391 { 1392 struct nvme_command c = { }; 1393 bool csi_seen = false; 1394 int status, pos, len; 1395 void *data; 1396 1397 if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl)) 1398 return 0; 1399 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST) 1400 return 0; 1401 1402 c.identify.opcode = nvme_admin_identify; 1403 c.identify.nsid = cpu_to_le32(nsid); 1404 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST; 1405 1406 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 1407 if (!data) 1408 return -ENOMEM; 1409 1410 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data, 1411 NVME_IDENTIFY_DATA_SIZE); 1412 if (status) { 1413 dev_warn(ctrl->device, 1414 "Identify Descriptors failed (nsid=%u, status=0x%x)\n", 1415 nsid, status); 1416 goto free_data; 1417 } 1418 1419 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) { 1420 struct nvme_ns_id_desc *cur = data + pos; 1421 1422 if (cur->nidl == 0) 1423 break; 1424 1425 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen); 1426 if (len < 0) 1427 break; 1428 1429 len += sizeof(*cur); 1430 } 1431 1432 if (nvme_multi_css(ctrl) && !csi_seen) { 1433 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n", 1434 nsid); 1435 status = -EINVAL; 1436 } 1437 1438 free_data: 1439 kfree(data); 1440 return status; 1441 } 1442 1443 static int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid, 1444 struct nvme_ns_ids *ids, struct nvme_id_ns **id) 1445 { 1446 struct nvme_command c = { }; 1447 int error; 1448 1449 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 1450 c.identify.opcode = nvme_admin_identify; 1451 c.identify.nsid = cpu_to_le32(nsid); 1452 c.identify.cns = NVME_ID_CNS_NS; 1453 1454 *id = kmalloc(sizeof(**id), GFP_KERNEL); 1455 if (!*id) 1456 return -ENOMEM; 1457 1458 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id)); 1459 if (error) { 1460 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error); 1461 goto out_free_id; 1462 } 1463 1464 error = NVME_SC_INVALID_NS | NVME_SC_DNR; 1465 if ((*id)->ncap == 0) /* namespace not allocated or attached */ 1466 goto out_free_id; 1467 1468 if (ctrl->vs >= NVME_VS(1, 1, 0) && 1469 !memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 1470 memcpy(ids->eui64, (*id)->eui64, sizeof(ids->eui64)); 1471 if (ctrl->vs >= NVME_VS(1, 2, 0) && 1472 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 1473 memcpy(ids->nguid, (*id)->nguid, sizeof(ids->nguid)); 1474 1475 return 0; 1476 1477 out_free_id: 1478 kfree(*id); 1479 return error; 1480 } 1481 1482 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid, 1483 unsigned int dword11, void *buffer, size_t buflen, u32 *result) 1484 { 1485 union nvme_result res = { 0 }; 1486 struct nvme_command c = { }; 1487 int ret; 1488 1489 c.features.opcode = op; 1490 c.features.fid = cpu_to_le32(fid); 1491 c.features.dword11 = cpu_to_le32(dword11); 1492 1493 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, 1494 buffer, buflen, 0, NVME_QID_ANY, 0, 0); 1495 if (ret >= 0 && result) 1496 *result = le32_to_cpu(res.u32); 1497 return ret; 1498 } 1499 1500 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid, 1501 unsigned int dword11, void *buffer, size_t buflen, 1502 u32 *result) 1503 { 1504 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer, 1505 buflen, result); 1506 } 1507 EXPORT_SYMBOL_GPL(nvme_set_features); 1508 1509 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid, 1510 unsigned int dword11, void *buffer, size_t buflen, 1511 u32 *result) 1512 { 1513 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer, 1514 buflen, result); 1515 } 1516 EXPORT_SYMBOL_GPL(nvme_get_features); 1517 1518 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count) 1519 { 1520 u32 q_count = (*count - 1) | ((*count - 1) << 16); 1521 u32 result; 1522 int status, nr_io_queues; 1523 1524 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0, 1525 &result); 1526 if (status < 0) 1527 return status; 1528 1529 /* 1530 * Degraded controllers might return an error when setting the queue 1531 * count. We still want to be able to bring them online and offer 1532 * access to the admin queue, as that might be only way to fix them up. 1533 */ 1534 if (status > 0) { 1535 dev_err(ctrl->device, "Could not set queue count (%d)\n", status); 1536 *count = 0; 1537 } else { 1538 nr_io_queues = min(result & 0xffff, result >> 16) + 1; 1539 *count = min(*count, nr_io_queues); 1540 } 1541 1542 return 0; 1543 } 1544 EXPORT_SYMBOL_GPL(nvme_set_queue_count); 1545 1546 #define NVME_AEN_SUPPORTED \ 1547 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \ 1548 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE) 1549 1550 static void nvme_enable_aen(struct nvme_ctrl *ctrl) 1551 { 1552 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED; 1553 int status; 1554 1555 if (!supported_aens) 1556 return; 1557 1558 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens, 1559 NULL, 0, &result); 1560 if (status) 1561 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n", 1562 supported_aens); 1563 1564 queue_work(nvme_wq, &ctrl->async_event_work); 1565 } 1566 1567 static int nvme_ns_open(struct nvme_ns *ns) 1568 { 1569 1570 /* should never be called due to GENHD_FL_HIDDEN */ 1571 if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head))) 1572 goto fail; 1573 if (!nvme_get_ns(ns)) 1574 goto fail; 1575 if (!try_module_get(ns->ctrl->ops->module)) 1576 goto fail_put_ns; 1577 1578 return 0; 1579 1580 fail_put_ns: 1581 nvme_put_ns(ns); 1582 fail: 1583 return -ENXIO; 1584 } 1585 1586 static void nvme_ns_release(struct nvme_ns *ns) 1587 { 1588 1589 module_put(ns->ctrl->ops->module); 1590 nvme_put_ns(ns); 1591 } 1592 1593 static int nvme_open(struct block_device *bdev, fmode_t mode) 1594 { 1595 return nvme_ns_open(bdev->bd_disk->private_data); 1596 } 1597 1598 static void nvme_release(struct gendisk *disk, fmode_t mode) 1599 { 1600 nvme_ns_release(disk->private_data); 1601 } 1602 1603 int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo) 1604 { 1605 /* some standard values */ 1606 geo->heads = 1 << 6; 1607 geo->sectors = 1 << 5; 1608 geo->cylinders = get_capacity(bdev->bd_disk) >> 11; 1609 return 0; 1610 } 1611 1612 #ifdef CONFIG_BLK_DEV_INTEGRITY 1613 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type, 1614 u32 max_integrity_segments) 1615 { 1616 struct blk_integrity integrity = { }; 1617 1618 switch (pi_type) { 1619 case NVME_NS_DPS_PI_TYPE3: 1620 integrity.profile = &t10_pi_type3_crc; 1621 integrity.tag_size = sizeof(u16) + sizeof(u32); 1622 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1623 break; 1624 case NVME_NS_DPS_PI_TYPE1: 1625 case NVME_NS_DPS_PI_TYPE2: 1626 integrity.profile = &t10_pi_type1_crc; 1627 integrity.tag_size = sizeof(u16); 1628 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1629 break; 1630 default: 1631 integrity.profile = NULL; 1632 break; 1633 } 1634 integrity.tuple_size = ms; 1635 blk_integrity_register(disk, &integrity); 1636 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments); 1637 } 1638 #else 1639 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type, 1640 u32 max_integrity_segments) 1641 { 1642 } 1643 #endif /* CONFIG_BLK_DEV_INTEGRITY */ 1644 1645 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns) 1646 { 1647 struct nvme_ctrl *ctrl = ns->ctrl; 1648 struct request_queue *queue = disk->queue; 1649 u32 size = queue_logical_block_size(queue); 1650 1651 if (ctrl->max_discard_sectors == 0) { 1652 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue); 1653 return; 1654 } 1655 1656 if (ctrl->nr_streams && ns->sws && ns->sgs) 1657 size *= ns->sws * ns->sgs; 1658 1659 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) < 1660 NVME_DSM_MAX_RANGES); 1661 1662 queue->limits.discard_alignment = 0; 1663 queue->limits.discard_granularity = size; 1664 1665 /* If discard is already enabled, don't reset queue limits */ 1666 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue)) 1667 return; 1668 1669 blk_queue_max_discard_sectors(queue, ctrl->max_discard_sectors); 1670 blk_queue_max_discard_segments(queue, ctrl->max_discard_segments); 1671 1672 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) 1673 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX); 1674 } 1675 1676 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids) 1677 { 1678 return !uuid_is_null(&ids->uuid) || 1679 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) || 1680 memchr_inv(ids->eui64, 0, sizeof(ids->eui64)); 1681 } 1682 1683 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b) 1684 { 1685 return uuid_equal(&a->uuid, &b->uuid) && 1686 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 && 1687 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 && 1688 a->csi == b->csi; 1689 } 1690 1691 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns, 1692 u32 *phys_bs, u32 *io_opt) 1693 { 1694 struct streams_directive_params s; 1695 int ret; 1696 1697 if (!ctrl->nr_streams) 1698 return 0; 1699 1700 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id); 1701 if (ret) 1702 return ret; 1703 1704 ns->sws = le32_to_cpu(s.sws); 1705 ns->sgs = le16_to_cpu(s.sgs); 1706 1707 if (ns->sws) { 1708 *phys_bs = ns->sws * (1 << ns->lba_shift); 1709 if (ns->sgs) 1710 *io_opt = *phys_bs * ns->sgs; 1711 } 1712 1713 return 0; 1714 } 1715 1716 static int nvme_configure_metadata(struct nvme_ns *ns, struct nvme_id_ns *id) 1717 { 1718 struct nvme_ctrl *ctrl = ns->ctrl; 1719 1720 /* 1721 * The PI implementation requires the metadata size to be equal to the 1722 * t10 pi tuple size. 1723 */ 1724 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms); 1725 if (ns->ms == sizeof(struct t10_pi_tuple)) 1726 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK; 1727 else 1728 ns->pi_type = 0; 1729 1730 ns->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS); 1731 if (!ns->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)) 1732 return 0; 1733 if (ctrl->ops->flags & NVME_F_FABRICS) { 1734 /* 1735 * The NVMe over Fabrics specification only supports metadata as 1736 * part of the extended data LBA. We rely on HCA/HBA support to 1737 * remap the separate metadata buffer from the block layer. 1738 */ 1739 if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT))) 1740 return -EINVAL; 1741 if (ctrl->max_integrity_segments) 1742 ns->features |= 1743 (NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS); 1744 } else { 1745 /* 1746 * For PCIe controllers, we can't easily remap the separate 1747 * metadata buffer from the block layer and thus require a 1748 * separate metadata buffer for block layer metadata/PI support. 1749 * We allow extended LBAs for the passthrough interface, though. 1750 */ 1751 if (id->flbas & NVME_NS_FLBAS_META_EXT) 1752 ns->features |= NVME_NS_EXT_LBAS; 1753 else 1754 ns->features |= NVME_NS_METADATA_SUPPORTED; 1755 } 1756 1757 return 0; 1758 } 1759 1760 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl, 1761 struct request_queue *q) 1762 { 1763 bool vwc = ctrl->vwc & NVME_CTRL_VWC_PRESENT; 1764 1765 if (ctrl->max_hw_sectors) { 1766 u32 max_segments = 1767 (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1; 1768 1769 max_segments = min_not_zero(max_segments, ctrl->max_segments); 1770 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors); 1771 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX)); 1772 } 1773 blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1); 1774 blk_queue_dma_alignment(q, 7); 1775 blk_queue_write_cache(q, vwc, vwc); 1776 } 1777 1778 static void nvme_update_disk_info(struct gendisk *disk, 1779 struct nvme_ns *ns, struct nvme_id_ns *id) 1780 { 1781 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze)); 1782 unsigned short bs = 1 << ns->lba_shift; 1783 u32 atomic_bs, phys_bs, io_opt = 0; 1784 1785 /* 1786 * The block layer can't support LBA sizes larger than the page size 1787 * yet, so catch this early and don't allow block I/O. 1788 */ 1789 if (ns->lba_shift > PAGE_SHIFT) { 1790 capacity = 0; 1791 bs = (1 << 9); 1792 } 1793 1794 blk_integrity_unregister(disk); 1795 1796 atomic_bs = phys_bs = bs; 1797 nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt); 1798 if (id->nabo == 0) { 1799 /* 1800 * Bit 1 indicates whether NAWUPF is defined for this namespace 1801 * and whether it should be used instead of AWUPF. If NAWUPF == 1802 * 0 then AWUPF must be used instead. 1803 */ 1804 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf) 1805 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs; 1806 else 1807 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs; 1808 } 1809 1810 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) { 1811 /* NPWG = Namespace Preferred Write Granularity */ 1812 phys_bs = bs * (1 + le16_to_cpu(id->npwg)); 1813 /* NOWS = Namespace Optimal Write Size */ 1814 io_opt = bs * (1 + le16_to_cpu(id->nows)); 1815 } 1816 1817 blk_queue_logical_block_size(disk->queue, bs); 1818 /* 1819 * Linux filesystems assume writing a single physical block is 1820 * an atomic operation. Hence limit the physical block size to the 1821 * value of the Atomic Write Unit Power Fail parameter. 1822 */ 1823 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs)); 1824 blk_queue_io_min(disk->queue, phys_bs); 1825 blk_queue_io_opt(disk->queue, io_opt); 1826 1827 /* 1828 * Register a metadata profile for PI, or the plain non-integrity NVMe 1829 * metadata masquerading as Type 0 if supported, otherwise reject block 1830 * I/O to namespaces with metadata except when the namespace supports 1831 * PI, as it can strip/insert in that case. 1832 */ 1833 if (ns->ms) { 1834 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) && 1835 (ns->features & NVME_NS_METADATA_SUPPORTED)) 1836 nvme_init_integrity(disk, ns->ms, ns->pi_type, 1837 ns->ctrl->max_integrity_segments); 1838 else if (!nvme_ns_has_pi(ns)) 1839 capacity = 0; 1840 } 1841 1842 set_capacity_and_notify(disk, capacity); 1843 1844 nvme_config_discard(disk, ns); 1845 blk_queue_max_write_zeroes_sectors(disk->queue, 1846 ns->ctrl->max_zeroes_sectors); 1847 1848 set_disk_ro(disk, (id->nsattr & NVME_NS_ATTR_RO) || 1849 test_bit(NVME_NS_FORCE_RO, &ns->flags)); 1850 } 1851 1852 static inline bool nvme_first_scan(struct gendisk *disk) 1853 { 1854 /* nvme_alloc_ns() scans the disk prior to adding it */ 1855 return !disk_live(disk); 1856 } 1857 1858 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id) 1859 { 1860 struct nvme_ctrl *ctrl = ns->ctrl; 1861 u32 iob; 1862 1863 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) && 1864 is_power_of_2(ctrl->max_hw_sectors)) 1865 iob = ctrl->max_hw_sectors; 1866 else 1867 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob)); 1868 1869 if (!iob) 1870 return; 1871 1872 if (!is_power_of_2(iob)) { 1873 if (nvme_first_scan(ns->disk)) 1874 pr_warn("%s: ignoring unaligned IO boundary:%u\n", 1875 ns->disk->disk_name, iob); 1876 return; 1877 } 1878 1879 if (blk_queue_is_zoned(ns->disk->queue)) { 1880 if (nvme_first_scan(ns->disk)) 1881 pr_warn("%s: ignoring zoned namespace IO boundary\n", 1882 ns->disk->disk_name); 1883 return; 1884 } 1885 1886 blk_queue_chunk_sectors(ns->queue, iob); 1887 } 1888 1889 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_id_ns *id) 1890 { 1891 unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK; 1892 int ret; 1893 1894 blk_mq_freeze_queue(ns->disk->queue); 1895 ns->lba_shift = id->lbaf[lbaf].ds; 1896 nvme_set_queue_limits(ns->ctrl, ns->queue); 1897 1898 ret = nvme_configure_metadata(ns, id); 1899 if (ret) 1900 goto out_unfreeze; 1901 nvme_set_chunk_sectors(ns, id); 1902 nvme_update_disk_info(ns->disk, ns, id); 1903 1904 if (ns->head->ids.csi == NVME_CSI_ZNS) { 1905 ret = nvme_update_zone_info(ns, lbaf); 1906 if (ret) 1907 goto out_unfreeze; 1908 } 1909 1910 set_bit(NVME_NS_READY, &ns->flags); 1911 blk_mq_unfreeze_queue(ns->disk->queue); 1912 1913 if (blk_queue_is_zoned(ns->queue)) { 1914 ret = nvme_revalidate_zones(ns); 1915 if (ret && !nvme_first_scan(ns->disk)) 1916 goto out; 1917 } 1918 1919 if (nvme_ns_head_multipath(ns->head)) { 1920 blk_mq_freeze_queue(ns->head->disk->queue); 1921 nvme_update_disk_info(ns->head->disk, ns, id); 1922 nvme_mpath_revalidate_paths(ns); 1923 blk_stack_limits(&ns->head->disk->queue->limits, 1924 &ns->queue->limits, 0); 1925 disk_update_readahead(ns->head->disk); 1926 blk_mq_unfreeze_queue(ns->head->disk->queue); 1927 } 1928 return 0; 1929 1930 out_unfreeze: 1931 blk_mq_unfreeze_queue(ns->disk->queue); 1932 out: 1933 /* 1934 * If probing fails due an unsupported feature, hide the block device, 1935 * but still allow other access. 1936 */ 1937 if (ret == -ENODEV) { 1938 ns->disk->flags |= GENHD_FL_HIDDEN; 1939 ret = 0; 1940 } 1941 return ret; 1942 } 1943 1944 static char nvme_pr_type(enum pr_type type) 1945 { 1946 switch (type) { 1947 case PR_WRITE_EXCLUSIVE: 1948 return 1; 1949 case PR_EXCLUSIVE_ACCESS: 1950 return 2; 1951 case PR_WRITE_EXCLUSIVE_REG_ONLY: 1952 return 3; 1953 case PR_EXCLUSIVE_ACCESS_REG_ONLY: 1954 return 4; 1955 case PR_WRITE_EXCLUSIVE_ALL_REGS: 1956 return 5; 1957 case PR_EXCLUSIVE_ACCESS_ALL_REGS: 1958 return 6; 1959 default: 1960 return 0; 1961 } 1962 }; 1963 1964 static int nvme_send_ns_head_pr_command(struct block_device *bdev, 1965 struct nvme_command *c, u8 data[16]) 1966 { 1967 struct nvme_ns_head *head = bdev->bd_disk->private_data; 1968 int srcu_idx = srcu_read_lock(&head->srcu); 1969 struct nvme_ns *ns = nvme_find_path(head); 1970 int ret = -EWOULDBLOCK; 1971 1972 if (ns) { 1973 c->common.nsid = cpu_to_le32(ns->head->ns_id); 1974 ret = nvme_submit_sync_cmd(ns->queue, c, data, 16); 1975 } 1976 srcu_read_unlock(&head->srcu, srcu_idx); 1977 return ret; 1978 } 1979 1980 static int nvme_send_ns_pr_command(struct nvme_ns *ns, struct nvme_command *c, 1981 u8 data[16]) 1982 { 1983 c->common.nsid = cpu_to_le32(ns->head->ns_id); 1984 return nvme_submit_sync_cmd(ns->queue, c, data, 16); 1985 } 1986 1987 static int nvme_pr_command(struct block_device *bdev, u32 cdw10, 1988 u64 key, u64 sa_key, u8 op) 1989 { 1990 struct nvme_command c = { }; 1991 u8 data[16] = { 0, }; 1992 1993 put_unaligned_le64(key, &data[0]); 1994 put_unaligned_le64(sa_key, &data[8]); 1995 1996 c.common.opcode = op; 1997 c.common.cdw10 = cpu_to_le32(cdw10); 1998 1999 if (IS_ENABLED(CONFIG_NVME_MULTIPATH) && 2000 bdev->bd_disk->fops == &nvme_ns_head_ops) 2001 return nvme_send_ns_head_pr_command(bdev, &c, data); 2002 return nvme_send_ns_pr_command(bdev->bd_disk->private_data, &c, data); 2003 } 2004 2005 static int nvme_pr_register(struct block_device *bdev, u64 old, 2006 u64 new, unsigned flags) 2007 { 2008 u32 cdw10; 2009 2010 if (flags & ~PR_FL_IGNORE_KEY) 2011 return -EOPNOTSUPP; 2012 2013 cdw10 = old ? 2 : 0; 2014 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0; 2015 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */ 2016 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register); 2017 } 2018 2019 static int nvme_pr_reserve(struct block_device *bdev, u64 key, 2020 enum pr_type type, unsigned flags) 2021 { 2022 u32 cdw10; 2023 2024 if (flags & ~PR_FL_IGNORE_KEY) 2025 return -EOPNOTSUPP; 2026 2027 cdw10 = nvme_pr_type(type) << 8; 2028 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0); 2029 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire); 2030 } 2031 2032 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new, 2033 enum pr_type type, bool abort) 2034 { 2035 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1); 2036 2037 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire); 2038 } 2039 2040 static int nvme_pr_clear(struct block_device *bdev, u64 key) 2041 { 2042 u32 cdw10 = 1 | (key ? 1 << 3 : 0); 2043 2044 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register); 2045 } 2046 2047 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type) 2048 { 2049 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0); 2050 2051 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release); 2052 } 2053 2054 const struct pr_ops nvme_pr_ops = { 2055 .pr_register = nvme_pr_register, 2056 .pr_reserve = nvme_pr_reserve, 2057 .pr_release = nvme_pr_release, 2058 .pr_preempt = nvme_pr_preempt, 2059 .pr_clear = nvme_pr_clear, 2060 }; 2061 2062 #ifdef CONFIG_BLK_SED_OPAL 2063 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len, 2064 bool send) 2065 { 2066 struct nvme_ctrl *ctrl = data; 2067 struct nvme_command cmd = { }; 2068 2069 if (send) 2070 cmd.common.opcode = nvme_admin_security_send; 2071 else 2072 cmd.common.opcode = nvme_admin_security_recv; 2073 cmd.common.nsid = 0; 2074 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8); 2075 cmd.common.cdw11 = cpu_to_le32(len); 2076 2077 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 0, 2078 NVME_QID_ANY, 1, 0); 2079 } 2080 EXPORT_SYMBOL_GPL(nvme_sec_submit); 2081 #endif /* CONFIG_BLK_SED_OPAL */ 2082 2083 #ifdef CONFIG_BLK_DEV_ZONED 2084 static int nvme_report_zones(struct gendisk *disk, sector_t sector, 2085 unsigned int nr_zones, report_zones_cb cb, void *data) 2086 { 2087 return nvme_ns_report_zones(disk->private_data, sector, nr_zones, cb, 2088 data); 2089 } 2090 #else 2091 #define nvme_report_zones NULL 2092 #endif /* CONFIG_BLK_DEV_ZONED */ 2093 2094 static const struct block_device_operations nvme_bdev_ops = { 2095 .owner = THIS_MODULE, 2096 .ioctl = nvme_ioctl, 2097 .open = nvme_open, 2098 .release = nvme_release, 2099 .getgeo = nvme_getgeo, 2100 .report_zones = nvme_report_zones, 2101 .pr_ops = &nvme_pr_ops, 2102 }; 2103 2104 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled) 2105 { 2106 unsigned long timeout = 2107 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies; 2108 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0; 2109 int ret; 2110 2111 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) { 2112 if (csts == ~0) 2113 return -ENODEV; 2114 if ((csts & NVME_CSTS_RDY) == bit) 2115 break; 2116 2117 usleep_range(1000, 2000); 2118 if (fatal_signal_pending(current)) 2119 return -EINTR; 2120 if (time_after(jiffies, timeout)) { 2121 dev_err(ctrl->device, 2122 "Device not ready; aborting %s, CSTS=0x%x\n", 2123 enabled ? "initialisation" : "reset", csts); 2124 return -ENODEV; 2125 } 2126 } 2127 2128 return ret; 2129 } 2130 2131 /* 2132 * If the device has been passed off to us in an enabled state, just clear 2133 * the enabled bit. The spec says we should set the 'shutdown notification 2134 * bits', but doing so may cause the device to complete commands to the 2135 * admin queue ... and we don't know what memory that might be pointing at! 2136 */ 2137 int nvme_disable_ctrl(struct nvme_ctrl *ctrl) 2138 { 2139 int ret; 2140 2141 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK; 2142 ctrl->ctrl_config &= ~NVME_CC_ENABLE; 2143 2144 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2145 if (ret) 2146 return ret; 2147 2148 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY) 2149 msleep(NVME_QUIRK_DELAY_AMOUNT); 2150 2151 return nvme_wait_ready(ctrl, ctrl->cap, false); 2152 } 2153 EXPORT_SYMBOL_GPL(nvme_disable_ctrl); 2154 2155 int nvme_enable_ctrl(struct nvme_ctrl *ctrl) 2156 { 2157 unsigned dev_page_min; 2158 int ret; 2159 2160 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap); 2161 if (ret) { 2162 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret); 2163 return ret; 2164 } 2165 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12; 2166 2167 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) { 2168 dev_err(ctrl->device, 2169 "Minimum device page size %u too large for host (%u)\n", 2170 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT); 2171 return -ENODEV; 2172 } 2173 2174 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI) 2175 ctrl->ctrl_config = NVME_CC_CSS_CSI; 2176 else 2177 ctrl->ctrl_config = NVME_CC_CSS_NVM; 2178 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT; 2179 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE; 2180 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES; 2181 ctrl->ctrl_config |= NVME_CC_ENABLE; 2182 2183 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2184 if (ret) 2185 return ret; 2186 return nvme_wait_ready(ctrl, ctrl->cap, true); 2187 } 2188 EXPORT_SYMBOL_GPL(nvme_enable_ctrl); 2189 2190 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl) 2191 { 2192 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ); 2193 u32 csts; 2194 int ret; 2195 2196 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK; 2197 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL; 2198 2199 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2200 if (ret) 2201 return ret; 2202 2203 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) { 2204 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT) 2205 break; 2206 2207 msleep(100); 2208 if (fatal_signal_pending(current)) 2209 return -EINTR; 2210 if (time_after(jiffies, timeout)) { 2211 dev_err(ctrl->device, 2212 "Device shutdown incomplete; abort shutdown\n"); 2213 return -ENODEV; 2214 } 2215 } 2216 2217 return ret; 2218 } 2219 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl); 2220 2221 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl) 2222 { 2223 __le64 ts; 2224 int ret; 2225 2226 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP)) 2227 return 0; 2228 2229 ts = cpu_to_le64(ktime_to_ms(ktime_get_real())); 2230 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts), 2231 NULL); 2232 if (ret) 2233 dev_warn_once(ctrl->device, 2234 "could not set timestamp (%d)\n", ret); 2235 return ret; 2236 } 2237 2238 static int nvme_configure_acre(struct nvme_ctrl *ctrl) 2239 { 2240 struct nvme_feat_host_behavior *host; 2241 int ret; 2242 2243 /* Don't bother enabling the feature if retry delay is not reported */ 2244 if (!ctrl->crdt[0]) 2245 return 0; 2246 2247 host = kzalloc(sizeof(*host), GFP_KERNEL); 2248 if (!host) 2249 return 0; 2250 2251 host->acre = NVME_ENABLE_ACRE; 2252 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0, 2253 host, sizeof(*host), NULL); 2254 kfree(host); 2255 return ret; 2256 } 2257 2258 /* 2259 * The function checks whether the given total (exlat + enlat) latency of 2260 * a power state allows the latter to be used as an APST transition target. 2261 * It does so by comparing the latency to the primary and secondary latency 2262 * tolerances defined by module params. If there's a match, the corresponding 2263 * timeout value is returned and the matching tolerance index (1 or 2) is 2264 * reported. 2265 */ 2266 static bool nvme_apst_get_transition_time(u64 total_latency, 2267 u64 *transition_time, unsigned *last_index) 2268 { 2269 if (total_latency <= apst_primary_latency_tol_us) { 2270 if (*last_index == 1) 2271 return false; 2272 *last_index = 1; 2273 *transition_time = apst_primary_timeout_ms; 2274 return true; 2275 } 2276 if (apst_secondary_timeout_ms && 2277 total_latency <= apst_secondary_latency_tol_us) { 2278 if (*last_index <= 2) 2279 return false; 2280 *last_index = 2; 2281 *transition_time = apst_secondary_timeout_ms; 2282 return true; 2283 } 2284 return false; 2285 } 2286 2287 /* 2288 * APST (Autonomous Power State Transition) lets us program a table of power 2289 * state transitions that the controller will perform automatically. 2290 * 2291 * Depending on module params, one of the two supported techniques will be used: 2292 * 2293 * - If the parameters provide explicit timeouts and tolerances, they will be 2294 * used to build a table with up to 2 non-operational states to transition to. 2295 * The default parameter values were selected based on the values used by 2296 * Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic 2297 * regeneration of the APST table in the event of switching between external 2298 * and battery power, the timeouts and tolerances reflect a compromise 2299 * between values used by Microsoft for AC and battery scenarios. 2300 * - If not, we'll configure the table with a simple heuristic: we are willing 2301 * to spend at most 2% of the time transitioning between power states. 2302 * Therefore, when running in any given state, we will enter the next 2303 * lower-power non-operational state after waiting 50 * (enlat + exlat) 2304 * microseconds, as long as that state's exit latency is under the requested 2305 * maximum latency. 2306 * 2307 * We will not autonomously enter any non-operational state for which the total 2308 * latency exceeds ps_max_latency_us. 2309 * 2310 * Users can set ps_max_latency_us to zero to turn off APST. 2311 */ 2312 static int nvme_configure_apst(struct nvme_ctrl *ctrl) 2313 { 2314 struct nvme_feat_auto_pst *table; 2315 unsigned apste = 0; 2316 u64 max_lat_us = 0; 2317 __le64 target = 0; 2318 int max_ps = -1; 2319 int state; 2320 int ret; 2321 unsigned last_lt_index = UINT_MAX; 2322 2323 /* 2324 * If APST isn't supported or if we haven't been initialized yet, 2325 * then don't do anything. 2326 */ 2327 if (!ctrl->apsta) 2328 return 0; 2329 2330 if (ctrl->npss > 31) { 2331 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n"); 2332 return 0; 2333 } 2334 2335 table = kzalloc(sizeof(*table), GFP_KERNEL); 2336 if (!table) 2337 return 0; 2338 2339 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) { 2340 /* Turn off APST. */ 2341 dev_dbg(ctrl->device, "APST disabled\n"); 2342 goto done; 2343 } 2344 2345 /* 2346 * Walk through all states from lowest- to highest-power. 2347 * According to the spec, lower-numbered states use more power. NPSS, 2348 * despite the name, is the index of the lowest-power state, not the 2349 * number of states. 2350 */ 2351 for (state = (int)ctrl->npss; state >= 0; state--) { 2352 u64 total_latency_us, exit_latency_us, transition_ms; 2353 2354 if (target) 2355 table->entries[state] = target; 2356 2357 /* 2358 * Don't allow transitions to the deepest state if it's quirked 2359 * off. 2360 */ 2361 if (state == ctrl->npss && 2362 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) 2363 continue; 2364 2365 /* 2366 * Is this state a useful non-operational state for higher-power 2367 * states to autonomously transition to? 2368 */ 2369 if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE)) 2370 continue; 2371 2372 exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat); 2373 if (exit_latency_us > ctrl->ps_max_latency_us) 2374 continue; 2375 2376 total_latency_us = exit_latency_us + 2377 le32_to_cpu(ctrl->psd[state].entry_lat); 2378 2379 /* 2380 * This state is good. It can be used as the APST idle target 2381 * for higher power states. 2382 */ 2383 if (apst_primary_timeout_ms && apst_primary_latency_tol_us) { 2384 if (!nvme_apst_get_transition_time(total_latency_us, 2385 &transition_ms, &last_lt_index)) 2386 continue; 2387 } else { 2388 transition_ms = total_latency_us + 19; 2389 do_div(transition_ms, 20); 2390 if (transition_ms > (1 << 24) - 1) 2391 transition_ms = (1 << 24) - 1; 2392 } 2393 2394 target = cpu_to_le64((state << 3) | (transition_ms << 8)); 2395 if (max_ps == -1) 2396 max_ps = state; 2397 if (total_latency_us > max_lat_us) 2398 max_lat_us = total_latency_us; 2399 } 2400 2401 if (max_ps == -1) 2402 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n"); 2403 else 2404 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n", 2405 max_ps, max_lat_us, (int)sizeof(*table), table); 2406 apste = 1; 2407 2408 done: 2409 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste, 2410 table, sizeof(*table), NULL); 2411 if (ret) 2412 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret); 2413 kfree(table); 2414 return ret; 2415 } 2416 2417 static void nvme_set_latency_tolerance(struct device *dev, s32 val) 2418 { 2419 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2420 u64 latency; 2421 2422 switch (val) { 2423 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT: 2424 case PM_QOS_LATENCY_ANY: 2425 latency = U64_MAX; 2426 break; 2427 2428 default: 2429 latency = val; 2430 } 2431 2432 if (ctrl->ps_max_latency_us != latency) { 2433 ctrl->ps_max_latency_us = latency; 2434 if (ctrl->state == NVME_CTRL_LIVE) 2435 nvme_configure_apst(ctrl); 2436 } 2437 } 2438 2439 struct nvme_core_quirk_entry { 2440 /* 2441 * NVMe model and firmware strings are padded with spaces. For 2442 * simplicity, strings in the quirk table are padded with NULLs 2443 * instead. 2444 */ 2445 u16 vid; 2446 const char *mn; 2447 const char *fr; 2448 unsigned long quirks; 2449 }; 2450 2451 static const struct nvme_core_quirk_entry core_quirks[] = { 2452 { 2453 /* 2454 * This Toshiba device seems to die using any APST states. See: 2455 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11 2456 */ 2457 .vid = 0x1179, 2458 .mn = "THNSF5256GPUK TOSHIBA", 2459 .quirks = NVME_QUIRK_NO_APST, 2460 }, 2461 { 2462 /* 2463 * This LiteON CL1-3D*-Q11 firmware version has a race 2464 * condition associated with actions related to suspend to idle 2465 * LiteON has resolved the problem in future firmware 2466 */ 2467 .vid = 0x14a4, 2468 .fr = "22301111", 2469 .quirks = NVME_QUIRK_SIMPLE_SUSPEND, 2470 } 2471 }; 2472 2473 /* match is null-terminated but idstr is space-padded. */ 2474 static bool string_matches(const char *idstr, const char *match, size_t len) 2475 { 2476 size_t matchlen; 2477 2478 if (!match) 2479 return true; 2480 2481 matchlen = strlen(match); 2482 WARN_ON_ONCE(matchlen > len); 2483 2484 if (memcmp(idstr, match, matchlen)) 2485 return false; 2486 2487 for (; matchlen < len; matchlen++) 2488 if (idstr[matchlen] != ' ') 2489 return false; 2490 2491 return true; 2492 } 2493 2494 static bool quirk_matches(const struct nvme_id_ctrl *id, 2495 const struct nvme_core_quirk_entry *q) 2496 { 2497 return q->vid == le16_to_cpu(id->vid) && 2498 string_matches(id->mn, q->mn, sizeof(id->mn)) && 2499 string_matches(id->fr, q->fr, sizeof(id->fr)); 2500 } 2501 2502 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl, 2503 struct nvme_id_ctrl *id) 2504 { 2505 size_t nqnlen; 2506 int off; 2507 2508 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) { 2509 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE); 2510 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) { 2511 strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE); 2512 return; 2513 } 2514 2515 if (ctrl->vs >= NVME_VS(1, 2, 1)) 2516 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n"); 2517 } 2518 2519 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */ 2520 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE, 2521 "nqn.2014.08.org.nvmexpress:%04x%04x", 2522 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid)); 2523 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn)); 2524 off += sizeof(id->sn); 2525 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn)); 2526 off += sizeof(id->mn); 2527 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off); 2528 } 2529 2530 static void nvme_release_subsystem(struct device *dev) 2531 { 2532 struct nvme_subsystem *subsys = 2533 container_of(dev, struct nvme_subsystem, dev); 2534 2535 if (subsys->instance >= 0) 2536 ida_simple_remove(&nvme_instance_ida, subsys->instance); 2537 kfree(subsys); 2538 } 2539 2540 static void nvme_destroy_subsystem(struct kref *ref) 2541 { 2542 struct nvme_subsystem *subsys = 2543 container_of(ref, struct nvme_subsystem, ref); 2544 2545 mutex_lock(&nvme_subsystems_lock); 2546 list_del(&subsys->entry); 2547 mutex_unlock(&nvme_subsystems_lock); 2548 2549 ida_destroy(&subsys->ns_ida); 2550 device_del(&subsys->dev); 2551 put_device(&subsys->dev); 2552 } 2553 2554 static void nvme_put_subsystem(struct nvme_subsystem *subsys) 2555 { 2556 kref_put(&subsys->ref, nvme_destroy_subsystem); 2557 } 2558 2559 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn) 2560 { 2561 struct nvme_subsystem *subsys; 2562 2563 lockdep_assert_held(&nvme_subsystems_lock); 2564 2565 /* 2566 * Fail matches for discovery subsystems. This results 2567 * in each discovery controller bound to a unique subsystem. 2568 * This avoids issues with validating controller values 2569 * that can only be true when there is a single unique subsystem. 2570 * There may be multiple and completely independent entities 2571 * that provide discovery controllers. 2572 */ 2573 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME)) 2574 return NULL; 2575 2576 list_for_each_entry(subsys, &nvme_subsystems, entry) { 2577 if (strcmp(subsys->subnqn, subsysnqn)) 2578 continue; 2579 if (!kref_get_unless_zero(&subsys->ref)) 2580 continue; 2581 return subsys; 2582 } 2583 2584 return NULL; 2585 } 2586 2587 #define SUBSYS_ATTR_RO(_name, _mode, _show) \ 2588 struct device_attribute subsys_attr_##_name = \ 2589 __ATTR(_name, _mode, _show, NULL) 2590 2591 static ssize_t nvme_subsys_show_nqn(struct device *dev, 2592 struct device_attribute *attr, 2593 char *buf) 2594 { 2595 struct nvme_subsystem *subsys = 2596 container_of(dev, struct nvme_subsystem, dev); 2597 2598 return sysfs_emit(buf, "%s\n", subsys->subnqn); 2599 } 2600 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn); 2601 2602 #define nvme_subsys_show_str_function(field) \ 2603 static ssize_t subsys_##field##_show(struct device *dev, \ 2604 struct device_attribute *attr, char *buf) \ 2605 { \ 2606 struct nvme_subsystem *subsys = \ 2607 container_of(dev, struct nvme_subsystem, dev); \ 2608 return sysfs_emit(buf, "%.*s\n", \ 2609 (int)sizeof(subsys->field), subsys->field); \ 2610 } \ 2611 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show); 2612 2613 nvme_subsys_show_str_function(model); 2614 nvme_subsys_show_str_function(serial); 2615 nvme_subsys_show_str_function(firmware_rev); 2616 2617 static struct attribute *nvme_subsys_attrs[] = { 2618 &subsys_attr_model.attr, 2619 &subsys_attr_serial.attr, 2620 &subsys_attr_firmware_rev.attr, 2621 &subsys_attr_subsysnqn.attr, 2622 #ifdef CONFIG_NVME_MULTIPATH 2623 &subsys_attr_iopolicy.attr, 2624 #endif 2625 NULL, 2626 }; 2627 2628 static const struct attribute_group nvme_subsys_attrs_group = { 2629 .attrs = nvme_subsys_attrs, 2630 }; 2631 2632 static const struct attribute_group *nvme_subsys_attrs_groups[] = { 2633 &nvme_subsys_attrs_group, 2634 NULL, 2635 }; 2636 2637 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl) 2638 { 2639 return ctrl->opts && ctrl->opts->discovery_nqn; 2640 } 2641 2642 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys, 2643 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 2644 { 2645 struct nvme_ctrl *tmp; 2646 2647 lockdep_assert_held(&nvme_subsystems_lock); 2648 2649 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) { 2650 if (nvme_state_terminal(tmp)) 2651 continue; 2652 2653 if (tmp->cntlid == ctrl->cntlid) { 2654 dev_err(ctrl->device, 2655 "Duplicate cntlid %u with %s, rejecting\n", 2656 ctrl->cntlid, dev_name(tmp->device)); 2657 return false; 2658 } 2659 2660 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) || 2661 nvme_discovery_ctrl(ctrl)) 2662 continue; 2663 2664 dev_err(ctrl->device, 2665 "Subsystem does not support multiple controllers\n"); 2666 return false; 2667 } 2668 2669 return true; 2670 } 2671 2672 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 2673 { 2674 struct nvme_subsystem *subsys, *found; 2675 int ret; 2676 2677 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL); 2678 if (!subsys) 2679 return -ENOMEM; 2680 2681 subsys->instance = -1; 2682 mutex_init(&subsys->lock); 2683 kref_init(&subsys->ref); 2684 INIT_LIST_HEAD(&subsys->ctrls); 2685 INIT_LIST_HEAD(&subsys->nsheads); 2686 nvme_init_subnqn(subsys, ctrl, id); 2687 memcpy(subsys->serial, id->sn, sizeof(subsys->serial)); 2688 memcpy(subsys->model, id->mn, sizeof(subsys->model)); 2689 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev)); 2690 subsys->vendor_id = le16_to_cpu(id->vid); 2691 subsys->cmic = id->cmic; 2692 subsys->awupf = le16_to_cpu(id->awupf); 2693 #ifdef CONFIG_NVME_MULTIPATH 2694 subsys->iopolicy = NVME_IOPOLICY_NUMA; 2695 #endif 2696 2697 subsys->dev.class = nvme_subsys_class; 2698 subsys->dev.release = nvme_release_subsystem; 2699 subsys->dev.groups = nvme_subsys_attrs_groups; 2700 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance); 2701 device_initialize(&subsys->dev); 2702 2703 mutex_lock(&nvme_subsystems_lock); 2704 found = __nvme_find_get_subsystem(subsys->subnqn); 2705 if (found) { 2706 put_device(&subsys->dev); 2707 subsys = found; 2708 2709 if (!nvme_validate_cntlid(subsys, ctrl, id)) { 2710 ret = -EINVAL; 2711 goto out_put_subsystem; 2712 } 2713 } else { 2714 ret = device_add(&subsys->dev); 2715 if (ret) { 2716 dev_err(ctrl->device, 2717 "failed to register subsystem device.\n"); 2718 put_device(&subsys->dev); 2719 goto out_unlock; 2720 } 2721 ida_init(&subsys->ns_ida); 2722 list_add_tail(&subsys->entry, &nvme_subsystems); 2723 } 2724 2725 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj, 2726 dev_name(ctrl->device)); 2727 if (ret) { 2728 dev_err(ctrl->device, 2729 "failed to create sysfs link from subsystem.\n"); 2730 goto out_put_subsystem; 2731 } 2732 2733 if (!found) 2734 subsys->instance = ctrl->instance; 2735 ctrl->subsys = subsys; 2736 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls); 2737 mutex_unlock(&nvme_subsystems_lock); 2738 return 0; 2739 2740 out_put_subsystem: 2741 nvme_put_subsystem(subsys); 2742 out_unlock: 2743 mutex_unlock(&nvme_subsystems_lock); 2744 return ret; 2745 } 2746 2747 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi, 2748 void *log, size_t size, u64 offset) 2749 { 2750 struct nvme_command c = { }; 2751 u32 dwlen = nvme_bytes_to_numd(size); 2752 2753 c.get_log_page.opcode = nvme_admin_get_log_page; 2754 c.get_log_page.nsid = cpu_to_le32(nsid); 2755 c.get_log_page.lid = log_page; 2756 c.get_log_page.lsp = lsp; 2757 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1)); 2758 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16); 2759 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset)); 2760 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset)); 2761 c.get_log_page.csi = csi; 2762 2763 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size); 2764 } 2765 2766 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi, 2767 struct nvme_effects_log **log) 2768 { 2769 struct nvme_effects_log *cel = xa_load(&ctrl->cels, csi); 2770 int ret; 2771 2772 if (cel) 2773 goto out; 2774 2775 cel = kzalloc(sizeof(*cel), GFP_KERNEL); 2776 if (!cel) 2777 return -ENOMEM; 2778 2779 ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi, 2780 cel, sizeof(*cel), 0); 2781 if (ret) { 2782 kfree(cel); 2783 return ret; 2784 } 2785 2786 xa_store(&ctrl->cels, csi, cel, GFP_KERNEL); 2787 out: 2788 *log = cel; 2789 return 0; 2790 } 2791 2792 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units) 2793 { 2794 u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val; 2795 2796 if (check_shl_overflow(1U, units + page_shift - 9, &val)) 2797 return UINT_MAX; 2798 return val; 2799 } 2800 2801 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl) 2802 { 2803 struct nvme_command c = { }; 2804 struct nvme_id_ctrl_nvm *id; 2805 int ret; 2806 2807 if (ctrl->oncs & NVME_CTRL_ONCS_DSM) { 2808 ctrl->max_discard_sectors = UINT_MAX; 2809 ctrl->max_discard_segments = NVME_DSM_MAX_RANGES; 2810 } else { 2811 ctrl->max_discard_sectors = 0; 2812 ctrl->max_discard_segments = 0; 2813 } 2814 2815 /* 2816 * Even though NVMe spec explicitly states that MDTS is not applicable 2817 * to the write-zeroes, we are cautious and limit the size to the 2818 * controllers max_hw_sectors value, which is based on the MDTS field 2819 * and possibly other limiting factors. 2820 */ 2821 if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) && 2822 !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES)) 2823 ctrl->max_zeroes_sectors = ctrl->max_hw_sectors; 2824 else 2825 ctrl->max_zeroes_sectors = 0; 2826 2827 if (nvme_ctrl_limited_cns(ctrl)) 2828 return 0; 2829 2830 id = kzalloc(sizeof(*id), GFP_KERNEL); 2831 if (!id) 2832 return 0; 2833 2834 c.identify.opcode = nvme_admin_identify; 2835 c.identify.cns = NVME_ID_CNS_CS_CTRL; 2836 c.identify.csi = NVME_CSI_NVM; 2837 2838 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id)); 2839 if (ret) 2840 goto free_data; 2841 2842 if (id->dmrl) 2843 ctrl->max_discard_segments = id->dmrl; 2844 if (id->dmrsl) 2845 ctrl->max_discard_sectors = le32_to_cpu(id->dmrsl); 2846 if (id->wzsl) 2847 ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl); 2848 2849 free_data: 2850 kfree(id); 2851 return ret; 2852 } 2853 2854 static int nvme_init_identify(struct nvme_ctrl *ctrl) 2855 { 2856 struct nvme_id_ctrl *id; 2857 u32 max_hw_sectors; 2858 bool prev_apst_enabled; 2859 int ret; 2860 2861 ret = nvme_identify_ctrl(ctrl, &id); 2862 if (ret) { 2863 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret); 2864 return -EIO; 2865 } 2866 2867 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) { 2868 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects); 2869 if (ret < 0) 2870 goto out_free; 2871 } 2872 2873 if (!(ctrl->ops->flags & NVME_F_FABRICS)) 2874 ctrl->cntlid = le16_to_cpu(id->cntlid); 2875 2876 if (!ctrl->identified) { 2877 unsigned int i; 2878 2879 ret = nvme_init_subsystem(ctrl, id); 2880 if (ret) 2881 goto out_free; 2882 2883 /* 2884 * Check for quirks. Quirk can depend on firmware version, 2885 * so, in principle, the set of quirks present can change 2886 * across a reset. As a possible future enhancement, we 2887 * could re-scan for quirks every time we reinitialize 2888 * the device, but we'd have to make sure that the driver 2889 * behaves intelligently if the quirks change. 2890 */ 2891 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) { 2892 if (quirk_matches(id, &core_quirks[i])) 2893 ctrl->quirks |= core_quirks[i].quirks; 2894 } 2895 } 2896 2897 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) { 2898 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n"); 2899 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS; 2900 } 2901 2902 ctrl->crdt[0] = le16_to_cpu(id->crdt1); 2903 ctrl->crdt[1] = le16_to_cpu(id->crdt2); 2904 ctrl->crdt[2] = le16_to_cpu(id->crdt3); 2905 2906 ctrl->oacs = le16_to_cpu(id->oacs); 2907 ctrl->oncs = le16_to_cpu(id->oncs); 2908 ctrl->mtfa = le16_to_cpu(id->mtfa); 2909 ctrl->oaes = le32_to_cpu(id->oaes); 2910 ctrl->wctemp = le16_to_cpu(id->wctemp); 2911 ctrl->cctemp = le16_to_cpu(id->cctemp); 2912 2913 atomic_set(&ctrl->abort_limit, id->acl + 1); 2914 ctrl->vwc = id->vwc; 2915 if (id->mdts) 2916 max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts); 2917 else 2918 max_hw_sectors = UINT_MAX; 2919 ctrl->max_hw_sectors = 2920 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors); 2921 2922 nvme_set_queue_limits(ctrl, ctrl->admin_q); 2923 ctrl->sgls = le32_to_cpu(id->sgls); 2924 ctrl->kas = le16_to_cpu(id->kas); 2925 ctrl->max_namespaces = le32_to_cpu(id->mnan); 2926 ctrl->ctratt = le32_to_cpu(id->ctratt); 2927 2928 if (id->rtd3e) { 2929 /* us -> s */ 2930 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC; 2931 2932 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time, 2933 shutdown_timeout, 60); 2934 2935 if (ctrl->shutdown_timeout != shutdown_timeout) 2936 dev_info(ctrl->device, 2937 "Shutdown timeout set to %u seconds\n", 2938 ctrl->shutdown_timeout); 2939 } else 2940 ctrl->shutdown_timeout = shutdown_timeout; 2941 2942 ctrl->npss = id->npss; 2943 ctrl->apsta = id->apsta; 2944 prev_apst_enabled = ctrl->apst_enabled; 2945 if (ctrl->quirks & NVME_QUIRK_NO_APST) { 2946 if (force_apst && id->apsta) { 2947 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n"); 2948 ctrl->apst_enabled = true; 2949 } else { 2950 ctrl->apst_enabled = false; 2951 } 2952 } else { 2953 ctrl->apst_enabled = id->apsta; 2954 } 2955 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd)); 2956 2957 if (ctrl->ops->flags & NVME_F_FABRICS) { 2958 ctrl->icdoff = le16_to_cpu(id->icdoff); 2959 ctrl->ioccsz = le32_to_cpu(id->ioccsz); 2960 ctrl->iorcsz = le32_to_cpu(id->iorcsz); 2961 ctrl->maxcmd = le16_to_cpu(id->maxcmd); 2962 2963 /* 2964 * In fabrics we need to verify the cntlid matches the 2965 * admin connect 2966 */ 2967 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) { 2968 dev_err(ctrl->device, 2969 "Mismatching cntlid: Connect %u vs Identify " 2970 "%u, rejecting\n", 2971 ctrl->cntlid, le16_to_cpu(id->cntlid)); 2972 ret = -EINVAL; 2973 goto out_free; 2974 } 2975 2976 if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) { 2977 dev_err(ctrl->device, 2978 "keep-alive support is mandatory for fabrics\n"); 2979 ret = -EINVAL; 2980 goto out_free; 2981 } 2982 } else { 2983 ctrl->hmpre = le32_to_cpu(id->hmpre); 2984 ctrl->hmmin = le32_to_cpu(id->hmmin); 2985 ctrl->hmminds = le32_to_cpu(id->hmminds); 2986 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd); 2987 } 2988 2989 ret = nvme_mpath_init_identify(ctrl, id); 2990 if (ret < 0) 2991 goto out_free; 2992 2993 if (ctrl->apst_enabled && !prev_apst_enabled) 2994 dev_pm_qos_expose_latency_tolerance(ctrl->device); 2995 else if (!ctrl->apst_enabled && prev_apst_enabled) 2996 dev_pm_qos_hide_latency_tolerance(ctrl->device); 2997 2998 out_free: 2999 kfree(id); 3000 return ret; 3001 } 3002 3003 /* 3004 * Initialize the cached copies of the Identify data and various controller 3005 * register in our nvme_ctrl structure. This should be called as soon as 3006 * the admin queue is fully up and running. 3007 */ 3008 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl) 3009 { 3010 int ret; 3011 3012 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs); 3013 if (ret) { 3014 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret); 3015 return ret; 3016 } 3017 3018 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize); 3019 3020 if (ctrl->vs >= NVME_VS(1, 1, 0)) 3021 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap); 3022 3023 ret = nvme_init_identify(ctrl); 3024 if (ret) 3025 return ret; 3026 3027 ret = nvme_init_non_mdts_limits(ctrl); 3028 if (ret < 0) 3029 return ret; 3030 3031 ret = nvme_configure_apst(ctrl); 3032 if (ret < 0) 3033 return ret; 3034 3035 ret = nvme_configure_timestamp(ctrl); 3036 if (ret < 0) 3037 return ret; 3038 3039 ret = nvme_configure_directives(ctrl); 3040 if (ret < 0) 3041 return ret; 3042 3043 ret = nvme_configure_acre(ctrl); 3044 if (ret < 0) 3045 return ret; 3046 3047 if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) { 3048 ret = nvme_hwmon_init(ctrl); 3049 if (ret < 0) 3050 return ret; 3051 } 3052 3053 ctrl->identified = true; 3054 3055 return 0; 3056 } 3057 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish); 3058 3059 static int nvme_dev_open(struct inode *inode, struct file *file) 3060 { 3061 struct nvme_ctrl *ctrl = 3062 container_of(inode->i_cdev, struct nvme_ctrl, cdev); 3063 3064 switch (ctrl->state) { 3065 case NVME_CTRL_LIVE: 3066 break; 3067 default: 3068 return -EWOULDBLOCK; 3069 } 3070 3071 nvme_get_ctrl(ctrl); 3072 if (!try_module_get(ctrl->ops->module)) { 3073 nvme_put_ctrl(ctrl); 3074 return -EINVAL; 3075 } 3076 3077 file->private_data = ctrl; 3078 return 0; 3079 } 3080 3081 static int nvme_dev_release(struct inode *inode, struct file *file) 3082 { 3083 struct nvme_ctrl *ctrl = 3084 container_of(inode->i_cdev, struct nvme_ctrl, cdev); 3085 3086 module_put(ctrl->ops->module); 3087 nvme_put_ctrl(ctrl); 3088 return 0; 3089 } 3090 3091 static const struct file_operations nvme_dev_fops = { 3092 .owner = THIS_MODULE, 3093 .open = nvme_dev_open, 3094 .release = nvme_dev_release, 3095 .unlocked_ioctl = nvme_dev_ioctl, 3096 .compat_ioctl = compat_ptr_ioctl, 3097 }; 3098 3099 static ssize_t nvme_sysfs_reset(struct device *dev, 3100 struct device_attribute *attr, const char *buf, 3101 size_t count) 3102 { 3103 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3104 int ret; 3105 3106 ret = nvme_reset_ctrl_sync(ctrl); 3107 if (ret < 0) 3108 return ret; 3109 return count; 3110 } 3111 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset); 3112 3113 static ssize_t nvme_sysfs_rescan(struct device *dev, 3114 struct device_attribute *attr, const char *buf, 3115 size_t count) 3116 { 3117 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3118 3119 nvme_queue_scan(ctrl); 3120 return count; 3121 } 3122 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan); 3123 3124 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev) 3125 { 3126 struct gendisk *disk = dev_to_disk(dev); 3127 3128 if (disk->fops == &nvme_bdev_ops) 3129 return nvme_get_ns_from_dev(dev)->head; 3130 else 3131 return disk->private_data; 3132 } 3133 3134 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr, 3135 char *buf) 3136 { 3137 struct nvme_ns_head *head = dev_to_ns_head(dev); 3138 struct nvme_ns_ids *ids = &head->ids; 3139 struct nvme_subsystem *subsys = head->subsys; 3140 int serial_len = sizeof(subsys->serial); 3141 int model_len = sizeof(subsys->model); 3142 3143 if (!uuid_is_null(&ids->uuid)) 3144 return sysfs_emit(buf, "uuid.%pU\n", &ids->uuid); 3145 3146 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 3147 return sysfs_emit(buf, "eui.%16phN\n", ids->nguid); 3148 3149 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 3150 return sysfs_emit(buf, "eui.%8phN\n", ids->eui64); 3151 3152 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' || 3153 subsys->serial[serial_len - 1] == '\0')) 3154 serial_len--; 3155 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' || 3156 subsys->model[model_len - 1] == '\0')) 3157 model_len--; 3158 3159 return sysfs_emit(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id, 3160 serial_len, subsys->serial, model_len, subsys->model, 3161 head->ns_id); 3162 } 3163 static DEVICE_ATTR_RO(wwid); 3164 3165 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr, 3166 char *buf) 3167 { 3168 return sysfs_emit(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid); 3169 } 3170 static DEVICE_ATTR_RO(nguid); 3171 3172 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr, 3173 char *buf) 3174 { 3175 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids; 3176 3177 /* For backward compatibility expose the NGUID to userspace if 3178 * we have no UUID set 3179 */ 3180 if (uuid_is_null(&ids->uuid)) { 3181 printk_ratelimited(KERN_WARNING 3182 "No UUID available providing old NGUID\n"); 3183 return sysfs_emit(buf, "%pU\n", ids->nguid); 3184 } 3185 return sysfs_emit(buf, "%pU\n", &ids->uuid); 3186 } 3187 static DEVICE_ATTR_RO(uuid); 3188 3189 static ssize_t eui_show(struct device *dev, struct device_attribute *attr, 3190 char *buf) 3191 { 3192 return sysfs_emit(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64); 3193 } 3194 static DEVICE_ATTR_RO(eui); 3195 3196 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr, 3197 char *buf) 3198 { 3199 return sysfs_emit(buf, "%d\n", dev_to_ns_head(dev)->ns_id); 3200 } 3201 static DEVICE_ATTR_RO(nsid); 3202 3203 static struct attribute *nvme_ns_id_attrs[] = { 3204 &dev_attr_wwid.attr, 3205 &dev_attr_uuid.attr, 3206 &dev_attr_nguid.attr, 3207 &dev_attr_eui.attr, 3208 &dev_attr_nsid.attr, 3209 #ifdef CONFIG_NVME_MULTIPATH 3210 &dev_attr_ana_grpid.attr, 3211 &dev_attr_ana_state.attr, 3212 #endif 3213 NULL, 3214 }; 3215 3216 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj, 3217 struct attribute *a, int n) 3218 { 3219 struct device *dev = container_of(kobj, struct device, kobj); 3220 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids; 3221 3222 if (a == &dev_attr_uuid.attr) { 3223 if (uuid_is_null(&ids->uuid) && 3224 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 3225 return 0; 3226 } 3227 if (a == &dev_attr_nguid.attr) { 3228 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 3229 return 0; 3230 } 3231 if (a == &dev_attr_eui.attr) { 3232 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 3233 return 0; 3234 } 3235 #ifdef CONFIG_NVME_MULTIPATH 3236 if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) { 3237 if (dev_to_disk(dev)->fops != &nvme_bdev_ops) /* per-path attr */ 3238 return 0; 3239 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl)) 3240 return 0; 3241 } 3242 #endif 3243 return a->mode; 3244 } 3245 3246 static const struct attribute_group nvme_ns_id_attr_group = { 3247 .attrs = nvme_ns_id_attrs, 3248 .is_visible = nvme_ns_id_attrs_are_visible, 3249 }; 3250 3251 const struct attribute_group *nvme_ns_id_attr_groups[] = { 3252 &nvme_ns_id_attr_group, 3253 NULL, 3254 }; 3255 3256 #define nvme_show_str_function(field) \ 3257 static ssize_t field##_show(struct device *dev, \ 3258 struct device_attribute *attr, char *buf) \ 3259 { \ 3260 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \ 3261 return sysfs_emit(buf, "%.*s\n", \ 3262 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \ 3263 } \ 3264 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL); 3265 3266 nvme_show_str_function(model); 3267 nvme_show_str_function(serial); 3268 nvme_show_str_function(firmware_rev); 3269 3270 #define nvme_show_int_function(field) \ 3271 static ssize_t field##_show(struct device *dev, \ 3272 struct device_attribute *attr, char *buf) \ 3273 { \ 3274 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \ 3275 return sysfs_emit(buf, "%d\n", ctrl->field); \ 3276 } \ 3277 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL); 3278 3279 nvme_show_int_function(cntlid); 3280 nvme_show_int_function(numa_node); 3281 nvme_show_int_function(queue_count); 3282 nvme_show_int_function(sqsize); 3283 nvme_show_int_function(kato); 3284 3285 static ssize_t nvme_sysfs_delete(struct device *dev, 3286 struct device_attribute *attr, const char *buf, 3287 size_t count) 3288 { 3289 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3290 3291 if (device_remove_file_self(dev, attr)) 3292 nvme_delete_ctrl_sync(ctrl); 3293 return count; 3294 } 3295 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete); 3296 3297 static ssize_t nvme_sysfs_show_transport(struct device *dev, 3298 struct device_attribute *attr, 3299 char *buf) 3300 { 3301 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3302 3303 return sysfs_emit(buf, "%s\n", ctrl->ops->name); 3304 } 3305 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL); 3306 3307 static ssize_t nvme_sysfs_show_state(struct device *dev, 3308 struct device_attribute *attr, 3309 char *buf) 3310 { 3311 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3312 static const char *const state_name[] = { 3313 [NVME_CTRL_NEW] = "new", 3314 [NVME_CTRL_LIVE] = "live", 3315 [NVME_CTRL_RESETTING] = "resetting", 3316 [NVME_CTRL_CONNECTING] = "connecting", 3317 [NVME_CTRL_DELETING] = "deleting", 3318 [NVME_CTRL_DELETING_NOIO]= "deleting (no IO)", 3319 [NVME_CTRL_DEAD] = "dead", 3320 }; 3321 3322 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) && 3323 state_name[ctrl->state]) 3324 return sysfs_emit(buf, "%s\n", state_name[ctrl->state]); 3325 3326 return sysfs_emit(buf, "unknown state\n"); 3327 } 3328 3329 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL); 3330 3331 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev, 3332 struct device_attribute *attr, 3333 char *buf) 3334 { 3335 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3336 3337 return sysfs_emit(buf, "%s\n", ctrl->subsys->subnqn); 3338 } 3339 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL); 3340 3341 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev, 3342 struct device_attribute *attr, 3343 char *buf) 3344 { 3345 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3346 3347 return sysfs_emit(buf, "%s\n", ctrl->opts->host->nqn); 3348 } 3349 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL); 3350 3351 static ssize_t nvme_sysfs_show_hostid(struct device *dev, 3352 struct device_attribute *attr, 3353 char *buf) 3354 { 3355 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3356 3357 return sysfs_emit(buf, "%pU\n", &ctrl->opts->host->id); 3358 } 3359 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL); 3360 3361 static ssize_t nvme_sysfs_show_address(struct device *dev, 3362 struct device_attribute *attr, 3363 char *buf) 3364 { 3365 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3366 3367 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE); 3368 } 3369 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL); 3370 3371 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev, 3372 struct device_attribute *attr, char *buf) 3373 { 3374 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3375 struct nvmf_ctrl_options *opts = ctrl->opts; 3376 3377 if (ctrl->opts->max_reconnects == -1) 3378 return sysfs_emit(buf, "off\n"); 3379 return sysfs_emit(buf, "%d\n", 3380 opts->max_reconnects * opts->reconnect_delay); 3381 } 3382 3383 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev, 3384 struct device_attribute *attr, const char *buf, size_t count) 3385 { 3386 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3387 struct nvmf_ctrl_options *opts = ctrl->opts; 3388 int ctrl_loss_tmo, err; 3389 3390 err = kstrtoint(buf, 10, &ctrl_loss_tmo); 3391 if (err) 3392 return -EINVAL; 3393 3394 if (ctrl_loss_tmo < 0) 3395 opts->max_reconnects = -1; 3396 else 3397 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo, 3398 opts->reconnect_delay); 3399 return count; 3400 } 3401 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR, 3402 nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store); 3403 3404 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev, 3405 struct device_attribute *attr, char *buf) 3406 { 3407 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3408 3409 if (ctrl->opts->reconnect_delay == -1) 3410 return sysfs_emit(buf, "off\n"); 3411 return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay); 3412 } 3413 3414 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev, 3415 struct device_attribute *attr, const char *buf, size_t count) 3416 { 3417 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3418 unsigned int v; 3419 int err; 3420 3421 err = kstrtou32(buf, 10, &v); 3422 if (err) 3423 return err; 3424 3425 ctrl->opts->reconnect_delay = v; 3426 return count; 3427 } 3428 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR, 3429 nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store); 3430 3431 static ssize_t nvme_ctrl_fast_io_fail_tmo_show(struct device *dev, 3432 struct device_attribute *attr, char *buf) 3433 { 3434 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3435 3436 if (ctrl->opts->fast_io_fail_tmo == -1) 3437 return sysfs_emit(buf, "off\n"); 3438 return sysfs_emit(buf, "%d\n", ctrl->opts->fast_io_fail_tmo); 3439 } 3440 3441 static ssize_t nvme_ctrl_fast_io_fail_tmo_store(struct device *dev, 3442 struct device_attribute *attr, const char *buf, size_t count) 3443 { 3444 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3445 struct nvmf_ctrl_options *opts = ctrl->opts; 3446 int fast_io_fail_tmo, err; 3447 3448 err = kstrtoint(buf, 10, &fast_io_fail_tmo); 3449 if (err) 3450 return -EINVAL; 3451 3452 if (fast_io_fail_tmo < 0) 3453 opts->fast_io_fail_tmo = -1; 3454 else 3455 opts->fast_io_fail_tmo = fast_io_fail_tmo; 3456 return count; 3457 } 3458 static DEVICE_ATTR(fast_io_fail_tmo, S_IRUGO | S_IWUSR, 3459 nvme_ctrl_fast_io_fail_tmo_show, nvme_ctrl_fast_io_fail_tmo_store); 3460 3461 static struct attribute *nvme_dev_attrs[] = { 3462 &dev_attr_reset_controller.attr, 3463 &dev_attr_rescan_controller.attr, 3464 &dev_attr_model.attr, 3465 &dev_attr_serial.attr, 3466 &dev_attr_firmware_rev.attr, 3467 &dev_attr_cntlid.attr, 3468 &dev_attr_delete_controller.attr, 3469 &dev_attr_transport.attr, 3470 &dev_attr_subsysnqn.attr, 3471 &dev_attr_address.attr, 3472 &dev_attr_state.attr, 3473 &dev_attr_numa_node.attr, 3474 &dev_attr_queue_count.attr, 3475 &dev_attr_sqsize.attr, 3476 &dev_attr_hostnqn.attr, 3477 &dev_attr_hostid.attr, 3478 &dev_attr_ctrl_loss_tmo.attr, 3479 &dev_attr_reconnect_delay.attr, 3480 &dev_attr_fast_io_fail_tmo.attr, 3481 &dev_attr_kato.attr, 3482 NULL 3483 }; 3484 3485 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj, 3486 struct attribute *a, int n) 3487 { 3488 struct device *dev = container_of(kobj, struct device, kobj); 3489 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3490 3491 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl) 3492 return 0; 3493 if (a == &dev_attr_address.attr && !ctrl->ops->get_address) 3494 return 0; 3495 if (a == &dev_attr_hostnqn.attr && !ctrl->opts) 3496 return 0; 3497 if (a == &dev_attr_hostid.attr && !ctrl->opts) 3498 return 0; 3499 if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts) 3500 return 0; 3501 if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts) 3502 return 0; 3503 if (a == &dev_attr_fast_io_fail_tmo.attr && !ctrl->opts) 3504 return 0; 3505 3506 return a->mode; 3507 } 3508 3509 static const struct attribute_group nvme_dev_attrs_group = { 3510 .attrs = nvme_dev_attrs, 3511 .is_visible = nvme_dev_attrs_are_visible, 3512 }; 3513 3514 static const struct attribute_group *nvme_dev_attr_groups[] = { 3515 &nvme_dev_attrs_group, 3516 NULL, 3517 }; 3518 3519 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys, 3520 unsigned nsid) 3521 { 3522 struct nvme_ns_head *h; 3523 3524 lockdep_assert_held(&subsys->lock); 3525 3526 list_for_each_entry(h, &subsys->nsheads, entry) { 3527 if (h->ns_id == nsid && nvme_tryget_ns_head(h)) 3528 return h; 3529 } 3530 3531 return NULL; 3532 } 3533 3534 static int __nvme_check_ids(struct nvme_subsystem *subsys, 3535 struct nvme_ns_head *new) 3536 { 3537 struct nvme_ns_head *h; 3538 3539 lockdep_assert_held(&subsys->lock); 3540 3541 list_for_each_entry(h, &subsys->nsheads, entry) { 3542 if (nvme_ns_ids_valid(&new->ids) && 3543 nvme_ns_ids_equal(&new->ids, &h->ids)) 3544 return -EINVAL; 3545 } 3546 3547 return 0; 3548 } 3549 3550 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device) 3551 { 3552 cdev_device_del(cdev, cdev_device); 3553 ida_simple_remove(&nvme_ns_chr_minor_ida, MINOR(cdev_device->devt)); 3554 } 3555 3556 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device, 3557 const struct file_operations *fops, struct module *owner) 3558 { 3559 int minor, ret; 3560 3561 minor = ida_simple_get(&nvme_ns_chr_minor_ida, 0, 0, GFP_KERNEL); 3562 if (minor < 0) 3563 return minor; 3564 cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor); 3565 cdev_device->class = nvme_ns_chr_class; 3566 device_initialize(cdev_device); 3567 cdev_init(cdev, fops); 3568 cdev->owner = owner; 3569 ret = cdev_device_add(cdev, cdev_device); 3570 if (ret) { 3571 put_device(cdev_device); 3572 ida_simple_remove(&nvme_ns_chr_minor_ida, minor); 3573 } 3574 return ret; 3575 } 3576 3577 static int nvme_ns_chr_open(struct inode *inode, struct file *file) 3578 { 3579 return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev)); 3580 } 3581 3582 static int nvme_ns_chr_release(struct inode *inode, struct file *file) 3583 { 3584 nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev)); 3585 return 0; 3586 } 3587 3588 static const struct file_operations nvme_ns_chr_fops = { 3589 .owner = THIS_MODULE, 3590 .open = nvme_ns_chr_open, 3591 .release = nvme_ns_chr_release, 3592 .unlocked_ioctl = nvme_ns_chr_ioctl, 3593 .compat_ioctl = compat_ptr_ioctl, 3594 }; 3595 3596 static int nvme_add_ns_cdev(struct nvme_ns *ns) 3597 { 3598 int ret; 3599 3600 ns->cdev_device.parent = ns->ctrl->device; 3601 ret = dev_set_name(&ns->cdev_device, "ng%dn%d", 3602 ns->ctrl->instance, ns->head->instance); 3603 if (ret) 3604 return ret; 3605 ret = nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops, 3606 ns->ctrl->ops->module); 3607 if (ret) 3608 kfree_const(ns->cdev_device.kobj.name); 3609 return ret; 3610 } 3611 3612 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl, 3613 unsigned nsid, struct nvme_ns_ids *ids) 3614 { 3615 struct nvme_ns_head *head; 3616 size_t size = sizeof(*head); 3617 int ret = -ENOMEM; 3618 3619 #ifdef CONFIG_NVME_MULTIPATH 3620 size += num_possible_nodes() * sizeof(struct nvme_ns *); 3621 #endif 3622 3623 head = kzalloc(size, GFP_KERNEL); 3624 if (!head) 3625 goto out; 3626 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL); 3627 if (ret < 0) 3628 goto out_free_head; 3629 head->instance = ret; 3630 INIT_LIST_HEAD(&head->list); 3631 ret = init_srcu_struct(&head->srcu); 3632 if (ret) 3633 goto out_ida_remove; 3634 head->subsys = ctrl->subsys; 3635 head->ns_id = nsid; 3636 head->ids = *ids; 3637 kref_init(&head->ref); 3638 3639 ret = __nvme_check_ids(ctrl->subsys, head); 3640 if (ret) { 3641 dev_err(ctrl->device, 3642 "duplicate IDs for nsid %d\n", nsid); 3643 goto out_cleanup_srcu; 3644 } 3645 3646 if (head->ids.csi) { 3647 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects); 3648 if (ret) 3649 goto out_cleanup_srcu; 3650 } else 3651 head->effects = ctrl->effects; 3652 3653 ret = nvme_mpath_alloc_disk(ctrl, head); 3654 if (ret) 3655 goto out_cleanup_srcu; 3656 3657 list_add_tail(&head->entry, &ctrl->subsys->nsheads); 3658 3659 kref_get(&ctrl->subsys->ref); 3660 3661 return head; 3662 out_cleanup_srcu: 3663 cleanup_srcu_struct(&head->srcu); 3664 out_ida_remove: 3665 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance); 3666 out_free_head: 3667 kfree(head); 3668 out: 3669 if (ret > 0) 3670 ret = blk_status_to_errno(nvme_error_status(ret)); 3671 return ERR_PTR(ret); 3672 } 3673 3674 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid, 3675 struct nvme_ns_ids *ids, bool is_shared) 3676 { 3677 struct nvme_ctrl *ctrl = ns->ctrl; 3678 struct nvme_ns_head *head = NULL; 3679 int ret = 0; 3680 3681 mutex_lock(&ctrl->subsys->lock); 3682 head = nvme_find_ns_head(ctrl->subsys, nsid); 3683 if (!head) { 3684 head = nvme_alloc_ns_head(ctrl, nsid, ids); 3685 if (IS_ERR(head)) { 3686 ret = PTR_ERR(head); 3687 goto out_unlock; 3688 } 3689 head->shared = is_shared; 3690 } else { 3691 ret = -EINVAL; 3692 if (!is_shared || !head->shared) { 3693 dev_err(ctrl->device, 3694 "Duplicate unshared namespace %d\n", nsid); 3695 goto out_put_ns_head; 3696 } 3697 if (!nvme_ns_ids_equal(&head->ids, ids)) { 3698 dev_err(ctrl->device, 3699 "IDs don't match for shared namespace %d\n", 3700 nsid); 3701 goto out_put_ns_head; 3702 } 3703 } 3704 3705 list_add_tail_rcu(&ns->siblings, &head->list); 3706 ns->head = head; 3707 mutex_unlock(&ctrl->subsys->lock); 3708 return 0; 3709 3710 out_put_ns_head: 3711 nvme_put_ns_head(head); 3712 out_unlock: 3713 mutex_unlock(&ctrl->subsys->lock); 3714 return ret; 3715 } 3716 3717 static int ns_cmp(void *priv, const struct list_head *a, 3718 const struct list_head *b) 3719 { 3720 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list); 3721 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list); 3722 3723 return nsa->head->ns_id - nsb->head->ns_id; 3724 } 3725 3726 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid) 3727 { 3728 struct nvme_ns *ns, *ret = NULL; 3729 3730 down_read(&ctrl->namespaces_rwsem); 3731 list_for_each_entry(ns, &ctrl->namespaces, list) { 3732 if (ns->head->ns_id == nsid) { 3733 if (!nvme_get_ns(ns)) 3734 continue; 3735 ret = ns; 3736 break; 3737 } 3738 if (ns->head->ns_id > nsid) 3739 break; 3740 } 3741 up_read(&ctrl->namespaces_rwsem); 3742 return ret; 3743 } 3744 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU); 3745 3746 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid, 3747 struct nvme_ns_ids *ids) 3748 { 3749 struct nvme_ns *ns; 3750 struct gendisk *disk; 3751 struct nvme_id_ns *id; 3752 int node = ctrl->numa_node; 3753 3754 if (nvme_identify_ns(ctrl, nsid, ids, &id)) 3755 return; 3756 3757 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node); 3758 if (!ns) 3759 goto out_free_id; 3760 3761 disk = blk_mq_alloc_disk(ctrl->tagset, ns); 3762 if (IS_ERR(disk)) 3763 goto out_free_ns; 3764 disk->fops = &nvme_bdev_ops; 3765 disk->private_data = ns; 3766 3767 ns->disk = disk; 3768 ns->queue = disk->queue; 3769 3770 if (ctrl->opts && ctrl->opts->data_digest) 3771 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, ns->queue); 3772 3773 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue); 3774 if (ctrl->ops->flags & NVME_F_PCI_P2PDMA) 3775 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue); 3776 3777 ns->ctrl = ctrl; 3778 kref_init(&ns->kref); 3779 3780 if (nvme_init_ns_head(ns, nsid, ids, id->nmic & NVME_NS_NMIC_SHARED)) 3781 goto out_cleanup_disk; 3782 3783 /* 3784 * Without the multipath code enabled, multiple controller per 3785 * subsystems are visible as devices and thus we cannot use the 3786 * subsystem instance. 3787 */ 3788 if (!nvme_mpath_set_disk_name(ns, disk->disk_name, &disk->flags)) 3789 sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance, 3790 ns->head->instance); 3791 3792 if (nvme_update_ns_info(ns, id)) 3793 goto out_unlink_ns; 3794 3795 down_write(&ctrl->namespaces_rwsem); 3796 list_add_tail(&ns->list, &ctrl->namespaces); 3797 up_write(&ctrl->namespaces_rwsem); 3798 3799 nvme_get_ctrl(ctrl); 3800 3801 if (device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups)) 3802 goto out_cleanup_ns_from_list; 3803 3804 if (!nvme_ns_head_multipath(ns->head)) 3805 nvme_add_ns_cdev(ns); 3806 3807 nvme_mpath_add_disk(ns, id); 3808 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name); 3809 kfree(id); 3810 3811 return; 3812 3813 out_cleanup_ns_from_list: 3814 nvme_put_ctrl(ctrl); 3815 down_write(&ctrl->namespaces_rwsem); 3816 list_del_init(&ns->list); 3817 up_write(&ctrl->namespaces_rwsem); 3818 out_unlink_ns: 3819 mutex_lock(&ctrl->subsys->lock); 3820 list_del_rcu(&ns->siblings); 3821 if (list_empty(&ns->head->list)) 3822 list_del_init(&ns->head->entry); 3823 mutex_unlock(&ctrl->subsys->lock); 3824 nvme_put_ns_head(ns->head); 3825 out_cleanup_disk: 3826 blk_cleanup_disk(disk); 3827 out_free_ns: 3828 kfree(ns); 3829 out_free_id: 3830 kfree(id); 3831 } 3832 3833 static void nvme_ns_remove(struct nvme_ns *ns) 3834 { 3835 bool last_path = false; 3836 3837 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags)) 3838 return; 3839 3840 clear_bit(NVME_NS_READY, &ns->flags); 3841 set_capacity(ns->disk, 0); 3842 nvme_fault_inject_fini(&ns->fault_inject); 3843 3844 mutex_lock(&ns->ctrl->subsys->lock); 3845 list_del_rcu(&ns->siblings); 3846 mutex_unlock(&ns->ctrl->subsys->lock); 3847 3848 /* guarantee not available in head->list */ 3849 synchronize_rcu(); 3850 3851 /* wait for concurrent submissions */ 3852 if (nvme_mpath_clear_current_path(ns)) 3853 synchronize_srcu(&ns->head->srcu); 3854 3855 if (!nvme_ns_head_multipath(ns->head)) 3856 nvme_cdev_del(&ns->cdev, &ns->cdev_device); 3857 del_gendisk(ns->disk); 3858 blk_cleanup_queue(ns->queue); 3859 if (blk_get_integrity(ns->disk)) 3860 blk_integrity_unregister(ns->disk); 3861 3862 down_write(&ns->ctrl->namespaces_rwsem); 3863 list_del_init(&ns->list); 3864 up_write(&ns->ctrl->namespaces_rwsem); 3865 3866 /* Synchronize with nvme_init_ns_head() */ 3867 mutex_lock(&ns->head->subsys->lock); 3868 if (list_empty(&ns->head->list)) { 3869 list_del_init(&ns->head->entry); 3870 last_path = true; 3871 } 3872 mutex_unlock(&ns->head->subsys->lock); 3873 if (last_path) 3874 nvme_mpath_shutdown_disk(ns->head); 3875 nvme_put_ns(ns); 3876 } 3877 3878 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid) 3879 { 3880 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid); 3881 3882 if (ns) { 3883 nvme_ns_remove(ns); 3884 nvme_put_ns(ns); 3885 } 3886 } 3887 3888 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_ids *ids) 3889 { 3890 struct nvme_id_ns *id; 3891 int ret = NVME_SC_INVALID_NS | NVME_SC_DNR; 3892 3893 if (test_bit(NVME_NS_DEAD, &ns->flags)) 3894 goto out; 3895 3896 ret = nvme_identify_ns(ns->ctrl, ns->head->ns_id, ids, &id); 3897 if (ret) 3898 goto out; 3899 3900 ret = NVME_SC_INVALID_NS | NVME_SC_DNR; 3901 if (!nvme_ns_ids_equal(&ns->head->ids, ids)) { 3902 dev_err(ns->ctrl->device, 3903 "identifiers changed for nsid %d\n", ns->head->ns_id); 3904 goto out_free_id; 3905 } 3906 3907 ret = nvme_update_ns_info(ns, id); 3908 3909 out_free_id: 3910 kfree(id); 3911 out: 3912 /* 3913 * Only remove the namespace if we got a fatal error back from the 3914 * device, otherwise ignore the error and just move on. 3915 * 3916 * TODO: we should probably schedule a delayed retry here. 3917 */ 3918 if (ret > 0 && (ret & NVME_SC_DNR)) 3919 nvme_ns_remove(ns); 3920 } 3921 3922 static void nvme_validate_or_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid) 3923 { 3924 struct nvme_ns_ids ids = { }; 3925 struct nvme_ns *ns; 3926 3927 if (nvme_identify_ns_descs(ctrl, nsid, &ids)) 3928 return; 3929 3930 ns = nvme_find_get_ns(ctrl, nsid); 3931 if (ns) { 3932 nvme_validate_ns(ns, &ids); 3933 nvme_put_ns(ns); 3934 return; 3935 } 3936 3937 switch (ids.csi) { 3938 case NVME_CSI_NVM: 3939 nvme_alloc_ns(ctrl, nsid, &ids); 3940 break; 3941 case NVME_CSI_ZNS: 3942 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) { 3943 dev_warn(ctrl->device, 3944 "nsid %u not supported without CONFIG_BLK_DEV_ZONED\n", 3945 nsid); 3946 break; 3947 } 3948 if (!nvme_multi_css(ctrl)) { 3949 dev_warn(ctrl->device, 3950 "command set not reported for nsid: %d\n", 3951 nsid); 3952 break; 3953 } 3954 nvme_alloc_ns(ctrl, nsid, &ids); 3955 break; 3956 default: 3957 dev_warn(ctrl->device, "unknown csi %u for nsid %u\n", 3958 ids.csi, nsid); 3959 break; 3960 } 3961 } 3962 3963 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl, 3964 unsigned nsid) 3965 { 3966 struct nvme_ns *ns, *next; 3967 LIST_HEAD(rm_list); 3968 3969 down_write(&ctrl->namespaces_rwsem); 3970 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) { 3971 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags)) 3972 list_move_tail(&ns->list, &rm_list); 3973 } 3974 up_write(&ctrl->namespaces_rwsem); 3975 3976 list_for_each_entry_safe(ns, next, &rm_list, list) 3977 nvme_ns_remove(ns); 3978 3979 } 3980 3981 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl) 3982 { 3983 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32); 3984 __le32 *ns_list; 3985 u32 prev = 0; 3986 int ret = 0, i; 3987 3988 if (nvme_ctrl_limited_cns(ctrl)) 3989 return -EOPNOTSUPP; 3990 3991 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 3992 if (!ns_list) 3993 return -ENOMEM; 3994 3995 for (;;) { 3996 struct nvme_command cmd = { 3997 .identify.opcode = nvme_admin_identify, 3998 .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST, 3999 .identify.nsid = cpu_to_le32(prev), 4000 }; 4001 4002 ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list, 4003 NVME_IDENTIFY_DATA_SIZE); 4004 if (ret) { 4005 dev_warn(ctrl->device, 4006 "Identify NS List failed (status=0x%x)\n", ret); 4007 goto free; 4008 } 4009 4010 for (i = 0; i < nr_entries; i++) { 4011 u32 nsid = le32_to_cpu(ns_list[i]); 4012 4013 if (!nsid) /* end of the list? */ 4014 goto out; 4015 nvme_validate_or_alloc_ns(ctrl, nsid); 4016 while (++prev < nsid) 4017 nvme_ns_remove_by_nsid(ctrl, prev); 4018 } 4019 } 4020 out: 4021 nvme_remove_invalid_namespaces(ctrl, prev); 4022 free: 4023 kfree(ns_list); 4024 return ret; 4025 } 4026 4027 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl) 4028 { 4029 struct nvme_id_ctrl *id; 4030 u32 nn, i; 4031 4032 if (nvme_identify_ctrl(ctrl, &id)) 4033 return; 4034 nn = le32_to_cpu(id->nn); 4035 kfree(id); 4036 4037 for (i = 1; i <= nn; i++) 4038 nvme_validate_or_alloc_ns(ctrl, i); 4039 4040 nvme_remove_invalid_namespaces(ctrl, nn); 4041 } 4042 4043 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl) 4044 { 4045 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32); 4046 __le32 *log; 4047 int error; 4048 4049 log = kzalloc(log_size, GFP_KERNEL); 4050 if (!log) 4051 return; 4052 4053 /* 4054 * We need to read the log to clear the AEN, but we don't want to rely 4055 * on it for the changed namespace information as userspace could have 4056 * raced with us in reading the log page, which could cause us to miss 4057 * updates. 4058 */ 4059 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0, 4060 NVME_CSI_NVM, log, log_size, 0); 4061 if (error) 4062 dev_warn(ctrl->device, 4063 "reading changed ns log failed: %d\n", error); 4064 4065 kfree(log); 4066 } 4067 4068 static void nvme_scan_work(struct work_struct *work) 4069 { 4070 struct nvme_ctrl *ctrl = 4071 container_of(work, struct nvme_ctrl, scan_work); 4072 4073 /* No tagset on a live ctrl means IO queues could not created */ 4074 if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset) 4075 return; 4076 4077 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) { 4078 dev_info(ctrl->device, "rescanning namespaces.\n"); 4079 nvme_clear_changed_ns_log(ctrl); 4080 } 4081 4082 mutex_lock(&ctrl->scan_lock); 4083 if (nvme_scan_ns_list(ctrl) != 0) 4084 nvme_scan_ns_sequential(ctrl); 4085 mutex_unlock(&ctrl->scan_lock); 4086 4087 down_write(&ctrl->namespaces_rwsem); 4088 list_sort(NULL, &ctrl->namespaces, ns_cmp); 4089 up_write(&ctrl->namespaces_rwsem); 4090 } 4091 4092 /* 4093 * This function iterates the namespace list unlocked to allow recovery from 4094 * controller failure. It is up to the caller to ensure the namespace list is 4095 * not modified by scan work while this function is executing. 4096 */ 4097 void nvme_remove_namespaces(struct nvme_ctrl *ctrl) 4098 { 4099 struct nvme_ns *ns, *next; 4100 LIST_HEAD(ns_list); 4101 4102 /* 4103 * make sure to requeue I/O to all namespaces as these 4104 * might result from the scan itself and must complete 4105 * for the scan_work to make progress 4106 */ 4107 nvme_mpath_clear_ctrl_paths(ctrl); 4108 4109 /* prevent racing with ns scanning */ 4110 flush_work(&ctrl->scan_work); 4111 4112 /* 4113 * The dead states indicates the controller was not gracefully 4114 * disconnected. In that case, we won't be able to flush any data while 4115 * removing the namespaces' disks; fail all the queues now to avoid 4116 * potentially having to clean up the failed sync later. 4117 */ 4118 if (ctrl->state == NVME_CTRL_DEAD) 4119 nvme_kill_queues(ctrl); 4120 4121 /* this is a no-op when called from the controller reset handler */ 4122 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO); 4123 4124 down_write(&ctrl->namespaces_rwsem); 4125 list_splice_init(&ctrl->namespaces, &ns_list); 4126 up_write(&ctrl->namespaces_rwsem); 4127 4128 list_for_each_entry_safe(ns, next, &ns_list, list) 4129 nvme_ns_remove(ns); 4130 } 4131 EXPORT_SYMBOL_GPL(nvme_remove_namespaces); 4132 4133 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env) 4134 { 4135 struct nvme_ctrl *ctrl = 4136 container_of(dev, struct nvme_ctrl, ctrl_device); 4137 struct nvmf_ctrl_options *opts = ctrl->opts; 4138 int ret; 4139 4140 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name); 4141 if (ret) 4142 return ret; 4143 4144 if (opts) { 4145 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr); 4146 if (ret) 4147 return ret; 4148 4149 ret = add_uevent_var(env, "NVME_TRSVCID=%s", 4150 opts->trsvcid ?: "none"); 4151 if (ret) 4152 return ret; 4153 4154 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s", 4155 opts->host_traddr ?: "none"); 4156 if (ret) 4157 return ret; 4158 4159 ret = add_uevent_var(env, "NVME_HOST_IFACE=%s", 4160 opts->host_iface ?: "none"); 4161 } 4162 return ret; 4163 } 4164 4165 static void nvme_aen_uevent(struct nvme_ctrl *ctrl) 4166 { 4167 char *envp[2] = { NULL, NULL }; 4168 u32 aen_result = ctrl->aen_result; 4169 4170 ctrl->aen_result = 0; 4171 if (!aen_result) 4172 return; 4173 4174 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result); 4175 if (!envp[0]) 4176 return; 4177 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp); 4178 kfree(envp[0]); 4179 } 4180 4181 static void nvme_async_event_work(struct work_struct *work) 4182 { 4183 struct nvme_ctrl *ctrl = 4184 container_of(work, struct nvme_ctrl, async_event_work); 4185 4186 nvme_aen_uevent(ctrl); 4187 ctrl->ops->submit_async_event(ctrl); 4188 } 4189 4190 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl) 4191 { 4192 4193 u32 csts; 4194 4195 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) 4196 return false; 4197 4198 if (csts == ~0) 4199 return false; 4200 4201 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP)); 4202 } 4203 4204 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl) 4205 { 4206 struct nvme_fw_slot_info_log *log; 4207 4208 log = kmalloc(sizeof(*log), GFP_KERNEL); 4209 if (!log) 4210 return; 4211 4212 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM, 4213 log, sizeof(*log), 0)) 4214 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n"); 4215 kfree(log); 4216 } 4217 4218 static void nvme_fw_act_work(struct work_struct *work) 4219 { 4220 struct nvme_ctrl *ctrl = container_of(work, 4221 struct nvme_ctrl, fw_act_work); 4222 unsigned long fw_act_timeout; 4223 4224 if (ctrl->mtfa) 4225 fw_act_timeout = jiffies + 4226 msecs_to_jiffies(ctrl->mtfa * 100); 4227 else 4228 fw_act_timeout = jiffies + 4229 msecs_to_jiffies(admin_timeout * 1000); 4230 4231 nvme_stop_queues(ctrl); 4232 while (nvme_ctrl_pp_status(ctrl)) { 4233 if (time_after(jiffies, fw_act_timeout)) { 4234 dev_warn(ctrl->device, 4235 "Fw activation timeout, reset controller\n"); 4236 nvme_try_sched_reset(ctrl); 4237 return; 4238 } 4239 msleep(100); 4240 } 4241 4242 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE)) 4243 return; 4244 4245 nvme_start_queues(ctrl); 4246 /* read FW slot information to clear the AER */ 4247 nvme_get_fw_slot_info(ctrl); 4248 } 4249 4250 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result) 4251 { 4252 u32 aer_notice_type = (result & 0xff00) >> 8; 4253 4254 trace_nvme_async_event(ctrl, aer_notice_type); 4255 4256 switch (aer_notice_type) { 4257 case NVME_AER_NOTICE_NS_CHANGED: 4258 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events); 4259 nvme_queue_scan(ctrl); 4260 break; 4261 case NVME_AER_NOTICE_FW_ACT_STARTING: 4262 /* 4263 * We are (ab)using the RESETTING state to prevent subsequent 4264 * recovery actions from interfering with the controller's 4265 * firmware activation. 4266 */ 4267 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) 4268 queue_work(nvme_wq, &ctrl->fw_act_work); 4269 break; 4270 #ifdef CONFIG_NVME_MULTIPATH 4271 case NVME_AER_NOTICE_ANA: 4272 if (!ctrl->ana_log_buf) 4273 break; 4274 queue_work(nvme_wq, &ctrl->ana_work); 4275 break; 4276 #endif 4277 case NVME_AER_NOTICE_DISC_CHANGED: 4278 ctrl->aen_result = result; 4279 break; 4280 default: 4281 dev_warn(ctrl->device, "async event result %08x\n", result); 4282 } 4283 } 4284 4285 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status, 4286 volatile union nvme_result *res) 4287 { 4288 u32 result = le32_to_cpu(res->u32); 4289 u32 aer_type = result & 0x07; 4290 4291 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS) 4292 return; 4293 4294 switch (aer_type) { 4295 case NVME_AER_NOTICE: 4296 nvme_handle_aen_notice(ctrl, result); 4297 break; 4298 case NVME_AER_ERROR: 4299 case NVME_AER_SMART: 4300 case NVME_AER_CSS: 4301 case NVME_AER_VS: 4302 trace_nvme_async_event(ctrl, aer_type); 4303 ctrl->aen_result = result; 4304 break; 4305 default: 4306 break; 4307 } 4308 queue_work(nvme_wq, &ctrl->async_event_work); 4309 } 4310 EXPORT_SYMBOL_GPL(nvme_complete_async_event); 4311 4312 void nvme_stop_ctrl(struct nvme_ctrl *ctrl) 4313 { 4314 nvme_mpath_stop(ctrl); 4315 nvme_stop_keep_alive(ctrl); 4316 nvme_stop_failfast_work(ctrl); 4317 flush_work(&ctrl->async_event_work); 4318 cancel_work_sync(&ctrl->fw_act_work); 4319 } 4320 EXPORT_SYMBOL_GPL(nvme_stop_ctrl); 4321 4322 void nvme_start_ctrl(struct nvme_ctrl *ctrl) 4323 { 4324 nvme_start_keep_alive(ctrl); 4325 4326 nvme_enable_aen(ctrl); 4327 4328 if (ctrl->queue_count > 1) { 4329 nvme_queue_scan(ctrl); 4330 nvme_start_queues(ctrl); 4331 } 4332 } 4333 EXPORT_SYMBOL_GPL(nvme_start_ctrl); 4334 4335 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl) 4336 { 4337 nvme_hwmon_exit(ctrl); 4338 nvme_fault_inject_fini(&ctrl->fault_inject); 4339 dev_pm_qos_hide_latency_tolerance(ctrl->device); 4340 cdev_device_del(&ctrl->cdev, ctrl->device); 4341 nvme_put_ctrl(ctrl); 4342 } 4343 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl); 4344 4345 static void nvme_free_cels(struct nvme_ctrl *ctrl) 4346 { 4347 struct nvme_effects_log *cel; 4348 unsigned long i; 4349 4350 xa_for_each(&ctrl->cels, i, cel) { 4351 xa_erase(&ctrl->cels, i); 4352 kfree(cel); 4353 } 4354 4355 xa_destroy(&ctrl->cels); 4356 } 4357 4358 static void nvme_free_ctrl(struct device *dev) 4359 { 4360 struct nvme_ctrl *ctrl = 4361 container_of(dev, struct nvme_ctrl, ctrl_device); 4362 struct nvme_subsystem *subsys = ctrl->subsys; 4363 4364 if (!subsys || ctrl->instance != subsys->instance) 4365 ida_simple_remove(&nvme_instance_ida, ctrl->instance); 4366 4367 nvme_free_cels(ctrl); 4368 nvme_mpath_uninit(ctrl); 4369 __free_page(ctrl->discard_page); 4370 4371 if (subsys) { 4372 mutex_lock(&nvme_subsystems_lock); 4373 list_del(&ctrl->subsys_entry); 4374 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device)); 4375 mutex_unlock(&nvme_subsystems_lock); 4376 } 4377 4378 ctrl->ops->free_ctrl(ctrl); 4379 4380 if (subsys) 4381 nvme_put_subsystem(subsys); 4382 } 4383 4384 /* 4385 * Initialize a NVMe controller structures. This needs to be called during 4386 * earliest initialization so that we have the initialized structured around 4387 * during probing. 4388 */ 4389 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev, 4390 const struct nvme_ctrl_ops *ops, unsigned long quirks) 4391 { 4392 int ret; 4393 4394 ctrl->state = NVME_CTRL_NEW; 4395 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 4396 spin_lock_init(&ctrl->lock); 4397 mutex_init(&ctrl->scan_lock); 4398 INIT_LIST_HEAD(&ctrl->namespaces); 4399 xa_init(&ctrl->cels); 4400 init_rwsem(&ctrl->namespaces_rwsem); 4401 ctrl->dev = dev; 4402 ctrl->ops = ops; 4403 ctrl->quirks = quirks; 4404 ctrl->numa_node = NUMA_NO_NODE; 4405 INIT_WORK(&ctrl->scan_work, nvme_scan_work); 4406 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work); 4407 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work); 4408 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work); 4409 init_waitqueue_head(&ctrl->state_wq); 4410 4411 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work); 4412 INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work); 4413 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd)); 4414 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive; 4415 4416 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) > 4417 PAGE_SIZE); 4418 ctrl->discard_page = alloc_page(GFP_KERNEL); 4419 if (!ctrl->discard_page) { 4420 ret = -ENOMEM; 4421 goto out; 4422 } 4423 4424 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL); 4425 if (ret < 0) 4426 goto out; 4427 ctrl->instance = ret; 4428 4429 device_initialize(&ctrl->ctrl_device); 4430 ctrl->device = &ctrl->ctrl_device; 4431 ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt), 4432 ctrl->instance); 4433 ctrl->device->class = nvme_class; 4434 ctrl->device->parent = ctrl->dev; 4435 ctrl->device->groups = nvme_dev_attr_groups; 4436 ctrl->device->release = nvme_free_ctrl; 4437 dev_set_drvdata(ctrl->device, ctrl); 4438 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance); 4439 if (ret) 4440 goto out_release_instance; 4441 4442 nvme_get_ctrl(ctrl); 4443 cdev_init(&ctrl->cdev, &nvme_dev_fops); 4444 ctrl->cdev.owner = ops->module; 4445 ret = cdev_device_add(&ctrl->cdev, ctrl->device); 4446 if (ret) 4447 goto out_free_name; 4448 4449 /* 4450 * Initialize latency tolerance controls. The sysfs files won't 4451 * be visible to userspace unless the device actually supports APST. 4452 */ 4453 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance; 4454 dev_pm_qos_update_user_latency_tolerance(ctrl->device, 4455 min(default_ps_max_latency_us, (unsigned long)S32_MAX)); 4456 4457 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device)); 4458 nvme_mpath_init_ctrl(ctrl); 4459 4460 return 0; 4461 out_free_name: 4462 nvme_put_ctrl(ctrl); 4463 kfree_const(ctrl->device->kobj.name); 4464 out_release_instance: 4465 ida_simple_remove(&nvme_instance_ida, ctrl->instance); 4466 out: 4467 if (ctrl->discard_page) 4468 __free_page(ctrl->discard_page); 4469 return ret; 4470 } 4471 EXPORT_SYMBOL_GPL(nvme_init_ctrl); 4472 4473 /** 4474 * nvme_kill_queues(): Ends all namespace queues 4475 * @ctrl: the dead controller that needs to end 4476 * 4477 * Call this function when the driver determines it is unable to get the 4478 * controller in a state capable of servicing IO. 4479 */ 4480 void nvme_kill_queues(struct nvme_ctrl *ctrl) 4481 { 4482 struct nvme_ns *ns; 4483 4484 down_read(&ctrl->namespaces_rwsem); 4485 4486 /* Forcibly unquiesce queues to avoid blocking dispatch */ 4487 if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q)) 4488 blk_mq_unquiesce_queue(ctrl->admin_q); 4489 4490 list_for_each_entry(ns, &ctrl->namespaces, list) 4491 nvme_set_queue_dying(ns); 4492 4493 up_read(&ctrl->namespaces_rwsem); 4494 } 4495 EXPORT_SYMBOL_GPL(nvme_kill_queues); 4496 4497 void nvme_unfreeze(struct nvme_ctrl *ctrl) 4498 { 4499 struct nvme_ns *ns; 4500 4501 down_read(&ctrl->namespaces_rwsem); 4502 list_for_each_entry(ns, &ctrl->namespaces, list) 4503 blk_mq_unfreeze_queue(ns->queue); 4504 up_read(&ctrl->namespaces_rwsem); 4505 } 4506 EXPORT_SYMBOL_GPL(nvme_unfreeze); 4507 4508 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout) 4509 { 4510 struct nvme_ns *ns; 4511 4512 down_read(&ctrl->namespaces_rwsem); 4513 list_for_each_entry(ns, &ctrl->namespaces, list) { 4514 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout); 4515 if (timeout <= 0) 4516 break; 4517 } 4518 up_read(&ctrl->namespaces_rwsem); 4519 return timeout; 4520 } 4521 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout); 4522 4523 void nvme_wait_freeze(struct nvme_ctrl *ctrl) 4524 { 4525 struct nvme_ns *ns; 4526 4527 down_read(&ctrl->namespaces_rwsem); 4528 list_for_each_entry(ns, &ctrl->namespaces, list) 4529 blk_mq_freeze_queue_wait(ns->queue); 4530 up_read(&ctrl->namespaces_rwsem); 4531 } 4532 EXPORT_SYMBOL_GPL(nvme_wait_freeze); 4533 4534 void nvme_start_freeze(struct nvme_ctrl *ctrl) 4535 { 4536 struct nvme_ns *ns; 4537 4538 down_read(&ctrl->namespaces_rwsem); 4539 list_for_each_entry(ns, &ctrl->namespaces, list) 4540 blk_freeze_queue_start(ns->queue); 4541 up_read(&ctrl->namespaces_rwsem); 4542 } 4543 EXPORT_SYMBOL_GPL(nvme_start_freeze); 4544 4545 void nvme_stop_queues(struct nvme_ctrl *ctrl) 4546 { 4547 struct nvme_ns *ns; 4548 4549 down_read(&ctrl->namespaces_rwsem); 4550 list_for_each_entry(ns, &ctrl->namespaces, list) 4551 blk_mq_quiesce_queue(ns->queue); 4552 up_read(&ctrl->namespaces_rwsem); 4553 } 4554 EXPORT_SYMBOL_GPL(nvme_stop_queues); 4555 4556 void nvme_start_queues(struct nvme_ctrl *ctrl) 4557 { 4558 struct nvme_ns *ns; 4559 4560 down_read(&ctrl->namespaces_rwsem); 4561 list_for_each_entry(ns, &ctrl->namespaces, list) 4562 blk_mq_unquiesce_queue(ns->queue); 4563 up_read(&ctrl->namespaces_rwsem); 4564 } 4565 EXPORT_SYMBOL_GPL(nvme_start_queues); 4566 4567 void nvme_sync_io_queues(struct nvme_ctrl *ctrl) 4568 { 4569 struct nvme_ns *ns; 4570 4571 down_read(&ctrl->namespaces_rwsem); 4572 list_for_each_entry(ns, &ctrl->namespaces, list) 4573 blk_sync_queue(ns->queue); 4574 up_read(&ctrl->namespaces_rwsem); 4575 } 4576 EXPORT_SYMBOL_GPL(nvme_sync_io_queues); 4577 4578 void nvme_sync_queues(struct nvme_ctrl *ctrl) 4579 { 4580 nvme_sync_io_queues(ctrl); 4581 if (ctrl->admin_q) 4582 blk_sync_queue(ctrl->admin_q); 4583 } 4584 EXPORT_SYMBOL_GPL(nvme_sync_queues); 4585 4586 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file) 4587 { 4588 if (file->f_op != &nvme_dev_fops) 4589 return NULL; 4590 return file->private_data; 4591 } 4592 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU); 4593 4594 /* 4595 * Check we didn't inadvertently grow the command structure sizes: 4596 */ 4597 static inline void _nvme_check_size(void) 4598 { 4599 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64); 4600 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64); 4601 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64); 4602 BUILD_BUG_ON(sizeof(struct nvme_features) != 64); 4603 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64); 4604 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64); 4605 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64); 4606 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64); 4607 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64); 4608 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64); 4609 BUILD_BUG_ON(sizeof(struct nvme_command) != 64); 4610 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE); 4611 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE); 4612 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE); 4613 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE); 4614 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE); 4615 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64); 4616 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512); 4617 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64); 4618 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64); 4619 } 4620 4621 4622 static int __init nvme_core_init(void) 4623 { 4624 int result = -ENOMEM; 4625 4626 _nvme_check_size(); 4627 4628 nvme_wq = alloc_workqueue("nvme-wq", 4629 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 4630 if (!nvme_wq) 4631 goto out; 4632 4633 nvme_reset_wq = alloc_workqueue("nvme-reset-wq", 4634 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 4635 if (!nvme_reset_wq) 4636 goto destroy_wq; 4637 4638 nvme_delete_wq = alloc_workqueue("nvme-delete-wq", 4639 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 4640 if (!nvme_delete_wq) 4641 goto destroy_reset_wq; 4642 4643 result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0, 4644 NVME_MINORS, "nvme"); 4645 if (result < 0) 4646 goto destroy_delete_wq; 4647 4648 nvme_class = class_create(THIS_MODULE, "nvme"); 4649 if (IS_ERR(nvme_class)) { 4650 result = PTR_ERR(nvme_class); 4651 goto unregister_chrdev; 4652 } 4653 nvme_class->dev_uevent = nvme_class_uevent; 4654 4655 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem"); 4656 if (IS_ERR(nvme_subsys_class)) { 4657 result = PTR_ERR(nvme_subsys_class); 4658 goto destroy_class; 4659 } 4660 4661 result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS, 4662 "nvme-generic"); 4663 if (result < 0) 4664 goto destroy_subsys_class; 4665 4666 nvme_ns_chr_class = class_create(THIS_MODULE, "nvme-generic"); 4667 if (IS_ERR(nvme_ns_chr_class)) { 4668 result = PTR_ERR(nvme_ns_chr_class); 4669 goto unregister_generic_ns; 4670 } 4671 4672 return 0; 4673 4674 unregister_generic_ns: 4675 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS); 4676 destroy_subsys_class: 4677 class_destroy(nvme_subsys_class); 4678 destroy_class: 4679 class_destroy(nvme_class); 4680 unregister_chrdev: 4681 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS); 4682 destroy_delete_wq: 4683 destroy_workqueue(nvme_delete_wq); 4684 destroy_reset_wq: 4685 destroy_workqueue(nvme_reset_wq); 4686 destroy_wq: 4687 destroy_workqueue(nvme_wq); 4688 out: 4689 return result; 4690 } 4691 4692 static void __exit nvme_core_exit(void) 4693 { 4694 class_destroy(nvme_ns_chr_class); 4695 class_destroy(nvme_subsys_class); 4696 class_destroy(nvme_class); 4697 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS); 4698 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS); 4699 destroy_workqueue(nvme_delete_wq); 4700 destroy_workqueue(nvme_reset_wq); 4701 destroy_workqueue(nvme_wq); 4702 ida_destroy(&nvme_ns_chr_minor_ida); 4703 ida_destroy(&nvme_instance_ida); 4704 } 4705 4706 MODULE_LICENSE("GPL"); 4707 MODULE_VERSION("1.0"); 4708 module_init(nvme_core_init); 4709 module_exit(nvme_core_exit); 4710