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