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