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_ctrl_base_chr_devt;
89 static struct class *nvme_class;
90 static struct class *nvme_subsys_class;
92 static DEFINE_IDA(nvme_ns_chr_minor_ida);
93 static dev_t nvme_ns_chr_devt;
94 static struct class *nvme_ns_chr_class;
96 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
97 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
101 * Prepare a queue for teardown.
103 * This must forcibly unquiesce queues to avoid blocking dispatch, and only set
104 * the capacity to 0 after that to avoid blocking dispatchers that may be
105 * holding bd_butex. This will end buffered writers dirtying pages that can't
108 static void nvme_set_queue_dying(struct nvme_ns *ns)
110 if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
113 blk_set_queue_dying(ns->queue);
114 blk_mq_unquiesce_queue(ns->queue);
116 set_capacity_and_notify(ns->disk, 0);
119 void nvme_queue_scan(struct nvme_ctrl *ctrl)
122 * Only new queue scan work when admin and IO queues are both alive
124 if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset)
125 queue_work(nvme_wq, &ctrl->scan_work);
129 * Use this function to proceed with scheduling reset_work for a controller
130 * that had previously been set to the resetting state. This is intended for
131 * code paths that can't be interrupted by other reset attempts. A hot removal
132 * may prevent this from succeeding.
134 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
136 if (ctrl->state != NVME_CTRL_RESETTING)
138 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
142 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
144 static void nvme_failfast_work(struct work_struct *work)
146 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
147 struct nvme_ctrl, failfast_work);
149 if (ctrl->state != NVME_CTRL_CONNECTING)
152 set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
153 dev_info(ctrl->device, "failfast expired\n");
154 nvme_kick_requeue_lists(ctrl);
157 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
159 if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
162 schedule_delayed_work(&ctrl->failfast_work,
163 ctrl->opts->fast_io_fail_tmo * HZ);
166 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
171 cancel_delayed_work_sync(&ctrl->failfast_work);
172 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
176 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
178 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
180 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
184 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
186 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
190 ret = nvme_reset_ctrl(ctrl);
192 flush_work(&ctrl->reset_work);
193 if (ctrl->state != NVME_CTRL_LIVE)
200 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
202 dev_info(ctrl->device,
203 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
205 flush_work(&ctrl->reset_work);
206 nvme_stop_ctrl(ctrl);
207 nvme_remove_namespaces(ctrl);
208 ctrl->ops->delete_ctrl(ctrl);
209 nvme_uninit_ctrl(ctrl);
212 static void nvme_delete_ctrl_work(struct work_struct *work)
214 struct nvme_ctrl *ctrl =
215 container_of(work, struct nvme_ctrl, delete_work);
217 nvme_do_delete_ctrl(ctrl);
220 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
222 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
224 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
228 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
230 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
233 * Keep a reference until nvme_do_delete_ctrl() complete,
234 * since ->delete_ctrl can free the controller.
237 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
238 nvme_do_delete_ctrl(ctrl);
242 static blk_status_t nvme_error_status(u16 status)
244 switch (status & 0x7ff) {
245 case NVME_SC_SUCCESS:
247 case NVME_SC_CAP_EXCEEDED:
248 return BLK_STS_NOSPC;
249 case NVME_SC_LBA_RANGE:
250 case NVME_SC_CMD_INTERRUPTED:
251 case NVME_SC_NS_NOT_READY:
252 return BLK_STS_TARGET;
253 case NVME_SC_BAD_ATTRIBUTES:
254 case NVME_SC_ONCS_NOT_SUPPORTED:
255 case NVME_SC_INVALID_OPCODE:
256 case NVME_SC_INVALID_FIELD:
257 case NVME_SC_INVALID_NS:
258 return BLK_STS_NOTSUPP;
259 case NVME_SC_WRITE_FAULT:
260 case NVME_SC_READ_ERROR:
261 case NVME_SC_UNWRITTEN_BLOCK:
262 case NVME_SC_ACCESS_DENIED:
263 case NVME_SC_READ_ONLY:
264 case NVME_SC_COMPARE_FAILED:
265 return BLK_STS_MEDIUM;
266 case NVME_SC_GUARD_CHECK:
267 case NVME_SC_APPTAG_CHECK:
268 case NVME_SC_REFTAG_CHECK:
269 case NVME_SC_INVALID_PI:
270 return BLK_STS_PROTECTION;
271 case NVME_SC_RESERVATION_CONFLICT:
272 return BLK_STS_NEXUS;
273 case NVME_SC_HOST_PATH_ERROR:
274 return BLK_STS_TRANSPORT;
275 case NVME_SC_ZONE_TOO_MANY_ACTIVE:
276 return BLK_STS_ZONE_ACTIVE_RESOURCE;
277 case NVME_SC_ZONE_TOO_MANY_OPEN:
278 return BLK_STS_ZONE_OPEN_RESOURCE;
280 return BLK_STS_IOERR;
284 static void nvme_retry_req(struct request *req)
286 unsigned long delay = 0;
289 /* The mask and shift result must be <= 3 */
290 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
292 delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
294 nvme_req(req)->retries++;
295 blk_mq_requeue_request(req, false);
296 blk_mq_delay_kick_requeue_list(req->q, delay);
299 enum nvme_disposition {
305 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
307 if (likely(nvme_req(req)->status == 0))
310 if (blk_noretry_request(req) ||
311 (nvme_req(req)->status & NVME_SC_DNR) ||
312 nvme_req(req)->retries >= nvme_max_retries)
315 if (req->cmd_flags & REQ_NVME_MPATH) {
316 if (nvme_is_path_error(nvme_req(req)->status) ||
317 blk_queue_dying(req->q))
320 if (blk_queue_dying(req->q))
327 static inline void nvme_end_req(struct request *req)
329 blk_status_t status = nvme_error_status(nvme_req(req)->status);
331 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
332 req_op(req) == REQ_OP_ZONE_APPEND)
333 req->__sector = nvme_lba_to_sect(req->q->queuedata,
334 le64_to_cpu(nvme_req(req)->result.u64));
336 nvme_trace_bio_complete(req);
337 blk_mq_end_request(req, status);
340 void nvme_complete_rq(struct request *req)
342 trace_nvme_complete_rq(req);
343 nvme_cleanup_cmd(req);
345 if (nvme_req(req)->ctrl->kas)
346 nvme_req(req)->ctrl->comp_seen = true;
348 switch (nvme_decide_disposition(req)) {
356 nvme_failover_req(req);
360 EXPORT_SYMBOL_GPL(nvme_complete_rq);
363 * Called to unwind from ->queue_rq on a failed command submission so that the
364 * multipathing code gets called to potentially failover to another path.
365 * The caller needs to unwind all transport specific resource allocations and
366 * must return propagate the return value.
368 blk_status_t nvme_host_path_error(struct request *req)
370 nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
371 blk_mq_set_request_complete(req);
372 nvme_complete_rq(req);
375 EXPORT_SYMBOL_GPL(nvme_host_path_error);
377 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
379 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
380 "Cancelling I/O %d", req->tag);
382 /* don't abort one completed request */
383 if (blk_mq_request_completed(req))
386 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
387 nvme_req(req)->flags |= NVME_REQ_CANCELLED;
388 blk_mq_complete_request(req);
391 EXPORT_SYMBOL_GPL(nvme_cancel_request);
393 void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
396 blk_mq_tagset_busy_iter(ctrl->tagset,
397 nvme_cancel_request, ctrl);
398 blk_mq_tagset_wait_completed_request(ctrl->tagset);
401 EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
403 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
405 if (ctrl->admin_tagset) {
406 blk_mq_tagset_busy_iter(ctrl->admin_tagset,
407 nvme_cancel_request, ctrl);
408 blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
411 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
413 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
414 enum nvme_ctrl_state new_state)
416 enum nvme_ctrl_state old_state;
418 bool changed = false;
420 spin_lock_irqsave(&ctrl->lock, flags);
422 old_state = ctrl->state;
427 case NVME_CTRL_RESETTING:
428 case NVME_CTRL_CONNECTING:
435 case NVME_CTRL_RESETTING:
445 case NVME_CTRL_CONNECTING:
448 case NVME_CTRL_RESETTING:
455 case NVME_CTRL_DELETING:
458 case NVME_CTRL_RESETTING:
459 case NVME_CTRL_CONNECTING:
466 case NVME_CTRL_DELETING_NOIO:
468 case NVME_CTRL_DELETING:
478 case NVME_CTRL_DELETING:
490 ctrl->state = new_state;
491 wake_up_all(&ctrl->state_wq);
494 spin_unlock_irqrestore(&ctrl->lock, flags);
498 if (ctrl->state == NVME_CTRL_LIVE) {
499 if (old_state == NVME_CTRL_CONNECTING)
500 nvme_stop_failfast_work(ctrl);
501 nvme_kick_requeue_lists(ctrl);
502 } else if (ctrl->state == NVME_CTRL_CONNECTING &&
503 old_state == NVME_CTRL_RESETTING) {
504 nvme_start_failfast_work(ctrl);
508 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
511 * Returns true for sink states that can't ever transition back to live.
513 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
515 switch (ctrl->state) {
518 case NVME_CTRL_RESETTING:
519 case NVME_CTRL_CONNECTING:
521 case NVME_CTRL_DELETING:
522 case NVME_CTRL_DELETING_NOIO:
526 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
532 * Waits for the controller state to be resetting, or returns false if it is
533 * not possible to ever transition to that state.
535 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
537 wait_event(ctrl->state_wq,
538 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
539 nvme_state_terminal(ctrl));
540 return ctrl->state == NVME_CTRL_RESETTING;
542 EXPORT_SYMBOL_GPL(nvme_wait_reset);
544 static void nvme_free_ns_head(struct kref *ref)
546 struct nvme_ns_head *head =
547 container_of(ref, struct nvme_ns_head, ref);
549 nvme_mpath_remove_disk(head);
550 ida_simple_remove(&head->subsys->ns_ida, head->instance);
551 cleanup_srcu_struct(&head->srcu);
552 nvme_put_subsystem(head->subsys);
556 bool nvme_tryget_ns_head(struct nvme_ns_head *head)
558 return kref_get_unless_zero(&head->ref);
561 void nvme_put_ns_head(struct nvme_ns_head *head)
563 kref_put(&head->ref, nvme_free_ns_head);
566 static void nvme_free_ns(struct kref *kref)
568 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
571 nvme_nvm_unregister(ns);
574 nvme_put_ns_head(ns->head);
575 nvme_put_ctrl(ns->ctrl);
579 static inline bool nvme_get_ns(struct nvme_ns *ns)
581 return kref_get_unless_zero(&ns->kref);
584 void nvme_put_ns(struct nvme_ns *ns)
586 kref_put(&ns->kref, nvme_free_ns);
588 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
590 static inline void nvme_clear_nvme_request(struct request *req)
592 struct nvme_command *cmd = nvme_req(req)->cmd;
594 memset(cmd, 0, sizeof(*cmd));
595 nvme_req(req)->retries = 0;
596 nvme_req(req)->flags = 0;
597 req->rq_flags |= RQF_DONTPREP;
600 static inline unsigned int nvme_req_op(struct nvme_command *cmd)
602 return nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
605 static inline void nvme_init_request(struct request *req,
606 struct nvme_command *cmd)
608 if (req->q->queuedata)
609 req->timeout = NVME_IO_TIMEOUT;
610 else /* no queuedata implies admin queue */
611 req->timeout = NVME_ADMIN_TIMEOUT;
613 /* passthru commands should let the driver set the SGL flags */
614 cmd->common.flags &= ~NVME_CMD_SGL_ALL;
616 req->cmd_flags |= REQ_FAILFAST_DRIVER;
617 nvme_clear_nvme_request(req);
618 memcpy(nvme_req(req)->cmd, cmd, sizeof(*cmd));
621 struct request *nvme_alloc_request(struct request_queue *q,
622 struct nvme_command *cmd, blk_mq_req_flags_t flags)
626 req = blk_mq_alloc_request(q, nvme_req_op(cmd), flags);
628 nvme_init_request(req, cmd);
631 EXPORT_SYMBOL_GPL(nvme_alloc_request);
633 static struct request *nvme_alloc_request_qid(struct request_queue *q,
634 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
638 req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), flags,
641 nvme_init_request(req, cmd);
645 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
647 struct nvme_command c;
649 memset(&c, 0, sizeof(c));
651 c.directive.opcode = nvme_admin_directive_send;
652 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
653 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
654 c.directive.dtype = NVME_DIR_IDENTIFY;
655 c.directive.tdtype = NVME_DIR_STREAMS;
656 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
658 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
661 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
663 return nvme_toggle_streams(ctrl, false);
666 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
668 return nvme_toggle_streams(ctrl, true);
671 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
672 struct streams_directive_params *s, u32 nsid)
674 struct nvme_command c;
676 memset(&c, 0, sizeof(c));
677 memset(s, 0, sizeof(*s));
679 c.directive.opcode = nvme_admin_directive_recv;
680 c.directive.nsid = cpu_to_le32(nsid);
681 c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
682 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
683 c.directive.dtype = NVME_DIR_STREAMS;
685 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
688 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
690 struct streams_directive_params s;
693 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
698 ret = nvme_enable_streams(ctrl);
702 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
704 goto out_disable_stream;
706 ctrl->nssa = le16_to_cpu(s.nssa);
707 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
708 dev_info(ctrl->device, "too few streams (%u) available\n",
710 goto out_disable_stream;
713 ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
714 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
718 nvme_disable_streams(ctrl);
723 * Check if 'req' has a write hint associated with it. If it does, assign
724 * a valid namespace stream to the write.
726 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
727 struct request *req, u16 *control,
730 enum rw_hint streamid = req->write_hint;
732 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
736 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
739 *control |= NVME_RW_DTYPE_STREAMS;
740 *dsmgmt |= streamid << 16;
743 if (streamid < ARRAY_SIZE(req->q->write_hints))
744 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
747 static inline void nvme_setup_flush(struct nvme_ns *ns,
748 struct nvme_command *cmnd)
750 cmnd->common.opcode = nvme_cmd_flush;
751 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
754 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
755 struct nvme_command *cmnd)
757 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
758 struct nvme_dsm_range *range;
762 * Some devices do not consider the DSM 'Number of Ranges' field when
763 * determining how much data to DMA. Always allocate memory for maximum
764 * number of segments to prevent device reading beyond end of buffer.
766 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
768 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
771 * If we fail allocation our range, fallback to the controller
772 * discard page. If that's also busy, it's safe to return
773 * busy, as we know we can make progress once that's freed.
775 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
776 return BLK_STS_RESOURCE;
778 range = page_address(ns->ctrl->discard_page);
781 __rq_for_each_bio(bio, req) {
782 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
783 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
786 range[n].cattr = cpu_to_le32(0);
787 range[n].nlb = cpu_to_le32(nlb);
788 range[n].slba = cpu_to_le64(slba);
793 if (WARN_ON_ONCE(n != segments)) {
794 if (virt_to_page(range) == ns->ctrl->discard_page)
795 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
798 return BLK_STS_IOERR;
801 cmnd->dsm.opcode = nvme_cmd_dsm;
802 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
803 cmnd->dsm.nr = cpu_to_le32(segments - 1);
804 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
806 req->special_vec.bv_page = virt_to_page(range);
807 req->special_vec.bv_offset = offset_in_page(range);
808 req->special_vec.bv_len = alloc_size;
809 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
814 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
815 struct request *req, struct nvme_command *cmnd)
817 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
818 return nvme_setup_discard(ns, req, cmnd);
820 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
821 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
822 cmnd->write_zeroes.slba =
823 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
824 cmnd->write_zeroes.length =
825 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
826 cmnd->write_zeroes.control = 0;
830 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
831 struct request *req, struct nvme_command *cmnd,
834 struct nvme_ctrl *ctrl = ns->ctrl;
838 if (req->cmd_flags & REQ_FUA)
839 control |= NVME_RW_FUA;
840 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
841 control |= NVME_RW_LR;
843 if (req->cmd_flags & REQ_RAHEAD)
844 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
846 cmnd->rw.opcode = op;
847 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
848 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
849 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
851 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
852 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
856 * If formated with metadata, the block layer always provides a
857 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
858 * we enable the PRACT bit for protection information or set the
859 * namespace capacity to zero to prevent any I/O.
861 if (!blk_integrity_rq(req)) {
862 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
863 return BLK_STS_NOTSUPP;
864 control |= NVME_RW_PRINFO_PRACT;
867 switch (ns->pi_type) {
868 case NVME_NS_DPS_PI_TYPE3:
869 control |= NVME_RW_PRINFO_PRCHK_GUARD;
871 case NVME_NS_DPS_PI_TYPE1:
872 case NVME_NS_DPS_PI_TYPE2:
873 control |= NVME_RW_PRINFO_PRCHK_GUARD |
874 NVME_RW_PRINFO_PRCHK_REF;
875 if (op == nvme_cmd_zone_append)
876 control |= NVME_RW_APPEND_PIREMAP;
877 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
882 cmnd->rw.control = cpu_to_le16(control);
883 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
887 void nvme_cleanup_cmd(struct request *req)
889 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
890 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
891 struct page *page = req->special_vec.bv_page;
893 if (page == ctrl->discard_page)
894 clear_bit_unlock(0, &ctrl->discard_page_busy);
896 kfree(page_address(page) + req->special_vec.bv_offset);
899 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
901 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
903 struct nvme_command *cmd = nvme_req(req)->cmd;
904 blk_status_t ret = BLK_STS_OK;
906 if (!(req->rq_flags & RQF_DONTPREP))
907 nvme_clear_nvme_request(req);
909 switch (req_op(req)) {
912 /* these are setup prior to execution in nvme_init_request() */
915 nvme_setup_flush(ns, cmd);
917 case REQ_OP_ZONE_RESET_ALL:
918 case REQ_OP_ZONE_RESET:
919 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
921 case REQ_OP_ZONE_OPEN:
922 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
924 case REQ_OP_ZONE_CLOSE:
925 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
927 case REQ_OP_ZONE_FINISH:
928 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
930 case REQ_OP_WRITE_ZEROES:
931 ret = nvme_setup_write_zeroes(ns, req, cmd);
934 ret = nvme_setup_discard(ns, req, cmd);
937 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
940 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
942 case REQ_OP_ZONE_APPEND:
943 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
947 return BLK_STS_IOERR;
950 cmd->common.command_id = req->tag;
951 trace_nvme_setup_cmd(req, cmd);
954 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
956 static void nvme_end_sync_rq(struct request *rq, blk_status_t error)
958 struct completion *waiting = rq->end_io_data;
960 rq->end_io_data = NULL;
964 static void nvme_execute_rq_polled(struct request_queue *q,
965 struct gendisk *bd_disk, struct request *rq, int at_head)
967 DECLARE_COMPLETION_ONSTACK(wait);
969 WARN_ON_ONCE(!test_bit(QUEUE_FLAG_POLL, &q->queue_flags));
971 rq->cmd_flags |= REQ_HIPRI;
972 rq->end_io_data = &wait;
973 blk_execute_rq_nowait(bd_disk, rq, at_head, nvme_end_sync_rq);
975 while (!completion_done(&wait)) {
976 blk_poll(q, request_to_qc_t(rq->mq_hctx, rq), true);
982 * Returns 0 on success. If the result is negative, it's a Linux error code;
983 * if the result is positive, it's an NVM Express status code
985 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
986 union nvme_result *result, void *buffer, unsigned bufflen,
987 unsigned timeout, int qid, int at_head,
988 blk_mq_req_flags_t flags, bool poll)
993 if (qid == NVME_QID_ANY)
994 req = nvme_alloc_request(q, cmd, flags);
996 req = nvme_alloc_request_qid(q, cmd, flags, qid);
1001 req->timeout = timeout;
1003 if (buffer && bufflen) {
1004 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
1010 nvme_execute_rq_polled(req->q, NULL, req, at_head);
1012 blk_execute_rq(NULL, req, at_head);
1014 *result = nvme_req(req)->result;
1015 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
1018 ret = nvme_req(req)->status;
1020 blk_mq_free_request(req);
1023 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
1025 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1026 void *buffer, unsigned bufflen)
1028 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
1029 NVME_QID_ANY, 0, 0, false);
1031 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
1033 static u32 nvme_known_admin_effects(u8 opcode)
1036 case nvme_admin_format_nvm:
1037 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_NCC |
1038 NVME_CMD_EFFECTS_CSE_MASK;
1039 case nvme_admin_sanitize_nvm:
1040 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK;
1047 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1052 if (ns->head->effects)
1053 effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
1054 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1055 dev_warn_once(ctrl->device,
1056 "IO command:%02x has unhandled effects:%08x\n",
1062 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1063 effects |= nvme_known_admin_effects(opcode);
1067 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
1069 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1072 u32 effects = nvme_command_effects(ctrl, ns, opcode);
1075 * For simplicity, IO to all namespaces is quiesced even if the command
1076 * effects say only one namespace is affected.
1078 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1079 mutex_lock(&ctrl->scan_lock);
1080 mutex_lock(&ctrl->subsys->lock);
1081 nvme_mpath_start_freeze(ctrl->subsys);
1082 nvme_mpath_wait_freeze(ctrl->subsys);
1083 nvme_start_freeze(ctrl);
1084 nvme_wait_freeze(ctrl);
1089 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1091 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1092 nvme_unfreeze(ctrl);
1093 nvme_mpath_unfreeze(ctrl->subsys);
1094 mutex_unlock(&ctrl->subsys->lock);
1095 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1096 mutex_unlock(&ctrl->scan_lock);
1098 if (effects & NVME_CMD_EFFECTS_CCC)
1099 nvme_init_ctrl_finish(ctrl);
1100 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1101 nvme_queue_scan(ctrl);
1102 flush_work(&ctrl->scan_work);
1106 void nvme_execute_passthru_rq(struct request *rq)
1108 struct nvme_command *cmd = nvme_req(rq)->cmd;
1109 struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl;
1110 struct nvme_ns *ns = rq->q->queuedata;
1111 struct gendisk *disk = ns ? ns->disk : NULL;
1114 effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode);
1115 blk_execute_rq(disk, rq, 0);
1116 if (effects) /* nothing to be done for zero cmd effects */
1117 nvme_passthru_end(ctrl, effects);
1119 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU);
1122 * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
1124 * The host should send Keep Alive commands at half of the Keep Alive Timeout
1125 * accounting for transport roundtrip times [..].
1127 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
1129 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ / 2);
1132 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
1134 struct nvme_ctrl *ctrl = rq->end_io_data;
1135 unsigned long flags;
1136 bool startka = false;
1138 blk_mq_free_request(rq);
1141 dev_err(ctrl->device,
1142 "failed nvme_keep_alive_end_io error=%d\n",
1147 ctrl->comp_seen = false;
1148 spin_lock_irqsave(&ctrl->lock, flags);
1149 if (ctrl->state == NVME_CTRL_LIVE ||
1150 ctrl->state == NVME_CTRL_CONNECTING)
1152 spin_unlock_irqrestore(&ctrl->lock, flags);
1154 nvme_queue_keep_alive_work(ctrl);
1157 static void nvme_keep_alive_work(struct work_struct *work)
1159 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1160 struct nvme_ctrl, ka_work);
1161 bool comp_seen = ctrl->comp_seen;
1164 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1165 dev_dbg(ctrl->device,
1166 "reschedule traffic based keep-alive timer\n");
1167 ctrl->comp_seen = false;
1168 nvme_queue_keep_alive_work(ctrl);
1172 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd,
1173 BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
1175 /* allocation failure, reset the controller */
1176 dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
1177 nvme_reset_ctrl(ctrl);
1181 rq->timeout = ctrl->kato * HZ;
1182 rq->end_io_data = ctrl;
1183 blk_execute_rq_nowait(NULL, rq, 0, nvme_keep_alive_end_io);
1186 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1188 if (unlikely(ctrl->kato == 0))
1191 nvme_queue_keep_alive_work(ctrl);
1194 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1196 if (unlikely(ctrl->kato == 0))
1199 cancel_delayed_work_sync(&ctrl->ka_work);
1201 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1204 * In NVMe 1.0 the CNS field was just a binary controller or namespace
1205 * flag, thus sending any new CNS opcodes has a big chance of not working.
1206 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1207 * (but not for any later version).
1209 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1211 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1212 return ctrl->vs < NVME_VS(1, 2, 0);
1213 return ctrl->vs < NVME_VS(1, 1, 0);
1216 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1218 struct nvme_command c = { };
1221 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1222 c.identify.opcode = nvme_admin_identify;
1223 c.identify.cns = NVME_ID_CNS_CTRL;
1225 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1229 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1230 sizeof(struct nvme_id_ctrl));
1236 static bool nvme_multi_css(struct nvme_ctrl *ctrl)
1238 return (ctrl->ctrl_config & NVME_CC_CSS_MASK) == NVME_CC_CSS_CSI;
1241 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1242 struct nvme_ns_id_desc *cur, bool *csi_seen)
1244 const char *warn_str = "ctrl returned bogus length:";
1247 switch (cur->nidt) {
1248 case NVME_NIDT_EUI64:
1249 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1250 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1251 warn_str, cur->nidl);
1254 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1255 return NVME_NIDT_EUI64_LEN;
1256 case NVME_NIDT_NGUID:
1257 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1258 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1259 warn_str, cur->nidl);
1262 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1263 return NVME_NIDT_NGUID_LEN;
1264 case NVME_NIDT_UUID:
1265 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1266 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1267 warn_str, cur->nidl);
1270 uuid_copy(&ids->uuid, data + sizeof(*cur));
1271 return NVME_NIDT_UUID_LEN;
1273 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1274 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1275 warn_str, cur->nidl);
1278 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1280 return NVME_NIDT_CSI_LEN;
1282 /* Skip unknown types */
1287 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1288 struct nvme_ns_ids *ids)
1290 struct nvme_command c = { };
1291 bool csi_seen = false;
1292 int status, pos, len;
1295 if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
1297 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1300 c.identify.opcode = nvme_admin_identify;
1301 c.identify.nsid = cpu_to_le32(nsid);
1302 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1304 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1308 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1309 NVME_IDENTIFY_DATA_SIZE);
1311 dev_warn(ctrl->device,
1312 "Identify Descriptors failed (nsid=%u, status=0x%x)\n",
1317 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1318 struct nvme_ns_id_desc *cur = data + pos;
1323 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1327 len += sizeof(*cur);
1330 if (nvme_multi_css(ctrl) && !csi_seen) {
1331 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1341 static int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
1342 struct nvme_ns_ids *ids, struct nvme_id_ns **id)
1344 struct nvme_command c = { };
1347 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1348 c.identify.opcode = nvme_admin_identify;
1349 c.identify.nsid = cpu_to_le32(nsid);
1350 c.identify.cns = NVME_ID_CNS_NS;
1352 *id = kmalloc(sizeof(**id), GFP_KERNEL);
1356 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1358 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1362 error = NVME_SC_INVALID_NS | NVME_SC_DNR;
1363 if ((*id)->ncap == 0) /* namespace not allocated or attached */
1366 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1367 !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
1368 memcpy(ids->eui64, (*id)->eui64, sizeof(ids->eui64));
1369 if (ctrl->vs >= NVME_VS(1, 2, 0) &&
1370 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
1371 memcpy(ids->nguid, (*id)->nguid, sizeof(ids->nguid));
1380 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1381 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1383 union nvme_result res = { 0 };
1384 struct nvme_command c;
1387 memset(&c, 0, sizeof(c));
1388 c.features.opcode = op;
1389 c.features.fid = cpu_to_le32(fid);
1390 c.features.dword11 = cpu_to_le32(dword11);
1392 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1393 buffer, buflen, 0, NVME_QID_ANY, 0, 0, false);
1394 if (ret >= 0 && result)
1395 *result = le32_to_cpu(res.u32);
1399 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1400 unsigned int dword11, void *buffer, size_t buflen,
1403 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1406 EXPORT_SYMBOL_GPL(nvme_set_features);
1408 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1409 unsigned int dword11, void *buffer, size_t buflen,
1412 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1415 EXPORT_SYMBOL_GPL(nvme_get_features);
1417 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1419 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1421 int status, nr_io_queues;
1423 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1429 * Degraded controllers might return an error when setting the queue
1430 * count. We still want to be able to bring them online and offer
1431 * access to the admin queue, as that might be only way to fix them up.
1434 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1437 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1438 *count = min(*count, nr_io_queues);
1443 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1445 #define NVME_AEN_SUPPORTED \
1446 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1447 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1449 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1451 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1454 if (!supported_aens)
1457 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1460 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1463 queue_work(nvme_wq, &ctrl->async_event_work);
1467 * Issue ioctl requests on the first available path. Note that unlike normal
1468 * block layer requests we will not retry failed request on another controller.
1470 struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1471 struct nvme_ns_head **head, int *srcu_idx)
1473 #ifdef CONFIG_NVME_MULTIPATH
1474 if (disk->fops == &nvme_ns_head_ops) {
1477 *head = disk->private_data;
1478 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1479 ns = nvme_find_path(*head);
1481 srcu_read_unlock(&(*head)->srcu, *srcu_idx);
1487 return disk->private_data;
1490 void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1493 srcu_read_unlock(&head->srcu, idx);
1496 static int nvme_ns_open(struct nvme_ns *ns)
1499 /* should never be called due to GENHD_FL_HIDDEN */
1500 if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
1502 if (!nvme_get_ns(ns))
1504 if (!try_module_get(ns->ctrl->ops->module))
1515 static void nvme_ns_release(struct nvme_ns *ns)
1518 module_put(ns->ctrl->ops->module);
1522 static int nvme_open(struct block_device *bdev, fmode_t mode)
1524 return nvme_ns_open(bdev->bd_disk->private_data);
1527 static void nvme_release(struct gendisk *disk, fmode_t mode)
1529 nvme_ns_release(disk->private_data);
1532 int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1534 /* some standard values */
1535 geo->heads = 1 << 6;
1536 geo->sectors = 1 << 5;
1537 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1541 #ifdef CONFIG_BLK_DEV_INTEGRITY
1542 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1543 u32 max_integrity_segments)
1545 struct blk_integrity integrity;
1547 memset(&integrity, 0, sizeof(integrity));
1549 case NVME_NS_DPS_PI_TYPE3:
1550 integrity.profile = &t10_pi_type3_crc;
1551 integrity.tag_size = sizeof(u16) + sizeof(u32);
1552 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1554 case NVME_NS_DPS_PI_TYPE1:
1555 case NVME_NS_DPS_PI_TYPE2:
1556 integrity.profile = &t10_pi_type1_crc;
1557 integrity.tag_size = sizeof(u16);
1558 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1561 integrity.profile = NULL;
1564 integrity.tuple_size = ms;
1565 blk_integrity_register(disk, &integrity);
1566 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1569 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1570 u32 max_integrity_segments)
1573 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1575 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1577 struct nvme_ctrl *ctrl = ns->ctrl;
1578 struct request_queue *queue = disk->queue;
1579 u32 size = queue_logical_block_size(queue);
1581 if (ctrl->max_discard_sectors == 0) {
1582 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1586 if (ctrl->nr_streams && ns->sws && ns->sgs)
1587 size *= ns->sws * ns->sgs;
1589 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1590 NVME_DSM_MAX_RANGES);
1592 queue->limits.discard_alignment = 0;
1593 queue->limits.discard_granularity = size;
1595 /* If discard is already enabled, don't reset queue limits */
1596 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1599 blk_queue_max_discard_sectors(queue, ctrl->max_discard_sectors);
1600 blk_queue_max_discard_segments(queue, ctrl->max_discard_segments);
1602 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1603 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1606 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1608 return !uuid_is_null(&ids->uuid) ||
1609 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1610 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1613 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1615 return uuid_equal(&a->uuid, &b->uuid) &&
1616 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1617 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1621 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1622 u32 *phys_bs, u32 *io_opt)
1624 struct streams_directive_params s;
1627 if (!ctrl->nr_streams)
1630 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1634 ns->sws = le32_to_cpu(s.sws);
1635 ns->sgs = le16_to_cpu(s.sgs);
1638 *phys_bs = ns->sws * (1 << ns->lba_shift);
1640 *io_opt = *phys_bs * ns->sgs;
1646 static int nvme_configure_metadata(struct nvme_ns *ns, struct nvme_id_ns *id)
1648 struct nvme_ctrl *ctrl = ns->ctrl;
1651 * The PI implementation requires the metadata size to be equal to the
1652 * t10 pi tuple size.
1654 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1655 if (ns->ms == sizeof(struct t10_pi_tuple))
1656 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1660 ns->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1661 if (!ns->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1663 if (ctrl->ops->flags & NVME_F_FABRICS) {
1665 * The NVMe over Fabrics specification only supports metadata as
1666 * part of the extended data LBA. We rely on HCA/HBA support to
1667 * remap the separate metadata buffer from the block layer.
1669 if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
1671 if (ctrl->max_integrity_segments)
1673 (NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1676 * For PCIe controllers, we can't easily remap the separate
1677 * metadata buffer from the block layer and thus require a
1678 * separate metadata buffer for block layer metadata/PI support.
1679 * We allow extended LBAs for the passthrough interface, though.
1681 if (id->flbas & NVME_NS_FLBAS_META_EXT)
1682 ns->features |= NVME_NS_EXT_LBAS;
1684 ns->features |= NVME_NS_METADATA_SUPPORTED;
1690 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1691 struct request_queue *q)
1693 bool vwc = ctrl->vwc & NVME_CTRL_VWC_PRESENT;
1695 if (ctrl->max_hw_sectors) {
1697 (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
1699 max_segments = min_not_zero(max_segments, ctrl->max_segments);
1700 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1701 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1703 blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
1704 blk_queue_dma_alignment(q, 7);
1705 blk_queue_write_cache(q, vwc, vwc);
1708 static void nvme_update_disk_info(struct gendisk *disk,
1709 struct nvme_ns *ns, struct nvme_id_ns *id)
1711 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1712 unsigned short bs = 1 << ns->lba_shift;
1713 u32 atomic_bs, phys_bs, io_opt = 0;
1716 * The block layer can't support LBA sizes larger than the page size
1717 * yet, so catch this early and don't allow block I/O.
1719 if (ns->lba_shift > PAGE_SHIFT) {
1724 blk_integrity_unregister(disk);
1726 atomic_bs = phys_bs = bs;
1727 nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1728 if (id->nabo == 0) {
1730 * Bit 1 indicates whether NAWUPF is defined for this namespace
1731 * and whether it should be used instead of AWUPF. If NAWUPF ==
1732 * 0 then AWUPF must be used instead.
1734 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1735 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1737 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1740 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1741 /* NPWG = Namespace Preferred Write Granularity */
1742 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1743 /* NOWS = Namespace Optimal Write Size */
1744 io_opt = bs * (1 + le16_to_cpu(id->nows));
1747 blk_queue_logical_block_size(disk->queue, bs);
1749 * Linux filesystems assume writing a single physical block is
1750 * an atomic operation. Hence limit the physical block size to the
1751 * value of the Atomic Write Unit Power Fail parameter.
1753 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1754 blk_queue_io_min(disk->queue, phys_bs);
1755 blk_queue_io_opt(disk->queue, io_opt);
1758 * Register a metadata profile for PI, or the plain non-integrity NVMe
1759 * metadata masquerading as Type 0 if supported, otherwise reject block
1760 * I/O to namespaces with metadata except when the namespace supports
1761 * PI, as it can strip/insert in that case.
1764 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
1765 (ns->features & NVME_NS_METADATA_SUPPORTED))
1766 nvme_init_integrity(disk, ns->ms, ns->pi_type,
1767 ns->ctrl->max_integrity_segments);
1768 else if (!nvme_ns_has_pi(ns))
1772 set_capacity_and_notify(disk, capacity);
1774 nvme_config_discard(disk, ns);
1775 blk_queue_max_write_zeroes_sectors(disk->queue,
1776 ns->ctrl->max_zeroes_sectors);
1778 set_disk_ro(disk, (id->nsattr & NVME_NS_ATTR_RO) ||
1779 test_bit(NVME_NS_FORCE_RO, &ns->flags));
1782 static inline bool nvme_first_scan(struct gendisk *disk)
1784 /* nvme_alloc_ns() scans the disk prior to adding it */
1785 return !(disk->flags & GENHD_FL_UP);
1788 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id)
1790 struct nvme_ctrl *ctrl = ns->ctrl;
1793 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1794 is_power_of_2(ctrl->max_hw_sectors))
1795 iob = ctrl->max_hw_sectors;
1797 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
1802 if (!is_power_of_2(iob)) {
1803 if (nvme_first_scan(ns->disk))
1804 pr_warn("%s: ignoring unaligned IO boundary:%u\n",
1805 ns->disk->disk_name, iob);
1809 if (blk_queue_is_zoned(ns->disk->queue)) {
1810 if (nvme_first_scan(ns->disk))
1811 pr_warn("%s: ignoring zoned namespace IO boundary\n",
1812 ns->disk->disk_name);
1816 blk_queue_chunk_sectors(ns->queue, iob);
1819 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_id_ns *id)
1821 unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
1824 blk_mq_freeze_queue(ns->disk->queue);
1825 ns->lba_shift = id->lbaf[lbaf].ds;
1826 nvme_set_queue_limits(ns->ctrl, ns->queue);
1828 ret = nvme_configure_metadata(ns, id);
1831 nvme_set_chunk_sectors(ns, id);
1832 nvme_update_disk_info(ns->disk, ns, id);
1834 if (ns->head->ids.csi == NVME_CSI_ZNS) {
1835 ret = nvme_update_zone_info(ns, lbaf);
1840 blk_mq_unfreeze_queue(ns->disk->queue);
1842 if (blk_queue_is_zoned(ns->queue)) {
1843 ret = nvme_revalidate_zones(ns);
1844 if (ret && !nvme_first_scan(ns->disk))
1848 if (nvme_ns_head_multipath(ns->head)) {
1849 blk_mq_freeze_queue(ns->head->disk->queue);
1850 nvme_update_disk_info(ns->head->disk, ns, id);
1851 blk_stack_limits(&ns->head->disk->queue->limits,
1852 &ns->queue->limits, 0);
1853 blk_queue_update_readahead(ns->head->disk->queue);
1854 blk_mq_unfreeze_queue(ns->head->disk->queue);
1859 blk_mq_unfreeze_queue(ns->disk->queue);
1862 * If probing fails due an unsupported feature, hide the block device,
1863 * but still allow other access.
1865 if (ret == -ENODEV) {
1866 ns->disk->flags |= GENHD_FL_HIDDEN;
1872 static char nvme_pr_type(enum pr_type type)
1875 case PR_WRITE_EXCLUSIVE:
1877 case PR_EXCLUSIVE_ACCESS:
1879 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1881 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1883 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1885 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1892 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1893 u64 key, u64 sa_key, u8 op)
1895 struct nvme_ns_head *head = NULL;
1897 struct nvme_command c;
1899 u8 data[16] = { 0, };
1901 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1903 return -EWOULDBLOCK;
1905 put_unaligned_le64(key, &data[0]);
1906 put_unaligned_le64(sa_key, &data[8]);
1908 memset(&c, 0, sizeof(c));
1909 c.common.opcode = op;
1910 c.common.nsid = cpu_to_le32(ns->head->ns_id);
1911 c.common.cdw10 = cpu_to_le32(cdw10);
1913 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1914 nvme_put_ns_from_disk(head, srcu_idx);
1918 static int nvme_pr_register(struct block_device *bdev, u64 old,
1919 u64 new, unsigned flags)
1923 if (flags & ~PR_FL_IGNORE_KEY)
1926 cdw10 = old ? 2 : 0;
1927 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1928 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1929 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1932 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1933 enum pr_type type, unsigned flags)
1937 if (flags & ~PR_FL_IGNORE_KEY)
1940 cdw10 = nvme_pr_type(type) << 8;
1941 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1942 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1945 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1946 enum pr_type type, bool abort)
1948 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1950 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1953 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1955 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1957 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1960 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1962 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
1964 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1967 const struct pr_ops nvme_pr_ops = {
1968 .pr_register = nvme_pr_register,
1969 .pr_reserve = nvme_pr_reserve,
1970 .pr_release = nvme_pr_release,
1971 .pr_preempt = nvme_pr_preempt,
1972 .pr_clear = nvme_pr_clear,
1975 #ifdef CONFIG_BLK_SED_OPAL
1976 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1979 struct nvme_ctrl *ctrl = data;
1980 struct nvme_command cmd;
1982 memset(&cmd, 0, sizeof(cmd));
1984 cmd.common.opcode = nvme_admin_security_send;
1986 cmd.common.opcode = nvme_admin_security_recv;
1987 cmd.common.nsid = 0;
1988 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1989 cmd.common.cdw11 = cpu_to_le32(len);
1991 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 0,
1992 NVME_QID_ANY, 1, 0, false);
1994 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1995 #endif /* CONFIG_BLK_SED_OPAL */
1997 static const struct block_device_operations nvme_bdev_ops = {
1998 .owner = THIS_MODULE,
1999 .ioctl = nvme_ioctl,
2001 .release = nvme_release,
2002 .getgeo = nvme_getgeo,
2003 .report_zones = nvme_report_zones,
2004 .pr_ops = &nvme_pr_ops,
2007 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2009 unsigned long timeout =
2010 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2011 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2014 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2017 if ((csts & NVME_CSTS_RDY) == bit)
2020 usleep_range(1000, 2000);
2021 if (fatal_signal_pending(current))
2023 if (time_after(jiffies, timeout)) {
2024 dev_err(ctrl->device,
2025 "Device not ready; aborting %s, CSTS=0x%x\n",
2026 enabled ? "initialisation" : "reset", csts);
2035 * If the device has been passed off to us in an enabled state, just clear
2036 * the enabled bit. The spec says we should set the 'shutdown notification
2037 * bits', but doing so may cause the device to complete commands to the
2038 * admin queue ... and we don't know what memory that might be pointing at!
2040 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2044 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2045 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2047 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2051 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2052 msleep(NVME_QUIRK_DELAY_AMOUNT);
2054 return nvme_wait_ready(ctrl, ctrl->cap, false);
2056 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2058 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2060 unsigned dev_page_min;
2063 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2065 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2068 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2070 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2071 dev_err(ctrl->device,
2072 "Minimum device page size %u too large for host (%u)\n",
2073 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2077 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2078 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2080 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2081 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2082 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2083 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2084 ctrl->ctrl_config |= NVME_CC_ENABLE;
2086 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2089 return nvme_wait_ready(ctrl, ctrl->cap, true);
2091 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2093 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2095 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2099 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2100 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2102 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2106 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2107 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2111 if (fatal_signal_pending(current))
2113 if (time_after(jiffies, timeout)) {
2114 dev_err(ctrl->device,
2115 "Device shutdown incomplete; abort shutdown\n");
2122 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2124 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2129 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2132 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2133 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2136 dev_warn_once(ctrl->device,
2137 "could not set timestamp (%d)\n", ret);
2141 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2143 struct nvme_feat_host_behavior *host;
2146 /* Don't bother enabling the feature if retry delay is not reported */
2150 host = kzalloc(sizeof(*host), GFP_KERNEL);
2154 host->acre = NVME_ENABLE_ACRE;
2155 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2156 host, sizeof(*host), NULL);
2162 * APST (Autonomous Power State Transition) lets us program a table of power
2163 * state transitions that the controller will perform automatically.
2164 * We configure it with a simple heuristic: we are willing to spend at most 2%
2165 * of the time transitioning between power states. Therefore, when running in
2166 * any given state, we will enter the next lower-power non-operational state
2167 * after waiting 50 * (enlat + exlat) microseconds, as long as that state's exit
2168 * latency is under the requested maximum latency.
2170 * We will not autonomously enter any non-operational state for which the total
2171 * latency exceeds ps_max_latency_us.
2173 * Users can set ps_max_latency_us to zero to turn off APST.
2175 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2177 struct nvme_feat_auto_pst *table;
2186 * If APST isn't supported or if we haven't been initialized yet,
2187 * then don't do anything.
2192 if (ctrl->npss > 31) {
2193 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2197 table = kzalloc(sizeof(*table), GFP_KERNEL);
2201 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2202 /* Turn off APST. */
2203 dev_dbg(ctrl->device, "APST disabled\n");
2208 * Walk through all states from lowest- to highest-power.
2209 * According to the spec, lower-numbered states use more power. NPSS,
2210 * despite the name, is the index of the lowest-power state, not the
2213 for (state = (int)ctrl->npss; state >= 0; state--) {
2214 u64 total_latency_us, exit_latency_us, transition_ms;
2217 table->entries[state] = target;
2220 * Don't allow transitions to the deepest state if it's quirked
2223 if (state == ctrl->npss &&
2224 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2228 * Is this state a useful non-operational state for higher-power
2229 * states to autonomously transition to?
2231 if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
2234 exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2235 if (exit_latency_us > ctrl->ps_max_latency_us)
2238 total_latency_us = exit_latency_us +
2239 le32_to_cpu(ctrl->psd[state].entry_lat);
2242 * This state is good. Use it as the APST idle target for
2243 * higher power states.
2245 transition_ms = total_latency_us + 19;
2246 do_div(transition_ms, 20);
2247 if (transition_ms > (1 << 24) - 1)
2248 transition_ms = (1 << 24) - 1;
2250 target = cpu_to_le64((state << 3) | (transition_ms << 8));
2253 if (total_latency_us > max_lat_us)
2254 max_lat_us = total_latency_us;
2258 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2260 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2261 max_ps, max_lat_us, (int)sizeof(*table), table);
2265 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2266 table, sizeof(*table), NULL);
2268 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2273 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2275 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2279 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2280 case PM_QOS_LATENCY_ANY:
2288 if (ctrl->ps_max_latency_us != latency) {
2289 ctrl->ps_max_latency_us = latency;
2290 if (ctrl->state == NVME_CTRL_LIVE)
2291 nvme_configure_apst(ctrl);
2295 struct nvme_core_quirk_entry {
2297 * NVMe model and firmware strings are padded with spaces. For
2298 * simplicity, strings in the quirk table are padded with NULLs
2304 unsigned long quirks;
2307 static const struct nvme_core_quirk_entry core_quirks[] = {
2310 * This Toshiba device seems to die using any APST states. See:
2311 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2314 .mn = "THNSF5256GPUK TOSHIBA",
2315 .quirks = NVME_QUIRK_NO_APST,
2319 * This LiteON CL1-3D*-Q11 firmware version has a race
2320 * condition associated with actions related to suspend to idle
2321 * LiteON has resolved the problem in future firmware
2325 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2329 /* match is null-terminated but idstr is space-padded. */
2330 static bool string_matches(const char *idstr, const char *match, size_t len)
2337 matchlen = strlen(match);
2338 WARN_ON_ONCE(matchlen > len);
2340 if (memcmp(idstr, match, matchlen))
2343 for (; matchlen < len; matchlen++)
2344 if (idstr[matchlen] != ' ')
2350 static bool quirk_matches(const struct nvme_id_ctrl *id,
2351 const struct nvme_core_quirk_entry *q)
2353 return q->vid == le16_to_cpu(id->vid) &&
2354 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2355 string_matches(id->fr, q->fr, sizeof(id->fr));
2358 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2359 struct nvme_id_ctrl *id)
2364 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2365 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2366 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2367 strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2371 if (ctrl->vs >= NVME_VS(1, 2, 1))
2372 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2375 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2376 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2377 "nqn.2014.08.org.nvmexpress:%04x%04x",
2378 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2379 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2380 off += sizeof(id->sn);
2381 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2382 off += sizeof(id->mn);
2383 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2386 static void nvme_release_subsystem(struct device *dev)
2388 struct nvme_subsystem *subsys =
2389 container_of(dev, struct nvme_subsystem, dev);
2391 if (subsys->instance >= 0)
2392 ida_simple_remove(&nvme_instance_ida, subsys->instance);
2396 static void nvme_destroy_subsystem(struct kref *ref)
2398 struct nvme_subsystem *subsys =
2399 container_of(ref, struct nvme_subsystem, ref);
2401 mutex_lock(&nvme_subsystems_lock);
2402 list_del(&subsys->entry);
2403 mutex_unlock(&nvme_subsystems_lock);
2405 ida_destroy(&subsys->ns_ida);
2406 device_del(&subsys->dev);
2407 put_device(&subsys->dev);
2410 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2412 kref_put(&subsys->ref, nvme_destroy_subsystem);
2415 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2417 struct nvme_subsystem *subsys;
2419 lockdep_assert_held(&nvme_subsystems_lock);
2422 * Fail matches for discovery subsystems. This results
2423 * in each discovery controller bound to a unique subsystem.
2424 * This avoids issues with validating controller values
2425 * that can only be true when there is a single unique subsystem.
2426 * There may be multiple and completely independent entities
2427 * that provide discovery controllers.
2429 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2432 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2433 if (strcmp(subsys->subnqn, subsysnqn))
2435 if (!kref_get_unless_zero(&subsys->ref))
2443 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2444 struct device_attribute subsys_attr_##_name = \
2445 __ATTR(_name, _mode, _show, NULL)
2447 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2448 struct device_attribute *attr,
2451 struct nvme_subsystem *subsys =
2452 container_of(dev, struct nvme_subsystem, dev);
2454 return sysfs_emit(buf, "%s\n", subsys->subnqn);
2456 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2458 #define nvme_subsys_show_str_function(field) \
2459 static ssize_t subsys_##field##_show(struct device *dev, \
2460 struct device_attribute *attr, char *buf) \
2462 struct nvme_subsystem *subsys = \
2463 container_of(dev, struct nvme_subsystem, dev); \
2464 return sysfs_emit(buf, "%.*s\n", \
2465 (int)sizeof(subsys->field), subsys->field); \
2467 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2469 nvme_subsys_show_str_function(model);
2470 nvme_subsys_show_str_function(serial);
2471 nvme_subsys_show_str_function(firmware_rev);
2473 static struct attribute *nvme_subsys_attrs[] = {
2474 &subsys_attr_model.attr,
2475 &subsys_attr_serial.attr,
2476 &subsys_attr_firmware_rev.attr,
2477 &subsys_attr_subsysnqn.attr,
2478 #ifdef CONFIG_NVME_MULTIPATH
2479 &subsys_attr_iopolicy.attr,
2484 static const struct attribute_group nvme_subsys_attrs_group = {
2485 .attrs = nvme_subsys_attrs,
2488 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2489 &nvme_subsys_attrs_group,
2493 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
2495 return ctrl->opts && ctrl->opts->discovery_nqn;
2498 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2499 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2501 struct nvme_ctrl *tmp;
2503 lockdep_assert_held(&nvme_subsystems_lock);
2505 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2506 if (nvme_state_terminal(tmp))
2509 if (tmp->cntlid == ctrl->cntlid) {
2510 dev_err(ctrl->device,
2511 "Duplicate cntlid %u with %s, rejecting\n",
2512 ctrl->cntlid, dev_name(tmp->device));
2516 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2517 nvme_discovery_ctrl(ctrl))
2520 dev_err(ctrl->device,
2521 "Subsystem does not support multiple controllers\n");
2528 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2530 struct nvme_subsystem *subsys, *found;
2533 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2537 subsys->instance = -1;
2538 mutex_init(&subsys->lock);
2539 kref_init(&subsys->ref);
2540 INIT_LIST_HEAD(&subsys->ctrls);
2541 INIT_LIST_HEAD(&subsys->nsheads);
2542 nvme_init_subnqn(subsys, ctrl, id);
2543 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2544 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2545 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2546 subsys->vendor_id = le16_to_cpu(id->vid);
2547 subsys->cmic = id->cmic;
2548 subsys->awupf = le16_to_cpu(id->awupf);
2549 #ifdef CONFIG_NVME_MULTIPATH
2550 subsys->iopolicy = NVME_IOPOLICY_NUMA;
2553 subsys->dev.class = nvme_subsys_class;
2554 subsys->dev.release = nvme_release_subsystem;
2555 subsys->dev.groups = nvme_subsys_attrs_groups;
2556 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2557 device_initialize(&subsys->dev);
2559 mutex_lock(&nvme_subsystems_lock);
2560 found = __nvme_find_get_subsystem(subsys->subnqn);
2562 put_device(&subsys->dev);
2565 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2567 goto out_put_subsystem;
2570 ret = device_add(&subsys->dev);
2572 dev_err(ctrl->device,
2573 "failed to register subsystem device.\n");
2574 put_device(&subsys->dev);
2577 ida_init(&subsys->ns_ida);
2578 list_add_tail(&subsys->entry, &nvme_subsystems);
2581 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2582 dev_name(ctrl->device));
2584 dev_err(ctrl->device,
2585 "failed to create sysfs link from subsystem.\n");
2586 goto out_put_subsystem;
2590 subsys->instance = ctrl->instance;
2591 ctrl->subsys = subsys;
2592 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2593 mutex_unlock(&nvme_subsystems_lock);
2597 nvme_put_subsystem(subsys);
2599 mutex_unlock(&nvme_subsystems_lock);
2603 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2604 void *log, size_t size, u64 offset)
2606 struct nvme_command c = { };
2607 u32 dwlen = nvme_bytes_to_numd(size);
2609 c.get_log_page.opcode = nvme_admin_get_log_page;
2610 c.get_log_page.nsid = cpu_to_le32(nsid);
2611 c.get_log_page.lid = log_page;
2612 c.get_log_page.lsp = lsp;
2613 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2614 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2615 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2616 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2617 c.get_log_page.csi = csi;
2619 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2622 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
2623 struct nvme_effects_log **log)
2625 struct nvme_effects_log *cel = xa_load(&ctrl->cels, csi);
2631 cel = kzalloc(sizeof(*cel), GFP_KERNEL);
2635 ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
2636 cel, sizeof(*cel), 0);
2642 xa_store(&ctrl->cels, csi, cel, GFP_KERNEL);
2648 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
2650 u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
2652 if (check_shl_overflow(1U, units + page_shift - 9, &val))
2657 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
2659 struct nvme_command c = { };
2660 struct nvme_id_ctrl_nvm *id;
2663 if (ctrl->oncs & NVME_CTRL_ONCS_DSM) {
2664 ctrl->max_discard_sectors = UINT_MAX;
2665 ctrl->max_discard_segments = NVME_DSM_MAX_RANGES;
2667 ctrl->max_discard_sectors = 0;
2668 ctrl->max_discard_segments = 0;
2672 * Even though NVMe spec explicitly states that MDTS is not applicable
2673 * to the write-zeroes, we are cautious and limit the size to the
2674 * controllers max_hw_sectors value, which is based on the MDTS field
2675 * and possibly other limiting factors.
2677 if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
2678 !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
2679 ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
2681 ctrl->max_zeroes_sectors = 0;
2683 if (nvme_ctrl_limited_cns(ctrl))
2686 id = kzalloc(sizeof(*id), GFP_KERNEL);
2690 c.identify.opcode = nvme_admin_identify;
2691 c.identify.cns = NVME_ID_CNS_CS_CTRL;
2692 c.identify.csi = NVME_CSI_NVM;
2694 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
2699 ctrl->max_discard_segments = id->dmrl;
2701 ctrl->max_discard_sectors = le32_to_cpu(id->dmrsl);
2703 ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
2710 static int nvme_init_identify(struct nvme_ctrl *ctrl)
2712 struct nvme_id_ctrl *id;
2714 bool prev_apst_enabled;
2717 ret = nvme_identify_ctrl(ctrl, &id);
2719 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2723 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2724 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
2729 if (!(ctrl->ops->flags & NVME_F_FABRICS))
2730 ctrl->cntlid = le16_to_cpu(id->cntlid);
2732 if (!ctrl->identified) {
2735 ret = nvme_init_subsystem(ctrl, id);
2740 * Check for quirks. Quirk can depend on firmware version,
2741 * so, in principle, the set of quirks present can change
2742 * across a reset. As a possible future enhancement, we
2743 * could re-scan for quirks every time we reinitialize
2744 * the device, but we'd have to make sure that the driver
2745 * behaves intelligently if the quirks change.
2747 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2748 if (quirk_matches(id, &core_quirks[i]))
2749 ctrl->quirks |= core_quirks[i].quirks;
2753 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2754 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2755 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2758 ctrl->crdt[0] = le16_to_cpu(id->crdt1);
2759 ctrl->crdt[1] = le16_to_cpu(id->crdt2);
2760 ctrl->crdt[2] = le16_to_cpu(id->crdt3);
2762 ctrl->oacs = le16_to_cpu(id->oacs);
2763 ctrl->oncs = le16_to_cpu(id->oncs);
2764 ctrl->mtfa = le16_to_cpu(id->mtfa);
2765 ctrl->oaes = le32_to_cpu(id->oaes);
2766 ctrl->wctemp = le16_to_cpu(id->wctemp);
2767 ctrl->cctemp = le16_to_cpu(id->cctemp);
2769 atomic_set(&ctrl->abort_limit, id->acl + 1);
2770 ctrl->vwc = id->vwc;
2772 max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
2774 max_hw_sectors = UINT_MAX;
2775 ctrl->max_hw_sectors =
2776 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2778 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2779 ctrl->sgls = le32_to_cpu(id->sgls);
2780 ctrl->kas = le16_to_cpu(id->kas);
2781 ctrl->max_namespaces = le32_to_cpu(id->mnan);
2782 ctrl->ctratt = le32_to_cpu(id->ctratt);
2786 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
2788 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2789 shutdown_timeout, 60);
2791 if (ctrl->shutdown_timeout != shutdown_timeout)
2792 dev_info(ctrl->device,
2793 "Shutdown timeout set to %u seconds\n",
2794 ctrl->shutdown_timeout);
2796 ctrl->shutdown_timeout = shutdown_timeout;
2798 ctrl->npss = id->npss;
2799 ctrl->apsta = id->apsta;
2800 prev_apst_enabled = ctrl->apst_enabled;
2801 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2802 if (force_apst && id->apsta) {
2803 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2804 ctrl->apst_enabled = true;
2806 ctrl->apst_enabled = false;
2809 ctrl->apst_enabled = id->apsta;
2811 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2813 if (ctrl->ops->flags & NVME_F_FABRICS) {
2814 ctrl->icdoff = le16_to_cpu(id->icdoff);
2815 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2816 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2817 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2820 * In fabrics we need to verify the cntlid matches the
2823 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2824 dev_err(ctrl->device,
2825 "Mismatching cntlid: Connect %u vs Identify "
2827 ctrl->cntlid, le16_to_cpu(id->cntlid));
2832 if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
2833 dev_err(ctrl->device,
2834 "keep-alive support is mandatory for fabrics\n");
2839 ctrl->hmpre = le32_to_cpu(id->hmpre);
2840 ctrl->hmmin = le32_to_cpu(id->hmmin);
2841 ctrl->hmminds = le32_to_cpu(id->hmminds);
2842 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2845 ret = nvme_mpath_init(ctrl, id);
2849 if (ctrl->apst_enabled && !prev_apst_enabled)
2850 dev_pm_qos_expose_latency_tolerance(ctrl->device);
2851 else if (!ctrl->apst_enabled && prev_apst_enabled)
2852 dev_pm_qos_hide_latency_tolerance(ctrl->device);
2860 * Initialize the cached copies of the Identify data and various controller
2861 * register in our nvme_ctrl structure. This should be called as soon as
2862 * the admin queue is fully up and running.
2864 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl)
2868 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
2870 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
2874 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
2876 if (ctrl->vs >= NVME_VS(1, 1, 0))
2877 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
2879 ret = nvme_init_identify(ctrl);
2883 ret = nvme_init_non_mdts_limits(ctrl);
2887 ret = nvme_configure_apst(ctrl);
2891 ret = nvme_configure_timestamp(ctrl);
2895 ret = nvme_configure_directives(ctrl);
2899 ret = nvme_configure_acre(ctrl);
2903 if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
2904 ret = nvme_hwmon_init(ctrl);
2909 ctrl->identified = true;
2913 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
2915 static int nvme_dev_open(struct inode *inode, struct file *file)
2917 struct nvme_ctrl *ctrl =
2918 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
2920 switch (ctrl->state) {
2921 case NVME_CTRL_LIVE:
2924 return -EWOULDBLOCK;
2927 nvme_get_ctrl(ctrl);
2928 if (!try_module_get(ctrl->ops->module)) {
2929 nvme_put_ctrl(ctrl);
2933 file->private_data = ctrl;
2937 static int nvme_dev_release(struct inode *inode, struct file *file)
2939 struct nvme_ctrl *ctrl =
2940 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
2942 module_put(ctrl->ops->module);
2943 nvme_put_ctrl(ctrl);
2947 static const struct file_operations nvme_dev_fops = {
2948 .owner = THIS_MODULE,
2949 .open = nvme_dev_open,
2950 .release = nvme_dev_release,
2951 .unlocked_ioctl = nvme_dev_ioctl,
2952 .compat_ioctl = compat_ptr_ioctl,
2955 static ssize_t nvme_sysfs_reset(struct device *dev,
2956 struct device_attribute *attr, const char *buf,
2959 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2962 ret = nvme_reset_ctrl_sync(ctrl);
2967 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2969 static ssize_t nvme_sysfs_rescan(struct device *dev,
2970 struct device_attribute *attr, const char *buf,
2973 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2975 nvme_queue_scan(ctrl);
2978 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2980 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
2982 struct gendisk *disk = dev_to_disk(dev);
2984 if (disk->fops == &nvme_bdev_ops)
2985 return nvme_get_ns_from_dev(dev)->head;
2987 return disk->private_data;
2990 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2993 struct nvme_ns_head *head = dev_to_ns_head(dev);
2994 struct nvme_ns_ids *ids = &head->ids;
2995 struct nvme_subsystem *subsys = head->subsys;
2996 int serial_len = sizeof(subsys->serial);
2997 int model_len = sizeof(subsys->model);
2999 if (!uuid_is_null(&ids->uuid))
3000 return sysfs_emit(buf, "uuid.%pU\n", &ids->uuid);
3002 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3003 return sysfs_emit(buf, "eui.%16phN\n", ids->nguid);
3005 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3006 return sysfs_emit(buf, "eui.%8phN\n", ids->eui64);
3008 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3009 subsys->serial[serial_len - 1] == '\0'))
3011 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3012 subsys->model[model_len - 1] == '\0'))
3015 return sysfs_emit(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3016 serial_len, subsys->serial, model_len, subsys->model,
3019 static DEVICE_ATTR_RO(wwid);
3021 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3024 return sysfs_emit(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3026 static DEVICE_ATTR_RO(nguid);
3028 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3031 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3033 /* For backward compatibility expose the NGUID to userspace if
3034 * we have no UUID set
3036 if (uuid_is_null(&ids->uuid)) {
3037 printk_ratelimited(KERN_WARNING
3038 "No UUID available providing old NGUID\n");
3039 return sysfs_emit(buf, "%pU\n", ids->nguid);
3041 return sysfs_emit(buf, "%pU\n", &ids->uuid);
3043 static DEVICE_ATTR_RO(uuid);
3045 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3048 return sysfs_emit(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3050 static DEVICE_ATTR_RO(eui);
3052 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3055 return sysfs_emit(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3057 static DEVICE_ATTR_RO(nsid);
3059 static struct attribute *nvme_ns_id_attrs[] = {
3060 &dev_attr_wwid.attr,
3061 &dev_attr_uuid.attr,
3062 &dev_attr_nguid.attr,
3064 &dev_attr_nsid.attr,
3065 #ifdef CONFIG_NVME_MULTIPATH
3066 &dev_attr_ana_grpid.attr,
3067 &dev_attr_ana_state.attr,
3072 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3073 struct attribute *a, int n)
3075 struct device *dev = container_of(kobj, struct device, kobj);
3076 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3078 if (a == &dev_attr_uuid.attr) {
3079 if (uuid_is_null(&ids->uuid) &&
3080 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3083 if (a == &dev_attr_nguid.attr) {
3084 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3087 if (a == &dev_attr_eui.attr) {
3088 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3091 #ifdef CONFIG_NVME_MULTIPATH
3092 if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3093 if (dev_to_disk(dev)->fops != &nvme_bdev_ops) /* per-path attr */
3095 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3102 static const struct attribute_group nvme_ns_id_attr_group = {
3103 .attrs = nvme_ns_id_attrs,
3104 .is_visible = nvme_ns_id_attrs_are_visible,
3107 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3108 &nvme_ns_id_attr_group,
3110 &nvme_nvm_attr_group,
3115 #define nvme_show_str_function(field) \
3116 static ssize_t field##_show(struct device *dev, \
3117 struct device_attribute *attr, char *buf) \
3119 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3120 return sysfs_emit(buf, "%.*s\n", \
3121 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
3123 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3125 nvme_show_str_function(model);
3126 nvme_show_str_function(serial);
3127 nvme_show_str_function(firmware_rev);
3129 #define nvme_show_int_function(field) \
3130 static ssize_t field##_show(struct device *dev, \
3131 struct device_attribute *attr, char *buf) \
3133 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3134 return sysfs_emit(buf, "%d\n", ctrl->field); \
3136 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3138 nvme_show_int_function(cntlid);
3139 nvme_show_int_function(numa_node);
3140 nvme_show_int_function(queue_count);
3141 nvme_show_int_function(sqsize);
3142 nvme_show_int_function(kato);
3144 static ssize_t nvme_sysfs_delete(struct device *dev,
3145 struct device_attribute *attr, const char *buf,
3148 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3150 if (device_remove_file_self(dev, attr))
3151 nvme_delete_ctrl_sync(ctrl);
3154 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3156 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3157 struct device_attribute *attr,
3160 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3162 return sysfs_emit(buf, "%s\n", ctrl->ops->name);
3164 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3166 static ssize_t nvme_sysfs_show_state(struct device *dev,
3167 struct device_attribute *attr,
3170 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3171 static const char *const state_name[] = {
3172 [NVME_CTRL_NEW] = "new",
3173 [NVME_CTRL_LIVE] = "live",
3174 [NVME_CTRL_RESETTING] = "resetting",
3175 [NVME_CTRL_CONNECTING] = "connecting",
3176 [NVME_CTRL_DELETING] = "deleting",
3177 [NVME_CTRL_DELETING_NOIO]= "deleting (no IO)",
3178 [NVME_CTRL_DEAD] = "dead",
3181 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3182 state_name[ctrl->state])
3183 return sysfs_emit(buf, "%s\n", state_name[ctrl->state]);
3185 return sysfs_emit(buf, "unknown state\n");
3188 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3190 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3191 struct device_attribute *attr,
3194 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3196 return sysfs_emit(buf, "%s\n", ctrl->subsys->subnqn);
3198 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3200 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3201 struct device_attribute *attr,
3204 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3206 return sysfs_emit(buf, "%s\n", ctrl->opts->host->nqn);
3208 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3210 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3211 struct device_attribute *attr,
3214 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3216 return sysfs_emit(buf, "%pU\n", &ctrl->opts->host->id);
3218 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3220 static ssize_t nvme_sysfs_show_address(struct device *dev,
3221 struct device_attribute *attr,
3224 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3226 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3228 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3230 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev,
3231 struct device_attribute *attr, char *buf)
3233 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3234 struct nvmf_ctrl_options *opts = ctrl->opts;
3236 if (ctrl->opts->max_reconnects == -1)
3237 return sysfs_emit(buf, "off\n");
3238 return sysfs_emit(buf, "%d\n",
3239 opts->max_reconnects * opts->reconnect_delay);
3242 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev,
3243 struct device_attribute *attr, const char *buf, size_t count)
3245 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3246 struct nvmf_ctrl_options *opts = ctrl->opts;
3247 int ctrl_loss_tmo, err;
3249 err = kstrtoint(buf, 10, &ctrl_loss_tmo);
3253 if (ctrl_loss_tmo < 0)
3254 opts->max_reconnects = -1;
3256 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
3257 opts->reconnect_delay);
3260 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR,
3261 nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store);
3263 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev,
3264 struct device_attribute *attr, char *buf)
3266 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3268 if (ctrl->opts->reconnect_delay == -1)
3269 return sysfs_emit(buf, "off\n");
3270 return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay);
3273 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev,
3274 struct device_attribute *attr, const char *buf, size_t count)
3276 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3280 err = kstrtou32(buf, 10, &v);
3284 ctrl->opts->reconnect_delay = v;
3287 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR,
3288 nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store);
3290 static ssize_t nvme_ctrl_fast_io_fail_tmo_show(struct device *dev,
3291 struct device_attribute *attr, char *buf)
3293 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3295 if (ctrl->opts->fast_io_fail_tmo == -1)
3296 return sysfs_emit(buf, "off\n");
3297 return sysfs_emit(buf, "%d\n", ctrl->opts->fast_io_fail_tmo);
3300 static ssize_t nvme_ctrl_fast_io_fail_tmo_store(struct device *dev,
3301 struct device_attribute *attr, const char *buf, size_t count)
3303 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3304 struct nvmf_ctrl_options *opts = ctrl->opts;
3305 int fast_io_fail_tmo, err;
3307 err = kstrtoint(buf, 10, &fast_io_fail_tmo);
3311 if (fast_io_fail_tmo < 0)
3312 opts->fast_io_fail_tmo = -1;
3314 opts->fast_io_fail_tmo = fast_io_fail_tmo;
3317 static DEVICE_ATTR(fast_io_fail_tmo, S_IRUGO | S_IWUSR,
3318 nvme_ctrl_fast_io_fail_tmo_show, nvme_ctrl_fast_io_fail_tmo_store);
3320 static struct attribute *nvme_dev_attrs[] = {
3321 &dev_attr_reset_controller.attr,
3322 &dev_attr_rescan_controller.attr,
3323 &dev_attr_model.attr,
3324 &dev_attr_serial.attr,
3325 &dev_attr_firmware_rev.attr,
3326 &dev_attr_cntlid.attr,
3327 &dev_attr_delete_controller.attr,
3328 &dev_attr_transport.attr,
3329 &dev_attr_subsysnqn.attr,
3330 &dev_attr_address.attr,
3331 &dev_attr_state.attr,
3332 &dev_attr_numa_node.attr,
3333 &dev_attr_queue_count.attr,
3334 &dev_attr_sqsize.attr,
3335 &dev_attr_hostnqn.attr,
3336 &dev_attr_hostid.attr,
3337 &dev_attr_ctrl_loss_tmo.attr,
3338 &dev_attr_reconnect_delay.attr,
3339 &dev_attr_fast_io_fail_tmo.attr,
3340 &dev_attr_kato.attr,
3344 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3345 struct attribute *a, int n)
3347 struct device *dev = container_of(kobj, struct device, kobj);
3348 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3350 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3352 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3354 if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3356 if (a == &dev_attr_hostid.attr && !ctrl->opts)
3358 if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts)
3360 if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts)
3362 if (a == &dev_attr_fast_io_fail_tmo.attr && !ctrl->opts)
3368 static const struct attribute_group nvme_dev_attrs_group = {
3369 .attrs = nvme_dev_attrs,
3370 .is_visible = nvme_dev_attrs_are_visible,
3373 static const struct attribute_group *nvme_dev_attr_groups[] = {
3374 &nvme_dev_attrs_group,
3378 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3381 struct nvme_ns_head *h;
3383 lockdep_assert_held(&subsys->lock);
3385 list_for_each_entry(h, &subsys->nsheads, entry) {
3386 if (h->ns_id == nsid && nvme_tryget_ns_head(h))
3393 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3394 struct nvme_ns_head *new)
3396 struct nvme_ns_head *h;
3398 lockdep_assert_held(&subsys->lock);
3400 list_for_each_entry(h, &subsys->nsheads, entry) {
3401 if (nvme_ns_ids_valid(&new->ids) &&
3402 nvme_ns_ids_equal(&new->ids, &h->ids))
3409 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
3411 cdev_device_del(cdev, cdev_device);
3412 ida_simple_remove(&nvme_ns_chr_minor_ida, MINOR(cdev_device->devt));
3415 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
3416 const struct file_operations *fops, struct module *owner)
3420 minor = ida_simple_get(&nvme_ns_chr_minor_ida, 0, 0, GFP_KERNEL);
3423 cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
3424 cdev_device->class = nvme_ns_chr_class;
3425 device_initialize(cdev_device);
3426 cdev_init(cdev, fops);
3427 cdev->owner = owner;
3428 ret = cdev_device_add(cdev, cdev_device);
3430 ida_simple_remove(&nvme_ns_chr_minor_ida, minor);
3434 static int nvme_ns_chr_open(struct inode *inode, struct file *file)
3436 return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
3439 static int nvme_ns_chr_release(struct inode *inode, struct file *file)
3441 nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
3445 static const struct file_operations nvme_ns_chr_fops = {
3446 .owner = THIS_MODULE,
3447 .open = nvme_ns_chr_open,
3448 .release = nvme_ns_chr_release,
3449 .unlocked_ioctl = nvme_ns_chr_ioctl,
3450 .compat_ioctl = compat_ptr_ioctl,
3453 static int nvme_add_ns_cdev(struct nvme_ns *ns)
3457 ns->cdev_device.parent = ns->ctrl->device;
3458 ret = dev_set_name(&ns->cdev_device, "ng%dn%d",
3459 ns->ctrl->instance, ns->head->instance);
3462 ret = nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops,
3463 ns->ctrl->ops->module);
3465 kfree_const(ns->cdev_device.kobj.name);
3469 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3470 unsigned nsid, struct nvme_ns_ids *ids)
3472 struct nvme_ns_head *head;
3473 size_t size = sizeof(*head);
3476 #ifdef CONFIG_NVME_MULTIPATH
3477 size += num_possible_nodes() * sizeof(struct nvme_ns *);
3480 head = kzalloc(size, GFP_KERNEL);
3483 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3486 head->instance = ret;
3487 INIT_LIST_HEAD(&head->list);
3488 ret = init_srcu_struct(&head->srcu);
3490 goto out_ida_remove;
3491 head->subsys = ctrl->subsys;
3494 kref_init(&head->ref);
3496 ret = __nvme_check_ids(ctrl->subsys, head);
3498 dev_err(ctrl->device,
3499 "duplicate IDs for nsid %d\n", nsid);
3500 goto out_cleanup_srcu;
3503 if (head->ids.csi) {
3504 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3506 goto out_cleanup_srcu;
3508 head->effects = ctrl->effects;
3510 ret = nvme_mpath_alloc_disk(ctrl, head);
3512 goto out_cleanup_srcu;
3514 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3516 kref_get(&ctrl->subsys->ref);
3520 cleanup_srcu_struct(&head->srcu);
3522 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3527 ret = blk_status_to_errno(nvme_error_status(ret));
3528 return ERR_PTR(ret);
3531 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3532 struct nvme_ns_ids *ids, bool is_shared)
3534 struct nvme_ctrl *ctrl = ns->ctrl;
3535 struct nvme_ns_head *head = NULL;
3538 mutex_lock(&ctrl->subsys->lock);
3539 head = nvme_find_ns_head(ctrl->subsys, nsid);
3541 head = nvme_alloc_ns_head(ctrl, nsid, ids);
3543 ret = PTR_ERR(head);
3546 head->shared = is_shared;
3549 if (!is_shared || !head->shared) {
3550 dev_err(ctrl->device,
3551 "Duplicate unshared namespace %d\n", nsid);
3552 goto out_put_ns_head;
3554 if (!nvme_ns_ids_equal(&head->ids, ids)) {
3555 dev_err(ctrl->device,
3556 "IDs don't match for shared namespace %d\n",
3558 goto out_put_ns_head;
3562 list_add_tail_rcu(&ns->siblings, &head->list);
3564 mutex_unlock(&ctrl->subsys->lock);
3568 nvme_put_ns_head(head);
3570 mutex_unlock(&ctrl->subsys->lock);
3574 static int ns_cmp(void *priv, const struct list_head *a,
3575 const struct list_head *b)
3577 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3578 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3580 return nsa->head->ns_id - nsb->head->ns_id;
3583 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3585 struct nvme_ns *ns, *ret = NULL;
3587 down_read(&ctrl->namespaces_rwsem);
3588 list_for_each_entry(ns, &ctrl->namespaces, list) {
3589 if (ns->head->ns_id == nsid) {
3590 if (!nvme_get_ns(ns))
3595 if (ns->head->ns_id > nsid)
3598 up_read(&ctrl->namespaces_rwsem);
3601 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3603 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid,
3604 struct nvme_ns_ids *ids)
3607 struct gendisk *disk;
3608 struct nvme_id_ns *id;
3609 int node = ctrl->numa_node;
3611 if (nvme_identify_ns(ctrl, nsid, ids, &id))
3614 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3618 ns->queue = blk_mq_init_queue(ctrl->tagset);
3619 if (IS_ERR(ns->queue))
3622 if (ctrl->opts && ctrl->opts->data_digest)
3623 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, ns->queue);
3625 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3626 if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3627 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3629 ns->queue->queuedata = ns;
3631 kref_init(&ns->kref);
3633 if (nvme_init_ns_head(ns, nsid, ids, id->nmic & NVME_NS_NMIC_SHARED))
3634 goto out_free_queue;
3636 disk = alloc_disk_node(0, node);
3640 disk->fops = &nvme_bdev_ops;
3641 disk->private_data = ns;
3642 disk->queue = ns->queue;
3643 disk->flags = GENHD_FL_EXT_DEVT;
3645 * Without the multipath code enabled, multiple controller per
3646 * subsystems are visible as devices and thus we cannot use the
3647 * subsystem instance.
3649 if (!nvme_mpath_set_disk_name(ns, disk->disk_name, &disk->flags))
3650 sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
3651 ns->head->instance);
3654 if (nvme_update_ns_info(ns, id))
3657 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3658 if (nvme_nvm_register(ns, disk->disk_name, node)) {
3659 dev_warn(ctrl->device, "LightNVM init failure\n");
3664 down_write(&ctrl->namespaces_rwsem);
3665 list_add_tail(&ns->list, &ctrl->namespaces);
3666 up_write(&ctrl->namespaces_rwsem);
3668 nvme_get_ctrl(ctrl);
3670 device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups);
3671 if (!nvme_ns_head_multipath(ns->head))
3672 nvme_add_ns_cdev(ns);
3674 nvme_mpath_add_disk(ns, id);
3675 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3680 /* prevent double queue cleanup */
3681 ns->disk->queue = NULL;
3684 mutex_lock(&ctrl->subsys->lock);
3685 list_del_rcu(&ns->siblings);
3686 if (list_empty(&ns->head->list))
3687 list_del_init(&ns->head->entry);
3688 mutex_unlock(&ctrl->subsys->lock);
3689 nvme_put_ns_head(ns->head);
3691 blk_cleanup_queue(ns->queue);
3698 static void nvme_ns_remove(struct nvme_ns *ns)
3700 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3703 set_capacity(ns->disk, 0);
3704 nvme_fault_inject_fini(&ns->fault_inject);
3706 mutex_lock(&ns->ctrl->subsys->lock);
3707 list_del_rcu(&ns->siblings);
3708 if (list_empty(&ns->head->list))
3709 list_del_init(&ns->head->entry);
3710 mutex_unlock(&ns->ctrl->subsys->lock);
3712 synchronize_rcu(); /* guarantee not available in head->list */
3713 nvme_mpath_clear_current_path(ns);
3714 synchronize_srcu(&ns->head->srcu); /* wait for concurrent submissions */
3716 if (ns->disk->flags & GENHD_FL_UP) {
3717 if (!nvme_ns_head_multipath(ns->head))
3718 nvme_cdev_del(&ns->cdev, &ns->cdev_device);
3719 del_gendisk(ns->disk);
3720 blk_cleanup_queue(ns->queue);
3721 if (blk_get_integrity(ns->disk))
3722 blk_integrity_unregister(ns->disk);
3725 down_write(&ns->ctrl->namespaces_rwsem);
3726 list_del_init(&ns->list);
3727 up_write(&ns->ctrl->namespaces_rwsem);
3729 nvme_mpath_check_last_path(ns);
3733 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
3735 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
3743 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_ids *ids)
3745 struct nvme_id_ns *id;
3746 int ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3748 if (test_bit(NVME_NS_DEAD, &ns->flags))
3751 ret = nvme_identify_ns(ns->ctrl, ns->head->ns_id, ids, &id);
3755 ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3756 if (!nvme_ns_ids_equal(&ns->head->ids, ids)) {
3757 dev_err(ns->ctrl->device,
3758 "identifiers changed for nsid %d\n", ns->head->ns_id);
3762 ret = nvme_update_ns_info(ns, id);
3768 * Only remove the namespace if we got a fatal error back from the
3769 * device, otherwise ignore the error and just move on.
3771 * TODO: we should probably schedule a delayed retry here.
3773 if (ret > 0 && (ret & NVME_SC_DNR))
3777 static void nvme_validate_or_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3779 struct nvme_ns_ids ids = { };
3782 if (nvme_identify_ns_descs(ctrl, nsid, &ids))
3785 ns = nvme_find_get_ns(ctrl, nsid);
3787 nvme_validate_ns(ns, &ids);
3794 nvme_alloc_ns(ctrl, nsid, &ids);
3797 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
3798 dev_warn(ctrl->device,
3799 "nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
3803 if (!nvme_multi_css(ctrl)) {
3804 dev_warn(ctrl->device,
3805 "command set not reported for nsid: %d\n",
3809 nvme_alloc_ns(ctrl, nsid, &ids);
3812 dev_warn(ctrl->device, "unknown csi %u for nsid %u\n",
3818 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3821 struct nvme_ns *ns, *next;
3824 down_write(&ctrl->namespaces_rwsem);
3825 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3826 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
3827 list_move_tail(&ns->list, &rm_list);
3829 up_write(&ctrl->namespaces_rwsem);
3831 list_for_each_entry_safe(ns, next, &rm_list, list)
3836 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
3838 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
3843 if (nvme_ctrl_limited_cns(ctrl))
3846 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3851 struct nvme_command cmd = {
3852 .identify.opcode = nvme_admin_identify,
3853 .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST,
3854 .identify.nsid = cpu_to_le32(prev),
3857 ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
3858 NVME_IDENTIFY_DATA_SIZE);
3860 dev_warn(ctrl->device,
3861 "Identify NS List failed (status=0x%x)\n", ret);
3865 for (i = 0; i < nr_entries; i++) {
3866 u32 nsid = le32_to_cpu(ns_list[i]);
3868 if (!nsid) /* end of the list? */
3870 nvme_validate_or_alloc_ns(ctrl, nsid);
3871 while (++prev < nsid)
3872 nvme_ns_remove_by_nsid(ctrl, prev);
3876 nvme_remove_invalid_namespaces(ctrl, prev);
3882 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
3884 struct nvme_id_ctrl *id;
3887 if (nvme_identify_ctrl(ctrl, &id))
3889 nn = le32_to_cpu(id->nn);
3892 for (i = 1; i <= nn; i++)
3893 nvme_validate_or_alloc_ns(ctrl, i);
3895 nvme_remove_invalid_namespaces(ctrl, nn);
3898 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
3900 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
3904 log = kzalloc(log_size, GFP_KERNEL);
3909 * We need to read the log to clear the AEN, but we don't want to rely
3910 * on it for the changed namespace information as userspace could have
3911 * raced with us in reading the log page, which could cause us to miss
3914 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
3915 NVME_CSI_NVM, log, log_size, 0);
3917 dev_warn(ctrl->device,
3918 "reading changed ns log failed: %d\n", error);
3923 static void nvme_scan_work(struct work_struct *work)
3925 struct nvme_ctrl *ctrl =
3926 container_of(work, struct nvme_ctrl, scan_work);
3928 /* No tagset on a live ctrl means IO queues could not created */
3929 if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
3932 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
3933 dev_info(ctrl->device, "rescanning namespaces.\n");
3934 nvme_clear_changed_ns_log(ctrl);
3937 mutex_lock(&ctrl->scan_lock);
3938 if (nvme_scan_ns_list(ctrl) != 0)
3939 nvme_scan_ns_sequential(ctrl);
3940 mutex_unlock(&ctrl->scan_lock);
3942 down_write(&ctrl->namespaces_rwsem);
3943 list_sort(NULL, &ctrl->namespaces, ns_cmp);
3944 up_write(&ctrl->namespaces_rwsem);
3948 * This function iterates the namespace list unlocked to allow recovery from
3949 * controller failure. It is up to the caller to ensure the namespace list is
3950 * not modified by scan work while this function is executing.
3952 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3954 struct nvme_ns *ns, *next;
3958 * make sure to requeue I/O to all namespaces as these
3959 * might result from the scan itself and must complete
3960 * for the scan_work to make progress
3962 nvme_mpath_clear_ctrl_paths(ctrl);
3964 /* prevent racing with ns scanning */
3965 flush_work(&ctrl->scan_work);
3968 * The dead states indicates the controller was not gracefully
3969 * disconnected. In that case, we won't be able to flush any data while
3970 * removing the namespaces' disks; fail all the queues now to avoid
3971 * potentially having to clean up the failed sync later.
3973 if (ctrl->state == NVME_CTRL_DEAD)
3974 nvme_kill_queues(ctrl);
3976 /* this is a no-op when called from the controller reset handler */
3977 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
3979 down_write(&ctrl->namespaces_rwsem);
3980 list_splice_init(&ctrl->namespaces, &ns_list);
3981 up_write(&ctrl->namespaces_rwsem);
3983 list_for_each_entry_safe(ns, next, &ns_list, list)
3986 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
3988 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
3990 struct nvme_ctrl *ctrl =
3991 container_of(dev, struct nvme_ctrl, ctrl_device);
3992 struct nvmf_ctrl_options *opts = ctrl->opts;
3995 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4000 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4004 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4005 opts->trsvcid ?: "none");
4009 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4010 opts->host_traddr ?: "none");
4015 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4017 char *envp[2] = { NULL, NULL };
4018 u32 aen_result = ctrl->aen_result;
4020 ctrl->aen_result = 0;
4024 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4027 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4031 static void nvme_async_event_work(struct work_struct *work)
4033 struct nvme_ctrl *ctrl =
4034 container_of(work, struct nvme_ctrl, async_event_work);
4036 nvme_aen_uevent(ctrl);
4037 ctrl->ops->submit_async_event(ctrl);
4040 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4045 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4051 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4054 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4056 struct nvme_fw_slot_info_log *log;
4058 log = kmalloc(sizeof(*log), GFP_KERNEL);
4062 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4063 log, sizeof(*log), 0))
4064 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4068 static void nvme_fw_act_work(struct work_struct *work)
4070 struct nvme_ctrl *ctrl = container_of(work,
4071 struct nvme_ctrl, fw_act_work);
4072 unsigned long fw_act_timeout;
4075 fw_act_timeout = jiffies +
4076 msecs_to_jiffies(ctrl->mtfa * 100);
4078 fw_act_timeout = jiffies +
4079 msecs_to_jiffies(admin_timeout * 1000);
4081 nvme_stop_queues(ctrl);
4082 while (nvme_ctrl_pp_status(ctrl)) {
4083 if (time_after(jiffies, fw_act_timeout)) {
4084 dev_warn(ctrl->device,
4085 "Fw activation timeout, reset controller\n");
4086 nvme_try_sched_reset(ctrl);
4092 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4095 nvme_start_queues(ctrl);
4096 /* read FW slot information to clear the AER */
4097 nvme_get_fw_slot_info(ctrl);
4100 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4102 u32 aer_notice_type = (result & 0xff00) >> 8;
4104 trace_nvme_async_event(ctrl, aer_notice_type);
4106 switch (aer_notice_type) {
4107 case NVME_AER_NOTICE_NS_CHANGED:
4108 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4109 nvme_queue_scan(ctrl);
4111 case NVME_AER_NOTICE_FW_ACT_STARTING:
4113 * We are (ab)using the RESETTING state to prevent subsequent
4114 * recovery actions from interfering with the controller's
4115 * firmware activation.
4117 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4118 queue_work(nvme_wq, &ctrl->fw_act_work);
4120 #ifdef CONFIG_NVME_MULTIPATH
4121 case NVME_AER_NOTICE_ANA:
4122 if (!ctrl->ana_log_buf)
4124 queue_work(nvme_wq, &ctrl->ana_work);
4127 case NVME_AER_NOTICE_DISC_CHANGED:
4128 ctrl->aen_result = result;
4131 dev_warn(ctrl->device, "async event result %08x\n", result);
4135 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4136 volatile union nvme_result *res)
4138 u32 result = le32_to_cpu(res->u32);
4139 u32 aer_type = result & 0x07;
4141 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4145 case NVME_AER_NOTICE:
4146 nvme_handle_aen_notice(ctrl, result);
4148 case NVME_AER_ERROR:
4149 case NVME_AER_SMART:
4152 trace_nvme_async_event(ctrl, aer_type);
4153 ctrl->aen_result = result;
4158 queue_work(nvme_wq, &ctrl->async_event_work);
4160 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4162 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4164 nvme_mpath_stop(ctrl);
4165 nvme_stop_keep_alive(ctrl);
4166 nvme_stop_failfast_work(ctrl);
4167 flush_work(&ctrl->async_event_work);
4168 cancel_work_sync(&ctrl->fw_act_work);
4170 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4172 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4174 nvme_start_keep_alive(ctrl);
4176 nvme_enable_aen(ctrl);
4178 if (ctrl->queue_count > 1) {
4179 nvme_queue_scan(ctrl);
4180 nvme_start_queues(ctrl);
4183 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4185 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4187 nvme_hwmon_exit(ctrl);
4188 nvme_fault_inject_fini(&ctrl->fault_inject);
4189 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4190 cdev_device_del(&ctrl->cdev, ctrl->device);
4191 nvme_put_ctrl(ctrl);
4193 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4195 static void nvme_free_cels(struct nvme_ctrl *ctrl)
4197 struct nvme_effects_log *cel;
4200 xa_for_each(&ctrl->cels, i, cel) {
4201 xa_erase(&ctrl->cels, i);
4205 xa_destroy(&ctrl->cels);
4208 static void nvme_free_ctrl(struct device *dev)
4210 struct nvme_ctrl *ctrl =
4211 container_of(dev, struct nvme_ctrl, ctrl_device);
4212 struct nvme_subsystem *subsys = ctrl->subsys;
4214 if (!subsys || ctrl->instance != subsys->instance)
4215 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4217 nvme_free_cels(ctrl);
4218 nvme_mpath_uninit(ctrl);
4219 __free_page(ctrl->discard_page);
4222 mutex_lock(&nvme_subsystems_lock);
4223 list_del(&ctrl->subsys_entry);
4224 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4225 mutex_unlock(&nvme_subsystems_lock);
4228 ctrl->ops->free_ctrl(ctrl);
4231 nvme_put_subsystem(subsys);
4235 * Initialize a NVMe controller structures. This needs to be called during
4236 * earliest initialization so that we have the initialized structured around
4239 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4240 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4244 ctrl->state = NVME_CTRL_NEW;
4245 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
4246 spin_lock_init(&ctrl->lock);
4247 mutex_init(&ctrl->scan_lock);
4248 INIT_LIST_HEAD(&ctrl->namespaces);
4249 xa_init(&ctrl->cels);
4250 init_rwsem(&ctrl->namespaces_rwsem);
4253 ctrl->quirks = quirks;
4254 ctrl->numa_node = NUMA_NO_NODE;
4255 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4256 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4257 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4258 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4259 init_waitqueue_head(&ctrl->state_wq);
4261 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4262 INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
4263 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4264 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4266 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4268 ctrl->discard_page = alloc_page(GFP_KERNEL);
4269 if (!ctrl->discard_page) {
4274 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4277 ctrl->instance = ret;
4279 device_initialize(&ctrl->ctrl_device);
4280 ctrl->device = &ctrl->ctrl_device;
4281 ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
4283 ctrl->device->class = nvme_class;
4284 ctrl->device->parent = ctrl->dev;
4285 ctrl->device->groups = nvme_dev_attr_groups;
4286 ctrl->device->release = nvme_free_ctrl;
4287 dev_set_drvdata(ctrl->device, ctrl);
4288 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4290 goto out_release_instance;
4292 nvme_get_ctrl(ctrl);
4293 cdev_init(&ctrl->cdev, &nvme_dev_fops);
4294 ctrl->cdev.owner = ops->module;
4295 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4300 * Initialize latency tolerance controls. The sysfs files won't
4301 * be visible to userspace unless the device actually supports APST.
4303 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4304 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4305 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4307 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4311 nvme_put_ctrl(ctrl);
4312 kfree_const(ctrl->device->kobj.name);
4313 out_release_instance:
4314 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4316 if (ctrl->discard_page)
4317 __free_page(ctrl->discard_page);
4320 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4323 * nvme_kill_queues(): Ends all namespace queues
4324 * @ctrl: the dead controller that needs to end
4326 * Call this function when the driver determines it is unable to get the
4327 * controller in a state capable of servicing IO.
4329 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4333 down_read(&ctrl->namespaces_rwsem);
4335 /* Forcibly unquiesce queues to avoid blocking dispatch */
4336 if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4337 blk_mq_unquiesce_queue(ctrl->admin_q);
4339 list_for_each_entry(ns, &ctrl->namespaces, list)
4340 nvme_set_queue_dying(ns);
4342 up_read(&ctrl->namespaces_rwsem);
4344 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4346 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4350 down_read(&ctrl->namespaces_rwsem);
4351 list_for_each_entry(ns, &ctrl->namespaces, list)
4352 blk_mq_unfreeze_queue(ns->queue);
4353 up_read(&ctrl->namespaces_rwsem);
4355 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4357 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4361 down_read(&ctrl->namespaces_rwsem);
4362 list_for_each_entry(ns, &ctrl->namespaces, list) {
4363 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4367 up_read(&ctrl->namespaces_rwsem);
4370 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4372 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4376 down_read(&ctrl->namespaces_rwsem);
4377 list_for_each_entry(ns, &ctrl->namespaces, list)
4378 blk_mq_freeze_queue_wait(ns->queue);
4379 up_read(&ctrl->namespaces_rwsem);
4381 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4383 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4387 down_read(&ctrl->namespaces_rwsem);
4388 list_for_each_entry(ns, &ctrl->namespaces, list)
4389 blk_freeze_queue_start(ns->queue);
4390 up_read(&ctrl->namespaces_rwsem);
4392 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4394 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4398 down_read(&ctrl->namespaces_rwsem);
4399 list_for_each_entry(ns, &ctrl->namespaces, list)
4400 blk_mq_quiesce_queue(ns->queue);
4401 up_read(&ctrl->namespaces_rwsem);
4403 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4405 void nvme_start_queues(struct nvme_ctrl *ctrl)
4409 down_read(&ctrl->namespaces_rwsem);
4410 list_for_each_entry(ns, &ctrl->namespaces, list)
4411 blk_mq_unquiesce_queue(ns->queue);
4412 up_read(&ctrl->namespaces_rwsem);
4414 EXPORT_SYMBOL_GPL(nvme_start_queues);
4416 void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
4420 down_read(&ctrl->namespaces_rwsem);
4421 list_for_each_entry(ns, &ctrl->namespaces, list)
4422 blk_sync_queue(ns->queue);
4423 up_read(&ctrl->namespaces_rwsem);
4425 EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
4427 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4429 nvme_sync_io_queues(ctrl);
4431 blk_sync_queue(ctrl->admin_q);
4433 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4435 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
4437 if (file->f_op != &nvme_dev_fops)
4439 return file->private_data;
4441 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU);
4444 * Check we didn't inadvertently grow the command structure sizes:
4446 static inline void _nvme_check_size(void)
4448 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4449 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4450 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4451 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4452 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4453 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4454 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4455 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4456 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4457 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4458 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4459 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4460 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4461 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4462 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4463 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
4464 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4465 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4466 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4467 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4471 static int __init nvme_core_init(void)
4473 int result = -ENOMEM;
4477 nvme_wq = alloc_workqueue("nvme-wq",
4478 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4482 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4483 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4487 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4488 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4489 if (!nvme_delete_wq)
4490 goto destroy_reset_wq;
4492 result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
4493 NVME_MINORS, "nvme");
4495 goto destroy_delete_wq;
4497 nvme_class = class_create(THIS_MODULE, "nvme");
4498 if (IS_ERR(nvme_class)) {
4499 result = PTR_ERR(nvme_class);
4500 goto unregister_chrdev;
4502 nvme_class->dev_uevent = nvme_class_uevent;
4504 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4505 if (IS_ERR(nvme_subsys_class)) {
4506 result = PTR_ERR(nvme_subsys_class);
4510 result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
4513 goto destroy_subsys_class;
4515 nvme_ns_chr_class = class_create(THIS_MODULE, "nvme-generic");
4516 if (IS_ERR(nvme_ns_chr_class)) {
4517 result = PTR_ERR(nvme_ns_chr_class);
4518 goto unregister_generic_ns;
4523 unregister_generic_ns:
4524 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4525 destroy_subsys_class:
4526 class_destroy(nvme_subsys_class);
4528 class_destroy(nvme_class);
4530 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4532 destroy_workqueue(nvme_delete_wq);
4534 destroy_workqueue(nvme_reset_wq);
4536 destroy_workqueue(nvme_wq);
4541 static void __exit nvme_core_exit(void)
4543 class_destroy(nvme_ns_chr_class);
4544 class_destroy(nvme_subsys_class);
4545 class_destroy(nvme_class);
4546 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4547 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4548 destroy_workqueue(nvme_delete_wq);
4549 destroy_workqueue(nvme_reset_wq);
4550 destroy_workqueue(nvme_wq);
4551 ida_destroy(&nvme_ns_chr_minor_ida);
4552 ida_destroy(&nvme_instance_ida);
4555 MODULE_LICENSE("GPL");
4556 MODULE_VERSION("1.0");
4557 module_init(nvme_core_init);
4558 module_exit(nvme_core_exit);