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>
31 #include <asm/unaligned.h>
36 #define NVME_MINORS (1U << MINORBITS)
38 unsigned char admin_timeout = 60;
39 module_param(admin_timeout, byte, 0644);
40 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
41 EXPORT_SYMBOL_GPL(admin_timeout);
43 unsigned char nvme_io_timeout = 30;
44 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
45 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
46 EXPORT_SYMBOL_GPL(nvme_io_timeout);
48 unsigned char shutdown_timeout = 5;
49 module_param(shutdown_timeout, byte, 0644);
50 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
52 static u8 nvme_max_retries = 5;
53 module_param_named(max_retries, nvme_max_retries, byte, 0644);
54 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
56 static int nvme_char_major;
57 module_param(nvme_char_major, int, 0);
59 static unsigned long default_ps_max_latency_us = 100000;
60 module_param(default_ps_max_latency_us, ulong, 0644);
61 MODULE_PARM_DESC(default_ps_max_latency_us,
62 "max power saving latency for new devices; use PM QOS to change per device");
64 static bool force_apst;
65 module_param(force_apst, bool, 0644);
66 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
68 struct workqueue_struct *nvme_wq;
69 EXPORT_SYMBOL_GPL(nvme_wq);
71 static LIST_HEAD(nvme_ctrl_list);
72 static DEFINE_SPINLOCK(dev_list_lock);
74 static struct class *nvme_class;
76 static blk_status_t nvme_error_status(struct request *req)
78 switch (nvme_req(req)->status & 0x7ff) {
81 case NVME_SC_CAP_EXCEEDED:
83 case NVME_SC_ONCS_NOT_SUPPORTED:
84 return BLK_STS_NOTSUPP;
85 case NVME_SC_WRITE_FAULT:
86 case NVME_SC_READ_ERROR:
87 case NVME_SC_UNWRITTEN_BLOCK:
88 return BLK_STS_MEDIUM;
94 static inline bool nvme_req_needs_retry(struct request *req)
96 if (blk_noretry_request(req))
98 if (nvme_req(req)->status & NVME_SC_DNR)
100 if (jiffies - req->start_time >= req->timeout)
102 if (nvme_req(req)->retries >= nvme_max_retries)
107 void nvme_complete_rq(struct request *req)
109 if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
110 nvme_req(req)->retries++;
111 blk_mq_requeue_request(req, !blk_mq_queue_stopped(req->q));
115 blk_mq_end_request(req, nvme_error_status(req));
117 EXPORT_SYMBOL_GPL(nvme_complete_rq);
119 void nvme_cancel_request(struct request *req, void *data, bool reserved)
123 if (!blk_mq_request_started(req))
126 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
127 "Cancelling I/O %d", req->tag);
129 status = NVME_SC_ABORT_REQ;
130 if (blk_queue_dying(req->q))
131 status |= NVME_SC_DNR;
132 nvme_req(req)->status = status;
133 blk_mq_complete_request(req);
136 EXPORT_SYMBOL_GPL(nvme_cancel_request);
138 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
139 enum nvme_ctrl_state new_state)
141 enum nvme_ctrl_state old_state;
142 bool changed = false;
144 spin_lock_irq(&ctrl->lock);
146 old_state = ctrl->state;
151 case NVME_CTRL_RESETTING:
152 case NVME_CTRL_RECONNECTING:
159 case NVME_CTRL_RESETTING:
169 case NVME_CTRL_RECONNECTING:
178 case NVME_CTRL_DELETING:
181 case NVME_CTRL_RESETTING:
182 case NVME_CTRL_RECONNECTING:
191 case NVME_CTRL_DELETING:
203 ctrl->state = new_state;
205 spin_unlock_irq(&ctrl->lock);
209 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
211 static void nvme_free_ns(struct kref *kref)
213 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
216 nvme_nvm_unregister(ns);
219 spin_lock(&dev_list_lock);
220 ns->disk->private_data = NULL;
221 spin_unlock(&dev_list_lock);
225 ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
226 nvme_put_ctrl(ns->ctrl);
230 static void nvme_put_ns(struct nvme_ns *ns)
232 kref_put(&ns->kref, nvme_free_ns);
235 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
239 spin_lock(&dev_list_lock);
240 ns = disk->private_data;
242 if (!kref_get_unless_zero(&ns->kref))
244 if (!try_module_get(ns->ctrl->ops->module))
247 spin_unlock(&dev_list_lock);
252 kref_put(&ns->kref, nvme_free_ns);
254 spin_unlock(&dev_list_lock);
258 struct request *nvme_alloc_request(struct request_queue *q,
259 struct nvme_command *cmd, unsigned int flags, int qid)
261 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
264 if (qid == NVME_QID_ANY) {
265 req = blk_mq_alloc_request(q, op, flags);
267 req = blk_mq_alloc_request_hctx(q, op, flags,
273 req->cmd_flags |= REQ_FAILFAST_DRIVER;
274 nvme_req(req)->cmd = cmd;
278 EXPORT_SYMBOL_GPL(nvme_alloc_request);
280 static inline void nvme_setup_flush(struct nvme_ns *ns,
281 struct nvme_command *cmnd)
283 memset(cmnd, 0, sizeof(*cmnd));
284 cmnd->common.opcode = nvme_cmd_flush;
285 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
288 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
289 struct nvme_command *cmnd)
291 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
292 struct nvme_dsm_range *range;
295 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
297 return BLK_STS_RESOURCE;
299 __rq_for_each_bio(bio, req) {
300 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
301 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
303 range[n].cattr = cpu_to_le32(0);
304 range[n].nlb = cpu_to_le32(nlb);
305 range[n].slba = cpu_to_le64(slba);
309 if (WARN_ON_ONCE(n != segments)) {
311 return BLK_STS_IOERR;
314 memset(cmnd, 0, sizeof(*cmnd));
315 cmnd->dsm.opcode = nvme_cmd_dsm;
316 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
317 cmnd->dsm.nr = cpu_to_le32(segments - 1);
318 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
320 req->special_vec.bv_page = virt_to_page(range);
321 req->special_vec.bv_offset = offset_in_page(range);
322 req->special_vec.bv_len = sizeof(*range) * segments;
323 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
328 static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
329 struct nvme_command *cmnd)
334 if (req->cmd_flags & REQ_FUA)
335 control |= NVME_RW_FUA;
336 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
337 control |= NVME_RW_LR;
339 if (req->cmd_flags & REQ_RAHEAD)
340 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
342 memset(cmnd, 0, sizeof(*cmnd));
343 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
344 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
345 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
346 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
349 switch (ns->pi_type) {
350 case NVME_NS_DPS_PI_TYPE3:
351 control |= NVME_RW_PRINFO_PRCHK_GUARD;
353 case NVME_NS_DPS_PI_TYPE1:
354 case NVME_NS_DPS_PI_TYPE2:
355 control |= NVME_RW_PRINFO_PRCHK_GUARD |
356 NVME_RW_PRINFO_PRCHK_REF;
357 cmnd->rw.reftag = cpu_to_le32(
358 nvme_block_nr(ns, blk_rq_pos(req)));
361 if (!blk_integrity_rq(req))
362 control |= NVME_RW_PRINFO_PRACT;
365 cmnd->rw.control = cpu_to_le16(control);
366 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
369 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
370 struct nvme_command *cmd)
372 blk_status_t ret = BLK_STS_OK;
374 if (!(req->rq_flags & RQF_DONTPREP)) {
375 nvme_req(req)->retries = 0;
376 nvme_req(req)->flags = 0;
377 req->rq_flags |= RQF_DONTPREP;
380 switch (req_op(req)) {
383 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
386 nvme_setup_flush(ns, cmd);
388 case REQ_OP_WRITE_ZEROES:
389 /* currently only aliased to deallocate for a few ctrls: */
391 ret = nvme_setup_discard(ns, req, cmd);
395 nvme_setup_rw(ns, req, cmd);
399 return BLK_STS_IOERR;
402 cmd->common.command_id = req->tag;
405 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
408 * Returns 0 on success. If the result is negative, it's a Linux error code;
409 * if the result is positive, it's an NVM Express status code
411 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
412 union nvme_result *result, void *buffer, unsigned bufflen,
413 unsigned timeout, int qid, int at_head, int flags)
418 req = nvme_alloc_request(q, cmd, flags, qid);
422 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
424 if (buffer && bufflen) {
425 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
430 blk_execute_rq(req->q, NULL, req, at_head);
432 *result = nvme_req(req)->result;
433 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
436 ret = nvme_req(req)->status;
438 blk_mq_free_request(req);
441 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
443 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
444 void *buffer, unsigned bufflen)
446 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
449 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
451 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
452 void __user *ubuffer, unsigned bufflen,
453 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
454 u32 *result, unsigned timeout)
456 bool write = nvme_is_write(cmd);
457 struct nvme_ns *ns = q->queuedata;
458 struct gendisk *disk = ns ? ns->disk : NULL;
460 struct bio *bio = NULL;
464 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
468 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
470 if (ubuffer && bufflen) {
471 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
479 bio->bi_bdev = bdget_disk(disk, 0);
485 if (meta_buffer && meta_len) {
486 struct bio_integrity_payload *bip;
488 meta = kmalloc(meta_len, GFP_KERNEL);
495 if (copy_from_user(meta, meta_buffer,
502 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
508 bip->bip_iter.bi_size = meta_len;
509 bip->bip_iter.bi_sector = meta_seed;
511 ret = bio_integrity_add_page(bio, virt_to_page(meta),
512 meta_len, offset_in_page(meta));
513 if (ret != meta_len) {
520 blk_execute_rq(req->q, disk, req, 0);
521 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
524 ret = nvme_req(req)->status;
526 *result = le32_to_cpu(nvme_req(req)->result.u32);
527 if (meta && !ret && !write) {
528 if (copy_to_user(meta_buffer, meta, meta_len))
535 if (disk && bio->bi_bdev)
537 blk_rq_unmap_user(bio);
540 blk_mq_free_request(req);
544 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
545 void __user *ubuffer, unsigned bufflen, u32 *result,
548 return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
552 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
554 struct nvme_ctrl *ctrl = rq->end_io_data;
556 blk_mq_free_request(rq);
559 dev_err(ctrl->device,
560 "failed nvme_keep_alive_end_io error=%d\n",
565 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
568 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
570 struct nvme_command c;
573 memset(&c, 0, sizeof(c));
574 c.common.opcode = nvme_admin_keep_alive;
576 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
581 rq->timeout = ctrl->kato * HZ;
582 rq->end_io_data = ctrl;
584 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
589 static void nvme_keep_alive_work(struct work_struct *work)
591 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
592 struct nvme_ctrl, ka_work);
594 if (nvme_keep_alive(ctrl)) {
595 /* allocation failure, reset the controller */
596 dev_err(ctrl->device, "keep-alive failed\n");
597 ctrl->ops->reset_ctrl(ctrl);
602 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
604 if (unlikely(ctrl->kato == 0))
607 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
608 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
610 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
612 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
614 if (unlikely(ctrl->kato == 0))
617 cancel_delayed_work_sync(&ctrl->ka_work);
619 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
621 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
623 struct nvme_command c = { };
626 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
627 c.identify.opcode = nvme_admin_identify;
628 c.identify.cns = NVME_ID_CNS_CTRL;
630 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
634 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
635 sizeof(struct nvme_id_ctrl));
641 static int nvme_identify_ns_descs(struct nvme_ns *ns, unsigned nsid)
643 struct nvme_command c = { };
649 c.identify.opcode = nvme_admin_identify;
650 c.identify.nsid = cpu_to_le32(nsid);
651 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
653 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
657 status = nvme_submit_sync_cmd(ns->ctrl->admin_q, &c, data,
658 NVME_IDENTIFY_DATA_SIZE);
662 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
663 struct nvme_ns_id_desc *cur = data + pos;
669 case NVME_NIDT_EUI64:
670 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
671 dev_warn(ns->ctrl->device,
672 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
676 len = NVME_NIDT_EUI64_LEN;
677 memcpy(ns->eui, data + pos + sizeof(*cur), len);
679 case NVME_NIDT_NGUID:
680 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
681 dev_warn(ns->ctrl->device,
682 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
686 len = NVME_NIDT_NGUID_LEN;
687 memcpy(ns->nguid, data + pos + sizeof(*cur), len);
690 if (cur->nidl != NVME_NIDT_UUID_LEN) {
691 dev_warn(ns->ctrl->device,
692 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
696 len = NVME_NIDT_UUID_LEN;
697 uuid_copy(&ns->uuid, data + pos + sizeof(*cur));
700 /* Skip unnkown types */
712 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
714 struct nvme_command c = { };
716 c.identify.opcode = nvme_admin_identify;
717 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
718 c.identify.nsid = cpu_to_le32(nsid);
719 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
722 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
723 struct nvme_id_ns **id)
725 struct nvme_command c = { };
728 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
729 c.identify.opcode = nvme_admin_identify;
730 c.identify.nsid = cpu_to_le32(nsid);
731 c.identify.cns = NVME_ID_CNS_NS;
733 *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
737 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
738 sizeof(struct nvme_id_ns));
744 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
745 void *buffer, size_t buflen, u32 *result)
747 struct nvme_command c;
748 union nvme_result res;
751 memset(&c, 0, sizeof(c));
752 c.features.opcode = nvme_admin_get_features;
753 c.features.nsid = cpu_to_le32(nsid);
754 c.features.fid = cpu_to_le32(fid);
756 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, buffer, buflen, 0,
758 if (ret >= 0 && result)
759 *result = le32_to_cpu(res.u32);
763 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
764 void *buffer, size_t buflen, u32 *result)
766 struct nvme_command c;
767 union nvme_result res;
770 memset(&c, 0, sizeof(c));
771 c.features.opcode = nvme_admin_set_features;
772 c.features.fid = cpu_to_le32(fid);
773 c.features.dword11 = cpu_to_le32(dword11);
775 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
776 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
777 if (ret >= 0 && result)
778 *result = le32_to_cpu(res.u32);
782 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
784 struct nvme_command c = { };
787 c.common.opcode = nvme_admin_get_log_page,
788 c.common.nsid = cpu_to_le32(0xFFFFFFFF),
789 c.common.cdw10[0] = cpu_to_le32(
790 (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
793 *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
797 error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
798 sizeof(struct nvme_smart_log));
804 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
806 u32 q_count = (*count - 1) | ((*count - 1) << 16);
808 int status, nr_io_queues;
810 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
816 * Degraded controllers might return an error when setting the queue
817 * count. We still want to be able to bring them online and offer
818 * access to the admin queue, as that might be only way to fix them up.
821 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
824 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
825 *count = min(*count, nr_io_queues);
830 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
832 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
834 struct nvme_user_io io;
835 struct nvme_command c;
836 unsigned length, meta_len;
837 void __user *metadata;
839 if (copy_from_user(&io, uio, sizeof(io)))
847 case nvme_cmd_compare:
853 length = (io.nblocks + 1) << ns->lba_shift;
854 meta_len = (io.nblocks + 1) * ns->ms;
855 metadata = (void __user *)(uintptr_t)io.metadata;
860 } else if (meta_len) {
861 if ((io.metadata & 3) || !io.metadata)
865 memset(&c, 0, sizeof(c));
866 c.rw.opcode = io.opcode;
867 c.rw.flags = io.flags;
868 c.rw.nsid = cpu_to_le32(ns->ns_id);
869 c.rw.slba = cpu_to_le64(io.slba);
870 c.rw.length = cpu_to_le16(io.nblocks);
871 c.rw.control = cpu_to_le16(io.control);
872 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
873 c.rw.reftag = cpu_to_le32(io.reftag);
874 c.rw.apptag = cpu_to_le16(io.apptag);
875 c.rw.appmask = cpu_to_le16(io.appmask);
877 return __nvme_submit_user_cmd(ns->queue, &c,
878 (void __user *)(uintptr_t)io.addr, length,
879 metadata, meta_len, io.slba, NULL, 0);
882 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
883 struct nvme_passthru_cmd __user *ucmd)
885 struct nvme_passthru_cmd cmd;
886 struct nvme_command c;
887 unsigned timeout = 0;
890 if (!capable(CAP_SYS_ADMIN))
892 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
897 memset(&c, 0, sizeof(c));
898 c.common.opcode = cmd.opcode;
899 c.common.flags = cmd.flags;
900 c.common.nsid = cpu_to_le32(cmd.nsid);
901 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
902 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
903 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
904 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
905 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
906 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
907 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
908 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
911 timeout = msecs_to_jiffies(cmd.timeout_ms);
913 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
914 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
915 &cmd.result, timeout);
917 if (put_user(cmd.result, &ucmd->result))
924 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
925 unsigned int cmd, unsigned long arg)
927 struct nvme_ns *ns = bdev->bd_disk->private_data;
931 force_successful_syscall_return();
933 case NVME_IOCTL_ADMIN_CMD:
934 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
935 case NVME_IOCTL_IO_CMD:
936 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
937 case NVME_IOCTL_SUBMIT_IO:
938 return nvme_submit_io(ns, (void __user *)arg);
939 #ifdef CONFIG_BLK_DEV_NVME_SCSI
940 case SG_GET_VERSION_NUM:
941 return nvme_sg_get_version_num((void __user *)arg);
943 return nvme_sg_io(ns, (void __user *)arg);
948 return nvme_nvm_ioctl(ns, cmd, arg);
950 if (is_sed_ioctl(cmd))
951 return sed_ioctl(ns->ctrl->opal_dev, cmd,
952 (void __user *) arg);
958 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
959 unsigned int cmd, unsigned long arg)
965 return nvme_ioctl(bdev, mode, cmd, arg);
968 #define nvme_compat_ioctl NULL
971 static int nvme_open(struct block_device *bdev, fmode_t mode)
973 return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
976 static void nvme_release(struct gendisk *disk, fmode_t mode)
978 struct nvme_ns *ns = disk->private_data;
980 module_put(ns->ctrl->ops->module);
984 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
986 /* some standard values */
988 geo->sectors = 1 << 5;
989 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
993 #ifdef CONFIG_BLK_DEV_INTEGRITY
994 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
997 struct nvme_ns *ns = disk->private_data;
1001 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1002 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1004 /* PI implementation requires metadata equal t10 pi tuple size */
1005 if (ns->ms == sizeof(struct t10_pi_tuple))
1006 pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1008 if (blk_get_integrity(disk) &&
1009 (ns->pi_type != pi_type || ns->ms != old_ms ||
1010 bs != queue_logical_block_size(disk->queue) ||
1011 (ns->ms && ns->ext)))
1012 blk_integrity_unregister(disk);
1014 ns->pi_type = pi_type;
1017 static void nvme_init_integrity(struct nvme_ns *ns)
1019 struct blk_integrity integrity;
1021 memset(&integrity, 0, sizeof(integrity));
1022 switch (ns->pi_type) {
1023 case NVME_NS_DPS_PI_TYPE3:
1024 integrity.profile = &t10_pi_type3_crc;
1025 integrity.tag_size = sizeof(u16) + sizeof(u32);
1026 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1028 case NVME_NS_DPS_PI_TYPE1:
1029 case NVME_NS_DPS_PI_TYPE2:
1030 integrity.profile = &t10_pi_type1_crc;
1031 integrity.tag_size = sizeof(u16);
1032 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1035 integrity.profile = NULL;
1038 integrity.tuple_size = ns->ms;
1039 blk_integrity_register(ns->disk, &integrity);
1040 blk_queue_max_integrity_segments(ns->queue, 1);
1043 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1047 static void nvme_init_integrity(struct nvme_ns *ns)
1050 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1052 static void nvme_config_discard(struct nvme_ns *ns)
1054 struct nvme_ctrl *ctrl = ns->ctrl;
1055 u32 logical_block_size = queue_logical_block_size(ns->queue);
1057 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1058 NVME_DSM_MAX_RANGES);
1060 ns->queue->limits.discard_alignment = logical_block_size;
1061 ns->queue->limits.discard_granularity = logical_block_size;
1062 blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
1063 blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1064 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1066 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1067 blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1070 static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
1072 if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
1073 dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
1077 if ((*id)->ncap == 0) {
1082 if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
1083 memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
1084 if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
1085 memcpy(ns->nguid, (*id)->nguid, sizeof(ns->nguid));
1086 if (ns->ctrl->vs >= NVME_VS(1, 3, 0)) {
1087 /* Don't treat error as fatal we potentially
1088 * already have a NGUID or EUI-64
1090 if (nvme_identify_ns_descs(ns, ns->ns_id))
1091 dev_warn(ns->ctrl->device,
1092 "%s: Identify Descriptors failed\n", __func__);
1098 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1100 struct nvme_ns *ns = disk->private_data;
1104 * If identify namespace failed, use default 512 byte block size so
1105 * block layer can use before failing read/write for 0 capacity.
1107 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1108 if (ns->lba_shift == 0)
1110 bs = 1 << ns->lba_shift;
1112 blk_mq_freeze_queue(disk->queue);
1114 if (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
1115 nvme_prep_integrity(disk, id, bs);
1116 blk_queue_logical_block_size(ns->queue, bs);
1117 if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1118 nvme_init_integrity(ns);
1119 if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1120 set_capacity(disk, 0);
1122 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1124 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
1125 nvme_config_discard(ns);
1126 blk_mq_unfreeze_queue(disk->queue);
1129 static int nvme_revalidate_disk(struct gendisk *disk)
1131 struct nvme_ns *ns = disk->private_data;
1132 struct nvme_id_ns *id = NULL;
1135 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1136 set_capacity(disk, 0);
1140 ret = nvme_revalidate_ns(ns, &id);
1144 __nvme_revalidate_disk(disk, id);
1150 static char nvme_pr_type(enum pr_type type)
1153 case PR_WRITE_EXCLUSIVE:
1155 case PR_EXCLUSIVE_ACCESS:
1157 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1159 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1161 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1163 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1170 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1171 u64 key, u64 sa_key, u8 op)
1173 struct nvme_ns *ns = bdev->bd_disk->private_data;
1174 struct nvme_command c;
1175 u8 data[16] = { 0, };
1177 put_unaligned_le64(key, &data[0]);
1178 put_unaligned_le64(sa_key, &data[8]);
1180 memset(&c, 0, sizeof(c));
1181 c.common.opcode = op;
1182 c.common.nsid = cpu_to_le32(ns->ns_id);
1183 c.common.cdw10[0] = cpu_to_le32(cdw10);
1185 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1188 static int nvme_pr_register(struct block_device *bdev, u64 old,
1189 u64 new, unsigned flags)
1193 if (flags & ~PR_FL_IGNORE_KEY)
1196 cdw10 = old ? 2 : 0;
1197 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1198 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1199 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1202 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1203 enum pr_type type, unsigned flags)
1207 if (flags & ~PR_FL_IGNORE_KEY)
1210 cdw10 = nvme_pr_type(type) << 8;
1211 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1212 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1215 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1216 enum pr_type type, bool abort)
1218 u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1219 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1222 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1224 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1225 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1228 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1230 u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1231 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1234 static const struct pr_ops nvme_pr_ops = {
1235 .pr_register = nvme_pr_register,
1236 .pr_reserve = nvme_pr_reserve,
1237 .pr_release = nvme_pr_release,
1238 .pr_preempt = nvme_pr_preempt,
1239 .pr_clear = nvme_pr_clear,
1242 #ifdef CONFIG_BLK_SED_OPAL
1243 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1246 struct nvme_ctrl *ctrl = data;
1247 struct nvme_command cmd;
1249 memset(&cmd, 0, sizeof(cmd));
1251 cmd.common.opcode = nvme_admin_security_send;
1253 cmd.common.opcode = nvme_admin_security_recv;
1254 cmd.common.nsid = 0;
1255 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1256 cmd.common.cdw10[1] = cpu_to_le32(len);
1258 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1259 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1261 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1262 #endif /* CONFIG_BLK_SED_OPAL */
1264 static const struct block_device_operations nvme_fops = {
1265 .owner = THIS_MODULE,
1266 .ioctl = nvme_ioctl,
1267 .compat_ioctl = nvme_compat_ioctl,
1269 .release = nvme_release,
1270 .getgeo = nvme_getgeo,
1271 .revalidate_disk= nvme_revalidate_disk,
1272 .pr_ops = &nvme_pr_ops,
1275 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1277 unsigned long timeout =
1278 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1279 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1282 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1285 if ((csts & NVME_CSTS_RDY) == bit)
1289 if (fatal_signal_pending(current))
1291 if (time_after(jiffies, timeout)) {
1292 dev_err(ctrl->device,
1293 "Device not ready; aborting %s\n", enabled ?
1294 "initialisation" : "reset");
1303 * If the device has been passed off to us in an enabled state, just clear
1304 * the enabled bit. The spec says we should set the 'shutdown notification
1305 * bits', but doing so may cause the device to complete commands to the
1306 * admin queue ... and we don't know what memory that might be pointing at!
1308 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1312 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1313 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1315 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1319 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1320 msleep(NVME_QUIRK_DELAY_AMOUNT);
1322 return nvme_wait_ready(ctrl, cap, false);
1324 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1326 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1329 * Default to a 4K page size, with the intention to update this
1330 * path in the future to accomodate architectures with differing
1331 * kernel and IO page sizes.
1333 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1336 if (page_shift < dev_page_min) {
1337 dev_err(ctrl->device,
1338 "Minimum device page size %u too large for host (%u)\n",
1339 1 << dev_page_min, 1 << page_shift);
1343 ctrl->page_size = 1 << page_shift;
1345 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1346 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1347 ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1348 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1349 ctrl->ctrl_config |= NVME_CC_ENABLE;
1351 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1354 return nvme_wait_ready(ctrl, cap, true);
1356 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1358 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1360 unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1364 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1365 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1367 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1371 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1372 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1376 if (fatal_signal_pending(current))
1378 if (time_after(jiffies, timeout)) {
1379 dev_err(ctrl->device,
1380 "Device shutdown incomplete; abort shutdown\n");
1387 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1389 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1390 struct request_queue *q)
1394 if (ctrl->max_hw_sectors) {
1396 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1398 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1399 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1401 if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1402 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1403 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1404 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1406 blk_queue_write_cache(q, vwc, vwc);
1409 static void nvme_configure_apst(struct nvme_ctrl *ctrl)
1412 * APST (Autonomous Power State Transition) lets us program a
1413 * table of power state transitions that the controller will
1414 * perform automatically. We configure it with a simple
1415 * heuristic: we are willing to spend at most 2% of the time
1416 * transitioning between power states. Therefore, when running
1417 * in any given state, we will enter the next lower-power
1418 * non-operational state after waiting 50 * (enlat + exlat)
1419 * microseconds, as long as that state's exit latency is under
1420 * the requested maximum latency.
1422 * We will not autonomously enter any non-operational state for
1423 * which the total latency exceeds ps_max_latency_us. Users
1424 * can set ps_max_latency_us to zero to turn off APST.
1428 struct nvme_feat_auto_pst *table;
1434 * If APST isn't supported or if we haven't been initialized yet,
1435 * then don't do anything.
1440 if (ctrl->npss > 31) {
1441 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1445 table = kzalloc(sizeof(*table), GFP_KERNEL);
1449 if (ctrl->ps_max_latency_us == 0) {
1450 /* Turn off APST. */
1452 dev_dbg(ctrl->device, "APST disabled\n");
1454 __le64 target = cpu_to_le64(0);
1458 * Walk through all states from lowest- to highest-power.
1459 * According to the spec, lower-numbered states use more
1460 * power. NPSS, despite the name, is the index of the
1461 * lowest-power state, not the number of states.
1463 for (state = (int)ctrl->npss; state >= 0; state--) {
1464 u64 total_latency_us, exit_latency_us, transition_ms;
1467 table->entries[state] = target;
1470 * Don't allow transitions to the deepest state
1471 * if it's quirked off.
1473 if (state == ctrl->npss &&
1474 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1478 * Is this state a useful non-operational state for
1479 * higher-power states to autonomously transition to?
1481 if (!(ctrl->psd[state].flags &
1482 NVME_PS_FLAGS_NON_OP_STATE))
1486 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1487 if (exit_latency_us > ctrl->ps_max_latency_us)
1492 le32_to_cpu(ctrl->psd[state].entry_lat);
1495 * This state is good. Use it as the APST idle
1496 * target for higher power states.
1498 transition_ms = total_latency_us + 19;
1499 do_div(transition_ms, 20);
1500 if (transition_ms > (1 << 24) - 1)
1501 transition_ms = (1 << 24) - 1;
1503 target = cpu_to_le64((state << 3) |
1504 (transition_ms << 8));
1509 if (total_latency_us > max_lat_us)
1510 max_lat_us = total_latency_us;
1516 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1518 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1519 max_ps, max_lat_us, (int)sizeof(*table), table);
1523 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1524 table, sizeof(*table), NULL);
1526 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1531 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1533 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1537 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1538 case PM_QOS_LATENCY_ANY:
1546 if (ctrl->ps_max_latency_us != latency) {
1547 ctrl->ps_max_latency_us = latency;
1548 nvme_configure_apst(ctrl);
1552 struct nvme_core_quirk_entry {
1554 * NVMe model and firmware strings are padded with spaces. For
1555 * simplicity, strings in the quirk table are padded with NULLs
1561 unsigned long quirks;
1564 static const struct nvme_core_quirk_entry core_quirks[] = {
1567 * This Toshiba device seems to die using any APST states. See:
1568 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1571 .mn = "THNSF5256GPUK TOSHIBA",
1572 .quirks = NVME_QUIRK_NO_APST,
1576 /* match is null-terminated but idstr is space-padded. */
1577 static bool string_matches(const char *idstr, const char *match, size_t len)
1584 matchlen = strlen(match);
1585 WARN_ON_ONCE(matchlen > len);
1587 if (memcmp(idstr, match, matchlen))
1590 for (; matchlen < len; matchlen++)
1591 if (idstr[matchlen] != ' ')
1597 static bool quirk_matches(const struct nvme_id_ctrl *id,
1598 const struct nvme_core_quirk_entry *q)
1600 return q->vid == le16_to_cpu(id->vid) &&
1601 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1602 string_matches(id->fr, q->fr, sizeof(id->fr));
1606 * Initialize the cached copies of the Identify data and various controller
1607 * register in our nvme_ctrl structure. This should be called as soon as
1608 * the admin queue is fully up and running.
1610 int nvme_init_identify(struct nvme_ctrl *ctrl)
1612 struct nvme_id_ctrl *id;
1614 int ret, page_shift;
1618 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1620 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1624 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1626 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1629 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1631 if (ctrl->vs >= NVME_VS(1, 1, 0))
1632 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1634 ret = nvme_identify_ctrl(ctrl, &id);
1636 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1640 if (!ctrl->identified) {
1642 * Check for quirks. Quirk can depend on firmware version,
1643 * so, in principle, the set of quirks present can change
1644 * across a reset. As a possible future enhancement, we
1645 * could re-scan for quirks every time we reinitialize
1646 * the device, but we'd have to make sure that the driver
1647 * behaves intelligently if the quirks change.
1652 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1653 if (quirk_matches(id, &core_quirks[i]))
1654 ctrl->quirks |= core_quirks[i].quirks;
1658 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1659 dev_warn(ctrl->dev, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1660 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1663 ctrl->oacs = le16_to_cpu(id->oacs);
1664 ctrl->vid = le16_to_cpu(id->vid);
1665 ctrl->oncs = le16_to_cpup(&id->oncs);
1666 atomic_set(&ctrl->abort_limit, id->acl + 1);
1667 ctrl->vwc = id->vwc;
1668 ctrl->cntlid = le16_to_cpup(&id->cntlid);
1669 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1670 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1671 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1673 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1675 max_hw_sectors = UINT_MAX;
1676 ctrl->max_hw_sectors =
1677 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1679 nvme_set_queue_limits(ctrl, ctrl->admin_q);
1680 ctrl->sgls = le32_to_cpu(id->sgls);
1681 ctrl->kas = le16_to_cpu(id->kas);
1683 ctrl->npss = id->npss;
1684 prev_apsta = ctrl->apsta;
1685 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1686 if (force_apst && id->apsta) {
1687 dev_warn(ctrl->dev, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1693 ctrl->apsta = id->apsta;
1695 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1697 if (ctrl->ops->flags & NVME_F_FABRICS) {
1698 ctrl->icdoff = le16_to_cpu(id->icdoff);
1699 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1700 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1701 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1704 * In fabrics we need to verify the cntlid matches the
1707 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1710 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1712 "keep-alive support is mandatory for fabrics\n");
1716 ctrl->cntlid = le16_to_cpu(id->cntlid);
1717 ctrl->hmpre = le32_to_cpu(id->hmpre);
1718 ctrl->hmmin = le32_to_cpu(id->hmmin);
1723 if (ctrl->apsta && !prev_apsta)
1724 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1725 else if (!ctrl->apsta && prev_apsta)
1726 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1728 nvme_configure_apst(ctrl);
1730 ctrl->identified = true;
1734 EXPORT_SYMBOL_GPL(nvme_init_identify);
1736 static int nvme_dev_open(struct inode *inode, struct file *file)
1738 struct nvme_ctrl *ctrl;
1739 int instance = iminor(inode);
1742 spin_lock(&dev_list_lock);
1743 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1744 if (ctrl->instance != instance)
1747 if (!ctrl->admin_q) {
1751 if (!kref_get_unless_zero(&ctrl->kref))
1753 file->private_data = ctrl;
1757 spin_unlock(&dev_list_lock);
1762 static int nvme_dev_release(struct inode *inode, struct file *file)
1764 nvme_put_ctrl(file->private_data);
1768 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1773 mutex_lock(&ctrl->namespaces_mutex);
1774 if (list_empty(&ctrl->namespaces)) {
1779 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1780 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1781 dev_warn(ctrl->device,
1782 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1787 dev_warn(ctrl->device,
1788 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1789 kref_get(&ns->kref);
1790 mutex_unlock(&ctrl->namespaces_mutex);
1792 ret = nvme_user_cmd(ctrl, ns, argp);
1797 mutex_unlock(&ctrl->namespaces_mutex);
1801 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1804 struct nvme_ctrl *ctrl = file->private_data;
1805 void __user *argp = (void __user *)arg;
1808 case NVME_IOCTL_ADMIN_CMD:
1809 return nvme_user_cmd(ctrl, NULL, argp);
1810 case NVME_IOCTL_IO_CMD:
1811 return nvme_dev_user_cmd(ctrl, argp);
1812 case NVME_IOCTL_RESET:
1813 dev_warn(ctrl->device, "resetting controller\n");
1814 return ctrl->ops->reset_ctrl(ctrl);
1815 case NVME_IOCTL_SUBSYS_RESET:
1816 return nvme_reset_subsystem(ctrl);
1817 case NVME_IOCTL_RESCAN:
1818 nvme_queue_scan(ctrl);
1825 static const struct file_operations nvme_dev_fops = {
1826 .owner = THIS_MODULE,
1827 .open = nvme_dev_open,
1828 .release = nvme_dev_release,
1829 .unlocked_ioctl = nvme_dev_ioctl,
1830 .compat_ioctl = nvme_dev_ioctl,
1833 static ssize_t nvme_sysfs_reset(struct device *dev,
1834 struct device_attribute *attr, const char *buf,
1837 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1840 ret = ctrl->ops->reset_ctrl(ctrl);
1845 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1847 static ssize_t nvme_sysfs_rescan(struct device *dev,
1848 struct device_attribute *attr, const char *buf,
1851 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1853 nvme_queue_scan(ctrl);
1856 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1858 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1861 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1862 struct nvme_ctrl *ctrl = ns->ctrl;
1863 int serial_len = sizeof(ctrl->serial);
1864 int model_len = sizeof(ctrl->model);
1866 if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1867 return sprintf(buf, "eui.%16phN\n", ns->nguid);
1869 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1870 return sprintf(buf, "eui.%8phN\n", ns->eui);
1872 while (ctrl->serial[serial_len - 1] == ' ')
1874 while (ctrl->model[model_len - 1] == ' ')
1877 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1878 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1880 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1882 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
1885 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1886 return sprintf(buf, "%pU\n", ns->nguid);
1888 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
1890 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1893 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1895 /* For backward compatibility expose the NGUID to userspace if
1896 * we have no UUID set
1898 if (uuid_is_null(&ns->uuid)) {
1899 printk_ratelimited(KERN_WARNING
1900 "No UUID available providing old NGUID\n");
1901 return sprintf(buf, "%pU\n", ns->nguid);
1903 return sprintf(buf, "%pU\n", &ns->uuid);
1905 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1907 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1910 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1911 return sprintf(buf, "%8phd\n", ns->eui);
1913 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1915 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1918 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1919 return sprintf(buf, "%d\n", ns->ns_id);
1921 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1923 static struct attribute *nvme_ns_attrs[] = {
1924 &dev_attr_wwid.attr,
1925 &dev_attr_uuid.attr,
1926 &dev_attr_nguid.attr,
1928 &dev_attr_nsid.attr,
1932 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1933 struct attribute *a, int n)
1935 struct device *dev = container_of(kobj, struct device, kobj);
1936 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1938 if (a == &dev_attr_uuid.attr) {
1939 if (uuid_is_null(&ns->uuid) ||
1940 !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1943 if (a == &dev_attr_nguid.attr) {
1944 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
1947 if (a == &dev_attr_eui.attr) {
1948 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1954 static const struct attribute_group nvme_ns_attr_group = {
1955 .attrs = nvme_ns_attrs,
1956 .is_visible = nvme_ns_attrs_are_visible,
1959 #define nvme_show_str_function(field) \
1960 static ssize_t field##_show(struct device *dev, \
1961 struct device_attribute *attr, char *buf) \
1963 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1964 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
1966 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1968 #define nvme_show_int_function(field) \
1969 static ssize_t field##_show(struct device *dev, \
1970 struct device_attribute *attr, char *buf) \
1972 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1973 return sprintf(buf, "%d\n", ctrl->field); \
1975 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1977 nvme_show_str_function(model);
1978 nvme_show_str_function(serial);
1979 nvme_show_str_function(firmware_rev);
1980 nvme_show_int_function(cntlid);
1982 static ssize_t nvme_sysfs_delete(struct device *dev,
1983 struct device_attribute *attr, const char *buf,
1986 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1988 if (device_remove_file_self(dev, attr))
1989 ctrl->ops->delete_ctrl(ctrl);
1992 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1994 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1995 struct device_attribute *attr,
1998 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2000 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2002 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2004 static ssize_t nvme_sysfs_show_state(struct device *dev,
2005 struct device_attribute *attr,
2008 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2009 static const char *const state_name[] = {
2010 [NVME_CTRL_NEW] = "new",
2011 [NVME_CTRL_LIVE] = "live",
2012 [NVME_CTRL_RESETTING] = "resetting",
2013 [NVME_CTRL_RECONNECTING]= "reconnecting",
2014 [NVME_CTRL_DELETING] = "deleting",
2015 [NVME_CTRL_DEAD] = "dead",
2018 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2019 state_name[ctrl->state])
2020 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2022 return sprintf(buf, "unknown state\n");
2025 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2027 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2028 struct device_attribute *attr,
2031 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2033 return snprintf(buf, PAGE_SIZE, "%s\n",
2034 ctrl->ops->get_subsysnqn(ctrl));
2036 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2038 static ssize_t nvme_sysfs_show_address(struct device *dev,
2039 struct device_attribute *attr,
2042 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2044 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2046 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2048 static struct attribute *nvme_dev_attrs[] = {
2049 &dev_attr_reset_controller.attr,
2050 &dev_attr_rescan_controller.attr,
2051 &dev_attr_model.attr,
2052 &dev_attr_serial.attr,
2053 &dev_attr_firmware_rev.attr,
2054 &dev_attr_cntlid.attr,
2055 &dev_attr_delete_controller.attr,
2056 &dev_attr_transport.attr,
2057 &dev_attr_subsysnqn.attr,
2058 &dev_attr_address.attr,
2059 &dev_attr_state.attr,
2063 #define CHECK_ATTR(ctrl, a, name) \
2064 if ((a) == &dev_attr_##name.attr && \
2065 !(ctrl)->ops->get_##name) \
2068 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2069 struct attribute *a, int n)
2071 struct device *dev = container_of(kobj, struct device, kobj);
2072 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2074 if (a == &dev_attr_delete_controller.attr) {
2075 if (!ctrl->ops->delete_ctrl)
2079 CHECK_ATTR(ctrl, a, subsysnqn);
2080 CHECK_ATTR(ctrl, a, address);
2085 static struct attribute_group nvme_dev_attrs_group = {
2086 .attrs = nvme_dev_attrs,
2087 .is_visible = nvme_dev_attrs_are_visible,
2090 static const struct attribute_group *nvme_dev_attr_groups[] = {
2091 &nvme_dev_attrs_group,
2095 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2097 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2098 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2100 return nsa->ns_id - nsb->ns_id;
2103 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2105 struct nvme_ns *ns, *ret = NULL;
2107 mutex_lock(&ctrl->namespaces_mutex);
2108 list_for_each_entry(ns, &ctrl->namespaces, list) {
2109 if (ns->ns_id == nsid) {
2110 kref_get(&ns->kref);
2114 if (ns->ns_id > nsid)
2117 mutex_unlock(&ctrl->namespaces_mutex);
2121 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2124 struct gendisk *disk;
2125 struct nvme_id_ns *id;
2126 char disk_name[DISK_NAME_LEN];
2127 int node = dev_to_node(ctrl->dev);
2129 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2133 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2134 if (ns->instance < 0)
2137 ns->queue = blk_mq_init_queue(ctrl->tagset);
2138 if (IS_ERR(ns->queue))
2139 goto out_release_instance;
2140 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2141 ns->queue->queuedata = ns;
2144 kref_init(&ns->kref);
2146 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2148 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2149 nvme_set_queue_limits(ctrl, ns->queue);
2151 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2153 if (nvme_revalidate_ns(ns, &id))
2154 goto out_free_queue;
2156 if (nvme_nvm_ns_supported(ns, id) &&
2157 nvme_nvm_register(ns, disk_name, node)) {
2158 dev_warn(ctrl->dev, "%s: LightNVM init failure\n", __func__);
2162 disk = alloc_disk_node(0, node);
2166 disk->fops = &nvme_fops;
2167 disk->private_data = ns;
2168 disk->queue = ns->queue;
2169 disk->flags = GENHD_FL_EXT_DEVT;
2170 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2173 __nvme_revalidate_disk(disk, id);
2175 mutex_lock(&ctrl->namespaces_mutex);
2176 list_add_tail(&ns->list, &ctrl->namespaces);
2177 mutex_unlock(&ctrl->namespaces_mutex);
2179 kref_get(&ctrl->kref);
2183 device_add_disk(ctrl->device, ns->disk);
2184 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2185 &nvme_ns_attr_group))
2186 pr_warn("%s: failed to create sysfs group for identification\n",
2187 ns->disk->disk_name);
2188 if (ns->ndev && nvme_nvm_register_sysfs(ns))
2189 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2190 ns->disk->disk_name);
2195 blk_cleanup_queue(ns->queue);
2196 out_release_instance:
2197 ida_simple_remove(&ctrl->ns_ida, ns->instance);
2202 static void nvme_ns_remove(struct nvme_ns *ns)
2204 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2207 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2208 if (blk_get_integrity(ns->disk))
2209 blk_integrity_unregister(ns->disk);
2210 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2211 &nvme_ns_attr_group);
2213 nvme_nvm_unregister_sysfs(ns);
2214 del_gendisk(ns->disk);
2215 blk_cleanup_queue(ns->queue);
2218 mutex_lock(&ns->ctrl->namespaces_mutex);
2219 list_del_init(&ns->list);
2220 mutex_unlock(&ns->ctrl->namespaces_mutex);
2225 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2229 ns = nvme_find_get_ns(ctrl, nsid);
2231 if (ns->disk && revalidate_disk(ns->disk))
2235 nvme_alloc_ns(ctrl, nsid);
2238 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2241 struct nvme_ns *ns, *next;
2243 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2244 if (ns->ns_id > nsid)
2249 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2253 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2256 ns_list = kzalloc(0x1000, GFP_KERNEL);
2260 for (i = 0; i < num_lists; i++) {
2261 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2265 for (j = 0; j < min(nn, 1024U); j++) {
2266 nsid = le32_to_cpu(ns_list[j]);
2270 nvme_validate_ns(ctrl, nsid);
2272 while (++prev < nsid) {
2273 ns = nvme_find_get_ns(ctrl, prev);
2283 nvme_remove_invalid_namespaces(ctrl, prev);
2289 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2293 for (i = 1; i <= nn; i++)
2294 nvme_validate_ns(ctrl, i);
2296 nvme_remove_invalid_namespaces(ctrl, nn);
2299 static void nvme_scan_work(struct work_struct *work)
2301 struct nvme_ctrl *ctrl =
2302 container_of(work, struct nvme_ctrl, scan_work);
2303 struct nvme_id_ctrl *id;
2306 if (ctrl->state != NVME_CTRL_LIVE)
2309 if (nvme_identify_ctrl(ctrl, &id))
2312 nn = le32_to_cpu(id->nn);
2313 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2314 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2315 if (!nvme_scan_ns_list(ctrl, nn))
2318 nvme_scan_ns_sequential(ctrl, nn);
2320 mutex_lock(&ctrl->namespaces_mutex);
2321 list_sort(NULL, &ctrl->namespaces, ns_cmp);
2322 mutex_unlock(&ctrl->namespaces_mutex);
2326 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2329 * Do not queue new scan work when a controller is reset during
2332 if (ctrl->state == NVME_CTRL_LIVE)
2333 queue_work(nvme_wq, &ctrl->scan_work);
2335 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2338 * This function iterates the namespace list unlocked to allow recovery from
2339 * controller failure. It is up to the caller to ensure the namespace list is
2340 * not modified by scan work while this function is executing.
2342 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2344 struct nvme_ns *ns, *next;
2347 * The dead states indicates the controller was not gracefully
2348 * disconnected. In that case, we won't be able to flush any data while
2349 * removing the namespaces' disks; fail all the queues now to avoid
2350 * potentially having to clean up the failed sync later.
2352 if (ctrl->state == NVME_CTRL_DEAD)
2353 nvme_kill_queues(ctrl);
2355 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2358 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2360 static void nvme_async_event_work(struct work_struct *work)
2362 struct nvme_ctrl *ctrl =
2363 container_of(work, struct nvme_ctrl, async_event_work);
2365 spin_lock_irq(&ctrl->lock);
2366 while (ctrl->event_limit > 0) {
2367 int aer_idx = --ctrl->event_limit;
2369 spin_unlock_irq(&ctrl->lock);
2370 ctrl->ops->submit_async_event(ctrl, aer_idx);
2371 spin_lock_irq(&ctrl->lock);
2373 spin_unlock_irq(&ctrl->lock);
2376 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2377 union nvme_result *res)
2379 u32 result = le32_to_cpu(res->u32);
2382 switch (le16_to_cpu(status) >> 1) {
2383 case NVME_SC_SUCCESS:
2386 case NVME_SC_ABORT_REQ:
2387 ++ctrl->event_limit;
2388 queue_work(nvme_wq, &ctrl->async_event_work);
2397 switch (result & 0xff07) {
2398 case NVME_AER_NOTICE_NS_CHANGED:
2399 dev_info(ctrl->device, "rescanning\n");
2400 nvme_queue_scan(ctrl);
2403 dev_warn(ctrl->device, "async event result %08x\n", result);
2406 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2408 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2410 ctrl->event_limit = NVME_NR_AERS;
2411 queue_work(nvme_wq, &ctrl->async_event_work);
2413 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2415 static DEFINE_IDA(nvme_instance_ida);
2417 static int nvme_set_instance(struct nvme_ctrl *ctrl)
2419 int instance, error;
2422 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2425 spin_lock(&dev_list_lock);
2426 error = ida_get_new(&nvme_instance_ida, &instance);
2427 spin_unlock(&dev_list_lock);
2428 } while (error == -EAGAIN);
2433 ctrl->instance = instance;
2437 static void nvme_release_instance(struct nvme_ctrl *ctrl)
2439 spin_lock(&dev_list_lock);
2440 ida_remove(&nvme_instance_ida, ctrl->instance);
2441 spin_unlock(&dev_list_lock);
2444 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2446 flush_work(&ctrl->async_event_work);
2447 flush_work(&ctrl->scan_work);
2448 nvme_remove_namespaces(ctrl);
2450 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
2452 spin_lock(&dev_list_lock);
2453 list_del(&ctrl->node);
2454 spin_unlock(&dev_list_lock);
2456 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2458 static void nvme_free_ctrl(struct kref *kref)
2460 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
2462 put_device(ctrl->device);
2463 nvme_release_instance(ctrl);
2464 ida_destroy(&ctrl->ns_ida);
2466 ctrl->ops->free_ctrl(ctrl);
2469 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2471 kref_put(&ctrl->kref, nvme_free_ctrl);
2473 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
2476 * Initialize a NVMe controller structures. This needs to be called during
2477 * earliest initialization so that we have the initialized structured around
2480 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2481 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2485 ctrl->state = NVME_CTRL_NEW;
2486 spin_lock_init(&ctrl->lock);
2487 INIT_LIST_HEAD(&ctrl->namespaces);
2488 mutex_init(&ctrl->namespaces_mutex);
2489 kref_init(&ctrl->kref);
2492 ctrl->quirks = quirks;
2493 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2494 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2496 ret = nvme_set_instance(ctrl);
2500 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2501 MKDEV(nvme_char_major, ctrl->instance),
2502 ctrl, nvme_dev_attr_groups,
2503 "nvme%d", ctrl->instance);
2504 if (IS_ERR(ctrl->device)) {
2505 ret = PTR_ERR(ctrl->device);
2506 goto out_release_instance;
2508 get_device(ctrl->device);
2509 ida_init(&ctrl->ns_ida);
2511 spin_lock(&dev_list_lock);
2512 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2513 spin_unlock(&dev_list_lock);
2516 * Initialize latency tolerance controls. The sysfs files won't
2517 * be visible to userspace unless the device actually supports APST.
2519 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2520 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2521 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2524 out_release_instance:
2525 nvme_release_instance(ctrl);
2529 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2532 * nvme_kill_queues(): Ends all namespace queues
2533 * @ctrl: the dead controller that needs to end
2535 * Call this function when the driver determines it is unable to get the
2536 * controller in a state capable of servicing IO.
2538 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2542 mutex_lock(&ctrl->namespaces_mutex);
2544 /* Forcibly start all queues to avoid having stuck requests */
2545 blk_mq_start_hw_queues(ctrl->admin_q);
2547 list_for_each_entry(ns, &ctrl->namespaces, list) {
2549 * Revalidating a dead namespace sets capacity to 0. This will
2550 * end buffered writers dirtying pages that can't be synced.
2552 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2554 revalidate_disk(ns->disk);
2555 blk_set_queue_dying(ns->queue);
2558 * Forcibly start all queues to avoid having stuck requests.
2559 * Note that we must ensure the queues are not stopped
2560 * when the final removal happens.
2562 blk_mq_start_hw_queues(ns->queue);
2564 /* draining requests in requeue list */
2565 blk_mq_kick_requeue_list(ns->queue);
2567 mutex_unlock(&ctrl->namespaces_mutex);
2569 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2571 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2575 mutex_lock(&ctrl->namespaces_mutex);
2576 list_for_each_entry(ns, &ctrl->namespaces, list)
2577 blk_mq_unfreeze_queue(ns->queue);
2578 mutex_unlock(&ctrl->namespaces_mutex);
2580 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2582 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2586 mutex_lock(&ctrl->namespaces_mutex);
2587 list_for_each_entry(ns, &ctrl->namespaces, list) {
2588 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2592 mutex_unlock(&ctrl->namespaces_mutex);
2594 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2596 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2600 mutex_lock(&ctrl->namespaces_mutex);
2601 list_for_each_entry(ns, &ctrl->namespaces, list)
2602 blk_mq_freeze_queue_wait(ns->queue);
2603 mutex_unlock(&ctrl->namespaces_mutex);
2605 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2607 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2611 mutex_lock(&ctrl->namespaces_mutex);
2612 list_for_each_entry(ns, &ctrl->namespaces, list)
2613 blk_freeze_queue_start(ns->queue);
2614 mutex_unlock(&ctrl->namespaces_mutex);
2616 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2618 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2622 mutex_lock(&ctrl->namespaces_mutex);
2623 list_for_each_entry(ns, &ctrl->namespaces, list)
2624 blk_mq_quiesce_queue(ns->queue);
2625 mutex_unlock(&ctrl->namespaces_mutex);
2627 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2629 void nvme_start_queues(struct nvme_ctrl *ctrl)
2633 mutex_lock(&ctrl->namespaces_mutex);
2634 list_for_each_entry(ns, &ctrl->namespaces, list) {
2635 blk_mq_start_stopped_hw_queues(ns->queue, true);
2636 blk_mq_kick_requeue_list(ns->queue);
2638 mutex_unlock(&ctrl->namespaces_mutex);
2640 EXPORT_SYMBOL_GPL(nvme_start_queues);
2642 int __init nvme_core_init(void)
2646 nvme_wq = alloc_workqueue("nvme-wq",
2647 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2651 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2655 else if (result > 0)
2656 nvme_char_major = result;
2658 nvme_class = class_create(THIS_MODULE, "nvme");
2659 if (IS_ERR(nvme_class)) {
2660 result = PTR_ERR(nvme_class);
2661 goto unregister_chrdev;
2667 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2669 destroy_workqueue(nvme_wq);
2673 void nvme_core_exit(void)
2675 class_destroy(nvme_class);
2676 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2677 destroy_workqueue(nvme_wq);
2680 MODULE_LICENSE("GPL");
2681 MODULE_VERSION("1.0");
2682 module_init(nvme_core_init);
2683 module_exit(nvme_core_exit);