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)
206 blk_mq_requeue_request(req);
207 spin_lock_irqsave(req->q->queue_lock, flags);
208 if (!blk_queue_stopped(req->q))
209 blk_mq_kick_requeue_list(req->q);
210 spin_unlock_irqrestore(req->q->queue_lock, flags);
212 EXPORT_SYMBOL_GPL(nvme_requeue_req);
214 struct request *nvme_alloc_request(struct request_queue *q,
215 struct nvme_command *cmd, unsigned int flags, int qid)
219 if (qid == NVME_QID_ANY) {
220 req = blk_mq_alloc_request(q, nvme_is_write(cmd), flags);
222 req = blk_mq_alloc_request_hctx(q, nvme_is_write(cmd), flags,
228 req->cmd_type = REQ_TYPE_DRV_PRIV;
229 req->cmd_flags |= REQ_FAILFAST_DRIVER;
230 req->cmd = (unsigned char *)cmd;
231 req->cmd_len = sizeof(struct nvme_command);
235 EXPORT_SYMBOL_GPL(nvme_alloc_request);
237 static inline void nvme_setup_flush(struct nvme_ns *ns,
238 struct nvme_command *cmnd)
240 memset(cmnd, 0, sizeof(*cmnd));
241 cmnd->common.opcode = nvme_cmd_flush;
242 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
245 static inline int nvme_setup_discard(struct nvme_ns *ns, struct request *req,
246 struct nvme_command *cmnd)
248 struct nvme_dsm_range *range;
251 unsigned int nr_bytes = blk_rq_bytes(req);
253 range = kmalloc(sizeof(*range), GFP_ATOMIC);
255 return BLK_MQ_RQ_QUEUE_BUSY;
257 range->cattr = cpu_to_le32(0);
258 range->nlb = cpu_to_le32(nr_bytes >> ns->lba_shift);
259 range->slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
261 memset(cmnd, 0, sizeof(*cmnd));
262 cmnd->dsm.opcode = nvme_cmd_dsm;
263 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
265 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
267 req->completion_data = range;
268 page = virt_to_page(range);
269 offset = offset_in_page(range);
270 blk_add_request_payload(req, page, offset, sizeof(*range));
273 * we set __data_len back to the size of the area to be discarded
274 * on disk. This allows us to report completion on the full amount
275 * of blocks described by the request.
277 req->__data_len = nr_bytes;
282 static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
283 struct nvme_command *cmnd)
288 if (req->cmd_flags & REQ_FUA)
289 control |= NVME_RW_FUA;
290 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
291 control |= NVME_RW_LR;
293 if (req->cmd_flags & REQ_RAHEAD)
294 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
296 memset(cmnd, 0, sizeof(*cmnd));
297 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
298 cmnd->rw.command_id = req->tag;
299 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
300 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
301 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
304 switch (ns->pi_type) {
305 case NVME_NS_DPS_PI_TYPE3:
306 control |= NVME_RW_PRINFO_PRCHK_GUARD;
308 case NVME_NS_DPS_PI_TYPE1:
309 case NVME_NS_DPS_PI_TYPE2:
310 control |= NVME_RW_PRINFO_PRCHK_GUARD |
311 NVME_RW_PRINFO_PRCHK_REF;
312 cmnd->rw.reftag = cpu_to_le32(
313 nvme_block_nr(ns, blk_rq_pos(req)));
316 if (!blk_integrity_rq(req))
317 control |= NVME_RW_PRINFO_PRACT;
320 cmnd->rw.control = cpu_to_le16(control);
321 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
324 int nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
325 struct nvme_command *cmd)
329 if (req->cmd_type == REQ_TYPE_DRV_PRIV)
330 memcpy(cmd, req->cmd, sizeof(*cmd));
331 else if (req_op(req) == REQ_OP_FLUSH)
332 nvme_setup_flush(ns, cmd);
333 else if (req_op(req) == REQ_OP_DISCARD)
334 ret = nvme_setup_discard(ns, req, cmd);
336 nvme_setup_rw(ns, req, cmd);
340 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
343 * Returns 0 on success. If the result is negative, it's a Linux error code;
344 * if the result is positive, it's an NVM Express status code
346 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
347 struct nvme_completion *cqe, void *buffer, unsigned bufflen,
348 unsigned timeout, int qid, int at_head, int flags)
353 req = nvme_alloc_request(q, cmd, flags, qid);
357 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
360 if (buffer && bufflen) {
361 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
366 blk_execute_rq(req->q, NULL, req, at_head);
369 blk_mq_free_request(req);
372 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
374 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
375 void *buffer, unsigned bufflen)
377 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
380 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
382 int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
383 void __user *ubuffer, unsigned bufflen,
384 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
385 u32 *result, unsigned timeout)
387 bool write = nvme_is_write(cmd);
388 struct nvme_completion cqe;
389 struct nvme_ns *ns = q->queuedata;
390 struct gendisk *disk = ns ? ns->disk : NULL;
392 struct bio *bio = NULL;
396 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
400 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
403 if (ubuffer && bufflen) {
404 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
412 bio->bi_bdev = bdget_disk(disk, 0);
418 if (meta_buffer && meta_len) {
419 struct bio_integrity_payload *bip;
421 meta = kmalloc(meta_len, GFP_KERNEL);
428 if (copy_from_user(meta, meta_buffer,
435 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
441 bip->bip_iter.bi_size = meta_len;
442 bip->bip_iter.bi_sector = meta_seed;
444 ret = bio_integrity_add_page(bio, virt_to_page(meta),
445 meta_len, offset_in_page(meta));
446 if (ret != meta_len) {
453 blk_execute_rq(req->q, disk, req, 0);
456 *result = le32_to_cpu(cqe.result);
457 if (meta && !ret && !write) {
458 if (copy_to_user(meta_buffer, meta, meta_len))
465 if (disk && bio->bi_bdev)
467 blk_rq_unmap_user(bio);
470 blk_mq_free_request(req);
474 int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
475 void __user *ubuffer, unsigned bufflen, u32 *result,
478 return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
482 static void nvme_keep_alive_end_io(struct request *rq, int error)
484 struct nvme_ctrl *ctrl = rq->end_io_data;
486 blk_mq_free_request(rq);
489 dev_err(ctrl->device,
490 "failed nvme_keep_alive_end_io error=%d\n", error);
494 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
497 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
499 struct nvme_command c;
502 memset(&c, 0, sizeof(c));
503 c.common.opcode = nvme_admin_keep_alive;
505 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
510 rq->timeout = ctrl->kato * HZ;
511 rq->end_io_data = ctrl;
513 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
518 static void nvme_keep_alive_work(struct work_struct *work)
520 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
521 struct nvme_ctrl, ka_work);
523 if (nvme_keep_alive(ctrl)) {
524 /* allocation failure, reset the controller */
525 dev_err(ctrl->device, "keep-alive failed\n");
526 ctrl->ops->reset_ctrl(ctrl);
531 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
533 if (unlikely(ctrl->kato == 0))
536 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
537 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
539 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
541 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
543 if (unlikely(ctrl->kato == 0))
546 cancel_delayed_work_sync(&ctrl->ka_work);
548 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
550 int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
552 struct nvme_command c = { };
555 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
556 c.identify.opcode = nvme_admin_identify;
557 c.identify.cns = cpu_to_le32(NVME_ID_CNS_CTRL);
559 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
563 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
564 sizeof(struct nvme_id_ctrl));
570 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
572 struct nvme_command c = { };
574 c.identify.opcode = nvme_admin_identify;
575 c.identify.cns = cpu_to_le32(NVME_ID_CNS_NS_ACTIVE_LIST);
576 c.identify.nsid = cpu_to_le32(nsid);
577 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
580 int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
581 struct nvme_id_ns **id)
583 struct nvme_command c = { };
586 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
587 c.identify.opcode = nvme_admin_identify,
588 c.identify.nsid = cpu_to_le32(nsid),
590 *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
594 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
595 sizeof(struct nvme_id_ns));
601 int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
602 void *buffer, size_t buflen, u32 *result)
604 struct nvme_command c;
605 struct nvme_completion cqe;
608 memset(&c, 0, sizeof(c));
609 c.features.opcode = nvme_admin_get_features;
610 c.features.nsid = cpu_to_le32(nsid);
611 c.features.fid = cpu_to_le32(fid);
613 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &cqe, buffer, buflen, 0,
615 if (ret >= 0 && result)
616 *result = le32_to_cpu(cqe.result);
620 int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
621 void *buffer, size_t buflen, u32 *result)
623 struct nvme_command c;
624 struct nvme_completion cqe;
627 memset(&c, 0, sizeof(c));
628 c.features.opcode = nvme_admin_set_features;
629 c.features.fid = cpu_to_le32(fid);
630 c.features.dword11 = cpu_to_le32(dword11);
632 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &cqe,
633 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
634 if (ret >= 0 && result)
635 *result = le32_to_cpu(cqe.result);
639 int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
641 struct nvme_command c = { };
644 c.common.opcode = nvme_admin_get_log_page,
645 c.common.nsid = cpu_to_le32(0xFFFFFFFF),
646 c.common.cdw10[0] = cpu_to_le32(
647 (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
650 *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
654 error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
655 sizeof(struct nvme_smart_log));
661 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
663 u32 q_count = (*count - 1) | ((*count - 1) << 16);
665 int status, nr_io_queues;
667 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
673 * Degraded controllers might return an error when setting the queue
674 * count. We still want to be able to bring them online and offer
675 * access to the admin queue, as that might be only way to fix them up.
678 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
681 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
682 *count = min(*count, nr_io_queues);
687 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
689 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
691 struct nvme_user_io io;
692 struct nvme_command c;
693 unsigned length, meta_len;
694 void __user *metadata;
696 if (copy_from_user(&io, uio, sizeof(io)))
704 case nvme_cmd_compare:
710 length = (io.nblocks + 1) << ns->lba_shift;
711 meta_len = (io.nblocks + 1) * ns->ms;
712 metadata = (void __user *)(uintptr_t)io.metadata;
717 } else if (meta_len) {
718 if ((io.metadata & 3) || !io.metadata)
722 memset(&c, 0, sizeof(c));
723 c.rw.opcode = io.opcode;
724 c.rw.flags = io.flags;
725 c.rw.nsid = cpu_to_le32(ns->ns_id);
726 c.rw.slba = cpu_to_le64(io.slba);
727 c.rw.length = cpu_to_le16(io.nblocks);
728 c.rw.control = cpu_to_le16(io.control);
729 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
730 c.rw.reftag = cpu_to_le32(io.reftag);
731 c.rw.apptag = cpu_to_le16(io.apptag);
732 c.rw.appmask = cpu_to_le16(io.appmask);
734 return __nvme_submit_user_cmd(ns->queue, &c,
735 (void __user *)(uintptr_t)io.addr, length,
736 metadata, meta_len, io.slba, NULL, 0);
739 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
740 struct nvme_passthru_cmd __user *ucmd)
742 struct nvme_passthru_cmd cmd;
743 struct nvme_command c;
744 unsigned timeout = 0;
747 if (!capable(CAP_SYS_ADMIN))
749 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
754 memset(&c, 0, sizeof(c));
755 c.common.opcode = cmd.opcode;
756 c.common.flags = cmd.flags;
757 c.common.nsid = cpu_to_le32(cmd.nsid);
758 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
759 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
760 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
761 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
762 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
763 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
764 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
765 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
768 timeout = msecs_to_jiffies(cmd.timeout_ms);
770 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
771 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
772 &cmd.result, timeout);
774 if (put_user(cmd.result, &ucmd->result))
781 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
782 unsigned int cmd, unsigned long arg)
784 struct nvme_ns *ns = bdev->bd_disk->private_data;
788 force_successful_syscall_return();
790 case NVME_IOCTL_ADMIN_CMD:
791 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
792 case NVME_IOCTL_IO_CMD:
793 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
794 case NVME_IOCTL_SUBMIT_IO:
795 return nvme_submit_io(ns, (void __user *)arg);
796 #ifdef CONFIG_BLK_DEV_NVME_SCSI
797 case SG_GET_VERSION_NUM:
798 return nvme_sg_get_version_num((void __user *)arg);
800 return nvme_sg_io(ns, (void __user *)arg);
808 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
809 unsigned int cmd, unsigned long arg)
815 return nvme_ioctl(bdev, mode, cmd, arg);
818 #define nvme_compat_ioctl NULL
821 static int nvme_open(struct block_device *bdev, fmode_t mode)
823 return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
826 static void nvme_release(struct gendisk *disk, fmode_t mode)
828 struct nvme_ns *ns = disk->private_data;
830 module_put(ns->ctrl->ops->module);
834 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
836 /* some standard values */
838 geo->sectors = 1 << 5;
839 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
843 #ifdef CONFIG_BLK_DEV_INTEGRITY
844 static void nvme_init_integrity(struct nvme_ns *ns)
846 struct blk_integrity integrity;
848 memset(&integrity, 0, sizeof(integrity));
849 switch (ns->pi_type) {
850 case NVME_NS_DPS_PI_TYPE3:
851 integrity.profile = &t10_pi_type3_crc;
852 integrity.tag_size = sizeof(u16) + sizeof(u32);
853 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
855 case NVME_NS_DPS_PI_TYPE1:
856 case NVME_NS_DPS_PI_TYPE2:
857 integrity.profile = &t10_pi_type1_crc;
858 integrity.tag_size = sizeof(u16);
859 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
862 integrity.profile = NULL;
865 integrity.tuple_size = ns->ms;
866 blk_integrity_register(ns->disk, &integrity);
867 blk_queue_max_integrity_segments(ns->queue, 1);
870 static void nvme_init_integrity(struct nvme_ns *ns)
873 #endif /* CONFIG_BLK_DEV_INTEGRITY */
875 static void nvme_config_discard(struct nvme_ns *ns)
877 struct nvme_ctrl *ctrl = ns->ctrl;
878 u32 logical_block_size = queue_logical_block_size(ns->queue);
880 if (ctrl->quirks & NVME_QUIRK_DISCARD_ZEROES)
881 ns->queue->limits.discard_zeroes_data = 1;
883 ns->queue->limits.discard_zeroes_data = 0;
885 ns->queue->limits.discard_alignment = logical_block_size;
886 ns->queue->limits.discard_granularity = logical_block_size;
887 blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
888 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
891 static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
893 if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
894 dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
898 if ((*id)->ncap == 0) {
903 if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
904 memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
905 if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
906 memcpy(ns->uuid, (*id)->nguid, sizeof(ns->uuid));
911 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
913 struct nvme_ns *ns = disk->private_data;
919 lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
920 ns->lba_shift = id->lbaf[lbaf].ds;
921 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
922 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
925 * If identify namespace failed, use default 512 byte block size so
926 * block layer can use before failing read/write for 0 capacity.
928 if (ns->lba_shift == 0)
930 bs = 1 << ns->lba_shift;
931 /* XXX: PI implementation requires metadata equal t10 pi tuple size */
932 pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
933 id->dps & NVME_NS_DPS_PI_MASK : 0;
935 blk_mq_freeze_queue(disk->queue);
936 if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
938 bs != queue_logical_block_size(disk->queue) ||
939 (ns->ms && ns->ext)))
940 blk_integrity_unregister(disk);
942 ns->pi_type = pi_type;
943 blk_queue_logical_block_size(ns->queue, bs);
945 if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
946 nvme_init_integrity(ns);
947 if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
948 set_capacity(disk, 0);
950 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
952 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
953 nvme_config_discard(ns);
954 blk_mq_unfreeze_queue(disk->queue);
957 static int nvme_revalidate_disk(struct gendisk *disk)
959 struct nvme_ns *ns = disk->private_data;
960 struct nvme_id_ns *id = NULL;
963 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
964 set_capacity(disk, 0);
968 ret = nvme_revalidate_ns(ns, &id);
972 __nvme_revalidate_disk(disk, id);
978 static char nvme_pr_type(enum pr_type type)
981 case PR_WRITE_EXCLUSIVE:
983 case PR_EXCLUSIVE_ACCESS:
985 case PR_WRITE_EXCLUSIVE_REG_ONLY:
987 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
989 case PR_WRITE_EXCLUSIVE_ALL_REGS:
991 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
998 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
999 u64 key, u64 sa_key, u8 op)
1001 struct nvme_ns *ns = bdev->bd_disk->private_data;
1002 struct nvme_command c;
1003 u8 data[16] = { 0, };
1005 put_unaligned_le64(key, &data[0]);
1006 put_unaligned_le64(sa_key, &data[8]);
1008 memset(&c, 0, sizeof(c));
1009 c.common.opcode = op;
1010 c.common.nsid = cpu_to_le32(ns->ns_id);
1011 c.common.cdw10[0] = cpu_to_le32(cdw10);
1013 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1016 static int nvme_pr_register(struct block_device *bdev, u64 old,
1017 u64 new, unsigned flags)
1021 if (flags & ~PR_FL_IGNORE_KEY)
1024 cdw10 = old ? 2 : 0;
1025 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1026 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1027 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1030 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1031 enum pr_type type, unsigned flags)
1035 if (flags & ~PR_FL_IGNORE_KEY)
1038 cdw10 = nvme_pr_type(type) << 8;
1039 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1040 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1043 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1044 enum pr_type type, bool abort)
1046 u32 cdw10 = nvme_pr_type(type) << 8 | (abort ? 2 : 1);
1048 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1051 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1053 u32 cdw10 = 1 | (key ? 0 : 1 << 3);
1055 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1058 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1060 u32 cdw10 = nvme_pr_type(type) << 8 | (key ? 0 : 1 << 3);
1062 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1065 static const struct pr_ops nvme_pr_ops = {
1066 .pr_register = nvme_pr_register,
1067 .pr_reserve = nvme_pr_reserve,
1068 .pr_release = nvme_pr_release,
1069 .pr_preempt = nvme_pr_preempt,
1070 .pr_clear = nvme_pr_clear,
1073 static const struct block_device_operations nvme_fops = {
1074 .owner = THIS_MODULE,
1075 .ioctl = nvme_ioctl,
1076 .compat_ioctl = nvme_compat_ioctl,
1078 .release = nvme_release,
1079 .getgeo = nvme_getgeo,
1080 .revalidate_disk= nvme_revalidate_disk,
1081 .pr_ops = &nvme_pr_ops,
1084 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1086 unsigned long timeout =
1087 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1088 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1091 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1094 if ((csts & NVME_CSTS_RDY) == bit)
1098 if (fatal_signal_pending(current))
1100 if (time_after(jiffies, timeout)) {
1101 dev_err(ctrl->device,
1102 "Device not ready; aborting %s\n", enabled ?
1103 "initialisation" : "reset");
1112 * If the device has been passed off to us in an enabled state, just clear
1113 * the enabled bit. The spec says we should set the 'shutdown notification
1114 * bits', but doing so may cause the device to complete commands to the
1115 * admin queue ... and we don't know what memory that might be pointing at!
1117 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1121 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1122 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1124 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1128 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1129 msleep(NVME_QUIRK_DELAY_AMOUNT);
1131 return nvme_wait_ready(ctrl, cap, false);
1133 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1135 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1138 * Default to a 4K page size, with the intention to update this
1139 * path in the future to accomodate architectures with differing
1140 * kernel and IO page sizes.
1142 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1145 if (page_shift < dev_page_min) {
1146 dev_err(ctrl->device,
1147 "Minimum device page size %u too large for host (%u)\n",
1148 1 << dev_page_min, 1 << page_shift);
1152 ctrl->page_size = 1 << page_shift;
1154 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1155 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1156 ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1157 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1158 ctrl->ctrl_config |= NVME_CC_ENABLE;
1160 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1163 return nvme_wait_ready(ctrl, cap, true);
1165 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1167 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1169 unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1173 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1174 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1176 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1180 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1181 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1185 if (fatal_signal_pending(current))
1187 if (time_after(jiffies, timeout)) {
1188 dev_err(ctrl->device,
1189 "Device shutdown incomplete; abort shutdown\n");
1196 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1198 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1199 struct request_queue *q)
1203 if (ctrl->max_hw_sectors) {
1205 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1207 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1208 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1210 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1211 is_power_of_2(ctrl->max_hw_sectors))
1212 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1213 blk_queue_virt_boundary(q, ctrl->page_size - 1);
1214 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1216 blk_queue_write_cache(q, vwc, vwc);
1220 * Initialize the cached copies of the Identify data and various controller
1221 * register in our nvme_ctrl structure. This should be called as soon as
1222 * the admin queue is fully up and running.
1224 int nvme_init_identify(struct nvme_ctrl *ctrl)
1226 struct nvme_id_ctrl *id;
1228 int ret, page_shift;
1231 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1233 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1237 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1239 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1242 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1244 if (ctrl->vs >= NVME_VS(1, 1, 0))
1245 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1247 ret = nvme_identify_ctrl(ctrl, &id);
1249 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1253 ctrl->vid = le16_to_cpu(id->vid);
1254 ctrl->oncs = le16_to_cpup(&id->oncs);
1255 atomic_set(&ctrl->abort_limit, id->acl + 1);
1256 ctrl->vwc = id->vwc;
1257 ctrl->cntlid = le16_to_cpup(&id->cntlid);
1258 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1259 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1260 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1262 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1264 max_hw_sectors = UINT_MAX;
1265 ctrl->max_hw_sectors =
1266 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1268 nvme_set_queue_limits(ctrl, ctrl->admin_q);
1269 ctrl->sgls = le32_to_cpu(id->sgls);
1270 ctrl->kas = le16_to_cpu(id->kas);
1272 if (ctrl->ops->is_fabrics) {
1273 ctrl->icdoff = le16_to_cpu(id->icdoff);
1274 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1275 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1276 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1279 * In fabrics we need to verify the cntlid matches the
1282 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1285 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1287 "keep-alive support is mandatory for fabrics\n");
1291 ctrl->cntlid = le16_to_cpu(id->cntlid);
1297 EXPORT_SYMBOL_GPL(nvme_init_identify);
1299 static int nvme_dev_open(struct inode *inode, struct file *file)
1301 struct nvme_ctrl *ctrl;
1302 int instance = iminor(inode);
1305 spin_lock(&dev_list_lock);
1306 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1307 if (ctrl->instance != instance)
1310 if (!ctrl->admin_q) {
1314 if (!kref_get_unless_zero(&ctrl->kref))
1316 file->private_data = ctrl;
1320 spin_unlock(&dev_list_lock);
1325 static int nvme_dev_release(struct inode *inode, struct file *file)
1327 nvme_put_ctrl(file->private_data);
1331 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1336 mutex_lock(&ctrl->namespaces_mutex);
1337 if (list_empty(&ctrl->namespaces)) {
1342 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1343 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1344 dev_warn(ctrl->device,
1345 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1350 dev_warn(ctrl->device,
1351 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1352 kref_get(&ns->kref);
1353 mutex_unlock(&ctrl->namespaces_mutex);
1355 ret = nvme_user_cmd(ctrl, ns, argp);
1360 mutex_unlock(&ctrl->namespaces_mutex);
1364 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1367 struct nvme_ctrl *ctrl = file->private_data;
1368 void __user *argp = (void __user *)arg;
1371 case NVME_IOCTL_ADMIN_CMD:
1372 return nvme_user_cmd(ctrl, NULL, argp);
1373 case NVME_IOCTL_IO_CMD:
1374 return nvme_dev_user_cmd(ctrl, argp);
1375 case NVME_IOCTL_RESET:
1376 dev_warn(ctrl->device, "resetting controller\n");
1377 return ctrl->ops->reset_ctrl(ctrl);
1378 case NVME_IOCTL_SUBSYS_RESET:
1379 return nvme_reset_subsystem(ctrl);
1380 case NVME_IOCTL_RESCAN:
1381 nvme_queue_scan(ctrl);
1388 static const struct file_operations nvme_dev_fops = {
1389 .owner = THIS_MODULE,
1390 .open = nvme_dev_open,
1391 .release = nvme_dev_release,
1392 .unlocked_ioctl = nvme_dev_ioctl,
1393 .compat_ioctl = nvme_dev_ioctl,
1396 static ssize_t nvme_sysfs_reset(struct device *dev,
1397 struct device_attribute *attr, const char *buf,
1400 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1403 ret = ctrl->ops->reset_ctrl(ctrl);
1408 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1410 static ssize_t nvme_sysfs_rescan(struct device *dev,
1411 struct device_attribute *attr, const char *buf,
1414 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1416 nvme_queue_scan(ctrl);
1419 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1421 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1424 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1425 struct nvme_ctrl *ctrl = ns->ctrl;
1426 int serial_len = sizeof(ctrl->serial);
1427 int model_len = sizeof(ctrl->model);
1429 if (memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1430 return sprintf(buf, "eui.%16phN\n", ns->uuid);
1432 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1433 return sprintf(buf, "eui.%8phN\n", ns->eui);
1435 while (ctrl->serial[serial_len - 1] == ' ')
1437 while (ctrl->model[model_len - 1] == ' ')
1440 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1441 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1443 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1445 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1448 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1449 return sprintf(buf, "%pU\n", ns->uuid);
1451 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1453 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1456 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1457 return sprintf(buf, "%8phd\n", ns->eui);
1459 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1461 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1464 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1465 return sprintf(buf, "%d\n", ns->ns_id);
1467 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1469 static struct attribute *nvme_ns_attrs[] = {
1470 &dev_attr_wwid.attr,
1471 &dev_attr_uuid.attr,
1473 &dev_attr_nsid.attr,
1477 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1478 struct attribute *a, int n)
1480 struct device *dev = container_of(kobj, struct device, kobj);
1481 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1483 if (a == &dev_attr_uuid.attr) {
1484 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1487 if (a == &dev_attr_eui.attr) {
1488 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1494 static const struct attribute_group nvme_ns_attr_group = {
1495 .attrs = nvme_ns_attrs,
1496 .is_visible = nvme_ns_attrs_are_visible,
1499 #define nvme_show_str_function(field) \
1500 static ssize_t field##_show(struct device *dev, \
1501 struct device_attribute *attr, char *buf) \
1503 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1504 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
1506 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1508 #define nvme_show_int_function(field) \
1509 static ssize_t field##_show(struct device *dev, \
1510 struct device_attribute *attr, char *buf) \
1512 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1513 return sprintf(buf, "%d\n", ctrl->field); \
1515 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1517 nvme_show_str_function(model);
1518 nvme_show_str_function(serial);
1519 nvme_show_str_function(firmware_rev);
1520 nvme_show_int_function(cntlid);
1522 static ssize_t nvme_sysfs_delete(struct device *dev,
1523 struct device_attribute *attr, const char *buf,
1526 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1528 if (device_remove_file_self(dev, attr))
1529 ctrl->ops->delete_ctrl(ctrl);
1532 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1534 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1535 struct device_attribute *attr,
1538 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1540 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
1542 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
1544 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
1545 struct device_attribute *attr,
1548 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1550 return snprintf(buf, PAGE_SIZE, "%s\n",
1551 ctrl->ops->get_subsysnqn(ctrl));
1553 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
1555 static ssize_t nvme_sysfs_show_address(struct device *dev,
1556 struct device_attribute *attr,
1559 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1561 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
1563 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
1565 static struct attribute *nvme_dev_attrs[] = {
1566 &dev_attr_reset_controller.attr,
1567 &dev_attr_rescan_controller.attr,
1568 &dev_attr_model.attr,
1569 &dev_attr_serial.attr,
1570 &dev_attr_firmware_rev.attr,
1571 &dev_attr_cntlid.attr,
1572 &dev_attr_delete_controller.attr,
1573 &dev_attr_transport.attr,
1574 &dev_attr_subsysnqn.attr,
1575 &dev_attr_address.attr,
1579 #define CHECK_ATTR(ctrl, a, name) \
1580 if ((a) == &dev_attr_##name.attr && \
1581 !(ctrl)->ops->get_##name) \
1584 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
1585 struct attribute *a, int n)
1587 struct device *dev = container_of(kobj, struct device, kobj);
1588 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1590 if (a == &dev_attr_delete_controller.attr) {
1591 if (!ctrl->ops->delete_ctrl)
1595 CHECK_ATTR(ctrl, a, subsysnqn);
1596 CHECK_ATTR(ctrl, a, address);
1601 static struct attribute_group nvme_dev_attrs_group = {
1602 .attrs = nvme_dev_attrs,
1603 .is_visible = nvme_dev_attrs_are_visible,
1606 static const struct attribute_group *nvme_dev_attr_groups[] = {
1607 &nvme_dev_attrs_group,
1611 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1613 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1614 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1616 return nsa->ns_id - nsb->ns_id;
1619 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1621 struct nvme_ns *ns, *ret = NULL;
1623 mutex_lock(&ctrl->namespaces_mutex);
1624 list_for_each_entry(ns, &ctrl->namespaces, list) {
1625 if (ns->ns_id == nsid) {
1626 if (!kref_get_unless_zero(&ns->kref))
1631 if (ns->ns_id > nsid)
1634 mutex_unlock(&ctrl->namespaces_mutex);
1638 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1641 struct gendisk *disk;
1642 struct nvme_id_ns *id;
1643 char disk_name[DISK_NAME_LEN];
1644 int node = dev_to_node(ctrl->dev);
1646 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
1650 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
1651 if (ns->instance < 0)
1654 ns->queue = blk_mq_init_queue(ctrl->tagset);
1655 if (IS_ERR(ns->queue))
1656 goto out_release_instance;
1657 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1658 ns->queue->queuedata = ns;
1661 kref_init(&ns->kref);
1663 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
1665 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1666 nvme_set_queue_limits(ctrl, ns->queue);
1668 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
1670 if (nvme_revalidate_ns(ns, &id))
1671 goto out_free_queue;
1673 if (nvme_nvm_ns_supported(ns, id)) {
1674 if (nvme_nvm_register(ns, disk_name, node,
1675 &nvme_ns_attr_group)) {
1676 dev_warn(ctrl->dev, "%s: LightNVM init failure\n",
1681 disk = alloc_disk_node(0, node);
1685 disk->fops = &nvme_fops;
1686 disk->private_data = ns;
1687 disk->queue = ns->queue;
1688 disk->flags = GENHD_FL_EXT_DEVT;
1689 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
1692 __nvme_revalidate_disk(disk, id);
1695 mutex_lock(&ctrl->namespaces_mutex);
1696 list_add_tail(&ns->list, &ctrl->namespaces);
1697 mutex_unlock(&ctrl->namespaces_mutex);
1699 kref_get(&ctrl->kref);
1706 device_add_disk(ctrl->device, ns->disk);
1707 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
1708 &nvme_ns_attr_group))
1709 pr_warn("%s: failed to create sysfs group for identification\n",
1710 ns->disk->disk_name);
1715 blk_cleanup_queue(ns->queue);
1716 out_release_instance:
1717 ida_simple_remove(&ctrl->ns_ida, ns->instance);
1722 static void nvme_ns_remove(struct nvme_ns *ns)
1724 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
1727 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
1728 if (blk_get_integrity(ns->disk))
1729 blk_integrity_unregister(ns->disk);
1730 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
1731 &nvme_ns_attr_group);
1732 del_gendisk(ns->disk);
1733 blk_cleanup_queue(ns->queue);
1736 mutex_lock(&ns->ctrl->namespaces_mutex);
1737 list_del_init(&ns->list);
1738 mutex_unlock(&ns->ctrl->namespaces_mutex);
1743 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1747 ns = nvme_find_get_ns(ctrl, nsid);
1749 if (ns->disk && revalidate_disk(ns->disk))
1753 nvme_alloc_ns(ctrl, nsid);
1756 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
1759 struct nvme_ns *ns, *next;
1761 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
1762 if (ns->ns_id > nsid)
1767 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
1771 unsigned i, j, nsid, prev = 0;
1772 unsigned num_lists = DIV_ROUND_UP_ULL((u64)nn, 1024);
1775 ns_list = kzalloc(0x1000, GFP_KERNEL);
1779 for (i = 0; i < num_lists; i++) {
1780 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
1784 for (j = 0; j < min(nn, 1024U); j++) {
1785 nsid = le32_to_cpu(ns_list[j]);
1789 nvme_validate_ns(ctrl, nsid);
1791 while (++prev < nsid) {
1792 ns = nvme_find_get_ns(ctrl, prev);
1802 nvme_remove_invalid_namespaces(ctrl, prev);
1808 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
1812 for (i = 1; i <= nn; i++)
1813 nvme_validate_ns(ctrl, i);
1815 nvme_remove_invalid_namespaces(ctrl, nn);
1818 static void nvme_scan_work(struct work_struct *work)
1820 struct nvme_ctrl *ctrl =
1821 container_of(work, struct nvme_ctrl, scan_work);
1822 struct nvme_id_ctrl *id;
1825 if (ctrl->state != NVME_CTRL_LIVE)
1828 if (nvme_identify_ctrl(ctrl, &id))
1831 nn = le32_to_cpu(id->nn);
1832 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1833 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
1834 if (!nvme_scan_ns_list(ctrl, nn))
1837 nvme_scan_ns_sequential(ctrl, nn);
1839 mutex_lock(&ctrl->namespaces_mutex);
1840 list_sort(NULL, &ctrl->namespaces, ns_cmp);
1841 mutex_unlock(&ctrl->namespaces_mutex);
1845 void nvme_queue_scan(struct nvme_ctrl *ctrl)
1848 * Do not queue new scan work when a controller is reset during
1851 if (ctrl->state == NVME_CTRL_LIVE)
1852 schedule_work(&ctrl->scan_work);
1854 EXPORT_SYMBOL_GPL(nvme_queue_scan);
1857 * This function iterates the namespace list unlocked to allow recovery from
1858 * controller failure. It is up to the caller to ensure the namespace list is
1859 * not modified by scan work while this function is executing.
1861 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
1863 struct nvme_ns *ns, *next;
1866 * The dead states indicates the controller was not gracefully
1867 * disconnected. In that case, we won't be able to flush any data while
1868 * removing the namespaces' disks; fail all the queues now to avoid
1869 * potentially having to clean up the failed sync later.
1871 if (ctrl->state == NVME_CTRL_DEAD)
1872 nvme_kill_queues(ctrl);
1874 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
1877 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
1879 static void nvme_async_event_work(struct work_struct *work)
1881 struct nvme_ctrl *ctrl =
1882 container_of(work, struct nvme_ctrl, async_event_work);
1884 spin_lock_irq(&ctrl->lock);
1885 while (ctrl->event_limit > 0) {
1886 int aer_idx = --ctrl->event_limit;
1888 spin_unlock_irq(&ctrl->lock);
1889 ctrl->ops->submit_async_event(ctrl, aer_idx);
1890 spin_lock_irq(&ctrl->lock);
1892 spin_unlock_irq(&ctrl->lock);
1895 void nvme_complete_async_event(struct nvme_ctrl *ctrl,
1896 struct nvme_completion *cqe)
1898 u16 status = le16_to_cpu(cqe->status) >> 1;
1899 u32 result = le32_to_cpu(cqe->result);
1901 if (status == NVME_SC_SUCCESS || status == NVME_SC_ABORT_REQ) {
1902 ++ctrl->event_limit;
1903 schedule_work(&ctrl->async_event_work);
1906 if (status != NVME_SC_SUCCESS)
1909 switch (result & 0xff07) {
1910 case NVME_AER_NOTICE_NS_CHANGED:
1911 dev_info(ctrl->device, "rescanning\n");
1912 nvme_queue_scan(ctrl);
1915 dev_warn(ctrl->device, "async event result %08x\n", result);
1918 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
1920 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
1922 ctrl->event_limit = NVME_NR_AERS;
1923 schedule_work(&ctrl->async_event_work);
1925 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
1927 static DEFINE_IDA(nvme_instance_ida);
1929 static int nvme_set_instance(struct nvme_ctrl *ctrl)
1931 int instance, error;
1934 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
1937 spin_lock(&dev_list_lock);
1938 error = ida_get_new(&nvme_instance_ida, &instance);
1939 spin_unlock(&dev_list_lock);
1940 } while (error == -EAGAIN);
1945 ctrl->instance = instance;
1949 static void nvme_release_instance(struct nvme_ctrl *ctrl)
1951 spin_lock(&dev_list_lock);
1952 ida_remove(&nvme_instance_ida, ctrl->instance);
1953 spin_unlock(&dev_list_lock);
1956 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
1958 flush_work(&ctrl->async_event_work);
1959 flush_work(&ctrl->scan_work);
1960 nvme_remove_namespaces(ctrl);
1962 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
1964 spin_lock(&dev_list_lock);
1965 list_del(&ctrl->node);
1966 spin_unlock(&dev_list_lock);
1968 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
1970 static void nvme_free_ctrl(struct kref *kref)
1972 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
1974 put_device(ctrl->device);
1975 nvme_release_instance(ctrl);
1976 ida_destroy(&ctrl->ns_ida);
1978 ctrl->ops->free_ctrl(ctrl);
1981 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
1983 kref_put(&ctrl->kref, nvme_free_ctrl);
1985 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
1988 * Initialize a NVMe controller structures. This needs to be called during
1989 * earliest initialization so that we have the initialized structured around
1992 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
1993 const struct nvme_ctrl_ops *ops, unsigned long quirks)
1997 ctrl->state = NVME_CTRL_NEW;
1998 spin_lock_init(&ctrl->lock);
1999 INIT_LIST_HEAD(&ctrl->namespaces);
2000 mutex_init(&ctrl->namespaces_mutex);
2001 kref_init(&ctrl->kref);
2004 ctrl->quirks = quirks;
2005 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2006 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2008 ret = nvme_set_instance(ctrl);
2012 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2013 MKDEV(nvme_char_major, ctrl->instance),
2014 ctrl, nvme_dev_attr_groups,
2015 "nvme%d", ctrl->instance);
2016 if (IS_ERR(ctrl->device)) {
2017 ret = PTR_ERR(ctrl->device);
2018 goto out_release_instance;
2020 get_device(ctrl->device);
2021 ida_init(&ctrl->ns_ida);
2023 spin_lock(&dev_list_lock);
2024 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2025 spin_unlock(&dev_list_lock);
2028 out_release_instance:
2029 nvme_release_instance(ctrl);
2033 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2036 * nvme_kill_queues(): Ends all namespace queues
2037 * @ctrl: the dead controller that needs to end
2039 * Call this function when the driver determines it is unable to get the
2040 * controller in a state capable of servicing IO.
2042 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2046 mutex_lock(&ctrl->namespaces_mutex);
2048 /* Forcibly start all queues to avoid having stuck requests */
2050 blk_mq_start_hw_queues(ctrl->admin_q);
2052 list_for_each_entry(ns, &ctrl->namespaces, list) {
2054 * Revalidating a dead namespace sets capacity to 0. This will
2055 * end buffered writers dirtying pages that can't be synced.
2057 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2059 revalidate_disk(ns->disk);
2060 blk_set_queue_dying(ns->queue);
2063 * Forcibly start all queues to avoid having stuck requests.
2064 * Note that we must ensure the queues are not stopped
2065 * when the final removal happens.
2067 blk_mq_start_hw_queues(ns->queue);
2069 /* draining requests in requeue list */
2070 blk_mq_kick_requeue_list(ns->queue);
2072 mutex_unlock(&ctrl->namespaces_mutex);
2074 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2076 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2080 mutex_lock(&ctrl->namespaces_mutex);
2081 list_for_each_entry(ns, &ctrl->namespaces, list) {
2082 spin_lock_irq(ns->queue->queue_lock);
2083 queue_flag_set(QUEUE_FLAG_STOPPED, ns->queue);
2084 spin_unlock_irq(ns->queue->queue_lock);
2086 blk_mq_cancel_requeue_work(ns->queue);
2087 blk_mq_stop_hw_queues(ns->queue);
2089 mutex_unlock(&ctrl->namespaces_mutex);
2091 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2093 void nvme_start_queues(struct nvme_ctrl *ctrl)
2097 mutex_lock(&ctrl->namespaces_mutex);
2098 list_for_each_entry(ns, &ctrl->namespaces, list) {
2099 queue_flag_clear_unlocked(QUEUE_FLAG_STOPPED, ns->queue);
2100 blk_mq_start_stopped_hw_queues(ns->queue, true);
2101 blk_mq_kick_requeue_list(ns->queue);
2103 mutex_unlock(&ctrl->namespaces_mutex);
2105 EXPORT_SYMBOL_GPL(nvme_start_queues);
2107 int __init nvme_core_init(void)
2111 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2115 else if (result > 0)
2116 nvme_char_major = result;
2118 nvme_class = class_create(THIS_MODULE, "nvme");
2119 if (IS_ERR(nvme_class)) {
2120 result = PTR_ERR(nvme_class);
2121 goto unregister_chrdev;
2127 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2131 void nvme_core_exit(void)
2133 class_destroy(nvme_class);
2134 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2137 MODULE_LICENSE("GPL");
2138 MODULE_VERSION("1.0");
2139 module_init(nvme_core_init);
2140 module_exit(nvme_core_exit);