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 unsigned char io_timeout = 30;
54 module_param(io_timeout, byte, 0644);
55 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
57 static int nvme_major;
58 module_param(nvme_major, int, 0);
60 static int use_threaded_interrupts;
61 module_param(use_threaded_interrupts, int, 0);
63 static DEFINE_SPINLOCK(dev_list_lock);
64 static LIST_HEAD(dev_list);
65 static struct task_struct *nvme_thread;
66 static struct workqueue_struct *nvme_workq;
67 static wait_queue_head_t nvme_kthread_wait;
69 static void nvme_reset_failed_dev(struct work_struct *ws);
71 struct async_cmd_info {
72 struct kthread_work work;
73 struct kthread_worker *worker;
80 * An NVM Express queue. Each device has at least two (one for admin
81 * commands and one for I/O commands).
84 struct rcu_head r_head;
85 struct device *q_dmadev;
87 char irqname[24]; /* nvme4294967295-65535\0 */
89 struct nvme_command *sq_cmds;
90 volatile struct nvme_completion *cqes;
91 dma_addr_t sq_dma_addr;
92 dma_addr_t cq_dma_addr;
93 wait_queue_head_t sq_full;
94 wait_queue_t sq_cong_wait;
95 struct bio_list sq_cong;
106 cpumask_var_t cpu_mask;
107 struct async_cmd_info cmdinfo;
108 unsigned long cmdid_data[];
112 * Check we didin't inadvertently grow the command struct
114 static inline void _nvme_check_size(void)
116 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
117 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
118 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
119 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
120 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
121 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
122 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
123 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
124 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
125 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
126 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
127 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
130 typedef void (*nvme_completion_fn)(struct nvme_dev *, void *,
131 struct nvme_completion *);
133 struct nvme_cmd_info {
134 nvme_completion_fn fn;
136 unsigned long timeout;
140 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
142 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
145 static unsigned nvme_queue_extra(int depth)
147 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
151 * alloc_cmdid() - Allocate a Command ID
152 * @nvmeq: The queue that will be used for this command
153 * @ctx: A pointer that will be passed to the handler
154 * @handler: The function to call on completion
156 * Allocate a Command ID for a queue. The data passed in will
157 * be passed to the completion handler. This is implemented by using
158 * the bottom two bits of the ctx pointer to store the handler ID.
159 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
160 * We can change this if it becomes a problem.
162 * May be called with local interrupts disabled and the q_lock held,
163 * or with interrupts enabled and no locks held.
165 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
166 nvme_completion_fn handler, unsigned timeout)
168 int depth = nvmeq->q_depth - 1;
169 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
173 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
176 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
178 info[cmdid].fn = handler;
179 info[cmdid].ctx = ctx;
180 info[cmdid].timeout = jiffies + timeout;
181 info[cmdid].aborted = 0;
185 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
186 nvme_completion_fn handler, unsigned timeout)
189 wait_event_killable(nvmeq->sq_full,
190 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
191 return (cmdid < 0) ? -EINTR : cmdid;
194 /* Special values must be less than 0x1000 */
195 #define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
196 #define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
197 #define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
198 #define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
199 #define CMD_CTX_FLUSH (0x318 + CMD_CTX_BASE)
200 #define CMD_CTX_ABORT (0x31C + CMD_CTX_BASE)
202 static void special_completion(struct nvme_dev *dev, void *ctx,
203 struct nvme_completion *cqe)
205 if (ctx == CMD_CTX_CANCELLED)
207 if (ctx == CMD_CTX_FLUSH)
209 if (ctx == CMD_CTX_ABORT) {
213 if (ctx == CMD_CTX_COMPLETED) {
214 dev_warn(&dev->pci_dev->dev,
215 "completed id %d twice on queue %d\n",
216 cqe->command_id, le16_to_cpup(&cqe->sq_id));
219 if (ctx == CMD_CTX_INVALID) {
220 dev_warn(&dev->pci_dev->dev,
221 "invalid id %d completed on queue %d\n",
222 cqe->command_id, le16_to_cpup(&cqe->sq_id));
226 dev_warn(&dev->pci_dev->dev, "Unknown special completion %p\n", ctx);
229 static void async_completion(struct nvme_dev *dev, void *ctx,
230 struct nvme_completion *cqe)
232 struct async_cmd_info *cmdinfo = ctx;
233 cmdinfo->result = le32_to_cpup(&cqe->result);
234 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
235 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
239 * Called with local interrupts disabled and the q_lock held. May not sleep.
241 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
242 nvme_completion_fn *fn)
245 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
247 if (cmdid >= nvmeq->q_depth) {
248 *fn = special_completion;
249 return CMD_CTX_INVALID;
252 *fn = info[cmdid].fn;
253 ctx = info[cmdid].ctx;
254 info[cmdid].fn = special_completion;
255 info[cmdid].ctx = CMD_CTX_COMPLETED;
256 clear_bit(cmdid, nvmeq->cmdid_data);
257 wake_up(&nvmeq->sq_full);
261 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
262 nvme_completion_fn *fn)
265 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
267 *fn = info[cmdid].fn;
268 ctx = info[cmdid].ctx;
269 info[cmdid].fn = special_completion;
270 info[cmdid].ctx = CMD_CTX_CANCELLED;
274 static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
276 return rcu_dereference_raw(dev->queues[qid]);
279 static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
281 unsigned queue_id = get_cpu_var(*dev->io_queue);
283 return rcu_dereference(dev->queues[queue_id]);
286 static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
289 put_cpu_var(nvmeq->dev->io_queue);
292 static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
296 return rcu_dereference(dev->queues[q_idx]);
299 static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
305 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
306 * @nvmeq: The queue to use
307 * @cmd: The command to send
309 * Safe to use from interrupt context
311 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
315 spin_lock_irqsave(&nvmeq->q_lock, flags);
316 if (nvmeq->q_suspended) {
317 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
320 tail = nvmeq->sq_tail;
321 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
322 if (++tail == nvmeq->q_depth)
324 writel(tail, nvmeq->q_db);
325 nvmeq->sq_tail = tail;
326 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
331 static __le64 **iod_list(struct nvme_iod *iod)
333 return ((void *)iod) + iod->offset;
337 * Will slightly overestimate the number of pages needed. This is OK
338 * as it only leads to a small amount of wasted memory for the lifetime of
341 static int nvme_npages(unsigned size)
343 unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
344 return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
347 static struct nvme_iod *
348 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
350 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
351 sizeof(__le64 *) * nvme_npages(nbytes) +
352 sizeof(struct scatterlist) * nseg, gfp);
355 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
357 iod->length = nbytes;
359 iod->start_time = jiffies;
365 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
367 const int last_prp = PAGE_SIZE / 8 - 1;
369 __le64 **list = iod_list(iod);
370 dma_addr_t prp_dma = iod->first_dma;
372 if (iod->npages == 0)
373 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
374 for (i = 0; i < iod->npages; i++) {
375 __le64 *prp_list = list[i];
376 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
377 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
378 prp_dma = next_prp_dma;
383 static void nvme_start_io_acct(struct bio *bio)
385 struct gendisk *disk = bio->bi_bdev->bd_disk;
386 const int rw = bio_data_dir(bio);
387 int cpu = part_stat_lock();
388 part_round_stats(cpu, &disk->part0);
389 part_stat_inc(cpu, &disk->part0, ios[rw]);
390 part_stat_add(cpu, &disk->part0, sectors[rw], bio_sectors(bio));
391 part_inc_in_flight(&disk->part0, rw);
395 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
397 struct gendisk *disk = bio->bi_bdev->bd_disk;
398 const int rw = bio_data_dir(bio);
399 unsigned long duration = jiffies - start_time;
400 int cpu = part_stat_lock();
401 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
402 part_round_stats(cpu, &disk->part0);
403 part_dec_in_flight(&disk->part0, rw);
407 static void bio_completion(struct nvme_dev *dev, void *ctx,
408 struct nvme_completion *cqe)
410 struct nvme_iod *iod = ctx;
411 struct bio *bio = iod->private;
412 u16 status = le16_to_cpup(&cqe->status) >> 1;
415 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
416 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
417 nvme_end_io_acct(bio, iod->start_time);
419 nvme_free_iod(dev, iod);
421 bio_endio(bio, -EIO);
426 /* length is in bytes. gfp flags indicates whether we may sleep. */
427 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_common_command *cmd,
428 struct nvme_iod *iod, int total_len, gfp_t gfp)
430 struct dma_pool *pool;
431 int length = total_len;
432 struct scatterlist *sg = iod->sg;
433 int dma_len = sg_dma_len(sg);
434 u64 dma_addr = sg_dma_address(sg);
435 int offset = offset_in_page(dma_addr);
437 __le64 **list = iod_list(iod);
441 cmd->prp1 = cpu_to_le64(dma_addr);
442 length -= (PAGE_SIZE - offset);
446 dma_len -= (PAGE_SIZE - offset);
448 dma_addr += (PAGE_SIZE - offset);
451 dma_addr = sg_dma_address(sg);
452 dma_len = sg_dma_len(sg);
455 if (length <= PAGE_SIZE) {
456 cmd->prp2 = cpu_to_le64(dma_addr);
460 nprps = DIV_ROUND_UP(length, PAGE_SIZE);
461 if (nprps <= (256 / 8)) {
462 pool = dev->prp_small_pool;
465 pool = dev->prp_page_pool;
469 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
471 cmd->prp2 = cpu_to_le64(dma_addr);
473 return (total_len - length) + PAGE_SIZE;
476 iod->first_dma = prp_dma;
477 cmd->prp2 = cpu_to_le64(prp_dma);
480 if (i == PAGE_SIZE / 8) {
481 __le64 *old_prp_list = prp_list;
482 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
484 return total_len - length;
485 list[iod->npages++] = prp_list;
486 prp_list[0] = old_prp_list[i - 1];
487 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
490 prp_list[i++] = cpu_to_le64(dma_addr);
491 dma_len -= PAGE_SIZE;
492 dma_addr += PAGE_SIZE;
500 dma_addr = sg_dma_address(sg);
501 dma_len = sg_dma_len(sg);
507 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
510 struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
514 bio_chain(split, bio);
516 if (bio_list_empty(&nvmeq->sq_cong))
517 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
518 bio_list_add(&nvmeq->sq_cong, split);
519 bio_list_add(&nvmeq->sq_cong, bio);
524 /* NVMe scatterlists require no holes in the virtual address */
525 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
526 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
528 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
529 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
531 struct bio_vec bvec, bvprv;
532 struct bvec_iter iter;
533 struct scatterlist *sg = NULL;
534 int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
537 if (nvmeq->dev->stripe_size)
538 split_len = nvmeq->dev->stripe_size -
539 ((bio->bi_iter.bi_sector << 9) &
540 (nvmeq->dev->stripe_size - 1));
542 sg_init_table(iod->sg, psegs);
543 bio_for_each_segment(bvec, bio, iter) {
544 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
545 sg->length += bvec.bv_len;
547 if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
548 return nvme_split_and_submit(bio, nvmeq,
551 sg = sg ? sg + 1 : iod->sg;
552 sg_set_page(sg, bvec.bv_page,
553 bvec.bv_len, bvec.bv_offset);
557 if (split_len - length < bvec.bv_len)
558 return nvme_split_and_submit(bio, nvmeq, split_len);
559 length += bvec.bv_len;
565 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
568 BUG_ON(length != bio->bi_iter.bi_size);
573 * We reuse the small pool to allocate the 16-byte range here as it is not
574 * worth having a special pool for these or additional cases to handle freeing
577 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
578 struct bio *bio, struct nvme_iod *iod, int cmdid)
580 struct nvme_dsm_range *range;
581 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
583 range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
588 iod_list(iod)[0] = (__le64 *)range;
591 range->cattr = cpu_to_le32(0);
592 range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
593 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
595 memset(cmnd, 0, sizeof(*cmnd));
596 cmnd->dsm.opcode = nvme_cmd_dsm;
597 cmnd->dsm.command_id = cmdid;
598 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
599 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
601 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
603 if (++nvmeq->sq_tail == nvmeq->q_depth)
605 writel(nvmeq->sq_tail, nvmeq->q_db);
610 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
613 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
615 memset(cmnd, 0, sizeof(*cmnd));
616 cmnd->common.opcode = nvme_cmd_flush;
617 cmnd->common.command_id = cmdid;
618 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
620 if (++nvmeq->sq_tail == nvmeq->q_depth)
622 writel(nvmeq->sq_tail, nvmeq->q_db);
627 int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
629 int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
630 special_completion, NVME_IO_TIMEOUT);
631 if (unlikely(cmdid < 0))
634 return nvme_submit_flush(nvmeq, ns, cmdid);
638 * Called with local interrupts disabled and the q_lock held. May not sleep.
640 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
643 struct nvme_command *cmnd;
644 struct nvme_iod *iod;
645 enum dma_data_direction dma_dir;
646 int cmdid, length, result;
649 int psegs = bio_phys_segments(ns->queue, bio);
651 if ((bio->bi_rw & REQ_FLUSH) && psegs) {
652 result = nvme_submit_flush_data(nvmeq, ns);
658 iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, GFP_ATOMIC);
664 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
665 if (unlikely(cmdid < 0))
668 if (bio->bi_rw & REQ_DISCARD) {
669 result = nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
674 if ((bio->bi_rw & REQ_FLUSH) && !psegs)
675 return nvme_submit_flush(nvmeq, ns, cmdid);
678 if (bio->bi_rw & REQ_FUA)
679 control |= NVME_RW_FUA;
680 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
681 control |= NVME_RW_LR;
684 if (bio->bi_rw & REQ_RAHEAD)
685 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
687 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
689 memset(cmnd, 0, sizeof(*cmnd));
690 if (bio_data_dir(bio)) {
691 cmnd->rw.opcode = nvme_cmd_write;
692 dma_dir = DMA_TO_DEVICE;
694 cmnd->rw.opcode = nvme_cmd_read;
695 dma_dir = DMA_FROM_DEVICE;
698 result = nvme_map_bio(nvmeq, iod, bio, dma_dir, psegs);
703 cmnd->rw.command_id = cmdid;
704 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
705 length = nvme_setup_prps(nvmeq->dev, &cmnd->common, iod, length,
707 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
708 cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
709 cmnd->rw.control = cpu_to_le16(control);
710 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
712 nvme_start_io_acct(bio);
713 if (++nvmeq->sq_tail == nvmeq->q_depth)
715 writel(nvmeq->sq_tail, nvmeq->q_db);
720 free_cmdid(nvmeq, cmdid, NULL);
722 nvme_free_iod(nvmeq->dev, iod);
727 static int nvme_process_cq(struct nvme_queue *nvmeq)
731 head = nvmeq->cq_head;
732 phase = nvmeq->cq_phase;
736 nvme_completion_fn fn;
737 struct nvme_completion cqe = nvmeq->cqes[head];
738 if ((le16_to_cpu(cqe.status) & 1) != phase)
740 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
741 if (++head == nvmeq->q_depth) {
746 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
747 fn(nvmeq->dev, ctx, &cqe);
750 /* If the controller ignores the cq head doorbell and continuously
751 * writes to the queue, it is theoretically possible to wrap around
752 * the queue twice and mistakenly return IRQ_NONE. Linux only
753 * requires that 0.1% of your interrupts are handled, so this isn't
756 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
759 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
760 nvmeq->cq_head = head;
761 nvmeq->cq_phase = phase;
767 static void nvme_make_request(struct request_queue *q, struct bio *bio)
769 struct nvme_ns *ns = q->queuedata;
770 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
775 bio_endio(bio, -EIO);
779 spin_lock_irq(&nvmeq->q_lock);
780 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
781 result = nvme_submit_bio_queue(nvmeq, ns, bio);
782 if (unlikely(result)) {
783 if (bio_list_empty(&nvmeq->sq_cong))
784 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
785 bio_list_add(&nvmeq->sq_cong, bio);
788 nvme_process_cq(nvmeq);
789 spin_unlock_irq(&nvmeq->q_lock);
793 static irqreturn_t nvme_irq(int irq, void *data)
796 struct nvme_queue *nvmeq = data;
797 spin_lock(&nvmeq->q_lock);
798 nvme_process_cq(nvmeq);
799 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
801 spin_unlock(&nvmeq->q_lock);
805 static irqreturn_t nvme_irq_check(int irq, void *data)
807 struct nvme_queue *nvmeq = data;
808 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
809 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
811 return IRQ_WAKE_THREAD;
814 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
816 spin_lock_irq(&nvmeq->q_lock);
817 cancel_cmdid(nvmeq, cmdid, NULL);
818 spin_unlock_irq(&nvmeq->q_lock);
821 struct sync_cmd_info {
822 struct task_struct *task;
827 static void sync_completion(struct nvme_dev *dev, void *ctx,
828 struct nvme_completion *cqe)
830 struct sync_cmd_info *cmdinfo = ctx;
831 cmdinfo->result = le32_to_cpup(&cqe->result);
832 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
833 wake_up_process(cmdinfo->task);
837 * Returns 0 on success. If the result is negative, it's a Linux error code;
838 * if the result is positive, it's an NVM Express status code
840 static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
841 struct nvme_command *cmd,
842 u32 *result, unsigned timeout)
845 struct sync_cmd_info cmdinfo;
846 struct nvme_queue *nvmeq;
848 nvmeq = lock_nvmeq(dev, q_idx);
854 cmdinfo.task = current;
855 cmdinfo.status = -EINTR;
857 cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
862 cmd->common.command_id = cmdid;
864 set_current_state(TASK_KILLABLE);
865 ret = nvme_submit_cmd(nvmeq, cmd);
867 free_cmdid(nvmeq, cmdid, NULL);
869 set_current_state(TASK_RUNNING);
873 schedule_timeout(timeout);
875 if (cmdinfo.status == -EINTR) {
876 nvmeq = lock_nvmeq(dev, q_idx);
878 nvme_abort_command(nvmeq, cmdid);
884 *result = cmdinfo.result;
886 return cmdinfo.status;
889 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
890 struct nvme_command *cmd,
891 struct async_cmd_info *cmdinfo, unsigned timeout)
895 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
898 cmdinfo->status = -EINTR;
899 cmd->common.command_id = cmdid;
900 return nvme_submit_cmd(nvmeq, cmd);
903 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
906 return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
909 int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
912 return nvme_submit_sync_cmd(dev, smp_processor_id() + 1, cmd, result,
916 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
917 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
919 return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
923 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
926 struct nvme_command c;
928 memset(&c, 0, sizeof(c));
929 c.delete_queue.opcode = opcode;
930 c.delete_queue.qid = cpu_to_le16(id);
932 status = nvme_submit_admin_cmd(dev, &c, NULL);
938 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
939 struct nvme_queue *nvmeq)
942 struct nvme_command c;
943 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
945 memset(&c, 0, sizeof(c));
946 c.create_cq.opcode = nvme_admin_create_cq;
947 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
948 c.create_cq.cqid = cpu_to_le16(qid);
949 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
950 c.create_cq.cq_flags = cpu_to_le16(flags);
951 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
953 status = nvme_submit_admin_cmd(dev, &c, NULL);
959 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
960 struct nvme_queue *nvmeq)
963 struct nvme_command c;
964 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
966 memset(&c, 0, sizeof(c));
967 c.create_sq.opcode = nvme_admin_create_sq;
968 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
969 c.create_sq.sqid = cpu_to_le16(qid);
970 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
971 c.create_sq.sq_flags = cpu_to_le16(flags);
972 c.create_sq.cqid = cpu_to_le16(qid);
974 status = nvme_submit_admin_cmd(dev, &c, NULL);
980 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
982 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
985 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
987 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
990 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
993 struct nvme_command c;
995 memset(&c, 0, sizeof(c));
996 c.identify.opcode = nvme_admin_identify;
997 c.identify.nsid = cpu_to_le32(nsid);
998 c.identify.prp1 = cpu_to_le64(dma_addr);
999 c.identify.cns = cpu_to_le32(cns);
1001 return nvme_submit_admin_cmd(dev, &c, NULL);
1004 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
1005 dma_addr_t dma_addr, u32 *result)
1007 struct nvme_command c;
1009 memset(&c, 0, sizeof(c));
1010 c.features.opcode = nvme_admin_get_features;
1011 c.features.nsid = cpu_to_le32(nsid);
1012 c.features.prp1 = cpu_to_le64(dma_addr);
1013 c.features.fid = cpu_to_le32(fid);
1015 return nvme_submit_admin_cmd(dev, &c, result);
1018 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1019 dma_addr_t dma_addr, u32 *result)
1021 struct nvme_command c;
1023 memset(&c, 0, sizeof(c));
1024 c.features.opcode = nvme_admin_set_features;
1025 c.features.prp1 = cpu_to_le64(dma_addr);
1026 c.features.fid = cpu_to_le32(fid);
1027 c.features.dword11 = cpu_to_le32(dword11);
1029 return nvme_submit_admin_cmd(dev, &c, result);
1033 * nvme_abort_cmd - Attempt aborting a command
1034 * @cmdid: Command id of a timed out IO
1035 * @queue: The queue with timed out IO
1037 * Schedule controller reset if the command was already aborted once before and
1038 * still hasn't been returned to the driver, or if this is the admin queue.
1040 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1043 struct nvme_command cmd;
1044 struct nvme_dev *dev = nvmeq->dev;
1045 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1046 struct nvme_queue *adminq;
1048 if (!nvmeq->qid || info[cmdid].aborted) {
1049 if (work_busy(&dev->reset_work))
1051 list_del_init(&dev->node);
1052 dev_warn(&dev->pci_dev->dev,
1053 "I/O %d QID %d timeout, reset controller\n", cmdid,
1055 PREPARE_WORK(&dev->reset_work, nvme_reset_failed_dev);
1056 queue_work(nvme_workq, &dev->reset_work);
1060 if (!dev->abort_limit)
1063 adminq = rcu_dereference(dev->queues[0]);
1064 a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
1069 memset(&cmd, 0, sizeof(cmd));
1070 cmd.abort.opcode = nvme_admin_abort_cmd;
1071 cmd.abort.cid = cmdid;
1072 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1073 cmd.abort.command_id = a_cmdid;
1076 info[cmdid].aborted = 1;
1077 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1079 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1081 nvme_submit_cmd(adminq, &cmd);
1085 * nvme_cancel_ios - Cancel outstanding I/Os
1086 * @queue: The queue to cancel I/Os on
1087 * @timeout: True to only cancel I/Os which have timed out
1089 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1091 int depth = nvmeq->q_depth - 1;
1092 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1093 unsigned long now = jiffies;
1096 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1098 nvme_completion_fn fn;
1099 static struct nvme_completion cqe = {
1100 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1103 if (timeout && !time_after(now, info[cmdid].timeout))
1105 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1107 if (timeout && nvmeq->dev->initialized) {
1108 nvme_abort_cmd(cmdid, nvmeq);
1111 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1113 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1114 fn(nvmeq->dev, ctx, &cqe);
1118 static void nvme_free_queue(struct rcu_head *r)
1120 struct nvme_queue *nvmeq = container_of(r, struct nvme_queue, r_head);
1122 spin_lock_irq(&nvmeq->q_lock);
1123 while (bio_list_peek(&nvmeq->sq_cong)) {
1124 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1125 bio_endio(bio, -EIO);
1127 spin_unlock_irq(&nvmeq->q_lock);
1129 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1130 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1131 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1132 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1134 free_cpumask_var(nvmeq->cpu_mask);
1138 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1142 for (i = dev->queue_count - 1; i >= lowest; i--) {
1143 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
1144 rcu_assign_pointer(dev->queues[i], NULL);
1145 call_rcu(&nvmeq->r_head, nvme_free_queue);
1151 * nvme_suspend_queue - put queue into suspended state
1152 * @nvmeq - queue to suspend
1154 * Returns 1 if already suspended, 0 otherwise.
1156 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1158 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1160 spin_lock_irq(&nvmeq->q_lock);
1161 if (nvmeq->q_suspended) {
1162 spin_unlock_irq(&nvmeq->q_lock);
1165 nvmeq->q_suspended = 1;
1166 nvmeq->dev->online_queues--;
1167 spin_unlock_irq(&nvmeq->q_lock);
1169 irq_set_affinity_hint(vector, NULL);
1170 free_irq(vector, nvmeq);
1175 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1177 spin_lock_irq(&nvmeq->q_lock);
1178 nvme_process_cq(nvmeq);
1179 nvme_cancel_ios(nvmeq, false);
1180 spin_unlock_irq(&nvmeq->q_lock);
1183 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1185 struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
1189 if (nvme_suspend_queue(nvmeq))
1192 /* Don't tell the adapter to delete the admin queue.
1193 * Don't tell a removed adapter to delete IO queues. */
1194 if (qid && readl(&dev->bar->csts) != -1) {
1195 adapter_delete_sq(dev, qid);
1196 adapter_delete_cq(dev, qid);
1198 nvme_clear_queue(nvmeq);
1201 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1202 int depth, int vector)
1204 struct device *dmadev = &dev->pci_dev->dev;
1205 unsigned extra = nvme_queue_extra(depth);
1206 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1210 nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1211 &nvmeq->cq_dma_addr, GFP_KERNEL);
1214 memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1216 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1217 &nvmeq->sq_dma_addr, GFP_KERNEL);
1218 if (!nvmeq->sq_cmds)
1221 if (qid && !zalloc_cpumask_var(&nvmeq->cpu_mask, GFP_KERNEL))
1224 nvmeq->q_dmadev = dmadev;
1226 snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1227 dev->instance, qid);
1228 spin_lock_init(&nvmeq->q_lock);
1230 nvmeq->cq_phase = 1;
1231 init_waitqueue_head(&nvmeq->sq_full);
1232 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1233 bio_list_init(&nvmeq->sq_cong);
1234 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1235 nvmeq->q_depth = depth;
1236 nvmeq->cq_vector = vector;
1238 nvmeq->q_suspended = 1;
1240 rcu_assign_pointer(dev->queues[qid], nvmeq);
1245 dma_free_coherent(dmadev, SQ_SIZE(depth), (void *)nvmeq->sq_cmds,
1246 nvmeq->sq_dma_addr);
1248 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1249 nvmeq->cq_dma_addr);
1255 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1258 if (use_threaded_interrupts)
1259 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1260 nvme_irq_check, nvme_irq, IRQF_SHARED,
1262 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1263 IRQF_SHARED, name, nvmeq);
1266 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1268 struct nvme_dev *dev = nvmeq->dev;
1269 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1273 nvmeq->cq_phase = 1;
1274 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1275 memset(nvmeq->cmdid_data, 0, extra);
1276 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1277 nvme_cancel_ios(nvmeq, false);
1278 nvmeq->q_suspended = 0;
1279 dev->online_queues++;
1282 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1284 struct nvme_dev *dev = nvmeq->dev;
1287 result = adapter_alloc_cq(dev, qid, nvmeq);
1291 result = adapter_alloc_sq(dev, qid, nvmeq);
1295 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1299 spin_lock_irq(&nvmeq->q_lock);
1300 nvme_init_queue(nvmeq, qid);
1301 spin_unlock_irq(&nvmeq->q_lock);
1306 adapter_delete_sq(dev, qid);
1308 adapter_delete_cq(dev, qid);
1312 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1314 unsigned long timeout;
1315 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1317 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1319 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1321 if (fatal_signal_pending(current))
1323 if (time_after(jiffies, timeout)) {
1324 dev_err(&dev->pci_dev->dev,
1325 "Device not ready; aborting initialisation\n");
1334 * If the device has been passed off to us in an enabled state, just clear
1335 * the enabled bit. The spec says we should set the 'shutdown notification
1336 * bits', but doing so may cause the device to complete commands to the
1337 * admin queue ... and we don't know what memory that might be pointing at!
1339 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1341 u32 cc = readl(&dev->bar->cc);
1343 if (cc & NVME_CC_ENABLE)
1344 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1345 return nvme_wait_ready(dev, cap, false);
1348 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1350 return nvme_wait_ready(dev, cap, true);
1353 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1355 unsigned long timeout;
1358 cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1359 writel(cc, &dev->bar->cc);
1361 timeout = 2 * HZ + jiffies;
1362 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1363 NVME_CSTS_SHST_CMPLT) {
1365 if (fatal_signal_pending(current))
1367 if (time_after(jiffies, timeout)) {
1368 dev_err(&dev->pci_dev->dev,
1369 "Device shutdown incomplete; abort shutdown\n");
1377 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1381 u64 cap = readq(&dev->bar->cap);
1382 struct nvme_queue *nvmeq;
1384 result = nvme_disable_ctrl(dev, cap);
1388 nvmeq = raw_nvmeq(dev, 0);
1390 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1395 aqa = nvmeq->q_depth - 1;
1398 dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1399 dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1400 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1401 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1403 writel(aqa, &dev->bar->aqa);
1404 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1405 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1406 writel(dev->ctrl_config, &dev->bar->cc);
1408 result = nvme_enable_ctrl(dev, cap);
1412 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1416 spin_lock_irq(&nvmeq->q_lock);
1417 nvme_init_queue(nvmeq, 0);
1418 spin_unlock_irq(&nvmeq->q_lock);
1422 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1423 unsigned long addr, unsigned length)
1425 int i, err, count, nents, offset;
1426 struct scatterlist *sg;
1427 struct page **pages;
1428 struct nvme_iod *iod;
1431 return ERR_PTR(-EINVAL);
1432 if (!length || length > INT_MAX - PAGE_SIZE)
1433 return ERR_PTR(-EINVAL);
1435 offset = offset_in_page(addr);
1436 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1437 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1439 return ERR_PTR(-ENOMEM);
1441 err = get_user_pages_fast(addr, count, 1, pages);
1448 iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1450 sg_init_table(sg, count);
1451 for (i = 0; i < count; i++) {
1452 sg_set_page(&sg[i], pages[i],
1453 min_t(unsigned, length, PAGE_SIZE - offset),
1455 length -= (PAGE_SIZE - offset);
1458 sg_mark_end(&sg[i - 1]);
1462 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1463 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1473 for (i = 0; i < count; i++)
1476 return ERR_PTR(err);
1479 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1480 struct nvme_iod *iod)
1484 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1485 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1487 for (i = 0; i < iod->nents; i++)
1488 put_page(sg_page(&iod->sg[i]));
1491 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1493 struct nvme_dev *dev = ns->dev;
1494 struct nvme_user_io io;
1495 struct nvme_command c;
1496 unsigned length, meta_len;
1498 struct nvme_iod *iod, *meta_iod = NULL;
1499 dma_addr_t meta_dma_addr;
1500 void *meta, *uninitialized_var(meta_mem);
1502 if (copy_from_user(&io, uio, sizeof(io)))
1504 length = (io.nblocks + 1) << ns->lba_shift;
1505 meta_len = (io.nblocks + 1) * ns->ms;
1507 if (meta_len && ((io.metadata & 3) || !io.metadata))
1510 switch (io.opcode) {
1511 case nvme_cmd_write:
1513 case nvme_cmd_compare:
1514 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1521 return PTR_ERR(iod);
1523 memset(&c, 0, sizeof(c));
1524 c.rw.opcode = io.opcode;
1525 c.rw.flags = io.flags;
1526 c.rw.nsid = cpu_to_le32(ns->ns_id);
1527 c.rw.slba = cpu_to_le64(io.slba);
1528 c.rw.length = cpu_to_le16(io.nblocks);
1529 c.rw.control = cpu_to_le16(io.control);
1530 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1531 c.rw.reftag = cpu_to_le32(io.reftag);
1532 c.rw.apptag = cpu_to_le16(io.apptag);
1533 c.rw.appmask = cpu_to_le16(io.appmask);
1536 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1538 if (IS_ERR(meta_iod)) {
1539 status = PTR_ERR(meta_iod);
1544 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1545 &meta_dma_addr, GFP_KERNEL);
1551 if (io.opcode & 1) {
1552 int meta_offset = 0;
1554 for (i = 0; i < meta_iod->nents; i++) {
1555 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1556 meta_iod->sg[i].offset;
1557 memcpy(meta_mem + meta_offset, meta,
1558 meta_iod->sg[i].length);
1559 kunmap_atomic(meta);
1560 meta_offset += meta_iod->sg[i].length;
1564 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1567 length = nvme_setup_prps(dev, &c.common, iod, length, GFP_KERNEL);
1569 if (length != (io.nblocks + 1) << ns->lba_shift)
1572 status = nvme_submit_io_cmd(dev, &c, NULL);
1575 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1576 int meta_offset = 0;
1578 for (i = 0; i < meta_iod->nents; i++) {
1579 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1580 meta_iod->sg[i].offset;
1581 memcpy(meta, meta_mem + meta_offset,
1582 meta_iod->sg[i].length);
1583 kunmap_atomic(meta);
1584 meta_offset += meta_iod->sg[i].length;
1588 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1593 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1594 nvme_free_iod(dev, iod);
1597 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1598 nvme_free_iod(dev, meta_iod);
1604 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1605 struct nvme_admin_cmd __user *ucmd)
1607 struct nvme_admin_cmd cmd;
1608 struct nvme_command c;
1610 struct nvme_iod *uninitialized_var(iod);
1613 if (!capable(CAP_SYS_ADMIN))
1615 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1618 memset(&c, 0, sizeof(c));
1619 c.common.opcode = cmd.opcode;
1620 c.common.flags = cmd.flags;
1621 c.common.nsid = cpu_to_le32(cmd.nsid);
1622 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1623 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1624 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1625 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1626 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1627 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1628 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1629 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1631 length = cmd.data_len;
1633 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1636 return PTR_ERR(iod);
1637 length = nvme_setup_prps(dev, &c.common, iod, length,
1641 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1643 if (length != cmd.data_len)
1646 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
1649 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1650 nvme_free_iod(dev, iod);
1653 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1654 sizeof(cmd.result)))
1660 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1663 struct nvme_ns *ns = bdev->bd_disk->private_data;
1667 force_successful_syscall_return();
1669 case NVME_IOCTL_ADMIN_CMD:
1670 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1671 case NVME_IOCTL_SUBMIT_IO:
1672 return nvme_submit_io(ns, (void __user *)arg);
1673 case SG_GET_VERSION_NUM:
1674 return nvme_sg_get_version_num((void __user *)arg);
1676 return nvme_sg_io(ns, (void __user *)arg);
1682 #ifdef CONFIG_COMPAT
1683 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1684 unsigned int cmd, unsigned long arg)
1686 struct nvme_ns *ns = bdev->bd_disk->private_data;
1690 return nvme_sg_io32(ns, arg);
1692 return nvme_ioctl(bdev, mode, cmd, arg);
1695 #define nvme_compat_ioctl NULL
1698 static int nvme_open(struct block_device *bdev, fmode_t mode)
1700 struct nvme_ns *ns = bdev->bd_disk->private_data;
1701 struct nvme_dev *dev = ns->dev;
1703 kref_get(&dev->kref);
1707 static void nvme_free_dev(struct kref *kref);
1709 static void nvme_release(struct gendisk *disk, fmode_t mode)
1711 struct nvme_ns *ns = disk->private_data;
1712 struct nvme_dev *dev = ns->dev;
1714 kref_put(&dev->kref, nvme_free_dev);
1717 static const struct block_device_operations nvme_fops = {
1718 .owner = THIS_MODULE,
1719 .ioctl = nvme_ioctl,
1720 .compat_ioctl = nvme_compat_ioctl,
1722 .release = nvme_release,
1725 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1727 while (bio_list_peek(&nvmeq->sq_cong)) {
1728 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1729 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1731 if (bio_list_empty(&nvmeq->sq_cong))
1732 remove_wait_queue(&nvmeq->sq_full,
1733 &nvmeq->sq_cong_wait);
1734 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1735 if (bio_list_empty(&nvmeq->sq_cong))
1736 add_wait_queue(&nvmeq->sq_full,
1737 &nvmeq->sq_cong_wait);
1738 bio_list_add_head(&nvmeq->sq_cong, bio);
1744 static int nvme_kthread(void *data)
1746 struct nvme_dev *dev, *next;
1748 while (!kthread_should_stop()) {
1749 set_current_state(TASK_INTERRUPTIBLE);
1750 spin_lock(&dev_list_lock);
1751 list_for_each_entry_safe(dev, next, &dev_list, node) {
1753 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1755 if (work_busy(&dev->reset_work))
1757 list_del_init(&dev->node);
1758 dev_warn(&dev->pci_dev->dev,
1759 "Failed status, reset controller\n");
1760 PREPARE_WORK(&dev->reset_work,
1761 nvme_reset_failed_dev);
1762 queue_work(nvme_workq, &dev->reset_work);
1766 for (i = 0; i < dev->queue_count; i++) {
1767 struct nvme_queue *nvmeq =
1768 rcu_dereference(dev->queues[i]);
1771 spin_lock_irq(&nvmeq->q_lock);
1772 if (nvmeq->q_suspended)
1774 nvme_process_cq(nvmeq);
1775 nvme_cancel_ios(nvmeq, true);
1776 nvme_resubmit_bios(nvmeq);
1778 spin_unlock_irq(&nvmeq->q_lock);
1782 spin_unlock(&dev_list_lock);
1783 schedule_timeout(round_jiffies_relative(HZ));
1788 static void nvme_config_discard(struct nvme_ns *ns)
1790 u32 logical_block_size = queue_logical_block_size(ns->queue);
1791 ns->queue->limits.discard_zeroes_data = 0;
1792 ns->queue->limits.discard_alignment = logical_block_size;
1793 ns->queue->limits.discard_granularity = logical_block_size;
1794 ns->queue->limits.max_discard_sectors = 0xffffffff;
1795 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1798 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1799 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1802 struct gendisk *disk;
1805 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1808 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1811 ns->queue = blk_alloc_queue(GFP_KERNEL);
1814 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1815 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1816 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1817 blk_queue_make_request(ns->queue, nvme_make_request);
1819 ns->queue->queuedata = ns;
1821 disk = alloc_disk(0);
1823 goto out_free_queue;
1826 lbaf = id->flbas & 0xf;
1827 ns->lba_shift = id->lbaf[lbaf].ds;
1828 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1829 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1830 if (dev->max_hw_sectors)
1831 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1833 disk->major = nvme_major;
1834 disk->first_minor = 0;
1835 disk->fops = &nvme_fops;
1836 disk->private_data = ns;
1837 disk->queue = ns->queue;
1838 disk->driverfs_dev = &dev->pci_dev->dev;
1839 disk->flags = GENHD_FL_EXT_DEVT;
1840 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1841 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1843 if (dev->oncs & NVME_CTRL_ONCS_DSM)
1844 nvme_config_discard(ns);
1849 blk_cleanup_queue(ns->queue);
1855 static int nvme_find_closest_node(int node)
1857 int n, val, min_val = INT_MAX, best_node = node;
1859 for_each_online_node(n) {
1862 val = node_distance(node, n);
1863 if (val < min_val) {
1871 static void nvme_set_queue_cpus(cpumask_t *qmask, struct nvme_queue *nvmeq,
1875 for_each_cpu(cpu, qmask) {
1876 if (cpumask_weight(nvmeq->cpu_mask) >= count)
1878 if (!cpumask_test_and_set_cpu(cpu, nvmeq->cpu_mask))
1879 *per_cpu_ptr(nvmeq->dev->io_queue, cpu) = nvmeq->qid;
1883 static void nvme_add_cpus(cpumask_t *mask, const cpumask_t *unassigned_cpus,
1884 const cpumask_t *new_mask, struct nvme_queue *nvmeq, int cpus_per_queue)
1887 for_each_cpu(next_cpu, new_mask) {
1888 cpumask_or(mask, mask, get_cpu_mask(next_cpu));
1889 cpumask_or(mask, mask, topology_thread_cpumask(next_cpu));
1890 cpumask_and(mask, mask, unassigned_cpus);
1891 nvme_set_queue_cpus(mask, nvmeq, cpus_per_queue);
1895 static void nvme_create_io_queues(struct nvme_dev *dev)
1899 max = min(dev->max_qid, num_online_cpus());
1900 for (i = dev->queue_count; i <= max; i++)
1901 if (!nvme_alloc_queue(dev, i, dev->q_depth, i - 1))
1904 max = min(dev->queue_count - 1, num_online_cpus());
1905 for (i = dev->online_queues; i <= max; i++)
1906 if (nvme_create_queue(raw_nvmeq(dev, i), i))
1911 * If there are fewer queues than online cpus, this will try to optimally
1912 * assign a queue to multiple cpus by grouping cpus that are "close" together:
1913 * thread siblings, core, socket, closest node, then whatever else is
1916 static void nvme_assign_io_queues(struct nvme_dev *dev)
1918 unsigned cpu, cpus_per_queue, queues, remainder, i;
1919 cpumask_var_t unassigned_cpus;
1921 nvme_create_io_queues(dev);
1923 queues = min(dev->online_queues - 1, num_online_cpus());
1927 cpus_per_queue = num_online_cpus() / queues;
1928 remainder = queues - (num_online_cpus() - queues * cpus_per_queue);
1930 if (!alloc_cpumask_var(&unassigned_cpus, GFP_KERNEL))
1933 cpumask_copy(unassigned_cpus, cpu_online_mask);
1934 cpu = cpumask_first(unassigned_cpus);
1935 for (i = 1; i <= queues; i++) {
1936 struct nvme_queue *nvmeq = lock_nvmeq(dev, i);
1939 cpumask_clear(nvmeq->cpu_mask);
1940 if (!cpumask_weight(unassigned_cpus)) {
1941 unlock_nvmeq(nvmeq);
1945 mask = *get_cpu_mask(cpu);
1946 nvme_set_queue_cpus(&mask, nvmeq, cpus_per_queue);
1947 if (cpus_weight(mask) < cpus_per_queue)
1948 nvme_add_cpus(&mask, unassigned_cpus,
1949 topology_thread_cpumask(cpu),
1950 nvmeq, cpus_per_queue);
1951 if (cpus_weight(mask) < cpus_per_queue)
1952 nvme_add_cpus(&mask, unassigned_cpus,
1953 topology_core_cpumask(cpu),
1954 nvmeq, cpus_per_queue);
1955 if (cpus_weight(mask) < cpus_per_queue)
1956 nvme_add_cpus(&mask, unassigned_cpus,
1957 cpumask_of_node(cpu_to_node(cpu)),
1958 nvmeq, cpus_per_queue);
1959 if (cpus_weight(mask) < cpus_per_queue)
1960 nvme_add_cpus(&mask, unassigned_cpus,
1962 nvme_find_closest_node(
1964 nvmeq, cpus_per_queue);
1965 if (cpus_weight(mask) < cpus_per_queue)
1966 nvme_add_cpus(&mask, unassigned_cpus,
1968 nvmeq, cpus_per_queue);
1970 WARN(cpumask_weight(nvmeq->cpu_mask) != cpus_per_queue,
1971 "nvme%d qid:%d mis-matched queue-to-cpu assignment\n",
1974 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
1976 cpumask_andnot(unassigned_cpus, unassigned_cpus,
1978 cpu = cpumask_next(cpu, unassigned_cpus);
1979 if (remainder && !--remainder)
1981 unlock_nvmeq(nvmeq);
1983 WARN(cpumask_weight(unassigned_cpus), "nvme%d unassigned online cpus\n",
1986 cpumask_andnot(unassigned_cpus, cpu_possible_mask, cpu_online_mask);
1987 for_each_cpu(cpu, unassigned_cpus)
1988 *per_cpu_ptr(dev->io_queue, cpu) = (i++ % queues) + 1;
1989 free_cpumask_var(unassigned_cpus);
1992 static int set_queue_count(struct nvme_dev *dev, int count)
1996 u32 q_count = (count - 1) | ((count - 1) << 16);
1998 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
2001 return status < 0 ? -EIO : -EBUSY;
2002 return min(result & 0xffff, result >> 16) + 1;
2005 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2007 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
2010 static int nvme_cpu_notify(struct notifier_block *self,
2011 unsigned long action, void *hcpu)
2013 struct nvme_dev *dev = container_of(self, struct nvme_dev, nb);
2017 nvme_assign_io_queues(dev);
2023 static int nvme_setup_io_queues(struct nvme_dev *dev)
2025 struct nvme_queue *adminq = raw_nvmeq(dev, 0);
2026 struct pci_dev *pdev = dev->pci_dev;
2027 int result, i, vecs, nr_io_queues, size;
2029 nr_io_queues = num_possible_cpus();
2030 result = set_queue_count(dev, nr_io_queues);
2033 if (result < nr_io_queues)
2034 nr_io_queues = result;
2036 size = db_bar_size(dev, nr_io_queues);
2040 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2043 if (!--nr_io_queues)
2045 size = db_bar_size(dev, nr_io_queues);
2047 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2048 adminq->q_db = dev->dbs;
2051 /* Deregister the admin queue's interrupt */
2052 free_irq(dev->entry[0].vector, adminq);
2054 vecs = nr_io_queues;
2055 for (i = 0; i < vecs; i++)
2056 dev->entry[i].entry = i;
2058 result = pci_enable_msix(pdev, dev->entry, vecs);
2065 vecs = nr_io_queues;
2069 result = pci_enable_msi_block(pdev, vecs);
2071 for (i = 0; i < vecs; i++)
2072 dev->entry[i].vector = i + pdev->irq;
2074 } else if (result < 0) {
2083 * Should investigate if there's a performance win from allocating
2084 * more queues than interrupt vectors; it might allow the submission
2085 * path to scale better, even if the receive path is limited by the
2086 * number of interrupts.
2088 nr_io_queues = vecs;
2089 dev->max_qid = nr_io_queues;
2091 result = queue_request_irq(dev, adminq, adminq->irqname);
2093 adminq->q_suspended = 1;
2097 /* Free previously allocated queues that are no longer usable */
2098 nvme_free_queues(dev, nr_io_queues + 1);
2099 nvme_assign_io_queues(dev);
2101 dev->nb.notifier_call = &nvme_cpu_notify;
2102 result = register_hotcpu_notifier(&dev->nb);
2109 nvme_free_queues(dev, 1);
2114 * Return: error value if an error occurred setting up the queues or calling
2115 * Identify Device. 0 if these succeeded, even if adding some of the
2116 * namespaces failed. At the moment, these failures are silent. TBD which
2117 * failures should be reported.
2119 static int nvme_dev_add(struct nvme_dev *dev)
2121 struct pci_dev *pdev = dev->pci_dev;
2125 struct nvme_id_ctrl *ctrl;
2126 struct nvme_id_ns *id_ns;
2128 dma_addr_t dma_addr;
2129 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
2131 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
2135 res = nvme_identify(dev, 0, 1, dma_addr);
2142 nn = le32_to_cpup(&ctrl->nn);
2143 dev->oncs = le16_to_cpup(&ctrl->oncs);
2144 dev->abort_limit = ctrl->acl + 1;
2145 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2146 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2147 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2149 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2150 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2151 (pdev->device == 0x0953) && ctrl->vs[3])
2152 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2155 for (i = 1; i <= nn; i++) {
2156 res = nvme_identify(dev, i, 0, dma_addr);
2160 if (id_ns->ncap == 0)
2163 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2164 dma_addr + 4096, NULL);
2166 memset(mem + 4096, 0, 4096);
2168 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2170 list_add_tail(&ns->list, &dev->namespaces);
2172 list_for_each_entry(ns, &dev->namespaces, list)
2177 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2181 static int nvme_dev_map(struct nvme_dev *dev)
2184 int bars, result = -ENOMEM;
2185 struct pci_dev *pdev = dev->pci_dev;
2187 if (pci_enable_device_mem(pdev))
2190 dev->entry[0].vector = pdev->irq;
2191 pci_set_master(pdev);
2192 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2193 if (pci_request_selected_regions(pdev, bars, "nvme"))
2196 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2197 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2200 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2203 if (readl(&dev->bar->csts) == -1) {
2207 cap = readq(&dev->bar->cap);
2208 dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2209 dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
2210 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2218 pci_release_regions(pdev);
2220 pci_disable_device(pdev);
2224 static void nvme_dev_unmap(struct nvme_dev *dev)
2226 if (dev->pci_dev->msi_enabled)
2227 pci_disable_msi(dev->pci_dev);
2228 else if (dev->pci_dev->msix_enabled)
2229 pci_disable_msix(dev->pci_dev);
2234 pci_release_regions(dev->pci_dev);
2237 if (pci_is_enabled(dev->pci_dev))
2238 pci_disable_device(dev->pci_dev);
2241 struct nvme_delq_ctx {
2242 struct task_struct *waiter;
2243 struct kthread_worker *worker;
2247 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2249 dq->waiter = current;
2253 set_current_state(TASK_KILLABLE);
2254 if (!atomic_read(&dq->refcount))
2256 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2257 fatal_signal_pending(current)) {
2258 set_current_state(TASK_RUNNING);
2260 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2261 nvme_disable_queue(dev, 0);
2263 send_sig(SIGKILL, dq->worker->task, 1);
2264 flush_kthread_worker(dq->worker);
2268 set_current_state(TASK_RUNNING);
2271 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2273 atomic_dec(&dq->refcount);
2275 wake_up_process(dq->waiter);
2278 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2280 atomic_inc(&dq->refcount);
2284 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2286 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2288 nvme_clear_queue(nvmeq);
2292 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2293 kthread_work_func_t fn)
2295 struct nvme_command c;
2297 memset(&c, 0, sizeof(c));
2298 c.delete_queue.opcode = opcode;
2299 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2301 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2302 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2305 static void nvme_del_cq_work_handler(struct kthread_work *work)
2307 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2309 nvme_del_queue_end(nvmeq);
2312 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2314 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2315 nvme_del_cq_work_handler);
2318 static void nvme_del_sq_work_handler(struct kthread_work *work)
2320 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2322 int status = nvmeq->cmdinfo.status;
2325 status = nvme_delete_cq(nvmeq);
2327 nvme_del_queue_end(nvmeq);
2330 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2332 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2333 nvme_del_sq_work_handler);
2336 static void nvme_del_queue_start(struct kthread_work *work)
2338 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2340 allow_signal(SIGKILL);
2341 if (nvme_delete_sq(nvmeq))
2342 nvme_del_queue_end(nvmeq);
2345 static void nvme_disable_io_queues(struct nvme_dev *dev)
2348 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2349 struct nvme_delq_ctx dq;
2350 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2351 &worker, "nvme%d", dev->instance);
2353 if (IS_ERR(kworker_task)) {
2354 dev_err(&dev->pci_dev->dev,
2355 "Failed to create queue del task\n");
2356 for (i = dev->queue_count - 1; i > 0; i--)
2357 nvme_disable_queue(dev, i);
2362 atomic_set(&dq.refcount, 0);
2363 dq.worker = &worker;
2364 for (i = dev->queue_count - 1; i > 0; i--) {
2365 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2367 if (nvme_suspend_queue(nvmeq))
2369 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2370 nvmeq->cmdinfo.worker = dq.worker;
2371 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2372 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2374 nvme_wait_dq(&dq, dev);
2375 kthread_stop(kworker_task);
2379 * Remove the node from the device list and check
2380 * for whether or not we need to stop the nvme_thread.
2382 static void nvme_dev_list_remove(struct nvme_dev *dev)
2384 struct task_struct *tmp = NULL;
2386 spin_lock(&dev_list_lock);
2387 list_del_init(&dev->node);
2388 if (list_empty(&dev_list) && !IS_ERR_OR_NULL(nvme_thread)) {
2392 spin_unlock(&dev_list_lock);
2398 static void nvme_dev_shutdown(struct nvme_dev *dev)
2402 dev->initialized = 0;
2403 unregister_hotcpu_notifier(&dev->nb);
2405 nvme_dev_list_remove(dev);
2407 if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2408 for (i = dev->queue_count - 1; i >= 0; i--) {
2409 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2410 nvme_suspend_queue(nvmeq);
2411 nvme_clear_queue(nvmeq);
2414 nvme_disable_io_queues(dev);
2415 nvme_shutdown_ctrl(dev);
2416 nvme_disable_queue(dev, 0);
2418 nvme_dev_unmap(dev);
2421 static void nvme_dev_remove(struct nvme_dev *dev)
2425 list_for_each_entry(ns, &dev->namespaces, list) {
2426 if (ns->disk->flags & GENHD_FL_UP)
2427 del_gendisk(ns->disk);
2428 if (!blk_queue_dying(ns->queue))
2429 blk_cleanup_queue(ns->queue);
2433 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2435 struct device *dmadev = &dev->pci_dev->dev;
2436 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2437 PAGE_SIZE, PAGE_SIZE, 0);
2438 if (!dev->prp_page_pool)
2441 /* Optimisation for I/Os between 4k and 128k */
2442 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2444 if (!dev->prp_small_pool) {
2445 dma_pool_destroy(dev->prp_page_pool);
2451 static void nvme_release_prp_pools(struct nvme_dev *dev)
2453 dma_pool_destroy(dev->prp_page_pool);
2454 dma_pool_destroy(dev->prp_small_pool);
2457 static DEFINE_IDA(nvme_instance_ida);
2459 static int nvme_set_instance(struct nvme_dev *dev)
2461 int instance, error;
2464 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2467 spin_lock(&dev_list_lock);
2468 error = ida_get_new(&nvme_instance_ida, &instance);
2469 spin_unlock(&dev_list_lock);
2470 } while (error == -EAGAIN);
2475 dev->instance = instance;
2479 static void nvme_release_instance(struct nvme_dev *dev)
2481 spin_lock(&dev_list_lock);
2482 ida_remove(&nvme_instance_ida, dev->instance);
2483 spin_unlock(&dev_list_lock);
2486 static void nvme_free_namespaces(struct nvme_dev *dev)
2488 struct nvme_ns *ns, *next;
2490 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2491 list_del(&ns->list);
2497 static void nvme_free_dev(struct kref *kref)
2499 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2501 nvme_free_namespaces(dev);
2502 free_percpu(dev->io_queue);
2508 static int nvme_dev_open(struct inode *inode, struct file *f)
2510 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2512 kref_get(&dev->kref);
2513 f->private_data = dev;
2517 static int nvme_dev_release(struct inode *inode, struct file *f)
2519 struct nvme_dev *dev = f->private_data;
2520 kref_put(&dev->kref, nvme_free_dev);
2524 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2526 struct nvme_dev *dev = f->private_data;
2528 case NVME_IOCTL_ADMIN_CMD:
2529 return nvme_user_admin_cmd(dev, (void __user *)arg);
2535 static const struct file_operations nvme_dev_fops = {
2536 .owner = THIS_MODULE,
2537 .open = nvme_dev_open,
2538 .release = nvme_dev_release,
2539 .unlocked_ioctl = nvme_dev_ioctl,
2540 .compat_ioctl = nvme_dev_ioctl,
2543 static int nvme_dev_start(struct nvme_dev *dev)
2546 bool start_thread = false;
2548 result = nvme_dev_map(dev);
2552 result = nvme_configure_admin_queue(dev);
2556 spin_lock(&dev_list_lock);
2557 if (list_empty(&dev_list) && IS_ERR_OR_NULL(nvme_thread)) {
2558 start_thread = true;
2561 list_add(&dev->node, &dev_list);
2562 spin_unlock(&dev_list_lock);
2565 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2566 wake_up(&nvme_kthread_wait);
2568 wait_event_killable(nvme_kthread_wait, nvme_thread);
2570 if (IS_ERR_OR_NULL(nvme_thread)) {
2571 result = nvme_thread ? PTR_ERR(nvme_thread) : -EINTR;
2575 result = nvme_setup_io_queues(dev);
2576 if (result && result != -EBUSY)
2582 nvme_disable_queue(dev, 0);
2583 nvme_dev_list_remove(dev);
2585 nvme_dev_unmap(dev);
2589 static int nvme_remove_dead_ctrl(void *arg)
2591 struct nvme_dev *dev = (struct nvme_dev *)arg;
2592 struct pci_dev *pdev = dev->pci_dev;
2594 if (pci_get_drvdata(pdev))
2595 pci_stop_and_remove_bus_device(pdev);
2596 kref_put(&dev->kref, nvme_free_dev);
2600 static void nvme_remove_disks(struct work_struct *ws)
2602 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2604 nvme_dev_remove(dev);
2605 nvme_free_queues(dev, 1);
2608 static int nvme_dev_resume(struct nvme_dev *dev)
2612 ret = nvme_dev_start(dev);
2613 if (ret && ret != -EBUSY)
2615 if (ret == -EBUSY) {
2616 spin_lock(&dev_list_lock);
2617 PREPARE_WORK(&dev->reset_work, nvme_remove_disks);
2618 queue_work(nvme_workq, &dev->reset_work);
2619 spin_unlock(&dev_list_lock);
2621 dev->initialized = 1;
2625 static void nvme_dev_reset(struct nvme_dev *dev)
2627 nvme_dev_shutdown(dev);
2628 if (nvme_dev_resume(dev)) {
2629 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2630 kref_get(&dev->kref);
2631 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2633 dev_err(&dev->pci_dev->dev,
2634 "Failed to start controller remove task\n");
2635 kref_put(&dev->kref, nvme_free_dev);
2640 static void nvme_reset_failed_dev(struct work_struct *ws)
2642 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2643 nvme_dev_reset(dev);
2646 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2648 int result = -ENOMEM;
2649 struct nvme_dev *dev;
2651 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2654 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2658 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2662 dev->io_queue = alloc_percpu(unsigned short);
2666 INIT_LIST_HEAD(&dev->namespaces);
2667 INIT_WORK(&dev->reset_work, nvme_reset_failed_dev);
2668 dev->pci_dev = pdev;
2669 pci_set_drvdata(pdev, dev);
2670 result = nvme_set_instance(dev);
2674 result = nvme_setup_prp_pools(dev);
2678 kref_init(&dev->kref);
2679 result = nvme_dev_start(dev);
2681 if (result == -EBUSY)
2686 result = nvme_dev_add(dev);
2691 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2692 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2693 dev->miscdev.parent = &pdev->dev;
2694 dev->miscdev.name = dev->name;
2695 dev->miscdev.fops = &nvme_dev_fops;
2696 result = misc_register(&dev->miscdev);
2700 dev->initialized = 1;
2704 nvme_dev_remove(dev);
2705 nvme_free_namespaces(dev);
2707 nvme_dev_shutdown(dev);
2709 nvme_free_queues(dev, 0);
2710 nvme_release_prp_pools(dev);
2712 nvme_release_instance(dev);
2714 free_percpu(dev->io_queue);
2721 static void nvme_shutdown(struct pci_dev *pdev)
2723 struct nvme_dev *dev = pci_get_drvdata(pdev);
2724 nvme_dev_shutdown(dev);
2727 static void nvme_remove(struct pci_dev *pdev)
2729 struct nvme_dev *dev = pci_get_drvdata(pdev);
2731 spin_lock(&dev_list_lock);
2732 list_del_init(&dev->node);
2733 spin_unlock(&dev_list_lock);
2735 pci_set_drvdata(pdev, NULL);
2736 flush_work(&dev->reset_work);
2737 misc_deregister(&dev->miscdev);
2738 nvme_dev_remove(dev);
2739 nvme_dev_shutdown(dev);
2740 nvme_free_queues(dev, 0);
2742 nvme_release_instance(dev);
2743 nvme_release_prp_pools(dev);
2744 kref_put(&dev->kref, nvme_free_dev);
2747 /* These functions are yet to be implemented */
2748 #define nvme_error_detected NULL
2749 #define nvme_dump_registers NULL
2750 #define nvme_link_reset NULL
2751 #define nvme_slot_reset NULL
2752 #define nvme_error_resume NULL
2754 #ifdef CONFIG_PM_SLEEP
2755 static int nvme_suspend(struct device *dev)
2757 struct pci_dev *pdev = to_pci_dev(dev);
2758 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2760 nvme_dev_shutdown(ndev);
2764 static int nvme_resume(struct device *dev)
2766 struct pci_dev *pdev = to_pci_dev(dev);
2767 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2769 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2770 PREPARE_WORK(&ndev->reset_work, nvme_reset_failed_dev);
2771 queue_work(nvme_workq, &ndev->reset_work);
2777 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2779 static const struct pci_error_handlers nvme_err_handler = {
2780 .error_detected = nvme_error_detected,
2781 .mmio_enabled = nvme_dump_registers,
2782 .link_reset = nvme_link_reset,
2783 .slot_reset = nvme_slot_reset,
2784 .resume = nvme_error_resume,
2787 /* Move to pci_ids.h later */
2788 #define PCI_CLASS_STORAGE_EXPRESS 0x010802
2790 static const struct pci_device_id nvme_id_table[] = {
2791 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2794 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2796 static struct pci_driver nvme_driver = {
2798 .id_table = nvme_id_table,
2799 .probe = nvme_probe,
2800 .remove = nvme_remove,
2801 .shutdown = nvme_shutdown,
2803 .pm = &nvme_dev_pm_ops,
2805 .err_handler = &nvme_err_handler,
2808 static int __init nvme_init(void)
2812 init_waitqueue_head(&nvme_kthread_wait);
2814 nvme_workq = create_singlethread_workqueue("nvme");
2818 result = register_blkdev(nvme_major, "nvme");
2821 else if (result > 0)
2822 nvme_major = result;
2824 result = pci_register_driver(&nvme_driver);
2826 goto unregister_blkdev;
2830 unregister_blkdev(nvme_major, "nvme");
2832 destroy_workqueue(nvme_workq);
2836 static void __exit nvme_exit(void)
2838 pci_unregister_driver(&nvme_driver);
2839 unregister_blkdev(nvme_major, "nvme");
2840 destroy_workqueue(nvme_workq);
2841 BUG_ON(nvme_thread && !IS_ERR(nvme_thread));
2844 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2845 MODULE_LICENSE("GPL");
2846 MODULE_VERSION("0.9");
2847 module_init(nvme_init);
2848 module_exit(nvme_exit);