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/async.h> 8 #include <linux/blkdev.h> 9 #include <linux/blk-mq.h> 10 #include <linux/blk-integrity.h> 11 #include <linux/compat.h> 12 #include <linux/delay.h> 13 #include <linux/errno.h> 14 #include <linux/hdreg.h> 15 #include <linux/kernel.h> 16 #include <linux/module.h> 17 #include <linux/backing-dev.h> 18 #include <linux/slab.h> 19 #include <linux/types.h> 20 #include <linux/pr.h> 21 #include <linux/ptrace.h> 22 #include <linux/nvme_ioctl.h> 23 #include <linux/pm_qos.h> 24 #include <linux/ratelimit.h> 25 #include <linux/unaligned.h> 26 27 #include "nvme.h" 28 #include "fabrics.h" 29 #include <linux/nvme-auth.h> 30 31 #define CREATE_TRACE_POINTS 32 #include "trace.h" 33 34 #define NVME_MINORS (1U << MINORBITS) 35 36 /* 37 * Write hints (bio->bi_write_stream) are u8, so FDP placement handles beyond 38 * U8_MAX can never be selected. Cap the handle count to bound both the RUH 39 * status buffer and the per-head plids array. 40 */ 41 #define NVME_MAX_PLIDS U8_MAX 42 43 struct nvme_ns_info { 44 struct nvme_ns_ids ids; 45 u32 nsid; 46 __le32 anagrpid; 47 u8 pi_offset; 48 u16 endgid; 49 u64 runs; 50 bool is_shared; 51 bool is_readonly; 52 bool is_ready; 53 bool is_removed; 54 bool is_rotational; 55 bool no_vwc; 56 }; 57 58 unsigned int admin_timeout = 60; 59 module_param(admin_timeout, uint, 0644); 60 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands"); 61 EXPORT_SYMBOL_GPL(admin_timeout); 62 63 unsigned int nvme_io_timeout = 30; 64 module_param_named(io_timeout, nvme_io_timeout, uint, 0644); 65 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O"); 66 EXPORT_SYMBOL_GPL(nvme_io_timeout); 67 68 static unsigned char shutdown_timeout = 5; 69 module_param(shutdown_timeout, byte, 0644); 70 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown"); 71 72 static u8 nvme_max_retries = 5; 73 module_param_named(max_retries, nvme_max_retries, byte, 0644); 74 MODULE_PARM_DESC(max_retries, "max number of retries a command may have"); 75 76 static unsigned long default_ps_max_latency_us = 100000; 77 module_param(default_ps_max_latency_us, ulong, 0644); 78 MODULE_PARM_DESC(default_ps_max_latency_us, 79 "max power saving latency for new devices; use PM QOS to change per device"); 80 81 static bool force_apst; 82 module_param(force_apst, bool, 0644); 83 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off"); 84 85 static unsigned long apst_primary_timeout_ms = 100; 86 module_param(apst_primary_timeout_ms, ulong, 0644); 87 MODULE_PARM_DESC(apst_primary_timeout_ms, 88 "primary APST timeout in ms"); 89 90 static unsigned long apst_secondary_timeout_ms = 2000; 91 module_param(apst_secondary_timeout_ms, ulong, 0644); 92 MODULE_PARM_DESC(apst_secondary_timeout_ms, 93 "secondary APST timeout in ms"); 94 95 static unsigned long apst_primary_latency_tol_us = 15000; 96 module_param(apst_primary_latency_tol_us, ulong, 0644); 97 MODULE_PARM_DESC(apst_primary_latency_tol_us, 98 "primary APST latency tolerance in us"); 99 100 static unsigned long apst_secondary_latency_tol_us = 100000; 101 module_param(apst_secondary_latency_tol_us, ulong, 0644); 102 MODULE_PARM_DESC(apst_secondary_latency_tol_us, 103 "secondary APST latency tolerance in us"); 104 105 /* 106 * Older kernels didn't enable protection information if it was at an offset. 107 * Newer kernels do, so it breaks reads on the upgrade if such formats were 108 * used in prior kernels since the metadata written did not contain a valid 109 * checksum. 110 */ 111 static bool disable_pi_offsets = false; 112 module_param(disable_pi_offsets, bool, 0444); 113 MODULE_PARM_DESC(disable_pi_offsets, 114 "disable protection information if it has an offset"); 115 116 /* 117 * nvme_wq - hosts nvme related works that are not reset or delete 118 * nvme_reset_wq - hosts nvme reset works 119 * nvme_delete_wq - hosts nvme delete works 120 * 121 * nvme_wq will host works such as scan, aen handling, fw activation, 122 * keep-alive, periodic reconnects etc. nvme_reset_wq 123 * runs reset works which also flush works hosted on nvme_wq for 124 * serialization purposes. nvme_delete_wq host controller deletion 125 * works which flush reset works for serialization. 126 */ 127 struct workqueue_struct *nvme_wq; 128 EXPORT_SYMBOL_GPL(nvme_wq); 129 130 struct workqueue_struct *nvme_reset_wq; 131 EXPORT_SYMBOL_GPL(nvme_reset_wq); 132 133 struct workqueue_struct *nvme_delete_wq; 134 EXPORT_SYMBOL_GPL(nvme_delete_wq); 135 136 DEFINE_MUTEX(nvme_subsystems_lock); 137 static LIST_HEAD_GUARDED(nvme_subsystems, nvme_subsystems_lock); 138 139 static DEFINE_IDA(nvme_instance_ida); 140 static dev_t nvme_ctrl_base_chr_devt; 141 static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env); 142 static const struct class nvme_class = { 143 .name = "nvme", 144 .dev_uevent = nvme_class_uevent, 145 }; 146 147 static const struct class nvme_subsys_class = { 148 .name = "nvme-subsystem", 149 }; 150 151 static DEFINE_IDA(nvme_ns_chr_minor_ida); 152 static dev_t nvme_ns_chr_devt; 153 static const struct class nvme_ns_chr_class = { 154 .name = "nvme-generic", 155 }; 156 157 static void nvme_put_subsystem(struct nvme_subsystem *subsys); 158 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl, 159 unsigned nsid); 160 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl, 161 struct nvme_command *cmd); 162 static int nvme_get_log_lsi(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, 163 u8 lsp, u8 csi, void *log, size_t size, u64 offset, u16 lsi); 164 165 void nvme_queue_scan(struct nvme_ctrl *ctrl) 166 { 167 /* 168 * Only new queue scan work when admin and IO queues are both alive 169 */ 170 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE && ctrl->tagset) 171 queue_work(nvme_wq, &ctrl->scan_work); 172 } 173 174 /* 175 * Use this function to proceed with scheduling reset_work for a controller 176 * that had previously been set to the resetting state. This is intended for 177 * code paths that can't be interrupted by other reset attempts. A hot removal 178 * may prevent this from succeeding. 179 */ 180 int nvme_try_sched_reset(struct nvme_ctrl *ctrl) 181 { 182 if (nvme_ctrl_state(ctrl) != NVME_CTRL_RESETTING) 183 return -EBUSY; 184 if (!queue_work(nvme_reset_wq, &ctrl->reset_work)) 185 return -EBUSY; 186 return 0; 187 } 188 EXPORT_SYMBOL_GPL(nvme_try_sched_reset); 189 190 static void nvme_failfast_work(struct work_struct *work) 191 { 192 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work), 193 struct nvme_ctrl, failfast_work); 194 195 if (nvme_ctrl_state(ctrl) != NVME_CTRL_CONNECTING) 196 return; 197 198 set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 199 dev_info(ctrl->device, "failfast expired\n"); 200 nvme_kick_requeue_lists(ctrl); 201 } 202 203 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl) 204 { 205 if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1) 206 return; 207 208 schedule_delayed_work(&ctrl->failfast_work, 209 ctrl->opts->fast_io_fail_tmo * HZ); 210 } 211 212 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl) 213 { 214 if (!ctrl->opts) 215 return; 216 217 cancel_delayed_work_sync(&ctrl->failfast_work); 218 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 219 } 220 221 222 int nvme_reset_ctrl(struct nvme_ctrl *ctrl) 223 { 224 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) 225 return -EBUSY; 226 if (!queue_work(nvme_reset_wq, &ctrl->reset_work)) 227 return -EBUSY; 228 return 0; 229 } 230 EXPORT_SYMBOL_GPL(nvme_reset_ctrl); 231 232 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl) 233 { 234 int ret; 235 236 ret = nvme_reset_ctrl(ctrl); 237 if (!ret) { 238 flush_work(&ctrl->reset_work); 239 if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE) 240 ret = -ENETRESET; 241 } 242 243 return ret; 244 } 245 246 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl) 247 { 248 dev_info(ctrl->device, 249 "Removing ctrl: NQN \"%s\"\n", nvmf_ctrl_subsysnqn(ctrl)); 250 251 flush_work(&ctrl->reset_work); 252 nvme_stop_ctrl(ctrl); 253 nvme_remove_namespaces(ctrl); 254 ctrl->ops->delete_ctrl(ctrl); 255 nvme_uninit_ctrl(ctrl); 256 } 257 258 static void nvme_delete_ctrl_work(struct work_struct *work) 259 { 260 struct nvme_ctrl *ctrl = 261 container_of(work, struct nvme_ctrl, delete_work); 262 263 nvme_do_delete_ctrl(ctrl); 264 } 265 266 int nvme_delete_ctrl(struct nvme_ctrl *ctrl) 267 { 268 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING)) 269 return -EBUSY; 270 if (!queue_work(nvme_delete_wq, &ctrl->delete_work)) 271 return -EBUSY; 272 return 0; 273 } 274 EXPORT_SYMBOL_GPL(nvme_delete_ctrl); 275 276 void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl) 277 { 278 /* 279 * Keep a reference until nvme_do_delete_ctrl() complete, 280 * since ->delete_ctrl can free the controller. 281 */ 282 nvme_get_ctrl(ctrl); 283 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING)) 284 nvme_do_delete_ctrl(ctrl); 285 nvme_put_ctrl(ctrl); 286 } 287 288 static blk_status_t nvme_error_status(u16 status) 289 { 290 switch (status & NVME_SCT_SC_MASK) { 291 case NVME_SC_SUCCESS: 292 return BLK_STS_OK; 293 case NVME_SC_CAP_EXCEEDED: 294 return BLK_STS_NOSPC; 295 case NVME_SC_LBA_RANGE: 296 case NVME_SC_CMD_INTERRUPTED: 297 case NVME_SC_NS_NOT_READY: 298 return BLK_STS_TARGET; 299 case NVME_SC_BAD_ATTRIBUTES: 300 case NVME_SC_INVALID_OPCODE: 301 case NVME_SC_INVALID_FIELD: 302 case NVME_SC_INVALID_NS: 303 return BLK_STS_NOTSUPP; 304 case NVME_SC_WRITE_FAULT: 305 case NVME_SC_READ_ERROR: 306 case NVME_SC_UNWRITTEN_BLOCK: 307 case NVME_SC_ACCESS_DENIED: 308 case NVME_SC_READ_ONLY: 309 case NVME_SC_COMPARE_FAILED: 310 return BLK_STS_MEDIUM; 311 case NVME_SC_GUARD_CHECK: 312 case NVME_SC_APPTAG_CHECK: 313 case NVME_SC_REFTAG_CHECK: 314 case NVME_SC_INVALID_PI: 315 return BLK_STS_PROTECTION; 316 case NVME_SC_RESERVATION_CONFLICT: 317 return BLK_STS_RESV_CONFLICT; 318 case NVME_SC_HOST_PATH_ERROR: 319 return BLK_STS_TRANSPORT; 320 case NVME_SC_ZONE_TOO_MANY_ACTIVE: 321 return BLK_STS_ZONE_ACTIVE_RESOURCE; 322 case NVME_SC_ZONE_TOO_MANY_OPEN: 323 return BLK_STS_ZONE_OPEN_RESOURCE; 324 default: 325 return BLK_STS_IOERR; 326 } 327 } 328 329 static void nvme_retry_req(struct request *req) 330 { 331 unsigned long delay = 0; 332 u16 crd; 333 struct nvme_ns *ns = req->q->queuedata; 334 335 /* The mask and shift result must be <= 3 */ 336 crd = (nvme_req(req)->status & NVME_STATUS_CRD) >> 11; 337 if (crd) 338 delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100; 339 340 nvme_req(req)->retries++; 341 if (ns) 342 atomic_long_inc(&ns->retries); 343 344 blk_mq_requeue_request(req, false); 345 blk_mq_delay_kick_requeue_list(req->q, delay); 346 } 347 348 static void nvme_log_error(struct request *req) 349 { 350 struct nvme_ns *ns = req->q->queuedata; 351 struct nvme_request *nr = nvme_req(req); 352 353 if (ns) { 354 pr_err_ratelimited("%s: %s(0x%x) @ LBA %llu, %u blocks, %s (sct 0x%x / sc 0x%x) %s%s\n", 355 ns->disk ? ns->disk->disk_name : "?", 356 nvme_get_opcode_str(nr->cmd->common.opcode), 357 nr->cmd->common.opcode, 358 nvme_sect_to_lba(ns->head, blk_rq_pos(req)), 359 blk_rq_bytes(req) >> ns->head->lba_shift, 360 nvme_get_error_status_str(nr->status), 361 NVME_SCT(nr->status), /* Status Code Type */ 362 nr->status & NVME_SC_MASK, /* Status Code */ 363 nr->status & NVME_STATUS_MORE ? "MORE " : "", 364 nr->status & NVME_STATUS_DNR ? "DNR " : ""); 365 return; 366 } 367 368 pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s\n", 369 dev_name(nr->ctrl->device), 370 nvme_get_admin_opcode_str(nr->cmd->common.opcode), 371 nr->cmd->common.opcode, 372 nvme_get_error_status_str(nr->status), 373 NVME_SCT(nr->status), /* Status Code Type */ 374 nr->status & NVME_SC_MASK, /* Status Code */ 375 nr->status & NVME_STATUS_MORE ? "MORE " : "", 376 nr->status & NVME_STATUS_DNR ? "DNR " : ""); 377 } 378 379 static void nvme_log_err_passthru(struct request *req) 380 { 381 struct nvme_ns *ns = req->q->queuedata; 382 struct nvme_request *nr = nvme_req(req); 383 384 pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s" 385 "cdw10=0x%x cdw11=0x%x cdw12=0x%x cdw13=0x%x cdw14=0x%x cdw15=0x%x\n", 386 ns ? ns->disk->disk_name : dev_name(nr->ctrl->device), 387 ns ? nvme_get_opcode_str(nr->cmd->common.opcode) : 388 nvme_get_admin_opcode_str(nr->cmd->common.opcode), 389 nr->cmd->common.opcode, 390 nvme_get_error_status_str(nr->status), 391 NVME_SCT(nr->status), /* Status Code Type */ 392 nr->status & NVME_SC_MASK, /* Status Code */ 393 nr->status & NVME_STATUS_MORE ? "MORE " : "", 394 nr->status & NVME_STATUS_DNR ? "DNR " : "", 395 le32_to_cpu(nr->cmd->common.cdw10), 396 le32_to_cpu(nr->cmd->common.cdw11), 397 le32_to_cpu(nr->cmd->common.cdw12), 398 le32_to_cpu(nr->cmd->common.cdw13), 399 le32_to_cpu(nr->cmd->common.cdw14), 400 le32_to_cpu(nr->cmd->common.cdw15)); 401 } 402 403 enum nvme_disposition { 404 COMPLETE, 405 RETRY, 406 FAILOVER, 407 AUTHENTICATE, 408 }; 409 410 static inline enum nvme_disposition nvme_decide_disposition(struct request *req) 411 { 412 if (likely(nvme_req(req)->status == 0)) 413 return COMPLETE; 414 415 if (blk_noretry_request(req) || 416 (nvme_req(req)->status & NVME_STATUS_DNR) || 417 nvme_req(req)->retries >= nvme_max_retries) 418 return COMPLETE; 419 420 if ((nvme_req(req)->status & NVME_SCT_SC_MASK) == NVME_SC_AUTH_REQUIRED) 421 return AUTHENTICATE; 422 423 if (req->cmd_flags & REQ_NVME_MPATH) { 424 if (nvme_is_path_error(nvme_req(req)->status) || 425 blk_queue_dying(req->q)) 426 return FAILOVER; 427 } else { 428 if (blk_queue_dying(req->q)) 429 return COMPLETE; 430 } 431 432 return RETRY; 433 } 434 435 static inline void nvme_end_req_zoned(struct request *req) 436 { 437 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) && 438 req_op(req) == REQ_OP_ZONE_APPEND) { 439 struct nvme_ns *ns = req->q->queuedata; 440 441 req->__sector = nvme_lba_to_sect(ns->head, 442 le64_to_cpu(nvme_req(req)->result.u64)); 443 } 444 } 445 446 static inline void __nvme_end_req(struct request *req) 447 { 448 struct nvme_ns *ns = req->q->queuedata; 449 struct nvme_request *nr = nvme_req(req); 450 451 if (unlikely(nr->status && !(req->rq_flags & RQF_QUIET))) { 452 if (blk_rq_is_passthrough(req)) 453 nvme_log_err_passthru(req); 454 else 455 nvme_log_error(req); 456 457 if (ns) 458 atomic_long_inc(&ns->errors); 459 else 460 atomic_long_inc(&nr->ctrl->errors); 461 } 462 nvme_end_req_zoned(req); 463 nvme_trace_bio_complete(req); 464 if (req->cmd_flags & REQ_NVME_MPATH) 465 nvme_mpath_end_request(req); 466 } 467 468 void nvme_end_req(struct request *req) 469 { 470 blk_status_t status = nvme_error_status(nvme_req(req)->status); 471 472 __nvme_end_req(req); 473 blk_mq_end_request(req, status); 474 } 475 476 static void __nvme_complete_rq(struct request *req) 477 { 478 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl; 479 480 nvme_cleanup_cmd(req); 481 482 /* 483 * Completions of long-running commands should not be able to 484 * defer sending of periodic keep alives, since the controller 485 * may have completed processing such commands a long time ago 486 * (arbitrarily close to command submission time). 487 * req->deadline - req->timeout is the command submission time 488 * in jiffies. 489 */ 490 if (ctrl->kas && 491 req->deadline - req->timeout >= ctrl->ka_last_check_time) 492 ctrl->comp_seen = true; 493 494 switch (nvme_decide_disposition(req)) { 495 case COMPLETE: 496 nvme_end_req(req); 497 return; 498 case RETRY: 499 nvme_retry_req(req); 500 return; 501 case FAILOVER: 502 nvme_failover_req(req); 503 return; 504 case AUTHENTICATE: 505 #ifdef CONFIG_NVME_HOST_AUTH 506 queue_work(nvme_wq, &ctrl->dhchap_auth_work); 507 nvme_retry_req(req); 508 #else 509 nvme_end_req(req); 510 #endif 511 return; 512 } 513 } 514 515 void nvme_complete_rq(struct request *req) 516 { 517 trace_nvme_complete_rq(req); 518 __nvme_complete_rq(req); 519 } 520 EXPORT_SYMBOL_GPL(nvme_complete_rq); 521 522 void nvme_complete_batch_req(struct request *req) 523 { 524 trace_nvme_complete_rq(req); 525 nvme_cleanup_cmd(req); 526 __nvme_end_req(req); 527 } 528 EXPORT_SYMBOL_GPL(nvme_complete_batch_req); 529 530 /* 531 * Called to unwind from ->queue_rq on a failed command submission so that the 532 * multipathing code gets called to potentially failover to another path. 533 * The caller needs to unwind all transport specific resource allocations and 534 * must return propagate the return value. 535 */ 536 blk_status_t nvme_host_path_error(struct request *req) 537 { 538 nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR; 539 blk_mq_set_request_complete(req); 540 __nvme_complete_rq(req); 541 return BLK_STS_OK; 542 } 543 EXPORT_SYMBOL_GPL(nvme_host_path_error); 544 545 bool nvme_cancel_request(struct request *req, void *data) 546 { 547 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device, 548 "Cancelling I/O %d", req->tag); 549 550 /* don't abort one completed or idle request */ 551 if (blk_mq_rq_state(req) != MQ_RQ_IN_FLIGHT) 552 return true; 553 554 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD; 555 nvme_req(req)->flags |= NVME_REQ_CANCELLED; 556 blk_mq_complete_request(req); 557 return true; 558 } 559 EXPORT_SYMBOL_GPL(nvme_cancel_request); 560 561 void nvme_cancel_tagset(struct nvme_ctrl *ctrl) 562 { 563 if (ctrl->tagset) { 564 blk_mq_tagset_busy_iter(ctrl->tagset, 565 nvme_cancel_request, ctrl); 566 blk_mq_tagset_wait_completed_request(ctrl->tagset); 567 } 568 } 569 EXPORT_SYMBOL_GPL(nvme_cancel_tagset); 570 571 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl) 572 { 573 if (ctrl->admin_tagset) { 574 blk_mq_tagset_busy_iter(ctrl->admin_tagset, 575 nvme_cancel_request, ctrl); 576 blk_mq_tagset_wait_completed_request(ctrl->admin_tagset); 577 } 578 } 579 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset); 580 581 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl, 582 enum nvme_ctrl_state new_state) 583 { 584 enum nvme_ctrl_state old_state; 585 unsigned long flags; 586 bool changed = false; 587 588 spin_lock_irqsave(&ctrl->lock, flags); 589 590 old_state = nvme_ctrl_state(ctrl); 591 switch (new_state) { 592 case NVME_CTRL_LIVE: 593 switch (old_state) { 594 case NVME_CTRL_CONNECTING: 595 changed = true; 596 fallthrough; 597 default: 598 break; 599 } 600 break; 601 case NVME_CTRL_RESETTING: 602 switch (old_state) { 603 case NVME_CTRL_NEW: 604 case NVME_CTRL_LIVE: 605 changed = true; 606 atomic_long_inc(&ctrl->nr_reset); 607 fallthrough; 608 default: 609 break; 610 } 611 break; 612 case NVME_CTRL_CONNECTING: 613 switch (old_state) { 614 case NVME_CTRL_NEW: 615 case NVME_CTRL_RESETTING: 616 changed = true; 617 fallthrough; 618 default: 619 break; 620 } 621 break; 622 case NVME_CTRL_DELETING: 623 switch (old_state) { 624 case NVME_CTRL_LIVE: 625 case NVME_CTRL_RESETTING: 626 case NVME_CTRL_CONNECTING: 627 changed = true; 628 fallthrough; 629 default: 630 break; 631 } 632 break; 633 case NVME_CTRL_DELETING_NOIO: 634 switch (old_state) { 635 case NVME_CTRL_DELETING: 636 case NVME_CTRL_DEAD: 637 changed = true; 638 fallthrough; 639 default: 640 break; 641 } 642 break; 643 case NVME_CTRL_DEAD: 644 switch (old_state) { 645 case NVME_CTRL_DELETING: 646 changed = true; 647 fallthrough; 648 default: 649 break; 650 } 651 break; 652 default: 653 break; 654 } 655 656 if (changed) { 657 WRITE_ONCE(ctrl->state, new_state); 658 wake_up_all(&ctrl->state_wq); 659 } 660 661 spin_unlock_irqrestore(&ctrl->lock, flags); 662 if (!changed) 663 return false; 664 665 if (new_state == NVME_CTRL_LIVE) { 666 if (old_state == NVME_CTRL_CONNECTING) 667 nvme_stop_failfast_work(ctrl); 668 nvme_kick_requeue_lists(ctrl); 669 } else if (new_state == NVME_CTRL_CONNECTING && 670 old_state == NVME_CTRL_RESETTING) { 671 nvme_start_failfast_work(ctrl); 672 } 673 return changed; 674 } 675 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state); 676 677 /* 678 * Waits for the controller state to be resetting, or returns false if it is 679 * not possible to ever transition to that state. 680 */ 681 bool nvme_wait_reset(struct nvme_ctrl *ctrl) 682 { 683 wait_event(ctrl->state_wq, 684 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) || 685 nvme_state_terminal(ctrl)); 686 return nvme_ctrl_state(ctrl) == NVME_CTRL_RESETTING; 687 } 688 EXPORT_SYMBOL_GPL(nvme_wait_reset); 689 690 static void nvme_free_ns_head(struct kref *ref) 691 { 692 struct nvme_ns_head *head = 693 container_of(ref, struct nvme_ns_head, ref); 694 695 nvme_mpath_put_disk(head); 696 ida_free(&head->subsys->ns_ida, head->instance); 697 cleanup_srcu_struct(&head->srcu); 698 nvme_put_subsystem(head->subsys); 699 kfree(head->plids); 700 kfree(head); 701 } 702 703 void nvme_get_ns_head(struct nvme_ns_head *head) 704 { 705 kref_get(&head->ref); 706 } 707 708 bool nvme_tryget_ns_head(struct nvme_ns_head *head) 709 { 710 return kref_get_unless_zero(&head->ref); 711 } 712 713 void nvme_put_ns_head(struct nvme_ns_head *head) 714 { 715 kref_put(&head->ref, nvme_free_ns_head); 716 } 717 718 static void nvme_free_ns(struct kref *kref) 719 { 720 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref); 721 722 put_disk(ns->disk); 723 nvme_put_ns_head(ns->head); 724 nvme_put_ctrl(ns->ctrl); 725 kfree(ns); 726 } 727 728 bool nvme_get_ns(struct nvme_ns *ns) 729 { 730 return kref_get_unless_zero(&ns->kref); 731 } 732 733 void nvme_put_ns(struct nvme_ns *ns) 734 { 735 kref_put(&ns->kref, nvme_free_ns); 736 } 737 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, "NVME_TARGET_PASSTHRU"); 738 739 static inline void nvme_clear_nvme_request(struct request *req) 740 { 741 nvme_req(req)->status = 0; 742 nvme_req(req)->retries = 0; 743 nvme_req(req)->flags = 0; 744 req->rq_flags |= RQF_DONTPREP; 745 } 746 747 /* initialize a passthrough request */ 748 void nvme_init_request(struct request *req, struct nvme_command *cmd) 749 { 750 struct nvme_request *nr = nvme_req(req); 751 bool logging_enabled; 752 753 if (req->q->queuedata) { 754 struct nvme_ns *ns = req->q->disk->private_data; 755 756 logging_enabled = ns->head->passthru_err_log_enabled; 757 } else { /* no queuedata implies admin queue */ 758 logging_enabled = nr->ctrl->passthru_err_log_enabled; 759 } 760 761 if (!logging_enabled) 762 req->rq_flags |= RQF_QUIET; 763 764 /* passthru commands should let the driver set the SGL flags */ 765 cmd->common.flags &= ~NVME_CMD_SGL_ALL; 766 767 req->cmd_flags |= REQ_FAILFAST_DRIVER; 768 if (req->mq_hctx->type == HCTX_TYPE_POLL) 769 req->cmd_flags |= REQ_POLLED; 770 nvme_clear_nvme_request(req); 771 memcpy(nr->cmd, cmd, sizeof(*cmd)); 772 } 773 EXPORT_SYMBOL_GPL(nvme_init_request); 774 775 /* 776 * For something we're not in a state to send to the device the default action 777 * is to busy it and retry it after the controller state is recovered. However, 778 * if the controller is deleting or if anything is marked for failfast or 779 * nvme multipath it is immediately failed. 780 * 781 * Note: commands used to initialize the controller will be marked for failfast. 782 * Note: nvme cli/ioctl commands are marked for failfast. 783 */ 784 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl, 785 struct request *rq) 786 { 787 enum nvme_ctrl_state state = nvme_ctrl_state(ctrl); 788 789 if (state != NVME_CTRL_DELETING_NOIO && 790 state != NVME_CTRL_DELETING && 791 state != NVME_CTRL_DEAD && 792 !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) && 793 !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH)) 794 return BLK_STS_RESOURCE; 795 796 if (!(rq->rq_flags & RQF_DONTPREP)) 797 nvme_clear_nvme_request(rq); 798 799 return nvme_host_path_error(rq); 800 } 801 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command); 802 803 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq, 804 bool queue_live, enum nvme_ctrl_state state) 805 { 806 struct nvme_request *req = nvme_req(rq); 807 808 /* 809 * currently we have a problem sending passthru commands 810 * on the admin_q if the controller is not LIVE because we can't 811 * make sure that they are going out after the admin connect, 812 * controller enable and/or other commands in the initialization 813 * sequence. until the controller will be LIVE, fail with 814 * BLK_STS_RESOURCE so that they will be rescheduled. 815 */ 816 if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD)) 817 return false; 818 819 if (ctrl->ops->flags & NVME_F_FABRICS) { 820 /* 821 * Only allow commands on a live queue, except for the connect 822 * command, which is require to set the queue live in the 823 * appropinquate states. 824 */ 825 switch (state) { 826 case NVME_CTRL_CONNECTING: 827 if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) && 828 (req->cmd->fabrics.fctype == nvme_fabrics_type_connect || 829 req->cmd->fabrics.fctype == nvme_fabrics_type_auth_send || 830 req->cmd->fabrics.fctype == nvme_fabrics_type_auth_receive)) 831 return true; 832 break; 833 default: 834 break; 835 case NVME_CTRL_DEAD: 836 return false; 837 } 838 } 839 840 return queue_live; 841 } 842 EXPORT_SYMBOL_GPL(__nvme_check_ready); 843 844 static inline void nvme_setup_flush(struct nvme_ns *ns, 845 struct nvme_command *cmnd) 846 { 847 memset(cmnd, 0, sizeof(*cmnd)); 848 cmnd->common.opcode = nvme_cmd_flush; 849 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id); 850 } 851 852 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req, 853 struct nvme_command *cmnd) 854 { 855 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0; 856 struct nvme_dsm_range *range; 857 struct bio *bio; 858 859 /* 860 * Some devices do not consider the DSM 'Number of Ranges' field when 861 * determining how much data to DMA. Always allocate memory for maximum 862 * number of segments to prevent device reading beyond end of buffer. 863 */ 864 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES; 865 866 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN); 867 if (!range) { 868 /* 869 * If we fail allocation our range, fallback to the controller 870 * discard page. If that's also busy, it's safe to return 871 * busy, as we know we can make progress once that's freed. 872 */ 873 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy)) 874 return BLK_STS_RESOURCE; 875 876 range = page_address(ns->ctrl->discard_page); 877 } 878 879 if (queue_max_discard_segments(req->q) == 1) { 880 u64 slba = nvme_sect_to_lba(ns->head, blk_rq_pos(req)); 881 u32 nlb = blk_rq_sectors(req) >> (ns->head->lba_shift - 9); 882 883 range[0].cattr = cpu_to_le32(0); 884 range[0].nlb = cpu_to_le32(nlb); 885 range[0].slba = cpu_to_le64(slba); 886 n = 1; 887 } else { 888 __rq_for_each_bio(bio, req) { 889 u64 slba = nvme_sect_to_lba(ns->head, 890 bio->bi_iter.bi_sector); 891 u32 nlb = bio->bi_iter.bi_size >> ns->head->lba_shift; 892 893 if (n < segments) { 894 range[n].cattr = cpu_to_le32(0); 895 range[n].nlb = cpu_to_le32(nlb); 896 range[n].slba = cpu_to_le64(slba); 897 } 898 n++; 899 } 900 } 901 902 if (WARN_ON_ONCE(n != segments)) { 903 if (virt_to_page(range) == ns->ctrl->discard_page) 904 clear_bit_unlock(0, &ns->ctrl->discard_page_busy); 905 else 906 kfree(range); 907 return BLK_STS_IOERR; 908 } 909 910 memset(cmnd, 0, sizeof(*cmnd)); 911 cmnd->dsm.opcode = nvme_cmd_dsm; 912 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id); 913 cmnd->dsm.nr = cpu_to_le32(segments - 1); 914 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD); 915 916 bvec_set_virt(&req->special_vec, range, alloc_size); 917 req->rq_flags |= RQF_SPECIAL_PAYLOAD; 918 919 return BLK_STS_OK; 920 } 921 922 static void nvme_set_app_tag(struct request *req, struct nvme_command *cmnd) 923 { 924 cmnd->rw.lbat = cpu_to_le16(bio_integrity(req->bio)->app_tag); 925 cmnd->rw.lbatm = cpu_to_le16(0xffff); 926 } 927 928 static void nvme_set_ref_tag(struct nvme_ns *ns, struct nvme_command *cmnd, 929 struct request *req) 930 { 931 u32 upper, lower; 932 u64 ref48; 933 934 /* only type1 and type 2 PI formats have a reftag */ 935 switch (ns->head->pi_type) { 936 case NVME_NS_DPS_PI_TYPE1: 937 case NVME_NS_DPS_PI_TYPE2: 938 break; 939 default: 940 return; 941 } 942 943 /* both rw and write zeroes share the same reftag format */ 944 switch (ns->head->guard_type) { 945 case NVME_NVM_NS_16B_GUARD: 946 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req)); 947 break; 948 case NVME_NVM_NS_64B_GUARD: 949 ref48 = ext_pi_ref_tag(req); 950 lower = lower_32_bits(ref48); 951 upper = upper_32_bits(ref48); 952 953 cmnd->rw.reftag = cpu_to_le32(lower); 954 cmnd->rw.cdw3 = cpu_to_le32(upper); 955 break; 956 default: 957 break; 958 } 959 } 960 961 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns, 962 struct request *req, struct nvme_command *cmnd) 963 { 964 memset(cmnd, 0, sizeof(*cmnd)); 965 966 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) 967 return nvme_setup_discard(ns, req, cmnd); 968 969 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes; 970 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id); 971 cmnd->write_zeroes.slba = 972 cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req))); 973 cmnd->write_zeroes.length = 974 cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1); 975 976 if (!(req->cmd_flags & REQ_NOUNMAP) && 977 (ns->head->features & NVME_NS_DEAC)) 978 cmnd->write_zeroes.control |= cpu_to_le16(NVME_WZ_DEAC); 979 980 if (nvme_ns_has_pi(ns->head)) { 981 cmnd->write_zeroes.control |= cpu_to_le16(NVME_RW_PRINFO_PRACT); 982 nvme_set_ref_tag(ns, cmnd, req); 983 } 984 985 return BLK_STS_OK; 986 } 987 988 /* 989 * NVMe does not support a dedicated command to issue an atomic write. A write 990 * which does adhere to the device atomic limits will silently be executed 991 * non-atomically. The request issuer should ensure that the write is within 992 * the queue atomic writes limits, but just validate this in case it is not. 993 */ 994 static bool nvme_valid_atomic_write(struct request *req) 995 { 996 struct request_queue *q = req->q; 997 u32 boundary_bytes = queue_atomic_write_boundary_bytes(q); 998 999 if (blk_rq_bytes(req) > queue_atomic_write_unit_max_bytes(q)) 1000 return false; 1001 1002 if (boundary_bytes) { 1003 u64 mask = boundary_bytes - 1, imask = ~mask; 1004 u64 start = blk_rq_pos(req) << SECTOR_SHIFT; 1005 u64 end = start + blk_rq_bytes(req) - 1; 1006 1007 /* If greater then must be crossing a boundary */ 1008 if (blk_rq_bytes(req) > boundary_bytes) 1009 return false; 1010 1011 if ((start & imask) != (end & imask)) 1012 return false; 1013 } 1014 1015 return true; 1016 } 1017 1018 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns, 1019 struct request *req, struct nvme_command *cmnd, 1020 enum nvme_opcode op) 1021 { 1022 u16 control = 0; 1023 u32 dsmgmt = 0; 1024 1025 if (req->cmd_flags & REQ_FUA) 1026 control |= NVME_RW_FUA; 1027 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD)) 1028 control |= NVME_RW_LR; 1029 1030 if (req->cmd_flags & REQ_RAHEAD) 1031 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH; 1032 1033 if (op == nvme_cmd_write && ns->head->nr_plids) { 1034 u16 write_stream = req->bio->bi_write_stream; 1035 1036 if (WARN_ON_ONCE(write_stream > ns->head->nr_plids)) 1037 return BLK_STS_INVAL; 1038 1039 if (write_stream) { 1040 dsmgmt |= ns->head->plids[write_stream - 1] << 16; 1041 control |= NVME_RW_DTYPE_DPLCMT; 1042 } 1043 } 1044 1045 if (req->cmd_flags & REQ_ATOMIC && !nvme_valid_atomic_write(req)) 1046 return BLK_STS_INVAL; 1047 1048 cmnd->rw.opcode = op; 1049 cmnd->rw.flags = 0; 1050 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id); 1051 cmnd->rw.cdw2 = 0; 1052 cmnd->rw.cdw3 = 0; 1053 cmnd->rw.metadata = 0; 1054 cmnd->rw.slba = 1055 cpu_to_le64(nvme_sect_to_lba(ns->head, blk_rq_pos(req))); 1056 cmnd->rw.length = 1057 cpu_to_le16((blk_rq_bytes(req) >> ns->head->lba_shift) - 1); 1058 cmnd->rw.reftag = 0; 1059 cmnd->rw.lbat = 0; 1060 cmnd->rw.lbatm = 0; 1061 1062 if (ns->head->ms) { 1063 /* 1064 * If formatted with metadata, the block layer always provides a 1065 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else 1066 * we enable the PRACT bit for protection information or set the 1067 * namespace capacity to zero to prevent any I/O. 1068 */ 1069 if (!blk_integrity_rq(req)) { 1070 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns->head))) 1071 return BLK_STS_NOTSUPP; 1072 control |= NVME_RW_PRINFO_PRACT; 1073 nvme_set_ref_tag(ns, cmnd, req); 1074 } 1075 1076 if (bio_integrity_flagged(req->bio, BIP_CHECK_GUARD)) 1077 control |= NVME_RW_PRINFO_PRCHK_GUARD; 1078 if (bio_integrity_flagged(req->bio, BIP_CHECK_REFTAG)) { 1079 control |= NVME_RW_PRINFO_PRCHK_REF; 1080 if (op == nvme_cmd_zone_append) 1081 control |= NVME_RW_APPEND_PIREMAP; 1082 nvme_set_ref_tag(ns, cmnd, req); 1083 } 1084 if (bio_integrity_flagged(req->bio, BIP_CHECK_APPTAG)) { 1085 control |= NVME_RW_PRINFO_PRCHK_APP; 1086 nvme_set_app_tag(req, cmnd); 1087 } 1088 } 1089 1090 cmnd->rw.control = cpu_to_le16(control); 1091 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt); 1092 return 0; 1093 } 1094 1095 void nvme_cleanup_cmd(struct request *req) 1096 { 1097 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) { 1098 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl; 1099 1100 if (req->special_vec.bv_page == ctrl->discard_page) 1101 clear_bit_unlock(0, &ctrl->discard_page_busy); 1102 else 1103 kfree(bvec_virt(&req->special_vec)); 1104 req->rq_flags &= ~RQF_SPECIAL_PAYLOAD; 1105 } 1106 } 1107 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd); 1108 1109 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req) 1110 { 1111 struct nvme_command *cmd = nvme_req(req)->cmd; 1112 blk_status_t ret = BLK_STS_OK; 1113 1114 if (!(req->rq_flags & RQF_DONTPREP)) 1115 nvme_clear_nvme_request(req); 1116 1117 switch (req_op(req)) { 1118 case REQ_OP_DRV_IN: 1119 case REQ_OP_DRV_OUT: 1120 /* these are setup prior to execution in nvme_init_request() */ 1121 break; 1122 case REQ_OP_FLUSH: 1123 nvme_setup_flush(ns, cmd); 1124 break; 1125 case REQ_OP_ZONE_RESET_ALL: 1126 case REQ_OP_ZONE_RESET: 1127 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET); 1128 break; 1129 case REQ_OP_ZONE_OPEN: 1130 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN); 1131 break; 1132 case REQ_OP_ZONE_CLOSE: 1133 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE); 1134 break; 1135 case REQ_OP_ZONE_FINISH: 1136 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH); 1137 break; 1138 case REQ_OP_WRITE_ZEROES: 1139 ret = nvme_setup_write_zeroes(ns, req, cmd); 1140 break; 1141 case REQ_OP_DISCARD: 1142 ret = nvme_setup_discard(ns, req, cmd); 1143 break; 1144 case REQ_OP_READ: 1145 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read); 1146 break; 1147 case REQ_OP_WRITE: 1148 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write); 1149 break; 1150 case REQ_OP_ZONE_APPEND: 1151 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append); 1152 break; 1153 default: 1154 WARN_ON_ONCE(1); 1155 return BLK_STS_IOERR; 1156 } 1157 1158 cmd->common.command_id = nvme_cid(req); 1159 trace_nvme_setup_cmd(req, cmd); 1160 return ret; 1161 } 1162 EXPORT_SYMBOL_GPL(nvme_setup_cmd); 1163 1164 /* 1165 * Return values: 1166 * 0: success 1167 * >0: nvme controller's cqe status response 1168 * <0: kernel error in lieu of controller response 1169 */ 1170 int nvme_execute_rq(struct request *rq, bool at_head) 1171 { 1172 blk_status_t status; 1173 1174 status = blk_execute_rq(rq, at_head); 1175 if (nvme_req(rq)->flags & NVME_REQ_CANCELLED) 1176 return -EINTR; 1177 if (nvme_req(rq)->status) 1178 return nvme_req(rq)->status; 1179 return blk_status_to_errno(status); 1180 } 1181 EXPORT_SYMBOL_NS_GPL(nvme_execute_rq, "NVME_TARGET_PASSTHRU"); 1182 1183 /* 1184 * Returns 0 on success. If the result is negative, it's a Linux error code; 1185 * if the result is positive, it's an NVM Express status code 1186 */ 1187 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 1188 union nvme_result *result, void *buffer, unsigned bufflen, 1189 int qid, nvme_submit_flags_t flags) 1190 { 1191 struct request *req; 1192 int ret; 1193 blk_mq_req_flags_t blk_flags = 0; 1194 1195 if (flags & NVME_SUBMIT_NOWAIT) 1196 blk_flags |= BLK_MQ_REQ_NOWAIT; 1197 if (flags & NVME_SUBMIT_RESERVED) 1198 blk_flags |= BLK_MQ_REQ_RESERVED; 1199 if (qid == NVME_QID_ANY) 1200 req = blk_mq_alloc_request(q, nvme_req_op(cmd), blk_flags); 1201 else 1202 req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), blk_flags, 1203 qid - 1); 1204 1205 if (IS_ERR(req)) 1206 return PTR_ERR(req); 1207 nvme_init_request(req, cmd); 1208 if (flags & NVME_SUBMIT_RETRY) 1209 req->cmd_flags &= ~REQ_FAILFAST_DRIVER; 1210 1211 if (buffer && bufflen) { 1212 ret = blk_rq_map_kern(req, buffer, bufflen, GFP_KERNEL); 1213 if (ret) 1214 goto out; 1215 } 1216 1217 ret = nvme_execute_rq(req, flags & NVME_SUBMIT_AT_HEAD); 1218 if (result && ret >= 0) 1219 *result = nvme_req(req)->result; 1220 out: 1221 blk_mq_free_request(req); 1222 return ret; 1223 } 1224 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd); 1225 1226 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 1227 void *buffer, unsigned bufflen) 1228 { 1229 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 1230 NVME_QID_ANY, 0); 1231 } 1232 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd); 1233 1234 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode) 1235 { 1236 u32 effects = 0; 1237 1238 if (ns) { 1239 effects = le32_to_cpu(ns->head->effects->iocs[opcode]); 1240 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC)) 1241 dev_warn_once(ctrl->device, 1242 "IO command:%02x has unusual effects:%08x\n", 1243 opcode, effects); 1244 1245 /* 1246 * NVME_CMD_EFFECTS_CSE_MASK causes a freeze all I/O queues, 1247 * which would deadlock when done on an I/O command. Note that 1248 * We already warn about an unusual effect above. 1249 */ 1250 effects &= ~NVME_CMD_EFFECTS_CSE_MASK; 1251 } else { 1252 effects = le32_to_cpu(ctrl->effects->acs[opcode]); 1253 1254 /* Ignore execution restrictions if any relaxation bits are set */ 1255 if (effects & NVME_CMD_EFFECTS_CSER_MASK) 1256 effects &= ~NVME_CMD_EFFECTS_CSE_MASK; 1257 } 1258 1259 return effects; 1260 } 1261 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, "NVME_TARGET_PASSTHRU"); 1262 1263 u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode) 1264 { 1265 u32 effects = nvme_command_effects(ctrl, ns, opcode); 1266 1267 /* 1268 * For simplicity, IO to all namespaces is quiesced even if the command 1269 * effects say only one namespace is affected. 1270 */ 1271 if (effects & NVME_CMD_EFFECTS_CSE_MASK) { 1272 mutex_lock(&ctrl->scan_lock); 1273 mutex_lock(&ctrl->subsys->lock); 1274 nvme_mpath_start_freeze(ctrl->subsys); 1275 nvme_mpath_wait_freeze(ctrl->subsys); 1276 nvme_start_freeze(ctrl); 1277 nvme_wait_freeze(ctrl); 1278 } 1279 return effects; 1280 } 1281 EXPORT_SYMBOL_NS_GPL(nvme_passthru_start, "NVME_TARGET_PASSTHRU"); 1282 1283 u32 nvme_passthru_end(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u32 effects, 1284 struct nvme_command *cmd, int status) 1285 { 1286 if (effects & NVME_CMD_EFFECTS_CSE_MASK) { 1287 nvme_unfreeze(ctrl); 1288 nvme_mpath_unfreeze(ctrl->subsys); 1289 mutex_unlock(&ctrl->subsys->lock); 1290 mutex_unlock(&ctrl->scan_lock); 1291 } 1292 if (effects & NVME_CMD_EFFECTS_CCC) { 1293 if (!test_and_set_bit(NVME_CTRL_DIRTY_CAPABILITY, 1294 &ctrl->flags)) { 1295 dev_info(ctrl->device, 1296 "controller capabilities changed, reset may be required to take effect.\n"); 1297 } 1298 } 1299 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) { 1300 nvme_queue_scan(ctrl); 1301 flush_work(&ctrl->scan_work); 1302 } 1303 if (ns) 1304 return effects; 1305 1306 switch (cmd->common.opcode) { 1307 case nvme_admin_set_features: 1308 switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) { 1309 case NVME_FEAT_KATO: 1310 /* 1311 * Keep alive commands interval on the host should be 1312 * updated when KATO is modified by Set Features 1313 * commands. 1314 */ 1315 if (!status) 1316 nvme_update_keep_alive(ctrl, cmd); 1317 break; 1318 default: 1319 break; 1320 } 1321 break; 1322 default: 1323 break; 1324 } 1325 1326 return effects; 1327 } 1328 EXPORT_SYMBOL_NS_GPL(nvme_passthru_end, "NVME_TARGET_PASSTHRU"); 1329 1330 /* 1331 * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1: 1332 * 1333 * The host should send Keep Alive commands at half of the Keep Alive Timeout 1334 * accounting for transport roundtrip times [..]. 1335 */ 1336 static unsigned long nvme_keep_alive_work_period(struct nvme_ctrl *ctrl) 1337 { 1338 unsigned long delay = ctrl->kato * HZ / 2; 1339 1340 /* 1341 * When using Traffic Based Keep Alive, we need to run 1342 * nvme_keep_alive_work at twice the normal frequency, as one 1343 * command completion can postpone sending a keep alive command 1344 * by up to twice the delay between runs. 1345 */ 1346 if (ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) 1347 delay /= 2; 1348 return delay; 1349 } 1350 1351 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl) 1352 { 1353 unsigned long now = jiffies; 1354 unsigned long delay = nvme_keep_alive_work_period(ctrl); 1355 unsigned long ka_next_check_tm = ctrl->ka_last_check_time + delay; 1356 1357 if (time_after(now, ka_next_check_tm)) 1358 delay = 0; 1359 else 1360 delay = ka_next_check_tm - now; 1361 1362 queue_delayed_work(nvme_wq, &ctrl->ka_work, delay); 1363 } 1364 1365 static enum rq_end_io_ret nvme_keep_alive_end_io(struct request *rq, 1366 blk_status_t status, 1367 const struct io_comp_batch *iob) 1368 { 1369 struct nvme_ctrl *ctrl = rq->end_io_data; 1370 unsigned long rtt = jiffies - (rq->deadline - rq->timeout); 1371 unsigned long delay = nvme_keep_alive_work_period(ctrl); 1372 enum nvme_ctrl_state state = nvme_ctrl_state(ctrl); 1373 1374 /* 1375 * Subtract off the keepalive RTT so nvme_keep_alive_work runs 1376 * at the desired frequency. 1377 */ 1378 if (rtt <= delay) { 1379 delay -= rtt; 1380 } else { 1381 dev_warn(ctrl->device, "long keepalive RTT (%u ms)\n", 1382 jiffies_to_msecs(rtt)); 1383 delay = 0; 1384 } 1385 1386 blk_mq_free_request(rq); 1387 1388 if (status) { 1389 dev_err(ctrl->device, 1390 "failed nvme_keep_alive_end_io error=%d\n", 1391 status); 1392 return RQ_END_IO_NONE; 1393 } 1394 1395 ctrl->ka_last_check_time = jiffies; 1396 ctrl->comp_seen = false; 1397 if (state == NVME_CTRL_LIVE || state == NVME_CTRL_CONNECTING) 1398 queue_delayed_work(nvme_wq, &ctrl->ka_work, delay); 1399 return RQ_END_IO_NONE; 1400 } 1401 1402 static void nvme_keep_alive_work(struct work_struct *work) 1403 { 1404 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work), 1405 struct nvme_ctrl, ka_work); 1406 bool comp_seen = ctrl->comp_seen; 1407 struct request *rq; 1408 1409 ctrl->ka_last_check_time = jiffies; 1410 1411 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) { 1412 dev_dbg(ctrl->device, 1413 "reschedule traffic based keep-alive timer\n"); 1414 ctrl->comp_seen = false; 1415 nvme_queue_keep_alive_work(ctrl); 1416 return; 1417 } 1418 1419 rq = blk_mq_alloc_request(ctrl->admin_q, nvme_req_op(&ctrl->ka_cmd), 1420 BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT); 1421 if (IS_ERR(rq)) { 1422 /* allocation failure, reset the controller */ 1423 dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq)); 1424 nvme_reset_ctrl(ctrl); 1425 return; 1426 } 1427 nvme_init_request(rq, &ctrl->ka_cmd); 1428 1429 rq->timeout = ctrl->kato * HZ; 1430 rq->end_io = nvme_keep_alive_end_io; 1431 rq->end_io_data = ctrl; 1432 blk_execute_rq_nowait(rq, false); 1433 } 1434 1435 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl) 1436 { 1437 if (unlikely(ctrl->kato == 0)) 1438 return; 1439 1440 nvme_queue_keep_alive_work(ctrl); 1441 } 1442 1443 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl) 1444 { 1445 if (unlikely(ctrl->kato == 0)) 1446 return; 1447 1448 cancel_delayed_work_sync(&ctrl->ka_work); 1449 } 1450 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive); 1451 1452 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl, 1453 struct nvme_command *cmd) 1454 { 1455 unsigned int new_kato = 1456 DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000); 1457 1458 dev_info(ctrl->device, 1459 "keep alive interval updated from %u ms to %u ms\n", 1460 ctrl->kato * 1000 / 2, new_kato * 1000 / 2); 1461 1462 nvme_stop_keep_alive(ctrl); 1463 ctrl->kato = new_kato; 1464 nvme_start_keep_alive(ctrl); 1465 } 1466 1467 static bool nvme_id_cns_ok(struct nvme_ctrl *ctrl, u8 cns) 1468 { 1469 /* 1470 * The CNS field occupies a full byte starting with NVMe 1.2 1471 */ 1472 if (ctrl->vs >= NVME_VS(1, 2, 0)) 1473 return true; 1474 1475 /* 1476 * NVMe 1.1 expanded the CNS value to two bits, which means values 1477 * larger than that could get truncated and treated as an incorrect 1478 * value. 1479 * 1480 * Qemu implemented 1.0 behavior for controllers claiming 1.1 1481 * compliance, so they need to be quirked here. 1482 */ 1483 if (ctrl->vs >= NVME_VS(1, 1, 0) && 1484 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) 1485 return cns <= 3; 1486 1487 /* 1488 * NVMe 1.0 used a single bit for the CNS value. 1489 */ 1490 return cns <= 1; 1491 } 1492 1493 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id) 1494 { 1495 struct nvme_command c = { }; 1496 int error; 1497 1498 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 1499 c.identify.opcode = nvme_admin_identify; 1500 c.identify.cns = NVME_ID_CNS_CTRL; 1501 1502 *id = kmalloc_obj(struct nvme_id_ctrl); 1503 if (!*id) 1504 return -ENOMEM; 1505 1506 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id, 1507 sizeof(struct nvme_id_ctrl)); 1508 if (error) { 1509 kfree(*id); 1510 *id = NULL; 1511 } 1512 return error; 1513 } 1514 1515 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids, 1516 struct nvme_ns_id_desc *cur, bool *csi_seen) 1517 { 1518 const char *warn_str = "ctrl returned bogus length:"; 1519 void *data = cur; 1520 1521 switch (cur->nidt) { 1522 case NVME_NIDT_EUI64: 1523 if (cur->nidl != NVME_NIDT_EUI64_LEN) { 1524 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n", 1525 warn_str, cur->nidl); 1526 return -1; 1527 } 1528 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) 1529 return NVME_NIDT_EUI64_LEN; 1530 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN); 1531 return NVME_NIDT_EUI64_LEN; 1532 case NVME_NIDT_NGUID: 1533 if (cur->nidl != NVME_NIDT_NGUID_LEN) { 1534 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n", 1535 warn_str, cur->nidl); 1536 return -1; 1537 } 1538 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) 1539 return NVME_NIDT_NGUID_LEN; 1540 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN); 1541 return NVME_NIDT_NGUID_LEN; 1542 case NVME_NIDT_UUID: 1543 if (cur->nidl != NVME_NIDT_UUID_LEN) { 1544 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n", 1545 warn_str, cur->nidl); 1546 return -1; 1547 } 1548 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) 1549 return NVME_NIDT_UUID_LEN; 1550 uuid_copy(&ids->uuid, data + sizeof(*cur)); 1551 return NVME_NIDT_UUID_LEN; 1552 case NVME_NIDT_CSI: 1553 if (cur->nidl != NVME_NIDT_CSI_LEN) { 1554 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n", 1555 warn_str, cur->nidl); 1556 return -1; 1557 } 1558 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN); 1559 *csi_seen = true; 1560 return NVME_NIDT_CSI_LEN; 1561 default: 1562 /* Skip unknown types */ 1563 return cur->nidl; 1564 } 1565 } 1566 1567 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, 1568 struct nvme_ns_info *info) 1569 { 1570 struct nvme_command c = { }; 1571 bool csi_seen = false; 1572 int status, pos, len; 1573 void *data; 1574 1575 if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl)) 1576 return 0; 1577 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST) 1578 return 0; 1579 1580 c.identify.opcode = nvme_admin_identify; 1581 c.identify.nsid = cpu_to_le32(info->nsid); 1582 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST; 1583 1584 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 1585 if (!data) 1586 return -ENOMEM; 1587 1588 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data, 1589 NVME_IDENTIFY_DATA_SIZE); 1590 if (status) { 1591 dev_warn(ctrl->device, 1592 "Identify Descriptors failed (nsid=%u, status=0x%x)\n", 1593 info->nsid, status); 1594 goto free_data; 1595 } 1596 1597 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) { 1598 struct nvme_ns_id_desc *cur = data + pos; 1599 1600 if (pos + sizeof(*cur) > NVME_IDENTIFY_DATA_SIZE) 1601 break; 1602 if (cur->nidl == 0) 1603 break; 1604 if (pos + sizeof(*cur) + cur->nidl > NVME_IDENTIFY_DATA_SIZE) 1605 break; 1606 1607 len = nvme_process_ns_desc(ctrl, &info->ids, cur, &csi_seen); 1608 if (len < 0) 1609 break; 1610 1611 len += sizeof(*cur); 1612 } 1613 1614 if (nvme_multi_css(ctrl) && !csi_seen) { 1615 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n", 1616 info->nsid); 1617 status = -EINVAL; 1618 } 1619 1620 free_data: 1621 kfree(data); 1622 return status; 1623 } 1624 1625 int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid, 1626 struct nvme_id_ns **id) 1627 { 1628 struct nvme_command c = { }; 1629 int error; 1630 1631 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 1632 c.identify.opcode = nvme_admin_identify; 1633 c.identify.nsid = cpu_to_le32(nsid); 1634 c.identify.cns = NVME_ID_CNS_NS; 1635 1636 *id = kmalloc_obj(**id); 1637 if (!*id) 1638 return -ENOMEM; 1639 1640 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id)); 1641 if (error) { 1642 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error); 1643 kfree(*id); 1644 *id = NULL; 1645 } 1646 return error; 1647 } 1648 1649 static int nvme_ns_info_from_identify(struct nvme_ctrl *ctrl, 1650 struct nvme_ns_info *info) 1651 { 1652 struct nvme_ns_ids *ids = &info->ids; 1653 struct nvme_id_ns *id; 1654 int ret; 1655 1656 ret = nvme_identify_ns(ctrl, info->nsid, &id); 1657 if (ret) 1658 return ret; 1659 1660 if (id->ncap == 0) { 1661 /* namespace not allocated or attached */ 1662 info->is_removed = true; 1663 ret = -ENODEV; 1664 goto error; 1665 } 1666 1667 info->anagrpid = id->anagrpid; 1668 info->is_shared = id->nmic & NVME_NS_NMIC_SHARED; 1669 info->is_readonly = id->nsattr & NVME_NS_ATTR_RO; 1670 info->is_ready = true; 1671 info->endgid = le16_to_cpu(id->endgid); 1672 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) { 1673 dev_info(ctrl->device, 1674 "Ignoring bogus Namespace Identifiers\n"); 1675 } else { 1676 if (ctrl->vs >= NVME_VS(1, 1, 0) && 1677 !memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 1678 memcpy(ids->eui64, id->eui64, sizeof(ids->eui64)); 1679 if (ctrl->vs >= NVME_VS(1, 2, 0) && 1680 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 1681 memcpy(ids->nguid, id->nguid, sizeof(ids->nguid)); 1682 } 1683 1684 error: 1685 kfree(id); 1686 return ret; 1687 } 1688 1689 static int nvme_ns_info_from_id_cs_indep(struct nvme_ctrl *ctrl, 1690 struct nvme_ns_info *info) 1691 { 1692 struct nvme_id_ns_cs_indep *id; 1693 struct nvme_command c = { 1694 .identify.opcode = nvme_admin_identify, 1695 .identify.nsid = cpu_to_le32(info->nsid), 1696 .identify.cns = NVME_ID_CNS_NS_CS_INDEP, 1697 }; 1698 int ret; 1699 1700 id = kmalloc_obj(*id); 1701 if (!id) 1702 return -ENOMEM; 1703 1704 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id)); 1705 if (!ret) { 1706 info->anagrpid = id->anagrpid; 1707 info->is_shared = id->nmic & NVME_NS_NMIC_SHARED; 1708 info->is_readonly = id->nsattr & NVME_NS_ATTR_RO; 1709 info->is_ready = id->nstat & NVME_NSTAT_NRDY; 1710 info->is_rotational = id->nsfeat & NVME_NS_ROTATIONAL; 1711 info->no_vwc = id->nsfeat & NVME_NS_VWC_NOT_PRESENT; 1712 info->endgid = le16_to_cpu(id->endgid); 1713 } 1714 kfree(id); 1715 return ret; 1716 } 1717 1718 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid, 1719 unsigned int dword11, void *buffer, size_t buflen, u32 *result) 1720 { 1721 union nvme_result res = { 0 }; 1722 struct nvme_command c = { }; 1723 int ret; 1724 1725 c.features.opcode = op; 1726 c.features.fid = cpu_to_le32(fid); 1727 c.features.dword11 = cpu_to_le32(dword11); 1728 1729 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, 1730 buffer, buflen, NVME_QID_ANY, 0); 1731 if (ret >= 0 && result) 1732 *result = le32_to_cpu(res.u32); 1733 return ret; 1734 } 1735 1736 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid, 1737 unsigned int dword11, void *buffer, size_t buflen, 1738 void *result) 1739 { 1740 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer, 1741 buflen, result); 1742 } 1743 EXPORT_SYMBOL_GPL(nvme_set_features); 1744 1745 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid, 1746 unsigned int dword11, void *buffer, size_t buflen, 1747 void *result) 1748 { 1749 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer, 1750 buflen, result); 1751 } 1752 EXPORT_SYMBOL_GPL(nvme_get_features); 1753 1754 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count) 1755 { 1756 u32 q_count = (*count - 1) | ((*count - 1) << 16); 1757 u32 result; 1758 int status, nr_io_queues; 1759 1760 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0, 1761 &result); 1762 1763 /* 1764 * It's either a kernel error or the host observed a connection 1765 * lost. In either case it's not possible communicate with the 1766 * controller and thus enter the error code path. 1767 */ 1768 if (status < 0 || status == NVME_SC_HOST_PATH_ERROR) 1769 return status; 1770 1771 /* 1772 * Degraded controllers might return an error when setting the queue 1773 * count. We still want to be able to bring them online and offer 1774 * access to the admin queue, as that might be only way to fix them up. 1775 */ 1776 if (status > 0) { 1777 dev_err(ctrl->device, "Could not set queue count (%d)\n", status); 1778 *count = 0; 1779 } else { 1780 nr_io_queues = min(result & 0xffff, result >> 16) + 1; 1781 *count = min(*count, nr_io_queues); 1782 } 1783 1784 return 0; 1785 } 1786 EXPORT_SYMBOL_GPL(nvme_set_queue_count); 1787 1788 #define NVME_AEN_SUPPORTED \ 1789 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \ 1790 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE) 1791 1792 static void nvme_enable_aen(struct nvme_ctrl *ctrl) 1793 { 1794 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED; 1795 int status; 1796 1797 if (!supported_aens) 1798 return; 1799 1800 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens, 1801 NULL, 0, &result); 1802 if (status) 1803 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n", 1804 supported_aens); 1805 1806 queue_work(nvme_wq, &ctrl->async_event_work); 1807 } 1808 1809 static int nvme_ns_open(struct nvme_ns *ns) 1810 { 1811 1812 /* should never be called due to GENHD_FL_HIDDEN */ 1813 if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head))) 1814 goto fail; 1815 if (!nvme_get_ns(ns)) 1816 goto fail; 1817 if (!try_module_get(ns->ctrl->ops->module)) 1818 goto fail_put_ns; 1819 1820 return 0; 1821 1822 fail_put_ns: 1823 nvme_put_ns(ns); 1824 fail: 1825 return -ENXIO; 1826 } 1827 1828 static void nvme_ns_release(struct nvme_ns *ns) 1829 { 1830 1831 module_put(ns->ctrl->ops->module); 1832 nvme_put_ns(ns); 1833 } 1834 1835 static int nvme_open(struct gendisk *disk, blk_mode_t mode) 1836 { 1837 return nvme_ns_open(disk->private_data); 1838 } 1839 1840 static void nvme_release(struct gendisk *disk) 1841 { 1842 nvme_ns_release(disk->private_data); 1843 } 1844 1845 int nvme_getgeo(struct gendisk *disk, struct hd_geometry *geo) 1846 { 1847 /* some standard values */ 1848 geo->heads = 1 << 6; 1849 geo->sectors = 1 << 5; 1850 geo->cylinders = get_capacity(disk) >> 11; 1851 return 0; 1852 } 1853 1854 static bool nvme_init_integrity(struct nvme_ns_head *head, 1855 struct queue_limits *lim, struct nvme_ns_info *info) 1856 { 1857 struct blk_integrity *bi = &lim->integrity; 1858 1859 memset(bi, 0, sizeof(*bi)); 1860 1861 if (!head->ms) 1862 return true; 1863 1864 /* 1865 * PI can always be supported as we can ask the controller to simply 1866 * insert/strip it, which is not possible for other kinds of metadata. 1867 */ 1868 if (!IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) || 1869 !(head->features & NVME_NS_METADATA_SUPPORTED)) 1870 return nvme_ns_has_pi(head); 1871 1872 switch (head->pi_type) { 1873 case NVME_NS_DPS_PI_TYPE3: 1874 switch (head->guard_type) { 1875 case NVME_NVM_NS_16B_GUARD: 1876 bi->csum_type = BLK_INTEGRITY_CSUM_CRC; 1877 bi->tag_size = sizeof(u16) + sizeof(u32); 1878 bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1879 break; 1880 case NVME_NVM_NS_64B_GUARD: 1881 bi->csum_type = BLK_INTEGRITY_CSUM_CRC64; 1882 bi->tag_size = sizeof(u16) + 6; 1883 bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1884 break; 1885 default: 1886 break; 1887 } 1888 break; 1889 case NVME_NS_DPS_PI_TYPE1: 1890 case NVME_NS_DPS_PI_TYPE2: 1891 switch (head->guard_type) { 1892 case NVME_NVM_NS_16B_GUARD: 1893 bi->csum_type = BLK_INTEGRITY_CSUM_CRC; 1894 bi->tag_size = sizeof(u16); 1895 bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE | 1896 BLK_INTEGRITY_REF_TAG; 1897 break; 1898 case NVME_NVM_NS_64B_GUARD: 1899 bi->csum_type = BLK_INTEGRITY_CSUM_CRC64; 1900 bi->tag_size = sizeof(u16); 1901 bi->flags |= BLK_INTEGRITY_DEVICE_CAPABLE | 1902 BLK_INTEGRITY_REF_TAG; 1903 break; 1904 default: 1905 break; 1906 } 1907 break; 1908 default: 1909 break; 1910 } 1911 1912 bi->flags |= BLK_SPLIT_INTERVAL_CAPABLE; 1913 bi->metadata_size = head->ms; 1914 if (bi->csum_type) { 1915 bi->pi_tuple_size = head->pi_size; 1916 bi->pi_offset = info->pi_offset; 1917 } 1918 return true; 1919 } 1920 1921 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b) 1922 { 1923 return uuid_equal(&a->uuid, &b->uuid) && 1924 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 && 1925 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 && 1926 a->csi == b->csi; 1927 } 1928 1929 static int nvme_identify_ns_nvm(struct nvme_ctrl *ctrl, unsigned int nsid, 1930 struct nvme_id_ns_nvm **nvmp) 1931 { 1932 struct nvme_command c = { 1933 .identify.opcode = nvme_admin_identify, 1934 .identify.nsid = cpu_to_le32(nsid), 1935 .identify.cns = NVME_ID_CNS_CS_NS, 1936 .identify.csi = NVME_CSI_NVM, 1937 }; 1938 struct nvme_id_ns_nvm *nvm; 1939 int ret; 1940 1941 nvm = kzalloc_obj(*nvm); 1942 if (!nvm) 1943 return -ENOMEM; 1944 1945 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, nvm, sizeof(*nvm)); 1946 if (ret) 1947 kfree(nvm); 1948 else 1949 *nvmp = nvm; 1950 return ret; 1951 } 1952 1953 static void nvme_configure_pi_elbas(struct nvme_ns_head *head, 1954 struct nvme_id_ns *id, struct nvme_id_ns_nvm *nvm) 1955 { 1956 u32 elbaf = le32_to_cpu(nvm->elbaf[nvme_lbaf_index(id->flbas)]); 1957 u8 guard_type; 1958 1959 /* no support for storage tag formats right now */ 1960 if (nvme_elbaf_sts(elbaf)) 1961 return; 1962 1963 guard_type = nvme_elbaf_guard_type(elbaf); 1964 if ((nvm->pic & NVME_ID_NS_NVM_QPIFS) && 1965 guard_type == NVME_NVM_NS_QTYPE_GUARD) 1966 guard_type = nvme_elbaf_qualified_guard_type(elbaf); 1967 1968 head->guard_type = guard_type; 1969 switch (head->guard_type) { 1970 case NVME_NVM_NS_64B_GUARD: 1971 head->pi_size = sizeof(struct crc64_pi_tuple); 1972 break; 1973 case NVME_NVM_NS_16B_GUARD: 1974 head->pi_size = sizeof(struct t10_pi_tuple); 1975 break; 1976 default: 1977 break; 1978 } 1979 } 1980 1981 static void nvme_configure_metadata(struct nvme_ctrl *ctrl, 1982 struct nvme_ns_head *head, struct nvme_id_ns *id, 1983 struct nvme_id_ns_nvm *nvm, struct nvme_ns_info *info) 1984 { 1985 head->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS); 1986 head->pi_type = 0; 1987 head->pi_size = 0; 1988 head->ms = le16_to_cpu(id->lbaf[nvme_lbaf_index(id->flbas)].ms); 1989 if (!head->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)) 1990 return; 1991 1992 if (nvm && (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)) { 1993 nvme_configure_pi_elbas(head, id, nvm); 1994 } else { 1995 head->pi_size = sizeof(struct t10_pi_tuple); 1996 head->guard_type = NVME_NVM_NS_16B_GUARD; 1997 } 1998 1999 if (head->pi_size && head->ms >= head->pi_size) 2000 head->pi_type = id->dps & NVME_NS_DPS_PI_MASK; 2001 if (!(id->dps & NVME_NS_DPS_PI_FIRST)) { 2002 if (disable_pi_offsets) 2003 head->pi_type = 0; 2004 else 2005 info->pi_offset = head->ms - head->pi_size; 2006 } 2007 2008 if (ctrl->ops->flags & NVME_F_FABRICS) { 2009 /* 2010 * The NVMe over Fabrics specification only supports metadata as 2011 * part of the extended data LBA. We rely on HCA/HBA support to 2012 * remap the separate metadata buffer from the block layer. 2013 */ 2014 if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT))) 2015 return; 2016 2017 head->features |= NVME_NS_EXT_LBAS; 2018 2019 /* 2020 * The current fabrics transport drivers support namespace 2021 * metadata formats only if nvme_ns_has_pi() returns true. 2022 * Suppress support for all other formats so the namespace will 2023 * have a 0 capacity and not be usable through the block stack. 2024 * 2025 * Note, this check will need to be modified if any drivers 2026 * gain the ability to use other metadata formats. 2027 */ 2028 if (ctrl->max_integrity_segments && nvme_ns_has_pi(head)) 2029 head->features |= NVME_NS_METADATA_SUPPORTED; 2030 } else { 2031 /* 2032 * For PCIe controllers, we can't easily remap the separate 2033 * metadata buffer from the block layer and thus require a 2034 * separate metadata buffer for block layer metadata/PI support. 2035 * We allow extended LBAs for the passthrough interface, though. 2036 */ 2037 if (id->flbas & NVME_NS_FLBAS_META_EXT) 2038 head->features |= NVME_NS_EXT_LBAS; 2039 else 2040 head->features |= NVME_NS_METADATA_SUPPORTED; 2041 } 2042 } 2043 2044 2045 static u32 nvme_configure_atomic_write(struct nvme_ns *ns, 2046 struct nvme_id_ns *id, struct queue_limits *lim, u32 bs) 2047 { 2048 u32 atomic_bs, boundary = 0; 2049 2050 /* 2051 * We do not support an offset for the atomic boundaries. 2052 */ 2053 if (id->nabo) 2054 return bs; 2055 2056 if ((id->nsfeat & NVME_NS_FEAT_ATOMICS) && id->nawupf) { 2057 /* 2058 * Use the per-namespace atomic write unit when available. 2059 */ 2060 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs; 2061 if (id->nabspf) 2062 boundary = (le16_to_cpu(id->nabspf) + 1) * bs; 2063 } else { 2064 if (ns->ctrl->awupf) 2065 dev_info_once(ns->ctrl->device, 2066 "AWUPF ignored, only NAWUPF accepted\n"); 2067 atomic_bs = bs; 2068 } 2069 2070 lim->atomic_write_hw_max = atomic_bs; 2071 lim->atomic_write_hw_boundary = boundary; 2072 lim->atomic_write_hw_unit_min = bs; 2073 lim->atomic_write_hw_unit_max = rounddown_pow_of_two(atomic_bs); 2074 lim->features |= BLK_FEAT_ATOMIC_WRITES; 2075 return atomic_bs; 2076 } 2077 2078 static u32 nvme_max_drv_segments(struct nvme_ctrl *ctrl) 2079 { 2080 return ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> SECTOR_SHIFT) + 1; 2081 } 2082 2083 static void nvme_set_ctrl_limits(struct nvme_ctrl *ctrl, 2084 struct queue_limits *lim, bool is_admin) 2085 { 2086 lim->max_hw_sectors = ctrl->max_hw_sectors; 2087 lim->max_segments = min_t(u32, USHRT_MAX, 2088 min_not_zero(nvme_max_drv_segments(ctrl), ctrl->max_segments)); 2089 lim->max_integrity_segments = ctrl->max_integrity_segments; 2090 lim->virt_boundary_mask = ctrl->ops->get_virt_boundary(ctrl, is_admin); 2091 lim->max_segment_size = UINT_MAX; 2092 if (is_admin && (ctrl->quirks & NVME_QUIRK_ADMIN_PAGE_ALIGN)) 2093 lim->dma_alignment = NVME_CTRL_PAGE_SIZE - 1; 2094 else 2095 lim->dma_alignment = 3; 2096 } 2097 2098 static bool nvme_update_disk_info(struct nvme_ns *ns, struct nvme_id_ns *id, 2099 struct nvme_id_ns_nvm *nvm, struct queue_limits *lim) 2100 { 2101 struct nvme_ns_head *head = ns->head; 2102 struct nvme_ctrl *ctrl = ns->ctrl; 2103 u32 bs = 1U << head->lba_shift; 2104 u32 atomic_bs, phys_bs, io_opt = 0; 2105 u32 npdg = 1, npda = 1; 2106 bool valid = true; 2107 u8 optperf; 2108 2109 /* 2110 * The block layer can't support LBA sizes larger than the page size 2111 * or smaller than a sector size yet, so catch this early and don't 2112 * allow block I/O. 2113 */ 2114 if (blk_validate_block_size(bs)) { 2115 bs = (1 << 9); 2116 valid = false; 2117 } 2118 2119 phys_bs = bs; 2120 atomic_bs = nvme_configure_atomic_write(ns, id, lim, bs); 2121 2122 optperf = id->nsfeat >> NVME_NS_FEAT_OPTPERF_SHIFT; 2123 if (ctrl->vs >= NVME_VS(2, 1, 0)) 2124 optperf &= NVME_NS_FEAT_OPTPERF_MASK_2_1; 2125 else 2126 optperf &= NVME_NS_FEAT_OPTPERF_MASK; 2127 if (optperf) { 2128 /* NPWG = Namespace Preferred Write Granularity */ 2129 phys_bs = bs * (1 + le16_to_cpu(id->npwg)); 2130 /* NOWS = Namespace Optimal Write Size */ 2131 if (id->nows) 2132 io_opt = bs * (1 + le16_to_cpu(id->nows)); 2133 } 2134 2135 /* 2136 * Linux filesystems assume writing a single physical block is 2137 * an atomic operation. Hence limit the physical block size to the 2138 * value of the Atomic Write Unit Power Fail parameter. 2139 */ 2140 lim->logical_block_size = bs; 2141 lim->physical_block_size = min(phys_bs, atomic_bs); 2142 lim->io_min = phys_bs; 2143 lim->io_opt = io_opt; 2144 if ((ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) && 2145 (ctrl->oncs & NVME_CTRL_ONCS_DSM)) 2146 lim->max_write_zeroes_sectors = UINT_MAX; 2147 else 2148 lim->max_write_zeroes_sectors = ctrl->max_zeroes_sectors; 2149 2150 if (ctrl->dmrsl && ctrl->dmrsl <= nvme_sect_to_lba(ns->head, UINT_MAX)) 2151 lim->max_hw_discard_sectors = 2152 nvme_lba_to_sect(ns->head, ctrl->dmrsl); 2153 else if (ctrl->oncs & NVME_CTRL_ONCS_DSM) 2154 lim->max_hw_discard_sectors = UINT_MAX; 2155 else 2156 lim->max_hw_discard_sectors = 0; 2157 2158 /* 2159 * NVMe namespaces advertise both a preferred deallocate granularity 2160 * (for a discard length) and alignment (for a discard starting offset). 2161 * However, Linux block devices advertise a single discard_granularity. 2162 * From NVM Command Set specification 1.1 section 5.2.2, the NPDGL/NPDAL 2163 * fields in the NVM Command Set Specific Identify Namespace structure 2164 * are preferred to NPDG/NPDA in the Identify Namespace structure since 2165 * they can represent larger values. However, NPDGL or NPDAL may be 0 if 2166 * unsupported. NPDG and NPDA are 0's based. 2167 * From Figure 115 of NVM Command Set specification 1.1, NPDGL and NPDAL 2168 * are supported if the high bit of OPTPERF is set. NPDG is supported if 2169 * the low bit of OPTPERF is set. NPDA is supported if either is set. 2170 * NPDG should be a multiple of NPDA, and likewise NPDGL should be a 2171 * multiple of NPDAL, but the spec doesn't say anything about NPDG vs. 2172 * NPDAL or NPDGL vs. NPDA. So compute the maximum instead of assuming 2173 * NPDG(L) is the larger. If neither NPDG, NPDGL, NPDA, nor NPDAL are 2174 * supported, default the discard_granularity to the logical block size. 2175 */ 2176 if (optperf & 0x2 && nvm && nvm->npdgl) 2177 npdg = le32_to_cpu(nvm->npdgl); 2178 else if (optperf & 0x1) 2179 npdg = from0based(id->npdg); 2180 if (optperf & 0x2 && nvm && nvm->npdal) 2181 npda = le32_to_cpu(nvm->npdal); 2182 else if (optperf) 2183 npda = from0based(id->npda); 2184 if (check_mul_overflow(max(npdg, npda), lim->logical_block_size, 2185 &lim->discard_granularity)) 2186 lim->discard_granularity = lim->logical_block_size; 2187 2188 if (ctrl->dmrl) 2189 lim->max_discard_segments = ctrl->dmrl; 2190 else 2191 lim->max_discard_segments = NVME_DSM_MAX_RANGES; 2192 return valid; 2193 } 2194 2195 static bool nvme_ns_is_readonly(struct nvme_ns *ns, struct nvme_ns_info *info) 2196 { 2197 return info->is_readonly || test_bit(NVME_NS_FORCE_RO, &ns->flags); 2198 } 2199 2200 static inline bool nvme_first_scan(struct gendisk *disk) 2201 { 2202 /* nvme_alloc_ns() scans the disk prior to adding it */ 2203 return !disk_live(disk); 2204 } 2205 2206 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id, 2207 struct queue_limits *lim) 2208 { 2209 struct nvme_ctrl *ctrl = ns->ctrl; 2210 u32 iob; 2211 2212 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) && 2213 is_power_of_2(ctrl->max_hw_sectors)) 2214 iob = ctrl->max_hw_sectors; 2215 else 2216 iob = nvme_lba_to_sect(ns->head, le16_to_cpu(id->noiob)); 2217 2218 if (!iob) 2219 return; 2220 2221 if (!is_power_of_2(iob)) { 2222 if (nvme_first_scan(ns->disk)) 2223 pr_warn("%s: ignoring unaligned IO boundary:%u\n", 2224 ns->disk->disk_name, iob); 2225 return; 2226 } 2227 2228 if (blk_queue_is_zoned(ns->disk->queue)) { 2229 if (nvme_first_scan(ns->disk)) 2230 pr_warn("%s: ignoring zoned namespace IO boundary\n", 2231 ns->disk->disk_name); 2232 return; 2233 } 2234 2235 lim->chunk_sectors = iob; 2236 } 2237 2238 static int nvme_update_ns_info_generic(struct nvme_ns *ns, 2239 struct nvme_ns_info *info) 2240 { 2241 struct queue_limits lim; 2242 unsigned int memflags; 2243 int ret; 2244 2245 lim = queue_limits_start_update(ns->disk->queue); 2246 nvme_set_ctrl_limits(ns->ctrl, &lim, false); 2247 2248 memflags = blk_mq_freeze_queue(ns->disk->queue); 2249 ret = queue_limits_commit_update(ns->disk->queue, &lim); 2250 set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info)); 2251 blk_mq_unfreeze_queue(ns->disk->queue, memflags); 2252 2253 /* Hide the block-interface for these devices */ 2254 if (!ret) 2255 ret = -ENODEV; 2256 return ret; 2257 } 2258 2259 static int nvme_query_fdp_granularity(struct nvme_ctrl *ctrl, 2260 struct nvme_ns_info *info, u8 fdp_idx) 2261 { 2262 struct nvme_fdp_config_log hdr, *h; 2263 struct nvme_fdp_config_desc *desc; 2264 size_t size = sizeof(hdr); 2265 void *log, *end; 2266 int i, n, ret; 2267 2268 ret = nvme_get_log_lsi(ctrl, 0, NVME_LOG_FDP_CONFIGS, 0, 2269 NVME_CSI_NVM, &hdr, size, 0, info->endgid); 2270 if (ret) { 2271 dev_warn(ctrl->device, 2272 "FDP configs log header status:0x%x endgid:%d\n", ret, 2273 info->endgid); 2274 return ret; 2275 } 2276 2277 size = le32_to_cpu(hdr.sze); 2278 if (size > PAGE_SIZE * MAX_ORDER_NR_PAGES) { 2279 dev_warn(ctrl->device, "FDP config size too large:%zu\n", 2280 size); 2281 return 0; 2282 } 2283 2284 h = kvmalloc(size, GFP_KERNEL); 2285 if (!h) 2286 return -ENOMEM; 2287 2288 ret = nvme_get_log_lsi(ctrl, 0, NVME_LOG_FDP_CONFIGS, 0, 2289 NVME_CSI_NVM, h, size, 0, info->endgid); 2290 if (ret) { 2291 dev_warn(ctrl->device, 2292 "FDP configs log status:0x%x endgid:%d\n", ret, 2293 info->endgid); 2294 goto out; 2295 } 2296 2297 n = le16_to_cpu(h->numfdpc) + 1; 2298 if (fdp_idx >= n) { 2299 dev_warn(ctrl->device, "FDP index:%d out of range:%d\n", 2300 fdp_idx, n); 2301 /* Proceed without registering FDP streams */ 2302 ret = 0; 2303 goto out; 2304 } 2305 2306 log = h + 1; 2307 desc = log; 2308 end = log + size - sizeof(*h); 2309 for (i = 0; i < fdp_idx; i++) { 2310 u16 dsze = le16_to_cpu(desc->dsze); 2311 2312 if (!dsze || log + dsze > end) { 2313 dev_warn(ctrl->device, 2314 "FDP invalid config descriptor at index %d\n", i); 2315 ret = 0; 2316 goto out; 2317 } 2318 log += dsze; 2319 desc = log; 2320 } 2321 2322 if (le32_to_cpu(desc->nrg) > 1) { 2323 dev_warn(ctrl->device, "FDP NRG > 1 not supported\n"); 2324 ret = 0; 2325 goto out; 2326 } 2327 2328 info->runs = le64_to_cpu(desc->runs); 2329 out: 2330 kvfree(h); 2331 return ret; 2332 } 2333 2334 static int nvme_query_fdp_info(struct nvme_ns *ns, struct nvme_ns_info *info) 2335 { 2336 struct nvme_ns_head *head = ns->head; 2337 struct nvme_ctrl *ctrl = ns->ctrl; 2338 struct nvme_fdp_ruh_status *ruhs; 2339 struct nvme_fdp_config fdp; 2340 struct nvme_command c = {}; 2341 size_t size; 2342 int i, ret; 2343 2344 /* 2345 * The FDP configuration is static for the lifetime of the namespace, 2346 * so return immediately if we've already registered this namespace's 2347 * streams. 2348 */ 2349 if (head->nr_plids) 2350 return 0; 2351 2352 ret = nvme_get_features(ctrl, NVME_FEAT_FDP, info->endgid, NULL, 0, 2353 &fdp); 2354 if (ret) { 2355 dev_warn(ctrl->device, "FDP get feature status:0x%x\n", ret); 2356 return ret; 2357 } 2358 2359 if (!(fdp.flags & FDPCFG_FDPE)) 2360 return 0; 2361 2362 ret = nvme_query_fdp_granularity(ctrl, info, fdp.fdpcidx); 2363 if (!info->runs) 2364 return ret; 2365 2366 size = struct_size(ruhs, ruhsd, NVME_MAX_PLIDS); 2367 ruhs = kzalloc(size, GFP_KERNEL); 2368 if (!ruhs) 2369 return -ENOMEM; 2370 2371 c.imr.opcode = nvme_cmd_io_mgmt_recv; 2372 c.imr.nsid = cpu_to_le32(head->ns_id); 2373 c.imr.mo = NVME_IO_MGMT_RECV_MO_RUHS; 2374 c.imr.numd = cpu_to_le32(nvme_bytes_to_numd(size)); 2375 ret = nvme_submit_sync_cmd(ns->queue, &c, ruhs, size); 2376 if (ret) { 2377 dev_warn(ctrl->device, "FDP io-mgmt status:0x%x\n", ret); 2378 goto free; 2379 } 2380 2381 head->nr_plids = min(le16_to_cpu(ruhs->nruhsd), NVME_MAX_PLIDS); 2382 if (!head->nr_plids) 2383 goto free; 2384 2385 head->plids = kcalloc(head->nr_plids, sizeof(*head->plids), 2386 GFP_KERNEL); 2387 if (!head->plids) { 2388 dev_warn(ctrl->device, 2389 "failed to allocate %u FDP placement IDs\n", 2390 head->nr_plids); 2391 head->nr_plids = 0; 2392 ret = -ENOMEM; 2393 goto free; 2394 } 2395 2396 for (i = 0; i < head->nr_plids; i++) 2397 head->plids[i] = le16_to_cpu(ruhs->ruhsd[i].pid); 2398 free: 2399 kfree(ruhs); 2400 return ret; 2401 } 2402 2403 static bool nvme_invalid_lba_sz(u64 nsze, signed int shift, sector_t *capacity) 2404 { 2405 return check_shl_overflow(nsze, shift, capacity); 2406 } 2407 2408 static int nvme_update_ns_info_block(struct nvme_ns *ns, 2409 struct nvme_ns_info *info) 2410 { 2411 struct queue_limits lim; 2412 struct nvme_id_ns_nvm *nvm = NULL; 2413 struct nvme_zone_info zi = {}; 2414 struct nvme_id_ns *id; 2415 unsigned int memflags; 2416 sector_t capacity; 2417 unsigned lbaf; 2418 int ret; 2419 2420 ret = nvme_identify_ns(ns->ctrl, info->nsid, &id); 2421 if (ret) 2422 return ret; 2423 2424 if (id->ncap == 0) { 2425 /* namespace not allocated or attached */ 2426 info->is_removed = true; 2427 ret = -ENXIO; 2428 goto out; 2429 } 2430 lbaf = nvme_lbaf_index(id->flbas); 2431 2432 if (nvme_id_cns_ok(ns->ctrl, NVME_ID_CNS_CS_NS)) { 2433 ret = nvme_identify_ns_nvm(ns->ctrl, info->nsid, &nvm); 2434 if (ret < 0) 2435 goto out; 2436 } 2437 2438 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) && 2439 ns->head->ids.csi == NVME_CSI_ZNS) { 2440 ret = nvme_query_zone_info(ns, lbaf, &zi); 2441 if (ret < 0) 2442 goto out; 2443 } 2444 2445 if (ns->ctrl->ctratt & NVME_CTRL_ATTR_FDPS) { 2446 ret = nvme_query_fdp_info(ns, info); 2447 if (ret < 0) 2448 goto out; 2449 } 2450 2451 if (nvme_invalid_lba_sz(le64_to_cpu(id->nsze), 2452 id->lbaf[lbaf].ds - SECTOR_SHIFT, &capacity)) { 2453 dev_warn_once(ns->ctrl->device, 2454 "invalid LBA data size %u, skipping namespace\n", 2455 id->lbaf[lbaf].ds); 2456 ret = -ENODEV; 2457 goto out; 2458 } 2459 2460 lim = queue_limits_start_update(ns->disk->queue); 2461 2462 memflags = blk_mq_freeze_queue(ns->disk->queue); 2463 ns->head->lba_shift = id->lbaf[lbaf].ds; 2464 ns->head->nuse = le64_to_cpu(id->nuse); 2465 nvme_set_ctrl_limits(ns->ctrl, &lim, false); 2466 nvme_configure_metadata(ns->ctrl, ns->head, id, nvm, info); 2467 nvme_set_chunk_sectors(ns, id, &lim); 2468 if (!nvme_update_disk_info(ns, id, nvm, &lim)) 2469 capacity = 0; 2470 2471 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) && 2472 ns->head->ids.csi == NVME_CSI_ZNS) 2473 nvme_update_zone_info(ns, &lim, &zi); 2474 2475 if ((ns->ctrl->vwc & NVME_CTRL_VWC_PRESENT) && !info->no_vwc) 2476 lim.features |= BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA; 2477 else 2478 lim.features &= ~(BLK_FEAT_WRITE_CACHE | BLK_FEAT_FUA); 2479 2480 if (info->is_rotational) 2481 lim.features |= BLK_FEAT_ROTATIONAL; 2482 2483 /* 2484 * Register a metadata profile for PI, or the plain non-integrity NVMe 2485 * metadata masquerading as Type 0 if supported, otherwise reject block 2486 * I/O to namespaces with metadata except when the namespace supports 2487 * PI, as it can strip/insert in that case. 2488 */ 2489 if (!nvme_init_integrity(ns->head, &lim, info)) 2490 capacity = 0; 2491 2492 lim.max_write_streams = ns->head->nr_plids; 2493 if (lim.max_write_streams) 2494 lim.write_stream_granularity = min(info->runs, U32_MAX); 2495 else 2496 lim.write_stream_granularity = 0; 2497 2498 /* 2499 * Only set the DEAC bit if the device guarantees that reads from 2500 * deallocated data return zeroes. While the DEAC bit does not 2501 * require that, it must be a no-op if reads from deallocated data 2502 * do not return zeroes. 2503 */ 2504 if ((id->dlfeat & 0x7) == 0x1 && (id->dlfeat & (1 << 3))) { 2505 ns->head->features |= NVME_NS_DEAC; 2506 lim.max_hw_wzeroes_unmap_sectors = lim.max_write_zeroes_sectors; 2507 } 2508 2509 ret = queue_limits_commit_update(ns->disk->queue, &lim); 2510 if (ret) { 2511 blk_mq_unfreeze_queue(ns->disk->queue, memflags); 2512 goto out; 2513 } 2514 2515 set_capacity_and_notify(ns->disk, capacity); 2516 set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info)); 2517 set_bit(NVME_NS_READY, &ns->flags); 2518 blk_mq_unfreeze_queue(ns->disk->queue, memflags); 2519 2520 if (blk_queue_is_zoned(ns->queue)) { 2521 ret = blk_revalidate_disk_zones(ns->disk); 2522 if (ret && !nvme_first_scan(ns->disk)) 2523 goto out; 2524 } 2525 2526 ret = 0; 2527 out: 2528 kfree(nvm); 2529 kfree(id); 2530 return ret; 2531 } 2532 2533 static void nvme_stack_zone_resources(struct queue_limits *t, 2534 const struct queue_limits *b) 2535 { 2536 t->max_open_zones = min_not_zero(t->max_open_zones, b->max_open_zones); 2537 t->max_active_zones = 2538 min_not_zero(t->max_active_zones, b->max_active_zones); 2539 } 2540 2541 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_ns_info *info) 2542 { 2543 bool unsupported = false; 2544 int ret; 2545 2546 switch (info->ids.csi) { 2547 case NVME_CSI_ZNS: 2548 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) { 2549 dev_info(ns->ctrl->device, 2550 "block device for nsid %u not supported without CONFIG_BLK_DEV_ZONED\n", 2551 info->nsid); 2552 ret = nvme_update_ns_info_generic(ns, info); 2553 break; 2554 } 2555 ret = nvme_update_ns_info_block(ns, info); 2556 break; 2557 case NVME_CSI_NVM: 2558 ret = nvme_update_ns_info_block(ns, info); 2559 break; 2560 default: 2561 dev_info(ns->ctrl->device, 2562 "block device for nsid %u not supported (csi %u)\n", 2563 info->nsid, info->ids.csi); 2564 ret = nvme_update_ns_info_generic(ns, info); 2565 break; 2566 } 2567 2568 /* 2569 * If probing fails due an unsupported feature, hide the block device, 2570 * but still allow other access. 2571 */ 2572 if (ret == -ENODEV) { 2573 ns->disk->flags |= GENHD_FL_HIDDEN; 2574 set_bit(NVME_NS_READY, &ns->flags); 2575 unsupported = true; 2576 ret = 0; 2577 } 2578 2579 if (!ret && nvme_ns_head_multipath(ns->head)) { 2580 struct queue_limits *ns_lim = &ns->disk->queue->limits; 2581 struct queue_limits lim; 2582 unsigned int memflags; 2583 2584 lim = queue_limits_start_update(ns->head->disk->queue); 2585 memflags = blk_mq_freeze_queue(ns->head->disk->queue); 2586 /* 2587 * queue_limits mixes values that are the hardware limitations 2588 * for bio splitting with what is the device configuration. 2589 * 2590 * For NVMe the device configuration can change after e.g. a 2591 * Format command, and we really want to pick up the new format 2592 * value here. But we must still stack the queue limits to the 2593 * least common denominator for multipathing to split the bios 2594 * properly. 2595 * 2596 * To work around this, we explicitly set the device 2597 * configuration to those that we just queried, but only stack 2598 * the splitting limits in to make sure we still obey possibly 2599 * lower limitations of other controllers. 2600 */ 2601 lim.logical_block_size = ns_lim->logical_block_size; 2602 lim.physical_block_size = ns_lim->physical_block_size; 2603 lim.io_min = ns_lim->io_min; 2604 lim.io_opt = ns_lim->io_opt; 2605 queue_limits_stack_bdev(&lim, ns->disk->part0, 0, 2606 ns->head->disk->disk_name); 2607 if (lim.features & BLK_FEAT_ZONED) 2608 nvme_stack_zone_resources(&lim, ns_lim); 2609 if (unsupported) 2610 ns->head->disk->flags |= GENHD_FL_HIDDEN; 2611 else 2612 nvme_init_integrity(ns->head, &lim, info); 2613 lim.max_write_streams = ns_lim->max_write_streams; 2614 lim.write_stream_granularity = ns_lim->write_stream_granularity; 2615 ret = queue_limits_commit_update(ns->head->disk->queue, &lim); 2616 if (ret) 2617 goto unfreeze_head_queue; 2618 2619 set_capacity_and_notify(ns->head->disk, get_capacity(ns->disk)); 2620 set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info)); 2621 nvme_mpath_revalidate_paths(ns->head); 2622 ret = nvme_mpath_revalidate_zones(ns->head); 2623 2624 unfreeze_head_queue: 2625 blk_mq_unfreeze_queue(ns->head->disk->queue, memflags); 2626 } 2627 2628 return ret; 2629 } 2630 2631 int nvme_ns_get_unique_id(struct nvme_ns *ns, u8 id[16], 2632 enum blk_unique_id type) 2633 { 2634 struct nvme_ns_ids *ids = &ns->head->ids; 2635 2636 if (type != BLK_UID_EUI64) 2637 return -EINVAL; 2638 2639 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) { 2640 memcpy(id, &ids->nguid, sizeof(ids->nguid)); 2641 return sizeof(ids->nguid); 2642 } 2643 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) { 2644 memcpy(id, &ids->eui64, sizeof(ids->eui64)); 2645 return sizeof(ids->eui64); 2646 } 2647 2648 return -EINVAL; 2649 } 2650 2651 static int nvme_get_unique_id(struct gendisk *disk, u8 id[16], 2652 enum blk_unique_id type) 2653 { 2654 return nvme_ns_get_unique_id(disk->private_data, id, type); 2655 } 2656 2657 #ifdef CONFIG_BLK_SED_OPAL 2658 static int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len, 2659 bool send) 2660 { 2661 struct nvme_ctrl *ctrl = data; 2662 struct nvme_command cmd = { }; 2663 2664 if (send) 2665 cmd.common.opcode = nvme_admin_security_send; 2666 else 2667 cmd.common.opcode = nvme_admin_security_recv; 2668 cmd.common.nsid = 0; 2669 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8); 2670 cmd.common.cdw11 = cpu_to_le32(len); 2671 2672 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 2673 NVME_QID_ANY, NVME_SUBMIT_AT_HEAD); 2674 } 2675 2676 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended) 2677 { 2678 if (ctrl->oacs & NVME_CTRL_OACS_SEC_SUPP) { 2679 if (!ctrl->opal_dev) 2680 ctrl->opal_dev = init_opal_dev(ctrl, &nvme_sec_submit); 2681 else if (was_suspended) 2682 opal_unlock_from_suspend(ctrl->opal_dev); 2683 } else { 2684 free_opal_dev(ctrl->opal_dev); 2685 ctrl->opal_dev = NULL; 2686 } 2687 } 2688 #else 2689 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended) 2690 { 2691 } 2692 #endif /* CONFIG_BLK_SED_OPAL */ 2693 2694 #ifdef CONFIG_BLK_DEV_ZONED 2695 static int nvme_report_zones(struct gendisk *disk, sector_t sector, 2696 unsigned int nr_zones, struct blk_report_zones_args *args) 2697 { 2698 return nvme_ns_report_zones(disk->private_data, sector, nr_zones, args); 2699 } 2700 #else 2701 #define nvme_report_zones NULL 2702 #endif /* CONFIG_BLK_DEV_ZONED */ 2703 2704 const struct block_device_operations nvme_bdev_ops = { 2705 .owner = THIS_MODULE, 2706 .ioctl = nvme_ioctl, 2707 .compat_ioctl = blkdev_compat_ptr_ioctl, 2708 .open = nvme_open, 2709 .release = nvme_release, 2710 .getgeo = nvme_getgeo, 2711 .get_unique_id = nvme_get_unique_id, 2712 .report_zones = nvme_report_zones, 2713 .pr_ops = &nvme_pr_ops, 2714 }; 2715 2716 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u32 mask, u32 val, 2717 u32 timeout, const char *op) 2718 { 2719 unsigned long timeout_jiffies = jiffies + timeout * HZ; 2720 u32 csts; 2721 int ret; 2722 2723 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) { 2724 if (csts == ~0) 2725 return -ENODEV; 2726 if ((csts & mask) == val) 2727 break; 2728 2729 usleep_range(1000, 2000); 2730 if (fatal_signal_pending(current)) 2731 return -EINTR; 2732 if (time_after(jiffies, timeout_jiffies)) { 2733 dev_err(ctrl->device, 2734 "Device not ready; aborting %s, CSTS=0x%x\n", 2735 op, csts); 2736 return -ENODEV; 2737 } 2738 } 2739 2740 return ret; 2741 } 2742 2743 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, bool shutdown) 2744 { 2745 int ret; 2746 2747 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK; 2748 if (shutdown) 2749 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL; 2750 else 2751 ctrl->ctrl_config &= ~NVME_CC_ENABLE; 2752 2753 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2754 if (ret) 2755 return ret; 2756 2757 if (shutdown) { 2758 return nvme_wait_ready(ctrl, NVME_CSTS_SHST_MASK, 2759 NVME_CSTS_SHST_CMPLT, 2760 ctrl->shutdown_timeout, "shutdown"); 2761 } 2762 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY) 2763 msleep(NVME_QUIRK_DELAY_AMOUNT); 2764 return nvme_wait_ready(ctrl, NVME_CSTS_RDY, 0, 2765 (NVME_CAP_TIMEOUT(ctrl->cap) + 1) / 2, "reset"); 2766 } 2767 EXPORT_SYMBOL_GPL(nvme_disable_ctrl); 2768 2769 int nvme_enable_ctrl(struct nvme_ctrl *ctrl) 2770 { 2771 unsigned dev_page_min; 2772 u32 timeout; 2773 int ret; 2774 2775 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap); 2776 if (ret) { 2777 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret); 2778 return ret; 2779 } 2780 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12; 2781 2782 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) { 2783 dev_err(ctrl->device, 2784 "Minimum device page size %u too large for host (%u)\n", 2785 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT); 2786 return -ENODEV; 2787 } 2788 2789 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI) 2790 ctrl->ctrl_config = NVME_CC_CSS_CSI; 2791 else 2792 ctrl->ctrl_config = NVME_CC_CSS_NVM; 2793 2794 /* 2795 * Setting CRIME results in CSTS.RDY before the media is ready. This 2796 * makes it possible for media related commands to return the error 2797 * NVME_SC_ADMIN_COMMAND_MEDIA_NOT_READY. Until the driver is 2798 * restructured to handle retries, disable CC.CRIME. 2799 */ 2800 ctrl->ctrl_config &= ~NVME_CC_CRIME; 2801 2802 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT; 2803 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE; 2804 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES; 2805 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2806 if (ret) 2807 return ret; 2808 2809 /* CAP value may change after initial CC write */ 2810 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap); 2811 if (ret) 2812 return ret; 2813 2814 timeout = NVME_CAP_TIMEOUT(ctrl->cap); 2815 if (ctrl->cap & NVME_CAP_CRMS_CRWMS) { 2816 u32 crto, ready_timeout; 2817 2818 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CRTO, &crto); 2819 if (ret) { 2820 dev_err(ctrl->device, "Reading CRTO failed (%d)\n", 2821 ret); 2822 return ret; 2823 } 2824 2825 /* 2826 * CRTO should always be greater or equal to CAP.TO, but some 2827 * devices are known to get this wrong. Use the larger of the 2828 * two values. 2829 */ 2830 ready_timeout = NVME_CRTO_CRWMT(crto); 2831 2832 if (ready_timeout < timeout) 2833 dev_warn_once(ctrl->device, "bad crto:%x cap:%llx\n", 2834 crto, ctrl->cap); 2835 else 2836 timeout = ready_timeout; 2837 } 2838 2839 ctrl->ctrl_config |= NVME_CC_ENABLE; 2840 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 2841 if (ret) 2842 return ret; 2843 return nvme_wait_ready(ctrl, NVME_CSTS_RDY, NVME_CSTS_RDY, 2844 (timeout + 1) / 2, "initialisation"); 2845 } 2846 EXPORT_SYMBOL_GPL(nvme_enable_ctrl); 2847 2848 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl) 2849 { 2850 __le64 ts; 2851 int ret; 2852 2853 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP)) 2854 return 0; 2855 2856 ts = cpu_to_le64(ktime_to_ms(ktime_get_real())); 2857 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts), 2858 NULL); 2859 if (ret) 2860 dev_warn_once(ctrl->device, 2861 "could not set timestamp (%d)\n", ret); 2862 return ret; 2863 } 2864 2865 static int nvme_configure_host_options(struct nvme_ctrl *ctrl) 2866 { 2867 struct nvme_feat_host_behavior *host; 2868 u8 acre = 0, lbafee = 0; 2869 int ret; 2870 2871 /* Don't bother enabling the feature if retry delay is not reported */ 2872 if (ctrl->crdt[0]) 2873 acre = NVME_ENABLE_ACRE; 2874 if (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS) 2875 lbafee = NVME_ENABLE_LBAFEE; 2876 2877 if (!acre && !lbafee) 2878 return 0; 2879 2880 host = kzalloc_obj(*host); 2881 if (!host) 2882 return 0; 2883 2884 host->acre = acre; 2885 host->lbafee = lbafee; 2886 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0, 2887 host, sizeof(*host), NULL); 2888 kfree(host); 2889 return ret; 2890 } 2891 2892 /* 2893 * The function checks whether the given total (exlat + enlat) latency of 2894 * a power state allows the latter to be used as an APST transition target. 2895 * It does so by comparing the latency to the primary and secondary latency 2896 * tolerances defined by module params. If there's a match, the corresponding 2897 * timeout value is returned and the matching tolerance index (1 or 2) is 2898 * reported. 2899 */ 2900 static bool nvme_apst_get_transition_time(u64 total_latency, 2901 u64 *transition_time, unsigned *last_index) 2902 { 2903 if (total_latency <= apst_primary_latency_tol_us) { 2904 if (*last_index == 1) 2905 return false; 2906 *last_index = 1; 2907 *transition_time = apst_primary_timeout_ms; 2908 return true; 2909 } 2910 if (apst_secondary_timeout_ms && 2911 total_latency <= apst_secondary_latency_tol_us) { 2912 if (*last_index <= 2) 2913 return false; 2914 *last_index = 2; 2915 *transition_time = apst_secondary_timeout_ms; 2916 return true; 2917 } 2918 return false; 2919 } 2920 2921 /* 2922 * APST (Autonomous Power State Transition) lets us program a table of power 2923 * state transitions that the controller will perform automatically. 2924 * 2925 * Depending on module params, one of the two supported techniques will be used: 2926 * 2927 * - If the parameters provide explicit timeouts and tolerances, they will be 2928 * used to build a table with up to 2 non-operational states to transition to. 2929 * The default parameter values were selected based on the values used by 2930 * Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic 2931 * regeneration of the APST table in the event of switching between external 2932 * and battery power, the timeouts and tolerances reflect a compromise 2933 * between values used by Microsoft for AC and battery scenarios. 2934 * - If not, we'll configure the table with a simple heuristic: we are willing 2935 * to spend at most 2% of the time transitioning between power states. 2936 * Therefore, when running in any given state, we will enter the next 2937 * lower-power non-operational state after waiting 50 * (enlat + exlat) 2938 * microseconds, as long as that state's exit latency is under the requested 2939 * maximum latency. 2940 * 2941 * We will not autonomously enter any non-operational state for which the total 2942 * latency exceeds ps_max_latency_us. 2943 * 2944 * Users can set ps_max_latency_us to zero to turn off APST. 2945 */ 2946 static int nvme_configure_apst(struct nvme_ctrl *ctrl) 2947 { 2948 struct nvme_feat_auto_pst *table; 2949 unsigned apste = 0; 2950 u64 max_lat_us = 0; 2951 __le64 target = 0; 2952 int max_ps = -1; 2953 int state; 2954 int ret; 2955 unsigned last_lt_index = UINT_MAX; 2956 2957 /* 2958 * If APST isn't supported or if we haven't been initialized yet, 2959 * then don't do anything. 2960 */ 2961 if (!ctrl->apsta) 2962 return 0; 2963 2964 if (ctrl->npss > 31) { 2965 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n"); 2966 return 0; 2967 } 2968 2969 table = kzalloc_obj(*table); 2970 if (!table) 2971 return 0; 2972 2973 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) { 2974 /* Turn off APST. */ 2975 dev_dbg(ctrl->device, "APST disabled\n"); 2976 goto done; 2977 } 2978 2979 /* 2980 * Walk through all states from lowest- to highest-power. 2981 * According to the spec, lower-numbered states use more power. NPSS, 2982 * despite the name, is the index of the lowest-power state, not the 2983 * number of states. 2984 */ 2985 for (state = (int)ctrl->npss; state >= 0; state--) { 2986 u64 total_latency_us, exit_latency_us, transition_ms; 2987 2988 if (target) 2989 table->entries[state] = target; 2990 2991 /* 2992 * Don't allow transitions to the deepest state if it's quirked 2993 * off. 2994 */ 2995 if (state == ctrl->npss && 2996 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) 2997 continue; 2998 2999 /* 3000 * Is this state a useful non-operational state for higher-power 3001 * states to autonomously transition to? 3002 */ 3003 if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE)) 3004 continue; 3005 3006 exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat); 3007 if (exit_latency_us > ctrl->ps_max_latency_us) 3008 continue; 3009 3010 total_latency_us = exit_latency_us + 3011 le32_to_cpu(ctrl->psd[state].entry_lat); 3012 3013 /* 3014 * This state is good. It can be used as the APST idle target 3015 * for higher power states. 3016 */ 3017 if (apst_primary_timeout_ms && apst_primary_latency_tol_us) { 3018 if (!nvme_apst_get_transition_time(total_latency_us, 3019 &transition_ms, &last_lt_index)) 3020 continue; 3021 } else { 3022 transition_ms = total_latency_us + 19; 3023 do_div(transition_ms, 20); 3024 if (transition_ms > (1 << 24) - 1) 3025 transition_ms = (1 << 24) - 1; 3026 } 3027 3028 target = cpu_to_le64((state << 3) | (transition_ms << 8)); 3029 if (max_ps == -1) 3030 max_ps = state; 3031 if (total_latency_us > max_lat_us) 3032 max_lat_us = total_latency_us; 3033 } 3034 3035 if (max_ps == -1) 3036 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n"); 3037 else 3038 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n", 3039 max_ps, max_lat_us, (int)sizeof(*table), table); 3040 apste = 1; 3041 3042 done: 3043 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste, 3044 table, sizeof(*table), NULL); 3045 if (ret) 3046 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret); 3047 kfree(table); 3048 return ret; 3049 } 3050 3051 static void nvme_set_latency_tolerance(struct device *dev, s32 val) 3052 { 3053 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 3054 u64 latency; 3055 3056 switch (val) { 3057 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT: 3058 case PM_QOS_LATENCY_ANY: 3059 latency = U64_MAX; 3060 break; 3061 3062 default: 3063 latency = val; 3064 } 3065 3066 if (ctrl->ps_max_latency_us != latency) { 3067 ctrl->ps_max_latency_us = latency; 3068 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE) 3069 nvme_configure_apst(ctrl); 3070 } 3071 } 3072 3073 struct nvme_core_quirk_entry { 3074 /* 3075 * NVMe model and firmware strings are padded with spaces. For 3076 * simplicity, strings in the quirk table are padded with NULLs 3077 * instead. 3078 */ 3079 u16 vid; 3080 const char *mn; 3081 const char *fr; 3082 unsigned long quirks; 3083 }; 3084 3085 static const struct nvme_core_quirk_entry core_quirks[] = { 3086 { 3087 /* 3088 * This Toshiba device seems to die using any APST states. See: 3089 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11 3090 */ 3091 .vid = 0x1179, 3092 .mn = "THNSF5256GPUK TOSHIBA", 3093 .quirks = NVME_QUIRK_NO_APST, 3094 }, 3095 { 3096 /* 3097 * This LiteON CL1-3D*-Q11 firmware version has a race 3098 * condition associated with actions related to suspend to idle 3099 * LiteON has resolved the problem in future firmware 3100 */ 3101 .vid = 0x14a4, 3102 .fr = "22301111", 3103 .quirks = NVME_QUIRK_SIMPLE_SUSPEND, 3104 }, 3105 { 3106 /* 3107 * This Kioxia CD6-V Series / HPE PE8030 device times out and 3108 * aborts I/O during any load, but more easily reproducible 3109 * with discards (fstrim). 3110 * 3111 * The device is left in a state where it is also not possible 3112 * to use "nvme set-feature" to disable APST, but booting with 3113 * nvme_core.default_ps_max_latency_us=0 works. 3114 */ 3115 .vid = 0x1e0f, 3116 .mn = "KCD6XVUL6T40", 3117 .quirks = NVME_QUIRK_NO_APST, 3118 }, 3119 { 3120 /* 3121 * The external Samsung X5 SSD fails initialization without a 3122 * delay before checking if it is ready and has a whole set of 3123 * other problems. To make this even more interesting, it 3124 * shares the PCI ID with internal Samsung 970 Evo Plus that 3125 * does not need or want these quirks. 3126 */ 3127 .vid = 0x144d, 3128 .mn = "Samsung Portable SSD X5", 3129 .quirks = NVME_QUIRK_DELAY_BEFORE_CHK_RDY | 3130 NVME_QUIRK_NO_DEEPEST_PS | 3131 NVME_QUIRK_IGNORE_DEV_SUBNQN, 3132 } 3133 }; 3134 3135 /* match is null-terminated but idstr is space-padded. */ 3136 static bool string_matches(const char *idstr, const char *match, size_t len) 3137 { 3138 size_t matchlen; 3139 3140 if (!match) 3141 return true; 3142 3143 matchlen = strlen(match); 3144 WARN_ON_ONCE(matchlen > len); 3145 3146 if (memcmp(idstr, match, matchlen)) 3147 return false; 3148 3149 for (; matchlen < len; matchlen++) 3150 if (idstr[matchlen] != ' ') 3151 return false; 3152 3153 return true; 3154 } 3155 3156 static bool quirk_matches(const struct nvme_id_ctrl *id, 3157 const struct nvme_core_quirk_entry *q) 3158 { 3159 return q->vid == le16_to_cpu(id->vid) && 3160 string_matches(id->mn, q->mn, sizeof(id->mn)) && 3161 string_matches(id->fr, q->fr, sizeof(id->fr)); 3162 } 3163 3164 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl, 3165 struct nvme_id_ctrl *id) 3166 { 3167 size_t nqnlen; 3168 int off; 3169 3170 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) { 3171 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE); 3172 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) { 3173 strscpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE); 3174 return; 3175 } 3176 3177 if (ctrl->vs >= NVME_VS(1, 2, 1)) 3178 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n"); 3179 } 3180 3181 /* 3182 * Generate a "fake" NQN similar to the one in Section 4.5 of the NVMe 3183 * Base Specification 2.0. It is slightly different from the format 3184 * specified there due to historic reasons, and we can't change it now. 3185 */ 3186 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE, 3187 "nqn.2014.08.org.nvmexpress:%04x%04x", 3188 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid)); 3189 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn)); 3190 off += sizeof(id->sn); 3191 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn)); 3192 off += sizeof(id->mn); 3193 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off); 3194 } 3195 3196 static void nvme_release_subsystem(struct device *dev) 3197 { 3198 struct nvme_subsystem *subsys = 3199 container_of(dev, struct nvme_subsystem, dev); 3200 3201 if (subsys->instance >= 0) 3202 ida_free(&nvme_instance_ida, subsys->instance); 3203 kfree(subsys); 3204 } 3205 3206 static void nvme_destroy_subsystem(struct kref *ref) 3207 { 3208 struct nvme_subsystem *subsys = 3209 container_of(ref, struct nvme_subsystem, ref); 3210 3211 mutex_lock(&nvme_subsystems_lock); 3212 list_del(&subsys->entry); 3213 mutex_unlock(&nvme_subsystems_lock); 3214 3215 ida_destroy(&subsys->ns_ida); 3216 device_del(&subsys->dev); 3217 put_device(&subsys->dev); 3218 } 3219 3220 static void nvme_put_subsystem(struct nvme_subsystem *subsys) 3221 { 3222 kref_put(&subsys->ref, nvme_destroy_subsystem); 3223 } 3224 3225 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn) 3226 __must_hold(&nvme_subsystems_lock) 3227 { 3228 struct nvme_subsystem *subsys; 3229 3230 lockdep_assert_held(&nvme_subsystems_lock); 3231 3232 /* 3233 * Fail matches for discovery subsystems. This results 3234 * in each discovery controller bound to a unique subsystem. 3235 * This avoids issues with validating controller values 3236 * that can only be true when there is a single unique subsystem. 3237 * There may be multiple and completely independent entities 3238 * that provide discovery controllers. 3239 */ 3240 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME)) 3241 return NULL; 3242 3243 list_for_each_entry(subsys, &nvme_subsystems, entry) { 3244 if (strcmp(subsys->subnqn, subsysnqn)) 3245 continue; 3246 if (!kref_get_unless_zero(&subsys->ref)) 3247 continue; 3248 return subsys; 3249 } 3250 3251 return NULL; 3252 } 3253 3254 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl) 3255 { 3256 return ctrl->opts && ctrl->opts->discovery_nqn; 3257 } 3258 3259 static inline bool nvme_admin_ctrl(struct nvme_ctrl *ctrl) 3260 { 3261 return ctrl->cntrltype == NVME_CTRL_ADMIN; 3262 } 3263 3264 static inline bool nvme_is_io_ctrl(struct nvme_ctrl *ctrl) 3265 { 3266 return !nvme_discovery_ctrl(ctrl) && !nvme_admin_ctrl(ctrl); 3267 } 3268 3269 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys, 3270 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 3271 __must_hold(&nvme_subsystems_lock) 3272 { 3273 struct nvme_ctrl *tmp; 3274 3275 lockdep_assert_held(&nvme_subsystems_lock); 3276 3277 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) { 3278 if (nvme_state_terminal(tmp)) 3279 continue; 3280 3281 if (tmp->cntlid == ctrl->cntlid) { 3282 dev_err(ctrl->device, 3283 "Duplicate cntlid %u with %s, subsys %s, rejecting\n", 3284 ctrl->cntlid, dev_name(tmp->device), 3285 subsys->subnqn); 3286 return false; 3287 } 3288 3289 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) || 3290 nvme_discovery_ctrl(ctrl)) 3291 continue; 3292 3293 dev_err(ctrl->device, 3294 "Subsystem does not support multiple controllers\n"); 3295 return false; 3296 } 3297 3298 return true; 3299 } 3300 3301 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 3302 __context_unsafe(/* initialize unpublished/lock-guarded variables */) 3303 { 3304 struct nvme_subsystem *subsys, *found; 3305 int ret; 3306 3307 subsys = kzalloc_obj(*subsys); 3308 if (!subsys) 3309 return -ENOMEM; 3310 3311 subsys->instance = -1; 3312 mutex_init(&subsys->lock); 3313 kref_init(&subsys->ref); 3314 INIT_LIST_HEAD(&subsys->ctrls); 3315 INIT_LIST_HEAD(&subsys->nsheads); 3316 nvme_init_subnqn(subsys, ctrl, id); 3317 memcpy(subsys->serial, id->sn, sizeof(subsys->serial)); 3318 memcpy(subsys->model, id->mn, sizeof(subsys->model)); 3319 subsys->vendor_id = le16_to_cpu(id->vid); 3320 subsys->cmic = id->cmic; 3321 3322 /* Versions prior to 1.4 don't necessarily report a valid type */ 3323 if (id->cntrltype == NVME_CTRL_DISC || 3324 !strcmp(subsys->subnqn, NVME_DISC_SUBSYS_NAME)) 3325 subsys->subtype = NVME_NQN_DISC; 3326 else 3327 subsys->subtype = NVME_NQN_NVME; 3328 3329 if (nvme_discovery_ctrl(ctrl) && subsys->subtype != NVME_NQN_DISC) { 3330 dev_err(ctrl->device, 3331 "Subsystem %s is not a discovery controller", 3332 subsys->subnqn); 3333 kfree(subsys); 3334 return -EINVAL; 3335 } 3336 nvme_mpath_default_iopolicy(subsys); 3337 3338 subsys->dev.class = &nvme_subsys_class; 3339 subsys->dev.release = nvme_release_subsystem; 3340 subsys->dev.groups = nvme_subsys_attrs_groups; 3341 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance); 3342 device_initialize(&subsys->dev); 3343 3344 mutex_lock(&nvme_subsystems_lock); 3345 found = __nvme_find_get_subsystem(subsys->subnqn); 3346 if (found) { 3347 put_device(&subsys->dev); 3348 subsys = found; 3349 3350 if (!nvme_validate_cntlid(subsys, ctrl, id)) { 3351 ret = -EINVAL; 3352 goto out_put_subsystem; 3353 } 3354 } else { 3355 ret = device_add(&subsys->dev); 3356 if (ret) { 3357 dev_err(ctrl->device, 3358 "failed to register subsystem device.\n"); 3359 put_device(&subsys->dev); 3360 goto out_unlock; 3361 } 3362 ida_init(&subsys->ns_ida); 3363 list_add_tail(&subsys->entry, &nvme_subsystems); 3364 } 3365 3366 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj, 3367 dev_name(ctrl->device)); 3368 if (ret) { 3369 dev_err(ctrl->device, 3370 "failed to create sysfs link from subsystem.\n"); 3371 goto out_put_subsystem; 3372 } 3373 3374 if (!found) 3375 subsys->instance = ctrl->instance; 3376 ctrl->subsys = subsys; 3377 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls); 3378 mutex_unlock(&nvme_subsystems_lock); 3379 return 0; 3380 3381 out_put_subsystem: 3382 nvme_put_subsystem(subsys); 3383 out_unlock: 3384 mutex_unlock(&nvme_subsystems_lock); 3385 return ret; 3386 } 3387 3388 static int nvme_get_log_lsi(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, 3389 u8 lsp, u8 csi, void *log, size_t size, u64 offset, u16 lsi) 3390 { 3391 struct nvme_command c = { }; 3392 u32 dwlen = nvme_bytes_to_numd(size); 3393 3394 c.get_log_page.opcode = nvme_admin_get_log_page; 3395 c.get_log_page.nsid = cpu_to_le32(nsid); 3396 c.get_log_page.lid = log_page; 3397 c.get_log_page.lsp = lsp; 3398 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1)); 3399 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16); 3400 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset)); 3401 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset)); 3402 c.get_log_page.csi = csi; 3403 c.get_log_page.lsi = cpu_to_le16(lsi); 3404 3405 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size); 3406 } 3407 3408 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi, 3409 void *log, size_t size, u64 offset) 3410 { 3411 return nvme_get_log_lsi(ctrl, nsid, log_page, lsp, csi, log, size, 3412 offset, 0); 3413 } 3414 3415 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi, 3416 struct nvme_effects_log **log) 3417 { 3418 struct nvme_effects_log *old, *cel = xa_load(&ctrl->cels, csi); 3419 int ret; 3420 3421 if (cel) 3422 goto out; 3423 3424 cel = kzalloc_obj(*cel); 3425 if (!cel) 3426 return -ENOMEM; 3427 3428 ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi, 3429 cel, sizeof(*cel), 0); 3430 if (ret) { 3431 kfree(cel); 3432 return ret; 3433 } 3434 3435 old = xa_store(&ctrl->cels, csi, cel, GFP_KERNEL); 3436 if (xa_is_err(old)) { 3437 kfree(cel); 3438 return xa_err(old); 3439 } 3440 out: 3441 *log = cel; 3442 return 0; 3443 } 3444 3445 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units) 3446 { 3447 u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val; 3448 3449 if (check_shl_overflow(1U, units + page_shift - 9, &val)) 3450 return UINT_MAX; 3451 return val; 3452 } 3453 3454 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl) 3455 { 3456 struct nvme_command c = { }; 3457 struct nvme_id_ctrl_nvm *id; 3458 int ret; 3459 3460 /* 3461 * Even though NVMe spec explicitly states that MDTS is not applicable 3462 * to the write-zeroes, we are cautious and limit the size to the 3463 * controllers max_hw_sectors value, which is based on the MDTS field 3464 * and possibly other limiting factors. 3465 */ 3466 if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) && 3467 !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES)) 3468 ctrl->max_zeroes_sectors = ctrl->max_hw_sectors; 3469 else 3470 ctrl->max_zeroes_sectors = 0; 3471 3472 if (!nvme_is_io_ctrl(ctrl) || 3473 !nvme_id_cns_ok(ctrl, NVME_ID_CNS_CS_CTRL) || 3474 test_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags)) 3475 return 0; 3476 3477 id = kzalloc_obj(*id); 3478 if (!id) 3479 return -ENOMEM; 3480 3481 c.identify.opcode = nvme_admin_identify; 3482 c.identify.cns = NVME_ID_CNS_CS_CTRL; 3483 c.identify.csi = NVME_CSI_NVM; 3484 3485 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id)); 3486 if (ret) 3487 goto free_data; 3488 3489 ctrl->dmrl = id->dmrl; 3490 ctrl->dmrsl = le32_to_cpu(id->dmrsl); 3491 if (id->wzsl && !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES)) 3492 ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl); 3493 3494 free_data: 3495 if (ret > 0) 3496 set_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags); 3497 kfree(id); 3498 return ret; 3499 } 3500 3501 static int nvme_init_effects_log(struct nvme_ctrl *ctrl, 3502 u8 csi, struct nvme_effects_log **log) 3503 { 3504 struct nvme_effects_log *effects, *old; 3505 3506 effects = kzalloc_obj(*effects); 3507 if (!effects) 3508 return -ENOMEM; 3509 3510 old = xa_store(&ctrl->cels, csi, effects, GFP_KERNEL); 3511 if (xa_is_err(old)) { 3512 kfree(effects); 3513 return xa_err(old); 3514 } 3515 3516 *log = effects; 3517 return 0; 3518 } 3519 3520 static void nvme_init_known_nvm_effects(struct nvme_ctrl *ctrl) 3521 { 3522 struct nvme_effects_log *log = ctrl->effects; 3523 3524 log->acs[nvme_admin_format_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC | 3525 NVME_CMD_EFFECTS_NCC | 3526 NVME_CMD_EFFECTS_CSE_MASK); 3527 log->acs[nvme_admin_sanitize_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC | 3528 NVME_CMD_EFFECTS_CSE_MASK); 3529 3530 /* 3531 * The spec says the result of a security receive command depends on 3532 * the previous security send command. As such, many vendors log this 3533 * command as one to submitted only when no other commands to the same 3534 * namespace are outstanding. The intention is to tell the host to 3535 * prevent mixing security send and receive. 3536 * 3537 * This driver can only enforce such exclusive access against IO 3538 * queues, though. We are not readily able to enforce such a rule for 3539 * two commands to the admin queue, which is the only queue that 3540 * matters for this command. 3541 * 3542 * Rather than blindly freezing the IO queues for this effect that 3543 * doesn't even apply to IO, mask it off. 3544 */ 3545 log->acs[nvme_admin_security_recv] &= cpu_to_le32(~NVME_CMD_EFFECTS_CSE_MASK); 3546 3547 log->iocs[nvme_cmd_write] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC); 3548 log->iocs[nvme_cmd_write_zeroes] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC); 3549 log->iocs[nvme_cmd_write_uncor] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC); 3550 } 3551 3552 static int nvme_init_effects(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 3553 { 3554 int ret = 0; 3555 3556 if (ctrl->effects) 3557 return 0; 3558 3559 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) { 3560 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects); 3561 if (ret < 0) 3562 return ret; 3563 } 3564 3565 if (!ctrl->effects) { 3566 ret = nvme_init_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects); 3567 if (ret < 0) 3568 return ret; 3569 } 3570 3571 nvme_init_known_nvm_effects(ctrl); 3572 return 0; 3573 } 3574 3575 static int nvme_check_ctrl_fabric_info(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 3576 { 3577 /* 3578 * In fabrics we need to verify the cntlid matches the 3579 * admin connect 3580 */ 3581 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) { 3582 dev_err(ctrl->device, 3583 "Mismatching cntlid: Connect %u vs Identify %u, rejecting\n", 3584 ctrl->cntlid, le16_to_cpu(id->cntlid)); 3585 return -EINVAL; 3586 } 3587 3588 if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) { 3589 dev_err(ctrl->device, 3590 "keep-alive support is mandatory for fabrics\n"); 3591 return -EINVAL; 3592 } 3593 3594 if (nvme_is_io_ctrl(ctrl) && ctrl->ioccsz < 4) { 3595 dev_err(ctrl->device, 3596 "I/O queue command capsule supported size %d < 4\n", 3597 ctrl->ioccsz); 3598 return -EINVAL; 3599 } 3600 3601 if (nvme_is_io_ctrl(ctrl) && ctrl->iorcsz < 1) { 3602 dev_err(ctrl->device, 3603 "I/O queue response capsule supported size %d < 1\n", 3604 ctrl->iorcsz); 3605 return -EINVAL; 3606 } 3607 3608 if (!ctrl->maxcmd) { 3609 dev_warn(ctrl->device, 3610 "Firmware bug: maximum outstanding commands is 0\n"); 3611 ctrl->maxcmd = ctrl->sqsize + 1; 3612 } 3613 3614 return 0; 3615 } 3616 3617 static int nvme_init_identify(struct nvme_ctrl *ctrl) 3618 { 3619 struct queue_limits lim; 3620 struct nvme_id_ctrl *id; 3621 u32 max_hw_sectors; 3622 bool prev_apst_enabled; 3623 int ret; 3624 3625 ret = nvme_identify_ctrl(ctrl, &id); 3626 if (ret) { 3627 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret); 3628 return -EIO; 3629 } 3630 3631 if (!(ctrl->ops->flags & NVME_F_FABRICS)) 3632 ctrl->cntlid = le16_to_cpu(id->cntlid); 3633 3634 if (!ctrl->identified) { 3635 unsigned int i; 3636 3637 /* 3638 * Check for quirks. Quirk can depend on firmware version, 3639 * so, in principle, the set of quirks present can change 3640 * across a reset. As a possible future enhancement, we 3641 * could re-scan for quirks every time we reinitialize 3642 * the device, but we'd have to make sure that the driver 3643 * behaves intelligently if the quirks change. 3644 */ 3645 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) { 3646 if (quirk_matches(id, &core_quirks[i])) 3647 ctrl->quirks |= core_quirks[i].quirks; 3648 } 3649 3650 ret = nvme_init_subsystem(ctrl, id); 3651 if (ret) 3652 goto out_free; 3653 3654 ret = nvme_init_effects(ctrl, id); 3655 if (ret) 3656 goto out_free; 3657 } 3658 memcpy(ctrl->subsys->firmware_rev, id->fr, 3659 sizeof(ctrl->subsys->firmware_rev)); 3660 3661 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) { 3662 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n"); 3663 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS; 3664 } 3665 3666 ctrl->crdt[0] = le16_to_cpu(id->crdt1); 3667 ctrl->crdt[1] = le16_to_cpu(id->crdt2); 3668 ctrl->crdt[2] = le16_to_cpu(id->crdt3); 3669 3670 ctrl->oacs = le16_to_cpu(id->oacs); 3671 ctrl->oncs = le16_to_cpu(id->oncs); 3672 ctrl->mtfa = le16_to_cpu(id->mtfa); 3673 ctrl->oaes = le32_to_cpu(id->oaes); 3674 ctrl->wctemp = le16_to_cpu(id->wctemp); 3675 ctrl->cctemp = le16_to_cpu(id->cctemp); 3676 3677 atomic_set(&ctrl->abort_limit, id->acl + 1); 3678 ctrl->vwc = id->vwc; 3679 if (id->mdts) 3680 max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts); 3681 else 3682 max_hw_sectors = UINT_MAX; 3683 ctrl->max_hw_sectors = 3684 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors); 3685 3686 lim = queue_limits_start_update(ctrl->admin_q); 3687 nvme_set_ctrl_limits(ctrl, &lim, true); 3688 ret = queue_limits_commit_update(ctrl->admin_q, &lim); 3689 if (ret) 3690 goto out_free; 3691 3692 ctrl->sgls = le32_to_cpu(id->sgls); 3693 ctrl->kas = le16_to_cpu(id->kas); 3694 ctrl->max_namespaces = le32_to_cpu(id->mnan); 3695 ctrl->ctratt = le32_to_cpu(id->ctratt); 3696 3697 ctrl->cntrltype = id->cntrltype; 3698 ctrl->dctype = id->dctype; 3699 3700 if (id->rtd3e) { 3701 /* us -> s */ 3702 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC; 3703 3704 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time, 3705 shutdown_timeout, 60); 3706 3707 if (ctrl->shutdown_timeout != shutdown_timeout) 3708 dev_info(ctrl->device, 3709 "D3 entry latency set to %u seconds\n", 3710 ctrl->shutdown_timeout); 3711 } else 3712 ctrl->shutdown_timeout = shutdown_timeout; 3713 3714 ctrl->npss = id->npss; 3715 ctrl->apsta = id->apsta; 3716 prev_apst_enabled = ctrl->apst_enabled; 3717 if (ctrl->quirks & NVME_QUIRK_NO_APST) { 3718 if (force_apst && id->apsta) { 3719 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n"); 3720 ctrl->apst_enabled = true; 3721 } else { 3722 ctrl->apst_enabled = false; 3723 } 3724 } else { 3725 ctrl->apst_enabled = id->apsta; 3726 } 3727 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd)); 3728 3729 if (ctrl->ops->flags & NVME_F_FABRICS) { 3730 ctrl->icdoff = le16_to_cpu(id->icdoff); 3731 ctrl->ioccsz = le32_to_cpu(id->ioccsz); 3732 ctrl->iorcsz = le32_to_cpu(id->iorcsz); 3733 ctrl->maxcmd = le16_to_cpu(id->maxcmd); 3734 3735 ret = nvme_check_ctrl_fabric_info(ctrl, id); 3736 if (ret) 3737 goto out_free; 3738 } else { 3739 ctrl->hmpre = le32_to_cpu(id->hmpre); 3740 ctrl->hmmin = le32_to_cpu(id->hmmin); 3741 ctrl->hmminds = le32_to_cpu(id->hmminds); 3742 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd); 3743 } 3744 3745 ret = nvme_mpath_init_identify(ctrl, id); 3746 if (ret < 0) 3747 goto out_free; 3748 3749 if (ctrl->apst_enabled && !prev_apst_enabled) 3750 dev_pm_qos_expose_latency_tolerance(ctrl->device); 3751 else if (!ctrl->apst_enabled && prev_apst_enabled) 3752 dev_pm_qos_hide_latency_tolerance(ctrl->device); 3753 ctrl->awupf = le16_to_cpu(id->awupf); 3754 out_free: 3755 kfree(id); 3756 return ret; 3757 } 3758 3759 /* 3760 * Initialize the cached copies of the Identify data and various controller 3761 * register in our nvme_ctrl structure. This should be called as soon as 3762 * the admin queue is fully up and running. 3763 */ 3764 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl, bool was_suspended) 3765 { 3766 int ret; 3767 3768 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs); 3769 if (ret) { 3770 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret); 3771 return ret; 3772 } 3773 3774 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize); 3775 3776 if (ctrl->vs >= NVME_VS(1, 1, 0)) 3777 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap); 3778 3779 ret = nvme_init_identify(ctrl); 3780 if (ret) 3781 return ret; 3782 3783 if (nvme_admin_ctrl(ctrl)) { 3784 /* 3785 * An admin controller has one admin queue, but no I/O queues. 3786 * Override queue_count so it only creates an admin queue. 3787 */ 3788 dev_dbg(ctrl->device, 3789 "Subsystem %s is an administrative controller", 3790 ctrl->subsys->subnqn); 3791 ctrl->queue_count = 1; 3792 } 3793 3794 ret = nvme_configure_apst(ctrl); 3795 if (ret < 0) 3796 return ret; 3797 3798 ret = nvme_configure_timestamp(ctrl); 3799 if (ret < 0) 3800 return ret; 3801 3802 ret = nvme_configure_host_options(ctrl); 3803 if (ret < 0) 3804 return ret; 3805 3806 nvme_configure_opal(ctrl, was_suspended); 3807 3808 if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) { 3809 /* 3810 * Do not return errors unless we are in a controller reset, 3811 * the controller works perfectly fine without hwmon. 3812 */ 3813 ret = nvme_hwmon_init(ctrl); 3814 if (ret == -EINTR) 3815 return ret; 3816 3817 if (!nvme_ctrl_sgl_supported(ctrl)) 3818 dev_info(ctrl->device, 3819 "passthrough uses implicit buffer lengths\n"); 3820 } 3821 3822 clear_bit(NVME_CTRL_DIRTY_CAPABILITY, &ctrl->flags); 3823 ctrl->identified = true; 3824 3825 nvme_start_keep_alive(ctrl); 3826 3827 return 0; 3828 } 3829 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish); 3830 3831 static int nvme_dev_open(struct inode *inode, struct file *file) 3832 { 3833 struct nvme_ctrl *ctrl = 3834 container_of(inode->i_cdev, struct nvme_ctrl, cdev); 3835 3836 switch (nvme_ctrl_state(ctrl)) { 3837 case NVME_CTRL_LIVE: 3838 break; 3839 default: 3840 return -EWOULDBLOCK; 3841 } 3842 3843 nvme_get_ctrl(ctrl); 3844 if (!try_module_get(ctrl->ops->module)) { 3845 nvme_put_ctrl(ctrl); 3846 return -EINVAL; 3847 } 3848 3849 file->private_data = ctrl; 3850 return 0; 3851 } 3852 3853 static int nvme_dev_release(struct inode *inode, struct file *file) 3854 { 3855 struct nvme_ctrl *ctrl = 3856 container_of(inode->i_cdev, struct nvme_ctrl, cdev); 3857 3858 module_put(ctrl->ops->module); 3859 nvme_put_ctrl(ctrl); 3860 return 0; 3861 } 3862 3863 static const struct file_operations nvme_dev_fops = { 3864 .owner = THIS_MODULE, 3865 .open = nvme_dev_open, 3866 .release = nvme_dev_release, 3867 .unlocked_ioctl = nvme_dev_ioctl, 3868 .compat_ioctl = compat_ptr_ioctl, 3869 .uring_cmd = nvme_dev_uring_cmd, 3870 }; 3871 3872 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_ctrl *ctrl, 3873 unsigned nsid) 3874 __must_hold(&ctrl->subsys->lock) 3875 { 3876 struct nvme_ns_head *h; 3877 3878 lockdep_assert_held(&ctrl->subsys->lock); 3879 3880 list_for_each_entry(h, &ctrl->subsys->nsheads, entry) { 3881 /* 3882 * Private namespaces can share NSIDs under some conditions. 3883 * In that case we can't use the same ns_head for namespaces 3884 * with the same NSID. 3885 */ 3886 if (h->ns_id != nsid || !nvme_is_unique_nsid(ctrl, h)) 3887 continue; 3888 if (nvme_tryget_ns_head(h)) 3889 return h; 3890 } 3891 3892 return NULL; 3893 } 3894 3895 static int nvme_subsys_check_duplicate_ids(struct nvme_subsystem *subsys, 3896 struct nvme_ns_ids *ids) 3897 __must_hold(&subsys->lock) 3898 { 3899 bool has_uuid = !uuid_is_null(&ids->uuid); 3900 bool has_nguid = memchr_inv(ids->nguid, 0, sizeof(ids->nguid)); 3901 bool has_eui64 = memchr_inv(ids->eui64, 0, sizeof(ids->eui64)); 3902 struct nvme_ns_head *h; 3903 3904 lockdep_assert_held(&subsys->lock); 3905 3906 list_for_each_entry(h, &subsys->nsheads, entry) { 3907 if (has_uuid && uuid_equal(&ids->uuid, &h->ids.uuid)) 3908 return -EINVAL; 3909 if (has_nguid && 3910 memcmp(&ids->nguid, &h->ids.nguid, sizeof(ids->nguid)) == 0) 3911 return -EINVAL; 3912 if (has_eui64 && 3913 memcmp(&ids->eui64, &h->ids.eui64, sizeof(ids->eui64)) == 0) 3914 return -EINVAL; 3915 } 3916 3917 return 0; 3918 } 3919 3920 static void nvme_cdev_rel(struct device *dev) 3921 { 3922 ida_free(&nvme_ns_chr_minor_ida, MINOR(dev->devt)); 3923 if (dev->parent->class == &nvme_class) 3924 nvme_put_ns(container_of(dev, struct nvme_ns, cdev_device)); 3925 else 3926 nvme_put_ns_head(container_of(dev, struct nvme_ns_head, 3927 cdev_device)); 3928 } 3929 3930 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device) 3931 { 3932 cdev_device_del(cdev, cdev_device); 3933 put_device(cdev_device); 3934 } 3935 3936 int nvme_cdev_add(const char *name, struct cdev *cdev, 3937 struct device *cdev_device, 3938 const struct file_operations *fops, struct module *owner) 3939 { 3940 int minor, ret; 3941 3942 minor = ida_alloc(&nvme_ns_chr_minor_ida, GFP_KERNEL); 3943 if (minor < 0) 3944 return minor; 3945 3946 ret = dev_set_name(cdev_device, name); 3947 if (ret) { 3948 ida_free(&nvme_ns_chr_minor_ida, minor); 3949 return ret; 3950 } 3951 cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor); 3952 cdev_device->class = &nvme_ns_chr_class; 3953 cdev_device->release = nvme_cdev_rel; 3954 device_initialize(cdev_device); 3955 cdev_init(cdev, fops); 3956 cdev->owner = owner; 3957 ret = cdev_device_add(cdev, cdev_device); 3958 if (ret) 3959 put_device(cdev_device); 3960 3961 return ret; 3962 } 3963 3964 static int nvme_ns_chr_open(struct inode *inode, struct file *file) 3965 { 3966 return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev)); 3967 } 3968 3969 static int nvme_ns_chr_release(struct inode *inode, struct file *file) 3970 { 3971 nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev)); 3972 return 0; 3973 } 3974 3975 static const struct file_operations nvme_ns_chr_fops = { 3976 .owner = THIS_MODULE, 3977 .open = nvme_ns_chr_open, 3978 .release = nvme_ns_chr_release, 3979 .unlocked_ioctl = nvme_ns_chr_ioctl, 3980 .compat_ioctl = compat_ptr_ioctl, 3981 .uring_cmd = nvme_ns_chr_uring_cmd, 3982 .uring_cmd_iopoll = nvme_ns_chr_uring_cmd_iopoll, 3983 }; 3984 3985 static void nvme_add_ns_cdev(struct nvme_ns *ns) 3986 { 3987 char name[32]; 3988 3989 ns->cdev_device.parent = ns->ctrl->device; 3990 snprintf(name, sizeof(name), "ng%dn%d", ns->ctrl->instance, 3991 ns->head->instance); 3992 3993 nvme_get_ns(ns); /* Undone in nvme_cdev_rel() */ 3994 if (nvme_cdev_add(name, &ns->cdev, &ns->cdev_device, 3995 &nvme_ns_chr_fops, ns->ctrl->ops->module)) { 3996 dev_err(ns->ctrl->device, "Unable to create the %s device\n", 3997 name); 3998 nvme_put_ns(ns); 3999 return; 4000 } 4001 set_bit(NVME_NS_CDEV_LIVE, &ns->flags); 4002 } 4003 4004 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl, 4005 struct nvme_ns_info *info) 4006 __must_hold(&ctrl->subsys->lock) 4007 { 4008 struct nvme_ns_head *head; 4009 size_t size = sizeof(*head); 4010 int ret = -ENOMEM; 4011 4012 #ifdef CONFIG_NVME_MULTIPATH 4013 size += nr_node_ids * sizeof(struct nvme_ns *); 4014 #endif 4015 4016 head = kzalloc(size, GFP_KERNEL); 4017 if (!head) 4018 goto out; 4019 ret = ida_alloc_min(&ctrl->subsys->ns_ida, 1, GFP_KERNEL); 4020 if (ret < 0) 4021 goto out_free_head; 4022 head->instance = ret; 4023 INIT_LIST_HEAD(&head->list); 4024 ret = init_srcu_struct(&head->srcu); 4025 if (ret) 4026 goto out_ida_remove; 4027 head->subsys = ctrl->subsys; 4028 head->ns_id = info->nsid; 4029 head->ids = info->ids; 4030 head->shared = info->is_shared; 4031 head->rotational = info->is_rotational; 4032 ratelimit_state_init(&head->rs_nuse, 5 * HZ, 1); 4033 ratelimit_set_flags(&head->rs_nuse, RATELIMIT_MSG_ON_RELEASE); 4034 kref_init(&head->ref); 4035 4036 if (head->ids.csi) { 4037 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects); 4038 if (ret) 4039 goto out_cleanup_srcu; 4040 } else 4041 head->effects = ctrl->effects; 4042 4043 ret = nvme_mpath_alloc_disk(ctrl, head); 4044 if (ret) 4045 goto out_cleanup_srcu; 4046 4047 list_add_tail(&head->entry, &ctrl->subsys->nsheads); 4048 4049 kref_get(&ctrl->subsys->ref); 4050 4051 return head; 4052 out_cleanup_srcu: 4053 cleanup_srcu_struct(&head->srcu); 4054 out_ida_remove: 4055 ida_free(&ctrl->subsys->ns_ida, head->instance); 4056 out_free_head: 4057 kfree(head); 4058 out: 4059 if (ret > 0) 4060 ret = blk_status_to_errno(nvme_error_status(ret)); 4061 return ERR_PTR(ret); 4062 } 4063 4064 static int nvme_global_check_duplicate_ids(struct nvme_subsystem *this, 4065 struct nvme_ns_ids *ids) 4066 { 4067 struct nvme_subsystem *s; 4068 int ret = 0; 4069 4070 /* 4071 * Note that this check is racy as we try to avoid holding the global 4072 * lock over the whole ns_head creation. But it is only intended as 4073 * a sanity check anyway. 4074 */ 4075 mutex_lock(&nvme_subsystems_lock); 4076 list_for_each_entry(s, &nvme_subsystems, entry) { 4077 if (s == this) 4078 continue; 4079 mutex_lock(&s->lock); 4080 ret = nvme_subsys_check_duplicate_ids(s, ids); 4081 mutex_unlock(&s->lock); 4082 if (ret) 4083 break; 4084 } 4085 mutex_unlock(&nvme_subsystems_lock); 4086 4087 return ret; 4088 } 4089 4090 static int nvme_init_ns_head(struct nvme_ns *ns, struct nvme_ns_info *info) 4091 { 4092 struct nvme_ctrl *ctrl = ns->ctrl; 4093 struct nvme_ns_head *head = NULL; 4094 int ret; 4095 4096 ret = nvme_global_check_duplicate_ids(ctrl->subsys, &info->ids); 4097 if (ret) { 4098 /* 4099 * We've found two different namespaces on two different 4100 * subsystems that report the same ID. This is pretty nasty 4101 * for anything that actually requires unique device 4102 * identification. In the kernel we need this for multipathing, 4103 * and in user space the /dev/disk/by-id/ links rely on it. 4104 * 4105 * If the device also claims to be multi-path capable back off 4106 * here now and refuse the probe the second device as this is a 4107 * recipe for data corruption. If not this is probably a 4108 * cheap consumer device if on the PCIe bus, so let the user 4109 * proceed and use the shiny toy, but warn that with changing 4110 * probing order (which due to our async probing could just be 4111 * device taking longer to startup) the other device could show 4112 * up at any time. 4113 */ 4114 nvme_print_device_info(ctrl); 4115 if ((ns->ctrl->ops->flags & NVME_F_FABRICS) || /* !PCIe */ 4116 ((ns->ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) && 4117 info->is_shared)) { 4118 dev_err(ctrl->device, 4119 "ignoring nsid %d because of duplicate IDs\n", 4120 info->nsid); 4121 return ret; 4122 } 4123 4124 dev_err(ctrl->device, 4125 "clearing duplicate IDs for nsid %d\n", info->nsid); 4126 dev_err(ctrl->device, 4127 "use of /dev/disk/by-id/ may cause data corruption\n"); 4128 memset(&info->ids.nguid, 0, sizeof(info->ids.nguid)); 4129 memset(&info->ids.uuid, 0, sizeof(info->ids.uuid)); 4130 memset(&info->ids.eui64, 0, sizeof(info->ids.eui64)); 4131 ctrl->quirks |= NVME_QUIRK_BOGUS_NID; 4132 } 4133 4134 mutex_lock(&ctrl->subsys->lock); 4135 head = nvme_find_ns_head(ctrl, info->nsid); 4136 if (!head) { 4137 ret = nvme_subsys_check_duplicate_ids(ctrl->subsys, &info->ids); 4138 if (ret) { 4139 dev_err(ctrl->device, 4140 "duplicate IDs in subsystem for nsid %d\n", 4141 info->nsid); 4142 goto out_unlock; 4143 } 4144 head = nvme_alloc_ns_head(ctrl, info); 4145 if (IS_ERR(head)) { 4146 ret = PTR_ERR(head); 4147 goto out_unlock; 4148 } 4149 } else { 4150 ret = -EINVAL; 4151 if ((!info->is_shared || !head->shared) && 4152 !list_empty(&head->list)) { 4153 dev_err(ctrl->device, 4154 "Duplicate unshared namespace %d\n", 4155 info->nsid); 4156 goto out_put_ns_head; 4157 } 4158 if (!nvme_ns_ids_equal(&head->ids, &info->ids)) { 4159 dev_err(ctrl->device, 4160 "IDs don't match for shared namespace %d\n", 4161 info->nsid); 4162 goto out_put_ns_head; 4163 } 4164 4165 if (!multipath) { 4166 dev_warn(ctrl->device, 4167 "Found shared namespace %d, but multipathing not supported.\n", 4168 info->nsid); 4169 dev_warn_once(ctrl->device, 4170 "Shared namespace support requires core_nvme.multipath=Y.\n"); 4171 } 4172 } 4173 4174 list_add_tail_rcu(&ns->siblings, &head->list); 4175 ns->head = head; 4176 mutex_unlock(&ctrl->subsys->lock); 4177 4178 #ifdef CONFIG_NVME_MULTIPATH 4179 if (cancel_delayed_work(&head->remove_work)) 4180 module_put(THIS_MODULE); 4181 #endif 4182 return 0; 4183 4184 out_put_ns_head: 4185 nvme_put_ns_head(head); 4186 out_unlock: 4187 mutex_unlock(&ctrl->subsys->lock); 4188 return ret; 4189 } 4190 4191 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid) 4192 { 4193 struct nvme_ns *ns, *ret = NULL; 4194 int srcu_idx; 4195 4196 srcu_idx = srcu_read_lock(&ctrl->srcu); 4197 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 4198 srcu_read_lock_held(&ctrl->srcu)) { 4199 if (ns->head->ns_id == nsid) { 4200 if (!nvme_get_ns(ns)) 4201 continue; 4202 ret = ns; 4203 break; 4204 } 4205 if (ns->head->ns_id > nsid) 4206 break; 4207 } 4208 srcu_read_unlock(&ctrl->srcu, srcu_idx); 4209 return ret; 4210 } 4211 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, "NVME_TARGET_PASSTHRU"); 4212 4213 /* 4214 * Add the namespace to the controller list while keeping the list ordered. 4215 */ 4216 static void nvme_ns_add_to_ctrl_list(struct nvme_ns *ns) 4217 { 4218 struct nvme_ns *tmp; 4219 4220 list_for_each_entry_reverse(tmp, &ns->ctrl->namespaces, list) { 4221 if (tmp->head->ns_id < ns->head->ns_id) { 4222 list_add_rcu(&ns->list, &tmp->list); 4223 return; 4224 } 4225 } 4226 list_add_rcu(&ns->list, &ns->ctrl->namespaces); 4227 } 4228 4229 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info) 4230 { 4231 struct queue_limits lim = { }; 4232 struct nvme_ns *ns; 4233 struct gendisk *disk; 4234 int node = ctrl->numa_node; 4235 bool last_path = false; 4236 4237 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node); 4238 if (!ns) 4239 return; 4240 4241 if (ctrl->opts && ctrl->opts->data_digest) 4242 lim.features |= BLK_FEAT_STABLE_WRITES; 4243 if (ctrl->ops->supports_pci_p2pdma && 4244 ctrl->ops->supports_pci_p2pdma(ctrl)) 4245 lim.features |= BLK_FEAT_PCI_P2PDMA; 4246 4247 disk = blk_mq_alloc_disk(ctrl->tagset, &lim, ns); 4248 if (IS_ERR(disk)) 4249 goto out_free_ns; 4250 disk->fops = &nvme_bdev_ops; 4251 disk->private_data = ns; 4252 4253 ns->disk = disk; 4254 ns->queue = disk->queue; 4255 ns->ctrl = ctrl; 4256 kref_init(&ns->kref); 4257 4258 if (nvme_init_ns_head(ns, info)) 4259 goto out_cleanup_disk; 4260 4261 /* 4262 * If multipathing is enabled, the device name for all disks and not 4263 * just those that represent shared namespaces needs to be based on the 4264 * subsystem instance. Using the controller instance for private 4265 * namespaces could lead to naming collisions between shared and private 4266 * namespaces if they don't use a common numbering scheme. 4267 * 4268 * If multipathing is not enabled, disk names must use the controller 4269 * instance as shared namespaces will show up as multiple block 4270 * devices. 4271 */ 4272 if (nvme_ns_head_multipath(ns->head)) { 4273 sprintf(disk->disk_name, "nvme%dc%dn%d", ctrl->subsys->instance, 4274 ctrl->instance, ns->head->instance); 4275 disk->flags |= GENHD_FL_HIDDEN; 4276 } else if (multipath) { 4277 sprintf(disk->disk_name, "nvme%dn%d", ctrl->subsys->instance, 4278 ns->head->instance); 4279 } else { 4280 sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance, 4281 ns->head->instance); 4282 } 4283 4284 if (nvme_update_ns_info(ns, info)) 4285 goto out_unlink_ns; 4286 4287 mutex_lock(&ctrl->namespaces_lock); 4288 /* 4289 * Ensure that no namespaces are added to the ctrl list after the queues 4290 * are frozen, thereby avoiding a deadlock between scan and reset. 4291 */ 4292 if (test_bit(NVME_CTRL_FROZEN, &ctrl->flags)) { 4293 mutex_unlock(&ctrl->namespaces_lock); 4294 goto out_unlink_ns; 4295 } 4296 blk_queue_rq_timeout(ns->queue, ctrl->io_timeout); 4297 nvme_ns_add_to_ctrl_list(ns); 4298 mutex_unlock(&ctrl->namespaces_lock); 4299 synchronize_srcu(&ctrl->srcu); 4300 nvme_get_ctrl(ctrl); 4301 4302 if (device_add_disk(ctrl->device, ns->disk, nvme_ns_attr_groups)) 4303 goto out_cleanup_ns_from_list; 4304 4305 if (!nvme_ns_head_multipath(ns->head)) 4306 nvme_add_ns_cdev(ns); 4307 4308 nvme_mpath_add_disk(ns, info->anagrpid); 4309 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name); 4310 4311 return; 4312 4313 out_cleanup_ns_from_list: 4314 nvme_put_ctrl(ctrl); 4315 mutex_lock(&ctrl->namespaces_lock); 4316 list_del_rcu(&ns->list); 4317 mutex_unlock(&ctrl->namespaces_lock); 4318 synchronize_srcu(&ctrl->srcu); 4319 out_unlink_ns: 4320 mutex_lock(&ctrl->subsys->lock); 4321 list_del_rcu(&ns->siblings); 4322 if (list_empty(&ns->head->list)) { 4323 list_del_init(&ns->head->entry); 4324 /* 4325 * If multipath is not configured, we still create a namespace 4326 * head (nshead), but head->disk is not initialized in that 4327 * case. As a result, only a single reference to nshead is held 4328 * (via kref_init()) when it is created. Therefore, ensure that 4329 * we do not release the reference to nshead twice if head->disk 4330 * is not present. 4331 */ 4332 if (ns->head->disk) 4333 last_path = true; 4334 } 4335 mutex_unlock(&ctrl->subsys->lock); 4336 if (last_path) 4337 nvme_put_ns_head(ns->head); 4338 nvme_put_ns_head(ns->head); 4339 out_cleanup_disk: 4340 put_disk(disk); 4341 out_free_ns: 4342 kfree(ns); 4343 } 4344 4345 static void nvme_ns_remove(struct nvme_ns *ns) 4346 { 4347 bool last_path = false; 4348 4349 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags)) 4350 return; 4351 4352 clear_bit(NVME_NS_READY, &ns->flags); 4353 set_capacity(ns->disk, 0); 4354 nvme_fault_inject_fini(&ns->fault_inject); 4355 4356 /* 4357 * Ensure that !NVME_NS_READY is seen by other threads to prevent 4358 * this ns going back into current_path. 4359 */ 4360 synchronize_srcu(&ns->head->srcu); 4361 4362 /* wait for concurrent submissions */ 4363 if (nvme_mpath_clear_current_path(ns)) 4364 synchronize_srcu(&ns->head->srcu); 4365 4366 mutex_lock(&ns->ctrl->subsys->lock); 4367 list_del_rcu(&ns->siblings); 4368 if (list_empty(&ns->head->list)) { 4369 if (!nvme_mpath_queue_if_no_path(ns->head)) 4370 list_del_init(&ns->head->entry); 4371 last_path = true; 4372 } 4373 mutex_unlock(&ns->ctrl->subsys->lock); 4374 4375 /* guarantee not available in head->list */ 4376 synchronize_srcu(&ns->head->srcu); 4377 4378 if (!nvme_ns_head_multipath(ns->head)) { 4379 if (test_and_clear_bit(NVME_NS_CDEV_LIVE, &ns->flags)) 4380 nvme_cdev_del(&ns->cdev, &ns->cdev_device); 4381 } 4382 4383 nvme_mpath_remove_sysfs_link(ns); 4384 4385 del_gendisk(ns->disk); 4386 4387 mutex_lock(&ns->ctrl->namespaces_lock); 4388 list_del_rcu(&ns->list); 4389 mutex_unlock(&ns->ctrl->namespaces_lock); 4390 synchronize_srcu(&ns->ctrl->srcu); 4391 4392 if (last_path) 4393 nvme_mpath_remove_disk(ns->head); 4394 nvme_put_ns(ns); 4395 } 4396 4397 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid) 4398 { 4399 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid); 4400 4401 if (ns) { 4402 nvme_ns_remove(ns); 4403 nvme_put_ns(ns); 4404 } 4405 } 4406 4407 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_info *info) 4408 { 4409 int ret = NVME_SC_INVALID_NS | NVME_STATUS_DNR; 4410 4411 if (!nvme_ns_ids_equal(&ns->head->ids, &info->ids)) { 4412 dev_err(ns->ctrl->device, 4413 "identifiers changed for nsid %d\n", ns->head->ns_id); 4414 goto out; 4415 } 4416 4417 ret = nvme_update_ns_info(ns, info); 4418 out: 4419 /* 4420 * Only remove the namespace if we got a fatal error back from the 4421 * device, otherwise ignore the error and just move on. 4422 * 4423 * TODO: we should probably schedule a delayed retry here. 4424 */ 4425 if (ret > 0 && (ret & NVME_STATUS_DNR)) 4426 nvme_ns_remove(ns); 4427 } 4428 4429 static void nvme_scan_ns(struct nvme_ctrl *ctrl, unsigned nsid) 4430 { 4431 struct nvme_ns_info info = { .nsid = nsid }; 4432 struct nvme_ns *ns; 4433 int ret = 1; 4434 4435 if (nvme_identify_ns_descs(ctrl, &info)) 4436 return; 4437 4438 if (info.ids.csi != NVME_CSI_NVM && !nvme_multi_css(ctrl)) { 4439 dev_warn(ctrl->device, 4440 "command set not reported for nsid: %d\n", nsid); 4441 return; 4442 } 4443 4444 /* 4445 * If available try to use the Command Set Independent Identify Namespace 4446 * data structure to find all the generic information that is needed to 4447 * set up a namespace. If not fall back to the legacy version. 4448 */ 4449 if ((ctrl->cap & NVME_CAP_CRMS_CRIMS) || 4450 (info.ids.csi != NVME_CSI_NVM && info.ids.csi != NVME_CSI_ZNS) || 4451 ctrl->vs >= NVME_VS(2, 0, 0)) 4452 ret = nvme_ns_info_from_id_cs_indep(ctrl, &info); 4453 if (ret > 0) 4454 ret = nvme_ns_info_from_identify(ctrl, &info); 4455 4456 if (info.is_removed) 4457 nvme_ns_remove_by_nsid(ctrl, nsid); 4458 4459 /* 4460 * Ignore the namespace if it is not ready. We will get an AEN once it 4461 * becomes ready and restart the scan. 4462 */ 4463 if (ret || !info.is_ready) 4464 return; 4465 4466 ns = nvme_find_get_ns(ctrl, nsid); 4467 if (ns) { 4468 nvme_validate_ns(ns, &info); 4469 nvme_put_ns(ns); 4470 } else { 4471 nvme_alloc_ns(ctrl, &info); 4472 } 4473 } 4474 4475 /** 4476 * struct async_scan_info - keeps track of controller & NSIDs to scan 4477 * @ctrl: Controller on which namespaces are being scanned 4478 * @next_nsid: Index of next NSID to scan in ns_list 4479 * @ns_list: Pointer to list of NSIDs to scan 4480 * 4481 * Note: There is a single async_scan_info structure shared by all instances 4482 * of nvme_scan_ns_async() scanning a given controller, so the atomic 4483 * operations on next_nsid are critical to ensure each instance scans a unique 4484 * NSID. 4485 */ 4486 struct async_scan_info { 4487 struct nvme_ctrl *ctrl; 4488 atomic_t next_nsid; 4489 __le32 *ns_list; 4490 }; 4491 4492 static void nvme_scan_ns_async(void *data, async_cookie_t cookie) 4493 { 4494 struct async_scan_info *scan_info = data; 4495 int idx; 4496 u32 nsid; 4497 4498 idx = (u32)atomic_fetch_inc(&scan_info->next_nsid); 4499 nsid = le32_to_cpu(scan_info->ns_list[idx]); 4500 4501 nvme_scan_ns(scan_info->ctrl, nsid); 4502 } 4503 4504 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl, 4505 unsigned nsid) 4506 { 4507 struct nvme_ns *ns, *next; 4508 LIST_HEAD(rm_list); 4509 4510 mutex_lock(&ctrl->namespaces_lock); 4511 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) { 4512 if (ns->head->ns_id > nsid) { 4513 list_del_rcu(&ns->list); 4514 synchronize_srcu(&ctrl->srcu); 4515 list_add_tail_rcu(&ns->list, &rm_list); 4516 } 4517 } 4518 mutex_unlock(&ctrl->namespaces_lock); 4519 4520 list_for_each_entry_safe(ns, next, &rm_list, list) 4521 nvme_ns_remove(ns); 4522 } 4523 4524 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl) 4525 { 4526 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32); 4527 __le32 *ns_list; 4528 u32 prev = 0; 4529 int ret = 0, i; 4530 ASYNC_DOMAIN(domain); 4531 struct async_scan_info scan_info; 4532 4533 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 4534 if (!ns_list) 4535 return -ENOMEM; 4536 4537 scan_info.ctrl = ctrl; 4538 scan_info.ns_list = ns_list; 4539 for (;;) { 4540 struct nvme_command cmd = { 4541 .identify.opcode = nvme_admin_identify, 4542 .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST, 4543 .identify.nsid = cpu_to_le32(prev), 4544 }; 4545 4546 ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list, 4547 NVME_IDENTIFY_DATA_SIZE); 4548 if (ret) { 4549 dev_warn(ctrl->device, 4550 "Identify NS List failed (status=0x%x)\n", ret); 4551 goto free; 4552 } 4553 4554 atomic_set(&scan_info.next_nsid, 0); 4555 for (i = 0; i < nr_entries; i++) { 4556 u32 nsid = le32_to_cpu(ns_list[i]); 4557 4558 if (!nsid) /* end of the list? */ 4559 goto out; 4560 async_schedule_domain(nvme_scan_ns_async, &scan_info, 4561 &domain); 4562 while (++prev < nsid) 4563 nvme_ns_remove_by_nsid(ctrl, prev); 4564 } 4565 async_synchronize_full_domain(&domain); 4566 } 4567 out: 4568 nvme_remove_invalid_namespaces(ctrl, prev); 4569 free: 4570 async_synchronize_full_domain(&domain); 4571 kfree(ns_list); 4572 return ret; 4573 } 4574 4575 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl) 4576 { 4577 struct nvme_id_ctrl *id; 4578 u32 nn, i; 4579 4580 if (nvme_identify_ctrl(ctrl, &id)) 4581 return; 4582 nn = le32_to_cpu(id->nn); 4583 kfree(id); 4584 4585 for (i = 1; i <= nn; i++) 4586 nvme_scan_ns(ctrl, i); 4587 4588 nvme_remove_invalid_namespaces(ctrl, nn); 4589 } 4590 4591 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl) 4592 { 4593 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32); 4594 __le32 *log; 4595 int error; 4596 4597 log = kzalloc(log_size, GFP_KERNEL); 4598 if (!log) 4599 return; 4600 4601 /* 4602 * We need to read the log to clear the AEN, but we don't want to rely 4603 * on it for the changed namespace information as userspace could have 4604 * raced with us in reading the log page, which could cause us to miss 4605 * updates. 4606 */ 4607 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0, 4608 NVME_CSI_NVM, log, log_size, 0); 4609 if (error) 4610 dev_warn(ctrl->device, 4611 "reading changed ns log failed: %d\n", error); 4612 4613 kfree(log); 4614 } 4615 4616 static void nvme_scan_work(struct work_struct *work) 4617 { 4618 struct nvme_ctrl *ctrl = 4619 container_of(work, struct nvme_ctrl, scan_work); 4620 int ret; 4621 4622 /* No tagset on a live ctrl means IO queues could not created */ 4623 if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE || !ctrl->tagset) 4624 return; 4625 4626 /* 4627 * Identify controller limits can change at controller reset due to 4628 * new firmware download, even though it is not common we cannot ignore 4629 * such scenario. Controller's non-mdts limits are reported in the unit 4630 * of logical blocks that is dependent on the format of attached 4631 * namespace. Hence re-read the limits at the time of ns allocation. 4632 */ 4633 ret = nvme_init_non_mdts_limits(ctrl); 4634 if (ret < 0) { 4635 dev_warn(ctrl->device, 4636 "reading non-mdts-limits failed: %d\n", ret); 4637 return; 4638 } 4639 4640 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) { 4641 dev_info(ctrl->device, "rescanning namespaces.\n"); 4642 nvme_clear_changed_ns_log(ctrl); 4643 } 4644 4645 mutex_lock(&ctrl->scan_lock); 4646 if (!nvme_id_cns_ok(ctrl, NVME_ID_CNS_NS_ACTIVE_LIST)) { 4647 nvme_scan_ns_sequential(ctrl); 4648 } else { 4649 /* 4650 * Fall back to sequential scan if DNR is set to handle broken 4651 * devices which should support Identify NS List (as per the VS 4652 * they report) but don't actually support it. 4653 */ 4654 ret = nvme_scan_ns_list(ctrl); 4655 if (ret > 0 && ret & NVME_STATUS_DNR) 4656 nvme_scan_ns_sequential(ctrl); 4657 } 4658 mutex_unlock(&ctrl->scan_lock); 4659 4660 /* Requeue if we have missed AENs */ 4661 if (test_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) 4662 nvme_queue_scan(ctrl); 4663 #ifdef CONFIG_NVME_MULTIPATH 4664 else if (ctrl->ana_log_buf) 4665 /* Re-read the ANA log page to not miss updates */ 4666 queue_work(nvme_wq, &ctrl->ana_work); 4667 #endif 4668 } 4669 4670 /* 4671 * This function iterates the namespace list unlocked to allow recovery from 4672 * controller failure. It is up to the caller to ensure the namespace list is 4673 * not modified by scan work while this function is executing. 4674 */ 4675 void nvme_remove_namespaces(struct nvme_ctrl *ctrl) 4676 { 4677 struct nvme_ns *ns, *next; 4678 LIST_HEAD(ns_list); 4679 4680 /* 4681 * make sure to requeue I/O to all namespaces as these 4682 * might result from the scan itself and must complete 4683 * for the scan_work to make progress 4684 */ 4685 nvme_mpath_clear_ctrl_paths(ctrl); 4686 4687 /* 4688 * Unquiesce io queues so any pending IO won't hang, especially 4689 * those submitted from scan work 4690 */ 4691 nvme_unquiesce_io_queues(ctrl); 4692 4693 /* prevent racing with ns scanning */ 4694 flush_work(&ctrl->scan_work); 4695 4696 /* 4697 * The dead states indicates the controller was not gracefully 4698 * disconnected. In that case, we won't be able to flush any data while 4699 * removing the namespaces' disks; fail all the queues now to avoid 4700 * potentially having to clean up the failed sync later. 4701 */ 4702 if (nvme_ctrl_state(ctrl) == NVME_CTRL_DEAD) 4703 nvme_mark_namespaces_dead(ctrl); 4704 4705 /* this is a no-op when called from the controller reset handler */ 4706 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO); 4707 4708 mutex_lock(&ctrl->namespaces_lock); 4709 list_splice_init_rcu(&ctrl->namespaces, &ns_list, synchronize_rcu); 4710 mutex_unlock(&ctrl->namespaces_lock); 4711 synchronize_srcu(&ctrl->srcu); 4712 4713 list_for_each_entry_safe(ns, next, &ns_list, list) 4714 nvme_ns_remove(ns); 4715 } 4716 EXPORT_SYMBOL_GPL(nvme_remove_namespaces); 4717 4718 static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env) 4719 { 4720 const struct nvme_ctrl *ctrl = 4721 container_of(dev, struct nvme_ctrl, ctrl_device); 4722 struct nvmf_ctrl_options *opts = ctrl->opts; 4723 int ret; 4724 4725 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name); 4726 if (ret) 4727 return ret; 4728 4729 if (opts) { 4730 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr); 4731 if (ret) 4732 return ret; 4733 4734 ret = add_uevent_var(env, "NVME_TRSVCID=%s", 4735 opts->trsvcid ?: "none"); 4736 if (ret) 4737 return ret; 4738 4739 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s", 4740 opts->host_traddr ?: "none"); 4741 if (ret) 4742 return ret; 4743 4744 ret = add_uevent_var(env, "NVME_HOST_IFACE=%s", 4745 opts->host_iface ?: "none"); 4746 } 4747 return ret; 4748 } 4749 4750 static void nvme_change_uevent(struct nvme_ctrl *ctrl, char *envdata) 4751 { 4752 char *envp[2] = { envdata, NULL }; 4753 4754 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp); 4755 } 4756 4757 static void nvme_aen_uevent(struct nvme_ctrl *ctrl) 4758 { 4759 char *envp[2] = { NULL, NULL }; 4760 u32 aen_result = ctrl->aen_result; 4761 4762 ctrl->aen_result = 0; 4763 if (!aen_result) 4764 return; 4765 4766 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result); 4767 if (!envp[0]) 4768 return; 4769 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp); 4770 kfree(envp[0]); 4771 } 4772 4773 static void nvme_async_event_work(struct work_struct *work) 4774 { 4775 struct nvme_ctrl *ctrl = 4776 container_of(work, struct nvme_ctrl, async_event_work); 4777 4778 nvme_aen_uevent(ctrl); 4779 4780 /* 4781 * The transport drivers must guarantee AER submission here is safe by 4782 * flushing ctrl async_event_work after changing the controller state 4783 * from LIVE and before freeing the admin queue. 4784 */ 4785 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE) 4786 ctrl->ops->submit_async_event(ctrl); 4787 } 4788 4789 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl) 4790 { 4791 4792 u32 csts; 4793 4794 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) 4795 return false; 4796 4797 if (csts == ~0) 4798 return false; 4799 4800 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP)); 4801 } 4802 4803 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl) 4804 { 4805 struct nvme_fw_slot_info_log *log; 4806 u8 next_fw_slot, cur_fw_slot; 4807 4808 log = kmalloc_obj(*log); 4809 if (!log) 4810 return; 4811 4812 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM, 4813 log, sizeof(*log), 0)) { 4814 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n"); 4815 goto out_free_log; 4816 } 4817 4818 cur_fw_slot = log->afi & 0x7; 4819 next_fw_slot = (log->afi & 0x70) >> 4; 4820 if (!cur_fw_slot || (next_fw_slot && (cur_fw_slot != next_fw_slot))) { 4821 dev_info(ctrl->device, 4822 "Firmware is activated after next Controller Level Reset\n"); 4823 goto out_free_log; 4824 } 4825 4826 memcpy(ctrl->subsys->firmware_rev, &log->frs[cur_fw_slot - 1], 4827 sizeof(ctrl->subsys->firmware_rev)); 4828 4829 out_free_log: 4830 kfree(log); 4831 } 4832 4833 static void nvme_fw_act_work(struct work_struct *work) 4834 { 4835 struct nvme_ctrl *ctrl = container_of(work, 4836 struct nvme_ctrl, fw_act_work); 4837 unsigned long fw_act_timeout; 4838 4839 nvme_auth_stop(ctrl); 4840 4841 if (ctrl->mtfa) 4842 fw_act_timeout = jiffies + msecs_to_jiffies(ctrl->mtfa * 100); 4843 else 4844 fw_act_timeout = jiffies + secs_to_jiffies(admin_timeout); 4845 4846 nvme_quiesce_io_queues(ctrl); 4847 while (nvme_ctrl_pp_status(ctrl)) { 4848 if (time_after(jiffies, fw_act_timeout)) { 4849 dev_warn(ctrl->device, 4850 "Fw activation timeout, reset controller\n"); 4851 nvme_try_sched_reset(ctrl); 4852 return; 4853 } 4854 msleep(100); 4855 } 4856 4857 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING) || 4858 !nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE)) 4859 return; 4860 4861 nvme_unquiesce_io_queues(ctrl); 4862 /* read FW slot information to clear the AER */ 4863 nvme_get_fw_slot_info(ctrl); 4864 4865 queue_work(nvme_wq, &ctrl->async_event_work); 4866 } 4867 4868 static u32 nvme_aer_type(u32 result) 4869 { 4870 return result & 0x7; 4871 } 4872 4873 static u32 nvme_aer_subtype(u32 result) 4874 { 4875 return (result & 0xff00) >> 8; 4876 } 4877 4878 static bool nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result) 4879 { 4880 u32 aer_notice_type = nvme_aer_subtype(result); 4881 bool requeue = true; 4882 4883 switch (aer_notice_type) { 4884 case NVME_AER_NOTICE_NS_CHANGED: 4885 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events); 4886 nvme_queue_scan(ctrl); 4887 break; 4888 case NVME_AER_NOTICE_FW_ACT_STARTING: 4889 /* 4890 * We are (ab)using the RESETTING state to prevent subsequent 4891 * recovery actions from interfering with the controller's 4892 * firmware activation. 4893 */ 4894 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) { 4895 requeue = false; 4896 queue_work(nvme_wq, &ctrl->fw_act_work); 4897 } 4898 break; 4899 #ifdef CONFIG_NVME_MULTIPATH 4900 case NVME_AER_NOTICE_ANA: 4901 if (!ctrl->ana_log_buf) 4902 break; 4903 queue_work(nvme_wq, &ctrl->ana_work); 4904 break; 4905 #endif 4906 case NVME_AER_NOTICE_DISC_CHANGED: 4907 ctrl->aen_result = result; 4908 break; 4909 default: 4910 dev_warn(ctrl->device, "async event result %08x\n", result); 4911 } 4912 return requeue; 4913 } 4914 4915 static void nvme_handle_aer_persistent_error(struct nvme_ctrl *ctrl) 4916 { 4917 dev_warn(ctrl->device, 4918 "resetting controller due to persistent internal error\n"); 4919 nvme_reset_ctrl(ctrl); 4920 } 4921 4922 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status, 4923 volatile union nvme_result *res) 4924 { 4925 u32 result = le32_to_cpu(res->u32); 4926 u32 aer_type = nvme_aer_type(result); 4927 u32 aer_subtype = nvme_aer_subtype(result); 4928 bool requeue = true; 4929 4930 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS) 4931 return; 4932 4933 trace_nvme_async_event(ctrl, result); 4934 switch (aer_type) { 4935 case NVME_AER_NOTICE: 4936 requeue = nvme_handle_aen_notice(ctrl, result); 4937 break; 4938 case NVME_AER_ERROR: 4939 /* 4940 * For a persistent internal error, don't run async_event_work 4941 * to submit a new AER. The controller reset will do it. 4942 */ 4943 if (aer_subtype == NVME_AER_ERROR_PERSIST_INT_ERR) { 4944 nvme_handle_aer_persistent_error(ctrl); 4945 return; 4946 } 4947 fallthrough; 4948 case NVME_AER_SMART: 4949 case NVME_AER_CSS: 4950 case NVME_AER_VS: 4951 ctrl->aen_result = result; 4952 break; 4953 default: 4954 break; 4955 } 4956 4957 if (requeue) 4958 queue_work(nvme_wq, &ctrl->async_event_work); 4959 } 4960 EXPORT_SYMBOL_GPL(nvme_complete_async_event); 4961 4962 int nvme_alloc_admin_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set, 4963 const struct blk_mq_ops *ops, unsigned int cmd_size) 4964 { 4965 int ret; 4966 4967 memset(set, 0, sizeof(*set)); 4968 set->ops = ops; 4969 set->queue_depth = NVME_AQ_MQ_TAG_DEPTH; 4970 if (ctrl->ops->flags & NVME_F_FABRICS) 4971 /* Reserved for fabric connect and keep alive */ 4972 set->reserved_tags = 2; 4973 set->numa_node = ctrl->numa_node; 4974 if (ctrl->ops->flags & NVME_F_BLOCKING) 4975 set->flags |= BLK_MQ_F_BLOCKING; 4976 set->cmd_size = cmd_size; 4977 set->driver_data = ctrl; 4978 set->nr_hw_queues = 1; 4979 set->timeout = NVME_ADMIN_TIMEOUT; 4980 ret = blk_mq_alloc_tag_set(set); 4981 if (ret) 4982 return ret; 4983 4984 WARN_ON_ONCE(ctrl->admin_q); 4985 4986 ctrl->admin_q = blk_mq_alloc_queue(set, NULL, NULL); 4987 if (IS_ERR(ctrl->admin_q)) { 4988 ret = PTR_ERR(ctrl->admin_q); 4989 goto out_free_tagset; 4990 } 4991 4992 if (ctrl->ops->flags & NVME_F_FABRICS) { 4993 ctrl->fabrics_q = blk_mq_alloc_queue(set, NULL, NULL); 4994 if (IS_ERR(ctrl->fabrics_q)) { 4995 ret = PTR_ERR(ctrl->fabrics_q); 4996 goto out_cleanup_admin_q; 4997 } 4998 } 4999 5000 ctrl->admin_tagset = set; 5001 return 0; 5002 5003 out_cleanup_admin_q: 5004 blk_mq_destroy_queue(ctrl->admin_q); 5005 blk_put_queue(ctrl->admin_q); 5006 out_free_tagset: 5007 blk_mq_free_tag_set(set); 5008 ctrl->admin_q = NULL; 5009 ctrl->fabrics_q = NULL; 5010 return ret; 5011 } 5012 EXPORT_SYMBOL_GPL(nvme_alloc_admin_tag_set); 5013 5014 void nvme_remove_admin_tag_set(struct nvme_ctrl *ctrl) 5015 { 5016 /* 5017 * As we're about to destroy the queue and free tagset 5018 * we can not have keep-alive work running. 5019 */ 5020 nvme_stop_keep_alive(ctrl); 5021 blk_mq_destroy_queue(ctrl->admin_q); 5022 if (ctrl->fabrics_q) 5023 blk_mq_destroy_queue(ctrl->fabrics_q); 5024 blk_mq_free_tag_set(ctrl->admin_tagset); 5025 } 5026 EXPORT_SYMBOL_GPL(nvme_remove_admin_tag_set); 5027 5028 int nvme_alloc_io_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set, 5029 const struct blk_mq_ops *ops, unsigned int nr_maps, 5030 unsigned int cmd_size) 5031 { 5032 int ret; 5033 5034 memset(set, 0, sizeof(*set)); 5035 set->ops = ops; 5036 set->queue_depth = min_t(unsigned, ctrl->sqsize, BLK_MQ_MAX_DEPTH - 1); 5037 /* 5038 * Some Apple controllers requires tags to be unique across admin and 5039 * the (only) I/O queue, so reserve the first 32 tags of the I/O queue. 5040 */ 5041 if (ctrl->quirks & NVME_QUIRK_SHARED_TAGS) 5042 set->reserved_tags = NVME_AQ_DEPTH; 5043 else if (ctrl->ops->flags & NVME_F_FABRICS) 5044 /* Reserved for fabric connect */ 5045 set->reserved_tags = 1; 5046 set->numa_node = ctrl->numa_node; 5047 if (ctrl->ops->flags & NVME_F_BLOCKING) 5048 set->flags |= BLK_MQ_F_BLOCKING; 5049 set->cmd_size = cmd_size; 5050 set->driver_data = ctrl; 5051 set->nr_hw_queues = ctrl->queue_count - 1; 5052 set->timeout = NVME_IO_TIMEOUT; 5053 set->nr_maps = nr_maps; 5054 ret = blk_mq_alloc_tag_set(set); 5055 if (ret) 5056 return ret; 5057 5058 if (ctrl->ops->flags & NVME_F_FABRICS) { 5059 struct queue_limits lim = { 5060 .features = BLK_FEAT_SKIP_TAGSET_QUIESCE, 5061 }; 5062 5063 ctrl->connect_q = blk_mq_alloc_queue(set, &lim, NULL); 5064 if (IS_ERR(ctrl->connect_q)) { 5065 ret = PTR_ERR(ctrl->connect_q); 5066 goto out_free_tag_set; 5067 } 5068 } 5069 5070 ctrl->tagset = set; 5071 return 0; 5072 5073 out_free_tag_set: 5074 blk_mq_free_tag_set(set); 5075 ctrl->connect_q = NULL; 5076 return ret; 5077 } 5078 EXPORT_SYMBOL_GPL(nvme_alloc_io_tag_set); 5079 5080 void nvme_remove_io_tag_set(struct nvme_ctrl *ctrl) 5081 { 5082 if (ctrl->ops->flags & NVME_F_FABRICS) { 5083 blk_mq_destroy_queue(ctrl->connect_q); 5084 blk_put_queue(ctrl->connect_q); 5085 } 5086 blk_mq_free_tag_set(ctrl->tagset); 5087 } 5088 EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set); 5089 5090 void nvme_stop_ctrl(struct nvme_ctrl *ctrl) 5091 { 5092 nvme_mpath_stop(ctrl); 5093 nvme_auth_stop(ctrl); 5094 nvme_stop_failfast_work(ctrl); 5095 flush_work(&ctrl->async_event_work); 5096 cancel_work_sync(&ctrl->fw_act_work); 5097 if (ctrl->ops->stop_ctrl) 5098 ctrl->ops->stop_ctrl(ctrl); 5099 } 5100 EXPORT_SYMBOL_GPL(nvme_stop_ctrl); 5101 5102 void nvme_start_ctrl(struct nvme_ctrl *ctrl) 5103 { 5104 nvme_enable_aen(ctrl); 5105 5106 /* 5107 * persistent discovery controllers need to send indication to userspace 5108 * to re-read the discovery log page to learn about possible changes 5109 * that were missed. We identify persistent discovery controllers by 5110 * checking that they started once before, hence are reconnecting back. 5111 */ 5112 if (test_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags) && 5113 nvme_discovery_ctrl(ctrl)) { 5114 if (!ctrl->kato) { 5115 nvme_stop_keep_alive(ctrl); 5116 ctrl->kato = NVME_DEFAULT_KATO; 5117 nvme_start_keep_alive(ctrl); 5118 } 5119 nvme_change_uevent(ctrl, "NVME_EVENT=rediscover"); 5120 } 5121 5122 if (ctrl->queue_count > 1) { 5123 nvme_queue_scan(ctrl); 5124 nvme_unquiesce_io_queues(ctrl); 5125 nvme_mpath_update(ctrl); 5126 } 5127 5128 set_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags); 5129 nvme_change_uevent(ctrl, "NVME_EVENT=connected"); 5130 } 5131 EXPORT_SYMBOL_GPL(nvme_start_ctrl); 5132 5133 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl) 5134 { 5135 nvme_stop_keep_alive(ctrl); 5136 nvme_hwmon_exit(ctrl); 5137 nvme_fault_inject_fini(&ctrl->fault_inject); 5138 dev_pm_qos_hide_latency_tolerance(ctrl->device); 5139 cdev_device_del(&ctrl->cdev, ctrl->device); 5140 nvme_put_ctrl(ctrl); 5141 } 5142 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl); 5143 5144 static void nvme_free_cels(struct nvme_ctrl *ctrl) 5145 { 5146 struct nvme_effects_log *cel; 5147 unsigned long i; 5148 5149 xa_for_each(&ctrl->cels, i, cel) { 5150 xa_erase(&ctrl->cels, i); 5151 kfree(cel); 5152 } 5153 5154 xa_destroy(&ctrl->cels); 5155 } 5156 5157 static void nvme_free_ctrl(struct device *dev) 5158 { 5159 struct nvme_ctrl *ctrl = 5160 container_of(dev, struct nvme_ctrl, ctrl_device); 5161 struct nvme_subsystem *subsys = ctrl->subsys; 5162 5163 if (ctrl->admin_q) 5164 blk_put_queue(ctrl->admin_q); 5165 if (ctrl->fabrics_q) 5166 blk_put_queue(ctrl->fabrics_q); 5167 if (!subsys || ctrl->instance != subsys->instance) 5168 ida_free(&nvme_instance_ida, ctrl->instance); 5169 nvme_free_cels(ctrl); 5170 nvme_mpath_uninit(ctrl); 5171 cleanup_srcu_struct(&ctrl->srcu); 5172 nvme_auth_stop(ctrl); 5173 nvme_auth_free(ctrl); 5174 __free_page(ctrl->discard_page); 5175 free_opal_dev(ctrl->opal_dev); 5176 5177 if (subsys) { 5178 mutex_lock(&nvme_subsystems_lock); 5179 list_del(&ctrl->subsys_entry); 5180 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device)); 5181 mutex_unlock(&nvme_subsystems_lock); 5182 } 5183 5184 ctrl->ops->free_ctrl(ctrl); 5185 5186 if (subsys) 5187 nvme_put_subsystem(subsys); 5188 } 5189 5190 /* 5191 * Initialize a NVMe controller structures. This needs to be called during 5192 * earliest initialization so that we have the initialized structured around 5193 * during probing. 5194 * 5195 * On success, the caller must use the nvme_put_ctrl() to release this when 5196 * needed, which also invokes the ops->free_ctrl() callback. 5197 */ 5198 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev, 5199 const struct nvme_ctrl_ops *ops, unsigned long quirks) 5200 { 5201 int ret; 5202 5203 WRITE_ONCE(ctrl->state, NVME_CTRL_NEW); 5204 ctrl->passthru_err_log_enabled = false; 5205 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags); 5206 spin_lock_init(&ctrl->lock); 5207 mutex_init(&ctrl->namespaces_lock); 5208 5209 ret = init_srcu_struct(&ctrl->srcu); 5210 if (ret) 5211 return ret; 5212 5213 mutex_init(&ctrl->scan_lock); 5214 INIT_LIST_HEAD(&ctrl->namespaces); 5215 xa_init(&ctrl->cels); 5216 ctrl->dev = dev; 5217 ctrl->ops = ops; 5218 ctrl->quirks = quirks; 5219 ctrl->numa_node = NUMA_NO_NODE; 5220 INIT_WORK(&ctrl->scan_work, nvme_scan_work); 5221 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work); 5222 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work); 5223 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work); 5224 init_waitqueue_head(&ctrl->state_wq); 5225 5226 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work); 5227 INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work); 5228 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd)); 5229 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive; 5230 ctrl->ka_last_check_time = jiffies; 5231 ctrl->admin_timeout = NVME_ADMIN_TIMEOUT; 5232 ctrl->io_timeout = NVME_IO_TIMEOUT; 5233 5234 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) > 5235 PAGE_SIZE); 5236 ctrl->discard_page = alloc_page(GFP_KERNEL | __GFP_ZERO); 5237 if (!ctrl->discard_page) { 5238 ret = -ENOMEM; 5239 goto out; 5240 } 5241 5242 ret = ida_alloc(&nvme_instance_ida, GFP_KERNEL); 5243 if (ret < 0) 5244 goto out; 5245 ctrl->instance = ret; 5246 5247 ret = nvme_auth_init_ctrl(ctrl); 5248 if (ret) 5249 goto out_release_instance; 5250 5251 nvme_mpath_init_ctrl(ctrl); 5252 5253 device_initialize(&ctrl->ctrl_device); 5254 ctrl->device = &ctrl->ctrl_device; 5255 ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt), 5256 ctrl->instance); 5257 ctrl->device->class = &nvme_class; 5258 ctrl->device->parent = ctrl->dev; 5259 if (ops->dev_attr_groups) 5260 ctrl->device->groups = ops->dev_attr_groups; 5261 else 5262 ctrl->device->groups = nvme_dev_attr_groups; 5263 ctrl->device->release = nvme_free_ctrl; 5264 dev_set_drvdata(ctrl->device, ctrl); 5265 5266 return ret; 5267 5268 out_release_instance: 5269 ida_free(&nvme_instance_ida, ctrl->instance); 5270 out: 5271 if (ctrl->discard_page) 5272 __free_page(ctrl->discard_page); 5273 cleanup_srcu_struct(&ctrl->srcu); 5274 return ret; 5275 } 5276 EXPORT_SYMBOL_GPL(nvme_init_ctrl); 5277 5278 /* 5279 * On success, returns with an elevated controller reference and caller must 5280 * use nvme_uninit_ctrl() to properly free resources associated with the ctrl. 5281 */ 5282 int nvme_add_ctrl(struct nvme_ctrl *ctrl) 5283 { 5284 int ret; 5285 5286 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance); 5287 if (ret) 5288 return ret; 5289 5290 cdev_init(&ctrl->cdev, &nvme_dev_fops); 5291 ctrl->cdev.owner = ctrl->ops->module; 5292 ret = cdev_device_add(&ctrl->cdev, ctrl->device); 5293 if (ret) 5294 return ret; 5295 5296 /* 5297 * Initialize latency tolerance controls. The sysfs files won't 5298 * be visible to userspace unless the device actually supports APST. 5299 */ 5300 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance; 5301 dev_pm_qos_update_user_latency_tolerance(ctrl->device, 5302 min(default_ps_max_latency_us, (unsigned long)S32_MAX)); 5303 5304 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device)); 5305 nvme_get_ctrl(ctrl); 5306 5307 return 0; 5308 } 5309 EXPORT_SYMBOL_GPL(nvme_add_ctrl); 5310 5311 /* let I/O to all namespaces fail in preparation for surprise removal */ 5312 void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl) 5313 { 5314 struct nvme_ns *ns; 5315 int srcu_idx; 5316 5317 srcu_idx = srcu_read_lock(&ctrl->srcu); 5318 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5319 srcu_read_lock_held(&ctrl->srcu)) 5320 blk_mark_disk_dead(ns->disk); 5321 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5322 } 5323 EXPORT_SYMBOL_GPL(nvme_mark_namespaces_dead); 5324 5325 void nvme_unfreeze(struct nvme_ctrl *ctrl) 5326 { 5327 struct nvme_ns *ns; 5328 int srcu_idx; 5329 5330 srcu_idx = srcu_read_lock(&ctrl->srcu); 5331 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5332 srcu_read_lock_held(&ctrl->srcu)) 5333 blk_mq_unfreeze_queue_non_owner(ns->queue); 5334 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5335 clear_bit(NVME_CTRL_FROZEN, &ctrl->flags); 5336 } 5337 EXPORT_SYMBOL_GPL(nvme_unfreeze); 5338 5339 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl) 5340 { 5341 long timeout = ctrl->io_timeout; 5342 struct nvme_ns *ns; 5343 int srcu_idx; 5344 5345 srcu_idx = srcu_read_lock(&ctrl->srcu); 5346 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5347 srcu_read_lock_held(&ctrl->srcu)) { 5348 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout); 5349 if (timeout <= 0) 5350 break; 5351 } 5352 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5353 return timeout; 5354 } 5355 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout); 5356 5357 void nvme_wait_freeze(struct nvme_ctrl *ctrl) 5358 { 5359 struct nvme_ns *ns; 5360 int srcu_idx; 5361 5362 srcu_idx = srcu_read_lock(&ctrl->srcu); 5363 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5364 srcu_read_lock_held(&ctrl->srcu)) 5365 blk_mq_freeze_queue_wait(ns->queue); 5366 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5367 } 5368 EXPORT_SYMBOL_GPL(nvme_wait_freeze); 5369 5370 void nvme_start_freeze(struct nvme_ctrl *ctrl) 5371 { 5372 struct nvme_ns *ns; 5373 int srcu_idx; 5374 5375 set_bit(NVME_CTRL_FROZEN, &ctrl->flags); 5376 srcu_idx = srcu_read_lock(&ctrl->srcu); 5377 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5378 srcu_read_lock_held(&ctrl->srcu)) 5379 /* 5380 * Typical non_owner use case is from pci driver, in which 5381 * start_freeze is called from timeout work function, but 5382 * unfreeze is done in reset work context 5383 */ 5384 blk_freeze_queue_start_non_owner(ns->queue); 5385 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5386 } 5387 EXPORT_SYMBOL_GPL(nvme_start_freeze); 5388 5389 void nvme_quiesce_io_queues(struct nvme_ctrl *ctrl) 5390 { 5391 if (!ctrl->tagset) 5392 return; 5393 if (!test_and_set_bit(NVME_CTRL_STOPPED, &ctrl->flags)) 5394 blk_mq_quiesce_tagset(ctrl->tagset); 5395 else 5396 blk_mq_wait_quiesce_done(ctrl->tagset); 5397 } 5398 EXPORT_SYMBOL_GPL(nvme_quiesce_io_queues); 5399 5400 void nvme_unquiesce_io_queues(struct nvme_ctrl *ctrl) 5401 { 5402 if (!ctrl->tagset) 5403 return; 5404 if (test_and_clear_bit(NVME_CTRL_STOPPED, &ctrl->flags)) 5405 blk_mq_unquiesce_tagset(ctrl->tagset); 5406 } 5407 EXPORT_SYMBOL_GPL(nvme_unquiesce_io_queues); 5408 5409 void nvme_quiesce_admin_queue(struct nvme_ctrl *ctrl) 5410 { 5411 if (!test_and_set_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags)) 5412 blk_mq_quiesce_queue(ctrl->admin_q); 5413 else 5414 blk_mq_wait_quiesce_done(ctrl->admin_q->tag_set); 5415 } 5416 EXPORT_SYMBOL_GPL(nvme_quiesce_admin_queue); 5417 5418 void nvme_unquiesce_admin_queue(struct nvme_ctrl *ctrl) 5419 { 5420 if (test_and_clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags)) 5421 blk_mq_unquiesce_queue(ctrl->admin_q); 5422 } 5423 EXPORT_SYMBOL_GPL(nvme_unquiesce_admin_queue); 5424 5425 void nvme_sync_io_queues(struct nvme_ctrl *ctrl) 5426 { 5427 struct nvme_ns *ns; 5428 int srcu_idx; 5429 5430 srcu_idx = srcu_read_lock(&ctrl->srcu); 5431 list_for_each_entry_srcu(ns, &ctrl->namespaces, list, 5432 srcu_read_lock_held(&ctrl->srcu)) 5433 blk_sync_queue(ns->queue); 5434 srcu_read_unlock(&ctrl->srcu, srcu_idx); 5435 } 5436 EXPORT_SYMBOL_GPL(nvme_sync_io_queues); 5437 5438 void nvme_sync_queues(struct nvme_ctrl *ctrl) 5439 { 5440 nvme_sync_io_queues(ctrl); 5441 if (ctrl->admin_q) 5442 blk_sync_queue(ctrl->admin_q); 5443 } 5444 EXPORT_SYMBOL_GPL(nvme_sync_queues); 5445 5446 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file) 5447 { 5448 if (file->f_op != &nvme_dev_fops) 5449 return NULL; 5450 return file->private_data; 5451 } 5452 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, "NVME_TARGET_PASSTHRU"); 5453 5454 /* 5455 * Check we didn't inadvertently grow the command structure sizes: 5456 */ 5457 static inline void _nvme_check_size(void) 5458 { 5459 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64); 5460 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64); 5461 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64); 5462 BUILD_BUG_ON(sizeof(struct nvme_features) != 64); 5463 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64); 5464 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64); 5465 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64); 5466 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64); 5467 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64); 5468 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64); 5469 BUILD_BUG_ON(sizeof(struct nvme_command) != 64); 5470 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE); 5471 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE); 5472 BUILD_BUG_ON(sizeof(struct nvme_id_ns_cs_indep) != 5473 NVME_IDENTIFY_DATA_SIZE); 5474 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE); 5475 BUILD_BUG_ON(sizeof(struct nvme_id_ns_nvm) != NVME_IDENTIFY_DATA_SIZE); 5476 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE); 5477 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE); 5478 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64); 5479 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512); 5480 BUILD_BUG_ON(sizeof(struct nvme_endurance_group_log) != 512); 5481 BUILD_BUG_ON(sizeof(struct nvme_rotational_media_log) != 512); 5482 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64); 5483 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64); 5484 BUILD_BUG_ON(sizeof(struct nvme_feat_host_behavior) != 512); 5485 } 5486 5487 5488 static int __init nvme_core_init(void) 5489 { 5490 unsigned int wq_flags = WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS; 5491 int result = -ENOMEM; 5492 5493 _nvme_check_size(); 5494 5495 nvme_wq = alloc_workqueue("nvme-wq", wq_flags, 0); 5496 if (!nvme_wq) 5497 goto out; 5498 5499 nvme_reset_wq = alloc_workqueue("nvme-reset-wq", wq_flags, 0); 5500 if (!nvme_reset_wq) 5501 goto destroy_wq; 5502 5503 nvme_delete_wq = alloc_workqueue("nvme-delete-wq", wq_flags, 0); 5504 if (!nvme_delete_wq) 5505 goto destroy_reset_wq; 5506 5507 result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0, 5508 NVME_MINORS, "nvme"); 5509 if (result < 0) 5510 goto destroy_delete_wq; 5511 5512 result = class_register(&nvme_class); 5513 if (result) 5514 goto unregister_chrdev; 5515 5516 result = class_register(&nvme_subsys_class); 5517 if (result) 5518 goto destroy_class; 5519 5520 result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS, 5521 "nvme-generic"); 5522 if (result < 0) 5523 goto destroy_subsys_class; 5524 5525 result = class_register(&nvme_ns_chr_class); 5526 if (result) 5527 goto unregister_generic_ns; 5528 5529 result = nvme_init_auth(); 5530 if (result) 5531 goto destroy_ns_chr; 5532 return 0; 5533 5534 destroy_ns_chr: 5535 class_unregister(&nvme_ns_chr_class); 5536 unregister_generic_ns: 5537 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS); 5538 destroy_subsys_class: 5539 class_unregister(&nvme_subsys_class); 5540 destroy_class: 5541 class_unregister(&nvme_class); 5542 unregister_chrdev: 5543 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS); 5544 destroy_delete_wq: 5545 destroy_workqueue(nvme_delete_wq); 5546 destroy_reset_wq: 5547 destroy_workqueue(nvme_reset_wq); 5548 destroy_wq: 5549 destroy_workqueue(nvme_wq); 5550 out: 5551 return result; 5552 } 5553 5554 static void __exit nvme_core_exit(void) 5555 { 5556 nvme_exit_auth(); 5557 class_unregister(&nvme_ns_chr_class); 5558 class_unregister(&nvme_subsys_class); 5559 class_unregister(&nvme_class); 5560 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS); 5561 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS); 5562 destroy_workqueue(nvme_delete_wq); 5563 destroy_workqueue(nvme_reset_wq); 5564 destroy_workqueue(nvme_wq); 5565 ida_destroy(&nvme_ns_chr_minor_ida); 5566 ida_destroy(&nvme_instance_ida); 5567 } 5568 5569 MODULE_LICENSE("GPL"); 5570 MODULE_VERSION("1.0"); 5571 MODULE_DESCRIPTION("NVMe host core framework"); 5572 module_init(nvme_core_init); 5573 module_exit(nvme_core_exit); 5574