2 * NVM Express device driver
3 * Copyright (c) 2011-2014, Intel Corporation.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms and conditions of the GNU General Public License,
7 * version 2, as published by the Free Software Foundation.
9 * This program is distributed in the hope it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <linux/pm_qos.h>
30 #include <asm/unaligned.h>
32 #define CREATE_TRACE_POINTS
38 #define NVME_MINORS (1U << MINORBITS)
40 unsigned int admin_timeout = 60;
41 module_param(admin_timeout, uint, 0644);
42 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
43 EXPORT_SYMBOL_GPL(admin_timeout);
45 unsigned int nvme_io_timeout = 30;
46 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
47 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
48 EXPORT_SYMBOL_GPL(nvme_io_timeout);
50 static unsigned char shutdown_timeout = 5;
51 module_param(shutdown_timeout, byte, 0644);
52 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
54 static u8 nvme_max_retries = 5;
55 module_param_named(max_retries, nvme_max_retries, byte, 0644);
56 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
58 static unsigned long default_ps_max_latency_us = 100000;
59 module_param(default_ps_max_latency_us, ulong, 0644);
60 MODULE_PARM_DESC(default_ps_max_latency_us,
61 "max power saving latency for new devices; use PM QOS to change per device");
63 static bool force_apst;
64 module_param(force_apst, bool, 0644);
65 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
68 module_param(streams, bool, 0644);
69 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
72 * nvme_wq - hosts nvme related works that are not reset or delete
73 * nvme_reset_wq - hosts nvme reset works
74 * nvme_delete_wq - hosts nvme delete works
76 * nvme_wq will host works such are scan, aen handling, fw activation,
77 * keep-alive error recovery, periodic reconnects etc. nvme_reset_wq
78 * runs reset works which also flush works hosted on nvme_wq for
79 * serialization purposes. nvme_delete_wq host controller deletion
80 * works which flush reset works for serialization.
82 struct workqueue_struct *nvme_wq;
83 EXPORT_SYMBOL_GPL(nvme_wq);
85 struct workqueue_struct *nvme_reset_wq;
86 EXPORT_SYMBOL_GPL(nvme_reset_wq);
88 struct workqueue_struct *nvme_delete_wq;
89 EXPORT_SYMBOL_GPL(nvme_delete_wq);
91 static DEFINE_IDA(nvme_subsystems_ida);
92 static LIST_HEAD(nvme_subsystems);
93 static DEFINE_MUTEX(nvme_subsystems_lock);
95 static DEFINE_IDA(nvme_instance_ida);
96 static dev_t nvme_chr_devt;
97 static struct class *nvme_class;
98 static struct class *nvme_subsys_class;
100 static void nvme_ns_remove(struct nvme_ns *ns);
101 static int nvme_revalidate_disk(struct gendisk *disk);
102 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
103 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
106 static void nvme_set_queue_dying(struct nvme_ns *ns)
109 * Revalidating a dead namespace sets capacity to 0. This will end
110 * buffered writers dirtying pages that can't be synced.
112 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
114 revalidate_disk(ns->disk);
115 blk_set_queue_dying(ns->queue);
116 /* Forcibly unquiesce queues to avoid blocking dispatch */
117 blk_mq_unquiesce_queue(ns->queue);
120 static void nvme_queue_scan(struct nvme_ctrl *ctrl)
123 * Only new queue scan work when admin and IO queues are both alive
125 if (ctrl->state == NVME_CTRL_LIVE)
126 queue_work(nvme_wq, &ctrl->scan_work);
129 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
131 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
133 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
137 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
139 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
143 ret = nvme_reset_ctrl(ctrl);
145 flush_work(&ctrl->reset_work);
146 if (ctrl->state != NVME_CTRL_LIVE &&
147 ctrl->state != NVME_CTRL_ADMIN_ONLY)
153 EXPORT_SYMBOL_GPL(nvme_reset_ctrl_sync);
155 static void nvme_delete_ctrl_work(struct work_struct *work)
157 struct nvme_ctrl *ctrl =
158 container_of(work, struct nvme_ctrl, delete_work);
160 dev_info(ctrl->device,
161 "Removing ctrl: NQN \"%s\"\n", ctrl->opts->subsysnqn);
163 flush_work(&ctrl->reset_work);
164 nvme_stop_ctrl(ctrl);
165 nvme_remove_namespaces(ctrl);
166 ctrl->ops->delete_ctrl(ctrl);
167 nvme_uninit_ctrl(ctrl);
171 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
173 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
175 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
179 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
181 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
186 * Keep a reference until the work is flushed since ->delete_ctrl
187 * can free the controller.
190 ret = nvme_delete_ctrl(ctrl);
192 flush_work(&ctrl->delete_work);
196 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
198 static inline bool nvme_ns_has_pi(struct nvme_ns *ns)
200 return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple);
203 static blk_status_t nvme_error_status(struct request *req)
205 switch (nvme_req(req)->status & 0x7ff) {
206 case NVME_SC_SUCCESS:
208 case NVME_SC_CAP_EXCEEDED:
209 return BLK_STS_NOSPC;
210 case NVME_SC_LBA_RANGE:
211 return BLK_STS_TARGET;
212 case NVME_SC_BAD_ATTRIBUTES:
213 case NVME_SC_ONCS_NOT_SUPPORTED:
214 case NVME_SC_INVALID_OPCODE:
215 case NVME_SC_INVALID_FIELD:
216 case NVME_SC_INVALID_NS:
217 return BLK_STS_NOTSUPP;
218 case NVME_SC_WRITE_FAULT:
219 case NVME_SC_READ_ERROR:
220 case NVME_SC_UNWRITTEN_BLOCK:
221 case NVME_SC_ACCESS_DENIED:
222 case NVME_SC_READ_ONLY:
223 case NVME_SC_COMPARE_FAILED:
224 return BLK_STS_MEDIUM;
225 case NVME_SC_GUARD_CHECK:
226 case NVME_SC_APPTAG_CHECK:
227 case NVME_SC_REFTAG_CHECK:
228 case NVME_SC_INVALID_PI:
229 return BLK_STS_PROTECTION;
230 case NVME_SC_RESERVATION_CONFLICT:
231 return BLK_STS_NEXUS;
233 return BLK_STS_IOERR;
237 static inline bool nvme_req_needs_retry(struct request *req)
239 if (blk_noretry_request(req))
241 if (nvme_req(req)->status & NVME_SC_DNR)
243 if (nvme_req(req)->retries >= nvme_max_retries)
248 void nvme_complete_rq(struct request *req)
250 blk_status_t status = nvme_error_status(req);
252 trace_nvme_complete_rq(req);
254 if (unlikely(status != BLK_STS_OK && nvme_req_needs_retry(req))) {
255 if (nvme_req_needs_failover(req, status)) {
256 nvme_failover_req(req);
260 if (!blk_queue_dying(req->q)) {
261 nvme_req(req)->retries++;
262 blk_mq_requeue_request(req, true);
266 blk_mq_end_request(req, status);
268 EXPORT_SYMBOL_GPL(nvme_complete_rq);
270 void nvme_cancel_request(struct request *req, void *data, bool reserved)
272 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
273 "Cancelling I/O %d", req->tag);
275 nvme_req(req)->status = NVME_SC_ABORT_REQ;
276 blk_mq_complete_request(req);
279 EXPORT_SYMBOL_GPL(nvme_cancel_request);
281 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
282 enum nvme_ctrl_state new_state)
284 enum nvme_ctrl_state old_state;
286 bool changed = false;
288 spin_lock_irqsave(&ctrl->lock, flags);
290 old_state = ctrl->state;
292 case NVME_CTRL_ADMIN_ONLY:
294 case NVME_CTRL_CONNECTING:
304 case NVME_CTRL_RESETTING:
305 case NVME_CTRL_CONNECTING:
312 case NVME_CTRL_RESETTING:
316 case NVME_CTRL_ADMIN_ONLY:
323 case NVME_CTRL_CONNECTING:
326 case NVME_CTRL_RESETTING:
333 case NVME_CTRL_DELETING:
336 case NVME_CTRL_ADMIN_ONLY:
337 case NVME_CTRL_RESETTING:
338 case NVME_CTRL_CONNECTING:
347 case NVME_CTRL_DELETING:
359 ctrl->state = new_state;
361 spin_unlock_irqrestore(&ctrl->lock, flags);
362 if (changed && ctrl->state == NVME_CTRL_LIVE)
363 nvme_kick_requeue_lists(ctrl);
366 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
368 static void nvme_free_ns_head(struct kref *ref)
370 struct nvme_ns_head *head =
371 container_of(ref, struct nvme_ns_head, ref);
373 nvme_mpath_remove_disk(head);
374 ida_simple_remove(&head->subsys->ns_ida, head->instance);
375 list_del_init(&head->entry);
376 cleanup_srcu_struct_quiesced(&head->srcu);
377 nvme_put_subsystem(head->subsys);
381 static void nvme_put_ns_head(struct nvme_ns_head *head)
383 kref_put(&head->ref, nvme_free_ns_head);
386 static void nvme_free_ns(struct kref *kref)
388 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
391 nvme_nvm_unregister(ns);
394 nvme_put_ns_head(ns->head);
395 nvme_put_ctrl(ns->ctrl);
399 static void nvme_put_ns(struct nvme_ns *ns)
401 kref_put(&ns->kref, nvme_free_ns);
404 static inline void nvme_clear_nvme_request(struct request *req)
406 if (!(req->rq_flags & RQF_DONTPREP)) {
407 nvme_req(req)->retries = 0;
408 nvme_req(req)->flags = 0;
409 req->rq_flags |= RQF_DONTPREP;
413 struct request *nvme_alloc_request(struct request_queue *q,
414 struct nvme_command *cmd, blk_mq_req_flags_t flags, int qid)
416 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
419 if (qid == NVME_QID_ANY) {
420 req = blk_mq_alloc_request(q, op, flags);
422 req = blk_mq_alloc_request_hctx(q, op, flags,
428 req->cmd_flags |= REQ_FAILFAST_DRIVER;
429 nvme_clear_nvme_request(req);
430 nvme_req(req)->cmd = cmd;
434 EXPORT_SYMBOL_GPL(nvme_alloc_request);
436 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
438 struct nvme_command c;
440 memset(&c, 0, sizeof(c));
442 c.directive.opcode = nvme_admin_directive_send;
443 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
444 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
445 c.directive.dtype = NVME_DIR_IDENTIFY;
446 c.directive.tdtype = NVME_DIR_STREAMS;
447 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
449 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
452 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
454 return nvme_toggle_streams(ctrl, false);
457 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
459 return nvme_toggle_streams(ctrl, true);
462 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
463 struct streams_directive_params *s, u32 nsid)
465 struct nvme_command c;
467 memset(&c, 0, sizeof(c));
468 memset(s, 0, sizeof(*s));
470 c.directive.opcode = nvme_admin_directive_recv;
471 c.directive.nsid = cpu_to_le32(nsid);
472 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
473 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
474 c.directive.dtype = NVME_DIR_STREAMS;
476 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
479 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
481 struct streams_directive_params s;
484 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
489 ret = nvme_enable_streams(ctrl);
493 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
497 ctrl->nssa = le16_to_cpu(s.nssa);
498 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
499 dev_info(ctrl->device, "too few streams (%u) available\n",
501 nvme_disable_streams(ctrl);
505 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
506 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
511 * Check if 'req' has a write hint associated with it. If it does, assign
512 * a valid namespace stream to the write.
514 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
515 struct request *req, u16 *control,
518 enum rw_hint streamid = req->write_hint;
520 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
524 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
527 *control |= NVME_RW_DTYPE_STREAMS;
528 *dsmgmt |= streamid << 16;
531 if (streamid < ARRAY_SIZE(req->q->write_hints))
532 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
535 static inline void nvme_setup_flush(struct nvme_ns *ns,
536 struct nvme_command *cmnd)
538 memset(cmnd, 0, sizeof(*cmnd));
539 cmnd->common.opcode = nvme_cmd_flush;
540 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
543 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
544 struct nvme_command *cmnd)
546 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
547 struct nvme_dsm_range *range;
550 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
552 return BLK_STS_RESOURCE;
554 __rq_for_each_bio(bio, req) {
555 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
556 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
559 range[n].cattr = cpu_to_le32(0);
560 range[n].nlb = cpu_to_le32(nlb);
561 range[n].slba = cpu_to_le64(slba);
566 if (WARN_ON_ONCE(n != segments)) {
568 return BLK_STS_IOERR;
571 memset(cmnd, 0, sizeof(*cmnd));
572 cmnd->dsm.opcode = nvme_cmd_dsm;
573 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
574 cmnd->dsm.nr = cpu_to_le32(segments - 1);
575 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
577 req->special_vec.bv_page = virt_to_page(range);
578 req->special_vec.bv_offset = offset_in_page(range);
579 req->special_vec.bv_len = sizeof(*range) * segments;
580 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
585 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
586 struct request *req, struct nvme_command *cmnd)
588 struct nvme_ctrl *ctrl = ns->ctrl;
592 if (req->cmd_flags & REQ_FUA)
593 control |= NVME_RW_FUA;
594 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
595 control |= NVME_RW_LR;
597 if (req->cmd_flags & REQ_RAHEAD)
598 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
600 memset(cmnd, 0, sizeof(*cmnd));
601 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
602 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
603 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
604 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
606 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
607 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
611 * If formated with metadata, the block layer always provides a
612 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
613 * we enable the PRACT bit for protection information or set the
614 * namespace capacity to zero to prevent any I/O.
616 if (!blk_integrity_rq(req)) {
617 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
618 return BLK_STS_NOTSUPP;
619 control |= NVME_RW_PRINFO_PRACT;
622 switch (ns->pi_type) {
623 case NVME_NS_DPS_PI_TYPE3:
624 control |= NVME_RW_PRINFO_PRCHK_GUARD;
626 case NVME_NS_DPS_PI_TYPE1:
627 case NVME_NS_DPS_PI_TYPE2:
628 control |= NVME_RW_PRINFO_PRCHK_GUARD |
629 NVME_RW_PRINFO_PRCHK_REF;
630 cmnd->rw.reftag = cpu_to_le32(
631 nvme_block_nr(ns, blk_rq_pos(req)));
636 cmnd->rw.control = cpu_to_le16(control);
637 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
641 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
642 struct nvme_command *cmd)
644 blk_status_t ret = BLK_STS_OK;
646 nvme_clear_nvme_request(req);
648 switch (req_op(req)) {
651 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
654 nvme_setup_flush(ns, cmd);
656 case REQ_OP_WRITE_ZEROES:
657 /* currently only aliased to deallocate for a few ctrls: */
659 ret = nvme_setup_discard(ns, req, cmd);
663 ret = nvme_setup_rw(ns, req, cmd);
667 return BLK_STS_IOERR;
670 cmd->common.command_id = req->tag;
672 trace_nvme_setup_nvm_cmd(req->q->id, cmd);
674 trace_nvme_setup_admin_cmd(cmd);
677 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
680 * Returns 0 on success. If the result is negative, it's a Linux error code;
681 * if the result is positive, it's an NVM Express status code
683 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
684 union nvme_result *result, void *buffer, unsigned bufflen,
685 unsigned timeout, int qid, int at_head,
686 blk_mq_req_flags_t flags)
691 req = nvme_alloc_request(q, cmd, flags, qid);
695 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
697 if (buffer && bufflen) {
698 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
703 blk_execute_rq(req->q, NULL, req, at_head);
705 *result = nvme_req(req)->result;
706 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
709 ret = nvme_req(req)->status;
711 blk_mq_free_request(req);
714 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
716 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
717 void *buffer, unsigned bufflen)
719 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
722 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
724 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
725 unsigned len, u32 seed, bool write)
727 struct bio_integrity_payload *bip;
731 buf = kmalloc(len, GFP_KERNEL);
736 if (write && copy_from_user(buf, ubuf, len))
739 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
745 bip->bip_iter.bi_size = len;
746 bip->bip_iter.bi_sector = seed;
747 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
748 offset_in_page(buf));
758 static int nvme_submit_user_cmd(struct request_queue *q,
759 struct nvme_command *cmd, void __user *ubuffer,
760 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
761 u32 meta_seed, u32 *result, unsigned timeout)
763 bool write = nvme_is_write(cmd);
764 struct nvme_ns *ns = q->queuedata;
765 struct gendisk *disk = ns ? ns->disk : NULL;
767 struct bio *bio = NULL;
771 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
775 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
776 nvme_req(req)->flags |= NVME_REQ_USERCMD;
778 if (ubuffer && bufflen) {
779 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
785 if (disk && meta_buffer && meta_len) {
786 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
792 req->cmd_flags |= REQ_INTEGRITY;
796 blk_execute_rq(req->q, disk, req, 0);
797 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
800 ret = nvme_req(req)->status;
802 *result = le32_to_cpu(nvme_req(req)->result.u32);
803 if (meta && !ret && !write) {
804 if (copy_to_user(meta_buffer, meta, meta_len))
810 blk_rq_unmap_user(bio);
812 blk_mq_free_request(req);
816 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
818 struct nvme_ctrl *ctrl = rq->end_io_data;
820 blk_mq_free_request(rq);
823 dev_err(ctrl->device,
824 "failed nvme_keep_alive_end_io error=%d\n",
829 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
832 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
836 rq = nvme_alloc_request(ctrl->admin_q, &ctrl->ka_cmd, BLK_MQ_REQ_RESERVED,
841 rq->timeout = ctrl->kato * HZ;
842 rq->end_io_data = ctrl;
844 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
849 static void nvme_keep_alive_work(struct work_struct *work)
851 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
852 struct nvme_ctrl, ka_work);
854 if (nvme_keep_alive(ctrl)) {
855 /* allocation failure, reset the controller */
856 dev_err(ctrl->device, "keep-alive failed\n");
857 nvme_reset_ctrl(ctrl);
862 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
864 if (unlikely(ctrl->kato == 0))
867 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
868 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
869 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
870 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
873 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
875 if (unlikely(ctrl->kato == 0))
878 cancel_delayed_work_sync(&ctrl->ka_work);
880 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
882 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
884 struct nvme_command c = { };
887 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
888 c.identify.opcode = nvme_admin_identify;
889 c.identify.cns = NVME_ID_CNS_CTRL;
891 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
895 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
896 sizeof(struct nvme_id_ctrl));
902 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
903 struct nvme_ns_ids *ids)
905 struct nvme_command c = { };
911 c.identify.opcode = nvme_admin_identify;
912 c.identify.nsid = cpu_to_le32(nsid);
913 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
915 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
919 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
920 NVME_IDENTIFY_DATA_SIZE);
924 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
925 struct nvme_ns_id_desc *cur = data + pos;
931 case NVME_NIDT_EUI64:
932 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
933 dev_warn(ctrl->device,
934 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
938 len = NVME_NIDT_EUI64_LEN;
939 memcpy(ids->eui64, data + pos + sizeof(*cur), len);
941 case NVME_NIDT_NGUID:
942 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
943 dev_warn(ctrl->device,
944 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
948 len = NVME_NIDT_NGUID_LEN;
949 memcpy(ids->nguid, data + pos + sizeof(*cur), len);
952 if (cur->nidl != NVME_NIDT_UUID_LEN) {
953 dev_warn(ctrl->device,
954 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
958 len = NVME_NIDT_UUID_LEN;
959 uuid_copy(&ids->uuid, data + pos + sizeof(*cur));
962 /* Skip unnkown types */
974 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
976 struct nvme_command c = { };
978 c.identify.opcode = nvme_admin_identify;
979 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
980 c.identify.nsid = cpu_to_le32(nsid);
981 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list,
982 NVME_IDENTIFY_DATA_SIZE);
985 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
988 struct nvme_id_ns *id;
989 struct nvme_command c = { };
992 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
993 c.identify.opcode = nvme_admin_identify;
994 c.identify.nsid = cpu_to_le32(nsid);
995 c.identify.cns = NVME_ID_CNS_NS;
997 id = kmalloc(sizeof(*id), GFP_KERNEL);
1001 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
1003 dev_warn(ctrl->device, "Identify namespace failed\n");
1011 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
1012 void *buffer, size_t buflen, u32 *result)
1014 struct nvme_command c;
1015 union nvme_result res;
1018 memset(&c, 0, sizeof(c));
1019 c.features.opcode = nvme_admin_set_features;
1020 c.features.fid = cpu_to_le32(fid);
1021 c.features.dword11 = cpu_to_le32(dword11);
1023 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1024 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
1025 if (ret >= 0 && result)
1026 *result = le32_to_cpu(res.u32);
1030 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1032 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1034 int status, nr_io_queues;
1036 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1042 * Degraded controllers might return an error when setting the queue
1043 * count. We still want to be able to bring them online and offer
1044 * access to the admin queue, as that might be only way to fix them up.
1047 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1050 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1051 *count = min(*count, nr_io_queues);
1056 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1058 #define NVME_AEN_SUPPORTED \
1059 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT)
1061 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1063 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1066 if (!supported_aens)
1069 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1072 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1076 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1078 struct nvme_user_io io;
1079 struct nvme_command c;
1080 unsigned length, meta_len;
1081 void __user *metadata;
1083 if (copy_from_user(&io, uio, sizeof(io)))
1088 switch (io.opcode) {
1089 case nvme_cmd_write:
1091 case nvme_cmd_compare:
1097 length = (io.nblocks + 1) << ns->lba_shift;
1098 meta_len = (io.nblocks + 1) * ns->ms;
1099 metadata = (void __user *)(uintptr_t)io.metadata;
1104 } else if (meta_len) {
1105 if ((io.metadata & 3) || !io.metadata)
1109 memset(&c, 0, sizeof(c));
1110 c.rw.opcode = io.opcode;
1111 c.rw.flags = io.flags;
1112 c.rw.nsid = cpu_to_le32(ns->head->ns_id);
1113 c.rw.slba = cpu_to_le64(io.slba);
1114 c.rw.length = cpu_to_le16(io.nblocks);
1115 c.rw.control = cpu_to_le16(io.control);
1116 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1117 c.rw.reftag = cpu_to_le32(io.reftag);
1118 c.rw.apptag = cpu_to_le16(io.apptag);
1119 c.rw.appmask = cpu_to_le16(io.appmask);
1121 return nvme_submit_user_cmd(ns->queue, &c,
1122 (void __user *)(uintptr_t)io.addr, length,
1123 metadata, meta_len, io.slba, NULL, 0);
1126 static u32 nvme_known_admin_effects(u8 opcode)
1129 case nvme_admin_format_nvm:
1130 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
1131 NVME_CMD_EFFECTS_CSE_MASK;
1132 case nvme_admin_sanitize_nvm:
1133 return NVME_CMD_EFFECTS_CSE_MASK;
1140 static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1147 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1148 if (effects & ~NVME_CMD_EFFECTS_CSUPP)
1149 dev_warn(ctrl->device,
1150 "IO command:%02x has unhandled effects:%08x\n",
1156 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1158 effects = nvme_known_admin_effects(opcode);
1161 * For simplicity, IO to all namespaces is quiesced even if the command
1162 * effects say only one namespace is affected.
1164 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1165 nvme_start_freeze(ctrl);
1166 nvme_wait_freeze(ctrl);
1171 static void nvme_update_formats(struct nvme_ctrl *ctrl)
1175 down_read(&ctrl->namespaces_rwsem);
1176 list_for_each_entry(ns, &ctrl->namespaces, list)
1177 if (ns->disk && nvme_revalidate_disk(ns->disk))
1178 nvme_set_queue_dying(ns);
1179 up_read(&ctrl->namespaces_rwsem);
1181 nvme_remove_invalid_namespaces(ctrl, NVME_NSID_ALL);
1184 static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1187 * Revalidate LBA changes prior to unfreezing. This is necessary to
1188 * prevent memory corruption if a logical block size was changed by
1191 if (effects & NVME_CMD_EFFECTS_LBCC)
1192 nvme_update_formats(ctrl);
1193 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK))
1194 nvme_unfreeze(ctrl);
1195 if (effects & NVME_CMD_EFFECTS_CCC)
1196 nvme_init_identify(ctrl);
1197 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC))
1198 nvme_queue_scan(ctrl);
1201 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1202 struct nvme_passthru_cmd __user *ucmd)
1204 struct nvme_passthru_cmd cmd;
1205 struct nvme_command c;
1206 unsigned timeout = 0;
1210 if (!capable(CAP_SYS_ADMIN))
1212 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1217 memset(&c, 0, sizeof(c));
1218 c.common.opcode = cmd.opcode;
1219 c.common.flags = cmd.flags;
1220 c.common.nsid = cpu_to_le32(cmd.nsid);
1221 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1222 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1223 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1224 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1225 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1226 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1227 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1228 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1231 timeout = msecs_to_jiffies(cmd.timeout_ms);
1233 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1234 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1235 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1236 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata_len,
1237 0, &cmd.result, timeout);
1238 nvme_passthru_end(ctrl, effects);
1241 if (put_user(cmd.result, &ucmd->result))
1249 * Issue ioctl requests on the first available path. Note that unlike normal
1250 * block layer requests we will not retry failed request on another controller.
1252 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk,
1253 struct nvme_ns_head **head, int *srcu_idx)
1255 #ifdef CONFIG_NVME_MULTIPATH
1256 if (disk->fops == &nvme_ns_head_ops) {
1257 *head = disk->private_data;
1258 *srcu_idx = srcu_read_lock(&(*head)->srcu);
1259 return nvme_find_path(*head);
1264 return disk->private_data;
1267 static void nvme_put_ns_from_disk(struct nvme_ns_head *head, int idx)
1270 srcu_read_unlock(&head->srcu, idx);
1273 static int nvme_ns_ioctl(struct nvme_ns *ns, unsigned cmd, unsigned long arg)
1277 force_successful_syscall_return();
1278 return ns->head->ns_id;
1279 case NVME_IOCTL_ADMIN_CMD:
1280 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1281 case NVME_IOCTL_IO_CMD:
1282 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1283 case NVME_IOCTL_SUBMIT_IO:
1284 return nvme_submit_io(ns, (void __user *)arg);
1288 return nvme_nvm_ioctl(ns, cmd, arg);
1290 if (is_sed_ioctl(cmd))
1291 return sed_ioctl(ns->ctrl->opal_dev, cmd,
1292 (void __user *) arg);
1297 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1298 unsigned int cmd, unsigned long arg)
1300 struct nvme_ns_head *head = NULL;
1304 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1308 ret = nvme_ns_ioctl(ns, cmd, arg);
1309 nvme_put_ns_from_disk(head, srcu_idx);
1313 static int nvme_open(struct block_device *bdev, fmode_t mode)
1315 struct nvme_ns *ns = bdev->bd_disk->private_data;
1317 #ifdef CONFIG_NVME_MULTIPATH
1318 /* should never be called due to GENHD_FL_HIDDEN */
1319 if (WARN_ON_ONCE(ns->head->disk))
1322 if (!kref_get_unless_zero(&ns->kref))
1324 if (!try_module_get(ns->ctrl->ops->module))
1335 static void nvme_release(struct gendisk *disk, fmode_t mode)
1337 struct nvme_ns *ns = disk->private_data;
1339 module_put(ns->ctrl->ops->module);
1343 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1345 /* some standard values */
1346 geo->heads = 1 << 6;
1347 geo->sectors = 1 << 5;
1348 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1352 #ifdef CONFIG_BLK_DEV_INTEGRITY
1353 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1355 struct blk_integrity integrity;
1357 memset(&integrity, 0, sizeof(integrity));
1359 case NVME_NS_DPS_PI_TYPE3:
1360 integrity.profile = &t10_pi_type3_crc;
1361 integrity.tag_size = sizeof(u16) + sizeof(u32);
1362 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1364 case NVME_NS_DPS_PI_TYPE1:
1365 case NVME_NS_DPS_PI_TYPE2:
1366 integrity.profile = &t10_pi_type1_crc;
1367 integrity.tag_size = sizeof(u16);
1368 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1371 integrity.profile = NULL;
1374 integrity.tuple_size = ms;
1375 blk_integrity_register(disk, &integrity);
1376 blk_queue_max_integrity_segments(disk->queue, 1);
1379 static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1382 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1384 static void nvme_set_chunk_size(struct nvme_ns *ns)
1386 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1387 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1390 static void nvme_config_discard(struct nvme_ns *ns)
1392 struct nvme_ctrl *ctrl = ns->ctrl;
1393 struct request_queue *queue = ns->queue;
1394 u32 size = queue_logical_block_size(queue);
1396 if (!(ctrl->oncs & NVME_CTRL_ONCS_DSM)) {
1397 blk_queue_flag_clear(QUEUE_FLAG_DISCARD, queue);
1401 if (ctrl->nr_streams && ns->sws && ns->sgs)
1402 size *= ns->sws * ns->sgs;
1404 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1405 NVME_DSM_MAX_RANGES);
1407 queue->limits.discard_alignment = 0;
1408 queue->limits.discard_granularity = size;
1410 /* If discard is already enabled, don't reset queue limits */
1411 if (blk_queue_flag_test_and_set(QUEUE_FLAG_DISCARD, queue))
1414 blk_queue_max_discard_sectors(queue, UINT_MAX);
1415 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1417 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1418 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1421 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1422 struct nvme_id_ns *id, struct nvme_ns_ids *ids)
1424 memset(ids, 0, sizeof(*ids));
1426 if (ctrl->vs >= NVME_VS(1, 1, 0))
1427 memcpy(ids->eui64, id->eui64, sizeof(id->eui64));
1428 if (ctrl->vs >= NVME_VS(1, 2, 0))
1429 memcpy(ids->nguid, id->nguid, sizeof(id->nguid));
1430 if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1431 /* Don't treat error as fatal we potentially
1432 * already have a NGUID or EUI-64
1434 if (nvme_identify_ns_descs(ctrl, nsid, ids))
1435 dev_warn(ctrl->device,
1436 "%s: Identify Descriptors failed\n", __func__);
1440 static bool nvme_ns_ids_valid(struct nvme_ns_ids *ids)
1442 return !uuid_is_null(&ids->uuid) ||
1443 memchr_inv(ids->nguid, 0, sizeof(ids->nguid)) ||
1444 memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
1447 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1449 return uuid_equal(&a->uuid, &b->uuid) &&
1450 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1451 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0;
1454 static void nvme_update_disk_info(struct gendisk *disk,
1455 struct nvme_ns *ns, struct nvme_id_ns *id)
1457 sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9);
1458 unsigned short bs = 1 << ns->lba_shift;
1460 blk_mq_freeze_queue(disk->queue);
1461 blk_integrity_unregister(disk);
1463 blk_queue_logical_block_size(disk->queue, bs);
1464 blk_queue_physical_block_size(disk->queue, bs);
1465 blk_queue_io_min(disk->queue, bs);
1467 if (ns->ms && !ns->ext &&
1468 (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1469 nvme_init_integrity(disk, ns->ms, ns->pi_type);
1470 if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk))
1473 set_capacity(disk, capacity);
1474 nvme_config_discard(ns);
1475 blk_mq_unfreeze_queue(disk->queue);
1478 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1480 struct nvme_ns *ns = disk->private_data;
1483 * If identify namespace failed, use default 512 byte block size so
1484 * block layer can use before failing read/write for 0 capacity.
1486 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1487 if (ns->lba_shift == 0)
1489 ns->noiob = le16_to_cpu(id->noiob);
1490 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1491 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1492 /* the PI implementation requires metadata equal t10 pi tuple size */
1493 if (ns->ms == sizeof(struct t10_pi_tuple))
1494 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1499 nvme_set_chunk_size(ns);
1500 nvme_update_disk_info(disk, ns, id);
1502 nvme_nvm_update_nvm_info(ns);
1503 #ifdef CONFIG_NVME_MULTIPATH
1505 nvme_update_disk_info(ns->head->disk, ns, id);
1509 static int nvme_revalidate_disk(struct gendisk *disk)
1511 struct nvme_ns *ns = disk->private_data;
1512 struct nvme_ctrl *ctrl = ns->ctrl;
1513 struct nvme_id_ns *id;
1514 struct nvme_ns_ids ids;
1517 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1518 set_capacity(disk, 0);
1522 id = nvme_identify_ns(ctrl, ns->head->ns_id);
1526 if (id->ncap == 0) {
1531 __nvme_revalidate_disk(disk, id);
1532 nvme_report_ns_ids(ctrl, ns->head->ns_id, id, &ids);
1533 if (!nvme_ns_ids_equal(&ns->head->ids, &ids)) {
1534 dev_err(ctrl->device,
1535 "identifiers changed for nsid %d\n", ns->head->ns_id);
1544 static char nvme_pr_type(enum pr_type type)
1547 case PR_WRITE_EXCLUSIVE:
1549 case PR_EXCLUSIVE_ACCESS:
1551 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1553 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1555 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1557 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1564 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1565 u64 key, u64 sa_key, u8 op)
1567 struct nvme_ns_head *head = NULL;
1569 struct nvme_command c;
1571 u8 data[16] = { 0, };
1573 ns = nvme_get_ns_from_disk(bdev->bd_disk, &head, &srcu_idx);
1575 return -EWOULDBLOCK;
1577 put_unaligned_le64(key, &data[0]);
1578 put_unaligned_le64(sa_key, &data[8]);
1580 memset(&c, 0, sizeof(c));
1581 c.common.opcode = op;
1582 c.common.nsid = cpu_to_le32(ns->head->ns_id);
1583 c.common.cdw10[0] = cpu_to_le32(cdw10);
1585 ret = nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1586 nvme_put_ns_from_disk(head, srcu_idx);
1590 static int nvme_pr_register(struct block_device *bdev, u64 old,
1591 u64 new, unsigned flags)
1595 if (flags & ~PR_FL_IGNORE_KEY)
1598 cdw10 = old ? 2 : 0;
1599 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1600 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1601 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1604 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1605 enum pr_type type, unsigned flags)
1609 if (flags & ~PR_FL_IGNORE_KEY)
1612 cdw10 = nvme_pr_type(type) << 8;
1613 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1614 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1617 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1618 enum pr_type type, bool abort)
1620 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1621 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1624 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1626 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1627 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1630 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1632 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 1 << 3 : 0);
1633 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1636 static const struct pr_ops nvme_pr_ops = {
1637 .pr_register = nvme_pr_register,
1638 .pr_reserve = nvme_pr_reserve,
1639 .pr_release = nvme_pr_release,
1640 .pr_preempt = nvme_pr_preempt,
1641 .pr_clear = nvme_pr_clear,
1644 #ifdef CONFIG_BLK_SED_OPAL
1645 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1648 struct nvme_ctrl *ctrl = data;
1649 struct nvme_command cmd;
1651 memset(&cmd, 0, sizeof(cmd));
1653 cmd.common.opcode = nvme_admin_security_send;
1655 cmd.common.opcode = nvme_admin_security_recv;
1656 cmd.common.nsid = 0;
1657 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1658 cmd.common.cdw10[1] = cpu_to_le32(len);
1660 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1661 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1663 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1664 #endif /* CONFIG_BLK_SED_OPAL */
1666 static const struct block_device_operations nvme_fops = {
1667 .owner = THIS_MODULE,
1668 .ioctl = nvme_ioctl,
1669 .compat_ioctl = nvme_ioctl,
1671 .release = nvme_release,
1672 .getgeo = nvme_getgeo,
1673 .revalidate_disk= nvme_revalidate_disk,
1674 .pr_ops = &nvme_pr_ops,
1677 #ifdef CONFIG_NVME_MULTIPATH
1678 static int nvme_ns_head_open(struct block_device *bdev, fmode_t mode)
1680 struct nvme_ns_head *head = bdev->bd_disk->private_data;
1682 if (!kref_get_unless_zero(&head->ref))
1687 static void nvme_ns_head_release(struct gendisk *disk, fmode_t mode)
1689 nvme_put_ns_head(disk->private_data);
1692 const struct block_device_operations nvme_ns_head_ops = {
1693 .owner = THIS_MODULE,
1694 .open = nvme_ns_head_open,
1695 .release = nvme_ns_head_release,
1696 .ioctl = nvme_ioctl,
1697 .compat_ioctl = nvme_ioctl,
1698 .getgeo = nvme_getgeo,
1699 .pr_ops = &nvme_pr_ops,
1701 #endif /* CONFIG_NVME_MULTIPATH */
1703 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1705 unsigned long timeout =
1706 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1707 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1710 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1713 if ((csts & NVME_CSTS_RDY) == bit)
1717 if (fatal_signal_pending(current))
1719 if (time_after(jiffies, timeout)) {
1720 dev_err(ctrl->device,
1721 "Device not ready; aborting %s\n", enabled ?
1722 "initialisation" : "reset");
1731 * If the device has been passed off to us in an enabled state, just clear
1732 * the enabled bit. The spec says we should set the 'shutdown notification
1733 * bits', but doing so may cause the device to complete commands to the
1734 * admin queue ... and we don't know what memory that might be pointing at!
1736 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1740 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1741 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1743 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1747 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1748 msleep(NVME_QUIRK_DELAY_AMOUNT);
1750 return nvme_wait_ready(ctrl, cap, false);
1752 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1754 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1757 * Default to a 4K page size, with the intention to update this
1758 * path in the future to accomodate architectures with differing
1759 * kernel and IO page sizes.
1761 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1764 if (page_shift < dev_page_min) {
1765 dev_err(ctrl->device,
1766 "Minimum device page size %u too large for host (%u)\n",
1767 1 << dev_page_min, 1 << page_shift);
1771 ctrl->page_size = 1 << page_shift;
1773 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1774 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1775 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1776 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1777 ctrl->ctrl_config |= NVME_CC_ENABLE;
1779 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1782 return nvme_wait_ready(ctrl, cap, true);
1784 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1786 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1788 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1792 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1793 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1795 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1799 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1800 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1804 if (fatal_signal_pending(current))
1806 if (time_after(jiffies, timeout)) {
1807 dev_err(ctrl->device,
1808 "Device shutdown incomplete; abort shutdown\n");
1815 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1817 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1818 struct request_queue *q)
1822 if (ctrl->max_hw_sectors) {
1824 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1826 max_segments = min_not_zero(max_segments, ctrl->max_segments);
1827 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1828 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1830 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1831 is_power_of_2(ctrl->max_hw_sectors))
1832 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1833 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1834 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1836 blk_queue_write_cache(q, vwc, vwc);
1839 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1844 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1847 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1848 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1851 dev_warn_once(ctrl->device,
1852 "could not set timestamp (%d)\n", ret);
1856 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1859 * APST (Autonomous Power State Transition) lets us program a
1860 * table of power state transitions that the controller will
1861 * perform automatically. We configure it with a simple
1862 * heuristic: we are willing to spend at most 2% of the time
1863 * transitioning between power states. Therefore, when running
1864 * in any given state, we will enter the next lower-power
1865 * non-operational state after waiting 50 * (enlat + exlat)
1866 * microseconds, as long as that state's exit latency is under
1867 * the requested maximum latency.
1869 * We will not autonomously enter any non-operational state for
1870 * which the total latency exceeds ps_max_latency_us. Users
1871 * can set ps_max_latency_us to zero to turn off APST.
1875 struct nvme_feat_auto_pst *table;
1881 * If APST isn't supported or if we haven't been initialized yet,
1882 * then don't do anything.
1887 if (ctrl->npss > 31) {
1888 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1892 table = kzalloc(sizeof(*table), GFP_KERNEL);
1896 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1897 /* Turn off APST. */
1899 dev_dbg(ctrl->device, "APST disabled\n");
1901 __le64 target = cpu_to_le64(0);
1905 * Walk through all states from lowest- to highest-power.
1906 * According to the spec, lower-numbered states use more
1907 * power. NPSS, despite the name, is the index of the
1908 * lowest-power state, not the number of states.
1910 for (state = (int)ctrl->npss; state >= 0; state--) {
1911 u64 total_latency_us, exit_latency_us, transition_ms;
1914 table->entries[state] = target;
1917 * Don't allow transitions to the deepest state
1918 * if it's quirked off.
1920 if (state == ctrl->npss &&
1921 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1925 * Is this state a useful non-operational state for
1926 * higher-power states to autonomously transition to?
1928 if (!(ctrl->psd[state].flags &
1929 NVME_PS_FLAGS_NON_OP_STATE))
1933 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1934 if (exit_latency_us > ctrl->ps_max_latency_us)
1939 le32_to_cpu(ctrl->psd[state].entry_lat);
1942 * This state is good. Use it as the APST idle
1943 * target for higher power states.
1945 transition_ms = total_latency_us + 19;
1946 do_div(transition_ms, 20);
1947 if (transition_ms > (1 << 24) - 1)
1948 transition_ms = (1 << 24) - 1;
1950 target = cpu_to_le64((state << 3) |
1951 (transition_ms << 8));
1956 if (total_latency_us > max_lat_us)
1957 max_lat_us = total_latency_us;
1963 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1965 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1966 max_ps, max_lat_us, (int)sizeof(*table), table);
1970 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1971 table, sizeof(*table), NULL);
1973 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1979 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1981 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1985 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1986 case PM_QOS_LATENCY_ANY:
1994 if (ctrl->ps_max_latency_us != latency) {
1995 ctrl->ps_max_latency_us = latency;
1996 nvme_configure_apst(ctrl);
2000 struct nvme_core_quirk_entry {
2002 * NVMe model and firmware strings are padded with spaces. For
2003 * simplicity, strings in the quirk table are padded with NULLs
2009 unsigned long quirks;
2012 static const struct nvme_core_quirk_entry core_quirks[] = {
2015 * This Toshiba device seems to die using any APST states. See:
2016 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2019 .mn = "THNSF5256GPUK TOSHIBA",
2020 .quirks = NVME_QUIRK_NO_APST,
2024 /* match is null-terminated but idstr is space-padded. */
2025 static bool string_matches(const char *idstr, const char *match, size_t len)
2032 matchlen = strlen(match);
2033 WARN_ON_ONCE(matchlen > len);
2035 if (memcmp(idstr, match, matchlen))
2038 for (; matchlen < len; matchlen++)
2039 if (idstr[matchlen] != ' ')
2045 static bool quirk_matches(const struct nvme_id_ctrl *id,
2046 const struct nvme_core_quirk_entry *q)
2048 return q->vid == le16_to_cpu(id->vid) &&
2049 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2050 string_matches(id->fr, q->fr, sizeof(id->fr));
2053 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2054 struct nvme_id_ctrl *id)
2059 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2060 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2061 strncpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2065 if (ctrl->vs >= NVME_VS(1, 2, 1))
2066 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2068 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
2069 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2070 "nqn.2014.08.org.nvmexpress:%4x%4x",
2071 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2072 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2073 off += sizeof(id->sn);
2074 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2075 off += sizeof(id->mn);
2076 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2079 static void __nvme_release_subsystem(struct nvme_subsystem *subsys)
2081 ida_simple_remove(&nvme_subsystems_ida, subsys->instance);
2085 static void nvme_release_subsystem(struct device *dev)
2087 __nvme_release_subsystem(container_of(dev, struct nvme_subsystem, dev));
2090 static void nvme_destroy_subsystem(struct kref *ref)
2092 struct nvme_subsystem *subsys =
2093 container_of(ref, struct nvme_subsystem, ref);
2095 mutex_lock(&nvme_subsystems_lock);
2096 list_del(&subsys->entry);
2097 mutex_unlock(&nvme_subsystems_lock);
2099 ida_destroy(&subsys->ns_ida);
2100 device_del(&subsys->dev);
2101 put_device(&subsys->dev);
2104 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2106 kref_put(&subsys->ref, nvme_destroy_subsystem);
2109 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2111 struct nvme_subsystem *subsys;
2113 lockdep_assert_held(&nvme_subsystems_lock);
2115 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2116 if (strcmp(subsys->subnqn, subsysnqn))
2118 if (!kref_get_unless_zero(&subsys->ref))
2126 #define SUBSYS_ATTR_RO(_name, _mode, _show) \
2127 struct device_attribute subsys_attr_##_name = \
2128 __ATTR(_name, _mode, _show, NULL)
2130 static ssize_t nvme_subsys_show_nqn(struct device *dev,
2131 struct device_attribute *attr,
2134 struct nvme_subsystem *subsys =
2135 container_of(dev, struct nvme_subsystem, dev);
2137 return snprintf(buf, PAGE_SIZE, "%s\n", subsys->subnqn);
2139 static SUBSYS_ATTR_RO(subsysnqn, S_IRUGO, nvme_subsys_show_nqn);
2141 #define nvme_subsys_show_str_function(field) \
2142 static ssize_t subsys_##field##_show(struct device *dev, \
2143 struct device_attribute *attr, char *buf) \
2145 struct nvme_subsystem *subsys = \
2146 container_of(dev, struct nvme_subsystem, dev); \
2147 return sprintf(buf, "%.*s\n", \
2148 (int)sizeof(subsys->field), subsys->field); \
2150 static SUBSYS_ATTR_RO(field, S_IRUGO, subsys_##field##_show);
2152 nvme_subsys_show_str_function(model);
2153 nvme_subsys_show_str_function(serial);
2154 nvme_subsys_show_str_function(firmware_rev);
2156 static struct attribute *nvme_subsys_attrs[] = {
2157 &subsys_attr_model.attr,
2158 &subsys_attr_serial.attr,
2159 &subsys_attr_firmware_rev.attr,
2160 &subsys_attr_subsysnqn.attr,
2164 static struct attribute_group nvme_subsys_attrs_group = {
2165 .attrs = nvme_subsys_attrs,
2168 static const struct attribute_group *nvme_subsys_attrs_groups[] = {
2169 &nvme_subsys_attrs_group,
2173 static int nvme_active_ctrls(struct nvme_subsystem *subsys)
2176 struct nvme_ctrl *ctrl;
2178 mutex_lock(&subsys->lock);
2179 list_for_each_entry(ctrl, &subsys->ctrls, subsys_entry) {
2180 if (ctrl->state != NVME_CTRL_DELETING &&
2181 ctrl->state != NVME_CTRL_DEAD)
2184 mutex_unlock(&subsys->lock);
2189 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2191 struct nvme_subsystem *subsys, *found;
2194 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2197 ret = ida_simple_get(&nvme_subsystems_ida, 0, 0, GFP_KERNEL);
2202 subsys->instance = ret;
2203 mutex_init(&subsys->lock);
2204 kref_init(&subsys->ref);
2205 INIT_LIST_HEAD(&subsys->ctrls);
2206 INIT_LIST_HEAD(&subsys->nsheads);
2207 nvme_init_subnqn(subsys, ctrl, id);
2208 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2209 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2210 memcpy(subsys->firmware_rev, id->fr, sizeof(subsys->firmware_rev));
2211 subsys->vendor_id = le16_to_cpu(id->vid);
2212 subsys->cmic = id->cmic;
2214 subsys->dev.class = nvme_subsys_class;
2215 subsys->dev.release = nvme_release_subsystem;
2216 subsys->dev.groups = nvme_subsys_attrs_groups;
2217 dev_set_name(&subsys->dev, "nvme-subsys%d", subsys->instance);
2218 device_initialize(&subsys->dev);
2220 mutex_lock(&nvme_subsystems_lock);
2221 found = __nvme_find_get_subsystem(subsys->subnqn);
2224 * Verify that the subsystem actually supports multiple
2225 * controllers, else bail out.
2227 if (!(ctrl->opts && ctrl->opts->discovery_nqn) &&
2228 nvme_active_ctrls(found) && !(id->cmic & (1 << 1))) {
2229 dev_err(ctrl->device,
2230 "ignoring ctrl due to duplicate subnqn (%s).\n",
2232 nvme_put_subsystem(found);
2237 __nvme_release_subsystem(subsys);
2240 ret = device_add(&subsys->dev);
2242 dev_err(ctrl->device,
2243 "failed to register subsystem device.\n");
2246 ida_init(&subsys->ns_ida);
2247 list_add_tail(&subsys->entry, &nvme_subsystems);
2250 ctrl->subsys = subsys;
2251 mutex_unlock(&nvme_subsystems_lock);
2253 if (sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2254 dev_name(ctrl->device))) {
2255 dev_err(ctrl->device,
2256 "failed to create sysfs link from subsystem.\n");
2257 /* the transport driver will eventually put the subsystem */
2261 mutex_lock(&subsys->lock);
2262 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2263 mutex_unlock(&subsys->lock);
2268 mutex_unlock(&nvme_subsystems_lock);
2269 put_device(&subsys->dev);
2273 int nvme_get_log_ext(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
2274 u8 log_page, void *log,
2275 size_t size, u64 offset)
2277 struct nvme_command c = { };
2278 unsigned long dwlen = size / 4 - 1;
2280 c.get_log_page.opcode = nvme_admin_get_log_page;
2283 c.get_log_page.nsid = cpu_to_le32(ns->head->ns_id);
2285 c.get_log_page.nsid = cpu_to_le32(NVME_NSID_ALL);
2287 c.get_log_page.lid = log_page;
2288 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2289 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2290 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2291 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2293 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2296 static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log,
2299 return nvme_get_log_ext(ctrl, NULL, log_page, log, size, 0);
2302 static int nvme_get_effects_log(struct nvme_ctrl *ctrl)
2307 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL);
2312 ret = nvme_get_log(ctrl, NVME_LOG_CMD_EFFECTS, ctrl->effects,
2313 sizeof(*ctrl->effects));
2315 kfree(ctrl->effects);
2316 ctrl->effects = NULL;
2322 * Initialize the cached copies of the Identify data and various controller
2323 * register in our nvme_ctrl structure. This should be called as soon as
2324 * the admin queue is fully up and running.
2326 int nvme_init_identify(struct nvme_ctrl *ctrl)
2328 struct nvme_id_ctrl *id;
2330 int ret, page_shift;
2332 bool prev_apst_enabled;
2334 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
2336 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
2340 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
2342 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2345 page_shift = NVME_CAP_MPSMIN(cap) + 12;
2347 if (ctrl->vs >= NVME_VS(1, 1, 0))
2348 ctrl->subsystem = NVME_CAP_NSSRC(cap);
2350 ret = nvme_identify_ctrl(ctrl, &id);
2352 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
2356 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
2357 ret = nvme_get_effects_log(ctrl);
2362 if (!ctrl->identified) {
2365 ret = nvme_init_subsystem(ctrl, id);
2370 * Check for quirks. Quirk can depend on firmware version,
2371 * so, in principle, the set of quirks present can change
2372 * across a reset. As a possible future enhancement, we
2373 * could re-scan for quirks every time we reinitialize
2374 * the device, but we'd have to make sure that the driver
2375 * behaves intelligently if the quirks change.
2377 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
2378 if (quirk_matches(id, &core_quirks[i]))
2379 ctrl->quirks |= core_quirks[i].quirks;
2383 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
2384 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
2385 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
2388 ctrl->oacs = le16_to_cpu(id->oacs);
2389 ctrl->oncs = le16_to_cpup(&id->oncs);
2390 ctrl->oaes = le32_to_cpu(id->oaes);
2391 atomic_set(&ctrl->abort_limit, id->acl + 1);
2392 ctrl->vwc = id->vwc;
2393 ctrl->cntlid = le16_to_cpup(&id->cntlid);
2395 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
2397 max_hw_sectors = UINT_MAX;
2398 ctrl->max_hw_sectors =
2399 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
2401 nvme_set_queue_limits(ctrl, ctrl->admin_q);
2402 ctrl->sgls = le32_to_cpu(id->sgls);
2403 ctrl->kas = le16_to_cpu(id->kas);
2407 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
2409 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
2410 shutdown_timeout, 60);
2412 if (ctrl->shutdown_timeout != shutdown_timeout)
2413 dev_info(ctrl->device,
2414 "Shutdown timeout set to %u seconds\n",
2415 ctrl->shutdown_timeout);
2417 ctrl->shutdown_timeout = shutdown_timeout;
2419 ctrl->npss = id->npss;
2420 ctrl->apsta = id->apsta;
2421 prev_apst_enabled = ctrl->apst_enabled;
2422 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
2423 if (force_apst && id->apsta) {
2424 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
2425 ctrl->apst_enabled = true;
2427 ctrl->apst_enabled = false;
2430 ctrl->apst_enabled = id->apsta;
2432 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
2434 if (ctrl->ops->flags & NVME_F_FABRICS) {
2435 ctrl->icdoff = le16_to_cpu(id->icdoff);
2436 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
2437 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
2438 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
2441 * In fabrics we need to verify the cntlid matches the
2444 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
2449 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
2450 dev_err(ctrl->device,
2451 "keep-alive support is mandatory for fabrics\n");
2456 ctrl->cntlid = le16_to_cpu(id->cntlid);
2457 ctrl->hmpre = le32_to_cpu(id->hmpre);
2458 ctrl->hmmin = le32_to_cpu(id->hmmin);
2459 ctrl->hmminds = le32_to_cpu(id->hmminds);
2460 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
2465 if (ctrl->apst_enabled && !prev_apst_enabled)
2466 dev_pm_qos_expose_latency_tolerance(ctrl->device);
2467 else if (!ctrl->apst_enabled && prev_apst_enabled)
2468 dev_pm_qos_hide_latency_tolerance(ctrl->device);
2470 ret = nvme_configure_apst(ctrl);
2474 ret = nvme_configure_timestamp(ctrl);
2478 ret = nvme_configure_directives(ctrl);
2482 ctrl->identified = true;
2490 EXPORT_SYMBOL_GPL(nvme_init_identify);
2492 static int nvme_dev_open(struct inode *inode, struct file *file)
2494 struct nvme_ctrl *ctrl =
2495 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
2497 switch (ctrl->state) {
2498 case NVME_CTRL_LIVE:
2499 case NVME_CTRL_ADMIN_ONLY:
2502 return -EWOULDBLOCK;
2505 file->private_data = ctrl;
2509 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
2514 down_read(&ctrl->namespaces_rwsem);
2515 if (list_empty(&ctrl->namespaces)) {
2520 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
2521 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
2522 dev_warn(ctrl->device,
2523 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
2528 dev_warn(ctrl->device,
2529 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
2530 kref_get(&ns->kref);
2531 up_read(&ctrl->namespaces_rwsem);
2533 ret = nvme_user_cmd(ctrl, ns, argp);
2538 up_read(&ctrl->namespaces_rwsem);
2542 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
2545 struct nvme_ctrl *ctrl = file->private_data;
2546 void __user *argp = (void __user *)arg;
2549 case NVME_IOCTL_ADMIN_CMD:
2550 return nvme_user_cmd(ctrl, NULL, argp);
2551 case NVME_IOCTL_IO_CMD:
2552 return nvme_dev_user_cmd(ctrl, argp);
2553 case NVME_IOCTL_RESET:
2554 dev_warn(ctrl->device, "resetting controller\n");
2555 return nvme_reset_ctrl_sync(ctrl);
2556 case NVME_IOCTL_SUBSYS_RESET:
2557 return nvme_reset_subsystem(ctrl);
2558 case NVME_IOCTL_RESCAN:
2559 nvme_queue_scan(ctrl);
2566 static const struct file_operations nvme_dev_fops = {
2567 .owner = THIS_MODULE,
2568 .open = nvme_dev_open,
2569 .unlocked_ioctl = nvme_dev_ioctl,
2570 .compat_ioctl = nvme_dev_ioctl,
2573 static ssize_t nvme_sysfs_reset(struct device *dev,
2574 struct device_attribute *attr, const char *buf,
2577 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2580 ret = nvme_reset_ctrl_sync(ctrl);
2585 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2587 static ssize_t nvme_sysfs_rescan(struct device *dev,
2588 struct device_attribute *attr, const char *buf,
2591 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2593 nvme_queue_scan(ctrl);
2596 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2598 static inline struct nvme_ns_head *dev_to_ns_head(struct device *dev)
2600 struct gendisk *disk = dev_to_disk(dev);
2602 if (disk->fops == &nvme_fops)
2603 return nvme_get_ns_from_dev(dev)->head;
2605 return disk->private_data;
2608 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2611 struct nvme_ns_head *head = dev_to_ns_head(dev);
2612 struct nvme_ns_ids *ids = &head->ids;
2613 struct nvme_subsystem *subsys = head->subsys;
2614 int serial_len = sizeof(subsys->serial);
2615 int model_len = sizeof(subsys->model);
2617 if (!uuid_is_null(&ids->uuid))
2618 return sprintf(buf, "uuid.%pU\n", &ids->uuid);
2620 if (memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2621 return sprintf(buf, "eui.%16phN\n", ids->nguid);
2623 if (memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2624 return sprintf(buf, "eui.%8phN\n", ids->eui64);
2626 while (serial_len > 0 && (subsys->serial[serial_len - 1] == ' ' ||
2627 subsys->serial[serial_len - 1] == '\0'))
2629 while (model_len > 0 && (subsys->model[model_len - 1] == ' ' ||
2630 subsys->model[model_len - 1] == '\0'))
2633 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", subsys->vendor_id,
2634 serial_len, subsys->serial, model_len, subsys->model,
2637 static DEVICE_ATTR_RO(wwid);
2639 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2642 return sprintf(buf, "%pU\n", dev_to_ns_head(dev)->ids.nguid);
2644 static DEVICE_ATTR_RO(nguid);
2646 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2649 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2651 /* For backward compatibility expose the NGUID to userspace if
2652 * we have no UUID set
2654 if (uuid_is_null(&ids->uuid)) {
2655 printk_ratelimited(KERN_WARNING
2656 "No UUID available providing old NGUID\n");
2657 return sprintf(buf, "%pU\n", ids->nguid);
2659 return sprintf(buf, "%pU\n", &ids->uuid);
2661 static DEVICE_ATTR_RO(uuid);
2663 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2666 return sprintf(buf, "%8ph\n", dev_to_ns_head(dev)->ids.eui64);
2668 static DEVICE_ATTR_RO(eui);
2670 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2673 return sprintf(buf, "%d\n", dev_to_ns_head(dev)->ns_id);
2675 static DEVICE_ATTR_RO(nsid);
2677 static struct attribute *nvme_ns_id_attrs[] = {
2678 &dev_attr_wwid.attr,
2679 &dev_attr_uuid.attr,
2680 &dev_attr_nguid.attr,
2682 &dev_attr_nsid.attr,
2686 static umode_t nvme_ns_id_attrs_are_visible(struct kobject *kobj,
2687 struct attribute *a, int n)
2689 struct device *dev = container_of(kobj, struct device, kobj);
2690 struct nvme_ns_ids *ids = &dev_to_ns_head(dev)->ids;
2692 if (a == &dev_attr_uuid.attr) {
2693 if (uuid_is_null(&ids->uuid) &&
2694 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2697 if (a == &dev_attr_nguid.attr) {
2698 if (!memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
2701 if (a == &dev_attr_eui.attr) {
2702 if (!memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
2708 const struct attribute_group nvme_ns_id_attr_group = {
2709 .attrs = nvme_ns_id_attrs,
2710 .is_visible = nvme_ns_id_attrs_are_visible,
2713 #define nvme_show_str_function(field) \
2714 static ssize_t field##_show(struct device *dev, \
2715 struct device_attribute *attr, char *buf) \
2717 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2718 return sprintf(buf, "%.*s\n", \
2719 (int)sizeof(ctrl->subsys->field), ctrl->subsys->field); \
2721 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2723 nvme_show_str_function(model);
2724 nvme_show_str_function(serial);
2725 nvme_show_str_function(firmware_rev);
2727 #define nvme_show_int_function(field) \
2728 static ssize_t field##_show(struct device *dev, \
2729 struct device_attribute *attr, char *buf) \
2731 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2732 return sprintf(buf, "%d\n", ctrl->field); \
2734 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2736 nvme_show_int_function(cntlid);
2738 static ssize_t nvme_sysfs_delete(struct device *dev,
2739 struct device_attribute *attr, const char *buf,
2742 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2744 if (device_remove_file_self(dev, attr))
2745 nvme_delete_ctrl_sync(ctrl);
2748 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2750 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2751 struct device_attribute *attr,
2754 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2756 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2758 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2760 static ssize_t nvme_sysfs_show_state(struct device *dev,
2761 struct device_attribute *attr,
2764 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2765 static const char *const state_name[] = {
2766 [NVME_CTRL_NEW] = "new",
2767 [NVME_CTRL_LIVE] = "live",
2768 [NVME_CTRL_ADMIN_ONLY] = "only-admin",
2769 [NVME_CTRL_RESETTING] = "resetting",
2770 [NVME_CTRL_CONNECTING] = "connecting",
2771 [NVME_CTRL_DELETING] = "deleting",
2772 [NVME_CTRL_DEAD] = "dead",
2775 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2776 state_name[ctrl->state])
2777 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2779 return sprintf(buf, "unknown state\n");
2782 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2784 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2785 struct device_attribute *attr,
2788 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2790 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subsys->subnqn);
2792 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2794 static ssize_t nvme_sysfs_show_address(struct device *dev,
2795 struct device_attribute *attr,
2798 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2800 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2802 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2804 static struct attribute *nvme_dev_attrs[] = {
2805 &dev_attr_reset_controller.attr,
2806 &dev_attr_rescan_controller.attr,
2807 &dev_attr_model.attr,
2808 &dev_attr_serial.attr,
2809 &dev_attr_firmware_rev.attr,
2810 &dev_attr_cntlid.attr,
2811 &dev_attr_delete_controller.attr,
2812 &dev_attr_transport.attr,
2813 &dev_attr_subsysnqn.attr,
2814 &dev_attr_address.attr,
2815 &dev_attr_state.attr,
2819 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2820 struct attribute *a, int n)
2822 struct device *dev = container_of(kobj, struct device, kobj);
2823 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2825 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2827 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2833 static struct attribute_group nvme_dev_attrs_group = {
2834 .attrs = nvme_dev_attrs,
2835 .is_visible = nvme_dev_attrs_are_visible,
2838 static const struct attribute_group *nvme_dev_attr_groups[] = {
2839 &nvme_dev_attrs_group,
2843 static struct nvme_ns_head *__nvme_find_ns_head(struct nvme_subsystem *subsys,
2846 struct nvme_ns_head *h;
2848 lockdep_assert_held(&subsys->lock);
2850 list_for_each_entry(h, &subsys->nsheads, entry) {
2851 if (h->ns_id == nsid && kref_get_unless_zero(&h->ref))
2858 static int __nvme_check_ids(struct nvme_subsystem *subsys,
2859 struct nvme_ns_head *new)
2861 struct nvme_ns_head *h;
2863 lockdep_assert_held(&subsys->lock);
2865 list_for_each_entry(h, &subsys->nsheads, entry) {
2866 if (nvme_ns_ids_valid(&new->ids) &&
2867 !list_empty(&h->list) &&
2868 nvme_ns_ids_equal(&new->ids, &h->ids))
2875 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
2876 unsigned nsid, struct nvme_id_ns *id)
2878 struct nvme_ns_head *head;
2881 head = kzalloc(sizeof(*head), GFP_KERNEL);
2884 ret = ida_simple_get(&ctrl->subsys->ns_ida, 1, 0, GFP_KERNEL);
2887 head->instance = ret;
2888 INIT_LIST_HEAD(&head->list);
2889 ret = init_srcu_struct(&head->srcu);
2891 goto out_ida_remove;
2892 head->subsys = ctrl->subsys;
2894 kref_init(&head->ref);
2896 nvme_report_ns_ids(ctrl, nsid, id, &head->ids);
2898 ret = __nvme_check_ids(ctrl->subsys, head);
2900 dev_err(ctrl->device,
2901 "duplicate IDs for nsid %d\n", nsid);
2902 goto out_cleanup_srcu;
2905 ret = nvme_mpath_alloc_disk(ctrl, head);
2907 goto out_cleanup_srcu;
2909 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
2911 kref_get(&ctrl->subsys->ref);
2915 cleanup_srcu_struct(&head->srcu);
2917 ida_simple_remove(&ctrl->subsys->ns_ida, head->instance);
2921 return ERR_PTR(ret);
2924 static int nvme_init_ns_head(struct nvme_ns *ns, unsigned nsid,
2925 struct nvme_id_ns *id)
2927 struct nvme_ctrl *ctrl = ns->ctrl;
2928 bool is_shared = id->nmic & (1 << 0);
2929 struct nvme_ns_head *head = NULL;
2932 mutex_lock(&ctrl->subsys->lock);
2934 head = __nvme_find_ns_head(ctrl->subsys, nsid);
2936 head = nvme_alloc_ns_head(ctrl, nsid, id);
2938 ret = PTR_ERR(head);
2942 struct nvme_ns_ids ids;
2944 nvme_report_ns_ids(ctrl, nsid, id, &ids);
2945 if (!nvme_ns_ids_equal(&head->ids, &ids)) {
2946 dev_err(ctrl->device,
2947 "IDs don't match for shared namespace %d\n",
2954 list_add_tail(&ns->siblings, &head->list);
2958 mutex_unlock(&ctrl->subsys->lock);
2962 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2964 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2965 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2967 return nsa->head->ns_id - nsb->head->ns_id;
2970 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2972 struct nvme_ns *ns, *ret = NULL;
2974 down_read(&ctrl->namespaces_rwsem);
2975 list_for_each_entry(ns, &ctrl->namespaces, list) {
2976 if (ns->head->ns_id == nsid) {
2977 if (!kref_get_unless_zero(&ns->kref))
2982 if (ns->head->ns_id > nsid)
2985 up_read(&ctrl->namespaces_rwsem);
2989 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2991 struct streams_directive_params s;
2994 if (!ctrl->nr_streams)
2997 ret = nvme_get_stream_params(ctrl, &s, ns->head->ns_id);
3001 ns->sws = le32_to_cpu(s.sws);
3002 ns->sgs = le16_to_cpu(s.sgs);
3005 unsigned int bs = 1 << ns->lba_shift;
3007 blk_queue_io_min(ns->queue, bs * ns->sws);
3009 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
3015 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3018 struct gendisk *disk;
3019 struct nvme_id_ns *id;
3020 char disk_name[DISK_NAME_LEN];
3021 int node = dev_to_node(ctrl->dev), flags = GENHD_FL_EXT_DEVT;
3023 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3027 ns->queue = blk_mq_init_queue(ctrl->tagset);
3028 if (IS_ERR(ns->queue))
3030 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3031 ns->queue->queuedata = ns;
3034 kref_init(&ns->kref);
3035 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
3037 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
3038 nvme_set_queue_limits(ctrl, ns->queue);
3040 id = nvme_identify_ns(ctrl, nsid);
3042 goto out_free_queue;
3047 if (nvme_init_ns_head(ns, nsid, id))
3049 nvme_setup_streams_ns(ctrl, ns);
3050 nvme_set_disk_name(disk_name, ns, ctrl, &flags);
3052 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
3053 if (nvme_nvm_register(ns, disk_name, node)) {
3054 dev_warn(ctrl->device, "LightNVM init failure\n");
3059 disk = alloc_disk_node(0, node);
3063 disk->fops = &nvme_fops;
3064 disk->private_data = ns;
3065 disk->queue = ns->queue;
3066 disk->flags = flags;
3067 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
3070 __nvme_revalidate_disk(disk, id);
3072 down_write(&ctrl->namespaces_rwsem);
3073 list_add_tail(&ns->list, &ctrl->namespaces);
3074 up_write(&ctrl->namespaces_rwsem);
3076 nvme_get_ctrl(ctrl);
3080 device_add_disk(ctrl->device, ns->disk);
3081 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
3082 &nvme_ns_id_attr_group))
3083 pr_warn("%s: failed to create sysfs group for identification\n",
3084 ns->disk->disk_name);
3085 if (ns->ndev && nvme_nvm_register_sysfs(ns))
3086 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
3087 ns->disk->disk_name);
3089 nvme_mpath_add_disk(ns->head);
3090 nvme_fault_inject_init(ns);
3093 mutex_lock(&ctrl->subsys->lock);
3094 list_del_rcu(&ns->siblings);
3095 mutex_unlock(&ctrl->subsys->lock);
3099 blk_cleanup_queue(ns->queue);
3104 static void nvme_ns_remove(struct nvme_ns *ns)
3106 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3109 nvme_fault_inject_fini(ns);
3110 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
3111 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
3112 &nvme_ns_id_attr_group);
3114 nvme_nvm_unregister_sysfs(ns);
3115 del_gendisk(ns->disk);
3116 blk_cleanup_queue(ns->queue);
3117 if (blk_get_integrity(ns->disk))
3118 blk_integrity_unregister(ns->disk);
3121 mutex_lock(&ns->ctrl->subsys->lock);
3122 nvme_mpath_clear_current_path(ns);
3123 list_del_rcu(&ns->siblings);
3124 mutex_unlock(&ns->ctrl->subsys->lock);
3126 down_write(&ns->ctrl->namespaces_rwsem);
3127 list_del_init(&ns->list);
3128 up_write(&ns->ctrl->namespaces_rwsem);
3130 synchronize_srcu(&ns->head->srcu);
3131 nvme_mpath_check_last_path(ns);
3135 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3139 ns = nvme_find_get_ns(ctrl, nsid);
3141 if (ns->disk && revalidate_disk(ns->disk))
3145 nvme_alloc_ns(ctrl, nsid);
3148 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3151 struct nvme_ns *ns, *next;
3154 down_write(&ctrl->namespaces_rwsem);
3155 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3156 if (ns->head->ns_id > nsid || test_bit(NVME_NS_DEAD, &ns->flags))
3157 list_move_tail(&ns->list, &rm_list);
3159 up_write(&ctrl->namespaces_rwsem);
3161 list_for_each_entry_safe(ns, next, &rm_list, list)
3166 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
3170 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
3173 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3177 for (i = 0; i < num_lists; i++) {
3178 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
3182 for (j = 0; j < min(nn, 1024U); j++) {
3183 nsid = le32_to_cpu(ns_list[j]);
3187 nvme_validate_ns(ctrl, nsid);
3189 while (++prev < nsid) {
3190 ns = nvme_find_get_ns(ctrl, prev);
3200 nvme_remove_invalid_namespaces(ctrl, prev);
3206 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
3210 for (i = 1; i <= nn; i++)
3211 nvme_validate_ns(ctrl, i);
3213 nvme_remove_invalid_namespaces(ctrl, nn);
3216 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
3218 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
3222 log = kzalloc(log_size, GFP_KERNEL);
3227 * We need to read the log to clear the AEN, but we don't want to rely
3228 * on it for the changed namespace information as userspace could have
3229 * raced with us in reading the log page, which could cause us to miss
3232 error = nvme_get_log(ctrl, NVME_LOG_CHANGED_NS, log, log_size);
3234 dev_warn(ctrl->device,
3235 "reading changed ns log failed: %d\n", error);
3240 static void nvme_scan_work(struct work_struct *work)
3242 struct nvme_ctrl *ctrl =
3243 container_of(work, struct nvme_ctrl, scan_work);
3244 struct nvme_id_ctrl *id;
3247 if (ctrl->state != NVME_CTRL_LIVE)
3250 WARN_ON_ONCE(!ctrl->tagset);
3252 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
3253 dev_info(ctrl->device, "rescanning namespaces.\n");
3254 nvme_clear_changed_ns_log(ctrl);
3257 if (nvme_identify_ctrl(ctrl, &id))
3260 nn = le32_to_cpu(id->nn);
3261 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
3262 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
3263 if (!nvme_scan_ns_list(ctrl, nn))
3266 nvme_scan_ns_sequential(ctrl, nn);
3269 down_write(&ctrl->namespaces_rwsem);
3270 list_sort(NULL, &ctrl->namespaces, ns_cmp);
3271 up_write(&ctrl->namespaces_rwsem);
3275 * This function iterates the namespace list unlocked to allow recovery from
3276 * controller failure. It is up to the caller to ensure the namespace list is
3277 * not modified by scan work while this function is executing.
3279 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3281 struct nvme_ns *ns, *next;
3285 * The dead states indicates the controller was not gracefully
3286 * disconnected. In that case, we won't be able to flush any data while
3287 * removing the namespaces' disks; fail all the queues now to avoid
3288 * potentially having to clean up the failed sync later.