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>
30 #include <asm/unaligned.h>
35 #define NVME_MINORS (1U << MINORBITS)
37 unsigned char admin_timeout = 60;
38 module_param(admin_timeout, byte, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
42 unsigned char nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
47 unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
51 unsigned int nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, uint, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
54 EXPORT_SYMBOL_GPL(nvme_max_retries);
56 static int nvme_char_major;
57 module_param(nvme_char_major, int, 0);
59 static LIST_HEAD(nvme_ctrl_list);
60 static DEFINE_SPINLOCK(dev_list_lock);
62 static struct class *nvme_class;
64 void nvme_cancel_request(struct request *req, void *data, bool reserved)
68 if (!blk_mq_request_started(req))
71 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
72 "Cancelling I/O %d", req->tag);
74 status = NVME_SC_ABORT_REQ;
75 if (blk_queue_dying(req->q))
76 status |= NVME_SC_DNR;
77 blk_mq_complete_request(req, status);
79 EXPORT_SYMBOL_GPL(nvme_cancel_request);
81 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
82 enum nvme_ctrl_state new_state)
84 enum nvme_ctrl_state old_state;
87 spin_lock_irq(&ctrl->lock);
89 old_state = ctrl->state;
94 case NVME_CTRL_RESETTING:
95 case NVME_CTRL_RECONNECTING:
102 case NVME_CTRL_RESETTING:
106 case NVME_CTRL_RECONNECTING:
113 case NVME_CTRL_RECONNECTING:
122 case NVME_CTRL_DELETING:
125 case NVME_CTRL_RESETTING:
126 case NVME_CTRL_RECONNECTING:
135 case NVME_CTRL_DELETING:
147 ctrl->state = new_state;
149 spin_unlock_irq(&ctrl->lock);
153 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
155 static void nvme_free_ns(struct kref *kref)
157 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
160 nvme_nvm_unregister(ns);
163 spin_lock(&dev_list_lock);
164 ns->disk->private_data = NULL;
165 spin_unlock(&dev_list_lock);
169 ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
170 nvme_put_ctrl(ns->ctrl);
174 static void nvme_put_ns(struct nvme_ns *ns)
176 kref_put(&ns->kref, nvme_free_ns);
179 static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
183 spin_lock(&dev_list_lock);
184 ns = disk->private_data;
186 if (!kref_get_unless_zero(&ns->kref))
188 if (!try_module_get(ns->ctrl->ops->module))
191 spin_unlock(&dev_list_lock);
196 kref_put(&ns->kref, nvme_free_ns);
198 spin_unlock(&dev_list_lock);
202 void nvme_requeue_req(struct request *req)
204 blk_mq_requeue_request(req, !blk_mq_queue_stopped(req->q));
206 EXPORT_SYMBOL_GPL(nvme_requeue_req);
208 struct request *nvme_alloc_request(struct request_queue *q,
209 struct nvme_command *cmd, unsigned int flags, int qid)
211 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
214 if (qid == NVME_QID_ANY) {
215 req = blk_mq_alloc_request(q, op, flags);
217 req = blk_mq_alloc_request_hctx(q, op, flags,
223 req->cmd_flags |= REQ_FAILFAST_DRIVER;
224 nvme_req(req)->cmd = cmd;
228 EXPORT_SYMBOL_GPL(nvme_alloc_request);
230 static inline void nvme_setup_flush(struct nvme_ns *ns,
231 struct nvme_command *cmnd)
233 memset(cmnd, 0, sizeof(*cmnd));
234 cmnd->common.opcode = nvme_cmd_flush;
235 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
238 static inline int nvme_setup_discard(struct nvme_ns *ns, struct request *req,
239 struct nvme_command *cmnd)
241 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
242 struct nvme_dsm_range *range;
245 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
247 return BLK_MQ_RQ_QUEUE_BUSY;
249 __rq_for_each_bio(bio, req) {
250 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
251 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
253 range[n].cattr = cpu_to_le32(0);
254 range[n].nlb = cpu_to_le32(nlb);
255 range[n].slba = cpu_to_le64(slba);
259 if (WARN_ON_ONCE(n != segments)) {
261 return BLK_MQ_RQ_QUEUE_ERROR;
264 memset(cmnd, 0, sizeof(*cmnd));
265 cmnd->dsm.opcode = nvme_cmd_dsm;
266 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
267 cmnd->dsm.nr = segments - 1;
268 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
270 req->special_vec.bv_page = virt_to_page(range);
271 req->special_vec.bv_offset = offset_in_page(range);
272 req->special_vec.bv_len = sizeof(*range) * segments;
273 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
275 return BLK_MQ_RQ_QUEUE_OK;
278 static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
279 struct nvme_command *cmnd)
284 if (req->cmd_flags & REQ_FUA)
285 control |= NVME_RW_FUA;
286 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
287 control |= NVME_RW_LR;
289 if (req->cmd_flags & REQ_RAHEAD)
290 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
292 memset(cmnd, 0, sizeof(*cmnd));
293 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
294 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
295 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
296 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
299 switch (ns->pi_type) {
300 case NVME_NS_DPS_PI_TYPE3:
301 control |= NVME_RW_PRINFO_PRCHK_GUARD;
303 case NVME_NS_DPS_PI_TYPE1:
304 case NVME_NS_DPS_PI_TYPE2:
305 control |= NVME_RW_PRINFO_PRCHK_GUARD |
306 NVME_RW_PRINFO_PRCHK_REF;
307 cmnd->rw.reftag = cpu_to_le32(
308 nvme_block_nr(ns, blk_rq_pos(req)));
311 if (!blk_integrity_rq(req))
312 control |= NVME_RW_PRINFO_PRACT;
315 cmnd->rw.control = cpu_to_le16(control);
316 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
319 int nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
320 struct nvme_command *cmd)
322 int ret = BLK_MQ_RQ_QUEUE_OK;
324 switch (req_op(req)) {
327 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
330 nvme_setup_flush(ns, cmd);
333 ret = nvme_setup_discard(ns, req, cmd);
337 nvme_setup_rw(ns, req, cmd);
341 return BLK_MQ_RQ_QUEUE_ERROR;
344 cmd->common.command_id = req->tag;
347 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
350 * Returns 0 on success. If the result is negative, it's a Linux error code;
351 * if the result is positive, it's an NVM Express status code
353 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
354 union nvme_result *result, void *buffer, unsigned bufflen,
355 unsigned timeout, int qid, int at_head, int flags)
360 req = nvme_alloc_request(q, cmd, flags, qid);
364 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
366 if (buffer && bufflen) {
367 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
372 blk_execute_rq(req->q, NULL, req, at_head);
374 *result = nvme_req(req)->result;
377 blk_mq_free_request(req);
380 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
382 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
383 void *buffer, unsigned bufflen)
385 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
388 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
390 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
391 void __user *ubuffer, unsigned bufflen,
392 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
393 u32 *result, unsigned timeout)
395 bool write = nvme_is_write(cmd);
396 struct nvme_ns *ns = q->queuedata;
397 struct gendisk *disk = ns ? ns->disk : NULL;
399 struct bio *bio = NULL;
403 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
407 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
409 if (ubuffer && bufflen) {
410 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
418 bio->bi_bdev = bdget_disk(disk, 0);
424 if (meta_buffer && meta_len) {
425 struct bio_integrity_payload *bip;
427 meta = kmalloc(meta_len, GFP_KERNEL);
434 if (copy_from_user(meta, meta_buffer,
441 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
447 bip->bip_iter.bi_size = meta_len;
448 bip->bip_iter.bi_sector = meta_seed;
450 ret = bio_integrity_add_page(bio, virt_to_page(meta),
451 meta_len, offset_in_page(meta));
452 if (ret != meta_len) {
459 blk_execute_rq(req->q, disk, req, 0);
462 *result = le32_to_cpu(nvme_req(req)->result.u32);
463 if (meta && !ret && !write) {
464 if (copy_to_user(meta_buffer, meta, meta_len))
471 if (disk && bio->bi_bdev)
473 blk_rq_unmap_user(bio);
476 blk_mq_free_request(req);
480 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
481 void __user *ubuffer, unsigned bufflen, u32 *result,
484 return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
488 static void nvme_keep_alive_end_io(struct request *rq, int error)
490 struct nvme_ctrl *ctrl = rq->end_io_data;
492 blk_mq_free_request(rq);
495 dev_err(ctrl->device,
496 "failed nvme_keep_alive_end_io error=%d\n", error);
500 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
503 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
505 struct nvme_command c;
508 memset(&c, 0, sizeof(c));
509 c.common.opcode = nvme_admin_keep_alive;
511 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
516 rq->timeout = ctrl->kato * HZ;
517 rq->end_io_data = ctrl;
519 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
524 static void nvme_keep_alive_work(struct work_struct *work)
526 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
527 struct nvme_ctrl, ka_work);
529 if (nvme_keep_alive(ctrl)) {
530 /* allocation failure, reset the controller */
531 dev_err(ctrl->device, "keep-alive failed\n");
532 ctrl->ops->reset_ctrl(ctrl);
537 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
539 if (unlikely(ctrl->kato == 0))
542 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
543 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
545 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
547 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
549 if (unlikely(ctrl->kato == 0))
552 cancel_delayed_work_sync(&ctrl->ka_work);
554 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
556 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
558 struct nvme_command c = { };
561 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
562 c.identify.opcode = nvme_admin_identify;
563 c.identify.cns = cpu_to_le32(NVME_ID_CNS_CTRL);
565 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
569 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
570 sizeof(struct nvme_id_ctrl));
576 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
578 struct nvme_command c = { };
580 c.identify.opcode = nvme_admin_identify;
581 c.identify.cns = cpu_to_le32(NVME_ID_CNS_NS_ACTIVE_LIST);
582 c.identify.nsid = cpu_to_le32(nsid);
583 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
586 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
587 struct nvme_id_ns **id)
589 struct nvme_command c = { };
592 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
593 c.identify.opcode = nvme_admin_identify,
594 c.identify.nsid = cpu_to_le32(nsid),
596 *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
600 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
601 sizeof(struct nvme_id_ns));
607 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
608 void *buffer, size_t buflen, u32 *result)
610 struct nvme_command c;
611 union nvme_result res;
614 memset(&c, 0, sizeof(c));
615 c.features.opcode = nvme_admin_get_features;
616 c.features.nsid = cpu_to_le32(nsid);
617 c.features.fid = cpu_to_le32(fid);
619 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, buffer, buflen, 0,
621 if (ret >= 0 && result)
622 *result = le32_to_cpu(res.u32);
626 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
627 void *buffer, size_t buflen, u32 *result)
629 struct nvme_command c;
630 union nvme_result res;
633 memset(&c, 0, sizeof(c));
634 c.features.opcode = nvme_admin_set_features;
635 c.features.fid = cpu_to_le32(fid);
636 c.features.dword11 = cpu_to_le32(dword11);
638 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
639 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
640 if (ret >= 0 && result)
641 *result = le32_to_cpu(res.u32);
645 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
647 struct nvme_command c = { };
650 c.common.opcode = nvme_admin_get_log_page,
651 c.common.nsid = cpu_to_le32(0xFFFFFFFF),
652 c.common.cdw10[0] = cpu_to_le32(
653 (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
656 *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
660 error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
661 sizeof(struct nvme_smart_log));
667 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
669 u32 q_count = (*count - 1) | ((*count - 1) << 16);
671 int status, nr_io_queues;
673 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
679 * Degraded controllers might return an error when setting the queue
680 * count. We still want to be able to bring them online and offer
681 * access to the admin queue, as that might be only way to fix them up.
684 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
687 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
688 *count = min(*count, nr_io_queues);
693 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
695 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
697 struct nvme_user_io io;
698 struct nvme_command c;
699 unsigned length, meta_len;
700 void __user *metadata;
702 if (copy_from_user(&io, uio, sizeof(io)))
710 case nvme_cmd_compare:
716 length = (io.nblocks + 1) << ns->lba_shift;
717 meta_len = (io.nblocks + 1) * ns->ms;
718 metadata = (void __user *)(uintptr_t)io.metadata;
723 } else if (meta_len) {
724 if ((io.metadata & 3) || !io.metadata)
728 memset(&c, 0, sizeof(c));
729 c.rw.opcode = io.opcode;
730 c.rw.flags = io.flags;
731 c.rw.nsid = cpu_to_le32(ns->ns_id);
732 c.rw.slba = cpu_to_le64(io.slba);
733 c.rw.length = cpu_to_le16(io.nblocks);
734 c.rw.control = cpu_to_le16(io.control);
735 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
736 c.rw.reftag = cpu_to_le32(io.reftag);
737 c.rw.apptag = cpu_to_le16(io.apptag);
738 c.rw.appmask = cpu_to_le16(io.appmask);
740 return __nvme_submit_user_cmd(ns->queue, &c,
741 (void __user *)(uintptr_t)io.addr, length,
742 metadata, meta_len, io.slba, NULL, 0);
745 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
746 struct nvme_passthru_cmd __user *ucmd)
748 struct nvme_passthru_cmd cmd;
749 struct nvme_command c;
750 unsigned timeout = 0;
753 if (!capable(CAP_SYS_ADMIN))
755 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
760 memset(&c, 0, sizeof(c));
761 c.common.opcode = cmd.opcode;
762 c.common.flags = cmd.flags;
763 c.common.nsid = cpu_to_le32(cmd.nsid);
764 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
765 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
766 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
767 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
768 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
769 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
770 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
771 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
774 timeout = msecs_to_jiffies(cmd.timeout_ms);
776 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
777 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
778 &cmd.result, timeout);
780 if (put_user(cmd.result, &ucmd->result))
787 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
788 unsigned int cmd, unsigned long arg)
790 struct nvme_ns *ns = bdev->bd_disk->private_data;
794 force_successful_syscall_return();
796 case NVME_IOCTL_ADMIN_CMD:
797 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
798 case NVME_IOCTL_IO_CMD:
799 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
800 case NVME_IOCTL_SUBMIT_IO:
801 return nvme_submit_io(ns, (void __user *)arg);
802 #ifdef CONFIG_BLK_DEV_NVME_SCSI
803 case SG_GET_VERSION_NUM:
804 return nvme_sg_get_version_num((void __user *)arg);
806 return nvme_sg_io(ns, (void __user *)arg);
814 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
815 unsigned int cmd, unsigned long arg)
821 return nvme_ioctl(bdev, mode, cmd, arg);
824 #define nvme_compat_ioctl NULL
827 static int nvme_open(struct block_device *bdev, fmode_t mode)
829 return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
832 static void nvme_release(struct gendisk *disk, fmode_t mode)
834 struct nvme_ns *ns = disk->private_data;
836 module_put(ns->ctrl->ops->module);
840 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
842 /* some standard values */
844 geo->sectors = 1 << 5;
845 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
849 #ifdef CONFIG_BLK_DEV_INTEGRITY
850 static void nvme_init_integrity(struct nvme_ns *ns)
852 struct blk_integrity integrity;
854 memset(&integrity, 0, sizeof(integrity));
855 switch (ns->pi_type) {
856 case NVME_NS_DPS_PI_TYPE3:
857 integrity.profile = &t10_pi_type3_crc;
858 integrity.tag_size = sizeof(u16) + sizeof(u32);
859 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
861 case NVME_NS_DPS_PI_TYPE1:
862 case NVME_NS_DPS_PI_TYPE2:
863 integrity.profile = &t10_pi_type1_crc;
864 integrity.tag_size = sizeof(u16);
865 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
868 integrity.profile = NULL;
871 integrity.tuple_size = ns->ms;
872 blk_integrity_register(ns->disk, &integrity);
873 blk_queue_max_integrity_segments(ns->queue, 1);
876 static void nvme_init_integrity(struct nvme_ns *ns)
879 #endif /* CONFIG_BLK_DEV_INTEGRITY */
881 static void nvme_config_discard(struct nvme_ns *ns)
883 struct nvme_ctrl *ctrl = ns->ctrl;
884 u32 logical_block_size = queue_logical_block_size(ns->queue);
886 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
887 NVME_DSM_MAX_RANGES);
889 if (ctrl->quirks & NVME_QUIRK_DISCARD_ZEROES)
890 ns->queue->limits.discard_zeroes_data = 1;
892 ns->queue->limits.discard_zeroes_data = 0;
894 ns->queue->limits.discard_alignment = logical_block_size;
895 ns->queue->limits.discard_granularity = logical_block_size;
896 blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
897 blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
898 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
901 static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
903 if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
904 dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
908 if ((*id)->ncap == 0) {
913 if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
914 memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
915 if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
916 memcpy(ns->uuid, (*id)->nguid, sizeof(ns->uuid));
921 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
923 struct nvme_ns *ns = disk->private_data;
929 lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
930 ns->lba_shift = id->lbaf[lbaf].ds;
931 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
932 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
935 * If identify namespace failed, use default 512 byte block size so
936 * block layer can use before failing read/write for 0 capacity.
938 if (ns->lba_shift == 0)
940 bs = 1 << ns->lba_shift;
941 /* XXX: PI implementation requires metadata equal t10 pi tuple size */
942 pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
943 id->dps & NVME_NS_DPS_PI_MASK : 0;
945 blk_mq_freeze_queue(disk->queue);
946 if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
948 bs != queue_logical_block_size(disk->queue) ||
949 (ns->ms && ns->ext)))
950 blk_integrity_unregister(disk);
952 ns->pi_type = pi_type;
953 blk_queue_logical_block_size(ns->queue, bs);
955 if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
956 nvme_init_integrity(ns);
957 if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
958 set_capacity(disk, 0);
960 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
962 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
963 nvme_config_discard(ns);
964 blk_mq_unfreeze_queue(disk->queue);
967 static int nvme_revalidate_disk(struct gendisk *disk)
969 struct nvme_ns *ns = disk->private_data;
970 struct nvme_id_ns *id = NULL;
973 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
974 set_capacity(disk, 0);
978 ret = nvme_revalidate_ns(ns, &id);
982 __nvme_revalidate_disk(disk, id);
988 static char nvme_pr_type(enum pr_type type)
991 case PR_WRITE_EXCLUSIVE:
993 case PR_EXCLUSIVE_ACCESS:
995 case PR_WRITE_EXCLUSIVE_REG_ONLY:
997 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
999 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1001 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1008 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1009 u64 key, u64 sa_key, u8 op)
1011 struct nvme_ns *ns = bdev->bd_disk->private_data;
1012 struct nvme_command c;
1013 u8 data[16] = { 0, };
1015 put_unaligned_le64(key, &data[0]);
1016 put_unaligned_le64(sa_key, &data[8]);
1018 memset(&c, 0, sizeof(c));
1019 c.common.opcode = op;
1020 c.common.nsid = cpu_to_le32(ns->ns_id);
1021 c.common.cdw10[0] = cpu_to_le32(cdw10);
1023 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1026 static int nvme_pr_register(struct block_device *bdev, u64 old,
1027 u64 new, unsigned flags)
1031 if (flags & ~PR_FL_IGNORE_KEY)
1034 cdw10 = old ? 2 : 0;
1035 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1036 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1037 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1040 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1041 enum pr_type type, unsigned flags)
1045 if (flags & ~PR_FL_IGNORE_KEY)
1048 cdw10 = nvme_pr_type(type) << 8;
1049 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1050 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1053 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1054 enum pr_type type, bool abort)
1056 u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1057 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1060 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1062 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1063 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1066 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1068 u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1069 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1072 static const struct pr_ops nvme_pr_ops = {
1073 .pr_register = nvme_pr_register,
1074 .pr_reserve = nvme_pr_reserve,
1075 .pr_release = nvme_pr_release,
1076 .pr_preempt = nvme_pr_preempt,
1077 .pr_clear = nvme_pr_clear,
1080 static const struct block_device_operations nvme_fops = {
1081 .owner = THIS_MODULE,
1082 .ioctl = nvme_ioctl,
1083 .compat_ioctl = nvme_compat_ioctl,
1085 .release = nvme_release,
1086 .getgeo = nvme_getgeo,
1087 .revalidate_disk= nvme_revalidate_disk,
1088 .pr_ops = &nvme_pr_ops,
1091 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1093 unsigned long timeout =
1094 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1095 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1098 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1101 if ((csts & NVME_CSTS_RDY) == bit)
1105 if (fatal_signal_pending(current))
1107 if (time_after(jiffies, timeout)) {
1108 dev_err(ctrl->device,
1109 "Device not ready; aborting %s\n", enabled ?
1110 "initialisation" : "reset");
1119 * If the device has been passed off to us in an enabled state, just clear
1120 * the enabled bit. The spec says we should set the 'shutdown notification
1121 * bits', but doing so may cause the device to complete commands to the
1122 * admin queue ... and we don't know what memory that might be pointing at!
1124 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1128 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1129 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1131 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1135 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1136 msleep(NVME_QUIRK_DELAY_AMOUNT);
1138 return nvme_wait_ready(ctrl, cap, false);
1140 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1142 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1145 * Default to a 4K page size, with the intention to update this
1146 * path in the future to accomodate architectures with differing
1147 * kernel and IO page sizes.
1149 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1152 if (page_shift < dev_page_min) {
1153 dev_err(ctrl->device,
1154 "Minimum device page size %u too large for host (%u)\n",
1155 1 << dev_page_min, 1 << page_shift);
1159 ctrl->page_size = 1 << page_shift;
1161 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1162 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1163 ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1164 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1165 ctrl->ctrl_config |= NVME_CC_ENABLE;
1167 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1170 return nvme_wait_ready(ctrl, cap, true);
1172 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1174 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1176 unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1180 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1181 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1183 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1187 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1188 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1192 if (fatal_signal_pending(current))
1194 if (time_after(jiffies, timeout)) {
1195 dev_err(ctrl->device,
1196 "Device shutdown incomplete; abort shutdown\n");
1203 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1205 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1206 struct request_queue *q)
1210 if (ctrl->max_hw_sectors) {
1212 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1214 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1215 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1217 if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1218 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1219 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1220 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1222 blk_queue_write_cache(q, vwc, vwc);
1226 * Initialize the cached copies of the Identify data and various controller
1227 * register in our nvme_ctrl structure. This should be called as soon as
1228 * the admin queue is fully up and running.
1230 int nvme_init_identify(struct nvme_ctrl *ctrl)
1232 struct nvme_id_ctrl *id;
1234 int ret, page_shift;
1237 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1239 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1243 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1245 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1248 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1250 if (ctrl->vs >= NVME_VS(1, 1, 0))
1251 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1253 ret = nvme_identify_ctrl(ctrl, &id);
1255 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1259 ctrl->vid = le16_to_cpu(id->vid);
1260 ctrl->oncs = le16_to_cpup(&id->oncs);
1261 atomic_set(&ctrl->abort_limit, id->acl + 1);
1262 ctrl->vwc = id->vwc;
1263 ctrl->cntlid = le16_to_cpup(&id->cntlid);
1264 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1265 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1266 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1268 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1270 max_hw_sectors = UINT_MAX;
1271 ctrl->max_hw_sectors =
1272 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1274 nvme_set_queue_limits(ctrl, ctrl->admin_q);
1275 ctrl->sgls = le32_to_cpu(id->sgls);
1276 ctrl->kas = le16_to_cpu(id->kas);
1278 if (ctrl->ops->is_fabrics) {
1279 ctrl->icdoff = le16_to_cpu(id->icdoff);
1280 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1281 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1282 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1285 * In fabrics we need to verify the cntlid matches the
1288 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1291 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1293 "keep-alive support is mandatory for fabrics\n");
1297 ctrl->cntlid = le16_to_cpu(id->cntlid);
1303 EXPORT_SYMBOL_GPL(nvme_init_identify);
1305 static int nvme_dev_open(struct inode *inode, struct file *file)
1307 struct nvme_ctrl *ctrl;
1308 int instance = iminor(inode);
1311 spin_lock(&dev_list_lock);
1312 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1313 if (ctrl->instance != instance)
1316 if (!ctrl->admin_q) {
1320 if (!kref_get_unless_zero(&ctrl->kref))
1322 file->private_data = ctrl;
1326 spin_unlock(&dev_list_lock);
1331 static int nvme_dev_release(struct inode *inode, struct file *file)
1333 nvme_put_ctrl(file->private_data);
1337 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1342 mutex_lock(&ctrl->namespaces_mutex);
1343 if (list_empty(&ctrl->namespaces)) {
1348 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1349 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1350 dev_warn(ctrl->device,
1351 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1356 dev_warn(ctrl->device,
1357 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1358 kref_get(&ns->kref);
1359 mutex_unlock(&ctrl->namespaces_mutex);
1361 ret = nvme_user_cmd(ctrl, ns, argp);
1366 mutex_unlock(&ctrl->namespaces_mutex);
1370 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1373 struct nvme_ctrl *ctrl = file->private_data;
1374 void __user *argp = (void __user *)arg;
1377 case NVME_IOCTL_ADMIN_CMD:
1378 return nvme_user_cmd(ctrl, NULL, argp);
1379 case NVME_IOCTL_IO_CMD:
1380 return nvme_dev_user_cmd(ctrl, argp);
1381 case NVME_IOCTL_RESET:
1382 dev_warn(ctrl->device, "resetting controller\n");
1383 return ctrl->ops->reset_ctrl(ctrl);
1384 case NVME_IOCTL_SUBSYS_RESET:
1385 return nvme_reset_subsystem(ctrl);
1386 case NVME_IOCTL_RESCAN:
1387 nvme_queue_scan(ctrl);
1394 static const struct file_operations nvme_dev_fops = {
1395 .owner = THIS_MODULE,
1396 .open = nvme_dev_open,
1397 .release = nvme_dev_release,
1398 .unlocked_ioctl = nvme_dev_ioctl,
1399 .compat_ioctl = nvme_dev_ioctl,
1402 static ssize_t nvme_sysfs_reset(struct device *dev,
1403 struct device_attribute *attr, const char *buf,
1406 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1409 ret = ctrl->ops->reset_ctrl(ctrl);
1414 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1416 static ssize_t nvme_sysfs_rescan(struct device *dev,
1417 struct device_attribute *attr, const char *buf,
1420 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1422 nvme_queue_scan(ctrl);
1425 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1427 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1430 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1431 struct nvme_ctrl *ctrl = ns->ctrl;
1432 int serial_len = sizeof(ctrl->serial);
1433 int model_len = sizeof(ctrl->model);
1435 if (memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1436 return sprintf(buf, "eui.%16phN\n", ns->uuid);
1438 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1439 return sprintf(buf, "eui.%8phN\n", ns->eui);
1441 while (ctrl->serial[serial_len - 1] == ' ')
1443 while (ctrl->model[model_len - 1] == ' ')
1446 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1447 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1449 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1451 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1454 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1455 return sprintf(buf, "%pU\n", ns->uuid);
1457 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1459 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1462 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1463 return sprintf(buf, "%8phd\n", ns->eui);
1465 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1467 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1470 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1471 return sprintf(buf, "%d\n", ns->ns_id);
1473 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1475 static struct attribute *nvme_ns_attrs[] = {
1476 &dev_attr_wwid.attr,
1477 &dev_attr_uuid.attr,
1479 &dev_attr_nsid.attr,
1483 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1484 struct attribute *a, int n)
1486 struct device *dev = container_of(kobj, struct device, kobj);
1487 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1489 if (a == &dev_attr_uuid.attr) {
1490 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1493 if (a == &dev_attr_eui.attr) {
1494 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1500 static const struct attribute_group nvme_ns_attr_group = {
1501 .attrs = nvme_ns_attrs,
1502 .is_visible = nvme_ns_attrs_are_visible,
1505 #define nvme_show_str_function(field) \
1506 static ssize_t field##_show(struct device *dev, \
1507 struct device_attribute *attr, char *buf) \
1509 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1510 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
1512 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1514 #define nvme_show_int_function(field) \
1515 static ssize_t field##_show(struct device *dev, \
1516 struct device_attribute *attr, char *buf) \
1518 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1519 return sprintf(buf, "%d\n", ctrl->field); \
1521 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1523 nvme_show_str_function(model);
1524 nvme_show_str_function(serial);
1525 nvme_show_str_function(firmware_rev);
1526 nvme_show_int_function(cntlid);
1528 static ssize_t nvme_sysfs_delete(struct device *dev,
1529 struct device_attribute *attr, const char *buf,
1532 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1534 if (device_remove_file_self(dev, attr))
1535 ctrl->ops->delete_ctrl(ctrl);
1538 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1540 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1541 struct device_attribute *attr,
1544 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1546 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
1548 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
1550 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
1551 struct device_attribute *attr,
1554 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1556 return snprintf(buf, PAGE_SIZE, "%s\n",
1557 ctrl->ops->get_subsysnqn(ctrl));
1559 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
1561 static ssize_t nvme_sysfs_show_address(struct device *dev,
1562 struct device_attribute *attr,
1565 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1567 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
1569 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
1571 static struct attribute *nvme_dev_attrs[] = {
1572 &dev_attr_reset_controller.attr,
1573 &dev_attr_rescan_controller.attr,
1574 &dev_attr_model.attr,
1575 &dev_attr_serial.attr,
1576 &dev_attr_firmware_rev.attr,
1577 &dev_attr_cntlid.attr,
1578 &dev_attr_delete_controller.attr,
1579 &dev_attr_transport.attr,
1580 &dev_attr_subsysnqn.attr,
1581 &dev_attr_address.attr,
1585 #define CHECK_ATTR(ctrl, a, name) \
1586 if ((a) == &dev_attr_##name.attr && \
1587 !(ctrl)->ops->get_##name) \
1590 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
1591 struct attribute *a, int n)
1593 struct device *dev = container_of(kobj, struct device, kobj);
1594 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1596 if (a == &dev_attr_delete_controller.attr) {
1597 if (!ctrl->ops->delete_ctrl)
1601 CHECK_ATTR(ctrl, a, subsysnqn);
1602 CHECK_ATTR(ctrl, a, address);
1607 static struct attribute_group nvme_dev_attrs_group = {
1608 .attrs = nvme_dev_attrs,
1609 .is_visible = nvme_dev_attrs_are_visible,
1612 static const struct attribute_group *nvme_dev_attr_groups[] = {
1613 &nvme_dev_attrs_group,
1617 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1619 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1620 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1622 return nsa->ns_id - nsb->ns_id;
1625 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1627 struct nvme_ns *ns, *ret = NULL;
1629 mutex_lock(&ctrl->namespaces_mutex);
1630 list_for_each_entry(ns, &ctrl->namespaces, list) {
1631 if (ns->ns_id == nsid) {
1632 kref_get(&ns->kref);
1636 if (ns->ns_id > nsid)
1639 mutex_unlock(&ctrl->namespaces_mutex);
1643 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1646 struct gendisk *disk;
1647 struct nvme_id_ns *id;
1648 char disk_name[DISK_NAME_LEN];
1649 int node = dev_to_node(ctrl->dev);
1651 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
1655 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
1656 if (ns->instance < 0)
1659 ns->queue = blk_mq_init_queue(ctrl->tagset);
1660 if (IS_ERR(ns->queue))
1661 goto out_release_instance;
1662 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1663 ns->queue->queuedata = ns;
1666 kref_init(&ns->kref);
1668 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
1670 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1671 nvme_set_queue_limits(ctrl, ns->queue);
1673 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
1675 if (nvme_revalidate_ns(ns, &id))
1676 goto out_free_queue;
1678 if (nvme_nvm_ns_supported(ns, id) &&
1679 nvme_nvm_register(ns, disk_name, node)) {
1680 dev_warn(ctrl->dev, "%s: LightNVM init failure\n", __func__);
1684 disk = alloc_disk_node(0, node);
1688 disk->fops = &nvme_fops;
1689 disk->private_data = ns;
1690 disk->queue = ns->queue;
1691 disk->flags = GENHD_FL_EXT_DEVT;
1692 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
1695 __nvme_revalidate_disk(disk, id);
1697 mutex_lock(&ctrl->namespaces_mutex);
1698 list_add_tail(&ns->list, &ctrl->namespaces);
1699 mutex_unlock(&ctrl->namespaces_mutex);
1701 kref_get(&ctrl->kref);
1705 device_add_disk(ctrl->device, ns->disk);
1706 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
1707 &nvme_ns_attr_group))
1708 pr_warn("%s: failed to create sysfs group for identification\n",
1709 ns->disk->disk_name);
1710 if (ns->ndev && nvme_nvm_register_sysfs(ns))
1711 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
1712 ns->disk->disk_name);
1717 blk_cleanup_queue(ns->queue);
1718 out_release_instance:
1719 ida_simple_remove(&ctrl->ns_ida, ns->instance);
1724 static void nvme_ns_remove(struct nvme_ns *ns)
1726 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
1729 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
1730 if (blk_get_integrity(ns->disk))
1731 blk_integrity_unregister(ns->disk);
1732 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
1733 &nvme_ns_attr_group);
1735 nvme_nvm_unregister_sysfs(ns);
1736 del_gendisk(ns->disk);
1737 blk_mq_abort_requeue_list(ns->queue);
1738 blk_cleanup_queue(ns->queue);
1741 mutex_lock(&ns->ctrl->namespaces_mutex);
1742 list_del_init(&ns->list);
1743 mutex_unlock(&ns->ctrl->namespaces_mutex);
1748 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1752 ns = nvme_find_get_ns(ctrl, nsid);
1754 if (ns->disk && revalidate_disk(ns->disk))
1758 nvme_alloc_ns(ctrl, nsid);
1761 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
1764 struct nvme_ns *ns, *next;
1766 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
1767 if (ns->ns_id > nsid)
1772 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
1776 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
1779 ns_list = kzalloc(0x1000, GFP_KERNEL);
1783 for (i = 0; i < num_lists; i++) {
1784 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
1788 for (j = 0; j < min(nn, 1024U); j++) {
1789 nsid = le32_to_cpu(ns_list[j]);
1793 nvme_validate_ns(ctrl, nsid);
1795 while (++prev < nsid) {
1796 ns = nvme_find_get_ns(ctrl, prev);
1806 nvme_remove_invalid_namespaces(ctrl, prev);
1812 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
1816 for (i = 1; i <= nn; i++)
1817 nvme_validate_ns(ctrl, i);
1819 nvme_remove_invalid_namespaces(ctrl, nn);
1822 static void nvme_scan_work(struct work_struct *work)
1824 struct nvme_ctrl *ctrl =
1825 container_of(work, struct nvme_ctrl, scan_work);
1826 struct nvme_id_ctrl *id;
1829 if (ctrl->state != NVME_CTRL_LIVE)
1832 if (nvme_identify_ctrl(ctrl, &id))
1835 nn = le32_to_cpu(id->nn);
1836 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1837 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
1838 if (!nvme_scan_ns_list(ctrl, nn))
1841 nvme_scan_ns_sequential(ctrl, nn);
1843 mutex_lock(&ctrl->namespaces_mutex);
1844 list_sort(NULL, &ctrl->namespaces, ns_cmp);
1845 mutex_unlock(&ctrl->namespaces_mutex);
1849 void nvme_queue_scan(struct nvme_ctrl *ctrl)
1852 * Do not queue new scan work when a controller is reset during
1855 if (ctrl->state == NVME_CTRL_LIVE)
1856 schedule_work(&ctrl->scan_work);
1858 EXPORT_SYMBOL_GPL(nvme_queue_scan);
1861 * This function iterates the namespace list unlocked to allow recovery from
1862 * controller failure. It is up to the caller to ensure the namespace list is
1863 * not modified by scan work while this function is executing.
1865 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
1867 struct nvme_ns *ns, *next;
1870 * The dead states indicates the controller was not gracefully
1871 * disconnected. In that case, we won't be able to flush any data while
1872 * removing the namespaces' disks; fail all the queues now to avoid
1873 * potentially having to clean up the failed sync later.
1875 if (ctrl->state == NVME_CTRL_DEAD)
1876 nvme_kill_queues(ctrl);
1878 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
1881 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
1883 static void nvme_async_event_work(struct work_struct *work)
1885 struct nvme_ctrl *ctrl =
1886 container_of(work, struct nvme_ctrl, async_event_work);
1888 spin_lock_irq(&ctrl->lock);
1889 while (ctrl->event_limit > 0) {
1890 int aer_idx = --ctrl->event_limit;
1892 spin_unlock_irq(&ctrl->lock);
1893 ctrl->ops->submit_async_event(ctrl, aer_idx);
1894 spin_lock_irq(&ctrl->lock);
1896 spin_unlock_irq(&ctrl->lock);
1899 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
1900 union nvme_result *res)
1902 u32 result = le32_to_cpu(res->u32);
1905 switch (le16_to_cpu(status) >> 1) {
1906 case NVME_SC_SUCCESS:
1909 case NVME_SC_ABORT_REQ:
1910 ++ctrl->event_limit;
1911 schedule_work(&ctrl->async_event_work);
1920 switch (result & 0xff07) {
1921 case NVME_AER_NOTICE_NS_CHANGED:
1922 dev_info(ctrl->device, "rescanning\n");
1923 nvme_queue_scan(ctrl);
1926 dev_warn(ctrl->device, "async event result %08x\n", result);
1929 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
1931 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
1933 ctrl->event_limit = NVME_NR_AERS;
1934 schedule_work(&ctrl->async_event_work);
1936 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
1938 static DEFINE_IDA(nvme_instance_ida);
1940 static int nvme_set_instance(struct nvme_ctrl *ctrl)
1942 int instance, error;
1945 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
1948 spin_lock(&dev_list_lock);
1949 error = ida_get_new(&nvme_instance_ida, &instance);
1950 spin_unlock(&dev_list_lock);
1951 } while (error == -EAGAIN);
1956 ctrl->instance = instance;
1960 static void nvme_release_instance(struct nvme_ctrl *ctrl)
1962 spin_lock(&dev_list_lock);
1963 ida_remove(&nvme_instance_ida, ctrl->instance);
1964 spin_unlock(&dev_list_lock);
1967 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
1969 flush_work(&ctrl->async_event_work);
1970 flush_work(&ctrl->scan_work);
1971 nvme_remove_namespaces(ctrl);
1973 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
1975 spin_lock(&dev_list_lock);
1976 list_del(&ctrl->node);
1977 spin_unlock(&dev_list_lock);
1979 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
1981 static void nvme_free_ctrl(struct kref *kref)
1983 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
1985 put_device(ctrl->device);
1986 nvme_release_instance(ctrl);
1987 ida_destroy(&ctrl->ns_ida);
1989 ctrl->ops->free_ctrl(ctrl);
1992 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
1994 kref_put(&ctrl->kref, nvme_free_ctrl);
1996 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
1999 * Initialize a NVMe controller structures. This needs to be called during
2000 * earliest initialization so that we have the initialized structured around
2003 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2004 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2008 ctrl->state = NVME_CTRL_NEW;
2009 spin_lock_init(&ctrl->lock);
2010 INIT_LIST_HEAD(&ctrl->namespaces);
2011 mutex_init(&ctrl->namespaces_mutex);
2012 kref_init(&ctrl->kref);
2015 ctrl->quirks = quirks;
2016 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2017 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2019 ret = nvme_set_instance(ctrl);
2023 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2024 MKDEV(nvme_char_major, ctrl->instance),
2025 ctrl, nvme_dev_attr_groups,
2026 "nvme%d", ctrl->instance);
2027 if (IS_ERR(ctrl->device)) {
2028 ret = PTR_ERR(ctrl->device);
2029 goto out_release_instance;
2031 get_device(ctrl->device);
2032 ida_init(&ctrl->ns_ida);
2034 spin_lock(&dev_list_lock);
2035 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2036 spin_unlock(&dev_list_lock);
2039 out_release_instance:
2040 nvme_release_instance(ctrl);
2044 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2047 * nvme_kill_queues(): Ends all namespace queues
2048 * @ctrl: the dead controller that needs to end
2050 * Call this function when the driver determines it is unable to get the
2051 * controller in a state capable of servicing IO.
2053 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2057 mutex_lock(&ctrl->namespaces_mutex);
2058 list_for_each_entry(ns, &ctrl->namespaces, list) {
2060 * Revalidating a dead namespace sets capacity to 0. This will
2061 * end buffered writers dirtying pages that can't be synced.
2063 if (ns->disk && !test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2064 revalidate_disk(ns->disk);
2066 blk_set_queue_dying(ns->queue);
2067 blk_mq_abort_requeue_list(ns->queue);
2068 blk_mq_start_stopped_hw_queues(ns->queue, true);
2070 mutex_unlock(&ctrl->namespaces_mutex);
2072 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2074 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2078 mutex_lock(&ctrl->namespaces_mutex);
2079 list_for_each_entry(ns, &ctrl->namespaces, list)
2080 blk_mq_quiesce_queue(ns->queue);
2081 mutex_unlock(&ctrl->namespaces_mutex);
2083 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2085 void nvme_start_queues(struct nvme_ctrl *ctrl)
2089 mutex_lock(&ctrl->namespaces_mutex);
2090 list_for_each_entry(ns, &ctrl->namespaces, list) {
2091 blk_mq_start_stopped_hw_queues(ns->queue, true);
2092 blk_mq_kick_requeue_list(ns->queue);
2094 mutex_unlock(&ctrl->namespaces_mutex);
2096 EXPORT_SYMBOL_GPL(nvme_start_queues);
2098 int __init nvme_core_init(void)
2102 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2106 else if (result > 0)
2107 nvme_char_major = result;
2109 nvme_class = class_create(THIS_MODULE, "nvme");
2110 if (IS_ERR(nvme_class)) {
2111 result = PTR_ERR(nvme_class);
2112 goto unregister_chrdev;
2118 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2122 void nvme_core_exit(void)
2124 class_destroy(nvme_class);
2125 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2128 MODULE_LICENSE("GPL");
2129 MODULE_VERSION("1.0");
2130 module_init(nvme_core_init);
2131 module_exit(nvme_core_exit);