2 * NVM Express device driver
3 * Copyright (c) 2011, 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
14 * You should have received a copy of the GNU General Public License along with
15 * this program; if not, write to the Free Software Foundation, Inc.,
16 * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
19 #include <linux/nvme.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/delay.h>
24 #include <linux/errno.h>
26 #include <linux/genhd.h>
27 #include <linux/idr.h>
28 #include <linux/init.h>
29 #include <linux/interrupt.h>
31 #include <linux/kdev_t.h>
32 #include <linux/kthread.h>
33 #include <linux/kernel.h>
35 #include <linux/module.h>
36 #include <linux/moduleparam.h>
37 #include <linux/pci.h>
38 #include <linux/poison.h>
39 #include <linux/ptrace.h>
40 #include <linux/sched.h>
41 #include <linux/slab.h>
42 #include <linux/types.h>
44 #include <asm-generic/io-64-nonatomic-lo-hi.h>
46 #define NVME_Q_DEPTH 1024
47 #define SQ_SIZE(depth) (depth * sizeof(struct nvme_command))
48 #define CQ_SIZE(depth) (depth * sizeof(struct nvme_completion))
49 #define ADMIN_TIMEOUT (60 * HZ)
51 static int nvme_major;
52 module_param(nvme_major, int, 0);
54 static int use_threaded_interrupts;
55 module_param(use_threaded_interrupts, int, 0);
57 static DEFINE_SPINLOCK(dev_list_lock);
58 static LIST_HEAD(dev_list);
59 static struct task_struct *nvme_thread;
60 static struct workqueue_struct *nvme_workq;
62 static void nvme_reset_failed_dev(struct work_struct *ws);
64 struct async_cmd_info {
65 struct kthread_work work;
66 struct kthread_worker *worker;
73 * An NVM Express queue. Each device has at least two (one for admin
74 * commands and one for I/O commands).
77 struct device *q_dmadev;
80 struct nvme_command *sq_cmds;
81 volatile struct nvme_completion *cqes;
82 dma_addr_t sq_dma_addr;
83 dma_addr_t cq_dma_addr;
84 wait_queue_head_t sq_full;
85 wait_queue_t sq_cong_wait;
86 struct bio_list sq_cong;
97 struct async_cmd_info cmdinfo;
98 unsigned long cmdid_data[];
102 * Check we didin't inadvertently grow the command struct
104 static inline void _nvme_check_size(void)
106 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
107 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
108 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
109 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
110 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
111 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
112 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
113 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
114 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
115 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
116 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
117 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
120 typedef void (*nvme_completion_fn)(struct nvme_dev *, void *,
121 struct nvme_completion *);
123 struct nvme_cmd_info {
124 nvme_completion_fn fn;
126 unsigned long timeout;
130 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
132 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
135 static unsigned nvme_queue_extra(int depth)
137 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
141 * alloc_cmdid() - Allocate a Command ID
142 * @nvmeq: The queue that will be used for this command
143 * @ctx: A pointer that will be passed to the handler
144 * @handler: The function to call on completion
146 * Allocate a Command ID for a queue. The data passed in will
147 * be passed to the completion handler. This is implemented by using
148 * the bottom two bits of the ctx pointer to store the handler ID.
149 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
150 * We can change this if it becomes a problem.
152 * May be called with local interrupts disabled and the q_lock held,
153 * or with interrupts enabled and no locks held.
155 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
156 nvme_completion_fn handler, unsigned timeout)
158 int depth = nvmeq->q_depth - 1;
159 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
163 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
166 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
168 info[cmdid].fn = handler;
169 info[cmdid].ctx = ctx;
170 info[cmdid].timeout = jiffies + timeout;
171 info[cmdid].aborted = 0;
175 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
176 nvme_completion_fn handler, unsigned timeout)
179 wait_event_killable(nvmeq->sq_full,
180 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
181 return (cmdid < 0) ? -EINTR : cmdid;
184 /* Special values must be less than 0x1000 */
185 #define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
186 #define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
187 #define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
188 #define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
189 #define CMD_CTX_FLUSH (0x318 + CMD_CTX_BASE)
190 #define CMD_CTX_ABORT (0x31C + CMD_CTX_BASE)
192 static void special_completion(struct nvme_dev *dev, void *ctx,
193 struct nvme_completion *cqe)
195 if (ctx == CMD_CTX_CANCELLED)
197 if (ctx == CMD_CTX_FLUSH)
199 if (ctx == CMD_CTX_ABORT) {
203 if (ctx == CMD_CTX_COMPLETED) {
204 dev_warn(&dev->pci_dev->dev,
205 "completed id %d twice on queue %d\n",
206 cqe->command_id, le16_to_cpup(&cqe->sq_id));
209 if (ctx == CMD_CTX_INVALID) {
210 dev_warn(&dev->pci_dev->dev,
211 "invalid id %d completed on queue %d\n",
212 cqe->command_id, le16_to_cpup(&cqe->sq_id));
216 dev_warn(&dev->pci_dev->dev, "Unknown special completion %p\n", ctx);
219 static void async_completion(struct nvme_dev *dev, void *ctx,
220 struct nvme_completion *cqe)
222 struct async_cmd_info *cmdinfo = ctx;
223 cmdinfo->result = le32_to_cpup(&cqe->result);
224 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
225 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
229 * Called with local interrupts disabled and the q_lock held. May not sleep.
231 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
232 nvme_completion_fn *fn)
235 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
237 if (cmdid >= nvmeq->q_depth) {
238 *fn = special_completion;
239 return CMD_CTX_INVALID;
242 *fn = info[cmdid].fn;
243 ctx = info[cmdid].ctx;
244 info[cmdid].fn = special_completion;
245 info[cmdid].ctx = CMD_CTX_COMPLETED;
246 clear_bit(cmdid, nvmeq->cmdid_data);
247 wake_up(&nvmeq->sq_full);
251 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
252 nvme_completion_fn *fn)
255 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
257 *fn = info[cmdid].fn;
258 ctx = info[cmdid].ctx;
259 info[cmdid].fn = special_completion;
260 info[cmdid].ctx = CMD_CTX_CANCELLED;
264 struct nvme_queue *get_nvmeq(struct nvme_dev *dev)
266 return dev->queues[get_cpu() + 1];
269 void put_nvmeq(struct nvme_queue *nvmeq)
275 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
276 * @nvmeq: The queue to use
277 * @cmd: The command to send
279 * Safe to use from interrupt context
281 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
285 spin_lock_irqsave(&nvmeq->q_lock, flags);
286 tail = nvmeq->sq_tail;
287 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
288 if (++tail == nvmeq->q_depth)
290 writel(tail, nvmeq->q_db);
291 nvmeq->sq_tail = tail;
292 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
297 static __le64 **iod_list(struct nvme_iod *iod)
299 return ((void *)iod) + iod->offset;
303 * Will slightly overestimate the number of pages needed. This is OK
304 * as it only leads to a small amount of wasted memory for the lifetime of
307 static int nvme_npages(unsigned size)
309 unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
310 return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
313 static struct nvme_iod *
314 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
316 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
317 sizeof(__le64 *) * nvme_npages(nbytes) +
318 sizeof(struct scatterlist) * nseg, gfp);
321 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
323 iod->length = nbytes;
325 iod->start_time = jiffies;
331 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
333 const int last_prp = PAGE_SIZE / 8 - 1;
335 __le64 **list = iod_list(iod);
336 dma_addr_t prp_dma = iod->first_dma;
338 if (iod->npages == 0)
339 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
340 for (i = 0; i < iod->npages; i++) {
341 __le64 *prp_list = list[i];
342 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
343 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
344 prp_dma = next_prp_dma;
349 static void nvme_start_io_acct(struct bio *bio)
351 struct gendisk *disk = bio->bi_bdev->bd_disk;
352 const int rw = bio_data_dir(bio);
353 int cpu = part_stat_lock();
354 part_round_stats(cpu, &disk->part0);
355 part_stat_inc(cpu, &disk->part0, ios[rw]);
356 part_stat_add(cpu, &disk->part0, sectors[rw], bio_sectors(bio));
357 part_inc_in_flight(&disk->part0, rw);
361 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
363 struct gendisk *disk = bio->bi_bdev->bd_disk;
364 const int rw = bio_data_dir(bio);
365 unsigned long duration = jiffies - start_time;
366 int cpu = part_stat_lock();
367 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
368 part_round_stats(cpu, &disk->part0);
369 part_dec_in_flight(&disk->part0, rw);
373 static void bio_completion(struct nvme_dev *dev, void *ctx,
374 struct nvme_completion *cqe)
376 struct nvme_iod *iod = ctx;
377 struct bio *bio = iod->private;
378 u16 status = le16_to_cpup(&cqe->status) >> 1;
381 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
382 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
383 nvme_end_io_acct(bio, iod->start_time);
385 nvme_free_iod(dev, iod);
387 bio_endio(bio, -EIO);
392 /* length is in bytes. gfp flags indicates whether we may sleep. */
393 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_common_command *cmd,
394 struct nvme_iod *iod, int total_len, gfp_t gfp)
396 struct dma_pool *pool;
397 int length = total_len;
398 struct scatterlist *sg = iod->sg;
399 int dma_len = sg_dma_len(sg);
400 u64 dma_addr = sg_dma_address(sg);
401 int offset = offset_in_page(dma_addr);
403 __le64 **list = iod_list(iod);
407 cmd->prp1 = cpu_to_le64(dma_addr);
408 length -= (PAGE_SIZE - offset);
412 dma_len -= (PAGE_SIZE - offset);
414 dma_addr += (PAGE_SIZE - offset);
417 dma_addr = sg_dma_address(sg);
418 dma_len = sg_dma_len(sg);
421 if (length <= PAGE_SIZE) {
422 cmd->prp2 = cpu_to_le64(dma_addr);
426 nprps = DIV_ROUND_UP(length, PAGE_SIZE);
427 if (nprps <= (256 / 8)) {
428 pool = dev->prp_small_pool;
431 pool = dev->prp_page_pool;
435 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
437 cmd->prp2 = cpu_to_le64(dma_addr);
439 return (total_len - length) + PAGE_SIZE;
442 iod->first_dma = prp_dma;
443 cmd->prp2 = cpu_to_le64(prp_dma);
446 if (i == PAGE_SIZE / 8) {
447 __le64 *old_prp_list = prp_list;
448 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
450 return total_len - length;
451 list[iod->npages++] = prp_list;
452 prp_list[0] = old_prp_list[i - 1];
453 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
456 prp_list[i++] = cpu_to_le64(dma_addr);
457 dma_len -= PAGE_SIZE;
458 dma_addr += PAGE_SIZE;
466 dma_addr = sg_dma_address(sg);
467 dma_len = sg_dma_len(sg);
473 struct nvme_bio_pair {
474 struct bio b1, b2, *parent;
475 struct bio_vec *bv1, *bv2;
480 static void nvme_bio_pair_endio(struct bio *bio, int err)
482 struct nvme_bio_pair *bp = bio->bi_private;
487 if (atomic_dec_and_test(&bp->cnt)) {
488 bio_endio(bp->parent, bp->err);
495 static struct nvme_bio_pair *nvme_bio_split(struct bio *bio, int idx,
498 struct nvme_bio_pair *bp;
500 BUG_ON(len > bio->bi_size);
501 BUG_ON(idx > bio->bi_vcnt);
503 bp = kmalloc(sizeof(*bp), GFP_ATOMIC);
511 bp->b1.bi_size = len;
512 bp->b2.bi_size -= len;
513 bp->b1.bi_vcnt = idx;
515 bp->b2.bi_sector += len >> 9;
518 bp->bv1 = kmalloc(bio->bi_max_vecs * sizeof(struct bio_vec),
523 bp->bv2 = kmalloc(bio->bi_max_vecs * sizeof(struct bio_vec),
528 memcpy(bp->bv1, bio->bi_io_vec,
529 bio->bi_max_vecs * sizeof(struct bio_vec));
530 memcpy(bp->bv2, bio->bi_io_vec,
531 bio->bi_max_vecs * sizeof(struct bio_vec));
533 bp->b1.bi_io_vec = bp->bv1;
534 bp->b2.bi_io_vec = bp->bv2;
535 bp->b2.bi_io_vec[idx].bv_offset += offset;
536 bp->b2.bi_io_vec[idx].bv_len -= offset;
537 bp->b1.bi_io_vec[idx].bv_len = offset;
540 bp->bv1 = bp->bv2 = NULL;
542 bp->b1.bi_private = bp;
543 bp->b2.bi_private = bp;
545 bp->b1.bi_end_io = nvme_bio_pair_endio;
546 bp->b2.bi_end_io = nvme_bio_pair_endio;
549 atomic_set(&bp->cnt, 2);
560 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
561 int idx, int len, int offset)
563 struct nvme_bio_pair *bp = nvme_bio_split(bio, idx, len, offset);
567 if (bio_list_empty(&nvmeq->sq_cong))
568 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
569 bio_list_add(&nvmeq->sq_cong, &bp->b1);
570 bio_list_add(&nvmeq->sq_cong, &bp->b2);
575 /* NVMe scatterlists require no holes in the virtual address */
576 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
577 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
579 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
580 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
582 struct bio_vec *bvec, *bvprv = NULL;
583 struct scatterlist *sg = NULL;
584 int i, length = 0, nsegs = 0, split_len = bio->bi_size;
586 if (nvmeq->dev->stripe_size)
587 split_len = nvmeq->dev->stripe_size -
588 ((bio->bi_sector << 9) & (nvmeq->dev->stripe_size - 1));
590 sg_init_table(iod->sg, psegs);
591 bio_for_each_segment(bvec, bio, i) {
592 if (bvprv && BIOVEC_PHYS_MERGEABLE(bvprv, bvec)) {
593 sg->length += bvec->bv_len;
595 if (bvprv && BIOVEC_NOT_VIRT_MERGEABLE(bvprv, bvec))
596 return nvme_split_and_submit(bio, nvmeq, i,
599 sg = sg ? sg + 1 : iod->sg;
600 sg_set_page(sg, bvec->bv_page, bvec->bv_len,
605 if (split_len - length < bvec->bv_len)
606 return nvme_split_and_submit(bio, nvmeq, i, split_len,
608 length += bvec->bv_len;
613 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
616 BUG_ON(length != bio->bi_size);
621 * We reuse the small pool to allocate the 16-byte range here as it is not
622 * worth having a special pool for these or additional cases to handle freeing
625 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
626 struct bio *bio, struct nvme_iod *iod, int cmdid)
628 struct nvme_dsm_range *range;
629 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
631 range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
636 iod_list(iod)[0] = (__le64 *)range;
639 range->cattr = cpu_to_le32(0);
640 range->nlb = cpu_to_le32(bio->bi_size >> ns->lba_shift);
641 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_sector));
643 memset(cmnd, 0, sizeof(*cmnd));
644 cmnd->dsm.opcode = nvme_cmd_dsm;
645 cmnd->dsm.command_id = cmdid;
646 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
647 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
649 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
651 if (++nvmeq->sq_tail == nvmeq->q_depth)
653 writel(nvmeq->sq_tail, nvmeq->q_db);
658 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
661 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
663 memset(cmnd, 0, sizeof(*cmnd));
664 cmnd->common.opcode = nvme_cmd_flush;
665 cmnd->common.command_id = cmdid;
666 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
668 if (++nvmeq->sq_tail == nvmeq->q_depth)
670 writel(nvmeq->sq_tail, nvmeq->q_db);
675 int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
677 int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
678 special_completion, NVME_IO_TIMEOUT);
679 if (unlikely(cmdid < 0))
682 return nvme_submit_flush(nvmeq, ns, cmdid);
686 * Called with local interrupts disabled and the q_lock held. May not sleep.
688 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
691 struct nvme_command *cmnd;
692 struct nvme_iod *iod;
693 enum dma_data_direction dma_dir;
694 int cmdid, length, result;
697 int psegs = bio_phys_segments(ns->queue, bio);
699 if ((bio->bi_rw & REQ_FLUSH) && psegs) {
700 result = nvme_submit_flush_data(nvmeq, ns);
706 iod = nvme_alloc_iod(psegs, bio->bi_size, GFP_ATOMIC);
712 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
713 if (unlikely(cmdid < 0))
716 if (bio->bi_rw & REQ_DISCARD) {
717 result = nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
722 if ((bio->bi_rw & REQ_FLUSH) && !psegs)
723 return nvme_submit_flush(nvmeq, ns, cmdid);
726 if (bio->bi_rw & REQ_FUA)
727 control |= NVME_RW_FUA;
728 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
729 control |= NVME_RW_LR;
732 if (bio->bi_rw & REQ_RAHEAD)
733 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
735 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
737 memset(cmnd, 0, sizeof(*cmnd));
738 if (bio_data_dir(bio)) {
739 cmnd->rw.opcode = nvme_cmd_write;
740 dma_dir = DMA_TO_DEVICE;
742 cmnd->rw.opcode = nvme_cmd_read;
743 dma_dir = DMA_FROM_DEVICE;
746 result = nvme_map_bio(nvmeq, iod, bio, dma_dir, psegs);
751 cmnd->rw.command_id = cmdid;
752 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
753 length = nvme_setup_prps(nvmeq->dev, &cmnd->common, iod, length,
755 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_sector));
756 cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
757 cmnd->rw.control = cpu_to_le16(control);
758 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
760 nvme_start_io_acct(bio);
761 if (++nvmeq->sq_tail == nvmeq->q_depth)
763 writel(nvmeq->sq_tail, nvmeq->q_db);
768 free_cmdid(nvmeq, cmdid, NULL);
770 nvme_free_iod(nvmeq->dev, iod);
775 static int nvme_process_cq(struct nvme_queue *nvmeq)
779 head = nvmeq->cq_head;
780 phase = nvmeq->cq_phase;
784 nvme_completion_fn fn;
785 struct nvme_completion cqe = nvmeq->cqes[head];
786 if ((le16_to_cpu(cqe.status) & 1) != phase)
788 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
789 if (++head == nvmeq->q_depth) {
794 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
795 fn(nvmeq->dev, ctx, &cqe);
798 /* If the controller ignores the cq head doorbell and continuously
799 * writes to the queue, it is theoretically possible to wrap around
800 * the queue twice and mistakenly return IRQ_NONE. Linux only
801 * requires that 0.1% of your interrupts are handled, so this isn't
804 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
807 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
808 nvmeq->cq_head = head;
809 nvmeq->cq_phase = phase;
815 static void nvme_make_request(struct request_queue *q, struct bio *bio)
817 struct nvme_ns *ns = q->queuedata;
818 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
823 bio_endio(bio, -EIO);
827 spin_lock_irq(&nvmeq->q_lock);
828 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
829 result = nvme_submit_bio_queue(nvmeq, ns, bio);
830 if (unlikely(result)) {
831 if (bio_list_empty(&nvmeq->sq_cong))
832 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
833 bio_list_add(&nvmeq->sq_cong, bio);
836 nvme_process_cq(nvmeq);
837 spin_unlock_irq(&nvmeq->q_lock);
841 static irqreturn_t nvme_irq(int irq, void *data)
844 struct nvme_queue *nvmeq = data;
845 spin_lock(&nvmeq->q_lock);
846 nvme_process_cq(nvmeq);
847 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
849 spin_unlock(&nvmeq->q_lock);
853 static irqreturn_t nvme_irq_check(int irq, void *data)
855 struct nvme_queue *nvmeq = data;
856 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
857 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
859 return IRQ_WAKE_THREAD;
862 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
864 spin_lock_irq(&nvmeq->q_lock);
865 cancel_cmdid(nvmeq, cmdid, NULL);
866 spin_unlock_irq(&nvmeq->q_lock);
869 struct sync_cmd_info {
870 struct task_struct *task;
875 static void sync_completion(struct nvme_dev *dev, void *ctx,
876 struct nvme_completion *cqe)
878 struct sync_cmd_info *cmdinfo = ctx;
879 cmdinfo->result = le32_to_cpup(&cqe->result);
880 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
881 wake_up_process(cmdinfo->task);
885 * Returns 0 on success. If the result is negative, it's a Linux error code;
886 * if the result is positive, it's an NVM Express status code
888 int nvme_submit_sync_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd,
889 u32 *result, unsigned timeout)
892 struct sync_cmd_info cmdinfo;
894 cmdinfo.task = current;
895 cmdinfo.status = -EINTR;
897 cmdid = alloc_cmdid_killable(nvmeq, &cmdinfo, sync_completion,
901 cmd->common.command_id = cmdid;
903 set_current_state(TASK_KILLABLE);
904 nvme_submit_cmd(nvmeq, cmd);
905 schedule_timeout(timeout);
907 if (cmdinfo.status == -EINTR) {
908 nvme_abort_command(nvmeq, cmdid);
913 *result = cmdinfo.result;
915 return cmdinfo.status;
918 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
919 struct nvme_command *cmd,
920 struct async_cmd_info *cmdinfo, unsigned timeout)
924 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
927 cmdinfo->status = -EINTR;
928 cmd->common.command_id = cmdid;
929 nvme_submit_cmd(nvmeq, cmd);
933 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
936 return nvme_submit_sync_cmd(dev->queues[0], cmd, result, ADMIN_TIMEOUT);
939 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
940 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
942 return nvme_submit_async_cmd(dev->queues[0], cmd, cmdinfo,
946 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
949 struct nvme_command c;
951 memset(&c, 0, sizeof(c));
952 c.delete_queue.opcode = opcode;
953 c.delete_queue.qid = cpu_to_le16(id);
955 status = nvme_submit_admin_cmd(dev, &c, NULL);
961 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
962 struct nvme_queue *nvmeq)
965 struct nvme_command c;
966 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
968 memset(&c, 0, sizeof(c));
969 c.create_cq.opcode = nvme_admin_create_cq;
970 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
971 c.create_cq.cqid = cpu_to_le16(qid);
972 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
973 c.create_cq.cq_flags = cpu_to_le16(flags);
974 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
976 status = nvme_submit_admin_cmd(dev, &c, NULL);
982 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
983 struct nvme_queue *nvmeq)
986 struct nvme_command c;
987 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
989 memset(&c, 0, sizeof(c));
990 c.create_sq.opcode = nvme_admin_create_sq;
991 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
992 c.create_sq.sqid = cpu_to_le16(qid);
993 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
994 c.create_sq.sq_flags = cpu_to_le16(flags);
995 c.create_sq.cqid = cpu_to_le16(qid);
997 status = nvme_submit_admin_cmd(dev, &c, NULL);
1003 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1005 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1008 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1010 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1013 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
1014 dma_addr_t dma_addr)
1016 struct nvme_command c;
1018 memset(&c, 0, sizeof(c));
1019 c.identify.opcode = nvme_admin_identify;
1020 c.identify.nsid = cpu_to_le32(nsid);
1021 c.identify.prp1 = cpu_to_le64(dma_addr);
1022 c.identify.cns = cpu_to_le32(cns);
1024 return nvme_submit_admin_cmd(dev, &c, NULL);
1027 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
1028 dma_addr_t dma_addr, u32 *result)
1030 struct nvme_command c;
1032 memset(&c, 0, sizeof(c));
1033 c.features.opcode = nvme_admin_get_features;
1034 c.features.nsid = cpu_to_le32(nsid);
1035 c.features.prp1 = cpu_to_le64(dma_addr);
1036 c.features.fid = cpu_to_le32(fid);
1038 return nvme_submit_admin_cmd(dev, &c, result);
1041 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1042 dma_addr_t dma_addr, u32 *result)
1044 struct nvme_command c;
1046 memset(&c, 0, sizeof(c));
1047 c.features.opcode = nvme_admin_set_features;
1048 c.features.prp1 = cpu_to_le64(dma_addr);
1049 c.features.fid = cpu_to_le32(fid);
1050 c.features.dword11 = cpu_to_le32(dword11);
1052 return nvme_submit_admin_cmd(dev, &c, result);
1056 * nvme_abort_cmd - Attempt aborting a command
1057 * @cmdid: Command id of a timed out IO
1058 * @queue: The queue with timed out IO
1060 * Schedule controller reset if the command was already aborted once before and
1061 * still hasn't been returned to the driver, or if this is the admin queue.
1063 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1066 struct nvme_command cmd;
1067 struct nvme_dev *dev = nvmeq->dev;
1068 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1070 if (!nvmeq->qid || info[cmdid].aborted) {
1071 if (work_busy(&dev->reset_work))
1073 list_del_init(&dev->node);
1074 dev_warn(&dev->pci_dev->dev,
1075 "I/O %d QID %d timeout, reset controller\n", cmdid,
1077 INIT_WORK(&dev->reset_work, nvme_reset_failed_dev);
1078 queue_work(nvme_workq, &dev->reset_work);
1082 if (!dev->abort_limit)
1085 a_cmdid = alloc_cmdid(dev->queues[0], CMD_CTX_ABORT, special_completion,
1090 memset(&cmd, 0, sizeof(cmd));
1091 cmd.abort.opcode = nvme_admin_abort_cmd;
1092 cmd.abort.cid = cmdid;
1093 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1094 cmd.abort.command_id = a_cmdid;
1097 info[cmdid].aborted = 1;
1098 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1100 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1102 nvme_submit_cmd(dev->queues[0], &cmd);
1106 * nvme_cancel_ios - Cancel outstanding I/Os
1107 * @queue: The queue to cancel I/Os on
1108 * @timeout: True to only cancel I/Os which have timed out
1110 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1112 int depth = nvmeq->q_depth - 1;
1113 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1114 unsigned long now = jiffies;
1117 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1119 nvme_completion_fn fn;
1120 static struct nvme_completion cqe = {
1121 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1124 if (timeout && !time_after(now, info[cmdid].timeout))
1126 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1128 if (timeout && nvmeq->dev->initialized) {
1129 nvme_abort_cmd(cmdid, nvmeq);
1132 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1134 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1135 fn(nvmeq->dev, ctx, &cqe);
1139 static void nvme_free_queue(struct nvme_queue *nvmeq)
1141 spin_lock_irq(&nvmeq->q_lock);
1142 while (bio_list_peek(&nvmeq->sq_cong)) {
1143 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1144 bio_endio(bio, -EIO);
1146 spin_unlock_irq(&nvmeq->q_lock);
1148 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1149 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1150 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1151 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1155 static void nvme_free_queues(struct nvme_dev *dev)
1159 for (i = dev->queue_count - 1; i >= 0; i--) {
1160 nvme_free_queue(dev->queues[i]);
1162 dev->queues[i] = NULL;
1167 * nvme_suspend_queue - put queue into suspended state
1168 * @nvmeq - queue to suspend
1170 * Returns 1 if already suspended, 0 otherwise.
1172 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1174 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1176 spin_lock_irq(&nvmeq->q_lock);
1177 if (nvmeq->q_suspended) {
1178 spin_unlock_irq(&nvmeq->q_lock);
1181 nvmeq->q_suspended = 1;
1182 spin_unlock_irq(&nvmeq->q_lock);
1184 irq_set_affinity_hint(vector, NULL);
1185 free_irq(vector, nvmeq);
1190 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1192 spin_lock_irq(&nvmeq->q_lock);
1193 nvme_process_cq(nvmeq);
1194 nvme_cancel_ios(nvmeq, false);
1195 spin_unlock_irq(&nvmeq->q_lock);
1198 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1200 struct nvme_queue *nvmeq = dev->queues[qid];
1204 if (nvme_suspend_queue(nvmeq))
1207 /* Don't tell the adapter to delete the admin queue.
1208 * Don't tell a removed adapter to delete IO queues. */
1209 if (qid && readl(&dev->bar->csts) != -1) {
1210 adapter_delete_sq(dev, qid);
1211 adapter_delete_cq(dev, qid);
1213 nvme_clear_queue(nvmeq);
1216 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1217 int depth, int vector)
1219 struct device *dmadev = &dev->pci_dev->dev;
1220 unsigned extra = nvme_queue_extra(depth);
1221 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1225 nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1226 &nvmeq->cq_dma_addr, GFP_KERNEL);
1229 memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1231 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1232 &nvmeq->sq_dma_addr, GFP_KERNEL);
1233 if (!nvmeq->sq_cmds)
1236 nvmeq->q_dmadev = dmadev;
1238 spin_lock_init(&nvmeq->q_lock);
1240 nvmeq->cq_phase = 1;
1241 init_waitqueue_head(&nvmeq->sq_full);
1242 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1243 bio_list_init(&nvmeq->sq_cong);
1244 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1245 nvmeq->q_depth = depth;
1246 nvmeq->cq_vector = vector;
1248 nvmeq->q_suspended = 1;
1254 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1255 nvmeq->cq_dma_addr);
1261 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1264 if (use_threaded_interrupts)
1265 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1266 nvme_irq_check, nvme_irq, IRQF_SHARED,
1268 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1269 IRQF_SHARED, name, nvmeq);
1272 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1274 struct nvme_dev *dev = nvmeq->dev;
1275 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1279 nvmeq->cq_phase = 1;
1280 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1281 memset(nvmeq->cmdid_data, 0, extra);
1282 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1283 nvme_cancel_ios(nvmeq, false);
1284 nvmeq->q_suspended = 0;
1287 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1289 struct nvme_dev *dev = nvmeq->dev;
1292 result = adapter_alloc_cq(dev, qid, nvmeq);
1296 result = adapter_alloc_sq(dev, qid, nvmeq);
1300 result = queue_request_irq(dev, nvmeq, "nvme");
1304 spin_lock_irq(&nvmeq->q_lock);
1305 nvme_init_queue(nvmeq, qid);
1306 spin_unlock_irq(&nvmeq->q_lock);
1311 adapter_delete_sq(dev, qid);
1313 adapter_delete_cq(dev, qid);
1317 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1319 unsigned long timeout;
1320 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1322 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1324 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1326 if (fatal_signal_pending(current))
1328 if (time_after(jiffies, timeout)) {
1329 dev_err(&dev->pci_dev->dev,
1330 "Device not ready; aborting initialisation\n");
1339 * If the device has been passed off to us in an enabled state, just clear
1340 * the enabled bit. The spec says we should set the 'shutdown notification
1341 * bits', but doing so may cause the device to complete commands to the
1342 * admin queue ... and we don't know what memory that might be pointing at!
1344 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1346 u32 cc = readl(&dev->bar->cc);
1348 if (cc & NVME_CC_ENABLE)
1349 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1350 return nvme_wait_ready(dev, cap, false);
1353 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1355 return nvme_wait_ready(dev, cap, true);
1358 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1360 unsigned long timeout;
1363 cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1364 writel(cc, &dev->bar->cc);
1366 timeout = 2 * HZ + jiffies;
1367 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1368 NVME_CSTS_SHST_CMPLT) {
1370 if (fatal_signal_pending(current))
1372 if (time_after(jiffies, timeout)) {
1373 dev_err(&dev->pci_dev->dev,
1374 "Device shutdown incomplete; abort shutdown\n");
1382 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1386 u64 cap = readq(&dev->bar->cap);
1387 struct nvme_queue *nvmeq;
1389 result = nvme_disable_ctrl(dev, cap);
1393 nvmeq = dev->queues[0];
1395 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1398 dev->queues[0] = nvmeq;
1401 aqa = nvmeq->q_depth - 1;
1404 dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1405 dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1406 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1407 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1409 writel(aqa, &dev->bar->aqa);
1410 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1411 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1412 writel(dev->ctrl_config, &dev->bar->cc);
1414 result = nvme_enable_ctrl(dev, cap);
1418 result = queue_request_irq(dev, nvmeq, "nvme admin");
1422 spin_lock_irq(&nvmeq->q_lock);
1423 nvme_init_queue(nvmeq, 0);
1424 spin_unlock_irq(&nvmeq->q_lock);
1428 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1429 unsigned long addr, unsigned length)
1431 int i, err, count, nents, offset;
1432 struct scatterlist *sg;
1433 struct page **pages;
1434 struct nvme_iod *iod;
1437 return ERR_PTR(-EINVAL);
1438 if (!length || length > INT_MAX - PAGE_SIZE)
1439 return ERR_PTR(-EINVAL);
1441 offset = offset_in_page(addr);
1442 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1443 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1445 return ERR_PTR(-ENOMEM);
1447 err = get_user_pages_fast(addr, count, 1, pages);
1454 iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1456 sg_init_table(sg, count);
1457 for (i = 0; i < count; i++) {
1458 sg_set_page(&sg[i], pages[i],
1459 min_t(unsigned, length, PAGE_SIZE - offset),
1461 length -= (PAGE_SIZE - offset);
1464 sg_mark_end(&sg[i - 1]);
1468 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1469 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1479 for (i = 0; i < count; i++)
1482 return ERR_PTR(err);
1485 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1486 struct nvme_iod *iod)
1490 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1491 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1493 for (i = 0; i < iod->nents; i++)
1494 put_page(sg_page(&iod->sg[i]));
1497 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1499 struct nvme_dev *dev = ns->dev;
1500 struct nvme_queue *nvmeq;
1501 struct nvme_user_io io;
1502 struct nvme_command c;
1503 unsigned length, meta_len;
1505 struct nvme_iod *iod, *meta_iod = NULL;
1506 dma_addr_t meta_dma_addr;
1507 void *meta, *uninitialized_var(meta_mem);
1509 if (copy_from_user(&io, uio, sizeof(io)))
1511 length = (io.nblocks + 1) << ns->lba_shift;
1512 meta_len = (io.nblocks + 1) * ns->ms;
1514 if (meta_len && ((io.metadata & 3) || !io.metadata))
1517 switch (io.opcode) {
1518 case nvme_cmd_write:
1520 case nvme_cmd_compare:
1521 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1528 return PTR_ERR(iod);
1530 memset(&c, 0, sizeof(c));
1531 c.rw.opcode = io.opcode;
1532 c.rw.flags = io.flags;
1533 c.rw.nsid = cpu_to_le32(ns->ns_id);
1534 c.rw.slba = cpu_to_le64(io.slba);
1535 c.rw.length = cpu_to_le16(io.nblocks);
1536 c.rw.control = cpu_to_le16(io.control);
1537 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1538 c.rw.reftag = cpu_to_le32(io.reftag);
1539 c.rw.apptag = cpu_to_le16(io.apptag);
1540 c.rw.appmask = cpu_to_le16(io.appmask);
1543 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1545 if (IS_ERR(meta_iod)) {
1546 status = PTR_ERR(meta_iod);
1551 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1552 &meta_dma_addr, GFP_KERNEL);
1558 if (io.opcode & 1) {
1559 int meta_offset = 0;
1561 for (i = 0; i < meta_iod->nents; i++) {
1562 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1563 meta_iod->sg[i].offset;
1564 memcpy(meta_mem + meta_offset, meta,
1565 meta_iod->sg[i].length);
1566 kunmap_atomic(meta);
1567 meta_offset += meta_iod->sg[i].length;
1571 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1574 length = nvme_setup_prps(dev, &c.common, iod, length, GFP_KERNEL);
1576 nvmeq = get_nvmeq(dev);
1578 * Since nvme_submit_sync_cmd sleeps, we can't keep preemption
1579 * disabled. We may be preempted at any point, and be rescheduled
1580 * to a different CPU. That will cause cacheline bouncing, but no
1581 * additional races since q_lock already protects against other CPUs.
1584 if (length != (io.nblocks + 1) << ns->lba_shift)
1586 else if (!nvmeq || nvmeq->q_suspended)
1589 status = nvme_submit_sync_cmd(nvmeq, &c, NULL, NVME_IO_TIMEOUT);
1592 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1593 int meta_offset = 0;
1595 for (i = 0; i < meta_iod->nents; i++) {
1596 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1597 meta_iod->sg[i].offset;
1598 memcpy(meta, meta_mem + meta_offset,
1599 meta_iod->sg[i].length);
1600 kunmap_atomic(meta);
1601 meta_offset += meta_iod->sg[i].length;
1605 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1610 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1611 nvme_free_iod(dev, iod);
1614 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1615 nvme_free_iod(dev, meta_iod);
1621 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1622 struct nvme_admin_cmd __user *ucmd)
1624 struct nvme_admin_cmd cmd;
1625 struct nvme_command c;
1627 struct nvme_iod *uninitialized_var(iod);
1630 if (!capable(CAP_SYS_ADMIN))
1632 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1635 memset(&c, 0, sizeof(c));
1636 c.common.opcode = cmd.opcode;
1637 c.common.flags = cmd.flags;
1638 c.common.nsid = cpu_to_le32(cmd.nsid);
1639 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1640 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1641 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1642 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1643 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1644 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1645 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1646 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1648 length = cmd.data_len;
1650 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1653 return PTR_ERR(iod);
1654 length = nvme_setup_prps(dev, &c.common, iod, length,
1658 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1660 if (length != cmd.data_len)
1663 status = nvme_submit_sync_cmd(dev->queues[0], &c, &cmd.result,
1667 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1668 nvme_free_iod(dev, iod);
1671 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1672 sizeof(cmd.result)))
1678 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1681 struct nvme_ns *ns = bdev->bd_disk->private_data;
1685 force_successful_syscall_return();
1687 case NVME_IOCTL_ADMIN_CMD:
1688 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1689 case NVME_IOCTL_SUBMIT_IO:
1690 return nvme_submit_io(ns, (void __user *)arg);
1691 case SG_GET_VERSION_NUM:
1692 return nvme_sg_get_version_num((void __user *)arg);
1694 return nvme_sg_io(ns, (void __user *)arg);
1700 #ifdef CONFIG_COMPAT
1701 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1702 unsigned int cmd, unsigned long arg)
1704 struct nvme_ns *ns = bdev->bd_disk->private_data;
1708 return nvme_sg_io32(ns, arg);
1710 return nvme_ioctl(bdev, mode, cmd, arg);
1713 #define nvme_compat_ioctl NULL
1716 static const struct block_device_operations nvme_fops = {
1717 .owner = THIS_MODULE,
1718 .ioctl = nvme_ioctl,
1719 .compat_ioctl = nvme_compat_ioctl,
1722 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1724 while (bio_list_peek(&nvmeq->sq_cong)) {
1725 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1726 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1728 if (bio_list_empty(&nvmeq->sq_cong))
1729 remove_wait_queue(&nvmeq->sq_full,
1730 &nvmeq->sq_cong_wait);
1731 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1732 if (bio_list_empty(&nvmeq->sq_cong))
1733 add_wait_queue(&nvmeq->sq_full,
1734 &nvmeq->sq_cong_wait);
1735 bio_list_add_head(&nvmeq->sq_cong, bio);
1741 static int nvme_kthread(void *data)
1743 struct nvme_dev *dev, *next;
1745 while (!kthread_should_stop()) {
1746 set_current_state(TASK_INTERRUPTIBLE);
1747 spin_lock(&dev_list_lock);
1748 list_for_each_entry_safe(dev, next, &dev_list, node) {
1750 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1752 if (work_busy(&dev->reset_work))
1754 list_del_init(&dev->node);
1755 dev_warn(&dev->pci_dev->dev,
1756 "Failed status, reset controller\n");
1757 INIT_WORK(&dev->reset_work,
1758 nvme_reset_failed_dev);
1759 queue_work(nvme_workq, &dev->reset_work);
1762 for (i = 0; i < dev->queue_count; i++) {
1763 struct nvme_queue *nvmeq = dev->queues[i];
1766 spin_lock_irq(&nvmeq->q_lock);
1767 if (nvmeq->q_suspended)
1769 nvme_process_cq(nvmeq);
1770 nvme_cancel_ios(nvmeq, true);
1771 nvme_resubmit_bios(nvmeq);
1773 spin_unlock_irq(&nvmeq->q_lock);
1776 spin_unlock(&dev_list_lock);
1777 schedule_timeout(round_jiffies_relative(HZ));
1782 static void nvme_config_discard(struct nvme_ns *ns)
1784 u32 logical_block_size = queue_logical_block_size(ns->queue);
1785 ns->queue->limits.discard_zeroes_data = 0;
1786 ns->queue->limits.discard_alignment = logical_block_size;
1787 ns->queue->limits.discard_granularity = logical_block_size;
1788 ns->queue->limits.max_discard_sectors = 0xffffffff;
1789 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1792 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1793 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1796 struct gendisk *disk;
1799 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1802 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1805 ns->queue = blk_alloc_queue(GFP_KERNEL);
1808 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1809 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1810 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1811 blk_queue_make_request(ns->queue, nvme_make_request);
1813 ns->queue->queuedata = ns;
1815 disk = alloc_disk(0);
1817 goto out_free_queue;
1820 lbaf = id->flbas & 0xf;
1821 ns->lba_shift = id->lbaf[lbaf].ds;
1822 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1823 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1824 if (dev->max_hw_sectors)
1825 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1827 disk->major = nvme_major;
1828 disk->first_minor = 0;
1829 disk->fops = &nvme_fops;
1830 disk->private_data = ns;
1831 disk->queue = ns->queue;
1832 disk->driverfs_dev = &dev->pci_dev->dev;
1833 disk->flags = GENHD_FL_EXT_DEVT;
1834 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1835 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1837 if (dev->oncs & NVME_CTRL_ONCS_DSM)
1838 nvme_config_discard(ns);
1843 blk_cleanup_queue(ns->queue);
1849 static void nvme_ns_free(struct nvme_ns *ns)
1852 blk_cleanup_queue(ns->queue);
1856 static int set_queue_count(struct nvme_dev *dev, int count)
1860 u32 q_count = (count - 1) | ((count - 1) << 16);
1862 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
1865 return status < 0 ? -EIO : -EBUSY;
1866 return min(result & 0xffff, result >> 16) + 1;
1869 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
1871 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
1874 static int nvme_setup_io_queues(struct nvme_dev *dev)
1876 struct pci_dev *pdev = dev->pci_dev;
1877 int result, cpu, i, vecs, nr_io_queues, size, q_depth;
1879 nr_io_queues = num_online_cpus();
1880 result = set_queue_count(dev, nr_io_queues);
1883 if (result < nr_io_queues)
1884 nr_io_queues = result;
1886 size = db_bar_size(dev, nr_io_queues);
1890 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
1893 if (!--nr_io_queues)
1895 size = db_bar_size(dev, nr_io_queues);
1897 dev->dbs = ((void __iomem *)dev->bar) + 4096;
1898 dev->queues[0]->q_db = dev->dbs;
1901 /* Deregister the admin queue's interrupt */
1902 free_irq(dev->entry[0].vector, dev->queues[0]);
1904 vecs = nr_io_queues;
1905 for (i = 0; i < vecs; i++)
1906 dev->entry[i].entry = i;
1908 result = pci_enable_msix(pdev, dev->entry, vecs);
1915 vecs = nr_io_queues;
1919 result = pci_enable_msi_block(pdev, vecs);
1921 for (i = 0; i < vecs; i++)
1922 dev->entry[i].vector = i + pdev->irq;
1924 } else if (result < 0) {
1933 * Should investigate if there's a performance win from allocating
1934 * more queues than interrupt vectors; it might allow the submission
1935 * path to scale better, even if the receive path is limited by the
1936 * number of interrupts.
1938 nr_io_queues = vecs;
1940 result = queue_request_irq(dev, dev->queues[0], "nvme admin");
1942 dev->queues[0]->q_suspended = 1;
1946 /* Free previously allocated queues that are no longer usable */
1947 spin_lock(&dev_list_lock);
1948 for (i = dev->queue_count - 1; i > nr_io_queues; i--) {
1949 struct nvme_queue *nvmeq = dev->queues[i];
1951 spin_lock_irq(&nvmeq->q_lock);
1952 nvme_cancel_ios(nvmeq, false);
1953 spin_unlock_irq(&nvmeq->q_lock);
1955 nvme_free_queue(nvmeq);
1957 dev->queues[i] = NULL;
1959 spin_unlock(&dev_list_lock);
1961 cpu = cpumask_first(cpu_online_mask);
1962 for (i = 0; i < nr_io_queues; i++) {
1963 irq_set_affinity_hint(dev->entry[i].vector, get_cpu_mask(cpu));
1964 cpu = cpumask_next(cpu, cpu_online_mask);
1967 q_depth = min_t(int, NVME_CAP_MQES(readq(&dev->bar->cap)) + 1,
1969 for (i = dev->queue_count - 1; i < nr_io_queues; i++) {
1970 dev->queues[i + 1] = nvme_alloc_queue(dev, i + 1, q_depth, i);
1971 if (!dev->queues[i + 1]) {
1977 for (; i < num_possible_cpus(); i++) {
1978 int target = i % rounddown_pow_of_two(dev->queue_count - 1);
1979 dev->queues[i + 1] = dev->queues[target + 1];
1982 for (i = 1; i < dev->queue_count; i++) {
1983 result = nvme_create_queue(dev->queues[i], i);
1985 for (--i; i > 0; i--)
1986 nvme_disable_queue(dev, i);
1994 nvme_free_queues(dev);
1999 * Return: error value if an error occurred setting up the queues or calling
2000 * Identify Device. 0 if these succeeded, even if adding some of the
2001 * namespaces failed. At the moment, these failures are silent. TBD which
2002 * failures should be reported.
2004 static int nvme_dev_add(struct nvme_dev *dev)
2006 struct pci_dev *pdev = dev->pci_dev;
2010 struct nvme_id_ctrl *ctrl;
2011 struct nvme_id_ns *id_ns;
2013 dma_addr_t dma_addr;
2014 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
2016 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
2020 res = nvme_identify(dev, 0, 1, dma_addr);
2027 nn = le32_to_cpup(&ctrl->nn);
2028 dev->oncs = le16_to_cpup(&ctrl->oncs);
2029 dev->abort_limit = ctrl->acl + 1;
2030 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2031 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2032 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2034 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2035 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2036 (pdev->device == 0x0953) && ctrl->vs[3])
2037 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2040 for (i = 1; i <= nn; i++) {
2041 res = nvme_identify(dev, i, 0, dma_addr);
2045 if (id_ns->ncap == 0)
2048 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2049 dma_addr + 4096, NULL);
2051 memset(mem + 4096, 0, 4096);
2053 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2055 list_add_tail(&ns->list, &dev->namespaces);
2057 list_for_each_entry(ns, &dev->namespaces, list)
2062 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2066 static int nvme_dev_map(struct nvme_dev *dev)
2068 int bars, result = -ENOMEM;
2069 struct pci_dev *pdev = dev->pci_dev;
2071 if (pci_enable_device_mem(pdev))
2074 dev->entry[0].vector = pdev->irq;
2075 pci_set_master(pdev);
2076 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2077 if (pci_request_selected_regions(pdev, bars, "nvme"))
2080 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2081 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2084 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2087 if (readl(&dev->bar->csts) == -1) {
2091 dev->db_stride = 1 << NVME_CAP_STRIDE(readq(&dev->bar->cap));
2092 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2100 pci_release_regions(pdev);
2102 pci_disable_device(pdev);
2106 static void nvme_dev_unmap(struct nvme_dev *dev)
2108 if (dev->pci_dev->msi_enabled)
2109 pci_disable_msi(dev->pci_dev);
2110 else if (dev->pci_dev->msix_enabled)
2111 pci_disable_msix(dev->pci_dev);
2116 pci_release_regions(dev->pci_dev);
2119 if (pci_is_enabled(dev->pci_dev))
2120 pci_disable_device(dev->pci_dev);
2123 struct nvme_delq_ctx {
2124 struct task_struct *waiter;
2125 struct kthread_worker *worker;
2129 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2131 dq->waiter = current;
2135 set_current_state(TASK_KILLABLE);
2136 if (!atomic_read(&dq->refcount))
2138 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2139 fatal_signal_pending(current)) {
2140 set_current_state(TASK_RUNNING);
2142 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2143 nvme_disable_queue(dev, 0);
2145 send_sig(SIGKILL, dq->worker->task, 1);
2146 flush_kthread_worker(dq->worker);
2150 set_current_state(TASK_RUNNING);
2153 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2155 atomic_dec(&dq->refcount);
2157 wake_up_process(dq->waiter);
2160 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2162 atomic_inc(&dq->refcount);
2166 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2168 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2170 nvme_clear_queue(nvmeq);
2174 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2175 kthread_work_func_t fn)
2177 struct nvme_command c;
2179 memset(&c, 0, sizeof(c));
2180 c.delete_queue.opcode = opcode;
2181 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2183 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2184 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2187 static void nvme_del_cq_work_handler(struct kthread_work *work)
2189 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2191 nvme_del_queue_end(nvmeq);
2194 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2196 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2197 nvme_del_cq_work_handler);
2200 static void nvme_del_sq_work_handler(struct kthread_work *work)
2202 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2204 int status = nvmeq->cmdinfo.status;
2207 status = nvme_delete_cq(nvmeq);
2209 nvme_del_queue_end(nvmeq);
2212 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2214 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2215 nvme_del_sq_work_handler);
2218 static void nvme_del_queue_start(struct kthread_work *work)
2220 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2222 allow_signal(SIGKILL);
2223 if (nvme_delete_sq(nvmeq))
2224 nvme_del_queue_end(nvmeq);
2227 static void nvme_disable_io_queues(struct nvme_dev *dev)
2230 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2231 struct nvme_delq_ctx dq;
2232 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2233 &worker, "nvme%d", dev->instance);
2235 if (IS_ERR(kworker_task)) {
2236 dev_err(&dev->pci_dev->dev,
2237 "Failed to create queue del task\n");
2238 for (i = dev->queue_count - 1; i > 0; i--)
2239 nvme_disable_queue(dev, i);
2244 atomic_set(&dq.refcount, 0);
2245 dq.worker = &worker;
2246 for (i = dev->queue_count - 1; i > 0; i--) {
2247 struct nvme_queue *nvmeq = dev->queues[i];
2249 if (nvme_suspend_queue(nvmeq))
2251 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2252 nvmeq->cmdinfo.worker = dq.worker;
2253 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2254 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2256 nvme_wait_dq(&dq, dev);
2257 kthread_stop(kworker_task);
2260 static void nvme_dev_shutdown(struct nvme_dev *dev)
2264 dev->initialized = 0;
2266 spin_lock(&dev_list_lock);
2267 list_del_init(&dev->node);
2268 spin_unlock(&dev_list_lock);
2270 if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2271 for (i = dev->queue_count - 1; i >= 0; i--) {
2272 struct nvme_queue *nvmeq = dev->queues[i];
2273 nvme_suspend_queue(nvmeq);
2274 nvme_clear_queue(nvmeq);
2277 nvme_disable_io_queues(dev);
2278 nvme_shutdown_ctrl(dev);
2279 nvme_disable_queue(dev, 0);
2281 nvme_dev_unmap(dev);
2284 static void nvme_dev_remove(struct nvme_dev *dev)
2286 struct nvme_ns *ns, *next;
2288 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2289 list_del(&ns->list);
2290 del_gendisk(ns->disk);
2295 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2297 struct device *dmadev = &dev->pci_dev->dev;
2298 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2299 PAGE_SIZE, PAGE_SIZE, 0);
2300 if (!dev->prp_page_pool)
2303 /* Optimisation for I/Os between 4k and 128k */
2304 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2306 if (!dev->prp_small_pool) {
2307 dma_pool_destroy(dev->prp_page_pool);
2313 static void nvme_release_prp_pools(struct nvme_dev *dev)
2315 dma_pool_destroy(dev->prp_page_pool);
2316 dma_pool_destroy(dev->prp_small_pool);
2319 static DEFINE_IDA(nvme_instance_ida);
2321 static int nvme_set_instance(struct nvme_dev *dev)
2323 int instance, error;
2326 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2329 spin_lock(&dev_list_lock);
2330 error = ida_get_new(&nvme_instance_ida, &instance);
2331 spin_unlock(&dev_list_lock);
2332 } while (error == -EAGAIN);
2337 dev->instance = instance;
2341 static void nvme_release_instance(struct nvme_dev *dev)
2343 spin_lock(&dev_list_lock);
2344 ida_remove(&nvme_instance_ida, dev->instance);
2345 spin_unlock(&dev_list_lock);
2348 static void nvme_free_dev(struct kref *kref)
2350 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2356 static int nvme_dev_open(struct inode *inode, struct file *f)
2358 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2360 kref_get(&dev->kref);
2361 f->private_data = dev;
2365 static int nvme_dev_release(struct inode *inode, struct file *f)
2367 struct nvme_dev *dev = f->private_data;
2368 kref_put(&dev->kref, nvme_free_dev);
2372 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2374 struct nvme_dev *dev = f->private_data;
2376 case NVME_IOCTL_ADMIN_CMD:
2377 return nvme_user_admin_cmd(dev, (void __user *)arg);
2383 static const struct file_operations nvme_dev_fops = {
2384 .owner = THIS_MODULE,
2385 .open = nvme_dev_open,
2386 .release = nvme_dev_release,
2387 .unlocked_ioctl = nvme_dev_ioctl,
2388 .compat_ioctl = nvme_dev_ioctl,
2391 static int nvme_dev_start(struct nvme_dev *dev)
2395 result = nvme_dev_map(dev);
2399 result = nvme_configure_admin_queue(dev);
2403 spin_lock(&dev_list_lock);
2404 list_add(&dev->node, &dev_list);
2405 spin_unlock(&dev_list_lock);
2407 result = nvme_setup_io_queues(dev);
2408 if (result && result != -EBUSY)
2414 spin_lock(&dev_list_lock);
2415 list_del_init(&dev->node);
2416 spin_unlock(&dev_list_lock);
2418 nvme_dev_unmap(dev);
2422 static int nvme_remove_dead_ctrl(void *arg)
2424 struct nvme_dev *dev = (struct nvme_dev *)arg;
2425 struct pci_dev *pdev = dev->pci_dev;
2427 if (pci_get_drvdata(pdev))
2428 pci_stop_and_remove_bus_device(pdev);
2429 kref_put(&dev->kref, nvme_free_dev);
2433 static void nvme_remove_disks(struct work_struct *ws)
2436 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2438 nvme_dev_remove(dev);
2439 spin_lock(&dev_list_lock);
2440 for (i = dev->queue_count - 1; i > 0; i--) {
2441 BUG_ON(!dev->queues[i] || !dev->queues[i]->q_suspended);
2442 nvme_free_queue(dev->queues[i]);
2444 dev->queues[i] = NULL;
2446 spin_unlock(&dev_list_lock);
2449 static int nvme_dev_resume(struct nvme_dev *dev)
2453 ret = nvme_dev_start(dev);
2454 if (ret && ret != -EBUSY)
2456 if (ret == -EBUSY) {
2457 spin_lock(&dev_list_lock);
2458 INIT_WORK(&dev->reset_work, nvme_remove_disks);
2459 queue_work(nvme_workq, &dev->reset_work);
2460 spin_unlock(&dev_list_lock);
2462 dev->initialized = 1;
2466 static void nvme_dev_reset(struct nvme_dev *dev)
2468 nvme_dev_shutdown(dev);
2469 if (nvme_dev_resume(dev)) {
2470 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2471 kref_get(&dev->kref);
2472 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2474 dev_err(&dev->pci_dev->dev,
2475 "Failed to start controller remove task\n");
2476 kref_put(&dev->kref, nvme_free_dev);
2481 static void nvme_reset_failed_dev(struct work_struct *ws)
2483 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2484 nvme_dev_reset(dev);
2487 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2489 int result = -ENOMEM;
2490 struct nvme_dev *dev;
2492 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2495 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2499 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2504 INIT_LIST_HEAD(&dev->namespaces);
2505 dev->pci_dev = pdev;
2506 pci_set_drvdata(pdev, dev);
2507 result = nvme_set_instance(dev);
2511 result = nvme_setup_prp_pools(dev);
2515 result = nvme_dev_start(dev);
2517 if (result == -EBUSY)
2522 result = nvme_dev_add(dev);
2527 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2528 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2529 dev->miscdev.parent = &pdev->dev;
2530 dev->miscdev.name = dev->name;
2531 dev->miscdev.fops = &nvme_dev_fops;
2532 result = misc_register(&dev->miscdev);
2536 dev->initialized = 1;
2537 kref_init(&dev->kref);
2541 nvme_dev_remove(dev);
2543 nvme_dev_shutdown(dev);
2545 nvme_free_queues(dev);
2546 nvme_release_prp_pools(dev);
2548 nvme_release_instance(dev);
2556 static void nvme_remove(struct pci_dev *pdev)
2558 struct nvme_dev *dev = pci_get_drvdata(pdev);
2560 spin_lock(&dev_list_lock);
2561 list_del_init(&dev->node);
2562 spin_unlock(&dev_list_lock);
2564 pci_set_drvdata(pdev, NULL);
2565 flush_work(&dev->reset_work);
2566 misc_deregister(&dev->miscdev);
2567 nvme_dev_remove(dev);
2568 nvme_dev_shutdown(dev);
2569 nvme_free_queues(dev);
2570 nvme_release_instance(dev);
2571 nvme_release_prp_pools(dev);
2572 kref_put(&dev->kref, nvme_free_dev);
2575 /* These functions are yet to be implemented */
2576 #define nvme_error_detected NULL
2577 #define nvme_dump_registers NULL
2578 #define nvme_link_reset NULL
2579 #define nvme_slot_reset NULL
2580 #define nvme_error_resume NULL
2582 static int nvme_suspend(struct device *dev)
2584 struct pci_dev *pdev = to_pci_dev(dev);
2585 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2587 nvme_dev_shutdown(ndev);
2591 static int nvme_resume(struct device *dev)
2593 struct pci_dev *pdev = to_pci_dev(dev);
2594 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2596 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2597 INIT_WORK(&ndev->reset_work, nvme_reset_failed_dev);
2598 queue_work(nvme_workq, &ndev->reset_work);
2603 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2605 static const struct pci_error_handlers nvme_err_handler = {
2606 .error_detected = nvme_error_detected,
2607 .mmio_enabled = nvme_dump_registers,
2608 .link_reset = nvme_link_reset,
2609 .slot_reset = nvme_slot_reset,
2610 .resume = nvme_error_resume,
2613 /* Move to pci_ids.h later */
2614 #define PCI_CLASS_STORAGE_EXPRESS 0x010802
2616 static DEFINE_PCI_DEVICE_TABLE(nvme_id_table) = {
2617 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2620 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2622 static struct pci_driver nvme_driver = {
2624 .id_table = nvme_id_table,
2625 .probe = nvme_probe,
2626 .remove = nvme_remove,
2628 .pm = &nvme_dev_pm_ops,
2630 .err_handler = &nvme_err_handler,
2633 static int __init nvme_init(void)
2637 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2638 if (IS_ERR(nvme_thread))
2639 return PTR_ERR(nvme_thread);
2642 nvme_workq = create_singlethread_workqueue("nvme");
2646 result = register_blkdev(nvme_major, "nvme");
2649 else if (result > 0)
2650 nvme_major = result;
2652 result = pci_register_driver(&nvme_driver);
2654 goto unregister_blkdev;
2658 unregister_blkdev(nvme_major, "nvme");
2660 destroy_workqueue(nvme_workq);
2662 kthread_stop(nvme_thread);
2666 static void __exit nvme_exit(void)
2668 pci_unregister_driver(&nvme_driver);
2669 unregister_blkdev(nvme_major, "nvme");
2670 destroy_workqueue(nvme_workq);
2671 kthread_stop(nvme_thread);
2674 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2675 MODULE_LICENSE("GPL");
2676 MODULE_VERSION("0.8");
2677 module_init(nvme_init);
2678 module_exit(nvme_exit);