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");
60 static unsigned long apst_primary_timeout_ms = 100;
61 module_param(apst_primary_timeout_ms, ulong, 0644);
62 MODULE_PARM_DESC(apst_primary_timeout_ms,
63 "primary APST timeout in ms");
65 static unsigned long apst_secondary_timeout_ms = 2000;
66 module_param(apst_secondary_timeout_ms, ulong, 0644);
67 MODULE_PARM_DESC(apst_secondary_timeout_ms,
68 "secondary APST timeout in ms");
70 static unsigned long apst_primary_latency_tol_us = 15000;
71 module_param(apst_primary_latency_tol_us, ulong, 0644);
72 MODULE_PARM_DESC(apst_primary_latency_tol_us,
73 "primary APST latency tolerance in us");
75 static unsigned long apst_secondary_latency_tol_us = 100000;
76 module_param(apst_secondary_latency_tol_us, ulong, 0644);
77 MODULE_PARM_DESC(apst_secondary_latency_tol_us,
78 "secondary APST latency tolerance in us");
81 module_param(streams, bool, 0644);
82 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
85 * nvme_wq - hosts nvme related works that are not reset or delete
86 * nvme_reset_wq - hosts nvme reset works
87 * nvme_delete_wq - hosts nvme delete works
89 * nvme_wq will host works such as scan, aen handling, fw activation,
90 * keep-alive, periodic reconnects etc. nvme_reset_wq
91 * runs reset works which also flush works hosted on nvme_wq for
92 * serialization purposes. nvme_delete_wq host controller deletion
93 * works which flush reset works for serialization.
95 struct workqueue_struct *nvme_wq;
96 EXPORT_SYMBOL_GPL(nvme_wq);
98 struct workqueue_struct *nvme_reset_wq;
99 EXPORT_SYMBOL_GPL(nvme_reset_wq);
101 struct workqueue_struct *nvme_delete_wq;
102 EXPORT_SYMBOL_GPL(nvme_delete_wq);
104 static LIST_HEAD(nvme_subsystems);
105 static DEFINE_MUTEX(nvme_subsystems_lock);
107 static DEFINE_IDA(nvme_instance_ida);
108 static dev_t nvme_ctrl_base_chr_devt;
109 static struct class *nvme_class;
110 static struct class *nvme_subsys_class;
112 static DEFINE_IDA(nvme_ns_chr_minor_ida);
113 static dev_t nvme_ns_chr_devt;
114 static struct class *nvme_ns_chr_class;
116 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
117 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
119 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
120 struct nvme_command *cmd);
123 * Prepare a queue for teardown.
125 * This must forcibly unquiesce queues to avoid blocking dispatch, and only set
126 * the capacity to 0 after that to avoid blocking dispatchers that may be
127 * holding bd_butex. This will end buffered writers dirtying pages that can't
130 static void nvme_set_queue_dying(struct nvme_ns *ns)
132 if (test_and_set_bit(NVME_NS_DEAD, &ns->flags))
135 blk_set_queue_dying(ns->queue);
136 blk_mq_unquiesce_queue(ns->queue);
138 set_capacity_and_notify(ns->disk, 0);
141 void nvme_queue_scan(struct nvme_ctrl *ctrl)
144 * Only new queue scan work when admin and IO queues are both alive
146 if (ctrl->state == NVME_CTRL_LIVE && ctrl->tagset)
147 queue_work(nvme_wq, &ctrl->scan_work);
151 * Use this function to proceed with scheduling reset_work for a controller
152 * that had previously been set to the resetting state. This is intended for
153 * code paths that can't be interrupted by other reset attempts. A hot removal
154 * may prevent this from succeeding.
156 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
158 if (ctrl->state != NVME_CTRL_RESETTING)
160 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
164 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
166 static void nvme_failfast_work(struct work_struct *work)
168 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
169 struct nvme_ctrl, failfast_work);
171 if (ctrl->state != NVME_CTRL_CONNECTING)
174 set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
175 dev_info(ctrl->device, "failfast expired\n");
176 nvme_kick_requeue_lists(ctrl);
179 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
181 if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
184 schedule_delayed_work(&ctrl->failfast_work,
185 ctrl->opts->fast_io_fail_tmo * HZ);
188 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
193 cancel_delayed_work_sync(&ctrl->failfast_work);
194 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
198 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
200 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
202 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
206 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
208 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
212 ret = nvme_reset_ctrl(ctrl);
214 flush_work(&ctrl->reset_work);
215 if (ctrl->state != NVME_CTRL_LIVE)
222 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
224 dev_info(ctrl->device,
225 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
227 flush_work(&ctrl->reset_work);
228 nvme_stop_ctrl(ctrl);
229 nvme_remove_namespaces(ctrl);
230 ctrl->ops->delete_ctrl(ctrl);
231 nvme_uninit_ctrl(ctrl);
234 static void nvme_delete_ctrl_work(struct work_struct *work)
236 struct nvme_ctrl *ctrl =
237 container_of(work, struct nvme_ctrl, delete_work);
239 nvme_do_delete_ctrl(ctrl);
242 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
244 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
246 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
250 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
252 static void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
255 * Keep a reference until nvme_do_delete_ctrl() complete,
256 * since ->delete_ctrl can free the controller.
259 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
260 nvme_do_delete_ctrl(ctrl);
264 static blk_status_t nvme_error_status(u16 status)
266 switch (status & 0x7ff) {
267 case NVME_SC_SUCCESS:
269 case NVME_SC_CAP_EXCEEDED:
270 return BLK_STS_NOSPC;
271 case NVME_SC_LBA_RANGE:
272 case NVME_SC_CMD_INTERRUPTED:
273 case NVME_SC_NS_NOT_READY:
274 return BLK_STS_TARGET;
275 case NVME_SC_BAD_ATTRIBUTES:
276 case NVME_SC_ONCS_NOT_SUPPORTED:
277 case NVME_SC_INVALID_OPCODE:
278 case NVME_SC_INVALID_FIELD:
279 case NVME_SC_INVALID_NS:
280 return BLK_STS_NOTSUPP;
281 case NVME_SC_WRITE_FAULT:
282 case NVME_SC_READ_ERROR:
283 case NVME_SC_UNWRITTEN_BLOCK:
284 case NVME_SC_ACCESS_DENIED:
285 case NVME_SC_READ_ONLY:
286 case NVME_SC_COMPARE_FAILED:
287 return BLK_STS_MEDIUM;
288 case NVME_SC_GUARD_CHECK:
289 case NVME_SC_APPTAG_CHECK:
290 case NVME_SC_REFTAG_CHECK:
291 case NVME_SC_INVALID_PI:
292 return BLK_STS_PROTECTION;
293 case NVME_SC_RESERVATION_CONFLICT:
294 return BLK_STS_NEXUS;
295 case NVME_SC_HOST_PATH_ERROR:
296 return BLK_STS_TRANSPORT;
297 case NVME_SC_ZONE_TOO_MANY_ACTIVE:
298 return BLK_STS_ZONE_ACTIVE_RESOURCE;
299 case NVME_SC_ZONE_TOO_MANY_OPEN:
300 return BLK_STS_ZONE_OPEN_RESOURCE;
302 return BLK_STS_IOERR;
306 static void nvme_retry_req(struct request *req)
308 unsigned long delay = 0;
311 /* The mask and shift result must be <= 3 */
312 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
314 delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
316 nvme_req(req)->retries++;
317 blk_mq_requeue_request(req, false);
318 blk_mq_delay_kick_requeue_list(req->q, delay);
321 enum nvme_disposition {
327 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
329 if (likely(nvme_req(req)->status == 0))
332 if (blk_noretry_request(req) ||
333 (nvme_req(req)->status & NVME_SC_DNR) ||
334 nvme_req(req)->retries >= nvme_max_retries)
337 if (req->cmd_flags & REQ_NVME_MPATH) {
338 if (nvme_is_path_error(nvme_req(req)->status) ||
339 blk_queue_dying(req->q))
342 if (blk_queue_dying(req->q))
349 static inline void nvme_end_req(struct request *req)
351 blk_status_t status = nvme_error_status(nvme_req(req)->status);
353 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
354 req_op(req) == REQ_OP_ZONE_APPEND)
355 req->__sector = nvme_lba_to_sect(req->q->queuedata,
356 le64_to_cpu(nvme_req(req)->result.u64));
358 nvme_trace_bio_complete(req);
359 blk_mq_end_request(req, status);
362 void nvme_complete_rq(struct request *req)
364 trace_nvme_complete_rq(req);
365 nvme_cleanup_cmd(req);
367 if (nvme_req(req)->ctrl->kas)
368 nvme_req(req)->ctrl->comp_seen = true;
370 switch (nvme_decide_disposition(req)) {
378 nvme_failover_req(req);
382 EXPORT_SYMBOL_GPL(nvme_complete_rq);
385 * Called to unwind from ->queue_rq on a failed command submission so that the
386 * multipathing code gets called to potentially failover to another path.
387 * The caller needs to unwind all transport specific resource allocations and
388 * must return propagate the return value.
390 blk_status_t nvme_host_path_error(struct request *req)
392 nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
393 blk_mq_set_request_complete(req);
394 nvme_complete_rq(req);
397 EXPORT_SYMBOL_GPL(nvme_host_path_error);
399 bool nvme_cancel_request(struct request *req, void *data, bool reserved)
401 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
402 "Cancelling I/O %d", req->tag);
404 /* don't abort one completed request */
405 if (blk_mq_request_completed(req))
408 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
409 nvme_req(req)->flags |= NVME_REQ_CANCELLED;
410 blk_mq_complete_request(req);
413 EXPORT_SYMBOL_GPL(nvme_cancel_request);
415 void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
418 blk_mq_tagset_busy_iter(ctrl->tagset,
419 nvme_cancel_request, ctrl);
420 blk_mq_tagset_wait_completed_request(ctrl->tagset);
423 EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
425 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
427 if (ctrl->admin_tagset) {
428 blk_mq_tagset_busy_iter(ctrl->admin_tagset,
429 nvme_cancel_request, ctrl);
430 blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
433 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
435 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
436 enum nvme_ctrl_state new_state)
438 enum nvme_ctrl_state old_state;
440 bool changed = false;
442 spin_lock_irqsave(&ctrl->lock, flags);
444 old_state = ctrl->state;
449 case NVME_CTRL_RESETTING:
450 case NVME_CTRL_CONNECTING:
457 case NVME_CTRL_RESETTING:
467 case NVME_CTRL_CONNECTING:
470 case NVME_CTRL_RESETTING:
477 case NVME_CTRL_DELETING:
480 case NVME_CTRL_RESETTING:
481 case NVME_CTRL_CONNECTING:
488 case NVME_CTRL_DELETING_NOIO:
490 case NVME_CTRL_DELETING:
500 case NVME_CTRL_DELETING:
512 ctrl->state = new_state;
513 wake_up_all(&ctrl->state_wq);
516 spin_unlock_irqrestore(&ctrl->lock, flags);
520 if (ctrl->state == NVME_CTRL_LIVE) {
521 if (old_state == NVME_CTRL_CONNECTING)
522 nvme_stop_failfast_work(ctrl);
523 nvme_kick_requeue_lists(ctrl);
524 } else if (ctrl->state == NVME_CTRL_CONNECTING &&
525 old_state == NVME_CTRL_RESETTING) {
526 nvme_start_failfast_work(ctrl);
530 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
533 * Returns true for sink states that can't ever transition back to live.
535 static bool nvme_state_terminal(struct nvme_ctrl *ctrl)
537 switch (ctrl->state) {
540 case NVME_CTRL_RESETTING:
541 case NVME_CTRL_CONNECTING:
543 case NVME_CTRL_DELETING:
544 case NVME_CTRL_DELETING_NOIO:
548 WARN_ONCE(1, "Unhandled ctrl state:%d", ctrl->state);
554 * Waits for the controller state to be resetting, or returns false if it is
555 * not possible to ever transition to that state.
557 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
559 wait_event(ctrl->state_wq,
560 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
561 nvme_state_terminal(ctrl));
562 return ctrl->state == NVME_CTRL_RESETTING;
564 EXPORT_SYMBOL_GPL(nvme_wait_reset);
566 static void nvme_free_ns_head(struct kref *ref)
568 struct nvme_ns_head *head =
569 container_of(ref, struct nvme_ns_head, ref);
571 nvme_mpath_remove_disk(head);
572 ida_simple_remove(&head->subsys->ns_ida, head->instance);
573 cleanup_srcu_struct(&head->srcu);
574 nvme_put_subsystem(head->subsys);
578 bool nvme_tryget_ns_head(struct nvme_ns_head *head)
580 return kref_get_unless_zero(&head->ref);
583 void nvme_put_ns_head(struct nvme_ns_head *head)
585 kref_put(&head->ref, nvme_free_ns_head);
588 static void nvme_free_ns(struct kref *kref)
590 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
593 nvme_put_ns_head(ns->head);
594 nvme_put_ctrl(ns->ctrl);
598 static inline bool nvme_get_ns(struct nvme_ns *ns)
600 return kref_get_unless_zero(&ns->kref);
603 void nvme_put_ns(struct nvme_ns *ns)
605 kref_put(&ns->kref, nvme_free_ns);
607 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
609 static inline void nvme_clear_nvme_request(struct request *req)
611 nvme_req(req)->status = 0;
612 nvme_req(req)->retries = 0;
613 nvme_req(req)->flags = 0;
614 req->rq_flags |= RQF_DONTPREP;
617 static inline unsigned int nvme_req_op(struct nvme_command *cmd)
619 return nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
622 static inline void nvme_init_request(struct request *req,
623 struct nvme_command *cmd)
625 if (req->q->queuedata)
626 req->timeout = NVME_IO_TIMEOUT;
627 else /* no queuedata implies admin queue */
628 req->timeout = NVME_ADMIN_TIMEOUT;
630 /* passthru commands should let the driver set the SGL flags */
631 cmd->common.flags &= ~NVME_CMD_SGL_ALL;
633 req->cmd_flags |= REQ_FAILFAST_DRIVER;
634 if (req->mq_hctx->type == HCTX_TYPE_POLL)
635 req->cmd_flags |= REQ_HIPRI;
636 nvme_clear_nvme_request(req);
637 memcpy(nvme_req(req)->cmd, cmd, sizeof(*cmd));
640 struct request *nvme_alloc_request(struct request_queue *q,
641 struct nvme_command *cmd, blk_mq_req_flags_t flags)
645 req = blk_mq_alloc_request(q, nvme_req_op(cmd), flags);
647 nvme_init_request(req, cmd);
650 EXPORT_SYMBOL_GPL(nvme_alloc_request);
652 static struct request *nvme_alloc_request_qid(struct request_queue *q,
653 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
657 req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), flags,
660 nvme_init_request(req, cmd);
665 * For something we're not in a state to send to the device the default action
666 * is to busy it and retry it after the controller state is recovered. However,
667 * if the controller is deleting or if anything is marked for failfast or
668 * nvme multipath it is immediately failed.
670 * Note: commands used to initialize the controller will be marked for failfast.
671 * Note: nvme cli/ioctl commands are marked for failfast.
673 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl,
676 if (ctrl->state != NVME_CTRL_DELETING_NOIO &&
677 ctrl->state != NVME_CTRL_DEAD &&
678 !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) &&
679 !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
680 return BLK_STS_RESOURCE;
681 return nvme_host_path_error(rq);
683 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command);
685 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
688 struct nvme_request *req = nvme_req(rq);
691 * currently we have a problem sending passthru commands
692 * on the admin_q if the controller is not LIVE because we can't
693 * make sure that they are going out after the admin connect,
694 * controller enable and/or other commands in the initialization
695 * sequence. until the controller will be LIVE, fail with
696 * BLK_STS_RESOURCE so that they will be rescheduled.
698 if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD))
701 if (ctrl->ops->flags & NVME_F_FABRICS) {
703 * Only allow commands on a live queue, except for the connect
704 * command, which is require to set the queue live in the
705 * appropinquate states.
707 switch (ctrl->state) {
708 case NVME_CTRL_CONNECTING:
709 if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) &&
710 req->cmd->fabrics.fctype == nvme_fabrics_type_connect)
722 EXPORT_SYMBOL_GPL(__nvme_check_ready);
724 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
726 struct nvme_command c = { };
728 c.directive.opcode = nvme_admin_directive_send;
729 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
730 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
731 c.directive.dtype = NVME_DIR_IDENTIFY;
732 c.directive.tdtype = NVME_DIR_STREAMS;
733 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
735 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
738 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
740 return nvme_toggle_streams(ctrl, false);
743 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
745 return nvme_toggle_streams(ctrl, true);
748 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
749 struct streams_directive_params *s, u32 nsid)
751 struct nvme_command c = { };
753 memset(s, 0, sizeof(*s));
755 c.directive.opcode = nvme_admin_directive_recv;
756 c.directive.nsid = cpu_to_le32(nsid);
757 c.directive.numd = cpu_to_le32(nvme_bytes_to_numd(sizeof(*s)));
758 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
759 c.directive.dtype = NVME_DIR_STREAMS;
761 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
764 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
766 struct streams_directive_params s;
769 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
774 ret = nvme_enable_streams(ctrl);
778 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
780 goto out_disable_stream;
782 ctrl->nssa = le16_to_cpu(s.nssa);
783 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
784 dev_info(ctrl->device, "too few streams (%u) available\n",
786 goto out_disable_stream;
789 ctrl->nr_streams = min_t(u16, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
790 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
794 nvme_disable_streams(ctrl);
799 * Check if 'req' has a write hint associated with it. If it does, assign
800 * a valid namespace stream to the write.
802 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
803 struct request *req, u16 *control,
806 enum rw_hint streamid = req->write_hint;
808 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
812 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
815 *control |= NVME_RW_DTYPE_STREAMS;
816 *dsmgmt |= streamid << 16;
819 if (streamid < ARRAY_SIZE(req->q->write_hints))
820 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
823 static inline void nvme_setup_flush(struct nvme_ns *ns,
824 struct nvme_command *cmnd)
826 cmnd->common.opcode = nvme_cmd_flush;
827 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
830 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
831 struct nvme_command *cmnd)
833 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
834 struct nvme_dsm_range *range;
838 * Some devices do not consider the DSM 'Number of Ranges' field when
839 * determining how much data to DMA. Always allocate memory for maximum
840 * number of segments to prevent device reading beyond end of buffer.
842 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
844 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
847 * If we fail allocation our range, fallback to the controller
848 * discard page. If that's also busy, it's safe to return
849 * busy, as we know we can make progress once that's freed.
851 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
852 return BLK_STS_RESOURCE;
854 range = page_address(ns->ctrl->discard_page);
857 __rq_for_each_bio(bio, req) {
858 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
859 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
862 range[n].cattr = cpu_to_le32(0);
863 range[n].nlb = cpu_to_le32(nlb);
864 range[n].slba = cpu_to_le64(slba);
869 if (WARN_ON_ONCE(n != segments)) {
870 if (virt_to_page(range) == ns->ctrl->discard_page)
871 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
874 return BLK_STS_IOERR;
877 cmnd->dsm.opcode = nvme_cmd_dsm;
878 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
879 cmnd->dsm.nr = cpu_to_le32(segments - 1);
880 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
882 req->special_vec.bv_page = virt_to_page(range);
883 req->special_vec.bv_offset = offset_in_page(range);
884 req->special_vec.bv_len = alloc_size;
885 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
890 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
891 struct request *req, struct nvme_command *cmnd)
893 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
894 return nvme_setup_discard(ns, req, cmnd);
896 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
897 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
898 cmnd->write_zeroes.slba =
899 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
900 cmnd->write_zeroes.length =
901 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
902 if (nvme_ns_has_pi(ns))
903 cmnd->write_zeroes.control = cpu_to_le16(NVME_RW_PRINFO_PRACT);
905 cmnd->write_zeroes.control = 0;
909 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
910 struct request *req, struct nvme_command *cmnd,
913 struct nvme_ctrl *ctrl = ns->ctrl;
917 if (req->cmd_flags & REQ_FUA)
918 control |= NVME_RW_FUA;
919 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
920 control |= NVME_RW_LR;
922 if (req->cmd_flags & REQ_RAHEAD)
923 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
925 cmnd->rw.opcode = op;
926 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
927 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
928 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
930 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
931 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
935 * If formated with metadata, the block layer always provides a
936 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
937 * we enable the PRACT bit for protection information or set the
938 * namespace capacity to zero to prevent any I/O.
940 if (!blk_integrity_rq(req)) {
941 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
942 return BLK_STS_NOTSUPP;
943 control |= NVME_RW_PRINFO_PRACT;
946 switch (ns->pi_type) {
947 case NVME_NS_DPS_PI_TYPE3:
948 control |= NVME_RW_PRINFO_PRCHK_GUARD;
950 case NVME_NS_DPS_PI_TYPE1:
951 case NVME_NS_DPS_PI_TYPE2:
952 control |= NVME_RW_PRINFO_PRCHK_GUARD |
953 NVME_RW_PRINFO_PRCHK_REF;
954 if (op == nvme_cmd_zone_append)
955 control |= NVME_RW_APPEND_PIREMAP;
956 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
961 cmnd->rw.control = cpu_to_le16(control);
962 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
966 void nvme_cleanup_cmd(struct request *req)
968 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
969 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
971 if (req->special_vec.bv_page == ctrl->discard_page)
972 clear_bit_unlock(0, &ctrl->discard_page_busy);
974 kfree(bvec_virt(&req->special_vec));
977 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
979 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
981 struct nvme_command *cmd = nvme_req(req)->cmd;
982 blk_status_t ret = BLK_STS_OK;
984 if (!(req->rq_flags & RQF_DONTPREP)) {
985 nvme_clear_nvme_request(req);
986 memset(cmd, 0, sizeof(*cmd));
989 switch (req_op(req)) {
992 /* these are setup prior to execution in nvme_init_request() */
995 nvme_setup_flush(ns, cmd);
997 case REQ_OP_ZONE_RESET_ALL:
998 case REQ_OP_ZONE_RESET:
999 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
1001 case REQ_OP_ZONE_OPEN:
1002 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
1004 case REQ_OP_ZONE_CLOSE:
1005 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
1007 case REQ_OP_ZONE_FINISH:
1008 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
1010 case REQ_OP_WRITE_ZEROES:
1011 ret = nvme_setup_write_zeroes(ns, req, cmd);
1013 case REQ_OP_DISCARD:
1014 ret = nvme_setup_discard(ns, req, cmd);
1017 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
1020 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
1022 case REQ_OP_ZONE_APPEND:
1023 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
1027 return BLK_STS_IOERR;
1030 nvme_req(req)->genctr++;
1031 cmd->common.command_id = nvme_cid(req);
1032 trace_nvme_setup_cmd(req, cmd);
1035 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
1040 * >0: nvme controller's cqe status response
1041 * <0: kernel error in lieu of controller response
1043 static int nvme_execute_rq(struct gendisk *disk, struct request *rq,
1046 blk_status_t status;
1048 status = blk_execute_rq(disk, rq, at_head);
1049 if (nvme_req(rq)->flags & NVME_REQ_CANCELLED)
1051 if (nvme_req(rq)->status)
1052 return nvme_req(rq)->status;
1053 return blk_status_to_errno(status);
1057 * Returns 0 on success. If the result is negative, it's a Linux error code;
1058 * if the result is positive, it's an NVM Express status code
1060 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1061 union nvme_result *result, void *buffer, unsigned bufflen,
1062 unsigned timeout, int qid, int at_head,
1063 blk_mq_req_flags_t flags)
1065 struct request *req;
1068 if (qid == NVME_QID_ANY)
1069 req = nvme_alloc_request(q, cmd, flags);
1071 req = nvme_alloc_request_qid(q, cmd, flags, qid);
1073 return PTR_ERR(req);
1076 req->timeout = timeout;
1078 if (buffer && bufflen) {
1079 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
1084 ret = nvme_execute_rq(NULL, req, at_head);
1085 if (result && ret >= 0)
1086 *result = nvme_req(req)->result;
1088 blk_mq_free_request(req);
1091 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
1093 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1094 void *buffer, unsigned bufflen)
1096 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
1097 NVME_QID_ANY, 0, 0);
1099 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
1101 static u32 nvme_known_admin_effects(u8 opcode)
1104 case nvme_admin_format_nvm:
1105 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_NCC |
1106 NVME_CMD_EFFECTS_CSE_MASK;
1107 case nvme_admin_sanitize_nvm:
1108 return NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK;
1115 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1120 if (ns->head->effects)
1121 effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
1122 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1123 dev_warn_once(ctrl->device,
1124 "IO command:%02x has unhandled effects:%08x\n",
1130 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1131 effects |= nvme_known_admin_effects(opcode);
1135 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
1137 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1140 u32 effects = nvme_command_effects(ctrl, ns, opcode);
1143 * For simplicity, IO to all namespaces is quiesced even if the command
1144 * effects say only one namespace is affected.
1146 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1147 mutex_lock(&ctrl->scan_lock);
1148 mutex_lock(&ctrl->subsys->lock);
1149 nvme_mpath_start_freeze(ctrl->subsys);
1150 nvme_mpath_wait_freeze(ctrl->subsys);
1151 nvme_start_freeze(ctrl);
1152 nvme_wait_freeze(ctrl);
1157 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects,
1158 struct nvme_command *cmd, int status)
1160 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1161 nvme_unfreeze(ctrl);
1162 nvme_mpath_unfreeze(ctrl->subsys);
1163 mutex_unlock(&ctrl->subsys->lock);
1164 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1165 mutex_unlock(&ctrl->scan_lock);
1167 if (effects & NVME_CMD_EFFECTS_CCC)
1168 nvme_init_ctrl_finish(ctrl);
1169 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1170 nvme_queue_scan(ctrl);
1171 flush_work(&ctrl->scan_work);
1174 switch (cmd->common.opcode) {
1175 case nvme_admin_set_features:
1176 switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) {
1177 case NVME_FEAT_KATO:
1179 * Keep alive commands interval on the host should be
1180 * updated when KATO is modified by Set Features
1184 nvme_update_keep_alive(ctrl, cmd);
1195 int nvme_execute_passthru_rq(struct request *rq)
1197 struct nvme_command *cmd = nvme_req(rq)->cmd;
1198 struct nvme_ctrl *ctrl = nvme_req(rq)->ctrl;
1199 struct nvme_ns *ns = rq->q->queuedata;
1200 struct gendisk *disk = ns ? ns->disk : NULL;
1204 effects = nvme_passthru_start(ctrl, ns, cmd->common.opcode);
1205 ret = nvme_execute_rq(disk, rq, false);
1206 if (effects) /* nothing to be done for zero cmd effects */
1207 nvme_passthru_end(ctrl, effects, cmd, ret);
1211 EXPORT_SYMBOL_NS_GPL(nvme_execute_passthru_rq, NVME_TARGET_PASSTHRU);
1214 * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
1216 * The host should send Keep Alive commands at half of the Keep Alive Timeout
1217 * accounting for transport roundtrip times [..].
1219 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
1221 queue_delayed_work(nvme_wq, &ctrl->ka_work, ctrl->kato * HZ / 2);
1224 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
1226 struct nvme_ctrl *ctrl = rq->end_io_data;
1227 unsigned long flags;
1228 bool startka = false;
1230 blk_mq_free_request(rq);
1233 dev_err(ctrl->device,
1234 "failed nvme_keep_alive_end_io error=%d\n",
1239 ctrl->comp_seen = false;
1240 spin_lock_irqsave(&ctrl->lock, flags);
1241 if (ctrl->state == NVME_CTRL_LIVE ||
1242 ctrl->state == NVME_CTRL_CONNECTING)
1244 spin_unlock_irqrestore(&ctrl->lock, flags);
1246 nvme_queue_keep_alive_work(ctrl);
1249 static void nvme_keep_alive_work(struct work_struct *work)
1251 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1252 struct nvme_ctrl, ka_work);
1253 bool comp_seen = ctrl->comp_seen;
1256 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1257 dev_dbg(ctrl->device,
1258 "reschedule traffic based keep-alive timer\n");
1259 ctrl->comp_seen = false;
1260 nvme_queue_keep_alive_work(ctrl);
1264 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd,
1265 BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
1267 /* allocation failure, reset the controller */
1268 dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
1269 nvme_reset_ctrl(ctrl);
1273 rq->timeout = ctrl->kato * HZ;
1274 rq->end_io_data = ctrl;
1275 blk_execute_rq_nowait(NULL, rq, 0, nvme_keep_alive_end_io);
1278 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1280 if (unlikely(ctrl->kato == 0))
1283 nvme_queue_keep_alive_work(ctrl);
1286 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1288 if (unlikely(ctrl->kato == 0))
1291 cancel_delayed_work_sync(&ctrl->ka_work);
1293 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1295 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
1296 struct nvme_command *cmd)
1298 unsigned int new_kato =
1299 DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000);
1301 dev_info(ctrl->device,
1302 "keep alive interval updated from %u ms to %u ms\n",
1303 ctrl->kato * 1000 / 2, new_kato * 1000 / 2);
1305 nvme_stop_keep_alive(ctrl);
1306 ctrl->kato = new_kato;
1307 nvme_start_keep_alive(ctrl);
1311 * In NVMe 1.0 the CNS field was just a binary controller or namespace
1312 * flag, thus sending any new CNS opcodes has a big chance of not working.
1313 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1314 * (but not for any later version).
1316 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1318 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1319 return ctrl->vs < NVME_VS(1, 2, 0);
1320 return ctrl->vs < NVME_VS(1, 1, 0);
1323 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1325 struct nvme_command c = { };
1328 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1329 c.identify.opcode = nvme_admin_identify;
1330 c.identify.cns = NVME_ID_CNS_CTRL;
1332 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1336 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1337 sizeof(struct nvme_id_ctrl));
1343 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1344 struct nvme_ns_id_desc *cur, bool *csi_seen)
1346 const char *warn_str = "ctrl returned bogus length:";
1349 switch (cur->nidt) {
1350 case NVME_NIDT_EUI64:
1351 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1352 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1353 warn_str, cur->nidl);
1356 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1357 return NVME_NIDT_EUI64_LEN;
1358 case NVME_NIDT_NGUID:
1359 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1360 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1361 warn_str, cur->nidl);
1364 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1365 return NVME_NIDT_NGUID_LEN;
1366 case NVME_NIDT_UUID:
1367 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1368 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1369 warn_str, cur->nidl);
1372 uuid_copy(&ids->uuid, data + sizeof(*cur));
1373 return NVME_NIDT_UUID_LEN;
1375 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1376 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1377 warn_str, cur->nidl);
1380 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1382 return NVME_NIDT_CSI_LEN;
1384 /* Skip unknown types */
1389 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
1390 struct nvme_ns_ids *ids)
1392 struct nvme_command c = { };
1393 bool csi_seen = false;
1394 int status, pos, len;
1397 if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
1399 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1402 c.identify.opcode = nvme_admin_identify;
1403 c.identify.nsid = cpu_to_le32(nsid);
1404 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1406 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1410 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1411 NVME_IDENTIFY_DATA_SIZE);
1413 dev_warn(ctrl->device,
1414 "Identify Descriptors failed (nsid=%u, status=0x%x)\n",
1419 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1420 struct nvme_ns_id_desc *cur = data + pos;
1425 len = nvme_process_ns_desc(ctrl, ids, cur, &csi_seen);
1429 len += sizeof(*cur);
1432 if (nvme_multi_css(ctrl) && !csi_seen) {
1433 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1443 static int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
1444 struct nvme_ns_ids *ids, struct nvme_id_ns **id)
1446 struct nvme_command c = { };
1449 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1450 c.identify.opcode = nvme_admin_identify;
1451 c.identify.nsid = cpu_to_le32(nsid);
1452 c.identify.cns = NVME_ID_CNS_NS;
1454 *id = kmalloc(sizeof(**id), GFP_KERNEL);
1458 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1460 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1464 error = NVME_SC_INVALID_NS | NVME_SC_DNR;
1465 if ((*id)->ncap == 0) /* namespace not allocated or attached */
1468 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1469 !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
1470 memcpy(ids->eui64, (*id)->eui64, sizeof(ids->eui64));
1471 if (ctrl->vs >= NVME_VS(1, 2, 0) &&
1472 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
1473 memcpy(ids->nguid, (*id)->nguid, sizeof(ids->nguid));
1482 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1483 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1485 union nvme_result res = { 0 };
1486 struct nvme_command c = { };
1489 c.features.opcode = op;
1490 c.features.fid = cpu_to_le32(fid);
1491 c.features.dword11 = cpu_to_le32(dword11);
1493 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1494 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
1495 if (ret >= 0 && result)
1496 *result = le32_to_cpu(res.u32);
1500 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1501 unsigned int dword11, void *buffer, size_t buflen,
1504 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1507 EXPORT_SYMBOL_GPL(nvme_set_features);
1509 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1510 unsigned int dword11, void *buffer, size_t buflen,
1513 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1516 EXPORT_SYMBOL_GPL(nvme_get_features);
1518 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1520 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1522 int status, nr_io_queues;
1524 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1530 * Degraded controllers might return an error when setting the queue
1531 * count. We still want to be able to bring them online and offer
1532 * access to the admin queue, as that might be only way to fix them up.
1535 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1538 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1539 *count = min(*count, nr_io_queues);
1544 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1546 #define NVME_AEN_SUPPORTED \
1547 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1548 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1550 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1552 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1555 if (!supported_aens)
1558 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1561 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1564 queue_work(nvme_wq, &ctrl->async_event_work);
1567 static int nvme_ns_open(struct nvme_ns *ns)
1570 /* should never be called due to GENHD_FL_HIDDEN */
1571 if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
1573 if (!nvme_get_ns(ns))
1575 if (!try_module_get(ns->ctrl->ops->module))
1586 static void nvme_ns_release(struct nvme_ns *ns)
1589 module_put(ns->ctrl->ops->module);
1593 static int nvme_open(struct block_device *bdev, fmode_t mode)
1595 return nvme_ns_open(bdev->bd_disk->private_data);
1598 static void nvme_release(struct gendisk *disk, fmode_t mode)
1600 nvme_ns_release(disk->private_data);
1603 int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1605 /* some standard values */
1606 geo->heads = 1 << 6;
1607 geo->sectors = 1 << 5;
1608 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1612 #ifdef CONFIG_BLK_DEV_INTEGRITY
1613 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1614 u32 max_integrity_segments)
1616 struct blk_integrity integrity = { };
1619 case NVME_NS_DPS_PI_TYPE3:
1620 integrity.profile = &t10_pi_type3_crc;
1621 integrity.tag_size = sizeof(u16) + sizeof(u32);
1622 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1624 case NVME_NS_DPS_PI_TYPE1:
1625 case NVME_NS_DPS_PI_TYPE2:
1626 integrity.profile = &t10_pi_type1_crc;
1627 integrity.tag_size = sizeof(u16);
1628 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1631 integrity.profile = NULL;
1634 integrity.tuple_size = ms;
1635 blk_integrity_register(disk, &integrity);
1636 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1639 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type,
1640 u32 max_integrity_segments)
1643 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1645 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1647 struct nvme_ctrl *ctrl = ns->ctrl;
1648 struct request_queue *queue = disk->queue;
1649 u32 size = queue_logical_block_size(queue);
1651 if (ctrl->max_discard_sectors == 0) {
1652 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1656 if (ctrl->nr_streams && ns->sws && ns->sgs)
1657 size *= ns->sws * ns->sgs;
1659 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1660 NVME_DSM_MAX_RANGES);
1662 queue->limits.discard_alignment = 0;
1663 queue->limits.discard_granularity = size;
1665 /* If discard is already enabled, don't reset queue limits */
1666 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1669 blk_queue_max_discard_sectors(queue, ctrl->max_discard_sectors);
1670 blk_queue_max_discard_segments(queue, ctrl->max_discard_segments);
1672 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1673 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1676 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1678 return !uuid_is_null(&ids->uuid) ||
1679 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1680 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1683 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1685 return uuid_equal(&a->uuid, &b->uuid) &&
1686 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1687 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1691 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1692 u32 *phys_bs, u32 *io_opt)
1694 struct streams_directive_params s;
1697 if (!ctrl->nr_streams)
1700 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
1704 ns->sws = le32_to_cpu(s.sws);
1705 ns->sgs = le16_to_cpu(s.sgs);
1708 *phys_bs = ns->sws * (1 << ns->lba_shift);
1710 *io_opt = *phys_bs * ns->sgs;
1716 static int nvme_configure_metadata(struct nvme_ns *ns, struct nvme_id_ns *id)
1718 struct nvme_ctrl *ctrl = ns->ctrl;
1721 * The PI implementation requires the metadata size to be equal to the
1722 * t10 pi tuple size.
1724 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1725 if (ns->ms == sizeof(struct t10_pi_tuple))
1726 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1730 ns->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1731 if (!ns->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1733 if (ctrl->ops->flags & NVME_F_FABRICS) {
1735 * The NVMe over Fabrics specification only supports metadata as
1736 * part of the extended data LBA. We rely on HCA/HBA support to
1737 * remap the separate metadata buffer from the block layer.
1739 if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
1741 if (ctrl->max_integrity_segments)
1743 (NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1746 * For PCIe controllers, we can't easily remap the separate
1747 * metadata buffer from the block layer and thus require a
1748 * separate metadata buffer for block layer metadata/PI support.
1749 * We allow extended LBAs for the passthrough interface, though.
1751 if (id->flbas & NVME_NS_FLBAS_META_EXT)
1752 ns->features |= NVME_NS_EXT_LBAS;
1754 ns->features |= NVME_NS_METADATA_SUPPORTED;
1760 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1761 struct request_queue *q)
1763 bool vwc = ctrl->vwc & NVME_CTRL_VWC_PRESENT;
1765 if (ctrl->max_hw_sectors) {
1767 (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
1769 max_segments = min_not_zero(max_segments, ctrl->max_segments);
1770 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1771 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1773 blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
1774 blk_queue_dma_alignment(q, 7);
1775 blk_queue_write_cache(q, vwc, vwc);
1778 static void nvme_update_disk_info(struct gendisk *disk,
1779 struct nvme_ns *ns, struct nvme_id_ns *id)
1781 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1782 unsigned short bs = 1 << ns->lba_shift;
1783 u32 atomic_bs, phys_bs, io_opt = 0;
1786 * The block layer can't support LBA sizes larger than the page size
1787 * yet, so catch this early and don't allow block I/O.
1789 if (ns->lba_shift > PAGE_SHIFT) {
1794 blk_integrity_unregister(disk);
1796 atomic_bs = phys_bs = bs;
1797 nvme_setup_streams_ns(ns->ctrl, ns, &phys_bs, &io_opt);
1798 if (id->nabo == 0) {
1800 * Bit 1 indicates whether NAWUPF is defined for this namespace
1801 * and whether it should be used instead of AWUPF. If NAWUPF ==
1802 * 0 then AWUPF must be used instead.
1804 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1805 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1807 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1810 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1811 /* NPWG = Namespace Preferred Write Granularity */
1812 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1813 /* NOWS = Namespace Optimal Write Size */
1814 io_opt = bs * (1 + le16_to_cpu(id->nows));
1817 blk_queue_logical_block_size(disk->queue, bs);
1819 * Linux filesystems assume writing a single physical block is
1820 * an atomic operation. Hence limit the physical block size to the
1821 * value of the Atomic Write Unit Power Fail parameter.
1823 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1824 blk_queue_io_min(disk->queue, phys_bs);
1825 blk_queue_io_opt(disk->queue, io_opt);
1828 * Register a metadata profile for PI, or the plain non-integrity NVMe
1829 * metadata masquerading as Type 0 if supported, otherwise reject block
1830 * I/O to namespaces with metadata except when the namespace supports
1831 * PI, as it can strip/insert in that case.
1834 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
1835 (ns->features & NVME_NS_METADATA_SUPPORTED))
1836 nvme_init_integrity(disk, ns->ms, ns->pi_type,
1837 ns->ctrl->max_integrity_segments);
1838 else if (!nvme_ns_has_pi(ns))
1842 set_capacity_and_notify(disk, capacity);
1844 nvme_config_discard(disk, ns);
1845 blk_queue_max_write_zeroes_sectors(disk->queue,
1846 ns->ctrl->max_zeroes_sectors);
1848 set_disk_ro(disk, (id->nsattr & NVME_NS_ATTR_RO) ||
1849 test_bit(NVME_NS_FORCE_RO, &ns->flags));
1852 static inline bool nvme_first_scan(struct gendisk *disk)
1854 /* nvme_alloc_ns() scans the disk prior to adding it */
1855 return !disk_live(disk);
1858 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id)
1860 struct nvme_ctrl *ctrl = ns->ctrl;
1863 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1864 is_power_of_2(ctrl->max_hw_sectors))
1865 iob = ctrl->max_hw_sectors;
1867 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
1872 if (!is_power_of_2(iob)) {
1873 if (nvme_first_scan(ns->disk))
1874 pr_warn("%s: ignoring unaligned IO boundary:%u\n",
1875 ns->disk->disk_name, iob);
1879 if (blk_queue_is_zoned(ns->disk->queue)) {
1880 if (nvme_first_scan(ns->disk))
1881 pr_warn("%s: ignoring zoned namespace IO boundary\n",
1882 ns->disk->disk_name);
1886 blk_queue_chunk_sectors(ns->queue, iob);
1889 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_id_ns *id)
1891 unsigned lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
1894 blk_mq_freeze_queue(ns->disk->queue);
1895 ns->lba_shift = id->lbaf[lbaf].ds;
1896 nvme_set_queue_limits(ns->ctrl, ns->queue);
1898 ret = nvme_configure_metadata(ns, id);
1901 nvme_set_chunk_sectors(ns, id);
1902 nvme_update_disk_info(ns->disk, ns, id);
1904 if (ns->head->ids.csi == NVME_CSI_ZNS) {
1905 ret = nvme_update_zone_info(ns, lbaf);
1910 set_bit(NVME_NS_READY, &ns->flags);
1911 blk_mq_unfreeze_queue(ns->disk->queue);
1913 if (blk_queue_is_zoned(ns->queue)) {
1914 ret = nvme_revalidate_zones(ns);
1915 if (ret && !nvme_first_scan(ns->disk))
1919 if (nvme_ns_head_multipath(ns->head)) {
1920 blk_mq_freeze_queue(ns->head->disk->queue);
1921 nvme_update_disk_info(ns->head->disk, ns, id);
1922 nvme_mpath_revalidate_paths(ns);
1923 blk_stack_limits(&ns->head->disk->queue->limits,
1924 &ns->queue->limits, 0);
1925 disk_update_readahead(ns->head->disk);
1926 blk_mq_unfreeze_queue(ns->head->disk->queue);
1931 blk_mq_unfreeze_queue(ns->disk->queue);
1934 * If probing fails due an unsupported feature, hide the block device,
1935 * but still allow other access.
1937 if (ret == -ENODEV) {
1938 ns->disk->flags |= GENHD_FL_HIDDEN;
1944 static char nvme_pr_type(enum pr_type type)
1947 case PR_WRITE_EXCLUSIVE:
1949 case PR_EXCLUSIVE_ACCESS:
1951 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1953 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1955 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1957 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1964 static int nvme_send_ns_head_pr_command(struct block_device *bdev,
1965 struct nvme_command *c, u8 data[16])
1967 struct nvme_ns_head *head = bdev->bd_disk->private_data;
1968 int srcu_idx = srcu_read_lock(&head->srcu);
1969 struct nvme_ns *ns = nvme_find_path(head);
1970 int ret = -EWOULDBLOCK;
1973 c->common.nsid = cpu_to_le32(ns->head->ns_id);
1974 ret = nvme_submit_sync_cmd(ns->queue, c, data, 16);
1976 srcu_read_unlock(&head->srcu, srcu_idx);
1980 static int nvme_send_ns_pr_command(struct nvme_ns *ns, struct nvme_command *c,
1983 c->common.nsid = cpu_to_le32(ns->head->ns_id);
1984 return nvme_submit_sync_cmd(ns->queue, c, data, 16);
1987 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1988 u64 key, u64 sa_key, u8 op)
1990 struct nvme_command c = { };
1991 u8 data[16] = { 0, };
1993 put_unaligned_le64(key, &data[0]);
1994 put_unaligned_le64(sa_key, &data[8]);
1996 c.common.opcode = op;
1997 c.common.cdw10 = cpu_to_le32(cdw10);
1999 if (IS_ENABLED(CONFIG_NVME_MULTIPATH) &&
2000 bdev->bd_disk->fops == &nvme_ns_head_ops)
2001 return nvme_send_ns_head_pr_command(bdev, &c, data);
2002 return nvme_send_ns_pr_command(bdev->bd_disk->private_data, &c, data);
2005 static int nvme_pr_register(struct block_device *bdev, u64 old,
2006 u64 new, unsigned flags)
2010 if (flags & ~PR_FL_IGNORE_KEY)
2013 cdw10 = old ? 2 : 0;
2014 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
2015 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
2016 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
2019 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
2020 enum pr_type type, unsigned flags)
2024 if (flags & ~PR_FL_IGNORE_KEY)
2027 cdw10 = nvme_pr_type(type) << 8;
2028 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
2029 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
2032 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
2033 enum pr_type type, bool abort)
2035 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
2037 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
2040 static int nvme_pr_clear(struct block_device *bdev, u64 key)
2042 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
2044 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
2047 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
2049 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
2051 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
2054 const struct pr_ops nvme_pr_ops = {
2055 .pr_register = nvme_pr_register,
2056 .pr_reserve = nvme_pr_reserve,
2057 .pr_release = nvme_pr_release,
2058 .pr_preempt = nvme_pr_preempt,
2059 .pr_clear = nvme_pr_clear,
2062 #ifdef CONFIG_BLK_SED_OPAL
2063 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2066 struct nvme_ctrl *ctrl = data;
2067 struct nvme_command cmd = { };
2070 cmd.common.opcode = nvme_admin_security_send;
2072 cmd.common.opcode = nvme_admin_security_recv;
2073 cmd.common.nsid = 0;
2074 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2075 cmd.common.cdw11 = cpu_to_le32(len);
2077 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len, 0,
2078 NVME_QID_ANY, 1, 0);
2080 EXPORT_SYMBOL_GPL(nvme_sec_submit);
2081 #endif /* CONFIG_BLK_SED_OPAL */
2083 #ifdef CONFIG_BLK_DEV_ZONED
2084 static int nvme_report_zones(struct gendisk *disk, sector_t sector,
2085 unsigned int nr_zones, report_zones_cb cb, void *data)
2087 return nvme_ns_report_zones(disk->private_data, sector, nr_zones, cb,
2091 #define nvme_report_zones NULL
2092 #endif /* CONFIG_BLK_DEV_ZONED */
2094 static const struct block_device_operations nvme_bdev_ops = {
2095 .owner = THIS_MODULE,
2096 .ioctl = nvme_ioctl,
2098 .release = nvme_release,
2099 .getgeo = nvme_getgeo,
2100 .report_zones = nvme_report_zones,
2101 .pr_ops = &nvme_pr_ops,
2104 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
2106 unsigned long timeout =
2107 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
2108 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
2111 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2114 if ((csts & NVME_CSTS_RDY) == bit)
2117 usleep_range(1000, 2000);
2118 if (fatal_signal_pending(current))
2120 if (time_after(jiffies, timeout)) {
2121 dev_err(ctrl->device,
2122 "Device not ready; aborting %s, CSTS=0x%x\n",
2123 enabled ? "initialisation" : "reset", csts);
2132 * If the device has been passed off to us in an enabled state, just clear
2133 * the enabled bit. The spec says we should set the 'shutdown notification
2134 * bits', but doing so may cause the device to complete commands to the
2135 * admin queue ... and we don't know what memory that might be pointing at!
2137 int nvme_disable_ctrl(struct nvme_ctrl *ctrl)
2141 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2142 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2144 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2148 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2149 msleep(NVME_QUIRK_DELAY_AMOUNT);
2151 return nvme_wait_ready(ctrl, ctrl->cap, false);
2153 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2155 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2157 unsigned dev_page_min;
2160 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2162 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2165 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2167 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2168 dev_err(ctrl->device,
2169 "Minimum device page size %u too large for host (%u)\n",
2170 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2174 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2175 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2177 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2178 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2179 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2180 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2181 ctrl->ctrl_config |= NVME_CC_ENABLE;
2183 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2186 return nvme_wait_ready(ctrl, ctrl->cap, true);
2188 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2190 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
2192 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
2196 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2197 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2199 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2203 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2204 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
2208 if (fatal_signal_pending(current))
2210 if (time_after(jiffies, timeout)) {
2211 dev_err(ctrl->device,
2212 "Device shutdown incomplete; abort shutdown\n");
2219 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
2221 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2226 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2229 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2230 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2233 dev_warn_once(ctrl->device,
2234 "could not set timestamp (%d)\n", ret);
2238 static int nvme_configure_acre(struct nvme_ctrl *ctrl)
2240 struct nvme_feat_host_behavior *host;
2243 /* Don't bother enabling the feature if retry delay is not reported */
2247 host = kzalloc(sizeof(*host), GFP_KERNEL);
2251 host->acre = NVME_ENABLE_ACRE;
2252 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2253 host, sizeof(*host), NULL);
2259 * The function checks whether the given total (exlat + enlat) latency of
2260 * a power state allows the latter to be used as an APST transition target.
2261 * It does so by comparing the latency to the primary and secondary latency
2262 * tolerances defined by module params. If there's a match, the corresponding
2263 * timeout value is returned and the matching tolerance index (1 or 2) is
2266 static bool nvme_apst_get_transition_time(u64 total_latency,
2267 u64 *transition_time, unsigned *last_index)
2269 if (total_latency <= apst_primary_latency_tol_us) {
2270 if (*last_index == 1)
2273 *transition_time = apst_primary_timeout_ms;
2276 if (apst_secondary_timeout_ms &&
2277 total_latency <= apst_secondary_latency_tol_us) {
2278 if (*last_index <= 2)
2281 *transition_time = apst_secondary_timeout_ms;
2288 * APST (Autonomous Power State Transition) lets us program a table of power
2289 * state transitions that the controller will perform automatically.
2291 * Depending on module params, one of the two supported techniques will be used:
2293 * - If the parameters provide explicit timeouts and tolerances, they will be
2294 * used to build a table with up to 2 non-operational states to transition to.
2295 * The default parameter values were selected based on the values used by
2296 * Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic
2297 * regeneration of the APST table in the event of switching between external
2298 * and battery power, the timeouts and tolerances reflect a compromise
2299 * between values used by Microsoft for AC and battery scenarios.
2300 * - If not, we'll configure the table with a simple heuristic: we are willing
2301 * to spend at most 2% of the time transitioning between power states.
2302 * Therefore, when running in any given state, we will enter the next
2303 * lower-power non-operational state after waiting 50 * (enlat + exlat)
2304 * microseconds, as long as that state's exit latency is under the requested
2307 * We will not autonomously enter any non-operational state for which the total
2308 * latency exceeds ps_max_latency_us.
2310 * Users can set ps_max_latency_us to zero to turn off APST.
2312 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2314 struct nvme_feat_auto_pst *table;
2321 unsigned last_lt_index = UINT_MAX;
2324 * If APST isn't supported or if we haven't been initialized yet,
2325 * then don't do anything.
2330 if (ctrl->npss > 31) {
2331 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2335 table = kzalloc(sizeof(*table), GFP_KERNEL);
2339 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2340 /* Turn off APST. */
2341 dev_dbg(ctrl->device, "APST disabled\n");
2346 * Walk through all states from lowest- to highest-power.
2347 * According to the spec, lower-numbered states use more power. NPSS,
2348 * despite the name, is the index of the lowest-power state, not the
2351 for (state = (int)ctrl->npss; state >= 0; state--) {
2352 u64 total_latency_us, exit_latency_us, transition_ms;
2355 table->entries[state] = target;
2358 * Don't allow transitions to the deepest state if it's quirked
2361 if (state == ctrl->npss &&
2362 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2366 * Is this state a useful non-operational state for higher-power
2367 * states to autonomously transition to?
2369 if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
2372 exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2373 if (exit_latency_us > ctrl->ps_max_latency_us)
2376 total_latency_us = exit_latency_us +
2377 le32_to_cpu(ctrl->psd[state].entry_lat);
2380 * This state is good. It can be used as the APST idle target
2381 * for higher power states.
2383 if (apst_primary_timeout_ms && apst_primary_latency_tol_us) {
2384 if (!nvme_apst_get_transition_time(total_latency_us,
2385 &transition_ms, &last_lt_index))
2388 transition_ms = total_latency_us + 19;
2389 do_div(transition_ms, 20);
2390 if (transition_ms > (1 << 24) - 1)
2391 transition_ms = (1 << 24) - 1;
2394 target = cpu_to_le64((state << 3) | (transition_ms << 8));
2397 if (total_latency_us > max_lat_us)
2398 max_lat_us = total_latency_us;
2402 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2404 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2405 max_ps, max_lat_us, (int)sizeof(*table), table);
2409 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2410 table, sizeof(*table), NULL);
2412 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2417 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2419 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2423 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2424 case PM_QOS_LATENCY_ANY:
2432 if (ctrl->ps_max_latency_us != latency) {
2433 ctrl->ps_max_latency_us = latency;
2434 if (ctrl->state == NVME_CTRL_LIVE)
2435 nvme_configure_apst(ctrl);
2439 struct nvme_core_quirk_entry {
2441 * NVMe model and firmware strings are padded with spaces. For
2442 * simplicity, strings in the quirk table are padded with NULLs
2448 unsigned long quirks;
2451 static const struct nvme_core_quirk_entry core_quirks[] = {
2454 * This Toshiba device seems to die using any APST states. See:
2455 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2458 .mn = "THNSF5256GPUK TOSHIBA",
2459 .quirks = NVME_QUIRK_NO_APST,
2463 * This LiteON CL1-3D*-Q11 firmware version has a race
2464 * condition associated with actions related to suspend to idle
2465 * LiteON has resolved the problem in future firmware
2469 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2473 /* match is null-terminated but idstr is space-padded. */
2474 static bool string_matches(const char *idstr, const char *match, size_t len)
2481 matchlen = strlen(match);
2482 WARN_ON_ONCE(matchlen > len);
2484 if (memcmp(idstr, match, matchlen))
2487 for (; matchlen < len; matchlen++)
2488 if (idstr[matchlen] != ' ')
2494 static bool quirk_matches(const struct nvme_id_ctrl *id,
2495 const struct nvme_core_quirk_entry *q)
2497 return q->vid == le16_to_cpu(id->vid) &&
2498 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2499 string_matches(id->fr, q->fr, sizeof(id->fr));
2502 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2503 struct nvme_id_ctrl *id)
2508 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2509 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2510 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2511 strlcpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2515 if (ctrl->vs >= NVME_VS(1, 2, 1))
2516 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2519 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2520 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2521 "nqn.2014.08.org.nvmexpress:%04x%04x",
2522 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2523 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2524 off += sizeof(id->sn);
2525 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2526 off += sizeof(id->mn);
2527 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2530 static void nvme_release_subsystem(struct device *dev)
2532 struct nvme_subsystem *subsys =
2533 container_of(dev, struct nvme_subsystem, dev);
2535 if (subsys->instance >= 0)
2536 ida_simple_remove(&nvme_instance_ida, subsys->instance);
2540 static void nvme_destroy_subsystem(struct kref *ref)
2542 struct nvme_subsystem *subsys =
2543 container_of(ref, struct nvme_subsystem, ref);
2545 mutex_lock(&nvme_subsystems_lock);
2546 list_del(&subsys->entry);
2547 mutex_unlock(&nvme_subsystems_lock);
2549 ida_destroy(&subsys->ns_ida);
2550 device_del(&subsys->dev);
2551 put_device(&subsys->dev);
2554 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2556 kref_put(&subsys->ref, nvme_destroy_subsystem);
2559 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2561 struct nvme_subsystem *subsys;
2563 lockdep_assert_held(&nvme_subsystems_lock);
2566 * Fail matches for discovery subsystems. This results
2567 * in each discovery controller bound to a unique subsystem.
2568 * This avoids issues with validating controller values
2569 * that can only be true when there is a single unique subsystem.
2570 * There may be multiple and completely independent entities
2571 * that provide discovery controllers.
2573 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2576 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2577 if (strcmp(subsys->subnqn, subsysnqn))
2579 if (!kref_get_unless_zero(&subsys->ref))
2587 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2588 struct device_attribute subsys_attr_##_name = \
2589 __ATTR(_name, _mode, _show, NULL)
2591 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2592 struct device_attribute *attr,
2595 struct nvme_subsystem *subsys =
2596 container_of(dev, struct nvme_subsystem, dev);
2598 return sysfs_emit(buf, "%s\n", subsys->subnqn);
2600 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2602 #define nvme_subsys_show_str_function(field) \
2603 static ssize_t subsys_##field##_show(struct device *dev, \
2604 struct device_attribute *attr, char *buf) \
2606 struct nvme_subsystem *subsys = \
2607 container_of(dev, struct nvme_subsystem, dev); \
2608 return sysfs_emit(buf, "%.*s\n", \
2609 (int)sizeof(subsys->field), subsys->field); \
2611 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2613 nvme_subsys_show_str_function(model);
2614 nvme_subsys_show_str_function(serial);
2615 nvme_subsys_show_str_function(firmware_rev);
2617 static struct attribute *nvme_subsys_attrs[] = {
2618 &subsys_attr_model.attr,
2619 &subsys_attr_serial.attr,
2620 &subsys_attr_firmware_rev.attr,
2621 &subsys_attr_subsysnqn.attr,
2622 #ifdef CONFIG_NVME_MULTIPATH
2623 &subsys_attr_iopolicy.attr,
2628 static const struct attribute_group nvme_subsys_attrs_group = {
2629 .attrs = nvme_subsys_attrs,
2632 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2633 &nvme_subsys_attrs_group,
2637 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
2639 return ctrl->opts && ctrl->opts->discovery_nqn;
2642 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2643 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2645 struct nvme_ctrl *tmp;
2647 lockdep_assert_held(&nvme_subsystems_lock);
2649 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2650 if (nvme_state_terminal(tmp))
2653 if (tmp->cntlid == ctrl->cntlid) {
2654 dev_err(ctrl->device,
2655 "Duplicate cntlid %u with %s, rejecting\n",
2656 ctrl->cntlid, dev_name(tmp->device));
2660 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2661 nvme_discovery_ctrl(ctrl))
2664 dev_err(ctrl->device,
2665 "Subsystem does not support multiple controllers\n");
2672 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2674 struct nvme_subsystem *subsys, *found;
2677 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2681 subsys->instance = -1;
2682 mutex_init(&subsys->lock);
2683 kref_init(&subsys->ref);
2684 INIT_LIST_HEAD(&subsys->ctrls);
2685 INIT_LIST_HEAD(&subsys->nsheads);
2686 nvme_init_subnqn(subsys, ctrl, id);
2687 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2688 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2689 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2690 subsys->vendor_id = le16_to_cpu(id->vid);
2691 subsys->cmic = id->cmic;
2692 subsys->awupf = le16_to_cpu(id->awupf);
2693 #ifdef CONFIG_NVME_MULTIPATH
2694 subsys->iopolicy = NVME_IOPOLICY_NUMA;
2697 subsys->dev.class = nvme_subsys_class;
2698 subsys->dev.release = nvme_release_subsystem;
2699 subsys->dev.groups = nvme_subsys_attrs_groups;
2700 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2701 device_initialize(&subsys->dev);
2703 mutex_lock(&nvme_subsystems_lock);
2704 found = __nvme_find_get_subsystem(subsys->subnqn);
2706 put_device(&subsys->dev);
2709 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2711 goto out_put_subsystem;
2714 ret = device_add(&subsys->dev);
2716 dev_err(ctrl->device,
2717 "failed to register subsystem device.\n");
2718 put_device(&subsys->dev);
2721 ida_init(&subsys->ns_ida);
2722 list_add_tail(&subsys->entry, &nvme_subsystems);
2725 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2726 dev_name(ctrl->device));
2728 dev_err(ctrl->device,
2729 "failed to create sysfs link from subsystem.\n");
2730 goto out_put_subsystem;
2734 subsys->instance = ctrl->instance;
2735 ctrl->subsys = subsys;
2736 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2737 mutex_unlock(&nvme_subsystems_lock);
2741 nvme_put_subsystem(subsys);
2743 mutex_unlock(&nvme_subsystems_lock);
2747 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2748 void *log, size_t size, u64 offset)
2750 struct nvme_command c = { };
2751 u32 dwlen = nvme_bytes_to_numd(size);
2753 c.get_log_page.opcode = nvme_admin_get_log_page;
2754 c.get_log_page.nsid = cpu_to_le32(nsid);
2755 c.get_log_page.lid = log_page;
2756 c.get_log_page.lsp = lsp;
2757 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2758 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2759 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2760 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2761 c.get_log_page.csi = csi;
2763 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2766 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
2767 struct nvme_effects_log **log)
2769 struct nvme_effects_log *cel = xa_load(&ctrl->cels, csi);
2775 cel = kzalloc(sizeof(*cel), GFP_KERNEL);
2779 ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
2780 cel, sizeof(*cel), 0);
2786 xa_store(&ctrl->cels, csi, cel, GFP_KERNEL);
2792 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
2794 u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
2796 if (check_shl_overflow(1U, units + page_shift - 9, &val))
2801 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
2803 struct nvme_command c = { };
2804 struct nvme_id_ctrl_nvm *id;
2807 if (ctrl->oncs & NVME_CTRL_ONCS_DSM) {
2808 ctrl->max_discard_sectors = UINT_MAX;
2809 ctrl->max_discard_segments = NVME_DSM_MAX_RANGES;
2811 ctrl->max_discard_sectors = 0;
2812 ctrl->max_discard_segments = 0;
2816 * Even though NVMe spec explicitly states that MDTS is not applicable
2817 * to the write-zeroes, we are cautious and limit the size to the
2818 * controllers max_hw_sectors value, which is based on the MDTS field
2819 * and possibly other limiting factors.
2821 if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
2822 !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
2823 ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
2825 ctrl->max_zeroes_sectors = 0;
2827 if (nvme_ctrl_limited_cns(ctrl))
2830 id = kzalloc(sizeof(*id), GFP_KERNEL);
2834 c.identify.opcode = nvme_admin_identify;
2835 c.identify.cns = NVME_ID_CNS_CS_CTRL;
2836 c.identify.csi = NVME_CSI_NVM;
2838 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
2843 ctrl->max_discard_segments = id->dmrl;
2845 ctrl->max_discard_sectors = le32_to_cpu(id->dmrsl);
2847 ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
2854 static int nvme_init_identify(struct nvme_ctrl *ctrl)
2856 struct nvme_id_ctrl *id;
2858 bool prev_apst_enabled;
2861 ret = nvme_identify_ctrl(ctrl, &id);
2863 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2867 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2868 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
2873 if (!(ctrl->ops->flags & NVME_F_FABRICS))
2874 ctrl->cntlid = le16_to_cpu(id->cntlid);
2876 if (!ctrl->identified) {
2879 ret = nvme_init_subsystem(ctrl, id);
2884 * Check for quirks. Quirk can depend on firmware version,
2885 * so, in principle, the set of quirks present can change
2886 * across a reset. As a possible future enhancement, we
2887 * could re-scan for quirks every time we reinitialize
2888 * the device, but we'd have to make sure that the driver
2889 * behaves intelligently if the quirks change.
2891 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2892 if (quirk_matches(id, &core_quirks[i]))
2893 ctrl->quirks |= core_quirks[i].quirks;
2897 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2898 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2899 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2902 ctrl->crdt[0] = le16_to_cpu(id->crdt1);
2903 ctrl->crdt[1] = le16_to_cpu(id->crdt2);
2904 ctrl->crdt[2] = le16_to_cpu(id->crdt3);
2906 ctrl->oacs = le16_to_cpu(id->oacs);
2907 ctrl->oncs = le16_to_cpu(id->oncs);
2908 ctrl->mtfa = le16_to_cpu(id->mtfa);
2909 ctrl->oaes = le32_to_cpu(id->oaes);
2910 ctrl->wctemp = le16_to_cpu(id->wctemp);
2911 ctrl->cctemp = le16_to_cpu(id->cctemp);
2913 atomic_set(&ctrl->abort_limit, id->acl + 1);
2914 ctrl->vwc = id->vwc;
2916 max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
2918 max_hw_sectors = UINT_MAX;
2919 ctrl->max_hw_sectors =
2920 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2922 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2923 ctrl->sgls = le32_to_cpu(id->sgls);
2924 ctrl->kas = le16_to_cpu(id->kas);
2925 ctrl->max_namespaces = le32_to_cpu(id->mnan);
2926 ctrl->ctratt = le32_to_cpu(id->ctratt);
2930 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
2932 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2933 shutdown_timeout, 60);
2935 if (ctrl->shutdown_timeout != shutdown_timeout)
2936 dev_info(ctrl->device,
2937 "Shutdown timeout set to %u seconds\n",
2938 ctrl->shutdown_timeout);
2940 ctrl->shutdown_timeout = shutdown_timeout;
2942 ctrl->npss = id->npss;
2943 ctrl->apsta = id->apsta;
2944 prev_apst_enabled = ctrl->apst_enabled;
2945 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2946 if (force_apst && id->apsta) {
2947 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2948 ctrl->apst_enabled = true;
2950 ctrl->apst_enabled = false;
2953 ctrl->apst_enabled = id->apsta;
2955 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2957 if (ctrl->ops->flags & NVME_F_FABRICS) {
2958 ctrl->icdoff = le16_to_cpu(id->icdoff);
2959 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2960 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2961 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2964 * In fabrics we need to verify the cntlid matches the
2967 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2968 dev_err(ctrl->device,
2969 "Mismatching cntlid: Connect %u vs Identify "
2971 ctrl->cntlid, le16_to_cpu(id->cntlid));
2976 if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
2977 dev_err(ctrl->device,
2978 "keep-alive support is mandatory for fabrics\n");
2983 ctrl->hmpre = le32_to_cpu(id->hmpre);
2984 ctrl->hmmin = le32_to_cpu(id->hmmin);
2985 ctrl->hmminds = le32_to_cpu(id->hmminds);
2986 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2989 ret = nvme_mpath_init_identify(ctrl, id);
2993 if (ctrl->apst_enabled && !prev_apst_enabled)
2994 dev_pm_qos_expose_latency_tolerance(ctrl->device);
2995 else if (!ctrl->apst_enabled && prev_apst_enabled)
2996 dev_pm_qos_hide_latency_tolerance(ctrl->device);
3004 * Initialize the cached copies of the Identify data and various controller
3005 * register in our nvme_ctrl structure. This should be called as soon as
3006 * the admin queue is fully up and running.
3008 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl)
3012 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3014 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3018 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3020 if (ctrl->vs >= NVME_VS(1, 1, 0))
3021 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3023 ret = nvme_init_identify(ctrl);
3027 ret = nvme_init_non_mdts_limits(ctrl);
3031 ret = nvme_configure_apst(ctrl);
3035 ret = nvme_configure_timestamp(ctrl);
3039 ret = nvme_configure_directives(ctrl);
3043 ret = nvme_configure_acre(ctrl);
3047 if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
3048 ret = nvme_hwmon_init(ctrl);
3053 ctrl->identified = true;
3057 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
3059 static int nvme_dev_open(struct inode *inode, struct file *file)
3061 struct nvme_ctrl *ctrl =
3062 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3064 switch (ctrl->state) {
3065 case NVME_CTRL_LIVE:
3068 return -EWOULDBLOCK;
3071 nvme_get_ctrl(ctrl);
3072 if (!try_module_get(ctrl->ops->module)) {
3073 nvme_put_ctrl(ctrl);
3077 file->private_data = ctrl;
3081 static int nvme_dev_release(struct inode *inode, struct file *file)
3083 struct nvme_ctrl *ctrl =
3084 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3086 module_put(ctrl->ops->module);
3087 nvme_put_ctrl(ctrl);
3091 static const struct file_operations nvme_dev_fops = {
3092 .owner = THIS_MODULE,
3093 .open = nvme_dev_open,
3094 .release = nvme_dev_release,
3095 .unlocked_ioctl = nvme_dev_ioctl,
3096 .compat_ioctl = compat_ptr_ioctl,
3099 static ssize_t nvme_sysfs_reset(struct device *dev,
3100 struct device_attribute *attr, const char *buf,
3103 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3106 ret = nvme_reset_ctrl_sync(ctrl);
3111 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
3113 static ssize_t nvme_sysfs_rescan(struct device *dev,
3114 struct device_attribute *attr, const char *buf,
3117 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3119 nvme_queue_scan(ctrl);
3122 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
3124 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
3126 struct gendisk *disk = dev_to_disk(dev);
3128 if (disk->fops == &nvme_bdev_ops)
3129 return nvme_get_ns_from_dev(dev)->head;
3131 return disk->private_data;
3134 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
3137 struct nvme_ns_head *head = dev_to_ns_head(dev);
3138 struct nvme_ns_ids *ids = &head->ids;
3139 struct nvme_subsystem *subsys = head->subsys;
3140 int serial_len = sizeof(subsys->serial);
3141 int model_len = sizeof(subsys->model);
3143 if (!uuid_is_null(&ids->uuid))
3144 return sysfs_emit(buf, "uuid.%pU\n", &ids->uuid);
3146 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3147 return sysfs_emit(buf, "eui.%16phN\n", ids->nguid);
3149 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3150 return sysfs_emit(buf, "eui.%8phN\n", ids->eui64);
3152 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
3153 subsys->serial[serial_len - 1] == '\0'))
3155 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
3156 subsys->model[model_len - 1] == '\0'))
3159 return sysfs_emit(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
3160 serial_len, subsys->serial, model_len, subsys->model,
3163 static DEVICE_ATTR_RO(wwid);
3165 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
3168 return sysfs_emit(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
3170 static DEVICE_ATTR_RO(nguid);
3172 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
3175 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3177 /* For backward compatibility expose the NGUID to userspace if
3178 * we have no UUID set
3180 if (uuid_is_null(&ids->uuid)) {
3181 printk_ratelimited(KERN_WARNING
3182 "No UUID available providing old NGUID\n");
3183 return sysfs_emit(buf, "%pU\n", ids->nguid);
3185 return sysfs_emit(buf, "%pU\n", &ids->uuid);
3187 static DEVICE_ATTR_RO(uuid);
3189 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
3192 return sysfs_emit(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
3194 static DEVICE_ATTR_RO(eui);
3196 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
3199 return sysfs_emit(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
3201 static DEVICE_ATTR_RO(nsid);
3203 static struct attribute *nvme_ns_id_attrs[] = {
3204 &dev_attr_wwid.attr,
3205 &dev_attr_uuid.attr,
3206 &dev_attr_nguid.attr,
3208 &dev_attr_nsid.attr,
3209 #ifdef CONFIG_NVME_MULTIPATH
3210 &dev_attr_ana_grpid.attr,
3211 &dev_attr_ana_state.attr,
3216 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
3217 struct attribute *a, int n)
3219 struct device *dev = container_of(kobj, struct device, kobj);
3220 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
3222 if (a == &dev_attr_uuid.attr) {
3223 if (uuid_is_null(&ids->uuid) &&
3224 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3227 if (a == &dev_attr_nguid.attr) {
3228 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
3231 if (a == &dev_attr_eui.attr) {
3232 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
3235 #ifdef CONFIG_NVME_MULTIPATH
3236 if (a == &dev_attr_ana_grpid.attr || a == &dev_attr_ana_state.attr) {
3237 if (dev_to_disk(dev)->fops != &nvme_bdev_ops) /* per-path attr */
3239 if (!nvme_ctrl_use_ana(nvme_get_ns_from_dev(dev)->ctrl))
3246 static const struct attribute_group nvme_ns_id_attr_group = {
3247 .attrs = nvme_ns_id_attrs,
3248 .is_visible = nvme_ns_id_attrs_are_visible,
3251 const struct attribute_group *nvme_ns_id_attr_groups[] = {
3252 &nvme_ns_id_attr_group,
3256 #define nvme_show_str_function(field) \
3257 static ssize_t field##_show(struct device *dev, \
3258 struct device_attribute *attr, char *buf) \
3260 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3261 return sysfs_emit(buf, "%.*s\n", \
3262 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
3264 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3266 nvme_show_str_function(model);
3267 nvme_show_str_function(serial);
3268 nvme_show_str_function(firmware_rev);
3270 #define nvme_show_int_function(field) \
3271 static ssize_t field##_show(struct device *dev, \
3272 struct device_attribute *attr, char *buf) \
3274 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
3275 return sysfs_emit(buf, "%d\n", ctrl->field); \
3277 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
3279 nvme_show_int_function(cntlid);
3280 nvme_show_int_function(numa_node);
3281 nvme_show_int_function(queue_count);
3282 nvme_show_int_function(sqsize);
3283 nvme_show_int_function(kato);
3285 static ssize_t nvme_sysfs_delete(struct device *dev,
3286 struct device_attribute *attr, const char *buf,
3289 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3291 if (device_remove_file_self(dev, attr))
3292 nvme_delete_ctrl_sync(ctrl);
3295 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
3297 static ssize_t nvme_sysfs_show_transport(struct device *dev,
3298 struct device_attribute *attr,
3301 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3303 return sysfs_emit(buf, "%s\n", ctrl->ops->name);
3305 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
3307 static ssize_t nvme_sysfs_show_state(struct device *dev,
3308 struct device_attribute *attr,
3311 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3312 static const char *const state_name[] = {
3313 [NVME_CTRL_NEW] = "new",
3314 [NVME_CTRL_LIVE] = "live",
3315 [NVME_CTRL_RESETTING] = "resetting",
3316 [NVME_CTRL_CONNECTING] = "connecting",
3317 [NVME_CTRL_DELETING] = "deleting",
3318 [NVME_CTRL_DELETING_NOIO]= "deleting (no IO)",
3319 [NVME_CTRL_DEAD] = "dead",
3322 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
3323 state_name[ctrl->state])
3324 return sysfs_emit(buf, "%s\n", state_name[ctrl->state]);
3326 return sysfs_emit(buf, "unknown state\n");
3329 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
3331 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
3332 struct device_attribute *attr,
3335 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3337 return sysfs_emit(buf, "%s\n", ctrl->subsys->subnqn);
3339 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
3341 static ssize_t nvme_sysfs_show_hostnqn(struct device *dev,
3342 struct device_attribute *attr,
3345 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3347 return sysfs_emit(buf, "%s\n", ctrl->opts->host->nqn);
3349 static DEVICE_ATTR(hostnqn, S_IRUGO, nvme_sysfs_show_hostnqn, NULL);
3351 static ssize_t nvme_sysfs_show_hostid(struct device *dev,
3352 struct device_attribute *attr,
3355 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3357 return sysfs_emit(buf, "%pU\n", &ctrl->opts->host->id);
3359 static DEVICE_ATTR(hostid, S_IRUGO, nvme_sysfs_show_hostid, NULL);
3361 static ssize_t nvme_sysfs_show_address(struct device *dev,
3362 struct device_attribute *attr,
3365 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3367 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
3369 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
3371 static ssize_t nvme_ctrl_loss_tmo_show(struct device *dev,
3372 struct device_attribute *attr, char *buf)
3374 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3375 struct nvmf_ctrl_options *opts = ctrl->opts;
3377 if (ctrl->opts->max_reconnects == -1)
3378 return sysfs_emit(buf, "off\n");
3379 return sysfs_emit(buf, "%d\n",
3380 opts->max_reconnects * opts->reconnect_delay);
3383 static ssize_t nvme_ctrl_loss_tmo_store(struct device *dev,
3384 struct device_attribute *attr, const char *buf, size_t count)
3386 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3387 struct nvmf_ctrl_options *opts = ctrl->opts;
3388 int ctrl_loss_tmo, err;
3390 err = kstrtoint(buf, 10, &ctrl_loss_tmo);
3394 if (ctrl_loss_tmo < 0)
3395 opts->max_reconnects = -1;
3397 opts->max_reconnects = DIV_ROUND_UP(ctrl_loss_tmo,
3398 opts->reconnect_delay);
3401 static DEVICE_ATTR(ctrl_loss_tmo, S_IRUGO | S_IWUSR,
3402 nvme_ctrl_loss_tmo_show, nvme_ctrl_loss_tmo_store);
3404 static ssize_t nvme_ctrl_reconnect_delay_show(struct device *dev,
3405 struct device_attribute *attr, char *buf)
3407 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3409 if (ctrl->opts->reconnect_delay == -1)
3410 return sysfs_emit(buf, "off\n");
3411 return sysfs_emit(buf, "%d\n", ctrl->opts->reconnect_delay);
3414 static ssize_t nvme_ctrl_reconnect_delay_store(struct device *dev,
3415 struct device_attribute *attr, const char *buf, size_t count)
3417 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3421 err = kstrtou32(buf, 10, &v);
3425 ctrl->opts->reconnect_delay = v;
3428 static DEVICE_ATTR(reconnect_delay, S_IRUGO | S_IWUSR,
3429 nvme_ctrl_reconnect_delay_show, nvme_ctrl_reconnect_delay_store);
3431 static ssize_t nvme_ctrl_fast_io_fail_tmo_show(struct device *dev,
3432 struct device_attribute *attr, char *buf)
3434 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3436 if (ctrl->opts->fast_io_fail_tmo == -1)
3437 return sysfs_emit(buf, "off\n");
3438 return sysfs_emit(buf, "%d\n", ctrl->opts->fast_io_fail_tmo);
3441 static ssize_t nvme_ctrl_fast_io_fail_tmo_store(struct device *dev,
3442 struct device_attribute *attr, const char *buf, size_t count)
3444 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3445 struct nvmf_ctrl_options *opts = ctrl->opts;
3446 int fast_io_fail_tmo, err;
3448 err = kstrtoint(buf, 10, &fast_io_fail_tmo);
3452 if (fast_io_fail_tmo < 0)
3453 opts->fast_io_fail_tmo = -1;
3455 opts->fast_io_fail_tmo = fast_io_fail_tmo;
3458 static DEVICE_ATTR(fast_io_fail_tmo, S_IRUGO | S_IWUSR,
3459 nvme_ctrl_fast_io_fail_tmo_show, nvme_ctrl_fast_io_fail_tmo_store);
3461 static struct attribute *nvme_dev_attrs[] = {
3462 &dev_attr_reset_controller.attr,
3463 &dev_attr_rescan_controller.attr,
3464 &dev_attr_model.attr,
3465 &dev_attr_serial.attr,
3466 &dev_attr_firmware_rev.attr,
3467 &dev_attr_cntlid.attr,
3468 &dev_attr_delete_controller.attr,
3469 &dev_attr_transport.attr,
3470 &dev_attr_subsysnqn.attr,
3471 &dev_attr_address.attr,
3472 &dev_attr_state.attr,
3473 &dev_attr_numa_node.attr,
3474 &dev_attr_queue_count.attr,
3475 &dev_attr_sqsize.attr,
3476 &dev_attr_hostnqn.attr,
3477 &dev_attr_hostid.attr,
3478 &dev_attr_ctrl_loss_tmo.attr,
3479 &dev_attr_reconnect_delay.attr,
3480 &dev_attr_fast_io_fail_tmo.attr,
3481 &dev_attr_kato.attr,
3485 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
3486 struct attribute *a, int n)
3488 struct device *dev = container_of(kobj, struct device, kobj);
3489 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
3491 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
3493 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
3495 if (a == &dev_attr_hostnqn.attr && !ctrl->opts)
3497 if (a == &dev_attr_hostid.attr && !ctrl->opts)
3499 if (a == &dev_attr_ctrl_loss_tmo.attr && !ctrl->opts)
3501 if (a == &dev_attr_reconnect_delay.attr && !ctrl->opts)
3503 if (a == &dev_attr_fast_io_fail_tmo.attr && !ctrl->opts)
3509 static const struct attribute_group nvme_dev_attrs_group = {
3510 .attrs = nvme_dev_attrs,
3511 .is_visible = nvme_dev_attrs_are_visible,
3514 static const struct attribute_group *nvme_dev_attr_groups[] = {
3515 &nvme_dev_attrs_group,
3519 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_subsystem *subsys,
3522 struct nvme_ns_head *h;
3524 lockdep_assert_held(&subsys->lock);
3526 list_for_each_entry(h, &subsys->nsheads, entry) {
3527 if (h->ns_id != nsid)
3529 if (!list_empty(&h->list) && nvme_tryget_ns_head(h))
3536 static int __nvme_check_ids(struct nvme_subsystem *subsys,
3537 struct nvme_ns_head *new)
3539 struct nvme_ns_head *h;
3541 lockdep_assert_held(&subsys->lock);
3543 list_for_each_entry(h, &subsys->nsheads, entry) {
3544 if (nvme_ns_ids_valid(&new->ids) &&
3545 nvme_ns_ids_equal(&new->ids, &h->ids))
3552 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
3554 cdev_device_del(cdev, cdev_device);
3555 ida_simple_remove(&nvme_ns_chr_minor_ida, MINOR(cdev_device->devt));
3558 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
3559 const struct file_operations *fops, struct module *owner)
3563 minor = ida_simple_get(&nvme_ns_chr_minor_ida, 0, 0, GFP_KERNEL);
3566 cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
3567 cdev_device->class = nvme_ns_chr_class;
3568 device_initialize(cdev_device);
3569 cdev_init(cdev, fops);
3570 cdev->owner = owner;
3571 ret = cdev_device_add(cdev, cdev_device);
3573 put_device(cdev_device);
3574 ida_simple_remove(&nvme_ns_chr_minor_ida, minor);
3579 static int nvme_ns_chr_open(struct inode *inode, struct file *file)
3581 return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
3584 static int nvme_ns_chr_release(struct inode *inode, struct file *file)
3586 nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
3590 static const struct file_operations nvme_ns_chr_fops = {
3591 .owner = THIS_MODULE,
3592 .open = nvme_ns_chr_open,
3593 .release = nvme_ns_chr_release,
3594 .unlocked_ioctl = nvme_ns_chr_ioctl,
3595 .compat_ioctl = compat_ptr_ioctl,
3598 static int nvme_add_ns_cdev(struct nvme_ns *ns)
3602 ns->cdev_device.parent = ns->ctrl->device;
3603 ret = dev_set_name(&ns->cdev_device, "ng%dn%d",
3604 ns->ctrl->instance, ns->head->instance);
3607 ret = nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops,
3608 ns->ctrl->ops->module);
3610 kfree_const(ns->cdev_device.kobj.name);
3614 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3615 unsigned nsid, struct nvme_ns_ids *ids)
3617 struct nvme_ns_head *head;
3618 size_t size = sizeof(*head);
3621 #ifdef CONFIG_NVME_MULTIPATH
3622 size += num_possible_nodes() * sizeof(struct nvme_ns *);
3625 head = kzalloc(size, GFP_KERNEL);
3628 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
3631 head->instance = ret;
3632 INIT_LIST_HEAD(&head->list);
3633 ret = init_srcu_struct(&head->srcu);
3635 goto out_ida_remove;
3636 head->subsys = ctrl->subsys;
3639 kref_init(&head->ref);
3641 ret = __nvme_check_ids(ctrl->subsys, head);
3643 dev_err(ctrl->device,
3644 "duplicate IDs for nsid %d\n", nsid);
3645 goto out_cleanup_srcu;
3648 if (head->ids.csi) {
3649 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3651 goto out_cleanup_srcu;
3653 head->effects = ctrl->effects;
3655 ret = nvme_mpath_alloc_disk(ctrl, head);
3657 goto out_cleanup_srcu;
3659 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3661 kref_get(&ctrl->subsys->ref);
3665 cleanup_srcu_struct(&head->srcu);
3667 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
3672 ret = blk_status_to_errno(nvme_error_status(ret));
3673 return ERR_PTR(ret);
3676 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
3677 struct nvme_ns_ids *ids, bool is_shared)
3679 struct nvme_ctrl *ctrl = ns->ctrl;
3680 struct nvme_ns_head *head = NULL;
3683 mutex_lock(&ctrl->subsys->lock);
3684 head = nvme_find_ns_head(ctrl->subsys, nsid);
3686 head = nvme_alloc_ns_head(ctrl, nsid, ids);
3688 ret = PTR_ERR(head);
3691 head->shared = is_shared;
3694 if (!is_shared || !head->shared) {
3695 dev_err(ctrl->device,
3696 "Duplicate unshared namespace %d\n", nsid);
3697 goto out_put_ns_head;
3699 if (!nvme_ns_ids_equal(&head->ids, ids)) {
3700 dev_err(ctrl->device,
3701 "IDs don't match for shared namespace %d\n",
3703 goto out_put_ns_head;
3707 list_add_tail_rcu(&ns->siblings, &head->list);
3709 mutex_unlock(&ctrl->subsys->lock);
3713 nvme_put_ns_head(head);
3715 mutex_unlock(&ctrl->subsys->lock);
3719 static int ns_cmp(void *priv, const struct list_head *a,
3720 const struct list_head *b)
3722 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
3723 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
3725 return nsa->head->ns_id - nsb->head->ns_id;
3728 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3730 struct nvme_ns *ns, *ret = NULL;
3732 down_read(&ctrl->namespaces_rwsem);
3733 list_for_each_entry(ns, &ctrl->namespaces, list) {
3734 if (ns->head->ns_id == nsid) {
3735 if (!nvme_get_ns(ns))
3740 if (ns->head->ns_id > nsid)
3743 up_read(&ctrl->namespaces_rwsem);
3746 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3748 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid,
3749 struct nvme_ns_ids *ids)
3752 struct gendisk *disk;
3753 struct nvme_id_ns *id;
3754 int node = ctrl->numa_node;
3756 if (nvme_identify_ns(ctrl, nsid, ids, &id))
3759 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3763 disk = blk_mq_alloc_disk(ctrl->tagset, ns);
3766 disk->fops = &nvme_bdev_ops;
3767 disk->private_data = ns;
3770 ns->queue = disk->queue;
3772 if (ctrl->opts && ctrl->opts->data_digest)
3773 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, ns->queue);
3775 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3776 if (ctrl->ops->flags & NVME_F_PCI_P2PDMA)
3777 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3780 kref_init(&ns->kref);
3782 if (nvme_init_ns_head(ns, nsid, ids, id->nmic & NVME_NS_NMIC_SHARED))
3783 goto out_cleanup_disk;
3786 * Without the multipath code enabled, multiple controller per
3787 * subsystems are visible as devices and thus we cannot use the
3788 * subsystem instance.
3790 if (!nvme_mpath_set_disk_name(ns, disk->disk_name, &disk->flags))
3791 sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
3792 ns->head->instance);
3794 if (nvme_update_ns_info(ns, id))
3797 down_write(&ctrl->namespaces_rwsem);
3798 list_add_tail(&ns->list, &ctrl->namespaces);
3799 up_write(&ctrl->namespaces_rwsem);
3801 nvme_get_ctrl(ctrl);
3803 if (device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups))
3804 goto out_cleanup_ns_from_list;
3806 if (!nvme_ns_head_multipath(ns->head))
3807 nvme_add_ns_cdev(ns);
3809 nvme_mpath_add_disk(ns, id);
3810 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3815 out_cleanup_ns_from_list:
3816 nvme_put_ctrl(ctrl);
3817 down_write(&ctrl->namespaces_rwsem);
3818 list_del_init(&ns->list);
3819 up_write(&ctrl->namespaces_rwsem);
3821 mutex_lock(&ctrl->subsys->lock);
3822 list_del_rcu(&ns->siblings);
3823 if (list_empty(&ns->head->list))
3824 list_del_init(&ns->head->entry);
3825 mutex_unlock(&ctrl->subsys->lock);
3826 nvme_put_ns_head(ns->head);
3828 blk_cleanup_disk(disk);
3835 static void nvme_ns_remove(struct nvme_ns *ns)
3837 bool last_path = false;
3839 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3842 clear_bit(NVME_NS_READY, &ns->flags);
3843 set_capacity(ns->disk, 0);
3844 nvme_fault_inject_fini(&ns->fault_inject);
3846 mutex_lock(&ns->ctrl->subsys->lock);
3847 list_del_rcu(&ns->siblings);
3848 if (list_empty(&ns->head->list)) {
3849 list_del_init(&ns->head->entry);
3852 mutex_unlock(&ns->ctrl->subsys->lock);
3854 /* guarantee not available in head->list */
3857 /* wait for concurrent submissions */
3858 if (nvme_mpath_clear_current_path(ns))
3859 synchronize_srcu(&ns->head->srcu);
3861 if (!nvme_ns_head_multipath(ns->head))
3862 nvme_cdev_del(&ns->cdev, &ns->cdev_device);
3863 del_gendisk(ns->disk);
3864 blk_cleanup_queue(ns->queue);
3866 down_write(&ns->ctrl->namespaces_rwsem);
3867 list_del_init(&ns->list);
3868 up_write(&ns->ctrl->namespaces_rwsem);
3871 nvme_mpath_shutdown_disk(ns->head);
3875 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
3877 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
3885 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_ids *ids)
3887 struct nvme_id_ns *id;
3888 int ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3890 if (test_bit(NVME_NS_DEAD, &ns->flags))
3893 ret = nvme_identify_ns(ns->ctrl, ns->head->ns_id, ids, &id);
3897 ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3898 if (!nvme_ns_ids_equal(&ns->head->ids, ids)) {
3899 dev_err(ns->ctrl->device,
3900 "identifiers changed for nsid %d\n", ns->head->ns_id);
3904 ret = nvme_update_ns_info(ns, id);
3910 * Only remove the namespace if we got a fatal error back from the
3911 * device, otherwise ignore the error and just move on.
3913 * TODO: we should probably schedule a delayed retry here.
3915 if (ret > 0 && (ret & NVME_SC_DNR))
3919 static void nvme_validate_or_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3921 struct nvme_ns_ids ids = { };
3924 if (nvme_identify_ns_descs(ctrl, nsid, &ids))
3927 ns = nvme_find_get_ns(ctrl, nsid);
3929 nvme_validate_ns(ns, &ids);
3936 nvme_alloc_ns(ctrl, nsid, &ids);
3939 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
3940 dev_warn(ctrl->device,
3941 "nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
3945 if (!nvme_multi_css(ctrl)) {
3946 dev_warn(ctrl->device,
3947 "command set not reported for nsid: %d\n",
3951 nvme_alloc_ns(ctrl, nsid, &ids);
3954 dev_warn(ctrl->device, "unknown csi %u for nsid %u\n",
3960 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3963 struct nvme_ns *ns, *next;
3966 down_write(&ctrl->namespaces_rwsem);
3967 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3968 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
3969 list_move_tail(&ns->list, &rm_list);
3971 up_write(&ctrl->namespaces_rwsem);
3973 list_for_each_entry_safe(ns, next, &rm_list, list)
3978 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
3980 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
3985 if (nvme_ctrl_limited_cns(ctrl))
3988 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3993 struct nvme_command cmd = {
3994 .identify.opcode = nvme_admin_identify,
3995 .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST,
3996 .identify.nsid = cpu_to_le32(prev),
3999 ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
4000 NVME_IDENTIFY_DATA_SIZE);
4002 dev_warn(ctrl->device,
4003 "Identify NS List failed (status=0x%x)\n", ret);
4007 for (i = 0; i < nr_entries; i++) {
4008 u32 nsid = le32_to_cpu(ns_list[i]);
4010 if (!nsid) /* end of the list? */
4012 nvme_validate_or_alloc_ns(ctrl, nsid);
4013 while (++prev < nsid)
4014 nvme_ns_remove_by_nsid(ctrl, prev);
4018 nvme_remove_invalid_namespaces(ctrl, prev);
4024 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
4026 struct nvme_id_ctrl *id;
4029 if (nvme_identify_ctrl(ctrl, &id))
4031 nn = le32_to_cpu(id->nn);
4034 for (i = 1; i <= nn; i++)
4035 nvme_validate_or_alloc_ns(ctrl, i);
4037 nvme_remove_invalid_namespaces(ctrl, nn);
4040 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
4042 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
4046 log = kzalloc(log_size, GFP_KERNEL);
4051 * We need to read the log to clear the AEN, but we don't want to rely
4052 * on it for the changed namespace information as userspace could have
4053 * raced with us in reading the log page, which could cause us to miss
4056 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
4057 NVME_CSI_NVM, log, log_size, 0);
4059 dev_warn(ctrl->device,
4060 "reading changed ns log failed: %d\n", error);
4065 static void nvme_scan_work(struct work_struct *work)
4067 struct nvme_ctrl *ctrl =
4068 container_of(work, struct nvme_ctrl, scan_work);
4070 /* No tagset on a live ctrl means IO queues could not created */
4071 if (ctrl->state != NVME_CTRL_LIVE || !ctrl->tagset)
4074 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
4075 dev_info(ctrl->device, "rescanning namespaces.\n");
4076 nvme_clear_changed_ns_log(ctrl);
4079 mutex_lock(&ctrl->scan_lock);
4080 if (nvme_scan_ns_list(ctrl) != 0)
4081 nvme_scan_ns_sequential(ctrl);
4082 mutex_unlock(&ctrl->scan_lock);
4084 down_write(&ctrl->namespaces_rwsem);
4085 list_sort(NULL, &ctrl->namespaces, ns_cmp);
4086 up_write(&ctrl->namespaces_rwsem);
4090 * This function iterates the namespace list unlocked to allow recovery from
4091 * controller failure. It is up to the caller to ensure the namespace list is
4092 * not modified by scan work while this function is executing.
4094 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
4096 struct nvme_ns *ns, *next;
4100 * make sure to requeue I/O to all namespaces as these
4101 * might result from the scan itself and must complete
4102 * for the scan_work to make progress
4104 nvme_mpath_clear_ctrl_paths(ctrl);
4106 /* prevent racing with ns scanning */
4107 flush_work(&ctrl->scan_work);
4110 * The dead states indicates the controller was not gracefully
4111 * disconnected. In that case, we won't be able to flush any data while
4112 * removing the namespaces' disks; fail all the queues now to avoid
4113 * potentially having to clean up the failed sync later.
4115 if (ctrl->state == NVME_CTRL_DEAD)
4116 nvme_kill_queues(ctrl);
4118 /* this is a no-op when called from the controller reset handler */
4119 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4121 down_write(&ctrl->namespaces_rwsem);
4122 list_splice_init(&ctrl->namespaces, &ns_list);
4123 up_write(&ctrl->namespaces_rwsem);
4125 list_for_each_entry_safe(ns, next, &ns_list, list)
4128 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4130 static int nvme_class_uevent(struct device *dev, struct kobj_uevent_env *env)
4132 struct nvme_ctrl *ctrl =
4133 container_of(dev, struct nvme_ctrl, ctrl_device);
4134 struct nvmf_ctrl_options *opts = ctrl->opts;
4137 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4142 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4146 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4147 opts->trsvcid ?: "none");
4151 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4152 opts->host_traddr ?: "none");
4156 ret = add_uevent_var(env, "NVME_HOST_IFACE=%s",
4157 opts->host_iface ?: "none");
4162 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4164 char *envp[2] = { NULL, NULL };
4165 u32 aen_result = ctrl->aen_result;
4167 ctrl->aen_result = 0;
4171 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4174 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4178 static void nvme_async_event_work(struct work_struct *work)
4180 struct nvme_ctrl *ctrl =
4181 container_of(work, struct nvme_ctrl, async_event_work);
4183 nvme_aen_uevent(ctrl);
4184 ctrl->ops->submit_async_event(ctrl);
4187 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4192 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4198 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4201 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4203 struct nvme_fw_slot_info_log *log;
4205 log = kmalloc(sizeof(*log), GFP_KERNEL);
4209 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4210 log, sizeof(*log), 0))
4211 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4215 static void nvme_fw_act_work(struct work_struct *work)
4217 struct nvme_ctrl *ctrl = container_of(work,
4218 struct nvme_ctrl, fw_act_work);
4219 unsigned long fw_act_timeout;
4222 fw_act_timeout = jiffies +
4223 msecs_to_jiffies(ctrl->mtfa * 100);
4225 fw_act_timeout = jiffies +
4226 msecs_to_jiffies(admin_timeout * 1000);
4228 nvme_stop_queues(ctrl);
4229 while (nvme_ctrl_pp_status(ctrl)) {
4230 if (time_after(jiffies, fw_act_timeout)) {
4231 dev_warn(ctrl->device,
4232 "Fw activation timeout, reset controller\n");
4233 nvme_try_sched_reset(ctrl);
4239 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4242 nvme_start_queues(ctrl);
4243 /* read FW slot information to clear the AER */
4244 nvme_get_fw_slot_info(ctrl);
4247 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4249 u32 aer_notice_type = (result & 0xff00) >> 8;
4251 trace_nvme_async_event(ctrl, aer_notice_type);
4253 switch (aer_notice_type) {
4254 case NVME_AER_NOTICE_NS_CHANGED:
4255 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4256 nvme_queue_scan(ctrl);
4258 case NVME_AER_NOTICE_FW_ACT_STARTING:
4260 * We are (ab)using the RESETTING state to prevent subsequent
4261 * recovery actions from interfering with the controller's
4262 * firmware activation.
4264 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
4265 queue_work(nvme_wq, &ctrl->fw_act_work);
4267 #ifdef CONFIG_NVME_MULTIPATH
4268 case NVME_AER_NOTICE_ANA:
4269 if (!ctrl->ana_log_buf)
4271 queue_work(nvme_wq, &ctrl->ana_work);
4274 case NVME_AER_NOTICE_DISC_CHANGED:
4275 ctrl->aen_result = result;
4278 dev_warn(ctrl->device, "async event result %08x\n", result);
4282 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4283 volatile union nvme_result *res)
4285 u32 result = le32_to_cpu(res->u32);
4286 u32 aer_type = result & 0x07;
4288 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4292 case NVME_AER_NOTICE:
4293 nvme_handle_aen_notice(ctrl, result);
4295 case NVME_AER_ERROR:
4296 case NVME_AER_SMART:
4299 trace_nvme_async_event(ctrl, aer_type);
4300 ctrl->aen_result = result;
4305 queue_work(nvme_wq, &ctrl->async_event_work);
4307 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4309 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4311 nvme_mpath_stop(ctrl);
4312 nvme_stop_keep_alive(ctrl);
4313 nvme_stop_failfast_work(ctrl);
4314 flush_work(&ctrl->async_event_work);
4315 cancel_work_sync(&ctrl->fw_act_work);
4317 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4319 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4321 nvme_start_keep_alive(ctrl);
4323 nvme_enable_aen(ctrl);
4325 if (ctrl->queue_count > 1) {
4326 nvme_queue_scan(ctrl);
4327 nvme_start_queues(ctrl);
4330 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4332 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4334 nvme_hwmon_exit(ctrl);
4335 nvme_fault_inject_fini(&ctrl->fault_inject);
4336 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4337 cdev_device_del(&ctrl->cdev, ctrl->device);
4338 nvme_put_ctrl(ctrl);
4340 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4342 static void nvme_free_cels(struct nvme_ctrl *ctrl)
4344 struct nvme_effects_log *cel;
4347 xa_for_each(&ctrl->cels, i, cel) {
4348 xa_erase(&ctrl->cels, i);
4352 xa_destroy(&ctrl->cels);
4355 static void nvme_free_ctrl(struct device *dev)
4357 struct nvme_ctrl *ctrl =
4358 container_of(dev, struct nvme_ctrl, ctrl_device);
4359 struct nvme_subsystem *subsys = ctrl->subsys;
4361 if (!subsys || ctrl->instance != subsys->instance)
4362 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4364 nvme_free_cels(ctrl);
4365 nvme_mpath_uninit(ctrl);
4366 __free_page(ctrl->discard_page);
4369 mutex_lock(&nvme_subsystems_lock);
4370 list_del(&ctrl->subsys_entry);
4371 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4372 mutex_unlock(&nvme_subsystems_lock);
4375 ctrl->ops->free_ctrl(ctrl);
4378 nvme_put_subsystem(subsys);
4382 * Initialize a NVMe controller structures. This needs to be called during
4383 * earliest initialization so that we have the initialized structured around
4386 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4387 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4391 ctrl->state = NVME_CTRL_NEW;
4392 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
4393 spin_lock_init(&ctrl->lock);
4394 mutex_init(&ctrl->scan_lock);
4395 INIT_LIST_HEAD(&ctrl->namespaces);
4396 xa_init(&ctrl->cels);
4397 init_rwsem(&ctrl->namespaces_rwsem);
4400 ctrl->quirks = quirks;
4401 ctrl->numa_node = NUMA_NO_NODE;
4402 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4403 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4404 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4405 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4406 init_waitqueue_head(&ctrl->state_wq);
4408 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4409 INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
4410 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4411 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4413 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4415 ctrl->discard_page = alloc_page(GFP_KERNEL);
4416 if (!ctrl->discard_page) {
4421 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
4424 ctrl->instance = ret;
4426 device_initialize(&ctrl->ctrl_device);
4427 ctrl->device = &ctrl->ctrl_device;
4428 ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
4430 ctrl->device->class = nvme_class;
4431 ctrl->device->parent = ctrl->dev;
4432 ctrl->device->groups = nvme_dev_attr_groups;
4433 ctrl->device->release = nvme_free_ctrl;
4434 dev_set_drvdata(ctrl->device, ctrl);
4435 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4437 goto out_release_instance;
4439 nvme_get_ctrl(ctrl);
4440 cdev_init(&ctrl->cdev, &nvme_dev_fops);
4441 ctrl->cdev.owner = ops->module;
4442 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4447 * Initialize latency tolerance controls. The sysfs files won't
4448 * be visible to userspace unless the device actually supports APST.
4450 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4451 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4452 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4454 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4455 nvme_mpath_init_ctrl(ctrl);
4459 nvme_put_ctrl(ctrl);
4460 kfree_const(ctrl->device->kobj.name);
4461 out_release_instance:
4462 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
4464 if (ctrl->discard_page)
4465 __free_page(ctrl->discard_page);
4468 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4471 * nvme_kill_queues(): Ends all namespace queues
4472 * @ctrl: the dead controller that needs to end
4474 * Call this function when the driver determines it is unable to get the
4475 * controller in a state capable of servicing IO.
4477 void nvme_kill_queues(struct nvme_ctrl *ctrl)
4481 down_read(&ctrl->namespaces_rwsem);
4483 /* Forcibly unquiesce queues to avoid blocking dispatch */
4484 if (ctrl->admin_q && !blk_queue_dying(ctrl->admin_q))
4485 blk_mq_unquiesce_queue(ctrl->admin_q);
4487 list_for_each_entry(ns, &ctrl->namespaces, list)
4488 nvme_set_queue_dying(ns);
4490 up_read(&ctrl->namespaces_rwsem);
4492 EXPORT_SYMBOL_GPL(nvme_kill_queues);
4494 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4498 down_read(&ctrl->namespaces_rwsem);
4499 list_for_each_entry(ns, &ctrl->namespaces, list)
4500 blk_mq_unfreeze_queue(ns->queue);
4501 up_read(&ctrl->namespaces_rwsem);
4503 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4505 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4509 down_read(&ctrl->namespaces_rwsem);
4510 list_for_each_entry(ns, &ctrl->namespaces, list) {
4511 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4515 up_read(&ctrl->namespaces_rwsem);
4518 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4520 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4524 down_read(&ctrl->namespaces_rwsem);
4525 list_for_each_entry(ns, &ctrl->namespaces, list)
4526 blk_mq_freeze_queue_wait(ns->queue);
4527 up_read(&ctrl->namespaces_rwsem);
4529 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4531 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4535 down_read(&ctrl->namespaces_rwsem);
4536 list_for_each_entry(ns, &ctrl->namespaces, list)
4537 blk_freeze_queue_start(ns->queue);
4538 up_read(&ctrl->namespaces_rwsem);
4540 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4542 void nvme_stop_queues(struct nvme_ctrl *ctrl)
4546 down_read(&ctrl->namespaces_rwsem);
4547 list_for_each_entry(ns, &ctrl->namespaces, list)
4548 blk_mq_quiesce_queue(ns->queue);
4549 up_read(&ctrl->namespaces_rwsem);
4551 EXPORT_SYMBOL_GPL(nvme_stop_queues);
4553 void nvme_start_queues(struct nvme_ctrl *ctrl)
4557 down_read(&ctrl->namespaces_rwsem);
4558 list_for_each_entry(ns, &ctrl->namespaces, list)
4559 blk_mq_unquiesce_queue(ns->queue);
4560 up_read(&ctrl->namespaces_rwsem);
4562 EXPORT_SYMBOL_GPL(nvme_start_queues);
4564 void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
4568 down_read(&ctrl->namespaces_rwsem);
4569 list_for_each_entry(ns, &ctrl->namespaces, list)
4570 blk_sync_queue(ns->queue);
4571 up_read(&ctrl->namespaces_rwsem);
4573 EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
4575 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4577 nvme_sync_io_queues(ctrl);
4579 blk_sync_queue(ctrl->admin_q);
4581 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4583 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
4585 if (file->f_op != &nvme_dev_fops)
4587 return file->private_data;
4589 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU);
4592 * Check we didn't inadvertently grow the command structure sizes:
4594 static inline void _nvme_check_size(void)
4596 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4597 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4598 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4599 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4600 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4601 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4602 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4603 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4604 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4605 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4606 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4607 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4608 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4609 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4610 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4611 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
4612 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4613 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4614 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4615 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4619 static int __init nvme_core_init(void)
4621 int result = -ENOMEM;
4625 nvme_wq = alloc_workqueue("nvme-wq",
4626 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4630 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4631 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4635 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4636 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4637 if (!nvme_delete_wq)
4638 goto destroy_reset_wq;
4640 result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
4641 NVME_MINORS, "nvme");
4643 goto destroy_delete_wq;
4645 nvme_class = class_create(THIS_MODULE, "nvme");
4646 if (IS_ERR(nvme_class)) {
4647 result = PTR_ERR(nvme_class);
4648 goto unregister_chrdev;
4650 nvme_class->dev_uevent = nvme_class_uevent;
4652 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
4653 if (IS_ERR(nvme_subsys_class)) {
4654 result = PTR_ERR(nvme_subsys_class);
4658 result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
4661 goto destroy_subsys_class;
4663 nvme_ns_chr_class = class_create(THIS_MODULE, "nvme-generic");
4664 if (IS_ERR(nvme_ns_chr_class)) {
4665 result = PTR_ERR(nvme_ns_chr_class);
4666 goto unregister_generic_ns;
4671 unregister_generic_ns:
4672 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4673 destroy_subsys_class:
4674 class_destroy(nvme_subsys_class);
4676 class_destroy(nvme_class);
4678 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4680 destroy_workqueue(nvme_delete_wq);
4682 destroy_workqueue(nvme_reset_wq);
4684 destroy_workqueue(nvme_wq);
4689 static void __exit nvme_core_exit(void)
4691 class_destroy(nvme_ns_chr_class);
4692 class_destroy(nvme_subsys_class);
4693 class_destroy(nvme_class);
4694 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4695 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4696 destroy_workqueue(nvme_delete_wq);
4697 destroy_workqueue(nvme_reset_wq);
4698 destroy_workqueue(nvme_wq);
4699 ida_destroy(&nvme_ns_chr_minor_ida);
4700 ida_destroy(&nvme_instance_ida);
4703 MODULE_LICENSE("GPL");
4704 MODULE_VERSION("1.0");
4705 module_init(nvme_core_init);
4706 module_exit(nvme_core_exit);