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