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);
103 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
105 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
107 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
111 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
113 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
117 ret = nvme_reset_ctrl(ctrl);
119 flush_work(&ctrl->reset_work);
120 if (ctrl->state != NVME_CTRL_LIVE)
126 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync);
128 static void nvme_delete_ctrl_work(struct work_struct *work)
130 struct nvme_ctrl *ctrl =
131 container_of(work, struct nvme_ctrl, delete_work);
133 dev_info(ctrl->device,
134 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
136 flush_work(&ctrl->reset_work);
137 nvme_stop_ctrl(ctrl);
138 nvme_remove_namespaces(ctrl);
139 ctrl->ops->delete_ctrl(ctrl);
140 nvme_uninit_ctrl(ctrl);
144 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
146 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
148 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
152 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
154 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
159 * Keep a reference until the work is flushed since ->delete_ctrl
160 * can free the controller.
163 ret = nvme_delete_ctrl(ctrl);
165 flush_work(&ctrl->delete_work);
169 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
171 static inline bool nvme_ns_has_pi(struct nvme_ns *ns)
173 return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple);
176 static blk_status_t nvme_error_status(struct request *req)
178 switch (nvme_req(req)->status & 0x7ff) {
179 case NVME_SC_SUCCESS:
181 case NVME_SC_CAP_EXCEEDED:
182 return BLK_STS_NOSPC;
183 case NVME_SC_LBA_RANGE:
184 return BLK_STS_TARGET;
185 case NVME_SC_BAD_ATTRIBUTES:
186 case NVME_SC_ONCS_NOT_SUPPORTED:
187 case NVME_SC_INVALID_OPCODE:
188 case NVME_SC_INVALID_FIELD:
189 case NVME_SC_INVALID_NS:
190 return BLK_STS_NOTSUPP;
191 case NVME_SC_WRITE_FAULT:
192 case NVME_SC_READ_ERROR:
193 case NVME_SC_UNWRITTEN_BLOCK:
194 case NVME_SC_ACCESS_DENIED:
195 case NVME_SC_READ_ONLY:
196 case NVME_SC_COMPARE_FAILED:
197 return BLK_STS_MEDIUM;
198 case NVME_SC_GUARD_CHECK:
199 case NVME_SC_APPTAG_CHECK:
200 case NVME_SC_REFTAG_CHECK:
201 case NVME_SC_INVALID_PI:
202 return BLK_STS_PROTECTION;
203 case NVME_SC_RESERVATION_CONFLICT:
204 return BLK_STS_NEXUS;
206 return BLK_STS_IOERR;
210 static inline bool nvme_req_needs_retry(struct request *req)
212 if (blk_noretry_request(req))
214 if (nvme_req(req)->status & NVME_SC_DNR)
216 if (nvme_req(req)->retries >= nvme_max_retries)
221 void nvme_complete_rq(struct request *req)
223 blk_status_t status = nvme_error_status(req);
225 trace_nvme_complete_rq(req);
227 if (unlikely(status != BLK_STS_OK && nvme_req_needs_retry(req))) {
228 if (nvme_req_needs_failover(req, status)) {
229 nvme_failover_req(req);
233 if (!blk_queue_dying(req->q)) {
234 nvme_req(req)->retries++;
235 blk_mq_requeue_request(req, true);
239 blk_mq_end_request(req, status);
241 EXPORT_SYMBOL_GPL(nvme_complete_rq);
243 void nvme_cancel_request(struct request *req, void *data, bool reserved)
245 if (!blk_mq_request_started(req))
248 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
249 "Cancelling I/O %d", req->tag);
251 nvme_req(req)->status = NVME_SC_ABORT_REQ;
252 blk_mq_complete_request(req);
255 EXPORT_SYMBOL_GPL(nvme_cancel_request);
257 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
258 enum nvme_ctrl_state new_state)
260 enum nvme_ctrl_state old_state;
262 bool changed = false;
264 spin_lock_irqsave(&ctrl->lock, flags);
266 old_state = ctrl->state;
268 case NVME_CTRL_ADMIN_ONLY:
270 case NVME_CTRL_CONNECTING:
280 case NVME_CTRL_RESETTING:
281 case NVME_CTRL_CONNECTING:
288 case NVME_CTRL_RESETTING:
292 case NVME_CTRL_ADMIN_ONLY:
299 case NVME_CTRL_CONNECTING:
302 case NVME_CTRL_RESETTING:
309 case NVME_CTRL_DELETING:
312 case NVME_CTRL_ADMIN_ONLY:
313 case NVME_CTRL_RESETTING:
314 case NVME_CTRL_CONNECTING:
323 case NVME_CTRL_DELETING:
335 ctrl->state = new_state;
337 spin_unlock_irqrestore(&ctrl->lock, flags);
338 if (changed && ctrl->state == NVME_CTRL_LIVE)
339 nvme_kick_requeue_lists(ctrl);
342 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
344 static void nvme_free_ns_head(struct kref *ref)
346 struct nvme_ns_head *head =
347 container_of(ref, struct nvme_ns_head, ref);
349 nvme_mpath_remove_disk(head);
350 ida_simple_remove(&head->subsys->ns_ida, head->instance);
351 list_del_init(&head->entry);
352 cleanup_srcu_struct(&head->srcu);
356 static void nvme_put_ns_head(struct nvme_ns_head *head)
358 kref_put(&head->ref, nvme_free_ns_head);
361 static void nvme_free_ns(struct kref *kref)
363 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
366 nvme_nvm_unregister(ns);
369 nvme_put_ns_head(ns->head);
370 nvme_put_ctrl(ns->ctrl);
374 static void nvme_put_ns(struct nvme_ns *ns)
376 kref_put(&ns->kref, nvme_free_ns);
379 static inline void nvme_clear_nvme_request(struct request *req)
381 if (!(req->rq_flags & RQF_DONTPREP)) {
382 nvme_req(req)->retries = 0;
383 nvme_req(req)->flags = 0;
384 req->rq_flags |= RQF_DONTPREP;
388 struct request *nvme_alloc_request(struct request_queue *q,
389 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
391 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
394 if (qid == NVME_QID_ANY) {
395 req = blk_mq_alloc_request(q, op, flags);
397 req = blk_mq_alloc_request_hctx(q, op, flags,
403 req->cmd_flags |= REQ_FAILFAST_DRIVER;
404 nvme_clear_nvme_request(req);
405 nvme_req(req)->cmd = cmd;
409 EXPORT_SYMBOL_GPL(nvme_alloc_request);
411 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
413 struct nvme_command c;
415 memset(&c, 0, sizeof(c));
417 c.directive.opcode = nvme_admin_directive_send;
418 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
419 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
420 c.directive.dtype = NVME_DIR_IDENTIFY;
421 c.directive.tdtype = NVME_DIR_STREAMS;
422 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
424 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
427 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
429 return nvme_toggle_streams(ctrl, false);
432 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
434 return nvme_toggle_streams(ctrl, true);
437 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
438 struct streams_directive_params *s, u32 nsid)
440 struct nvme_command c;
442 memset(&c, 0, sizeof(c));
443 memset(s, 0, sizeof(*s));
445 c.directive.opcode = nvme_admin_directive_recv;
446 c.directive.nsid = cpu_to_le32(nsid);
447 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
448 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
449 c.directive.dtype = NVME_DIR_STREAMS;
451 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
454 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
456 struct streams_directive_params s;
459 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
464 ret = nvme_enable_streams(ctrl);
468 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
472 ctrl->nssa = le16_to_cpu(s.nssa);
473 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
474 dev_info(ctrl->device, "too few streams (%u) available\n",
476 nvme_disable_streams(ctrl);
480 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
481 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
486 * Check if 'req' has a write hint associated with it. If it does, assign
487 * a valid namespace stream to the write.
489 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
490 struct request *req, u16 *control,
493 enum rw_hint streamid = req->write_hint;
495 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
499 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
502 *control |= NVME_RW_DTYPE_STREAMS;
503 *dsmgmt |= streamid << 16;
506 if (streamid < ARRAY_SIZE(req->q->write_hints))
507 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
510 static inline void nvme_setup_flush(struct nvme_ns *ns,
511 struct nvme_command *cmnd)
513 memset(cmnd, 0, sizeof(*cmnd));
514 cmnd->common.opcode = nvme_cmd_flush;
515 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
518 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
519 struct nvme_command *cmnd)
521 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
522 struct nvme_dsm_range *range;
525 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
527 return BLK_STS_RESOURCE;
529 __rq_for_each_bio(bio, req) {
530 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
531 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
534 range[n].cattr = cpu_to_le32(0);
535 range[n].nlb = cpu_to_le32(nlb);
536 range[n].slba = cpu_to_le64(slba);
541 if (WARN_ON_ONCE(n != segments)) {
543 return BLK_STS_IOERR;
546 memset(cmnd, 0, sizeof(*cmnd));
547 cmnd->dsm.opcode = nvme_cmd_dsm;
548 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
549 cmnd->dsm.nr = cpu_to_le32(segments - 1);
550 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
552 req->special_vec.bv_page = virt_to_page(range);
553 req->special_vec.bv_offset = offset_in_page(range);
554 req->special_vec.bv_len = sizeof(*range) * segments;
555 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
560 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
561 struct request *req, struct nvme_command *cmnd)
563 struct nvme_ctrl *ctrl = ns->ctrl;
567 if (req->cmd_flags & REQ_FUA)
568 control |= NVME_RW_FUA;
569 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
570 control |= NVME_RW_LR;
572 if (req->cmd_flags & REQ_RAHEAD)
573 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
575 memset(cmnd, 0, sizeof(*cmnd));
576 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
577 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
578 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
579 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
581 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
582 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
586 * If formated with metadata, the block layer always provides a
587 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
588 * we enable the PRACT bit for protection information or set the
589 * namespace capacity to zero to prevent any I/O.
591 if (!blk_integrity_rq(req)) {
592 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
593 return BLK_STS_NOTSUPP;
594 control |= NVME_RW_PRINFO_PRACT;
597 switch (ns->pi_type) {
598 case NVME_NS_DPS_PI_TYPE3:
599 control |= NVME_RW_PRINFO_PRCHK_GUARD;
601 case NVME_NS_DPS_PI_TYPE1:
602 case NVME_NS_DPS_PI_TYPE2:
603 control |= NVME_RW_PRINFO_PRCHK_GUARD |
604 NVME_RW_PRINFO_PRCHK_REF;
605 cmnd->rw.reftag = cpu_to_le32(
606 nvme_block_nr(ns, blk_rq_pos(req)));
611 cmnd->rw.control = cpu_to_le16(control);
612 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
616 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
617 struct nvme_command *cmd)
619 blk_status_t ret = BLK_STS_OK;
621 nvme_clear_nvme_request(req);
623 switch (req_op(req)) {
626 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
629 nvme_setup_flush(ns, cmd);
631 case REQ_OP_WRITE_ZEROES:
632 /* currently only aliased to deallocate for a few ctrls: */
634 ret = nvme_setup_discard(ns, req, cmd);
638 ret = nvme_setup_rw(ns, req, cmd);
642 return BLK_STS_IOERR;
645 cmd->common.command_id = req->tag;
647 trace_nvme_setup_nvm_cmd(req->q->id, cmd);
649 trace_nvme_setup_admin_cmd(cmd);
652 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
655 * Returns 0 on success. If the result is negative, it's a Linux error code;
656 * if the result is positive, it's an NVM Express status code
658 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
659 union nvme_result *result, void *buffer, unsigned bufflen,
660 unsigned timeout, int qid, int at_head,
661 blk_mq_req_flags_t flags)
666 req = nvme_alloc_request(q, cmd, flags, qid);
670 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
672 if (buffer && bufflen) {
673 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
678 blk_execute_rq(req->q, NULL, req, at_head);
680 *result = nvme_req(req)->result;
681 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
684 ret = nvme_req(req)->status;
686 blk_mq_free_request(req);
689 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
691 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
692 void *buffer, unsigned bufflen)
694 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
697 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
699 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
700 unsigned len, u32 seed, bool write)
702 struct bio_integrity_payload *bip;
706 buf = kmalloc(len, GFP_KERNEL);
711 if (write && copy_from_user(buf, ubuf, len))
714 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
720 bip->bip_iter.bi_size = len;
721 bip->bip_iter.bi_sector = seed;
722 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
723 offset_in_page(buf));
733 static int nvme_submit_user_cmd(struct request_queue *q,
734 struct nvme_command *cmd, void __user *ubuffer,
735 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
736 u32 meta_seed, u32 *result, unsigned timeout)
738 bool write = nvme_is_write(cmd);
739 struct nvme_ns *ns = q->queuedata;
740 struct gendisk *disk = ns ? ns->disk : NULL;
742 struct bio *bio = NULL;
746 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
750 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
751 nvme_req(req)->flags |= NVME_REQ_USERCMD;
753 if (ubuffer && bufflen) {
754 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
760 if (disk && meta_buffer && meta_len) {
761 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
767 req->cmd_flags |= REQ_INTEGRITY;
771 blk_execute_rq(req->q, disk, req, 0);
772 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
775 ret = nvme_req(req)->status;
777 *result = le32_to_cpu(nvme_req(req)->result.u32);
778 if (meta && !ret && !write) {
779 if (copy_to_user(meta_buffer, meta, meta_len))
785 blk_rq_unmap_user(bio);
787 blk_mq_free_request(req);
791 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
793 struct nvme_ctrl *ctrl = rq->end_io_data;
795 blk_mq_free_request(rq);
798 dev_err(ctrl->device,
799 "failed nvme_keep_alive_end_io error=%d\n",
804 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
807 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
811 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
816 rq->timeout = ctrl->kato * HZ;
817 rq->end_io_data = ctrl;
819 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
824 static void nvme_keep_alive_work(struct work_struct *work)
826 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
827 struct nvme_ctrl, ka_work);
829 if (nvme_keep_alive(ctrl)) {
830 /* allocation failure, reset the controller */
831 dev_err(ctrl->device, "keep-alive failed\n");
832 nvme_reset_ctrl(ctrl);
837 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
839 if (unlikely(ctrl->kato == 0))
842 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
843 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
844 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
845 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
848 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
850 if (unlikely(ctrl->kato == 0))
853 cancel_delayed_work_sync(&ctrl->ka_work);
855 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
857 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
859 struct nvme_command c = { };
862 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
863 c.identify.opcode = nvme_admin_identify;
864 c.identify.cns = NVME_ID_CNS_CTRL;
866 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
870 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
871 sizeof(struct nvme_id_ctrl));
877 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
878 struct nvme_ns_ids *ids)
880 struct nvme_command c = { };
886 c.identify.opcode = nvme_admin_identify;
887 c.identify.nsid = cpu_to_le32(nsid);
888 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
890 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
894 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
895 NVME_IDENTIFY_DATA_SIZE);
899 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
900 struct nvme_ns_id_desc *cur = data + pos;
906 case NVME_NIDT_EUI64:
907 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
908 dev_warn(ctrl->device,
909 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
913 len = NVME_NIDT_EUI64_LEN;
914 memcpy(ids->eui64, data + pos + sizeof(*cur), len);
916 case NVME_NIDT_NGUID:
917 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
918 dev_warn(ctrl->device,
919 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
923 len = NVME_NIDT_NGUID_LEN;
924 memcpy(ids->nguid, data + pos + sizeof(*cur), len);
927 if (cur->nidl != NVME_NIDT_UUID_LEN) {
928 dev_warn(ctrl->device,
929 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
933 len = NVME_NIDT_UUID_LEN;
934 uuid_copy(&ids->uuid, data + pos + sizeof(*cur));
937 /* Skip unnkown types */
949 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
951 struct nvme_command c = { };
953 c.identify.opcode = nvme_admin_identify;
954 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
955 c.identify.nsid = cpu_to_le32(nsid);
956 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
957 NVME_IDENTIFY_DATA_SIZE);
960 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
963 struct nvme_id_ns *id;
964 struct nvme_command c = { };
967 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
968 c.identify.opcode = nvme_admin_identify;
969 c.identify.nsid = cpu_to_le32(nsid);
970 c.identify.cns = NVME_ID_CNS_NS;
972 id = kmalloc(sizeof(*id), GFP_KERNEL);
976 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
978 dev_warn(ctrl->device, "Identify namespace failed\n");
986 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
987 void *buffer, size_t buflen, u32 *result)
989 struct nvme_command c;
990 union nvme_result res;
993 memset(&c, 0, sizeof(c));
994 c.features.opcode = nvme_admin_set_features;
995 c.features.fid = cpu_to_le32(fid);
996 c.features.dword11 = cpu_to_le32(dword11);
998 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
999 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
1000 if (ret >= 0 && result)
1001 *result = le32_to_cpu(res.u32);
1005 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1007 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1009 int status, nr_io_queues;
1011 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1017 * Degraded controllers might return an error when setting the queue
1018 * count. We still want to be able to bring them online and offer
1019 * access to the admin queue, as that might be only way to fix them up.
1022 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1025 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1026 *count = min(*count, nr_io_queues);
1031 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1033 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1035 struct nvme_user_io io;
1036 struct nvme_command c;
1037 unsigned length, meta_len;
1038 void __user *metadata;
1040 if (copy_from_user(&io, uio, sizeof(io)))
1045 switch (io.opcode) {
1046 case nvme_cmd_write:
1048 case nvme_cmd_compare:
1054 length = (io.nblocks + 1) << ns->lba_shift;
1055 meta_len = (io.nblocks + 1) * ns->ms;
1056 metadata = (void __user *)(uintptr_t)io.metadata;
1061 } else if (meta_len) {
1062 if ((io.metadata & 3) || !io.metadata)
1066 memset(&c, 0, sizeof(c));
1067 c.rw.opcode = io.opcode;
1068 c.rw.flags = io.flags;
1069 c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1070 c.rw.slba = cpu_to_le64(io.slba);
1071 c.rw.length = cpu_to_le16(io.nblocks);
1072 c.rw.control = cpu_to_le16(io.control);
1073 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1074 c.rw.reftag = cpu_to_le32(io.reftag);
1075 c.rw.apptag = cpu_to_le16(io.apptag);
1076 c.rw.appmask = cpu_to_le16(io.appmask);
1078 return nvme_submit_user_cmd(ns->queue, &c,
1079 (void __user *)(uintptr_t)io.addr, length,
1080 metadata, meta_len, io.slba, NULL, 0);
1083 static u32 nvme_known_admin_effects(u8 opcode)
1086 case nvme_admin_format_nvm:
1087 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
1088 NVME_CMD_EFFECTS_CSE_MASK;
1089 case nvme_admin_sanitize_nvm:
1090 return NVME_CMD_EFFECTS_CSE_MASK;
1097 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1104 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1105 if (effects & ~NVME_CMD_EFFECTS_CSUPP)
1106 dev_warn(ctrl->device,
1107 "IO command:%02x has unhandled effects:%08x\n",
1113 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1115 effects = nvme_known_admin_effects(opcode);
1118 * For simplicity, IO to all namespaces is quiesced even if the command
1119 * effects say only one namespace is affected.
1121 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1122 nvme_start_freeze(ctrl);
1123 nvme_wait_freeze(ctrl);
1128 static void nvme_update_formats(struct nvme_ctrl *ctrl)
1130 struct nvme_ns *ns, *next;
1133 down_write(&ctrl->namespaces_rwsem);
1134 list_for_each_entry(ns, &ctrl->namespaces, list) {
1135 if (ns->disk && nvme_revalidate_disk(ns->disk)) {
1136 list_move_tail(&ns->list, &rm_list);
1139 up_write(&ctrl->namespaces_rwsem);
1141 list_for_each_entry_safe(ns, next, &rm_list, list)
1145 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1148 * Revalidate LBA changes prior to unfreezing. This is necessary to
1149 * prevent memory corruption if a logical block size was changed by
1152 if (effects & NVME_CMD_EFFECTS_LBCC)
1153 nvme_update_formats(ctrl);
1154 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK))
1155 nvme_unfreeze(ctrl);
1156 if (effects & NVME_CMD_EFFECTS_CCC)
1157 nvme_init_identify(ctrl);
1158 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC))
1159 nvme_queue_scan(ctrl);
1162 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1163 struct nvme_passthru_cmd __user *ucmd)
1165 struct nvme_passthru_cmd cmd;
1166 struct nvme_command c;
1167 unsigned timeout = 0;
1171 if (!capable(CAP_SYS_ADMIN))
1173 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1178 memset(&c, 0, sizeof(c));
1179 c.common.opcode = cmd.opcode;
1180 c.common.flags = cmd.flags;
1181 c.common.nsid = cpu_to_le32(cmd.nsid);
1182 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1183 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1184 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1185 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1186 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1187 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1188 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1189 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1192 timeout = msecs_to_jiffies(cmd.timeout_ms);
1194 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1195 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1196 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1197 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1198 0, &cmd.result, timeout);
1199 nvme_passthru_end(ctrl, effects);
1202 if (put_user(cmd.result, &ucmd->result))
1210 * Issue ioctl requests on the first available path. Note that unlike normal
1211 * block layer requests we will not retry failed request on another controller.
1213 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1214 struct nvme_ns_head **head, int *srcu_idx)
1216 #ifdef CONFIG_NVME_MULTIPATH
1217 if (disk->fops == &nvme_ns_head_ops) {
1218 *head = disk->private_data;
1219 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1220 return nvme_find_path(*head);
1225 return disk->private_data;
1228 static void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1231 srcu_read_unlock(&head->srcu, idx);
1234 static int nvme_ns_ioctl(struct nvme_ns *ns, unsigned cmd, unsigned long arg)
1238 force_successful_syscall_return();
1239 return ns->head->ns_id;
1240 case NVME_IOCTL_ADMIN_CMD:
1241 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1242 case NVME_IOCTL_IO_CMD:
1243 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1244 case NVME_IOCTL_SUBMIT_IO:
1245 return nvme_submit_io(ns, (void __user *)arg);
1249 return nvme_nvm_ioctl(ns, cmd, arg);
1251 if (is_sed_ioctl(cmd))
1252 return sed_ioctl(ns->ctrl->opal_dev, cmd,
1253 (void __user *) arg);
1258 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1259 unsigned int cmd, unsigned long arg)
1261 struct nvme_ns_head *head = NULL;
1265 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1269 ret = nvme_ns_ioctl(ns, cmd, arg);
1270 nvme_put_ns_from_disk(head, srcu_idx);
1274 static int nvme_open(struct block_device *bdev, fmode_t mode)
1276 struct nvme_ns *ns = bdev->bd_disk->private_data;
1278 #ifdef CONFIG_NVME_MULTIPATH
1279 /* should never be called due to GENHD_FL_HIDDEN */
1280 if (WARN_ON_ONCE(ns->head->disk))
1283 if (!kref_get_unless_zero(&ns->kref))
1285 if (!try_module_get(ns->ctrl->ops->module))
1296 static void nvme_release(struct gendisk *disk, fmode_t mode)
1298 struct nvme_ns *ns = disk->private_data;
1300 module_put(ns->ctrl->ops->module);
1304 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1306 /* some standard values */
1307 geo->heads = 1 << 6;
1308 geo->sectors = 1 << 5;
1309 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1313 #ifdef CONFIG_BLK_DEV_INTEGRITY
1314 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1316 struct blk_integrity integrity;
1318 memset(&integrity, 0, sizeof(integrity));
1320 case NVME_NS_DPS_PI_TYPE3:
1321 integrity.profile = &t10_pi_type3_crc;
1322 integrity.tag_size = sizeof(u16) + sizeof(u32);
1323 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1325 case NVME_NS_DPS_PI_TYPE1:
1326 case NVME_NS_DPS_PI_TYPE2:
1327 integrity.profile = &t10_pi_type1_crc;
1328 integrity.tag_size = sizeof(u16);
1329 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1332 integrity.profile = NULL;
1335 integrity.tuple_size = ms;
1336 blk_integrity_register(disk, &integrity);
1337 blk_queue_max_integrity_segments(disk->queue, 1);
1340 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1343 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1345 static void nvme_set_chunk_size(struct nvme_ns *ns)
1347 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1348 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1351 static void nvme_config_discard(struct nvme_ns *ns)
1353 struct nvme_ctrl *ctrl = ns->ctrl;
1354 struct request_queue *queue = ns->queue;
1355 u32 size = queue_logical_block_size(queue);
1357 if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1358 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1362 if (ctrl->nr_streams && ns->sws && ns->sgs)
1363 size *= ns->sws * ns->sgs;
1365 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1366 NVME_DSM_MAX_RANGES);
1368 queue->limits.discard_alignment = 0;
1369 queue->limits.discard_granularity = size;
1371 /* If discard is already enabled, don't reset queue limits */
1372 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1375 blk_queue_max_discard_sectors(queue, UINT_MAX);
1376 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1378 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1379 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1382 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1383 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1385 memset(ids, 0, sizeof(*ids));
1387 if (ctrl->vs >= NVME_VS(1, 1, 0))
1388 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1389 if (ctrl->vs >= NVME_VS(1, 2, 0))
1390 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1391 if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1392 /* Don't treat error as fatal we potentially
1393 * already have a NGUID or EUI-64
1395 if (nvme_identify_ns_descs(ctrl, nsid, ids))
1396 dev_warn(ctrl->device,
1397 "%s: Identify Descriptors failed\n", __func__);
1401 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1403 return !uuid_is_null(&ids->uuid) ||
1404 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1405 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1408 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1410 return uuid_equal(&a->uuid, &b->uuid) &&
1411 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1412 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0;
1415 static void nvme_update_disk_info(struct gendisk *disk,
1416 struct nvme_ns *ns, struct nvme_id_ns *id)
1418 sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9);
1419 unsigned short bs = 1 << ns->lba_shift;
1421 blk_mq_freeze_queue(disk->queue);
1422 blk_integrity_unregister(disk);
1424 blk_queue_logical_block_size(disk->queue, bs);
1425 blk_queue_physical_block_size(disk->queue, bs);
1426 blk_queue_io_min(disk->queue, bs);
1428 if (ns->ms && !ns->ext &&
1429 (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1430 nvme_init_integrity(disk, ns->ms, ns->pi_type);
1431 if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk))
1434 set_capacity(disk, capacity);
1435 nvme_config_discard(ns);
1436 blk_mq_unfreeze_queue(disk->queue);
1439 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1441 struct nvme_ns *ns = disk->private_data;
1444 * If identify namespace failed, use default 512 byte block size so
1445 * block layer can use before failing read/write for 0 capacity.
1447 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1448 if (ns->lba_shift == 0)
1450 ns->noiob = le16_to_cpu(id->noiob);
1451 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1452 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1453 /* the PI implementation requires metadata equal t10 pi tuple size */
1454 if (ns->ms == sizeof(struct t10_pi_tuple))
1455 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1460 nvme_set_chunk_size(ns);
1461 nvme_update_disk_info(disk, ns, id);
1463 nvme_nvm_update_nvm_info(ns);
1464 #ifdef CONFIG_NVME_MULTIPATH
1466 nvme_update_disk_info(ns->head->disk, ns, id);
1470 static int nvme_revalidate_disk(struct gendisk *disk)
1472 struct nvme_ns *ns = disk->private_data;
1473 struct nvme_ctrl *ctrl = ns->ctrl;
1474 struct nvme_id_ns *id;
1475 struct nvme_ns_ids ids;
1478 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1479 set_capacity(disk, 0);
1483 id = nvme_identify_ns(ctrl, ns->head->ns_id);
1487 if (id->ncap == 0) {
1492 __nvme_revalidate_disk(disk, id);
1493 nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
1494 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
1495 dev_err(ctrl->device,
1496 "identifiers changed for nsid %d\n", ns->head->ns_id);
1505 static char nvme_pr_type(enum pr_type type)
1508 case PR_WRITE_EXCLUSIVE:
1510 case PR_EXCLUSIVE_ACCESS:
1512 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1514 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1516 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1518 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1525 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1526 u64 key, u64 sa_key, u8 op)
1528 struct nvme_ns_head *head = NULL;
1530 struct nvme_command c;
1532 u8 data[16] = { 0, };
1534 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1536 return -EWOULDBLOCK;
1538 put_unaligned_le64(key, &data[0]);
1539 put_unaligned_le64(sa_key, &data[8]);
1541 memset(&c, 0, sizeof(c));
1542 c.common.opcode = op;
1543 c.common.nsid = cpu_to_le32(ns->head->ns_id);
1544 c.common.cdw10[0] = cpu_to_le32(cdw10);
1546 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1547 nvme_put_ns_from_disk(head, srcu_idx);
1551 static int nvme_pr_register(struct block_device *bdev, u64 old,
1552 u64 new, unsigned flags)
1556 if (flags & ~PR_FL_IGNORE_KEY)
1559 cdw10 = old ? 2 : 0;
1560 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1561 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1562 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1565 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1566 enum pr_type type, unsigned flags)
1570 if (flags & ~PR_FL_IGNORE_KEY)
1573 cdw10 = nvme_pr_type(type) << 8;
1574 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1575 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1578 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1579 enum pr_type type, bool abort)
1581 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1582 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1585 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1587 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1588 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1591 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1593 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
1594 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1597 static const struct pr_ops nvme_pr_ops = {
1598 .pr_register = nvme_pr_register,
1599 .pr_reserve = nvme_pr_reserve,
1600 .pr_release = nvme_pr_release,
1601 .pr_preempt = nvme_pr_preempt,
1602 .pr_clear = nvme_pr_clear,
1605 #ifdef CONFIG_BLK_SED_OPAL
1606 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1609 struct nvme_ctrl *ctrl = data;
1610 struct nvme_command cmd;
1612 memset(&cmd, 0, sizeof(cmd));
1614 cmd.common.opcode = nvme_admin_security_send;
1616 cmd.common.opcode = nvme_admin_security_recv;
1617 cmd.common.nsid = 0;
1618 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1619 cmd.common.cdw10[1] = cpu_to_le32(len);
1621 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1622 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1624 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1625 #endif /* CONFIG_BLK_SED_OPAL */
1627 static const struct block_device_operations nvme_fops = {
1628 .owner = THIS_MODULE,
1629 .ioctl = nvme_ioctl,
1630 .compat_ioctl = nvme_ioctl,
1632 .release = nvme_release,
1633 .getgeo = nvme_getgeo,
1634 .revalidate_disk= nvme_revalidate_disk,
1635 .pr_ops = &nvme_pr_ops,
1638 #ifdef CONFIG_NVME_MULTIPATH
1639 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
1641 struct nvme_ns_head *head = bdev->bd_disk->private_data;
1643 if (!kref_get_unless_zero(&head->ref))
1648 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
1650 nvme_put_ns_head(disk->private_data);
1653 const struct block_device_operations nvme_ns_head_ops = {
1654 .owner = THIS_MODULE,
1655 .open = nvme_ns_head_open,
1656 .release = nvme_ns_head_release,
1657 .ioctl = nvme_ioctl,
1658 .compat_ioctl = nvme_ioctl,
1659 .getgeo = nvme_getgeo,
1660 .pr_ops = &nvme_pr_ops,
1662 #endif /* CONFIG_NVME_MULTIPATH */
1664 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1666 unsigned long timeout =
1667 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1668 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1671 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1674 if ((csts & NVME_CSTS_RDY) == bit)
1678 if (fatal_signal_pending(current))
1680 if (time_after(jiffies, timeout)) {
1681 dev_err(ctrl->device,
1682 "Device not ready; aborting %s\n", enabled ?
1683 "initialisation" : "reset");
1692 * If the device has been passed off to us in an enabled state, just clear
1693 * the enabled bit. The spec says we should set the 'shutdown notification
1694 * bits', but doing so may cause the device to complete commands to the
1695 * admin queue ... and we don't know what memory that might be pointing at!
1697 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1701 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1702 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1704 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1708 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1709 msleep(NVME_QUIRK_DELAY_AMOUNT);
1711 return nvme_wait_ready(ctrl, cap, false);
1713 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1715 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1718 * Default to a 4K page size, with the intention to update this
1719 * path in the future to accomodate architectures with differing
1720 * kernel and IO page sizes.
1722 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1725 if (page_shift < dev_page_min) {
1726 dev_err(ctrl->device,
1727 "Minimum device page size %u too large for host (%u)\n",
1728 1 << dev_page_min, 1 << page_shift);
1732 ctrl->page_size = 1 << page_shift;
1734 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1735 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1736 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1737 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1738 ctrl->ctrl_config |= NVME_CC_ENABLE;
1740 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1743 return nvme_wait_ready(ctrl, cap, true);
1745 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1747 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1749 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1753 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1754 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1756 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1760 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1761 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1765 if (fatal_signal_pending(current))
1767 if (time_after(jiffies, timeout)) {
1768 dev_err(ctrl->device,
1769 "Device shutdown incomplete; abort shutdown\n");
1776 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1778 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1779 struct request_queue *q)
1783 if (ctrl->max_hw_sectors) {
1785 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1787 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1788 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1790 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1791 is_power_of_2(ctrl->max_hw_sectors))
1792 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1793 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1794 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1796 blk_queue_write_cache(q, vwc, vwc);
1799 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1804 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1807 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1808 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1811 dev_warn_once(ctrl->device,
1812 "could not set timestamp (%d)\n", ret);
1816 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1819 * APST (Autonomous Power State Transition) lets us program a
1820 * table of power state transitions that the controller will
1821 * perform automatically. We configure it with a simple
1822 * heuristic: we are willing to spend at most 2% of the time
1823 * transitioning between power states. Therefore, when running
1824 * in any given state, we will enter the next lower-power
1825 * non-operational state after waiting 50 * (enlat + exlat)
1826 * microseconds, as long as that state's exit latency is under
1827 * the requested maximum latency.
1829 * We will not autonomously enter any non-operational state for
1830 * which the total latency exceeds ps_max_latency_us. Users
1831 * can set ps_max_latency_us to zero to turn off APST.
1835 struct nvme_feat_auto_pst *table;
1841 * If APST isn't supported or if we haven't been initialized yet,
1842 * then don't do anything.
1847 if (ctrl->npss > 31) {
1848 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1852 table = kzalloc(sizeof(*table), GFP_KERNEL);
1856 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1857 /* Turn off APST. */
1859 dev_dbg(ctrl->device, "APST disabled\n");
1861 __le64 target = cpu_to_le64(0);
1865 * Walk through all states from lowest- to highest-power.
1866 * According to the spec, lower-numbered states use more
1867 * power. NPSS, despite the name, is the index of the
1868 * lowest-power state, not the number of states.
1870 for (state = (int)ctrl->npss; state >= 0; state--) {
1871 u64 total_latency_us, exit_latency_us, transition_ms;
1874 table->entries[state] = target;
1877 * Don't allow transitions to the deepest state
1878 * if it's quirked off.
1880 if (state == ctrl->npss &&
1881 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1885 * Is this state a useful non-operational state for
1886 * higher-power states to autonomously transition to?
1888 if (!(ctrl->psd[state].flags &
1889 NVME_PS_FLAGS_NON_OP_STATE))
1893 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1894 if (exit_latency_us > ctrl->ps_max_latency_us)
1899 le32_to_cpu(ctrl->psd[state].entry_lat);
1902 * This state is good. Use it as the APST idle
1903 * target for higher power states.
1905 transition_ms = total_latency_us + 19;
1906 do_div(transition_ms, 20);
1907 if (transition_ms > (1 << 24) - 1)
1908 transition_ms = (1 << 24) - 1;
1910 target = cpu_to_le64((state << 3) |
1911 (transition_ms << 8));
1916 if (total_latency_us > max_lat_us)
1917 max_lat_us = total_latency_us;
1923 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1925 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1926 max_ps, max_lat_us, (int)sizeof(*table), table);
1930 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1931 table, sizeof(*table), NULL);
1933 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1939 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1941 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1945 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1946 case PM_QOS_LATENCY_ANY:
1954 if (ctrl->ps_max_latency_us != latency) {
1955 ctrl->ps_max_latency_us = latency;
1956 nvme_configure_apst(ctrl);
1960 struct nvme_core_quirk_entry {
1962 * NVMe model and firmware strings are padded with spaces. For
1963 * simplicity, strings in the quirk table are padded with NULLs
1969 unsigned long quirks;
1972 static const struct nvme_core_quirk_entry core_quirks[] = {
1975 * This Toshiba device seems to die using any APST states. See:
1976 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1979 .mn = "THNSF5256GPUK TOSHIBA",
1980 .quirks = NVME_QUIRK_NO_APST,
1984 /* match is null-terminated but idstr is space-padded. */
1985 static bool string_matches(const char *idstr, const char *match, size_t len)
1992 matchlen = strlen(match);
1993 WARN_ON_ONCE(matchlen > len);
1995 if (memcmp(idstr, match, matchlen))
1998 for (; matchlen < len; matchlen++)
1999 if (idstr[matchlen] != ' ')
2005 static bool quirk_matches(const struct nvme_id_ctrl *id,
2006 const struct nvme_core_quirk_entry *q)
2008 return q->vid == le16_to_cpu(id->vid) &&
2009 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2010 string_matches(id->fr, q->fr, sizeof(id->fr));
2013 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2014 struct nvme_id_ctrl *id)
2019 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2020 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2021 strncpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2025 if (ctrl->vs >= NVME_VS(1, 2, 1))
2026 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2028 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2029 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2030 "nqn.2014.08.org.nvmexpress:%4x%4x",
2031 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2032 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2033 off += sizeof(id->sn);
2034 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2035 off += sizeof(id->mn);
2036 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2039 static void __nvme_release_subsystem(struct nvme_subsystem *subsys)
2041 ida_simple_remove(&nvme_subsystems_ida, subsys->instance);
2045 static void nvme_release_subsystem(struct device *dev)
2047 __nvme_release_subsystem(container_of(dev, struct nvme_subsystem, dev));
2050 static void nvme_destroy_subsystem(struct kref *ref)
2052 struct nvme_subsystem *subsys =
2053 container_of(ref, struct nvme_subsystem, ref);
2055 mutex_lock(&nvme_subsystems_lock);
2056 list_del(&subsys->entry);
2057 mutex_unlock(&nvme_subsystems_lock);
2059 ida_destroy(&subsys->ns_ida);
2060 device_del(&subsys->dev);
2061 put_device(&subsys->dev);
2064 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2066 kref_put(&subsys->ref, nvme_destroy_subsystem);
2069 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2071 struct nvme_subsystem *subsys;
2073 lockdep_assert_held(&nvme_subsystems_lock);
2075 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2076 if (strcmp(subsys->subnqn, subsysnqn))
2078 if (!kref_get_unless_zero(&subsys->ref))
2086 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2087 struct device_attribute subsys_attr_##_name = \
2088 __ATTR(_name, _mode, _show, NULL)
2090 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2091 struct device_attribute *attr,
2094 struct nvme_subsystem *subsys =
2095 container_of(dev, struct nvme_subsystem, dev);
2097 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2099 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2101 #define nvme_subsys_show_str_function(field) \
2102 static ssize_t subsys_##field##_show(struct device *dev, \
2103 struct device_attribute *attr, char *buf) \
2105 struct nvme_subsystem *subsys = \
2106 container_of(dev, struct nvme_subsystem, dev); \
2107 return sprintf(buf, "%.*s\n", \
2108 (int)sizeof(subsys->field), subsys->field); \
2110 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2112 nvme_subsys_show_str_function(model);
2113 nvme_subsys_show_str_function(serial);
2114 nvme_subsys_show_str_function(firmware_rev);
2116 static struct attribute *nvme_subsys_attrs[] = {
2117 &subsys_attr_model.attr,
2118 &subsys_attr_serial.attr,
2119 &subsys_attr_firmware_rev.attr,
2120 &subsys_attr_subsysnqn.attr,
2124 static struct attribute_group nvme_subsys_attrs_group = {
2125 .attrs = nvme_subsys_attrs,
2128 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2129 &nvme_subsys_attrs_group,
2133 static int nvme_active_ctrls(struct nvme_subsystem *subsys)
2136 struct nvme_ctrl *ctrl;
2138 mutex_lock(&subsys->lock);
2139 list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
2140 if (ctrl->state != NVME_CTRL_DELETING &&
2141 ctrl->state != NVME_CTRL_DEAD)
2144 mutex_unlock(&subsys->lock);
2149 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2151 struct nvme_subsystem *subsys, *found;
2154 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2157 ret = ida_simple_get(&nvme_subsystems_ida, 0, 0, GFP_KERNEL);
2162 subsys->instance = ret;
2163 mutex_init(&subsys->lock);
2164 kref_init(&subsys->ref);
2165 INIT_LIST_HEAD(&subsys->ctrls);
2166 INIT_LIST_HEAD(&subsys->nsheads);
2167 nvme_init_subnqn(subsys, ctrl, id);
2168 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2169 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2170 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2171 subsys->vendor_id = le16_to_cpu(id->vid);
2172 subsys->cmic = id->cmic;
2174 subsys->dev.class = nvme_subsys_class;
2175 subsys->dev.release = nvme_release_subsystem;
2176 subsys->dev.groups = nvme_subsys_attrs_groups;
2177 dev_set_name(&subsys->dev, "nvme-subsys%d", subsys->instance);
2178 device_initialize(&subsys->dev);
2180 mutex_lock(&nvme_subsystems_lock);
2181 found = __nvme_find_get_subsystem(subsys->subnqn);
2184 * Verify that the subsystem actually supports multiple
2185 * controllers, else bail out.
2187 if (!ctrl->opts->discovery_nqn &&
2188 nvme_active_ctrls(found) && !(id->cmic & (1 << 1))) {
2189 dev_err(ctrl->device,
2190 "ignoring ctrl due to duplicate subnqn (%s).\n",
2192 nvme_put_subsystem(found);
2197 __nvme_release_subsystem(subsys);
2200 ret = device_add(&subsys->dev);
2202 dev_err(ctrl->device,
2203 "failed to register subsystem device.\n");
2206 ida_init(&subsys->ns_ida);
2207 list_add_tail(&subsys->entry, &nvme_subsystems);
2210 ctrl->subsys = subsys;
2211 mutex_unlock(&nvme_subsystems_lock);
2213 if (sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2214 dev_name(ctrl->device))) {
2215 dev_err(ctrl->device,
2216 "failed to create sysfs link from subsystem.\n");
2217 /* the transport driver will eventually put the subsystem */
2221 mutex_lock(&subsys->lock);
2222 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2223 mutex_unlock(&subsys->lock);
2228 mutex_unlock(&nvme_subsystems_lock);
2229 put_device(&subsys->dev);
2233 int nvme_get_log_ext(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
2234 u8 log_page, void *log,
2235 size_t size, u64 offset)
2237 struct nvme_command c = { };
2238 unsigned long dwlen = size / 4 - 1;
2240 c.get_log_page.opcode = nvme_admin_get_log_page;
2243 c.get_log_page.nsid = cpu_to_le32(ns->head->ns_id);
2245 c.get_log_page.nsid = cpu_to_le32(NVME_NSID_ALL);
2247 c.get_log_page.lid = log_page;
2248 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2249 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2250 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2251 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2253 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2256 static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log,
2259 return nvme_get_log_ext(ctrl, NULL, log_page, log, size, 0);
2262 static int nvme_get_effects_log(struct nvme_ctrl *ctrl)
2267 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL);
2272 ret = nvme_get_log(ctrl, NVME_LOG_CMD_EFFECTS, ctrl->effects,
2273 sizeof(*ctrl->effects));
2275 kfree(ctrl->effects);
2276 ctrl->effects = NULL;
2282 * Initialize the cached copies of the Identify data and various controller
2283 * register in our nvme_ctrl structure. This should be called as soon as
2284 * the admin queue is fully up and running.
2286 int nvme_init_identify(struct nvme_ctrl *ctrl)
2288 struct nvme_id_ctrl *id;
2290 int ret, page_shift;
2292 bool prev_apst_enabled;
2294 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
2296 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
2300 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
2302 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2305 page_shift = NVME_CAP_MPSMIN(cap) + 12;
2307 if (ctrl->vs >= NVME_VS(1, 1, 0))
2308 ctrl->subsystem = NVME_CAP_NSSRC(cap);
2310 ret = nvme_identify_ctrl(ctrl, &id);
2312 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2316 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2317 ret = nvme_get_effects_log(ctrl);
2322 if (!ctrl->identified) {
2325 ret = nvme_init_subsystem(ctrl, id);
2330 * Check for quirks. Quirk can depend on firmware version,
2331 * so, in principle, the set of quirks present can change
2332 * across a reset. As a possible future enhancement, we
2333 * could re-scan for quirks every time we reinitialize
2334 * the device, but we'd have to make sure that the driver
2335 * behaves intelligently if the quirks change.
2337 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2338 if (quirk_matches(id, &core_quirks[i]))
2339 ctrl->quirks |= core_quirks[i].quirks;
2343 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2344 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2345 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2348 ctrl->oacs = le16_to_cpu(id->oacs);
2349 ctrl->oncs = le16_to_cpup(&id->oncs);
2350 atomic_set(&ctrl->abort_limit, id->acl + 1);
2351 ctrl->vwc = id->vwc;
2352 ctrl->cntlid = le16_to_cpup(&id->cntlid);
2354 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
2356 max_hw_sectors = UINT_MAX;
2357 ctrl->max_hw_sectors =
2358 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2360 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2361 ctrl->sgls = le32_to_cpu(id->sgls);
2362 ctrl->kas = le16_to_cpu(id->kas);
2366 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
2368 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2369 shutdown_timeout, 60);
2371 if (ctrl->shutdown_timeout != shutdown_timeout)
2372 dev_info(ctrl->device,
2373 "Shutdown timeout set to %u seconds\n",
2374 ctrl->shutdown_timeout);
2376 ctrl->shutdown_timeout = shutdown_timeout;
2378 ctrl->npss = id->npss;
2379 ctrl->apsta = id->apsta;
2380 prev_apst_enabled = ctrl->apst_enabled;
2381 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2382 if (force_apst && id->apsta) {
2383 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2384 ctrl->apst_enabled = true;
2386 ctrl->apst_enabled = false;
2389 ctrl->apst_enabled = id->apsta;
2391 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2393 if (ctrl->ops->flags & NVME_F_FABRICS) {
2394 ctrl->icdoff = le16_to_cpu(id->icdoff);
2395 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2396 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2397 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2400 * In fabrics we need to verify the cntlid matches the
2403 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2408 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
2409 dev_err(ctrl->device,
2410 "keep-alive support is mandatory for fabrics\n");
2415 ctrl->cntlid = le16_to_cpu(id->cntlid);
2416 ctrl->hmpre = le32_to_cpu(id->hmpre);
2417 ctrl->hmmin = le32_to_cpu(id->hmmin);
2418 ctrl->hmminds = le32_to_cpu(id->hmminds);
2419 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2424 if (ctrl->apst_enabled && !prev_apst_enabled)
2425 dev_pm_qos_expose_latency_tolerance(ctrl->device);
2426 else if (!ctrl->apst_enabled && prev_apst_enabled)
2427 dev_pm_qos_hide_latency_tolerance(ctrl->device);
2429 ret = nvme_configure_apst(ctrl);
2433 ret = nvme_configure_timestamp(ctrl);
2437 ret = nvme_configure_directives(ctrl);
2441 ctrl->identified = true;
2449 EXPORT_SYMBOL_GPL(nvme_init_identify);
2451 static int nvme_dev_open(struct inode *inode, struct file *file)
2453 struct nvme_ctrl *ctrl =
2454 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
2456 switch (ctrl->state) {
2457 case NVME_CTRL_LIVE:
2458 case NVME_CTRL_ADMIN_ONLY:
2461 return -EWOULDBLOCK;
2464 file->private_data = ctrl;
2468 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
2473 down_read(&ctrl->namespaces_rwsem);
2474 if (list_empty(&ctrl->namespaces)) {
2479 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
2480 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
2481 dev_warn(ctrl->device,
2482 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
2487 dev_warn(ctrl->device,
2488 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
2489 kref_get(&ns->kref);
2490 up_read(&ctrl->namespaces_rwsem);
2492 ret = nvme_user_cmd(ctrl, ns, argp);
2497 up_read(&ctrl->namespaces_rwsem);
2501 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
2504 struct nvme_ctrl *ctrl = file->private_data;
2505 void __user *argp = (void __user *)arg;
2508 case NVME_IOCTL_ADMIN_CMD:
2509 return nvme_user_cmd(ctrl, NULL, argp);
2510 case NVME_IOCTL_IO_CMD:
2511 return nvme_dev_user_cmd(ctrl, argp);
2512 case NVME_IOCTL_RESET:
2513 dev_warn(ctrl->device, "resetting controller\n");
2514 return nvme_reset_ctrl_sync(ctrl);
2515 case NVME_IOCTL_SUBSYS_RESET:
2516 return nvme_reset_subsystem(ctrl);
2517 case NVME_IOCTL_RESCAN:
2518 nvme_queue_scan(ctrl);
2525 static const struct file_operations nvme_dev_fops = {
2526 .owner = THIS_MODULE,
2527 .open = nvme_dev_open,
2528 .unlocked_ioctl = nvme_dev_ioctl,
2529 .compat_ioctl = nvme_dev_ioctl,
2532 static ssize_t nvme_sysfs_reset(struct device *dev,
2533 struct device_attribute *attr, const char *buf,
2536 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2539 ret = nvme_reset_ctrl_sync(ctrl);
2544 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2546 static ssize_t nvme_sysfs_rescan(struct device *dev,
2547 struct device_attribute *attr, const char *buf,
2550 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2552 nvme_queue_scan(ctrl);
2555 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2557 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
2559 struct gendisk *disk = dev_to_disk(dev);
2561 if (disk->fops == &nvme_fops)
2562 return nvme_get_ns_from_dev(dev)->head;
2564 return disk->private_data;
2567 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2570 struct nvme_ns_head *head = dev_to_ns_head(dev);
2571 struct nvme_ns_ids *ids = &head->ids;
2572 struct nvme_subsystem *subsys = head->subsys;
2573 int serial_len = sizeof(subsys->serial);
2574 int model_len = sizeof(subsys->model);
2576 if (!uuid_is_null(&ids->uuid))
2577 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
2579 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2580 return sprintf(buf, "eui.%16phN\n", ids->nguid);
2582 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2583 return sprintf(buf, "eui.%8phN\n", ids->eui64);
2585 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
2586 subsys->serial[serial_len - 1] == '\0'))
2588 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
2589 subsys->model[model_len - 1] == '\0'))
2592 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
2593 serial_len, subsys->serial, model_len, subsys->model,
2596 static DEVICE_ATTR_RO(wwid);
2598 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2601 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
2603 static DEVICE_ATTR_RO(nguid);
2605 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2608 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2610 /* For backward compatibility expose the NGUID to userspace if
2611 * we have no UUID set
2613 if (uuid_is_null(&ids->uuid)) {
2614 printk_ratelimited(KERN_WARNING
2615 "No UUID available providing old NGUID\n");
2616 return sprintf(buf, "%pU\n", ids->nguid);
2618 return sprintf(buf, "%pU\n", &ids->uuid);
2620 static DEVICE_ATTR_RO(uuid);
2622 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2625 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
2627 static DEVICE_ATTR_RO(eui);
2629 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2632 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
2634 static DEVICE_ATTR_RO(nsid);
2636 static struct attribute *nvme_ns_id_attrs[] = {
2637 &dev_attr_wwid.attr,
2638 &dev_attr_uuid.attr,
2639 &dev_attr_nguid.attr,
2641 &dev_attr_nsid.attr,
2645 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
2646 struct attribute *a, int n)
2648 struct device *dev = container_of(kobj, struct device, kobj);
2649 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2651 if (a == &dev_attr_uuid.attr) {
2652 if (uuid_is_null(&ids->uuid) &&
2653 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2656 if (a == &dev_attr_nguid.attr) {
2657 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2660 if (a == &dev_attr_eui.attr) {
2661 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2667 const struct attribute_group nvme_ns_id_attr_group = {
2668 .attrs = nvme_ns_id_attrs,
2669 .is_visible = nvme_ns_id_attrs_are_visible,
2672 #define nvme_show_str_function(field) \
2673 static ssize_t field##_show(struct device *dev, \
2674 struct device_attribute *attr, char *buf) \
2676 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2677 return sprintf(buf, "%.*s\n", \
2678 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
2680 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2682 nvme_show_str_function(model);
2683 nvme_show_str_function(serial);
2684 nvme_show_str_function(firmware_rev);
2686 #define nvme_show_int_function(field) \
2687 static ssize_t field##_show(struct device *dev, \
2688 struct device_attribute *attr, char *buf) \
2690 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2691 return sprintf(buf, "%d\n", ctrl->field); \
2693 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2695 nvme_show_int_function(cntlid);
2697 static ssize_t nvme_sysfs_delete(struct device *dev,
2698 struct device_attribute *attr, const char *buf,
2701 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2703 if (device_remove_file_self(dev, attr))
2704 nvme_delete_ctrl_sync(ctrl);
2707 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2709 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2710 struct device_attribute *attr,
2713 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2715 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2717 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2719 static ssize_t nvme_sysfs_show_state(struct device *dev,
2720 struct device_attribute *attr,
2723 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2724 static const char *const state_name[] = {
2725 [NVME_CTRL_NEW] = "new",
2726 [NVME_CTRL_LIVE] = "live",
2727 [NVME_CTRL_ADMIN_ONLY] = "only-admin",
2728 [NVME_CTRL_RESETTING] = "resetting",
2729 [NVME_CTRL_CONNECTING] = "connecting",
2730 [NVME_CTRL_DELETING] = "deleting",
2731 [NVME_CTRL_DEAD] = "dead",
2734 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2735 state_name[ctrl->state])
2736 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2738 return sprintf(buf, "unknown state\n");
2741 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2743 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2744 struct device_attribute *attr,
2747 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2749 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
2751 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2753 static ssize_t nvme_sysfs_show_address(struct device *dev,
2754 struct device_attribute *attr,
2757 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2759 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2761 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2763 static struct attribute *nvme_dev_attrs[] = {
2764 &dev_attr_reset_controller.attr,
2765 &dev_attr_rescan_controller.attr,
2766 &dev_attr_model.attr,
2767 &dev_attr_serial.attr,
2768 &dev_attr_firmware_rev.attr,
2769 &dev_attr_cntlid.attr,
2770 &dev_attr_delete_controller.attr,
2771 &dev_attr_transport.attr,
2772 &dev_attr_subsysnqn.attr,
2773 &dev_attr_address.attr,
2774 &dev_attr_state.attr,
2778 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2779 struct attribute *a, int n)
2781 struct device *dev = container_of(kobj, struct device, kobj);
2782 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2784 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2786 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2792 static struct attribute_group nvme_dev_attrs_group = {
2793 .attrs = nvme_dev_attrs,
2794 .is_visible = nvme_dev_attrs_are_visible,
2797 static const struct attribute_group *nvme_dev_attr_groups[] = {
2798 &nvme_dev_attrs_group,
2802 static struct nvme_ns_head *__nvme_find_ns_head(struct nvme_subsystem *subsys,
2805 struct nvme_ns_head *h;
2807 lockdep_assert_held(&subsys->lock);
2809 list_for_each_entry(h, &subsys->nsheads, entry) {
2810 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
2817 static int __nvme_check_ids(struct nvme_subsystem *subsys,
2818 struct nvme_ns_head *new)
2820 struct nvme_ns_head *h;
2822 lockdep_assert_held(&subsys->lock);
2824 list_for_each_entry(h, &subsys->nsheads, entry) {
2825 if (nvme_ns_ids_valid(&new->ids) &&
2826 !list_empty(&h->list) &&
2827 nvme_ns_ids_equal(&new->ids, &h->ids))
2834 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
2835 unsigned nsid, struct nvme_id_ns *id)
2837 struct nvme_ns_head *head;
2840 head = kzalloc(sizeof(*head), GFP_KERNEL);
2843 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
2846 head->instance = ret;
2847 INIT_LIST_HEAD(&head->list);
2848 ret = init_srcu_struct(&head->srcu);
2850 goto out_ida_remove;
2851 head->subsys = ctrl->subsys;
2853 kref_init(&head->ref);
2855 nvme_report_ns_ids(ctrl, nsid, id, &head->ids);
2857 ret = __nvme_check_ids(ctrl->subsys, head);
2859 dev_err(ctrl->device,
2860 "duplicate IDs for nsid %d\n", nsid);
2861 goto out_cleanup_srcu;
2864 ret = nvme_mpath_alloc_disk(ctrl, head);
2866 goto out_cleanup_srcu;
2868 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
2871 cleanup_srcu_struct(&head->srcu);
2873 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
2877 return ERR_PTR(ret);
2880 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
2881 struct nvme_id_ns *id)
2883 struct nvme_ctrl *ctrl = ns->ctrl;
2884 bool is_shared = id->nmic & (1 << 0);
2885 struct nvme_ns_head *head = NULL;
2888 mutex_lock(&ctrl->subsys->lock);
2890 head = __nvme_find_ns_head(ctrl->subsys, nsid);
2892 head = nvme_alloc_ns_head(ctrl, nsid, id);
2894 ret = PTR_ERR(head);
2898 struct nvme_ns_ids ids;
2900 nvme_report_ns_ids(ctrl, nsid, id, &ids);
2901 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
2902 dev_err(ctrl->device,
2903 "IDs don't match for shared namespace %d\n",
2910 list_add_tail(&ns->siblings, &head->list);
2914 mutex_unlock(&ctrl->subsys->lock);
2918 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2920 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2921 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2923 return nsa->head->ns_id - nsb->head->ns_id;
2926 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2928 struct nvme_ns *ns, *ret = NULL;
2930 down_read(&ctrl->namespaces_rwsem);
2931 list_for_each_entry(ns, &ctrl->namespaces, list) {
2932 if (ns->head->ns_id == nsid) {
2933 if (!kref_get_unless_zero(&ns->kref))
2938 if (ns->head->ns_id > nsid)
2941 up_read(&ctrl->namespaces_rwsem);
2945 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2947 struct streams_directive_params s;
2950 if (!ctrl->nr_streams)
2953 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
2957 ns->sws = le32_to_cpu(s.sws);
2958 ns->sgs = le16_to_cpu(s.sgs);
2961 unsigned int bs = 1 << ns->lba_shift;
2963 blk_queue_io_min(ns->queue, bs * ns->sws);
2965 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2971 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2974 struct gendisk *disk;
2975 struct nvme_id_ns *id;
2976 char disk_name[DISK_NAME_LEN];
2977 int node = dev_to_node(ctrl->dev), flags = GENHD_FL_EXT_DEVT;
2979 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2983 ns->queue = blk_mq_init_queue(ctrl->tagset);
2984 if (IS_ERR(ns->queue))
2986 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
2987 ns->queue->queuedata = ns;
2990 kref_init(&ns->kref);
2991 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2993 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2994 nvme_set_queue_limits(ctrl, ns->queue);
2996 id = nvme_identify_ns(ctrl, nsid);
2998 goto out_free_queue;
3003 if (nvme_init_ns_head(ns, nsid, id))
3005 nvme_setup_streams_ns(ctrl, ns);
3006 nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3008 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3009 if (nvme_nvm_register(ns, disk_name, node)) {
3010 dev_warn(ctrl->device, "LightNVM init failure\n");
3015 disk = alloc_disk_node(0, node);
3019 disk->fops = &nvme_fops;
3020 disk->private_data = ns;
3021 disk->queue = ns->queue;
3022 disk->flags = flags;
3023 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3026 __nvme_revalidate_disk(disk, id);
3028 down_write(&ctrl->namespaces_rwsem);
3029 list_add_tail(&ns->list, &ctrl->namespaces);
3030 up_write(&ctrl->namespaces_rwsem);
3032 nvme_get_ctrl(ctrl);
3036 device_add_disk(ctrl->device, ns->disk);
3037 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
3038 &nvme_ns_id_attr_group))
3039 pr_warn("%s: failed to create sysfs group for identification\n",
3040 ns->disk->disk_name);
3041 if (ns->ndev && nvme_nvm_register_sysfs(ns))
3042 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
3043 ns->disk->disk_name);
3045 nvme_mpath_add_disk(ns->head);
3046 nvme_fault_inject_init(ns);
3049 mutex_lock(&ctrl->subsys->lock);
3050 list_del_rcu(&ns->siblings);
3051 mutex_unlock(&ctrl->subsys->lock);
3055 blk_cleanup_queue(ns->queue);
3060 static void nvme_ns_remove(struct nvme_ns *ns)
3062 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3065 nvme_fault_inject_fini(ns);
3066 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
3067 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
3068 &nvme_ns_id_attr_group);
3070 nvme_nvm_unregister_sysfs(ns);
3071 del_gendisk(ns->disk);
3072 blk_cleanup_queue(ns->queue);
3073 if (blk_get_integrity(ns->disk))
3074 blk_integrity_unregister(ns->disk);
3077 mutex_lock(&ns->ctrl->subsys->lock);
3078 nvme_mpath_clear_current_path(ns);
3079 list_del_rcu(&ns->siblings);
3080 mutex_unlock(&ns->ctrl->subsys->lock);
3082 down_write(&ns->ctrl->namespaces_rwsem);
3083 list_del_init(&ns->list);
3084 up_write(&ns->ctrl->namespaces_rwsem);
3086 synchronize_srcu(&ns->head->srcu);
3087 nvme_mpath_check_last_path(ns);
3091 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3095 ns = nvme_find_get_ns(ctrl, nsid);
3097 if (ns->disk && revalidate_disk(ns->disk))
3101 nvme_alloc_ns(ctrl, nsid);
3104 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3107 struct nvme_ns *ns, *next;
3110 down_write(&ctrl->namespaces_rwsem);
3111 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3112 if (ns->head->ns_id > nsid)
3113 list_move_tail(&ns->list, &rm_list);
3115 up_write(&ctrl->namespaces_rwsem);
3117 list_for_each_entry_safe(ns, next, &rm_list, list)
3122 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
3126 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
3129 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3133 for (i = 0; i < num_lists; i++) {
3134 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
3138 for (j = 0; j < min(nn, 1024U); j++) {
3139 nsid = le32_to_cpu(ns_list[j]);
3143 nvme_validate_ns(ctrl, nsid);
3145 while (++prev < nsid) {
3146 ns = nvme_find_get_ns(ctrl, prev);
3156 nvme_remove_invalid_namespaces(ctrl, prev);
3162 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
3166 for (i = 1; i <= nn; i++)
3167 nvme_validate_ns(ctrl, i);
3169 nvme_remove_invalid_namespaces(ctrl, nn);
3172 static void nvme_scan_work(struct work_struct *work)
3174 struct nvme_ctrl *ctrl =
3175 container_of(work, struct nvme_ctrl, scan_work);
3176 struct nvme_id_ctrl *id;
3179 if (ctrl->state != NVME_CTRL_LIVE)
3182 WARN_ON_ONCE(!ctrl->tagset);
3184 if (nvme_identify_ctrl(ctrl, &id))
3187 nn = le32_to_cpu(id->nn);
3188 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
3189 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
3190 if (!nvme_scan_ns_list(ctrl, nn))
3193 nvme_scan_ns_sequential(ctrl, nn);
3195 down_write(&ctrl->namespaces_rwsem);
3196 list_sort(NULL, &ctrl->namespaces, ns_cmp);
3197 up_write(&ctrl->namespaces_rwsem);
3201 void nvme_queue_scan(struct nvme_ctrl *ctrl)
3204 * Only new queue scan work when admin and IO queues are both alive
3206 if (ctrl->state == NVME_CTRL_LIVE)
3207 queue_work(nvme_wq, &ctrl->scan_work);
3209 EXPORT_SYMBOL_GPL(nvme_queue_scan);
3212 * This function iterates the namespace list unlocked to allow recovery from
3213 * controller failure. It is up to the caller to ensure the namespace list is
3214 * not modified by scan work while this function is executing.
3216 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3218 struct nvme_ns *ns, *next;
3222 * The dead states indicates the controller was not gracefully
3223 * disconnected. In that case, we won't be able to flush any data while
3224 * removing the namespaces' disks; fail all the queues now to avoid
3225 * potentially having to clean up the failed sync later.
3227 if (ctrl->state == NVME_CTRL_DEAD)
3228 nvme_kill_queues(ctrl);
3230 down_write(&ctrl->namespaces_rwsem);
3231 list_splice_init(&ctrl->namespaces, &ns_list);
3232 up_write(&ctrl->namespaces_rwsem);
3234 list_for_each_entry_safe(ns, next, &ns_list, list)
3237 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
3239 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
3241 char *envp[2] = { NULL, NULL };
3242 u32 aen_result = ctrl->aen_result;
3244 ctrl->aen_result = 0;
3248 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
3251 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
3255 static void nvme_async_event_work(struct work_struct *work)
3257 struct nvme_ctrl *ctrl =
3258 container_of(work, struct nvme_ctrl, async_event_work);
3260 nvme_aen_uevent(ctrl);
3261 ctrl->ops->submit_async_event(ctrl);
3264 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
3269 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
3275 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
3278 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
3280 struct nvme_fw_slot_info_log *log;
3282 log = kmalloc(sizeof(*log), GFP_KERNEL);
3286 if (nvme_get_log(ctrl, NVME_LOG_FW_SLOT, log, sizeof(*log)))
3287 dev_warn(ctrl->device,
3288 "Get FW SLOT INFO log error\n");
3292 static void nvme_fw_act_work(struct work_struct *work)
3294 struct nvme_ctrl *ctrl = container_of(work,
3295 struct nvme_ctrl, fw_act_work);
3296 unsigned long fw_act_timeout;
3299 fw_act_timeout = jiffies +
3300 msecs_to_jiffies(ctrl->mtfa * 100);
3302 fw_act_timeout = jiffies +
3303 msecs_to_jiffies(admin_timeout * 1000);
3305 nvme_stop_queues(ctrl);
3306 while (nvme_ctrl_pp_status(ctrl)) {
3307 if (time_after(jiffies, fw_act_timeout)) {
3308 dev_warn(ctrl->device,
3309 "Fw activation timeout, reset controller\n");
3310 nvme_reset_ctrl(ctrl);
3316 if (ctrl->state != NVME_CTRL_LIVE)
3319 nvme_start_queues(ctrl);
3320 /* read FW slot information to clear the AER */
3321 nvme_get_fw_slot_info(ctrl);
3324 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
3325 volatile union nvme_result *res)
3327 u32 result = le32_to_cpu(res->u32);
3329 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
3332 switch (result & 0x7) {
3333 case NVME_AER_ERROR:
3334 case NVME_AER_SMART:
3337 ctrl->aen_result = result;
3343 switch (result & 0xff07) {
3344 case NVME_AER_NOTICE_NS_CHANGED:
3345 dev_info(ctrl->device, "rescanning\n");
3346 nvme_queue_scan(ctrl);
3348 case NVME_AER_NOTICE_FW_ACT_STARTING:
3349 queue_work(nvme_wq, &ctrl->fw_act_work);
3352 dev_warn(ctrl->device, "async event result %08x\n", result);
3354 queue_work(nvme_wq, &ctrl->async_event_work);
3356 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
3358 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
3360 nvme_stop_keep_alive(ctrl);
3361 flush_work(&ctrl->async_event_work);
3362 flush_work(&ctrl->scan_work);
3363 cancel_work_sync(&ctrl->fw_act_work);
3364 if (ctrl->ops->stop_ctrl)
3365 ctrl->ops->stop_ctrl(ctrl);
3367 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
3369 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
3372 nvme_start_keep_alive(ctrl);
3374 if (ctrl->queue_count > 1) {
3375 nvme_queue_scan(ctrl);
3376 queue_work(nvme_wq, &ctrl->async_event_work);
3377 nvme_start_queues(ctrl);
3380 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
3382 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
3384 cdev_device_del(&ctrl->cdev, ctrl->device);
3386 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
3388 static void nvme_free_ctrl(struct device *dev)
3390 struct nvme_ctrl *ctrl =
3391 container_of(dev, struct nvme_ctrl, ctrl_device);
3392 struct nvme_subsystem *subsys = ctrl->subsys;
3394 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
3395 kfree(ctrl->effects);
3398 mutex_lock(&subsys->lock);
3399 list_del(&ctrl->subsys_entry);
3400 mutex_unlock(&subsys->lock);
3401 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
3404 ctrl->ops->free_ctrl(ctrl);
3407 nvme_put_subsystem(subsys);
3411 * Initialize a NVMe controller structures. This needs to be called during
3412 * earliest initialization so that we have the initialized structured around
3415 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
3416 const struct nvme_ctrl_ops *ops, unsigned long quirks)
3420 ctrl->state = NVME_CTRL_NEW;
3421 spin_lock_init(&ctrl->lock);
3422 INIT_LIST_HEAD(&ctrl->namespaces);
3423 init_rwsem(&ctrl->namespaces_rwsem);
3426 ctrl->quirks = quirks;
3427 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
3428 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
3429 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
3430 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
3432 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
3435 ctrl->instance = ret;
3437 device_initialize(&ctrl->ctrl_device);
3438 ctrl->device = &ctrl->ctrl_device;
3439 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
3440 ctrl->device->class = nvme_class;
3441 ctrl->device->parent = ctrl->dev;
3442 ctrl->device->groups = nvme_dev_attr_groups;
3443 ctrl->device->release = nvme_free_ctrl;
3444 dev_set_drvdata(ctrl->device, ctrl);
3445 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
3447 goto out_release_instance;
3449 cdev_init(&ctrl->cdev, &nvme_dev_fops);
3450 ctrl->cdev.owner = ops->module;
3451 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
3456 * Initialize latency tolerance controls. The sysfs files won't
3457 * be visible to userspace unless the device actually supports APST.
3459 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
3460 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
3461 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
3465 kfree_const(dev->kobj.name);
3466 out_release_instance:
3467 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
3471 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
3474 * nvme_kill_queues(): Ends all namespace queues
3475 * @ctrl: the dead controller that needs to end
3477 * Call this function when the driver determines it is unable to get the
3478 * controller in a state capable of servicing IO.
3480 void nvme_kill_queues(struct nvme_ctrl *ctrl)
3484 down_read(&ctrl->namespaces_rwsem);
3486 /* Forcibly unquiesce queues to avoid blocking dispatch */
3488 blk_mq_unquiesce_queue(ctrl->admin_q);
3490 list_for_each_entry(ns, &ctrl->namespaces, list) {
3492 * Revalidating a dead namespace sets capacity to 0. This will
3493 * end buffered writers dirtying pages that can't be synced.
3495 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
3497 revalidate_disk(ns->disk);
3498 blk_set_queue_dying(ns->queue);
3500 /* Forcibly unquiesce queues to avoid blocking dispatch */
3501 blk_mq_unquiesce_queue(ns->queue);
3503 up_read(&ctrl->namespaces_rwsem);
3505 EXPORT_SYMBOL_GPL(nvme_kill_queues);
3507 void nvme_unfreeze(struct nvme_ctrl *ctrl)
3511 down_read(&ctrl->namespaces_rwsem);
3512 list_for_each_entry(ns, &ctrl->namespaces, list)
3513 blk_mq_unfreeze_queue(ns->queue);
3514 up_read(&ctrl->namespaces_rwsem);
3516 EXPORT_SYMBOL_GPL(nvme_unfreeze);
3518 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
3522 down_read(&ctrl->namespaces_rwsem);
3523 list_for_each_entry(ns, &ctrl->namespaces, list) {
3524 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
3528 up_read(&ctrl->namespaces_rwsem);
3530 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
3532 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
3536 down_read(&ctrl->namespaces_rwsem);
3537 list_for_each_entry(ns, &ctrl->namespaces, list)
3538 blk_mq_freeze_queue_wait(ns->queue);
3539 up_read(&ctrl->namespaces_rwsem);
3541 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
3543 void nvme_start_freeze(struct nvme_ctrl *ctrl)
3547 down_read(&ctrl->namespaces_rwsem);
3548 list_for_each_entry(ns, &ctrl->namespaces, list)
3549 blk_freeze_queue_start(ns->queue);
3550 up_read(&ctrl->namespaces_rwsem);
3552 EXPORT_SYMBOL_GPL(nvme_start_freeze);
3554 void nvme_stop_queues(struct nvme_ctrl *ctrl)
3558 down_read(&ctrl->namespaces_rwsem);
3559 list_for_each_entry(ns, &ctrl->namespaces, list)
3560 blk_mq_quiesce_queue(ns->queue);
3561 up_read(&ctrl->namespaces_rwsem);
3563 EXPORT_SYMBOL_GPL(nvme_stop_queues);
3565 void nvme_start_queues(struct nvme_ctrl *ctrl)
3569 down_read(&ctrl->namespaces_rwsem);
3570 list_for_each_entry(ns, &ctrl->namespaces, list)
3571 blk_mq_unquiesce_queue(ns->queue);
3572 up_read(&ctrl->namespaces_rwsem);
3574 EXPORT_SYMBOL_GPL(nvme_start_queues);
3576 int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set)
3578 if (!ctrl->ops->reinit_request)
3581 return blk_mq_tagset_iter(set, set->driver_data,
3582 ctrl->ops->reinit_request);
3584 EXPORT_SYMBOL_GPL(nvme_reinit_tagset);
3586 int __init nvme_core_init(void)
3588 int result = -ENOMEM;
3590 nvme_wq = alloc_workqueue("nvme-wq",
3591 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3595 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
3596 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3600 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
3601 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3602 if (!nvme_delete_wq)
3603 goto destroy_reset_wq;
3605 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
3607 goto destroy_delete_wq;
3609 nvme_class = class_create(THIS_MODULE, "nvme");
3610 if (IS_ERR(nvme_class)) {
3611 result = PTR_ERR(nvme_class);
3612 goto unregister_chrdev;
3615 nvme_subsys_class = class_create(THIS_MODULE, "nvme-subsystem");
3616 if (IS_ERR(nvme_subsys_class)) {
3617 result = PTR_ERR(nvme_subsys_class);
3623 class_destroy(nvme_class);
3625 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
3627 destroy_workqueue(nvme_delete_wq);
3629 destroy_workqueue(nvme_reset_wq);
3631 destroy_workqueue(nvme_wq);
3636 void nvme_core_exit(void)
3638 ida_destroy(&nvme_subsystems_ida);
3639 class_destroy(nvme_subsys_class);
3640 class_destroy(nvme_class);
3641 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
3642 destroy_workqueue(nvme_delete_wq);
3643 destroy_workqueue(nvme_reset_wq);
3644 destroy_workqueue(nvme_wq);
3647 MODULE_LICENSE("GPL");
3648 MODULE_VERSION("1.0");
3649 module_init(nvme_core_init);
3650 module_exit(nvme_core_exit);