1 /* 2 * NVM Express device driver 3 * Copyright (c) 2011-2014, Intel Corporation. 4 * 5 * This program is free software; you can redistribute it and/or modify it 6 * under the terms and conditions of the GNU General Public License, 7 * version 2, as published by the Free Software Foundation. 8 * 9 * This program is distributed in the hope it will be useful, but WITHOUT 10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 12 * more details. 13 */ 14 15 #include <linux/blkdev.h> 16 #include <linux/blk-mq.h> 17 #include <linux/delay.h> 18 #include <linux/errno.h> 19 #include <linux/hdreg.h> 20 #include <linux/kernel.h> 21 #include <linux/module.h> 22 #include <linux/list_sort.h> 23 #include <linux/slab.h> 24 #include <linux/types.h> 25 #include <linux/pr.h> 26 #include <linux/ptrace.h> 27 #include <linux/nvme_ioctl.h> 28 #include <linux/t10-pi.h> 29 #include <linux/pm_qos.h> 30 #include <asm/unaligned.h> 31 32 #define CREATE_TRACE_POINTS 33 #include "trace.h" 34 35 #include "nvme.h" 36 #include "fabrics.h" 37 38 #define NVME_MINORS (1U << MINORBITS) 39 40 unsigned int admin_timeout = 60; 41 module_param(admin_timeout, uint, 0644); 42 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands"); 43 EXPORT_SYMBOL_GPL(admin_timeout); 44 45 unsigned int nvme_io_timeout = 30; 46 module_param_named(io_timeout, nvme_io_timeout, uint, 0644); 47 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O"); 48 EXPORT_SYMBOL_GPL(nvme_io_timeout); 49 50 static unsigned char shutdown_timeout = 5; 51 module_param(shutdown_timeout, byte, 0644); 52 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown"); 53 54 static u8 nvme_max_retries = 5; 55 module_param_named(max_retries, nvme_max_retries, byte, 0644); 56 MODULE_PARM_DESC(max_retries, "max number of retries a command may have"); 57 58 static unsigned long default_ps_max_latency_us = 100000; 59 module_param(default_ps_max_latency_us, ulong, 0644); 60 MODULE_PARM_DESC(default_ps_max_latency_us, 61 "max power saving latency for new devices; use PM QOS to change per device"); 62 63 static bool force_apst; 64 module_param(force_apst, bool, 0644); 65 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off"); 66 67 static bool streams; 68 module_param(streams, bool, 0644); 69 MODULE_PARM_DESC(streams, "turn on support for Streams write directives"); 70 71 /* 72 * nvme_wq - hosts nvme related works that are not reset or delete 73 * nvme_reset_wq - hosts nvme reset works 74 * nvme_delete_wq - hosts nvme delete works 75 * 76 * nvme_wq will host works such are scan, aen handling, fw activation, 77 * keep-alive error recovery, periodic reconnects etc. nvme_reset_wq 78 * runs reset works which also flush works hosted on nvme_wq for 79 * serialization purposes. nvme_delete_wq host controller deletion 80 * works which flush reset works for serialization. 81 */ 82 struct workqueue_struct *nvme_wq; 83 EXPORT_SYMBOL_GPL(nvme_wq); 84 85 struct workqueue_struct *nvme_reset_wq; 86 EXPORT_SYMBOL_GPL(nvme_reset_wq); 87 88 struct workqueue_struct *nvme_delete_wq; 89 EXPORT_SYMBOL_GPL(nvme_delete_wq); 90 91 static DEFINE_IDA(nvme_subsystems_ida); 92 static LIST_HEAD(nvme_subsystems); 93 static DEFINE_MUTEX(nvme_subsystems_lock); 94 95 static DEFINE_IDA(nvme_instance_ida); 96 static dev_t nvme_chr_devt; 97 static struct class *nvme_class; 98 static struct class *nvme_subsys_class; 99 100 static void nvme_ns_remove(struct nvme_ns *ns); 101 static int nvme_revalidate_disk(struct gendisk *disk); 102 103 int nvme_reset_ctrl(struct nvme_ctrl *ctrl) 104 { 105 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) 106 return -EBUSY; 107 if (!queue_work(nvme_reset_wq, &ctrl->reset_work)) 108 return -EBUSY; 109 return 0; 110 } 111 EXPORT_SYMBOL_GPL(nvme_reset_ctrl); 112 113 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl) 114 { 115 int ret; 116 117 ret = nvme_reset_ctrl(ctrl); 118 if (!ret) { 119 flush_work(&ctrl->reset_work); 120 if (ctrl->state != NVME_CTRL_LIVE) 121 ret = -ENETRESET; 122 } 123 124 return ret; 125 } 126 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync); 127 128 static void nvme_delete_ctrl_work(struct work_struct *work) 129 { 130 struct nvme_ctrl *ctrl = 131 container_of(work, struct nvme_ctrl, delete_work); 132 133 dev_info(ctrl->device, 134 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn); 135 136 flush_work(&ctrl->reset_work); 137 nvme_stop_ctrl(ctrl); 138 nvme_remove_namespaces(ctrl); 139 ctrl->ops->delete_ctrl(ctrl); 140 nvme_uninit_ctrl(ctrl); 141 nvme_put_ctrl(ctrl); 142 } 143 144 int nvme_delete_ctrl(struct nvme_ctrl *ctrl) 145 { 146 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING)) 147 return -EBUSY; 148 if (!queue_work(nvme_delete_wq, &ctrl->delete_work)) 149 return -EBUSY; 150 return 0; 151 } 152 EXPORT_SYMBOL_GPL(nvme_delete_ctrl); 153 154 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl) 155 { 156 int ret = 0; 157 158 /* 159 * Keep a reference until the work is flushed since ->delete_ctrl 160 * can free the controller. 161 */ 162 nvme_get_ctrl(ctrl); 163 ret = nvme_delete_ctrl(ctrl); 164 if (!ret) 165 flush_work(&ctrl->delete_work); 166 nvme_put_ctrl(ctrl); 167 return ret; 168 } 169 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync); 170 171 static inline bool nvme_ns_has_pi(struct nvme_ns *ns) 172 { 173 return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple); 174 } 175 176 static blk_status_t nvme_error_status(struct request *req) 177 { 178 switch (nvme_req(req)->status & 0x7ff) { 179 case NVME_SC_SUCCESS: 180 return BLK_STS_OK; 181 case NVME_SC_CAP_EXCEEDED: 182 return BLK_STS_NOSPC; 183 case NVME_SC_LBA_RANGE: 184 return BLK_STS_TARGET; 185 case NVME_SC_BAD_ATTRIBUTES: 186 case NVME_SC_ONCS_NOT_SUPPORTED: 187 case NVME_SC_INVALID_OPCODE: 188 case NVME_SC_INVALID_FIELD: 189 case NVME_SC_INVALID_NS: 190 return BLK_STS_NOTSUPP; 191 case NVME_SC_WRITE_FAULT: 192 case NVME_SC_READ_ERROR: 193 case NVME_SC_UNWRITTEN_BLOCK: 194 case NVME_SC_ACCESS_DENIED: 195 case NVME_SC_READ_ONLY: 196 case NVME_SC_COMPARE_FAILED: 197 return BLK_STS_MEDIUM; 198 case NVME_SC_GUARD_CHECK: 199 case NVME_SC_APPTAG_CHECK: 200 case NVME_SC_REFTAG_CHECK: 201 case NVME_SC_INVALID_PI: 202 return BLK_STS_PROTECTION; 203 case NVME_SC_RESERVATION_CONFLICT: 204 return BLK_STS_NEXUS; 205 default: 206 return BLK_STS_IOERR; 207 } 208 } 209 210 static inline bool nvme_req_needs_retry(struct request *req) 211 { 212 if (blk_noretry_request(req)) 213 return false; 214 if (nvme_req(req)->status & NVME_SC_DNR) 215 return false; 216 if (nvme_req(req)->retries >= nvme_max_retries) 217 return false; 218 return true; 219 } 220 221 void nvme_complete_rq(struct request *req) 222 { 223 blk_status_t status = nvme_error_status(req); 224 225 trace_nvme_complete_rq(req); 226 227 if (unlikely(status != BLK_STS_OK && nvme_req_needs_retry(req))) { 228 if (nvme_req_needs_failover(req, status)) { 229 nvme_failover_req(req); 230 return; 231 } 232 233 if (!blk_queue_dying(req->q)) { 234 nvme_req(req)->retries++; 235 blk_mq_requeue_request(req, true); 236 return; 237 } 238 } 239 blk_mq_end_request(req, status); 240 } 241 EXPORT_SYMBOL_GPL(nvme_complete_rq); 242 243 void nvme_cancel_request(struct request *req, void *data, bool reserved) 244 { 245 if (!blk_mq_request_started(req)) 246 return; 247 248 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device, 249 "Cancelling I/O %d", req->tag); 250 251 nvme_req(req)->status = NVME_SC_ABORT_REQ; 252 blk_mq_complete_request(req); 253 254 } 255 EXPORT_SYMBOL_GPL(nvme_cancel_request); 256 257 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl, 258 enum nvme_ctrl_state new_state) 259 { 260 enum nvme_ctrl_state old_state; 261 unsigned long flags; 262 bool changed = false; 263 264 spin_lock_irqsave(&ctrl->lock, flags); 265 266 old_state = ctrl->state; 267 switch (new_state) { 268 case NVME_CTRL_ADMIN_ONLY: 269 switch (old_state) { 270 case NVME_CTRL_CONNECTING: 271 changed = true; 272 /* FALLTHRU */ 273 default: 274 break; 275 } 276 break; 277 case NVME_CTRL_LIVE: 278 switch (old_state) { 279 case NVME_CTRL_NEW: 280 case NVME_CTRL_RESETTING: 281 case NVME_CTRL_CONNECTING: 282 changed = true; 283 /* FALLTHRU */ 284 default: 285 break; 286 } 287 break; 288 case NVME_CTRL_RESETTING: 289 switch (old_state) { 290 case NVME_CTRL_NEW: 291 case NVME_CTRL_LIVE: 292 case NVME_CTRL_ADMIN_ONLY: 293 changed = true; 294 /* FALLTHRU */ 295 default: 296 break; 297 } 298 break; 299 case NVME_CTRL_CONNECTING: 300 switch (old_state) { 301 case NVME_CTRL_NEW: 302 case NVME_CTRL_RESETTING: 303 changed = true; 304 /* FALLTHRU */ 305 default: 306 break; 307 } 308 break; 309 case NVME_CTRL_DELETING: 310 switch (old_state) { 311 case NVME_CTRL_LIVE: 312 case NVME_CTRL_ADMIN_ONLY: 313 case NVME_CTRL_RESETTING: 314 case NVME_CTRL_CONNECTING: 315 changed = true; 316 /* FALLTHRU */ 317 default: 318 break; 319 } 320 break; 321 case NVME_CTRL_DEAD: 322 switch (old_state) { 323 case NVME_CTRL_DELETING: 324 changed = true; 325 /* FALLTHRU */ 326 default: 327 break; 328 } 329 break; 330 default: 331 break; 332 } 333 334 if (changed) 335 ctrl->state = new_state; 336 337 spin_unlock_irqrestore(&ctrl->lock, flags); 338 if (changed && ctrl->state == NVME_CTRL_LIVE) 339 nvme_kick_requeue_lists(ctrl); 340 return changed; 341 } 342 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state); 343 344 static void nvme_free_ns_head(struct kref *ref) 345 { 346 struct nvme_ns_head *head = 347 container_of(ref, struct nvme_ns_head, ref); 348 349 nvme_mpath_remove_disk(head); 350 ida_simple_remove(&head->subsys->ns_ida, head->instance); 351 list_del_init(&head->entry); 352 cleanup_srcu_struct(&head->srcu); 353 kfree(head); 354 } 355 356 static void nvme_put_ns_head(struct nvme_ns_head *head) 357 { 358 kref_put(&head->ref, nvme_free_ns_head); 359 } 360 361 static void nvme_free_ns(struct kref *kref) 362 { 363 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref); 364 365 if (ns->ndev) 366 nvme_nvm_unregister(ns); 367 368 put_disk(ns->disk); 369 nvme_put_ns_head(ns->head); 370 nvme_put_ctrl(ns->ctrl); 371 kfree(ns); 372 } 373 374 static void nvme_put_ns(struct nvme_ns *ns) 375 { 376 kref_put(&ns->kref, nvme_free_ns); 377 } 378 379 static inline void nvme_clear_nvme_request(struct request *req) 380 { 381 if (!(req->rq_flags & RQF_DONTPREP)) { 382 nvme_req(req)->retries = 0; 383 nvme_req(req)->flags = 0; 384 req->rq_flags |= RQF_DONTPREP; 385 } 386 } 387 388 struct request *nvme_alloc_request(struct request_queue *q, 389 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid) 390 { 391 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN; 392 struct request *req; 393 394 if (qid == NVME_QID_ANY) { 395 req = blk_mq_alloc_request(q, op, flags); 396 } else { 397 req = blk_mq_alloc_request_hctx(q, op, flags, 398 qid ? qid - 1 : 0); 399 } 400 if (IS_ERR(req)) 401 return req; 402 403 req->cmd_flags |= REQ_FAILFAST_DRIVER; 404 nvme_clear_nvme_request(req); 405 nvme_req(req)->cmd = cmd; 406 407 return req; 408 } 409 EXPORT_SYMBOL_GPL(nvme_alloc_request); 410 411 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable) 412 { 413 struct nvme_command c; 414 415 memset(&c, 0, sizeof(c)); 416 417 c.directive.opcode = nvme_admin_directive_send; 418 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL); 419 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE; 420 c.directive.dtype = NVME_DIR_IDENTIFY; 421 c.directive.tdtype = NVME_DIR_STREAMS; 422 c.directive.endir = enable ? NVME_DIR_ENDIR : 0; 423 424 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0); 425 } 426 427 static int nvme_disable_streams(struct nvme_ctrl *ctrl) 428 { 429 return nvme_toggle_streams(ctrl, false); 430 } 431 432 static int nvme_enable_streams(struct nvme_ctrl *ctrl) 433 { 434 return nvme_toggle_streams(ctrl, true); 435 } 436 437 static int nvme_get_stream_params(struct nvme_ctrl *ctrl, 438 struct streams_directive_params *s, u32 nsid) 439 { 440 struct nvme_command c; 441 442 memset(&c, 0, sizeof(c)); 443 memset(s, 0, sizeof(*s)); 444 445 c.directive.opcode = nvme_admin_directive_recv; 446 c.directive.nsid = cpu_to_le32(nsid); 447 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1); 448 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM; 449 c.directive.dtype = NVME_DIR_STREAMS; 450 451 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s)); 452 } 453 454 static int nvme_configure_directives(struct nvme_ctrl *ctrl) 455 { 456 struct streams_directive_params s; 457 int ret; 458 459 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES)) 460 return 0; 461 if (!streams) 462 return 0; 463 464 ret = nvme_enable_streams(ctrl); 465 if (ret) 466 return ret; 467 468 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL); 469 if (ret) 470 return ret; 471 472 ctrl->nssa = le16_to_cpu(s.nssa); 473 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) { 474 dev_info(ctrl->device, "too few streams (%u) available\n", 475 ctrl->nssa); 476 nvme_disable_streams(ctrl); 477 return 0; 478 } 479 480 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1); 481 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams); 482 return 0; 483 } 484 485 /* 486 * Check if 'req' has a write hint associated with it. If it does, assign 487 * a valid namespace stream to the write. 488 */ 489 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl, 490 struct request *req, u16 *control, 491 u32 *dsmgmt) 492 { 493 enum rw_hint streamid = req->write_hint; 494 495 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE) 496 streamid = 0; 497 else { 498 streamid--; 499 if (WARN_ON_ONCE(streamid > ctrl->nr_streams)) 500 return; 501 502 *control |= NVME_RW_DTYPE_STREAMS; 503 *dsmgmt |= streamid << 16; 504 } 505 506 if (streamid < ARRAY_SIZE(req->q->write_hints)) 507 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9; 508 } 509 510 static inline void nvme_setup_flush(struct nvme_ns *ns, 511 struct nvme_command *cmnd) 512 { 513 memset(cmnd, 0, sizeof(*cmnd)); 514 cmnd->common.opcode = nvme_cmd_flush; 515 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id); 516 } 517 518 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req, 519 struct nvme_command *cmnd) 520 { 521 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0; 522 struct nvme_dsm_range *range; 523 struct bio *bio; 524 525 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC); 526 if (!range) 527 return BLK_STS_RESOURCE; 528 529 __rq_for_each_bio(bio, req) { 530 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector); 531 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift; 532 533 if (n < segments) { 534 range[n].cattr = cpu_to_le32(0); 535 range[n].nlb = cpu_to_le32(nlb); 536 range[n].slba = cpu_to_le64(slba); 537 } 538 n++; 539 } 540 541 if (WARN_ON_ONCE(n != segments)) { 542 kfree(range); 543 return BLK_STS_IOERR; 544 } 545 546 memset(cmnd, 0, sizeof(*cmnd)); 547 cmnd->dsm.opcode = nvme_cmd_dsm; 548 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id); 549 cmnd->dsm.nr = cpu_to_le32(segments - 1); 550 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD); 551 552 req->special_vec.bv_page = virt_to_page(range); 553 req->special_vec.bv_offset = offset_in_page(range); 554 req->special_vec.bv_len = sizeof(*range) * segments; 555 req->rq_flags |= RQF_SPECIAL_PAYLOAD; 556 557 return BLK_STS_OK; 558 } 559 560 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns, 561 struct request *req, struct nvme_command *cmnd) 562 { 563 struct nvme_ctrl *ctrl = ns->ctrl; 564 u16 control = 0; 565 u32 dsmgmt = 0; 566 567 if (req->cmd_flags & REQ_FUA) 568 control |= NVME_RW_FUA; 569 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD)) 570 control |= NVME_RW_LR; 571 572 if (req->cmd_flags & REQ_RAHEAD) 573 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH; 574 575 memset(cmnd, 0, sizeof(*cmnd)); 576 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read); 577 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id); 578 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req))); 579 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1); 580 581 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams) 582 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt); 583 584 if (ns->ms) { 585 /* 586 * If formated with metadata, the block layer always provides a 587 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else 588 * we enable the PRACT bit for protection information or set the 589 * namespace capacity to zero to prevent any I/O. 590 */ 591 if (!blk_integrity_rq(req)) { 592 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns))) 593 return BLK_STS_NOTSUPP; 594 control |= NVME_RW_PRINFO_PRACT; 595 } 596 597 switch (ns->pi_type) { 598 case NVME_NS_DPS_PI_TYPE3: 599 control |= NVME_RW_PRINFO_PRCHK_GUARD; 600 break; 601 case NVME_NS_DPS_PI_TYPE1: 602 case NVME_NS_DPS_PI_TYPE2: 603 control |= NVME_RW_PRINFO_PRCHK_GUARD | 604 NVME_RW_PRINFO_PRCHK_REF; 605 cmnd->rw.reftag = cpu_to_le32( 606 nvme_block_nr(ns, blk_rq_pos(req))); 607 break; 608 } 609 } 610 611 cmnd->rw.control = cpu_to_le16(control); 612 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt); 613 return 0; 614 } 615 616 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req, 617 struct nvme_command *cmd) 618 { 619 blk_status_t ret = BLK_STS_OK; 620 621 nvme_clear_nvme_request(req); 622 623 switch (req_op(req)) { 624 case REQ_OP_DRV_IN: 625 case REQ_OP_DRV_OUT: 626 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd)); 627 break; 628 case REQ_OP_FLUSH: 629 nvme_setup_flush(ns, cmd); 630 break; 631 case REQ_OP_WRITE_ZEROES: 632 /* currently only aliased to deallocate for a few ctrls: */ 633 case REQ_OP_DISCARD: 634 ret = nvme_setup_discard(ns, req, cmd); 635 break; 636 case REQ_OP_READ: 637 case REQ_OP_WRITE: 638 ret = nvme_setup_rw(ns, req, cmd); 639 break; 640 default: 641 WARN_ON_ONCE(1); 642 return BLK_STS_IOERR; 643 } 644 645 cmd->common.command_id = req->tag; 646 if (ns) 647 trace_nvme_setup_nvm_cmd(req->q->id, cmd); 648 else 649 trace_nvme_setup_admin_cmd(cmd); 650 return ret; 651 } 652 EXPORT_SYMBOL_GPL(nvme_setup_cmd); 653 654 /* 655 * Returns 0 on success. If the result is negative, it's a Linux error code; 656 * if the result is positive, it's an NVM Express status code 657 */ 658 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 659 union nvme_result *result, void *buffer, unsigned bufflen, 660 unsigned timeout, int qid, int at_head, 661 blk_mq_req_flags_t flags) 662 { 663 struct request *req; 664 int ret; 665 666 req = nvme_alloc_request(q, cmd, flags, qid); 667 if (IS_ERR(req)) 668 return PTR_ERR(req); 669 670 req->timeout = timeout ? timeout : ADMIN_TIMEOUT; 671 672 if (buffer && bufflen) { 673 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL); 674 if (ret) 675 goto out; 676 } 677 678 blk_execute_rq(req->q, NULL, req, at_head); 679 if (result) 680 *result = nvme_req(req)->result; 681 if (nvme_req(req)->flags & NVME_REQ_CANCELLED) 682 ret = -EINTR; 683 else 684 ret = nvme_req(req)->status; 685 out: 686 blk_mq_free_request(req); 687 return ret; 688 } 689 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd); 690 691 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd, 692 void *buffer, unsigned bufflen) 693 { 694 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0, 695 NVME_QID_ANY, 0, 0); 696 } 697 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd); 698 699 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf, 700 unsigned len, u32 seed, bool write) 701 { 702 struct bio_integrity_payload *bip; 703 int ret = -ENOMEM; 704 void *buf; 705 706 buf = kmalloc(len, GFP_KERNEL); 707 if (!buf) 708 goto out; 709 710 ret = -EFAULT; 711 if (write && copy_from_user(buf, ubuf, len)) 712 goto out_free_meta; 713 714 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1); 715 if (IS_ERR(bip)) { 716 ret = PTR_ERR(bip); 717 goto out_free_meta; 718 } 719 720 bip->bip_iter.bi_size = len; 721 bip->bip_iter.bi_sector = seed; 722 ret = bio_integrity_add_page(bio, virt_to_page(buf), len, 723 offset_in_page(buf)); 724 if (ret == len) 725 return buf; 726 ret = -ENOMEM; 727 out_free_meta: 728 kfree(buf); 729 out: 730 return ERR_PTR(ret); 731 } 732 733 static int nvme_submit_user_cmd(struct request_queue *q, 734 struct nvme_command *cmd, void __user *ubuffer, 735 unsigned bufflen, void __user *meta_buffer, unsigned meta_len, 736 u32 meta_seed, u32 *result, unsigned timeout) 737 { 738 bool write = nvme_is_write(cmd); 739 struct nvme_ns *ns = q->queuedata; 740 struct gendisk *disk = ns ? ns->disk : NULL; 741 struct request *req; 742 struct bio *bio = NULL; 743 void *meta = NULL; 744 int ret; 745 746 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY); 747 if (IS_ERR(req)) 748 return PTR_ERR(req); 749 750 req->timeout = timeout ? timeout : ADMIN_TIMEOUT; 751 nvme_req(req)->flags |= NVME_REQ_USERCMD; 752 753 if (ubuffer && bufflen) { 754 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen, 755 GFP_KERNEL); 756 if (ret) 757 goto out; 758 bio = req->bio; 759 bio->bi_disk = disk; 760 if (disk && meta_buffer && meta_len) { 761 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len, 762 meta_seed, write); 763 if (IS_ERR(meta)) { 764 ret = PTR_ERR(meta); 765 goto out_unmap; 766 } 767 req->cmd_flags |= REQ_INTEGRITY; 768 } 769 } 770 771 blk_execute_rq(req->q, disk, req, 0); 772 if (nvme_req(req)->flags & NVME_REQ_CANCELLED) 773 ret = -EINTR; 774 else 775 ret = nvme_req(req)->status; 776 if (result) 777 *result = le32_to_cpu(nvme_req(req)->result.u32); 778 if (meta && !ret && !write) { 779 if (copy_to_user(meta_buffer, meta, meta_len)) 780 ret = -EFAULT; 781 } 782 kfree(meta); 783 out_unmap: 784 if (bio) 785 blk_rq_unmap_user(bio); 786 out: 787 blk_mq_free_request(req); 788 return ret; 789 } 790 791 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status) 792 { 793 struct nvme_ctrl *ctrl = rq->end_io_data; 794 795 blk_mq_free_request(rq); 796 797 if (status) { 798 dev_err(ctrl->device, 799 "failed nvme_keep_alive_end_io error=%d\n", 800 status); 801 return; 802 } 803 804 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ); 805 } 806 807 static int nvme_keep_alive(struct nvme_ctrl *ctrl) 808 { 809 struct request *rq; 810 811 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED, 812 NVME_QID_ANY); 813 if (IS_ERR(rq)) 814 return PTR_ERR(rq); 815 816 rq->timeout = ctrl->kato * HZ; 817 rq->end_io_data = ctrl; 818 819 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io); 820 821 return 0; 822 } 823 824 static void nvme_keep_alive_work(struct work_struct *work) 825 { 826 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work), 827 struct nvme_ctrl, ka_work); 828 829 if (nvme_keep_alive(ctrl)) { 830 /* allocation failure, reset the controller */ 831 dev_err(ctrl->device, "keep-alive failed\n"); 832 nvme_reset_ctrl(ctrl); 833 return; 834 } 835 } 836 837 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl) 838 { 839 if (unlikely(ctrl->kato == 0)) 840 return; 841 842 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work); 843 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd)); 844 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive; 845 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ); 846 } 847 848 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl) 849 { 850 if (unlikely(ctrl->kato == 0)) 851 return; 852 853 cancel_delayed_work_sync(&ctrl->ka_work); 854 } 855 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive); 856 857 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id) 858 { 859 struct nvme_command c = { }; 860 int error; 861 862 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 863 c.identify.opcode = nvme_admin_identify; 864 c.identify.cns = NVME_ID_CNS_CTRL; 865 866 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL); 867 if (!*id) 868 return -ENOMEM; 869 870 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id, 871 sizeof(struct nvme_id_ctrl)); 872 if (error) 873 kfree(*id); 874 return error; 875 } 876 877 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid, 878 struct nvme_ns_ids *ids) 879 { 880 struct nvme_command c = { }; 881 int status; 882 void *data; 883 int pos; 884 int len; 885 886 c.identify.opcode = nvme_admin_identify; 887 c.identify.nsid = cpu_to_le32(nsid); 888 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST; 889 890 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 891 if (!data) 892 return -ENOMEM; 893 894 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data, 895 NVME_IDENTIFY_DATA_SIZE); 896 if (status) 897 goto free_data; 898 899 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) { 900 struct nvme_ns_id_desc *cur = data + pos; 901 902 if (cur->nidl == 0) 903 break; 904 905 switch (cur->nidt) { 906 case NVME_NIDT_EUI64: 907 if (cur->nidl != NVME_NIDT_EUI64_LEN) { 908 dev_warn(ctrl->device, 909 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n", 910 cur->nidl); 911 goto free_data; 912 } 913 len = NVME_NIDT_EUI64_LEN; 914 memcpy(ids->eui64, data + pos + sizeof(*cur), len); 915 break; 916 case NVME_NIDT_NGUID: 917 if (cur->nidl != NVME_NIDT_NGUID_LEN) { 918 dev_warn(ctrl->device, 919 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n", 920 cur->nidl); 921 goto free_data; 922 } 923 len = NVME_NIDT_NGUID_LEN; 924 memcpy(ids->nguid, data + pos + sizeof(*cur), len); 925 break; 926 case NVME_NIDT_UUID: 927 if (cur->nidl != NVME_NIDT_UUID_LEN) { 928 dev_warn(ctrl->device, 929 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n", 930 cur->nidl); 931 goto free_data; 932 } 933 len = NVME_NIDT_UUID_LEN; 934 uuid_copy(&ids->uuid, data + pos + sizeof(*cur)); 935 break; 936 default: 937 /* Skip unnkown types */ 938 len = cur->nidl; 939 break; 940 } 941 942 len += sizeof(*cur); 943 } 944 free_data: 945 kfree(data); 946 return status; 947 } 948 949 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list) 950 { 951 struct nvme_command c = { }; 952 953 c.identify.opcode = nvme_admin_identify; 954 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST; 955 c.identify.nsid = cpu_to_le32(nsid); 956 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 957 NVME_IDENTIFY_DATA_SIZE); 958 } 959 960 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl, 961 unsigned nsid) 962 { 963 struct nvme_id_ns *id; 964 struct nvme_command c = { }; 965 int error; 966 967 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */ 968 c.identify.opcode = nvme_admin_identify; 969 c.identify.nsid = cpu_to_le32(nsid); 970 c.identify.cns = NVME_ID_CNS_NS; 971 972 id = kmalloc(sizeof(*id), GFP_KERNEL); 973 if (!id) 974 return NULL; 975 976 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id)); 977 if (error) { 978 dev_warn(ctrl->device, "Identify namespace failed\n"); 979 kfree(id); 980 return NULL; 981 } 982 983 return id; 984 } 985 986 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11, 987 void *buffer, size_t buflen, u32 *result) 988 { 989 struct nvme_command c; 990 union nvme_result res; 991 int ret; 992 993 memset(&c, 0, sizeof(c)); 994 c.features.opcode = nvme_admin_set_features; 995 c.features.fid = cpu_to_le32(fid); 996 c.features.dword11 = cpu_to_le32(dword11); 997 998 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, 999 buffer, buflen, 0, NVME_QID_ANY, 0, 0); 1000 if (ret >= 0 && result) 1001 *result = le32_to_cpu(res.u32); 1002 return ret; 1003 } 1004 1005 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count) 1006 { 1007 u32 q_count = (*count - 1) | ((*count - 1) << 16); 1008 u32 result; 1009 int status, nr_io_queues; 1010 1011 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0, 1012 &result); 1013 if (status < 0) 1014 return status; 1015 1016 /* 1017 * Degraded controllers might return an error when setting the queue 1018 * count. We still want to be able to bring them online and offer 1019 * access to the admin queue, as that might be only way to fix them up. 1020 */ 1021 if (status > 0) { 1022 dev_err(ctrl->device, "Could not set queue count (%d)\n", status); 1023 *count = 0; 1024 } else { 1025 nr_io_queues = min(result & 0xffff, result >> 16) + 1; 1026 *count = min(*count, nr_io_queues); 1027 } 1028 1029 return 0; 1030 } 1031 EXPORT_SYMBOL_GPL(nvme_set_queue_count); 1032 1033 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio) 1034 { 1035 struct nvme_user_io io; 1036 struct nvme_command c; 1037 unsigned length, meta_len; 1038 void __user *metadata; 1039 1040 if (copy_from_user(&io, uio, sizeof(io))) 1041 return -EFAULT; 1042 if (io.flags) 1043 return -EINVAL; 1044 1045 switch (io.opcode) { 1046 case nvme_cmd_write: 1047 case nvme_cmd_read: 1048 case nvme_cmd_compare: 1049 break; 1050 default: 1051 return -EINVAL; 1052 } 1053 1054 length = (io.nblocks + 1) << ns->lba_shift; 1055 meta_len = (io.nblocks + 1) * ns->ms; 1056 metadata = (void __user *)(uintptr_t)io.metadata; 1057 1058 if (ns->ext) { 1059 length += meta_len; 1060 meta_len = 0; 1061 } else if (meta_len) { 1062 if ((io.metadata & 3) || !io.metadata) 1063 return -EINVAL; 1064 } 1065 1066 memset(&c, 0, sizeof(c)); 1067 c.rw.opcode = io.opcode; 1068 c.rw.flags = io.flags; 1069 c.rw.nsid = cpu_to_le32(ns->head->ns_id); 1070 c.rw.slba = cpu_to_le64(io.slba); 1071 c.rw.length = cpu_to_le16(io.nblocks); 1072 c.rw.control = cpu_to_le16(io.control); 1073 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt); 1074 c.rw.reftag = cpu_to_le32(io.reftag); 1075 c.rw.apptag = cpu_to_le16(io.apptag); 1076 c.rw.appmask = cpu_to_le16(io.appmask); 1077 1078 return nvme_submit_user_cmd(ns->queue, &c, 1079 (void __user *)(uintptr_t)io.addr, length, 1080 metadata, meta_len, io.slba, NULL, 0); 1081 } 1082 1083 static u32 nvme_known_admin_effects(u8 opcode) 1084 { 1085 switch (opcode) { 1086 case nvme_admin_format_nvm: 1087 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC | 1088 NVME_CMD_EFFECTS_CSE_MASK; 1089 case nvme_admin_sanitize_nvm: 1090 return NVME_CMD_EFFECTS_CSE_MASK; 1091 default: 1092 break; 1093 } 1094 return 0; 1095 } 1096 1097 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, 1098 u8 opcode) 1099 { 1100 u32 effects = 0; 1101 1102 if (ns) { 1103 if (ctrl->effects) 1104 effects = le32_to_cpu(ctrl->effects->iocs[opcode]); 1105 if (effects & ~NVME_CMD_EFFECTS_CSUPP) 1106 dev_warn(ctrl->device, 1107 "IO command:%02x has unhandled effects:%08x\n", 1108 opcode, effects); 1109 return 0; 1110 } 1111 1112 if (ctrl->effects) 1113 effects = le32_to_cpu(ctrl->effects->acs[opcode]); 1114 else 1115 effects = nvme_known_admin_effects(opcode); 1116 1117 /* 1118 * For simplicity, IO to all namespaces is quiesced even if the command 1119 * effects say only one namespace is affected. 1120 */ 1121 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) { 1122 nvme_start_freeze(ctrl); 1123 nvme_wait_freeze(ctrl); 1124 } 1125 return effects; 1126 } 1127 1128 static void nvme_update_formats(struct nvme_ctrl *ctrl) 1129 { 1130 struct nvme_ns *ns, *next; 1131 LIST_HEAD(rm_list); 1132 1133 down_write(&ctrl->namespaces_rwsem); 1134 list_for_each_entry(ns, &ctrl->namespaces, list) { 1135 if (ns->disk && nvme_revalidate_disk(ns->disk)) { 1136 list_move_tail(&ns->list, &rm_list); 1137 } 1138 } 1139 up_write(&ctrl->namespaces_rwsem); 1140 1141 list_for_each_entry_safe(ns, next, &rm_list, list) 1142 nvme_ns_remove(ns); 1143 } 1144 1145 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects) 1146 { 1147 /* 1148 * Revalidate LBA changes prior to unfreezing. This is necessary to 1149 * prevent memory corruption if a logical block size was changed by 1150 * this command. 1151 */ 1152 if (effects & NVME_CMD_EFFECTS_LBCC) 1153 nvme_update_formats(ctrl); 1154 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) 1155 nvme_unfreeze(ctrl); 1156 if (effects & NVME_CMD_EFFECTS_CCC) 1157 nvme_init_identify(ctrl); 1158 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) 1159 nvme_queue_scan(ctrl); 1160 } 1161 1162 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns, 1163 struct nvme_passthru_cmd __user *ucmd) 1164 { 1165 struct nvme_passthru_cmd cmd; 1166 struct nvme_command c; 1167 unsigned timeout = 0; 1168 u32 effects; 1169 int status; 1170 1171 if (!capable(CAP_SYS_ADMIN)) 1172 return -EACCES; 1173 if (copy_from_user(&cmd, ucmd, sizeof(cmd))) 1174 return -EFAULT; 1175 if (cmd.flags) 1176 return -EINVAL; 1177 1178 memset(&c, 0, sizeof(c)); 1179 c.common.opcode = cmd.opcode; 1180 c.common.flags = cmd.flags; 1181 c.common.nsid = cpu_to_le32(cmd.nsid); 1182 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2); 1183 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3); 1184 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10); 1185 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11); 1186 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12); 1187 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13); 1188 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14); 1189 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15); 1190 1191 if (cmd.timeout_ms) 1192 timeout = msecs_to_jiffies(cmd.timeout_ms); 1193 1194 effects = nvme_passthru_start(ctrl, ns, cmd.opcode); 1195 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c, 1196 (void __user *)(uintptr_t)cmd.addr, cmd.data_len, 1197 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata, 1198 0, &cmd.result, timeout); 1199 nvme_passthru_end(ctrl, effects); 1200 1201 if (status >= 0) { 1202 if (put_user(cmd.result, &ucmd->result)) 1203 return -EFAULT; 1204 } 1205 1206 return status; 1207 } 1208 1209 /* 1210 * Issue ioctl requests on the first available path. Note that unlike normal 1211 * block layer requests we will not retry failed request on another controller. 1212 */ 1213 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk, 1214 struct nvme_ns_head **head, int *srcu_idx) 1215 { 1216 #ifdef CONFIG_NVME_MULTIPATH 1217 if (disk->fops == &nvme_ns_head_ops) { 1218 *head = disk->private_data; 1219 *srcu_idx = srcu_read_lock(&(*head)->srcu); 1220 return nvme_find_path(*head); 1221 } 1222 #endif 1223 *head = NULL; 1224 *srcu_idx = -1; 1225 return disk->private_data; 1226 } 1227 1228 static void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx) 1229 { 1230 if (head) 1231 srcu_read_unlock(&head->srcu, idx); 1232 } 1233 1234 static int nvme_ns_ioctl(struct nvme_ns *ns, unsigned cmd, unsigned long arg) 1235 { 1236 switch (cmd) { 1237 case NVME_IOCTL_ID: 1238 force_successful_syscall_return(); 1239 return ns->head->ns_id; 1240 case NVME_IOCTL_ADMIN_CMD: 1241 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg); 1242 case NVME_IOCTL_IO_CMD: 1243 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg); 1244 case NVME_IOCTL_SUBMIT_IO: 1245 return nvme_submit_io(ns, (void __user *)arg); 1246 default: 1247 #ifdef CONFIG_NVM 1248 if (ns->ndev) 1249 return nvme_nvm_ioctl(ns, cmd, arg); 1250 #endif 1251 if (is_sed_ioctl(cmd)) 1252 return sed_ioctl(ns->ctrl->opal_dev, cmd, 1253 (void __user *) arg); 1254 return -ENOTTY; 1255 } 1256 } 1257 1258 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, 1259 unsigned int cmd, unsigned long arg) 1260 { 1261 struct nvme_ns_head *head = NULL; 1262 struct nvme_ns *ns; 1263 int srcu_idx, ret; 1264 1265 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx); 1266 if (unlikely(!ns)) 1267 ret = -EWOULDBLOCK; 1268 else 1269 ret = nvme_ns_ioctl(ns, cmd, arg); 1270 nvme_put_ns_from_disk(head, srcu_idx); 1271 return ret; 1272 } 1273 1274 static int nvme_open(struct block_device *bdev, fmode_t mode) 1275 { 1276 struct nvme_ns *ns = bdev->bd_disk->private_data; 1277 1278 #ifdef CONFIG_NVME_MULTIPATH 1279 /* should never be called due to GENHD_FL_HIDDEN */ 1280 if (WARN_ON_ONCE(ns->head->disk)) 1281 goto fail; 1282 #endif 1283 if (!kref_get_unless_zero(&ns->kref)) 1284 goto fail; 1285 if (!try_module_get(ns->ctrl->ops->module)) 1286 goto fail_put_ns; 1287 1288 return 0; 1289 1290 fail_put_ns: 1291 nvme_put_ns(ns); 1292 fail: 1293 return -ENXIO; 1294 } 1295 1296 static void nvme_release(struct gendisk *disk, fmode_t mode) 1297 { 1298 struct nvme_ns *ns = disk->private_data; 1299 1300 module_put(ns->ctrl->ops->module); 1301 nvme_put_ns(ns); 1302 } 1303 1304 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo) 1305 { 1306 /* some standard values */ 1307 geo->heads = 1 << 6; 1308 geo->sectors = 1 << 5; 1309 geo->cylinders = get_capacity(bdev->bd_disk) >> 11; 1310 return 0; 1311 } 1312 1313 #ifdef CONFIG_BLK_DEV_INTEGRITY 1314 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type) 1315 { 1316 struct blk_integrity integrity; 1317 1318 memset(&integrity, 0, sizeof(integrity)); 1319 switch (pi_type) { 1320 case NVME_NS_DPS_PI_TYPE3: 1321 integrity.profile = &t10_pi_type3_crc; 1322 integrity.tag_size = sizeof(u16) + sizeof(u32); 1323 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1324 break; 1325 case NVME_NS_DPS_PI_TYPE1: 1326 case NVME_NS_DPS_PI_TYPE2: 1327 integrity.profile = &t10_pi_type1_crc; 1328 integrity.tag_size = sizeof(u16); 1329 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE; 1330 break; 1331 default: 1332 integrity.profile = NULL; 1333 break; 1334 } 1335 integrity.tuple_size = ms; 1336 blk_integrity_register(disk, &integrity); 1337 blk_queue_max_integrity_segments(disk->queue, 1); 1338 } 1339 #else 1340 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type) 1341 { 1342 } 1343 #endif /* CONFIG_BLK_DEV_INTEGRITY */ 1344 1345 static void nvme_set_chunk_size(struct nvme_ns *ns) 1346 { 1347 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9)); 1348 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size)); 1349 } 1350 1351 static void nvme_config_discard(struct nvme_ctrl *ctrl, 1352 unsigned stream_alignment, struct request_queue *queue) 1353 { 1354 u32 size = queue_logical_block_size(queue); 1355 1356 if (stream_alignment) 1357 size *= stream_alignment; 1358 1359 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) < 1360 NVME_DSM_MAX_RANGES); 1361 1362 queue->limits.discard_alignment = 0; 1363 queue->limits.discard_granularity = size; 1364 1365 blk_queue_max_discard_sectors(queue, UINT_MAX); 1366 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES); 1367 blk_queue_flag_set(QUEUE_FLAG_DISCARD, queue); 1368 1369 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES) 1370 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX); 1371 } 1372 1373 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid, 1374 struct nvme_id_ns *id, struct nvme_ns_ids *ids) 1375 { 1376 memset(ids, 0, sizeof(*ids)); 1377 1378 if (ctrl->vs >= NVME_VS(1, 1, 0)) 1379 memcpy(ids->eui64, id->eui64, sizeof(id->eui64)); 1380 if (ctrl->vs >= NVME_VS(1, 2, 0)) 1381 memcpy(ids->nguid, id->nguid, sizeof(id->nguid)); 1382 if (ctrl->vs >= NVME_VS(1, 3, 0)) { 1383 /* Don't treat error as fatal we potentially 1384 * already have a NGUID or EUI-64 1385 */ 1386 if (nvme_identify_ns_descs(ctrl, nsid, ids)) 1387 dev_warn(ctrl->device, 1388 "%s: Identify Descriptors failed\n", __func__); 1389 } 1390 } 1391 1392 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids) 1393 { 1394 return !uuid_is_null(&ids->uuid) || 1395 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) || 1396 memchr_inv(ids->eui64, 0, sizeof(ids->eui64)); 1397 } 1398 1399 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b) 1400 { 1401 return uuid_equal(&a->uuid, &b->uuid) && 1402 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 && 1403 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0; 1404 } 1405 1406 static void nvme_update_disk_info(struct gendisk *disk, 1407 struct nvme_ns *ns, struct nvme_id_ns *id) 1408 { 1409 sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9); 1410 unsigned short bs = 1 << ns->lba_shift; 1411 unsigned stream_alignment = 0; 1412 1413 if (ns->ctrl->nr_streams && ns->sws && ns->sgs) 1414 stream_alignment = ns->sws * ns->sgs; 1415 1416 blk_mq_freeze_queue(disk->queue); 1417 blk_integrity_unregister(disk); 1418 1419 blk_queue_logical_block_size(disk->queue, bs); 1420 blk_queue_physical_block_size(disk->queue, bs); 1421 blk_queue_io_min(disk->queue, bs); 1422 1423 if (ns->ms && !ns->ext && 1424 (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)) 1425 nvme_init_integrity(disk, ns->ms, ns->pi_type); 1426 if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk)) 1427 capacity = 0; 1428 set_capacity(disk, capacity); 1429 1430 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM) 1431 nvme_config_discard(ns->ctrl, stream_alignment, disk->queue); 1432 blk_mq_unfreeze_queue(disk->queue); 1433 } 1434 1435 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id) 1436 { 1437 struct nvme_ns *ns = disk->private_data; 1438 1439 /* 1440 * If identify namespace failed, use default 512 byte block size so 1441 * block layer can use before failing read/write for 0 capacity. 1442 */ 1443 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds; 1444 if (ns->lba_shift == 0) 1445 ns->lba_shift = 9; 1446 ns->noiob = le16_to_cpu(id->noiob); 1447 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT); 1448 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms); 1449 /* the PI implementation requires metadata equal t10 pi tuple size */ 1450 if (ns->ms == sizeof(struct t10_pi_tuple)) 1451 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK; 1452 else 1453 ns->pi_type = 0; 1454 1455 if (ns->noiob) 1456 nvme_set_chunk_size(ns); 1457 nvme_update_disk_info(disk, ns, id); 1458 if (ns->ndev) 1459 nvme_nvm_update_nvm_info(ns); 1460 #ifdef CONFIG_NVME_MULTIPATH 1461 if (ns->head->disk) 1462 nvme_update_disk_info(ns->head->disk, ns, id); 1463 #endif 1464 } 1465 1466 static int nvme_revalidate_disk(struct gendisk *disk) 1467 { 1468 struct nvme_ns *ns = disk->private_data; 1469 struct nvme_ctrl *ctrl = ns->ctrl; 1470 struct nvme_id_ns *id; 1471 struct nvme_ns_ids ids; 1472 int ret = 0; 1473 1474 if (test_bit(NVME_NS_DEAD, &ns->flags)) { 1475 set_capacity(disk, 0); 1476 return -ENODEV; 1477 } 1478 1479 id = nvme_identify_ns(ctrl, ns->head->ns_id); 1480 if (!id) 1481 return -ENODEV; 1482 1483 if (id->ncap == 0) { 1484 ret = -ENODEV; 1485 goto out; 1486 } 1487 1488 __nvme_revalidate_disk(disk, id); 1489 nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids); 1490 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) { 1491 dev_err(ctrl->device, 1492 "identifiers changed for nsid %d\n", ns->head->ns_id); 1493 ret = -ENODEV; 1494 } 1495 1496 out: 1497 kfree(id); 1498 return ret; 1499 } 1500 1501 static char nvme_pr_type(enum pr_type type) 1502 { 1503 switch (type) { 1504 case PR_WRITE_EXCLUSIVE: 1505 return 1; 1506 case PR_EXCLUSIVE_ACCESS: 1507 return 2; 1508 case PR_WRITE_EXCLUSIVE_REG_ONLY: 1509 return 3; 1510 case PR_EXCLUSIVE_ACCESS_REG_ONLY: 1511 return 4; 1512 case PR_WRITE_EXCLUSIVE_ALL_REGS: 1513 return 5; 1514 case PR_EXCLUSIVE_ACCESS_ALL_REGS: 1515 return 6; 1516 default: 1517 return 0; 1518 } 1519 }; 1520 1521 static int nvme_pr_command(struct block_device *bdev, u32 cdw10, 1522 u64 key, u64 sa_key, u8 op) 1523 { 1524 struct nvme_ns_head *head = NULL; 1525 struct nvme_ns *ns; 1526 struct nvme_command c; 1527 int srcu_idx, ret; 1528 u8 data[16] = { 0, }; 1529 1530 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx); 1531 if (unlikely(!ns)) 1532 return -EWOULDBLOCK; 1533 1534 put_unaligned_le64(key, &data[0]); 1535 put_unaligned_le64(sa_key, &data[8]); 1536 1537 memset(&c, 0, sizeof(c)); 1538 c.common.opcode = op; 1539 c.common.nsid = cpu_to_le32(ns->head->ns_id); 1540 c.common.cdw10[0] = cpu_to_le32(cdw10); 1541 1542 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16); 1543 nvme_put_ns_from_disk(head, srcu_idx); 1544 return ret; 1545 } 1546 1547 static int nvme_pr_register(struct block_device *bdev, u64 old, 1548 u64 new, unsigned flags) 1549 { 1550 u32 cdw10; 1551 1552 if (flags & ~PR_FL_IGNORE_KEY) 1553 return -EOPNOTSUPP; 1554 1555 cdw10 = old ? 2 : 0; 1556 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0; 1557 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */ 1558 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register); 1559 } 1560 1561 static int nvme_pr_reserve(struct block_device *bdev, u64 key, 1562 enum pr_type type, unsigned flags) 1563 { 1564 u32 cdw10; 1565 1566 if (flags & ~PR_FL_IGNORE_KEY) 1567 return -EOPNOTSUPP; 1568 1569 cdw10 = nvme_pr_type(type) << 8; 1570 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0); 1571 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire); 1572 } 1573 1574 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new, 1575 enum pr_type type, bool abort) 1576 { 1577 u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1; 1578 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire); 1579 } 1580 1581 static int nvme_pr_clear(struct block_device *bdev, u64 key) 1582 { 1583 u32 cdw10 = 1 | (key ? 1 << 3 : 0); 1584 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register); 1585 } 1586 1587 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type) 1588 { 1589 u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0; 1590 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release); 1591 } 1592 1593 static const struct pr_ops nvme_pr_ops = { 1594 .pr_register = nvme_pr_register, 1595 .pr_reserve = nvme_pr_reserve, 1596 .pr_release = nvme_pr_release, 1597 .pr_preempt = nvme_pr_preempt, 1598 .pr_clear = nvme_pr_clear, 1599 }; 1600 1601 #ifdef CONFIG_BLK_SED_OPAL 1602 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len, 1603 bool send) 1604 { 1605 struct nvme_ctrl *ctrl = data; 1606 struct nvme_command cmd; 1607 1608 memset(&cmd, 0, sizeof(cmd)); 1609 if (send) 1610 cmd.common.opcode = nvme_admin_security_send; 1611 else 1612 cmd.common.opcode = nvme_admin_security_recv; 1613 cmd.common.nsid = 0; 1614 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8); 1615 cmd.common.cdw10[1] = cpu_to_le32(len); 1616 1617 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 1618 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0); 1619 } 1620 EXPORT_SYMBOL_GPL(nvme_sec_submit); 1621 #endif /* CONFIG_BLK_SED_OPAL */ 1622 1623 static const struct block_device_operations nvme_fops = { 1624 .owner = THIS_MODULE, 1625 .ioctl = nvme_ioctl, 1626 .compat_ioctl = nvme_ioctl, 1627 .open = nvme_open, 1628 .release = nvme_release, 1629 .getgeo = nvme_getgeo, 1630 .revalidate_disk= nvme_revalidate_disk, 1631 .pr_ops = &nvme_pr_ops, 1632 }; 1633 1634 #ifdef CONFIG_NVME_MULTIPATH 1635 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode) 1636 { 1637 struct nvme_ns_head *head = bdev->bd_disk->private_data; 1638 1639 if (!kref_get_unless_zero(&head->ref)) 1640 return -ENXIO; 1641 return 0; 1642 } 1643 1644 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode) 1645 { 1646 nvme_put_ns_head(disk->private_data); 1647 } 1648 1649 const struct block_device_operations nvme_ns_head_ops = { 1650 .owner = THIS_MODULE, 1651 .open = nvme_ns_head_open, 1652 .release = nvme_ns_head_release, 1653 .ioctl = nvme_ioctl, 1654 .compat_ioctl = nvme_ioctl, 1655 .getgeo = nvme_getgeo, 1656 .pr_ops = &nvme_pr_ops, 1657 }; 1658 #endif /* CONFIG_NVME_MULTIPATH */ 1659 1660 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled) 1661 { 1662 unsigned long timeout = 1663 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies; 1664 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0; 1665 int ret; 1666 1667 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) { 1668 if (csts == ~0) 1669 return -ENODEV; 1670 if ((csts & NVME_CSTS_RDY) == bit) 1671 break; 1672 1673 msleep(100); 1674 if (fatal_signal_pending(current)) 1675 return -EINTR; 1676 if (time_after(jiffies, timeout)) { 1677 dev_err(ctrl->device, 1678 "Device not ready; aborting %s\n", enabled ? 1679 "initialisation" : "reset"); 1680 return -ENODEV; 1681 } 1682 } 1683 1684 return ret; 1685 } 1686 1687 /* 1688 * If the device has been passed off to us in an enabled state, just clear 1689 * the enabled bit. The spec says we should set the 'shutdown notification 1690 * bits', but doing so may cause the device to complete commands to the 1691 * admin queue ... and we don't know what memory that might be pointing at! 1692 */ 1693 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap) 1694 { 1695 int ret; 1696 1697 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK; 1698 ctrl->ctrl_config &= ~NVME_CC_ENABLE; 1699 1700 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 1701 if (ret) 1702 return ret; 1703 1704 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY) 1705 msleep(NVME_QUIRK_DELAY_AMOUNT); 1706 1707 return nvme_wait_ready(ctrl, cap, false); 1708 } 1709 EXPORT_SYMBOL_GPL(nvme_disable_ctrl); 1710 1711 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap) 1712 { 1713 /* 1714 * Default to a 4K page size, with the intention to update this 1715 * path in the future to accomodate architectures with differing 1716 * kernel and IO page sizes. 1717 */ 1718 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12; 1719 int ret; 1720 1721 if (page_shift < dev_page_min) { 1722 dev_err(ctrl->device, 1723 "Minimum device page size %u too large for host (%u)\n", 1724 1 << dev_page_min, 1 << page_shift); 1725 return -ENODEV; 1726 } 1727 1728 ctrl->page_size = 1 << page_shift; 1729 1730 ctrl->ctrl_config = NVME_CC_CSS_NVM; 1731 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT; 1732 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE; 1733 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES; 1734 ctrl->ctrl_config |= NVME_CC_ENABLE; 1735 1736 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 1737 if (ret) 1738 return ret; 1739 return nvme_wait_ready(ctrl, cap, true); 1740 } 1741 EXPORT_SYMBOL_GPL(nvme_enable_ctrl); 1742 1743 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl) 1744 { 1745 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ); 1746 u32 csts; 1747 int ret; 1748 1749 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK; 1750 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL; 1751 1752 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config); 1753 if (ret) 1754 return ret; 1755 1756 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) { 1757 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT) 1758 break; 1759 1760 msleep(100); 1761 if (fatal_signal_pending(current)) 1762 return -EINTR; 1763 if (time_after(jiffies, timeout)) { 1764 dev_err(ctrl->device, 1765 "Device shutdown incomplete; abort shutdown\n"); 1766 return -ENODEV; 1767 } 1768 } 1769 1770 return ret; 1771 } 1772 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl); 1773 1774 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl, 1775 struct request_queue *q) 1776 { 1777 bool vwc = false; 1778 1779 if (ctrl->max_hw_sectors) { 1780 u32 max_segments = 1781 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1; 1782 1783 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors); 1784 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX)); 1785 } 1786 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) && 1787 is_power_of_2(ctrl->max_hw_sectors)) 1788 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors); 1789 blk_queue_virt_boundary(q, ctrl->page_size - 1); 1790 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT) 1791 vwc = true; 1792 blk_queue_write_cache(q, vwc, vwc); 1793 } 1794 1795 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl) 1796 { 1797 __le64 ts; 1798 int ret; 1799 1800 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP)) 1801 return 0; 1802 1803 ts = cpu_to_le64(ktime_to_ms(ktime_get_real())); 1804 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts), 1805 NULL); 1806 if (ret) 1807 dev_warn_once(ctrl->device, 1808 "could not set timestamp (%d)\n", ret); 1809 return ret; 1810 } 1811 1812 static int nvme_configure_apst(struct nvme_ctrl *ctrl) 1813 { 1814 /* 1815 * APST (Autonomous Power State Transition) lets us program a 1816 * table of power state transitions that the controller will 1817 * perform automatically. We configure it with a simple 1818 * heuristic: we are willing to spend at most 2% of the time 1819 * transitioning between power states. Therefore, when running 1820 * in any given state, we will enter the next lower-power 1821 * non-operational state after waiting 50 * (enlat + exlat) 1822 * microseconds, as long as that state's exit latency is under 1823 * the requested maximum latency. 1824 * 1825 * We will not autonomously enter any non-operational state for 1826 * which the total latency exceeds ps_max_latency_us. Users 1827 * can set ps_max_latency_us to zero to turn off APST. 1828 */ 1829 1830 unsigned apste; 1831 struct nvme_feat_auto_pst *table; 1832 u64 max_lat_us = 0; 1833 int max_ps = -1; 1834 int ret; 1835 1836 /* 1837 * If APST isn't supported or if we haven't been initialized yet, 1838 * then don't do anything. 1839 */ 1840 if (!ctrl->apsta) 1841 return 0; 1842 1843 if (ctrl->npss > 31) { 1844 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n"); 1845 return 0; 1846 } 1847 1848 table = kzalloc(sizeof(*table), GFP_KERNEL); 1849 if (!table) 1850 return 0; 1851 1852 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) { 1853 /* Turn off APST. */ 1854 apste = 0; 1855 dev_dbg(ctrl->device, "APST disabled\n"); 1856 } else { 1857 __le64 target = cpu_to_le64(0); 1858 int state; 1859 1860 /* 1861 * Walk through all states from lowest- to highest-power. 1862 * According to the spec, lower-numbered states use more 1863 * power. NPSS, despite the name, is the index of the 1864 * lowest-power state, not the number of states. 1865 */ 1866 for (state = (int)ctrl->npss; state >= 0; state--) { 1867 u64 total_latency_us, exit_latency_us, transition_ms; 1868 1869 if (target) 1870 table->entries[state] = target; 1871 1872 /* 1873 * Don't allow transitions to the deepest state 1874 * if it's quirked off. 1875 */ 1876 if (state == ctrl->npss && 1877 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) 1878 continue; 1879 1880 /* 1881 * Is this state a useful non-operational state for 1882 * higher-power states to autonomously transition to? 1883 */ 1884 if (!(ctrl->psd[state].flags & 1885 NVME_PS_FLAGS_NON_OP_STATE)) 1886 continue; 1887 1888 exit_latency_us = 1889 (u64)le32_to_cpu(ctrl->psd[state].exit_lat); 1890 if (exit_latency_us > ctrl->ps_max_latency_us) 1891 continue; 1892 1893 total_latency_us = 1894 exit_latency_us + 1895 le32_to_cpu(ctrl->psd[state].entry_lat); 1896 1897 /* 1898 * This state is good. Use it as the APST idle 1899 * target for higher power states. 1900 */ 1901 transition_ms = total_latency_us + 19; 1902 do_div(transition_ms, 20); 1903 if (transition_ms > (1 << 24) - 1) 1904 transition_ms = (1 << 24) - 1; 1905 1906 target = cpu_to_le64((state << 3) | 1907 (transition_ms << 8)); 1908 1909 if (max_ps == -1) 1910 max_ps = state; 1911 1912 if (total_latency_us > max_lat_us) 1913 max_lat_us = total_latency_us; 1914 } 1915 1916 apste = 1; 1917 1918 if (max_ps == -1) { 1919 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n"); 1920 } else { 1921 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n", 1922 max_ps, max_lat_us, (int)sizeof(*table), table); 1923 } 1924 } 1925 1926 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste, 1927 table, sizeof(*table), NULL); 1928 if (ret) 1929 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret); 1930 1931 kfree(table); 1932 return ret; 1933 } 1934 1935 static void nvme_set_latency_tolerance(struct device *dev, s32 val) 1936 { 1937 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 1938 u64 latency; 1939 1940 switch (val) { 1941 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT: 1942 case PM_QOS_LATENCY_ANY: 1943 latency = U64_MAX; 1944 break; 1945 1946 default: 1947 latency = val; 1948 } 1949 1950 if (ctrl->ps_max_latency_us != latency) { 1951 ctrl->ps_max_latency_us = latency; 1952 nvme_configure_apst(ctrl); 1953 } 1954 } 1955 1956 struct nvme_core_quirk_entry { 1957 /* 1958 * NVMe model and firmware strings are padded with spaces. For 1959 * simplicity, strings in the quirk table are padded with NULLs 1960 * instead. 1961 */ 1962 u16 vid; 1963 const char *mn; 1964 const char *fr; 1965 unsigned long quirks; 1966 }; 1967 1968 static const struct nvme_core_quirk_entry core_quirks[] = { 1969 { 1970 /* 1971 * This Toshiba device seems to die using any APST states. See: 1972 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11 1973 */ 1974 .vid = 0x1179, 1975 .mn = "THNSF5256GPUK TOSHIBA", 1976 .quirks = NVME_QUIRK_NO_APST, 1977 } 1978 }; 1979 1980 /* match is null-terminated but idstr is space-padded. */ 1981 static bool string_matches(const char *idstr, const char *match, size_t len) 1982 { 1983 size_t matchlen; 1984 1985 if (!match) 1986 return true; 1987 1988 matchlen = strlen(match); 1989 WARN_ON_ONCE(matchlen > len); 1990 1991 if (memcmp(idstr, match, matchlen)) 1992 return false; 1993 1994 for (; matchlen < len; matchlen++) 1995 if (idstr[matchlen] != ' ') 1996 return false; 1997 1998 return true; 1999 } 2000 2001 static bool quirk_matches(const struct nvme_id_ctrl *id, 2002 const struct nvme_core_quirk_entry *q) 2003 { 2004 return q->vid == le16_to_cpu(id->vid) && 2005 string_matches(id->mn, q->mn, sizeof(id->mn)) && 2006 string_matches(id->fr, q->fr, sizeof(id->fr)); 2007 } 2008 2009 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl, 2010 struct nvme_id_ctrl *id) 2011 { 2012 size_t nqnlen; 2013 int off; 2014 2015 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE); 2016 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) { 2017 strncpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE); 2018 return; 2019 } 2020 2021 if (ctrl->vs >= NVME_VS(1, 2, 1)) 2022 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n"); 2023 2024 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */ 2025 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE, 2026 "nqn.2014.08.org.nvmexpress:%4x%4x", 2027 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid)); 2028 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn)); 2029 off += sizeof(id->sn); 2030 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn)); 2031 off += sizeof(id->mn); 2032 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off); 2033 } 2034 2035 static void __nvme_release_subsystem(struct nvme_subsystem *subsys) 2036 { 2037 ida_simple_remove(&nvme_subsystems_ida, subsys->instance); 2038 kfree(subsys); 2039 } 2040 2041 static void nvme_release_subsystem(struct device *dev) 2042 { 2043 __nvme_release_subsystem(container_of(dev, struct nvme_subsystem, dev)); 2044 } 2045 2046 static void nvme_destroy_subsystem(struct kref *ref) 2047 { 2048 struct nvme_subsystem *subsys = 2049 container_of(ref, struct nvme_subsystem, ref); 2050 2051 mutex_lock(&nvme_subsystems_lock); 2052 list_del(&subsys->entry); 2053 mutex_unlock(&nvme_subsystems_lock); 2054 2055 ida_destroy(&subsys->ns_ida); 2056 device_del(&subsys->dev); 2057 put_device(&subsys->dev); 2058 } 2059 2060 static void nvme_put_subsystem(struct nvme_subsystem *subsys) 2061 { 2062 kref_put(&subsys->ref, nvme_destroy_subsystem); 2063 } 2064 2065 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn) 2066 { 2067 struct nvme_subsystem *subsys; 2068 2069 lockdep_assert_held(&nvme_subsystems_lock); 2070 2071 list_for_each_entry(subsys, &nvme_subsystems, entry) { 2072 if (strcmp(subsys->subnqn, subsysnqn)) 2073 continue; 2074 if (!kref_get_unless_zero(&subsys->ref)) 2075 continue; 2076 return subsys; 2077 } 2078 2079 return NULL; 2080 } 2081 2082 #define SUBSYS_ATTR_RO(_name, _mode, _show) \ 2083 struct device_attribute subsys_attr_##_name = \ 2084 __ATTR(_name, _mode, _show, NULL) 2085 2086 static ssize_t nvme_subsys_show_nqn(struct device *dev, 2087 struct device_attribute *attr, 2088 char *buf) 2089 { 2090 struct nvme_subsystem *subsys = 2091 container_of(dev, struct nvme_subsystem, dev); 2092 2093 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn); 2094 } 2095 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn); 2096 2097 #define nvme_subsys_show_str_function(field) \ 2098 static ssize_t subsys_##field##_show(struct device *dev, \ 2099 struct device_attribute *attr, char *buf) \ 2100 { \ 2101 struct nvme_subsystem *subsys = \ 2102 container_of(dev, struct nvme_subsystem, dev); \ 2103 return sprintf(buf, "%.*s\n", \ 2104 (int)sizeof(subsys->field), subsys->field); \ 2105 } \ 2106 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show); 2107 2108 nvme_subsys_show_str_function(model); 2109 nvme_subsys_show_str_function(serial); 2110 nvme_subsys_show_str_function(firmware_rev); 2111 2112 static struct attribute *nvme_subsys_attrs[] = { 2113 &subsys_attr_model.attr, 2114 &subsys_attr_serial.attr, 2115 &subsys_attr_firmware_rev.attr, 2116 &subsys_attr_subsysnqn.attr, 2117 NULL, 2118 }; 2119 2120 static struct attribute_group nvme_subsys_attrs_group = { 2121 .attrs = nvme_subsys_attrs, 2122 }; 2123 2124 static const struct attribute_group *nvme_subsys_attrs_groups[] = { 2125 &nvme_subsys_attrs_group, 2126 NULL, 2127 }; 2128 2129 static int nvme_active_ctrls(struct nvme_subsystem *subsys) 2130 { 2131 int count = 0; 2132 struct nvme_ctrl *ctrl; 2133 2134 mutex_lock(&subsys->lock); 2135 list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) { 2136 if (ctrl->state != NVME_CTRL_DELETING && 2137 ctrl->state != NVME_CTRL_DEAD) 2138 count++; 2139 } 2140 mutex_unlock(&subsys->lock); 2141 2142 return count; 2143 } 2144 2145 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id) 2146 { 2147 struct nvme_subsystem *subsys, *found; 2148 int ret; 2149 2150 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL); 2151 if (!subsys) 2152 return -ENOMEM; 2153 ret = ida_simple_get(&nvme_subsystems_ida, 0, 0, GFP_KERNEL); 2154 if (ret < 0) { 2155 kfree(subsys); 2156 return ret; 2157 } 2158 subsys->instance = ret; 2159 mutex_init(&subsys->lock); 2160 kref_init(&subsys->ref); 2161 INIT_LIST_HEAD(&subsys->ctrls); 2162 INIT_LIST_HEAD(&subsys->nsheads); 2163 nvme_init_subnqn(subsys, ctrl, id); 2164 memcpy(subsys->serial, id->sn, sizeof(subsys->serial)); 2165 memcpy(subsys->model, id->mn, sizeof(subsys->model)); 2166 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev)); 2167 subsys->vendor_id = le16_to_cpu(id->vid); 2168 subsys->cmic = id->cmic; 2169 2170 subsys->dev.class = nvme_subsys_class; 2171 subsys->dev.release = nvme_release_subsystem; 2172 subsys->dev.groups = nvme_subsys_attrs_groups; 2173 dev_set_name(&subsys->dev, "nvme-subsys%d", subsys->instance); 2174 device_initialize(&subsys->dev); 2175 2176 mutex_lock(&nvme_subsystems_lock); 2177 found = __nvme_find_get_subsystem(subsys->subnqn); 2178 if (found) { 2179 /* 2180 * Verify that the subsystem actually supports multiple 2181 * controllers, else bail out. 2182 */ 2183 if (nvme_active_ctrls(found) && !(id->cmic & (1 << 1))) { 2184 dev_err(ctrl->device, 2185 "ignoring ctrl due to duplicate subnqn (%s).\n", 2186 found->subnqn); 2187 nvme_put_subsystem(found); 2188 ret = -EINVAL; 2189 goto out_unlock; 2190 } 2191 2192 __nvme_release_subsystem(subsys); 2193 subsys = found; 2194 } else { 2195 ret = device_add(&subsys->dev); 2196 if (ret) { 2197 dev_err(ctrl->device, 2198 "failed to register subsystem device.\n"); 2199 goto out_unlock; 2200 } 2201 ida_init(&subsys->ns_ida); 2202 list_add_tail(&subsys->entry, &nvme_subsystems); 2203 } 2204 2205 ctrl->subsys = subsys; 2206 mutex_unlock(&nvme_subsystems_lock); 2207 2208 if (sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj, 2209 dev_name(ctrl->device))) { 2210 dev_err(ctrl->device, 2211 "failed to create sysfs link from subsystem.\n"); 2212 /* the transport driver will eventually put the subsystem */ 2213 return -EINVAL; 2214 } 2215 2216 mutex_lock(&subsys->lock); 2217 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls); 2218 mutex_unlock(&subsys->lock); 2219 2220 return 0; 2221 2222 out_unlock: 2223 mutex_unlock(&nvme_subsystems_lock); 2224 put_device(&subsys->dev); 2225 return ret; 2226 } 2227 2228 int nvme_get_log_ext(struct nvme_ctrl *ctrl, struct nvme_ns *ns, 2229 u8 log_page, void *log, 2230 size_t size, u64 offset) 2231 { 2232 struct nvme_command c = { }; 2233 unsigned long dwlen = size / 4 - 1; 2234 2235 c.get_log_page.opcode = nvme_admin_get_log_page; 2236 2237 if (ns) 2238 c.get_log_page.nsid = cpu_to_le32(ns->head->ns_id); 2239 else 2240 c.get_log_page.nsid = cpu_to_le32(NVME_NSID_ALL); 2241 2242 c.get_log_page.lid = log_page; 2243 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1)); 2244 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16); 2245 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset)); 2246 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset)); 2247 2248 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size); 2249 } 2250 2251 static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log, 2252 size_t size) 2253 { 2254 return nvme_get_log_ext(ctrl, NULL, log_page, log, size, 0); 2255 } 2256 2257 static int nvme_get_effects_log(struct nvme_ctrl *ctrl) 2258 { 2259 int ret; 2260 2261 if (!ctrl->effects) 2262 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL); 2263 2264 if (!ctrl->effects) 2265 return 0; 2266 2267 ret = nvme_get_log(ctrl, NVME_LOG_CMD_EFFECTS, ctrl->effects, 2268 sizeof(*ctrl->effects)); 2269 if (ret) { 2270 kfree(ctrl->effects); 2271 ctrl->effects = NULL; 2272 } 2273 return ret; 2274 } 2275 2276 /* 2277 * Initialize the cached copies of the Identify data and various controller 2278 * register in our nvme_ctrl structure. This should be called as soon as 2279 * the admin queue is fully up and running. 2280 */ 2281 int nvme_init_identify(struct nvme_ctrl *ctrl) 2282 { 2283 struct nvme_id_ctrl *id; 2284 u64 cap; 2285 int ret, page_shift; 2286 u32 max_hw_sectors; 2287 bool prev_apst_enabled; 2288 2289 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs); 2290 if (ret) { 2291 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret); 2292 return ret; 2293 } 2294 2295 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap); 2296 if (ret) { 2297 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret); 2298 return ret; 2299 } 2300 page_shift = NVME_CAP_MPSMIN(cap) + 12; 2301 2302 if (ctrl->vs >= NVME_VS(1, 1, 0)) 2303 ctrl->subsystem = NVME_CAP_NSSRC(cap); 2304 2305 ret = nvme_identify_ctrl(ctrl, &id); 2306 if (ret) { 2307 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret); 2308 return -EIO; 2309 } 2310 2311 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) { 2312 ret = nvme_get_effects_log(ctrl); 2313 if (ret < 0) 2314 return ret; 2315 } 2316 2317 if (!ctrl->identified) { 2318 int i; 2319 2320 ret = nvme_init_subsystem(ctrl, id); 2321 if (ret) 2322 goto out_free; 2323 2324 /* 2325 * Check for quirks. Quirk can depend on firmware version, 2326 * so, in principle, the set of quirks present can change 2327 * across a reset. As a possible future enhancement, we 2328 * could re-scan for quirks every time we reinitialize 2329 * the device, but we'd have to make sure that the driver 2330 * behaves intelligently if the quirks change. 2331 */ 2332 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) { 2333 if (quirk_matches(id, &core_quirks[i])) 2334 ctrl->quirks |= core_quirks[i].quirks; 2335 } 2336 } 2337 2338 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) { 2339 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n"); 2340 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS; 2341 } 2342 2343 ctrl->oacs = le16_to_cpu(id->oacs); 2344 ctrl->oncs = le16_to_cpup(&id->oncs); 2345 atomic_set(&ctrl->abort_limit, id->acl + 1); 2346 ctrl->vwc = id->vwc; 2347 ctrl->cntlid = le16_to_cpup(&id->cntlid); 2348 if (id->mdts) 2349 max_hw_sectors = 1 << (id->mdts + page_shift - 9); 2350 else 2351 max_hw_sectors = UINT_MAX; 2352 ctrl->max_hw_sectors = 2353 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors); 2354 2355 nvme_set_queue_limits(ctrl, ctrl->admin_q); 2356 ctrl->sgls = le32_to_cpu(id->sgls); 2357 ctrl->kas = le16_to_cpu(id->kas); 2358 2359 if (id->rtd3e) { 2360 /* us -> s */ 2361 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000; 2362 2363 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time, 2364 shutdown_timeout, 60); 2365 2366 if (ctrl->shutdown_timeout != shutdown_timeout) 2367 dev_info(ctrl->device, 2368 "Shutdown timeout set to %u seconds\n", 2369 ctrl->shutdown_timeout); 2370 } else 2371 ctrl->shutdown_timeout = shutdown_timeout; 2372 2373 ctrl->npss = id->npss; 2374 ctrl->apsta = id->apsta; 2375 prev_apst_enabled = ctrl->apst_enabled; 2376 if (ctrl->quirks & NVME_QUIRK_NO_APST) { 2377 if (force_apst && id->apsta) { 2378 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n"); 2379 ctrl->apst_enabled = true; 2380 } else { 2381 ctrl->apst_enabled = false; 2382 } 2383 } else { 2384 ctrl->apst_enabled = id->apsta; 2385 } 2386 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd)); 2387 2388 if (ctrl->ops->flags & NVME_F_FABRICS) { 2389 ctrl->icdoff = le16_to_cpu(id->icdoff); 2390 ctrl->ioccsz = le32_to_cpu(id->ioccsz); 2391 ctrl->iorcsz = le32_to_cpu(id->iorcsz); 2392 ctrl->maxcmd = le16_to_cpu(id->maxcmd); 2393 2394 /* 2395 * In fabrics we need to verify the cntlid matches the 2396 * admin connect 2397 */ 2398 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) { 2399 ret = -EINVAL; 2400 goto out_free; 2401 } 2402 2403 if (!ctrl->opts->discovery_nqn && !ctrl->kas) { 2404 dev_err(ctrl->device, 2405 "keep-alive support is mandatory for fabrics\n"); 2406 ret = -EINVAL; 2407 goto out_free; 2408 } 2409 } else { 2410 ctrl->cntlid = le16_to_cpu(id->cntlid); 2411 ctrl->hmpre = le32_to_cpu(id->hmpre); 2412 ctrl->hmmin = le32_to_cpu(id->hmmin); 2413 ctrl->hmminds = le32_to_cpu(id->hmminds); 2414 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd); 2415 } 2416 2417 kfree(id); 2418 2419 if (ctrl->apst_enabled && !prev_apst_enabled) 2420 dev_pm_qos_expose_latency_tolerance(ctrl->device); 2421 else if (!ctrl->apst_enabled && prev_apst_enabled) 2422 dev_pm_qos_hide_latency_tolerance(ctrl->device); 2423 2424 ret = nvme_configure_apst(ctrl); 2425 if (ret < 0) 2426 return ret; 2427 2428 ret = nvme_configure_timestamp(ctrl); 2429 if (ret < 0) 2430 return ret; 2431 2432 ret = nvme_configure_directives(ctrl); 2433 if (ret < 0) 2434 return ret; 2435 2436 ctrl->identified = true; 2437 2438 return 0; 2439 2440 out_free: 2441 kfree(id); 2442 return ret; 2443 } 2444 EXPORT_SYMBOL_GPL(nvme_init_identify); 2445 2446 static int nvme_dev_open(struct inode *inode, struct file *file) 2447 { 2448 struct nvme_ctrl *ctrl = 2449 container_of(inode->i_cdev, struct nvme_ctrl, cdev); 2450 2451 switch (ctrl->state) { 2452 case NVME_CTRL_LIVE: 2453 case NVME_CTRL_ADMIN_ONLY: 2454 break; 2455 default: 2456 return -EWOULDBLOCK; 2457 } 2458 2459 file->private_data = ctrl; 2460 return 0; 2461 } 2462 2463 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp) 2464 { 2465 struct nvme_ns *ns; 2466 int ret; 2467 2468 down_read(&ctrl->namespaces_rwsem); 2469 if (list_empty(&ctrl->namespaces)) { 2470 ret = -ENOTTY; 2471 goto out_unlock; 2472 } 2473 2474 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list); 2475 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) { 2476 dev_warn(ctrl->device, 2477 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n"); 2478 ret = -EINVAL; 2479 goto out_unlock; 2480 } 2481 2482 dev_warn(ctrl->device, 2483 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n"); 2484 kref_get(&ns->kref); 2485 up_read(&ctrl->namespaces_rwsem); 2486 2487 ret = nvme_user_cmd(ctrl, ns, argp); 2488 nvme_put_ns(ns); 2489 return ret; 2490 2491 out_unlock: 2492 up_read(&ctrl->namespaces_rwsem); 2493 return ret; 2494 } 2495 2496 static long nvme_dev_ioctl(struct file *file, unsigned int cmd, 2497 unsigned long arg) 2498 { 2499 struct nvme_ctrl *ctrl = file->private_data; 2500 void __user *argp = (void __user *)arg; 2501 2502 switch (cmd) { 2503 case NVME_IOCTL_ADMIN_CMD: 2504 return nvme_user_cmd(ctrl, NULL, argp); 2505 case NVME_IOCTL_IO_CMD: 2506 return nvme_dev_user_cmd(ctrl, argp); 2507 case NVME_IOCTL_RESET: 2508 dev_warn(ctrl->device, "resetting controller\n"); 2509 return nvme_reset_ctrl_sync(ctrl); 2510 case NVME_IOCTL_SUBSYS_RESET: 2511 return nvme_reset_subsystem(ctrl); 2512 case NVME_IOCTL_RESCAN: 2513 nvme_queue_scan(ctrl); 2514 return 0; 2515 default: 2516 return -ENOTTY; 2517 } 2518 } 2519 2520 static const struct file_operations nvme_dev_fops = { 2521 .owner = THIS_MODULE, 2522 .open = nvme_dev_open, 2523 .unlocked_ioctl = nvme_dev_ioctl, 2524 .compat_ioctl = nvme_dev_ioctl, 2525 }; 2526 2527 static ssize_t nvme_sysfs_reset(struct device *dev, 2528 struct device_attribute *attr, const char *buf, 2529 size_t count) 2530 { 2531 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2532 int ret; 2533 2534 ret = nvme_reset_ctrl_sync(ctrl); 2535 if (ret < 0) 2536 return ret; 2537 return count; 2538 } 2539 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset); 2540 2541 static ssize_t nvme_sysfs_rescan(struct device *dev, 2542 struct device_attribute *attr, const char *buf, 2543 size_t count) 2544 { 2545 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2546 2547 nvme_queue_scan(ctrl); 2548 return count; 2549 } 2550 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan); 2551 2552 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev) 2553 { 2554 struct gendisk *disk = dev_to_disk(dev); 2555 2556 if (disk->fops == &nvme_fops) 2557 return nvme_get_ns_from_dev(dev)->head; 2558 else 2559 return disk->private_data; 2560 } 2561 2562 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr, 2563 char *buf) 2564 { 2565 struct nvme_ns_head *head = dev_to_ns_head(dev); 2566 struct nvme_ns_ids *ids = &head->ids; 2567 struct nvme_subsystem *subsys = head->subsys; 2568 int serial_len = sizeof(subsys->serial); 2569 int model_len = sizeof(subsys->model); 2570 2571 if (!uuid_is_null(&ids->uuid)) 2572 return sprintf(buf, "uuid.%pU\n", &ids->uuid); 2573 2574 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 2575 return sprintf(buf, "eui.%16phN\n", ids->nguid); 2576 2577 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 2578 return sprintf(buf, "eui.%8phN\n", ids->eui64); 2579 2580 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' || 2581 subsys->serial[serial_len - 1] == '\0')) 2582 serial_len--; 2583 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' || 2584 subsys->model[model_len - 1] == '\0')) 2585 model_len--; 2586 2587 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id, 2588 serial_len, subsys->serial, model_len, subsys->model, 2589 head->ns_id); 2590 } 2591 static DEVICE_ATTR_RO(wwid); 2592 2593 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr, 2594 char *buf) 2595 { 2596 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid); 2597 } 2598 static DEVICE_ATTR_RO(nguid); 2599 2600 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr, 2601 char *buf) 2602 { 2603 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids; 2604 2605 /* For backward compatibility expose the NGUID to userspace if 2606 * we have no UUID set 2607 */ 2608 if (uuid_is_null(&ids->uuid)) { 2609 printk_ratelimited(KERN_WARNING 2610 "No UUID available providing old NGUID\n"); 2611 return sprintf(buf, "%pU\n", ids->nguid); 2612 } 2613 return sprintf(buf, "%pU\n", &ids->uuid); 2614 } 2615 static DEVICE_ATTR_RO(uuid); 2616 2617 static ssize_t eui_show(struct device *dev, struct device_attribute *attr, 2618 char *buf) 2619 { 2620 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64); 2621 } 2622 static DEVICE_ATTR_RO(eui); 2623 2624 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr, 2625 char *buf) 2626 { 2627 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id); 2628 } 2629 static DEVICE_ATTR_RO(nsid); 2630 2631 static struct attribute *nvme_ns_id_attrs[] = { 2632 &dev_attr_wwid.attr, 2633 &dev_attr_uuid.attr, 2634 &dev_attr_nguid.attr, 2635 &dev_attr_eui.attr, 2636 &dev_attr_nsid.attr, 2637 NULL, 2638 }; 2639 2640 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj, 2641 struct attribute *a, int n) 2642 { 2643 struct device *dev = container_of(kobj, struct device, kobj); 2644 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids; 2645 2646 if (a == &dev_attr_uuid.attr) { 2647 if (uuid_is_null(&ids->uuid) && 2648 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 2649 return 0; 2650 } 2651 if (a == &dev_attr_nguid.attr) { 2652 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid))) 2653 return 0; 2654 } 2655 if (a == &dev_attr_eui.attr) { 2656 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64))) 2657 return 0; 2658 } 2659 return a->mode; 2660 } 2661 2662 const struct attribute_group nvme_ns_id_attr_group = { 2663 .attrs = nvme_ns_id_attrs, 2664 .is_visible = nvme_ns_id_attrs_are_visible, 2665 }; 2666 2667 #define nvme_show_str_function(field) \ 2668 static ssize_t field##_show(struct device *dev, \ 2669 struct device_attribute *attr, char *buf) \ 2670 { \ 2671 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \ 2672 return sprintf(buf, "%.*s\n", \ 2673 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \ 2674 } \ 2675 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL); 2676 2677 nvme_show_str_function(model); 2678 nvme_show_str_function(serial); 2679 nvme_show_str_function(firmware_rev); 2680 2681 #define nvme_show_int_function(field) \ 2682 static ssize_t field##_show(struct device *dev, \ 2683 struct device_attribute *attr, char *buf) \ 2684 { \ 2685 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \ 2686 return sprintf(buf, "%d\n", ctrl->field); \ 2687 } \ 2688 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL); 2689 2690 nvme_show_int_function(cntlid); 2691 2692 static ssize_t nvme_sysfs_delete(struct device *dev, 2693 struct device_attribute *attr, const char *buf, 2694 size_t count) 2695 { 2696 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2697 2698 if (device_remove_file_self(dev, attr)) 2699 nvme_delete_ctrl_sync(ctrl); 2700 return count; 2701 } 2702 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete); 2703 2704 static ssize_t nvme_sysfs_show_transport(struct device *dev, 2705 struct device_attribute *attr, 2706 char *buf) 2707 { 2708 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2709 2710 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name); 2711 } 2712 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL); 2713 2714 static ssize_t nvme_sysfs_show_state(struct device *dev, 2715 struct device_attribute *attr, 2716 char *buf) 2717 { 2718 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2719 static const char *const state_name[] = { 2720 [NVME_CTRL_NEW] = "new", 2721 [NVME_CTRL_LIVE] = "live", 2722 [NVME_CTRL_ADMIN_ONLY] = "only-admin", 2723 [NVME_CTRL_RESETTING] = "resetting", 2724 [NVME_CTRL_CONNECTING] = "connecting", 2725 [NVME_CTRL_DELETING] = "deleting", 2726 [NVME_CTRL_DEAD] = "dead", 2727 }; 2728 2729 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) && 2730 state_name[ctrl->state]) 2731 return sprintf(buf, "%s\n", state_name[ctrl->state]); 2732 2733 return sprintf(buf, "unknown state\n"); 2734 } 2735 2736 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL); 2737 2738 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev, 2739 struct device_attribute *attr, 2740 char *buf) 2741 { 2742 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2743 2744 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn); 2745 } 2746 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL); 2747 2748 static ssize_t nvme_sysfs_show_address(struct device *dev, 2749 struct device_attribute *attr, 2750 char *buf) 2751 { 2752 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2753 2754 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE); 2755 } 2756 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL); 2757 2758 static struct attribute *nvme_dev_attrs[] = { 2759 &dev_attr_reset_controller.attr, 2760 &dev_attr_rescan_controller.attr, 2761 &dev_attr_model.attr, 2762 &dev_attr_serial.attr, 2763 &dev_attr_firmware_rev.attr, 2764 &dev_attr_cntlid.attr, 2765 &dev_attr_delete_controller.attr, 2766 &dev_attr_transport.attr, 2767 &dev_attr_subsysnqn.attr, 2768 &dev_attr_address.attr, 2769 &dev_attr_state.attr, 2770 NULL 2771 }; 2772 2773 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj, 2774 struct attribute *a, int n) 2775 { 2776 struct device *dev = container_of(kobj, struct device, kobj); 2777 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); 2778 2779 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl) 2780 return 0; 2781 if (a == &dev_attr_address.attr && !ctrl->ops->get_address) 2782 return 0; 2783 2784 return a->mode; 2785 } 2786 2787 static struct attribute_group nvme_dev_attrs_group = { 2788 .attrs = nvme_dev_attrs, 2789 .is_visible = nvme_dev_attrs_are_visible, 2790 }; 2791 2792 static const struct attribute_group *nvme_dev_attr_groups[] = { 2793 &nvme_dev_attrs_group, 2794 NULL, 2795 }; 2796 2797 static struct nvme_ns_head *__nvme_find_ns_head(struct nvme_subsystem *subsys, 2798 unsigned nsid) 2799 { 2800 struct nvme_ns_head *h; 2801 2802 lockdep_assert_held(&subsys->lock); 2803 2804 list_for_each_entry(h, &subsys->nsheads, entry) { 2805 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref)) 2806 return h; 2807 } 2808 2809 return NULL; 2810 } 2811 2812 static int __nvme_check_ids(struct nvme_subsystem *subsys, 2813 struct nvme_ns_head *new) 2814 { 2815 struct nvme_ns_head *h; 2816 2817 lockdep_assert_held(&subsys->lock); 2818 2819 list_for_each_entry(h, &subsys->nsheads, entry) { 2820 if (nvme_ns_ids_valid(&new->ids) && 2821 !list_empty(&h->list) && 2822 nvme_ns_ids_equal(&new->ids, &h->ids)) 2823 return -EINVAL; 2824 } 2825 2826 return 0; 2827 } 2828 2829 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl, 2830 unsigned nsid, struct nvme_id_ns *id) 2831 { 2832 struct nvme_ns_head *head; 2833 int ret = -ENOMEM; 2834 2835 head = kzalloc(sizeof(*head), GFP_KERNEL); 2836 if (!head) 2837 goto out; 2838 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL); 2839 if (ret < 0) 2840 goto out_free_head; 2841 head->instance = ret; 2842 INIT_LIST_HEAD(&head->list); 2843 ret = init_srcu_struct(&head->srcu); 2844 if (ret) 2845 goto out_ida_remove; 2846 head->subsys = ctrl->subsys; 2847 head->ns_id = nsid; 2848 kref_init(&head->ref); 2849 2850 nvme_report_ns_ids(ctrl, nsid, id, &head->ids); 2851 2852 ret = __nvme_check_ids(ctrl->subsys, head); 2853 if (ret) { 2854 dev_err(ctrl->device, 2855 "duplicate IDs for nsid %d\n", nsid); 2856 goto out_cleanup_srcu; 2857 } 2858 2859 ret = nvme_mpath_alloc_disk(ctrl, head); 2860 if (ret) 2861 goto out_cleanup_srcu; 2862 2863 list_add_tail(&head->entry, &ctrl->subsys->nsheads); 2864 return head; 2865 out_cleanup_srcu: 2866 cleanup_srcu_struct(&head->srcu); 2867 out_ida_remove: 2868 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance); 2869 out_free_head: 2870 kfree(head); 2871 out: 2872 return ERR_PTR(ret); 2873 } 2874 2875 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid, 2876 struct nvme_id_ns *id) 2877 { 2878 struct nvme_ctrl *ctrl = ns->ctrl; 2879 bool is_shared = id->nmic & (1 << 0); 2880 struct nvme_ns_head *head = NULL; 2881 int ret = 0; 2882 2883 mutex_lock(&ctrl->subsys->lock); 2884 if (is_shared) 2885 head = __nvme_find_ns_head(ctrl->subsys, nsid); 2886 if (!head) { 2887 head = nvme_alloc_ns_head(ctrl, nsid, id); 2888 if (IS_ERR(head)) { 2889 ret = PTR_ERR(head); 2890 goto out_unlock; 2891 } 2892 } else { 2893 struct nvme_ns_ids ids; 2894 2895 nvme_report_ns_ids(ctrl, nsid, id, &ids); 2896 if (!nvme_ns_ids_equal(&head->ids, &ids)) { 2897 dev_err(ctrl->device, 2898 "IDs don't match for shared namespace %d\n", 2899 nsid); 2900 ret = -EINVAL; 2901 goto out_unlock; 2902 } 2903 } 2904 2905 list_add_tail(&ns->siblings, &head->list); 2906 ns->head = head; 2907 2908 out_unlock: 2909 mutex_unlock(&ctrl->subsys->lock); 2910 return ret; 2911 } 2912 2913 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b) 2914 { 2915 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list); 2916 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list); 2917 2918 return nsa->head->ns_id - nsb->head->ns_id; 2919 } 2920 2921 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid) 2922 { 2923 struct nvme_ns *ns, *ret = NULL; 2924 2925 down_read(&ctrl->namespaces_rwsem); 2926 list_for_each_entry(ns, &ctrl->namespaces, list) { 2927 if (ns->head->ns_id == nsid) { 2928 if (!kref_get_unless_zero(&ns->kref)) 2929 continue; 2930 ret = ns; 2931 break; 2932 } 2933 if (ns->head->ns_id > nsid) 2934 break; 2935 } 2936 up_read(&ctrl->namespaces_rwsem); 2937 return ret; 2938 } 2939 2940 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns) 2941 { 2942 struct streams_directive_params s; 2943 int ret; 2944 2945 if (!ctrl->nr_streams) 2946 return 0; 2947 2948 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id); 2949 if (ret) 2950 return ret; 2951 2952 ns->sws = le32_to_cpu(s.sws); 2953 ns->sgs = le16_to_cpu(s.sgs); 2954 2955 if (ns->sws) { 2956 unsigned int bs = 1 << ns->lba_shift; 2957 2958 blk_queue_io_min(ns->queue, bs * ns->sws); 2959 if (ns->sgs) 2960 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs); 2961 } 2962 2963 return 0; 2964 } 2965 2966 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid) 2967 { 2968 struct nvme_ns *ns; 2969 struct gendisk *disk; 2970 struct nvme_id_ns *id; 2971 char disk_name[DISK_NAME_LEN]; 2972 int node = dev_to_node(ctrl->dev), flags = GENHD_FL_EXT_DEVT; 2973 2974 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node); 2975 if (!ns) 2976 return; 2977 2978 ns->queue = blk_mq_init_queue(ctrl->tagset); 2979 if (IS_ERR(ns->queue)) 2980 goto out_free_ns; 2981 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue); 2982 ns->queue->queuedata = ns; 2983 ns->ctrl = ctrl; 2984 2985 kref_init(&ns->kref); 2986 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */ 2987 2988 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift); 2989 nvme_set_queue_limits(ctrl, ns->queue); 2990 2991 id = nvme_identify_ns(ctrl, nsid); 2992 if (!id) 2993 goto out_free_queue; 2994 2995 if (id->ncap == 0) 2996 goto out_free_id; 2997 2998 if (nvme_init_ns_head(ns, nsid, id)) 2999 goto out_free_id; 3000 nvme_setup_streams_ns(ctrl, ns); 3001 nvme_set_disk_name(disk_name, ns, ctrl, &flags); 3002 3003 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) { 3004 if (nvme_nvm_register(ns, disk_name, node)) { 3005 dev_warn(ctrl->device, "LightNVM init failure\n"); 3006 goto out_unlink_ns; 3007 } 3008 } 3009 3010 disk = alloc_disk_node(0, node); 3011 if (!disk) 3012 goto out_unlink_ns; 3013 3014 disk->fops = &nvme_fops; 3015 disk->private_data = ns; 3016 disk->queue = ns->queue; 3017 disk->flags = flags; 3018 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN); 3019 ns->disk = disk; 3020 3021 __nvme_revalidate_disk(disk, id); 3022 3023 down_write(&ctrl->namespaces_rwsem); 3024 list_add_tail(&ns->list, &ctrl->namespaces); 3025 up_write(&ctrl->namespaces_rwsem); 3026 3027 nvme_get_ctrl(ctrl); 3028 3029 kfree(id); 3030 3031 device_add_disk(ctrl->device, ns->disk); 3032 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj, 3033 &nvme_ns_id_attr_group)) 3034 pr_warn("%s: failed to create sysfs group for identification\n", 3035 ns->disk->disk_name); 3036 if (ns->ndev && nvme_nvm_register_sysfs(ns)) 3037 pr_warn("%s: failed to register lightnvm sysfs group for identification\n", 3038 ns->disk->disk_name); 3039 3040 nvme_mpath_add_disk(ns->head); 3041 nvme_fault_inject_init(ns); 3042 return; 3043 out_unlink_ns: 3044 mutex_lock(&ctrl->subsys->lock); 3045 list_del_rcu(&ns->siblings); 3046 mutex_unlock(&ctrl->subsys->lock); 3047 out_free_id: 3048 kfree(id); 3049 out_free_queue: 3050 blk_cleanup_queue(ns->queue); 3051 out_free_ns: 3052 kfree(ns); 3053 } 3054 3055 static void nvme_ns_remove(struct nvme_ns *ns) 3056 { 3057 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags)) 3058 return; 3059 3060 nvme_fault_inject_fini(ns); 3061 if (ns->disk && ns->disk->flags & GENHD_FL_UP) { 3062 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj, 3063 &nvme_ns_id_attr_group); 3064 if (ns->ndev) 3065 nvme_nvm_unregister_sysfs(ns); 3066 del_gendisk(ns->disk); 3067 blk_cleanup_queue(ns->queue); 3068 if (blk_get_integrity(ns->disk)) 3069 blk_integrity_unregister(ns->disk); 3070 } 3071 3072 mutex_lock(&ns->ctrl->subsys->lock); 3073 nvme_mpath_clear_current_path(ns); 3074 list_del_rcu(&ns->siblings); 3075 mutex_unlock(&ns->ctrl->subsys->lock); 3076 3077 down_write(&ns->ctrl->namespaces_rwsem); 3078 list_del_init(&ns->list); 3079 up_write(&ns->ctrl->namespaces_rwsem); 3080 3081 synchronize_srcu(&ns->head->srcu); 3082 nvme_mpath_check_last_path(ns); 3083 nvme_put_ns(ns); 3084 } 3085 3086 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid) 3087 { 3088 struct nvme_ns *ns; 3089 3090 ns = nvme_find_get_ns(ctrl, nsid); 3091 if (ns) { 3092 if (ns->disk && revalidate_disk(ns->disk)) 3093 nvme_ns_remove(ns); 3094 nvme_put_ns(ns); 3095 } else 3096 nvme_alloc_ns(ctrl, nsid); 3097 } 3098 3099 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl, 3100 unsigned nsid) 3101 { 3102 struct nvme_ns *ns, *next; 3103 LIST_HEAD(rm_list); 3104 3105 down_write(&ctrl->namespaces_rwsem); 3106 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) { 3107 if (ns->head->ns_id > nsid) 3108 list_move_tail(&ns->list, &rm_list); 3109 } 3110 up_write(&ctrl->namespaces_rwsem); 3111 3112 list_for_each_entry_safe(ns, next, &rm_list, list) 3113 nvme_ns_remove(ns); 3114 3115 } 3116 3117 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn) 3118 { 3119 struct nvme_ns *ns; 3120 __le32 *ns_list; 3121 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024); 3122 int ret = 0; 3123 3124 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL); 3125 if (!ns_list) 3126 return -ENOMEM; 3127 3128 for (i = 0; i < num_lists; i++) { 3129 ret = nvme_identify_ns_list(ctrl, prev, ns_list); 3130 if (ret) 3131 goto free; 3132 3133 for (j = 0; j < min(nn, 1024U); j++) { 3134 nsid = le32_to_cpu(ns_list[j]); 3135 if (!nsid) 3136 goto out; 3137 3138 nvme_validate_ns(ctrl, nsid); 3139 3140 while (++prev < nsid) { 3141 ns = nvme_find_get_ns(ctrl, prev); 3142 if (ns) { 3143 nvme_ns_remove(ns); 3144 nvme_put_ns(ns); 3145 } 3146 } 3147 } 3148 nn -= j; 3149 } 3150 out: 3151 nvme_remove_invalid_namespaces(ctrl, prev); 3152 free: 3153 kfree(ns_list); 3154 return ret; 3155 } 3156 3157 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn) 3158 { 3159 unsigned i; 3160 3161 for (i = 1; i <= nn; i++) 3162 nvme_validate_ns(ctrl, i); 3163 3164 nvme_remove_invalid_namespaces(ctrl, nn); 3165 } 3166 3167 static void nvme_scan_work(struct work_struct *work) 3168 { 3169 struct nvme_ctrl *ctrl = 3170 container_of(work, struct nvme_ctrl, scan_work); 3171 struct nvme_id_ctrl *id; 3172 unsigned nn; 3173 3174 if (ctrl->state != NVME_CTRL_LIVE) 3175 return; 3176 3177 WARN_ON_ONCE(!ctrl->tagset); 3178 3179 if (nvme_identify_ctrl(ctrl, &id)) 3180 return; 3181 3182 nn = le32_to_cpu(id->nn); 3183 if (ctrl->vs >= NVME_VS(1, 1, 0) && 3184 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) { 3185 if (!nvme_scan_ns_list(ctrl, nn)) 3186 goto done; 3187 } 3188 nvme_scan_ns_sequential(ctrl, nn); 3189 done: 3190 down_write(&ctrl->namespaces_rwsem); 3191 list_sort(NULL, &ctrl->namespaces, ns_cmp); 3192 up_write(&ctrl->namespaces_rwsem); 3193 kfree(id); 3194 } 3195 3196 void nvme_queue_scan(struct nvme_ctrl *ctrl) 3197 { 3198 /* 3199 * Only new queue scan work when admin and IO queues are both alive 3200 */ 3201 if (ctrl->state == NVME_CTRL_LIVE) 3202 queue_work(nvme_wq, &ctrl->scan_work); 3203 } 3204 EXPORT_SYMBOL_GPL(nvme_queue_scan); 3205 3206 /* 3207 * This function iterates the namespace list unlocked to allow recovery from 3208 * controller failure. It is up to the caller to ensure the namespace list is 3209 * not modified by scan work while this function is executing. 3210 */ 3211 void nvme_remove_namespaces(struct nvme_ctrl *ctrl) 3212 { 3213 struct nvme_ns *ns, *next; 3214 LIST_HEAD(ns_list); 3215 3216 /* 3217 * The dead states indicates the controller was not gracefully 3218 * disconnected. In that case, we won't be able to flush any data while 3219 * removing the namespaces' disks; fail all the queues now to avoid 3220 * potentially having to clean up the failed sync later. 3221 */ 3222 if (ctrl->state == NVME_CTRL_DEAD) 3223 nvme_kill_queues(ctrl); 3224 3225 down_write(&ctrl->namespaces_rwsem); 3226 list_splice_init(&ctrl->namespaces, &ns_list); 3227 up_write(&ctrl->namespaces_rwsem); 3228 3229 list_for_each_entry_safe(ns, next, &ns_list, list) 3230 nvme_ns_remove(ns); 3231 } 3232 EXPORT_SYMBOL_GPL(nvme_remove_namespaces); 3233 3234 static void nvme_aen_uevent(struct nvme_ctrl *ctrl) 3235 { 3236 char *envp[2] = { NULL, NULL }; 3237 u32 aen_result = ctrl->aen_result; 3238 3239 ctrl->aen_result = 0; 3240 if (!aen_result) 3241 return; 3242 3243 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result); 3244 if (!envp[0]) 3245 return; 3246 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp); 3247 kfree(envp[0]); 3248 } 3249 3250 static void nvme_async_event_work(struct work_struct *work) 3251 { 3252 struct nvme_ctrl *ctrl = 3253 container_of(work, struct nvme_ctrl, async_event_work); 3254 3255 nvme_aen_uevent(ctrl); 3256 ctrl->ops->submit_async_event(ctrl); 3257 } 3258 3259 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl) 3260 { 3261 3262 u32 csts; 3263 3264 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) 3265 return false; 3266 3267 if (csts == ~0) 3268 return false; 3269 3270 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP)); 3271 } 3272 3273 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl) 3274 { 3275 struct nvme_fw_slot_info_log *log; 3276 3277 log = kmalloc(sizeof(*log), GFP_KERNEL); 3278 if (!log) 3279 return; 3280 3281 if (nvme_get_log(ctrl, NVME_LOG_FW_SLOT, log, sizeof(*log))) 3282 dev_warn(ctrl->device, 3283 "Get FW SLOT INFO log error\n"); 3284 kfree(log); 3285 } 3286 3287 static void nvme_fw_act_work(struct work_struct *work) 3288 { 3289 struct nvme_ctrl *ctrl = container_of(work, 3290 struct nvme_ctrl, fw_act_work); 3291 unsigned long fw_act_timeout; 3292 3293 if (ctrl->mtfa) 3294 fw_act_timeout = jiffies + 3295 msecs_to_jiffies(ctrl->mtfa * 100); 3296 else 3297 fw_act_timeout = jiffies + 3298 msecs_to_jiffies(admin_timeout * 1000); 3299 3300 nvme_stop_queues(ctrl); 3301 while (nvme_ctrl_pp_status(ctrl)) { 3302 if (time_after(jiffies, fw_act_timeout)) { 3303 dev_warn(ctrl->device, 3304 "Fw activation timeout, reset controller\n"); 3305 nvme_reset_ctrl(ctrl); 3306 break; 3307 } 3308 msleep(100); 3309 } 3310 3311 if (ctrl->state != NVME_CTRL_LIVE) 3312 return; 3313 3314 nvme_start_queues(ctrl); 3315 /* read FW slot information to clear the AER */ 3316 nvme_get_fw_slot_info(ctrl); 3317 } 3318 3319 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status, 3320 union nvme_result *res) 3321 { 3322 u32 result = le32_to_cpu(res->u32); 3323 3324 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS) 3325 return; 3326 3327 switch (result & 0x7) { 3328 case NVME_AER_ERROR: 3329 case NVME_AER_SMART: 3330 case NVME_AER_CSS: 3331 case NVME_AER_VS: 3332 ctrl->aen_result = result; 3333 break; 3334 default: 3335 break; 3336 } 3337 3338 switch (result & 0xff07) { 3339 case NVME_AER_NOTICE_NS_CHANGED: 3340 dev_info(ctrl->device, "rescanning\n"); 3341 nvme_queue_scan(ctrl); 3342 break; 3343 case NVME_AER_NOTICE_FW_ACT_STARTING: 3344 queue_work(nvme_wq, &ctrl->fw_act_work); 3345 break; 3346 default: 3347 dev_warn(ctrl->device, "async event result %08x\n", result); 3348 } 3349 queue_work(nvme_wq, &ctrl->async_event_work); 3350 } 3351 EXPORT_SYMBOL_GPL(nvme_complete_async_event); 3352 3353 void nvme_stop_ctrl(struct nvme_ctrl *ctrl) 3354 { 3355 nvme_stop_keep_alive(ctrl); 3356 flush_work(&ctrl->async_event_work); 3357 flush_work(&ctrl->scan_work); 3358 cancel_work_sync(&ctrl->fw_act_work); 3359 if (ctrl->ops->stop_ctrl) 3360 ctrl->ops->stop_ctrl(ctrl); 3361 } 3362 EXPORT_SYMBOL_GPL(nvme_stop_ctrl); 3363 3364 void nvme_start_ctrl(struct nvme_ctrl *ctrl) 3365 { 3366 if (ctrl->kato) 3367 nvme_start_keep_alive(ctrl); 3368 3369 if (ctrl->queue_count > 1) { 3370 nvme_queue_scan(ctrl); 3371 queue_work(nvme_wq, &ctrl->async_event_work); 3372 nvme_start_queues(ctrl); 3373 } 3374 } 3375 EXPORT_SYMBOL_GPL(nvme_start_ctrl); 3376 3377 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl) 3378 { 3379 cdev_device_del(&ctrl->cdev, ctrl->device); 3380 } 3381 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl); 3382 3383 static void nvme_free_ctrl(struct device *dev) 3384 { 3385 struct nvme_ctrl *ctrl = 3386 container_of(dev, struct nvme_ctrl, ctrl_device); 3387 struct nvme_subsystem *subsys = ctrl->subsys; 3388 3389 ida_simple_remove(&nvme_instance_ida, ctrl->instance); 3390 kfree(ctrl->effects); 3391 3392 if (subsys) { 3393 mutex_lock(&subsys->lock); 3394 list_del(&ctrl->subsys_entry); 3395 mutex_unlock(&subsys->lock); 3396 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device)); 3397 } 3398 3399 ctrl->ops->free_ctrl(ctrl); 3400 3401 if (subsys) 3402 nvme_put_subsystem(subsys); 3403 } 3404 3405 /* 3406 * Initialize a NVMe controller structures. This needs to be called during 3407 * earliest initialization so that we have the initialized structured around 3408 * during probing. 3409 */ 3410 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev, 3411 const struct nvme_ctrl_ops *ops, unsigned long quirks) 3412 { 3413 int ret; 3414 3415 ctrl->state = NVME_CTRL_NEW; 3416 spin_lock_init(&ctrl->lock); 3417 INIT_LIST_HEAD(&ctrl->namespaces); 3418 init_rwsem(&ctrl->namespaces_rwsem); 3419 ctrl->dev = dev; 3420 ctrl->ops = ops; 3421 ctrl->quirks = quirks; 3422 INIT_WORK(&ctrl->scan_work, nvme_scan_work); 3423 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work); 3424 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work); 3425 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work); 3426 3427 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL); 3428 if (ret < 0) 3429 goto out; 3430 ctrl->instance = ret; 3431 3432 device_initialize(&ctrl->ctrl_device); 3433 ctrl->device = &ctrl->ctrl_device; 3434 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance); 3435 ctrl->device->class = nvme_class; 3436 ctrl->device->parent = ctrl->dev; 3437 ctrl->device->groups = nvme_dev_attr_groups; 3438 ctrl->device->release = nvme_free_ctrl; 3439 dev_set_drvdata(ctrl->device, ctrl); 3440 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance); 3441 if (ret) 3442 goto out_release_instance; 3443 3444 cdev_init(&ctrl->cdev, &nvme_dev_fops); 3445 ctrl->cdev.owner = ops->module; 3446 ret = cdev_device_add(&ctrl->cdev, ctrl->device); 3447 if (ret) 3448 goto out_free_name; 3449 3450 /* 3451 * Initialize latency tolerance controls. The sysfs files won't 3452 * be visible to userspace unless the device actually supports APST. 3453 */ 3454 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance; 3455 dev_pm_qos_update_user_latency_tolerance(ctrl->device, 3456 min(default_ps_max_latency_us, (unsigned long)S32_MAX)); 3457 3458 return 0; 3459 out_free_name: 3460 kfree_const(dev->kobj.name); 3461 out_release_instance: 3462 ida_simple_remove(&nvme_instance_ida, ctrl->instance); 3463 out: 3464 return ret; 3465 } 3466 EXPORT_SYMBOL_GPL(nvme_init_ctrl); 3467 3468 /** 3469 * nvme_kill_queues(): Ends all namespace queues 3470 * @ctrl: the dead controller that needs to end 3471 * 3472 * Call this function when the driver determines it is unable to get the 3473 * controller in a state capable of servicing IO. 3474 */ 3475 void nvme_kill_queues(struct nvme_ctrl *ctrl) 3476 { 3477 struct nvme_ns *ns; 3478 3479 down_read(&ctrl->namespaces_rwsem); 3480 3481 /* Forcibly unquiesce queues to avoid blocking dispatch */ 3482 if (ctrl->admin_q) 3483 blk_mq_unquiesce_queue(ctrl->admin_q); 3484 3485 list_for_each_entry(ns, &ctrl->namespaces, list) { 3486 /* 3487 * Revalidating a dead namespace sets capacity to 0. This will 3488 * end buffered writers dirtying pages that can't be synced. 3489 */ 3490 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags)) 3491 continue; 3492 revalidate_disk(ns->disk); 3493 blk_set_queue_dying(ns->queue); 3494 3495 /* Forcibly unquiesce queues to avoid blocking dispatch */ 3496 blk_mq_unquiesce_queue(ns->queue); 3497 } 3498 up_read(&ctrl->namespaces_rwsem); 3499 } 3500 EXPORT_SYMBOL_GPL(nvme_kill_queues); 3501 3502 void nvme_unfreeze(struct nvme_ctrl *ctrl) 3503 { 3504 struct nvme_ns *ns; 3505 3506 down_read(&ctrl->namespaces_rwsem); 3507 list_for_each_entry(ns, &ctrl->namespaces, list) 3508 blk_mq_unfreeze_queue(ns->queue); 3509 up_read(&ctrl->namespaces_rwsem); 3510 } 3511 EXPORT_SYMBOL_GPL(nvme_unfreeze); 3512 3513 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout) 3514 { 3515 struct nvme_ns *ns; 3516 3517 down_read(&ctrl->namespaces_rwsem); 3518 list_for_each_entry(ns, &ctrl->namespaces, list) { 3519 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout); 3520 if (timeout <= 0) 3521 break; 3522 } 3523 up_read(&ctrl->namespaces_rwsem); 3524 } 3525 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout); 3526 3527 void nvme_wait_freeze(struct nvme_ctrl *ctrl) 3528 { 3529 struct nvme_ns *ns; 3530 3531 down_read(&ctrl->namespaces_rwsem); 3532 list_for_each_entry(ns, &ctrl->namespaces, list) 3533 blk_mq_freeze_queue_wait(ns->queue); 3534 up_read(&ctrl->namespaces_rwsem); 3535 } 3536 EXPORT_SYMBOL_GPL(nvme_wait_freeze); 3537 3538 void nvme_start_freeze(struct nvme_ctrl *ctrl) 3539 { 3540 struct nvme_ns *ns; 3541 3542 down_read(&ctrl->namespaces_rwsem); 3543 list_for_each_entry(ns, &ctrl->namespaces, list) 3544 blk_freeze_queue_start(ns->queue); 3545 up_read(&ctrl->namespaces_rwsem); 3546 } 3547 EXPORT_SYMBOL_GPL(nvme_start_freeze); 3548 3549 void nvme_stop_queues(struct nvme_ctrl *ctrl) 3550 { 3551 struct nvme_ns *ns; 3552 3553 down_read(&ctrl->namespaces_rwsem); 3554 list_for_each_entry(ns, &ctrl->namespaces, list) 3555 blk_mq_quiesce_queue(ns->queue); 3556 up_read(&ctrl->namespaces_rwsem); 3557 } 3558 EXPORT_SYMBOL_GPL(nvme_stop_queues); 3559 3560 void nvme_start_queues(struct nvme_ctrl *ctrl) 3561 { 3562 struct nvme_ns *ns; 3563 3564 down_read(&ctrl->namespaces_rwsem); 3565 list_for_each_entry(ns, &ctrl->namespaces, list) 3566 blk_mq_unquiesce_queue(ns->queue); 3567 up_read(&ctrl->namespaces_rwsem); 3568 } 3569 EXPORT_SYMBOL_GPL(nvme_start_queues); 3570 3571 int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set) 3572 { 3573 if (!ctrl->ops->reinit_request) 3574 return 0; 3575 3576 return blk_mq_tagset_iter(set, set->driver_data, 3577 ctrl->ops->reinit_request); 3578 } 3579 EXPORT_SYMBOL_GPL(nvme_reinit_tagset); 3580 3581 int __init nvme_core_init(void) 3582 { 3583 int result = -ENOMEM; 3584 3585 nvme_wq = alloc_workqueue("nvme-wq", 3586 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 3587 if (!nvme_wq) 3588 goto out; 3589 3590 nvme_reset_wq = alloc_workqueue("nvme-reset-wq", 3591 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 3592 if (!nvme_reset_wq) 3593 goto destroy_wq; 3594 3595 nvme_delete_wq = alloc_workqueue("nvme-delete-wq", 3596 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0); 3597 if (!nvme_delete_wq) 3598 goto destroy_reset_wq; 3599 3600 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme"); 3601 if (result < 0) 3602 goto destroy_delete_wq; 3603 3604 nvme_class = class_create(THIS_MODULE, "nvme"); 3605 if (IS_ERR(nvme_class)) { 3606 result = PTR_ERR(nvme_class); 3607 goto unregister_chrdev; 3608 } 3609 3610 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem"); 3611 if (IS_ERR(nvme_subsys_class)) { 3612 result = PTR_ERR(nvme_subsys_class); 3613 goto destroy_class; 3614 } 3615 return 0; 3616 3617 destroy_class: 3618 class_destroy(nvme_class); 3619 unregister_chrdev: 3620 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS); 3621 destroy_delete_wq: 3622 destroy_workqueue(nvme_delete_wq); 3623 destroy_reset_wq: 3624 destroy_workqueue(nvme_reset_wq); 3625 destroy_wq: 3626 destroy_workqueue(nvme_wq); 3627 out: 3628 return result; 3629 } 3630 3631 void nvme_core_exit(void) 3632 { 3633 ida_destroy(&nvme_subsystems_ida); 3634 class_destroy(nvme_subsys_class); 3635 class_destroy(nvme_class); 3636 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS); 3637 destroy_workqueue(nvme_delete_wq); 3638 destroy_workqueue(nvme_reset_wq); 3639 destroy_workqueue(nvme_wq); 3640 } 3641 3642 MODULE_LICENSE("GPL"); 3643 MODULE_VERSION("1.0"); 3644 module_init(nvme_core_init); 3645 module_exit(nvme_core_exit); 3646