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;
77 static void nvme_reset_failed_dev(struct work_struct *ws);
79 struct async_cmd_info {
80 struct kthread_work work;
81 struct kthread_worker *worker;
88 * An NVM Express queue. Each device has at least two (one for admin
89 * commands and one for I/O commands).
92 struct rcu_head r_head;
93 struct device *q_dmadev;
95 char irqname[24]; /* nvme4294967295-65535\0 */
97 struct nvme_command *sq_cmds;
98 volatile struct nvme_completion *cqes;
99 dma_addr_t sq_dma_addr;
100 dma_addr_t cq_dma_addr;
101 wait_queue_head_t sq_full;
102 wait_queue_t sq_cong_wait;
103 struct bio_list sq_cong;
104 struct list_head iod_bio;
115 cpumask_var_t cpu_mask;
116 struct async_cmd_info cmdinfo;
117 unsigned long cmdid_data[];
121 * Check we didin't inadvertently grow the command struct
123 static inline void _nvme_check_size(void)
125 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
126 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
127 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
128 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
129 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
130 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
131 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
132 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
133 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
134 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
135 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
136 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
139 typedef void (*nvme_completion_fn)(struct nvme_queue *, void *,
140 struct nvme_completion *);
142 struct nvme_cmd_info {
143 nvme_completion_fn fn;
145 unsigned long timeout;
149 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
151 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
154 static unsigned nvme_queue_extra(int depth)
156 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
160 * alloc_cmdid() - Allocate a Command ID
161 * @nvmeq: The queue that will be used for this command
162 * @ctx: A pointer that will be passed to the handler
163 * @handler: The function to call on completion
165 * Allocate a Command ID for a queue. The data passed in will
166 * be passed to the completion handler. This is implemented by using
167 * the bottom two bits of the ctx pointer to store the handler ID.
168 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
169 * We can change this if it becomes a problem.
171 * May be called with local interrupts disabled and the q_lock held,
172 * or with interrupts enabled and no locks held.
174 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
175 nvme_completion_fn handler, unsigned timeout)
177 int depth = nvmeq->q_depth - 1;
178 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
182 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
185 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
187 info[cmdid].fn = handler;
188 info[cmdid].ctx = ctx;
189 info[cmdid].timeout = jiffies + timeout;
190 info[cmdid].aborted = 0;
194 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
195 nvme_completion_fn handler, unsigned timeout)
198 wait_event_killable(nvmeq->sq_full,
199 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
200 return (cmdid < 0) ? -EINTR : cmdid;
203 /* Special values must be less than 0x1000 */
204 #define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
205 #define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
206 #define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
207 #define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
208 #define CMD_CTX_ABORT (0x318 + CMD_CTX_BASE)
210 static void special_completion(struct nvme_queue *nvmeq, void *ctx,
211 struct nvme_completion *cqe)
213 if (ctx == CMD_CTX_CANCELLED)
215 if (ctx == CMD_CTX_ABORT) {
216 ++nvmeq->dev->abort_limit;
219 if (ctx == CMD_CTX_COMPLETED) {
220 dev_warn(nvmeq->q_dmadev,
221 "completed id %d twice on queue %d\n",
222 cqe->command_id, le16_to_cpup(&cqe->sq_id));
225 if (ctx == CMD_CTX_INVALID) {
226 dev_warn(nvmeq->q_dmadev,
227 "invalid id %d completed on queue %d\n",
228 cqe->command_id, le16_to_cpup(&cqe->sq_id));
232 dev_warn(nvmeq->q_dmadev, "Unknown special completion %p\n", ctx);
235 static void async_completion(struct nvme_queue *nvmeq, void *ctx,
236 struct nvme_completion *cqe)
238 struct async_cmd_info *cmdinfo = ctx;
239 cmdinfo->result = le32_to_cpup(&cqe->result);
240 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
241 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
245 * Called with local interrupts disabled and the q_lock held. May not sleep.
247 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
248 nvme_completion_fn *fn)
251 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
253 if (cmdid >= nvmeq->q_depth || !info[cmdid].fn) {
255 *fn = special_completion;
256 return CMD_CTX_INVALID;
259 *fn = info[cmdid].fn;
260 ctx = info[cmdid].ctx;
261 info[cmdid].fn = special_completion;
262 info[cmdid].ctx = CMD_CTX_COMPLETED;
263 clear_bit(cmdid, nvmeq->cmdid_data);
264 wake_up(&nvmeq->sq_full);
268 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
269 nvme_completion_fn *fn)
272 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
274 *fn = info[cmdid].fn;
275 ctx = info[cmdid].ctx;
276 info[cmdid].fn = special_completion;
277 info[cmdid].ctx = CMD_CTX_CANCELLED;
281 static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
283 return rcu_dereference_raw(dev->queues[qid]);
286 static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
288 struct nvme_queue *nvmeq;
289 unsigned queue_id = get_cpu_var(*dev->io_queue);
292 nvmeq = rcu_dereference(dev->queues[queue_id]);
297 put_cpu_var(*dev->io_queue);
301 static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
304 put_cpu_var(nvmeq->dev->io_queue);
307 static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
310 struct nvme_queue *nvmeq;
313 nvmeq = rcu_dereference(dev->queues[q_idx]);
321 static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
327 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
328 * @nvmeq: The queue to use
329 * @cmd: The command to send
331 * Safe to use from interrupt context
333 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
337 spin_lock_irqsave(&nvmeq->q_lock, flags);
338 if (nvmeq->q_suspended) {
339 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
342 tail = nvmeq->sq_tail;
343 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
344 if (++tail == nvmeq->q_depth)
346 writel(tail, nvmeq->q_db);
347 nvmeq->sq_tail = tail;
348 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
353 static __le64 **iod_list(struct nvme_iod *iod)
355 return ((void *)iod) + iod->offset;
359 * Will slightly overestimate the number of pages needed. This is OK
360 * as it only leads to a small amount of wasted memory for the lifetime of
363 static int nvme_npages(unsigned size)
365 unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
366 return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
369 static struct nvme_iod *
370 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
372 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
373 sizeof(__le64 *) * nvme_npages(nbytes) +
374 sizeof(struct scatterlist) * nseg, gfp);
377 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
379 iod->length = nbytes;
381 iod->first_dma = 0ULL;
382 iod->start_time = jiffies;
388 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
390 const int last_prp = PAGE_SIZE / 8 - 1;
392 __le64 **list = iod_list(iod);
393 dma_addr_t prp_dma = iod->first_dma;
395 if (iod->npages == 0)
396 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
397 for (i = 0; i < iod->npages; i++) {
398 __le64 *prp_list = list[i];
399 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
400 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
401 prp_dma = next_prp_dma;
406 static void nvme_start_io_acct(struct bio *bio)
408 struct gendisk *disk = bio->bi_bdev->bd_disk;
409 if (blk_queue_io_stat(disk->queue)) {
410 const int rw = bio_data_dir(bio);
411 int cpu = part_stat_lock();
412 part_round_stats(cpu, &disk->part0);
413 part_stat_inc(cpu, &disk->part0, ios[rw]);
414 part_stat_add(cpu, &disk->part0, sectors[rw],
416 part_inc_in_flight(&disk->part0, rw);
421 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
423 struct gendisk *disk = bio->bi_bdev->bd_disk;
424 if (blk_queue_io_stat(disk->queue)) {
425 const int rw = bio_data_dir(bio);
426 unsigned long duration = jiffies - start_time;
427 int cpu = part_stat_lock();
428 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
429 part_round_stats(cpu, &disk->part0);
430 part_dec_in_flight(&disk->part0, rw);
435 static void bio_completion(struct nvme_queue *nvmeq, void *ctx,
436 struct nvme_completion *cqe)
438 struct nvme_iod *iod = ctx;
439 struct bio *bio = iod->private;
440 u16 status = le16_to_cpup(&cqe->status) >> 1;
443 if (unlikely(status)) {
444 if (!(status & NVME_SC_DNR ||
445 bio->bi_rw & REQ_FAILFAST_MASK) &&
446 (jiffies - iod->start_time) < IOD_TIMEOUT) {
447 if (!waitqueue_active(&nvmeq->sq_full))
448 add_wait_queue(&nvmeq->sq_full,
449 &nvmeq->sq_cong_wait);
450 list_add_tail(&iod->node, &nvmeq->iod_bio);
451 wake_up(&nvmeq->sq_full);
457 dma_unmap_sg(nvmeq->q_dmadev, iod->sg, iod->nents,
458 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
459 nvme_end_io_acct(bio, iod->start_time);
461 nvme_free_iod(nvmeq->dev, iod);
463 trace_block_bio_complete(bdev_get_queue(bio->bi_bdev), bio, error);
464 bio_endio(bio, error);
467 /* length is in bytes. gfp flags indicates whether we may sleep. */
468 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_iod *iod, int total_len,
471 struct dma_pool *pool;
472 int length = total_len;
473 struct scatterlist *sg = iod->sg;
474 int dma_len = sg_dma_len(sg);
475 u64 dma_addr = sg_dma_address(sg);
476 int offset = offset_in_page(dma_addr);
478 __le64 **list = iod_list(iod);
482 length -= (PAGE_SIZE - offset);
486 dma_len -= (PAGE_SIZE - offset);
488 dma_addr += (PAGE_SIZE - offset);
491 dma_addr = sg_dma_address(sg);
492 dma_len = sg_dma_len(sg);
495 if (length <= PAGE_SIZE) {
496 iod->first_dma = dma_addr;
500 nprps = DIV_ROUND_UP(length, PAGE_SIZE);
501 if (nprps <= (256 / 8)) {
502 pool = dev->prp_small_pool;
505 pool = dev->prp_page_pool;
509 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
511 iod->first_dma = dma_addr;
513 return (total_len - length) + PAGE_SIZE;
516 iod->first_dma = prp_dma;
519 if (i == PAGE_SIZE / 8) {
520 __le64 *old_prp_list = prp_list;
521 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
523 return total_len - length;
524 list[iod->npages++] = prp_list;
525 prp_list[0] = old_prp_list[i - 1];
526 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
529 prp_list[i++] = cpu_to_le64(dma_addr);
530 dma_len -= PAGE_SIZE;
531 dma_addr += PAGE_SIZE;
539 dma_addr = sg_dma_address(sg);
540 dma_len = sg_dma_len(sg);
546 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
549 struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
553 trace_block_split(bdev_get_queue(bio->bi_bdev), bio,
554 split->bi_iter.bi_sector);
555 bio_chain(split, bio);
557 if (!waitqueue_active(&nvmeq->sq_full))
558 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
559 bio_list_add(&nvmeq->sq_cong, split);
560 bio_list_add(&nvmeq->sq_cong, bio);
561 wake_up(&nvmeq->sq_full);
566 /* NVMe scatterlists require no holes in the virtual address */
567 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
568 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
570 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
571 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
573 struct bio_vec bvec, bvprv;
574 struct bvec_iter iter;
575 struct scatterlist *sg = NULL;
576 int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
579 if (nvmeq->dev->stripe_size)
580 split_len = nvmeq->dev->stripe_size -
581 ((bio->bi_iter.bi_sector << 9) &
582 (nvmeq->dev->stripe_size - 1));
584 sg_init_table(iod->sg, psegs);
585 bio_for_each_segment(bvec, bio, iter) {
586 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
587 sg->length += bvec.bv_len;
589 if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
590 return nvme_split_and_submit(bio, nvmeq,
593 sg = sg ? sg + 1 : iod->sg;
594 sg_set_page(sg, bvec.bv_page,
595 bvec.bv_len, bvec.bv_offset);
599 if (split_len - length < bvec.bv_len)
600 return nvme_split_and_submit(bio, nvmeq, split_len);
601 length += bvec.bv_len;
607 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
610 BUG_ON(length != bio->bi_iter.bi_size);
614 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
615 struct bio *bio, struct nvme_iod *iod, int cmdid)
617 struct nvme_dsm_range *range =
618 (struct nvme_dsm_range *)iod_list(iod)[0];
619 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
621 range->cattr = cpu_to_le32(0);
622 range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
623 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
625 memset(cmnd, 0, sizeof(*cmnd));
626 cmnd->dsm.opcode = nvme_cmd_dsm;
627 cmnd->dsm.command_id = cmdid;
628 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
629 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
631 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
633 if (++nvmeq->sq_tail == nvmeq->q_depth)
635 writel(nvmeq->sq_tail, nvmeq->q_db);
640 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
643 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
645 memset(cmnd, 0, sizeof(*cmnd));
646 cmnd->common.opcode = nvme_cmd_flush;
647 cmnd->common.command_id = cmdid;
648 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
650 if (++nvmeq->sq_tail == nvmeq->q_depth)
652 writel(nvmeq->sq_tail, nvmeq->q_db);
657 static int nvme_submit_iod(struct nvme_queue *nvmeq, struct nvme_iod *iod)
659 struct bio *bio = iod->private;
660 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
661 struct nvme_command *cmnd;
666 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
667 if (unlikely(cmdid < 0))
670 if (bio->bi_rw & REQ_DISCARD)
671 return nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
672 if (bio->bi_rw & REQ_FLUSH)
673 return nvme_submit_flush(nvmeq, ns, cmdid);
676 if (bio->bi_rw & REQ_FUA)
677 control |= NVME_RW_FUA;
678 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
679 control |= NVME_RW_LR;
682 if (bio->bi_rw & REQ_RAHEAD)
683 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
685 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
686 memset(cmnd, 0, sizeof(*cmnd));
688 cmnd->rw.opcode = bio_data_dir(bio) ? nvme_cmd_write : nvme_cmd_read;
689 cmnd->rw.command_id = cmdid;
690 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
691 cmnd->rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
692 cmnd->rw.prp2 = cpu_to_le64(iod->first_dma);
693 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
695 cpu_to_le16((bio->bi_iter.bi_size >> ns->lba_shift) - 1);
696 cmnd->rw.control = cpu_to_le16(control);
697 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
699 if (++nvmeq->sq_tail == nvmeq->q_depth)
701 writel(nvmeq->sq_tail, nvmeq->q_db);
706 static int nvme_split_flush_data(struct nvme_queue *nvmeq, struct bio *bio)
708 struct bio *split = bio_clone(bio, GFP_ATOMIC);
712 split->bi_iter.bi_size = 0;
713 split->bi_phys_segments = 0;
714 bio->bi_rw &= ~REQ_FLUSH;
715 bio_chain(split, bio);
717 if (!waitqueue_active(&nvmeq->sq_full))
718 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
719 bio_list_add(&nvmeq->sq_cong, split);
720 bio_list_add(&nvmeq->sq_cong, bio);
721 wake_up_process(nvme_thread);
727 * Called with local interrupts disabled and the q_lock held. May not sleep.
729 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
732 struct nvme_iod *iod;
733 int psegs = bio_phys_segments(ns->queue, bio);
736 if ((bio->bi_rw & REQ_FLUSH) && psegs)
737 return nvme_split_flush_data(nvmeq, bio);
739 iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, GFP_ATOMIC);
744 if (bio->bi_rw & REQ_DISCARD) {
747 * We reuse the small pool to allocate the 16-byte range here
748 * as it is not worth having a special pool for these or
749 * additional cases to handle freeing the iod.
751 range = dma_pool_alloc(nvmeq->dev->prp_small_pool,
758 iod_list(iod)[0] = (__le64 *)range;
761 result = nvme_map_bio(nvmeq, iod, bio,
762 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE,
766 if (nvme_setup_prps(nvmeq->dev, iod, result, GFP_ATOMIC) !=
771 nvme_start_io_acct(bio);
773 if (unlikely(nvme_submit_iod(nvmeq, iod))) {
774 if (!waitqueue_active(&nvmeq->sq_full))
775 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
776 list_add_tail(&iod->node, &nvmeq->iod_bio);
781 nvme_free_iod(nvmeq->dev, iod);
785 static int nvme_process_cq(struct nvme_queue *nvmeq)
789 head = nvmeq->cq_head;
790 phase = nvmeq->cq_phase;
794 nvme_completion_fn fn;
795 struct nvme_completion cqe = nvmeq->cqes[head];
796 if ((le16_to_cpu(cqe.status) & 1) != phase)
798 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
799 if (++head == nvmeq->q_depth) {
804 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
805 fn(nvmeq, ctx, &cqe);
808 /* If the controller ignores the cq head doorbell and continuously
809 * writes to the queue, it is theoretically possible to wrap around
810 * the queue twice and mistakenly return IRQ_NONE. Linux only
811 * requires that 0.1% of your interrupts are handled, so this isn't
814 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
817 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
818 nvmeq->cq_head = head;
819 nvmeq->cq_phase = phase;
825 static void nvme_make_request(struct request_queue *q, struct bio *bio)
827 struct nvme_ns *ns = q->queuedata;
828 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
832 bio_endio(bio, -EIO);
836 spin_lock_irq(&nvmeq->q_lock);
837 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
838 result = nvme_submit_bio_queue(nvmeq, ns, bio);
839 if (unlikely(result)) {
840 if (!waitqueue_active(&nvmeq->sq_full))
841 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
842 bio_list_add(&nvmeq->sq_cong, bio);
845 nvme_process_cq(nvmeq);
846 spin_unlock_irq(&nvmeq->q_lock);
850 static irqreturn_t nvme_irq(int irq, void *data)
853 struct nvme_queue *nvmeq = data;
854 spin_lock(&nvmeq->q_lock);
855 nvme_process_cq(nvmeq);
856 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
858 spin_unlock(&nvmeq->q_lock);
862 static irqreturn_t nvme_irq_check(int irq, void *data)
864 struct nvme_queue *nvmeq = data;
865 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
866 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
868 return IRQ_WAKE_THREAD;
871 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
873 spin_lock_irq(&nvmeq->q_lock);
874 cancel_cmdid(nvmeq, cmdid, NULL);
875 spin_unlock_irq(&nvmeq->q_lock);
878 struct sync_cmd_info {
879 struct task_struct *task;
884 static void sync_completion(struct nvme_queue *nvmeq, void *ctx,
885 struct nvme_completion *cqe)
887 struct sync_cmd_info *cmdinfo = ctx;
888 cmdinfo->result = le32_to_cpup(&cqe->result);
889 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
890 wake_up_process(cmdinfo->task);
894 * Returns 0 on success. If the result is negative, it's a Linux error code;
895 * if the result is positive, it's an NVM Express status code
897 static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
898 struct nvme_command *cmd,
899 u32 *result, unsigned timeout)
902 struct sync_cmd_info cmdinfo;
903 struct nvme_queue *nvmeq;
905 nvmeq = lock_nvmeq(dev, q_idx);
909 cmdinfo.task = current;
910 cmdinfo.status = -EINTR;
912 cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
917 cmd->common.command_id = cmdid;
919 set_current_state(TASK_KILLABLE);
920 ret = nvme_submit_cmd(nvmeq, cmd);
922 free_cmdid(nvmeq, cmdid, NULL);
924 set_current_state(TASK_RUNNING);
928 schedule_timeout(timeout);
930 if (cmdinfo.status == -EINTR) {
931 nvmeq = lock_nvmeq(dev, q_idx);
933 nvme_abort_command(nvmeq, cmdid);
940 *result = cmdinfo.result;
942 return cmdinfo.status;
945 static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
946 struct nvme_command *cmd,
947 struct async_cmd_info *cmdinfo, unsigned timeout)
951 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
954 cmdinfo->status = -EINTR;
955 cmd->common.command_id = cmdid;
956 return nvme_submit_cmd(nvmeq, cmd);
959 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
962 return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
965 int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
968 return nvme_submit_sync_cmd(dev, smp_processor_id() + 1, cmd, result,
972 static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
973 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
975 return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
979 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
982 struct nvme_command c;
984 memset(&c, 0, sizeof(c));
985 c.delete_queue.opcode = opcode;
986 c.delete_queue.qid = cpu_to_le16(id);
988 status = nvme_submit_admin_cmd(dev, &c, NULL);
994 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
995 struct nvme_queue *nvmeq)
998 struct nvme_command c;
999 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
1001 memset(&c, 0, sizeof(c));
1002 c.create_cq.opcode = nvme_admin_create_cq;
1003 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1004 c.create_cq.cqid = cpu_to_le16(qid);
1005 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1006 c.create_cq.cq_flags = cpu_to_le16(flags);
1007 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
1009 status = nvme_submit_admin_cmd(dev, &c, NULL);
1015 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1016 struct nvme_queue *nvmeq)
1019 struct nvme_command c;
1020 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
1022 memset(&c, 0, sizeof(c));
1023 c.create_sq.opcode = nvme_admin_create_sq;
1024 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1025 c.create_sq.sqid = cpu_to_le16(qid);
1026 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1027 c.create_sq.sq_flags = cpu_to_le16(flags);
1028 c.create_sq.cqid = cpu_to_le16(qid);
1030 status = nvme_submit_admin_cmd(dev, &c, NULL);
1036 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1038 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1041 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1043 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1046 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
1047 dma_addr_t dma_addr)
1049 struct nvme_command c;
1051 memset(&c, 0, sizeof(c));
1052 c.identify.opcode = nvme_admin_identify;
1053 c.identify.nsid = cpu_to_le32(nsid);
1054 c.identify.prp1 = cpu_to_le64(dma_addr);
1055 c.identify.cns = cpu_to_le32(cns);
1057 return nvme_submit_admin_cmd(dev, &c, NULL);
1060 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
1061 dma_addr_t dma_addr, u32 *result)
1063 struct nvme_command c;
1065 memset(&c, 0, sizeof(c));
1066 c.features.opcode = nvme_admin_get_features;
1067 c.features.nsid = cpu_to_le32(nsid);
1068 c.features.prp1 = cpu_to_le64(dma_addr);
1069 c.features.fid = cpu_to_le32(fid);
1071 return nvme_submit_admin_cmd(dev, &c, result);
1074 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
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_set_features;
1081 c.features.prp1 = cpu_to_le64(dma_addr);
1082 c.features.fid = cpu_to_le32(fid);
1083 c.features.dword11 = cpu_to_le32(dword11);
1085 return nvme_submit_admin_cmd(dev, &c, result);
1089 * nvme_abort_cmd - Attempt aborting a command
1090 * @cmdid: Command id of a timed out IO
1091 * @queue: The queue with timed out IO
1093 * Schedule controller reset if the command was already aborted once before and
1094 * still hasn't been returned to the driver, or if this is the admin queue.
1096 static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1099 struct nvme_command cmd;
1100 struct nvme_dev *dev = nvmeq->dev;
1101 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1102 struct nvme_queue *adminq;
1104 if (!nvmeq->qid || info[cmdid].aborted) {
1105 if (work_busy(&dev->reset_work))
1107 list_del_init(&dev->node);
1108 dev_warn(&dev->pci_dev->dev,
1109 "I/O %d QID %d timeout, reset controller\n", cmdid,
1111 dev->reset_workfn = nvme_reset_failed_dev;
1112 queue_work(nvme_workq, &dev->reset_work);
1116 if (!dev->abort_limit)
1119 adminq = rcu_dereference(dev->queues[0]);
1120 a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
1125 memset(&cmd, 0, sizeof(cmd));
1126 cmd.abort.opcode = nvme_admin_abort_cmd;
1127 cmd.abort.cid = cmdid;
1128 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1129 cmd.abort.command_id = a_cmdid;
1132 info[cmdid].aborted = 1;
1133 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1135 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1137 nvme_submit_cmd(adminq, &cmd);
1141 * nvme_cancel_ios - Cancel outstanding I/Os
1142 * @queue: The queue to cancel I/Os on
1143 * @timeout: True to only cancel I/Os which have timed out
1145 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1147 int depth = nvmeq->q_depth - 1;
1148 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1149 unsigned long now = jiffies;
1152 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1154 nvme_completion_fn fn;
1155 static struct nvme_completion cqe = {
1156 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1159 if (timeout && !time_after(now, info[cmdid].timeout))
1161 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1163 if (timeout && nvmeq->dev->initialized) {
1164 nvme_abort_cmd(cmdid, nvmeq);
1167 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1169 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1170 fn(nvmeq, ctx, &cqe);
1174 static void nvme_free_queue(struct rcu_head *r)
1176 struct nvme_queue *nvmeq = container_of(r, struct nvme_queue, r_head);
1178 spin_lock_irq(&nvmeq->q_lock);
1179 while (bio_list_peek(&nvmeq->sq_cong)) {
1180 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1181 bio_endio(bio, -EIO);
1183 while (!list_empty(&nvmeq->iod_bio)) {
1184 static struct nvme_completion cqe = {
1185 .status = cpu_to_le16(
1186 (NVME_SC_ABORT_REQ | NVME_SC_DNR) << 1),
1188 struct nvme_iod *iod = list_first_entry(&nvmeq->iod_bio,
1191 list_del(&iod->node);
1192 bio_completion(nvmeq, iod, &cqe);
1194 spin_unlock_irq(&nvmeq->q_lock);
1196 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1197 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1198 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1199 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1201 free_cpumask_var(nvmeq->cpu_mask);
1205 static void nvme_free_queues(struct nvme_dev *dev, int lowest)
1209 for (i = dev->queue_count - 1; i >= lowest; i--) {
1210 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
1211 rcu_assign_pointer(dev->queues[i], NULL);
1212 call_rcu(&nvmeq->r_head, nvme_free_queue);
1218 * nvme_suspend_queue - put queue into suspended state
1219 * @nvmeq - queue to suspend
1221 * Returns 1 if already suspended, 0 otherwise.
1223 static int nvme_suspend_queue(struct nvme_queue *nvmeq)
1225 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
1227 spin_lock_irq(&nvmeq->q_lock);
1228 if (nvmeq->q_suspended) {
1229 spin_unlock_irq(&nvmeq->q_lock);
1232 nvmeq->q_suspended = 1;
1233 nvmeq->dev->online_queues--;
1234 spin_unlock_irq(&nvmeq->q_lock);
1236 irq_set_affinity_hint(vector, NULL);
1237 free_irq(vector, nvmeq);
1242 static void nvme_clear_queue(struct nvme_queue *nvmeq)
1244 spin_lock_irq(&nvmeq->q_lock);
1245 nvme_process_cq(nvmeq);
1246 nvme_cancel_ios(nvmeq, false);
1247 spin_unlock_irq(&nvmeq->q_lock);
1250 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1252 struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
1256 if (nvme_suspend_queue(nvmeq))
1259 /* Don't tell the adapter to delete the admin queue.
1260 * Don't tell a removed adapter to delete IO queues. */
1261 if (qid && readl(&dev->bar->csts) != -1) {
1262 adapter_delete_sq(dev, qid);
1263 adapter_delete_cq(dev, qid);
1265 nvme_clear_queue(nvmeq);
1268 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1269 int depth, int vector)
1271 struct device *dmadev = &dev->pci_dev->dev;
1272 unsigned extra = nvme_queue_extra(depth);
1273 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1277 nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1278 &nvmeq->cq_dma_addr, GFP_KERNEL);
1281 memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1283 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1284 &nvmeq->sq_dma_addr, GFP_KERNEL);
1285 if (!nvmeq->sq_cmds)
1288 if (qid && !zalloc_cpumask_var(&nvmeq->cpu_mask, GFP_KERNEL))
1291 nvmeq->q_dmadev = dmadev;
1293 snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1294 dev->instance, qid);
1295 spin_lock_init(&nvmeq->q_lock);
1297 nvmeq->cq_phase = 1;
1298 init_waitqueue_head(&nvmeq->sq_full);
1299 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1300 bio_list_init(&nvmeq->sq_cong);
1301 INIT_LIST_HEAD(&nvmeq->iod_bio);
1302 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1303 nvmeq->q_depth = depth;
1304 nvmeq->cq_vector = vector;
1306 nvmeq->q_suspended = 1;
1308 rcu_assign_pointer(dev->queues[qid], nvmeq);
1313 dma_free_coherent(dmadev, SQ_SIZE(depth), (void *)nvmeq->sq_cmds,
1314 nvmeq->sq_dma_addr);
1316 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1317 nvmeq->cq_dma_addr);
1323 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1326 if (use_threaded_interrupts)
1327 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1328 nvme_irq_check, nvme_irq, IRQF_SHARED,
1330 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1331 IRQF_SHARED, name, nvmeq);
1334 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1336 struct nvme_dev *dev = nvmeq->dev;
1337 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1341 nvmeq->cq_phase = 1;
1342 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1343 memset(nvmeq->cmdid_data, 0, extra);
1344 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1345 nvme_cancel_ios(nvmeq, false);
1346 nvmeq->q_suspended = 0;
1347 dev->online_queues++;
1350 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1352 struct nvme_dev *dev = nvmeq->dev;
1355 result = adapter_alloc_cq(dev, qid, nvmeq);
1359 result = adapter_alloc_sq(dev, qid, nvmeq);
1363 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1367 spin_lock_irq(&nvmeq->q_lock);
1368 nvme_init_queue(nvmeq, qid);
1369 spin_unlock_irq(&nvmeq->q_lock);
1374 adapter_delete_sq(dev, qid);
1376 adapter_delete_cq(dev, qid);
1380 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1382 unsigned long timeout;
1383 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1385 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1387 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1389 if (fatal_signal_pending(current))
1391 if (time_after(jiffies, timeout)) {
1392 dev_err(&dev->pci_dev->dev,
1393 "Device not ready; aborting %s\n", enabled ?
1394 "initialisation" : "reset");
1403 * If the device has been passed off to us in an enabled state, just clear
1404 * the enabled bit. The spec says we should set the 'shutdown notification
1405 * bits', but doing so may cause the device to complete commands to the
1406 * admin queue ... and we don't know what memory that might be pointing at!
1408 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1410 u32 cc = readl(&dev->bar->cc);
1412 if (cc & NVME_CC_ENABLE)
1413 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1414 return nvme_wait_ready(dev, cap, false);
1417 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1419 return nvme_wait_ready(dev, cap, true);
1422 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1424 unsigned long timeout;
1427 cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1428 writel(cc, &dev->bar->cc);
1430 timeout = 2 * HZ + jiffies;
1431 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1432 NVME_CSTS_SHST_CMPLT) {
1434 if (fatal_signal_pending(current))
1436 if (time_after(jiffies, timeout)) {
1437 dev_err(&dev->pci_dev->dev,
1438 "Device shutdown incomplete; abort shutdown\n");
1446 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1450 u64 cap = readq(&dev->bar->cap);
1451 struct nvme_queue *nvmeq;
1453 result = nvme_disable_ctrl(dev, cap);
1457 nvmeq = raw_nvmeq(dev, 0);
1459 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1464 aqa = nvmeq->q_depth - 1;
1467 dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1468 dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1469 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1470 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1472 writel(aqa, &dev->bar->aqa);
1473 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1474 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1475 writel(dev->ctrl_config, &dev->bar->cc);
1477 result = nvme_enable_ctrl(dev, cap);
1481 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
1485 spin_lock_irq(&nvmeq->q_lock);
1486 nvme_init_queue(nvmeq, 0);
1487 spin_unlock_irq(&nvmeq->q_lock);
1491 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1492 unsigned long addr, unsigned length)
1494 int i, err, count, nents, offset;
1495 struct scatterlist *sg;
1496 struct page **pages;
1497 struct nvme_iod *iod;
1500 return ERR_PTR(-EINVAL);
1501 if (!length || length > INT_MAX - PAGE_SIZE)
1502 return ERR_PTR(-EINVAL);
1504 offset = offset_in_page(addr);
1505 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1506 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1508 return ERR_PTR(-ENOMEM);
1510 err = get_user_pages_fast(addr, count, 1, pages);
1518 iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1523 sg_init_table(sg, count);
1524 for (i = 0; i < count; i++) {
1525 sg_set_page(&sg[i], pages[i],
1526 min_t(unsigned, length, PAGE_SIZE - offset),
1528 length -= (PAGE_SIZE - offset);
1531 sg_mark_end(&sg[i - 1]);
1534 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1535 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1545 for (i = 0; i < count; i++)
1548 return ERR_PTR(err);
1551 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1552 struct nvme_iod *iod)
1556 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1557 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1559 for (i = 0; i < iod->nents; i++)
1560 put_page(sg_page(&iod->sg[i]));
1563 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1565 struct nvme_dev *dev = ns->dev;
1566 struct nvme_user_io io;
1567 struct nvme_command c;
1568 unsigned length, meta_len;
1570 struct nvme_iod *iod, *meta_iod = NULL;
1571 dma_addr_t meta_dma_addr;
1572 void *meta, *uninitialized_var(meta_mem);
1574 if (copy_from_user(&io, uio, sizeof(io)))
1576 length = (io.nblocks + 1) << ns->lba_shift;
1577 meta_len = (io.nblocks + 1) * ns->ms;
1579 if (meta_len && ((io.metadata & 3) || !io.metadata))
1582 switch (io.opcode) {
1583 case nvme_cmd_write:
1585 case nvme_cmd_compare:
1586 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1593 return PTR_ERR(iod);
1595 memset(&c, 0, sizeof(c));
1596 c.rw.opcode = io.opcode;
1597 c.rw.flags = io.flags;
1598 c.rw.nsid = cpu_to_le32(ns->ns_id);
1599 c.rw.slba = cpu_to_le64(io.slba);
1600 c.rw.length = cpu_to_le16(io.nblocks);
1601 c.rw.control = cpu_to_le16(io.control);
1602 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1603 c.rw.reftag = cpu_to_le32(io.reftag);
1604 c.rw.apptag = cpu_to_le16(io.apptag);
1605 c.rw.appmask = cpu_to_le16(io.appmask);
1608 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1610 if (IS_ERR(meta_iod)) {
1611 status = PTR_ERR(meta_iod);
1616 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1617 &meta_dma_addr, GFP_KERNEL);
1623 if (io.opcode & 1) {
1624 int meta_offset = 0;
1626 for (i = 0; i < meta_iod->nents; i++) {
1627 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1628 meta_iod->sg[i].offset;
1629 memcpy(meta_mem + meta_offset, meta,
1630 meta_iod->sg[i].length);
1631 kunmap_atomic(meta);
1632 meta_offset += meta_iod->sg[i].length;
1636 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1639 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1640 c.rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1641 c.rw.prp2 = cpu_to_le64(iod->first_dma);
1643 if (length != (io.nblocks + 1) << ns->lba_shift)
1646 status = nvme_submit_io_cmd(dev, &c, NULL);
1649 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1650 int meta_offset = 0;
1652 for (i = 0; i < meta_iod->nents; i++) {
1653 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1654 meta_iod->sg[i].offset;
1655 memcpy(meta, meta_mem + meta_offset,
1656 meta_iod->sg[i].length);
1657 kunmap_atomic(meta);
1658 meta_offset += meta_iod->sg[i].length;
1662 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1667 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1668 nvme_free_iod(dev, iod);
1671 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1672 nvme_free_iod(dev, meta_iod);
1678 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1679 struct nvme_admin_cmd __user *ucmd)
1681 struct nvme_admin_cmd cmd;
1682 struct nvme_command c;
1684 struct nvme_iod *uninitialized_var(iod);
1687 if (!capable(CAP_SYS_ADMIN))
1689 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1692 memset(&c, 0, sizeof(c));
1693 c.common.opcode = cmd.opcode;
1694 c.common.flags = cmd.flags;
1695 c.common.nsid = cpu_to_le32(cmd.nsid);
1696 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1697 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1698 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1699 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1700 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1701 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1702 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1703 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1705 length = cmd.data_len;
1707 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1710 return PTR_ERR(iod);
1711 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1712 c.common.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1713 c.common.prp2 = cpu_to_le64(iod->first_dma);
1716 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1718 if (length != cmd.data_len)
1721 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
1724 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1725 nvme_free_iod(dev, iod);
1728 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1729 sizeof(cmd.result)))
1735 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1738 struct nvme_ns *ns = bdev->bd_disk->private_data;
1742 force_successful_syscall_return();
1744 case NVME_IOCTL_ADMIN_CMD:
1745 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1746 case NVME_IOCTL_SUBMIT_IO:
1747 return nvme_submit_io(ns, (void __user *)arg);
1748 case SG_GET_VERSION_NUM:
1749 return nvme_sg_get_version_num((void __user *)arg);
1751 return nvme_sg_io(ns, (void __user *)arg);
1757 #ifdef CONFIG_COMPAT
1758 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1759 unsigned int cmd, unsigned long arg)
1761 struct nvme_ns *ns = bdev->bd_disk->private_data;
1765 return nvme_sg_io32(ns, arg);
1767 return nvme_ioctl(bdev, mode, cmd, arg);
1770 #define nvme_compat_ioctl NULL
1773 static int nvme_open(struct block_device *bdev, fmode_t mode)
1775 struct nvme_ns *ns = bdev->bd_disk->private_data;
1776 struct nvme_dev *dev = ns->dev;
1778 kref_get(&dev->kref);
1782 static void nvme_free_dev(struct kref *kref);
1784 static void nvme_release(struct gendisk *disk, fmode_t mode)
1786 struct nvme_ns *ns = disk->private_data;
1787 struct nvme_dev *dev = ns->dev;
1789 kref_put(&dev->kref, nvme_free_dev);
1792 static int nvme_getgeo(struct block_device *bd, struct hd_geometry *geo)
1794 /* some standard values */
1795 geo->heads = 1 << 6;
1796 geo->sectors = 1 << 5;
1797 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
1801 static const struct block_device_operations nvme_fops = {
1802 .owner = THIS_MODULE,
1803 .ioctl = nvme_ioctl,
1804 .compat_ioctl = nvme_compat_ioctl,
1806 .release = nvme_release,
1807 .getgeo = nvme_getgeo,
1810 static void nvme_resubmit_iods(struct nvme_queue *nvmeq)
1812 struct nvme_iod *iod, *next;
1814 list_for_each_entry_safe(iod, next, &nvmeq->iod_bio, node) {
1815 if (unlikely(nvme_submit_iod(nvmeq, iod)))
1817 list_del(&iod->node);
1818 if (bio_list_empty(&nvmeq->sq_cong) &&
1819 list_empty(&nvmeq->iod_bio))
1820 remove_wait_queue(&nvmeq->sq_full,
1821 &nvmeq->sq_cong_wait);
1825 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1827 while (bio_list_peek(&nvmeq->sq_cong)) {
1828 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1829 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1831 if (bio_list_empty(&nvmeq->sq_cong) &&
1832 list_empty(&nvmeq->iod_bio))
1833 remove_wait_queue(&nvmeq->sq_full,
1834 &nvmeq->sq_cong_wait);
1835 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1836 if (!waitqueue_active(&nvmeq->sq_full))
1837 add_wait_queue(&nvmeq->sq_full,
1838 &nvmeq->sq_cong_wait);
1839 bio_list_add_head(&nvmeq->sq_cong, bio);
1845 static int nvme_kthread(void *data)
1847 struct nvme_dev *dev, *next;
1849 while (!kthread_should_stop()) {
1850 set_current_state(TASK_INTERRUPTIBLE);
1851 spin_lock(&dev_list_lock);
1852 list_for_each_entry_safe(dev, next, &dev_list, node) {
1854 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1856 if (work_busy(&dev->reset_work))
1858 list_del_init(&dev->node);
1859 dev_warn(&dev->pci_dev->dev,
1860 "Failed status, reset controller\n");
1861 dev->reset_workfn = nvme_reset_failed_dev;
1862 queue_work(nvme_workq, &dev->reset_work);
1866 for (i = 0; i < dev->queue_count; i++) {
1867 struct nvme_queue *nvmeq =
1868 rcu_dereference(dev->queues[i]);
1871 spin_lock_irq(&nvmeq->q_lock);
1872 if (nvmeq->q_suspended)
1874 nvme_process_cq(nvmeq);
1875 nvme_cancel_ios(nvmeq, true);
1876 nvme_resubmit_bios(nvmeq);
1877 nvme_resubmit_iods(nvmeq);
1879 spin_unlock_irq(&nvmeq->q_lock);
1883 spin_unlock(&dev_list_lock);
1884 schedule_timeout(round_jiffies_relative(HZ));
1889 static void nvme_config_discard(struct nvme_ns *ns)
1891 u32 logical_block_size = queue_logical_block_size(ns->queue);
1892 ns->queue->limits.discard_zeroes_data = 0;
1893 ns->queue->limits.discard_alignment = logical_block_size;
1894 ns->queue->limits.discard_granularity = logical_block_size;
1895 ns->queue->limits.max_discard_sectors = 0xffffffff;
1896 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1899 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1900 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1903 struct gendisk *disk;
1906 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1909 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1912 ns->queue = blk_alloc_queue(GFP_KERNEL);
1915 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1916 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1917 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1918 blk_queue_make_request(ns->queue, nvme_make_request);
1920 ns->queue->queuedata = ns;
1922 disk = alloc_disk(0);
1924 goto out_free_queue;
1927 lbaf = id->flbas & 0xf;
1928 ns->lba_shift = id->lbaf[lbaf].ds;
1929 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1930 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1931 if (dev->max_hw_sectors)
1932 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1933 if (dev->vwc & NVME_CTRL_VWC_PRESENT)
1934 blk_queue_flush(ns->queue, REQ_FLUSH | REQ_FUA);
1936 disk->major = nvme_major;
1937 disk->first_minor = 0;
1938 disk->fops = &nvme_fops;
1939 disk->private_data = ns;
1940 disk->queue = ns->queue;
1941 disk->driverfs_dev = &dev->pci_dev->dev;
1942 disk->flags = GENHD_FL_EXT_DEVT;
1943 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1944 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1946 if (dev->oncs & NVME_CTRL_ONCS_DSM)
1947 nvme_config_discard(ns);
1952 blk_cleanup_queue(ns->queue);
1958 static int nvme_find_closest_node(int node)
1960 int n, val, min_val = INT_MAX, best_node = node;
1962 for_each_online_node(n) {
1965 val = node_distance(node, n);
1966 if (val < min_val) {
1974 static void nvme_set_queue_cpus(cpumask_t *qmask, struct nvme_queue *nvmeq,
1978 for_each_cpu(cpu, qmask) {
1979 if (cpumask_weight(nvmeq->cpu_mask) >= count)
1981 if (!cpumask_test_and_set_cpu(cpu, nvmeq->cpu_mask))
1982 *per_cpu_ptr(nvmeq->dev->io_queue, cpu) = nvmeq->qid;
1986 static void nvme_add_cpus(cpumask_t *mask, const cpumask_t *unassigned_cpus,
1987 const cpumask_t *new_mask, struct nvme_queue *nvmeq, int cpus_per_queue)
1990 for_each_cpu(next_cpu, new_mask) {
1991 cpumask_or(mask, mask, get_cpu_mask(next_cpu));
1992 cpumask_or(mask, mask, topology_thread_cpumask(next_cpu));
1993 cpumask_and(mask, mask, unassigned_cpus);
1994 nvme_set_queue_cpus(mask, nvmeq, cpus_per_queue);
1998 static void nvme_create_io_queues(struct nvme_dev *dev)
2002 max = min(dev->max_qid, num_online_cpus());
2003 for (i = dev->queue_count; i <= max; i++)
2004 if (!nvme_alloc_queue(dev, i, dev->q_depth, i - 1))
2007 max = min(dev->queue_count - 1, num_online_cpus());
2008 for (i = dev->online_queues; i <= max; i++)
2009 if (nvme_create_queue(raw_nvmeq(dev, i), i))
2014 * If there are fewer queues than online cpus, this will try to optimally
2015 * assign a queue to multiple cpus by grouping cpus that are "close" together:
2016 * thread siblings, core, socket, closest node, then whatever else is
2019 static void nvme_assign_io_queues(struct nvme_dev *dev)
2021 unsigned cpu, cpus_per_queue, queues, remainder, i;
2022 cpumask_var_t unassigned_cpus;
2024 nvme_create_io_queues(dev);
2026 queues = min(dev->online_queues - 1, num_online_cpus());
2030 cpus_per_queue = num_online_cpus() / queues;
2031 remainder = queues - (num_online_cpus() - queues * cpus_per_queue);
2033 if (!alloc_cpumask_var(&unassigned_cpus, GFP_KERNEL))
2036 cpumask_copy(unassigned_cpus, cpu_online_mask);
2037 cpu = cpumask_first(unassigned_cpus);
2038 for (i = 1; i <= queues; i++) {
2039 struct nvme_queue *nvmeq = lock_nvmeq(dev, i);
2042 cpumask_clear(nvmeq->cpu_mask);
2043 if (!cpumask_weight(unassigned_cpus)) {
2044 unlock_nvmeq(nvmeq);
2048 mask = *get_cpu_mask(cpu);
2049 nvme_set_queue_cpus(&mask, nvmeq, cpus_per_queue);
2050 if (cpus_weight(mask) < cpus_per_queue)
2051 nvme_add_cpus(&mask, unassigned_cpus,
2052 topology_thread_cpumask(cpu),
2053 nvmeq, cpus_per_queue);
2054 if (cpus_weight(mask) < cpus_per_queue)
2055 nvme_add_cpus(&mask, unassigned_cpus,
2056 topology_core_cpumask(cpu),
2057 nvmeq, cpus_per_queue);
2058 if (cpus_weight(mask) < cpus_per_queue)
2059 nvme_add_cpus(&mask, unassigned_cpus,
2060 cpumask_of_node(cpu_to_node(cpu)),
2061 nvmeq, cpus_per_queue);
2062 if (cpus_weight(mask) < cpus_per_queue)
2063 nvme_add_cpus(&mask, unassigned_cpus,
2065 nvme_find_closest_node(
2067 nvmeq, cpus_per_queue);
2068 if (cpus_weight(mask) < cpus_per_queue)
2069 nvme_add_cpus(&mask, unassigned_cpus,
2071 nvmeq, cpus_per_queue);
2073 WARN(cpumask_weight(nvmeq->cpu_mask) != cpus_per_queue,
2074 "nvme%d qid:%d mis-matched queue-to-cpu assignment\n",
2077 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
2079 cpumask_andnot(unassigned_cpus, unassigned_cpus,
2081 cpu = cpumask_next(cpu, unassigned_cpus);
2082 if (remainder && !--remainder)
2084 unlock_nvmeq(nvmeq);
2086 WARN(cpumask_weight(unassigned_cpus), "nvme%d unassigned online cpus\n",
2089 cpumask_andnot(unassigned_cpus, cpu_possible_mask, cpu_online_mask);
2090 for_each_cpu(cpu, unassigned_cpus)
2091 *per_cpu_ptr(dev->io_queue, cpu) = (i++ % queues) + 1;
2092 free_cpumask_var(unassigned_cpus);
2095 static int set_queue_count(struct nvme_dev *dev, int count)
2099 u32 q_count = (count - 1) | ((count - 1) << 16);
2101 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
2106 dev_err(&dev->pci_dev->dev, "Could not set queue count (%d)\n",
2110 return min(result & 0xffff, result >> 16) + 1;
2113 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2115 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
2118 static int nvme_cpu_notify(struct notifier_block *self,
2119 unsigned long action, void *hcpu)
2121 struct nvme_dev *dev = container_of(self, struct nvme_dev, nb);
2125 nvme_assign_io_queues(dev);
2131 static int nvme_setup_io_queues(struct nvme_dev *dev)
2133 struct nvme_queue *adminq = raw_nvmeq(dev, 0);
2134 struct pci_dev *pdev = dev->pci_dev;
2135 int result, i, vecs, nr_io_queues, size;
2137 nr_io_queues = num_possible_cpus();
2138 result = set_queue_count(dev, nr_io_queues);
2141 if (result < nr_io_queues)
2142 nr_io_queues = result;
2144 size = db_bar_size(dev, nr_io_queues);
2148 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2151 if (!--nr_io_queues)
2153 size = db_bar_size(dev, nr_io_queues);
2155 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2156 adminq->q_db = dev->dbs;
2159 /* Deregister the admin queue's interrupt */
2160 free_irq(dev->entry[0].vector, adminq);
2162 for (i = 0; i < nr_io_queues; i++)
2163 dev->entry[i].entry = i;
2164 vecs = pci_enable_msix_range(pdev, dev->entry, 1, nr_io_queues);
2166 vecs = pci_enable_msi_range(pdev, 1, min(nr_io_queues, 32));
2170 for (i = 0; i < vecs; i++)
2171 dev->entry[i].vector = i + pdev->irq;
2176 * Should investigate if there's a performance win from allocating
2177 * more queues than interrupt vectors; it might allow the submission
2178 * path to scale better, even if the receive path is limited by the
2179 * number of interrupts.
2181 nr_io_queues = vecs;
2182 dev->max_qid = nr_io_queues;
2184 result = queue_request_irq(dev, adminq, adminq->irqname);
2186 adminq->q_suspended = 1;
2190 /* Free previously allocated queues that are no longer usable */
2191 nvme_free_queues(dev, nr_io_queues + 1);
2192 nvme_assign_io_queues(dev);
2194 dev->nb.notifier_call = &nvme_cpu_notify;
2195 result = register_hotcpu_notifier(&dev->nb);
2202 nvme_free_queues(dev, 1);
2207 * Return: error value if an error occurred setting up the queues or calling
2208 * Identify Device. 0 if these succeeded, even if adding some of the
2209 * namespaces failed. At the moment, these failures are silent. TBD which
2210 * failures should be reported.
2212 static int nvme_dev_add(struct nvme_dev *dev)
2214 struct pci_dev *pdev = dev->pci_dev;
2218 struct nvme_id_ctrl *ctrl;
2219 struct nvme_id_ns *id_ns;
2221 dma_addr_t dma_addr;
2222 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
2224 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
2228 res = nvme_identify(dev, 0, 1, dma_addr);
2230 dev_err(&pdev->dev, "Identify Controller failed (%d)\n", res);
2236 nn = le32_to_cpup(&ctrl->nn);
2237 dev->oncs = le16_to_cpup(&ctrl->oncs);
2238 dev->abort_limit = ctrl->acl + 1;
2239 dev->vwc = ctrl->vwc;
2240 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2241 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2242 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
2244 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
2245 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2246 (pdev->device == 0x0953) && ctrl->vs[3])
2247 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
2250 for (i = 1; i <= nn; i++) {
2251 res = nvme_identify(dev, i, 0, dma_addr);
2255 if (id_ns->ncap == 0)
2258 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
2259 dma_addr + 4096, NULL);
2261 memset(mem + 4096, 0, 4096);
2263 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
2265 list_add_tail(&ns->list, &dev->namespaces);
2267 list_for_each_entry(ns, &dev->namespaces, list)
2272 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
2276 static int nvme_dev_map(struct nvme_dev *dev)
2279 int bars, result = -ENOMEM;
2280 struct pci_dev *pdev = dev->pci_dev;
2282 if (pci_enable_device_mem(pdev))
2285 dev->entry[0].vector = pdev->irq;
2286 pci_set_master(pdev);
2287 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2288 if (pci_request_selected_regions(pdev, bars, "nvme"))
2291 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2292 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2295 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2298 if (readl(&dev->bar->csts) == -1) {
2302 cap = readq(&dev->bar->cap);
2303 dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2304 dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
2305 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2313 pci_release_regions(pdev);
2315 pci_disable_device(pdev);
2319 static void nvme_dev_unmap(struct nvme_dev *dev)
2321 if (dev->pci_dev->msi_enabled)
2322 pci_disable_msi(dev->pci_dev);
2323 else if (dev->pci_dev->msix_enabled)
2324 pci_disable_msix(dev->pci_dev);
2329 pci_release_regions(dev->pci_dev);
2332 if (pci_is_enabled(dev->pci_dev))
2333 pci_disable_device(dev->pci_dev);
2336 struct nvme_delq_ctx {
2337 struct task_struct *waiter;
2338 struct kthread_worker *worker;
2342 static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2344 dq->waiter = current;
2348 set_current_state(TASK_KILLABLE);
2349 if (!atomic_read(&dq->refcount))
2351 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2352 fatal_signal_pending(current)) {
2353 set_current_state(TASK_RUNNING);
2355 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2356 nvme_disable_queue(dev, 0);
2358 send_sig(SIGKILL, dq->worker->task, 1);
2359 flush_kthread_worker(dq->worker);
2363 set_current_state(TASK_RUNNING);
2366 static void nvme_put_dq(struct nvme_delq_ctx *dq)
2368 atomic_dec(&dq->refcount);
2370 wake_up_process(dq->waiter);
2373 static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2375 atomic_inc(&dq->refcount);
2379 static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2381 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2383 nvme_clear_queue(nvmeq);
2387 static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2388 kthread_work_func_t fn)
2390 struct nvme_command c;
2392 memset(&c, 0, sizeof(c));
2393 c.delete_queue.opcode = opcode;
2394 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2396 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2397 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2400 static void nvme_del_cq_work_handler(struct kthread_work *work)
2402 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2404 nvme_del_queue_end(nvmeq);
2407 static int nvme_delete_cq(struct nvme_queue *nvmeq)
2409 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2410 nvme_del_cq_work_handler);
2413 static void nvme_del_sq_work_handler(struct kthread_work *work)
2415 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2417 int status = nvmeq->cmdinfo.status;
2420 status = nvme_delete_cq(nvmeq);
2422 nvme_del_queue_end(nvmeq);
2425 static int nvme_delete_sq(struct nvme_queue *nvmeq)
2427 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2428 nvme_del_sq_work_handler);
2431 static void nvme_del_queue_start(struct kthread_work *work)
2433 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2435 allow_signal(SIGKILL);
2436 if (nvme_delete_sq(nvmeq))
2437 nvme_del_queue_end(nvmeq);
2440 static void nvme_disable_io_queues(struct nvme_dev *dev)
2443 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2444 struct nvme_delq_ctx dq;
2445 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2446 &worker, "nvme%d", dev->instance);
2448 if (IS_ERR(kworker_task)) {
2449 dev_err(&dev->pci_dev->dev,
2450 "Failed to create queue del task\n");
2451 for (i = dev->queue_count - 1; i > 0; i--)
2452 nvme_disable_queue(dev, i);
2457 atomic_set(&dq.refcount, 0);
2458 dq.worker = &worker;
2459 for (i = dev->queue_count - 1; i > 0; i--) {
2460 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2462 if (nvme_suspend_queue(nvmeq))
2464 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2465 nvmeq->cmdinfo.worker = dq.worker;
2466 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2467 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2469 nvme_wait_dq(&dq, dev);
2470 kthread_stop(kworker_task);
2474 * Remove the node from the device list and check
2475 * for whether or not we need to stop the nvme_thread.
2477 static void nvme_dev_list_remove(struct nvme_dev *dev)
2479 struct task_struct *tmp = NULL;
2481 spin_lock(&dev_list_lock);
2482 list_del_init(&dev->node);
2483 if (list_empty(&dev_list) && !IS_ERR_OR_NULL(nvme_thread)) {
2487 spin_unlock(&dev_list_lock);
2493 static void nvme_dev_shutdown(struct nvme_dev *dev)
2497 dev->initialized = 0;
2498 unregister_hotcpu_notifier(&dev->nb);
2500 nvme_dev_list_remove(dev);
2502 if (!dev->bar || (dev->bar && readl(&dev->bar->csts) == -1)) {
2503 for (i = dev->queue_count - 1; i >= 0; i--) {
2504 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
2505 nvme_suspend_queue(nvmeq);
2506 nvme_clear_queue(nvmeq);
2509 nvme_disable_io_queues(dev);
2510 nvme_shutdown_ctrl(dev);
2511 nvme_disable_queue(dev, 0);
2513 nvme_dev_unmap(dev);
2516 static void nvme_dev_remove(struct nvme_dev *dev)
2520 list_for_each_entry(ns, &dev->namespaces, list) {
2521 if (ns->disk->flags & GENHD_FL_UP)
2522 del_gendisk(ns->disk);
2523 if (!blk_queue_dying(ns->queue))
2524 blk_cleanup_queue(ns->queue);
2528 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2530 struct device *dmadev = &dev->pci_dev->dev;
2531 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2532 PAGE_SIZE, PAGE_SIZE, 0);
2533 if (!dev->prp_page_pool)
2536 /* Optimisation for I/Os between 4k and 128k */
2537 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2539 if (!dev->prp_small_pool) {
2540 dma_pool_destroy(dev->prp_page_pool);
2546 static void nvme_release_prp_pools(struct nvme_dev *dev)
2548 dma_pool_destroy(dev->prp_page_pool);
2549 dma_pool_destroy(dev->prp_small_pool);
2552 static DEFINE_IDA(nvme_instance_ida);
2554 static int nvme_set_instance(struct nvme_dev *dev)
2556 int instance, error;
2559 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2562 spin_lock(&dev_list_lock);
2563 error = ida_get_new(&nvme_instance_ida, &instance);
2564 spin_unlock(&dev_list_lock);
2565 } while (error == -EAGAIN);
2570 dev->instance = instance;
2574 static void nvme_release_instance(struct nvme_dev *dev)
2576 spin_lock(&dev_list_lock);
2577 ida_remove(&nvme_instance_ida, dev->instance);
2578 spin_unlock(&dev_list_lock);
2581 static void nvme_free_namespaces(struct nvme_dev *dev)
2583 struct nvme_ns *ns, *next;
2585 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2586 list_del(&ns->list);
2592 static void nvme_free_dev(struct kref *kref)
2594 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2596 nvme_free_namespaces(dev);
2597 free_percpu(dev->io_queue);
2603 static int nvme_dev_open(struct inode *inode, struct file *f)
2605 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2607 kref_get(&dev->kref);
2608 f->private_data = dev;
2612 static int nvme_dev_release(struct inode *inode, struct file *f)
2614 struct nvme_dev *dev = f->private_data;
2615 kref_put(&dev->kref, nvme_free_dev);
2619 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2621 struct nvme_dev *dev = f->private_data;
2623 case NVME_IOCTL_ADMIN_CMD:
2624 return nvme_user_admin_cmd(dev, (void __user *)arg);
2630 static const struct file_operations nvme_dev_fops = {
2631 .owner = THIS_MODULE,
2632 .open = nvme_dev_open,
2633 .release = nvme_dev_release,
2634 .unlocked_ioctl = nvme_dev_ioctl,
2635 .compat_ioctl = nvme_dev_ioctl,
2638 static int nvme_dev_start(struct nvme_dev *dev)
2641 bool start_thread = false;
2643 result = nvme_dev_map(dev);
2647 result = nvme_configure_admin_queue(dev);
2651 spin_lock(&dev_list_lock);
2652 if (list_empty(&dev_list) && IS_ERR_OR_NULL(nvme_thread)) {
2653 start_thread = true;
2656 list_add(&dev->node, &dev_list);
2657 spin_unlock(&dev_list_lock);
2660 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2661 wake_up(&nvme_kthread_wait);
2663 wait_event_killable(nvme_kthread_wait, nvme_thread);
2665 if (IS_ERR_OR_NULL(nvme_thread)) {
2666 result = nvme_thread ? PTR_ERR(nvme_thread) : -EINTR;
2670 result = nvme_setup_io_queues(dev);
2671 if (result && result != -EBUSY)
2677 nvme_disable_queue(dev, 0);
2678 nvme_dev_list_remove(dev);
2680 nvme_dev_unmap(dev);
2684 static int nvme_remove_dead_ctrl(void *arg)
2686 struct nvme_dev *dev = (struct nvme_dev *)arg;
2687 struct pci_dev *pdev = dev->pci_dev;
2689 if (pci_get_drvdata(pdev))
2690 pci_stop_and_remove_bus_device(pdev);
2691 kref_put(&dev->kref, nvme_free_dev);
2695 static void nvme_remove_disks(struct work_struct *ws)
2697 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2699 nvme_dev_remove(dev);
2700 nvme_free_queues(dev, 1);
2703 static int nvme_dev_resume(struct nvme_dev *dev)
2707 ret = nvme_dev_start(dev);
2708 if (ret && ret != -EBUSY)
2710 if (ret == -EBUSY) {
2711 spin_lock(&dev_list_lock);
2712 dev->reset_workfn = nvme_remove_disks;
2713 queue_work(nvme_workq, &dev->reset_work);
2714 spin_unlock(&dev_list_lock);
2716 dev->initialized = 1;
2720 static void nvme_dev_reset(struct nvme_dev *dev)
2722 nvme_dev_shutdown(dev);
2723 if (nvme_dev_resume(dev)) {
2724 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2725 kref_get(&dev->kref);
2726 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2728 dev_err(&dev->pci_dev->dev,
2729 "Failed to start controller remove task\n");
2730 kref_put(&dev->kref, nvme_free_dev);
2735 static void nvme_reset_failed_dev(struct work_struct *ws)
2737 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2738 nvme_dev_reset(dev);
2741 static void nvme_reset_workfn(struct work_struct *work)
2743 struct nvme_dev *dev = container_of(work, struct nvme_dev, reset_work);
2744 dev->reset_workfn(work);
2747 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2749 int result = -ENOMEM;
2750 struct nvme_dev *dev;
2752 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2755 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2759 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2763 dev->io_queue = alloc_percpu(unsigned short);
2767 INIT_LIST_HEAD(&dev->namespaces);
2768 dev->reset_workfn = nvme_reset_failed_dev;
2769 INIT_WORK(&dev->reset_work, nvme_reset_workfn);
2770 dev->pci_dev = pdev;
2771 pci_set_drvdata(pdev, dev);
2772 result = nvme_set_instance(dev);
2776 result = nvme_setup_prp_pools(dev);
2780 kref_init(&dev->kref);
2781 result = nvme_dev_start(dev);
2783 if (result == -EBUSY)
2788 result = nvme_dev_add(dev);
2793 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2794 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2795 dev->miscdev.parent = &pdev->dev;
2796 dev->miscdev.name = dev->name;
2797 dev->miscdev.fops = &nvme_dev_fops;
2798 result = misc_register(&dev->miscdev);
2802 dev->initialized = 1;
2806 nvme_dev_remove(dev);
2807 nvme_free_namespaces(dev);
2809 nvme_dev_shutdown(dev);
2811 nvme_free_queues(dev, 0);
2812 nvme_release_prp_pools(dev);
2814 nvme_release_instance(dev);
2816 free_percpu(dev->io_queue);
2823 static void nvme_shutdown(struct pci_dev *pdev)
2825 struct nvme_dev *dev = pci_get_drvdata(pdev);
2826 nvme_dev_shutdown(dev);
2829 static void nvme_remove(struct pci_dev *pdev)
2831 struct nvme_dev *dev = pci_get_drvdata(pdev);
2833 spin_lock(&dev_list_lock);
2834 list_del_init(&dev->node);
2835 spin_unlock(&dev_list_lock);
2837 pci_set_drvdata(pdev, NULL);
2838 flush_work(&dev->reset_work);
2839 misc_deregister(&dev->miscdev);
2840 nvme_dev_remove(dev);
2841 nvme_dev_shutdown(dev);
2842 nvme_free_queues(dev, 0);
2844 nvme_release_instance(dev);
2845 nvme_release_prp_pools(dev);
2846 kref_put(&dev->kref, nvme_free_dev);
2849 /* These functions are yet to be implemented */
2850 #define nvme_error_detected NULL
2851 #define nvme_dump_registers NULL
2852 #define nvme_link_reset NULL
2853 #define nvme_slot_reset NULL
2854 #define nvme_error_resume NULL
2856 #ifdef CONFIG_PM_SLEEP
2857 static int nvme_suspend(struct device *dev)
2859 struct pci_dev *pdev = to_pci_dev(dev);
2860 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2862 nvme_dev_shutdown(ndev);
2866 static int nvme_resume(struct device *dev)
2868 struct pci_dev *pdev = to_pci_dev(dev);
2869 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2871 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2872 ndev->reset_workfn = nvme_reset_failed_dev;
2873 queue_work(nvme_workq, &ndev->reset_work);
2879 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2881 static const struct pci_error_handlers nvme_err_handler = {
2882 .error_detected = nvme_error_detected,
2883 .mmio_enabled = nvme_dump_registers,
2884 .link_reset = nvme_link_reset,
2885 .slot_reset = nvme_slot_reset,
2886 .resume = nvme_error_resume,
2889 /* Move to pci_ids.h later */
2890 #define PCI_CLASS_STORAGE_EXPRESS 0x010802
2892 static const struct pci_device_id nvme_id_table[] = {
2893 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2896 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2898 static struct pci_driver nvme_driver = {
2900 .id_table = nvme_id_table,
2901 .probe = nvme_probe,
2902 .remove = nvme_remove,
2903 .shutdown = nvme_shutdown,
2905 .pm = &nvme_dev_pm_ops,
2907 .err_handler = &nvme_err_handler,
2910 static int __init nvme_init(void)
2914 init_waitqueue_head(&nvme_kthread_wait);
2916 nvme_workq = create_singlethread_workqueue("nvme");
2920 result = register_blkdev(nvme_major, "nvme");
2923 else if (result > 0)
2924 nvme_major = result;
2926 result = pci_register_driver(&nvme_driver);
2928 goto unregister_blkdev;
2932 unregister_blkdev(nvme_major, "nvme");
2934 destroy_workqueue(nvme_workq);
2938 static void __exit nvme_exit(void)
2940 pci_unregister_driver(&nvme_driver);
2941 unregister_blkdev(nvme_major, "nvme");
2942 destroy_workqueue(nvme_workq);
2943 BUG_ON(nvme_thread && !IS_ERR(nvme_thread));
2947 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2948 MODULE_LICENSE("GPL");
2949 MODULE_VERSION("0.9");
2950 module_init(nvme_init);
2951 module_exit(nvme_exit);