2 * NVM Express device driver
3 * Copyright (c) 2011-2014, Intel Corporation.
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms and conditions of the GNU General Public License,
7 * version 2, as published by the Free Software Foundation.
9 * This program is distributed in the hope it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
15 #include <linux/nvme.h>
16 #include <linux/bio.h>
17 #include <linux/bitops.h>
18 #include <linux/blkdev.h>
19 #include <linux/cpu.h>
20 #include <linux/delay.h>
21 #include <linux/errno.h>
23 #include <linux/genhd.h>
24 #include <linux/hdreg.h>
25 #include <linux/idr.h>
26 #include <linux/init.h>
27 #include <linux/interrupt.h>
29 #include <linux/kdev_t.h>
30 #include <linux/kthread.h>
31 #include <linux/kernel.h>
33 #include <linux/module.h>
34 #include <linux/moduleparam.h>
35 #include <linux/pci.h>
36 #include <linux/percpu.h>
37 #include <linux/poison.h>
38 #include <linux/ptrace.h>
39 #include <linux/sched.h>
40 #include <linux/slab.h>
41 #include <linux/types.h>
43 #include <asm-generic/io-64-nonatomic-lo-hi.h>
45 #include <trace/events/block.h>
47 #define NVME_Q_DEPTH 1024
48 #define SQ_SIZE(depth) (depth * sizeof(struct nvme_command))
49 #define CQ_SIZE(depth) (depth * sizeof(struct nvme_completion))
50 #define ADMIN_TIMEOUT (admin_timeout * HZ)
51 #define IOD_TIMEOUT (retry_time * HZ)
53 static unsigned char admin_timeout = 60;
54 module_param(admin_timeout, byte, 0644);
55 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
57 unsigned char nvme_io_timeout = 30;
58 module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
59 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
61 static unsigned char retry_time = 30;
62 module_param(retry_time, byte, 0644);
63 MODULE_PARM_DESC(retry_time, "time in seconds to retry failed I/O");
65 static int nvme_major;
66 module_param(nvme_major, int, 0);
68 static int use_threaded_interrupts;
69 module_param(use_threaded_interrupts, int, 0);
71 static DEFINE_SPINLOCK(dev_list_lock);
72 static LIST_HEAD(dev_list);
73 static struct task_struct *nvme_thread;
74 static struct workqueue_struct *nvme_workq;
75 static wait_queue_head_t nvme_kthread_wait;
76 static struct notifier_block nvme_nb;
78 static void nvme_reset_failed_dev(struct work_struct *ws);
80 struct async_cmd_info {
81 struct kthread_work work;
82 struct kthread_worker *worker;
89 * An NVM Express queue. Each device has at least two (one for admin
90 * commands and one for I/O commands).
93 struct rcu_head r_head;
94 struct device *q_dmadev;
96 char irqname[24]; /* nvme4294967295-65535\0 */
98 struct nvme_command *sq_cmds;
99 volatile struct nvme_completion *cqes;
100 dma_addr_t sq_dma_addr;
101 dma_addr_t cq_dma_addr;
102 wait_queue_head_t sq_full;
103 wait_queue_t sq_cong_wait;
104 struct bio_list sq_cong;
105 struct list_head iod_bio;
116 cpumask_var_t cpu_mask;
117 struct async_cmd_info cmdinfo;
118 unsigned long cmdid_data[];
122 * Check we didin't inadvertently grow the command struct
124 static inline void _nvme_check_size(void)
126 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
127 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
128 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
129 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
130 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
131 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
132 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
133 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
134 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
135 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
136 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
137 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
140 typedef void (*nvme_completion_fn)(struct nvme_queue *, void *,
141 struct nvme_completion *);
143 struct nvme_cmd_info {
144 nvme_completion_fn fn;
146 unsigned long timeout;
150 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
152 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
155 static unsigned nvme_queue_extra(int depth)
157 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
161 * alloc_cmdid() - Allocate a Command ID
162 * @nvmeq: The queue that will be used for this command
163 * @ctx: A pointer that will be passed to the handler
164 * @handler: The function to call on completion
166 * Allocate a Command ID for a queue. The data passed in will
167 * be passed to the completion handler. This is implemented by using
168 * the bottom two bits of the ctx pointer to store the handler ID.
169 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
170 * We can change this if it becomes a problem.
172 * May be called with local interrupts disabled and the q_lock held,
173 * or with interrupts enabled and no locks held.
175 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
176 nvme_completion_fn handler, unsigned timeout)
178 int depth = nvmeq->q_depth - 1;
179 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
183 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
186 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
188 info[cmdid].fn = handler;
189 info[cmdid].ctx = ctx;
190 info[cmdid].timeout = jiffies + timeout;
191 info[cmdid].aborted = 0;
195 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
196 nvme_completion_fn handler, unsigned timeout)
199 wait_event_killable(nvmeq->sq_full,
200 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
201 return (cmdid < 0) ? -EINTR : cmdid;
204 /* Special values must be less than 0x1000 */
205 #define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
206 #define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
207 #define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
208 #define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
209 #define CMD_CTX_ABORT (0x318 + CMD_CTX_BASE)
210 #define CMD_CTX_ASYNC (0x31C + CMD_CTX_BASE)
212 static void special_completion(struct nvme_queue *nvmeq, void *ctx,
213 struct nvme_completion *cqe)
215 if (ctx == CMD_CTX_CANCELLED)
217 if (ctx == CMD_CTX_ABORT) {
218 ++nvmeq->dev->abort_limit;
221 if (ctx == CMD_CTX_COMPLETED) {
222 dev_warn(nvmeq->q_dmadev,
223 "completed id %d twice on queue %d\n",
224 cqe->command_id, le16_to_cpup(&cqe->sq_id));
227 if (ctx == CMD_CTX_INVALID) {
228 dev_warn(nvmeq->q_dmadev,
229 "invalid id %d completed on queue %d\n",
230 cqe->command_id, le16_to_cpup(&cqe->sq_id));
233 if (ctx == CMD_CTX_ASYNC) {
234 u32 result = le32_to_cpup(&cqe->result);
235 u16 status = le16_to_cpup(&cqe->status) >> 1;
237 if (status == NVME_SC_SUCCESS || status == NVME_SC_ABORT_REQ)
238 ++nvmeq->dev->event_limit;
239 if (status == NVME_SC_SUCCESS)
240 dev_warn(nvmeq->q_dmadev,
241 "async event result %08x\n", result);
245 dev_warn(nvmeq->q_dmadev, "Unknown special completion %p\n", ctx);
248 static void async_completion(struct nvme_queue *nvmeq, void *ctx,
249 struct nvme_completion *cqe)
251 struct async_cmd_info *cmdinfo = ctx;
252 cmdinfo->result = le32_to_cpup(&cqe->result);
253 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
254 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
258 * Called with local interrupts disabled and the q_lock held. May not sleep.
260 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
261 nvme_completion_fn *fn)
264 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
266 if (cmdid >= nvmeq->q_depth || !info[cmdid].fn) {
268 *fn = special_completion;
269 return CMD_CTX_INVALID;
272 *fn = info[cmdid].fn;
273 ctx = info[cmdid].ctx;
274 info[cmdid].fn = special_completion;
275 info[cmdid].ctx = CMD_CTX_COMPLETED;
276 clear_bit(cmdid, nvmeq->cmdid_data);
277 wake_up(&nvmeq->sq_full);
281 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
282 nvme_completion_fn *fn)
285 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
287 *fn = info[cmdid].fn;
288 ctx = info[cmdid].ctx;
289 info[cmdid].fn = special_completion;
290 info[cmdid].ctx = CMD_CTX_CANCELLED;
294 static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
296 return rcu_dereference_raw(dev->queues[qid]);
299 static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
301 struct nvme_queue *nvmeq;
302 unsigned queue_id = get_cpu_var(*dev->io_queue);
305 nvmeq = rcu_dereference(dev->queues[queue_id]);
310 put_cpu_var(*dev->io_queue);
314 static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
317 put_cpu_var(nvmeq->dev->io_queue);
320 static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
323 struct nvme_queue *nvmeq;
326 nvmeq = rcu_dereference(dev->queues[q_idx]);
334 static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
340 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
341 * @nvmeq: The queue to use
342 * @cmd: The command to send
344 * Safe to use from interrupt context
346 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
350 spin_lock_irqsave(&nvmeq->q_lock, flags);
351 if (nvmeq->q_suspended) {
352 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
355 tail = nvmeq->sq_tail;
356 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
357 if (++tail == nvmeq->q_depth)
359 writel(tail, nvmeq->q_db);
360 nvmeq->sq_tail = tail;
361 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
366 static __le64 **iod_list(struct nvme_iod *iod)
368 return ((void *)iod) + iod->offset;
372 * Will slightly overestimate the number of pages needed. This is OK
373 * as it only leads to a small amount of wasted memory for the lifetime of
376 static int nvme_npages(unsigned size, struct nvme_dev *dev)
378 unsigned nprps = DIV_ROUND_UP(size + dev->page_size, dev->page_size);
379 return DIV_ROUND_UP(8 * nprps, dev->page_size - 8);
382 static struct nvme_iod *
383 nvme_alloc_iod(unsigned nseg, unsigned nbytes, struct nvme_dev *dev, gfp_t gfp)
385 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
386 sizeof(__le64 *) * nvme_npages(nbytes, dev) +
387 sizeof(struct scatterlist) * nseg, gfp);
390 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
392 iod->length = nbytes;
394 iod->first_dma = 0ULL;
395 iod->start_time = jiffies;
401 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
403 const int last_prp = dev->page_size / 8 - 1;
405 __le64 **list = iod_list(iod);
406 dma_addr_t prp_dma = iod->first_dma;
408 if (iod->npages == 0)
409 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
410 for (i = 0; i < iod->npages; i++) {
411 __le64 *prp_list = list[i];
412 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
413 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
414 prp_dma = next_prp_dma;
419 static void nvme_start_io_acct(struct bio *bio)
421 struct gendisk *disk = bio->bi_bdev->bd_disk;
422 if (blk_queue_io_stat(disk->queue)) {
423 const int rw = bio_data_dir(bio);
424 int cpu = part_stat_lock();
425 part_round_stats(cpu, &disk->part0);
426 part_stat_inc(cpu, &disk->part0, ios[rw]);
427 part_stat_add(cpu, &disk->part0, sectors[rw],
429 part_inc_in_flight(&disk->part0, rw);
434 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
436 struct gendisk *disk = bio->bi_bdev->bd_disk;
437 if (blk_queue_io_stat(disk->queue)) {
438 const int rw = bio_data_dir(bio);
439 unsigned long duration = jiffies - start_time;
440 int cpu = part_stat_lock();
441 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
442 part_round_stats(cpu, &disk->part0);
443 part_dec_in_flight(&disk->part0, rw);
448 static void bio_completion(struct nvme_queue *nvmeq, void *ctx,
449 struct nvme_completion *cqe)
451 struct nvme_iod *iod = ctx;
452 struct bio *bio = iod->private;
453 u16 status = le16_to_cpup(&cqe->status) >> 1;
456 if (unlikely(status)) {
457 if (!(status & NVME_SC_DNR ||
458 bio->bi_rw & REQ_FAILFAST_MASK) &&
459 (jiffies - iod->start_time) < IOD_TIMEOUT) {
460 if (!waitqueue_active(&nvmeq->sq_full))
461 add_wait_queue(&nvmeq->sq_full,
462 &nvmeq->sq_cong_wait);
463 list_add_tail(&iod->node, &nvmeq->iod_bio);
464 wake_up(&nvmeq->sq_full);
470 dma_unmap_sg(nvmeq->q_dmadev, iod->sg, iod->nents,
471 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
472 nvme_end_io_acct(bio, iod->start_time);
474 nvme_free_iod(nvmeq->dev, iod);
476 trace_block_bio_complete(bdev_get_queue(bio->bi_bdev), bio, error);
477 bio_endio(bio, error);
480 /* length is in bytes. gfp flags indicates whether we may sleep. */
481 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_iod *iod, int total_len,
484 struct dma_pool *pool;
485 int length = total_len;
486 struct scatterlist *sg = iod->sg;
487 int dma_len = sg_dma_len(sg);
488 u64 dma_addr = sg_dma_address(sg);
489 int offset = offset_in_page(dma_addr);
491 __le64 **list = iod_list(iod);
494 u32 page_size = dev->page_size;
496 length -= (page_size - offset);
500 dma_len -= (page_size - offset);
502 dma_addr += (page_size - offset);
505 dma_addr = sg_dma_address(sg);
506 dma_len = sg_dma_len(sg);
509 if (length <= page_size) {
510 iod->first_dma = dma_addr;
514 nprps = DIV_ROUND_UP(length, page_size);
515 if (nprps <= (256 / 8)) {
516 pool = dev->prp_small_pool;
519 pool = dev->prp_page_pool;
523 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
525 iod->first_dma = dma_addr;
527 return (total_len - length) + page_size;
530 iod->first_dma = prp_dma;
533 if (i == page_size >> 3) {
534 __le64 *old_prp_list = prp_list;
535 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
537 return total_len - length;
538 list[iod->npages++] = prp_list;
539 prp_list[0] = old_prp_list[i - 1];
540 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
543 prp_list[i++] = cpu_to_le64(dma_addr);
544 dma_len -= page_size;
545 dma_addr += page_size;
553 dma_addr = sg_dma_address(sg);
554 dma_len = sg_dma_len(sg);
560 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
563 struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
567 trace_block_split(bdev_get_queue(bio->bi_bdev), bio,
568 split->bi_iter.bi_sector);
569 bio_chain(split, bio);
571 if (!waitqueue_active(&nvmeq->sq_full))
572 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
573 bio_list_add(&nvmeq->sq_cong, split);
574 bio_list_add(&nvmeq->sq_cong, bio);
575 wake_up(&nvmeq->sq_full);
580 /* NVMe scatterlists require no holes in the virtual address */
581 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
582 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
584 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
585 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
587 struct bio_vec bvec, bvprv;
588 struct bvec_iter iter;
589 struct scatterlist *sg = NULL;
590 int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
593 if (nvmeq->dev->stripe_size)
594 split_len = nvmeq->dev->stripe_size -
595 ((bio->bi_iter.bi_sector << 9) &
596 (nvmeq->dev->stripe_size - 1));
598 sg_init_table(iod->sg, psegs);
599 bio_for_each_segment(bvec, bio, iter) {
600 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
601 sg->length += bvec.bv_len;
603 if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
604 return nvme_split_and_submit(bio, nvmeq,
607 sg = sg ? sg + 1 : iod->sg;
608 sg_set_page(sg, bvec.bv_page,
609 bvec.bv_len, bvec.bv_offset);
613 if (split_len - length < bvec.bv_len)
614 return nvme_split_and_submit(bio, nvmeq, split_len);
615 length += bvec.bv_len;
621 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
624 BUG_ON(length != bio->bi_iter.bi_size);
628 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
629 struct bio *bio, struct nvme_iod *iod, int cmdid)
631 struct nvme_dsm_range *range =
632 (struct nvme_dsm_range *)iod_list(iod)[0];
633 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
635 range->cattr = cpu_to_le32(0);
636 range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
637 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
639 memset(cmnd, 0, sizeof(*cmnd));
640 cmnd->dsm.opcode = nvme_cmd_dsm;
641 cmnd->dsm.command_id = cmdid;
642 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
643 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
645 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
647 if (++nvmeq->sq_tail == nvmeq->q_depth)
649 writel(nvmeq->sq_tail, nvmeq->q_db);
654 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
657 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
659 memset(cmnd, 0, sizeof(*cmnd));
660 cmnd->common.opcode = nvme_cmd_flush;
661 cmnd->common.command_id = cmdid;
662 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
664 if (++nvmeq->sq_tail == nvmeq->q_depth)
666 writel(nvmeq->sq_tail, nvmeq->q_db);
671 static int nvme_submit_iod(struct nvme_queue *nvmeq, struct nvme_iod *iod)
673 struct bio *bio = iod->private;
674 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
675 struct nvme_command *cmnd;
680 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
681 if (unlikely(cmdid < 0))
684 if (bio->bi_rw & REQ_DISCARD)
685 return nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
686 if (bio->bi_rw & REQ_FLUSH)
687 return nvme_submit_flush(nvmeq, ns, cmdid);
690 if (bio->bi_rw & REQ_FUA)
691 control |= NVME_RW_FUA;
692 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
693 control |= NVME_RW_LR;
696 if (bio->bi_rw & REQ_RAHEAD)
697 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
699 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
700 memset(cmnd, 0, sizeof(*cmnd));
702 cmnd->rw.opcode = bio_data_dir(bio) ? nvme_cmd_write : nvme_cmd_read;
703 cmnd->rw.command_id = cmdid;
704 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
705 cmnd->rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
706 cmnd->rw.prp2 = cpu_to_le64(iod->first_dma);
707 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
709 cpu_to_le16((bio->bi_iter.bi_size >> ns->lba_shift) - 1);
710 cmnd->rw.control = cpu_to_le16(control);
711 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
713 if (++nvmeq->sq_tail == nvmeq->q_depth)
715 writel(nvmeq->sq_tail, nvmeq->q_db);
720 static int nvme_split_flush_data(struct nvme_queue *nvmeq, struct bio *bio)
722 struct bio *split = bio_clone(bio, GFP_ATOMIC);
726 split->bi_iter.bi_size = 0;
727 split->bi_phys_segments = 0;
728 bio->bi_rw &= ~REQ_FLUSH;
729 bio_chain(split, bio);
731 if (!waitqueue_active(&nvmeq->sq_full))
732 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
733 bio_list_add(&nvmeq->sq_cong, split);
734 bio_list_add(&nvmeq->sq_cong, bio);
735 wake_up_process(nvme_thread);
741 * Called with local interrupts disabled and the q_lock held. May not sleep.
743 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
746 struct nvme_iod *iod;
747 int psegs = bio_phys_segments(ns->queue, bio);
750 if ((bio->bi_rw & REQ_FLUSH) && psegs)
751 return nvme_split_flush_data(nvmeq, bio);
753 iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, ns->dev, GFP_ATOMIC);
758 if (bio->bi_rw & REQ_DISCARD) {
761 * We reuse the small pool to allocate the 16-byte range here
762 * as it is not worth having a special pool for these or
763 * additional cases to handle freeing the iod.
765 range = dma_pool_alloc(nvmeq->dev->prp_small_pool,
772 iod_list(iod)[0] = (__le64 *)range;
775 result = nvme_map_bio(nvmeq, iod, bio,
776 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE,
780 if (nvme_setup_prps(nvmeq->dev, iod, result, GFP_ATOMIC) !=
785 nvme_start_io_acct(bio);
787 if (unlikely(nvme_submit_iod(nvmeq, iod))) {
788 if (!waitqueue_active(&nvmeq->sq_full))
789 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
790 list_add_tail(&iod->node, &nvmeq->iod_bio);
795 nvme_free_iod(nvmeq->dev, iod);
799 static int nvme_process_cq(struct nvme_queue *nvmeq)
803 head = nvmeq->cq_head;
804 phase = nvmeq->cq_phase;
808 nvme_completion_fn fn;
809 struct nvme_completion cqe = nvmeq->cqes[head];
810 if ((le16_to_cpu(cqe.status) & 1) != phase)
812 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
813 if (++head == nvmeq->q_depth) {
818 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
819 fn(nvmeq, ctx, &cqe);
822 /* If the controller ignores the cq head doorbell and continuously
823 * writes to the queue, it is theoretically possible to wrap around
824 * the queue twice and mistakenly return IRQ_NONE. Linux only
825 * requires that 0.1% of your interrupts are handled, so this isn't
828 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
831 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
832 nvmeq->cq_head = head;
833 nvmeq->cq_phase = phase;
839 static void nvme_make_request(struct request_queue *q, struct bio *bio)
841 struct nvme_ns *ns = q->queuedata;
842 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
846 bio_endio(bio, -EIO);
850 spin_lock_irq(&nvmeq->q_lock);
851 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
852 result = nvme_submit_bio_queue(nvmeq, ns, bio);
853 if (unlikely(result)) {
854 if (!waitqueue_active(&nvmeq->sq_full))
855 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
856 bio_list_add(&nvmeq->sq_cong, bio);
859 nvme_process_cq(nvmeq);
860 spin_unlock_irq(&nvmeq->q_lock);
864 static irqreturn_t nvme_irq(int irq, void *data)
867 struct nvme_queue *nvmeq = data;
868 spin_lock(&nvmeq->q_lock);
869 nvme_process_cq(nvmeq);
870 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
872 spin_unlock(&nvmeq->q_lock);
876 static irqreturn_t nvme_irq_check(int irq, void *data)
878 struct nvme_queue *nvmeq = data;
879 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
880 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
882 return IRQ_WAKE_THREAD;
885 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
887 spin_lock_irq(&nvmeq->q_lock);
888 cancel_cmdid(nvmeq, cmdid, NULL);
889 spin_unlock_irq(&nvmeq->q_lock);
892 struct sync_cmd_info {
893 struct task_struct *task;
898 static void sync_completion(struct nvme_queue *nvmeq, void *ctx,
899 struct nvme_completion *cqe)
901 struct sync_cmd_info *cmdinfo = ctx;
902 cmdinfo->result = le32_to_cpup(&cqe->result);
903 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
904 wake_up_process(cmdinfo->task);
908 * Returns 0 on success. If the result is negative, it's a Linux error code;
909 * if the result is positive, it's an NVM Express status code
911 static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
912 struct nvme_command *cmd,
913 u32 *result, unsigned timeout)
916 struct sync_cmd_info cmdinfo;
917 struct nvme_queue *nvmeq;
919 nvmeq = lock_nvmeq(dev, q_idx);
923 cmdinfo.task = current;
924 cmdinfo.status = -EINTR;
926 cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
931 cmd->common.command_id = cmdid;
933 set_current_state(TASK_KILLABLE);
934 ret = nvme_submit_cmd(nvmeq, cmd);
936 free_cmdid(nvmeq, cmdid, NULL);
938 set_current_state(TASK_RUNNING);
942 schedule_timeout(timeout);
944 if (cmdinfo.status == -EINTR) {
945 nvmeq = lock_nvmeq(dev, q_idx);
947 nvme_abort_command(nvmeq, cmdid);
954 *result = cmdinfo.result;
956 return cmdinfo.status;
959 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
960 struct nvme_command *cmd,
961 struct async_cmd_info *cmdinfo, unsigned timeout)
965 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
968 cmdinfo->status = -EINTR;
969 cmd->common.command_id = cmdid;
970 return nvme_submit_cmd(nvmeq, cmd);
973 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
976 return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
979 int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
982 return nvme_submit_sync_cmd(dev, smp_processor_id() + 1, cmd, result,
986 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
987 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
989 return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
993 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
996 struct nvme_command c;
998 memset(&c, 0, sizeof(c));
999 c.delete_queue.opcode = opcode;
1000 c.delete_queue.qid = cpu_to_le16(id);
1002 status = nvme_submit_admin_cmd(dev, &c, NULL);
1008 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
1009 struct nvme_queue *nvmeq)
1012 struct nvme_command c;
1013 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
1015 memset(&c, 0, sizeof(c));
1016 c.create_cq.opcode = nvme_admin_create_cq;
1017 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1018 c.create_cq.cqid = cpu_to_le16(qid);
1019 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1020 c.create_cq.cq_flags = cpu_to_le16(flags);
1021 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
1023 status = nvme_submit_admin_cmd(dev, &c, NULL);
1029 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1030 struct nvme_queue *nvmeq)
1033 struct nvme_command c;
1034 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
1036 memset(&c, 0, sizeof(c));
1037 c.create_sq.opcode = nvme_admin_create_sq;
1038 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1039 c.create_sq.sqid = cpu_to_le16(qid);
1040 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1041 c.create_sq.sq_flags = cpu_to_le16(flags);
1042 c.create_sq.cqid = cpu_to_le16(qid);
1044 status = nvme_submit_admin_cmd(dev, &c, NULL);
1050 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1052 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1055 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1057 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1060 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
1061 dma_addr_t dma_addr)
1063 struct nvme_command c;
1065 memset(&c, 0, sizeof(c));
1066 c.identify.opcode = nvme_admin_identify;
1067 c.identify.nsid = cpu_to_le32(nsid);
1068 c.identify.prp1 = cpu_to_le64(dma_addr);
1069 c.identify.cns = cpu_to_le32(cns);
1071 return nvme_submit_admin_cmd(dev, &c, NULL);
1074 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
1075 dma_addr_t dma_addr, u32 *result)
1077 struct nvme_command c;
1079 memset(&c, 0, sizeof(c));
1080 c.features.opcode = nvme_admin_get_features;
1081 c.features.nsid = cpu_to_le32(nsid);
1082 c.features.prp1 = cpu_to_le64(dma_addr);
1083 c.features.fid = cpu_to_le32(fid);
1085 return nvme_submit_admin_cmd(dev, &c, result);
1088 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1089 dma_addr_t dma_addr, u32 *result)
1091 struct nvme_command c;
1093 memset(&c, 0, sizeof(c));
1094 c.features.opcode = nvme_admin_set_features;
1095 c.features.prp1 = cpu_to_le64(dma_addr);
1096 c.features.fid = cpu_to_le32(fid);
1097 c.features.dword11 = cpu_to_le32(dword11);
1099 return nvme_submit_admin_cmd(dev, &c, result);
1103 * nvme_abort_cmd - Attempt aborting a command
1104 * @cmdid: Command id of a timed out IO
1105 * @queue: The queue with timed out IO
1107 * Schedule controller reset if the command was already aborted once before and
1108 * still hasn't been returned to the driver, or if this is the admin queue.
1110 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1113 struct nvme_command cmd;
1114 struct nvme_dev *dev = nvmeq->dev;
1115 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1116 struct nvme_queue *adminq;
1118 if (!nvmeq->qid || info[cmdid].aborted) {
1119 if (work_busy(&dev->reset_work))
1121 list_del_init(&dev->node);
1122 dev_warn(&dev->pci_dev->dev,
1123 "I/O %d QID %d timeout, reset controller\n", cmdid,
1125 dev->reset_workfn = nvme_reset_failed_dev;
1126 queue_work(nvme_workq, &dev->reset_work);
1130 if (!dev->abort_limit)
1133 adminq = rcu_dereference(dev->queues[0]);
1134 a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
1139 memset(&cmd, 0, sizeof(cmd));
1140 cmd.abort.opcode = nvme_admin_abort_cmd;
1141 cmd.abort.cid = cmdid;
1142 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1143 cmd.abort.command_id = a_cmdid;
1146 info[cmdid].aborted = 1;
1147 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1149 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1151 nvme_submit_cmd(adminq, &cmd);
1155 * nvme_cancel_ios - Cancel outstanding I/Os
1156 * @queue: The queue to cancel I/Os on
1157 * @timeout: True to only cancel I/Os which have timed out
1159 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1161 int depth = nvmeq->q_depth - 1;
1162 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1163 unsigned long now = jiffies;
1166 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1168 nvme_completion_fn fn;
1169 static struct nvme_completion cqe = {
1170 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1173 if (timeout && !time_after(now, info[cmdid].timeout))
1175 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1177 if (timeout && info[cmdid].ctx == CMD_CTX_ASYNC)
1179 if (timeout && nvmeq->dev->initialized) {
1180 nvme_abort_cmd(cmdid, nvmeq);
1183 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1185 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1186 fn(nvmeq, ctx, &cqe);
1190 static void nvme_free_queue(struct rcu_head *r)
1192 struct nvme_queue *nvmeq = container_of(r, struct nvme_queue, r_head);
1194 spin_lock_irq(&nvmeq->q_lock);
1195 while (bio_list_peek(&nvmeq->sq_cong)) {
1196 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1197 bio_endio(bio, -EIO);
1199 while (!list_empty(&nvmeq->iod_bio)) {
1200 static struct nvme_completion cqe = {
1201 .status = cpu_to_le16(
1202 (NVME_SC_ABORT_REQ | NVME_SC_DNR) << 1),
1204 struct nvme_iod *iod = list_first_entry(&nvmeq->iod_bio,
1207 list_del(&iod->node);
1208 bio_completion(nvmeq, iod, &cqe);
1210 spin_unlock_irq(&nvmeq->q_lock);
1212 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1213 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1214 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1215 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1217 free_cpumask_var(nvmeq->cpu_mask);
1221 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1225 for (i = dev->queue_count - 1; i >= lowest; i--) {
1226 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
1227 rcu_assign_pointer(dev->queues[i], NULL);
1228 call_rcu(&nvmeq->r_head, nvme_free_queue);
1234 * nvme_suspend_queue - put queue into suspended state
1235 * @nvmeq - queue to suspend
1237 * Returns 1 if already suspended, 0 otherwise.
1239 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1241 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1243 spin_lock_irq(&nvmeq->q_lock);
1244 if (nvmeq->q_suspended) {
1245 spin_unlock_irq(&nvmeq->q_lock);
1248 nvmeq->q_suspended = 1;
1249 nvmeq->dev->online_queues--;
1250 spin_unlock_irq(&nvmeq->q_lock);
1252 irq_set_affinity_hint(vector, NULL);
1253 free_irq(vector, nvmeq);
1258 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1260 spin_lock_irq(&nvmeq->q_lock);
1261 nvme_process_cq(nvmeq);
1262 nvme_cancel_ios(nvmeq, false);
1263 spin_unlock_irq(&nvmeq->q_lock);
1266 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1268 struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
1272 if (nvme_suspend_queue(nvmeq))
1275 /* Don't tell the adapter to delete the admin queue.
1276 * Don't tell a removed adapter to delete IO queues. */
1277 if (qid && readl(&dev->bar->csts) != -1) {
1278 adapter_delete_sq(dev, qid);
1279 adapter_delete_cq(dev, qid);
1281 nvme_clear_queue(nvmeq);
1284 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1285 int depth, int vector)
1287 struct device *dmadev = &dev->pci_dev->dev;
1288 unsigned extra = nvme_queue_extra(depth);
1289 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1293 nvmeq->cqes = dma_zalloc_coherent(dmadev, CQ_SIZE(depth),
1294 &nvmeq->cq_dma_addr, GFP_KERNEL);
1298 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1299 &nvmeq->sq_dma_addr, GFP_KERNEL);
1300 if (!nvmeq->sq_cmds)
1303 if (qid && !zalloc_cpumask_var(&nvmeq->cpu_mask, GFP_KERNEL))
1306 nvmeq->q_dmadev = dmadev;
1308 snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1309 dev->instance, qid);
1310 spin_lock_init(&nvmeq->q_lock);
1312 nvmeq->cq_phase = 1;
1313 init_waitqueue_head(&nvmeq->sq_full);
1314 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1315 bio_list_init(&nvmeq->sq_cong);
1316 INIT_LIST_HEAD(&nvmeq->iod_bio);
1317 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1318 nvmeq->q_depth = depth;
1319 nvmeq->cq_vector = vector;
1321 nvmeq->q_suspended = 1;
1323 rcu_assign_pointer(dev->queues[qid], nvmeq);
1328 dma_free_coherent(dmadev, SQ_SIZE(depth), (void *)nvmeq->sq_cmds,
1329 nvmeq->sq_dma_addr);
1331 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1332 nvmeq->cq_dma_addr);
1338 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1341 if (use_threaded_interrupts)
1342 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1343 nvme_irq_check, nvme_irq, IRQF_SHARED,
1345 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1346 IRQF_SHARED, name, nvmeq);
1349 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1351 struct nvme_dev *dev = nvmeq->dev;
1352 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1356 nvmeq->cq_phase = 1;
1357 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1358 memset(nvmeq->cmdid_data, 0, extra);
1359 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1360 nvme_cancel_ios(nvmeq, false);
1361 nvmeq->q_suspended = 0;
1362 dev->online_queues++;
1365 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1367 struct nvme_dev *dev = nvmeq->dev;
1370 result = adapter_alloc_cq(dev, qid, nvmeq);
1374 result = adapter_alloc_sq(dev, qid, nvmeq);
1378 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1382 spin_lock_irq(&nvmeq->q_lock);
1383 nvme_init_queue(nvmeq, qid);
1384 spin_unlock_irq(&nvmeq->q_lock);
1389 adapter_delete_sq(dev, qid);
1391 adapter_delete_cq(dev, qid);
1395 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1397 unsigned long timeout;
1398 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1400 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1402 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1404 if (fatal_signal_pending(current))
1406 if (time_after(jiffies, timeout)) {
1407 dev_err(&dev->pci_dev->dev,
1408 "Device not ready; aborting %s\n", enabled ?
1409 "initialisation" : "reset");
1418 * If the device has been passed off to us in an enabled state, just clear
1419 * the enabled bit. The spec says we should set the 'shutdown notification
1420 * bits', but doing so may cause the device to complete commands to the
1421 * admin queue ... and we don't know what memory that might be pointing at!
1423 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1425 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1426 dev->ctrl_config &= ~NVME_CC_ENABLE;
1427 writel(dev->ctrl_config, &dev->bar->cc);
1429 return nvme_wait_ready(dev, cap, false);
1432 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1434 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1435 dev->ctrl_config |= NVME_CC_ENABLE;
1436 writel(dev->ctrl_config, &dev->bar->cc);
1438 return nvme_wait_ready(dev, cap, true);
1441 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1443 unsigned long timeout;
1445 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1446 dev->ctrl_config |= NVME_CC_SHN_NORMAL;
1448 writel(dev->ctrl_config, &dev->bar->cc);
1450 timeout = 2 * HZ + jiffies;
1451 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1452 NVME_CSTS_SHST_CMPLT) {
1454 if (fatal_signal_pending(current))
1456 if (time_after(jiffies, timeout)) {
1457 dev_err(&dev->pci_dev->dev,
1458 "Device shutdown incomplete; abort shutdown\n");
1466 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1470 u64 cap = readq(&dev->bar->cap);
1471 struct nvme_queue *nvmeq;
1472 unsigned page_shift = PAGE_SHIFT;
1473 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12;
1474 unsigned dev_page_max = NVME_CAP_MPSMAX(cap) + 12;
1476 if (page_shift < dev_page_min) {
1477 dev_err(&dev->pci_dev->dev,
1478 "Minimum device page size (%u) too large for "
1479 "host (%u)\n", 1 << dev_page_min,
1483 if (page_shift > dev_page_max) {
1484 dev_info(&dev->pci_dev->dev,
1485 "Device maximum page size (%u) smaller than "
1486 "host (%u); enabling work-around\n",
1487 1 << dev_page_max, 1 << page_shift);
1488 page_shift = dev_page_max;
1491 result = nvme_disable_ctrl(dev, cap);
1495 nvmeq = raw_nvmeq(dev, 0);
1497 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1502 aqa = nvmeq->q_depth - 1;
1505 dev->page_size = 1 << page_shift;
1507 dev->ctrl_config = NVME_CC_CSS_NVM;
1508 dev->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1509 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1510 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1512 writel(aqa, &dev->bar->aqa);
1513 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1514 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1516 result = nvme_enable_ctrl(dev, cap);
1520 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1524 spin_lock_irq(&nvmeq->q_lock);
1525 nvme_init_queue(nvmeq, 0);
1526 spin_unlock_irq(&nvmeq->q_lock);
1530 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1531 unsigned long addr, unsigned length)
1533 int i, err, count, nents, offset;
1534 struct scatterlist *sg;
1535 struct page **pages;
1536 struct nvme_iod *iod;
1539 return ERR_PTR(-EINVAL);
1540 if (!length || length > INT_MAX - PAGE_SIZE)
1541 return ERR_PTR(-EINVAL);
1543 offset = offset_in_page(addr);
1544 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1545 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1547 return ERR_PTR(-ENOMEM);
1549 err = get_user_pages_fast(addr, count, 1, pages);
1557 iod = nvme_alloc_iod(count, length, dev, GFP_KERNEL);
1562 sg_init_table(sg, count);
1563 for (i = 0; i < count; i++) {
1564 sg_set_page(&sg[i], pages[i],
1565 min_t(unsigned, length, PAGE_SIZE - offset),
1567 length -= (PAGE_SIZE - offset);
1570 sg_mark_end(&sg[i - 1]);
1573 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1574 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1584 for (i = 0; i < count; i++)
1587 return ERR_PTR(err);
1590 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1591 struct nvme_iod *iod)
1595 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1596 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1598 for (i = 0; i < iod->nents; i++)
1599 put_page(sg_page(&iod->sg[i]));
1602 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1604 struct nvme_dev *dev = ns->dev;
1605 struct nvme_user_io io;
1606 struct nvme_command c;
1607 unsigned length, meta_len;
1609 struct nvme_iod *iod, *meta_iod = NULL;
1610 dma_addr_t meta_dma_addr;
1611 void *meta, *uninitialized_var(meta_mem);
1613 if (copy_from_user(&io, uio, sizeof(io)))
1615 length = (io.nblocks + 1) << ns->lba_shift;
1616 meta_len = (io.nblocks + 1) * ns->ms;
1618 if (meta_len && ((io.metadata & 3) || !io.metadata))
1621 switch (io.opcode) {
1622 case nvme_cmd_write:
1624 case nvme_cmd_compare:
1625 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1632 return PTR_ERR(iod);
1634 memset(&c, 0, sizeof(c));
1635 c.rw.opcode = io.opcode;
1636 c.rw.flags = io.flags;
1637 c.rw.nsid = cpu_to_le32(ns->ns_id);
1638 c.rw.slba = cpu_to_le64(io.slba);
1639 c.rw.length = cpu_to_le16(io.nblocks);
1640 c.rw.control = cpu_to_le16(io.control);
1641 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1642 c.rw.reftag = cpu_to_le32(io.reftag);
1643 c.rw.apptag = cpu_to_le16(io.apptag);
1644 c.rw.appmask = cpu_to_le16(io.appmask);
1647 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1649 if (IS_ERR(meta_iod)) {
1650 status = PTR_ERR(meta_iod);
1655 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1656 &meta_dma_addr, GFP_KERNEL);
1662 if (io.opcode & 1) {
1663 int meta_offset = 0;
1665 for (i = 0; i < meta_iod->nents; i++) {
1666 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1667 meta_iod->sg[i].offset;
1668 memcpy(meta_mem + meta_offset, meta,
1669 meta_iod->sg[i].length);
1670 kunmap_atomic(meta);
1671 meta_offset += meta_iod->sg[i].length;
1675 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1678 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1679 c.rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1680 c.rw.prp2 = cpu_to_le64(iod->first_dma);
1682 if (length != (io.nblocks + 1) << ns->lba_shift)
1685 status = nvme_submit_io_cmd(dev, &c, NULL);
1688 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1689 int meta_offset = 0;
1691 for (i = 0; i < meta_iod->nents; i++) {
1692 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1693 meta_iod->sg[i].offset;
1694 memcpy(meta, meta_mem + meta_offset,
1695 meta_iod->sg[i].length);
1696 kunmap_atomic(meta);
1697 meta_offset += meta_iod->sg[i].length;
1701 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1706 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1707 nvme_free_iod(dev, iod);
1710 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1711 nvme_free_iod(dev, meta_iod);
1717 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1718 struct nvme_admin_cmd __user *ucmd)
1720 struct nvme_admin_cmd cmd;
1721 struct nvme_command c;
1723 struct nvme_iod *uninitialized_var(iod);
1726 if (!capable(CAP_SYS_ADMIN))
1728 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1731 memset(&c, 0, sizeof(c));
1732 c.common.opcode = cmd.opcode;
1733 c.common.flags = cmd.flags;
1734 c.common.nsid = cpu_to_le32(cmd.nsid);
1735 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1736 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1737 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1738 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1739 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1740 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1741 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1742 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1744 length = cmd.data_len;
1746 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1749 return PTR_ERR(iod);
1750 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1751 c.common.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1752 c.common.prp2 = cpu_to_le64(iod->first_dma);
1755 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1757 if (length != cmd.data_len)
1760 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
1763 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1764 nvme_free_iod(dev, iod);
1767 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1768 sizeof(cmd.result)))
1774 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1777 struct nvme_ns *ns = bdev->bd_disk->private_data;
1781 force_successful_syscall_return();
1783 case NVME_IOCTL_ADMIN_CMD:
1784 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1785 case NVME_IOCTL_SUBMIT_IO:
1786 return nvme_submit_io(ns, (void __user *)arg);
1787 case SG_GET_VERSION_NUM:
1788 return nvme_sg_get_version_num((void __user *)arg);
1790 return nvme_sg_io(ns, (void __user *)arg);
1796 #ifdef CONFIG_COMPAT
1797 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1798 unsigned int cmd, unsigned long arg)
1800 struct nvme_ns *ns = bdev->bd_disk->private_data;
1804 return nvme_sg_io32(ns, arg);
1806 return nvme_ioctl(bdev, mode, cmd, arg);
1809 #define nvme_compat_ioctl NULL
1812 static int nvme_open(struct block_device *bdev, fmode_t mode)
1814 struct nvme_ns *ns = bdev->bd_disk->private_data;
1815 struct nvme_dev *dev = ns->dev;
1817 kref_get(&dev->kref);
1821 static void nvme_free_dev(struct kref *kref);
1823 static void nvme_release(struct gendisk *disk, fmode_t mode)
1825 struct nvme_ns *ns = disk->private_data;
1826 struct nvme_dev *dev = ns->dev;
1828 kref_put(&dev->kref, nvme_free_dev);
1831 static int nvme_getgeo(struct block_device *bd, struct hd_geometry *geo)
1833 /* some standard values */
1834 geo->heads = 1 << 6;
1835 geo->sectors = 1 << 5;
1836 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
1840 static const struct block_device_operations nvme_fops = {
1841 .owner = THIS_MODULE,
1842 .ioctl = nvme_ioctl,
1843 .compat_ioctl = nvme_compat_ioctl,
1845 .release = nvme_release,
1846 .getgeo = nvme_getgeo,
1849 static void nvme_resubmit_iods(struct nvme_queue *nvmeq)
1851 struct nvme_iod *iod, *next;
1853 list_for_each_entry_safe(iod, next, &nvmeq->iod_bio, node) {
1854 if (unlikely(nvme_submit_iod(nvmeq, iod)))
1856 list_del(&iod->node);
1857 if (bio_list_empty(&nvmeq->sq_cong) &&
1858 list_empty(&nvmeq->iod_bio))
1859 remove_wait_queue(&nvmeq->sq_full,
1860 &nvmeq->sq_cong_wait);
1864 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1866 while (bio_list_peek(&nvmeq->sq_cong)) {
1867 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1868 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1870 if (bio_list_empty(&nvmeq->sq_cong) &&
1871 list_empty(&nvmeq->iod_bio))
1872 remove_wait_queue(&nvmeq->sq_full,
1873 &nvmeq->sq_cong_wait);
1874 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1875 if (!waitqueue_active(&nvmeq->sq_full))
1876 add_wait_queue(&nvmeq->sq_full,
1877 &nvmeq->sq_cong_wait);
1878 bio_list_add_head(&nvmeq->sq_cong, bio);
1884 static int nvme_submit_async_req(struct nvme_queue *nvmeq)
1886 struct nvme_command *c;
1889 cmdid = alloc_cmdid(nvmeq, CMD_CTX_ASYNC, special_completion, 0);
1893 c = &nvmeq->sq_cmds[nvmeq->sq_tail];
1894 memset(c, 0, sizeof(*c));
1895 c->common.opcode = nvme_admin_async_event;
1896 c->common.command_id = cmdid;
1898 if (++nvmeq->sq_tail == nvmeq->q_depth)
1900 writel(nvmeq->sq_tail, nvmeq->q_db);
1905 static int nvme_kthread(void *data)
1907 struct nvme_dev *dev, *next;
1909 while (!kthread_should_stop()) {
1910 set_current_state(TASK_INTERRUPTIBLE);
1911 spin_lock(&dev_list_lock);
1912 list_for_each_entry_safe(dev, next, &dev_list, node) {
1914 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1916 if (work_busy(&dev->reset_work))
1918 list_del_init(&dev->node);
1919 dev_warn(&dev->pci_dev->dev,
1920 "Failed status, reset controller\n");
1921 dev->reset_workfn = nvme_reset_failed_dev;
1922 queue_work(nvme_workq, &dev->reset_work);
1926 for (i = 0; i < dev->queue_count; i++) {
1927 struct nvme_queue *nvmeq =
1928 rcu_dereference(dev->queues[i]);
1931 spin_lock_irq(&nvmeq->q_lock);
1932 if (nvmeq->q_suspended)
1934 nvme_process_cq(nvmeq);
1935 nvme_cancel_ios(nvmeq, true);
1936 nvme_resubmit_bios(nvmeq);
1937 nvme_resubmit_iods(nvmeq);
1939 while ((i == 0) && (dev->event_limit > 0)) {
1940 if (nvme_submit_async_req(nvmeq))
1945 spin_unlock_irq(&nvmeq->q_lock);
1949 spin_unlock(&dev_list_lock);
1950 schedule_timeout(round_jiffies_relative(HZ));
1955 static void nvme_config_discard(struct nvme_ns *ns)
1957 u32 logical_block_size = queue_logical_block_size(ns->queue);
1958 ns->queue->limits.discard_zeroes_data = 0;
1959 ns->queue->limits.discard_alignment = logical_block_size;
1960 ns->queue->limits.discard_granularity = logical_block_size;
1961 ns->queue->limits.max_discard_sectors = 0xffffffff;
1962 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1965 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1966 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1969 struct gendisk *disk;
1972 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1975 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1978 ns->queue = blk_alloc_queue(GFP_KERNEL);
1981 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1982 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1983 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1984 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, ns->queue);
1985 blk_queue_make_request(ns->queue, nvme_make_request);
1987 ns->queue->queuedata = ns;
1989 disk = alloc_disk(0);
1991 goto out_free_queue;
1994 lbaf = id->flbas & 0xf;
1995 ns->lba_shift = id->lbaf[lbaf].ds;
1996 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1997 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1998 if (dev->max_hw_sectors)
1999 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
2000 if (dev->vwc & NVME_CTRL_VWC_PRESENT)
2001 blk_queue_flush(ns->queue, REQ_FLUSH | REQ_FUA);
2003 disk->major = nvme_major;
2004 disk->first_minor = 0;
2005 disk->fops = &nvme_fops;
2006 disk->private_data = ns;
2007 disk->queue = ns->queue;
2008 disk->driverfs_dev = &dev->pci_dev->dev;
2009 disk->flags = GENHD_FL_EXT_DEVT;
2010 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
2011 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
2013 if (dev->oncs & NVME_CTRL_ONCS_DSM)
2014 nvme_config_discard(ns);
2019 blk_cleanup_queue(ns->queue);
2025 static int nvme_find_closest_node(int node)
2027 int n, val, min_val = INT_MAX, best_node = node;
2029 for_each_online_node(n) {
2032 val = node_distance(node, n);
2033 if (val < min_val) {
2041 static void nvme_set_queue_cpus(cpumask_t *qmask, struct nvme_queue *nvmeq,
2045 for_each_cpu(cpu, qmask) {
2046 if (cpumask_weight(nvmeq->cpu_mask) >= count)
2048 if (!cpumask_test_and_set_cpu(cpu, nvmeq->cpu_mask))
2049 *per_cpu_ptr(nvmeq->dev->io_queue, cpu) = nvmeq->qid;
2053 static void nvme_add_cpus(cpumask_t *mask, const cpumask_t *unassigned_cpus,
2054 const cpumask_t *new_mask, struct nvme_queue *nvmeq, int cpus_per_queue)
2057 for_each_cpu(next_cpu, new_mask) {
2058 cpumask_or(mask, mask, get_cpu_mask(next_cpu));
2059 cpumask_or(mask, mask, topology_thread_cpumask(next_cpu));
2060 cpumask_and(mask, mask, unassigned_cpus);
2061 nvme_set_queue_cpus(mask, nvmeq, cpus_per_queue);
2065 static void nvme_create_io_queues(struct nvme_dev *dev)
2069 max = min(dev->max_qid, num_online_cpus());
2070 for (i = dev->queue_count; i <= max; i++)
2071 if (!nvme_alloc_queue(dev, i, dev->q_depth, i - 1))
2074 max = min(dev->queue_count - 1, num_online_cpus());
2075 for (i = dev->online_queues; i <= max; i++)
2076 if (nvme_create_queue(raw_nvmeq(dev, i), i))
2081 * If there are fewer queues than online cpus, this will try to optimally
2082 * assign a queue to multiple cpus by grouping cpus that are "close" together:
2083 * thread siblings, core, socket, closest node, then whatever else is
2086 static void nvme_assign_io_queues(struct nvme_dev *dev)
2088 unsigned cpu, cpus_per_queue, queues, remainder, i;
2089 cpumask_var_t unassigned_cpus;
2091 nvme_create_io_queues(dev);
2093 queues = min(dev->online_queues - 1, num_online_cpus());
2097 cpus_per_queue = num_online_cpus() / queues;
2098 remainder = queues - (num_online_cpus() - queues * cpus_per_queue);
2100 if (!alloc_cpumask_var(&unassigned_cpus, GFP_KERNEL))
2103 cpumask_copy(unassigned_cpus, cpu_online_mask);
2104 cpu = cpumask_first(unassigned_cpus);
2105 for (i = 1; i <= queues; i++) {
2106 struct nvme_queue *nvmeq = lock_nvmeq(dev, i);
2109 cpumask_clear(nvmeq->cpu_mask);
2110 if (!cpumask_weight(unassigned_cpus)) {
2111 unlock_nvmeq(nvmeq);
2115 mask = *get_cpu_mask(cpu);
2116 nvme_set_queue_cpus(&mask, nvmeq, cpus_per_queue);
2117 if (cpus_weight(mask) < cpus_per_queue)
2118 nvme_add_cpus(&mask, unassigned_cpus,
2119 topology_thread_cpumask(cpu),
2120 nvmeq, cpus_per_queue);
2121 if (cpus_weight(mask) < cpus_per_queue)
2122 nvme_add_cpus(&mask, unassigned_cpus,
2123 topology_core_cpumask(cpu),
2124 nvmeq, cpus_per_queue);
2125 if (cpus_weight(mask) < cpus_per_queue)
2126 nvme_add_cpus(&mask, unassigned_cpus,
2127 cpumask_of_node(cpu_to_node(cpu)),
2128 nvmeq, cpus_per_queue);
2129 if (cpus_weight(mask) < cpus_per_queue)
2130 nvme_add_cpus(&mask, unassigned_cpus,
2132 nvme_find_closest_node(
2134 nvmeq, cpus_per_queue);
2135 if (cpus_weight(mask) < cpus_per_queue)
2136 nvme_add_cpus(&mask, unassigned_cpus,
2138 nvmeq, cpus_per_queue);
2140 WARN(cpumask_weight(nvmeq->cpu_mask) != cpus_per_queue,
2141 "nvme%d qid:%d mis-matched queue-to-cpu assignment\n",
2144 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
2146 cpumask_andnot(unassigned_cpus, unassigned_cpus,
2148 cpu = cpumask_next(cpu, unassigned_cpus);
2149 if (remainder && !--remainder)
2151 unlock_nvmeq(nvmeq);
2153 WARN(cpumask_weight(unassigned_cpus), "nvme%d unassigned online cpus\n",
2156 cpumask_andnot(unassigned_cpus, cpu_possible_mask, cpu_online_mask);
2157 for_each_cpu(cpu, unassigned_cpus)
2158 *per_cpu_ptr(dev->io_queue, cpu) = (i++ % queues) + 1;
2159 free_cpumask_var(unassigned_cpus);
2162 static int set_queue_count(struct nvme_dev *dev, int count)
2166 u32 q_count = (count - 1) | ((count - 1) << 16);
2168 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
2173 dev_err(&dev->pci_dev->dev, "Could not set queue count (%d)\n",
2177 return min(result & 0xffff, result >> 16) + 1;
2180 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2182 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
2185 static void nvme_cpu_workfn(struct work_struct *work)
2187 struct nvme_dev *dev = container_of(work, struct nvme_dev, cpu_work);
2188 if (dev->initialized)
2189 nvme_assign_io_queues(dev);
2192 static int nvme_cpu_notify(struct notifier_block *self,
2193 unsigned long action, void *hcpu)
2195 struct nvme_dev *dev;
2200 spin_lock(&dev_list_lock);
2201 list_for_each_entry(dev, &dev_list, node)
2202 schedule_work(&dev->cpu_work);
2203 spin_unlock(&dev_list_lock);
2209 static int nvme_setup_io_queues(struct nvme_dev *dev)
2211 struct nvme_queue *adminq = raw_nvmeq(dev, 0);
2212 struct pci_dev *pdev = dev->pci_dev;
2213 int result, i, vecs, nr_io_queues, size;
2215 nr_io_queues = num_possible_cpus();
2216 result = set_queue_count(dev, nr_io_queues);
2219 if (result < nr_io_queues)
2220 nr_io_queues = result;
2222 size = db_bar_size(dev, nr_io_queues);
2226 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2229 if (!--nr_io_queues)
2231 size = db_bar_size(dev, nr_io_queues);
2233 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2234 adminq->q_db = dev->dbs;
2237 /* Deregister the admin queue's interrupt */
2238 free_irq(dev->entry[0].vector, adminq);
2240 for (i = 0; i < nr_io_queues; i++)
2241 dev->entry[i].entry = i;
2242 vecs = pci_enable_msix_range(pdev, dev->entry, 1, nr_io_queues);
2244 vecs = pci_enable_msi_range(pdev, 1, min(nr_io_queues, 32));
2248 for (i = 0; i < vecs; i++)
2249 dev->entry[i].vector = i + pdev->irq;
2254 * Should investigate if there's a performance win from allocating
2255 * more queues than interrupt vectors; it might allow the submission
2256 * path to scale better, even if the receive path is limited by the
2257 * number of interrupts.
2259 nr_io_queues = vecs;
2260 dev->max_qid = nr_io_queues;
2262 result = queue_request_irq(dev, adminq, adminq->irqname);
2264 adminq->q_suspended = 1;
2268 /* Free previously allocated queues that are no longer usable */
2269 nvme_free_queues(dev, nr_io_queues + 1);
2270 nvme_assign_io_queues(dev);
2275 nvme_free_queues(dev, 1);
2280 * Return: error value if an error occurred setting up the queues or calling
2281 * Identify Device. 0 if these succeeded, even if adding some of the
2282 * namespaces failed. At the moment, these failures are silent. TBD which
2283 * failures should be reported.
2285 static int nvme_dev_add(struct nvme_dev *dev)
2287 struct pci_dev *pdev = dev->pci_dev;
2291 struct nvme_id_ctrl *ctrl;
2292 struct nvme_id_ns *id_ns;
2294 dma_addr_t dma_addr;
2295 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
2297 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
2301 res = nvme_identify(dev, 0, 1, dma_addr);
2303 dev_err(&pdev->dev, "Identify Controller failed (%d)\n", res);
2309 nn = le32_to_cpup(&ctrl->nn);
2310 dev->oncs = le16_to_cpup(&ctrl->oncs);
2311 dev->abort_limit = ctrl->acl + 1;
2312 dev->vwc = ctrl->vwc;
2313 dev->event_limit = min(ctrl->aerl + 1, 8);
2314 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2315 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2316 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2318 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2319 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2320 (pdev->device == 0x0953) && ctrl->vs[3])
2321 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2324 for (i = 1; i <= nn; i++) {
2325 res = nvme_identify(dev, i, 0, dma_addr);
2329 if (id_ns->ncap == 0)
2332 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2333 dma_addr + 4096, NULL);
2335 memset(mem + 4096, 0, 4096);
2337 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2339 list_add_tail(&ns->list, &dev->namespaces);
2341 list_for_each_entry(ns, &dev->namespaces, list)
2346 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2350 static int nvme_dev_map(struct nvme_dev *dev)
2353 int bars, result = -ENOMEM;
2354 struct pci_dev *pdev = dev->pci_dev;
2356 if (pci_enable_device_mem(pdev))
2359 dev->entry[0].vector = pdev->irq;
2360 pci_set_master(pdev);
2361 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2362 if (pci_request_selected_regions(pdev, bars, "nvme"))
2365 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2366 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2369 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2372 if (readl(&dev->bar->csts) == -1) {
2376 cap = readq(&dev->bar->cap);
2377 dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2378 dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
2379 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2387 pci_release_regions(pdev);
2389 pci_disable_device(pdev);
2393 static void nvme_dev_unmap(struct nvme_dev *dev)
2395 if (dev->pci_dev->msi_enabled)
2396 pci_disable_msi(dev->pci_dev);
2397 else if (dev->pci_dev->msix_enabled)
2398 pci_disable_msix(dev->pci_dev);
2403 pci_release_regions(dev->pci_dev);
2406 if (pci_is_enabled(dev->pci_dev))
2407 pci_disable_device(dev->pci_dev);
2410 struct nvme_delq_ctx {
2411 struct task_struct *waiter;
2412 struct kthread_worker *worker;
2416 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2418 dq->waiter = current;
2422 set_current_state(TASK_KILLABLE);
2423 if (!atomic_read(&dq->refcount))
2425 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2426 fatal_signal_pending(current)) {
2427 set_current_state(TASK_RUNNING);
2429 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2430 nvme_disable_queue(dev, 0);
2432 send_sig(SIGKILL, dq->worker->task, 1);
2433 flush_kthread_worker(dq->worker);
2437 set_current_state(TASK_RUNNING);
2440 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2442 atomic_dec(&dq->refcount);
2444 wake_up_process(dq->waiter);
2447 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2449 atomic_inc(&dq->refcount);
2453 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2455 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2457 nvme_clear_queue(nvmeq);
2461 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2462 kthread_work_func_t fn)
2464 struct nvme_command c;
2466 memset(&c, 0, sizeof(c));
2467 c.delete_queue.opcode = opcode;
2468 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2470 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2471 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2474 static void nvme_del_cq_work_handler(struct kthread_work *work)
2476 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2478 nvme_del_queue_end(nvmeq);
2481 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2483 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2484 nvme_del_cq_work_handler);
2487 static void nvme_del_sq_work_handler(struct kthread_work *work)
2489 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2491 int status = nvmeq->cmdinfo.status;
2494 status = nvme_delete_cq(nvmeq);
2496 nvme_del_queue_end(nvmeq);
2499 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2501 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2502 nvme_del_sq_work_handler);
2505 static void nvme_del_queue_start(struct kthread_work *work)
2507 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2509 allow_signal(SIGKILL);
2510 if (nvme_delete_sq(nvmeq))
2511 nvme_del_queue_end(nvmeq);
2514 static void nvme_disable_io_queues(struct nvme_dev *dev)
2517 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2518 struct nvme_delq_ctx dq;
2519 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2520 &worker, "nvme%d", dev->instance);
2522 if (IS_ERR(kworker_task)) {
2523 dev_err(&dev->pci_dev->dev,
2524 "Failed to create queue del task\n");
2525 for (i = dev->queue_count - 1; i > 0; i--)
2526 nvme_disable_queue(dev, i);
2531 atomic_set(&dq.refcount, 0);
2532 dq.worker = &worker;
2533 for (i = dev->queue_count - 1; i > 0; i--) {
2534 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2536 if (nvme_suspend_queue(nvmeq))
2538 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2539 nvmeq->cmdinfo.worker = dq.worker;
2540 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2541 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2543 nvme_wait_dq(&dq, dev);
2544 kthread_stop(kworker_task);
2548 * Remove the node from the device list and check
2549 * for whether or not we need to stop the nvme_thread.
2551 static void nvme_dev_list_remove(struct nvme_dev *dev)
2553 struct task_struct *tmp = NULL;
2555 spin_lock(&dev_list_lock);
2556 list_del_init(&dev->node);
2557 if (list_empty(&dev_list) && !IS_ERR_OR_NULL(nvme_thread)) {
2561 spin_unlock(&dev_list_lock);
2567 static void nvme_dev_shutdown(struct nvme_dev *dev)
2571 dev->initialized = 0;
2572 nvme_dev_list_remove(dev);
2574 if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2575 for (i = dev->queue_count - 1; i >= 0; i--) {
2576 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2577 nvme_suspend_queue(nvmeq);
2578 nvme_clear_queue(nvmeq);
2581 nvme_disable_io_queues(dev);
2582 nvme_shutdown_ctrl(dev);
2583 nvme_disable_queue(dev, 0);
2585 nvme_dev_unmap(dev);
2588 static void nvme_dev_remove(struct nvme_dev *dev)
2592 list_for_each_entry(ns, &dev->namespaces, list) {
2593 if (ns->disk->flags & GENHD_FL_UP)
2594 del_gendisk(ns->disk);
2595 if (!blk_queue_dying(ns->queue))
2596 blk_cleanup_queue(ns->queue);
2600 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2602 struct device *dmadev = &dev->pci_dev->dev;
2603 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2604 PAGE_SIZE, PAGE_SIZE, 0);
2605 if (!dev->prp_page_pool)
2608 /* Optimisation for I/Os between 4k and 128k */
2609 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2611 if (!dev->prp_small_pool) {
2612 dma_pool_destroy(dev->prp_page_pool);
2618 static void nvme_release_prp_pools(struct nvme_dev *dev)
2620 dma_pool_destroy(dev->prp_page_pool);
2621 dma_pool_destroy(dev->prp_small_pool);
2624 static DEFINE_IDA(nvme_instance_ida);
2626 static int nvme_set_instance(struct nvme_dev *dev)
2628 int instance, error;
2631 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2634 spin_lock(&dev_list_lock);
2635 error = ida_get_new(&nvme_instance_ida, &instance);
2636 spin_unlock(&dev_list_lock);
2637 } while (error == -EAGAIN);
2642 dev->instance = instance;
2646 static void nvme_release_instance(struct nvme_dev *dev)
2648 spin_lock(&dev_list_lock);
2649 ida_remove(&nvme_instance_ida, dev->instance);
2650 spin_unlock(&dev_list_lock);
2653 static void nvme_free_namespaces(struct nvme_dev *dev)
2655 struct nvme_ns *ns, *next;
2657 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2658 list_del(&ns->list);
2664 static void nvme_free_dev(struct kref *kref)
2666 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2668 nvme_free_namespaces(dev);
2669 free_percpu(dev->io_queue);
2675 static int nvme_dev_open(struct inode *inode, struct file *f)
2677 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2679 kref_get(&dev->kref);
2680 f->private_data = dev;
2684 static int nvme_dev_release(struct inode *inode, struct file *f)
2686 struct nvme_dev *dev = f->private_data;
2687 kref_put(&dev->kref, nvme_free_dev);
2691 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2693 struct nvme_dev *dev = f->private_data;
2695 case NVME_IOCTL_ADMIN_CMD:
2696 return nvme_user_admin_cmd(dev, (void __user *)arg);
2702 static const struct file_operations nvme_dev_fops = {
2703 .owner = THIS_MODULE,
2704 .open = nvme_dev_open,
2705 .release = nvme_dev_release,
2706 .unlocked_ioctl = nvme_dev_ioctl,
2707 .compat_ioctl = nvme_dev_ioctl,
2710 static int nvme_dev_start(struct nvme_dev *dev)
2713 bool start_thread = false;
2715 result = nvme_dev_map(dev);
2719 result = nvme_configure_admin_queue(dev);
2723 spin_lock(&dev_list_lock);
2724 if (list_empty(&dev_list) && IS_ERR_OR_NULL(nvme_thread)) {
2725 start_thread = true;
2728 list_add(&dev->node, &dev_list);
2729 spin_unlock(&dev_list_lock);
2732 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2733 wake_up(&nvme_kthread_wait);
2735 wait_event_killable(nvme_kthread_wait, nvme_thread);
2737 if (IS_ERR_OR_NULL(nvme_thread)) {
2738 result = nvme_thread ? PTR_ERR(nvme_thread) : -EINTR;
2742 result = nvme_setup_io_queues(dev);
2749 nvme_disable_queue(dev, 0);
2750 nvme_dev_list_remove(dev);
2752 nvme_dev_unmap(dev);
2756 static int nvme_remove_dead_ctrl(void *arg)
2758 struct nvme_dev *dev = (struct nvme_dev *)arg;
2759 struct pci_dev *pdev = dev->pci_dev;
2761 if (pci_get_drvdata(pdev))
2762 pci_stop_and_remove_bus_device(pdev);
2763 kref_put(&dev->kref, nvme_free_dev);
2767 static void nvme_remove_disks(struct work_struct *ws)
2769 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2771 nvme_dev_remove(dev);
2772 nvme_free_queues(dev, 1);
2775 static int nvme_dev_resume(struct nvme_dev *dev)
2779 ret = nvme_dev_start(dev);
2782 if (dev->online_queues < 2) {
2783 spin_lock(&dev_list_lock);
2784 dev->reset_workfn = nvme_remove_disks;
2785 queue_work(nvme_workq, &dev->reset_work);
2786 spin_unlock(&dev_list_lock);
2788 dev->initialized = 1;
2792 static void nvme_dev_reset(struct nvme_dev *dev)
2794 nvme_dev_shutdown(dev);
2795 if (nvme_dev_resume(dev)) {
2796 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2797 kref_get(&dev->kref);
2798 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2800 dev_err(&dev->pci_dev->dev,
2801 "Failed to start controller remove task\n");
2802 kref_put(&dev->kref, nvme_free_dev);
2807 static void nvme_reset_failed_dev(struct work_struct *ws)
2809 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2810 nvme_dev_reset(dev);
2813 static void nvme_reset_workfn(struct work_struct *work)
2815 struct nvme_dev *dev = container_of(work, struct nvme_dev, reset_work);
2816 dev->reset_workfn(work);
2819 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2821 int result = -ENOMEM;
2822 struct nvme_dev *dev;
2824 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2827 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2831 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2835 dev->io_queue = alloc_percpu(unsigned short);
2839 INIT_LIST_HEAD(&dev->namespaces);
2840 dev->reset_workfn = nvme_reset_failed_dev;
2841 INIT_WORK(&dev->reset_work, nvme_reset_workfn);
2842 INIT_WORK(&dev->cpu_work, nvme_cpu_workfn);
2843 dev->pci_dev = pdev;
2844 pci_set_drvdata(pdev, dev);
2845 result = nvme_set_instance(dev);
2849 result = nvme_setup_prp_pools(dev);
2853 kref_init(&dev->kref);
2854 result = nvme_dev_start(dev);
2858 if (dev->online_queues > 1)
2859 result = nvme_dev_add(dev);
2863 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2864 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2865 dev->miscdev.parent = &pdev->dev;
2866 dev->miscdev.name = dev->name;
2867 dev->miscdev.fops = &nvme_dev_fops;
2868 result = misc_register(&dev->miscdev);
2872 dev->initialized = 1;
2876 nvme_dev_remove(dev);
2877 nvme_free_namespaces(dev);
2879 nvme_dev_shutdown(dev);
2881 nvme_free_queues(dev, 0);
2882 nvme_release_prp_pools(dev);
2884 nvme_release_instance(dev);
2886 free_percpu(dev->io_queue);
2893 static void nvme_reset_notify(struct pci_dev *pdev, bool prepare)
2895 struct nvme_dev *dev = pci_get_drvdata(pdev);
2898 nvme_dev_shutdown(dev);
2900 nvme_dev_resume(dev);
2903 static void nvme_shutdown(struct pci_dev *pdev)
2905 struct nvme_dev *dev = pci_get_drvdata(pdev);
2906 nvme_dev_shutdown(dev);
2909 static void nvme_remove(struct pci_dev *pdev)
2911 struct nvme_dev *dev = pci_get_drvdata(pdev);
2913 spin_lock(&dev_list_lock);
2914 list_del_init(&dev->node);
2915 spin_unlock(&dev_list_lock);
2917 pci_set_drvdata(pdev, NULL);
2918 flush_work(&dev->reset_work);
2919 flush_work(&dev->cpu_work);
2920 misc_deregister(&dev->miscdev);
2921 nvme_dev_remove(dev);
2922 nvme_dev_shutdown(dev);
2923 nvme_free_queues(dev, 0);
2925 nvme_release_instance(dev);
2926 nvme_release_prp_pools(dev);
2927 kref_put(&dev->kref, nvme_free_dev);
2930 /* These functions are yet to be implemented */
2931 #define nvme_error_detected NULL
2932 #define nvme_dump_registers NULL
2933 #define nvme_link_reset NULL
2934 #define nvme_slot_reset NULL
2935 #define nvme_error_resume NULL
2937 #ifdef CONFIG_PM_SLEEP
2938 static int nvme_suspend(struct device *dev)
2940 struct pci_dev *pdev = to_pci_dev(dev);
2941 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2943 nvme_dev_shutdown(ndev);
2947 static int nvme_resume(struct device *dev)
2949 struct pci_dev *pdev = to_pci_dev(dev);
2950 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2952 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2953 ndev->reset_workfn = nvme_reset_failed_dev;
2954 queue_work(nvme_workq, &ndev->reset_work);
2960 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2962 static const struct pci_error_handlers nvme_err_handler = {
2963 .error_detected = nvme_error_detected,
2964 .mmio_enabled = nvme_dump_registers,
2965 .link_reset = nvme_link_reset,
2966 .slot_reset = nvme_slot_reset,
2967 .resume = nvme_error_resume,
2968 .reset_notify = nvme_reset_notify,
2971 /* Move to pci_ids.h later */
2972 #define PCI_CLASS_STORAGE_EXPRESS 0x010802
2974 static const struct pci_device_id nvme_id_table[] = {
2975 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2978 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2980 static struct pci_driver nvme_driver = {
2982 .id_table = nvme_id_table,
2983 .probe = nvme_probe,
2984 .remove = nvme_remove,
2985 .shutdown = nvme_shutdown,
2987 .pm = &nvme_dev_pm_ops,
2989 .err_handler = &nvme_err_handler,
2992 static int __init nvme_init(void)
2996 init_waitqueue_head(&nvme_kthread_wait);
2998 nvme_workq = create_singlethread_workqueue("nvme");
3002 result = register_blkdev(nvme_major, "nvme");
3005 else if (result > 0)
3006 nvme_major = result;
3008 nvme_nb.notifier_call = &nvme_cpu_notify;
3009 result = register_hotcpu_notifier(&nvme_nb);
3011 goto unregister_blkdev;
3013 result = pci_register_driver(&nvme_driver);
3015 goto unregister_hotcpu;
3019 unregister_hotcpu_notifier(&nvme_nb);
3021 unregister_blkdev(nvme_major, "nvme");
3023 destroy_workqueue(nvme_workq);
3027 static void __exit nvme_exit(void)
3029 pci_unregister_driver(&nvme_driver);
3030 unregister_hotcpu_notifier(&nvme_nb);
3031 unregister_blkdev(nvme_major, "nvme");
3032 destroy_workqueue(nvme_workq);
3033 BUG_ON(nvme_thread && !IS_ERR(nvme_thread));
3037 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
3038 MODULE_LICENSE("GPL");
3039 MODULE_VERSION("0.9");
3040 module_init(nvme_init);
3041 module_exit(nvme_exit);