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>
35 #define NVME_MINORS (1U << MINORBITS)
37 unsigned char admin_timeout = 60;
38 module_param(admin_timeout, byte, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
42 unsigned char nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
47 static unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
51 static u8 nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, byte, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
55 static int nvme_char_major;
56 module_param(nvme_char_major, int, 0);
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");
71 struct workqueue_struct *nvme_wq;
72 EXPORT_SYMBOL_GPL(nvme_wq);
74 static LIST_HEAD(nvme_ctrl_list);
75 static DEFINE_SPINLOCK(dev_list_lock);
77 static struct class *nvme_class;
79 static __le32 nvme_get_log_dw10(u8 lid, size_t size)
81 return cpu_to_le32((((size / 4) - 1) << 16) | lid);
84 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
86 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
88 if (!queue_work(nvme_wq, &ctrl->reset_work))
92 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
94 static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
98 ret = nvme_reset_ctrl(ctrl);
100 flush_work(&ctrl->reset_work);
104 static blk_status_t nvme_error_status(struct request *req)
106 switch (nvme_req(req)->status & 0x7ff) {
107 case NVME_SC_SUCCESS:
109 case NVME_SC_CAP_EXCEEDED:
110 return BLK_STS_NOSPC;
111 case NVME_SC_ONCS_NOT_SUPPORTED:
112 return BLK_STS_NOTSUPP;
113 case NVME_SC_WRITE_FAULT:
114 case NVME_SC_READ_ERROR:
115 case NVME_SC_UNWRITTEN_BLOCK:
116 case NVME_SC_ACCESS_DENIED:
117 case NVME_SC_READ_ONLY:
118 return BLK_STS_MEDIUM;
119 case NVME_SC_GUARD_CHECK:
120 case NVME_SC_APPTAG_CHECK:
121 case NVME_SC_REFTAG_CHECK:
122 case NVME_SC_INVALID_PI:
123 return BLK_STS_PROTECTION;
124 case NVME_SC_RESERVATION_CONFLICT:
125 return BLK_STS_NEXUS;
127 return BLK_STS_IOERR;
131 static inline bool nvme_req_needs_retry(struct request *req)
133 if (blk_noretry_request(req))
135 if (nvme_req(req)->status & NVME_SC_DNR)
137 if (nvme_req(req)->retries >= nvme_max_retries)
142 void nvme_complete_rq(struct request *req)
144 if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
145 nvme_req(req)->retries++;
146 blk_mq_requeue_request(req, true);
150 blk_mq_end_request(req, nvme_error_status(req));
152 EXPORT_SYMBOL_GPL(nvme_complete_rq);
154 void nvme_cancel_request(struct request *req, void *data, bool reserved)
158 if (!blk_mq_request_started(req))
161 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
162 "Cancelling I/O %d", req->tag);
164 status = NVME_SC_ABORT_REQ;
165 if (blk_queue_dying(req->q))
166 status |= NVME_SC_DNR;
167 nvme_req(req)->status = status;
168 blk_mq_complete_request(req);
171 EXPORT_SYMBOL_GPL(nvme_cancel_request);
173 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
174 enum nvme_ctrl_state new_state)
176 enum nvme_ctrl_state old_state;
178 bool changed = false;
180 spin_lock_irqsave(&ctrl->lock, flags);
182 old_state = ctrl->state;
187 case NVME_CTRL_RESETTING:
188 case NVME_CTRL_RECONNECTING:
195 case NVME_CTRL_RESETTING:
205 case NVME_CTRL_RECONNECTING:
214 case NVME_CTRL_DELETING:
217 case NVME_CTRL_RESETTING:
218 case NVME_CTRL_RECONNECTING:
227 case NVME_CTRL_DELETING:
239 ctrl->state = new_state;
241 spin_unlock_irqrestore(&ctrl->lock, flags);
245 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
247 static void nvme_free_ns(struct kref *kref)
249 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
252 nvme_nvm_unregister(ns);
255 spin_lock(&dev_list_lock);
256 ns->disk->private_data = NULL;
257 spin_unlock(&dev_list_lock);
261 ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
262 nvme_put_ctrl(ns->ctrl);
266 static void nvme_put_ns(struct nvme_ns *ns)
268 kref_put(&ns->kref, nvme_free_ns);
271 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
275 spin_lock(&dev_list_lock);
276 ns = disk->private_data;
278 if (!kref_get_unless_zero(&ns->kref))
280 if (!try_module_get(ns->ctrl->ops->module))
283 spin_unlock(&dev_list_lock);
288 kref_put(&ns->kref, nvme_free_ns);
290 spin_unlock(&dev_list_lock);
294 struct request *nvme_alloc_request(struct request_queue *q,
295 struct nvme_command *cmd, unsigned int flags, int qid)
297 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
300 if (qid == NVME_QID_ANY) {
301 req = blk_mq_alloc_request(q, op, flags);
303 req = blk_mq_alloc_request_hctx(q, op, flags,
309 req->cmd_flags |= REQ_FAILFAST_DRIVER;
310 nvme_req(req)->cmd = cmd;
314 EXPORT_SYMBOL_GPL(nvme_alloc_request);
316 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
318 struct nvme_command c;
320 memset(&c, 0, sizeof(c));
322 c.directive.opcode = nvme_admin_directive_send;
323 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
324 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
325 c.directive.dtype = NVME_DIR_IDENTIFY;
326 c.directive.tdtype = NVME_DIR_STREAMS;
327 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
329 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
332 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
334 return nvme_toggle_streams(ctrl, false);
337 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
339 return nvme_toggle_streams(ctrl, true);
342 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
343 struct streams_directive_params *s, u32 nsid)
345 struct nvme_command c;
347 memset(&c, 0, sizeof(c));
348 memset(s, 0, sizeof(*s));
350 c.directive.opcode = nvme_admin_directive_recv;
351 c.directive.nsid = cpu_to_le32(nsid);
352 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
353 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
354 c.directive.dtype = NVME_DIR_STREAMS;
356 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
359 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
361 struct streams_directive_params s;
364 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
369 ret = nvme_enable_streams(ctrl);
373 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
377 ctrl->nssa = le16_to_cpu(s.nssa);
378 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
379 dev_info(ctrl->device, "too few streams (%u) available\n",
381 nvme_disable_streams(ctrl);
385 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
386 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
391 * Check if 'req' has a write hint associated with it. If it does, assign
392 * a valid namespace stream to the write.
394 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
395 struct request *req, u16 *control,
398 enum rw_hint streamid = req->write_hint;
400 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
404 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
407 *control |= NVME_RW_DTYPE_STREAMS;
408 *dsmgmt |= streamid << 16;
411 if (streamid < ARRAY_SIZE(req->q->write_hints))
412 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
415 static inline void nvme_setup_flush(struct nvme_ns *ns,
416 struct nvme_command *cmnd)
418 memset(cmnd, 0, sizeof(*cmnd));
419 cmnd->common.opcode = nvme_cmd_flush;
420 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
423 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
424 struct nvme_command *cmnd)
426 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
427 struct nvme_dsm_range *range;
430 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
432 return BLK_STS_RESOURCE;
434 __rq_for_each_bio(bio, req) {
435 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
436 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
438 range[n].cattr = cpu_to_le32(0);
439 range[n].nlb = cpu_to_le32(nlb);
440 range[n].slba = cpu_to_le64(slba);
444 if (WARN_ON_ONCE(n != segments)) {
446 return BLK_STS_IOERR;
449 memset(cmnd, 0, sizeof(*cmnd));
450 cmnd->dsm.opcode = nvme_cmd_dsm;
451 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
452 cmnd->dsm.nr = cpu_to_le32(segments - 1);
453 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
455 req->special_vec.bv_page = virt_to_page(range);
456 req->special_vec.bv_offset = offset_in_page(range);
457 req->special_vec.bv_len = sizeof(*range) * segments;
458 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
463 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
464 struct request *req, struct nvme_command *cmnd)
466 struct nvme_ctrl *ctrl = ns->ctrl;
471 * If formated with metadata, require the block layer provide a buffer
472 * unless this namespace is formated such that the metadata can be
473 * stripped/generated by the controller with PRACT=1.
476 (!ns->pi_type || ns->ms != sizeof(struct t10_pi_tuple)) &&
477 !blk_integrity_rq(req) && !blk_rq_is_passthrough(req))
478 return BLK_STS_NOTSUPP;
480 if (req->cmd_flags & REQ_FUA)
481 control |= NVME_RW_FUA;
482 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
483 control |= NVME_RW_LR;
485 if (req->cmd_flags & REQ_RAHEAD)
486 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
488 memset(cmnd, 0, sizeof(*cmnd));
489 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
490 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
491 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
492 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
494 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
495 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
498 switch (ns->pi_type) {
499 case NVME_NS_DPS_PI_TYPE3:
500 control |= NVME_RW_PRINFO_PRCHK_GUARD;
502 case NVME_NS_DPS_PI_TYPE1:
503 case NVME_NS_DPS_PI_TYPE2:
504 control |= NVME_RW_PRINFO_PRCHK_GUARD |
505 NVME_RW_PRINFO_PRCHK_REF;
506 cmnd->rw.reftag = cpu_to_le32(
507 nvme_block_nr(ns, blk_rq_pos(req)));
510 if (!blk_integrity_rq(req))
511 control |= NVME_RW_PRINFO_PRACT;
514 cmnd->rw.control = cpu_to_le16(control);
515 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
519 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
520 struct nvme_command *cmd)
522 blk_status_t ret = BLK_STS_OK;
524 if (!(req->rq_flags & RQF_DONTPREP)) {
525 nvme_req(req)->retries = 0;
526 nvme_req(req)->flags = 0;
527 req->rq_flags |= RQF_DONTPREP;
530 switch (req_op(req)) {
533 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
536 nvme_setup_flush(ns, cmd);
538 case REQ_OP_WRITE_ZEROES:
539 /* currently only aliased to deallocate for a few ctrls: */
541 ret = nvme_setup_discard(ns, req, cmd);
545 ret = nvme_setup_rw(ns, req, cmd);
549 return BLK_STS_IOERR;
552 cmd->common.command_id = req->tag;
555 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
558 * Returns 0 on success. If the result is negative, it's a Linux error code;
559 * if the result is positive, it's an NVM Express status code
561 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
562 union nvme_result *result, void *buffer, unsigned bufflen,
563 unsigned timeout, int qid, int at_head, int flags)
568 req = nvme_alloc_request(q, cmd, flags, qid);
572 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
574 if (buffer && bufflen) {
575 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
580 blk_execute_rq(req->q, NULL, req, at_head);
582 *result = nvme_req(req)->result;
583 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
586 ret = nvme_req(req)->status;
588 blk_mq_free_request(req);
591 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
593 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
594 void *buffer, unsigned bufflen)
596 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
599 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
601 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
602 unsigned len, u32 seed, bool write)
604 struct bio_integrity_payload *bip;
608 buf = kmalloc(len, GFP_KERNEL);
613 if (write && copy_from_user(buf, ubuf, len))
616 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
622 bip->bip_iter.bi_size = len;
623 bip->bip_iter.bi_sector = seed;
624 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
625 offset_in_page(buf));
635 static int nvme_submit_user_cmd(struct request_queue *q,
636 struct nvme_command *cmd, void __user *ubuffer,
637 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
638 u32 meta_seed, u32 *result, unsigned timeout)
640 bool write = nvme_is_write(cmd);
641 struct nvme_ns *ns = q->queuedata;
642 struct gendisk *disk = ns ? ns->disk : NULL;
644 struct bio *bio = NULL;
648 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
652 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
654 if (ubuffer && bufflen) {
655 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
661 if (disk && meta_buffer && meta_len) {
662 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
668 req->cmd_flags |= REQ_INTEGRITY;
672 blk_execute_rq(req->q, disk, req, 0);
673 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
676 ret = nvme_req(req)->status;
678 *result = le32_to_cpu(nvme_req(req)->result.u32);
679 if (meta && !ret && !write) {
680 if (copy_to_user(meta_buffer, meta, meta_len))
686 blk_rq_unmap_user(bio);
688 blk_mq_free_request(req);
692 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
694 struct nvme_ctrl *ctrl = rq->end_io_data;
696 blk_mq_free_request(rq);
699 dev_err(ctrl->device,
700 "failed nvme_keep_alive_end_io error=%d\n",
705 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
708 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
710 struct nvme_command c;
713 memset(&c, 0, sizeof(c));
714 c.common.opcode = nvme_admin_keep_alive;
716 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
721 rq->timeout = ctrl->kato * HZ;
722 rq->end_io_data = ctrl;
724 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
729 static void nvme_keep_alive_work(struct work_struct *work)
731 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
732 struct nvme_ctrl, ka_work);
734 if (nvme_keep_alive(ctrl)) {
735 /* allocation failure, reset the controller */
736 dev_err(ctrl->device, "keep-alive failed\n");
737 nvme_reset_ctrl(ctrl);
742 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
744 if (unlikely(ctrl->kato == 0))
747 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
748 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
750 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
752 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
754 if (unlikely(ctrl->kato == 0))
757 cancel_delayed_work_sync(&ctrl->ka_work);
759 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
762 * In NVMe 1.0 the CNS field was just a binary controller or namespace
763 * flag, thus sending any new CNS opcodes has a big chance of not working.
764 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
765 * (but not for any later version).
767 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
769 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
770 return ctrl->vs < NVME_VS(1, 2, 0);
771 return ctrl->vs < NVME_VS(1, 1, 0);
774 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
776 struct nvme_command c = { };
779 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
780 c.identify.opcode = nvme_admin_identify;
781 c.identify.cns = NVME_ID_CNS_CTRL;
783 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
787 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
788 sizeof(struct nvme_id_ctrl));
794 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
795 u8 *eui64, u8 *nguid, uuid_t *uuid)
797 struct nvme_command c = { };
803 c.identify.opcode = nvme_admin_identify;
804 c.identify.nsid = cpu_to_le32(nsid);
805 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
807 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
811 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
812 NVME_IDENTIFY_DATA_SIZE);
816 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
817 struct nvme_ns_id_desc *cur = data + pos;
823 case NVME_NIDT_EUI64:
824 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
825 dev_warn(ctrl->device,
826 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
830 len = NVME_NIDT_EUI64_LEN;
831 memcpy(eui64, data + pos + sizeof(*cur), len);
833 case NVME_NIDT_NGUID:
834 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
835 dev_warn(ctrl->device,
836 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
840 len = NVME_NIDT_NGUID_LEN;
841 memcpy(nguid, data + pos + sizeof(*cur), len);
844 if (cur->nidl != NVME_NIDT_UUID_LEN) {
845 dev_warn(ctrl->device,
846 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
850 len = NVME_NIDT_UUID_LEN;
851 uuid_copy(uuid, data + pos + sizeof(*cur));
854 /* Skip unnkown types */
866 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
868 struct nvme_command c = { };
870 c.identify.opcode = nvme_admin_identify;
871 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
872 c.identify.nsid = cpu_to_le32(nsid);
873 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
876 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
879 struct nvme_id_ns *id;
880 struct nvme_command c = { };
883 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
884 c.identify.opcode = nvme_admin_identify;
885 c.identify.nsid = cpu_to_le32(nsid);
886 c.identify.cns = NVME_ID_CNS_NS;
888 id = kmalloc(sizeof(*id), GFP_KERNEL);
892 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
894 dev_warn(ctrl->device, "Identify namespace failed\n");
902 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
903 void *buffer, size_t buflen, u32 *result)
905 union nvme_result res = { 0 };
906 struct nvme_command c;
909 memset(&c, 0, sizeof(c));
910 c.features.opcode = nvme_admin_set_features;
911 c.features.fid = cpu_to_le32(fid);
912 c.features.dword11 = cpu_to_le32(dword11);
914 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
915 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
916 if (ret >= 0 && result)
917 *result = le32_to_cpu(res.u32);
921 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
923 u32 q_count = (*count - 1) | ((*count - 1) << 16);
925 int status, nr_io_queues;
927 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
933 * Degraded controllers might return an error when setting the queue
934 * count. We still want to be able to bring them online and offer
935 * access to the admin queue, as that might be only way to fix them up.
938 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
941 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
942 *count = min(*count, nr_io_queues);
947 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
949 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
951 struct nvme_user_io io;
952 struct nvme_command c;
953 unsigned length, meta_len;
954 void __user *metadata;
956 if (copy_from_user(&io, uio, sizeof(io)))
964 case nvme_cmd_compare:
970 length = (io.nblocks + 1) << ns->lba_shift;
971 meta_len = (io.nblocks + 1) * ns->ms;
972 metadata = (void __user *)(uintptr_t)io.metadata;
977 } else if (meta_len) {
978 if ((io.metadata & 3) || !io.metadata)
982 memset(&c, 0, sizeof(c));
983 c.rw.opcode = io.opcode;
984 c.rw.flags = io.flags;
985 c.rw.nsid = cpu_to_le32(ns->ns_id);
986 c.rw.slba = cpu_to_le64(io.slba);
987 c.rw.length = cpu_to_le16(io.nblocks);
988 c.rw.control = cpu_to_le16(io.control);
989 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
990 c.rw.reftag = cpu_to_le32(io.reftag);
991 c.rw.apptag = cpu_to_le16(io.apptag);
992 c.rw.appmask = cpu_to_le16(io.appmask);
994 return nvme_submit_user_cmd(ns->queue, &c,
995 (void __user *)(uintptr_t)io.addr, length,
996 metadata, meta_len, io.slba, NULL, 0);
999 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1000 struct nvme_passthru_cmd __user *ucmd)
1002 struct nvme_passthru_cmd cmd;
1003 struct nvme_command c;
1004 unsigned timeout = 0;
1007 if (!capable(CAP_SYS_ADMIN))
1009 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1014 memset(&c, 0, sizeof(c));
1015 c.common.opcode = cmd.opcode;
1016 c.common.flags = cmd.flags;
1017 c.common.nsid = cpu_to_le32(cmd.nsid);
1018 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1019 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1020 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1021 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1022 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1023 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1024 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1025 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1028 timeout = msecs_to_jiffies(cmd.timeout_ms);
1030 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1031 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1032 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata_len,
1033 0, &cmd.result, timeout);
1035 if (put_user(cmd.result, &ucmd->result))
1042 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1043 unsigned int cmd, unsigned long arg)
1045 struct nvme_ns *ns = bdev->bd_disk->private_data;
1049 force_successful_syscall_return();
1051 case NVME_IOCTL_ADMIN_CMD:
1052 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1053 case NVME_IOCTL_IO_CMD:
1054 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1055 case NVME_IOCTL_SUBMIT_IO:
1056 return nvme_submit_io(ns, (void __user *)arg);
1059 return nvme_nvm_ioctl(ns, cmd, arg);
1060 if (is_sed_ioctl(cmd))
1061 return sed_ioctl(ns->ctrl->opal_dev, cmd,
1062 (void __user *) arg);
1067 #ifdef CONFIG_COMPAT
1068 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1069 unsigned int cmd, unsigned long arg)
1071 return nvme_ioctl(bdev, mode, cmd, arg);
1074 #define nvme_compat_ioctl NULL
1077 static int nvme_open(struct block_device *bdev, fmode_t mode)
1079 return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
1082 static void nvme_release(struct gendisk *disk, fmode_t mode)
1084 struct nvme_ns *ns = disk->private_data;
1086 module_put(ns->ctrl->ops->module);
1090 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1092 /* some standard values */
1093 geo->heads = 1 << 6;
1094 geo->sectors = 1 << 5;
1095 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1099 #ifdef CONFIG_BLK_DEV_INTEGRITY
1100 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1103 struct nvme_ns *ns = disk->private_data;
1104 u16 old_ms = ns->ms;
1107 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1108 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1110 /* PI implementation requires metadata equal t10 pi tuple size */
1111 if (ns->ms == sizeof(struct t10_pi_tuple))
1112 pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1114 if (blk_get_integrity(disk) &&
1115 (ns->pi_type != pi_type || ns->ms != old_ms ||
1116 bs != queue_logical_block_size(disk->queue) ||
1117 (ns->ms && ns->ext)))
1118 blk_integrity_unregister(disk);
1120 ns->pi_type = pi_type;
1123 static void nvme_init_integrity(struct nvme_ns *ns)
1125 struct blk_integrity integrity;
1127 memset(&integrity, 0, sizeof(integrity));
1128 switch (ns->pi_type) {
1129 case NVME_NS_DPS_PI_TYPE3:
1130 integrity.profile = &t10_pi_type3_crc;
1131 integrity.tag_size = sizeof(u16) + sizeof(u32);
1132 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1134 case NVME_NS_DPS_PI_TYPE1:
1135 case NVME_NS_DPS_PI_TYPE2:
1136 integrity.profile = &t10_pi_type1_crc;
1137 integrity.tag_size = sizeof(u16);
1138 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1141 integrity.profile = NULL;
1144 integrity.tuple_size = ns->ms;
1145 blk_integrity_register(ns->disk, &integrity);
1146 blk_queue_max_integrity_segments(ns->queue, 1);
1149 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1153 static void nvme_init_integrity(struct nvme_ns *ns)
1156 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1158 static void nvme_set_chunk_size(struct nvme_ns *ns)
1160 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1161 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1164 static void nvme_config_discard(struct nvme_ns *ns)
1166 struct nvme_ctrl *ctrl = ns->ctrl;
1167 u32 logical_block_size = queue_logical_block_size(ns->queue);
1169 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1170 NVME_DSM_MAX_RANGES);
1172 if (ctrl->nr_streams && ns->sws && ns->sgs) {
1173 unsigned int sz = logical_block_size * ns->sws * ns->sgs;
1175 ns->queue->limits.discard_alignment = sz;
1176 ns->queue->limits.discard_granularity = sz;
1178 ns->queue->limits.discard_alignment = logical_block_size;
1179 ns->queue->limits.discard_granularity = logical_block_size;
1181 blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
1182 blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1183 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1185 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1186 blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1189 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1190 struct nvme_id_ns *id, u8 *eui64, u8 *nguid, uuid_t *uuid)
1192 if (ctrl->vs >= NVME_VS(1, 1, 0))
1193 memcpy(eui64, id->eui64, sizeof(id->eui64));
1194 if (ctrl->vs >= NVME_VS(1, 2, 0))
1195 memcpy(nguid, id->nguid, sizeof(id->nguid));
1196 if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1197 /* Don't treat error as fatal we potentially
1198 * already have a NGUID or EUI-64
1200 if (nvme_identify_ns_descs(ctrl, nsid, eui64, nguid, uuid))
1201 dev_warn(ctrl->device,
1202 "%s: Identify Descriptors failed\n", __func__);
1206 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1208 struct nvme_ns *ns = disk->private_data;
1209 struct nvme_ctrl *ctrl = ns->ctrl;
1213 * If identify namespace failed, use default 512 byte block size so
1214 * block layer can use before failing read/write for 0 capacity.
1216 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1217 if (ns->lba_shift == 0)
1219 bs = 1 << ns->lba_shift;
1220 ns->noiob = le16_to_cpu(id->noiob);
1222 blk_mq_freeze_queue(disk->queue);
1224 if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
1225 nvme_prep_integrity(disk, id, bs);
1226 blk_queue_logical_block_size(ns->queue, bs);
1228 nvme_set_chunk_size(ns);
1229 if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1230 nvme_init_integrity(ns);
1231 if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1232 set_capacity(disk, 0);
1234 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1236 if (ctrl->oncs & NVME_CTRL_ONCS_DSM)
1237 nvme_config_discard(ns);
1238 blk_mq_unfreeze_queue(disk->queue);
1241 static int nvme_revalidate_disk(struct gendisk *disk)
1243 struct nvme_ns *ns = disk->private_data;
1244 struct nvme_ctrl *ctrl = ns->ctrl;
1245 struct nvme_id_ns *id;
1246 u8 eui64[8] = { 0 }, nguid[16] = { 0 };
1247 uuid_t uuid = uuid_null;
1250 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1251 set_capacity(disk, 0);
1255 id = nvme_identify_ns(ctrl, ns->ns_id);
1259 if (id->ncap == 0) {
1264 __nvme_revalidate_disk(disk, id);
1265 nvme_report_ns_ids(ctrl, ns->ns_id, id, eui64, nguid, &uuid);
1266 if (!uuid_equal(&ns->uuid, &uuid) ||
1267 memcmp(&ns->nguid, &nguid, sizeof(ns->nguid)) ||
1268 memcmp(&ns->eui, &eui64, sizeof(ns->eui))) {
1269 dev_err(ctrl->device,
1270 "identifiers changed for nsid %d\n", ns->ns_id);
1279 static char nvme_pr_type(enum pr_type type)
1282 case PR_WRITE_EXCLUSIVE:
1284 case PR_EXCLUSIVE_ACCESS:
1286 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1288 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1290 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1292 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1299 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1300 u64 key, u64 sa_key, u8 op)
1302 struct nvme_ns *ns = bdev->bd_disk->private_data;
1303 struct nvme_command c;
1304 u8 data[16] = { 0, };
1306 put_unaligned_le64(key, &data[0]);
1307 put_unaligned_le64(sa_key, &data[8]);
1309 memset(&c, 0, sizeof(c));
1310 c.common.opcode = op;
1311 c.common.nsid = cpu_to_le32(ns->ns_id);
1312 c.common.cdw10[0] = cpu_to_le32(cdw10);
1314 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1317 static int nvme_pr_register(struct block_device *bdev, u64 old,
1318 u64 new, unsigned flags)
1322 if (flags & ~PR_FL_IGNORE_KEY)
1325 cdw10 = old ? 2 : 0;
1326 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1327 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1328 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1331 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1332 enum pr_type type, unsigned flags)
1336 if (flags & ~PR_FL_IGNORE_KEY)
1339 cdw10 = nvme_pr_type(type) << 8;
1340 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1341 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1344 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1345 enum pr_type type, bool abort)
1347 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1348 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1351 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1353 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1354 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1357 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1359 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
1360 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1363 static const struct pr_ops nvme_pr_ops = {
1364 .pr_register = nvme_pr_register,
1365 .pr_reserve = nvme_pr_reserve,
1366 .pr_release = nvme_pr_release,
1367 .pr_preempt = nvme_pr_preempt,
1368 .pr_clear = nvme_pr_clear,
1371 #ifdef CONFIG_BLK_SED_OPAL
1372 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1375 struct nvme_ctrl *ctrl = data;
1376 struct nvme_command cmd;
1378 memset(&cmd, 0, sizeof(cmd));
1380 cmd.common.opcode = nvme_admin_security_send;
1382 cmd.common.opcode = nvme_admin_security_recv;
1383 cmd.common.nsid = 0;
1384 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1385 cmd.common.cdw10[1] = cpu_to_le32(len);
1387 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1388 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1390 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1391 #endif /* CONFIG_BLK_SED_OPAL */
1393 static const struct block_device_operations nvme_fops = {
1394 .owner = THIS_MODULE,
1395 .ioctl = nvme_ioctl,
1396 .compat_ioctl = nvme_compat_ioctl,
1398 .release = nvme_release,
1399 .getgeo = nvme_getgeo,
1400 .revalidate_disk= nvme_revalidate_disk,
1401 .pr_ops = &nvme_pr_ops,
1404 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1406 unsigned long timeout =
1407 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1408 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1411 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1414 if ((csts & NVME_CSTS_RDY) == bit)
1418 if (fatal_signal_pending(current))
1420 if (time_after(jiffies, timeout)) {
1421 dev_err(ctrl->device,
1422 "Device not ready; aborting %s\n", enabled ?
1423 "initialisation" : "reset");
1432 * If the device has been passed off to us in an enabled state, just clear
1433 * the enabled bit. The spec says we should set the 'shutdown notification
1434 * bits', but doing so may cause the device to complete commands to the
1435 * admin queue ... and we don't know what memory that might be pointing at!
1437 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1441 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1442 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1444 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1448 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1449 msleep(NVME_QUIRK_DELAY_AMOUNT);
1451 return nvme_wait_ready(ctrl, cap, false);
1453 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1455 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1458 * Default to a 4K page size, with the intention to update this
1459 * path in the future to accomodate architectures with differing
1460 * kernel and IO page sizes.
1462 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1465 if (page_shift < dev_page_min) {
1466 dev_err(ctrl->device,
1467 "Minimum device page size %u too large for host (%u)\n",
1468 1 << dev_page_min, 1 << page_shift);
1472 ctrl->page_size = 1 << page_shift;
1474 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1475 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1476 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1477 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1478 ctrl->ctrl_config |= NVME_CC_ENABLE;
1480 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1483 return nvme_wait_ready(ctrl, cap, true);
1485 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1487 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1489 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1493 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1494 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1496 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1500 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1501 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1505 if (fatal_signal_pending(current))
1507 if (time_after(jiffies, timeout)) {
1508 dev_err(ctrl->device,
1509 "Device shutdown incomplete; abort shutdown\n");
1516 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1518 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1519 struct request_queue *q)
1523 if (ctrl->max_hw_sectors) {
1525 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1527 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1528 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1530 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1531 is_power_of_2(ctrl->max_hw_sectors))
1532 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1533 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1534 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1536 blk_queue_write_cache(q, vwc, vwc);
1539 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1544 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1547 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1548 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1551 dev_warn_once(ctrl->device,
1552 "could not set timestamp (%d)\n", ret);
1556 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1559 * APST (Autonomous Power State Transition) lets us program a
1560 * table of power state transitions that the controller will
1561 * perform automatically. We configure it with a simple
1562 * heuristic: we are willing to spend at most 2% of the time
1563 * transitioning between power states. Therefore, when running
1564 * in any given state, we will enter the next lower-power
1565 * non-operational state after waiting 50 * (enlat + exlat)
1566 * microseconds, as long as that state's exit latency is under
1567 * the requested maximum latency.
1569 * We will not autonomously enter any non-operational state for
1570 * which the total latency exceeds ps_max_latency_us. Users
1571 * can set ps_max_latency_us to zero to turn off APST.
1575 struct nvme_feat_auto_pst *table;
1581 * If APST isn't supported or if we haven't been initialized yet,
1582 * then don't do anything.
1587 if (ctrl->npss > 31) {
1588 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1592 table = kzalloc(sizeof(*table), GFP_KERNEL);
1596 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1597 /* Turn off APST. */
1599 dev_dbg(ctrl->device, "APST disabled\n");
1601 __le64 target = cpu_to_le64(0);
1605 * Walk through all states from lowest- to highest-power.
1606 * According to the spec, lower-numbered states use more
1607 * power. NPSS, despite the name, is the index of the
1608 * lowest-power state, not the number of states.
1610 for (state = (int)ctrl->npss; state >= 0; state--) {
1611 u64 total_latency_us, exit_latency_us, transition_ms;
1614 table->entries[state] = target;
1617 * Don't allow transitions to the deepest state
1618 * if it's quirked off.
1620 if (state == ctrl->npss &&
1621 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1625 * Is this state a useful non-operational state for
1626 * higher-power states to autonomously transition to?
1628 if (!(ctrl->psd[state].flags &
1629 NVME_PS_FLAGS_NON_OP_STATE))
1633 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1634 if (exit_latency_us > ctrl->ps_max_latency_us)
1639 le32_to_cpu(ctrl->psd[state].entry_lat);
1642 * This state is good. Use it as the APST idle
1643 * target for higher power states.
1645 transition_ms = total_latency_us + 19;
1646 do_div(transition_ms, 20);
1647 if (transition_ms > (1 << 24) - 1)
1648 transition_ms = (1 << 24) - 1;
1650 target = cpu_to_le64((state << 3) |
1651 (transition_ms << 8));
1656 if (total_latency_us > max_lat_us)
1657 max_lat_us = total_latency_us;
1663 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1665 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1666 max_ps, max_lat_us, (int)sizeof(*table), table);
1670 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1671 table, sizeof(*table), NULL);
1673 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1679 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1681 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1685 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1686 case PM_QOS_LATENCY_ANY:
1694 if (ctrl->ps_max_latency_us != latency) {
1695 ctrl->ps_max_latency_us = latency;
1696 nvme_configure_apst(ctrl);
1700 struct nvme_core_quirk_entry {
1702 * NVMe model and firmware strings are padded with spaces. For
1703 * simplicity, strings in the quirk table are padded with NULLs
1709 unsigned long quirks;
1712 static const struct nvme_core_quirk_entry core_quirks[] = {
1715 * This Toshiba device seems to die using any APST states. See:
1716 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1719 .mn = "THNSF5256GPUK TOSHIBA",
1720 .quirks = NVME_QUIRK_NO_APST,
1724 /* match is null-terminated but idstr is space-padded. */
1725 static bool string_matches(const char *idstr, const char *match, size_t len)
1732 matchlen = strlen(match);
1733 WARN_ON_ONCE(matchlen > len);
1735 if (memcmp(idstr, match, matchlen))
1738 for (; matchlen < len; matchlen++)
1739 if (idstr[matchlen] != ' ')
1745 static bool quirk_matches(const struct nvme_id_ctrl *id,
1746 const struct nvme_core_quirk_entry *q)
1748 return q->vid == le16_to_cpu(id->vid) &&
1749 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1750 string_matches(id->fr, q->fr, sizeof(id->fr));
1753 static void nvme_init_subnqn(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1758 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
1759 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
1760 strcpy(ctrl->subnqn, id->subnqn);
1764 if (ctrl->vs >= NVME_VS(1, 2, 1))
1765 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
1767 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
1768 off = snprintf(ctrl->subnqn, NVMF_NQN_SIZE,
1769 "nqn.2014.08.org.nvmexpress:%4x%4x",
1770 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
1771 memcpy(ctrl->subnqn + off, id->sn, sizeof(id->sn));
1772 off += sizeof(id->sn);
1773 memcpy(ctrl->subnqn + off, id->mn, sizeof(id->mn));
1774 off += sizeof(id->mn);
1775 memset(ctrl->subnqn + off, 0, sizeof(ctrl->subnqn) - off);
1779 * Initialize the cached copies of the Identify data and various controller
1780 * register in our nvme_ctrl structure. This should be called as soon as
1781 * the admin queue is fully up and running.
1783 int nvme_init_identify(struct nvme_ctrl *ctrl)
1785 struct nvme_id_ctrl *id;
1787 int ret, page_shift;
1789 bool prev_apst_enabled;
1791 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1793 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1797 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1799 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1802 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1804 if (ctrl->vs >= NVME_VS(1, 1, 0))
1805 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1807 ret = nvme_identify_ctrl(ctrl, &id);
1809 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1813 nvme_init_subnqn(ctrl, id);
1815 if (!ctrl->identified) {
1817 * Check for quirks. Quirk can depend on firmware version,
1818 * so, in principle, the set of quirks present can change
1819 * across a reset. As a possible future enhancement, we
1820 * could re-scan for quirks every time we reinitialize
1821 * the device, but we'd have to make sure that the driver
1822 * behaves intelligently if the quirks change.
1827 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1828 if (quirk_matches(id, &core_quirks[i]))
1829 ctrl->quirks |= core_quirks[i].quirks;
1833 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1834 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1835 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1838 ctrl->oacs = le16_to_cpu(id->oacs);
1839 ctrl->vid = le16_to_cpu(id->vid);
1840 ctrl->oncs = le16_to_cpup(&id->oncs);
1841 atomic_set(&ctrl->abort_limit, id->acl + 1);
1842 ctrl->vwc = id->vwc;
1843 ctrl->cntlid = le16_to_cpup(&id->cntlid);
1844 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1845 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1846 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1848 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1850 max_hw_sectors = UINT_MAX;
1851 ctrl->max_hw_sectors =
1852 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1854 nvme_set_queue_limits(ctrl, ctrl->admin_q);
1855 ctrl->sgls = le32_to_cpu(id->sgls);
1856 ctrl->kas = le16_to_cpu(id->kas);
1860 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
1862 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
1863 shutdown_timeout, 60);
1865 if (ctrl->shutdown_timeout != shutdown_timeout)
1866 dev_warn(ctrl->device,
1867 "Shutdown timeout set to %u seconds\n",
1868 ctrl->shutdown_timeout);
1870 ctrl->shutdown_timeout = shutdown_timeout;
1872 ctrl->npss = id->npss;
1873 ctrl->apsta = id->apsta;
1874 prev_apst_enabled = ctrl->apst_enabled;
1875 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1876 if (force_apst && id->apsta) {
1877 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1878 ctrl->apst_enabled = true;
1880 ctrl->apst_enabled = false;
1883 ctrl->apst_enabled = id->apsta;
1885 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1887 if (ctrl->ops->flags & NVME_F_FABRICS) {
1888 ctrl->icdoff = le16_to_cpu(id->icdoff);
1889 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1890 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1891 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1894 * In fabrics we need to verify the cntlid matches the
1897 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
1902 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1903 dev_err(ctrl->device,
1904 "keep-alive support is mandatory for fabrics\n");
1909 ctrl->cntlid = le16_to_cpu(id->cntlid);
1910 ctrl->hmpre = le32_to_cpu(id->hmpre);
1911 ctrl->hmmin = le32_to_cpu(id->hmmin);
1912 ctrl->hmminds = le32_to_cpu(id->hmminds);
1913 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
1918 if (ctrl->apst_enabled && !prev_apst_enabled)
1919 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1920 else if (!ctrl->apst_enabled && prev_apst_enabled)
1921 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1923 ret = nvme_configure_apst(ctrl);
1927 ret = nvme_configure_timestamp(ctrl);
1931 ret = nvme_configure_directives(ctrl);
1935 ctrl->identified = true;
1943 EXPORT_SYMBOL_GPL(nvme_init_identify);
1945 static int nvme_dev_open(struct inode *inode, struct file *file)
1947 struct nvme_ctrl *ctrl;
1948 int instance = iminor(inode);
1951 spin_lock(&dev_list_lock);
1952 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1953 if (ctrl->instance != instance)
1956 if (!ctrl->admin_q) {
1960 if (!kref_get_unless_zero(&ctrl->kref))
1962 file->private_data = ctrl;
1966 spin_unlock(&dev_list_lock);
1971 static int nvme_dev_release(struct inode *inode, struct file *file)
1973 nvme_put_ctrl(file->private_data);
1977 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1982 mutex_lock(&ctrl->namespaces_mutex);
1983 if (list_empty(&ctrl->namespaces)) {
1988 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1989 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1990 dev_warn(ctrl->device,
1991 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1996 dev_warn(ctrl->device,
1997 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1998 kref_get(&ns->kref);
1999 mutex_unlock(&ctrl->namespaces_mutex);
2001 ret = nvme_user_cmd(ctrl, ns, argp);
2006 mutex_unlock(&ctrl->namespaces_mutex);
2010 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
2013 struct nvme_ctrl *ctrl = file->private_data;
2014 void __user *argp = (void __user *)arg;
2017 case NVME_IOCTL_ADMIN_CMD:
2018 return nvme_user_cmd(ctrl, NULL, argp);
2019 case NVME_IOCTL_IO_CMD:
2020 return nvme_dev_user_cmd(ctrl, argp);
2021 case NVME_IOCTL_RESET:
2022 dev_warn(ctrl->device, "resetting controller\n");
2023 return nvme_reset_ctrl_sync(ctrl);
2024 case NVME_IOCTL_SUBSYS_RESET:
2025 return nvme_reset_subsystem(ctrl);
2026 case NVME_IOCTL_RESCAN:
2027 nvme_queue_scan(ctrl);
2034 static const struct file_operations nvme_dev_fops = {
2035 .owner = THIS_MODULE,
2036 .open = nvme_dev_open,
2037 .release = nvme_dev_release,
2038 .unlocked_ioctl = nvme_dev_ioctl,
2039 .compat_ioctl = nvme_dev_ioctl,
2042 static ssize_t nvme_sysfs_reset(struct device *dev,
2043 struct device_attribute *attr, const char *buf,
2046 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2049 ret = nvme_reset_ctrl_sync(ctrl);
2054 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2056 static ssize_t nvme_sysfs_rescan(struct device *dev,
2057 struct device_attribute *attr, const char *buf,
2060 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2062 nvme_queue_scan(ctrl);
2065 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2067 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2070 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2071 struct nvme_ctrl *ctrl = ns->ctrl;
2072 int serial_len = sizeof(ctrl->serial);
2073 int model_len = sizeof(ctrl->model);
2075 if (!uuid_is_null(&ns->uuid))
2076 return sprintf(buf, "uuid.%pU\n", &ns->uuid);
2078 if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2079 return sprintf(buf, "eui.%16phN\n", ns->nguid);
2081 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2082 return sprintf(buf, "eui.%8phN\n", ns->eui);
2084 while (serial_len > 0 && (ctrl->serial[serial_len - 1] == ' ' ||
2085 ctrl->serial[serial_len - 1] == '\0'))
2087 while (model_len > 0 && (ctrl->model[model_len - 1] == ' ' ||
2088 ctrl->model[model_len - 1] == '\0'))
2091 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
2092 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
2094 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
2096 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2099 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2100 return sprintf(buf, "%pU\n", ns->nguid);
2102 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
2104 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2107 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2109 /* For backward compatibility expose the NGUID to userspace if
2110 * we have no UUID set
2112 if (uuid_is_null(&ns->uuid)) {
2113 printk_ratelimited(KERN_WARNING
2114 "No UUID available providing old NGUID\n");
2115 return sprintf(buf, "%pU\n", ns->nguid);
2117 return sprintf(buf, "%pU\n", &ns->uuid);
2119 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
2121 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2124 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2125 return sprintf(buf, "%8phd\n", ns->eui);
2127 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
2129 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2132 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2133 return sprintf(buf, "%d\n", ns->ns_id);
2135 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
2137 static struct attribute *nvme_ns_attrs[] = {
2138 &dev_attr_wwid.attr,
2139 &dev_attr_uuid.attr,
2140 &dev_attr_nguid.attr,
2142 &dev_attr_nsid.attr,
2146 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2147 struct attribute *a, int n)
2149 struct device *dev = container_of(kobj, struct device, kobj);
2150 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2152 if (a == &dev_attr_uuid.attr) {
2153 if (uuid_is_null(&ns->uuid) &&
2154 !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2157 if (a == &dev_attr_nguid.attr) {
2158 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2161 if (a == &dev_attr_eui.attr) {
2162 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2168 static const struct attribute_group nvme_ns_attr_group = {
2169 .attrs = nvme_ns_attrs,
2170 .is_visible = nvme_ns_attrs_are_visible,
2173 #define nvme_show_str_function(field) \
2174 static ssize_t field##_show(struct device *dev, \
2175 struct device_attribute *attr, char *buf) \
2177 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2178 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
2180 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2182 #define nvme_show_int_function(field) \
2183 static ssize_t field##_show(struct device *dev, \
2184 struct device_attribute *attr, char *buf) \
2186 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2187 return sprintf(buf, "%d\n", ctrl->field); \
2189 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2191 nvme_show_str_function(model);
2192 nvme_show_str_function(serial);
2193 nvme_show_str_function(firmware_rev);
2194 nvme_show_int_function(cntlid);
2196 static ssize_t nvme_sysfs_delete(struct device *dev,
2197 struct device_attribute *attr, const char *buf,
2200 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2202 if (device_remove_file_self(dev, attr))
2203 ctrl->ops->delete_ctrl(ctrl);
2206 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2208 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2209 struct device_attribute *attr,
2212 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2214 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2216 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2218 static ssize_t nvme_sysfs_show_state(struct device *dev,
2219 struct device_attribute *attr,
2222 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2223 static const char *const state_name[] = {
2224 [NVME_CTRL_NEW] = "new",
2225 [NVME_CTRL_LIVE] = "live",
2226 [NVME_CTRL_RESETTING] = "resetting",
2227 [NVME_CTRL_RECONNECTING]= "reconnecting",
2228 [NVME_CTRL_DELETING] = "deleting",
2229 [NVME_CTRL_DEAD] = "dead",
2232 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2233 state_name[ctrl->state])
2234 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2236 return sprintf(buf, "unknown state\n");
2239 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2241 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2242 struct device_attribute *attr,
2245 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2247 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subnqn);
2249 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2251 static ssize_t nvme_sysfs_show_address(struct device *dev,
2252 struct device_attribute *attr,
2255 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2257 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2259 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2261 static struct attribute *nvme_dev_attrs[] = {
2262 &dev_attr_reset_controller.attr,
2263 &dev_attr_rescan_controller.attr,
2264 &dev_attr_model.attr,
2265 &dev_attr_serial.attr,
2266 &dev_attr_firmware_rev.attr,
2267 &dev_attr_cntlid.attr,
2268 &dev_attr_delete_controller.attr,
2269 &dev_attr_transport.attr,
2270 &dev_attr_subsysnqn.attr,
2271 &dev_attr_address.attr,
2272 &dev_attr_state.attr,
2276 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2277 struct attribute *a, int n)
2279 struct device *dev = container_of(kobj, struct device, kobj);
2280 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2282 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2284 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2290 static struct attribute_group nvme_dev_attrs_group = {
2291 .attrs = nvme_dev_attrs,
2292 .is_visible = nvme_dev_attrs_are_visible,
2295 static const struct attribute_group *nvme_dev_attr_groups[] = {
2296 &nvme_dev_attrs_group,
2300 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2302 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2303 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2305 return nsa->ns_id - nsb->ns_id;
2308 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2310 struct nvme_ns *ns, *ret = NULL;
2312 mutex_lock(&ctrl->namespaces_mutex);
2313 list_for_each_entry(ns, &ctrl->namespaces, list) {
2314 if (ns->ns_id == nsid) {
2315 if (!kref_get_unless_zero(&ns->kref))
2320 if (ns->ns_id > nsid)
2323 mutex_unlock(&ctrl->namespaces_mutex);
2327 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2329 struct streams_directive_params s;
2332 if (!ctrl->nr_streams)
2335 ret = nvme_get_stream_params(ctrl, &s, ns->ns_id);
2339 ns->sws = le32_to_cpu(s.sws);
2340 ns->sgs = le16_to_cpu(s.sgs);
2343 unsigned int bs = 1 << ns->lba_shift;
2345 blk_queue_io_min(ns->queue, bs * ns->sws);
2347 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2353 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2356 struct gendisk *disk;
2357 struct nvme_id_ns *id;
2358 char disk_name[DISK_NAME_LEN];
2359 int node = dev_to_node(ctrl->dev);
2361 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2365 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2366 if (ns->instance < 0)
2369 ns->queue = blk_mq_init_queue(ctrl->tagset);
2370 if (IS_ERR(ns->queue))
2371 goto out_release_instance;
2372 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2373 ns->queue->queuedata = ns;
2376 kref_init(&ns->kref);
2378 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2380 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2381 nvme_set_queue_limits(ctrl, ns->queue);
2382 nvme_setup_streams_ns(ctrl, ns);
2384 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2386 id = nvme_identify_ns(ctrl, nsid);
2388 goto out_free_queue;
2393 nvme_report_ns_ids(ctrl, ns->ns_id, id, ns->eui, ns->nguid, &ns->uuid);
2395 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
2396 if (nvme_nvm_register(ns, disk_name, node)) {
2397 dev_warn(ctrl->device, "LightNVM init failure\n");
2402 disk = alloc_disk_node(0, node);
2406 disk->fops = &nvme_fops;
2407 disk->private_data = ns;
2408 disk->queue = ns->queue;
2409 disk->flags = GENHD_FL_EXT_DEVT;
2410 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2413 __nvme_revalidate_disk(disk, id);
2415 mutex_lock(&ctrl->namespaces_mutex);
2416 list_add_tail(&ns->list, &ctrl->namespaces);
2417 mutex_unlock(&ctrl->namespaces_mutex);
2419 kref_get(&ctrl->kref);
2423 device_add_disk(ctrl->device, ns->disk);
2424 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2425 &nvme_ns_attr_group))
2426 pr_warn("%s: failed to create sysfs group for identification\n",
2427 ns->disk->disk_name);
2428 if (ns->ndev && nvme_nvm_register_sysfs(ns))
2429 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2430 ns->disk->disk_name);
2435 blk_cleanup_queue(ns->queue);
2436 out_release_instance:
2437 ida_simple_remove(&ctrl->ns_ida, ns->instance);
2442 static void nvme_ns_remove(struct nvme_ns *ns)
2444 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2447 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2448 if (blk_get_integrity(ns->disk))
2449 blk_integrity_unregister(ns->disk);
2450 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2451 &nvme_ns_attr_group);
2453 nvme_nvm_unregister_sysfs(ns);
2454 del_gendisk(ns->disk);
2455 blk_cleanup_queue(ns->queue);
2458 mutex_lock(&ns->ctrl->namespaces_mutex);
2459 list_del_init(&ns->list);
2460 mutex_unlock(&ns->ctrl->namespaces_mutex);
2465 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2469 ns = nvme_find_get_ns(ctrl, nsid);
2471 if (ns->disk && revalidate_disk(ns->disk))
2475 nvme_alloc_ns(ctrl, nsid);
2478 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2481 struct nvme_ns *ns, *next;
2483 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2484 if (ns->ns_id > nsid)
2489 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2493 unsigned i, j, nsid, prev = 0;
2494 unsigned num_lists = DIV_ROUND_UP_ULL((u64)nn, 1024);
2497 ns_list = kzalloc(0x1000, GFP_KERNEL);
2501 for (i = 0; i < num_lists; i++) {
2502 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2506 for (j = 0; j < min(nn, 1024U); j++) {
2507 nsid = le32_to_cpu(ns_list[j]);
2511 nvme_validate_ns(ctrl, nsid);
2513 while (++prev < nsid) {
2514 ns = nvme_find_get_ns(ctrl, prev);
2524 nvme_remove_invalid_namespaces(ctrl, prev);
2530 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2534 for (i = 1; i <= nn; i++)
2535 nvme_validate_ns(ctrl, i);
2537 nvme_remove_invalid_namespaces(ctrl, nn);
2540 static void nvme_scan_work(struct work_struct *work)
2542 struct nvme_ctrl *ctrl =
2543 container_of(work, struct nvme_ctrl, scan_work);
2544 struct nvme_id_ctrl *id;
2547 if (ctrl->state != NVME_CTRL_LIVE)
2550 if (nvme_identify_ctrl(ctrl, &id))
2553 nn = le32_to_cpu(id->nn);
2554 if (!nvme_ctrl_limited_cns(ctrl)) {
2555 if (!nvme_scan_ns_list(ctrl, nn))
2558 nvme_scan_ns_sequential(ctrl, nn);
2560 mutex_lock(&ctrl->namespaces_mutex);
2561 list_sort(NULL, &ctrl->namespaces, ns_cmp);
2562 mutex_unlock(&ctrl->namespaces_mutex);
2566 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2569 * Do not queue new scan work when a controller is reset during
2572 if (ctrl->state == NVME_CTRL_LIVE)
2573 queue_work(nvme_wq, &ctrl->scan_work);
2575 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2578 * This function iterates the namespace list unlocked to allow recovery from
2579 * controller failure. It is up to the caller to ensure the namespace list is
2580 * not modified by scan work while this function is executing.
2582 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2584 struct nvme_ns *ns, *next;
2586 /* prevent racing with ns scanning */
2587 flush_work(&ctrl->scan_work);
2590 * The dead states indicates the controller was not gracefully
2591 * disconnected. In that case, we won't be able to flush any data while
2592 * removing the namespaces' disks; fail all the queues now to avoid
2593 * potentially having to clean up the failed sync later.
2595 if (ctrl->state == NVME_CTRL_DEAD)
2596 nvme_kill_queues(ctrl);
2598 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2601 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2603 static void nvme_async_event_work(struct work_struct *work)
2605 struct nvme_ctrl *ctrl =
2606 container_of(work, struct nvme_ctrl, async_event_work);
2608 spin_lock_irq(&ctrl->lock);
2609 while (ctrl->state == NVME_CTRL_LIVE && ctrl->event_limit > 0) {
2610 int aer_idx = --ctrl->event_limit;
2612 spin_unlock_irq(&ctrl->lock);
2613 ctrl->ops->submit_async_event(ctrl, aer_idx);
2614 spin_lock_irq(&ctrl->lock);
2616 spin_unlock_irq(&ctrl->lock);
2619 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
2624 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
2630 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
2633 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
2635 struct nvme_command c = { };
2636 struct nvme_fw_slot_info_log *log;
2638 log = kmalloc(sizeof(*log), GFP_KERNEL);
2642 c.common.opcode = nvme_admin_get_log_page;
2643 c.common.nsid = cpu_to_le32(NVME_NSID_ALL);
2644 c.common.cdw10[0] = nvme_get_log_dw10(NVME_LOG_FW_SLOT, sizeof(*log));
2646 if (!nvme_submit_sync_cmd(ctrl->admin_q, &c, log, sizeof(*log)))
2647 dev_warn(ctrl->device,
2648 "Get FW SLOT INFO log error\n");
2652 static void nvme_fw_act_work(struct work_struct *work)
2654 struct nvme_ctrl *ctrl = container_of(work,
2655 struct nvme_ctrl, fw_act_work);
2656 unsigned long fw_act_timeout;
2659 fw_act_timeout = jiffies +
2660 msecs_to_jiffies(ctrl->mtfa * 100);
2662 fw_act_timeout = jiffies +
2663 msecs_to_jiffies(admin_timeout * 1000);
2665 nvme_stop_queues(ctrl);
2666 while (nvme_ctrl_pp_status(ctrl)) {
2667 if (time_after(jiffies, fw_act_timeout)) {
2668 dev_warn(ctrl->device,
2669 "Fw activation timeout, reset controller\n");
2670 nvme_reset_ctrl(ctrl);
2676 if (ctrl->state != NVME_CTRL_LIVE)
2679 nvme_start_queues(ctrl);
2680 /* read FW slot informationi to clear the AER*/
2681 nvme_get_fw_slot_info(ctrl);
2684 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2685 union nvme_result *res)
2687 u32 result = le32_to_cpu(res->u32);
2690 switch (le16_to_cpu(status) >> 1) {
2691 case NVME_SC_SUCCESS:
2694 case NVME_SC_ABORT_REQ:
2695 ++ctrl->event_limit;
2696 if (ctrl->state == NVME_CTRL_LIVE)
2697 queue_work(nvme_wq, &ctrl->async_event_work);
2706 switch (result & 0xff07) {
2707 case NVME_AER_NOTICE_NS_CHANGED:
2708 dev_info(ctrl->device, "rescanning\n");
2709 nvme_queue_scan(ctrl);
2711 case NVME_AER_NOTICE_FW_ACT_STARTING:
2712 queue_work(nvme_wq, &ctrl->fw_act_work);
2715 dev_warn(ctrl->device, "async event result %08x\n", result);
2718 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2720 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2722 ctrl->event_limit = NVME_NR_AERS;
2723 queue_work(nvme_wq, &ctrl->async_event_work);
2725 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2727 static DEFINE_IDA(nvme_instance_ida);
2729 static int nvme_set_instance(struct nvme_ctrl *ctrl)
2731 int instance, error;
2734 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2737 spin_lock(&dev_list_lock);
2738 error = ida_get_new(&nvme_instance_ida, &instance);
2739 spin_unlock(&dev_list_lock);
2740 } while (error == -EAGAIN);
2745 ctrl->instance = instance;
2749 static void nvme_release_instance(struct nvme_ctrl *ctrl)
2751 spin_lock(&dev_list_lock);
2752 ida_remove(&nvme_instance_ida, ctrl->instance);
2753 spin_unlock(&dev_list_lock);
2756 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
2758 nvme_stop_keep_alive(ctrl);
2759 flush_work(&ctrl->async_event_work);
2760 cancel_work_sync(&ctrl->fw_act_work);
2762 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
2764 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
2767 nvme_start_keep_alive(ctrl);
2769 if (ctrl->queue_count > 1) {
2770 nvme_queue_scan(ctrl);
2771 nvme_queue_async_events(ctrl);
2772 nvme_start_queues(ctrl);
2775 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
2777 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2779 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
2781 spin_lock(&dev_list_lock);
2782 list_del(&ctrl->node);
2783 spin_unlock(&dev_list_lock);
2785 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2787 static void nvme_free_ctrl(struct kref *kref)
2789 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
2791 put_device(ctrl->device);
2792 nvme_release_instance(ctrl);
2793 ida_destroy(&ctrl->ns_ida);
2795 ctrl->ops->free_ctrl(ctrl);
2798 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2800 kref_put(&ctrl->kref, nvme_free_ctrl);
2802 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
2805 * Initialize a NVMe controller structures. This needs to be called during
2806 * earliest initialization so that we have the initialized structured around
2809 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2810 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2814 ctrl->state = NVME_CTRL_NEW;
2815 spin_lock_init(&ctrl->lock);
2816 INIT_LIST_HEAD(&ctrl->namespaces);
2817 mutex_init(&ctrl->namespaces_mutex);
2818 kref_init(&ctrl->kref);
2821 ctrl->quirks = quirks;
2822 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2823 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2824 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
2826 ret = nvme_set_instance(ctrl);
2830 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2831 MKDEV(nvme_char_major, ctrl->instance),
2832 ctrl, nvme_dev_attr_groups,
2833 "nvme%d", ctrl->instance);
2834 if (IS_ERR(ctrl->device)) {
2835 ret = PTR_ERR(ctrl->device);
2836 goto out_release_instance;
2838 get_device(ctrl->device);
2839 ida_init(&ctrl->ns_ida);
2841 spin_lock(&dev_list_lock);
2842 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2843 spin_unlock(&dev_list_lock);
2846 * Initialize latency tolerance controls. The sysfs files won't
2847 * be visible to userspace unless the device actually supports APST.
2849 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2850 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2851 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2854 out_release_instance:
2855 nvme_release_instance(ctrl);
2859 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2862 * nvme_kill_queues(): Ends all namespace queues
2863 * @ctrl: the dead controller that needs to end
2865 * Call this function when the driver determines it is unable to get the
2866 * controller in a state capable of servicing IO.
2868 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2872 mutex_lock(&ctrl->namespaces_mutex);
2874 /* Forcibly unquiesce queues to avoid blocking dispatch */
2876 blk_mq_unquiesce_queue(ctrl->admin_q);
2878 list_for_each_entry(ns, &ctrl->namespaces, list) {
2880 * Revalidating a dead namespace sets capacity to 0. This will
2881 * end buffered writers dirtying pages that can't be synced.
2883 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2885 revalidate_disk(ns->disk);
2886 blk_set_queue_dying(ns->queue);
2888 /* Forcibly unquiesce queues to avoid blocking dispatch */
2889 blk_mq_unquiesce_queue(ns->queue);
2891 mutex_unlock(&ctrl->namespaces_mutex);
2893 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2895 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2899 mutex_lock(&ctrl->namespaces_mutex);
2900 list_for_each_entry(ns, &ctrl->namespaces, list)
2901 blk_mq_unfreeze_queue(ns->queue);
2902 mutex_unlock(&ctrl->namespaces_mutex);
2904 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2906 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2910 mutex_lock(&ctrl->namespaces_mutex);
2911 list_for_each_entry(ns, &ctrl->namespaces, list) {
2912 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2916 mutex_unlock(&ctrl->namespaces_mutex);
2918 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2920 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2924 mutex_lock(&ctrl->namespaces_mutex);
2925 list_for_each_entry(ns, &ctrl->namespaces, list)
2926 blk_mq_freeze_queue_wait(ns->queue);
2927 mutex_unlock(&ctrl->namespaces_mutex);
2929 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2931 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2935 mutex_lock(&ctrl->namespaces_mutex);
2936 list_for_each_entry(ns, &ctrl->namespaces, list)
2937 blk_freeze_queue_start(ns->queue);
2938 mutex_unlock(&ctrl->namespaces_mutex);
2940 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2942 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2946 mutex_lock(&ctrl->namespaces_mutex);
2947 list_for_each_entry(ns, &ctrl->namespaces, list)
2948 blk_mq_quiesce_queue(ns->queue);
2949 mutex_unlock(&ctrl->namespaces_mutex);
2951 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2953 void nvme_start_queues(struct nvme_ctrl *ctrl)
2957 mutex_lock(&ctrl->namespaces_mutex);
2958 list_for_each_entry(ns, &ctrl->namespaces, list)
2959 blk_mq_unquiesce_queue(ns->queue);
2960 mutex_unlock(&ctrl->namespaces_mutex);
2962 EXPORT_SYMBOL_GPL(nvme_start_queues);
2964 int __init nvme_core_init(void)
2968 nvme_wq = alloc_workqueue("nvme-wq",
2969 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2973 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2977 else if (result > 0)
2978 nvme_char_major = result;
2980 nvme_class = class_create(THIS_MODULE, "nvme");
2981 if (IS_ERR(nvme_class)) {
2982 result = PTR_ERR(nvme_class);
2983 goto unregister_chrdev;
2989 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2991 destroy_workqueue(nvme_wq);
2995 void nvme_core_exit(void)
2997 class_destroy(nvme_class);
2998 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2999 destroy_workqueue(nvme_wq);
3002 MODULE_LICENSE("GPL");
3003 MODULE_VERSION("1.0");
3004 module_init(nvme_core_init);
3005 module_exit(nvme_core_exit);