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 (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 void nvme_retry_req(struct request *req)
246 struct nvme_ns *ns = req->q->queuedata;
247 unsigned long delay = 0;
250 /* The mask and shift result must be <= 3 */
251 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
253 delay = ns->ctrl->crdt[crd - 1] * 100;
255 nvme_req(req)->retries++;
256 blk_mq_requeue_request(req, false);
257 blk_mq_delay_kick_requeue_list(req->q, delay);
260 enum nvme_disposition {
266 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
268 if (likely(nvme_req(req)->status == 0))
271 if (blk_noretry_request(req) ||
272 (nvme_req(req)->status & NVME_SC_DNR) ||
273 nvme_req(req)->retries >= nvme_max_retries)
276 if (req->cmd_flags & REQ_NVME_MPATH) {
277 if (nvme_is_path_error(nvme_req(req)->status) ||
278 blk_queue_dying(req->q))
281 if (blk_queue_dying(req->q))
288 static inline void nvme_end_req(struct request *req)
290 blk_status_t status = nvme_error_status(nvme_req(req)->status);
292 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
293 req_op(req) == REQ_OP_ZONE_APPEND)
294 req->__sector = nvme_lba_to_sect(req->q->queuedata,
295 le64_to_cpu(nvme_req(req)->result.u64));
297 nvme_trace_bio_complete(req, status);
298 blk_mq_end_request(req, status);
301 void nvme_complete_rq(struct request *req)
303 trace_nvme_complete_rq(req);
304 nvme_cleanup_cmd(req);
306 if (nvme_req(req)->ctrl->kas)
307 nvme_req(req)->ctrl->comp_seen = true;
309 switch (nvme_decide_disposition(req)) {
317 nvme_failover_req(req);
321 EXPORT_SYMBOL_GPL(nvme_complete_rq);
323 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
325 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
326 "Cancelling I/O %d", req->tag);
328 /* don't abort one completed request */
329 if (blk_mq_request_completed(req))
332 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
333 blk_mq_complete_request(req);
336 EXPORT_SYMBOL_GPL(nvme_cancel_request);
338 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
339 enum nvme_ctrl_state new_state)
341 enum nvme_ctrl_state old_state;
343 bool changed = false;
345 spin_lock_irqsave(&ctrl->lock, flags);
347 old_state = ctrl->state;
352 case NVME_CTRL_RESETTING:
353 case NVME_CTRL_CONNECTING:
360 case NVME_CTRL_RESETTING:
370 case NVME_CTRL_CONNECTING:
373 case NVME_CTRL_RESETTING:
380 case NVME_CTRL_DELETING:
383 case NVME_CTRL_RESETTING:
384 case NVME_CTRL_CONNECTING:
391 case NVME_CTRL_DELETING_NOIO:
393 case NVME_CTRL_DELETING:
403 case NVME_CTRL_DELETING:
415 ctrl->state = new_state;
416 wake_up_all(&ctrl->state_wq);
419 spin_unlock_irqrestore(&ctrl->lock, flags);
420 if (changed && ctrl->state == NVME_CTRL_LIVE)
421 nvme_kick_requeue_lists(ctrl);
424 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
427 * Returns true for sink states that can't ever transition back to live.
429 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
431 switch (ctrl->state) {
434 case NVME_CTRL_RESETTING:
435 case NVME_CTRL_CONNECTING:
437 case NVME_CTRL_DELETING:
438 case NVME_CTRL_DELETING_NOIO:
442 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
448 * Waits for the controller state to be resetting, or returns false if it is
449 * not possible to ever transition to that state.
451 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
453 wait_event(ctrl->state_wq,
454 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
455 nvme_state_terminal(ctrl));
456 return ctrl->state == NVME_CTRL_RESETTING;
458 EXPORT_SYMBOL_GPL(nvme_wait_reset);
460 static void nvme_free_ns_head(struct kref *ref)
462 struct nvme_ns_head *head =
463 container_of(ref, struct nvme_ns_head, ref);
465 nvme_mpath_remove_disk(head);
466 ida_simple_remove(&head->subsys->ns_ida, head->instance);
467 cleanup_srcu_struct(&head->srcu);
468 nvme_put_subsystem(head->subsys);
472 static void nvme_put_ns_head(struct nvme_ns_head *head)
474 kref_put(&head->ref, nvme_free_ns_head);
477 static void nvme_free_ns(struct kref *kref)
479 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
482 nvme_nvm_unregister(ns);
485 nvme_put_ns_head(ns->head);
486 nvme_put_ctrl(ns->ctrl);
490 void nvme_put_ns(struct nvme_ns *ns)
492 kref_put(&ns->kref, nvme_free_ns);
494 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
496 static inline void nvme_clear_nvme_request(struct request *req)
498 if (!(req->rq_flags & RQF_DONTPREP)) {
499 nvme_req(req)->retries = 0;
500 nvme_req(req)->flags = 0;
501 req->rq_flags |= RQF_DONTPREP;
505 struct request *nvme_alloc_request(struct request_queue *q,
506 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
508 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
511 if (qid == NVME_QID_ANY) {
512 req = blk_mq_alloc_request(q, op, flags);
514 req = blk_mq_alloc_request_hctx(q, op, flags,
520 req->cmd_flags |= REQ_FAILFAST_DRIVER;
521 nvme_clear_nvme_request(req);
522 nvme_req(req)->cmd = cmd;
526 EXPORT_SYMBOL_GPL(nvme_alloc_request);
528 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
530 struct nvme_command c;
532 memset(&c, 0, sizeof(c));
534 c.directive.opcode = nvme_admin_directive_send;
535 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
536 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
537 c.directive.dtype = NVME_DIR_IDENTIFY;
538 c.directive.tdtype = NVME_DIR_STREAMS;
539 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
541 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
544 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
546 return nvme_toggle_streams(ctrl, false);
549 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
551 return nvme_toggle_streams(ctrl, true);
554 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
555 struct streams_directive_params *s, u32 nsid)
557 struct nvme_command c;
559 memset(&c, 0, sizeof(c));
560 memset(s, 0, sizeof(*s));
562 c.directive.opcode = nvme_admin_directive_recv;
563 c.directive.nsid = cpu_to_le32(nsid);
564 c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
565 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
566 c.directive.dtype = NVME_DIR_STREAMS;
568 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
571 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
573 struct streams_directive_params s;
576 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
581 ret = nvme_enable_streams(ctrl);
585 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
587 goto out_disable_stream;
589 ctrl->nssa = le16_to_cpu(s.nssa);
590 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
591 dev_info(ctrl->device, "too few streams (%u) available\n",
593 goto out_disable_stream;
596 ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
597 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
601 nvme_disable_streams(ctrl);
606 * Check if 'req' has a write hint associated with it. If it does, assign
607 * a valid namespace stream to the write.
609 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
610 struct request *req, u16 *control,
613 enum rw_hint streamid = req->write_hint;
615 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
619 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
622 *control |= NVME_RW_DTYPE_STREAMS;
623 *dsmgmt |= streamid << 16;
626 if (streamid < ARRAY_SIZE(req->q->write_hints))
627 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
630 static void nvme_setup_passthrough(struct request *req,
631 struct nvme_command *cmd)
633 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
634 /* passthru commands should let the driver set the SGL flags */
635 cmd->common.flags &= ~NVME_CMD_SGL_ALL;
638 static inline void nvme_setup_flush(struct nvme_ns *ns,
639 struct nvme_command *cmnd)
641 cmnd->common.opcode = nvme_cmd_flush;
642 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
645 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
646 struct nvme_command *cmnd)
648 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
649 struct nvme_dsm_range *range;
653 * Some devices do not consider the DSM 'Number of Ranges' field when
654 * determining how much data to DMA. Always allocate memory for maximum
655 * number of segments to prevent device reading beyond end of buffer.
657 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
659 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
662 * If we fail allocation our range, fallback to the controller
663 * discard page. If that's also busy, it's safe to return
664 * busy, as we know we can make progress once that's freed.
666 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
667 return BLK_STS_RESOURCE;
669 range = page_address(ns->ctrl->discard_page);
672 __rq_for_each_bio(bio, req) {
673 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
674 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
677 range[n].cattr = cpu_to_le32(0);
678 range[n].nlb = cpu_to_le32(nlb);
679 range[n].slba = cpu_to_le64(slba);
684 if (WARN_ON_ONCE(n != segments)) {
685 if (virt_to_page(range) == ns->ctrl->discard_page)
686 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
689 return BLK_STS_IOERR;
692 cmnd->dsm.opcode = nvme_cmd_dsm;
693 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
694 cmnd->dsm.nr = cpu_to_le32(segments - 1);
695 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
697 req->special_vec.bv_page = virt_to_page(range);
698 req->special_vec.bv_offset = offset_in_page(range);
699 req->special_vec.bv_len = alloc_size;
700 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
705 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
706 struct request *req, struct nvme_command *cmnd)
708 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
709 return nvme_setup_discard(ns, req, cmnd);
711 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
712 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
713 cmnd->write_zeroes.slba =
714 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
715 cmnd->write_zeroes.length =
716 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
717 cmnd->write_zeroes.control = 0;
721 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
722 struct request *req, struct nvme_command *cmnd,
725 struct nvme_ctrl *ctrl = ns->ctrl;
729 if (req->cmd_flags & REQ_FUA)
730 control |= NVME_RW_FUA;
731 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
732 control |= NVME_RW_LR;
734 if (req->cmd_flags & REQ_RAHEAD)
735 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
737 cmnd->rw.opcode = op;
738 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
739 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
740 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
742 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
743 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
747 * If formated with metadata, the block layer always provides a
748 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
749 * we enable the PRACT bit for protection information or set the
750 * namespace capacity to zero to prevent any I/O.
752 if (!blk_integrity_rq(req)) {
753 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
754 return BLK_STS_NOTSUPP;
755 control |= NVME_RW_PRINFO_PRACT;
758 switch (ns->pi_type) {
759 case NVME_NS_DPS_PI_TYPE3:
760 control |= NVME_RW_PRINFO_PRCHK_GUARD;
762 case NVME_NS_DPS_PI_TYPE1:
763 case NVME_NS_DPS_PI_TYPE2:
764 control |= NVME_RW_PRINFO_PRCHK_GUARD |
765 NVME_RW_PRINFO_PRCHK_REF;
766 if (op == nvme_cmd_zone_append)
767 control |= NVME_RW_APPEND_PIREMAP;
768 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
773 cmnd->rw.control = cpu_to_le16(control);
774 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
778 void nvme_cleanup_cmd(struct request *req)
780 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
781 struct nvme_ns *ns = req->rq_disk->private_data;
782 struct page *page = req->special_vec.bv_page;
784 if (page == ns->ctrl->discard_page)
785 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
787 kfree(page_address(page) + req->special_vec.bv_offset);
790 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
792 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
793 struct nvme_command *cmd)
795 blk_status_t ret = BLK_STS_OK;
797 nvme_clear_nvme_request(req);
799 memset(cmd, 0, sizeof(*cmd));
800 switch (req_op(req)) {
803 nvme_setup_passthrough(req, cmd);
806 nvme_setup_flush(ns, cmd);
808 case REQ_OP_ZONE_RESET_ALL:
809 case REQ_OP_ZONE_RESET:
810 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
812 case REQ_OP_ZONE_OPEN:
813 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
815 case REQ_OP_ZONE_CLOSE:
816 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
818 case REQ_OP_ZONE_FINISH:
819 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
821 case REQ_OP_WRITE_ZEROES:
822 ret = nvme_setup_write_zeroes(ns, req, cmd);
825 ret = nvme_setup_discard(ns, req, cmd);
828 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
831 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
833 case REQ_OP_ZONE_APPEND:
834 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
838 return BLK_STS_IOERR;
841 cmd->common.command_id = req->tag;
842 trace_nvme_setup_cmd(req, cmd);
845 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
847 static void nvme_end_sync_rq(struct request *rq, blk_status_t error)
849 struct completion *waiting = rq->end_io_data;
851 rq->end_io_data = NULL;
855 static void nvme_execute_rq_polled(struct request_queue *q,
856 struct gendisk *bd_disk, struct request *rq, int at_head)
858 DECLARE_COMPLETION_ONSTACK(wait);
860 WARN_ON_ONCE(!test_bit(QUEUE_FLAG_POLL, &q->queue_flags));
862 rq->cmd_flags |= REQ_HIPRI;
863 rq->end_io_data = &wait;
864 blk_execute_rq_nowait(q, bd_disk, rq, at_head, nvme_end_sync_rq);
866 while (!completion_done(&wait)) {
867 blk_poll(q, request_to_qc_t(rq->mq_hctx, rq), true);
873 * Returns 0 on success. If the result is negative, it's a Linux error code;
874 * if the result is positive, it's an NVM Express status code
876 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
877 union nvme_result *result, void *buffer, unsigned bufflen,
878 unsigned timeout, int qid, int at_head,
879 blk_mq_req_flags_t flags, bool poll)
884 req = nvme_alloc_request(q, cmd, flags, qid);
888 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
890 if (buffer && bufflen) {
891 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
897 nvme_execute_rq_polled(req->q, NULL, req, at_head);
899 blk_execute_rq(req->q, NULL, req, at_head);
901 *result = nvme_req(req)->result;
902 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
905 ret = nvme_req(req)->status;
907 blk_mq_free_request(req);
910 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
912 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
913 void *buffer, unsigned bufflen)
915 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
916 NVME_QID_ANY, 0, 0, false);
918 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
920 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
921 unsigned len, u32 seed, bool write)
923 struct bio_integrity_payload *bip;
927 buf = kmalloc(len, GFP_KERNEL);
932 if (write && copy_from_user(buf, ubuf, len))
935 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
941 bip->bip_iter.bi_size = len;
942 bip->bip_iter.bi_sector = seed;
943 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
944 offset_in_page(buf));
954 static u32 nvme_known_admin_effects(u8 opcode)
957 case nvme_admin_format_nvm:
958 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
959 NVME_CMD_EFFECTS_CSE_MASK;
960 case nvme_admin_sanitize_nvm:
961 return NVME_CMD_EFFECTS_CSE_MASK;
968 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
973 if (ns->head->effects)
974 effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
975 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
976 dev_warn(ctrl->device,
977 "IO command:%02x has unhandled effects:%08x\n",
983 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
984 effects |= nvme_known_admin_effects(opcode);
988 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
990 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
993 u32 effects = nvme_command_effects(ctrl, ns, opcode);
996 * For simplicity, IO to all namespaces is quiesced even if the command
997 * effects say only one namespace is affected.
999 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1000 mutex_lock(&ctrl->scan_lock);
1001 mutex_lock(&ctrl->subsys->lock);
1002 nvme_mpath_start_freeze(ctrl->subsys);
1003 nvme_mpath_wait_freeze(ctrl->subsys);
1004 nvme_start_freeze(ctrl);
1005 nvme_wait_freeze(ctrl);
1010 static void nvme_update_formats(struct nvme_ctrl *ctrl, u32 *effects)
1014 down_read(&ctrl->namespaces_rwsem);
1015 list_for_each_entry(ns, &ctrl->namespaces, list)
1016 if (_nvme_revalidate_disk(ns->disk))
1017 nvme_set_queue_dying(ns);
1018 else if (blk_queue_is_zoned(ns->disk->queue)) {
1020 * IO commands are required to fully revalidate a zoned
1021 * device. Force the command effects to trigger rescan
1022 * work so report zones can run in a context with
1023 * unfrozen IO queues.
1025 *effects |= NVME_CMD_EFFECTS_NCC;
1027 up_read(&ctrl->namespaces_rwsem);
1030 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1033 * Revalidate LBA changes prior to unfreezing. This is necessary to
1034 * prevent memory corruption if a logical block size was changed by
1037 if (effects & NVME_CMD_EFFECTS_LBCC)
1038 nvme_update_formats(ctrl, &effects);
1039 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1040 nvme_unfreeze(ctrl);
1041 nvme_mpath_unfreeze(ctrl->subsys);
1042 mutex_unlock(&ctrl->subsys->lock);
1043 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1044 mutex_unlock(&ctrl->scan_lock);
1046 if (effects & NVME_CMD_EFFECTS_CCC)
1047 nvme_init_identify(ctrl);
1048 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1049 nvme_queue_scan(ctrl);
1050 flush_work(&ctrl->scan_work);
1054 void nvme_execute_passthru_rq(struct request *rq)
1056 struct nvme_command *cmd = nvme_req(rq)->cmd;
1057 struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl;
1058 struct nvme_ns *ns = rq->q->queuedata;
1059 struct gendisk *disk = ns ? ns->disk : NULL;
1062 effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode);
1063 blk_execute_rq(rq->q, disk, rq, 0);
1064 nvme_passthru_end(ctrl, effects);
1066 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU);
1068 static int nvme_submit_user_cmd(struct request_queue *q,
1069 struct nvme_command *cmd, void __user *ubuffer,
1070 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
1071 u32 meta_seed, u64 *result, unsigned timeout)
1073 bool write = nvme_is_write(cmd);
1074 struct nvme_ns *ns = q->queuedata;
1075 struct gendisk *disk = ns ? ns->disk : NULL;
1076 struct request *req;
1077 struct bio *bio = NULL;
1081 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
1083 return PTR_ERR(req);
1085 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
1086 nvme_req(req)->flags |= NVME_REQ_USERCMD;
1088 if (ubuffer && bufflen) {
1089 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
1094 bio->bi_disk = disk;
1095 if (disk && meta_buffer && meta_len) {
1096 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
1099 ret = PTR_ERR(meta);
1102 req->cmd_flags |= REQ_INTEGRITY;
1106 nvme_execute_passthru_rq(req);
1107 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
1110 ret = nvme_req(req)->status;
1112 *result = le64_to_cpu(nvme_req(req)->result.u64);
1113 if (meta && !ret && !write) {
1114 if (copy_to_user(meta_buffer, meta, meta_len))
1120 blk_rq_unmap_user(bio);
1122 blk_mq_free_request(req);
1126 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
1128 struct nvme_ctrl *ctrl = rq->end_io_data;
1129 unsigned long flags;
1130 bool startka = false;
1132 blk_mq_free_request(rq);
1135 dev_err(ctrl->device,
1136 "failed nvme_keep_alive_end_io error=%d\n",
1141 ctrl->comp_seen = false;
1142 spin_lock_irqsave(&ctrl->lock, flags);
1143 if (ctrl->state == NVME_CTRL_LIVE ||
1144 ctrl->state == NVME_CTRL_CONNECTING)
1146 spin_unlock_irqrestore(&ctrl->lock, flags);
1148 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1151 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
1155 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
1160 rq->timeout = ctrl->kato * HZ;
1161 rq->end_io_data = ctrl;
1163 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
1168 static void nvme_keep_alive_work(struct work_struct *work)
1170 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1171 struct nvme_ctrl, ka_work);
1172 bool comp_seen = ctrl->comp_seen;
1174 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1175 dev_dbg(ctrl->device,
1176 "reschedule traffic based keep-alive timer\n");
1177 ctrl->comp_seen = false;
1178 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1182 if (nvme_keep_alive(ctrl)) {
1183 /* allocation failure, reset the controller */
1184 dev_err(ctrl->device, "keep-alive failed\n");
1185 nvme_reset_ctrl(ctrl);
1190 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1192 if (unlikely(ctrl->kato == 0))
1195 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ);
1198 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1200 if (unlikely(ctrl->kato == 0))
1203 cancel_delayed_work_sync(&ctrl->ka_work);
1205 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1208 * In NVMe 1.0 the CNS field was just a binary controller or namespace
1209 * flag, thus sending any new CNS opcodes has a big chance of not working.
1210 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1211 * (but not for any later version).
1213 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1215 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1216 return ctrl->vs < NVME_VS(1, 2, 0);
1217 return ctrl->vs < NVME_VS(1, 1, 0);
1220 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1222 struct nvme_command c = { };
1225 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1226 c.identify.opcode = nvme_admin_identify;
1227 c.identify.cns = NVME_ID_CNS_CTRL;
1229 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1233 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1234 sizeof(struct nvme_id_ctrl));
1240 static bool nvme_multi_css(struct nvme_ctrl *ctrl)
1242 return (ctrl->ctrl_config & NVME_CC_CSS_MASK) == NVME_CC_CSS_CSI;
1245 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1246 struct nvme_ns_id_desc *cur, bool *csi_seen)
1248 const char *warn_str = "ctrl returned bogus length:";
1251 switch (cur->nidt) {
1252 case NVME_NIDT_EUI64:
1253 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1254 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1255 warn_str, cur->nidl);
1258 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1259 return NVME_NIDT_EUI64_LEN;
1260 case NVME_NIDT_NGUID:
1261 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1262 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1263 warn_str, cur->nidl);
1266 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1267 return NVME_NIDT_NGUID_LEN;
1268 case NVME_NIDT_UUID:
1269 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1270 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1271 warn_str, cur->nidl);
1274 uuid_copy(&ids->uuid, data + sizeof(*cur));
1275 return NVME_NIDT_UUID_LEN;
1277 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1278 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1279 warn_str, cur->nidl);
1282 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1284 return NVME_NIDT_CSI_LEN;
1286 /* Skip unknown types */
1291 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1292 struct nvme_ns_ids *ids)
1294 struct nvme_command c = { };
1295 bool csi_seen = false;
1296 int status, pos, len;
1299 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1302 c.identify.opcode = nvme_admin_identify;
1303 c.identify.nsid = cpu_to_le32(nsid);
1304 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1306 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1310 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1311 NVME_IDENTIFY_DATA_SIZE);
1313 dev_warn(ctrl->device,
1314 "Identify Descriptors failed (%d)\n", status);
1318 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1319 struct nvme_ns_id_desc *cur = data + pos;
1324 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1328 len += sizeof(*cur);
1331 if (nvme_multi_css(ctrl) && !csi_seen) {
1332 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1342 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
1344 struct nvme_command c = { };
1346 c.identify.opcode = nvme_admin_identify;
1347 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
1348 c.identify.nsid = cpu_to_le32(nsid);
1349 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
1350 NVME_IDENTIFY_DATA_SIZE);
1353 static int nvme_identify_ns(struct nvme_ctrl *ctrl,
1354 unsigned nsid, struct nvme_id_ns **id)
1356 struct nvme_command c = { };
1359 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1360 c.identify.opcode = nvme_admin_identify;
1361 c.identify.nsid = cpu_to_le32(nsid);
1362 c.identify.cns = NVME_ID_CNS_NS;
1364 *id = kmalloc(sizeof(**id), GFP_KERNEL);
1368 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1370 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1377 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1378 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1380 union nvme_result res = { 0 };
1381 struct nvme_command c;
1384 memset(&c, 0, sizeof(c));
1385 c.features.opcode = op;
1386 c.features.fid = cpu_to_le32(fid);
1387 c.features.dword11 = cpu_to_le32(dword11);
1389 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1390 buffer, buflen, 0, NVME_QID_ANY, 0, 0, false);
1391 if (ret >= 0 && result)
1392 *result = le32_to_cpu(res.u32);
1396 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1397 unsigned int dword11, void *buffer, size_t buflen,
1400 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1403 EXPORT_SYMBOL_GPL(nvme_set_features);
1405 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1406 unsigned int dword11, void *buffer, size_t buflen,
1409 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1412 EXPORT_SYMBOL_GPL(nvme_get_features);
1414 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1416 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1418 int status, nr_io_queues;
1420 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1426 * Degraded controllers might return an error when setting the queue
1427 * count. We still want to be able to bring them online and offer
1428 * access to the admin queue, as that might be only way to fix them up.
1431 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1434 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1435 *count = min(*count, nr_io_queues);
1440 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1442 #define NVME_AEN_SUPPORTED \
1443 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1444 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1446 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1448 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1451 if (!supported_aens)
1454 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1457 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1460 queue_work(nvme_wq, &ctrl->async_event_work);
1464 * Convert integer values from ioctl structures to user pointers, silently
1465 * ignoring the upper bits in the compat case to match behaviour of 32-bit
1468 static void __user *nvme_to_user_ptr(uintptr_t ptrval)
1470 if (in_compat_syscall())
1471 ptrval = (compat_uptr_t)ptrval;
1472 return (void __user *)ptrval;
1475 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1477 struct nvme_user_io io;
1478 struct nvme_command c;
1479 unsigned length, meta_len;
1480 void __user *metadata;
1482 if (copy_from_user(&io, uio, sizeof(io)))
1487 switch (io.opcode) {
1488 case nvme_cmd_write:
1490 case nvme_cmd_compare:
1496 length = (io.nblocks + 1) << ns->lba_shift;
1497 meta_len = (io.nblocks + 1) * ns->ms;
1498 metadata = nvme_to_user_ptr(io.metadata);
1500 if (ns->features & NVME_NS_EXT_LBAS) {
1503 } else if (meta_len) {
1504 if ((io.metadata & 3) || !io.metadata)
1508 memset(&c, 0, sizeof(c));
1509 c.rw.opcode = io.opcode;
1510 c.rw.flags = io.flags;
1511 c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1512 c.rw.slba = cpu_to_le64(io.slba);
1513 c.rw.length = cpu_to_le16(io.nblocks);
1514 c.rw.control = cpu_to_le16(io.control);
1515 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1516 c.rw.reftag = cpu_to_le32(io.reftag);
1517 c.rw.apptag = cpu_to_le16(io.apptag);
1518 c.rw.appmask = cpu_to_le16(io.appmask);
1520 return nvme_submit_user_cmd(ns->queue, &c,
1521 nvme_to_user_ptr(io.addr), length,
1522 metadata, meta_len, lower_32_bits(io.slba), NULL, 0);
1525 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1526 struct nvme_passthru_cmd __user *ucmd)
1528 struct nvme_passthru_cmd cmd;
1529 struct nvme_command c;
1530 unsigned timeout = 0;
1534 if (!capable(CAP_SYS_ADMIN))
1536 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1541 memset(&c, 0, sizeof(c));
1542 c.common.opcode = cmd.opcode;
1543 c.common.flags = cmd.flags;
1544 c.common.nsid = cpu_to_le32(cmd.nsid);
1545 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1546 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1547 c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1548 c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1549 c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1550 c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1551 c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1552 c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1555 timeout = msecs_to_jiffies(cmd.timeout_ms);
1557 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1558 nvme_to_user_ptr(cmd.addr), cmd.data_len,
1559 nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1560 0, &result, timeout);
1563 if (put_user(result, &ucmd->result))
1570 static int nvme_user_cmd64(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1571 struct nvme_passthru_cmd64 __user *ucmd)
1573 struct nvme_passthru_cmd64 cmd;
1574 struct nvme_command c;
1575 unsigned timeout = 0;
1578 if (!capable(CAP_SYS_ADMIN))
1580 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1585 memset(&c, 0, sizeof(c));
1586 c.common.opcode = cmd.opcode;
1587 c.common.flags = cmd.flags;
1588 c.common.nsid = cpu_to_le32(cmd.nsid);
1589 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1590 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1591 c.common.cdw10 = cpu_to_le32(cmd.cdw10);
1592 c.common.cdw11 = cpu_to_le32(cmd.cdw11);
1593 c.common.cdw12 = cpu_to_le32(cmd.cdw12);
1594 c.common.cdw13 = cpu_to_le32(cmd.cdw13);
1595 c.common.cdw14 = cpu_to_le32(cmd.cdw14);
1596 c.common.cdw15 = cpu_to_le32(cmd.cdw15);
1599 timeout = msecs_to_jiffies(cmd.timeout_ms);
1601 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1602 nvme_to_user_ptr(cmd.addr), cmd.data_len,
1603 nvme_to_user_ptr(cmd.metadata), cmd.metadata_len,
1604 0, &cmd.result, timeout);
1607 if (put_user(cmd.result, &ucmd->result))
1615 * Issue ioctl requests on the first available path. Note that unlike normal
1616 * block layer requests we will not retry failed request on another controller.
1618 struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1619 struct nvme_ns_head **head, int *srcu_idx)
1621 #ifdef CONFIG_NVME_MULTIPATH
1622 if (disk->fops == &nvme_ns_head_ops) {
1625 *head = disk->private_data;
1626 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1627 ns = nvme_find_path(*head);
1629 srcu_read_unlock(&(*head)->srcu, *srcu_idx);
1635 return disk->private_data;
1638 void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1641 srcu_read_unlock(&head->srcu, idx);
1644 static bool is_ctrl_ioctl(unsigned int cmd)
1646 if (cmd == NVME_IOCTL_ADMIN_CMD || cmd == NVME_IOCTL_ADMIN64_CMD)
1648 if (is_sed_ioctl(cmd))
1653 static int nvme_handle_ctrl_ioctl(struct nvme_ns *ns, unsigned int cmd,
1655 struct nvme_ns_head *head,
1658 struct nvme_ctrl *ctrl = ns->ctrl;
1661 nvme_get_ctrl(ns->ctrl);
1662 nvme_put_ns_from_disk(head, srcu_idx);
1665 case NVME_IOCTL_ADMIN_CMD:
1666 ret = nvme_user_cmd(ctrl, NULL, argp);
1668 case NVME_IOCTL_ADMIN64_CMD:
1669 ret = nvme_user_cmd64(ctrl, NULL, argp);
1672 ret = sed_ioctl(ctrl->opal_dev, cmd, argp);
1675 nvme_put_ctrl(ctrl);
1679 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1680 unsigned int cmd, unsigned long arg)
1682 struct nvme_ns_head *head = NULL;
1683 void __user *argp = (void __user *)arg;
1687 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1689 return -EWOULDBLOCK;
1692 * Handle ioctls that apply to the controller instead of the namespace
1693 * seperately and drop the ns SRCU reference early. This avoids a
1694 * deadlock when deleting namespaces using the passthrough interface.
1696 if (is_ctrl_ioctl(cmd))
1697 return nvme_handle_ctrl_ioctl(ns, cmd, argp, head, srcu_idx);
1701 force_successful_syscall_return();
1702 ret = ns->head->ns_id;
1704 case NVME_IOCTL_IO_CMD:
1705 ret = nvme_user_cmd(ns->ctrl, ns, argp);
1707 case NVME_IOCTL_SUBMIT_IO:
1708 ret = nvme_submit_io(ns, argp);
1710 case NVME_IOCTL_IO64_CMD:
1711 ret = nvme_user_cmd64(ns->ctrl, ns, argp);
1715 ret = nvme_nvm_ioctl(ns, cmd, arg);
1720 nvme_put_ns_from_disk(head, srcu_idx);
1724 #ifdef CONFIG_COMPAT
1725 struct nvme_user_io32 {
1738 } __attribute__((__packed__));
1740 #define NVME_IOCTL_SUBMIT_IO32 _IOW('N', 0x42, struct nvme_user_io32)
1742 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1743 unsigned int cmd, unsigned long arg)
1746 * Corresponds to the difference of NVME_IOCTL_SUBMIT_IO
1747 * between 32 bit programs and 64 bit kernel.
1748 * The cause is that the results of sizeof(struct nvme_user_io),
1749 * which is used to define NVME_IOCTL_SUBMIT_IO,
1750 * are not same between 32 bit compiler and 64 bit compiler.
1751 * NVME_IOCTL_SUBMIT_IO32 is for 64 bit kernel handling
1752 * NVME_IOCTL_SUBMIT_IO issued from 32 bit programs.
1753 * Other IOCTL numbers are same between 32 bit and 64 bit.
1754 * So there is nothing to do regarding to other IOCTL numbers.
1756 if (cmd == NVME_IOCTL_SUBMIT_IO32)
1757 return nvme_ioctl(bdev, mode, NVME_IOCTL_SUBMIT_IO, arg);
1759 return nvme_ioctl(bdev, mode, cmd, arg);
1762 #define nvme_compat_ioctl NULL
1763 #endif /* CONFIG_COMPAT */
1765 static int nvme_open(struct block_device *bdev, fmode_t mode)
1767 struct nvme_ns *ns = bdev->bd_disk->private_data;
1769 #ifdef CONFIG_NVME_MULTIPATH
1770 /* should never be called due to GENHD_FL_HIDDEN */
1771 if (WARN_ON_ONCE(ns->head->disk))
1774 if (!kref_get_unless_zero(&ns->kref))
1776 if (!try_module_get(ns->ctrl->ops->module))
1787 static void nvme_release(struct gendisk *disk, fmode_t mode)
1789 struct nvme_ns *ns = disk->private_data;
1791 module_put(ns->ctrl->ops->module);
1795 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1797 /* some standard values */
1798 geo->heads = 1 << 6;
1799 geo->sectors = 1 << 5;
1800 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1804 #ifdef CONFIG_BLK_DEV_INTEGRITY
1805 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1806 u32 max_integrity_segments)
1808 struct blk_integrity integrity;
1810 memset(&integrity, 0, sizeof(integrity));
1812 case NVME_NS_DPS_PI_TYPE3:
1813 integrity.profile = &t10_pi_type3_crc;
1814 integrity.tag_size = sizeof(u16) + sizeof(u32);
1815 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1817 case NVME_NS_DPS_PI_TYPE1:
1818 case NVME_NS_DPS_PI_TYPE2:
1819 integrity.profile = &t10_pi_type1_crc;
1820 integrity.tag_size = sizeof(u16);
1821 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1824 integrity.profile = NULL;
1827 integrity.tuple_size = ms;
1828 blk_integrity_register(disk, &integrity);
1829 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1832 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1833 u32 max_integrity_segments)
1836 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1838 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1840 struct nvme_ctrl *ctrl = ns->ctrl;
1841 struct request_queue *queue = disk->queue;
1842 u32 size = queue_logical_block_size(queue);
1844 if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1845 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1849 if (ctrl->nr_streams && ns->sws && ns->sgs)
1850 size *= ns->sws * ns->sgs;
1852 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1853 NVME_DSM_MAX_RANGES);
1855 queue->limits.discard_alignment = 0;
1856 queue->limits.discard_granularity = size;
1858 /* If discard is already enabled, don't reset queue limits */
1859 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1862 blk_queue_max_discard_sectors(queue, UINT_MAX);
1863 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1865 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1866 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1869 static void nvme_config_write_zeroes(struct gendisk *disk, struct nvme_ns *ns)
1873 if (!(ns->ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) ||
1874 (ns->ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
1877 * Even though NVMe spec explicitly states that MDTS is not
1878 * applicable to the write-zeroes:- "The restriction does not apply to
1879 * commands that do not transfer data between the host and the
1880 * controller (e.g., Write Uncorrectable ro Write Zeroes command).".
1881 * In order to be more cautious use controller's max_hw_sectors value
1882 * to configure the maximum sectors for the write-zeroes which is
1883 * configured based on the controller's MDTS field in the
1884 * nvme_init_identify() if available.
1886 if (ns->ctrl->max_hw_sectors == UINT_MAX)
1887 max_blocks = (u64)USHRT_MAX + 1;
1889 max_blocks = ns->ctrl->max_hw_sectors + 1;
1891 blk_queue_max_write_zeroes_sectors(disk->queue,
1892 nvme_lba_to_sect(ns, max_blocks));
1895 static int nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1896 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1898 memset(ids, 0, sizeof(*ids));
1900 if (ctrl->vs >= NVME_VS(1, 1, 0))
1901 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1902 if (ctrl->vs >= NVME_VS(1, 2, 0))
1903 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1904 if (ctrl->vs >= NVME_VS(1, 3, 0) || nvme_multi_css(ctrl))
1905 return nvme_identify_ns_descs(ctrl, nsid, ids);
1909 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1911 return !uuid_is_null(&ids->uuid) ||
1912 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1913 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1916 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1918 return uuid_equal(&a->uuid, &b->uuid) &&
1919 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1920 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1924 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1925 u32 *phys_bs, u32 *io_opt)
1927 struct streams_directive_params s;
1930 if (!ctrl->nr_streams)
1933 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1937 ns->sws = le32_to_cpu(s.sws);
1938 ns->sgs = le16_to_cpu(s.sgs);
1941 *phys_bs = ns->sws * (1 << ns->lba_shift);
1943 *io_opt = *phys_bs * ns->sgs;
1949 static void nvme_update_disk_info(struct gendisk *disk,
1950 struct nvme_ns *ns, struct nvme_id_ns *id)
1952 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1953 unsigned short bs = 1 << ns->lba_shift;
1954 u32 atomic_bs, phys_bs, io_opt = 0;
1956 if (ns->lba_shift > PAGE_SHIFT) {
1957 /* unsupported block size, set capacity to 0 later */
1960 blk_mq_freeze_queue(disk->queue);
1961 blk_integrity_unregister(disk);
1963 atomic_bs = phys_bs = bs;
1964 nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1965 if (id->nabo == 0) {
1967 * Bit 1 indicates whether NAWUPF is defined for this namespace
1968 * and whether it should be used instead of AWUPF. If NAWUPF ==
1969 * 0 then AWUPF must be used instead.
1971 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1972 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1974 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1977 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1978 /* NPWG = Namespace Preferred Write Granularity */
1979 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1980 /* NOWS = Namespace Optimal Write Size */
1981 io_opt = bs * (1 + le16_to_cpu(id->nows));
1984 blk_queue_logical_block_size(disk->queue, bs);
1986 * Linux filesystems assume writing a single physical block is
1987 * an atomic operation. Hence limit the physical block size to the
1988 * value of the Atomic Write Unit Power Fail parameter.
1990 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1991 blk_queue_io_min(disk->queue, phys_bs);
1992 blk_queue_io_opt(disk->queue, io_opt);
1995 * The block layer can't support LBA sizes larger than the page size
1996 * yet, so catch this early and don't allow block I/O.
1998 if (ns->lba_shift > PAGE_SHIFT)
2002 * Register a metadata profile for PI, or the plain non-integrity NVMe
2003 * metadata masquerading as Type 0 if supported, otherwise reject block
2004 * I/O to namespaces with metadata except when the namespace supports
2005 * PI, as it can strip/insert in that case.
2008 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
2009 (ns->features & NVME_NS_METADATA_SUPPORTED))
2010 nvme_init_integrity(disk, ns->ms, ns->pi_type,
2011 ns->ctrl->max_integrity_segments);
2012 else if (!nvme_ns_has_pi(ns))
2016 set_capacity_revalidate_and_notify(disk, capacity, false);
2018 nvme_config_discard(disk, ns);
2019 nvme_config_write_zeroes(disk, ns);
2021 if (id->nsattr & NVME_NS_ATTR_RO)
2022 set_disk_ro(disk, true);
2024 set_disk_ro(disk, false);
2026 blk_mq_unfreeze_queue(disk->queue);
2029 static inline bool nvme_first_scan(struct gendisk *disk)
2031 /* nvme_alloc_ns() scans the disk prior to adding it */
2032 return !(disk->flags & GENHD_FL_UP);
2035 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id)
2037 struct nvme_ctrl *ctrl = ns->ctrl;
2040 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
2041 is_power_of_2(ctrl->max_hw_sectors))
2042 iob = ctrl->max_hw_sectors;
2044 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
2049 if (!is_power_of_2(iob)) {
2050 if (nvme_first_scan(ns->disk))
2051 pr_warn("%s: ignoring unaligned IO boundary:%u\n",
2052 ns->disk->disk_name, iob);
2056 if (blk_queue_is_zoned(ns->disk->queue)) {
2057 if (nvme_first_scan(ns->disk))
2058 pr_warn("%s: ignoring zoned namespace IO boundary\n",
2059 ns->disk->disk_name);
2063 blk_queue_chunk_sectors(ns->queue, iob);
2066 static int __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
2068 unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
2069 struct nvme_ns *ns = disk->private_data;
2070 struct nvme_ctrl *ctrl = ns->ctrl;
2074 * If identify namespace failed, use default 512 byte block size so
2075 * block layer can use before failing read/write for 0 capacity.
2077 ns->lba_shift = id->lbaf[lbaf].ds;
2078 if (ns->lba_shift == 0)
2081 switch (ns->head->ids.csi) {
2085 ret = nvme_update_zone_info(disk, ns, lbaf);
2087 dev_warn(ctrl->device,
2088 "failed to add zoned namespace:%u ret:%d\n",
2089 ns->head->ns_id, ret);
2094 dev_warn(ctrl->device, "unknown csi:%u ns:%u\n",
2095 ns->head->ids.csi, ns->head->ns_id);
2100 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
2101 /* the PI implementation requires metadata equal t10 pi tuple size */
2102 if (ns->ms == sizeof(struct t10_pi_tuple))
2103 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
2109 * For PCIe only the separate metadata pointer is supported,
2110 * as the block layer supplies metadata in a separate bio_vec
2111 * chain. For Fabrics, only metadata as part of extended data
2112 * LBA is supported on the wire per the Fabrics specification,
2113 * but the HBA/HCA will do the remapping from the separate
2114 * metadata buffers for us.
2116 if (id->flbas & NVME_NS_FLBAS_META_EXT) {
2117 ns->features |= NVME_NS_EXT_LBAS;
2118 if ((ctrl->ops->flags & NVME_F_FABRICS) &&
2119 (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED) &&
2120 ctrl->max_integrity_segments)
2121 ns->features |= NVME_NS_METADATA_SUPPORTED;
2123 if (WARN_ON_ONCE(ctrl->ops->flags & NVME_F_FABRICS))
2125 if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
2126 ns->features |= NVME_NS_METADATA_SUPPORTED;
2130 nvme_set_chunk_sectors(ns, id);
2131 nvme_update_disk_info(disk, ns, id);
2132 #ifdef CONFIG_NVME_MULTIPATH
2133 if (ns->head->disk) {
2134 nvme_update_disk_info(ns->head->disk, ns, id);
2135 blk_stack_limits(&ns->head->disk->queue->limits,
2136 &ns->queue->limits, 0);
2137 nvme_mpath_update_disk_size(ns->head->disk);
2143 static int _nvme_revalidate_disk(struct gendisk *disk)
2145 struct nvme_ns *ns = disk->private_data;
2146 struct nvme_ctrl *ctrl = ns->ctrl;
2147 struct nvme_id_ns *id;
2148 struct nvme_ns_ids ids;
2151 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
2152 set_capacity(disk, 0);
2156 ret = nvme_identify_ns(ctrl, ns->head->ns_id, &id);
2160 if (id->ncap == 0) {
2165 ret = nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
2169 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
2170 dev_err(ctrl->device,
2171 "identifiers changed for nsid %d\n", ns->head->ns_id);
2176 ret = __nvme_revalidate_disk(disk, id);
2181 * Only fail the function if we got a fatal error back from the
2182 * device, otherwise ignore the error and just move on.
2184 if (ret == -ENOMEM || (ret > 0 && !(ret & NVME_SC_DNR)))
2187 ret = blk_status_to_errno(nvme_error_status(ret));
2191 static int nvme_revalidate_disk(struct gendisk *disk)
2195 ret = _nvme_revalidate_disk(disk);
2199 #ifdef CONFIG_BLK_DEV_ZONED
2200 if (blk_queue_is_zoned(disk->queue)) {
2201 struct nvme_ns *ns = disk->private_data;
2202 struct nvme_ctrl *ctrl = ns->ctrl;
2204 ret = blk_revalidate_disk_zones(disk, NULL);
2206 blk_queue_max_zone_append_sectors(disk->queue,
2207 ctrl->max_zone_append);
2213 static char nvme_pr_type(enum pr_type type)
2216 case PR_WRITE_EXCLUSIVE:
2218 case PR_EXCLUSIVE_ACCESS:
2220 case PR_WRITE_EXCLUSIVE_REG_ONLY:
2222 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
2224 case PR_WRITE_EXCLUSIVE_ALL_REGS:
2226 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
2233 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
2234 u64 key, u64 sa_key, u8 op)
2236 struct nvme_ns_head *head = NULL;
2238 struct nvme_command c;
2240 u8 data[16] = { 0, };
2242 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
2244 return -EWOULDBLOCK;
2246 put_unaligned_le64(key, &data[0]);
2247 put_unaligned_le64(sa_key, &data[8]);
2249 memset(&c, 0, sizeof(c));
2250 c.common.opcode = op;
2251 c.common.nsid = cpu_to_le32(ns->head->ns_id);
2252 c.common.cdw10 = cpu_to_le32(cdw10);
2254 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
2255 nvme_put_ns_from_disk(head, srcu_idx);
2259 static int nvme_pr_register(struct block_device *bdev, u64 old,
2260 u64 new, unsigned flags)
2264 if (flags & ~PR_FL_IGNORE_KEY)
2267 cdw10 = old ? 2 : 0;
2268 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2269 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2270 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2273 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2274 enum pr_type type, unsigned flags)
2278 if (flags & ~PR_FL_IGNORE_KEY)
2281 cdw10 = nvme_pr_type(type) << 8;
2282 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2283 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2286 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2287 enum pr_type type, bool abort)
2289 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
2290 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2293 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2295 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2296 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2299 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2301 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
2302 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2305 static const struct pr_ops nvme_pr_ops = {
2306 .pr_register = nvme_pr_register,
2307 .pr_reserve = nvme_pr_reserve,
2308 .pr_release = nvme_pr_release,
2309 .pr_preempt = nvme_pr_preempt,
2310 .pr_clear = nvme_pr_clear,
2313 #ifdef CONFIG_BLK_SED_OPAL
2314 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2317 struct nvme_ctrl *ctrl = data;
2318 struct nvme_command cmd;
2320 memset(&cmd, 0, sizeof(cmd));
2322 cmd.common.opcode = nvme_admin_security_send;
2324 cmd.common.opcode = nvme_admin_security_recv;
2325 cmd.common.nsid = 0;
2326 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2327 cmd.common.cdw11 = cpu_to_le32(len);
2329 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
2330 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0, false);
2332 EXPORT_SYMBOL_GPL(nvme_sec_submit);
2333 #endif /* CONFIG_BLK_SED_OPAL */
2335 static const struct block_device_operations nvme_fops = {
2336 .owner = THIS_MODULE,
2337 .ioctl = nvme_ioctl,
2338 .compat_ioctl = nvme_compat_ioctl,
2340 .release = nvme_release,
2341 .getgeo = nvme_getgeo,
2342 .revalidate_disk= nvme_revalidate_disk,
2343 .report_zones = nvme_report_zones,
2344 .pr_ops = &nvme_pr_ops,
2347 #ifdef CONFIG_NVME_MULTIPATH
2348 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
2350 struct nvme_ns_head *head = bdev->bd_disk->private_data;
2352 if (!kref_get_unless_zero(&head->ref))
2357 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
2359 nvme_put_ns_head(disk->private_data);
2362 const struct block_device_operations nvme_ns_head_ops = {
2363 .owner = THIS_MODULE,
2364 .submit_bio = nvme_ns_head_submit_bio,
2365 .open = nvme_ns_head_open,
2366 .release = nvme_ns_head_release,
2367 .ioctl = nvme_ioctl,
2368 .compat_ioctl = nvme_compat_ioctl,
2369 .getgeo = nvme_getgeo,
2370 .report_zones = nvme_report_zones,
2371 .pr_ops = &nvme_pr_ops,
2373 #endif /* CONFIG_NVME_MULTIPATH */
2375 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2377 unsigned long timeout =
2378 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2379 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2382 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2385 if ((csts & NVME_CSTS_RDY) == bit)
2388 usleep_range(1000, 2000);
2389 if (fatal_signal_pending(current))
2391 if (time_after(jiffies, timeout)) {
2392 dev_err(ctrl->device,
2393 "Device not ready; aborting %s, CSTS=0x%x\n",
2394 enabled ? "initialisation" : "reset", csts);
2403 * If the device has been passed off to us in an enabled state, just clear
2404 * the enabled bit. The spec says we should set the 'shutdown notification
2405 * bits', but doing so may cause the device to complete commands to the
2406 * admin queue ... and we don't know what memory that might be pointing at!
2408 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2412 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2413 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2415 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2419 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2420 msleep(NVME_QUIRK_DELAY_AMOUNT);
2422 return nvme_wait_ready(ctrl, ctrl->cap, false);
2424 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2426 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2428 unsigned dev_page_min;
2431 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2433 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2436 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2438 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2439 dev_err(ctrl->device,
2440 "Minimum device page size %u too large for host (%u)\n",
2441 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2445 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2446 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2448 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2449 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2450 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2451 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2452 ctrl->ctrl_config |= NVME_CC_ENABLE;
2454 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2457 return nvme_wait_ready(ctrl, ctrl->cap, true);
2459 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2461 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2463 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2467 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2468 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2470 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2474 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2475 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2479 if (fatal_signal_pending(current))
2481 if (time_after(jiffies, timeout)) {
2482 dev_err(ctrl->device,
2483 "Device shutdown incomplete; abort shutdown\n");
2490 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2492 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
2493 struct request_queue *q)
2497 if (ctrl->max_hw_sectors) {
2499 (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
2501 max_segments = min_not_zero(max_segments, ctrl->max_segments);
2502 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
2503 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
2505 blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
2506 blk_queue_dma_alignment(q, 7);
2507 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
2509 blk_queue_write_cache(q, vwc, vwc);
2512 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2517 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2520 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2521 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2524 dev_warn_once(ctrl->device,
2525 "could not set timestamp (%d)\n", ret);
2529 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2531 struct nvme_feat_host_behavior *host;
2534 /* Don't bother enabling the feature if retry delay is not reported */
2538 host = kzalloc(sizeof(*host), GFP_KERNEL);
2542 host->acre = NVME_ENABLE_ACRE;
2543 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2544 host, sizeof(*host), NULL);
2549 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2552 * APST (Autonomous Power State Transition) lets us program a
2553 * table of power state transitions that the controller will
2554 * perform automatically. We configure it with a simple
2555 * heuristic: we are willing to spend at most 2% of the time
2556 * transitioning between power states. Therefore, when running
2557 * in any given state, we will enter the next lower-power
2558 * non-operational state after waiting 50 * (enlat + exlat)
2559 * microseconds, as long as that state's exit latency is under
2560 * the requested maximum latency.
2562 * We will not autonomously enter any non-operational state for
2563 * which the total latency exceeds ps_max_latency_us. Users
2564 * can set ps_max_latency_us to zero to turn off APST.
2568 struct nvme_feat_auto_pst *table;
2574 * If APST isn't supported or if we haven't been initialized yet,
2575 * then don't do anything.
2580 if (ctrl->npss > 31) {
2581 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2585 table = kzalloc(sizeof(*table), GFP_KERNEL);
2589 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2590 /* Turn off APST. */
2592 dev_dbg(ctrl->device, "APST disabled\n");
2594 __le64 target = cpu_to_le64(0);
2598 * Walk through all states from lowest- to highest-power.
2599 * According to the spec, lower-numbered states use more
2600 * power. NPSS, despite the name, is the index of the
2601 * lowest-power state, not the number of states.
2603 for (state = (int)ctrl->npss; state >= 0; state--) {
2604 u64 total_latency_us, exit_latency_us, transition_ms;
2607 table->entries[state] = target;
2610 * Don't allow transitions to the deepest state
2611 * if it's quirked off.
2613 if (state == ctrl->npss &&
2614 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2618 * Is this state a useful non-operational state for
2619 * higher-power states to autonomously transition to?
2621 if (!(ctrl->psd[state].flags &
2622 NVME_PS_FLAGS_NON_OP_STATE))
2626 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2627 if (exit_latency_us > ctrl->ps_max_latency_us)
2632 le32_to_cpu(ctrl->psd[state].entry_lat);
2635 * This state is good. Use it as the APST idle
2636 * target for higher power states.
2638 transition_ms = total_latency_us + 19;
2639 do_div(transition_ms, 20);
2640 if (transition_ms > (1 << 24) - 1)
2641 transition_ms = (1 << 24) - 1;
2643 target = cpu_to_le64((state << 3) |
2644 (transition_ms << 8));
2649 if (total_latency_us > max_lat_us)
2650 max_lat_us = total_latency_us;
2656 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2658 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2659 max_ps, max_lat_us, (int)sizeof(*table), table);
2663 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2664 table, sizeof(*table), NULL);
2666 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2672 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2674 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2678 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2679 case PM_QOS_LATENCY_ANY:
2687 if (ctrl->ps_max_latency_us != latency) {
2688 ctrl->ps_max_latency_us = latency;
2689 nvme_configure_apst(ctrl);
2693 struct nvme_core_quirk_entry {
2695 * NVMe model and firmware strings are padded with spaces. For
2696 * simplicity, strings in the quirk table are padded with NULLs
2702 unsigned long quirks;
2705 static const struct nvme_core_quirk_entry core_quirks[] = {
2708 * This Toshiba device seems to die using any APST states. See:
2709 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2712 .mn = "THNSF5256GPUK TOSHIBA",
2713 .quirks = NVME_QUIRK_NO_APST,
2717 * This LiteON CL1-3D*-Q11 firmware version has a race
2718 * condition associated with actions related to suspend to idle
2719 * LiteON has resolved the problem in future firmware
2723 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2727 /* match is null-terminated but idstr is space-padded. */
2728 static bool string_matches(const char *idstr, const char *match, size_t len)
2735 matchlen = strlen(match);
2736 WARN_ON_ONCE(matchlen > len);
2738 if (memcmp(idstr, match, matchlen))
2741 for (; matchlen < len; matchlen++)
2742 if (idstr[matchlen] != ' ')
2748 static bool quirk_matches(const struct nvme_id_ctrl *id,
2749 const struct nvme_core_quirk_entry *q)
2751 return q->vid == le16_to_cpu(id->vid) &&
2752 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2753 string_matches(id->fr, q->fr, sizeof(id->fr));
2756 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2757 struct nvme_id_ctrl *id)
2762 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2763 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2764 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2765 strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2769 if (ctrl->vs >= NVME_VS(1, 2, 1))
2770 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2773 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2774 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2775 "nqn.2014.08.org.nvmexpress:%04x%04x",
2776 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2777 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2778 off += sizeof(id->sn);
2779 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2780 off += sizeof(id->mn);
2781 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2784 static void nvme_release_subsystem(struct device *dev)
2786 struct nvme_subsystem *subsys =
2787 container_of(dev, struct nvme_subsystem, dev);
2789 if (subsys->instance >= 0)
2790 ida_simple_remove(&nvme_instance_ida, subsys->instance);
2794 static void nvme_destroy_subsystem(struct kref *ref)
2796 struct nvme_subsystem *subsys =
2797 container_of(ref, struct nvme_subsystem, ref);
2799 mutex_lock(&nvme_subsystems_lock);
2800 list_del(&subsys->entry);
2801 mutex_unlock(&nvme_subsystems_lock);
2803 ida_destroy(&subsys->ns_ida);
2804 device_del(&subsys->dev);
2805 put_device(&subsys->dev);
2808 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2810 kref_put(&subsys->ref, nvme_destroy_subsystem);
2813 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2815 struct nvme_subsystem *subsys;
2817 lockdep_assert_held(&nvme_subsystems_lock);
2820 * Fail matches for discovery subsystems. This results
2821 * in each discovery controller bound to a unique subsystem.
2822 * This avoids issues with validating controller values
2823 * that can only be true when there is a single unique subsystem.
2824 * There may be multiple and completely independent entities
2825 * that provide discovery controllers.
2827 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2830 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2831 if (strcmp(subsys->subnqn, subsysnqn))
2833 if (!kref_get_unless_zero(&subsys->ref))
2841 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2842 struct device_attribute subsys_attr_##_name = \
2843 __ATTR(_name, _mode, _show, NULL)
2845 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2846 struct device_attribute *attr,
2849 struct nvme_subsystem *subsys =
2850 container_of(dev, struct nvme_subsystem, dev);
2852 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2854 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2856 #define nvme_subsys_show_str_function(field) \
2857 static ssize_t subsys_##field##_show(struct device *dev, \
2858 struct device_attribute *attr, char *buf) \
2860 struct nvme_subsystem *subsys = \
2861 container_of(dev, struct nvme_subsystem, dev); \
2862 return sprintf(buf, "%.*s\n", \
2863 (int)sizeof(subsys->field), subsys->field); \
2865 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2867 nvme_subsys_show_str_function(model);
2868 nvme_subsys_show_str_function(serial);
2869 nvme_subsys_show_str_function(firmware_rev);
2871 static struct attribute *nvme_subsys_attrs[] = {
2872 &subsys_attr_model.attr,
2873 &subsys_attr_serial.attr,
2874 &subsys_attr_firmware_rev.attr,
2875 &subsys_attr_subsysnqn.attr,
2876 #ifdef CONFIG_NVME_MULTIPATH
2877 &subsys_attr_iopolicy.attr,
2882 static struct attribute_group nvme_subsys_attrs_group = {
2883 .attrs = nvme_subsys_attrs,
2886 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2887 &nvme_subsys_attrs_group,
2891 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2892 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2894 struct nvme_ctrl *tmp;
2896 lockdep_assert_held(&nvme_subsystems_lock);
2898 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2899 if (nvme_state_terminal(tmp))
2902 if (tmp->cntlid == ctrl->cntlid) {
2903 dev_err(ctrl->device,
2904 "Duplicate cntlid %u with %s, rejecting\n",
2905 ctrl->cntlid, dev_name(tmp->device));
2909 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2910 (ctrl->opts && ctrl->opts->discovery_nqn))
2913 dev_err(ctrl->device,
2914 "Subsystem does not support multiple controllers\n");
2921 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2923 struct nvme_subsystem *subsys, *found;
2926 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2930 subsys->instance = -1;
2931 mutex_init(&subsys->lock);
2932 kref_init(&subsys->ref);
2933 INIT_LIST_HEAD(&subsys->ctrls);
2934 INIT_LIST_HEAD(&subsys->nsheads);
2935 nvme_init_subnqn(subsys, ctrl, id);
2936 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2937 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2938 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2939 subsys->vendor_id = le16_to_cpu(id->vid);
2940 subsys->cmic = id->cmic;
2941 subsys->awupf = le16_to_cpu(id->awupf);
2942 #ifdef CONFIG_NVME_MULTIPATH
2943 subsys->iopolicy = NVME_IOPOLICY_NUMA;
2946 subsys->dev.class = nvme_subsys_class;
2947 subsys->dev.release = nvme_release_subsystem;
2948 subsys->dev.groups = nvme_subsys_attrs_groups;
2949 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2950 device_initialize(&subsys->dev);
2952 mutex_lock(&nvme_subsystems_lock);
2953 found = __nvme_find_get_subsystem(subsys->subnqn);
2955 put_device(&subsys->dev);
2958 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2960 goto out_put_subsystem;
2963 ret = device_add(&subsys->dev);
2965 dev_err(ctrl->device,
2966 "failed to register subsystem device.\n");
2967 put_device(&subsys->dev);
2970 ida_init(&subsys->ns_ida);
2971 list_add_tail(&subsys->entry, &nvme_subsystems);
2974 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2975 dev_name(ctrl->device));
2977 dev_err(ctrl->device,
2978 "failed to create sysfs link from subsystem.\n");
2979 goto out_put_subsystem;
2983 subsys->instance = ctrl->instance;
2984 ctrl->subsys = subsys;
2985 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2986 mutex_unlock(&nvme_subsystems_lock);
2990 nvme_put_subsystem(subsys);
2992 mutex_unlock(&nvme_subsystems_lock);
2996 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2997 void *log, size_t size, u64 offset)
2999 struct nvme_command c = { };
3000 u32 dwlen = nvme_bytes_to_numd(size);
3002 c.get_log_page.opcode = nvme_admin_get_log_page;
3003 c.get_log_page.nsid = cpu_to_le32(nsid);
3004 c.get_log_page.lid = log_page;
3005 c.get_log_page.lsp = lsp;
3006 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
3007 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
3008 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
3009 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
3010 c.get_log_page.csi = csi;
3012 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
3015 static struct nvme_cel *nvme_find_cel(struct nvme_ctrl *ctrl, u8 csi)
3017 struct nvme_cel *cel, *ret = NULL;
3019 spin_lock_irq(&ctrl->lock);
3020 list_for_each_entry(cel, &ctrl->cels, entry) {
3021 if (cel->csi == csi) {
3026 spin_unlock_irq(&ctrl->lock);
3031 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
3032 struct nvme_effects_log **log)
3034 struct nvme_cel *cel = nvme_find_cel(ctrl, csi);
3040 cel = kzalloc(sizeof(*cel), GFP_KERNEL);
3044 ret = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CMD_EFFECTS, 0, csi,
3045 &cel->log, sizeof(cel->log), 0);
3053 spin_lock_irq(&ctrl->lock);
3054 list_add_tail(&cel->entry, &ctrl->cels);
3055 spin_unlock_irq(&ctrl->lock);
3062 * Initialize the cached copies of the Identify data and various controller
3063 * register in our nvme_ctrl structure. This should be called as soon as
3064 * the admin queue is fully up and running.
3066 int nvme_init_identify(struct nvme_ctrl *ctrl)
3068 struct nvme_id_ctrl *id;
3069 int ret, page_shift;
3071 bool prev_apst_enabled;
3073 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3075 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3078 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12;
3079 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3081 if (ctrl->vs >= NVME_VS(1, 1, 0))
3082 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3084 ret = nvme_identify_ctrl(ctrl, &id);
3086 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
3090 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
3091 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3096 if (!(ctrl->ops->flags & NVME_F_FABRICS))
3097 ctrl->cntlid = le16_to_cpu(id->cntlid);
3099 if (!ctrl->identified) {
3102 ret = nvme_init_subsystem(ctrl, id);
3107 * Check for quirks. Quirk can depend on firmware version,
3108 * so, in principle, the set of quirks present can change
3109 * across a reset. As a possible future enhancement, we
3110 * could re-scan for quirks every time we reinitialize
3111 * the device, but we'd have to make sure that the driver
3112 * behaves intelligently if the quirks change.
3114 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
3115 if (quirk_matches(id, &core_quirks[i]))
3116 ctrl->quirks |= core_quirks[i].quirks;
3120 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
3121 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
3122 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
3125 ctrl->crdt[0] = le16_to_cpu(id->crdt1);
3126 ctrl->crdt[1] = le16_to_cpu(id->crdt2);
3127 ctrl->crdt[2] = le16_to_cpu(id->crdt3);
3129 ctrl->oacs = le16_to_cpu(id->oacs);
3130 ctrl->oncs = le16_to_cpu(id->oncs);
3131 ctrl->mtfa = le16_to_cpu(id->mtfa);
3132 ctrl->oaes = le32_to_cpu(id->oaes);
3133 ctrl->wctemp = le16_to_cpu(id->wctemp);
3134 ctrl->cctemp = le16_to_cpu(id->cctemp);
3136 atomic_set(&ctrl->abort_limit, id->acl + 1);
3137 ctrl->vwc = id->vwc;
3139 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
3141 max_hw_sectors = UINT_MAX;
3142 ctrl->max_hw_sectors =
3143 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
3145 nvme_set_queue_limits(ctrl, ctrl->admin_q);
3146 ctrl->sgls = le32_to_cpu(id->sgls);
3147 ctrl->kas = le16_to_cpu(id->kas);
3148 ctrl->max_namespaces = le32_to_cpu(id->mnan);
3149 ctrl->ctratt = le32_to_cpu(id->ctratt);
3153 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
3155 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
3156 shutdown_timeout, 60);
3158 if (ctrl->shutdown_timeout != shutdown_timeout)
3159 dev_info(ctrl->device,
3160 "Shutdown timeout set to %u seconds\n",
3161 ctrl->shutdown_timeout);
3163 ctrl->shutdown_timeout = shutdown_timeout;
3165 ctrl->npss = id->npss;
3166 ctrl->apsta = id->apsta;
3167 prev_apst_enabled = ctrl->apst_enabled;
3168 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
3169 if (force_apst && id->apsta) {
3170 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
3171 ctrl->apst_enabled = true;
3173 ctrl->apst_enabled = false;
3176 ctrl->apst_enabled = id->apsta;
3178 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
3180 if (ctrl->ops->flags & NVME_F_FABRICS) {
3181 ctrl->icdoff = le16_to_cpu(id->icdoff);
3182 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
3183 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
3184 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
3187 * In fabrics we need to verify the cntlid matches the
3190 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
3191 dev_err(ctrl->device,
3192 "Mismatching cntlid: Connect %u vs Identify "
3194 ctrl->cntlid, le16_to_cpu(id->cntlid));
3199 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
3200 dev_err(ctrl->device,
3201 "keep-alive support is mandatory for fabrics\n");
3206 ctrl->hmpre = le32_to_cpu(id->hmpre);
3207 ctrl->hmmin = le32_to_cpu(id->hmmin);
3208 ctrl->hmminds = le32_to_cpu(id->hmminds);
3209 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
3212 ret = nvme_mpath_init(ctrl, id);
3218 if (ctrl->apst_enabled && !prev_apst_enabled)
3219 dev_pm_qos_expose_latency_tolerance(ctrl->device);
3220 else if (!ctrl->apst_enabled && prev_apst_enabled)
3221 dev_pm_qos_hide_latency_tolerance(ctrl->device);
3223 ret = nvme_configure_apst(ctrl);
3227 ret = nvme_configure_timestamp(ctrl);
3231 ret = nvme_configure_directives(ctrl);
3235 ret = nvme_configure_acre(ctrl);
3239 if (!ctrl->identified)
3240 nvme_hwmon_init(ctrl);
3242 ctrl->identified = true;
3250 EXPORT_SYMBOL_GPL(nvme_init_identify);
3252 static int nvme_dev_open(struct inode *inode, struct file *file)
3254 struct nvme_ctrl *ctrl =
3255 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3257 switch (ctrl->state) {
3258 case NVME_CTRL_LIVE:
3261 return -EWOULDBLOCK;
3264 file->private_data = ctrl;
3268 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
3273 down_read(&ctrl->namespaces_rwsem);
3274 if (list_empty(&ctrl->namespaces)) {
3279 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
3280 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
3281 dev_warn(ctrl->device,
3282 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
3287 dev_warn(ctrl->device,
3288 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
3289 kref_get(&ns->kref);
3290 up_read(&ctrl->namespaces_rwsem);
3292 ret = nvme_user_cmd(ctrl, ns, argp);
3297 up_read(&ctrl->namespaces_rwsem);
3301 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
3304 struct nvme_ctrl *ctrl = file->private_data;
3305 void __user *argp = (void __user *)arg;
3308 case NVME_IOCTL_ADMIN_CMD:
3309 return nvme_user_cmd(ctrl, NULL, argp);
3310 case NVME_IOCTL_ADMIN64_CMD:
3311 return nvme_user_cmd64(ctrl, NULL, argp);
3312 case NVME_IOCTL_IO_CMD:
3313 return nvme_dev_user_cmd(ctrl, argp);
3314 case NVME_IOCTL_RESET:
3315 dev_warn(ctrl->device, "resetting controller\n");
3316 return nvme_reset_ctrl_sync(ctrl);
3317 case NVME_IOCTL_SUBSYS_RESET:
3318 return nvme_reset_subsystem(ctrl);
3319 case NVME_IOCTL_RESCAN:
3320 nvme_queue_scan(ctrl);
3327 static const struct file_operations nvme_dev_fops = {
3328 .owner = THIS_MODULE,
3329 .open = nvme_dev_open,
3330 .unlocked_ioctl = nvme_dev_ioctl,
3331 .compat_ioctl = compat_ptr_ioctl,
3334 static ssize_t nvme_sysfs_reset(struct device *dev,
3335 struct device_attribute *attr, const char *buf,
3338 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3341 ret = nvme_reset_ctrl_sync(ctrl);
3346 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3348 static ssize_t nvme_sysfs_rescan(struct device *dev,
3349 struct device_attribute *attr, const char *buf,
3352 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3354 nvme_queue_scan(ctrl);
3357 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
3359 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
3361 struct gendisk *disk = dev_to_disk(dev);
3363 if (disk->fops == &nvme_fops)
3364 return nvme_get_ns_from_dev(dev)->head;
3366 return disk->private_data;
3369 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
3372 struct nvme_ns_head *head = dev_to_ns_head(dev);
3373 struct nvme_ns_ids *ids = &head->ids;
3374 struct nvme_subsystem *subsys = head->subsys;
3375 int serial_len = sizeof(subsys->serial);
3376 int model_len = sizeof(subsys->model);
3378 if (!uuid_is_null(&ids->uuid))
3379 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
3381 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3382 return sprintf(buf, "eui.%16phN\n", ids->nguid);
3384 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3385 return sprintf(buf, "eui.%8phN\n", ids->eui64);
3387 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3388 subsys->serial[serial_len - 1] == '\0'))
3390 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3391 subsys->model[model_len - 1] == '\0'))
3394 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3395 serial_len, subsys->serial, model_len, subsys->model,
3398 static DEVICE_ATTR_RO(wwid);
3400 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3403 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3405 static DEVICE_ATTR_RO(nguid);
3407 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3410 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3412 /* For backward compatibility expose the NGUID to userspace if
3413 * we have no UUID set
3415 if (uuid_is_null(&ids->uuid)) {
3416 printk_ratelimited(KERN_WARNING
3417 "No UUID available providing old NGUID\n");
3418 return sprintf(buf, "%pU\n", ids->nguid);
3420 return sprintf(buf, "%pU\n", &ids->uuid);
3422 static DEVICE_ATTR_RO(uuid);
3424 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3427 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3429 static DEVICE_ATTR_RO(eui);
3431 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3434 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3436 static DEVICE_ATTR_RO(nsid);
3438 static struct attribute *nvme_ns_id_attrs[] = {
3439 &dev_attr_wwid.attr,
3440 &dev_attr_uuid.attr,
3441 &dev_attr_nguid.attr,
3443 &dev_attr_nsid.attr,
3444 #ifdef CONFIG_NVME_MULTIPATH
3445 &dev_attr_ana_grpid.attr,
3446 &dev_attr_ana_state.attr,
3451 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3452 struct attribute *a, int n)
3454 struct device *dev = container_of(kobj, struct device, kobj);
3455 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3457 if (a == &dev_attr_uuid.attr) {
3458 if (uuid_is_null(&ids->uuid) &&
3459 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3462 if (a == &dev_attr_nguid.attr) {
3463 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3466 if (a == &dev_attr_eui.attr) {
3467 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3470 #ifdef CONFIG_NVME_MULTIPATH
3471 if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3472 if (dev_to_disk(dev)->fops != &nvme_fops) /* per-path attr */
3474 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3481 static const struct attribute_group nvme_ns_id_attr_group = {
3482 .attrs = nvme_ns_id_attrs,
3483 .is_visible = nvme_ns_id_attrs_are_visible,
3486 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3487 &nvme_ns_id_attr_group,
3489 &nvme_nvm_attr_group,
3494 #define nvme_show_str_function(field) \
3495 static ssize_t field##_show(struct device *dev, \
3496 struct device_attribute *attr, char *buf) \
3498 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3499 return sprintf(buf, "%.*s\n", \
3500 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
3502 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3504 nvme_show_str_function(model);
3505 nvme_show_str_function(serial);
3506 nvme_show_str_function(firmware_rev);
3508 #define nvme_show_int_function(field) \
3509 static ssize_t field##_show(struct device *dev, \
3510 struct device_attribute *attr, char *buf) \
3512 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3513 return sprintf(buf, "%d\n", ctrl->field); \
3515 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3517 nvme_show_int_function(cntlid);
3518 nvme_show_int_function(numa_node);
3519 nvme_show_int_function(queue_count);
3520 nvme_show_int_function(sqsize);
3522 static ssize_t nvme_sysfs_delete(struct device *dev,
3523 struct device_attribute *attr, const char *buf,
3526 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3528 if (device_remove_file_self(dev, attr))
3529 nvme_delete_ctrl_sync(ctrl);
3532 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3534 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3535 struct device_attribute *attr,
3538 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3540 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
3542 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3544 static ssize_t nvme_sysfs_show_state(struct device *dev,
3545 struct device_attribute *attr,
3548 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3549 static const char *const state_name[] = {
3550 [NVME_CTRL_NEW] = "new",
3551 [NVME_CTRL_LIVE] = "live",
3552 [NVME_CTRL_RESETTING] = "resetting",
3553 [NVME_CTRL_CONNECTING] = "connecting",
3554 [NVME_CTRL_DELETING] = "deleting",
3555 [NVME_CTRL_DELETING_NOIO]= "deleting (no IO)",
3556 [NVME_CTRL_DEAD] = "dead",
3559 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3560 state_name[ctrl->state])
3561 return sprintf(buf, "%s\n", state_name[ctrl->state]);
3563 return sprintf(buf, "unknown state\n");
3566 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3568 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3569 struct device_attribute *attr,
3572 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3574 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
3576 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3578 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3579 struct device_attribute *attr,
3582 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3584 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->opts->host->nqn);
3586 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3588 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3589 struct device_attribute *attr,
3592 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3594 return snprintf(buf, PAGE_SIZE, "%pU\n", &ctrl->opts->host->id);
3596 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3598 static ssize_t nvme_sysfs_show_address(struct device *dev,
3599 struct device_attribute *attr,
3602 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3604 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3606 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3608 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev,
3609 struct device_attribute *attr, char *buf)
3611 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3612 struct nvmf_ctrl_options *opts = ctrl->opts;
3614 if (ctrl->opts->max_reconnects == -1)
3615 return sprintf(buf, "off\n");
3616 return sprintf(buf, "%d\n",
3617 opts->max_reconnects * opts->reconnect_delay);
3620 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev,
3621 struct device_attribute *attr, const char *buf, size_t count)
3623 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3624 struct nvmf_ctrl_options *opts = ctrl->opts;
3625 int ctrl_loss_tmo, err;
3627 err = kstrtoint(buf, 10, &ctrl_loss_tmo);
3631 else if (ctrl_loss_tmo < 0)
3632 opts->max_reconnects = -1;
3634 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
3635 opts->reconnect_delay);
3638 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR,
3639 nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store);
3641 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev,
3642 struct device_attribute *attr, char *buf)
3644 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3646 if (ctrl->opts->reconnect_delay == -1)
3647 return sprintf(buf, "off\n");
3648 return sprintf(buf, "%d\n", ctrl->opts->reconnect_delay);
3651 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev,
3652 struct device_attribute *attr, const char *buf, size_t count)
3654 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3658 err = kstrtou32(buf, 10, &v);
3662 ctrl->opts->reconnect_delay = v;
3665 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR,
3666 nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store);
3668 static struct attribute *nvme_dev_attrs[] = {
3669 &dev_attr_reset_controller.attr,
3670 &dev_attr_rescan_controller.attr,
3671 &dev_attr_model.attr,
3672 &dev_attr_serial.attr,
3673 &dev_attr_firmware_rev.attr,
3674 &dev_attr_cntlid.attr,
3675 &dev_attr_delete_controller.attr,
3676 &dev_attr_transport.attr,
3677 &dev_attr_subsysnqn.attr,
3678 &dev_attr_address.attr,
3679 &dev_attr_state.attr,
3680 &dev_attr_numa_node.attr,
3681 &dev_attr_queue_count.attr,
3682 &dev_attr_sqsize.attr,
3683 &dev_attr_hostnqn.attr,
3684 &dev_attr_hostid.attr,
3685 &dev_attr_ctrl_loss_tmo.attr,
3686 &dev_attr_reconnect_delay.attr,
3690 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3691 struct attribute *a, int n)
3693 struct device *dev = container_of(kobj, struct device, kobj);
3694 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3696 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3698 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3700 if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3702 if (a == &dev_attr_hostid.attr && !ctrl->opts)
3704 if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts)
3706 if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts)
3712 static struct attribute_group nvme_dev_attrs_group = {
3713 .attrs = nvme_dev_attrs,
3714 .is_visible = nvme_dev_attrs_are_visible,
3717 static const struct attribute_group *nvme_dev_attr_groups[] = {
3718 &nvme_dev_attrs_group,
3722 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3725 struct nvme_ns_head *h;
3727 lockdep_assert_held(&subsys->lock);
3729 list_for_each_entry(h, &subsys->nsheads, entry) {
3730 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
3737 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3738 struct nvme_ns_head *new)
3740 struct nvme_ns_head *h;
3742 lockdep_assert_held(&subsys->lock);
3744 list_for_each_entry(h, &subsys->nsheads, entry) {
3745 if (nvme_ns_ids_valid(&new->ids) &&
3746 nvme_ns_ids_equal(&new->ids, &h->ids))
3753 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3754 unsigned nsid, struct nvme_ns_ids *ids)
3756 struct nvme_ns_head *head;
3757 size_t size = sizeof(*head);
3760 #ifdef CONFIG_NVME_MULTIPATH
3761 size += num_possible_nodes() * sizeof(struct nvme_ns *);
3764 head = kzalloc(size, GFP_KERNEL);
3767 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3770 head->instance = ret;
3771 INIT_LIST_HEAD(&head->list);
3772 ret = init_srcu_struct(&head->srcu);
3774 goto out_ida_remove;
3775 head->subsys = ctrl->subsys;
3778 kref_init(&head->ref);
3780 ret = __nvme_check_ids(ctrl->subsys, head);
3782 dev_err(ctrl->device,
3783 "duplicate IDs for nsid %d\n", nsid);
3784 goto out_cleanup_srcu;
3787 if (head->ids.csi) {
3788 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3790 goto out_cleanup_srcu;
3792 head->effects = ctrl->effects;
3794 ret = nvme_mpath_alloc_disk(ctrl, head);
3796 goto out_cleanup_srcu;
3798 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3800 kref_get(&ctrl->subsys->ref);
3804 cleanup_srcu_struct(&head->srcu);
3806 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3811 ret = blk_status_to_errno(nvme_error_status(ret));
3812 return ERR_PTR(ret);
3815 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3816 struct nvme_id_ns *id)
3818 struct nvme_ctrl *ctrl = ns->ctrl;
3819 bool is_shared = id->nmic & NVME_NS_NMIC_SHARED;
3820 struct nvme_ns_head *head = NULL;
3821 struct nvme_ns_ids ids;
3824 ret = nvme_report_ns_ids(ctrl, nsid, id, &ids);
3828 return blk_status_to_errno(nvme_error_status(ret));
3831 mutex_lock(&ctrl->subsys->lock);
3832 head = nvme_find_ns_head(ctrl->subsys, nsid);
3834 head = nvme_alloc_ns_head(ctrl, nsid, &ids);
3836 ret = PTR_ERR(head);
3839 head->shared = is_shared;
3842 if (!is_shared || !head->shared) {
3843 dev_err(ctrl->device,
3844 "Duplicate unshared namespace %d\n", nsid);
3845 goto out_put_ns_head;
3847 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
3848 dev_err(ctrl->device,
3849 "IDs don't match for shared namespace %d\n",
3851 goto out_put_ns_head;
3855 list_add_tail(&ns->siblings, &head->list);
3857 mutex_unlock(&ctrl->subsys->lock);
3861 nvme_put_ns_head(head);
3863 mutex_unlock(&ctrl->subsys->lock);
3867 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
3869 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3870 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3872 return nsa->head->ns_id - nsb->head->ns_id;
3875 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3877 struct nvme_ns *ns, *ret = NULL;
3879 down_read(&ctrl->namespaces_rwsem);
3880 list_for_each_entry(ns, &ctrl->namespaces, list) {
3881 if (ns->head->ns_id == nsid) {
3882 if (!kref_get_unless_zero(&ns->kref))
3887 if (ns->head->ns_id > nsid)
3890 up_read(&ctrl->namespaces_rwsem);
3893 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3895 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3898 struct gendisk *disk;
3899 struct nvme_id_ns *id;
3900 char disk_name[DISK_NAME_LEN];
3901 int node = ctrl->numa_node, flags = GENHD_FL_EXT_DEVT, ret;
3903 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3907 ns->queue = blk_mq_init_queue(ctrl->tagset);
3908 if (IS_ERR(ns->queue))
3911 if (ctrl->opts && ctrl->opts->data_digest)
3912 ns->queue->backing_dev_info->capabilities
3913 |= BDI_CAP_STABLE_WRITES;
3915 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3916 if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3917 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3919 ns->queue->queuedata = ns;
3922 kref_init(&ns->kref);
3923 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
3925 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
3926 nvme_set_queue_limits(ctrl, ns->queue);
3928 ret = nvme_identify_ns(ctrl, nsid, &id);
3930 goto out_free_queue;
3932 if (id->ncap == 0) /* no namespace (legacy quirk) */
3935 ret = nvme_init_ns_head(ns, nsid, id);
3938 nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3940 disk = alloc_disk_node(0, node);
3944 disk->fops = &nvme_fops;
3945 disk->private_data = ns;
3946 disk->queue = ns->queue;
3947 disk->flags = flags;
3948 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3951 if (__nvme_revalidate_disk(disk, id))
3954 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3955 ret = nvme_nvm_register(ns, disk_name, node);
3957 dev_warn(ctrl->device, "LightNVM init failure\n");
3962 down_write(&ctrl->namespaces_rwsem);
3963 list_add_tail(&ns->list, &ctrl->namespaces);
3964 up_write(&ctrl->namespaces_rwsem);
3966 nvme_get_ctrl(ctrl);
3968 device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups);
3970 nvme_mpath_add_disk(ns, id);
3971 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3976 /* prevent double queue cleanup */
3977 ns->disk->queue = NULL;
3980 mutex_lock(&ctrl->subsys->lock);
3981 list_del_rcu(&ns->siblings);
3982 if (list_empty(&ns->head->list))
3983 list_del_init(&ns->head->entry);
3984 mutex_unlock(&ctrl->subsys->lock);
3985 nvme_put_ns_head(ns->head);
3989 blk_cleanup_queue(ns->queue);
3994 static void nvme_ns_remove(struct nvme_ns *ns)
3996 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3999 nvme_fault_inject_fini(&ns->fault_inject);
4001 mutex_lock(&ns->ctrl->subsys->lock);
4002 list_del_rcu(&ns->siblings);
4003 if (list_empty(&ns->head->list))
4004 list_del_init(&ns->head->entry);
4005 mutex_unlock(&ns->ctrl->subsys->lock);
4007 synchronize_rcu(); /* guarantee not available in head->list */
4008 nvme_mpath_clear_current_path(ns);
4009 synchronize_srcu(&ns->head->srcu); /* wait for concurrent submissions */
4011 if (ns->disk->flags & GENHD_FL_UP) {
4012 del_gendisk(ns->disk);
4013 blk_cleanup_queue(ns->queue);
4014 if (blk_get_integrity(ns->disk))
4015 blk_integrity_unregister(ns->disk);
4018 down_write(&ns->ctrl->namespaces_rwsem);
4019 list_del_init(&ns->list);
4020 up_write(&ns->ctrl->namespaces_rwsem);
4022 nvme_mpath_check_last_path(ns);
4026 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
4028 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
4036 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
4040 ns = nvme_find_get_ns(ctrl, nsid);
4042 if (revalidate_disk(ns->disk))
4046 nvme_alloc_ns(ctrl, nsid);
4049 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
4052 struct nvme_ns *ns, *next;
4055 down_write(&ctrl->namespaces_rwsem);
4056 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
4057 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
4058 list_move_tail(&ns->list, &rm_list);
4060 up_write(&ctrl->namespaces_rwsem);
4062 list_for_each_entry_safe(ns, next, &rm_list, list)
4067 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
4069 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
4074 if (nvme_ctrl_limited_cns(ctrl))
4077 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
4082 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
4086 for (i = 0; i < nr_entries; i++) {
4087 u32 nsid = le32_to_cpu(ns_list[i]);
4089 if (!nsid) /* end of the list? */
4091 nvme_validate_ns(ctrl, nsid);
4092 while (++prev < nsid)
4093 nvme_ns_remove_by_nsid(ctrl, prev);
4097 nvme_remove_invalid_namespaces(ctrl, prev);
4103 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
4105 struct nvme_id_ctrl *id;
4108 if (nvme_identify_ctrl(ctrl, &id))
4110 nn = le32_to_cpu(id->nn);
4113 for (i = 1; i <= nn; i++)
4114 nvme_validate_ns(ctrl, i);
4116 nvme_remove_invalid_namespaces(ctrl, nn);
4119 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
4121 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
4125 log = kzalloc(log_size, GFP_KERNEL);
4130 * We need to read the log to clear the AEN, but we don't want to rely
4131 * on it for the changed namespace information as userspace could have
4132 * raced with us in reading the log page, which could cause us to miss
4135 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
4136 NVME_CSI_NVM, log, log_size, 0);
4138 dev_warn(ctrl->device,
4139 "reading changed ns log failed: %d\n", error);
4144 static void nvme_scan_work(struct work_struct *work)
4146 struct nvme_ctrl *ctrl =
4147 container_of(work, struct nvme_ctrl, scan_work);
4149 /* No tagset on a live ctrl means IO queues could not created */
4150 if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
4153 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
4154 dev_info(ctrl->device, "rescanning namespaces.\n");
4155 nvme_clear_changed_ns_log(ctrl);
4158 mutex_lock(&ctrl->scan_lock);
4159 if (nvme_scan_ns_list(ctrl) != 0)
4160 nvme_scan_ns_sequential(ctrl);
4161 mutex_unlock(&ctrl->scan_lock);
4163 down_write(&ctrl->namespaces_rwsem);
4164 list_sort(NULL, &ctrl->namespaces, ns_cmp);
4165 up_write(&ctrl->namespaces_rwsem);
4169 * This function iterates the namespace list unlocked to allow recovery from
4170 * controller failure. It is up to the caller to ensure the namespace list is
4171 * not modified by scan work while this function is executing.
4173 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
4175 struct nvme_ns *ns, *next;
4179 * make sure to requeue I/O to all namespaces as these
4180 * might result from the scan itself and must complete
4181 * for the scan_work to make progress
4183 nvme_mpath_clear_ctrl_paths(ctrl);
4185 /* prevent racing with ns scanning */
4186 flush_work(&ctrl->scan_work);
4189 * The dead states indicates the controller was not gracefully
4190 * disconnected. In that case, we won't be able to flush any data while
4191 * removing the namespaces' disks; fail all the queues now to avoid
4192 * potentially having to clean up the failed sync later.
4194 if (ctrl->state == NVME_CTRL_DEAD)
4195 nvme_kill_queues(ctrl);
4197 /* this is a no-op when called from the controller reset handler */
4198 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4200 down_write(&ctrl->namespaces_rwsem);
4201 list_splice_init(&ctrl->namespaces, &ns_list);
4202 up_write(&ctrl->namespaces_rwsem);
4204 list_for_each_entry_safe(ns, next, &ns_list, list)
4207 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4209 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
4211 struct nvme_ctrl *ctrl =
4212 container_of(dev, struct nvme_ctrl, ctrl_device);
4213 struct nvmf_ctrl_options *opts = ctrl->opts;
4216 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4221 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4225 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4226 opts->trsvcid ?: "none");
4230 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4231 opts->host_traddr ?: "none");
4236 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4238 char *envp[2] = { NULL, NULL };
4239 u32 aen_result = ctrl->aen_result;
4241 ctrl->aen_result = 0;
4245 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4248 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4252 static void nvme_async_event_work(struct work_struct *work)
4254 struct nvme_ctrl *ctrl =
4255 container_of(work, struct nvme_ctrl, async_event_work);
4257 nvme_aen_uevent(ctrl);
4258 ctrl->ops->submit_async_event(ctrl);
4261 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4266 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4272 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4275 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4277 struct nvme_fw_slot_info_log *log;
4279 log = kmalloc(sizeof(*log), GFP_KERNEL);
4283 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4284 log, sizeof(*log), 0))
4285 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4289 static void nvme_fw_act_work(struct work_struct *work)
4291 struct nvme_ctrl *ctrl = container_of(work,
4292 struct nvme_ctrl, fw_act_work);
4293 unsigned long fw_act_timeout;
4296 fw_act_timeout = jiffies +
4297 msecs_to_jiffies(ctrl->mtfa * 100);
4299 fw_act_timeout = jiffies +
4300 msecs_to_jiffies(admin_timeout * 1000);
4302 nvme_stop_queues(ctrl);
4303 while (nvme_ctrl_pp_status(ctrl)) {
4304 if (time_after(jiffies, fw_act_timeout)) {
4305 dev_warn(ctrl->device,
4306 "Fw activation timeout, reset controller\n");
4307 nvme_try_sched_reset(ctrl);
4313 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4316 nvme_start_queues(ctrl);
4317 /* read FW slot information to clear the AER */
4318 nvme_get_fw_slot_info(ctrl);
4321 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4323 u32 aer_notice_type = (result & 0xff00) >> 8;
4325 trace_nvme_async_event(ctrl, aer_notice_type);
4327 switch (aer_notice_type) {
4328 case NVME_AER_NOTICE_NS_CHANGED:
4329 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4330 nvme_queue_scan(ctrl);
4332 case NVME_AER_NOTICE_FW_ACT_STARTING:
4334 * We are (ab)using the RESETTING state to prevent subsequent
4335 * recovery actions from interfering with the controller's
4336 * firmware activation.
4338 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4339 queue_work(nvme_wq, &ctrl->fw_act_work);
4341 #ifdef CONFIG_NVME_MULTIPATH
4342 case NVME_AER_NOTICE_ANA:
4343 if (!ctrl->ana_log_buf)
4345 queue_work(nvme_wq, &ctrl->ana_work);
4348 case NVME_AER_NOTICE_DISC_CHANGED:
4349 ctrl->aen_result = result;
4352 dev_warn(ctrl->device, "async event result %08x\n", result);
4356 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4357 volatile union nvme_result *res)
4359 u32 result = le32_to_cpu(res->u32);
4360 u32 aer_type = result & 0x07;
4362 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4366 case NVME_AER_NOTICE:
4367 nvme_handle_aen_notice(ctrl, result);
4369 case NVME_AER_ERROR:
4370 case NVME_AER_SMART:
4373 trace_nvme_async_event(ctrl, aer_type);
4374 ctrl->aen_result = result;
4379 queue_work(nvme_wq, &ctrl->async_event_work);
4381 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4383 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4385 nvme_mpath_stop(ctrl);
4386 nvme_stop_keep_alive(ctrl);
4387 flush_work(&ctrl->async_event_work);
4388 cancel_work_sync(&ctrl->fw_act_work);
4390 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4392 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4394 nvme_start_keep_alive(ctrl);
4396 nvme_enable_aen(ctrl);
4398 if (ctrl->queue_count > 1) {
4399 nvme_queue_scan(ctrl);
4400 nvme_start_queues(ctrl);
4403 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4405 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4407 nvme_fault_inject_fini(&ctrl->fault_inject);
4408 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4409 cdev_device_del(&ctrl->cdev, ctrl->device);
4410 nvme_put_ctrl(ctrl);
4412 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4414 static void nvme_free_ctrl(struct device *dev)
4416 struct nvme_ctrl *ctrl =
4417 container_of(dev, struct nvme_ctrl, ctrl_device);
4418 struct nvme_subsystem *subsys = ctrl->subsys;
4419 struct nvme_cel *cel, *next;
4421 if (!subsys || ctrl->instance != subsys->instance)
4422 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4424 list_for_each_entry_safe(cel, next, &ctrl->cels, entry) {
4425 list_del(&cel->entry);
4429 nvme_mpath_uninit(ctrl);
4430 __free_page(ctrl->discard_page);
4433 mutex_lock(&nvme_subsystems_lock);
4434 list_del(&ctrl->subsys_entry);
4435 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4436 mutex_unlock(&nvme_subsystems_lock);
4439 ctrl->ops->free_ctrl(ctrl);
4442 nvme_put_subsystem(subsys);
4446 * Initialize a NVMe controller structures. This needs to be called during
4447 * earliest initialization so that we have the initialized structured around
4450 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4451 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4455 ctrl->state = NVME_CTRL_NEW;
4456 spin_lock_init(&ctrl->lock);
4457 mutex_init(&ctrl->scan_lock);
4458 INIT_LIST_HEAD(&ctrl->namespaces);
4459 INIT_LIST_HEAD(&ctrl->cels);
4460 init_rwsem(&ctrl->namespaces_rwsem);
4463 ctrl->quirks = quirks;
4464 ctrl->numa_node = NUMA_NO_NODE;
4465 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4466 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4467 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4468 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4469 init_waitqueue_head(&ctrl->state_wq);
4471 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4472 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4473 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4475 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4477 ctrl->discard_page = alloc_page(GFP_KERNEL);
4478 if (!ctrl->discard_page) {
4483 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4486 ctrl->instance = ret;
4488 device_initialize(&ctrl->ctrl_device);
4489 ctrl->device = &ctrl->ctrl_device;
4490 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
4491 ctrl->device->class = nvme_class;
4492 ctrl->device->parent = ctrl->dev;
4493 ctrl->device->groups = nvme_dev_attr_groups;
4494 ctrl->device->release = nvme_free_ctrl;
4495 dev_set_drvdata(ctrl->device, ctrl);
4496 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4498 goto out_release_instance;
4500 nvme_get_ctrl(ctrl);
4501 cdev_init(&ctrl->cdev, &nvme_dev_fops);
4502 ctrl->cdev.owner = ops->module;
4503 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4508 * Initialize latency tolerance controls. The sysfs files won't
4509 * be visible to userspace unless the device actually supports APST.
4511 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4512 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4513 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4515 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4519 nvme_put_ctrl(ctrl);
4520 kfree_const(ctrl->device->kobj.name);
4521 out_release_instance:
4522 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4524 if (ctrl->discard_page)
4525 __free_page(ctrl->discard_page);
4528 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4531 * nvme_kill_queues(): Ends all namespace queues
4532 * @ctrl: the dead controller that needs to end
4534 * Call this function when the driver determines it is unable to get the
4535 * controller in a state capable of servicing IO.
4537 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4541 down_read(&ctrl->namespaces_rwsem);
4543 /* Forcibly unquiesce queues to avoid blocking dispatch */
4544 if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4545 blk_mq_unquiesce_queue(ctrl->admin_q);
4547 list_for_each_entry(ns, &ctrl->namespaces, list)
4548 nvme_set_queue_dying(ns);
4550 up_read(&ctrl->namespaces_rwsem);
4552 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4554 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4558 down_read(&ctrl->namespaces_rwsem);
4559 list_for_each_entry(ns, &ctrl->namespaces, list)
4560 blk_mq_unfreeze_queue(ns->queue);
4561 up_read(&ctrl->namespaces_rwsem);
4563 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4565 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4569 down_read(&ctrl->namespaces_rwsem);
4570 list_for_each_entry(ns, &ctrl->namespaces, list) {
4571 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4575 up_read(&ctrl->namespaces_rwsem);
4578 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4580 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4584 down_read(&ctrl->namespaces_rwsem);
4585 list_for_each_entry(ns, &ctrl->namespaces, list)
4586 blk_mq_freeze_queue_wait(ns->queue);
4587 up_read(&ctrl->namespaces_rwsem);
4589 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4591 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4595 down_read(&ctrl->namespaces_rwsem);
4596 list_for_each_entry(ns, &ctrl->namespaces, list)
4597 blk_freeze_queue_start(ns->queue);
4598 up_read(&ctrl->namespaces_rwsem);
4600 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4602 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4606 down_read(&ctrl->namespaces_rwsem);
4607 list_for_each_entry(ns, &ctrl->namespaces, list)
4608 blk_mq_quiesce_queue(ns->queue);
4609 up_read(&ctrl->namespaces_rwsem);
4611 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4613 void nvme_start_queues(struct nvme_ctrl *ctrl)
4617 down_read(&ctrl->namespaces_rwsem);
4618 list_for_each_entry(ns, &ctrl->namespaces, list)
4619 blk_mq_unquiesce_queue(ns->queue);
4620 up_read(&ctrl->namespaces_rwsem);
4622 EXPORT_SYMBOL_GPL(nvme_start_queues);
4625 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4629 down_read(&ctrl->namespaces_rwsem);
4630 list_for_each_entry(ns, &ctrl->namespaces, list)
4631 blk_sync_queue(ns->queue);
4632 up_read(&ctrl->namespaces_rwsem);
4635 blk_sync_queue(ctrl->admin_q);
4637 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4639 struct nvme_ctrl *nvme_ctrl_get_by_path(const char *path)
4641 struct nvme_ctrl *ctrl;
4644 f = filp_open(path, O_RDWR, 0);
4648 if (f->f_op != &nvme_dev_fops) {
4649 ctrl = ERR_PTR(-EINVAL);
4653 ctrl = f->private_data;
4654 nvme_get_ctrl(ctrl);
4657 filp_close(f, NULL);
4660 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_get_by_path, NVME_TARGET_PASSTHRU);
4663 * Check we didn't inadvertently grow the command structure sizes:
4665 static inline void _nvme_check_size(void)
4667 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4668 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4669 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4670 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4671 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4672 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4673 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4674 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4675 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4676 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4677 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4678 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4679 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4680 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4681 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4682 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4683 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4684 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4685 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4689 static int __init nvme_core_init(void)
4691 int result = -ENOMEM;
4695 nvme_wq = alloc_workqueue("nvme-wq",
4696 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4700 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4701 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4705 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4706 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4707 if (!nvme_delete_wq)
4708 goto destroy_reset_wq;
4710 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
4712 goto destroy_delete_wq;
4714 nvme_class = class_create(THIS_MODULE, "nvme");
4715 if (IS_ERR(nvme_class)) {
4716 result = PTR_ERR(nvme_class);
4717 goto unregister_chrdev;
4719 nvme_class->dev_uevent = nvme_class_uevent;
4721 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4722 if (IS_ERR(nvme_subsys_class)) {
4723 result = PTR_ERR(nvme_subsys_class);
4729 class_destroy(nvme_class);
4731 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4733 destroy_workqueue(nvme_delete_wq);
4735 destroy_workqueue(nvme_reset_wq);
4737 destroy_workqueue(nvme_wq);
4742 static void __exit nvme_core_exit(void)
4744 class_destroy(nvme_subsys_class);
4745 class_destroy(nvme_class);
4746 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
4747 destroy_workqueue(nvme_delete_wq);
4748 destroy_workqueue(nvme_reset_wq);
4749 destroy_workqueue(nvme_wq);
4750 ida_destroy(&nvme_instance_ida);
4753 MODULE_LICENSE("GPL");
4754 MODULE_VERSION("1.0");
4755 module_init(nvme_core_init);
4756 module_exit(nvme_core_exit);