NVMe: Schedule reset for failed controllers
[linux-2.6-block.git] / drivers / block / nvme-core.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011, Intel Corporation.
4  *
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.
8  *
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
12  * more details.
13  *
14  * You should have received a copy of the GNU General Public License along with
15  * this program; if not, write to the Free Software Foundation, Inc.,
16  * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA.
17  */
18
19 #include <linux/nvme.h>
20 #include <linux/bio.h>
21 #include <linux/bitops.h>
22 #include <linux/blkdev.h>
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/fs.h>
26 #include <linux/genhd.h>
27 #include <linux/idr.h>
28 #include <linux/init.h>
29 #include <linux/interrupt.h>
30 #include <linux/io.h>
31 #include <linux/kdev_t.h>
32 #include <linux/kthread.h>
33 #include <linux/kernel.h>
34 #include <linux/mm.h>
35 #include <linux/module.h>
36 #include <linux/moduleparam.h>
37 #include <linux/pci.h>
38 #include <linux/poison.h>
39 #include <linux/ptrace.h>
40 #include <linux/sched.h>
41 #include <linux/slab.h>
42 #include <linux/types.h>
43 #include <scsi/sg.h>
44 #include <asm-generic/io-64-nonatomic-lo-hi.h>
45
46 #define NVME_Q_DEPTH 1024
47 #define SQ_SIZE(depth)          (depth * sizeof(struct nvme_command))
48 #define CQ_SIZE(depth)          (depth * sizeof(struct nvme_completion))
49 #define NVME_MINORS 64
50 #define ADMIN_TIMEOUT   (60 * HZ)
51
52 static int nvme_major;
53 module_param(nvme_major, int, 0);
54
55 static int use_threaded_interrupts;
56 module_param(use_threaded_interrupts, int, 0);
57
58 static DEFINE_SPINLOCK(dev_list_lock);
59 static LIST_HEAD(dev_list);
60 static struct task_struct *nvme_thread;
61 static struct workqueue_struct *nvme_workq;
62
63 static void nvme_reset_failed_dev(struct work_struct *ws);
64
65 /*
66  * An NVM Express queue.  Each device has at least two (one for admin
67  * commands and one for I/O commands).
68  */
69 struct nvme_queue {
70         struct device *q_dmadev;
71         struct nvme_dev *dev;
72         spinlock_t q_lock;
73         struct nvme_command *sq_cmds;
74         volatile struct nvme_completion *cqes;
75         dma_addr_t sq_dma_addr;
76         dma_addr_t cq_dma_addr;
77         wait_queue_head_t sq_full;
78         wait_queue_t sq_cong_wait;
79         struct bio_list sq_cong;
80         u32 __iomem *q_db;
81         u16 q_depth;
82         u16 cq_vector;
83         u16 sq_head;
84         u16 sq_tail;
85         u16 cq_head;
86         u8 cq_phase;
87         u8 cqe_seen;
88         u8 q_suspended;
89         unsigned long cmdid_data[];
90 };
91
92 /*
93  * Check we didin't inadvertently grow the command struct
94  */
95 static inline void _nvme_check_size(void)
96 {
97         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
98         BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
99         BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
100         BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
101         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
102         BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
103         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
104         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
105         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
106         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
107         BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
108 }
109
110 typedef void (*nvme_completion_fn)(struct nvme_dev *, void *,
111                                                 struct nvme_completion *);
112
113 struct nvme_cmd_info {
114         nvme_completion_fn fn;
115         void *ctx;
116         unsigned long timeout;
117 };
118
119 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
120 {
121         return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
122 }
123
124 static unsigned nvme_queue_extra(int depth)
125 {
126         return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
127 }
128
129 /**
130  * alloc_cmdid() - Allocate a Command ID
131  * @nvmeq: The queue that will be used for this command
132  * @ctx: A pointer that will be passed to the handler
133  * @handler: The function to call on completion
134  *
135  * Allocate a Command ID for a queue.  The data passed in will
136  * be passed to the completion handler.  This is implemented by using
137  * the bottom two bits of the ctx pointer to store the handler ID.
138  * Passing in a pointer that's not 4-byte aligned will cause a BUG.
139  * We can change this if it becomes a problem.
140  *
141  * May be called with local interrupts disabled and the q_lock held,
142  * or with interrupts enabled and no locks held.
143  */
144 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
145                                 nvme_completion_fn handler, unsigned timeout)
146 {
147         int depth = nvmeq->q_depth - 1;
148         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
149         int cmdid;
150
151         do {
152                 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
153                 if (cmdid >= depth)
154                         return -EBUSY;
155         } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
156
157         info[cmdid].fn = handler;
158         info[cmdid].ctx = ctx;
159         info[cmdid].timeout = jiffies + timeout;
160         return cmdid;
161 }
162
163 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
164                                 nvme_completion_fn handler, unsigned timeout)
165 {
166         int cmdid;
167         wait_event_killable(nvmeq->sq_full,
168                 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
169         return (cmdid < 0) ? -EINTR : cmdid;
170 }
171
172 /* Special values must be less than 0x1000 */
173 #define CMD_CTX_BASE            ((void *)POISON_POINTER_DELTA)
174 #define CMD_CTX_CANCELLED       (0x30C + CMD_CTX_BASE)
175 #define CMD_CTX_COMPLETED       (0x310 + CMD_CTX_BASE)
176 #define CMD_CTX_INVALID         (0x314 + CMD_CTX_BASE)
177 #define CMD_CTX_FLUSH           (0x318 + CMD_CTX_BASE)
178
179 static void special_completion(struct nvme_dev *dev, void *ctx,
180                                                 struct nvme_completion *cqe)
181 {
182         if (ctx == CMD_CTX_CANCELLED)
183                 return;
184         if (ctx == CMD_CTX_FLUSH)
185                 return;
186         if (ctx == CMD_CTX_COMPLETED) {
187                 dev_warn(&dev->pci_dev->dev,
188                                 "completed id %d twice on queue %d\n",
189                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
190                 return;
191         }
192         if (ctx == CMD_CTX_INVALID) {
193                 dev_warn(&dev->pci_dev->dev,
194                                 "invalid id %d completed on queue %d\n",
195                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
196                 return;
197         }
198
199         dev_warn(&dev->pci_dev->dev, "Unknown special completion %p\n", ctx);
200 }
201
202 /*
203  * Called with local interrupts disabled and the q_lock held.  May not sleep.
204  */
205 static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
206                                                 nvme_completion_fn *fn)
207 {
208         void *ctx;
209         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
210
211         if (cmdid >= nvmeq->q_depth) {
212                 *fn = special_completion;
213                 return CMD_CTX_INVALID;
214         }
215         if (fn)
216                 *fn = info[cmdid].fn;
217         ctx = info[cmdid].ctx;
218         info[cmdid].fn = special_completion;
219         info[cmdid].ctx = CMD_CTX_COMPLETED;
220         clear_bit(cmdid, nvmeq->cmdid_data);
221         wake_up(&nvmeq->sq_full);
222         return ctx;
223 }
224
225 static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
226                                                 nvme_completion_fn *fn)
227 {
228         void *ctx;
229         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
230         if (fn)
231                 *fn = info[cmdid].fn;
232         ctx = info[cmdid].ctx;
233         info[cmdid].fn = special_completion;
234         info[cmdid].ctx = CMD_CTX_CANCELLED;
235         return ctx;
236 }
237
238 struct nvme_queue *get_nvmeq(struct nvme_dev *dev)
239 {
240         return dev->queues[get_cpu() + 1];
241 }
242
243 void put_nvmeq(struct nvme_queue *nvmeq)
244 {
245         put_cpu();
246 }
247
248 /**
249  * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
250  * @nvmeq: The queue to use
251  * @cmd: The command to send
252  *
253  * Safe to use from interrupt context
254  */
255 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
256 {
257         unsigned long flags;
258         u16 tail;
259         spin_lock_irqsave(&nvmeq->q_lock, flags);
260         tail = nvmeq->sq_tail;
261         memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
262         if (++tail == nvmeq->q_depth)
263                 tail = 0;
264         writel(tail, nvmeq->q_db);
265         nvmeq->sq_tail = tail;
266         spin_unlock_irqrestore(&nvmeq->q_lock, flags);
267
268         return 0;
269 }
270
271 static __le64 **iod_list(struct nvme_iod *iod)
272 {
273         return ((void *)iod) + iod->offset;
274 }
275
276 /*
277  * Will slightly overestimate the number of pages needed.  This is OK
278  * as it only leads to a small amount of wasted memory for the lifetime of
279  * the I/O.
280  */
281 static int nvme_npages(unsigned size)
282 {
283         unsigned nprps = DIV_ROUND_UP(size + PAGE_SIZE, PAGE_SIZE);
284         return DIV_ROUND_UP(8 * nprps, PAGE_SIZE - 8);
285 }
286
287 static struct nvme_iod *
288 nvme_alloc_iod(unsigned nseg, unsigned nbytes, gfp_t gfp)
289 {
290         struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
291                                 sizeof(__le64 *) * nvme_npages(nbytes) +
292                                 sizeof(struct scatterlist) * nseg, gfp);
293
294         if (iod) {
295                 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
296                 iod->npages = -1;
297                 iod->length = nbytes;
298                 iod->nents = 0;
299                 iod->start_time = jiffies;
300         }
301
302         return iod;
303 }
304
305 void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
306 {
307         const int last_prp = PAGE_SIZE / 8 - 1;
308         int i;
309         __le64 **list = iod_list(iod);
310         dma_addr_t prp_dma = iod->first_dma;
311
312         if (iod->npages == 0)
313                 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
314         for (i = 0; i < iod->npages; i++) {
315                 __le64 *prp_list = list[i];
316                 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
317                 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
318                 prp_dma = next_prp_dma;
319         }
320         kfree(iod);
321 }
322
323 static void nvme_start_io_acct(struct bio *bio)
324 {
325         struct gendisk *disk = bio->bi_bdev->bd_disk;
326         const int rw = bio_data_dir(bio);
327         int cpu = part_stat_lock();
328         part_round_stats(cpu, &disk->part0);
329         part_stat_inc(cpu, &disk->part0, ios[rw]);
330         part_stat_add(cpu, &disk->part0, sectors[rw], bio_sectors(bio));
331         part_inc_in_flight(&disk->part0, rw);
332         part_stat_unlock();
333 }
334
335 static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
336 {
337         struct gendisk *disk = bio->bi_bdev->bd_disk;
338         const int rw = bio_data_dir(bio);
339         unsigned long duration = jiffies - start_time;
340         int cpu = part_stat_lock();
341         part_stat_add(cpu, &disk->part0, ticks[rw], duration);
342         part_round_stats(cpu, &disk->part0);
343         part_dec_in_flight(&disk->part0, rw);
344         part_stat_unlock();
345 }
346
347 static void bio_completion(struct nvme_dev *dev, void *ctx,
348                                                 struct nvme_completion *cqe)
349 {
350         struct nvme_iod *iod = ctx;
351         struct bio *bio = iod->private;
352         u16 status = le16_to_cpup(&cqe->status) >> 1;
353
354         if (iod->nents) {
355                 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
356                         bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
357                 nvme_end_io_acct(bio, iod->start_time);
358         }
359         nvme_free_iod(dev, iod);
360         if (status)
361                 bio_endio(bio, -EIO);
362         else
363                 bio_endio(bio, 0);
364 }
365
366 /* length is in bytes.  gfp flags indicates whether we may sleep. */
367 int nvme_setup_prps(struct nvme_dev *dev, struct nvme_common_command *cmd,
368                         struct nvme_iod *iod, int total_len, gfp_t gfp)
369 {
370         struct dma_pool *pool;
371         int length = total_len;
372         struct scatterlist *sg = iod->sg;
373         int dma_len = sg_dma_len(sg);
374         u64 dma_addr = sg_dma_address(sg);
375         int offset = offset_in_page(dma_addr);
376         __le64 *prp_list;
377         __le64 **list = iod_list(iod);
378         dma_addr_t prp_dma;
379         int nprps, i;
380
381         cmd->prp1 = cpu_to_le64(dma_addr);
382         length -= (PAGE_SIZE - offset);
383         if (length <= 0)
384                 return total_len;
385
386         dma_len -= (PAGE_SIZE - offset);
387         if (dma_len) {
388                 dma_addr += (PAGE_SIZE - offset);
389         } else {
390                 sg = sg_next(sg);
391                 dma_addr = sg_dma_address(sg);
392                 dma_len = sg_dma_len(sg);
393         }
394
395         if (length <= PAGE_SIZE) {
396                 cmd->prp2 = cpu_to_le64(dma_addr);
397                 return total_len;
398         }
399
400         nprps = DIV_ROUND_UP(length, PAGE_SIZE);
401         if (nprps <= (256 / 8)) {
402                 pool = dev->prp_small_pool;
403                 iod->npages = 0;
404         } else {
405                 pool = dev->prp_page_pool;
406                 iod->npages = 1;
407         }
408
409         prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
410         if (!prp_list) {
411                 cmd->prp2 = cpu_to_le64(dma_addr);
412                 iod->npages = -1;
413                 return (total_len - length) + PAGE_SIZE;
414         }
415         list[0] = prp_list;
416         iod->first_dma = prp_dma;
417         cmd->prp2 = cpu_to_le64(prp_dma);
418         i = 0;
419         for (;;) {
420                 if (i == PAGE_SIZE / 8) {
421                         __le64 *old_prp_list = prp_list;
422                         prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
423                         if (!prp_list)
424                                 return total_len - length;
425                         list[iod->npages++] = prp_list;
426                         prp_list[0] = old_prp_list[i - 1];
427                         old_prp_list[i - 1] = cpu_to_le64(prp_dma);
428                         i = 1;
429                 }
430                 prp_list[i++] = cpu_to_le64(dma_addr);
431                 dma_len -= PAGE_SIZE;
432                 dma_addr += PAGE_SIZE;
433                 length -= PAGE_SIZE;
434                 if (length <= 0)
435                         break;
436                 if (dma_len > 0)
437                         continue;
438                 BUG_ON(dma_len < 0);
439                 sg = sg_next(sg);
440                 dma_addr = sg_dma_address(sg);
441                 dma_len = sg_dma_len(sg);
442         }
443
444         return total_len;
445 }
446
447 struct nvme_bio_pair {
448         struct bio b1, b2, *parent;
449         struct bio_vec *bv1, *bv2;
450         int err;
451         atomic_t cnt;
452 };
453
454 static void nvme_bio_pair_endio(struct bio *bio, int err)
455 {
456         struct nvme_bio_pair *bp = bio->bi_private;
457
458         if (err)
459                 bp->err = err;
460
461         if (atomic_dec_and_test(&bp->cnt)) {
462                 bio_endio(bp->parent, bp->err);
463                 kfree(bp->bv1);
464                 kfree(bp->bv2);
465                 kfree(bp);
466         }
467 }
468
469 static struct nvme_bio_pair *nvme_bio_split(struct bio *bio, int idx,
470                                                         int len, int offset)
471 {
472         struct nvme_bio_pair *bp;
473
474         BUG_ON(len > bio->bi_size);
475         BUG_ON(idx > bio->bi_vcnt);
476
477         bp = kmalloc(sizeof(*bp), GFP_ATOMIC);
478         if (!bp)
479                 return NULL;
480         bp->err = 0;
481
482         bp->b1 = *bio;
483         bp->b2 = *bio;
484
485         bp->b1.bi_size = len;
486         bp->b2.bi_size -= len;
487         bp->b1.bi_vcnt = idx;
488         bp->b2.bi_idx = idx;
489         bp->b2.bi_sector += len >> 9;
490
491         if (offset) {
492                 bp->bv1 = kmalloc(bio->bi_max_vecs * sizeof(struct bio_vec),
493                                                                 GFP_ATOMIC);
494                 if (!bp->bv1)
495                         goto split_fail_1;
496
497                 bp->bv2 = kmalloc(bio->bi_max_vecs * sizeof(struct bio_vec),
498                                                                 GFP_ATOMIC);
499                 if (!bp->bv2)
500                         goto split_fail_2;
501
502                 memcpy(bp->bv1, bio->bi_io_vec,
503                         bio->bi_max_vecs * sizeof(struct bio_vec));
504                 memcpy(bp->bv2, bio->bi_io_vec,
505                         bio->bi_max_vecs * sizeof(struct bio_vec));
506
507                 bp->b1.bi_io_vec = bp->bv1;
508                 bp->b2.bi_io_vec = bp->bv2;
509                 bp->b2.bi_io_vec[idx].bv_offset += offset;
510                 bp->b2.bi_io_vec[idx].bv_len -= offset;
511                 bp->b1.bi_io_vec[idx].bv_len = offset;
512                 bp->b1.bi_vcnt++;
513         } else
514                 bp->bv1 = bp->bv2 = NULL;
515
516         bp->b1.bi_private = bp;
517         bp->b2.bi_private = bp;
518
519         bp->b1.bi_end_io = nvme_bio_pair_endio;
520         bp->b2.bi_end_io = nvme_bio_pair_endio;
521
522         bp->parent = bio;
523         atomic_set(&bp->cnt, 2);
524
525         return bp;
526
527  split_fail_2:
528         kfree(bp->bv1);
529  split_fail_1:
530         kfree(bp);
531         return NULL;
532 }
533
534 static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
535                                                 int idx, int len, int offset)
536 {
537         struct nvme_bio_pair *bp = nvme_bio_split(bio, idx, len, offset);
538         if (!bp)
539                 return -ENOMEM;
540
541         if (bio_list_empty(&nvmeq->sq_cong))
542                 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
543         bio_list_add(&nvmeq->sq_cong, &bp->b1);
544         bio_list_add(&nvmeq->sq_cong, &bp->b2);
545
546         return 0;
547 }
548
549 /* NVMe scatterlists require no holes in the virtual address */
550 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2)   ((vec2)->bv_offset || \
551                         (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
552
553 static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
554                 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
555 {
556         struct bio_vec *bvec, *bvprv = NULL;
557         struct scatterlist *sg = NULL;
558         int i, length = 0, nsegs = 0, split_len = bio->bi_size;
559
560         if (nvmeq->dev->stripe_size)
561                 split_len = nvmeq->dev->stripe_size -
562                         ((bio->bi_sector << 9) & (nvmeq->dev->stripe_size - 1));
563
564         sg_init_table(iod->sg, psegs);
565         bio_for_each_segment(bvec, bio, i) {
566                 if (bvprv && BIOVEC_PHYS_MERGEABLE(bvprv, bvec)) {
567                         sg->length += bvec->bv_len;
568                 } else {
569                         if (bvprv && BIOVEC_NOT_VIRT_MERGEABLE(bvprv, bvec))
570                                 return nvme_split_and_submit(bio, nvmeq, i,
571                                                                 length, 0);
572
573                         sg = sg ? sg + 1 : iod->sg;
574                         sg_set_page(sg, bvec->bv_page, bvec->bv_len,
575                                                         bvec->bv_offset);
576                         nsegs++;
577                 }
578
579                 if (split_len - length < bvec->bv_len)
580                         return nvme_split_and_submit(bio, nvmeq, i, split_len,
581                                                         split_len - length);
582                 length += bvec->bv_len;
583                 bvprv = bvec;
584         }
585         iod->nents = nsegs;
586         sg_mark_end(sg);
587         if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
588                 return -ENOMEM;
589
590         BUG_ON(length != bio->bi_size);
591         return length;
592 }
593
594 /*
595  * We reuse the small pool to allocate the 16-byte range here as it is not
596  * worth having a special pool for these or additional cases to handle freeing
597  * the iod.
598  */
599 static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
600                 struct bio *bio, struct nvme_iod *iod, int cmdid)
601 {
602         struct nvme_dsm_range *range;
603         struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
604
605         range = dma_pool_alloc(nvmeq->dev->prp_small_pool, GFP_ATOMIC,
606                                                         &iod->first_dma);
607         if (!range)
608                 return -ENOMEM;
609
610         iod_list(iod)[0] = (__le64 *)range;
611         iod->npages = 0;
612
613         range->cattr = cpu_to_le32(0);
614         range->nlb = cpu_to_le32(bio->bi_size >> ns->lba_shift);
615         range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_sector));
616
617         memset(cmnd, 0, sizeof(*cmnd));
618         cmnd->dsm.opcode = nvme_cmd_dsm;
619         cmnd->dsm.command_id = cmdid;
620         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
621         cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
622         cmnd->dsm.nr = 0;
623         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
624
625         if (++nvmeq->sq_tail == nvmeq->q_depth)
626                 nvmeq->sq_tail = 0;
627         writel(nvmeq->sq_tail, nvmeq->q_db);
628
629         return 0;
630 }
631
632 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
633                                                                 int cmdid)
634 {
635         struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
636
637         memset(cmnd, 0, sizeof(*cmnd));
638         cmnd->common.opcode = nvme_cmd_flush;
639         cmnd->common.command_id = cmdid;
640         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
641
642         if (++nvmeq->sq_tail == nvmeq->q_depth)
643                 nvmeq->sq_tail = 0;
644         writel(nvmeq->sq_tail, nvmeq->q_db);
645
646         return 0;
647 }
648
649 int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
650 {
651         int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
652                                         special_completion, NVME_IO_TIMEOUT);
653         if (unlikely(cmdid < 0))
654                 return cmdid;
655
656         return nvme_submit_flush(nvmeq, ns, cmdid);
657 }
658
659 /*
660  * Called with local interrupts disabled and the q_lock held.  May not sleep.
661  */
662 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
663                                                                 struct bio *bio)
664 {
665         struct nvme_command *cmnd;
666         struct nvme_iod *iod;
667         enum dma_data_direction dma_dir;
668         int cmdid, length, result;
669         u16 control;
670         u32 dsmgmt;
671         int psegs = bio_phys_segments(ns->queue, bio);
672
673         if ((bio->bi_rw & REQ_FLUSH) && psegs) {
674                 result = nvme_submit_flush_data(nvmeq, ns);
675                 if (result)
676                         return result;
677         }
678
679         result = -ENOMEM;
680         iod = nvme_alloc_iod(psegs, bio->bi_size, GFP_ATOMIC);
681         if (!iod)
682                 goto nomem;
683         iod->private = bio;
684
685         result = -EBUSY;
686         cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
687         if (unlikely(cmdid < 0))
688                 goto free_iod;
689
690         if (bio->bi_rw & REQ_DISCARD) {
691                 result = nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
692                 if (result)
693                         goto free_cmdid;
694                 return result;
695         }
696         if ((bio->bi_rw & REQ_FLUSH) && !psegs)
697                 return nvme_submit_flush(nvmeq, ns, cmdid);
698
699         control = 0;
700         if (bio->bi_rw & REQ_FUA)
701                 control |= NVME_RW_FUA;
702         if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
703                 control |= NVME_RW_LR;
704
705         dsmgmt = 0;
706         if (bio->bi_rw & REQ_RAHEAD)
707                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
708
709         cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
710
711         memset(cmnd, 0, sizeof(*cmnd));
712         if (bio_data_dir(bio)) {
713                 cmnd->rw.opcode = nvme_cmd_write;
714                 dma_dir = DMA_TO_DEVICE;
715         } else {
716                 cmnd->rw.opcode = nvme_cmd_read;
717                 dma_dir = DMA_FROM_DEVICE;
718         }
719
720         result = nvme_map_bio(nvmeq, iod, bio, dma_dir, psegs);
721         if (result <= 0)
722                 goto free_cmdid;
723         length = result;
724
725         cmnd->rw.command_id = cmdid;
726         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
727         length = nvme_setup_prps(nvmeq->dev, &cmnd->common, iod, length,
728                                                                 GFP_ATOMIC);
729         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_sector));
730         cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
731         cmnd->rw.control = cpu_to_le16(control);
732         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
733
734         nvme_start_io_acct(bio);
735         if (++nvmeq->sq_tail == nvmeq->q_depth)
736                 nvmeq->sq_tail = 0;
737         writel(nvmeq->sq_tail, nvmeq->q_db);
738
739         return 0;
740
741  free_cmdid:
742         free_cmdid(nvmeq, cmdid, NULL);
743  free_iod:
744         nvme_free_iod(nvmeq->dev, iod);
745  nomem:
746         return result;
747 }
748
749 static int nvme_process_cq(struct nvme_queue *nvmeq)
750 {
751         u16 head, phase;
752
753         head = nvmeq->cq_head;
754         phase = nvmeq->cq_phase;
755
756         for (;;) {
757                 void *ctx;
758                 nvme_completion_fn fn;
759                 struct nvme_completion cqe = nvmeq->cqes[head];
760                 if ((le16_to_cpu(cqe.status) & 1) != phase)
761                         break;
762                 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
763                 if (++head == nvmeq->q_depth) {
764                         head = 0;
765                         phase = !phase;
766                 }
767
768                 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
769                 fn(nvmeq->dev, ctx, &cqe);
770         }
771
772         /* If the controller ignores the cq head doorbell and continuously
773          * writes to the queue, it is theoretically possible to wrap around
774          * the queue twice and mistakenly return IRQ_NONE.  Linux only
775          * requires that 0.1% of your interrupts are handled, so this isn't
776          * a big problem.
777          */
778         if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
779                 return 0;
780
781         writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
782         nvmeq->cq_head = head;
783         nvmeq->cq_phase = phase;
784
785         nvmeq->cqe_seen = 1;
786         return 1;
787 }
788
789 static void nvme_make_request(struct request_queue *q, struct bio *bio)
790 {
791         struct nvme_ns *ns = q->queuedata;
792         struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
793         int result = -EBUSY;
794
795         if (!nvmeq) {
796                 put_nvmeq(NULL);
797                 bio_endio(bio, -EIO);
798                 return;
799         }
800
801         spin_lock_irq(&nvmeq->q_lock);
802         if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
803                 result = nvme_submit_bio_queue(nvmeq, ns, bio);
804         if (unlikely(result)) {
805                 if (bio_list_empty(&nvmeq->sq_cong))
806                         add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
807                 bio_list_add(&nvmeq->sq_cong, bio);
808         }
809
810         nvme_process_cq(nvmeq);
811         spin_unlock_irq(&nvmeq->q_lock);
812         put_nvmeq(nvmeq);
813 }
814
815 static irqreturn_t nvme_irq(int irq, void *data)
816 {
817         irqreturn_t result;
818         struct nvme_queue *nvmeq = data;
819         spin_lock(&nvmeq->q_lock);
820         nvme_process_cq(nvmeq);
821         result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
822         nvmeq->cqe_seen = 0;
823         spin_unlock(&nvmeq->q_lock);
824         return result;
825 }
826
827 static irqreturn_t nvme_irq_check(int irq, void *data)
828 {
829         struct nvme_queue *nvmeq = data;
830         struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
831         if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
832                 return IRQ_NONE;
833         return IRQ_WAKE_THREAD;
834 }
835
836 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
837 {
838         spin_lock_irq(&nvmeq->q_lock);
839         cancel_cmdid(nvmeq, cmdid, NULL);
840         spin_unlock_irq(&nvmeq->q_lock);
841 }
842
843 struct sync_cmd_info {
844         struct task_struct *task;
845         u32 result;
846         int status;
847 };
848
849 static void sync_completion(struct nvme_dev *dev, void *ctx,
850                                                 struct nvme_completion *cqe)
851 {
852         struct sync_cmd_info *cmdinfo = ctx;
853         cmdinfo->result = le32_to_cpup(&cqe->result);
854         cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
855         wake_up_process(cmdinfo->task);
856 }
857
858 /*
859  * Returns 0 on success.  If the result is negative, it's a Linux error code;
860  * if the result is positive, it's an NVM Express status code
861  */
862 int nvme_submit_sync_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd,
863                                                 u32 *result, unsigned timeout)
864 {
865         int cmdid;
866         struct sync_cmd_info cmdinfo;
867
868         cmdinfo.task = current;
869         cmdinfo.status = -EINTR;
870
871         cmdid = alloc_cmdid_killable(nvmeq, &cmdinfo, sync_completion,
872                                                                 timeout);
873         if (cmdid < 0)
874                 return cmdid;
875         cmd->common.command_id = cmdid;
876
877         set_current_state(TASK_KILLABLE);
878         nvme_submit_cmd(nvmeq, cmd);
879         schedule_timeout(timeout);
880
881         if (cmdinfo.status == -EINTR) {
882                 nvme_abort_command(nvmeq, cmdid);
883                 return -EINTR;
884         }
885
886         if (result)
887                 *result = cmdinfo.result;
888
889         return cmdinfo.status;
890 }
891
892 int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
893                                                                 u32 *result)
894 {
895         return nvme_submit_sync_cmd(dev->queues[0], cmd, result, ADMIN_TIMEOUT);
896 }
897
898 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
899 {
900         int status;
901         struct nvme_command c;
902
903         memset(&c, 0, sizeof(c));
904         c.delete_queue.opcode = opcode;
905         c.delete_queue.qid = cpu_to_le16(id);
906
907         status = nvme_submit_admin_cmd(dev, &c, NULL);
908         if (status)
909                 return -EIO;
910         return 0;
911 }
912
913 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
914                                                 struct nvme_queue *nvmeq)
915 {
916         int status;
917         struct nvme_command c;
918         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
919
920         memset(&c, 0, sizeof(c));
921         c.create_cq.opcode = nvme_admin_create_cq;
922         c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
923         c.create_cq.cqid = cpu_to_le16(qid);
924         c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
925         c.create_cq.cq_flags = cpu_to_le16(flags);
926         c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
927
928         status = nvme_submit_admin_cmd(dev, &c, NULL);
929         if (status)
930                 return -EIO;
931         return 0;
932 }
933
934 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
935                                                 struct nvme_queue *nvmeq)
936 {
937         int status;
938         struct nvme_command c;
939         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
940
941         memset(&c, 0, sizeof(c));
942         c.create_sq.opcode = nvme_admin_create_sq;
943         c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
944         c.create_sq.sqid = cpu_to_le16(qid);
945         c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
946         c.create_sq.sq_flags = cpu_to_le16(flags);
947         c.create_sq.cqid = cpu_to_le16(qid);
948
949         status = nvme_submit_admin_cmd(dev, &c, NULL);
950         if (status)
951                 return -EIO;
952         return 0;
953 }
954
955 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
956 {
957         return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
958 }
959
960 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
961 {
962         return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
963 }
964
965 int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
966                                                         dma_addr_t dma_addr)
967 {
968         struct nvme_command c;
969
970         memset(&c, 0, sizeof(c));
971         c.identify.opcode = nvme_admin_identify;
972         c.identify.nsid = cpu_to_le32(nsid);
973         c.identify.prp1 = cpu_to_le64(dma_addr);
974         c.identify.cns = cpu_to_le32(cns);
975
976         return nvme_submit_admin_cmd(dev, &c, NULL);
977 }
978
979 int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
980                                         dma_addr_t dma_addr, u32 *result)
981 {
982         struct nvme_command c;
983
984         memset(&c, 0, sizeof(c));
985         c.features.opcode = nvme_admin_get_features;
986         c.features.nsid = cpu_to_le32(nsid);
987         c.features.prp1 = cpu_to_le64(dma_addr);
988         c.features.fid = cpu_to_le32(fid);
989
990         return nvme_submit_admin_cmd(dev, &c, result);
991 }
992
993 int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
994                                         dma_addr_t dma_addr, u32 *result)
995 {
996         struct nvme_command c;
997
998         memset(&c, 0, sizeof(c));
999         c.features.opcode = nvme_admin_set_features;
1000         c.features.prp1 = cpu_to_le64(dma_addr);
1001         c.features.fid = cpu_to_le32(fid);
1002         c.features.dword11 = cpu_to_le32(dword11);
1003
1004         return nvme_submit_admin_cmd(dev, &c, result);
1005 }
1006
1007 /**
1008  * nvme_cancel_ios - Cancel outstanding I/Os
1009  * @queue: The queue to cancel I/Os on
1010  * @timeout: True to only cancel I/Os which have timed out
1011  */
1012 static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1013 {
1014         int depth = nvmeq->q_depth - 1;
1015         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1016         unsigned long now = jiffies;
1017         int cmdid;
1018
1019         for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1020                 void *ctx;
1021                 nvme_completion_fn fn;
1022                 static struct nvme_completion cqe = {
1023                         .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
1024                 };
1025
1026                 if (timeout && !time_after(now, info[cmdid].timeout))
1027                         continue;
1028                 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1029                         continue;
1030                 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d\n", cmdid);
1031                 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
1032                 fn(nvmeq->dev, ctx, &cqe);
1033         }
1034 }
1035
1036 static void nvme_free_queue(struct nvme_queue *nvmeq)
1037 {
1038         spin_lock_irq(&nvmeq->q_lock);
1039         while (bio_list_peek(&nvmeq->sq_cong)) {
1040                 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1041                 bio_endio(bio, -EIO);
1042         }
1043         spin_unlock_irq(&nvmeq->q_lock);
1044
1045         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1046                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1047         dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1048                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
1049         kfree(nvmeq);
1050 }
1051
1052 static void nvme_free_queues(struct nvme_dev *dev)
1053 {
1054         int i;
1055
1056         for (i = dev->queue_count - 1; i >= 0; i--) {
1057                 nvme_free_queue(dev->queues[i]);
1058                 dev->queue_count--;
1059                 dev->queues[i] = NULL;
1060         }
1061 }
1062
1063 static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1064 {
1065         struct nvme_queue *nvmeq = dev->queues[qid];
1066         int vector = dev->entry[nvmeq->cq_vector].vector;
1067
1068         spin_lock_irq(&nvmeq->q_lock);
1069         if (nvmeq->q_suspended) {
1070                 spin_unlock_irq(&nvmeq->q_lock);
1071                 return;
1072         }
1073         nvmeq->q_suspended = 1;
1074         spin_unlock_irq(&nvmeq->q_lock);
1075
1076         irq_set_affinity_hint(vector, NULL);
1077         free_irq(vector, nvmeq);
1078
1079         /* Don't tell the adapter to delete the admin queue */
1080         if (qid) {
1081                 adapter_delete_sq(dev, qid);
1082                 adapter_delete_cq(dev, qid);
1083         }
1084
1085         spin_lock_irq(&nvmeq->q_lock);
1086         nvme_process_cq(nvmeq);
1087         nvme_cancel_ios(nvmeq, false);
1088         spin_unlock_irq(&nvmeq->q_lock);
1089 }
1090
1091 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1092                                                         int depth, int vector)
1093 {
1094         struct device *dmadev = &dev->pci_dev->dev;
1095         unsigned extra = nvme_queue_extra(depth);
1096         struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1097         if (!nvmeq)
1098                 return NULL;
1099
1100         nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
1101                                         &nvmeq->cq_dma_addr, GFP_KERNEL);
1102         if (!nvmeq->cqes)
1103                 goto free_nvmeq;
1104         memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
1105
1106         nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1107                                         &nvmeq->sq_dma_addr, GFP_KERNEL);
1108         if (!nvmeq->sq_cmds)
1109                 goto free_cqdma;
1110
1111         nvmeq->q_dmadev = dmadev;
1112         nvmeq->dev = dev;
1113         spin_lock_init(&nvmeq->q_lock);
1114         nvmeq->cq_head = 0;
1115         nvmeq->cq_phase = 1;
1116         init_waitqueue_head(&nvmeq->sq_full);
1117         init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
1118         bio_list_init(&nvmeq->sq_cong);
1119         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1120         nvmeq->q_depth = depth;
1121         nvmeq->cq_vector = vector;
1122         nvmeq->q_suspended = 1;
1123         dev->queue_count++;
1124
1125         return nvmeq;
1126
1127  free_cqdma:
1128         dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
1129                                                         nvmeq->cq_dma_addr);
1130  free_nvmeq:
1131         kfree(nvmeq);
1132         return NULL;
1133 }
1134
1135 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1136                                                         const char *name)
1137 {
1138         if (use_threaded_interrupts)
1139                 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
1140                                         nvme_irq_check, nvme_irq, IRQF_SHARED,
1141                                         name, nvmeq);
1142         return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
1143                                 IRQF_SHARED, name, nvmeq);
1144 }
1145
1146 static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
1147 {
1148         struct nvme_dev *dev = nvmeq->dev;
1149         unsigned extra = nvme_queue_extra(nvmeq->q_depth);
1150
1151         nvmeq->sq_tail = 0;
1152         nvmeq->cq_head = 0;
1153         nvmeq->cq_phase = 1;
1154         nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
1155         memset(nvmeq->cmdid_data, 0, extra);
1156         memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1157         nvme_cancel_ios(nvmeq, false);
1158         nvmeq->q_suspended = 0;
1159 }
1160
1161 static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1162 {
1163         struct nvme_dev *dev = nvmeq->dev;
1164         int result;
1165
1166         result = adapter_alloc_cq(dev, qid, nvmeq);
1167         if (result < 0)
1168                 return result;
1169
1170         result = adapter_alloc_sq(dev, qid, nvmeq);
1171         if (result < 0)
1172                 goto release_cq;
1173
1174         result = queue_request_irq(dev, nvmeq, "nvme");
1175         if (result < 0)
1176                 goto release_sq;
1177
1178         spin_lock_irq(&nvmeq->q_lock);
1179         nvme_init_queue(nvmeq, qid);
1180         spin_unlock_irq(&nvmeq->q_lock);
1181
1182         return result;
1183
1184  release_sq:
1185         adapter_delete_sq(dev, qid);
1186  release_cq:
1187         adapter_delete_cq(dev, qid);
1188         return result;
1189 }
1190
1191 static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1192 {
1193         unsigned long timeout;
1194         u32 bit = enabled ? NVME_CSTS_RDY : 0;
1195
1196         timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1197
1198         while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1199                 msleep(100);
1200                 if (fatal_signal_pending(current))
1201                         return -EINTR;
1202                 if (time_after(jiffies, timeout)) {
1203                         dev_err(&dev->pci_dev->dev,
1204                                 "Device not ready; aborting initialisation\n");
1205                         return -ENODEV;
1206                 }
1207         }
1208
1209         return 0;
1210 }
1211
1212 /*
1213  * If the device has been passed off to us in an enabled state, just clear
1214  * the enabled bit.  The spec says we should set the 'shutdown notification
1215  * bits', but doing so may cause the device to complete commands to the
1216  * admin queue ... and we don't know what memory that might be pointing at!
1217  */
1218 static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1219 {
1220         u32 cc = readl(&dev->bar->cc);
1221
1222         if (cc & NVME_CC_ENABLE)
1223                 writel(cc & ~NVME_CC_ENABLE, &dev->bar->cc);
1224         return nvme_wait_ready(dev, cap, false);
1225 }
1226
1227 static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1228 {
1229         return nvme_wait_ready(dev, cap, true);
1230 }
1231
1232 static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1233 {
1234         unsigned long timeout;
1235         u32 cc;
1236
1237         cc = (readl(&dev->bar->cc) & ~NVME_CC_SHN_MASK) | NVME_CC_SHN_NORMAL;
1238         writel(cc, &dev->bar->cc);
1239
1240         timeout = 2 * HZ + jiffies;
1241         while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1242                                                         NVME_CSTS_SHST_CMPLT) {
1243                 msleep(100);
1244                 if (fatal_signal_pending(current))
1245                         return -EINTR;
1246                 if (time_after(jiffies, timeout)) {
1247                         dev_err(&dev->pci_dev->dev,
1248                                 "Device shutdown incomplete; abort shutdown\n");
1249                         return -ENODEV;
1250                 }
1251         }
1252
1253         return 0;
1254 }
1255
1256 static int nvme_configure_admin_queue(struct nvme_dev *dev)
1257 {
1258         int result;
1259         u32 aqa;
1260         u64 cap = readq(&dev->bar->cap);
1261         struct nvme_queue *nvmeq;
1262
1263         result = nvme_disable_ctrl(dev, cap);
1264         if (result < 0)
1265                 return result;
1266
1267         nvmeq = dev->queues[0];
1268         if (!nvmeq) {
1269                 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1270                 if (!nvmeq)
1271                         return -ENOMEM;
1272                 dev->queues[0] = nvmeq;
1273         }
1274
1275         aqa = nvmeq->q_depth - 1;
1276         aqa |= aqa << 16;
1277
1278         dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
1279         dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
1280         dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1281         dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1282
1283         writel(aqa, &dev->bar->aqa);
1284         writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1285         writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
1286         writel(dev->ctrl_config, &dev->bar->cc);
1287
1288         result = nvme_enable_ctrl(dev, cap);
1289         if (result)
1290                 return result;
1291
1292         result = queue_request_irq(dev, nvmeq, "nvme admin");
1293         if (result)
1294                 return result;
1295
1296         spin_lock_irq(&nvmeq->q_lock);
1297         nvme_init_queue(nvmeq, 0);
1298         spin_unlock_irq(&nvmeq->q_lock);
1299         return result;
1300 }
1301
1302 struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
1303                                 unsigned long addr, unsigned length)
1304 {
1305         int i, err, count, nents, offset;
1306         struct scatterlist *sg;
1307         struct page **pages;
1308         struct nvme_iod *iod;
1309
1310         if (addr & 3)
1311                 return ERR_PTR(-EINVAL);
1312         if (!length || length > INT_MAX - PAGE_SIZE)
1313                 return ERR_PTR(-EINVAL);
1314
1315         offset = offset_in_page(addr);
1316         count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1317         pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
1318         if (!pages)
1319                 return ERR_PTR(-ENOMEM);
1320
1321         err = get_user_pages_fast(addr, count, 1, pages);
1322         if (err < count) {
1323                 count = err;
1324                 err = -EFAULT;
1325                 goto put_pages;
1326         }
1327
1328         iod = nvme_alloc_iod(count, length, GFP_KERNEL);
1329         sg = iod->sg;
1330         sg_init_table(sg, count);
1331         for (i = 0; i < count; i++) {
1332                 sg_set_page(&sg[i], pages[i],
1333                             min_t(unsigned, length, PAGE_SIZE - offset),
1334                             offset);
1335                 length -= (PAGE_SIZE - offset);
1336                 offset = 0;
1337         }
1338         sg_mark_end(&sg[i - 1]);
1339         iod->nents = count;
1340
1341         err = -ENOMEM;
1342         nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1343                                 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1344         if (!nents)
1345                 goto free_iod;
1346
1347         kfree(pages);
1348         return iod;
1349
1350  free_iod:
1351         kfree(iod);
1352  put_pages:
1353         for (i = 0; i < count; i++)
1354                 put_page(pages[i]);
1355         kfree(pages);
1356         return ERR_PTR(err);
1357 }
1358
1359 void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1360                         struct nvme_iod *iod)
1361 {
1362         int i;
1363
1364         dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1365                                 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
1366
1367         for (i = 0; i < iod->nents; i++)
1368                 put_page(sg_page(&iod->sg[i]));
1369 }
1370
1371 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1372 {
1373         struct nvme_dev *dev = ns->dev;
1374         struct nvme_queue *nvmeq;
1375         struct nvme_user_io io;
1376         struct nvme_command c;
1377         unsigned length, meta_len;
1378         int status, i;
1379         struct nvme_iod *iod, *meta_iod = NULL;
1380         dma_addr_t meta_dma_addr;
1381         void *meta, *uninitialized_var(meta_mem);
1382
1383         if (copy_from_user(&io, uio, sizeof(io)))
1384                 return -EFAULT;
1385         length = (io.nblocks + 1) << ns->lba_shift;
1386         meta_len = (io.nblocks + 1) * ns->ms;
1387
1388         if (meta_len && ((io.metadata & 3) || !io.metadata))
1389                 return -EINVAL;
1390
1391         switch (io.opcode) {
1392         case nvme_cmd_write:
1393         case nvme_cmd_read:
1394         case nvme_cmd_compare:
1395                 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
1396                 break;
1397         default:
1398                 return -EINVAL;
1399         }
1400
1401         if (IS_ERR(iod))
1402                 return PTR_ERR(iod);
1403
1404         memset(&c, 0, sizeof(c));
1405         c.rw.opcode = io.opcode;
1406         c.rw.flags = io.flags;
1407         c.rw.nsid = cpu_to_le32(ns->ns_id);
1408         c.rw.slba = cpu_to_le64(io.slba);
1409         c.rw.length = cpu_to_le16(io.nblocks);
1410         c.rw.control = cpu_to_le16(io.control);
1411         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1412         c.rw.reftag = cpu_to_le32(io.reftag);
1413         c.rw.apptag = cpu_to_le16(io.apptag);
1414         c.rw.appmask = cpu_to_le16(io.appmask);
1415
1416         if (meta_len) {
1417                 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1418                                                                 meta_len);
1419                 if (IS_ERR(meta_iod)) {
1420                         status = PTR_ERR(meta_iod);
1421                         meta_iod = NULL;
1422                         goto unmap;
1423                 }
1424
1425                 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1426                                                 &meta_dma_addr, GFP_KERNEL);
1427                 if (!meta_mem) {
1428                         status = -ENOMEM;
1429                         goto unmap;
1430                 }
1431
1432                 if (io.opcode & 1) {
1433                         int meta_offset = 0;
1434
1435                         for (i = 0; i < meta_iod->nents; i++) {
1436                                 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1437                                                 meta_iod->sg[i].offset;
1438                                 memcpy(meta_mem + meta_offset, meta,
1439                                                 meta_iod->sg[i].length);
1440                                 kunmap_atomic(meta);
1441                                 meta_offset += meta_iod->sg[i].length;
1442                         }
1443                 }
1444
1445                 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1446         }
1447
1448         length = nvme_setup_prps(dev, &c.common, iod, length, GFP_KERNEL);
1449
1450         nvmeq = get_nvmeq(dev);
1451         /*
1452          * Since nvme_submit_sync_cmd sleeps, we can't keep preemption
1453          * disabled.  We may be preempted at any point, and be rescheduled
1454          * to a different CPU.  That will cause cacheline bouncing, but no
1455          * additional races since q_lock already protects against other CPUs.
1456          */
1457         put_nvmeq(nvmeq);
1458         if (length != (io.nblocks + 1) << ns->lba_shift)
1459                 status = -ENOMEM;
1460         else if (!nvmeq || nvmeq->q_suspended)
1461                 status = -EBUSY;
1462         else
1463                 status = nvme_submit_sync_cmd(nvmeq, &c, NULL, NVME_IO_TIMEOUT);
1464
1465         if (meta_len) {
1466                 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1467                         int meta_offset = 0;
1468
1469                         for (i = 0; i < meta_iod->nents; i++) {
1470                                 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1471                                                 meta_iod->sg[i].offset;
1472                                 memcpy(meta, meta_mem + meta_offset,
1473                                                 meta_iod->sg[i].length);
1474                                 kunmap_atomic(meta);
1475                                 meta_offset += meta_iod->sg[i].length;
1476                         }
1477                 }
1478
1479                 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1480                                                                 meta_dma_addr);
1481         }
1482
1483  unmap:
1484         nvme_unmap_user_pages(dev, io.opcode & 1, iod);
1485         nvme_free_iod(dev, iod);
1486
1487         if (meta_iod) {
1488                 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1489                 nvme_free_iod(dev, meta_iod);
1490         }
1491
1492         return status;
1493 }
1494
1495 static int nvme_user_admin_cmd(struct nvme_dev *dev,
1496                                         struct nvme_admin_cmd __user *ucmd)
1497 {
1498         struct nvme_admin_cmd cmd;
1499         struct nvme_command c;
1500         int status, length;
1501         struct nvme_iod *uninitialized_var(iod);
1502         unsigned timeout;
1503
1504         if (!capable(CAP_SYS_ADMIN))
1505                 return -EACCES;
1506         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1507                 return -EFAULT;
1508
1509         memset(&c, 0, sizeof(c));
1510         c.common.opcode = cmd.opcode;
1511         c.common.flags = cmd.flags;
1512         c.common.nsid = cpu_to_le32(cmd.nsid);
1513         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1514         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1515         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1516         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1517         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1518         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1519         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1520         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1521
1522         length = cmd.data_len;
1523         if (cmd.data_len) {
1524                 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1525                                                                 length);
1526                 if (IS_ERR(iod))
1527                         return PTR_ERR(iod);
1528                 length = nvme_setup_prps(dev, &c.common, iod, length,
1529                                                                 GFP_KERNEL);
1530         }
1531
1532         timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1533                                                                 ADMIN_TIMEOUT;
1534         if (length != cmd.data_len)
1535                 status = -ENOMEM;
1536         else
1537                 status = nvme_submit_sync_cmd(dev->queues[0], &c, &cmd.result,
1538                                                                 timeout);
1539
1540         if (cmd.data_len) {
1541                 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
1542                 nvme_free_iod(dev, iod);
1543         }
1544
1545         if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
1546                                                         sizeof(cmd.result)))
1547                 status = -EFAULT;
1548
1549         return status;
1550 }
1551
1552 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1553                                                         unsigned long arg)
1554 {
1555         struct nvme_ns *ns = bdev->bd_disk->private_data;
1556
1557         switch (cmd) {
1558         case NVME_IOCTL_ID:
1559                 force_successful_syscall_return();
1560                 return ns->ns_id;
1561         case NVME_IOCTL_ADMIN_CMD:
1562                 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
1563         case NVME_IOCTL_SUBMIT_IO:
1564                 return nvme_submit_io(ns, (void __user *)arg);
1565         case SG_GET_VERSION_NUM:
1566                 return nvme_sg_get_version_num((void __user *)arg);
1567         case SG_IO:
1568                 return nvme_sg_io(ns, (void __user *)arg);
1569         default:
1570                 return -ENOTTY;
1571         }
1572 }
1573
1574 #ifdef CONFIG_COMPAT
1575 static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1576                                         unsigned int cmd, unsigned long arg)
1577 {
1578         struct nvme_ns *ns = bdev->bd_disk->private_data;
1579
1580         switch (cmd) {
1581         case SG_IO:
1582                 return nvme_sg_io32(ns, arg);
1583         }
1584         return nvme_ioctl(bdev, mode, cmd, arg);
1585 }
1586 #else
1587 #define nvme_compat_ioctl       NULL
1588 #endif
1589
1590 static const struct block_device_operations nvme_fops = {
1591         .owner          = THIS_MODULE,
1592         .ioctl          = nvme_ioctl,
1593         .compat_ioctl   = nvme_compat_ioctl,
1594 };
1595
1596 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1597 {
1598         while (bio_list_peek(&nvmeq->sq_cong)) {
1599                 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1600                 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1601
1602                 if (bio_list_empty(&nvmeq->sq_cong))
1603                         remove_wait_queue(&nvmeq->sq_full,
1604                                                         &nvmeq->sq_cong_wait);
1605                 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1606                         if (bio_list_empty(&nvmeq->sq_cong))
1607                                 add_wait_queue(&nvmeq->sq_full,
1608                                                         &nvmeq->sq_cong_wait);
1609                         bio_list_add_head(&nvmeq->sq_cong, bio);
1610                         break;
1611                 }
1612         }
1613 }
1614
1615 static int nvme_kthread(void *data)
1616 {
1617         struct nvme_dev *dev, *next;
1618
1619         while (!kthread_should_stop()) {
1620                 set_current_state(TASK_INTERRUPTIBLE);
1621                 spin_lock(&dev_list_lock);
1622                 list_for_each_entry_safe(dev, next, &dev_list, node) {
1623                         int i;
1624                         if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1625                                                         dev->initialized) {
1626                                 if (work_busy(&dev->reset_work))
1627                                         continue;
1628                                 list_del_init(&dev->node);
1629                                 dev_warn(&dev->pci_dev->dev,
1630                                         "Failed status, reset controller\n");
1631                                 INIT_WORK(&dev->reset_work,
1632                                                         nvme_reset_failed_dev);
1633                                 queue_work(nvme_workq, &dev->reset_work);
1634                                 continue;
1635                         }
1636                         for (i = 0; i < dev->queue_count; i++) {
1637                                 struct nvme_queue *nvmeq = dev->queues[i];
1638                                 if (!nvmeq)
1639                                         continue;
1640                                 spin_lock_irq(&nvmeq->q_lock);
1641                                 if (nvmeq->q_suspended)
1642                                         goto unlock;
1643                                 nvme_process_cq(nvmeq);
1644                                 nvme_cancel_ios(nvmeq, true);
1645                                 nvme_resubmit_bios(nvmeq);
1646  unlock:
1647                                 spin_unlock_irq(&nvmeq->q_lock);
1648                         }
1649                 }
1650                 spin_unlock(&dev_list_lock);
1651                 schedule_timeout(round_jiffies_relative(HZ));
1652         }
1653         return 0;
1654 }
1655
1656 static DEFINE_IDA(nvme_index_ida);
1657
1658 static int nvme_get_ns_idx(void)
1659 {
1660         int index, error;
1661
1662         do {
1663                 if (!ida_pre_get(&nvme_index_ida, GFP_KERNEL))
1664                         return -1;
1665
1666                 spin_lock(&dev_list_lock);
1667                 error = ida_get_new(&nvme_index_ida, &index);
1668                 spin_unlock(&dev_list_lock);
1669         } while (error == -EAGAIN);
1670
1671         if (error)
1672                 index = -1;
1673         return index;
1674 }
1675
1676 static void nvme_put_ns_idx(int index)
1677 {
1678         spin_lock(&dev_list_lock);
1679         ida_remove(&nvme_index_ida, index);
1680         spin_unlock(&dev_list_lock);
1681 }
1682
1683 static void nvme_config_discard(struct nvme_ns *ns)
1684 {
1685         u32 logical_block_size = queue_logical_block_size(ns->queue);
1686         ns->queue->limits.discard_zeroes_data = 0;
1687         ns->queue->limits.discard_alignment = logical_block_size;
1688         ns->queue->limits.discard_granularity = logical_block_size;
1689         ns->queue->limits.max_discard_sectors = 0xffffffff;
1690         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1691 }
1692
1693 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
1694                         struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1695 {
1696         struct nvme_ns *ns;
1697         struct gendisk *disk;
1698         int lbaf;
1699
1700         if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1701                 return NULL;
1702
1703         ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1704         if (!ns)
1705                 return NULL;
1706         ns->queue = blk_alloc_queue(GFP_KERNEL);
1707         if (!ns->queue)
1708                 goto out_free_ns;
1709         ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
1710         queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
1711         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1712         blk_queue_make_request(ns->queue, nvme_make_request);
1713         ns->dev = dev;
1714         ns->queue->queuedata = ns;
1715
1716         disk = alloc_disk(NVME_MINORS);
1717         if (!disk)
1718                 goto out_free_queue;
1719         ns->ns_id = nsid;
1720         ns->disk = disk;
1721         lbaf = id->flbas & 0xf;
1722         ns->lba_shift = id->lbaf[lbaf].ds;
1723         ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1724         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1725         if (dev->max_hw_sectors)
1726                 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
1727
1728         disk->major = nvme_major;
1729         disk->minors = NVME_MINORS;
1730         disk->first_minor = NVME_MINORS * nvme_get_ns_idx();
1731         disk->fops = &nvme_fops;
1732         disk->private_data = ns;
1733         disk->queue = ns->queue;
1734         disk->driverfs_dev = &dev->pci_dev->dev;
1735         sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
1736         set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1737
1738         if (dev->oncs & NVME_CTRL_ONCS_DSM)
1739                 nvme_config_discard(ns);
1740
1741         return ns;
1742
1743  out_free_queue:
1744         blk_cleanup_queue(ns->queue);
1745  out_free_ns:
1746         kfree(ns);
1747         return NULL;
1748 }
1749
1750 static void nvme_ns_free(struct nvme_ns *ns)
1751 {
1752         int index = ns->disk->first_minor / NVME_MINORS;
1753         put_disk(ns->disk);
1754         nvme_put_ns_idx(index);
1755         blk_cleanup_queue(ns->queue);
1756         kfree(ns);
1757 }
1758
1759 static int set_queue_count(struct nvme_dev *dev, int count)
1760 {
1761         int status;
1762         u32 result;
1763         u32 q_count = (count - 1) | ((count - 1) << 16);
1764
1765         status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
1766                                                                 &result);
1767         if (status)
1768                 return status < 0 ? -EIO : -EBUSY;
1769         return min(result & 0xffff, result >> 16) + 1;
1770 }
1771
1772 static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
1773 {
1774         return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
1775 }
1776
1777 static int nvme_setup_io_queues(struct nvme_dev *dev)
1778 {
1779         struct pci_dev *pdev = dev->pci_dev;
1780         int result, cpu, i, vecs, nr_io_queues, size, q_depth;
1781
1782         nr_io_queues = num_online_cpus();
1783         result = set_queue_count(dev, nr_io_queues);
1784         if (result < 0)
1785                 return result;
1786         if (result < nr_io_queues)
1787                 nr_io_queues = result;
1788
1789         size = db_bar_size(dev, nr_io_queues);
1790         if (size > 8192) {
1791                 iounmap(dev->bar);
1792                 do {
1793                         dev->bar = ioremap(pci_resource_start(pdev, 0), size);
1794                         if (dev->bar)
1795                                 break;
1796                         if (!--nr_io_queues)
1797                                 return -ENOMEM;
1798                         size = db_bar_size(dev, nr_io_queues);
1799                 } while (1);
1800                 dev->dbs = ((void __iomem *)dev->bar) + 4096;
1801                 dev->queues[0]->q_db = dev->dbs;
1802         }
1803
1804         /* Deregister the admin queue's interrupt */
1805         free_irq(dev->entry[0].vector, dev->queues[0]);
1806
1807         vecs = nr_io_queues;
1808         for (i = 0; i < vecs; i++)
1809                 dev->entry[i].entry = i;
1810         for (;;) {
1811                 result = pci_enable_msix(pdev, dev->entry, vecs);
1812                 if (result <= 0)
1813                         break;
1814                 vecs = result;
1815         }
1816
1817         if (result < 0) {
1818                 vecs = nr_io_queues;
1819                 if (vecs > 32)
1820                         vecs = 32;
1821                 for (;;) {
1822                         result = pci_enable_msi_block(pdev, vecs);
1823                         if (result == 0) {
1824                                 for (i = 0; i < vecs; i++)
1825                                         dev->entry[i].vector = i + pdev->irq;
1826                                 break;
1827                         } else if (result < 0) {
1828                                 vecs = 1;
1829                                 break;
1830                         }
1831                         vecs = result;
1832                 }
1833         }
1834
1835         /*
1836          * Should investigate if there's a performance win from allocating
1837          * more queues than interrupt vectors; it might allow the submission
1838          * path to scale better, even if the receive path is limited by the
1839          * number of interrupts.
1840          */
1841         nr_io_queues = vecs;
1842
1843         result = queue_request_irq(dev, dev->queues[0], "nvme admin");
1844         if (result) {
1845                 dev->queues[0]->q_suspended = 1;
1846                 goto free_queues;
1847         }
1848
1849         /* Free previously allocated queues that are no longer usable */
1850         spin_lock(&dev_list_lock);
1851         for (i = dev->queue_count - 1; i > nr_io_queues; i--) {
1852                 struct nvme_queue *nvmeq = dev->queues[i];
1853
1854                 spin_lock_irq(&nvmeq->q_lock);
1855                 nvme_cancel_ios(nvmeq, false);
1856                 spin_unlock_irq(&nvmeq->q_lock);
1857
1858                 nvme_free_queue(nvmeq);
1859                 dev->queue_count--;
1860                 dev->queues[i] = NULL;
1861         }
1862         spin_unlock(&dev_list_lock);
1863
1864         cpu = cpumask_first(cpu_online_mask);
1865         for (i = 0; i < nr_io_queues; i++) {
1866                 irq_set_affinity_hint(dev->entry[i].vector, get_cpu_mask(cpu));
1867                 cpu = cpumask_next(cpu, cpu_online_mask);
1868         }
1869
1870         q_depth = min_t(int, NVME_CAP_MQES(readq(&dev->bar->cap)) + 1,
1871                                                                 NVME_Q_DEPTH);
1872         for (i = dev->queue_count - 1; i < nr_io_queues; i++) {
1873                 dev->queues[i + 1] = nvme_alloc_queue(dev, i + 1, q_depth, i);
1874                 if (!dev->queues[i + 1]) {
1875                         result = -ENOMEM;
1876                         goto free_queues;
1877                 }
1878         }
1879
1880         for (; i < num_possible_cpus(); i++) {
1881                 int target = i % rounddown_pow_of_two(dev->queue_count - 1);
1882                 dev->queues[i + 1] = dev->queues[target + 1];
1883         }
1884
1885         for (i = 1; i < dev->queue_count; i++) {
1886                 result = nvme_create_queue(dev->queues[i], i);
1887                 if (result) {
1888                         for (--i; i > 0; i--)
1889                                 nvme_disable_queue(dev, i);
1890                         goto free_queues;
1891                 }
1892         }
1893
1894         return 0;
1895
1896  free_queues:
1897         nvme_free_queues(dev);
1898         return result;
1899 }
1900
1901 /*
1902  * Return: error value if an error occurred setting up the queues or calling
1903  * Identify Device.  0 if these succeeded, even if adding some of the
1904  * namespaces failed.  At the moment, these failures are silent.  TBD which
1905  * failures should be reported.
1906  */
1907 static int nvme_dev_add(struct nvme_dev *dev)
1908 {
1909         struct pci_dev *pdev = dev->pci_dev;
1910         int res;
1911         unsigned nn, i;
1912         struct nvme_ns *ns;
1913         struct nvme_id_ctrl *ctrl;
1914         struct nvme_id_ns *id_ns;
1915         void *mem;
1916         dma_addr_t dma_addr;
1917         int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
1918
1919         mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
1920         if (!mem)
1921                 return -ENOMEM;
1922
1923         res = nvme_identify(dev, 0, 1, dma_addr);
1924         if (res) {
1925                 res = -EIO;
1926                 goto out;
1927         }
1928
1929         ctrl = mem;
1930         nn = le32_to_cpup(&ctrl->nn);
1931         dev->oncs = le16_to_cpup(&ctrl->oncs);
1932         memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
1933         memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
1934         memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
1935         if (ctrl->mdts)
1936                 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
1937         if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
1938                         (pdev->device == 0x0953) && ctrl->vs[3])
1939                 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
1940
1941         id_ns = mem;
1942         for (i = 1; i <= nn; i++) {
1943                 res = nvme_identify(dev, i, 0, dma_addr);
1944                 if (res)
1945                         continue;
1946
1947                 if (id_ns->ncap == 0)
1948                         continue;
1949
1950                 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
1951                                                         dma_addr + 4096, NULL);
1952                 if (res)
1953                         memset(mem + 4096, 0, 4096);
1954
1955                 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
1956                 if (ns)
1957                         list_add_tail(&ns->list, &dev->namespaces);
1958         }
1959         list_for_each_entry(ns, &dev->namespaces, list)
1960                 add_disk(ns->disk);
1961         res = 0;
1962
1963  out:
1964         dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
1965         return res;
1966 }
1967
1968 static int nvme_dev_map(struct nvme_dev *dev)
1969 {
1970         int bars, result = -ENOMEM;
1971         struct pci_dev *pdev = dev->pci_dev;
1972
1973         if (pci_enable_device_mem(pdev))
1974                 return result;
1975
1976         dev->entry[0].vector = pdev->irq;
1977         pci_set_master(pdev);
1978         bars = pci_select_bars(pdev, IORESOURCE_MEM);
1979         if (pci_request_selected_regions(pdev, bars, "nvme"))
1980                 goto disable_pci;
1981
1982         if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
1983             dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
1984                 goto disable;
1985
1986         dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
1987         if (!dev->bar)
1988                 goto disable;
1989
1990         dev->db_stride = 1 << NVME_CAP_STRIDE(readq(&dev->bar->cap));
1991         dev->dbs = ((void __iomem *)dev->bar) + 4096;
1992
1993         return 0;
1994
1995  disable:
1996         pci_release_regions(pdev);
1997  disable_pci:
1998         pci_disable_device(pdev);
1999         return result;
2000 }
2001
2002 static void nvme_dev_unmap(struct nvme_dev *dev)
2003 {
2004         if (dev->pci_dev->msi_enabled)
2005                 pci_disable_msi(dev->pci_dev);
2006         else if (dev->pci_dev->msix_enabled)
2007                 pci_disable_msix(dev->pci_dev);
2008
2009         if (dev->bar) {
2010                 iounmap(dev->bar);
2011                 dev->bar = NULL;
2012                 pci_release_regions(dev->pci_dev);
2013         }
2014
2015         if (pci_is_enabled(dev->pci_dev))
2016                 pci_disable_device(dev->pci_dev);
2017 }
2018
2019 static void nvme_dev_shutdown(struct nvme_dev *dev)
2020 {
2021         int i;
2022
2023         dev->initialized = 0;
2024         for (i = dev->queue_count - 1; i >= 0; i--)
2025                 nvme_disable_queue(dev, i);
2026
2027         spin_lock(&dev_list_lock);
2028         list_del_init(&dev->node);
2029         spin_unlock(&dev_list_lock);
2030
2031         if (dev->bar)
2032                 nvme_shutdown_ctrl(dev);
2033         nvme_dev_unmap(dev);
2034 }
2035
2036 static void nvme_dev_remove(struct nvme_dev *dev)
2037 {
2038         struct nvme_ns *ns, *next;
2039
2040         list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2041                 list_del(&ns->list);
2042                 del_gendisk(ns->disk);
2043                 nvme_ns_free(ns);
2044         }
2045 }
2046
2047 static int nvme_setup_prp_pools(struct nvme_dev *dev)
2048 {
2049         struct device *dmadev = &dev->pci_dev->dev;
2050         dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2051                                                 PAGE_SIZE, PAGE_SIZE, 0);
2052         if (!dev->prp_page_pool)
2053                 return -ENOMEM;
2054
2055         /* Optimisation for I/Os between 4k and 128k */
2056         dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2057                                                 256, 256, 0);
2058         if (!dev->prp_small_pool) {
2059                 dma_pool_destroy(dev->prp_page_pool);
2060                 return -ENOMEM;
2061         }
2062         return 0;
2063 }
2064
2065 static void nvme_release_prp_pools(struct nvme_dev *dev)
2066 {
2067         dma_pool_destroy(dev->prp_page_pool);
2068         dma_pool_destroy(dev->prp_small_pool);
2069 }
2070
2071 static DEFINE_IDA(nvme_instance_ida);
2072
2073 static int nvme_set_instance(struct nvme_dev *dev)
2074 {
2075         int instance, error;
2076
2077         do {
2078                 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2079                         return -ENODEV;
2080
2081                 spin_lock(&dev_list_lock);
2082                 error = ida_get_new(&nvme_instance_ida, &instance);
2083                 spin_unlock(&dev_list_lock);
2084         } while (error == -EAGAIN);
2085
2086         if (error)
2087                 return -ENODEV;
2088
2089         dev->instance = instance;
2090         return 0;
2091 }
2092
2093 static void nvme_release_instance(struct nvme_dev *dev)
2094 {
2095         spin_lock(&dev_list_lock);
2096         ida_remove(&nvme_instance_ida, dev->instance);
2097         spin_unlock(&dev_list_lock);
2098 }
2099
2100 static void nvme_free_dev(struct kref *kref)
2101 {
2102         struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
2103         kfree(dev->queues);
2104         kfree(dev->entry);
2105         kfree(dev);
2106 }
2107
2108 static int nvme_dev_open(struct inode *inode, struct file *f)
2109 {
2110         struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2111                                                                 miscdev);
2112         kref_get(&dev->kref);
2113         f->private_data = dev;
2114         return 0;
2115 }
2116
2117 static int nvme_dev_release(struct inode *inode, struct file *f)
2118 {
2119         struct nvme_dev *dev = f->private_data;
2120         kref_put(&dev->kref, nvme_free_dev);
2121         return 0;
2122 }
2123
2124 static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2125 {
2126         struct nvme_dev *dev = f->private_data;
2127         switch (cmd) {
2128         case NVME_IOCTL_ADMIN_CMD:
2129                 return nvme_user_admin_cmd(dev, (void __user *)arg);
2130         default:
2131                 return -ENOTTY;
2132         }
2133 }
2134
2135 static const struct file_operations nvme_dev_fops = {
2136         .owner          = THIS_MODULE,
2137         .open           = nvme_dev_open,
2138         .release        = nvme_dev_release,
2139         .unlocked_ioctl = nvme_dev_ioctl,
2140         .compat_ioctl   = nvme_dev_ioctl,
2141 };
2142
2143 static int nvme_dev_start(struct nvme_dev *dev)
2144 {
2145         int result;
2146
2147         result = nvme_dev_map(dev);
2148         if (result)
2149                 return result;
2150
2151         result = nvme_configure_admin_queue(dev);
2152         if (result)
2153                 goto unmap;
2154
2155         spin_lock(&dev_list_lock);
2156         list_add(&dev->node, &dev_list);
2157         spin_unlock(&dev_list_lock);
2158
2159         result = nvme_setup_io_queues(dev);
2160         if (result && result != -EBUSY)
2161                 goto disable;
2162
2163         return result;
2164
2165  disable:
2166         spin_lock(&dev_list_lock);
2167         list_del_init(&dev->node);
2168         spin_unlock(&dev_list_lock);
2169  unmap:
2170         nvme_dev_unmap(dev);
2171         return result;
2172 }
2173
2174 static int nvme_remove_dead_ctrl(void *arg)
2175 {
2176         struct nvme_dev *dev = (struct nvme_dev *)arg;
2177         struct pci_dev *pdev = dev->pci_dev;
2178
2179         if (pci_get_drvdata(pdev))
2180                 pci_stop_and_remove_bus_device(pdev);
2181         kref_put(&dev->kref, nvme_free_dev);
2182         return 0;
2183 }
2184
2185 static void nvme_remove_disks(struct work_struct *ws)
2186 {
2187         int i;
2188         struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2189
2190         nvme_dev_remove(dev);
2191         spin_lock(&dev_list_lock);
2192         for (i = dev->queue_count - 1; i > 0; i--) {
2193                 BUG_ON(!dev->queues[i] || !dev->queues[i]->q_suspended);
2194                 nvme_free_queue(dev->queues[i]);
2195                 dev->queue_count--;
2196                 dev->queues[i] = NULL;
2197         }
2198         spin_unlock(&dev_list_lock);
2199 }
2200
2201 static int nvme_dev_resume(struct nvme_dev *dev)
2202 {
2203         int ret;
2204
2205         ret = nvme_dev_start(dev);
2206         if (ret && ret != -EBUSY)
2207                 return ret;
2208         if (ret == -EBUSY) {
2209                 spin_lock(&dev_list_lock);
2210                 INIT_WORK(&dev->reset_work, nvme_remove_disks);
2211                 queue_work(nvme_workq, &dev->reset_work);
2212                 spin_unlock(&dev_list_lock);
2213         }
2214         dev->initialized = 1;
2215         return 0;
2216 }
2217
2218 static void nvme_dev_reset(struct nvme_dev *dev)
2219 {
2220         nvme_dev_shutdown(dev);
2221         if (nvme_dev_resume(dev)) {
2222                 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2223                 kref_get(&dev->kref);
2224                 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2225                                                         dev->instance))) {
2226                         dev_err(&dev->pci_dev->dev,
2227                                 "Failed to start controller remove task\n");
2228                         kref_put(&dev->kref, nvme_free_dev);
2229                 }
2230         }
2231 }
2232
2233 static void nvme_reset_failed_dev(struct work_struct *ws)
2234 {
2235         struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2236         nvme_dev_reset(dev);
2237 }
2238
2239 static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
2240 {
2241         int result = -ENOMEM;
2242         struct nvme_dev *dev;
2243
2244         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2245         if (!dev)
2246                 return -ENOMEM;
2247         dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2248                                                                 GFP_KERNEL);
2249         if (!dev->entry)
2250                 goto free;
2251         dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2252                                                                 GFP_KERNEL);
2253         if (!dev->queues)
2254                 goto free;
2255
2256         INIT_LIST_HEAD(&dev->namespaces);
2257         dev->pci_dev = pdev;
2258         pci_set_drvdata(pdev, dev);
2259         result = nvme_set_instance(dev);
2260         if (result)
2261                 goto free;
2262
2263         result = nvme_setup_prp_pools(dev);
2264         if (result)
2265                 goto release;
2266
2267         result = nvme_dev_start(dev);
2268         if (result) {
2269                 if (result == -EBUSY)
2270                         goto create_cdev;
2271                 goto release_pools;
2272         }
2273
2274         result = nvme_dev_add(dev);
2275         if (result)
2276                 goto shutdown;
2277
2278  create_cdev:
2279         scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2280         dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2281         dev->miscdev.parent = &pdev->dev;
2282         dev->miscdev.name = dev->name;
2283         dev->miscdev.fops = &nvme_dev_fops;
2284         result = misc_register(&dev->miscdev);
2285         if (result)
2286                 goto remove;
2287
2288         dev->initialized = 1;
2289         kref_init(&dev->kref);
2290         return 0;
2291
2292  remove:
2293         nvme_dev_remove(dev);
2294  shutdown:
2295         nvme_dev_shutdown(dev);
2296  release_pools:
2297         nvme_free_queues(dev);
2298         nvme_release_prp_pools(dev);
2299  release:
2300         nvme_release_instance(dev);
2301  free:
2302         kfree(dev->queues);
2303         kfree(dev->entry);
2304         kfree(dev);
2305         return result;
2306 }
2307
2308 static void nvme_remove(struct pci_dev *pdev)
2309 {
2310         struct nvme_dev *dev = pci_get_drvdata(pdev);
2311
2312         spin_lock(&dev_list_lock);
2313         list_del_init(&dev->node);
2314         spin_unlock(&dev_list_lock);
2315
2316         pci_set_drvdata(pdev, NULL);
2317         flush_work(&dev->reset_work);
2318         misc_deregister(&dev->miscdev);
2319         nvme_dev_remove(dev);
2320         nvme_dev_shutdown(dev);
2321         nvme_free_queues(dev);
2322         nvme_release_instance(dev);
2323         nvme_release_prp_pools(dev);
2324         kref_put(&dev->kref, nvme_free_dev);
2325 }
2326
2327 /* These functions are yet to be implemented */
2328 #define nvme_error_detected NULL
2329 #define nvme_dump_registers NULL
2330 #define nvme_link_reset NULL
2331 #define nvme_slot_reset NULL
2332 #define nvme_error_resume NULL
2333
2334 static int nvme_suspend(struct device *dev)
2335 {
2336         struct pci_dev *pdev = to_pci_dev(dev);
2337         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2338
2339         nvme_dev_shutdown(ndev);
2340         return 0;
2341 }
2342
2343 static int nvme_resume(struct device *dev)
2344 {
2345         struct pci_dev *pdev = to_pci_dev(dev);
2346         struct nvme_dev *ndev = pci_get_drvdata(pdev);
2347
2348         if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
2349                 INIT_WORK(&ndev->reset_work, nvme_reset_failed_dev);
2350                 queue_work(nvme_workq, &ndev->reset_work);
2351         }
2352         return 0;
2353 }
2354
2355 static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
2356
2357 static const struct pci_error_handlers nvme_err_handler = {
2358         .error_detected = nvme_error_detected,
2359         .mmio_enabled   = nvme_dump_registers,
2360         .link_reset     = nvme_link_reset,
2361         .slot_reset     = nvme_slot_reset,
2362         .resume         = nvme_error_resume,
2363 };
2364
2365 /* Move to pci_ids.h later */
2366 #define PCI_CLASS_STORAGE_EXPRESS       0x010802
2367
2368 static DEFINE_PCI_DEVICE_TABLE(nvme_id_table) = {
2369         { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
2370         { 0, }
2371 };
2372 MODULE_DEVICE_TABLE(pci, nvme_id_table);
2373
2374 static struct pci_driver nvme_driver = {
2375         .name           = "nvme",
2376         .id_table       = nvme_id_table,
2377         .probe          = nvme_probe,
2378         .remove         = nvme_remove,
2379         .driver         = {
2380                 .pm     = &nvme_dev_pm_ops,
2381         },
2382         .err_handler    = &nvme_err_handler,
2383 };
2384
2385 static int __init nvme_init(void)
2386 {
2387         int result;
2388
2389         nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2390         if (IS_ERR(nvme_thread))
2391                 return PTR_ERR(nvme_thread);
2392
2393         result = -ENOMEM;
2394         nvme_workq = create_singlethread_workqueue("nvme");
2395         if (!nvme_workq)
2396                 goto kill_kthread;
2397
2398         result = register_blkdev(nvme_major, "nvme");
2399         if (result < 0)
2400                 goto kill_workq;
2401         else if (result > 0)
2402                 nvme_major = result;
2403
2404         result = pci_register_driver(&nvme_driver);
2405         if (result)
2406                 goto unregister_blkdev;
2407         return 0;
2408
2409  unregister_blkdev:
2410         unregister_blkdev(nvme_major, "nvme");
2411  kill_workq:
2412         destroy_workqueue(nvme_workq);
2413  kill_kthread:
2414         kthread_stop(nvme_thread);
2415         return result;
2416 }
2417
2418 static void __exit nvme_exit(void)
2419 {
2420         pci_unregister_driver(&nvme_driver);
2421         unregister_blkdev(nvme_major, "nvme");
2422         destroy_workqueue(nvme_workq);
2423         kthread_stop(nvme_thread);
2424 }
2425
2426 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
2427 MODULE_LICENSE("GPL");
2428 MODULE_VERSION("0.8");
2429 module_init(nvme_init);
2430 module_exit(nvme_exit);