2 * NVM Express device driver
3 * Copyright (c) 2011-2014, Intel Corporation.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms and conditions of the GNU General Public License,
7 * version 2, as published by the Free Software Foundation.
9 * This program is distributed in the hope it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <linux/pm_qos.h>
30 #include <asm/unaligned.h>
32 #define CREATE_TRACE_POINTS
38 #define NVME_MINORS (1U << MINORBITS)
40 unsigned int admin_timeout = 60;
41 module_param(admin_timeout, uint, 0644);
42 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
43 EXPORT_SYMBOL_GPL(admin_timeout);
45 unsigned int nvme_io_timeout = 30;
46 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
47 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
48 EXPORT_SYMBOL_GPL(nvme_io_timeout);
50 static unsigned char shutdown_timeout = 5;
51 module_param(shutdown_timeout, byte, 0644);
52 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
54 static u8 nvme_max_retries = 5;
55 module_param_named(max_retries, nvme_max_retries, byte, 0644);
56 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
58 static unsigned long default_ps_max_latency_us = 100000;
59 module_param(default_ps_max_latency_us, ulong, 0644);
60 MODULE_PARM_DESC(default_ps_max_latency_us,
61 "max power saving latency for new devices; use PM QOS to change per device");
63 static bool force_apst;
64 module_param(force_apst, bool, 0644);
65 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
68 module_param(streams, bool, 0644);
69 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
72 * nvme_wq - hosts nvme related works that are not reset or delete
73 * nvme_reset_wq - hosts nvme reset works
74 * nvme_delete_wq - hosts nvme delete works
76 * nvme_wq will host works such are scan, aen handling, fw activation,
77 * keep-alive error recovery, periodic reconnects etc. nvme_reset_wq
78 * runs reset works which also flush works hosted on nvme_wq for
79 * serialization purposes. nvme_delete_wq host controller deletion
80 * works which flush reset works for serialization.
82 struct workqueue_struct *nvme_wq;
83 EXPORT_SYMBOL_GPL(nvme_wq);
85 struct workqueue_struct *nvme_reset_wq;
86 EXPORT_SYMBOL_GPL(nvme_reset_wq);
88 struct workqueue_struct *nvme_delete_wq;
89 EXPORT_SYMBOL_GPL(nvme_delete_wq);
91 static DEFINE_IDA(nvme_subsystems_ida);
92 static LIST_HEAD(nvme_subsystems);
93 static DEFINE_MUTEX(nvme_subsystems_lock);
95 static DEFINE_IDA(nvme_instance_ida);
96 static dev_t nvme_chr_devt;
97 static struct class *nvme_class;
98 static struct class *nvme_subsys_class;
100 static void nvme_ns_remove(struct nvme_ns *ns);
101 static int nvme_revalidate_disk(struct gendisk *disk);
102 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
104 static void nvme_queue_scan(struct nvme_ctrl *ctrl)
107 * Only new queue scan work when admin and IO queues are both alive
109 if (ctrl->state == NVME_CTRL_LIVE)
110 queue_work(nvme_wq, &ctrl->scan_work);
113 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
115 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
117 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
121 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
123 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
127 ret = nvme_reset_ctrl(ctrl);
129 flush_work(&ctrl->reset_work);
130 if (ctrl->state != NVME_CTRL_LIVE &&
131 ctrl->state != NVME_CTRL_ADMIN_ONLY)
137 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync);
139 static void nvme_delete_ctrl_work(struct work_struct *work)
141 struct nvme_ctrl *ctrl =
142 container_of(work, struct nvme_ctrl, delete_work);
144 dev_info(ctrl->device,
145 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
147 flush_work(&ctrl->reset_work);
148 nvme_stop_ctrl(ctrl);
149 nvme_remove_namespaces(ctrl);
150 ctrl->ops->delete_ctrl(ctrl);
151 nvme_uninit_ctrl(ctrl);
155 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
157 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
159 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
163 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
165 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
170 * Keep a reference until the work is flushed since ->delete_ctrl
171 * can free the controller.
174 ret = nvme_delete_ctrl(ctrl);
176 flush_work(&ctrl->delete_work);
180 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
182 static inline bool nvme_ns_has_pi(struct nvme_ns *ns)
184 return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple);
187 static blk_status_t nvme_error_status(struct request *req)
189 switch (nvme_req(req)->status & 0x7ff) {
190 case NVME_SC_SUCCESS:
192 case NVME_SC_CAP_EXCEEDED:
193 return BLK_STS_NOSPC;
194 case NVME_SC_LBA_RANGE:
195 return BLK_STS_TARGET;
196 case NVME_SC_BAD_ATTRIBUTES:
197 case NVME_SC_ONCS_NOT_SUPPORTED:
198 case NVME_SC_INVALID_OPCODE:
199 case NVME_SC_INVALID_FIELD:
200 case NVME_SC_INVALID_NS:
201 return BLK_STS_NOTSUPP;
202 case NVME_SC_WRITE_FAULT:
203 case NVME_SC_READ_ERROR:
204 case NVME_SC_UNWRITTEN_BLOCK:
205 case NVME_SC_ACCESS_DENIED:
206 case NVME_SC_READ_ONLY:
207 case NVME_SC_COMPARE_FAILED:
208 return BLK_STS_MEDIUM;
209 case NVME_SC_GUARD_CHECK:
210 case NVME_SC_APPTAG_CHECK:
211 case NVME_SC_REFTAG_CHECK:
212 case NVME_SC_INVALID_PI:
213 return BLK_STS_PROTECTION;
214 case NVME_SC_RESERVATION_CONFLICT:
215 return BLK_STS_NEXUS;
217 return BLK_STS_IOERR;
221 static inline bool nvme_req_needs_retry(struct request *req)
223 if (blk_noretry_request(req))
225 if (nvme_req(req)->status & NVME_SC_DNR)
227 if (nvme_req(req)->retries >= nvme_max_retries)
232 void nvme_complete_rq(struct request *req)
234 blk_status_t status = nvme_error_status(req);
236 trace_nvme_complete_rq(req);
238 if (unlikely(status != BLK_STS_OK && nvme_req_needs_retry(req))) {
239 if (nvme_req_needs_failover(req, status)) {
240 nvme_failover_req(req);
244 if (!blk_queue_dying(req->q)) {
245 nvme_req(req)->retries++;
246 blk_mq_requeue_request(req, true);
250 blk_mq_end_request(req, status);
252 EXPORT_SYMBOL_GPL(nvme_complete_rq);
254 void nvme_cancel_request(struct request *req, void *data, bool reserved)
256 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
257 "Cancelling I/O %d", req->tag);
259 nvme_req(req)->status = NVME_SC_ABORT_REQ;
260 blk_mq_complete_request(req);
263 EXPORT_SYMBOL_GPL(nvme_cancel_request);
265 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
266 enum nvme_ctrl_state new_state)
268 enum nvme_ctrl_state old_state;
270 bool changed = false;
272 spin_lock_irqsave(&ctrl->lock, flags);
274 old_state = ctrl->state;
276 case NVME_CTRL_ADMIN_ONLY:
278 case NVME_CTRL_CONNECTING:
288 case NVME_CTRL_RESETTING:
289 case NVME_CTRL_CONNECTING:
296 case NVME_CTRL_RESETTING:
300 case NVME_CTRL_ADMIN_ONLY:
307 case NVME_CTRL_CONNECTING:
310 case NVME_CTRL_RESETTING:
317 case NVME_CTRL_DELETING:
320 case NVME_CTRL_ADMIN_ONLY:
321 case NVME_CTRL_RESETTING:
322 case NVME_CTRL_CONNECTING:
331 case NVME_CTRL_DELETING:
343 ctrl->state = new_state;
345 spin_unlock_irqrestore(&ctrl->lock, flags);
346 if (changed && ctrl->state == NVME_CTRL_LIVE)
347 nvme_kick_requeue_lists(ctrl);
350 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
352 static void nvme_free_ns_head(struct kref *ref)
354 struct nvme_ns_head *head =
355 container_of(ref, struct nvme_ns_head, ref);
357 nvme_mpath_remove_disk(head);
358 ida_simple_remove(&head->subsys->ns_ida, head->instance);
359 list_del_init(&head->entry);
360 cleanup_srcu_struct_quiesced(&head->srcu);
361 nvme_put_subsystem(head->subsys);
365 static void nvme_put_ns_head(struct nvme_ns_head *head)
367 kref_put(&head->ref, nvme_free_ns_head);
370 static void nvme_free_ns(struct kref *kref)
372 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
375 nvme_nvm_unregister(ns);
378 nvme_put_ns_head(ns->head);
379 nvme_put_ctrl(ns->ctrl);
383 static void nvme_put_ns(struct nvme_ns *ns)
385 kref_put(&ns->kref, nvme_free_ns);
388 static inline void nvme_clear_nvme_request(struct request *req)
390 if (!(req->rq_flags & RQF_DONTPREP)) {
391 nvme_req(req)->retries = 0;
392 nvme_req(req)->flags = 0;
393 req->rq_flags |= RQF_DONTPREP;
397 struct request *nvme_alloc_request(struct request_queue *q,
398 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
400 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
403 if (qid == NVME_QID_ANY) {
404 req = blk_mq_alloc_request(q, op, flags);
406 req = blk_mq_alloc_request_hctx(q, op, flags,
412 req->cmd_flags |= REQ_FAILFAST_DRIVER;
413 nvme_clear_nvme_request(req);
414 nvme_req(req)->cmd = cmd;
418 EXPORT_SYMBOL_GPL(nvme_alloc_request);
420 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
422 struct nvme_command c;
424 memset(&c, 0, sizeof(c));
426 c.directive.opcode = nvme_admin_directive_send;
427 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
428 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
429 c.directive.dtype = NVME_DIR_IDENTIFY;
430 c.directive.tdtype = NVME_DIR_STREAMS;
431 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
433 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
436 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
438 return nvme_toggle_streams(ctrl, false);
441 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
443 return nvme_toggle_streams(ctrl, true);
446 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
447 struct streams_directive_params *s, u32 nsid)
449 struct nvme_command c;
451 memset(&c, 0, sizeof(c));
452 memset(s, 0, sizeof(*s));
454 c.directive.opcode = nvme_admin_directive_recv;
455 c.directive.nsid = cpu_to_le32(nsid);
456 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
457 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
458 c.directive.dtype = NVME_DIR_STREAMS;
460 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
463 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
465 struct streams_directive_params s;
468 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
473 ret = nvme_enable_streams(ctrl);
477 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
481 ctrl->nssa = le16_to_cpu(s.nssa);
482 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
483 dev_info(ctrl->device, "too few streams (%u) available\n",
485 nvme_disable_streams(ctrl);
489 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
490 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
495 * Check if 'req' has a write hint associated with it. If it does, assign
496 * a valid namespace stream to the write.
498 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
499 struct request *req, u16 *control,
502 enum rw_hint streamid = req->write_hint;
504 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
508 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
511 *control |= NVME_RW_DTYPE_STREAMS;
512 *dsmgmt |= streamid << 16;
515 if (streamid < ARRAY_SIZE(req->q->write_hints))
516 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
519 static inline void nvme_setup_flush(struct nvme_ns *ns,
520 struct nvme_command *cmnd)
522 memset(cmnd, 0, sizeof(*cmnd));
523 cmnd->common.opcode = nvme_cmd_flush;
524 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
527 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
528 struct nvme_command *cmnd)
530 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
531 struct nvme_dsm_range *range;
534 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
536 return BLK_STS_RESOURCE;
538 __rq_for_each_bio(bio, req) {
539 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
540 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
543 range[n].cattr = cpu_to_le32(0);
544 range[n].nlb = cpu_to_le32(nlb);
545 range[n].slba = cpu_to_le64(slba);
550 if (WARN_ON_ONCE(n != segments)) {
552 return BLK_STS_IOERR;
555 memset(cmnd, 0, sizeof(*cmnd));
556 cmnd->dsm.opcode = nvme_cmd_dsm;
557 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
558 cmnd->dsm.nr = cpu_to_le32(segments - 1);
559 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
561 req->special_vec.bv_page = virt_to_page(range);
562 req->special_vec.bv_offset = offset_in_page(range);
563 req->special_vec.bv_len = sizeof(*range) * segments;
564 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
569 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
570 struct request *req, struct nvme_command *cmnd)
572 struct nvme_ctrl *ctrl = ns->ctrl;
576 if (req->cmd_flags & REQ_FUA)
577 control |= NVME_RW_FUA;
578 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
579 control |= NVME_RW_LR;
581 if (req->cmd_flags & REQ_RAHEAD)
582 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
584 memset(cmnd, 0, sizeof(*cmnd));
585 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
586 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
587 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
588 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
590 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
591 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
595 * If formated with metadata, the block layer always provides a
596 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
597 * we enable the PRACT bit for protection information or set the
598 * namespace capacity to zero to prevent any I/O.
600 if (!blk_integrity_rq(req)) {
601 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
602 return BLK_STS_NOTSUPP;
603 control |= NVME_RW_PRINFO_PRACT;
606 switch (ns->pi_type) {
607 case NVME_NS_DPS_PI_TYPE3:
608 control |= NVME_RW_PRINFO_PRCHK_GUARD;
610 case NVME_NS_DPS_PI_TYPE1:
611 case NVME_NS_DPS_PI_TYPE2:
612 control |= NVME_RW_PRINFO_PRCHK_GUARD |
613 NVME_RW_PRINFO_PRCHK_REF;
614 cmnd->rw.reftag = cpu_to_le32(
615 nvme_block_nr(ns, blk_rq_pos(req)));
620 cmnd->rw.control = cpu_to_le16(control);
621 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
625 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
626 struct nvme_command *cmd)
628 blk_status_t ret = BLK_STS_OK;
630 nvme_clear_nvme_request(req);
632 switch (req_op(req)) {
635 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
638 nvme_setup_flush(ns, cmd);
640 case REQ_OP_WRITE_ZEROES:
641 /* currently only aliased to deallocate for a few ctrls: */
643 ret = nvme_setup_discard(ns, req, cmd);
647 ret = nvme_setup_rw(ns, req, cmd);
651 return BLK_STS_IOERR;
654 cmd->common.command_id = req->tag;
656 trace_nvme_setup_nvm_cmd(req->q->id, cmd);
658 trace_nvme_setup_admin_cmd(cmd);
661 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
664 * Returns 0 on success. If the result is negative, it's a Linux error code;
665 * if the result is positive, it's an NVM Express status code
667 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
668 union nvme_result *result, void *buffer, unsigned bufflen,
669 unsigned timeout, int qid, int at_head,
670 blk_mq_req_flags_t flags)
675 req = nvme_alloc_request(q, cmd, flags, qid);
679 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
681 if (buffer && bufflen) {
682 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
687 blk_execute_rq(req->q, NULL, req, at_head);
689 *result = nvme_req(req)->result;
690 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
693 ret = nvme_req(req)->status;
695 blk_mq_free_request(req);
698 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
700 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
701 void *buffer, unsigned bufflen)
703 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
706 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
708 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
709 unsigned len, u32 seed, bool write)
711 struct bio_integrity_payload *bip;
715 buf = kmalloc(len, GFP_KERNEL);
720 if (write && copy_from_user(buf, ubuf, len))
723 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
729 bip->bip_iter.bi_size = len;
730 bip->bip_iter.bi_sector = seed;
731 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
732 offset_in_page(buf));
742 static int nvme_submit_user_cmd(struct request_queue *q,
743 struct nvme_command *cmd, void __user *ubuffer,
744 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
745 u32 meta_seed, u32 *result, unsigned timeout)
747 bool write = nvme_is_write(cmd);
748 struct nvme_ns *ns = q->queuedata;
749 struct gendisk *disk = ns ? ns->disk : NULL;
751 struct bio *bio = NULL;
755 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
759 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
760 nvme_req(req)->flags |= NVME_REQ_USERCMD;
762 if (ubuffer && bufflen) {
763 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
769 if (disk && meta_buffer && meta_len) {
770 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
776 req->cmd_flags |= REQ_INTEGRITY;
780 blk_execute_rq(req->q, disk, req, 0);
781 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
784 ret = nvme_req(req)->status;
786 *result = le32_to_cpu(nvme_req(req)->result.u32);
787 if (meta && !ret && !write) {
788 if (copy_to_user(meta_buffer, meta, meta_len))
794 blk_rq_unmap_user(bio);
796 blk_mq_free_request(req);
800 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
802 struct nvme_ctrl *ctrl = rq->end_io_data;
804 blk_mq_free_request(rq);
807 dev_err(ctrl->device,
808 "failed nvme_keep_alive_end_io error=%d\n",
813 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
816 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
820 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
825 rq->timeout = ctrl->kato * HZ;
826 rq->end_io_data = ctrl;
828 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
833 static void nvme_keep_alive_work(struct work_struct *work)
835 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
836 struct nvme_ctrl, ka_work);
838 if (nvme_keep_alive(ctrl)) {
839 /* allocation failure, reset the controller */
840 dev_err(ctrl->device, "keep-alive failed\n");
841 nvme_reset_ctrl(ctrl);
846 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
848 if (unlikely(ctrl->kato == 0))
851 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
852 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
853 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
854 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
857 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
859 if (unlikely(ctrl->kato == 0))
862 cancel_delayed_work_sync(&ctrl->ka_work);
864 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
866 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
868 struct nvme_command c = { };
871 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
872 c.identify.opcode = nvme_admin_identify;
873 c.identify.cns = NVME_ID_CNS_CTRL;
875 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
879 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
880 sizeof(struct nvme_id_ctrl));
886 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
887 struct nvme_ns_ids *ids)
889 struct nvme_command c = { };
895 c.identify.opcode = nvme_admin_identify;
896 c.identify.nsid = cpu_to_le32(nsid);
897 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
899 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
903 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
904 NVME_IDENTIFY_DATA_SIZE);
908 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
909 struct nvme_ns_id_desc *cur = data + pos;
915 case NVME_NIDT_EUI64:
916 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
917 dev_warn(ctrl->device,
918 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
922 len = NVME_NIDT_EUI64_LEN;
923 memcpy(ids->eui64, data + pos + sizeof(*cur), len);
925 case NVME_NIDT_NGUID:
926 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
927 dev_warn(ctrl->device,
928 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
932 len = NVME_NIDT_NGUID_LEN;
933 memcpy(ids->nguid, data + pos + sizeof(*cur), len);
936 if (cur->nidl != NVME_NIDT_UUID_LEN) {
937 dev_warn(ctrl->device,
938 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
942 len = NVME_NIDT_UUID_LEN;
943 uuid_copy(&ids->uuid, data + pos + sizeof(*cur));
946 /* Skip unnkown types */
958 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
960 struct nvme_command c = { };
962 c.identify.opcode = nvme_admin_identify;
963 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
964 c.identify.nsid = cpu_to_le32(nsid);
965 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
966 NVME_IDENTIFY_DATA_SIZE);
969 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
972 struct nvme_id_ns *id;
973 struct nvme_command c = { };
976 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
977 c.identify.opcode = nvme_admin_identify;
978 c.identify.nsid = cpu_to_le32(nsid);
979 c.identify.cns = NVME_ID_CNS_NS;
981 id = kmalloc(sizeof(*id), GFP_KERNEL);
985 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
987 dev_warn(ctrl->device, "Identify namespace failed\n");
995 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
996 void *buffer, size_t buflen, u32 *result)
998 struct nvme_command c;
999 union nvme_result res;
1002 memset(&c, 0, sizeof(c));
1003 c.features.opcode = nvme_admin_set_features;
1004 c.features.fid = cpu_to_le32(fid);
1005 c.features.dword11 = cpu_to_le32(dword11);
1007 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1008 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
1009 if (ret >= 0 && result)
1010 *result = le32_to_cpu(res.u32);
1014 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1016 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1018 int status, nr_io_queues;
1020 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1026 * Degraded controllers might return an error when setting the queue
1027 * count. We still want to be able to bring them online and offer
1028 * access to the admin queue, as that might be only way to fix them up.
1031 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1034 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1035 *count = min(*count, nr_io_queues);
1040 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1042 #define NVME_AEN_SUPPORTED \
1043 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT)
1045 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1050 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT,
1051 ctrl->oaes & NVME_AEN_SUPPORTED, NULL, 0, &result);
1053 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1054 ctrl->oaes & NVME_AEN_SUPPORTED);
1057 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1059 struct nvme_user_io io;
1060 struct nvme_command c;
1061 unsigned length, meta_len;
1062 void __user *metadata;
1064 if (copy_from_user(&io, uio, sizeof(io)))
1069 switch (io.opcode) {
1070 case nvme_cmd_write:
1072 case nvme_cmd_compare:
1078 length = (io.nblocks + 1) << ns->lba_shift;
1079 meta_len = (io.nblocks + 1) * ns->ms;
1080 metadata = (void __user *)(uintptr_t)io.metadata;
1085 } else if (meta_len) {
1086 if ((io.metadata & 3) || !io.metadata)
1090 memset(&c, 0, sizeof(c));
1091 c.rw.opcode = io.opcode;
1092 c.rw.flags = io.flags;
1093 c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1094 c.rw.slba = cpu_to_le64(io.slba);
1095 c.rw.length = cpu_to_le16(io.nblocks);
1096 c.rw.control = cpu_to_le16(io.control);
1097 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1098 c.rw.reftag = cpu_to_le32(io.reftag);
1099 c.rw.apptag = cpu_to_le16(io.apptag);
1100 c.rw.appmask = cpu_to_le16(io.appmask);
1102 return nvme_submit_user_cmd(ns->queue, &c,
1103 (void __user *)(uintptr_t)io.addr, length,
1104 metadata, meta_len, io.slba, NULL, 0);
1107 static u32 nvme_known_admin_effects(u8 opcode)
1110 case nvme_admin_format_nvm:
1111 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
1112 NVME_CMD_EFFECTS_CSE_MASK;
1113 case nvme_admin_sanitize_nvm:
1114 return NVME_CMD_EFFECTS_CSE_MASK;
1121 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1128 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1129 if (effects & ~NVME_CMD_EFFECTS_CSUPP)
1130 dev_warn(ctrl->device,
1131 "IO command:%02x has unhandled effects:%08x\n",
1137 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1139 effects = nvme_known_admin_effects(opcode);
1142 * For simplicity, IO to all namespaces is quiesced even if the command
1143 * effects say only one namespace is affected.
1145 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1146 nvme_start_freeze(ctrl);
1147 nvme_wait_freeze(ctrl);
1152 static void nvme_update_formats(struct nvme_ctrl *ctrl)
1154 struct nvme_ns *ns, *next;
1157 down_write(&ctrl->namespaces_rwsem);
1158 list_for_each_entry(ns, &ctrl->namespaces, list) {
1159 if (ns->disk && nvme_revalidate_disk(ns->disk)) {
1160 list_move_tail(&ns->list, &rm_list);
1163 up_write(&ctrl->namespaces_rwsem);
1165 list_for_each_entry_safe(ns, next, &rm_list, list)
1169 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1172 * Revalidate LBA changes prior to unfreezing. This is necessary to
1173 * prevent memory corruption if a logical block size was changed by
1176 if (effects & NVME_CMD_EFFECTS_LBCC)
1177 nvme_update_formats(ctrl);
1178 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK))
1179 nvme_unfreeze(ctrl);
1180 if (effects & NVME_CMD_EFFECTS_CCC)
1181 nvme_init_identify(ctrl);
1182 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC))
1183 nvme_queue_scan(ctrl);
1186 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1187 struct nvme_passthru_cmd __user *ucmd)
1189 struct nvme_passthru_cmd cmd;
1190 struct nvme_command c;
1191 unsigned timeout = 0;
1195 if (!capable(CAP_SYS_ADMIN))
1197 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1202 memset(&c, 0, sizeof(c));
1203 c.common.opcode = cmd.opcode;
1204 c.common.flags = cmd.flags;
1205 c.common.nsid = cpu_to_le32(cmd.nsid);
1206 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1207 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1208 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1209 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1210 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1211 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1212 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1213 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1216 timeout = msecs_to_jiffies(cmd.timeout_ms);
1218 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1219 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1220 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1221 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1222 0, &cmd.result, timeout);
1223 nvme_passthru_end(ctrl, effects);
1226 if (put_user(cmd.result, &ucmd->result))
1234 * Issue ioctl requests on the first available path. Note that unlike normal
1235 * block layer requests we will not retry failed request on another controller.
1237 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1238 struct nvme_ns_head **head, int *srcu_idx)
1240 #ifdef CONFIG_NVME_MULTIPATH
1241 if (disk->fops == &nvme_ns_head_ops) {
1242 *head = disk->private_data;
1243 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1244 return nvme_find_path(*head);
1249 return disk->private_data;
1252 static void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1255 srcu_read_unlock(&head->srcu, idx);
1258 static int nvme_ns_ioctl(struct nvme_ns *ns, unsigned cmd, unsigned long arg)
1262 force_successful_syscall_return();
1263 return ns->head->ns_id;
1264 case NVME_IOCTL_ADMIN_CMD:
1265 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1266 case NVME_IOCTL_IO_CMD:
1267 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1268 case NVME_IOCTL_SUBMIT_IO:
1269 return nvme_submit_io(ns, (void __user *)arg);
1273 return nvme_nvm_ioctl(ns, cmd, arg);
1275 if (is_sed_ioctl(cmd))
1276 return sed_ioctl(ns->ctrl->opal_dev, cmd,
1277 (void __user *) arg);
1282 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1283 unsigned int cmd, unsigned long arg)
1285 struct nvme_ns_head *head = NULL;
1289 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1293 ret = nvme_ns_ioctl(ns, cmd, arg);
1294 nvme_put_ns_from_disk(head, srcu_idx);
1298 static int nvme_open(struct block_device *bdev, fmode_t mode)
1300 struct nvme_ns *ns = bdev->bd_disk->private_data;
1302 #ifdef CONFIG_NVME_MULTIPATH
1303 /* should never be called due to GENHD_FL_HIDDEN */
1304 if (WARN_ON_ONCE(ns->head->disk))
1307 if (!kref_get_unless_zero(&ns->kref))
1309 if (!try_module_get(ns->ctrl->ops->module))
1320 static void nvme_release(struct gendisk *disk, fmode_t mode)
1322 struct nvme_ns *ns = disk->private_data;
1324 module_put(ns->ctrl->ops->module);
1328 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1330 /* some standard values */
1331 geo->heads = 1 << 6;
1332 geo->sectors = 1 << 5;
1333 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1337 #ifdef CONFIG_BLK_DEV_INTEGRITY
1338 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1340 struct blk_integrity integrity;
1342 memset(&integrity, 0, sizeof(integrity));
1344 case NVME_NS_DPS_PI_TYPE3:
1345 integrity.profile = &t10_pi_type3_crc;
1346 integrity.tag_size = sizeof(u16) + sizeof(u32);
1347 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1349 case NVME_NS_DPS_PI_TYPE1:
1350 case NVME_NS_DPS_PI_TYPE2:
1351 integrity.profile = &t10_pi_type1_crc;
1352 integrity.tag_size = sizeof(u16);
1353 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1356 integrity.profile = NULL;
1359 integrity.tuple_size = ms;
1360 blk_integrity_register(disk, &integrity);
1361 blk_queue_max_integrity_segments(disk->queue, 1);
1364 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1367 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1369 static void nvme_set_chunk_size(struct nvme_ns *ns)
1371 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1372 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1375 static void nvme_config_discard(struct nvme_ns *ns)
1377 struct nvme_ctrl *ctrl = ns->ctrl;
1378 struct request_queue *queue = ns->queue;
1379 u32 size = queue_logical_block_size(queue);
1381 if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1382 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1386 if (ctrl->nr_streams && ns->sws && ns->sgs)
1387 size *= ns->sws * ns->sgs;
1389 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1390 NVME_DSM_MAX_RANGES);
1392 queue->limits.discard_alignment = 0;
1393 queue->limits.discard_granularity = size;
1395 /* If discard is already enabled, don't reset queue limits */
1396 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1399 blk_queue_max_discard_sectors(queue, UINT_MAX);
1400 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1402 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1403 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1406 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1407 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1409 memset(ids, 0, sizeof(*ids));
1411 if (ctrl->vs >= NVME_VS(1, 1, 0))
1412 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1413 if (ctrl->vs >= NVME_VS(1, 2, 0))
1414 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1415 if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1416 /* Don't treat error as fatal we potentially
1417 * already have a NGUID or EUI-64
1419 if (nvme_identify_ns_descs(ctrl, nsid, ids))
1420 dev_warn(ctrl->device,
1421 "%s: Identify Descriptors failed\n", __func__);
1425 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1427 return !uuid_is_null(&ids->uuid) ||
1428 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1429 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1432 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1434 return uuid_equal(&a->uuid, &b->uuid) &&
1435 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1436 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0;
1439 static void nvme_update_disk_info(struct gendisk *disk,
1440 struct nvme_ns *ns, struct nvme_id_ns *id)
1442 sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9);
1443 unsigned short bs = 1 << ns->lba_shift;
1445 blk_mq_freeze_queue(disk->queue);
1446 blk_integrity_unregister(disk);
1448 blk_queue_logical_block_size(disk->queue, bs);
1449 blk_queue_physical_block_size(disk->queue, bs);
1450 blk_queue_io_min(disk->queue, bs);
1452 if (ns->ms && !ns->ext &&
1453 (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1454 nvme_init_integrity(disk, ns->ms, ns->pi_type);
1455 if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk))
1458 set_capacity(disk, capacity);
1459 nvme_config_discard(ns);
1460 blk_mq_unfreeze_queue(disk->queue);
1463 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1465 struct nvme_ns *ns = disk->private_data;
1468 * If identify namespace failed, use default 512 byte block size so
1469 * block layer can use before failing read/write for 0 capacity.
1471 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1472 if (ns->lba_shift == 0)
1474 ns->noiob = le16_to_cpu(id->noiob);
1475 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1476 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1477 /* the PI implementation requires metadata equal t10 pi tuple size */
1478 if (ns->ms == sizeof(struct t10_pi_tuple))
1479 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1484 nvme_set_chunk_size(ns);
1485 nvme_update_disk_info(disk, ns, id);
1487 nvme_nvm_update_nvm_info(ns);
1488 #ifdef CONFIG_NVME_MULTIPATH
1490 nvme_update_disk_info(ns->head->disk, ns, id);
1494 static int nvme_revalidate_disk(struct gendisk *disk)
1496 struct nvme_ns *ns = disk->private_data;
1497 struct nvme_ctrl *ctrl = ns->ctrl;
1498 struct nvme_id_ns *id;
1499 struct nvme_ns_ids ids;
1502 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1503 set_capacity(disk, 0);
1507 id = nvme_identify_ns(ctrl, ns->head->ns_id);
1511 if (id->ncap == 0) {
1516 __nvme_revalidate_disk(disk, id);
1517 nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
1518 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
1519 dev_err(ctrl->device,
1520 "identifiers changed for nsid %d\n", ns->head->ns_id);
1529 static char nvme_pr_type(enum pr_type type)
1532 case PR_WRITE_EXCLUSIVE:
1534 case PR_EXCLUSIVE_ACCESS:
1536 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1538 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1540 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1542 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1549 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1550 u64 key, u64 sa_key, u8 op)
1552 struct nvme_ns_head *head = NULL;
1554 struct nvme_command c;
1556 u8 data[16] = { 0, };
1558 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1560 return -EWOULDBLOCK;
1562 put_unaligned_le64(key, &data[0]);
1563 put_unaligned_le64(sa_key, &data[8]);
1565 memset(&c, 0, sizeof(c));
1566 c.common.opcode = op;
1567 c.common.nsid = cpu_to_le32(ns->head->ns_id);
1568 c.common.cdw10[0] = cpu_to_le32(cdw10);
1570 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1571 nvme_put_ns_from_disk(head, srcu_idx);
1575 static int nvme_pr_register(struct block_device *bdev, u64 old,
1576 u64 new, unsigned flags)
1580 if (flags & ~PR_FL_IGNORE_KEY)
1583 cdw10 = old ? 2 : 0;
1584 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1585 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1586 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1589 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1590 enum pr_type type, unsigned flags)
1594 if (flags & ~PR_FL_IGNORE_KEY)
1597 cdw10 = nvme_pr_type(type) << 8;
1598 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1599 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1602 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1603 enum pr_type type, bool abort)
1605 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1606 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1609 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1611 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1612 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1615 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1617 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
1618 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1621 static const struct pr_ops nvme_pr_ops = {
1622 .pr_register = nvme_pr_register,
1623 .pr_reserve = nvme_pr_reserve,
1624 .pr_release = nvme_pr_release,
1625 .pr_preempt = nvme_pr_preempt,
1626 .pr_clear = nvme_pr_clear,
1629 #ifdef CONFIG_BLK_SED_OPAL
1630 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1633 struct nvme_ctrl *ctrl = data;
1634 struct nvme_command cmd;
1636 memset(&cmd, 0, sizeof(cmd));
1638 cmd.common.opcode = nvme_admin_security_send;
1640 cmd.common.opcode = nvme_admin_security_recv;
1641 cmd.common.nsid = 0;
1642 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1643 cmd.common.cdw10[1] = cpu_to_le32(len);
1645 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1646 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1648 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1649 #endif /* CONFIG_BLK_SED_OPAL */
1651 static const struct block_device_operations nvme_fops = {
1652 .owner = THIS_MODULE,
1653 .ioctl = nvme_ioctl,
1654 .compat_ioctl = nvme_ioctl,
1656 .release = nvme_release,
1657 .getgeo = nvme_getgeo,
1658 .revalidate_disk= nvme_revalidate_disk,
1659 .pr_ops = &nvme_pr_ops,
1662 #ifdef CONFIG_NVME_MULTIPATH
1663 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
1665 struct nvme_ns_head *head = bdev->bd_disk->private_data;
1667 if (!kref_get_unless_zero(&head->ref))
1672 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
1674 nvme_put_ns_head(disk->private_data);
1677 const struct block_device_operations nvme_ns_head_ops = {
1678 .owner = THIS_MODULE,
1679 .open = nvme_ns_head_open,
1680 .release = nvme_ns_head_release,
1681 .ioctl = nvme_ioctl,
1682 .compat_ioctl = nvme_ioctl,
1683 .getgeo = nvme_getgeo,
1684 .pr_ops = &nvme_pr_ops,
1686 #endif /* CONFIG_NVME_MULTIPATH */
1688 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1690 unsigned long timeout =
1691 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1692 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1695 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1698 if ((csts & NVME_CSTS_RDY) == bit)
1702 if (fatal_signal_pending(current))
1704 if (time_after(jiffies, timeout)) {
1705 dev_err(ctrl->device,
1706 "Device not ready; aborting %s\n", enabled ?
1707 "initialisation" : "reset");
1716 * If the device has been passed off to us in an enabled state, just clear
1717 * the enabled bit. The spec says we should set the 'shutdown notification
1718 * bits', but doing so may cause the device to complete commands to the
1719 * admin queue ... and we don't know what memory that might be pointing at!
1721 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1725 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1726 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1728 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1732 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1733 msleep(NVME_QUIRK_DELAY_AMOUNT);
1735 return nvme_wait_ready(ctrl, cap, false);
1737 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1739 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1742 * Default to a 4K page size, with the intention to update this
1743 * path in the future to accomodate architectures with differing
1744 * kernel and IO page sizes.
1746 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1749 if (page_shift < dev_page_min) {
1750 dev_err(ctrl->device,
1751 "Minimum device page size %u too large for host (%u)\n",
1752 1 << dev_page_min, 1 << page_shift);
1756 ctrl->page_size = 1 << page_shift;
1758 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1759 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1760 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1761 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1762 ctrl->ctrl_config |= NVME_CC_ENABLE;
1764 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1767 return nvme_wait_ready(ctrl, cap, true);
1769 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1771 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1773 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1777 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1778 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1780 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1784 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1785 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1789 if (fatal_signal_pending(current))
1791 if (time_after(jiffies, timeout)) {
1792 dev_err(ctrl->device,
1793 "Device shutdown incomplete; abort shutdown\n");
1800 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1802 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1803 struct request_queue *q)
1807 if (ctrl->max_hw_sectors) {
1809 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1811 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1812 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1814 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1815 is_power_of_2(ctrl->max_hw_sectors))
1816 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1817 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1818 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1820 blk_queue_write_cache(q, vwc, vwc);
1823 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1828 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1831 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1832 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1835 dev_warn_once(ctrl->device,
1836 "could not set timestamp (%d)\n", ret);
1840 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1843 * APST (Autonomous Power State Transition) lets us program a
1844 * table of power state transitions that the controller will
1845 * perform automatically. We configure it with a simple
1846 * heuristic: we are willing to spend at most 2% of the time
1847 * transitioning between power states. Therefore, when running
1848 * in any given state, we will enter the next lower-power
1849 * non-operational state after waiting 50 * (enlat + exlat)
1850 * microseconds, as long as that state's exit latency is under
1851 * the requested maximum latency.
1853 * We will not autonomously enter any non-operational state for
1854 * which the total latency exceeds ps_max_latency_us. Users
1855 * can set ps_max_latency_us to zero to turn off APST.
1859 struct nvme_feat_auto_pst *table;
1865 * If APST isn't supported or if we haven't been initialized yet,
1866 * then don't do anything.
1871 if (ctrl->npss > 31) {
1872 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1876 table = kzalloc(sizeof(*table), GFP_KERNEL);
1880 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1881 /* Turn off APST. */
1883 dev_dbg(ctrl->device, "APST disabled\n");
1885 __le64 target = cpu_to_le64(0);
1889 * Walk through all states from lowest- to highest-power.
1890 * According to the spec, lower-numbered states use more
1891 * power. NPSS, despite the name, is the index of the
1892 * lowest-power state, not the number of states.
1894 for (state = (int)ctrl->npss; state >= 0; state--) {
1895 u64 total_latency_us, exit_latency_us, transition_ms;
1898 table->entries[state] = target;
1901 * Don't allow transitions to the deepest state
1902 * if it's quirked off.
1904 if (state == ctrl->npss &&
1905 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1909 * Is this state a useful non-operational state for
1910 * higher-power states to autonomously transition to?
1912 if (!(ctrl->psd[state].flags &
1913 NVME_PS_FLAGS_NON_OP_STATE))
1917 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1918 if (exit_latency_us > ctrl->ps_max_latency_us)
1923 le32_to_cpu(ctrl->psd[state].entry_lat);
1926 * This state is good. Use it as the APST idle
1927 * target for higher power states.
1929 transition_ms = total_latency_us + 19;
1930 do_div(transition_ms, 20);
1931 if (transition_ms > (1 << 24) - 1)
1932 transition_ms = (1 << 24) - 1;
1934 target = cpu_to_le64((state << 3) |
1935 (transition_ms << 8));
1940 if (total_latency_us > max_lat_us)
1941 max_lat_us = total_latency_us;
1947 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1949 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1950 max_ps, max_lat_us, (int)sizeof(*table), table);
1954 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1955 table, sizeof(*table), NULL);
1957 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1963 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1965 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1969 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1970 case PM_QOS_LATENCY_ANY:
1978 if (ctrl->ps_max_latency_us != latency) {
1979 ctrl->ps_max_latency_us = latency;
1980 nvme_configure_apst(ctrl);
1984 struct nvme_core_quirk_entry {
1986 * NVMe model and firmware strings are padded with spaces. For
1987 * simplicity, strings in the quirk table are padded with NULLs
1993 unsigned long quirks;
1996 static const struct nvme_core_quirk_entry core_quirks[] = {
1999 * This Toshiba device seems to die using any APST states. See:
2000 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2003 .mn = "THNSF5256GPUK TOSHIBA",
2004 .quirks = NVME_QUIRK_NO_APST,
2008 /* match is null-terminated but idstr is space-padded. */
2009 static bool string_matches(const char *idstr, const char *match, size_t len)
2016 matchlen = strlen(match);
2017 WARN_ON_ONCE(matchlen > len);
2019 if (memcmp(idstr, match, matchlen))
2022 for (; matchlen < len; matchlen++)
2023 if (idstr[matchlen] != ' ')
2029 static bool quirk_matches(const struct nvme_id_ctrl *id,
2030 const struct nvme_core_quirk_entry *q)
2032 return q->vid == le16_to_cpu(id->vid) &&
2033 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2034 string_matches(id->fr, q->fr, sizeof(id->fr));
2037 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2038 struct nvme_id_ctrl *id)
2043 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2044 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2045 strncpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2049 if (ctrl->vs >= NVME_VS(1, 2, 1))
2050 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2052 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2053 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2054 "nqn.2014.08.org.nvmexpress:%4x%4x",
2055 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2056 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2057 off += sizeof(id->sn);
2058 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2059 off += sizeof(id->mn);
2060 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2063 static void __nvme_release_subsystem(struct nvme_subsystem *subsys)
2065 ida_simple_remove(&nvme_subsystems_ida, subsys->instance);
2069 static void nvme_release_subsystem(struct device *dev)
2071 __nvme_release_subsystem(container_of(dev, struct nvme_subsystem, dev));
2074 static void nvme_destroy_subsystem(struct kref *ref)
2076 struct nvme_subsystem *subsys =
2077 container_of(ref, struct nvme_subsystem, ref);
2079 mutex_lock(&nvme_subsystems_lock);
2080 list_del(&subsys->entry);
2081 mutex_unlock(&nvme_subsystems_lock);
2083 ida_destroy(&subsys->ns_ida);
2084 device_del(&subsys->dev);
2085 put_device(&subsys->dev);
2088 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2090 kref_put(&subsys->ref, nvme_destroy_subsystem);
2093 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2095 struct nvme_subsystem *subsys;
2097 lockdep_assert_held(&nvme_subsystems_lock);
2099 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2100 if (strcmp(subsys->subnqn, subsysnqn))
2102 if (!kref_get_unless_zero(&subsys->ref))
2110 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2111 struct device_attribute subsys_attr_##_name = \
2112 __ATTR(_name, _mode, _show, NULL)
2114 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2115 struct device_attribute *attr,
2118 struct nvme_subsystem *subsys =
2119 container_of(dev, struct nvme_subsystem, dev);
2121 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2123 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2125 #define nvme_subsys_show_str_function(field) \
2126 static ssize_t subsys_##field##_show(struct device *dev, \
2127 struct device_attribute *attr, char *buf) \
2129 struct nvme_subsystem *subsys = \
2130 container_of(dev, struct nvme_subsystem, dev); \
2131 return sprintf(buf, "%.*s\n", \
2132 (int)sizeof(subsys->field), subsys->field); \
2134 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2136 nvme_subsys_show_str_function(model);
2137 nvme_subsys_show_str_function(serial);
2138 nvme_subsys_show_str_function(firmware_rev);
2140 static struct attribute *nvme_subsys_attrs[] = {
2141 &subsys_attr_model.attr,
2142 &subsys_attr_serial.attr,
2143 &subsys_attr_firmware_rev.attr,
2144 &subsys_attr_subsysnqn.attr,
2148 static struct attribute_group nvme_subsys_attrs_group = {
2149 .attrs = nvme_subsys_attrs,
2152 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2153 &nvme_subsys_attrs_group,
2157 static int nvme_active_ctrls(struct nvme_subsystem *subsys)
2160 struct nvme_ctrl *ctrl;
2162 mutex_lock(&subsys->lock);
2163 list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
2164 if (ctrl->state != NVME_CTRL_DELETING &&
2165 ctrl->state != NVME_CTRL_DEAD)
2168 mutex_unlock(&subsys->lock);
2173 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2175 struct nvme_subsystem *subsys, *found;
2178 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2181 ret = ida_simple_get(&nvme_subsystems_ida, 0, 0, GFP_KERNEL);
2186 subsys->instance = ret;
2187 mutex_init(&subsys->lock);
2188 kref_init(&subsys->ref);
2189 INIT_LIST_HEAD(&subsys->ctrls);
2190 INIT_LIST_HEAD(&subsys->nsheads);
2191 nvme_init_subnqn(subsys, ctrl, id);
2192 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2193 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2194 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2195 subsys->vendor_id = le16_to_cpu(id->vid);
2196 subsys->cmic = id->cmic;
2198 subsys->dev.class = nvme_subsys_class;
2199 subsys->dev.release = nvme_release_subsystem;
2200 subsys->dev.groups = nvme_subsys_attrs_groups;
2201 dev_set_name(&subsys->dev, "nvme-subsys%d", subsys->instance);
2202 device_initialize(&subsys->dev);
2204 mutex_lock(&nvme_subsystems_lock);
2205 found = __nvme_find_get_subsystem(subsys->subnqn);
2208 * Verify that the subsystem actually supports multiple
2209 * controllers, else bail out.
2211 if (!ctrl->opts->discovery_nqn &&
2212 nvme_active_ctrls(found) && !(id->cmic & (1 << 1))) {
2213 dev_err(ctrl->device,
2214 "ignoring ctrl due to duplicate subnqn (%s).\n",
2216 nvme_put_subsystem(found);
2221 __nvme_release_subsystem(subsys);
2224 ret = device_add(&subsys->dev);
2226 dev_err(ctrl->device,
2227 "failed to register subsystem device.\n");
2230 ida_init(&subsys->ns_ida);
2231 list_add_tail(&subsys->entry, &nvme_subsystems);
2234 ctrl->subsys = subsys;
2235 mutex_unlock(&nvme_subsystems_lock);
2237 if (sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2238 dev_name(ctrl->device))) {
2239 dev_err(ctrl->device,
2240 "failed to create sysfs link from subsystem.\n");
2241 /* the transport driver will eventually put the subsystem */
2245 mutex_lock(&subsys->lock);
2246 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2247 mutex_unlock(&subsys->lock);
2252 mutex_unlock(&nvme_subsystems_lock);
2253 put_device(&subsys->dev);
2257 int nvme_get_log_ext(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
2258 u8 log_page, void *log,
2259 size_t size, u64 offset)
2261 struct nvme_command c = { };
2262 unsigned long dwlen = size / 4 - 1;
2264 c.get_log_page.opcode = nvme_admin_get_log_page;
2267 c.get_log_page.nsid = cpu_to_le32(ns->head->ns_id);
2269 c.get_log_page.nsid = cpu_to_le32(NVME_NSID_ALL);
2271 c.get_log_page.lid = log_page;
2272 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2273 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2274 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2275 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2277 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2280 static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log,
2283 return nvme_get_log_ext(ctrl, NULL, log_page, log, size, 0);
2286 static int nvme_get_effects_log(struct nvme_ctrl *ctrl)
2291 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL);
2296 ret = nvme_get_log(ctrl, NVME_LOG_CMD_EFFECTS, ctrl->effects,
2297 sizeof(*ctrl->effects));
2299 kfree(ctrl->effects);
2300 ctrl->effects = NULL;
2306 * Initialize the cached copies of the Identify data and various controller
2307 * register in our nvme_ctrl structure. This should be called as soon as
2308 * the admin queue is fully up and running.
2310 int nvme_init_identify(struct nvme_ctrl *ctrl)
2312 struct nvme_id_ctrl *id;
2314 int ret, page_shift;
2316 bool prev_apst_enabled;
2318 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
2320 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
2324 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
2326 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2329 page_shift = NVME_CAP_MPSMIN(cap) + 12;
2331 if (ctrl->vs >= NVME_VS(1, 1, 0))
2332 ctrl->subsystem = NVME_CAP_NSSRC(cap);
2334 ret = nvme_identify_ctrl(ctrl, &id);
2336 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2340 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2341 ret = nvme_get_effects_log(ctrl);
2346 if (!ctrl->identified) {
2349 ret = nvme_init_subsystem(ctrl, id);
2354 * Check for quirks. Quirk can depend on firmware version,
2355 * so, in principle, the set of quirks present can change
2356 * across a reset. As a possible future enhancement, we
2357 * could re-scan for quirks every time we reinitialize
2358 * the device, but we'd have to make sure that the driver
2359 * behaves intelligently if the quirks change.
2361 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2362 if (quirk_matches(id, &core_quirks[i]))
2363 ctrl->quirks |= core_quirks[i].quirks;
2367 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2368 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2369 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2372 ctrl->oacs = le16_to_cpu(id->oacs);
2373 ctrl->oncs = le16_to_cpup(&id->oncs);
2374 ctrl->oaes = le32_to_cpu(id->oaes);
2375 atomic_set(&ctrl->abort_limit, id->acl + 1);
2376 ctrl->vwc = id->vwc;
2377 ctrl->cntlid = le16_to_cpup(&id->cntlid);
2379 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
2381 max_hw_sectors = UINT_MAX;
2382 ctrl->max_hw_sectors =
2383 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2385 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2386 ctrl->sgls = le32_to_cpu(id->sgls);
2387 ctrl->kas = le16_to_cpu(id->kas);
2391 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
2393 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2394 shutdown_timeout, 60);
2396 if (ctrl->shutdown_timeout != shutdown_timeout)
2397 dev_info(ctrl->device,
2398 "Shutdown timeout set to %u seconds\n",
2399 ctrl->shutdown_timeout);
2401 ctrl->shutdown_timeout = shutdown_timeout;
2403 ctrl->npss = id->npss;
2404 ctrl->apsta = id->apsta;
2405 prev_apst_enabled = ctrl->apst_enabled;
2406 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2407 if (force_apst && id->apsta) {
2408 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2409 ctrl->apst_enabled = true;
2411 ctrl->apst_enabled = false;
2414 ctrl->apst_enabled = id->apsta;
2416 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2418 if (ctrl->ops->flags & NVME_F_FABRICS) {
2419 ctrl->icdoff = le16_to_cpu(id->icdoff);
2420 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2421 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2422 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2425 * In fabrics we need to verify the cntlid matches the
2428 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2433 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
2434 dev_err(ctrl->device,
2435 "keep-alive support is mandatory for fabrics\n");
2440 ctrl->cntlid = le16_to_cpu(id->cntlid);
2441 ctrl->hmpre = le32_to_cpu(id->hmpre);
2442 ctrl->hmmin = le32_to_cpu(id->hmmin);
2443 ctrl->hmminds = le32_to_cpu(id->hmminds);
2444 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2449 if (ctrl->apst_enabled && !prev_apst_enabled)
2450 dev_pm_qos_expose_latency_tolerance(ctrl->device);
2451 else if (!ctrl->apst_enabled && prev_apst_enabled)
2452 dev_pm_qos_hide_latency_tolerance(ctrl->device);
2454 ret = nvme_configure_apst(ctrl);
2458 ret = nvme_configure_timestamp(ctrl);
2462 ret = nvme_configure_directives(ctrl);
2466 ctrl->identified = true;
2474 EXPORT_SYMBOL_GPL(nvme_init_identify);
2476 static int nvme_dev_open(struct inode *inode, struct file *file)
2478 struct nvme_ctrl *ctrl =
2479 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
2481 switch (ctrl->state) {
2482 case NVME_CTRL_LIVE:
2483 case NVME_CTRL_ADMIN_ONLY:
2486 return -EWOULDBLOCK;
2489 file->private_data = ctrl;
2493 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
2498 down_read(&ctrl->namespaces_rwsem);
2499 if (list_empty(&ctrl->namespaces)) {
2504 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
2505 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
2506 dev_warn(ctrl->device,
2507 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
2512 dev_warn(ctrl->device,
2513 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
2514 kref_get(&ns->kref);
2515 up_read(&ctrl->namespaces_rwsem);
2517 ret = nvme_user_cmd(ctrl, ns, argp);
2522 up_read(&ctrl->namespaces_rwsem);
2526 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
2529 struct nvme_ctrl *ctrl = file->private_data;
2530 void __user *argp = (void __user *)arg;
2533 case NVME_IOCTL_ADMIN_CMD:
2534 return nvme_user_cmd(ctrl, NULL, argp);
2535 case NVME_IOCTL_IO_CMD:
2536 return nvme_dev_user_cmd(ctrl, argp);
2537 case NVME_IOCTL_RESET:
2538 dev_warn(ctrl->device, "resetting controller\n");
2539 return nvme_reset_ctrl_sync(ctrl);
2540 case NVME_IOCTL_SUBSYS_RESET:
2541 return nvme_reset_subsystem(ctrl);
2542 case NVME_IOCTL_RESCAN:
2543 nvme_queue_scan(ctrl);
2550 static const struct file_operations nvme_dev_fops = {
2551 .owner = THIS_MODULE,
2552 .open = nvme_dev_open,
2553 .unlocked_ioctl = nvme_dev_ioctl,
2554 .compat_ioctl = nvme_dev_ioctl,
2557 static ssize_t nvme_sysfs_reset(struct device *dev,
2558 struct device_attribute *attr, const char *buf,
2561 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2564 ret = nvme_reset_ctrl_sync(ctrl);
2569 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2571 static ssize_t nvme_sysfs_rescan(struct device *dev,
2572 struct device_attribute *attr, const char *buf,
2575 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2577 nvme_queue_scan(ctrl);
2580 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2582 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
2584 struct gendisk *disk = dev_to_disk(dev);
2586 if (disk->fops == &nvme_fops)
2587 return nvme_get_ns_from_dev(dev)->head;
2589 return disk->private_data;
2592 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2595 struct nvme_ns_head *head = dev_to_ns_head(dev);
2596 struct nvme_ns_ids *ids = &head->ids;
2597 struct nvme_subsystem *subsys = head->subsys;
2598 int serial_len = sizeof(subsys->serial);
2599 int model_len = sizeof(subsys->model);
2601 if (!uuid_is_null(&ids->uuid))
2602 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
2604 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2605 return sprintf(buf, "eui.%16phN\n", ids->nguid);
2607 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2608 return sprintf(buf, "eui.%8phN\n", ids->eui64);
2610 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
2611 subsys->serial[serial_len - 1] == '\0'))
2613 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
2614 subsys->model[model_len - 1] == '\0'))
2617 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
2618 serial_len, subsys->serial, model_len, subsys->model,
2621 static DEVICE_ATTR_RO(wwid);
2623 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2626 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
2628 static DEVICE_ATTR_RO(nguid);
2630 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2633 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2635 /* For backward compatibility expose the NGUID to userspace if
2636 * we have no UUID set
2638 if (uuid_is_null(&ids->uuid)) {
2639 printk_ratelimited(KERN_WARNING
2640 "No UUID available providing old NGUID\n");
2641 return sprintf(buf, "%pU\n", ids->nguid);
2643 return sprintf(buf, "%pU\n", &ids->uuid);
2645 static DEVICE_ATTR_RO(uuid);
2647 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2650 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
2652 static DEVICE_ATTR_RO(eui);
2654 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2657 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
2659 static DEVICE_ATTR_RO(nsid);
2661 static struct attribute *nvme_ns_id_attrs[] = {
2662 &dev_attr_wwid.attr,
2663 &dev_attr_uuid.attr,
2664 &dev_attr_nguid.attr,
2666 &dev_attr_nsid.attr,
2670 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
2671 struct attribute *a, int n)
2673 struct device *dev = container_of(kobj, struct device, kobj);
2674 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2676 if (a == &dev_attr_uuid.attr) {
2677 if (uuid_is_null(&ids->uuid) &&
2678 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2681 if (a == &dev_attr_nguid.attr) {
2682 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2685 if (a == &dev_attr_eui.attr) {
2686 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2692 const struct attribute_group nvme_ns_id_attr_group = {
2693 .attrs = nvme_ns_id_attrs,
2694 .is_visible = nvme_ns_id_attrs_are_visible,
2697 #define nvme_show_str_function(field) \
2698 static ssize_t field##_show(struct device *dev, \
2699 struct device_attribute *attr, char *buf) \
2701 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2702 return sprintf(buf, "%.*s\n", \
2703 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
2705 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2707 nvme_show_str_function(model);
2708 nvme_show_str_function(serial);
2709 nvme_show_str_function(firmware_rev);
2711 #define nvme_show_int_function(field) \
2712 static ssize_t field##_show(struct device *dev, \
2713 struct device_attribute *attr, char *buf) \
2715 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2716 return sprintf(buf, "%d\n", ctrl->field); \
2718 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2720 nvme_show_int_function(cntlid);
2722 static ssize_t nvme_sysfs_delete(struct device *dev,
2723 struct device_attribute *attr, const char *buf,
2726 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2728 if (device_remove_file_self(dev, attr))
2729 nvme_delete_ctrl_sync(ctrl);
2732 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2734 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2735 struct device_attribute *attr,
2738 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2740 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2742 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2744 static ssize_t nvme_sysfs_show_state(struct device *dev,
2745 struct device_attribute *attr,
2748 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2749 static const char *const state_name[] = {
2750 [NVME_CTRL_NEW] = "new",
2751 [NVME_CTRL_LIVE] = "live",
2752 [NVME_CTRL_ADMIN_ONLY] = "only-admin",
2753 [NVME_CTRL_RESETTING] = "resetting",
2754 [NVME_CTRL_CONNECTING] = "connecting",
2755 [NVME_CTRL_DELETING] = "deleting",
2756 [NVME_CTRL_DEAD] = "dead",
2759 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2760 state_name[ctrl->state])
2761 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2763 return sprintf(buf, "unknown state\n");
2766 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2768 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2769 struct device_attribute *attr,
2772 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2774 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
2776 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2778 static ssize_t nvme_sysfs_show_address(struct device *dev,
2779 struct device_attribute *attr,
2782 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2784 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2786 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2788 static struct attribute *nvme_dev_attrs[] = {
2789 &dev_attr_reset_controller.attr,
2790 &dev_attr_rescan_controller.attr,
2791 &dev_attr_model.attr,
2792 &dev_attr_serial.attr,
2793 &dev_attr_firmware_rev.attr,
2794 &dev_attr_cntlid.attr,
2795 &dev_attr_delete_controller.attr,
2796 &dev_attr_transport.attr,
2797 &dev_attr_subsysnqn.attr,
2798 &dev_attr_address.attr,
2799 &dev_attr_state.attr,
2803 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2804 struct attribute *a, int n)
2806 struct device *dev = container_of(kobj, struct device, kobj);
2807 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2809 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2811 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2817 static struct attribute_group nvme_dev_attrs_group = {
2818 .attrs = nvme_dev_attrs,
2819 .is_visible = nvme_dev_attrs_are_visible,
2822 static const struct attribute_group *nvme_dev_attr_groups[] = {
2823 &nvme_dev_attrs_group,
2827 static struct nvme_ns_head *__nvme_find_ns_head(struct nvme_subsystem *subsys,
2830 struct nvme_ns_head *h;
2832 lockdep_assert_held(&subsys->lock);
2834 list_for_each_entry(h, &subsys->nsheads, entry) {
2835 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
2842 static int __nvme_check_ids(struct nvme_subsystem *subsys,
2843 struct nvme_ns_head *new)
2845 struct nvme_ns_head *h;
2847 lockdep_assert_held(&subsys->lock);
2849 list_for_each_entry(h, &subsys->nsheads, entry) {
2850 if (nvme_ns_ids_valid(&new->ids) &&
2851 !list_empty(&h->list) &&
2852 nvme_ns_ids_equal(&new->ids, &h->ids))
2859 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
2860 unsigned nsid, struct nvme_id_ns *id)
2862 struct nvme_ns_head *head;
2865 head = kzalloc(sizeof(*head), GFP_KERNEL);
2868 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
2871 head->instance = ret;
2872 INIT_LIST_HEAD(&head->list);
2873 ret = init_srcu_struct(&head->srcu);
2875 goto out_ida_remove;
2876 head->subsys = ctrl->subsys;
2878 kref_init(&head->ref);
2880 nvme_report_ns_ids(ctrl, nsid, id, &head->ids);
2882 ret = __nvme_check_ids(ctrl->subsys, head);
2884 dev_err(ctrl->device,
2885 "duplicate IDs for nsid %d\n", nsid);
2886 goto out_cleanup_srcu;
2889 ret = nvme_mpath_alloc_disk(ctrl, head);
2891 goto out_cleanup_srcu;
2893 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
2895 kref_get(&ctrl->subsys->ref);
2899 cleanup_srcu_struct(&head->srcu);
2901 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
2905 return ERR_PTR(ret);
2908 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
2909 struct nvme_id_ns *id)
2911 struct nvme_ctrl *ctrl = ns->ctrl;
2912 bool is_shared = id->nmic & (1 << 0);
2913 struct nvme_ns_head *head = NULL;
2916 mutex_lock(&ctrl->subsys->lock);
2918 head = __nvme_find_ns_head(ctrl->subsys, nsid);
2920 head = nvme_alloc_ns_head(ctrl, nsid, id);
2922 ret = PTR_ERR(head);
2926 struct nvme_ns_ids ids;
2928 nvme_report_ns_ids(ctrl, nsid, id, &ids);
2929 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
2930 dev_err(ctrl->device,
2931 "IDs don't match for shared namespace %d\n",
2938 list_add_tail(&ns->siblings, &head->list);
2942 mutex_unlock(&ctrl->subsys->lock);
2946 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2948 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2949 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2951 return nsa->head->ns_id - nsb->head->ns_id;
2954 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2956 struct nvme_ns *ns, *ret = NULL;
2958 down_read(&ctrl->namespaces_rwsem);
2959 list_for_each_entry(ns, &ctrl->namespaces, list) {
2960 if (ns->head->ns_id == nsid) {
2961 if (!kref_get_unless_zero(&ns->kref))
2966 if (ns->head->ns_id > nsid)
2969 up_read(&ctrl->namespaces_rwsem);
2973 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2975 struct streams_directive_params s;
2978 if (!ctrl->nr_streams)
2981 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
2985 ns->sws = le32_to_cpu(s.sws);
2986 ns->sgs = le16_to_cpu(s.sgs);
2989 unsigned int bs = 1 << ns->lba_shift;
2991 blk_queue_io_min(ns->queue, bs * ns->sws);
2993 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2999 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3002 struct gendisk *disk;
3003 struct nvme_id_ns *id;
3004 char disk_name[DISK_NAME_LEN];
3005 int node = dev_to_node(ctrl->dev), flags = GENHD_FL_EXT_DEVT;
3007 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3011 ns->queue = blk_mq_init_queue(ctrl->tagset);
3012 if (IS_ERR(ns->queue))
3014 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3015 ns->queue->queuedata = ns;
3018 kref_init(&ns->kref);
3019 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
3021 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
3022 nvme_set_queue_limits(ctrl, ns->queue);
3024 id = nvme_identify_ns(ctrl, nsid);
3026 goto out_free_queue;
3031 if (nvme_init_ns_head(ns, nsid, id))
3033 nvme_setup_streams_ns(ctrl, ns);
3034 nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3036 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3037 if (nvme_nvm_register(ns, disk_name, node)) {
3038 dev_warn(ctrl->device, "LightNVM init failure\n");
3043 disk = alloc_disk_node(0, node);
3047 disk->fops = &nvme_fops;
3048 disk->private_data = ns;
3049 disk->queue = ns->queue;
3050 disk->flags = flags;
3051 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3054 __nvme_revalidate_disk(disk, id);
3056 down_write(&ctrl->namespaces_rwsem);
3057 list_add_tail(&ns->list, &ctrl->namespaces);
3058 up_write(&ctrl->namespaces_rwsem);
3060 nvme_get_ctrl(ctrl);
3064 device_add_disk(ctrl->device, ns->disk);
3065 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
3066 &nvme_ns_id_attr_group))
3067 pr_warn("%s: failed to create sysfs group for identification\n",
3068 ns->disk->disk_name);
3069 if (ns->ndev && nvme_nvm_register_sysfs(ns))
3070 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
3071 ns->disk->disk_name);
3073 nvme_mpath_add_disk(ns->head);
3074 nvme_fault_inject_init(ns);
3077 mutex_lock(&ctrl->subsys->lock);
3078 list_del_rcu(&ns->siblings);
3079 mutex_unlock(&ctrl->subsys->lock);
3083 blk_cleanup_queue(ns->queue);
3088 static void nvme_ns_remove(struct nvme_ns *ns)
3090 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3093 nvme_fault_inject_fini(ns);
3094 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
3095 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
3096 &nvme_ns_id_attr_group);
3098 nvme_nvm_unregister_sysfs(ns);
3099 del_gendisk(ns->disk);
3100 blk_cleanup_queue(ns->queue);
3101 if (blk_get_integrity(ns->disk))
3102 blk_integrity_unregister(ns->disk);
3105 mutex_lock(&ns->ctrl->subsys->lock);
3106 nvme_mpath_clear_current_path(ns);
3107 list_del_rcu(&ns->siblings);
3108 mutex_unlock(&ns->ctrl->subsys->lock);
3110 down_write(&ns->ctrl->namespaces_rwsem);
3111 list_del_init(&ns->list);
3112 up_write(&ns->ctrl->namespaces_rwsem);
3114 synchronize_srcu(&ns->head->srcu);
3115 nvme_mpath_check_last_path(ns);
3119 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3123 ns = nvme_find_get_ns(ctrl, nsid);
3125 if (ns->disk && revalidate_disk(ns->disk))
3129 nvme_alloc_ns(ctrl, nsid);
3132 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3135 struct nvme_ns *ns, *next;
3138 down_write(&ctrl->namespaces_rwsem);
3139 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3140 if (ns->head->ns_id > nsid)
3141 list_move_tail(&ns->list, &rm_list);
3143 up_write(&ctrl->namespaces_rwsem);
3145 list_for_each_entry_safe(ns, next, &rm_list, list)
3150 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
3154 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
3157 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3161 for (i = 0; i < num_lists; i++) {
3162 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
3166 for (j = 0; j < min(nn, 1024U); j++) {
3167 nsid = le32_to_cpu(ns_list[j]);
3171 nvme_validate_ns(ctrl, nsid);
3173 while (++prev < nsid) {
3174 ns = nvme_find_get_ns(ctrl, prev);
3184 nvme_remove_invalid_namespaces(ctrl, prev);
3190 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
3194 for (i = 1; i <= nn; i++)
3195 nvme_validate_ns(ctrl, i);
3197 nvme_remove_invalid_namespaces(ctrl, nn);
3200 static bool nvme_scan_changed_ns_log(struct nvme_ctrl *ctrl)
3202 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
3207 log = kzalloc(log_size, GFP_KERNEL);
3211 error = nvme_get_log(ctrl, NVME_LOG_CHANGED_NS, log, log_size);
3213 dev_warn(ctrl->device,
3214 "reading changed ns log failed: %d\n", error);
3218 if (log[0] == cpu_to_le32(0xffffffff))
3221 for (i = 0; i < NVME_MAX_CHANGED_NAMESPACES; i++) {
3222 u32 nsid = le32_to_cpu(log[i]);
3226 dev_info(ctrl->device, "rescanning namespace %d.\n", nsid);
3227 nvme_validate_ns(ctrl, nsid);
3236 static void nvme_scan_work(struct work_struct *work)
3238 struct nvme_ctrl *ctrl =
3239 container_of(work, struct nvme_ctrl, scan_work);
3240 struct nvme_id_ctrl *id;
3243 if (ctrl->state != NVME_CTRL_LIVE)
3246 WARN_ON_ONCE(!ctrl->tagset);
3248 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
3249 if (nvme_scan_changed_ns_log(ctrl))
3250 goto out_sort_namespaces;
3251 dev_info(ctrl->device, "rescanning namespaces.\n");
3254 if (nvme_identify_ctrl(ctrl, &id))
3257 nn = le32_to_cpu(id->nn);
3258 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
3259 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
3260 if (!nvme_scan_ns_list(ctrl, nn))
3263 nvme_scan_ns_sequential(ctrl, nn);
3266 out_sort_namespaces:
3267 down_write(&ctrl->namespaces_rwsem);
3268 list_sort(NULL, &ctrl->namespaces, ns_cmp);
3269 up_write(&ctrl->namespaces_rwsem);
3273 * This function iterates the namespace list unlocked to allow recovery from
3274 * controller failure. It is up to the caller to ensure the namespace list is
3275 * not modified by scan work while this function is executing.
3277 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3279 struct nvme_ns *ns, *next;
3283 * The dead states indicates the controller was not gracefully
3284 * disconnected. In that case, we won't be able to flush any data while
3285 * removing the namespaces' disks; fail all the queues now to avoid
3286 * potentially having to clean up the failed sync later.
3288 if (ctrl->state == NVME_CTRL_DEAD)
3289 nvme_kill_queues(ctrl);
3291 down_write(&ctrl->namespaces_rwsem);
3292 list_splice_init(&ctrl->namespaces, &ns_list);
3293 up_write(&ctrl->namespaces_rwsem);
3295 list_for_each_entry_safe(ns, next, &ns_list, list)
3298 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
3300 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
3302 char *envp[2] = { NULL, NULL };
3303 u32 aen_result = ctrl->aen_result;
3305 ctrl->aen_result = 0;
3309 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
3312 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
3316 static void nvme_async_event_work(struct work_struct *work)
3318 struct nvme_ctrl *ctrl =
3319 container_of(work, struct nvme_ctrl, async_event_work);
3321 nvme_aen_uevent(ctrl);
3322 ctrl->ops->submit_async_event(ctrl);
3325 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
3330 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
3336 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
3339 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
3341 struct nvme_fw_slot_info_log *log;
3343 log = kmalloc(sizeof(*log), GFP_KERNEL);
3347 if (nvme_get_log(ctrl, NVME_LOG_FW_SLOT, log, sizeof(*log)))
3348 dev_warn(ctrl->device,
3349 "Get FW SLOT INFO log error\n");
3353 static void nvme_fw_act_work(struct work_struct *work)
3355 struct nvme_ctrl *ctrl = container_of(work,
3356 struct nvme_ctrl, fw_act_work);
3357 unsigned long fw_act_timeout;
3360 fw_act_timeout = jiffies +
3361 msecs_to_jiffies(ctrl->mtfa * 100);
3363 fw_act_timeout = jiffies +
3364 msecs_to_jiffies(admin_timeout * 1000);
3366 nvme_stop_queues(ctrl);
3367 while (nvme_ctrl_pp_status(ctrl)) {
3368 if (time_after(jiffies, fw_act_timeout)) {
3369 dev_warn(ctrl->device,
3370 "Fw activation timeout, reset controller\n");
3371 nvme_reset_ctrl(ctrl);
3377 if (ctrl->state != NVME_CTRL_LIVE)
3380 nvme_start_queues(ctrl);
3381 /* read FW slot information to clear the AER */
3382 nvme_get_fw_slot_info(ctrl);
3385 static void nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
3387 switch ((result & 0xff00) >> 8) {
3388 case NVME_AER_NOTICE_NS_CHANGED:
3389 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
3390 nvme_queue_scan(ctrl);
3392 case NVME_AER_NOTICE_FW_ACT_STARTING:
3393 queue_work(nvme_wq, &ctrl->fw_act_work);
3396 dev_warn(ctrl->device, "async event result %08x\n", result);
3400 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
3401 volatile union nvme_result *res)
3403 u32 result = le32_to_cpu(res->u32);
3405 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
3408 switch (result & 0x7) {
3409 case NVME_AER_NOTICE:
3410 nvme_handle_aen_notice(ctrl, result);
3412 case NVME_AER_ERROR:
3413 case NVME_AER_SMART:
3416 ctrl->aen_result = result;
3421 queue_work(nvme_wq, &ctrl->async_event_work);
3423 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
3425 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
3427 nvme_stop_keep_alive(ctrl);
3428 flush_work(&ctrl->async_event_work);
3429 flush_work(&ctrl->scan_work);
3430 cancel_work_sync(&ctrl->fw_act_work);
3431 if (ctrl->ops->stop_ctrl)
3432 ctrl->ops->stop_ctrl(ctrl);
3434 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
3436 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
3439 nvme_start_keep_alive(ctrl);
3441 if (ctrl->queue_count > 1) {
3442 nvme_queue_scan(ctrl);
3443 nvme_enable_aen(ctrl);
3444 queue_work(nvme_wq, &ctrl->async_event_work);
3445 nvme_start_queues(ctrl);
3448 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
3450 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
3452 cdev_device_del(&ctrl->cdev, ctrl->device);
3454 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
3456 static void nvme_free_ctrl(struct device *dev)
3458 struct nvme_ctrl *ctrl =
3459 container_of(dev, struct nvme_ctrl, ctrl_device);
3460 struct nvme_subsystem *subsys = ctrl->subsys;
3462 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
3463 kfree(ctrl->effects);
3466 mutex_lock(&subsys->lock);
3467 list_del(&ctrl->subsys_entry);
3468 mutex_unlock(&subsys->lock);
3469 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
3472 ctrl->ops->free_ctrl(ctrl);
3475 nvme_put_subsystem(subsys);
3479 * Initialize a NVMe controller structures. This needs to be called during
3480 * earliest initialization so that we have the initialized structured around
3483 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
3484 const struct nvme_ctrl_ops *ops, unsigned long quirks)
3488 ctrl->state = NVME_CTRL_NEW;
3489 spin_lock_init(&ctrl->lock);
3490 INIT_LIST_HEAD(&ctrl->namespaces);
3491 init_rwsem(&ctrl->namespaces_rwsem);
3494 ctrl->quirks = quirks;
3495 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
3496 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
3497 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
3498 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
3500 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
3503 ctrl->instance = ret;
3505 device_initialize(&ctrl->ctrl_device);
3506 ctrl->device = &ctrl->ctrl_device;
3507 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
3508 ctrl->device->class = nvme_class;
3509 ctrl->device->parent = ctrl->dev;
3510 ctrl->device->groups = nvme_dev_attr_groups;
3511 ctrl->device->release = nvme_free_ctrl;
3512 dev_set_drvdata(ctrl->device, ctrl);
3513 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
3515 goto out_release_instance;
3517 cdev_init(&ctrl->cdev, &nvme_dev_fops);
3518 ctrl->cdev.owner = ops->module;
3519 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
3524 * Initialize latency tolerance controls. The sysfs files won't
3525 * be visible to userspace unless the device actually supports APST.
3527 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
3528 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
3529 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
3533 kfree_const(dev->kobj.name);
3534 out_release_instance:
3535 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
3539 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
3542 * nvme_kill_queues(): Ends all namespace queues
3543 * @ctrl: the dead controller that needs to end
3545 * Call this function when the driver determines it is unable to get the
3546 * controller in a state capable of servicing IO.
3548 void nvme_kill_queues(struct nvme_ctrl *ctrl)
3552 down_read(&ctrl->namespaces_rwsem);
3554 /* Forcibly unquiesce queues to avoid blocking dispatch */
3556 blk_mq_unquiesce_queue(ctrl->admin_q);
3558 list_for_each_entry(ns, &ctrl->namespaces, list) {
3560 * Revalidating a dead namespace sets capacity to 0. This will
3561 * end buffered writers dirtying pages that can't be synced.
3563 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
3565 revalidate_disk(ns->disk);
3566 blk_set_queue_dying(ns->queue);
3568 /* Forcibly unquiesce queues to avoid blocking dispatch */
3569 blk_mq_unquiesce_queue(ns->queue);
3571 up_read(&ctrl->namespaces_rwsem);
3573 EXPORT_SYMBOL_GPL(nvme_kill_queues);
3575 void nvme_unfreeze(struct nvme_ctrl *ctrl)
3579 down_read(&ctrl->namespaces_rwsem);
3580 list_for_each_entry(ns, &ctrl->namespaces, list)
3581 blk_mq_unfreeze_queue(ns->queue);
3582 up_read(&ctrl->namespaces_rwsem);
3584 EXPORT_SYMBOL_GPL(nvme_unfreeze);
3586 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
3590 down_read(&ctrl->namespaces_rwsem);
3591 list_for_each_entry(ns, &ctrl->namespaces, list) {
3592 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
3596 up_read(&ctrl->namespaces_rwsem);
3598 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
3600 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
3604 down_read(&ctrl->namespaces_rwsem);
3605 list_for_each_entry(ns, &ctrl->namespaces, list)
3606 blk_mq_freeze_queue_wait(ns->queue);
3607 up_read(&ctrl->namespaces_rwsem);
3609 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
3611 void nvme_start_freeze(struct nvme_ctrl *ctrl)
3615 down_read(&ctrl->namespaces_rwsem);
3616 list_for_each_entry(ns, &ctrl->namespaces, list)
3617 blk_freeze_queue_start(ns->queue);
3618 up_read(&ctrl->namespaces_rwsem);
3620 EXPORT_SYMBOL_GPL(nvme_start_freeze);
3622 void nvme_stop_queues(struct nvme_ctrl *ctrl)
3626 down_read(&ctrl->namespaces_rwsem);
3627 list_for_each_entry(ns, &ctrl->namespaces, list)
3628 blk_mq_quiesce_queue(ns->queue);
3629 up_read(&ctrl->namespaces_rwsem);
3631 EXPORT_SYMBOL_GPL(nvme_stop_queues);
3633 void nvme_start_queues(struct nvme_ctrl *ctrl)
3637 down_read(&ctrl->namespaces_rwsem);
3638 list_for_each_entry(ns, &ctrl->namespaces, list)
3639 blk_mq_unquiesce_queue(ns->queue);
3640 up_read(&ctrl->namespaces_rwsem);
3642 EXPORT_SYMBOL_GPL(nvme_start_queues);
3644 int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set)
3646 if (!ctrl->ops->reinit_request)
3649 return blk_mq_tagset_iter(set, set->driver_data,
3650 ctrl->ops->reinit_request);
3652 EXPORT_SYMBOL_GPL(nvme_reinit_tagset);
3654 int __init nvme_core_init(void)
3656 int result = -ENOMEM;
3658 nvme_wq = alloc_workqueue("nvme-wq",
3659 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3663 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
3664 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3668 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
3669 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3670 if (!nvme_delete_wq)
3671 goto destroy_reset_wq;
3673 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
3675 goto destroy_delete_wq;
3677 nvme_class = class_create(THIS_MODULE, "nvme");
3678 if (IS_ERR(nvme_class)) {
3679 result = PTR_ERR(nvme_class);
3680 goto unregister_chrdev;
3683 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
3684 if (IS_ERR(nvme_subsys_class)) {
3685 result = PTR_ERR(nvme_subsys_class);
3691 class_destroy(nvme_class);
3693 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
3695 destroy_workqueue(nvme_delete_wq);
3697 destroy_workqueue(nvme_reset_wq);
3699 destroy_workqueue(nvme_wq);
3704 void nvme_core_exit(void)
3706 ida_destroy(&nvme_subsystems_ida);
3707 class_destroy(nvme_subsys_class);
3708 class_destroy(nvme_class);
3709 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
3710 destroy_workqueue(nvme_delete_wq);
3711 destroy_workqueue(nvme_reset_wq);
3712 destroy_workqueue(nvme_wq);
3715 MODULE_LICENSE("GPL");
3716 MODULE_VERSION("1.0");
3717 module_init(nvme_core_init);
3718 module_exit(nvme_core_exit);