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