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
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/cpu.h>
24 #include <linux/delay.h>
25 #include <linux/errno.h>
27 #include <linux/genhd.h>
28 #include <linux/idr.h>
29 #include <linux/init.h>
30 #include <linux/interrupt.h>
32 #include <linux/kdev_t.h>
33 #include <linux/kthread.h>
34 #include <linux/kernel.h>
36 #include <linux/module.h>
37 #include <linux/moduleparam.h>
38 #include <linux/pci.h>
39 #include <linux/percpu.h>
40 #include <linux/poison.h>
41 #include <linux/ptrace.h>
42 #include <linux/sched.h>
43 #include <linux/slab.h>
44 #include <linux/types.h>
46 #include <asm-generic/io-64-nonatomic-lo-hi.h>
48 #define NVME_Q_DEPTH 1024
49 #define SQ_SIZE(depth) (depth * sizeof(struct nvme_command))
50 #define CQ_SIZE(depth) (depth * sizeof(struct nvme_completion))
51 #define ADMIN_TIMEOUT (60 * HZ)
53 static int nvme_major;
54 module_param(nvme_major, int, 0);
56 static int use_threaded_interrupts;
57 module_param(use_threaded_interrupts, int, 0);
59 static DEFINE_SPINLOCK(dev_list_lock);
60 static LIST_HEAD(dev_list);
61 static struct task_struct *nvme_thread;
62 static struct workqueue_struct *nvme_workq;
64 static void nvme_reset_failed_dev(struct work_struct *ws);
66 struct async_cmd_info {
67 struct kthread_work work;
68 struct kthread_worker *worker;
75 * An NVM Express queue. Each device has at least two (one for admin
76 * commands and one for I/O commands).
79 struct rcu_head r_head;
80 struct device *q_dmadev;
82 char irqname[24]; /* nvme4294967295-65535\0 */
84 struct nvme_command *sq_cmds;
85 volatile struct nvme_completion *cqes;
86 dma_addr_t sq_dma_addr;
87 dma_addr_t cq_dma_addr;
88 wait_queue_head_t sq_full;
89 wait_queue_t sq_cong_wait;
90 struct bio_list sq_cong;
101 cpumask_var_t cpu_mask;
102 struct async_cmd_info cmdinfo;
103 unsigned long cmdid_data[];
107 * Check we didin't inadvertently grow the command struct
109 static inline void _nvme_check_size(void)
111 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
112 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
113 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
114 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
115 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
116 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
117 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
118 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
119 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
120 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
121 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
122 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
125 typedef void (*nvme_completion_fn)(struct nvme_dev *, void *,
126 struct nvme_completion *);
128 struct nvme_cmd_info {
129 nvme_completion_fn fn;
131 unsigned long timeout;
135 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
137 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
140 static unsigned nvme_queue_extra(int depth)
142 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
146 * alloc_cmdid() - Allocate a Command ID
147 * @nvmeq: The queue that will be used for this command
148 * @ctx: A pointer that will be passed to the handler
149 * @handler: The function to call on completion
151 * Allocate a Command ID for a queue. The data passed in will
152 * be passed to the completion handler. This is implemented by using
153 * the bottom two bits of the ctx pointer to store the handler ID.
154 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
155 * We can change this if it becomes a problem.
157 * May be called with local interrupts disabled and the q_lock held,
158 * or with interrupts enabled and no locks held.
160 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
161 nvme_completion_fn handler, unsigned timeout)
163 int depth = nvmeq->q_depth - 1;
164 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
168 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
171 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
173 info[cmdid].fn = handler;
174 info[cmdid].ctx = ctx;
175 info[cmdid].timeout = jiffies + timeout;
176 info[cmdid].aborted = 0;
180 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
181 nvme_completion_fn handler, unsigned timeout)
184 wait_event_killable(nvmeq->sq_full,
185 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
186 return (cmdid < 0) ? -EINTR : cmdid;
189 /* Special values must be less than 0x1000 */
190 #define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
191 #define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
192 #define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
193 #define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
194 #define CMD_CTX_FLUSH (0x318 + CMD_CTX_BASE)
195 #define CMD_CTX_ABORT (0x31C + CMD_CTX_BASE)
197 static void special_completion(struct nvme_dev *dev, void *ctx,
198 struct nvme_completion *cqe)
200 if (ctx == CMD_CTX_CANCELLED)
202 if (ctx == CMD_CTX_FLUSH)
204 if (ctx == CMD_CTX_ABORT) {
208 if (ctx == CMD_CTX_COMPLETED) {
209 dev_warn(&dev->pci_dev->dev,
210 "completed id %d twice on queue %d\n",
211 cqe->command_id, le16_to_cpup(&cqe->sq_id));
214 if (ctx == CMD_CTX_INVALID) {
215 dev_warn(&dev->pci_dev->dev,
216 "invalid id %d completed on queue %d\n",
217 cqe->command_id, le16_to_cpup(&cqe->sq_id));
221 dev_warn(&dev->pci_dev->dev, "Unknown special completion %p\n", ctx);
224 static void async_completion(struct nvme_dev *dev, void *ctx,
225 struct nvme_completion *cqe)
227 struct async_cmd_info *cmdinfo = ctx;
228 cmdinfo->result = le32_to_cpup(&cqe->result);
229 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
230 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
234 * Called with local interrupts disabled and the q_lock held. May not sleep.
236 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
237 nvme_completion_fn *fn)
240 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
242 if (cmdid >= nvmeq->q_depth) {
243 *fn = special_completion;
244 return CMD_CTX_INVALID;
247 *fn = info[cmdid].fn;
248 ctx = info[cmdid].ctx;
249 info[cmdid].fn = special_completion;
250 info[cmdid].ctx = CMD_CTX_COMPLETED;
251 clear_bit(cmdid, nvmeq->cmdid_data);
252 wake_up(&nvmeq->sq_full);
256 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
257 nvme_completion_fn *fn)
260 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
262 *fn = info[cmdid].fn;
263 ctx = info[cmdid].ctx;
264 info[cmdid].fn = special_completion;
265 info[cmdid].ctx = CMD_CTX_CANCELLED;
269 static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
271 return rcu_dereference_raw(dev->queues[qid]);
274 static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
276 unsigned queue_id = get_cpu_var(*dev->io_queue);
278 return rcu_dereference(dev->queues[queue_id]);
281 static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
284 put_cpu_var(nvmeq->dev->io_queue);
287 static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
291 return rcu_dereference(dev->queues[q_idx]);
294 static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
300 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
301 * @nvmeq: The queue to use
302 * @cmd: The command to send
304 * Safe to use from interrupt context
306 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
310 spin_lock_irqsave(&nvmeq->q_lock, flags);
311 if (nvmeq->q_suspended) {
312 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
315 tail = nvmeq->sq_tail;
316 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
317 if (++tail == nvmeq->q_depth)
319 writel(tail, nvmeq->q_db);
320 nvmeq->sq_tail = tail;
321 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
326 static __le64 **iod_list(struct nvme_iod *iod)
328 return ((void *)iod) + iod->offset;
332 * Will slightly overestimate the number of pages needed. This is OK
333 * as it only leads to a small amount of wasted memory for the lifetime of
336 static int nvme_npages(unsigned size)
338 unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
339 return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
342 static struct nvme_iod *
343 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
345 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
346 sizeof(__le64 *) * nvme_npages(nbytes) +
347 sizeof(struct scatterlist) * nseg, gfp);
350 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
352 iod->length = nbytes;
354 iod->start_time = jiffies;
360 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
362 const int last_prp = PAGE_SIZE / 8 - 1;
364 __le64 **list = iod_list(iod);
365 dma_addr_t prp_dma = iod->first_dma;
367 if (iod->npages == 0)
368 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
369 for (i = 0; i < iod->npages; i++) {
370 __le64 *prp_list = list[i];
371 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
372 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
373 prp_dma = next_prp_dma;
378 static void nvme_start_io_acct(struct bio *bio)
380 struct gendisk *disk = bio->bi_bdev->bd_disk;
381 const int rw = bio_data_dir(bio);
382 int cpu = part_stat_lock();
383 part_round_stats(cpu, &disk->part0);
384 part_stat_inc(cpu, &disk->part0, ios[rw]);
385 part_stat_add(cpu, &disk->part0, sectors[rw], bio_sectors(bio));
386 part_inc_in_flight(&disk->part0, rw);
390 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
392 struct gendisk *disk = bio->bi_bdev->bd_disk;
393 const int rw = bio_data_dir(bio);
394 unsigned long duration = jiffies - start_time;
395 int cpu = part_stat_lock();
396 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
397 part_round_stats(cpu, &disk->part0);
398 part_dec_in_flight(&disk->part0, rw);
402 static void bio_completion(struct nvme_dev *dev, void *ctx,
403 struct nvme_completion *cqe)
405 struct nvme_iod *iod = ctx;
406 struct bio *bio = iod->private;
407 u16 status = le16_to_cpup(&cqe->status) >> 1;
410 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
411 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
412 nvme_end_io_acct(bio, iod->start_time);
414 nvme_free_iod(dev, iod);
416 bio_endio(bio, -EIO);
421 /* length is in bytes. gfp flags indicates whether we may sleep. */
422 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_common_command *cmd,
423 struct nvme_iod *iod, int total_len, gfp_t gfp)
425 struct dma_pool *pool;
426 int length = total_len;
427 struct scatterlist *sg = iod->sg;
428 int dma_len = sg_dma_len(sg);
429 u64 dma_addr = sg_dma_address(sg);
430 int offset = offset_in_page(dma_addr);
432 __le64 **list = iod_list(iod);
436 cmd->prp1 = cpu_to_le64(dma_addr);
437 length -= (PAGE_SIZE - offset);
441 dma_len -= (PAGE_SIZE - offset);
443 dma_addr += (PAGE_SIZE - offset);
446 dma_addr = sg_dma_address(sg);
447 dma_len = sg_dma_len(sg);
450 if (length <= PAGE_SIZE) {
451 cmd->prp2 = cpu_to_le64(dma_addr);
455 nprps = DIV_ROUND_UP(length, PAGE_SIZE);
456 if (nprps <= (256 / 8)) {
457 pool = dev->prp_small_pool;
460 pool = dev->prp_page_pool;
464 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
466 cmd->prp2 = cpu_to_le64(dma_addr);
468 return (total_len - length) + PAGE_SIZE;
471 iod->first_dma = prp_dma;
472 cmd->prp2 = cpu_to_le64(prp_dma);
475 if (i == PAGE_SIZE / 8) {
476 __le64 *old_prp_list = prp_list;
477 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
479 return total_len - length;
480 list[iod->npages++] = prp_list;
481 prp_list[0] = old_prp_list[i - 1];
482 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
485 prp_list[i++] = cpu_to_le64(dma_addr);
486 dma_len -= PAGE_SIZE;
487 dma_addr += PAGE_SIZE;
495 dma_addr = sg_dma_address(sg);
496 dma_len = sg_dma_len(sg);
502 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
505 struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
509 bio_chain(split, bio);
511 if (bio_list_empty(&nvmeq->sq_cong))
512 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
513 bio_list_add(&nvmeq->sq_cong, split);
514 bio_list_add(&nvmeq->sq_cong, bio);
519 /* NVMe scatterlists require no holes in the virtual address */
520 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
521 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
523 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
524 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
526 struct bio_vec bvec, bvprv;
527 struct bvec_iter iter;
528 struct scatterlist *sg = NULL;
529 int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
532 if (nvmeq->dev->stripe_size)
533 split_len = nvmeq->dev->stripe_size -
534 ((bio->bi_iter.bi_sector << 9) &
535 (nvmeq->dev->stripe_size - 1));
537 sg_init_table(iod->sg, psegs);
538 bio_for_each_segment(bvec, bio, iter) {
539 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
540 sg->length += bvec.bv_len;
542 if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
543 return nvme_split_and_submit(bio, nvmeq,
546 sg = sg ? sg + 1 : iod->sg;
547 sg_set_page(sg, bvec.bv_page,
548 bvec.bv_len, bvec.bv_offset);
552 if (split_len - length < bvec.bv_len)
553 return nvme_split_and_submit(bio, nvmeq, split_len);
554 length += bvec.bv_len;
560 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
563 BUG_ON(length != bio->bi_iter.bi_size);
568 * We reuse the small pool to allocate the 16-byte range here as it is not
569 * worth having a special pool for these or additional cases to handle freeing
572 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
573 struct bio *bio, struct nvme_iod *iod, int cmdid)
575 struct nvme_dsm_range *range;
576 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
578 range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
583 iod_list(iod)[0] = (__le64 *)range;
586 range->cattr = cpu_to_le32(0);
587 range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
588 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
590 memset(cmnd, 0, sizeof(*cmnd));
591 cmnd->dsm.opcode = nvme_cmd_dsm;
592 cmnd->dsm.command_id = cmdid;
593 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
594 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
596 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
598 if (++nvmeq->sq_tail == nvmeq->q_depth)
600 writel(nvmeq->sq_tail, nvmeq->q_db);
605 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
608 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
610 memset(cmnd, 0, sizeof(*cmnd));
611 cmnd->common.opcode = nvme_cmd_flush;
612 cmnd->common.command_id = cmdid;
613 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
615 if (++nvmeq->sq_tail == nvmeq->q_depth)
617 writel(nvmeq->sq_tail, nvmeq->q_db);
622 int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
624 int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
625 special_completion, NVME_IO_TIMEOUT);
626 if (unlikely(cmdid < 0))
629 return nvme_submit_flush(nvmeq, ns, cmdid);
633 * Called with local interrupts disabled and the q_lock held. May not sleep.
635 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
638 struct nvme_command *cmnd;
639 struct nvme_iod *iod;
640 enum dma_data_direction dma_dir;
641 int cmdid, length, result;
644 int psegs = bio_phys_segments(ns->queue, bio);
646 if ((bio->bi_rw & REQ_FLUSH) && psegs) {
647 result = nvme_submit_flush_data(nvmeq, ns);
653 iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, GFP_ATOMIC);
659 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
660 if (unlikely(cmdid < 0))
663 if (bio->bi_rw & REQ_DISCARD) {
664 result = nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
669 if ((bio->bi_rw & REQ_FLUSH) && !psegs)
670 return nvme_submit_flush(nvmeq, ns, cmdid);
673 if (bio->bi_rw & REQ_FUA)
674 control |= NVME_RW_FUA;
675 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
676 control |= NVME_RW_LR;
679 if (bio->bi_rw & REQ_RAHEAD)
680 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
682 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
684 memset(cmnd, 0, sizeof(*cmnd));
685 if (bio_data_dir(bio)) {
686 cmnd->rw.opcode = nvme_cmd_write;
687 dma_dir = DMA_TO_DEVICE;
689 cmnd->rw.opcode = nvme_cmd_read;
690 dma_dir = DMA_FROM_DEVICE;
693 result = nvme_map_bio(nvmeq, iod, bio, dma_dir, psegs);
698 cmnd->rw.command_id = cmdid;
699 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
700 length = nvme_setup_prps(nvmeq->dev, &cmnd->common, iod, length,
702 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
703 cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
704 cmnd->rw.control = cpu_to_le16(control);
705 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
707 nvme_start_io_acct(bio);
708 if (++nvmeq->sq_tail == nvmeq->q_depth)
710 writel(nvmeq->sq_tail, nvmeq->q_db);
715 free_cmdid(nvmeq, cmdid, NULL);
717 nvme_free_iod(nvmeq->dev, iod);
722 static int nvme_process_cq(struct nvme_queue *nvmeq)
726 head = nvmeq->cq_head;
727 phase = nvmeq->cq_phase;
731 nvme_completion_fn fn;
732 struct nvme_completion cqe = nvmeq->cqes[head];
733 if ((le16_to_cpu(cqe.status) & 1) != phase)
735 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
736 if (++head == nvmeq->q_depth) {
741 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
742 fn(nvmeq->dev, ctx, &cqe);
745 /* If the controller ignores the cq head doorbell and continuously
746 * writes to the queue, it is theoretically possible to wrap around
747 * the queue twice and mistakenly return IRQ_NONE. Linux only
748 * requires that 0.1% of your interrupts are handled, so this isn't
751 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
754 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
755 nvmeq->cq_head = head;
756 nvmeq->cq_phase = phase;
762 static void nvme_make_request(struct request_queue *q, struct bio *bio)
764 struct nvme_ns *ns = q->queuedata;
765 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
770 bio_endio(bio, -EIO);
774 spin_lock_irq(&nvmeq->q_lock);
775 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
776 result = nvme_submit_bio_queue(nvmeq, ns, bio);
777 if (unlikely(result)) {
778 if (bio_list_empty(&nvmeq->sq_cong))
779 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
780 bio_list_add(&nvmeq->sq_cong, bio);
783 nvme_process_cq(nvmeq);
784 spin_unlock_irq(&nvmeq->q_lock);
788 static irqreturn_t nvme_irq(int irq, void *data)
791 struct nvme_queue *nvmeq = data;
792 spin_lock(&nvmeq->q_lock);
793 nvme_process_cq(nvmeq);
794 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
796 spin_unlock(&nvmeq->q_lock);
800 static irqreturn_t nvme_irq_check(int irq, void *data)
802 struct nvme_queue *nvmeq = data;
803 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
804 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
806 return IRQ_WAKE_THREAD;
809 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
811 spin_lock_irq(&nvmeq->q_lock);
812 cancel_cmdid(nvmeq, cmdid, NULL);
813 spin_unlock_irq(&nvmeq->q_lock);
816 struct sync_cmd_info {
817 struct task_struct *task;
822 static void sync_completion(struct nvme_dev *dev, void *ctx,
823 struct nvme_completion *cqe)
825 struct sync_cmd_info *cmdinfo = ctx;
826 cmdinfo->result = le32_to_cpup(&cqe->result);
827 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
828 wake_up_process(cmdinfo->task);
832 * Returns 0 on success. If the result is negative, it's a Linux error code;
833 * if the result is positive, it's an NVM Express status code
835 static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
836 struct nvme_command *cmd,
837 u32 *result, unsigned timeout)
840 struct sync_cmd_info cmdinfo;
841 struct nvme_queue *nvmeq;
843 nvmeq = lock_nvmeq(dev, q_idx);
849 cmdinfo.task = current;
850 cmdinfo.status = -EINTR;
852 cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
857 cmd->common.command_id = cmdid;
859 set_current_state(TASK_KILLABLE);
860 ret = nvme_submit_cmd(nvmeq, cmd);
862 free_cmdid(nvmeq, cmdid, NULL);
864 set_current_state(TASK_RUNNING);
868 schedule_timeout(timeout);
870 if (cmdinfo.status == -EINTR) {
871 nvmeq = lock_nvmeq(dev, q_idx);
873 nvme_abort_command(nvmeq, cmdid);
879 *result = cmdinfo.result;
881 return cmdinfo.status;
884 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
885 struct nvme_command *cmd,
886 struct async_cmd_info *cmdinfo, unsigned timeout)
890 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
893 cmdinfo->status = -EINTR;
894 cmd->common.command_id = cmdid;
895 return nvme_submit_cmd(nvmeq, cmd);
898 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
901 return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
904 int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
907 return nvme_submit_sync_cmd(dev, smp_processor_id() + 1, cmd, result,
911 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
912 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
914 return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
918 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
921 struct nvme_command c;
923 memset(&c, 0, sizeof(c));
924 c.delete_queue.opcode = opcode;
925 c.delete_queue.qid = cpu_to_le16(id);
927 status = nvme_submit_admin_cmd(dev, &c, NULL);
933 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
934 struct nvme_queue *nvmeq)
937 struct nvme_command c;
938 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
940 memset(&c, 0, sizeof(c));
941 c.create_cq.opcode = nvme_admin_create_cq;
942 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
943 c.create_cq.cqid = cpu_to_le16(qid);
944 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
945 c.create_cq.cq_flags = cpu_to_le16(flags);
946 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
948 status = nvme_submit_admin_cmd(dev, &c, NULL);
954 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
955 struct nvme_queue *nvmeq)
958 struct nvme_command c;
959 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
961 memset(&c, 0, sizeof(c));
962 c.create_sq.opcode = nvme_admin_create_sq;
963 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
964 c.create_sq.sqid = cpu_to_le16(qid);
965 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
966 c.create_sq.sq_flags = cpu_to_le16(flags);
967 c.create_sq.cqid = cpu_to_le16(qid);
969 status = nvme_submit_admin_cmd(dev, &c, NULL);
975 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
977 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
980 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
982 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
985 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
988 struct nvme_command c;
990 memset(&c, 0, sizeof(c));
991 c.identify.opcode = nvme_admin_identify;
992 c.identify.nsid = cpu_to_le32(nsid);
993 c.identify.prp1 = cpu_to_le64(dma_addr);
994 c.identify.cns = cpu_to_le32(cns);
996 return nvme_submit_admin_cmd(dev, &c, NULL);
999 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
1000 dma_addr_t dma_addr, u32 *result)
1002 struct nvme_command c;
1004 memset(&c, 0, sizeof(c));
1005 c.features.opcode = nvme_admin_get_features;
1006 c.features.nsid = cpu_to_le32(nsid);
1007 c.features.prp1 = cpu_to_le64(dma_addr);
1008 c.features.fid = cpu_to_le32(fid);
1010 return nvme_submit_admin_cmd(dev, &c, result);
1013 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1014 dma_addr_t dma_addr, u32 *result)
1016 struct nvme_command c;
1018 memset(&c, 0, sizeof(c));
1019 c.features.opcode = nvme_admin_set_features;
1020 c.features.prp1 = cpu_to_le64(dma_addr);
1021 c.features.fid = cpu_to_le32(fid);
1022 c.features.dword11 = cpu_to_le32(dword11);
1024 return nvme_submit_admin_cmd(dev, &c, result);
1028 * nvme_abort_cmd - Attempt aborting a command
1029 * @cmdid: Command id of a timed out IO
1030 * @queue: The queue with timed out IO
1032 * Schedule controller reset if the command was already aborted once before and
1033 * still hasn't been returned to the driver, or if this is the admin queue.
1035 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1038 struct nvme_command cmd;
1039 struct nvme_dev *dev = nvmeq->dev;
1040 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1041 struct nvme_queue *adminq;
1043 if (!nvmeq->qid || info[cmdid].aborted) {
1044 if (work_busy(&dev->reset_work))
1046 list_del_init(&dev->node);
1047 dev_warn(&dev->pci_dev->dev,
1048 "I/O %d QID %d timeout, reset controller\n", cmdid,
1050 PREPARE_WORK(&dev->reset_work, nvme_reset_failed_dev);
1051 queue_work(nvme_workq, &dev->reset_work);
1055 if (!dev->abort_limit)
1058 adminq = rcu_dereference(dev->queues[0]);
1059 a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
1064 memset(&cmd, 0, sizeof(cmd));
1065 cmd.abort.opcode = nvme_admin_abort_cmd;
1066 cmd.abort.cid = cmdid;
1067 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1068 cmd.abort.command_id = a_cmdid;
1071 info[cmdid].aborted = 1;
1072 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1074 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1076 nvme_submit_cmd(adminq, &cmd);
1080 * nvme_cancel_ios - Cancel outstanding I/Os
1081 * @queue: The queue to cancel I/Os on
1082 * @timeout: True to only cancel I/Os which have timed out
1084 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1086 int depth = nvmeq->q_depth - 1;
1087 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1088 unsigned long now = jiffies;
1091 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1093 nvme_completion_fn fn;
1094 static struct nvme_completion cqe = {
1095 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1098 if (timeout && !time_after(now, info[cmdid].timeout))
1100 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1102 if (timeout && nvmeq->dev->initialized) {
1103 nvme_abort_cmd(cmdid, nvmeq);
1106 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1108 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1109 fn(nvmeq->dev, ctx, &cqe);
1113 static void nvme_free_queue(struct rcu_head *r)
1115 struct nvme_queue *nvmeq = container_of(r, struct nvme_queue, r_head);
1117 spin_lock_irq(&nvmeq->q_lock);
1118 while (bio_list_peek(&nvmeq->sq_cong)) {
1119 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1120 bio_endio(bio, -EIO);
1122 spin_unlock_irq(&nvmeq->q_lock);
1124 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1125 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1126 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1127 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1129 free_cpumask_var(nvmeq->cpu_mask);
1133 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1137 for (i = dev->queue_count - 1; i >= lowest; i--) {
1138 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
1139 rcu_assign_pointer(dev->queues[i], NULL);
1140 call_rcu(&nvmeq->r_head, nvme_free_queue);
1146 * nvme_suspend_queue - put queue into suspended state
1147 * @nvmeq - queue to suspend
1149 * Returns 1 if already suspended, 0 otherwise.
1151 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1153 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1155 spin_lock_irq(&nvmeq->q_lock);
1156 if (nvmeq->q_suspended) {
1157 spin_unlock_irq(&nvmeq->q_lock);
1160 nvmeq->q_suspended = 1;
1161 nvmeq->dev->online_queues--;
1162 spin_unlock_irq(&nvmeq->q_lock);
1164 irq_set_affinity_hint(vector, NULL);
1165 free_irq(vector, nvmeq);
1170 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1172 spin_lock_irq(&nvmeq->q_lock);
1173 nvme_process_cq(nvmeq);
1174 nvme_cancel_ios(nvmeq, false);
1175 spin_unlock_irq(&nvmeq->q_lock);
1178 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1180 struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
1184 if (nvme_suspend_queue(nvmeq))
1187 /* Don't tell the adapter to delete the admin queue.
1188 * Don't tell a removed adapter to delete IO queues. */
1189 if (qid && readl(&dev->bar->csts) != -1) {
1190 adapter_delete_sq(dev, qid);
1191 adapter_delete_cq(dev, qid);
1193 nvme_clear_queue(nvmeq);
1196 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1197 int depth, int vector)
1199 struct device *dmadev = &dev->pci_dev->dev;
1200 unsigned extra = nvme_queue_extra(depth);
1201 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1205 nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1206 &nvmeq->cq_dma_addr, GFP_KERNEL);
1209 memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1211 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1212 &nvmeq->sq_dma_addr, GFP_KERNEL);
1213 if (!nvmeq->sq_cmds)
1216 if (qid && !zalloc_cpumask_var(&nvmeq->cpu_mask, GFP_KERNEL))
1219 nvmeq->q_dmadev = dmadev;
1221 snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1222 dev->instance, qid);
1223 spin_lock_init(&nvmeq->q_lock);
1225 nvmeq->cq_phase = 1;
1226 init_waitqueue_head(&nvmeq->sq_full);
1227 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1228 bio_list_init(&nvmeq->sq_cong);
1229 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1230 nvmeq->q_depth = depth;
1231 nvmeq->cq_vector = vector;
1233 nvmeq->q_suspended = 1;
1235 rcu_assign_pointer(dev->queues[qid], nvmeq);
1240 dma_free_coherent(dmadev, SQ_SIZE(depth), (void *)nvmeq->sq_cmds,
1241 nvmeq->sq_dma_addr);
1243 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1244 nvmeq->cq_dma_addr);
1250 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1253 if (use_threaded_interrupts)
1254 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1255 nvme_irq_check, nvme_irq, IRQF_SHARED,
1257 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1258 IRQF_SHARED, name, nvmeq);
1261 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1263 struct nvme_dev *dev = nvmeq->dev;
1264 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1268 nvmeq->cq_phase = 1;
1269 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1270 memset(nvmeq->cmdid_data, 0, extra);
1271 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1272 nvme_cancel_ios(nvmeq, false);
1273 nvmeq->q_suspended = 0;
1274 dev->online_queues++;
1277 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1279 struct nvme_dev *dev = nvmeq->dev;
1282 result = adapter_alloc_cq(dev, qid, nvmeq);
1286 result = adapter_alloc_sq(dev, qid, nvmeq);
1290 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1294 spin_lock_irq(&nvmeq->q_lock);
1295 nvme_init_queue(nvmeq, qid);
1296 spin_unlock_irq(&nvmeq->q_lock);
1301 adapter_delete_sq(dev, qid);
1303 adapter_delete_cq(dev, qid);
1307 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1309 unsigned long timeout;
1310 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1312 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1314 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1316 if (fatal_signal_pending(current))
1318 if (time_after(jiffies, timeout)) {
1319 dev_err(&dev->pci_dev->dev,
1320 "Device not ready; aborting initialisation\n");
1329 * If the device has been passed off to us in an enabled state, just clear
1330 * the enabled bit. The spec says we should set the 'shutdown notification
1331 * bits', but doing so may cause the device to complete commands to the
1332 * admin queue ... and we don't know what memory that might be pointing at!
1334 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1336 u32 cc = readl(&dev->bar->cc);
1338 if (cc & NVME_CC_ENABLE)
1339 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1340 return nvme_wait_ready(dev, cap, false);
1343 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1345 return nvme_wait_ready(dev, cap, true);
1348 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1350 unsigned long timeout;
1353 cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1354 writel(cc, &dev->bar->cc);
1356 timeout = 2 * HZ + jiffies;
1357 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1358 NVME_CSTS_SHST_CMPLT) {
1360 if (fatal_signal_pending(current))
1362 if (time_after(jiffies, timeout)) {
1363 dev_err(&dev->pci_dev->dev,
1364 "Device shutdown incomplete; abort shutdown\n");
1372 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1376 u64 cap = readq(&dev->bar->cap);
1377 struct nvme_queue *nvmeq;
1379 result = nvme_disable_ctrl(dev, cap);
1383 nvmeq = raw_nvmeq(dev, 0);
1385 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1390 aqa = nvmeq->q_depth - 1;
1393 dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1394 dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1395 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1396 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1398 writel(aqa, &dev->bar->aqa);
1399 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1400 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1401 writel(dev->ctrl_config, &dev->bar->cc);
1403 result = nvme_enable_ctrl(dev, cap);
1407 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1411 spin_lock_irq(&nvmeq->q_lock);
1412 nvme_init_queue(nvmeq, 0);
1413 spin_unlock_irq(&nvmeq->q_lock);
1417 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1418 unsigned long addr, unsigned length)
1420 int i, err, count, nents, offset;
1421 struct scatterlist *sg;
1422 struct page **pages;
1423 struct nvme_iod *iod;
1426 return ERR_PTR(-EINVAL);
1427 if (!length || length > INT_MAX - PAGE_SIZE)
1428 return ERR_PTR(-EINVAL);
1430 offset = offset_in_page(addr);
1431 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1432 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1434 return ERR_PTR(-ENOMEM);
1436 err = get_user_pages_fast(addr, count, 1, pages);
1443 iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1445 sg_init_table(sg, count);
1446 for (i = 0; i < count; i++) {
1447 sg_set_page(&sg[i], pages[i],
1448 min_t(unsigned, length, PAGE_SIZE - offset),
1450 length -= (PAGE_SIZE - offset);
1453 sg_mark_end(&sg[i - 1]);
1457 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1458 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1468 for (i = 0; i < count; i++)
1471 return ERR_PTR(err);
1474 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1475 struct nvme_iod *iod)
1479 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1480 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1482 for (i = 0; i < iod->nents; i++)
1483 put_page(sg_page(&iod->sg[i]));
1486 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1488 struct nvme_dev *dev = ns->dev;
1489 struct nvme_user_io io;
1490 struct nvme_command c;
1491 unsigned length, meta_len;
1493 struct nvme_iod *iod, *meta_iod = NULL;
1494 dma_addr_t meta_dma_addr;
1495 void *meta, *uninitialized_var(meta_mem);
1497 if (copy_from_user(&io, uio, sizeof(io)))
1499 length = (io.nblocks + 1) << ns->lba_shift;
1500 meta_len = (io.nblocks + 1) * ns->ms;
1502 if (meta_len && ((io.metadata & 3) || !io.metadata))
1505 switch (io.opcode) {
1506 case nvme_cmd_write:
1508 case nvme_cmd_compare:
1509 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1516 return PTR_ERR(iod);
1518 memset(&c, 0, sizeof(c));
1519 c.rw.opcode = io.opcode;
1520 c.rw.flags = io.flags;
1521 c.rw.nsid = cpu_to_le32(ns->ns_id);
1522 c.rw.slba = cpu_to_le64(io.slba);
1523 c.rw.length = cpu_to_le16(io.nblocks);
1524 c.rw.control = cpu_to_le16(io.control);
1525 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1526 c.rw.reftag = cpu_to_le32(io.reftag);
1527 c.rw.apptag = cpu_to_le16(io.apptag);
1528 c.rw.appmask = cpu_to_le16(io.appmask);
1531 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1533 if (IS_ERR(meta_iod)) {
1534 status = PTR_ERR(meta_iod);
1539 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1540 &meta_dma_addr, GFP_KERNEL);
1546 if (io.opcode & 1) {
1547 int meta_offset = 0;
1549 for (i = 0; i < meta_iod->nents; i++) {
1550 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1551 meta_iod->sg[i].offset;
1552 memcpy(meta_mem + meta_offset, meta,
1553 meta_iod->sg[i].length);
1554 kunmap_atomic(meta);
1555 meta_offset += meta_iod->sg[i].length;
1559 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1562 length = nvme_setup_prps(dev, &c.common, iod, length, GFP_KERNEL);
1564 if (length != (io.nblocks + 1) << ns->lba_shift)
1567 status = nvme_submit_io_cmd(dev, &c, NULL);
1570 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1571 int meta_offset = 0;
1573 for (i = 0; i < meta_iod->nents; i++) {
1574 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1575 meta_iod->sg[i].offset;
1576 memcpy(meta, meta_mem + meta_offset,
1577 meta_iod->sg[i].length);
1578 kunmap_atomic(meta);
1579 meta_offset += meta_iod->sg[i].length;
1583 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1588 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1589 nvme_free_iod(dev, iod);
1592 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1593 nvme_free_iod(dev, meta_iod);
1599 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1600 struct nvme_admin_cmd __user *ucmd)
1602 struct nvme_admin_cmd cmd;
1603 struct nvme_command c;
1605 struct nvme_iod *uninitialized_var(iod);
1608 if (!capable(CAP_SYS_ADMIN))
1610 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1613 memset(&c, 0, sizeof(c));
1614 c.common.opcode = cmd.opcode;
1615 c.common.flags = cmd.flags;
1616 c.common.nsid = cpu_to_le32(cmd.nsid);
1617 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1618 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1619 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1620 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1621 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1622 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1623 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1624 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1626 length = cmd.data_len;
1628 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1631 return PTR_ERR(iod);
1632 length = nvme_setup_prps(dev, &c.common, iod, length,
1636 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1638 if (length != cmd.data_len)
1641 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
1644 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1645 nvme_free_iod(dev, iod);
1648 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1649 sizeof(cmd.result)))
1655 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1658 struct nvme_ns *ns = bdev->bd_disk->private_data;
1662 force_successful_syscall_return();
1664 case NVME_IOCTL_ADMIN_CMD:
1665 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1666 case NVME_IOCTL_SUBMIT_IO:
1667 return nvme_submit_io(ns, (void __user *)arg);
1668 case SG_GET_VERSION_NUM:
1669 return nvme_sg_get_version_num((void __user *)arg);
1671 return nvme_sg_io(ns, (void __user *)arg);
1677 #ifdef CONFIG_COMPAT
1678 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1679 unsigned int cmd, unsigned long arg)
1681 struct nvme_ns *ns = bdev->bd_disk->private_data;
1685 return nvme_sg_io32(ns, arg);
1687 return nvme_ioctl(bdev, mode, cmd, arg);
1690 #define nvme_compat_ioctl NULL
1693 static int nvme_open(struct block_device *bdev, fmode_t mode)
1695 struct nvme_ns *ns = bdev->bd_disk->private_data;
1696 struct nvme_dev *dev = ns->dev;
1698 kref_get(&dev->kref);
1702 static void nvme_free_dev(struct kref *kref);
1704 static void nvme_release(struct gendisk *disk, fmode_t mode)
1706 struct nvme_ns *ns = disk->private_data;
1707 struct nvme_dev *dev = ns->dev;
1709 kref_put(&dev->kref, nvme_free_dev);
1712 static const struct block_device_operations nvme_fops = {
1713 .owner = THIS_MODULE,
1714 .ioctl = nvme_ioctl,
1715 .compat_ioctl = nvme_compat_ioctl,
1717 .release = nvme_release,
1720 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1722 while (bio_list_peek(&nvmeq->sq_cong)) {
1723 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1724 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1726 if (bio_list_empty(&nvmeq->sq_cong))
1727 remove_wait_queue(&nvmeq->sq_full,
1728 &nvmeq->sq_cong_wait);
1729 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1730 if (bio_list_empty(&nvmeq->sq_cong))
1731 add_wait_queue(&nvmeq->sq_full,
1732 &nvmeq->sq_cong_wait);
1733 bio_list_add_head(&nvmeq->sq_cong, bio);
1739 static int nvme_kthread(void *data)
1741 struct nvme_dev *dev, *next;
1743 while (!kthread_should_stop()) {
1744 set_current_state(TASK_INTERRUPTIBLE);
1745 spin_lock(&dev_list_lock);
1746 list_for_each_entry_safe(dev, next, &dev_list, node) {
1748 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1750 if (work_busy(&dev->reset_work))
1752 list_del_init(&dev->node);
1753 dev_warn(&dev->pci_dev->dev,
1754 "Failed status, reset controller\n");
1755 PREPARE_WORK(&dev->reset_work,
1756 nvme_reset_failed_dev);
1757 queue_work(nvme_workq, &dev->reset_work);
1761 for (i = 0; i < dev->queue_count; i++) {
1762 struct nvme_queue *nvmeq =
1763 rcu_dereference(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);
1777 spin_unlock(&dev_list_lock);
1778 schedule_timeout(round_jiffies_relative(HZ));
1783 static void nvme_config_discard(struct nvme_ns *ns)
1785 u32 logical_block_size = queue_logical_block_size(ns->queue);
1786 ns->queue->limits.discard_zeroes_data = 0;
1787 ns->queue->limits.discard_alignment = logical_block_size;
1788 ns->queue->limits.discard_granularity = logical_block_size;
1789 ns->queue->limits.max_discard_sectors = 0xffffffff;
1790 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1793 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1794 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1797 struct gendisk *disk;
1800 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1803 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1806 ns->queue = blk_alloc_queue(GFP_KERNEL);
1809 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1810 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1811 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1812 blk_queue_make_request(ns->queue, nvme_make_request);
1814 ns->queue->queuedata = ns;
1816 disk = alloc_disk(0);
1818 goto out_free_queue;
1821 lbaf = id->flbas & 0xf;
1822 ns->lba_shift = id->lbaf[lbaf].ds;
1823 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1824 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1825 if (dev->max_hw_sectors)
1826 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1828 disk->major = nvme_major;
1829 disk->first_minor = 0;
1830 disk->fops = &nvme_fops;
1831 disk->private_data = ns;
1832 disk->queue = ns->queue;
1833 disk->driverfs_dev = &dev->pci_dev->dev;
1834 disk->flags = GENHD_FL_EXT_DEVT;
1835 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1836 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1838 if (dev->oncs & NVME_CTRL_ONCS_DSM)
1839 nvme_config_discard(ns);
1844 blk_cleanup_queue(ns->queue);
1850 static int nvme_find_closest_node(int node)
1852 int n, val, min_val = INT_MAX, best_node = node;
1854 for_each_online_node(n) {
1857 val = node_distance(node, n);
1858 if (val < min_val) {
1866 static void nvme_set_queue_cpus(cpumask_t *qmask, struct nvme_queue *nvmeq,
1870 for_each_cpu(cpu, qmask) {
1871 if (cpumask_weight(nvmeq->cpu_mask) >= count)
1873 if (!cpumask_test_and_set_cpu(cpu, nvmeq->cpu_mask))
1874 *per_cpu_ptr(nvmeq->dev->io_queue, cpu) = nvmeq->qid;
1878 static void nvme_add_cpus(cpumask_t *mask, const cpumask_t *unassigned_cpus,
1879 const cpumask_t *new_mask, struct nvme_queue *nvmeq, int cpus_per_queue)
1882 for_each_cpu(next_cpu, new_mask) {
1883 cpumask_or(mask, mask, get_cpu_mask(next_cpu));
1884 cpumask_or(mask, mask, topology_thread_cpumask(next_cpu));
1885 cpumask_and(mask, mask, unassigned_cpus);
1886 nvme_set_queue_cpus(mask, nvmeq, cpus_per_queue);
1890 static void nvme_create_io_queues(struct nvme_dev *dev)
1894 max = min(dev->max_qid, num_online_cpus());
1895 for (i = dev->queue_count; i <= max; i++)
1896 if (!nvme_alloc_queue(dev, i, dev->q_depth, i - 1))
1899 max = min(dev->queue_count - 1, num_online_cpus());
1900 for (i = dev->online_queues; i <= max; i++)
1901 if (nvme_create_queue(raw_nvmeq(dev, i), i))
1906 * If there are fewer queues than online cpus, this will try to optimally
1907 * assign a queue to multiple cpus by grouping cpus that are "close" together:
1908 * thread siblings, core, socket, closest node, then whatever else is
1911 static void nvme_assign_io_queues(struct nvme_dev *dev)
1913 unsigned cpu, cpus_per_queue, queues, remainder, i;
1914 cpumask_var_t unassigned_cpus;
1916 nvme_create_io_queues(dev);
1918 queues = min(dev->online_queues - 1, num_online_cpus());
1922 cpus_per_queue = num_online_cpus() / queues;
1923 remainder = queues - (num_online_cpus() - queues * cpus_per_queue);
1925 if (!alloc_cpumask_var(&unassigned_cpus, GFP_KERNEL))
1928 cpumask_copy(unassigned_cpus, cpu_online_mask);
1929 cpu = cpumask_first(unassigned_cpus);
1930 for (i = 1; i <= queues; i++) {
1931 struct nvme_queue *nvmeq = lock_nvmeq(dev, i);
1934 cpumask_clear(nvmeq->cpu_mask);
1935 if (!cpumask_weight(unassigned_cpus)) {
1936 unlock_nvmeq(nvmeq);
1940 mask = *get_cpu_mask(cpu);
1941 nvme_set_queue_cpus(&mask, nvmeq, cpus_per_queue);
1942 if (cpus_weight(mask) < cpus_per_queue)
1943 nvme_add_cpus(&mask, unassigned_cpus,
1944 topology_thread_cpumask(cpu),
1945 nvmeq, cpus_per_queue);
1946 if (cpus_weight(mask) < cpus_per_queue)
1947 nvme_add_cpus(&mask, unassigned_cpus,
1948 topology_core_cpumask(cpu),
1949 nvmeq, cpus_per_queue);
1950 if (cpus_weight(mask) < cpus_per_queue)
1951 nvme_add_cpus(&mask, unassigned_cpus,
1952 cpumask_of_node(cpu_to_node(cpu)),
1953 nvmeq, cpus_per_queue);
1954 if (cpus_weight(mask) < cpus_per_queue)
1955 nvme_add_cpus(&mask, unassigned_cpus,
1957 nvme_find_closest_node(
1959 nvmeq, cpus_per_queue);
1960 if (cpus_weight(mask) < cpus_per_queue)
1961 nvme_add_cpus(&mask, unassigned_cpus,
1963 nvmeq, cpus_per_queue);
1965 WARN(cpumask_weight(nvmeq->cpu_mask) != cpus_per_queue,
1966 "nvme%d qid:%d mis-matched queue-to-cpu assignment\n",
1969 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
1971 cpumask_andnot(unassigned_cpus, unassigned_cpus,
1973 cpu = cpumask_next(cpu, unassigned_cpus);
1974 if (remainder && !--remainder)
1976 unlock_nvmeq(nvmeq);
1978 WARN(cpumask_weight(unassigned_cpus), "nvme%d unassigned online cpus\n",
1981 cpumask_andnot(unassigned_cpus, cpu_possible_mask, cpu_online_mask);
1982 for_each_cpu(cpu, unassigned_cpus)
1983 *per_cpu_ptr(dev->io_queue, cpu) = (i++ % queues) + 1;
1984 free_cpumask_var(unassigned_cpus);
1987 static int set_queue_count(struct nvme_dev *dev, int count)
1991 u32 q_count = (count - 1) | ((count - 1) << 16);
1993 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
1996 return status < 0 ? -EIO : -EBUSY;
1997 return min(result & 0xffff, result >> 16) + 1;
2000 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2002 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
2005 static int nvme_cpu_notify(struct notifier_block *self,
2006 unsigned long action, void *hcpu)
2008 struct nvme_dev *dev = container_of(self, struct nvme_dev, nb);
2012 nvme_assign_io_queues(dev);
2018 static int nvme_setup_io_queues(struct nvme_dev *dev)
2020 struct nvme_queue *adminq = raw_nvmeq(dev, 0);
2021 struct pci_dev *pdev = dev->pci_dev;
2022 int result, i, vecs, nr_io_queues, size;
2024 nr_io_queues = num_possible_cpus();
2025 result = set_queue_count(dev, nr_io_queues);
2028 if (result < nr_io_queues)
2029 nr_io_queues = result;
2031 size = db_bar_size(dev, nr_io_queues);
2035 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2038 if (!--nr_io_queues)
2040 size = db_bar_size(dev, nr_io_queues);
2042 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2043 adminq->q_db = dev->dbs;
2046 /* Deregister the admin queue's interrupt */
2047 free_irq(dev->entry[0].vector, adminq);
2049 vecs = nr_io_queues;
2050 for (i = 0; i < vecs; i++)
2051 dev->entry[i].entry = i;
2053 result = pci_enable_msix(pdev, dev->entry, vecs);
2060 vecs = nr_io_queues;
2064 result = pci_enable_msi_block(pdev, vecs);
2066 for (i = 0; i < vecs; i++)
2067 dev->entry[i].vector = i + pdev->irq;
2069 } else if (result < 0) {
2078 * Should investigate if there's a performance win from allocating
2079 * more queues than interrupt vectors; it might allow the submission
2080 * path to scale better, even if the receive path is limited by the
2081 * number of interrupts.
2083 nr_io_queues = vecs;
2084 dev->max_qid = nr_io_queues;
2086 result = queue_request_irq(dev, adminq, adminq->irqname);
2088 adminq->q_suspended = 1;
2092 /* Free previously allocated queues that are no longer usable */
2093 nvme_free_queues(dev, nr_io_queues + 1);
2094 nvme_assign_io_queues(dev);
2096 dev->nb.notifier_call = &nvme_cpu_notify;
2097 result = register_hotcpu_notifier(&dev->nb);
2104 nvme_free_queues(dev, 1);
2109 * Return: error value if an error occurred setting up the queues or calling
2110 * Identify Device. 0 if these succeeded, even if adding some of the
2111 * namespaces failed. At the moment, these failures are silent. TBD which
2112 * failures should be reported.
2114 static int nvme_dev_add(struct nvme_dev *dev)
2116 struct pci_dev *pdev = dev->pci_dev;
2120 struct nvme_id_ctrl *ctrl;
2121 struct nvme_id_ns *id_ns;
2123 dma_addr_t dma_addr;
2124 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
2126 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
2130 res = nvme_identify(dev, 0, 1, dma_addr);
2137 nn = le32_to_cpup(&ctrl->nn);
2138 dev->oncs = le16_to_cpup(&ctrl->oncs);
2139 dev->abort_limit = ctrl->acl + 1;
2140 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2141 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2142 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2144 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2145 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2146 (pdev->device == 0x0953) && ctrl->vs[3])
2147 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2150 for (i = 1; i <= nn; i++) {
2151 res = nvme_identify(dev, i, 0, dma_addr);
2155 if (id_ns->ncap == 0)
2158 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2159 dma_addr + 4096, NULL);
2161 memset(mem + 4096, 0, 4096);
2163 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2165 list_add_tail(&ns->list, &dev->namespaces);
2167 list_for_each_entry(ns, &dev->namespaces, list)
2172 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2176 static int nvme_dev_map(struct nvme_dev *dev)
2179 int bars, result = -ENOMEM;
2180 struct pci_dev *pdev = dev->pci_dev;
2182 if (pci_enable_device_mem(pdev))
2185 dev->entry[0].vector = pdev->irq;
2186 pci_set_master(pdev);
2187 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2188 if (pci_request_selected_regions(pdev, bars, "nvme"))
2191 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2192 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2195 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2198 if (readl(&dev->bar->csts) == -1) {
2202 cap = readq(&dev->bar->cap);
2203 dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2204 dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
2205 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2213 pci_release_regions(pdev);
2215 pci_disable_device(pdev);
2219 static void nvme_dev_unmap(struct nvme_dev *dev)
2221 if (dev->pci_dev->msi_enabled)
2222 pci_disable_msi(dev->pci_dev);
2223 else if (dev->pci_dev->msix_enabled)
2224 pci_disable_msix(dev->pci_dev);
2229 pci_release_regions(dev->pci_dev);
2232 if (pci_is_enabled(dev->pci_dev))
2233 pci_disable_device(dev->pci_dev);
2236 struct nvme_delq_ctx {
2237 struct task_struct *waiter;
2238 struct kthread_worker *worker;
2242 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2244 dq->waiter = current;
2248 set_current_state(TASK_KILLABLE);
2249 if (!atomic_read(&dq->refcount))
2251 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2252 fatal_signal_pending(current)) {
2253 set_current_state(TASK_RUNNING);
2255 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2256 nvme_disable_queue(dev, 0);
2258 send_sig(SIGKILL, dq->worker->task, 1);
2259 flush_kthread_worker(dq->worker);
2263 set_current_state(TASK_RUNNING);
2266 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2268 atomic_dec(&dq->refcount);
2270 wake_up_process(dq->waiter);
2273 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2275 atomic_inc(&dq->refcount);
2279 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2281 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2283 nvme_clear_queue(nvmeq);
2287 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2288 kthread_work_func_t fn)
2290 struct nvme_command c;
2292 memset(&c, 0, sizeof(c));
2293 c.delete_queue.opcode = opcode;
2294 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2296 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2297 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2300 static void nvme_del_cq_work_handler(struct kthread_work *work)
2302 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2304 nvme_del_queue_end(nvmeq);
2307 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2309 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2310 nvme_del_cq_work_handler);
2313 static void nvme_del_sq_work_handler(struct kthread_work *work)
2315 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2317 int status = nvmeq->cmdinfo.status;
2320 status = nvme_delete_cq(nvmeq);
2322 nvme_del_queue_end(nvmeq);
2325 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2327 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2328 nvme_del_sq_work_handler);
2331 static void nvme_del_queue_start(struct kthread_work *work)
2333 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2335 allow_signal(SIGKILL);
2336 if (nvme_delete_sq(nvmeq))
2337 nvme_del_queue_end(nvmeq);
2340 static void nvme_disable_io_queues(struct nvme_dev *dev)
2343 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2344 struct nvme_delq_ctx dq;
2345 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2346 &worker, "nvme%d", dev->instance);
2348 if (IS_ERR(kworker_task)) {
2349 dev_err(&dev->pci_dev->dev,
2350 "Failed to create queue del task\n");
2351 for (i = dev->queue_count - 1; i > 0; i--)
2352 nvme_disable_queue(dev, i);
2357 atomic_set(&dq.refcount, 0);
2358 dq.worker = &worker;
2359 for (i = dev->queue_count - 1; i > 0; i--) {
2360 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2362 if (nvme_suspend_queue(nvmeq))
2364 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2365 nvmeq->cmdinfo.worker = dq.worker;
2366 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2367 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2369 nvme_wait_dq(&dq, dev);
2370 kthread_stop(kworker_task);
2373 static void nvme_dev_shutdown(struct nvme_dev *dev)
2377 dev->initialized = 0;
2378 unregister_hotcpu_notifier(&dev->nb);
2380 spin_lock(&dev_list_lock);
2381 list_del_init(&dev->node);
2382 spin_unlock(&dev_list_lock);
2384 if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2385 for (i = dev->queue_count - 1; i >= 0; i--) {
2386 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2387 nvme_suspend_queue(nvmeq);
2388 nvme_clear_queue(nvmeq);
2391 nvme_disable_io_queues(dev);
2392 nvme_shutdown_ctrl(dev);
2393 nvme_disable_queue(dev, 0);
2395 nvme_dev_unmap(dev);
2398 static void nvme_dev_remove(struct nvme_dev *dev)
2402 list_for_each_entry(ns, &dev->namespaces, list) {
2403 if (ns->disk->flags & GENHD_FL_UP)
2404 del_gendisk(ns->disk);
2405 if (!blk_queue_dying(ns->queue))
2406 blk_cleanup_queue(ns->queue);
2410 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2412 struct device *dmadev = &dev->pci_dev->dev;
2413 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2414 PAGE_SIZE, PAGE_SIZE, 0);
2415 if (!dev->prp_page_pool)
2418 /* Optimisation for I/Os between 4k and 128k */
2419 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2421 if (!dev->prp_small_pool) {
2422 dma_pool_destroy(dev->prp_page_pool);
2428 static void nvme_release_prp_pools(struct nvme_dev *dev)
2430 dma_pool_destroy(dev->prp_page_pool);
2431 dma_pool_destroy(dev->prp_small_pool);
2434 static DEFINE_IDA(nvme_instance_ida);
2436 static int nvme_set_instance(struct nvme_dev *dev)
2438 int instance, error;
2441 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2444 spin_lock(&dev_list_lock);
2445 error = ida_get_new(&nvme_instance_ida, &instance);
2446 spin_unlock(&dev_list_lock);
2447 } while (error == -EAGAIN);
2452 dev->instance = instance;
2456 static void nvme_release_instance(struct nvme_dev *dev)
2458 spin_lock(&dev_list_lock);
2459 ida_remove(&nvme_instance_ida, dev->instance);
2460 spin_unlock(&dev_list_lock);
2463 static void nvme_free_namespaces(struct nvme_dev *dev)
2465 struct nvme_ns *ns, *next;
2467 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2468 list_del(&ns->list);
2474 static void nvme_free_dev(struct kref *kref)
2476 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2478 nvme_free_namespaces(dev);
2479 free_percpu(dev->io_queue);
2485 static int nvme_dev_open(struct inode *inode, struct file *f)
2487 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2489 kref_get(&dev->kref);
2490 f->private_data = dev;
2494 static int nvme_dev_release(struct inode *inode, struct file *f)
2496 struct nvme_dev *dev = f->private_data;
2497 kref_put(&dev->kref, nvme_free_dev);
2501 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2503 struct nvme_dev *dev = f->private_data;
2505 case NVME_IOCTL_ADMIN_CMD:
2506 return nvme_user_admin_cmd(dev, (void __user *)arg);
2512 static const struct file_operations nvme_dev_fops = {
2513 .owner = THIS_MODULE,
2514 .open = nvme_dev_open,
2515 .release = nvme_dev_release,
2516 .unlocked_ioctl = nvme_dev_ioctl,
2517 .compat_ioctl = nvme_dev_ioctl,
2520 static int nvme_dev_start(struct nvme_dev *dev)
2524 result = nvme_dev_map(dev);
2528 result = nvme_configure_admin_queue(dev);
2532 spin_lock(&dev_list_lock);
2533 list_add(&dev->node, &dev_list);
2534 spin_unlock(&dev_list_lock);
2536 result = nvme_setup_io_queues(dev);
2537 if (result && result != -EBUSY)
2543 nvme_disable_queue(dev, 0);
2544 spin_lock(&dev_list_lock);
2545 list_del_init(&dev->node);
2546 spin_unlock(&dev_list_lock);
2548 nvme_dev_unmap(dev);
2552 static int nvme_remove_dead_ctrl(void *arg)
2554 struct nvme_dev *dev = (struct nvme_dev *)arg;
2555 struct pci_dev *pdev = dev->pci_dev;
2557 if (pci_get_drvdata(pdev))
2558 pci_stop_and_remove_bus_device(pdev);
2559 kref_put(&dev->kref, nvme_free_dev);
2563 static void nvme_remove_disks(struct work_struct *ws)
2565 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2567 nvme_dev_remove(dev);
2568 nvme_free_queues(dev, 1);
2571 static int nvme_dev_resume(struct nvme_dev *dev)
2575 ret = nvme_dev_start(dev);
2576 if (ret && ret != -EBUSY)
2578 if (ret == -EBUSY) {
2579 spin_lock(&dev_list_lock);
2580 PREPARE_WORK(&dev->reset_work, nvme_remove_disks);
2581 queue_work(nvme_workq, &dev->reset_work);
2582 spin_unlock(&dev_list_lock);
2584 dev->initialized = 1;
2588 static void nvme_dev_reset(struct nvme_dev *dev)
2590 nvme_dev_shutdown(dev);
2591 if (nvme_dev_resume(dev)) {
2592 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2593 kref_get(&dev->kref);
2594 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2596 dev_err(&dev->pci_dev->dev,
2597 "Failed to start controller remove task\n");
2598 kref_put(&dev->kref, nvme_free_dev);
2603 static void nvme_reset_failed_dev(struct work_struct *ws)
2605 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2606 nvme_dev_reset(dev);
2609 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2611 int result = -ENOMEM;
2612 struct nvme_dev *dev;
2614 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2617 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2621 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2625 dev->io_queue = alloc_percpu(unsigned short);
2629 INIT_LIST_HEAD(&dev->namespaces);
2630 INIT_WORK(&dev->reset_work, nvme_reset_failed_dev);
2631 dev->pci_dev = pdev;
2632 pci_set_drvdata(pdev, dev);
2633 result = nvme_set_instance(dev);
2637 result = nvme_setup_prp_pools(dev);
2641 kref_init(&dev->kref);
2642 result = nvme_dev_start(dev);
2644 if (result == -EBUSY)
2649 result = nvme_dev_add(dev);
2654 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2655 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2656 dev->miscdev.parent = &pdev->dev;
2657 dev->miscdev.name = dev->name;
2658 dev->miscdev.fops = &nvme_dev_fops;
2659 result = misc_register(&dev->miscdev);
2663 dev->initialized = 1;
2667 nvme_dev_remove(dev);
2668 nvme_free_namespaces(dev);
2670 nvme_dev_shutdown(dev);
2672 nvme_free_queues(dev, 0);
2673 nvme_release_prp_pools(dev);
2675 nvme_release_instance(dev);
2677 free_percpu(dev->io_queue);
2684 static void nvme_shutdown(struct pci_dev *pdev)
2686 struct nvme_dev *dev = pci_get_drvdata(pdev);
2687 nvme_dev_shutdown(dev);
2690 static void nvme_remove(struct pci_dev *pdev)
2692 struct nvme_dev *dev = pci_get_drvdata(pdev);
2694 spin_lock(&dev_list_lock);
2695 list_del_init(&dev->node);
2696 spin_unlock(&dev_list_lock);
2698 pci_set_drvdata(pdev, NULL);
2699 flush_work(&dev->reset_work);
2700 misc_deregister(&dev->miscdev);
2701 nvme_dev_remove(dev);
2702 nvme_dev_shutdown(dev);
2703 nvme_free_queues(dev, 0);
2705 nvme_release_instance(dev);
2706 nvme_release_prp_pools(dev);
2707 kref_put(&dev->kref, nvme_free_dev);
2710 /* These functions are yet to be implemented */
2711 #define nvme_error_detected NULL
2712 #define nvme_dump_registers NULL
2713 #define nvme_link_reset NULL
2714 #define nvme_slot_reset NULL
2715 #define nvme_error_resume NULL
2717 #ifdef CONFIG_PM_SLEEP
2718 static int nvme_suspend(struct device *dev)
2720 struct pci_dev *pdev = to_pci_dev(dev);
2721 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2723 nvme_dev_shutdown(ndev);
2727 static int nvme_resume(struct device *dev)
2729 struct pci_dev *pdev = to_pci_dev(dev);
2730 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2732 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2733 PREPARE_WORK(&ndev->reset_work, nvme_reset_failed_dev);
2734 queue_work(nvme_workq, &ndev->reset_work);
2740 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2742 static const struct pci_error_handlers nvme_err_handler = {
2743 .error_detected = nvme_error_detected,
2744 .mmio_enabled = nvme_dump_registers,
2745 .link_reset = nvme_link_reset,
2746 .slot_reset = nvme_slot_reset,
2747 .resume = nvme_error_resume,
2750 /* Move to pci_ids.h later */
2751 #define PCI_CLASS_STORAGE_EXPRESS 0x010802
2753 static const struct pci_device_id nvme_id_table[] = {
2754 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2757 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2759 static struct pci_driver nvme_driver = {
2761 .id_table = nvme_id_table,
2762 .probe = nvme_probe,
2763 .remove = nvme_remove,
2764 .shutdown = nvme_shutdown,
2766 .pm = &nvme_dev_pm_ops,
2768 .err_handler = &nvme_err_handler,
2771 static int __init nvme_init(void)
2775 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2776 if (IS_ERR(nvme_thread))
2777 return PTR_ERR(nvme_thread);
2780 nvme_workq = create_singlethread_workqueue("nvme");
2784 result = register_blkdev(nvme_major, "nvme");
2787 else if (result > 0)
2788 nvme_major = result;
2790 result = pci_register_driver(&nvme_driver);
2792 goto unregister_blkdev;
2796 unregister_blkdev(nvme_major, "nvme");
2798 destroy_workqueue(nvme_workq);
2800 kthread_stop(nvme_thread);
2804 static void __exit nvme_exit(void)
2806 pci_unregister_driver(&nvme_driver);
2807 unregister_blkdev(nvme_major, "nvme");
2808 destroy_workqueue(nvme_workq);
2809 kthread_stop(nvme_thread);
2812 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2813 MODULE_LICENSE("GPL");
2814 MODULE_VERSION("0.9");
2815 module_init(nvme_init);
2816 module_exit(nvme_exit);