1 // SPDX-License-Identifier: GPL-2.0
3 * NVM Express device driver
4 * Copyright (c) 2011-2014, Intel Corporation.
7 #include <linux/blkdev.h>
8 #include <linux/blk-mq.h>
9 #include <linux/compat.h>
10 #include <linux/delay.h>
11 #include <linux/errno.h>
12 #include <linux/hdreg.h>
13 #include <linux/kernel.h>
14 #include <linux/module.h>
15 #include <linux/backing-dev.h>
16 #include <linux/list_sort.h>
17 #include <linux/slab.h>
18 #include <linux/types.h>
20 #include <linux/ptrace.h>
21 #include <linux/nvme_ioctl.h>
22 #include <linux/pm_qos.h>
23 #include <asm/unaligned.h>
28 #define CREATE_TRACE_POINTS
31 #define NVME_MINORS (1U << MINORBITS)
33 unsigned int admin_timeout = 60;
34 module_param(admin_timeout, uint, 0644);
35 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
36 EXPORT_SYMBOL_GPL(admin_timeout);
38 unsigned int nvme_io_timeout = 30;
39 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
40 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
41 EXPORT_SYMBOL_GPL(nvme_io_timeout);
43 static unsigned char shutdown_timeout = 5;
44 module_param(shutdown_timeout, byte, 0644);
45 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
47 static u8 nvme_max_retries = 5;
48 module_param_named(max_retries, nvme_max_retries, byte, 0644);
49 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
51 static unsigned long default_ps_max_latency_us = 100000;
52 module_param(default_ps_max_latency_us, ulong, 0644);
53 MODULE_PARM_DESC(default_ps_max_latency_us,
54 "max power saving latency for new devices; use PM QOS to change per device");
56 static bool force_apst;
57 module_param(force_apst, bool, 0644);
58 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
61 module_param(streams, bool, 0644);
62 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
65 * nvme_wq - hosts nvme related works that are not reset or delete
66 * nvme_reset_wq - hosts nvme reset works
67 * nvme_delete_wq - hosts nvme delete works
69 * nvme_wq will host works such as scan, aen handling, fw activation,
70 * keep-alive, periodic reconnects etc. nvme_reset_wq
71 * runs reset works which also flush works hosted on nvme_wq for
72 * serialization purposes. nvme_delete_wq host controller deletion
73 * works which flush reset works for serialization.
75 struct workqueue_struct *nvme_wq;
76 EXPORT_SYMBOL_GPL(nvme_wq);
78 struct workqueue_struct *nvme_reset_wq;
79 EXPORT_SYMBOL_GPL(nvme_reset_wq);
81 struct workqueue_struct *nvme_delete_wq;
82 EXPORT_SYMBOL_GPL(nvme_delete_wq);
84 static LIST_HEAD(nvme_subsystems);
85 static DEFINE_MUTEX(nvme_subsystems_lock);
87 static DEFINE_IDA(nvme_instance_ida);
88 static dev_t nvme_chr_devt;
89 static struct class *nvme_class;
90 static struct class *nvme_subsys_class;
92 static int nvme_revalidate_disk(struct gendisk *disk);
93 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
94 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
97 static void nvme_set_queue_dying(struct nvme_ns *ns)
100 * Revalidating a dead namespace sets capacity to 0. This will end
101 * buffered writers dirtying pages that can't be synced.
103 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
105 blk_set_queue_dying(ns->queue);
106 /* Forcibly unquiesce queues to avoid blocking dispatch */
107 blk_mq_unquiesce_queue(ns->queue);
109 * Revalidate after unblocking dispatchers that may be holding bd_butex
111 revalidate_disk(ns->disk);
114 static void nvme_queue_scan(struct nvme_ctrl *ctrl)
117 * Only new queue scan work when admin and IO queues are both alive
119 if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset)
120 queue_work(nvme_wq, &ctrl->scan_work);
124 * Use this function to proceed with scheduling reset_work for a controller
125 * that had previously been set to the resetting state. This is intended for
126 * code paths that can't be interrupted by other reset attempts. A hot removal
127 * may prevent this from succeeding.
129 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
131 if (ctrl->state != NVME_CTRL_RESETTING)
133 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
137 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
139 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
141 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
143 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
147 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
149 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
153 ret = nvme_reset_ctrl(ctrl);
155 flush_work(&ctrl->reset_work);
156 if (ctrl->state != NVME_CTRL_LIVE)
162 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync);
164 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
166 dev_info(ctrl->device,
167 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
169 flush_work(&ctrl->reset_work);
170 nvme_stop_ctrl(ctrl);
171 nvme_remove_namespaces(ctrl);
172 ctrl->ops->delete_ctrl(ctrl);
173 nvme_uninit_ctrl(ctrl);
176 static void nvme_delete_ctrl_work(struct work_struct *work)
178 struct nvme_ctrl *ctrl =
179 container_of(work, struct nvme_ctrl, delete_work);
181 nvme_do_delete_ctrl(ctrl);
184 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
186 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
188 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
192 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
194 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
197 * Keep a reference until nvme_do_delete_ctrl() complete,
198 * since ->delete_ctrl can free the controller.
201 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
202 nvme_do_delete_ctrl(ctrl);
206 static blk_status_t nvme_error_status(u16 status)
208 switch (status & 0x7ff) {
209 case NVME_SC_SUCCESS:
211 case NVME_SC_CAP_EXCEEDED:
212 return BLK_STS_NOSPC;
213 case NVME_SC_LBA_RANGE:
214 case NVME_SC_CMD_INTERRUPTED:
215 case NVME_SC_NS_NOT_READY:
216 return BLK_STS_TARGET;
217 case NVME_SC_BAD_ATTRIBUTES:
218 case NVME_SC_ONCS_NOT_SUPPORTED:
219 case NVME_SC_INVALID_OPCODE:
220 case NVME_SC_INVALID_FIELD:
221 case NVME_SC_INVALID_NS:
222 return BLK_STS_NOTSUPP;
223 case NVME_SC_WRITE_FAULT:
224 case NVME_SC_READ_ERROR:
225 case NVME_SC_UNWRITTEN_BLOCK:
226 case NVME_SC_ACCESS_DENIED:
227 case NVME_SC_READ_ONLY:
228 case NVME_SC_COMPARE_FAILED:
229 return BLK_STS_MEDIUM;
230 case NVME_SC_GUARD_CHECK:
231 case NVME_SC_APPTAG_CHECK:
232 case NVME_SC_REFTAG_CHECK:
233 case NVME_SC_INVALID_PI:
234 return BLK_STS_PROTECTION;
235 case NVME_SC_RESERVATION_CONFLICT:
236 return BLK_STS_NEXUS;
237 case NVME_SC_HOST_PATH_ERROR:
238 return BLK_STS_TRANSPORT;
240 return BLK_STS_IOERR;
244 static inline bool nvme_req_needs_retry(struct request *req)
246 if (blk_noretry_request(req))
248 if (nvme_req(req)->status & NVME_SC_DNR)
250 if (nvme_req(req)->retries >= nvme_max_retries)
255 static void nvme_retry_req(struct request *req)
257 struct nvme_ns *ns = req->q->queuedata;
258 unsigned long delay = 0;
261 /* The mask and shift result must be <= 3 */
262 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
264 delay = ns->ctrl->crdt[crd - 1] * 100;
266 nvme_req(req)->retries++;
267 blk_mq_requeue_request(req, false);
268 blk_mq_delay_kick_requeue_list(req->q, delay);
271 void nvme_complete_rq(struct request *req)
273 blk_status_t status = nvme_error_status(nvme_req(req)->status);
275 trace_nvme_complete_rq(req);
277 nvme_cleanup_cmd(req);
279 if (nvme_req(req)->ctrl->kas)
280 nvme_req(req)->ctrl->comp_seen = true;
282 if (unlikely(status != BLK_STS_OK && nvme_req_needs_retry(req))) {
283 if ((req->cmd_flags & REQ_NVME_MPATH) && nvme_failover_req(req))
286 if (!blk_queue_dying(req->q)) {
292 nvme_trace_bio_complete(req, status);
293 blk_mq_end_request(req, status);
295 EXPORT_SYMBOL_GPL(nvme_complete_rq);
297 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
299 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
300 "Cancelling I/O %d", req->tag);
302 /* don't abort one completed request */
303 if (blk_mq_request_completed(req))
306 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
307 blk_mq_complete_request(req);
310 EXPORT_SYMBOL_GPL(nvme_cancel_request);
312 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
313 enum nvme_ctrl_state new_state)
315 enum nvme_ctrl_state old_state;
317 bool changed = false;
319 spin_lock_irqsave(&ctrl->lock, flags);
321 old_state = ctrl->state;
326 case NVME_CTRL_RESETTING:
327 case NVME_CTRL_CONNECTING:
334 case NVME_CTRL_RESETTING:
344 case NVME_CTRL_CONNECTING:
347 case NVME_CTRL_RESETTING:
354 case NVME_CTRL_DELETING:
357 case NVME_CTRL_RESETTING:
358 case NVME_CTRL_CONNECTING:
367 case NVME_CTRL_DELETING:
379 ctrl->state = new_state;
380 wake_up_all(&ctrl->state_wq);
383 spin_unlock_irqrestore(&ctrl->lock, flags);
384 if (changed && ctrl->state == NVME_CTRL_LIVE)
385 nvme_kick_requeue_lists(ctrl);
388 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
391 * Returns true for sink states that can't ever transition back to live.
393 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
395 switch (ctrl->state) {
398 case NVME_CTRL_RESETTING:
399 case NVME_CTRL_CONNECTING:
401 case NVME_CTRL_DELETING:
405 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
411 * Waits for the controller state to be resetting, or returns false if it is
412 * not possible to ever transition to that state.
414 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
416 wait_event(ctrl->state_wq,
417 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
418 nvme_state_terminal(ctrl));
419 return ctrl->state == NVME_CTRL_RESETTING;
421 EXPORT_SYMBOL_GPL(nvme_wait_reset);
423 static void nvme_free_ns_head(struct kref *ref)
425 struct nvme_ns_head *head =
426 container_of(ref, struct nvme_ns_head, ref);
428 nvme_mpath_remove_disk(head);
429 ida_simple_remove(&head->subsys->ns_ida, head->instance);
430 cleanup_srcu_struct(&head->srcu);
431 nvme_put_subsystem(head->subsys);
435 static void nvme_put_ns_head(struct nvme_ns_head *head)
437 kref_put(&head->ref, nvme_free_ns_head);
440 static void nvme_free_ns(struct kref *kref)
442 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
445 nvme_nvm_unregister(ns);
448 nvme_put_ns_head(ns->head);
449 nvme_put_ctrl(ns->ctrl);
453 static void nvme_put_ns(struct nvme_ns *ns)
455 kref_put(&ns->kref, nvme_free_ns);
458 static inline void nvme_clear_nvme_request(struct request *req)
460 if (!(req->rq_flags & RQF_DONTPREP)) {
461 nvme_req(req)->retries = 0;
462 nvme_req(req)->flags = 0;
463 req->rq_flags |= RQF_DONTPREP;
467 struct request *nvme_alloc_request(struct request_queue *q,
468 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
470 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
473 if (qid == NVME_QID_ANY) {
474 req = blk_mq_alloc_request(q, op, flags);
476 req = blk_mq_alloc_request_hctx(q, op, flags,
482 req->cmd_flags |= REQ_FAILFAST_DRIVER;
483 nvme_clear_nvme_request(req);
484 nvme_req(req)->cmd = cmd;
488 EXPORT_SYMBOL_GPL(nvme_alloc_request);
490 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
492 struct nvme_command c;
494 memset(&c, 0, sizeof(c));
496 c.directive.opcode = nvme_admin_directive_send;
497 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
498 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
499 c.directive.dtype = NVME_DIR_IDENTIFY;
500 c.directive.tdtype = NVME_DIR_STREAMS;
501 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
503 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
506 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
508 return nvme_toggle_streams(ctrl, false);
511 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
513 return nvme_toggle_streams(ctrl, true);
516 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
517 struct streams_directive_params *s, u32 nsid)
519 struct nvme_command c;
521 memset(&c, 0, sizeof(c));
522 memset(s, 0, sizeof(*s));
524 c.directive.opcode = nvme_admin_directive_recv;
525 c.directive.nsid = cpu_to_le32(nsid);
526 c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
527 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
528 c.directive.dtype = NVME_DIR_STREAMS;
530 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
533 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
535 struct streams_directive_params s;
538 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
543 ret = nvme_enable_streams(ctrl);
547 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
549 goto out_disable_stream;
551 ctrl->nssa = le16_to_cpu(s.nssa);
552 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
553 dev_info(ctrl->device, "too few streams (%u) available\n",
555 goto out_disable_stream;
558 ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
559 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
563 nvme_disable_streams(ctrl);
568 * Check if 'req' has a write hint associated with it. If it does, assign
569 * a valid namespace stream to the write.
571 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
572 struct request *req, u16 *control,
575 enum rw_hint streamid = req->write_hint;
577 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
581 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
584 *control |= NVME_RW_DTYPE_STREAMS;
585 *dsmgmt |= streamid << 16;
588 if (streamid < ARRAY_SIZE(req->q->write_hints))
589 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
592 static inline void nvme_setup_flush(struct nvme_ns *ns,
593 struct nvme_command *cmnd)
595 cmnd->common.opcode = nvme_cmd_flush;
596 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
599 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
600 struct nvme_command *cmnd)
602 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
603 struct nvme_dsm_range *range;
607 * Some devices do not consider the DSM 'Number of Ranges' field when
608 * determining how much data to DMA. Always allocate memory for maximum
609 * number of segments to prevent device reading beyond end of buffer.
611 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
613 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
616 * If we fail allocation our range, fallback to the controller
617 * discard page. If that's also busy, it's safe to return
618 * busy, as we know we can make progress once that's freed.
620 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
621 return BLK_STS_RESOURCE;
623 range = page_address(ns->ctrl->discard_page);
626 __rq_for_each_bio(bio, req) {
627 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
628 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
631 range[n].cattr = cpu_to_le32(0);
632 range[n].nlb = cpu_to_le32(nlb);
633 range[n].slba = cpu_to_le64(slba);
638 if (WARN_ON_ONCE(n != segments)) {
639 if (virt_to_page(range) == ns->ctrl->discard_page)
640 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
643 return BLK_STS_IOERR;
646 cmnd->dsm.opcode = nvme_cmd_dsm;
647 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
648 cmnd->dsm.nr = cpu_to_le32(segments - 1);
649 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
651 req->special_vec.bv_page = virt_to_page(range);
652 req->special_vec.bv_offset = offset_in_page(range);
653 req->special_vec.bv_len = alloc_size;
654 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
659 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
660 struct request *req, struct nvme_command *cmnd)
662 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
663 return nvme_setup_discard(ns, req, cmnd);
665 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
666 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
667 cmnd->write_zeroes.slba =
668 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
669 cmnd->write_zeroes.length =
670 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
671 cmnd->write_zeroes.control = 0;
675 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
676 struct request *req, struct nvme_command *cmnd)
678 struct nvme_ctrl *ctrl = ns->ctrl;
682 if (req->cmd_flags & REQ_FUA)
683 control |= NVME_RW_FUA;
684 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
685 control |= NVME_RW_LR;
687 if (req->cmd_flags & REQ_RAHEAD)
688 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
690 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
691 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
692 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
693 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
695 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
696 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
700 * If formated with metadata, the block layer always provides a
701 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
702 * we enable the PRACT bit for protection information or set the
703 * namespace capacity to zero to prevent any I/O.
705 if (!blk_integrity_rq(req)) {
706 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
707 return BLK_STS_NOTSUPP;
708 control |= NVME_RW_PRINFO_PRACT;
711 switch (ns->pi_type) {
712 case NVME_NS_DPS_PI_TYPE3:
713 control |= NVME_RW_PRINFO_PRCHK_GUARD;
715 case NVME_NS_DPS_PI_TYPE1:
716 case NVME_NS_DPS_PI_TYPE2:
717 control |= NVME_RW_PRINFO_PRCHK_GUARD |
718 NVME_RW_PRINFO_PRCHK_REF;
719 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
724 cmnd->rw.control = cpu_to_le16(control);
725 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
729 void nvme_cleanup_cmd(struct request *req)
731 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
732 struct nvme_ns *ns = req->rq_disk->private_data;
733 struct page *page = req->special_vec.bv_page;
735 if (page == ns->ctrl->discard_page)
736 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
738 kfree(page_address(page) + req->special_vec.bv_offset);
741 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
743 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
744 struct nvme_command *cmd)
746 blk_status_t ret = BLK_STS_OK;
748 nvme_clear_nvme_request(req);
750 memset(cmd, 0, sizeof(*cmd));
751 switch (req_op(req)) {
754 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
757 nvme_setup_flush(ns, cmd);
759 case REQ_OP_WRITE_ZEROES:
760 ret = nvme_setup_write_zeroes(ns, req, cmd);
763 ret = nvme_setup_discard(ns, req, cmd);
767 ret = nvme_setup_rw(ns, req, cmd);
771 return BLK_STS_IOERR;
774 cmd->common.command_id = req->tag;
775 trace_nvme_setup_cmd(req, cmd);
778 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
780 static void nvme_end_sync_rq(struct request *rq, blk_status_t error)
782 struct completion *waiting = rq->end_io_data;
784 rq->end_io_data = NULL;
788 static void nvme_execute_rq_polled(struct request_queue *q,
789 struct gendisk *bd_disk, struct request *rq, int at_head)
791 DECLARE_COMPLETION_ONSTACK(wait);
793 WARN_ON_ONCE(!test_bit(QUEUE_FLAG_POLL, &q->queue_flags));
795 rq->cmd_flags |= REQ_HIPRI;
796 rq->end_io_data = &wait;
797 blk_execute_rq_nowait(q, bd_disk, rq, at_head, nvme_end_sync_rq);
799 while (!completion_done(&wait)) {
800 blk_poll(q, request_to_qc_t(rq->mq_hctx, rq), true);
806 * Returns 0 on success. If the result is negative, it's a Linux error code;
807 * if the result is positive, it's an NVM Express status code
809 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
810 union nvme_result *result, void *buffer, unsigned bufflen,
811 unsigned timeout, int qid, int at_head,
812 blk_mq_req_flags_t flags, bool poll)
817 req = nvme_alloc_request(q, cmd, flags, qid);
821 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
823 if (buffer && bufflen) {
824 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
830 nvme_execute_rq_polled(req->q, NULL, req, at_head);
832 blk_execute_rq(req->q, NULL, req, at_head);
834 *result = nvme_req(req)->result;
835 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
838 ret = nvme_req(req)->status;
840 blk_mq_free_request(req);
843 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
845 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
846 void *buffer, unsigned bufflen)
848 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
849 NVME_QID_ANY, 0, 0, false);
851 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
853 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
854 unsigned len, u32 seed, bool write)
856 struct bio_integrity_payload *bip;
860 buf = kmalloc(len, GFP_KERNEL);
865 if (write && copy_from_user(buf, ubuf, len))
868 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
874 bip->bip_iter.bi_size = len;
875 bip->bip_iter.bi_sector = seed;
876 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
877 offset_in_page(buf));
887 static int nvme_submit_user_cmd(struct request_queue *q,
888 struct nvme_command *cmd, void __user *ubuffer,
889 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
890 u32 meta_seed, u64 *result, unsigned timeout)
892 bool write = nvme_is_write(cmd);
893 struct nvme_ns *ns = q->queuedata;
894 struct gendisk *disk = ns ? ns->disk : NULL;
896 struct bio *bio = NULL;
900 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
904 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
905 nvme_req(req)->flags |= NVME_REQ_USERCMD;
907 if (ubuffer && bufflen) {
908 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
914 if (disk && meta_buffer && meta_len) {
915 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
921 req->cmd_flags |= REQ_INTEGRITY;
925 blk_execute_rq(req->q, disk, req, 0);
926 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
929 ret = nvme_req(req)->status;
931 *result = le64_to_cpu(nvme_req(req)->result.u64);
932 if (meta && !ret && !write) {
933 if (copy_to_user(meta_buffer, meta, meta_len))
939 blk_rq_unmap_user(bio);
941 blk_mq_free_request(req);
945 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
947 struct nvme_ctrl *ctrl = rq->end_io_data;
949 bool startka = false;
951 blk_mq_free_request(rq);
954 dev_err(ctrl->device,
955 "failed nvme_keep_alive_end_io error=%d\n",
960 ctrl->comp_seen = false;
961 spin_lock_irqsave(&ctrl->lock, flags);
962 if (ctrl->state == NVME_CTRL_LIVE ||
963 ctrl->state == NVME_CTRL_CONNECTING)
965 spin_unlock_irqrestore(&ctrl->lock, flags);
967 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
970 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
974 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
979 rq->timeout = ctrl->kato * HZ;
980 rq->end_io_data = ctrl;
982 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
987 static void nvme_keep_alive_work(struct work_struct *work)
989 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
990 struct nvme_ctrl, ka_work);
991 bool comp_seen = ctrl->comp_seen;
993 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
994 dev_dbg(ctrl->device,
995 "reschedule traffic based keep-alive timer\n");
996 ctrl->comp_seen = false;
997 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1001 if (nvme_keep_alive(ctrl)) {
1002 /* allocation failure, reset the controller */
1003 dev_err(ctrl->device, "keep-alive failed\n");
1004 nvme_reset_ctrl(ctrl);
1009 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1011 if (unlikely(ctrl->kato == 0))
1014 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1017 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1019 if (unlikely(ctrl->kato == 0))
1022 cancel_delayed_work_sync(&ctrl->ka_work);
1024 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1027 * In NVMe 1.0 the CNS field was just a binary controller or namespace
1028 * flag, thus sending any new CNS opcodes has a big chance of not working.
1029 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1030 * (but not for any later version).
1032 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1034 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1035 return ctrl->vs < NVME_VS(1, 2, 0);
1036 return ctrl->vs < NVME_VS(1, 1, 0);
1039 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1041 struct nvme_command c = { };
1044 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1045 c.identify.opcode = nvme_admin_identify;
1046 c.identify.cns = NVME_ID_CNS_CTRL;
1048 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1052 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1053 sizeof(struct nvme_id_ctrl));
1059 static bool nvme_multi_css(struct nvme_ctrl *ctrl)
1061 return (ctrl->ctrl_config & NVME_CC_CSS_MASK) == NVME_CC_CSS_CSI;
1064 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1065 struct nvme_ns_id_desc *cur, bool *csi_seen)
1067 const char *warn_str = "ctrl returned bogus length:";
1070 switch (cur->nidt) {
1071 case NVME_NIDT_EUI64:
1072 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1073 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1074 warn_str, cur->nidl);
1077 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1078 return NVME_NIDT_EUI64_LEN;
1079 case NVME_NIDT_NGUID:
1080 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1081 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1082 warn_str, cur->nidl);
1085 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1086 return NVME_NIDT_NGUID_LEN;
1087 case NVME_NIDT_UUID:
1088 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1089 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1090 warn_str, cur->nidl);
1093 uuid_copy(&ids->uuid, data + sizeof(*cur));
1094 return NVME_NIDT_UUID_LEN;
1096 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1097 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1098 warn_str, cur->nidl);
1101 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1103 return NVME_NIDT_CSI_LEN;
1105 /* Skip unknown types */
1110 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1111 struct nvme_ns_ids *ids)
1113 struct nvme_command c = { };
1114 bool csi_seen = false;
1115 int status, pos, len;
1118 c.identify.opcode = nvme_admin_identify;
1119 c.identify.nsid = cpu_to_le32(nsid);
1120 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1122 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1126 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1127 NVME_IDENTIFY_DATA_SIZE);
1129 dev_warn(ctrl->device,
1130 "Identify Descriptors failed (%d)\n", status);
1132 * Don't treat non-retryable errors as fatal, as we potentially
1133 * already have a NGUID or EUI-64. If we failed with DNR set,
1134 * we want to silently ignore the error as we can still
1135 * identify the device, but if the status has DNR set, we want
1136 * to propagate the error back specifically for the disk
1137 * revalidation flow to make sure we don't abandon the
1138 * device just because of a temporal retry-able error (such
1139 * as path of transport errors).
1141 if (status > 0 && (status & NVME_SC_DNR) && !nvme_multi_css(ctrl))
1146 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1147 struct nvme_ns_id_desc *cur = data + pos;
1152 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1156 len += sizeof(*cur);
1159 if (nvme_multi_css(ctrl) && !csi_seen) {
1160 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1170 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
1172 struct nvme_command c = { };
1174 c.identify.opcode = nvme_admin_identify;
1175 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
1176 c.identify.nsid = cpu_to_le32(nsid);
1177 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
1178 NVME_IDENTIFY_DATA_SIZE);
1181 static int nvme_identify_ns(struct nvme_ctrl *ctrl,
1182 unsigned nsid, struct nvme_id_ns **id)
1184 struct nvme_command c = { };
1187 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1188 c.identify.opcode = nvme_admin_identify;
1189 c.identify.nsid = cpu_to_le32(nsid);
1190 c.identify.cns = NVME_ID_CNS_NS;
1192 *id = kmalloc(sizeof(**id), GFP_KERNEL);
1196 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1198 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1205 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1206 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1208 union nvme_result res = { 0 };
1209 struct nvme_command c;
1212 memset(&c, 0, sizeof(c));
1213 c.features.opcode = op;
1214 c.features.fid = cpu_to_le32(fid);
1215 c.features.dword11 = cpu_to_le32(dword11);
1217 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1218 buffer, buflen, 0, NVME_QID_ANY, 0, 0, false);
1219 if (ret >= 0 && result)
1220 *result = le32_to_cpu(res.u32);
1224 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1225 unsigned int dword11, void *buffer, size_t buflen,
1228 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1231 EXPORT_SYMBOL_GPL(nvme_set_features);
1233 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1234 unsigned int dword11, void *buffer, size_t buflen,
1237 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1240 EXPORT_SYMBOL_GPL(nvme_get_features);
1242 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1244 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1246 int status, nr_io_queues;
1248 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1254 * Degraded controllers might return an error when setting the queue
1255 * count. We still want to be able to bring them online and offer
1256 * access to the admin queue, as that might be only way to fix them up.
1259 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1262 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1263 *count = min(*count, nr_io_queues);
1268 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1270 #define NVME_AEN_SUPPORTED \
1271 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1272 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1274 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1276 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1279 if (!supported_aens)
1282 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1285 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1288 queue_work(nvme_wq, &ctrl->async_event_work);
1292 * Convert integer values from ioctl structures to user pointers, silently
1293 * ignoring the upper bits in the compat case to match behaviour of 32-bit
1296 static void __user *nvme_to_user_ptr(uintptr_t ptrval)
1298 if (in_compat_syscall())
1299 ptrval = (compat_uptr_t)ptrval;
1300 return (void __user *)ptrval;
1303 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1305 struct nvme_user_io io;
1306 struct nvme_command c;
1307 unsigned length, meta_len;
1308 void __user *metadata;
1310 if (copy_from_user(&io, uio, sizeof(io)))
1315 switch (io.opcode) {
1316 case nvme_cmd_write:
1318 case nvme_cmd_compare:
1324 length = (io.nblocks + 1) << ns->lba_shift;
1325 meta_len = (io.nblocks + 1) * ns->ms;
1326 metadata = nvme_to_user_ptr(io.metadata);
1328 if (ns->features & NVME_NS_EXT_LBAS) {
1331 } else if (meta_len) {
1332 if ((io.metadata & 3) || !io.metadata)
1336 memset(&c, 0, sizeof(c));
1337 c.rw.opcode = io.opcode;
1338 c.rw.flags = io.flags;
1339 c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1340 c.rw.slba = cpu_to_le64(io.slba);
1341 c.rw.length = cpu_to_le16(io.nblocks);
1342 c.rw.control = cpu_to_le16(io.control);
1343 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1344 c.rw.reftag = cpu_to_le32(io.reftag);
1345 c.rw.apptag = cpu_to_le16(io.apptag);
1346 c.rw.appmask = cpu_to_le16(io.appmask);
1348 return nvme_submit_user_cmd(ns->queue, &c,
1349 nvme_to_user_ptr(io.addr), length,
1350 metadata, meta_len, lower_32_bits(io.slba), NULL, 0);
1353 static u32 nvme_known_admin_effects(u8 opcode)
1356 case nvme_admin_format_nvm:
1357 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
1358 NVME_CMD_EFFECTS_CSE_MASK;
1359 case nvme_admin_sanitize_nvm:
1360 return NVME_CMD_EFFECTS_CSE_MASK;
1367 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1374 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1375 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1376 dev_warn(ctrl->device,
1377 "IO command:%02x has unhandled effects:%08x\n",
1383 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1384 effects |= nvme_known_admin_effects(opcode);
1387 * For simplicity, IO to all namespaces is quiesced even if the command
1388 * effects say only one namespace is affected.
1390 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1391 mutex_lock(&ctrl->scan_lock);
1392 mutex_lock(&ctrl->subsys->lock);
1393 nvme_mpath_start_freeze(ctrl->subsys);
1394 nvme_mpath_wait_freeze(ctrl->subsys);
1395 nvme_start_freeze(ctrl);
1396 nvme_wait_freeze(ctrl);
1401 static void nvme_update_formats(struct nvme_ctrl *ctrl)
1405 down_read(&ctrl->namespaces_rwsem);
1406 list_for_each_entry(ns, &ctrl->namespaces, list)
1407 if (ns->disk && nvme_revalidate_disk(ns->disk))
1408 nvme_set_queue_dying(ns);
1409 up_read(&ctrl->namespaces_rwsem);
1412 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1415 * Revalidate LBA changes prior to unfreezing. This is necessary to
1416 * prevent memory corruption if a logical block size was changed by
1419 if (effects & NVME_CMD_EFFECTS_LBCC)
1420 nvme_update_formats(ctrl);
1421 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1422 nvme_unfreeze(ctrl);
1423 nvme_mpath_unfreeze(ctrl->subsys);
1424 mutex_unlock(&ctrl->subsys->lock);
1425 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1426 mutex_unlock(&ctrl->scan_lock);
1428 if (effects & NVME_CMD_EFFECTS_CCC)
1429 nvme_init_identify(ctrl);
1430 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1431 nvme_queue_scan(ctrl);
1432 flush_work(&ctrl->scan_work);
1436 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1437 struct nvme_passthru_cmd __user *ucmd)
1439 struct nvme_passthru_cmd cmd;
1440 struct nvme_command c;
1441 unsigned timeout = 0;
1446 if (!capable(CAP_SYS_ADMIN))
1448 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1453 memset(&c, 0, sizeof(c));
1454 c.common.opcode = cmd.opcode;
1455 c.common.flags = cmd.flags;
1456 c.common.nsid = cpu_to_le32(cmd.nsid);
1457 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1458 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1459 c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1460 c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1461 c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1462 c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1463 c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1464 c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1467 timeout = msecs_to_jiffies(cmd.timeout_ms);
1469 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1470 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1471 nvme_to_user_ptr(cmd.addr), cmd.data_len,
1472 nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1473 0, &result, timeout);
1474 nvme_passthru_end(ctrl, effects);
1477 if (put_user(result, &ucmd->result))
1484 static int nvme_user_cmd64(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1485 struct nvme_passthru_cmd64 __user *ucmd)
1487 struct nvme_passthru_cmd64 cmd;
1488 struct nvme_command c;
1489 unsigned timeout = 0;
1493 if (!capable(CAP_SYS_ADMIN))
1495 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1500 memset(&c, 0, sizeof(c));
1501 c.common.opcode = cmd.opcode;
1502 c.common.flags = cmd.flags;
1503 c.common.nsid = cpu_to_le32(cmd.nsid);
1504 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1505 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1506 c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1507 c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1508 c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1509 c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1510 c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1511 c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1514 timeout = msecs_to_jiffies(cmd.timeout_ms);
1516 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1517 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1518 nvme_to_user_ptr(cmd.addr), cmd.data_len,
1519 nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1520 0, &cmd.result, timeout);
1521 nvme_passthru_end(ctrl, effects);
1524 if (put_user(cmd.result, &ucmd->result))
1532 * Issue ioctl requests on the first available path. Note that unlike normal
1533 * block layer requests we will not retry failed request on another controller.
1535 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1536 struct nvme_ns_head **head, int *srcu_idx)
1538 #ifdef CONFIG_NVME_MULTIPATH
1539 if (disk->fops == &nvme_ns_head_ops) {
1542 *head = disk->private_data;
1543 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1544 ns = nvme_find_path(*head);
1546 srcu_read_unlock(&(*head)->srcu, *srcu_idx);
1552 return disk->private_data;
1555 static void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1558 srcu_read_unlock(&head->srcu, idx);
1561 static bool is_ctrl_ioctl(unsigned int cmd)
1563 if (cmd == NVME_IOCTL_ADMIN_CMD || cmd == NVME_IOCTL_ADMIN64_CMD)
1565 if (is_sed_ioctl(cmd))
1570 static int nvme_handle_ctrl_ioctl(struct nvme_ns *ns, unsigned int cmd,
1572 struct nvme_ns_head *head,
1575 struct nvme_ctrl *ctrl = ns->ctrl;
1578 nvme_get_ctrl(ns->ctrl);
1579 nvme_put_ns_from_disk(head, srcu_idx);
1582 case NVME_IOCTL_ADMIN_CMD:
1583 ret = nvme_user_cmd(ctrl, NULL, argp);
1585 case NVME_IOCTL_ADMIN64_CMD:
1586 ret = nvme_user_cmd64(ctrl, NULL, argp);
1589 ret = sed_ioctl(ctrl->opal_dev, cmd, argp);
1592 nvme_put_ctrl(ctrl);
1596 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1597 unsigned int cmd, unsigned long arg)
1599 struct nvme_ns_head *head = NULL;
1600 void __user *argp = (void __user *)arg;
1604 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1606 return -EWOULDBLOCK;
1609 * Handle ioctls that apply to the controller instead of the namespace
1610 * seperately and drop the ns SRCU reference early. This avoids a
1611 * deadlock when deleting namespaces using the passthrough interface.
1613 if (is_ctrl_ioctl(cmd))
1614 return nvme_handle_ctrl_ioctl(ns, cmd, argp, head, srcu_idx);
1618 force_successful_syscall_return();
1619 ret = ns->head->ns_id;
1621 case NVME_IOCTL_IO_CMD:
1622 ret = nvme_user_cmd(ns->ctrl, ns, argp);
1624 case NVME_IOCTL_SUBMIT_IO:
1625 ret = nvme_submit_io(ns, argp);
1627 case NVME_IOCTL_IO64_CMD:
1628 ret = nvme_user_cmd64(ns->ctrl, ns, argp);
1632 ret = nvme_nvm_ioctl(ns, cmd, arg);
1637 nvme_put_ns_from_disk(head, srcu_idx);
1641 #ifdef CONFIG_COMPAT
1642 struct nvme_user_io32 {
1655 } __attribute__((__packed__));
1657 #define NVME_IOCTL_SUBMIT_IO32 _IOW('N', 0x42, struct nvme_user_io32)
1659 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1660 unsigned int cmd, unsigned long arg)
1663 * Corresponds to the difference of NVME_IOCTL_SUBMIT_IO
1664 * between 32 bit programs and 64 bit kernel.
1665 * The cause is that the results of sizeof(struct nvme_user_io),
1666 * which is used to define NVME_IOCTL_SUBMIT_IO,
1667 * are not same between 32 bit compiler and 64 bit compiler.
1668 * NVME_IOCTL_SUBMIT_IO32 is for 64 bit kernel handling
1669 * NVME_IOCTL_SUBMIT_IO issued from 32 bit programs.
1670 * Other IOCTL numbers are same between 32 bit and 64 bit.
1671 * So there is nothing to do regarding to other IOCTL numbers.
1673 if (cmd == NVME_IOCTL_SUBMIT_IO32)
1674 return nvme_ioctl(bdev, mode, NVME_IOCTL_SUBMIT_IO, arg);
1676 return nvme_ioctl(bdev, mode, cmd, arg);
1679 #define nvme_compat_ioctl NULL
1680 #endif /* CONFIG_COMPAT */
1682 static int nvme_open(struct block_device *bdev, fmode_t mode)
1684 struct nvme_ns *ns = bdev->bd_disk->private_data;
1686 #ifdef CONFIG_NVME_MULTIPATH
1687 /* should never be called due to GENHD_FL_HIDDEN */
1688 if (WARN_ON_ONCE(ns->head->disk))
1691 if (!kref_get_unless_zero(&ns->kref))
1693 if (!try_module_get(ns->ctrl->ops->module))
1704 static void nvme_release(struct gendisk *disk, fmode_t mode)
1706 struct nvme_ns *ns = disk->private_data;
1708 module_put(ns->ctrl->ops->module);
1712 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1714 /* some standard values */
1715 geo->heads = 1 << 6;
1716 geo->sectors = 1 << 5;
1717 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1721 #ifdef CONFIG_BLK_DEV_INTEGRITY
1722 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1723 u32 max_integrity_segments)
1725 struct blk_integrity integrity;
1727 memset(&integrity, 0, sizeof(integrity));
1729 case NVME_NS_DPS_PI_TYPE3:
1730 integrity.profile = &t10_pi_type3_crc;
1731 integrity.tag_size = sizeof(u16) + sizeof(u32);
1732 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1734 case NVME_NS_DPS_PI_TYPE1:
1735 case NVME_NS_DPS_PI_TYPE2:
1736 integrity.profile = &t10_pi_type1_crc;
1737 integrity.tag_size = sizeof(u16);
1738 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1741 integrity.profile = NULL;
1744 integrity.tuple_size = ms;
1745 blk_integrity_register(disk, &integrity);
1746 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1749 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1750 u32 max_integrity_segments)
1753 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1755 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1757 struct nvme_ctrl *ctrl = ns->ctrl;
1758 struct request_queue *queue = disk->queue;
1759 u32 size = queue_logical_block_size(queue);
1761 if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1762 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1766 if (ctrl->nr_streams && ns->sws && ns->sgs)
1767 size *= ns->sws * ns->sgs;
1769 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1770 NVME_DSM_MAX_RANGES);
1772 queue->limits.discard_alignment = 0;
1773 queue->limits.discard_granularity = size;
1775 /* If discard is already enabled, don't reset queue limits */
1776 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1779 blk_queue_max_discard_sectors(queue, UINT_MAX);
1780 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1782 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1783 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1786 static void nvme_config_write_zeroes(struct gendisk *disk, struct nvme_ns *ns)
1790 if (!(ns->ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) ||
1791 (ns->ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
1794 * Even though NVMe spec explicitly states that MDTS is not
1795 * applicable to the write-zeroes:- "The restriction does not apply to
1796 * commands that do not transfer data between the host and the
1797 * controller (e.g., Write Uncorrectable ro Write Zeroes command).".
1798 * In order to be more cautious use controller's max_hw_sectors value
1799 * to configure the maximum sectors for the write-zeroes which is
1800 * configured based on the controller's MDTS field in the
1801 * nvme_init_identify() if available.
1803 if (ns->ctrl->max_hw_sectors == UINT_MAX)
1804 max_blocks = (u64)USHRT_MAX + 1;
1806 max_blocks = ns->ctrl->max_hw_sectors + 1;
1808 blk_queue_max_write_zeroes_sectors(disk->queue,
1809 nvme_lba_to_sect(ns, max_blocks));
1812 static int nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1813 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1815 memset(ids, 0, sizeof(*ids));
1817 if (ctrl->vs >= NVME_VS(1, 1, 0))
1818 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1819 if (ctrl->vs >= NVME_VS(1, 2, 0))
1820 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1821 if (ctrl->vs >= NVME_VS(1, 3, 0) || nvme_multi_css(ctrl))
1822 return nvme_identify_ns_descs(ctrl, nsid, ids);
1826 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1828 return !uuid_is_null(&ids->uuid) ||
1829 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1830 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1833 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1835 return uuid_equal(&a->uuid, &b->uuid) &&
1836 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1837 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1841 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1842 u32 *phys_bs, u32 *io_opt)
1844 struct streams_directive_params s;
1847 if (!ctrl->nr_streams)
1850 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1854 ns->sws = le32_to_cpu(s.sws);
1855 ns->sgs = le16_to_cpu(s.sgs);
1858 *phys_bs = ns->sws * (1 << ns->lba_shift);
1860 *io_opt = *phys_bs * ns->sgs;
1866 static void nvme_update_disk_info(struct gendisk *disk,
1867 struct nvme_ns *ns, struct nvme_id_ns *id)
1869 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1870 unsigned short bs = 1 << ns->lba_shift;
1871 u32 atomic_bs, phys_bs, io_opt = 0;
1873 if (ns->lba_shift > PAGE_SHIFT) {
1874 /* unsupported block size, set capacity to 0 later */
1877 blk_mq_freeze_queue(disk->queue);
1878 blk_integrity_unregister(disk);
1880 atomic_bs = phys_bs = bs;
1881 nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1882 if (id->nabo == 0) {
1884 * Bit 1 indicates whether NAWUPF is defined for this namespace
1885 * and whether it should be used instead of AWUPF. If NAWUPF ==
1886 * 0 then AWUPF must be used instead.
1888 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1889 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1891 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1894 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1895 /* NPWG = Namespace Preferred Write Granularity */
1896 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1897 /* NOWS = Namespace Optimal Write Size */
1898 io_opt = bs * (1 + le16_to_cpu(id->nows));
1901 blk_queue_logical_block_size(disk->queue, bs);
1903 * Linux filesystems assume writing a single physical block is
1904 * an atomic operation. Hence limit the physical block size to the
1905 * value of the Atomic Write Unit Power Fail parameter.
1907 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1908 blk_queue_io_min(disk->queue, phys_bs);
1909 blk_queue_io_opt(disk->queue, io_opt);
1912 * The block layer can't support LBA sizes larger than the page size
1913 * yet, so catch this early and don't allow block I/O.
1915 if (ns->lba_shift > PAGE_SHIFT)
1919 * Register a metadata profile for PI, or the plain non-integrity NVMe
1920 * metadata masquerading as Type 0 if supported, otherwise reject block
1921 * I/O to namespaces with metadata except when the namespace supports
1922 * PI, as it can strip/insert in that case.
1925 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
1926 (ns->features & NVME_NS_METADATA_SUPPORTED))
1927 nvme_init_integrity(disk, ns->ms, ns->pi_type,
1928 ns->ctrl->max_integrity_segments);
1929 else if (!nvme_ns_has_pi(ns))
1933 set_capacity_revalidate_and_notify(disk, capacity, false);
1935 nvme_config_discard(disk, ns);
1936 nvme_config_write_zeroes(disk, ns);
1938 if (id->nsattr & NVME_NS_ATTR_RO)
1939 set_disk_ro(disk, true);
1941 set_disk_ro(disk, false);
1943 blk_mq_unfreeze_queue(disk->queue);
1946 static int __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1948 struct nvme_ns *ns = disk->private_data;
1949 struct nvme_ctrl *ctrl = ns->ctrl;
1953 * If identify namespace failed, use default 512 byte block size so
1954 * block layer can use before failing read/write for 0 capacity.
1956 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1957 if (ns->lba_shift == 0)
1960 switch (ns->head->ids.csi) {
1964 dev_warn(ctrl->device, "unknown csi:%d ns:%d\n",
1965 ns->head->ids.csi, ns->head->ns_id);
1969 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1970 is_power_of_2(ctrl->max_hw_sectors))
1971 iob = ctrl->max_hw_sectors;
1973 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
1976 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1977 /* the PI implementation requires metadata equal t10 pi tuple size */
1978 if (ns->ms == sizeof(struct t10_pi_tuple))
1979 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1985 * For PCIe only the separate metadata pointer is supported,
1986 * as the block layer supplies metadata in a separate bio_vec
1987 * chain. For Fabrics, only metadata as part of extended data
1988 * LBA is supported on the wire per the Fabrics specification,
1989 * but the HBA/HCA will do the remapping from the separate
1990 * metadata buffers for us.
1992 if (id->flbas & NVME_NS_FLBAS_META_EXT) {
1993 ns->features |= NVME_NS_EXT_LBAS;
1994 if ((ctrl->ops->flags & NVME_F_FABRICS) &&
1995 (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED) &&
1996 ctrl->max_integrity_segments)
1997 ns->features |= NVME_NS_METADATA_SUPPORTED;
1999 if (WARN_ON_ONCE(ctrl->ops->flags & NVME_F_FABRICS))
2001 if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
2002 ns->features |= NVME_NS_METADATA_SUPPORTED;
2007 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(iob));
2008 nvme_update_disk_info(disk, ns, id);
2009 #ifdef CONFIG_NVME_MULTIPATH
2010 if (ns->head->disk) {
2011 nvme_update_disk_info(ns->head->disk, ns, id);
2012 blk_queue_stack_limits(ns->head->disk->queue, ns->queue);
2018 static int nvme_revalidate_disk(struct gendisk *disk)
2020 struct nvme_ns *ns = disk->private_data;
2021 struct nvme_ctrl *ctrl = ns->ctrl;
2022 struct nvme_id_ns *id;
2023 struct nvme_ns_ids ids;
2026 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
2027 set_capacity(disk, 0);
2031 ret = nvme_identify_ns(ctrl, ns->head->ns_id, &id);
2035 if (id->ncap == 0) {
2040 ret = nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
2044 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
2045 dev_err(ctrl->device,
2046 "identifiers changed for nsid %d\n", ns->head->ns_id);
2051 ret = __nvme_revalidate_disk(disk, id);
2056 * Only fail the function if we got a fatal error back from the
2057 * device, otherwise ignore the error and just move on.
2059 if (ret == -ENOMEM || (ret > 0 && !(ret & NVME_SC_DNR)))
2062 ret = blk_status_to_errno(nvme_error_status(ret));
2066 static char nvme_pr_type(enum pr_type type)
2069 case PR_WRITE_EXCLUSIVE:
2071 case PR_EXCLUSIVE_ACCESS:
2073 case PR_WRITE_EXCLUSIVE_REG_ONLY:
2075 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
2077 case PR_WRITE_EXCLUSIVE_ALL_REGS:
2079 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
2086 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
2087 u64 key, u64 sa_key, u8 op)
2089 struct nvme_ns_head *head = NULL;
2091 struct nvme_command c;
2093 u8 data[16] = { 0, };
2095 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
2097 return -EWOULDBLOCK;
2099 put_unaligned_le64(key, &data[0]);
2100 put_unaligned_le64(sa_key, &data[8]);
2102 memset(&c, 0, sizeof(c));
2103 c.common.opcode = op;
2104 c.common.nsid = cpu_to_le32(ns->head->ns_id);
2105 c.common.cdw10 = cpu_to_le32(cdw10);
2107 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
2108 nvme_put_ns_from_disk(head, srcu_idx);
2112 static int nvme_pr_register(struct block_device *bdev, u64 old,
2113 u64 new, unsigned flags)
2117 if (flags & ~PR_FL_IGNORE_KEY)
2120 cdw10 = old ? 2 : 0;
2121 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2122 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2123 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2126 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2127 enum pr_type type, unsigned flags)
2131 if (flags & ~PR_FL_IGNORE_KEY)
2134 cdw10 = nvme_pr_type(type) << 8;
2135 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2136 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2139 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2140 enum pr_type type, bool abort)
2142 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
2143 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2146 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2148 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2149 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2152 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2154 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
2155 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2158 static const struct pr_ops nvme_pr_ops = {
2159 .pr_register = nvme_pr_register,
2160 .pr_reserve = nvme_pr_reserve,
2161 .pr_release = nvme_pr_release,
2162 .pr_preempt = nvme_pr_preempt,
2163 .pr_clear = nvme_pr_clear,
2166 #ifdef CONFIG_BLK_SED_OPAL
2167 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2170 struct nvme_ctrl *ctrl = data;
2171 struct nvme_command cmd;
2173 memset(&cmd, 0, sizeof(cmd));
2175 cmd.common.opcode = nvme_admin_security_send;
2177 cmd.common.opcode = nvme_admin_security_recv;
2178 cmd.common.nsid = 0;
2179 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2180 cmd.common.cdw11 = cpu_to_le32(len);
2182 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
2183 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0, false);
2185 EXPORT_SYMBOL_GPL(nvme_sec_submit);
2186 #endif /* CONFIG_BLK_SED_OPAL */
2188 static const struct block_device_operations nvme_fops = {
2189 .owner = THIS_MODULE,
2190 .ioctl = nvme_ioctl,
2191 .compat_ioctl = nvme_compat_ioctl,
2193 .release = nvme_release,
2194 .getgeo = nvme_getgeo,
2195 .revalidate_disk= nvme_revalidate_disk,
2196 .pr_ops = &nvme_pr_ops,
2199 #ifdef CONFIG_NVME_MULTIPATH
2200 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
2202 struct nvme_ns_head *head = bdev->bd_disk->private_data;
2204 if (!kref_get_unless_zero(&head->ref))
2209 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
2211 nvme_put_ns_head(disk->private_data);
2214 const struct block_device_operations nvme_ns_head_ops = {
2215 .owner = THIS_MODULE,
2216 .submit_bio = nvme_ns_head_submit_bio,
2217 .open = nvme_ns_head_open,
2218 .release = nvme_ns_head_release,
2219 .ioctl = nvme_ioctl,
2220 .compat_ioctl = nvme_compat_ioctl,
2221 .getgeo = nvme_getgeo,
2222 .pr_ops = &nvme_pr_ops,
2224 #endif /* CONFIG_NVME_MULTIPATH */
2226 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2228 unsigned long timeout =
2229 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2230 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2233 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2236 if ((csts & NVME_CSTS_RDY) == bit)
2239 usleep_range(1000, 2000);
2240 if (fatal_signal_pending(current))
2242 if (time_after(jiffies, timeout)) {
2243 dev_err(ctrl->device,
2244 "Device not ready; aborting %s, CSTS=0x%x\n",
2245 enabled ? "initialisation" : "reset", csts);
2254 * If the device has been passed off to us in an enabled state, just clear
2255 * the enabled bit. The spec says we should set the 'shutdown notification
2256 * bits', but doing so may cause the device to complete commands to the
2257 * admin queue ... and we don't know what memory that might be pointing at!
2259 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2263 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2264 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2266 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2270 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2271 msleep(NVME_QUIRK_DELAY_AMOUNT);
2273 return nvme_wait_ready(ctrl, ctrl->cap, false);
2275 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2277 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2280 * Default to a 4K page size, with the intention to update this
2281 * path in the future to accomodate architectures with differing
2282 * kernel and IO page sizes.
2284 unsigned dev_page_min, page_shift = 12;
2287 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2289 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2292 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2294 if (page_shift < dev_page_min) {
2295 dev_err(ctrl->device,
2296 "Minimum device page size %u too large for host (%u)\n",
2297 1 << dev_page_min, 1 << page_shift);
2301 ctrl->page_size = 1 << page_shift;
2303 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2304 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2306 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2307 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
2308 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2309 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2310 ctrl->ctrl_config |= NVME_CC_ENABLE;
2312 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2315 return nvme_wait_ready(ctrl, ctrl->cap, true);
2317 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2319 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2321 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2325 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2326 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2328 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2332 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2333 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2337 if (fatal_signal_pending(current))
2339 if (time_after(jiffies, timeout)) {
2340 dev_err(ctrl->device,
2341 "Device shutdown incomplete; abort shutdown\n");
2348 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2350 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
2351 struct request_queue *q)
2355 if (ctrl->max_hw_sectors) {
2357 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
2359 max_segments = min_not_zero(max_segments, ctrl->max_segments);
2360 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
2361 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
2363 blk_queue_virt_boundary(q, ctrl->page_size - 1);
2364 blk_queue_dma_alignment(q, 7);
2365 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
2367 blk_queue_write_cache(q, vwc, vwc);
2370 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2375 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2378 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2379 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2382 dev_warn_once(ctrl->device,
2383 "could not set timestamp (%d)\n", ret);
2387 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2389 struct nvme_feat_host_behavior *host;
2392 /* Don't bother enabling the feature if retry delay is not reported */
2396 host = kzalloc(sizeof(*host), GFP_KERNEL);
2400 host->acre = NVME_ENABLE_ACRE;
2401 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2402 host, sizeof(*host), NULL);
2407 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2410 * APST (Autonomous Power State Transition) lets us program a
2411 * table of power state transitions that the controller will
2412 * perform automatically. We configure it with a simple
2413 * heuristic: we are willing to spend at most 2% of the time
2414 * transitioning between power states. Therefore, when running
2415 * in any given state, we will enter the next lower-power
2416 * non-operational state after waiting 50 * (enlat + exlat)
2417 * microseconds, as long as that state's exit latency is under
2418 * the requested maximum latency.
2420 * We will not autonomously enter any non-operational state for
2421 * which the total latency exceeds ps_max_latency_us. Users
2422 * can set ps_max_latency_us to zero to turn off APST.
2426 struct nvme_feat_auto_pst *table;
2432 * If APST isn't supported or if we haven't been initialized yet,
2433 * then don't do anything.
2438 if (ctrl->npss > 31) {
2439 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2443 table = kzalloc(sizeof(*table), GFP_KERNEL);
2447 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2448 /* Turn off APST. */
2450 dev_dbg(ctrl->device, "APST disabled\n");
2452 __le64 target = cpu_to_le64(0);
2456 * Walk through all states from lowest- to highest-power.
2457 * According to the spec, lower-numbered states use more
2458 * power. NPSS, despite the name, is the index of the
2459 * lowest-power state, not the number of states.
2461 for (state = (int)ctrl->npss; state >= 0; state--) {
2462 u64 total_latency_us, exit_latency_us, transition_ms;
2465 table->entries[state] = target;
2468 * Don't allow transitions to the deepest state
2469 * if it's quirked off.
2471 if (state == ctrl->npss &&
2472 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2476 * Is this state a useful non-operational state for
2477 * higher-power states to autonomously transition to?
2479 if (!(ctrl->psd[state].flags &
2480 NVME_PS_FLAGS_NON_OP_STATE))
2484 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2485 if (exit_latency_us > ctrl->ps_max_latency_us)
2490 le32_to_cpu(ctrl->psd[state].entry_lat);
2493 * This state is good. Use it as the APST idle
2494 * target for higher power states.
2496 transition_ms = total_latency_us + 19;
2497 do_div(transition_ms, 20);
2498 if (transition_ms > (1 << 24) - 1)
2499 transition_ms = (1 << 24) - 1;
2501 target = cpu_to_le64((state << 3) |
2502 (transition_ms << 8));
2507 if (total_latency_us > max_lat_us)
2508 max_lat_us = total_latency_us;
2514 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2516 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2517 max_ps, max_lat_us, (int)sizeof(*table), table);
2521 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2522 table, sizeof(*table), NULL);
2524 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2530 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2532 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2536 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2537 case PM_QOS_LATENCY_ANY:
2545 if (ctrl->ps_max_latency_us != latency) {
2546 ctrl->ps_max_latency_us = latency;
2547 nvme_configure_apst(ctrl);
2551 struct nvme_core_quirk_entry {
2553 * NVMe model and firmware strings are padded with spaces. For
2554 * simplicity, strings in the quirk table are padded with NULLs
2560 unsigned long quirks;
2563 static const struct nvme_core_quirk_entry core_quirks[] = {
2566 * This Toshiba device seems to die using any APST states. See:
2567 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2570 .mn = "THNSF5256GPUK TOSHIBA",
2571 .quirks = NVME_QUIRK_NO_APST,
2575 * This LiteON CL1-3D*-Q11 firmware version has a race
2576 * condition associated with actions related to suspend to idle
2577 * LiteON has resolved the problem in future firmware
2581 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2585 /* match is null-terminated but idstr is space-padded. */
2586 static bool string_matches(const char *idstr, const char *match, size_t len)
2593 matchlen = strlen(match);
2594 WARN_ON_ONCE(matchlen > len);
2596 if (memcmp(idstr, match, matchlen))
2599 for (; matchlen < len; matchlen++)
2600 if (idstr[matchlen] != ' ')
2606 static bool quirk_matches(const struct nvme_id_ctrl *id,
2607 const struct nvme_core_quirk_entry *q)
2609 return q->vid == le16_to_cpu(id->vid) &&
2610 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2611 string_matches(id->fr, q->fr, sizeof(id->fr));
2614 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2615 struct nvme_id_ctrl *id)
2620 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2621 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2622 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2623 strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2627 if (ctrl->vs >= NVME_VS(1, 2, 1))
2628 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2631 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2632 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2633 "nqn.2014.08.org.nvmexpress:%04x%04x",
2634 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2635 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2636 off += sizeof(id->sn);
2637 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2638 off += sizeof(id->mn);
2639 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2642 static void nvme_release_subsystem(struct device *dev)
2644 struct nvme_subsystem *subsys =
2645 container_of(dev, struct nvme_subsystem, dev);
2647 if (subsys->instance >= 0)
2648 ida_simple_remove(&nvme_instance_ida, subsys->instance);
2652 static void nvme_destroy_subsystem(struct kref *ref)
2654 struct nvme_subsystem *subsys =
2655 container_of(ref, struct nvme_subsystem, ref);
2657 mutex_lock(&nvme_subsystems_lock);
2658 list_del(&subsys->entry);
2659 mutex_unlock(&nvme_subsystems_lock);
2661 ida_destroy(&subsys->ns_ida);
2662 device_del(&subsys->dev);
2663 put_device(&subsys->dev);
2666 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2668 kref_put(&subsys->ref, nvme_destroy_subsystem);
2671 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2673 struct nvme_subsystem *subsys;
2675 lockdep_assert_held(&nvme_subsystems_lock);
2678 * Fail matches for discovery subsystems. This results
2679 * in each discovery controller bound to a unique subsystem.
2680 * This avoids issues with validating controller values
2681 * that can only be true when there is a single unique subsystem.
2682 * There may be multiple and completely independent entities
2683 * that provide discovery controllers.
2685 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2688 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2689 if (strcmp(subsys->subnqn, subsysnqn))
2691 if (!kref_get_unless_zero(&subsys->ref))
2699 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2700 struct device_attribute subsys_attr_##_name = \
2701 __ATTR(_name, _mode, _show, NULL)
2703 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2704 struct device_attribute *attr,
2707 struct nvme_subsystem *subsys =
2708 container_of(dev, struct nvme_subsystem, dev);
2710 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2712 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2714 #define nvme_subsys_show_str_function(field) \
2715 static ssize_t subsys_##field##_show(struct device *dev, \
2716 struct device_attribute *attr, char *buf) \
2718 struct nvme_subsystem *subsys = \
2719 container_of(dev, struct nvme_subsystem, dev); \
2720 return sprintf(buf, "%.*s\n", \
2721 (int)sizeof(subsys->field), subsys->field); \
2723 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2725 nvme_subsys_show_str_function(model);
2726 nvme_subsys_show_str_function(serial);
2727 nvme_subsys_show_str_function(firmware_rev);
2729 static struct attribute *nvme_subsys_attrs[] = {
2730 &subsys_attr_model.attr,
2731 &subsys_attr_serial.attr,
2732 &subsys_attr_firmware_rev.attr,
2733 &subsys_attr_subsysnqn.attr,
2734 #ifdef CONFIG_NVME_MULTIPATH
2735 &subsys_attr_iopolicy.attr,
2740 static struct attribute_group nvme_subsys_attrs_group = {
2741 .attrs = nvme_subsys_attrs,
2744 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2745 &nvme_subsys_attrs_group,
2749 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2750 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2752 struct nvme_ctrl *tmp;
2754 lockdep_assert_held(&nvme_subsystems_lock);
2756 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2757 if (nvme_state_terminal(tmp))
2760 if (tmp->cntlid == ctrl->cntlid) {
2761 dev_err(ctrl->device,
2762 "Duplicate cntlid %u with %s, rejecting\n",
2763 ctrl->cntlid, dev_name(tmp->device));
2767 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2768 (ctrl->opts && ctrl->opts->discovery_nqn))
2771 dev_err(ctrl->device,
2772 "Subsystem does not support multiple controllers\n");
2779 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2781 struct nvme_subsystem *subsys, *found;
2784 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2788 subsys->instance = -1;
2789 mutex_init(&subsys->lock);
2790 kref_init(&subsys->ref);
2791 INIT_LIST_HEAD(&subsys->ctrls);
2792 INIT_LIST_HEAD(&subsys->nsheads);
2793 nvme_init_subnqn(subsys, ctrl, id);
2794 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2795 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2796 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2797 subsys->vendor_id = le16_to_cpu(id->vid);
2798 subsys->cmic = id->cmic;
2799 subsys->awupf = le16_to_cpu(id->awupf);
2800 #ifdef CONFIG_NVME_MULTIPATH
2801 subsys->iopolicy = NVME_IOPOLICY_NUMA;
2804 subsys->dev.class = nvme_subsys_class;
2805 subsys->dev.release = nvme_release_subsystem;
2806 subsys->dev.groups = nvme_subsys_attrs_groups;
2807 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2808 device_initialize(&subsys->dev);
2810 mutex_lock(&nvme_subsystems_lock);
2811 found = __nvme_find_get_subsystem(subsys->subnqn);
2813 put_device(&subsys->dev);
2816 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2818 goto out_put_subsystem;
2821 ret = device_add(&subsys->dev);
2823 dev_err(ctrl->device,
2824 "failed to register subsystem device.\n");
2825 put_device(&subsys->dev);
2828 ida_init(&subsys->ns_ida);
2829 list_add_tail(&subsys->entry, &nvme_subsystems);
2832 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2833 dev_name(ctrl->device));
2835 dev_err(ctrl->device,
2836 "failed to create sysfs link from subsystem.\n");
2837 goto out_put_subsystem;
2841 subsys->instance = ctrl->instance;
2842 ctrl->subsys = subsys;
2843 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2844 mutex_unlock(&nvme_subsystems_lock);
2848 nvme_put_subsystem(subsys);
2850 mutex_unlock(&nvme_subsystems_lock);
2854 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp,
2855 void *log, size_t size, u64 offset)
2857 struct nvme_command c = { };
2858 u32 dwlen = nvme_bytes_to_numd(size);
2860 c.get_log_page.opcode = nvme_admin_get_log_page;
2861 c.get_log_page.nsid = cpu_to_le32(nsid);
2862 c.get_log_page.lid = log_page;
2863 c.get_log_page.lsp = lsp;
2864 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2865 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2866 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2867 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2869 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2872 static int nvme_get_effects_log(struct nvme_ctrl *ctrl)
2877 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL);
2882 ret = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CMD_EFFECTS, 0,
2883 ctrl->effects, sizeof(*ctrl->effects), 0);
2885 kfree(ctrl->effects);
2886 ctrl->effects = NULL;
2892 * Initialize the cached copies of the Identify data and various controller
2893 * register in our nvme_ctrl structure. This should be called as soon as
2894 * the admin queue is fully up and running.
2896 int nvme_init_identify(struct nvme_ctrl *ctrl)
2898 struct nvme_id_ctrl *id;
2899 int ret, page_shift;
2901 bool prev_apst_enabled;
2903 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
2905 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
2908 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2909 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
2911 if (ctrl->vs >= NVME_VS(1, 1, 0))
2912 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
2914 ret = nvme_identify_ctrl(ctrl, &id);
2916 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2920 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2921 ret = nvme_get_effects_log(ctrl);
2926 if (!(ctrl->ops->flags & NVME_F_FABRICS))
2927 ctrl->cntlid = le16_to_cpu(id->cntlid);
2929 if (!ctrl->identified) {
2932 ret = nvme_init_subsystem(ctrl, id);
2937 * Check for quirks. Quirk can depend on firmware version,
2938 * so, in principle, the set of quirks present can change
2939 * across a reset. As a possible future enhancement, we
2940 * could re-scan for quirks every time we reinitialize
2941 * the device, but we'd have to make sure that the driver
2942 * behaves intelligently if the quirks change.
2944 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2945 if (quirk_matches(id, &core_quirks[i]))
2946 ctrl->quirks |= core_quirks[i].quirks;
2950 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2951 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2952 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2955 ctrl->crdt[0] = le16_to_cpu(id->crdt1);
2956 ctrl->crdt[1] = le16_to_cpu(id->crdt2);
2957 ctrl->crdt[2] = le16_to_cpu(id->crdt3);
2959 ctrl->oacs = le16_to_cpu(id->oacs);
2960 ctrl->oncs = le16_to_cpu(id->oncs);
2961 ctrl->mtfa = le16_to_cpu(id->mtfa);
2962 ctrl->oaes = le32_to_cpu(id->oaes);
2963 ctrl->wctemp = le16_to_cpu(id->wctemp);
2964 ctrl->cctemp = le16_to_cpu(id->cctemp);
2966 atomic_set(&ctrl->abort_limit, id->acl + 1);
2967 ctrl->vwc = id->vwc;
2969 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
2971 max_hw_sectors = UINT_MAX;
2972 ctrl->max_hw_sectors =
2973 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2975 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2976 ctrl->sgls = le32_to_cpu(id->sgls);
2977 ctrl->kas = le16_to_cpu(id->kas);
2978 ctrl->max_namespaces = le32_to_cpu(id->mnan);
2979 ctrl->ctratt = le32_to_cpu(id->ctratt);
2983 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
2985 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2986 shutdown_timeout, 60);
2988 if (ctrl->shutdown_timeout != shutdown_timeout)
2989 dev_info(ctrl->device,
2990 "Shutdown timeout set to %u seconds\n",
2991 ctrl->shutdown_timeout);
2993 ctrl->shutdown_timeout = shutdown_timeout;
2995 ctrl->npss = id->npss;
2996 ctrl->apsta = id->apsta;
2997 prev_apst_enabled = ctrl->apst_enabled;
2998 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2999 if (force_apst && id->apsta) {
3000 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
3001 ctrl->apst_enabled = true;
3003 ctrl->apst_enabled = false;
3006 ctrl->apst_enabled = id->apsta;
3008 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
3010 if (ctrl->ops->flags & NVME_F_FABRICS) {
3011 ctrl->icdoff = le16_to_cpu(id->icdoff);
3012 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
3013 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
3014 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
3017 * In fabrics we need to verify the cntlid matches the
3020 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
3021 dev_err(ctrl->device,
3022 "Mismatching cntlid: Connect %u vs Identify "
3024 ctrl->cntlid, le16_to_cpu(id->cntlid));
3029 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
3030 dev_err(ctrl->device,
3031 "keep-alive support is mandatory for fabrics\n");
3036 ctrl->hmpre = le32_to_cpu(id->hmpre);
3037 ctrl->hmmin = le32_to_cpu(id->hmmin);
3038 ctrl->hmminds = le32_to_cpu(id->hmminds);
3039 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
3042 ret = nvme_mpath_init(ctrl, id);
3048 if (ctrl->apst_enabled && !prev_apst_enabled)
3049 dev_pm_qos_expose_latency_tolerance(ctrl->device);
3050 else if (!ctrl->apst_enabled && prev_apst_enabled)
3051 dev_pm_qos_hide_latency_tolerance(ctrl->device);
3053 ret = nvme_configure_apst(ctrl);
3057 ret = nvme_configure_timestamp(ctrl);
3061 ret = nvme_configure_directives(ctrl);
3065 ret = nvme_configure_acre(ctrl);
3069 if (!ctrl->identified)
3070 nvme_hwmon_init(ctrl);
3072 ctrl->identified = true;
3080 EXPORT_SYMBOL_GPL(nvme_init_identify);
3082 static int nvme_dev_open(struct inode *inode, struct file *file)
3084 struct nvme_ctrl *ctrl =
3085 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3087 switch (ctrl->state) {
3088 case NVME_CTRL_LIVE:
3091 return -EWOULDBLOCK;
3094 file->private_data = ctrl;
3098 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
3103 down_read(&ctrl->namespaces_rwsem);
3104 if (list_empty(&ctrl->namespaces)) {
3109 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
3110 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
3111 dev_warn(ctrl->device,
3112 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
3117 dev_warn(ctrl->device,
3118 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
3119 kref_get(&ns->kref);
3120 up_read(&ctrl->namespaces_rwsem);
3122 ret = nvme_user_cmd(ctrl, ns, argp);
3127 up_read(&ctrl->namespaces_rwsem);
3131 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
3134 struct nvme_ctrl *ctrl = file->private_data;
3135 void __user *argp = (void __user *)arg;
3138 case NVME_IOCTL_ADMIN_CMD:
3139 return nvme_user_cmd(ctrl, NULL, argp);
3140 case NVME_IOCTL_ADMIN64_CMD:
3141 return nvme_user_cmd64(ctrl, NULL, argp);
3142 case NVME_IOCTL_IO_CMD:
3143 return nvme_dev_user_cmd(ctrl, argp);
3144 case NVME_IOCTL_RESET:
3145 dev_warn(ctrl->device, "resetting controller\n");
3146 return nvme_reset_ctrl_sync(ctrl);
3147 case NVME_IOCTL_SUBSYS_RESET:
3148 return nvme_reset_subsystem(ctrl);
3149 case NVME_IOCTL_RESCAN:
3150 nvme_queue_scan(ctrl);
3157 static const struct file_operations nvme_dev_fops = {
3158 .owner = THIS_MODULE,
3159 .open = nvme_dev_open,
3160 .unlocked_ioctl = nvme_dev_ioctl,
3161 .compat_ioctl = compat_ptr_ioctl,
3164 static ssize_t nvme_sysfs_reset(struct device *dev,
3165 struct device_attribute *attr, const char *buf,
3168 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3171 ret = nvme_reset_ctrl_sync(ctrl);
3176 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3178 static ssize_t nvme_sysfs_rescan(struct device *dev,
3179 struct device_attribute *attr, const char *buf,
3182 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3184 nvme_queue_scan(ctrl);
3187 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
3189 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
3191 struct gendisk *disk = dev_to_disk(dev);
3193 if (disk->fops == &nvme_fops)
3194 return nvme_get_ns_from_dev(dev)->head;
3196 return disk->private_data;
3199 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
3202 struct nvme_ns_head *head = dev_to_ns_head(dev);
3203 struct nvme_ns_ids *ids = &head->ids;
3204 struct nvme_subsystem *subsys = head->subsys;
3205 int serial_len = sizeof(subsys->serial);
3206 int model_len = sizeof(subsys->model);
3208 if (!uuid_is_null(&ids->uuid))
3209 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
3211 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3212 return sprintf(buf, "eui.%16phN\n", ids->nguid);
3214 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3215 return sprintf(buf, "eui.%8phN\n", ids->eui64);
3217 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3218 subsys->serial[serial_len - 1] == '\0'))
3220 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3221 subsys->model[model_len - 1] == '\0'))
3224 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3225 serial_len, subsys->serial, model_len, subsys->model,
3228 static DEVICE_ATTR_RO(wwid);
3230 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3233 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3235 static DEVICE_ATTR_RO(nguid);
3237 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3240 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3242 /* For backward compatibility expose the NGUID to userspace if
3243 * we have no UUID set
3245 if (uuid_is_null(&ids->uuid)) {
3246 printk_ratelimited(KERN_WARNING
3247 "No UUID available providing old NGUID\n");
3248 return sprintf(buf, "%pU\n", ids->nguid);
3250 return sprintf(buf, "%pU\n", &ids->uuid);
3252 static DEVICE_ATTR_RO(uuid);
3254 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3257 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3259 static DEVICE_ATTR_RO(eui);
3261 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3264 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3266 static DEVICE_ATTR_RO(nsid);
3268 static struct attribute *nvme_ns_id_attrs[] = {
3269 &dev_attr_wwid.attr,
3270 &dev_attr_uuid.attr,
3271 &dev_attr_nguid.attr,
3273 &dev_attr_nsid.attr,
3274 #ifdef CONFIG_NVME_MULTIPATH
3275 &dev_attr_ana_grpid.attr,
3276 &dev_attr_ana_state.attr,
3281 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3282 struct attribute *a, int n)
3284 struct device *dev = container_of(kobj, struct device, kobj);
3285 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3287 if (a == &dev_attr_uuid.attr) {
3288 if (uuid_is_null(&ids->uuid) &&
3289 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3292 if (a == &dev_attr_nguid.attr) {
3293 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3296 if (a == &dev_attr_eui.attr) {
3297 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3300 #ifdef CONFIG_NVME_MULTIPATH
3301 if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3302 if (dev_to_disk(dev)->fops != &nvme_fops) /* per-path attr */
3304 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3311 static const struct attribute_group nvme_ns_id_attr_group = {
3312 .attrs = nvme_ns_id_attrs,
3313 .is_visible = nvme_ns_id_attrs_are_visible,
3316 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3317 &nvme_ns_id_attr_group,
3319 &nvme_nvm_attr_group,
3324 #define nvme_show_str_function(field) \
3325 static ssize_t field##_show(struct device *dev, \
3326 struct device_attribute *attr, char *buf) \
3328 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3329 return sprintf(buf, "%.*s\n", \
3330 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
3332 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3334 nvme_show_str_function(model);
3335 nvme_show_str_function(serial);
3336 nvme_show_str_function(firmware_rev);
3338 #define nvme_show_int_function(field) \
3339 static ssize_t field##_show(struct device *dev, \
3340 struct device_attribute *attr, char *buf) \
3342 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3343 return sprintf(buf, "%d\n", ctrl->field); \
3345 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3347 nvme_show_int_function(cntlid);
3348 nvme_show_int_function(numa_node);
3349 nvme_show_int_function(queue_count);
3350 nvme_show_int_function(sqsize);
3352 static ssize_t nvme_sysfs_delete(struct device *dev,
3353 struct device_attribute *attr, const char *buf,
3356 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3358 /* Can't delete non-created controllers */
3362 if (device_remove_file_self(dev, attr))
3363 nvme_delete_ctrl_sync(ctrl);
3366 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3368 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3369 struct device_attribute *attr,
3372 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3374 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
3376 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3378 static ssize_t nvme_sysfs_show_state(struct device *dev,
3379 struct device_attribute *attr,
3382 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3383 static const char *const state_name[] = {
3384 [NVME_CTRL_NEW] = "new",
3385 [NVME_CTRL_LIVE] = "live",
3386 [NVME_CTRL_RESETTING] = "resetting",
3387 [NVME_CTRL_CONNECTING] = "connecting",
3388 [NVME_CTRL_DELETING] = "deleting",
3389 [NVME_CTRL_DEAD] = "dead",
3392 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3393 state_name[ctrl->state])
3394 return sprintf(buf, "%s\n", state_name[ctrl->state]);
3396 return sprintf(buf, "unknown state\n");
3399 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3401 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3402 struct device_attribute *attr,
3405 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3407 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
3409 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3411 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3412 struct device_attribute *attr,
3415 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3417 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->opts->host->nqn);
3419 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3421 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3422 struct device_attribute *attr,
3425 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3427 return snprintf(buf, PAGE_SIZE, "%pU\n", &ctrl->opts->host->id);
3429 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3431 static ssize_t nvme_sysfs_show_address(struct device *dev,
3432 struct device_attribute *attr,
3435 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3437 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3439 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3441 static struct attribute *nvme_dev_attrs[] = {
3442 &dev_attr_reset_controller.attr,
3443 &dev_attr_rescan_controller.attr,
3444 &dev_attr_model.attr,
3445 &dev_attr_serial.attr,
3446 &dev_attr_firmware_rev.attr,
3447 &dev_attr_cntlid.attr,
3448 &dev_attr_delete_controller.attr,
3449 &dev_attr_transport.attr,
3450 &dev_attr_subsysnqn.attr,
3451 &dev_attr_address.attr,
3452 &dev_attr_state.attr,
3453 &dev_attr_numa_node.attr,
3454 &dev_attr_queue_count.attr,
3455 &dev_attr_sqsize.attr,
3456 &dev_attr_hostnqn.attr,
3457 &dev_attr_hostid.attr,
3461 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3462 struct attribute *a, int n)
3464 struct device *dev = container_of(kobj, struct device, kobj);
3465 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3467 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3469 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3471 if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3473 if (a == &dev_attr_hostid.attr && !ctrl->opts)
3479 static struct attribute_group nvme_dev_attrs_group = {
3480 .attrs = nvme_dev_attrs,
3481 .is_visible = nvme_dev_attrs_are_visible,
3484 static const struct attribute_group *nvme_dev_attr_groups[] = {
3485 &nvme_dev_attrs_group,
3489 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3492 struct nvme_ns_head *h;
3494 lockdep_assert_held(&subsys->lock);
3496 list_for_each_entry(h, &subsys->nsheads, entry) {
3497 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
3504 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3505 struct nvme_ns_head *new)
3507 struct nvme_ns_head *h;
3509 lockdep_assert_held(&subsys->lock);
3511 list_for_each_entry(h, &subsys->nsheads, entry) {
3512 if (nvme_ns_ids_valid(&new->ids) &&
3513 nvme_ns_ids_equal(&new->ids, &h->ids))
3520 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3521 unsigned nsid, struct nvme_ns_ids *ids)
3523 struct nvme_ns_head *head;
3524 size_t size = sizeof(*head);
3527 #ifdef CONFIG_NVME_MULTIPATH
3528 size += num_possible_nodes() * sizeof(struct nvme_ns *);
3531 head = kzalloc(size, GFP_KERNEL);
3534 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3537 head->instance = ret;
3538 INIT_LIST_HEAD(&head->list);
3539 ret = init_srcu_struct(&head->srcu);
3541 goto out_ida_remove;
3542 head->subsys = ctrl->subsys;
3545 kref_init(&head->ref);
3547 ret = __nvme_check_ids(ctrl->subsys, head);
3549 dev_err(ctrl->device,
3550 "duplicate IDs for nsid %d\n", nsid);
3551 goto out_cleanup_srcu;
3554 ret = nvme_mpath_alloc_disk(ctrl, head);
3556 goto out_cleanup_srcu;
3558 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3560 kref_get(&ctrl->subsys->ref);
3564 cleanup_srcu_struct(&head->srcu);
3566 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3571 ret = blk_status_to_errno(nvme_error_status(ret));
3572 return ERR_PTR(ret);
3575 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3576 struct nvme_id_ns *id)
3578 struct nvme_ctrl *ctrl = ns->ctrl;
3579 bool is_shared = id->nmic & NVME_NS_NMIC_SHARED;
3580 struct nvme_ns_head *head = NULL;
3581 struct nvme_ns_ids ids;
3584 ret = nvme_report_ns_ids(ctrl, nsid, id, &ids);
3588 return blk_status_to_errno(nvme_error_status(ret));
3591 mutex_lock(&ctrl->subsys->lock);
3592 head = nvme_find_ns_head(ctrl->subsys, nsid);
3594 head = nvme_alloc_ns_head(ctrl, nsid, &ids);
3596 ret = PTR_ERR(head);
3599 head->shared = is_shared;
3602 if (!is_shared || !head->shared) {
3603 dev_err(ctrl->device,
3604 "Duplicate unshared namespace %d\n", nsid);
3605 goto out_put_ns_head;
3607 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
3608 dev_err(ctrl->device,
3609 "IDs don't match for shared namespace %d\n",
3611 goto out_put_ns_head;
3615 list_add_tail(&ns->siblings, &head->list);
3617 mutex_unlock(&ctrl->subsys->lock);
3621 nvme_put_ns_head(head);
3623 mutex_unlock(&ctrl->subsys->lock);
3627 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
3629 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3630 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3632 return nsa->head->ns_id - nsb->head->ns_id;
3635 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3637 struct nvme_ns *ns, *ret = NULL;
3639 down_read(&ctrl->namespaces_rwsem);
3640 list_for_each_entry(ns, &ctrl->namespaces, list) {
3641 if (ns->head->ns_id == nsid) {
3642 if (!kref_get_unless_zero(&ns->kref))
3647 if (ns->head->ns_id > nsid)
3650 up_read(&ctrl->namespaces_rwsem);
3654 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3657 struct gendisk *disk;
3658 struct nvme_id_ns *id;
3659 char disk_name[DISK_NAME_LEN];
3660 int node = ctrl->numa_node, flags = GENHD_FL_EXT_DEVT, ret;
3662 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3666 ns->queue = blk_mq_init_queue(ctrl->tagset);
3667 if (IS_ERR(ns->queue))
3670 if (ctrl->opts && ctrl->opts->data_digest)
3671 ns->queue->backing_dev_info->capabilities
3672 |= BDI_CAP_STABLE_WRITES;
3674 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3675 if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3676 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3678 ns->queue->queuedata = ns;
3681 kref_init(&ns->kref);
3682 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
3684 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
3685 nvme_set_queue_limits(ctrl, ns->queue);
3687 ret = nvme_identify_ns(ctrl, nsid, &id);
3689 goto out_free_queue;
3691 if (id->ncap == 0) /* no namespace (legacy quirk) */
3694 ret = nvme_init_ns_head(ns, nsid, id);
3697 nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3699 disk = alloc_disk_node(0, node);
3703 disk->fops = &nvme_fops;
3704 disk->private_data = ns;
3705 disk->queue = ns->queue;
3706 disk->flags = flags;
3707 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3710 if (__nvme_revalidate_disk(disk, id))
3713 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3714 ret = nvme_nvm_register(ns, disk_name, node);
3716 dev_warn(ctrl->device, "LightNVM init failure\n");
3721 down_write(&ctrl->namespaces_rwsem);
3722 list_add_tail(&ns->list, &ctrl->namespaces);
3723 up_write(&ctrl->namespaces_rwsem);
3725 nvme_get_ctrl(ctrl);
3727 device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups);
3729 nvme_mpath_add_disk(ns, id);
3730 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3735 /* prevent double queue cleanup */
3736 ns->disk->queue = NULL;
3739 mutex_lock(&ctrl->subsys->lock);
3740 list_del_rcu(&ns->siblings);
3741 if (list_empty(&ns->head->list))
3742 list_del_init(&ns->head->entry);
3743 mutex_unlock(&ctrl->subsys->lock);
3744 nvme_put_ns_head(ns->head);
3748 blk_cleanup_queue(ns->queue);
3753 static void nvme_ns_remove(struct nvme_ns *ns)
3755 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3758 nvme_fault_inject_fini(&ns->fault_inject);
3760 mutex_lock(&ns->ctrl->subsys->lock);
3761 list_del_rcu(&ns->siblings);
3762 if (list_empty(&ns->head->list))
3763 list_del_init(&ns->head->entry);
3764 mutex_unlock(&ns->ctrl->subsys->lock);
3766 synchronize_rcu(); /* guarantee not available in head->list */
3767 nvme_mpath_clear_current_path(ns);
3768 synchronize_srcu(&ns->head->srcu); /* wait for concurrent submissions */
3770 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
3771 del_gendisk(ns->disk);
3772 blk_cleanup_queue(ns->queue);
3773 if (blk_get_integrity(ns->disk))
3774 blk_integrity_unregister(ns->disk);
3777 down_write(&ns->ctrl->namespaces_rwsem);
3778 list_del_init(&ns->list);
3779 up_write(&ns->ctrl->namespaces_rwsem);
3781 nvme_mpath_check_last_path(ns);
3785 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
3787 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
3795 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3799 ns = nvme_find_get_ns(ctrl, nsid);
3801 if (ns->disk && revalidate_disk(ns->disk))
3805 nvme_alloc_ns(ctrl, nsid);
3808 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3811 struct nvme_ns *ns, *next;
3814 down_write(&ctrl->namespaces_rwsem);
3815 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3816 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
3817 list_move_tail(&ns->list, &rm_list);
3819 up_write(&ctrl->namespaces_rwsem);
3821 list_for_each_entry_safe(ns, next, &rm_list, list)
3826 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
3828 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
3833 if (nvme_ctrl_limited_cns(ctrl))
3836 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3841 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
3845 for (i = 0; i < nr_entries; i++) {
3846 u32 nsid = le32_to_cpu(ns_list[i]);
3848 if (!nsid) /* end of the list? */
3850 nvme_validate_ns(ctrl, nsid);
3851 while (++prev < nsid)
3852 nvme_ns_remove_by_nsid(ctrl, prev);
3856 nvme_remove_invalid_namespaces(ctrl, prev);
3862 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
3864 struct nvme_id_ctrl *id;
3867 if (nvme_identify_ctrl(ctrl, &id))
3869 nn = le32_to_cpu(id->nn);
3872 for (i = 1; i <= nn; i++)
3873 nvme_validate_ns(ctrl, i);
3875 nvme_remove_invalid_namespaces(ctrl, nn);
3878 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
3880 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
3884 log = kzalloc(log_size, GFP_KERNEL);
3889 * We need to read the log to clear the AEN, but we don't want to rely
3890 * on it for the changed namespace information as userspace could have
3891 * raced with us in reading the log page, which could cause us to miss
3894 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0, log,
3897 dev_warn(ctrl->device,
3898 "reading changed ns log failed: %d\n", error);
3903 static void nvme_scan_work(struct work_struct *work)
3905 struct nvme_ctrl *ctrl =
3906 container_of(work, struct nvme_ctrl, scan_work);
3908 /* No tagset on a live ctrl means IO queues could not created */
3909 if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
3912 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
3913 dev_info(ctrl->device, "rescanning namespaces.\n");
3914 nvme_clear_changed_ns_log(ctrl);
3917 mutex_lock(&ctrl->scan_lock);
3918 if (nvme_scan_ns_list(ctrl) != 0)
3919 nvme_scan_ns_sequential(ctrl);
3920 mutex_unlock(&ctrl->scan_lock);
3922 down_write(&ctrl->namespaces_rwsem);
3923 list_sort(NULL, &ctrl->namespaces, ns_cmp);
3924 up_write(&ctrl->namespaces_rwsem);
3928 * This function iterates the namespace list unlocked to allow recovery from
3929 * controller failure. It is up to the caller to ensure the namespace list is
3930 * not modified by scan work while this function is executing.
3932 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3934 struct nvme_ns *ns, *next;
3938 * make sure to requeue I/O to all namespaces as these
3939 * might result from the scan itself and must complete
3940 * for the scan_work to make progress
3942 nvme_mpath_clear_ctrl_paths(ctrl);
3944 /* prevent racing with ns scanning */
3945 flush_work(&ctrl->scan_work);
3948 * The dead states indicates the controller was not gracefully
3949 * disconnected. In that case, we won't be able to flush any data while
3950 * removing the namespaces' disks; fail all the queues now to avoid
3951 * potentially having to clean up the failed sync later.
3953 if (ctrl->state == NVME_CTRL_DEAD)
3954 nvme_kill_queues(ctrl);
3956 down_write(&ctrl->namespaces_rwsem);
3957 list_splice_init(&ctrl->namespaces, &ns_list);
3958 up_write(&ctrl->namespaces_rwsem);
3960 list_for_each_entry_safe(ns, next, &ns_list, list)
3963 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
3965 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
3967 struct nvme_ctrl *ctrl =
3968 container_of(dev, struct nvme_ctrl, ctrl_device);
3969 struct nvmf_ctrl_options *opts = ctrl->opts;
3972 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
3977 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
3981 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
3982 opts->trsvcid ?: "none");
3986 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
3987 opts->host_traddr ?: "none");
3992 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
3994 char *envp[2] = { NULL, NULL };
3995 u32 aen_result = ctrl->aen_result;
3997 ctrl->aen_result = 0;
4001 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4004 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4008 static void nvme_async_event_work(struct work_struct *work)
4010 struct nvme_ctrl *ctrl =
4011 container_of(work, struct nvme_ctrl, async_event_work);
4013 nvme_aen_uevent(ctrl);
4014 ctrl->ops->submit_async_event(ctrl);
4017 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4022 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4028 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4031 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4033 struct nvme_fw_slot_info_log *log;
4035 log = kmalloc(sizeof(*log), GFP_KERNEL);
4039 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, log,
4041 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4045 static void nvme_fw_act_work(struct work_struct *work)
4047 struct nvme_ctrl *ctrl = container_of(work,
4048 struct nvme_ctrl, fw_act_work);
4049 unsigned long fw_act_timeout;
4052 fw_act_timeout = jiffies +
4053 msecs_to_jiffies(ctrl->mtfa * 100);
4055 fw_act_timeout = jiffies +
4056 msecs_to_jiffies(admin_timeout * 1000);
4058 nvme_stop_queues(ctrl);
4059 while (nvme_ctrl_pp_status(ctrl)) {
4060 if (time_after(jiffies, fw_act_timeout)) {
4061 dev_warn(ctrl->device,
4062 "Fw activation timeout, reset controller\n");
4063 nvme_try_sched_reset(ctrl);
4069 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4072 nvme_start_queues(ctrl);
4073 /* read FW slot information to clear the AER */
4074 nvme_get_fw_slot_info(ctrl);
4077 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4079 u32 aer_notice_type = (result & 0xff00) >> 8;
4081 trace_nvme_async_event(ctrl, aer_notice_type);
4083 switch (aer_notice_type) {
4084 case NVME_AER_NOTICE_NS_CHANGED:
4085 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4086 nvme_queue_scan(ctrl);
4088 case NVME_AER_NOTICE_FW_ACT_STARTING:
4090 * We are (ab)using the RESETTING state to prevent subsequent
4091 * recovery actions from interfering with the controller's
4092 * firmware activation.
4094 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4095 queue_work(nvme_wq, &ctrl->fw_act_work);
4097 #ifdef CONFIG_NVME_MULTIPATH
4098 case NVME_AER_NOTICE_ANA:
4099 if (!ctrl->ana_log_buf)
4101 queue_work(nvme_wq, &ctrl->ana_work);
4104 case NVME_AER_NOTICE_DISC_CHANGED:
4105 ctrl->aen_result = result;
4108 dev_warn(ctrl->device, "async event result %08x\n", result);
4112 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4113 volatile union nvme_result *res)
4115 u32 result = le32_to_cpu(res->u32);
4116 u32 aer_type = result & 0x07;
4118 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4122 case NVME_AER_NOTICE:
4123 nvme_handle_aen_notice(ctrl, result);
4125 case NVME_AER_ERROR:
4126 case NVME_AER_SMART:
4129 trace_nvme_async_event(ctrl, aer_type);
4130 ctrl->aen_result = result;
4135 queue_work(nvme_wq, &ctrl->async_event_work);
4137 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4139 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4141 nvme_mpath_stop(ctrl);
4142 nvme_stop_keep_alive(ctrl);
4143 flush_work(&ctrl->async_event_work);
4144 cancel_work_sync(&ctrl->fw_act_work);
4146 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4148 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4151 nvme_start_keep_alive(ctrl);
4153 nvme_enable_aen(ctrl);
4155 if (ctrl->queue_count > 1) {
4156 nvme_queue_scan(ctrl);
4157 nvme_start_queues(ctrl);
4159 ctrl->created = true;
4161 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4163 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4165 nvme_fault_inject_fini(&ctrl->fault_inject);
4166 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4167 cdev_device_del(&ctrl->cdev, ctrl->device);
4168 nvme_put_ctrl(ctrl);
4170 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4172 static void nvme_free_ctrl(struct device *dev)
4174 struct nvme_ctrl *ctrl =
4175 container_of(dev, struct nvme_ctrl, ctrl_device);
4176 struct nvme_subsystem *subsys = ctrl->subsys;
4178 if (subsys && ctrl->instance != subsys->instance)
4179 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4181 kfree(ctrl->effects);
4182 nvme_mpath_uninit(ctrl);
4183 __free_page(ctrl->discard_page);
4186 mutex_lock(&nvme_subsystems_lock);
4187 list_del(&ctrl->subsys_entry);
4188 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4189 mutex_unlock(&nvme_subsystems_lock);
4192 ctrl->ops->free_ctrl(ctrl);
4195 nvme_put_subsystem(subsys);
4199 * Initialize a NVMe controller structures. This needs to be called during
4200 * earliest initialization so that we have the initialized structured around
4203 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4204 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4208 ctrl->state = NVME_CTRL_NEW;
4209 spin_lock_init(&ctrl->lock);
4210 mutex_init(&ctrl->scan_lock);
4211 INIT_LIST_HEAD(&ctrl->namespaces);
4212 init_rwsem(&ctrl->namespaces_rwsem);
4215 ctrl->quirks = quirks;
4216 ctrl->numa_node = NUMA_NO_NODE;
4217 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4218 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4219 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4220 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4221 init_waitqueue_head(&ctrl->state_wq);
4223 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4224 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4225 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4227 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4229 ctrl->discard_page = alloc_page(GFP_KERNEL);
4230 if (!ctrl->discard_page) {
4235 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4238 ctrl->instance = ret;
4240 device_initialize(&ctrl->ctrl_device);
4241 ctrl->device = &ctrl->ctrl_device;
4242 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
4243 ctrl->device->class = nvme_class;
4244 ctrl->device->parent = ctrl->dev;
4245 ctrl->device->groups = nvme_dev_attr_groups;
4246 ctrl->device->release = nvme_free_ctrl;
4247 dev_set_drvdata(ctrl->device, ctrl);
4248 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4250 goto out_release_instance;
4252 nvme_get_ctrl(ctrl);
4253 cdev_init(&ctrl->cdev, &nvme_dev_fops);
4254 ctrl->cdev.owner = ops->module;
4255 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4260 * Initialize latency tolerance controls. The sysfs files won't
4261 * be visible to userspace unless the device actually supports APST.
4263 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4264 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4265 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4267 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4271 nvme_put_ctrl(ctrl);
4272 kfree_const(ctrl->device->kobj.name);
4273 out_release_instance:
4274 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4276 if (ctrl->discard_page)
4277 __free_page(ctrl->discard_page);
4280 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4283 * nvme_kill_queues(): Ends all namespace queues
4284 * @ctrl: the dead controller that needs to end
4286 * Call this function when the driver determines it is unable to get the
4287 * controller in a state capable of servicing IO.
4289 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4293 down_read(&ctrl->namespaces_rwsem);
4295 /* Forcibly unquiesce queues to avoid blocking dispatch */
4296 if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4297 blk_mq_unquiesce_queue(ctrl->admin_q);
4299 list_for_each_entry(ns, &ctrl->namespaces, list)
4300 nvme_set_queue_dying(ns);
4302 up_read(&ctrl->namespaces_rwsem);
4304 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4306 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4310 down_read(&ctrl->namespaces_rwsem);
4311 list_for_each_entry(ns, &ctrl->namespaces, list)
4312 blk_mq_unfreeze_queue(ns->queue);
4313 up_read(&ctrl->namespaces_rwsem);
4315 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4317 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4321 down_read(&ctrl->namespaces_rwsem);
4322 list_for_each_entry(ns, &ctrl->namespaces, list) {
4323 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4327 up_read(&ctrl->namespaces_rwsem);
4329 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4331 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4335 down_read(&ctrl->namespaces_rwsem);
4336 list_for_each_entry(ns, &ctrl->namespaces, list)
4337 blk_mq_freeze_queue_wait(ns->queue);
4338 up_read(&ctrl->namespaces_rwsem);
4340 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4342 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4346 down_read(&ctrl->namespaces_rwsem);
4347 list_for_each_entry(ns, &ctrl->namespaces, list)
4348 blk_freeze_queue_start(ns->queue);
4349 up_read(&ctrl->namespaces_rwsem);
4351 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4353 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4357 down_read(&ctrl->namespaces_rwsem);
4358 list_for_each_entry(ns, &ctrl->namespaces, list)
4359 blk_mq_quiesce_queue(ns->queue);
4360 up_read(&ctrl->namespaces_rwsem);
4362 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4364 void nvme_start_queues(struct nvme_ctrl *ctrl)
4368 down_read(&ctrl->namespaces_rwsem);
4369 list_for_each_entry(ns, &ctrl->namespaces, list)
4370 blk_mq_unquiesce_queue(ns->queue);
4371 up_read(&ctrl->namespaces_rwsem);
4373 EXPORT_SYMBOL_GPL(nvme_start_queues);
4376 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4380 down_read(&ctrl->namespaces_rwsem);
4381 list_for_each_entry(ns, &ctrl->namespaces, list)
4382 blk_sync_queue(ns->queue);
4383 up_read(&ctrl->namespaces_rwsem);
4386 blk_sync_queue(ctrl->admin_q);
4388 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4391 * Check we didn't inadvertently grow the command structure sizes:
4393 static inline void _nvme_check_size(void)
4395 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4396 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4397 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4398 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4399 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4400 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4401 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4402 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4403 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4404 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4405 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4406 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4407 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4408 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4409 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4410 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4411 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4415 static int __init nvme_core_init(void)
4417 int result = -ENOMEM;
4421 nvme_wq = alloc_workqueue("nvme-wq",
4422 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4426 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4427 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4431 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4432 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4433 if (!nvme_delete_wq)
4434 goto destroy_reset_wq;
4436 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
4438 goto destroy_delete_wq;
4440 nvme_class = class_create(THIS_MODULE, "nvme");
4441 if (IS_ERR(nvme_class)) {
4442 result = PTR_ERR(nvme_class);
4443 goto unregister_chrdev;
4445 nvme_class->dev_uevent = nvme_class_uevent;
4447 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4448 if (IS_ERR(nvme_subsys_class)) {
4449 result = PTR_ERR(nvme_subsys_class);
4455 class_destroy(nvme_class);
4457 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4459 destroy_workqueue(nvme_delete_wq);
4461 destroy_workqueue(nvme_reset_wq);
4463 destroy_workqueue(nvme_wq);
4468 static void __exit nvme_core_exit(void)
4470 class_destroy(nvme_subsys_class);
4471 class_destroy(nvme_class);
4472 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4473 destroy_workqueue(nvme_delete_wq);
4474 destroy_workqueue(nvme_reset_wq);
4475 destroy_workqueue(nvme_wq);
4476 ida_destroy(&nvme_instance_ida);
4479 MODULE_LICENSE("GPL");
4480 MODULE_VERSION("1.0");
4481 module_init(nvme_core_init);
4482 module_exit(nvme_core_exit);