]> git.karo-electronics.de Git - karo-tx-linux.git/blob - drivers/block/nvme.c
NVMe: Add include of delay.h for msleep
[karo-tx-linux.git] / drivers / block / nvme.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/init.h>
28 #include <linux/interrupt.h>
29 #include <linux/io.h>
30 #include <linux/kdev_t.h>
31 #include <linux/kthread.h>
32 #include <linux/kernel.h>
33 #include <linux/mm.h>
34 #include <linux/module.h>
35 #include <linux/moduleparam.h>
36 #include <linux/pci.h>
37 #include <linux/poison.h>
38 #include <linux/sched.h>
39 #include <linux/slab.h>
40 #include <linux/types.h>
41 #include <linux/version.h>
42
43 #define NVME_Q_DEPTH 1024
44 #define SQ_SIZE(depth)          (depth * sizeof(struct nvme_command))
45 #define CQ_SIZE(depth)          (depth * sizeof(struct nvme_completion))
46 #define NVME_MINORS 64
47 #define IO_TIMEOUT      (5 * HZ)
48 #define ADMIN_TIMEOUT   (60 * HZ)
49
50 static int nvme_major;
51 module_param(nvme_major, int, 0);
52
53 static int use_threaded_interrupts;
54 module_param(use_threaded_interrupts, int, 0);
55
56 static DEFINE_SPINLOCK(dev_list_lock);
57 static LIST_HEAD(dev_list);
58 static struct task_struct *nvme_thread;
59
60 /*
61  * Represents an NVM Express device.  Each nvme_dev is a PCI function.
62  */
63 struct nvme_dev {
64         struct list_head node;
65         struct nvme_queue **queues;
66         u32 __iomem *dbs;
67         struct pci_dev *pci_dev;
68         struct dma_pool *prp_page_pool;
69         struct dma_pool *prp_small_pool;
70         int instance;
71         int queue_count;
72         u32 ctrl_config;
73         struct msix_entry *entry;
74         struct nvme_bar __iomem *bar;
75         struct list_head namespaces;
76         char serial[20];
77         char model[40];
78         char firmware_rev[8];
79 };
80
81 /*
82  * An NVM Express namespace is equivalent to a SCSI LUN
83  */
84 struct nvme_ns {
85         struct list_head list;
86
87         struct nvme_dev *dev;
88         struct request_queue *queue;
89         struct gendisk *disk;
90
91         int ns_id;
92         int lba_shift;
93 };
94
95 /*
96  * An NVM Express queue.  Each device has at least two (one for admin
97  * commands and one for I/O commands).
98  */
99 struct nvme_queue {
100         struct device *q_dmadev;
101         struct nvme_dev *dev;
102         spinlock_t q_lock;
103         struct nvme_command *sq_cmds;
104         volatile struct nvme_completion *cqes;
105         dma_addr_t sq_dma_addr;
106         dma_addr_t cq_dma_addr;
107         wait_queue_head_t sq_full;
108         wait_queue_t sq_cong_wait;
109         struct bio_list sq_cong;
110         u32 __iomem *q_db;
111         u16 q_depth;
112         u16 cq_vector;
113         u16 sq_head;
114         u16 sq_tail;
115         u16 cq_head;
116         u16 cq_phase;
117         unsigned long cmdid_data[];
118 };
119
120 /*
121  * Check we didin't inadvertently grow the command struct
122  */
123 static inline void _nvme_check_size(void)
124 {
125         BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
126         BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
127         BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
128         BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
129         BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
130         BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
131         BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
132         BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
133         BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
134 }
135
136 struct nvme_cmd_info {
137         unsigned long ctx;
138         unsigned long timeout;
139 };
140
141 static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
142 {
143         return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
144 }
145
146 /**
147  * alloc_cmdid() - Allocate a Command ID
148  * @nvmeq: The queue that will be used for this command
149  * @ctx: A pointer that will be passed to the handler
150  * @handler: The ID of the handler to call
151  *
152  * Allocate a Command ID for a queue.  The data passed in will
153  * be passed to the completion handler.  This is implemented by using
154  * the bottom two bits of the ctx pointer to store the handler ID.
155  * Passing in a pointer that's not 4-byte aligned will cause a BUG.
156  * We can change this if it becomes a problem.
157  */
158 static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx, int handler,
159                                                         unsigned timeout)
160 {
161         int depth = nvmeq->q_depth - 1;
162         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
163         int cmdid;
164
165         BUG_ON((unsigned long)ctx & 3);
166
167         do {
168                 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
169                 if (cmdid >= depth)
170                         return -EBUSY;
171         } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
172
173         info[cmdid].ctx = (unsigned long)ctx | handler;
174         info[cmdid].timeout = jiffies + timeout;
175         return cmdid;
176 }
177
178 static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
179                                                 int handler, unsigned timeout)
180 {
181         int cmdid;
182         wait_event_killable(nvmeq->sq_full,
183                 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
184         return (cmdid < 0) ? -EINTR : cmdid;
185 }
186
187 /*
188  * If you need more than four handlers, you'll need to change how
189  * alloc_cmdid and nvme_process_cq work.  Consider using a special
190  * CMD_CTX value instead, if that works for your situation.
191  */
192 enum {
193         sync_completion_id = 0,
194         bio_completion_id,
195 };
196
197 /* Special values must be a multiple of 4, and less than 0x1000 */
198 #define CMD_CTX_BASE            (POISON_POINTER_DELTA + sync_completion_id)
199 #define CMD_CTX_CANCELLED       (0x30C + CMD_CTX_BASE)
200 #define CMD_CTX_COMPLETED       (0x310 + CMD_CTX_BASE)
201 #define CMD_CTX_INVALID         (0x314 + CMD_CTX_BASE)
202 #define CMD_CTX_FLUSH           (0x318 + CMD_CTX_BASE)
203
204 static unsigned long free_cmdid(struct nvme_queue *nvmeq, int cmdid)
205 {
206         unsigned long data;
207         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
208
209         if (cmdid >= nvmeq->q_depth)
210                 return CMD_CTX_INVALID;
211         data = info[cmdid].ctx;
212         info[cmdid].ctx = CMD_CTX_COMPLETED;
213         clear_bit(cmdid, nvmeq->cmdid_data);
214         wake_up(&nvmeq->sq_full);
215         return data;
216 }
217
218 static unsigned long cancel_cmdid(struct nvme_queue *nvmeq, int cmdid)
219 {
220         unsigned long data;
221         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
222         data = info[cmdid].ctx;
223         info[cmdid].ctx = CMD_CTX_CANCELLED;
224         return data;
225 }
226
227 static struct nvme_queue *get_nvmeq(struct nvme_ns *ns)
228 {
229         return ns->dev->queues[get_cpu() + 1];
230 }
231
232 static void put_nvmeq(struct nvme_queue *nvmeq)
233 {
234         put_cpu();
235 }
236
237 /**
238  * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
239  * @nvmeq: The queue to use
240  * @cmd: The command to send
241  *
242  * Safe to use from interrupt context
243  */
244 static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
245 {
246         unsigned long flags;
247         u16 tail;
248         spin_lock_irqsave(&nvmeq->q_lock, flags);
249         tail = nvmeq->sq_tail;
250         memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
251         if (++tail == nvmeq->q_depth)
252                 tail = 0;
253         writel(tail, nvmeq->q_db);
254         nvmeq->sq_tail = tail;
255         spin_unlock_irqrestore(&nvmeq->q_lock, flags);
256
257         return 0;
258 }
259
260 struct nvme_prps {
261         int npages;
262         dma_addr_t first_dma;
263         __le64 *list[0];
264 };
265
266 static void nvme_free_prps(struct nvme_dev *dev, struct nvme_prps *prps)
267 {
268         const int last_prp = PAGE_SIZE / 8 - 1;
269         int i;
270         dma_addr_t prp_dma;
271
272         if (!prps)
273                 return;
274
275         prp_dma = prps->first_dma;
276
277         if (prps->npages == 0)
278                 dma_pool_free(dev->prp_small_pool, prps->list[0], prp_dma);
279         for (i = 0; i < prps->npages; i++) {
280                 __le64 *prp_list = prps->list[i];
281                 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
282                 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
283                 prp_dma = next_prp_dma;
284         }
285         kfree(prps);
286 }
287
288 struct nvme_bio {
289         struct bio *bio;
290         int nents;
291         struct nvme_prps *prps;
292         struct scatterlist sg[0];
293 };
294
295 /* XXX: use a mempool */
296 static struct nvme_bio *alloc_nbio(unsigned nseg, gfp_t gfp)
297 {
298         return kzalloc(sizeof(struct nvme_bio) +
299                         sizeof(struct scatterlist) * nseg, gfp);
300 }
301
302 static void free_nbio(struct nvme_queue *nvmeq, struct nvme_bio *nbio)
303 {
304         nvme_free_prps(nvmeq->dev, nbio->prps);
305         kfree(nbio);
306 }
307
308 static void bio_completion(struct nvme_queue *nvmeq, void *ctx,
309                                                 struct nvme_completion *cqe)
310 {
311         struct nvme_bio *nbio = ctx;
312         struct bio *bio = nbio->bio;
313         u16 status = le16_to_cpup(&cqe->status) >> 1;
314
315         dma_unmap_sg(nvmeq->q_dmadev, nbio->sg, nbio->nents,
316                         bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
317         free_nbio(nvmeq, nbio);
318         if (status) {
319                 bio_endio(bio, -EIO);
320         } else if (bio->bi_vcnt > bio->bi_idx) {
321                 bio_list_add(&nvmeq->sq_cong, bio);
322                 wake_up_process(nvme_thread);
323         } else {
324                 bio_endio(bio, 0);
325         }
326 }
327
328 /* length is in bytes */
329 static struct nvme_prps *nvme_setup_prps(struct nvme_dev *dev,
330                                         struct nvme_common_command *cmd,
331                                         struct scatterlist *sg, int length)
332 {
333         struct dma_pool *pool;
334         int dma_len = sg_dma_len(sg);
335         u64 dma_addr = sg_dma_address(sg);
336         int offset = offset_in_page(dma_addr);
337         __le64 *prp_list;
338         dma_addr_t prp_dma;
339         int nprps, npages, i, prp_page;
340         struct nvme_prps *prps = NULL;
341
342         cmd->prp1 = cpu_to_le64(dma_addr);
343         length -= (PAGE_SIZE - offset);
344         if (length <= 0)
345                 return prps;
346
347         dma_len -= (PAGE_SIZE - offset);
348         if (dma_len) {
349                 dma_addr += (PAGE_SIZE - offset);
350         } else {
351                 sg = sg_next(sg);
352                 dma_addr = sg_dma_address(sg);
353                 dma_len = sg_dma_len(sg);
354         }
355
356         if (length <= PAGE_SIZE) {
357                 cmd->prp2 = cpu_to_le64(dma_addr);
358                 return prps;
359         }
360
361         nprps = DIV_ROUND_UP(length, PAGE_SIZE);
362         npages = DIV_ROUND_UP(8 * nprps, PAGE_SIZE);
363         prps = kmalloc(sizeof(*prps) + sizeof(__le64 *) * npages, GFP_ATOMIC);
364         prp_page = 0;
365         if (nprps <= (256 / 8)) {
366                 pool = dev->prp_small_pool;
367                 prps->npages = 0;
368         } else {
369                 pool = dev->prp_page_pool;
370                 prps->npages = npages;
371         }
372
373         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
374         prps->list[prp_page++] = prp_list;
375         prps->first_dma = prp_dma;
376         cmd->prp2 = cpu_to_le64(prp_dma);
377         i = 0;
378         for (;;) {
379                 if (i == PAGE_SIZE / 8) {
380                         __le64 *old_prp_list = prp_list;
381                         prp_list = dma_pool_alloc(pool, GFP_ATOMIC, &prp_dma);
382                         prps->list[prp_page++] = prp_list;
383                         prp_list[0] = old_prp_list[i - 1];
384                         old_prp_list[i - 1] = cpu_to_le64(prp_dma);
385                         i = 1;
386                 }
387                 prp_list[i++] = cpu_to_le64(dma_addr);
388                 dma_len -= PAGE_SIZE;
389                 dma_addr += PAGE_SIZE;
390                 length -= PAGE_SIZE;
391                 if (length <= 0)
392                         break;
393                 if (dma_len > 0)
394                         continue;
395                 BUG_ON(dma_len < 0);
396                 sg = sg_next(sg);
397                 dma_addr = sg_dma_address(sg);
398                 dma_len = sg_dma_len(sg);
399         }
400
401         return prps;
402 }
403
404 /* NVMe scatterlists require no holes in the virtual address */
405 #define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2)   ((vec2)->bv_offset || \
406                         (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
407
408 static int nvme_map_bio(struct device *dev, struct nvme_bio *nbio,
409                 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
410 {
411         struct bio_vec *bvec, *bvprv = NULL;
412         struct scatterlist *sg = NULL;
413         int i, old_idx, length = 0, nsegs = 0;
414
415         sg_init_table(nbio->sg, psegs);
416         old_idx = bio->bi_idx;
417         bio_for_each_segment(bvec, bio, i) {
418                 if (bvprv && BIOVEC_PHYS_MERGEABLE(bvprv, bvec)) {
419                         sg->length += bvec->bv_len;
420                 } else {
421                         if (bvprv && BIOVEC_NOT_VIRT_MERGEABLE(bvprv, bvec))
422                                 break;
423                         sg = sg ? sg + 1 : nbio->sg;
424                         sg_set_page(sg, bvec->bv_page, bvec->bv_len,
425                                                         bvec->bv_offset);
426                         nsegs++;
427                 }
428                 length += bvec->bv_len;
429                 bvprv = bvec;
430         }
431         bio->bi_idx = i;
432         nbio->nents = nsegs;
433         sg_mark_end(sg);
434         if (dma_map_sg(dev, nbio->sg, nbio->nents, dma_dir) == 0) {
435                 bio->bi_idx = old_idx;
436                 return -ENOMEM;
437         }
438         return length;
439 }
440
441 static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
442                                                                 int cmdid)
443 {
444         struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
445
446         memset(cmnd, 0, sizeof(*cmnd));
447         cmnd->common.opcode = nvme_cmd_flush;
448         cmnd->common.command_id = cmdid;
449         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
450
451         if (++nvmeq->sq_tail == nvmeq->q_depth)
452                 nvmeq->sq_tail = 0;
453         writel(nvmeq->sq_tail, nvmeq->q_db);
454
455         return 0;
456 }
457
458 static int nvme_submit_flush_data(struct nvme_queue *nvmeq, struct nvme_ns *ns)
459 {
460         int cmdid = alloc_cmdid(nvmeq, (void *)CMD_CTX_FLUSH,
461                                                 sync_completion_id, IO_TIMEOUT);
462         if (unlikely(cmdid < 0))
463                 return cmdid;
464
465         return nvme_submit_flush(nvmeq, ns, cmdid);
466 }
467
468 static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
469                                                                 struct bio *bio)
470 {
471         struct nvme_command *cmnd;
472         struct nvme_bio *nbio;
473         enum dma_data_direction dma_dir;
474         int cmdid, length, result = -ENOMEM;
475         u16 control;
476         u32 dsmgmt;
477         int psegs = bio_phys_segments(ns->queue, bio);
478
479         if ((bio->bi_rw & REQ_FLUSH) && psegs) {
480                 result = nvme_submit_flush_data(nvmeq, ns);
481                 if (result)
482                         return result;
483         }
484
485         nbio = alloc_nbio(psegs, GFP_ATOMIC);
486         if (!nbio)
487                 goto nomem;
488         nbio->bio = bio;
489
490         result = -EBUSY;
491         cmdid = alloc_cmdid(nvmeq, nbio, bio_completion_id, IO_TIMEOUT);
492         if (unlikely(cmdid < 0))
493                 goto free_nbio;
494
495         if ((bio->bi_rw & REQ_FLUSH) && !psegs)
496                 return nvme_submit_flush(nvmeq, ns, cmdid);
497
498         control = 0;
499         if (bio->bi_rw & REQ_FUA)
500                 control |= NVME_RW_FUA;
501         if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
502                 control |= NVME_RW_LR;
503
504         dsmgmt = 0;
505         if (bio->bi_rw & REQ_RAHEAD)
506                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
507
508         cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
509
510         memset(cmnd, 0, sizeof(*cmnd));
511         if (bio_data_dir(bio)) {
512                 cmnd->rw.opcode = nvme_cmd_write;
513                 dma_dir = DMA_TO_DEVICE;
514         } else {
515                 cmnd->rw.opcode = nvme_cmd_read;
516                 dma_dir = DMA_FROM_DEVICE;
517         }
518
519         result = nvme_map_bio(nvmeq->q_dmadev, nbio, bio, dma_dir, psegs);
520         if (result < 0)
521                 goto free_nbio;
522         length = result;
523
524         cmnd->rw.command_id = cmdid;
525         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
526         nbio->prps = nvme_setup_prps(nvmeq->dev, &cmnd->common, nbio->sg,
527                                                                 length);
528         cmnd->rw.slba = cpu_to_le64(bio->bi_sector >> (ns->lba_shift - 9));
529         cmnd->rw.length = cpu_to_le16((length >> ns->lba_shift) - 1);
530         cmnd->rw.control = cpu_to_le16(control);
531         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
532
533         bio->bi_sector += length >> 9;
534
535         if (++nvmeq->sq_tail == nvmeq->q_depth)
536                 nvmeq->sq_tail = 0;
537         writel(nvmeq->sq_tail, nvmeq->q_db);
538
539         return 0;
540
541  free_nbio:
542         free_nbio(nvmeq, nbio);
543  nomem:
544         return result;
545 }
546
547 /*
548  * NB: return value of non-zero would mean that we were a stacking driver.
549  * make_request must always succeed.
550  */
551 static int nvme_make_request(struct request_queue *q, struct bio *bio)
552 {
553         struct nvme_ns *ns = q->queuedata;
554         struct nvme_queue *nvmeq = get_nvmeq(ns);
555         int result = -EBUSY;
556
557         spin_lock_irq(&nvmeq->q_lock);
558         if (bio_list_empty(&nvmeq->sq_cong))
559                 result = nvme_submit_bio_queue(nvmeq, ns, bio);
560         if (unlikely(result)) {
561                 if (bio_list_empty(&nvmeq->sq_cong))
562                         add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
563                 bio_list_add(&nvmeq->sq_cong, bio);
564         }
565
566         spin_unlock_irq(&nvmeq->q_lock);
567         put_nvmeq(nvmeq);
568
569         return 0;
570 }
571
572 struct sync_cmd_info {
573         struct task_struct *task;
574         u32 result;
575         int status;
576 };
577
578 static void sync_completion(struct nvme_queue *nvmeq, void *ctx,
579                                                 struct nvme_completion *cqe)
580 {
581         struct sync_cmd_info *cmdinfo = ctx;
582         if (unlikely((unsigned long)cmdinfo == CMD_CTX_CANCELLED))
583                 return;
584         if ((unsigned long)cmdinfo == CMD_CTX_FLUSH)
585                 return;
586         if (unlikely((unsigned long)cmdinfo == CMD_CTX_COMPLETED)) {
587                 dev_warn(nvmeq->q_dmadev,
588                                 "completed id %d twice on queue %d\n",
589                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
590                 return;
591         }
592         if (unlikely((unsigned long)cmdinfo == CMD_CTX_INVALID)) {
593                 dev_warn(nvmeq->q_dmadev,
594                                 "invalid id %d completed on queue %d\n",
595                                 cqe->command_id, le16_to_cpup(&cqe->sq_id));
596                 return;
597         }
598         cmdinfo->result = le32_to_cpup(&cqe->result);
599         cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
600         wake_up_process(cmdinfo->task);
601 }
602
603 typedef void (*completion_fn)(struct nvme_queue *, void *,
604                                                 struct nvme_completion *);
605
606 static const completion_fn nvme_completions[4] = {
607         [sync_completion_id] = sync_completion,
608         [bio_completion_id]  = bio_completion,
609 };
610
611 static irqreturn_t nvme_process_cq(struct nvme_queue *nvmeq)
612 {
613         u16 head, phase;
614
615         head = nvmeq->cq_head;
616         phase = nvmeq->cq_phase;
617
618         for (;;) {
619                 unsigned long data;
620                 void *ptr;
621                 unsigned char handler;
622                 struct nvme_completion cqe = nvmeq->cqes[head];
623                 if ((le16_to_cpu(cqe.status) & 1) != phase)
624                         break;
625                 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
626                 if (++head == nvmeq->q_depth) {
627                         head = 0;
628                         phase = !phase;
629                 }
630
631                 data = free_cmdid(nvmeq, cqe.command_id);
632                 handler = data & 3;
633                 ptr = (void *)(data & ~3UL);
634                 nvme_completions[handler](nvmeq, ptr, &cqe);
635         }
636
637         /* If the controller ignores the cq head doorbell and continuously
638          * writes to the queue, it is theoretically possible to wrap around
639          * the queue twice and mistakenly return IRQ_NONE.  Linux only
640          * requires that 0.1% of your interrupts are handled, so this isn't
641          * a big problem.
642          */
643         if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
644                 return IRQ_NONE;
645
646         writel(head, nvmeq->q_db + 1);
647         nvmeq->cq_head = head;
648         nvmeq->cq_phase = phase;
649
650         return IRQ_HANDLED;
651 }
652
653 static irqreturn_t nvme_irq(int irq, void *data)
654 {
655         irqreturn_t result;
656         struct nvme_queue *nvmeq = data;
657         spin_lock(&nvmeq->q_lock);
658         result = nvme_process_cq(nvmeq);
659         spin_unlock(&nvmeq->q_lock);
660         return result;
661 }
662
663 static irqreturn_t nvme_irq_check(int irq, void *data)
664 {
665         struct nvme_queue *nvmeq = data;
666         struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
667         if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
668                 return IRQ_NONE;
669         return IRQ_WAKE_THREAD;
670 }
671
672 static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
673 {
674         spin_lock_irq(&nvmeq->q_lock);
675         cancel_cmdid(nvmeq, cmdid);
676         spin_unlock_irq(&nvmeq->q_lock);
677 }
678
679 /*
680  * Returns 0 on success.  If the result is negative, it's a Linux error code;
681  * if the result is positive, it's an NVM Express status code
682  */
683 static int nvme_submit_sync_cmd(struct nvme_queue *nvmeq,
684                         struct nvme_command *cmd, u32 *result, unsigned timeout)
685 {
686         int cmdid;
687         struct sync_cmd_info cmdinfo;
688
689         cmdinfo.task = current;
690         cmdinfo.status = -EINTR;
691
692         cmdid = alloc_cmdid_killable(nvmeq, &cmdinfo, sync_completion_id,
693                                                                 timeout);
694         if (cmdid < 0)
695                 return cmdid;
696         cmd->common.command_id = cmdid;
697
698         set_current_state(TASK_KILLABLE);
699         nvme_submit_cmd(nvmeq, cmd);
700         schedule();
701
702         if (cmdinfo.status == -EINTR) {
703                 nvme_abort_command(nvmeq, cmdid);
704                 return -EINTR;
705         }
706
707         if (result)
708                 *result = cmdinfo.result;
709
710         return cmdinfo.status;
711 }
712
713 static int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
714                                                                 u32 *result)
715 {
716         return nvme_submit_sync_cmd(dev->queues[0], cmd, result, ADMIN_TIMEOUT);
717 }
718
719 static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
720 {
721         int status;
722         struct nvme_command c;
723
724         memset(&c, 0, sizeof(c));
725         c.delete_queue.opcode = opcode;
726         c.delete_queue.qid = cpu_to_le16(id);
727
728         status = nvme_submit_admin_cmd(dev, &c, NULL);
729         if (status)
730                 return -EIO;
731         return 0;
732 }
733
734 static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
735                                                 struct nvme_queue *nvmeq)
736 {
737         int status;
738         struct nvme_command c;
739         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
740
741         memset(&c, 0, sizeof(c));
742         c.create_cq.opcode = nvme_admin_create_cq;
743         c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
744         c.create_cq.cqid = cpu_to_le16(qid);
745         c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
746         c.create_cq.cq_flags = cpu_to_le16(flags);
747         c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
748
749         status = nvme_submit_admin_cmd(dev, &c, NULL);
750         if (status)
751                 return -EIO;
752         return 0;
753 }
754
755 static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
756                                                 struct nvme_queue *nvmeq)
757 {
758         int status;
759         struct nvme_command c;
760         int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
761
762         memset(&c, 0, sizeof(c));
763         c.create_sq.opcode = nvme_admin_create_sq;
764         c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
765         c.create_sq.sqid = cpu_to_le16(qid);
766         c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
767         c.create_sq.sq_flags = cpu_to_le16(flags);
768         c.create_sq.cqid = cpu_to_le16(qid);
769
770         status = nvme_submit_admin_cmd(dev, &c, NULL);
771         if (status)
772                 return -EIO;
773         return 0;
774 }
775
776 static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
777 {
778         return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
779 }
780
781 static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
782 {
783         return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
784 }
785
786 static void nvme_free_queue(struct nvme_dev *dev, int qid)
787 {
788         struct nvme_queue *nvmeq = dev->queues[qid];
789         int vector = dev->entry[nvmeq->cq_vector].vector;
790
791         irq_set_affinity_hint(vector, NULL);
792         free_irq(vector, nvmeq);
793
794         /* Don't tell the adapter to delete the admin queue */
795         if (qid) {
796                 adapter_delete_sq(dev, qid);
797                 adapter_delete_cq(dev, qid);
798         }
799
800         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
801                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
802         dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
803                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
804         kfree(nvmeq);
805 }
806
807 static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
808                                                         int depth, int vector)
809 {
810         struct device *dmadev = &dev->pci_dev->dev;
811         unsigned extra = (depth / 8) + (depth * sizeof(struct nvme_cmd_info));
812         struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
813         if (!nvmeq)
814                 return NULL;
815
816         nvmeq->cqes = dma_alloc_coherent(dmadev, CQ_SIZE(depth),
817                                         &nvmeq->cq_dma_addr, GFP_KERNEL);
818         if (!nvmeq->cqes)
819                 goto free_nvmeq;
820         memset((void *)nvmeq->cqes, 0, CQ_SIZE(depth));
821
822         nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
823                                         &nvmeq->sq_dma_addr, GFP_KERNEL);
824         if (!nvmeq->sq_cmds)
825                 goto free_cqdma;
826
827         nvmeq->q_dmadev = dmadev;
828         nvmeq->dev = dev;
829         spin_lock_init(&nvmeq->q_lock);
830         nvmeq->cq_head = 0;
831         nvmeq->cq_phase = 1;
832         init_waitqueue_head(&nvmeq->sq_full);
833         init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
834         bio_list_init(&nvmeq->sq_cong);
835         nvmeq->q_db = &dev->dbs[qid * 2];
836         nvmeq->q_depth = depth;
837         nvmeq->cq_vector = vector;
838
839         return nvmeq;
840
841  free_cqdma:
842         dma_free_coherent(dmadev, CQ_SIZE(nvmeq->q_depth), (void *)nvmeq->cqes,
843                                                         nvmeq->cq_dma_addr);
844  free_nvmeq:
845         kfree(nvmeq);
846         return NULL;
847 }
848
849 static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
850                                                         const char *name)
851 {
852         if (use_threaded_interrupts)
853                 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
854                                         nvme_irq_check, nvme_irq,
855                                         IRQF_DISABLED | IRQF_SHARED,
856                                         name, nvmeq);
857         return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
858                                 IRQF_DISABLED | IRQF_SHARED, name, nvmeq);
859 }
860
861 static __devinit struct nvme_queue *nvme_create_queue(struct nvme_dev *dev,
862                                         int qid, int cq_size, int vector)
863 {
864         int result;
865         struct nvme_queue *nvmeq = nvme_alloc_queue(dev, qid, cq_size, vector);
866
867         if (!nvmeq)
868                 return NULL;
869
870         result = adapter_alloc_cq(dev, qid, nvmeq);
871         if (result < 0)
872                 goto free_nvmeq;
873
874         result = adapter_alloc_sq(dev, qid, nvmeq);
875         if (result < 0)
876                 goto release_cq;
877
878         result = queue_request_irq(dev, nvmeq, "nvme");
879         if (result < 0)
880                 goto release_sq;
881
882         return nvmeq;
883
884  release_sq:
885         adapter_delete_sq(dev, qid);
886  release_cq:
887         adapter_delete_cq(dev, qid);
888  free_nvmeq:
889         dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
890                                 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
891         dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
892                                         nvmeq->sq_cmds, nvmeq->sq_dma_addr);
893         kfree(nvmeq);
894         return NULL;
895 }
896
897 static int __devinit nvme_configure_admin_queue(struct nvme_dev *dev)
898 {
899         int result;
900         u32 aqa;
901         u64 cap;
902         unsigned long timeout;
903         struct nvme_queue *nvmeq;
904
905         dev->dbs = ((void __iomem *)dev->bar) + 4096;
906
907         nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
908         if (!nvmeq)
909                 return -ENOMEM;
910
911         aqa = nvmeq->q_depth - 1;
912         aqa |= aqa << 16;
913
914         dev->ctrl_config = NVME_CC_ENABLE | NVME_CC_CSS_NVM;
915         dev->ctrl_config |= (PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
916         dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
917         dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
918
919         writel(0, &dev->bar->cc);
920         writel(aqa, &dev->bar->aqa);
921         writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
922         writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
923         writel(dev->ctrl_config, &dev->bar->cc);
924
925         cap = readq(&dev->bar->cap);
926         timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
927
928         while (!(readl(&dev->bar->csts) & NVME_CSTS_RDY)) {
929                 msleep(100);
930                 if (fatal_signal_pending(current))
931                         return -EINTR;
932                 if (time_after(jiffies, timeout)) {
933                         dev_err(&dev->pci_dev->dev,
934                                 "Device not ready; aborting initialisation\n");
935                         return -ENODEV;
936                 }
937         }
938
939         result = queue_request_irq(dev, nvmeq, "nvme admin");
940         dev->queues[0] = nvmeq;
941         return result;
942 }
943
944 static int nvme_map_user_pages(struct nvme_dev *dev, int write,
945                                 unsigned long addr, unsigned length,
946                                 struct scatterlist **sgp)
947 {
948         int i, err, count, nents, offset;
949         struct scatterlist *sg;
950         struct page **pages;
951
952         if (addr & 3)
953                 return -EINVAL;
954         if (!length)
955                 return -EINVAL;
956
957         offset = offset_in_page(addr);
958         count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
959         pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
960
961         err = get_user_pages_fast(addr, count, 1, pages);
962         if (err < count) {
963                 count = err;
964                 err = -EFAULT;
965                 goto put_pages;
966         }
967
968         sg = kcalloc(count, sizeof(*sg), GFP_KERNEL);
969         sg_init_table(sg, count);
970         sg_set_page(&sg[0], pages[0], PAGE_SIZE - offset, offset);
971         length -= (PAGE_SIZE - offset);
972         for (i = 1; i < count; i++) {
973                 sg_set_page(&sg[i], pages[i], min_t(int, length, PAGE_SIZE), 0);
974                 length -= PAGE_SIZE;
975         }
976
977         err = -ENOMEM;
978         nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
979                                 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
980         if (!nents)
981                 goto put_pages;
982
983         kfree(pages);
984         *sgp = sg;
985         return nents;
986
987  put_pages:
988         for (i = 0; i < count; i++)
989                 put_page(pages[i]);
990         kfree(pages);
991         return err;
992 }
993
994 static void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
995                                 unsigned long addr, int length,
996                                 struct scatterlist *sg, int nents)
997 {
998         int i, count;
999
1000         count = DIV_ROUND_UP(offset_in_page(addr) + length, PAGE_SIZE);
1001         dma_unmap_sg(&dev->pci_dev->dev, sg, nents, DMA_FROM_DEVICE);
1002
1003         for (i = 0; i < count; i++)
1004                 put_page(sg_page(&sg[i]));
1005 }
1006
1007 static int nvme_submit_user_admin_command(struct nvme_dev *dev,
1008                                         unsigned long addr, unsigned length,
1009                                         struct nvme_command *cmd)
1010 {
1011         int err, nents;
1012         struct scatterlist *sg;
1013         struct nvme_prps *prps;
1014
1015         nents = nvme_map_user_pages(dev, 0, addr, length, &sg);
1016         if (nents < 0)
1017                 return nents;
1018         prps = nvme_setup_prps(dev, &cmd->common, sg, length);
1019         err = nvme_submit_admin_cmd(dev, cmd, NULL);
1020         nvme_unmap_user_pages(dev, 0, addr, length, sg, nents);
1021         nvme_free_prps(dev, prps);
1022         return err ? -EIO : 0;
1023 }
1024
1025 static int nvme_identify(struct nvme_ns *ns, unsigned long addr, int cns)
1026 {
1027         struct nvme_command c;
1028
1029         memset(&c, 0, sizeof(c));
1030         c.identify.opcode = nvme_admin_identify;
1031         c.identify.nsid = cns ? 0 : cpu_to_le32(ns->ns_id);
1032         c.identify.cns = cpu_to_le32(cns);
1033
1034         return nvme_submit_user_admin_command(ns->dev, addr, 4096, &c);
1035 }
1036
1037 static int nvme_get_range_type(struct nvme_ns *ns, unsigned long addr)
1038 {
1039         struct nvme_command c;
1040
1041         memset(&c, 0, sizeof(c));
1042         c.features.opcode = nvme_admin_get_features;
1043         c.features.nsid = cpu_to_le32(ns->ns_id);
1044         c.features.fid = cpu_to_le32(NVME_FEAT_LBA_RANGE);
1045
1046         return nvme_submit_user_admin_command(ns->dev, addr, 4096, &c);
1047 }
1048
1049 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1050 {
1051         struct nvme_dev *dev = ns->dev;
1052         struct nvme_queue *nvmeq;
1053         struct nvme_user_io io;
1054         struct nvme_command c;
1055         unsigned length;
1056         int nents, status;
1057         struct scatterlist *sg;
1058         struct nvme_prps *prps;
1059
1060         if (copy_from_user(&io, uio, sizeof(io)))
1061                 return -EFAULT;
1062         length = (io.nblocks + 1) << ns->lba_shift;
1063
1064         switch (io.opcode) {
1065         case nvme_cmd_write:
1066         case nvme_cmd_read:
1067                 nents = nvme_map_user_pages(dev, io.opcode & 1, io.addr,
1068                                                                 length, &sg);
1069         default:
1070                 return -EFAULT;
1071         }
1072
1073         if (nents < 0)
1074                 return nents;
1075
1076         memset(&c, 0, sizeof(c));
1077         c.rw.opcode = io.opcode;
1078         c.rw.flags = io.flags;
1079         c.rw.nsid = cpu_to_le32(ns->ns_id);
1080         c.rw.slba = cpu_to_le64(io.slba);
1081         c.rw.length = cpu_to_le16(io.nblocks);
1082         c.rw.control = cpu_to_le16(io.control);
1083         c.rw.dsmgmt = cpu_to_le16(io.dsmgmt);
1084         c.rw.reftag = io.reftag;
1085         c.rw.apptag = io.apptag;
1086         c.rw.appmask = io.appmask;
1087         /* XXX: metadata */
1088         prps = nvme_setup_prps(dev, &c.common, sg, length);
1089
1090         nvmeq = get_nvmeq(ns);
1091         /*
1092          * Since nvme_submit_sync_cmd sleeps, we can't keep preemption
1093          * disabled.  We may be preempted at any point, and be rescheduled
1094          * to a different CPU.  That will cause cacheline bouncing, but no
1095          * additional races since q_lock already protects against other CPUs.
1096          */
1097         put_nvmeq(nvmeq);
1098         status = nvme_submit_sync_cmd(nvmeq, &c, NULL, IO_TIMEOUT);
1099
1100         nvme_unmap_user_pages(dev, io.opcode & 1, io.addr, length, sg, nents);
1101         nvme_free_prps(dev, prps);
1102         return status;
1103 }
1104
1105 static int nvme_download_firmware(struct nvme_ns *ns,
1106                                                 struct nvme_dlfw __user *udlfw)
1107 {
1108         struct nvme_dev *dev = ns->dev;
1109         struct nvme_dlfw dlfw;
1110         struct nvme_command c;
1111         int nents, status;
1112         struct scatterlist *sg;
1113         struct nvme_prps *prps;
1114
1115         if (copy_from_user(&dlfw, udlfw, sizeof(dlfw)))
1116                 return -EFAULT;
1117         if (dlfw.length >= (1 << 30))
1118                 return -EINVAL;
1119
1120         nents = nvme_map_user_pages(dev, 1, dlfw.addr, dlfw.length * 4, &sg);
1121         if (nents < 0)
1122                 return nents;
1123
1124         memset(&c, 0, sizeof(c));
1125         c.dlfw.opcode = nvme_admin_download_fw;
1126         c.dlfw.numd = cpu_to_le32(dlfw.length);
1127         c.dlfw.offset = cpu_to_le32(dlfw.offset);
1128         prps = nvme_setup_prps(dev, &c.common, sg, dlfw.length * 4);
1129
1130         status = nvme_submit_admin_cmd(dev, &c, NULL);
1131         nvme_unmap_user_pages(dev, 0, dlfw.addr, dlfw.length * 4, sg, nents);
1132         nvme_free_prps(dev, prps);
1133         return status;
1134 }
1135
1136 static int nvme_activate_firmware(struct nvme_ns *ns, unsigned long arg)
1137 {
1138         struct nvme_dev *dev = ns->dev;
1139         struct nvme_command c;
1140
1141         memset(&c, 0, sizeof(c));
1142         c.common.opcode = nvme_admin_activate_fw;
1143         c.common.rsvd10[0] = cpu_to_le32(arg);
1144
1145         return nvme_submit_admin_cmd(dev, &c, NULL);
1146 }
1147
1148 static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1149                                                         unsigned long arg)
1150 {
1151         struct nvme_ns *ns = bdev->bd_disk->private_data;
1152
1153         switch (cmd) {
1154         case NVME_IOCTL_IDENTIFY_NS:
1155                 return nvme_identify(ns, arg, 0);
1156         case NVME_IOCTL_IDENTIFY_CTRL:
1157                 return nvme_identify(ns, arg, 1);
1158         case NVME_IOCTL_GET_RANGE_TYPE:
1159                 return nvme_get_range_type(ns, arg);
1160         case NVME_IOCTL_SUBMIT_IO:
1161                 return nvme_submit_io(ns, (void __user *)arg);
1162         case NVME_IOCTL_DOWNLOAD_FW:
1163                 return nvme_download_firmware(ns, (void __user *)arg);
1164         case NVME_IOCTL_ACTIVATE_FW:
1165                 return nvme_activate_firmware(ns, arg);
1166         default:
1167                 return -ENOTTY;
1168         }
1169 }
1170
1171 static const struct block_device_operations nvme_fops = {
1172         .owner          = THIS_MODULE,
1173         .ioctl          = nvme_ioctl,
1174         .compat_ioctl   = nvme_ioctl,
1175 };
1176
1177 static void nvme_timeout_ios(struct nvme_queue *nvmeq)
1178 {
1179         int depth = nvmeq->q_depth - 1;
1180         struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1181         unsigned long now = jiffies;
1182         int cmdid;
1183
1184         for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1185                 unsigned long data;
1186                 void *ptr;
1187                 unsigned char handler;
1188                 static struct nvme_completion cqe = { .status = cpu_to_le16(NVME_SC_ABORT_REQ) << 1, };
1189
1190                 if (!time_after(now, info[cmdid].timeout))
1191                         continue;
1192                 dev_warn(nvmeq->q_dmadev, "Timing out I/O %d\n", cmdid);
1193                 data = cancel_cmdid(nvmeq, cmdid);
1194                 handler = data & 3;
1195                 ptr = (void *)(data & ~3UL);
1196                 nvme_completions[handler](nvmeq, ptr, &cqe);
1197         }
1198 }
1199
1200 static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1201 {
1202         while (bio_list_peek(&nvmeq->sq_cong)) {
1203                 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1204                 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
1205                 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
1206                         bio_list_add_head(&nvmeq->sq_cong, bio);
1207                         break;
1208                 }
1209                 if (bio_list_empty(&nvmeq->sq_cong))
1210                         remove_wait_queue(&nvmeq->sq_full,
1211                                                         &nvmeq->sq_cong_wait);
1212         }
1213 }
1214
1215 static int nvme_kthread(void *data)
1216 {
1217         struct nvme_dev *dev;
1218
1219         while (!kthread_should_stop()) {
1220                 __set_current_state(TASK_RUNNING);
1221                 spin_lock(&dev_list_lock);
1222                 list_for_each_entry(dev, &dev_list, node) {
1223                         int i;
1224                         for (i = 0; i < dev->queue_count; i++) {
1225                                 struct nvme_queue *nvmeq = dev->queues[i];
1226                                 if (!nvmeq)
1227                                         continue;
1228                                 spin_lock_irq(&nvmeq->q_lock);
1229                                 if (nvme_process_cq(nvmeq))
1230                                         printk("process_cq did something\n");
1231                                 nvme_timeout_ios(nvmeq);
1232                                 nvme_resubmit_bios(nvmeq);
1233                                 spin_unlock_irq(&nvmeq->q_lock);
1234                         }
1235                 }
1236                 spin_unlock(&dev_list_lock);
1237                 set_current_state(TASK_INTERRUPTIBLE);
1238                 schedule_timeout(HZ);
1239         }
1240         return 0;
1241 }
1242
1243 static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, int index,
1244                         struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
1245 {
1246         struct nvme_ns *ns;
1247         struct gendisk *disk;
1248         int lbaf;
1249
1250         if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
1251                 return NULL;
1252
1253         ns = kzalloc(sizeof(*ns), GFP_KERNEL);
1254         if (!ns)
1255                 return NULL;
1256         ns->queue = blk_alloc_queue(GFP_KERNEL);
1257         if (!ns->queue)
1258                 goto out_free_ns;
1259         ns->queue->queue_flags = QUEUE_FLAG_DEFAULT | QUEUE_FLAG_NOMERGES |
1260                                 QUEUE_FLAG_NONROT | QUEUE_FLAG_DISCARD;
1261         blk_queue_make_request(ns->queue, nvme_make_request);
1262         ns->dev = dev;
1263         ns->queue->queuedata = ns;
1264
1265         disk = alloc_disk(NVME_MINORS);
1266         if (!disk)
1267                 goto out_free_queue;
1268         ns->ns_id = index;
1269         ns->disk = disk;
1270         lbaf = id->flbas & 0xf;
1271         ns->lba_shift = id->lbaf[lbaf].ds;
1272
1273         disk->major = nvme_major;
1274         disk->minors = NVME_MINORS;
1275         disk->first_minor = NVME_MINORS * index;
1276         disk->fops = &nvme_fops;
1277         disk->private_data = ns;
1278         disk->queue = ns->queue;
1279         disk->driverfs_dev = &dev->pci_dev->dev;
1280         sprintf(disk->disk_name, "nvme%dn%d", dev->instance, index);
1281         set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1282
1283         return ns;
1284
1285  out_free_queue:
1286         blk_cleanup_queue(ns->queue);
1287  out_free_ns:
1288         kfree(ns);
1289         return NULL;
1290 }
1291
1292 static void nvme_ns_free(struct nvme_ns *ns)
1293 {
1294         put_disk(ns->disk);
1295         blk_cleanup_queue(ns->queue);
1296         kfree(ns);
1297 }
1298
1299 static int set_queue_count(struct nvme_dev *dev, int count)
1300 {
1301         int status;
1302         u32 result;
1303         struct nvme_command c;
1304         u32 q_count = (count - 1) | ((count - 1) << 16);
1305
1306         memset(&c, 0, sizeof(c));
1307         c.features.opcode = nvme_admin_get_features;
1308         c.features.fid = cpu_to_le32(NVME_FEAT_NUM_QUEUES);
1309         c.features.dword11 = cpu_to_le32(q_count);
1310
1311         status = nvme_submit_admin_cmd(dev, &c, &result);
1312         if (status)
1313                 return -EIO;
1314         return min(result & 0xffff, result >> 16) + 1;
1315 }
1316
1317 static int __devinit nvme_setup_io_queues(struct nvme_dev *dev)
1318 {
1319         int result, cpu, i, nr_io_queues;
1320
1321         nr_io_queues = num_online_cpus();
1322         result = set_queue_count(dev, nr_io_queues);
1323         if (result < 0)
1324                 return result;
1325         if (result < nr_io_queues)
1326                 nr_io_queues = result;
1327
1328         /* Deregister the admin queue's interrupt */
1329         free_irq(dev->entry[0].vector, dev->queues[0]);
1330
1331         for (i = 0; i < nr_io_queues; i++)
1332                 dev->entry[i].entry = i;
1333         for (;;) {
1334                 result = pci_enable_msix(dev->pci_dev, dev->entry,
1335                                                                 nr_io_queues);
1336                 if (result == 0) {
1337                         break;
1338                 } else if (result > 0) {
1339                         nr_io_queues = result;
1340                         continue;
1341                 } else {
1342                         nr_io_queues = 1;
1343                         break;
1344                 }
1345         }
1346
1347         result = queue_request_irq(dev, dev->queues[0], "nvme admin");
1348         /* XXX: handle failure here */
1349
1350         cpu = cpumask_first(cpu_online_mask);
1351         for (i = 0; i < nr_io_queues; i++) {
1352                 irq_set_affinity_hint(dev->entry[i].vector, get_cpu_mask(cpu));
1353                 cpu = cpumask_next(cpu, cpu_online_mask);
1354         }
1355
1356         for (i = 0; i < nr_io_queues; i++) {
1357                 dev->queues[i + 1] = nvme_create_queue(dev, i + 1,
1358                                                         NVME_Q_DEPTH, i);
1359                 if (!dev->queues[i + 1])
1360                         return -ENOMEM;
1361                 dev->queue_count++;
1362         }
1363
1364         for (; i < num_possible_cpus(); i++) {
1365                 int target = i % rounddown_pow_of_two(dev->queue_count - 1);
1366                 dev->queues[i + 1] = dev->queues[target + 1];
1367         }
1368
1369         return 0;
1370 }
1371
1372 static void nvme_free_queues(struct nvme_dev *dev)
1373 {
1374         int i;
1375
1376         for (i = dev->queue_count - 1; i >= 0; i--)
1377                 nvme_free_queue(dev, i);
1378 }
1379
1380 static int __devinit nvme_dev_add(struct nvme_dev *dev)
1381 {
1382         int res, nn, i;
1383         struct nvme_ns *ns, *next;
1384         struct nvme_id_ctrl *ctrl;
1385         void *id;
1386         dma_addr_t dma_addr;
1387         struct nvme_command cid, crt;
1388
1389         res = nvme_setup_io_queues(dev);
1390         if (res)
1391                 return res;
1392
1393         /* XXX: Switch to a SG list once prp2 works */
1394         id = dma_alloc_coherent(&dev->pci_dev->dev, 8192, &dma_addr,
1395                                                                 GFP_KERNEL);
1396
1397         memset(&cid, 0, sizeof(cid));
1398         cid.identify.opcode = nvme_admin_identify;
1399         cid.identify.nsid = 0;
1400         cid.identify.prp1 = cpu_to_le64(dma_addr);
1401         cid.identify.cns = cpu_to_le32(1);
1402
1403         res = nvme_submit_admin_cmd(dev, &cid, NULL);
1404         if (res) {
1405                 res = -EIO;
1406                 goto out_free;
1407         }
1408
1409         ctrl = id;
1410         nn = le32_to_cpup(&ctrl->nn);
1411         memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
1412         memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
1413         memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
1414
1415         cid.identify.cns = 0;
1416         memset(&crt, 0, sizeof(crt));
1417         crt.features.opcode = nvme_admin_get_features;
1418         crt.features.prp1 = cpu_to_le64(dma_addr + 4096);
1419         crt.features.fid = cpu_to_le32(NVME_FEAT_LBA_RANGE);
1420
1421         for (i = 0; i <= nn; i++) {
1422                 cid.identify.nsid = cpu_to_le32(i);
1423                 res = nvme_submit_admin_cmd(dev, &cid, NULL);
1424                 if (res)
1425                         continue;
1426
1427                 if (((struct nvme_id_ns *)id)->ncap == 0)
1428                         continue;
1429
1430                 crt.features.nsid = cpu_to_le32(i);
1431                 res = nvme_submit_admin_cmd(dev, &crt, NULL);
1432                 if (res)
1433                         continue;
1434
1435                 ns = nvme_alloc_ns(dev, i, id, id + 4096);
1436                 if (ns)
1437                         list_add_tail(&ns->list, &dev->namespaces);
1438         }
1439         list_for_each_entry(ns, &dev->namespaces, list)
1440                 add_disk(ns->disk);
1441
1442         dma_free_coherent(&dev->pci_dev->dev, 4096, id, dma_addr);
1443         return 0;
1444
1445  out_free:
1446         list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
1447                 list_del(&ns->list);
1448                 nvme_ns_free(ns);
1449         }
1450
1451         dma_free_coherent(&dev->pci_dev->dev, 4096, id, dma_addr);
1452         return res;
1453 }
1454
1455 static int nvme_dev_remove(struct nvme_dev *dev)
1456 {
1457         struct nvme_ns *ns, *next;
1458
1459         spin_lock(&dev_list_lock);
1460         list_del(&dev->node);
1461         spin_unlock(&dev_list_lock);
1462
1463         /* TODO: wait all I/O finished or cancel them */
1464
1465         list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
1466                 list_del(&ns->list);
1467                 del_gendisk(ns->disk);
1468                 nvme_ns_free(ns);
1469         }
1470
1471         nvme_free_queues(dev);
1472
1473         return 0;
1474 }
1475
1476 static int nvme_setup_prp_pools(struct nvme_dev *dev)
1477 {
1478         struct device *dmadev = &dev->pci_dev->dev;
1479         dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
1480                                                 PAGE_SIZE, PAGE_SIZE, 0);
1481         if (!dev->prp_page_pool)
1482                 return -ENOMEM;
1483
1484         /* Optimisation for I/Os between 4k and 128k */
1485         dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
1486                                                 256, 256, 0);
1487         if (!dev->prp_small_pool) {
1488                 dma_pool_destroy(dev->prp_page_pool);
1489                 return -ENOMEM;
1490         }
1491         return 0;
1492 }
1493
1494 static void nvme_release_prp_pools(struct nvme_dev *dev)
1495 {
1496         dma_pool_destroy(dev->prp_page_pool);
1497         dma_pool_destroy(dev->prp_small_pool);
1498 }
1499
1500 /* XXX: Use an ida or something to let remove / add work correctly */
1501 static void nvme_set_instance(struct nvme_dev *dev)
1502 {
1503         static int instance;
1504         dev->instance = instance++;
1505 }
1506
1507 static void nvme_release_instance(struct nvme_dev *dev)
1508 {
1509 }
1510
1511 static int __devinit nvme_probe(struct pci_dev *pdev,
1512                                                 const struct pci_device_id *id)
1513 {
1514         int bars, result = -ENOMEM;
1515         struct nvme_dev *dev;
1516
1517         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1518         if (!dev)
1519                 return -ENOMEM;
1520         dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
1521                                                                 GFP_KERNEL);
1522         if (!dev->entry)
1523                 goto free;
1524         dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
1525                                                                 GFP_KERNEL);
1526         if (!dev->queues)
1527                 goto free;
1528
1529         if (pci_enable_device_mem(pdev))
1530                 goto free;
1531         pci_set_master(pdev);
1532         bars = pci_select_bars(pdev, IORESOURCE_MEM);
1533         if (pci_request_selected_regions(pdev, bars, "nvme"))
1534                 goto disable;
1535
1536         INIT_LIST_HEAD(&dev->namespaces);
1537         dev->pci_dev = pdev;
1538         pci_set_drvdata(pdev, dev);
1539         dma_set_mask(&pdev->dev, DMA_BIT_MASK(64));
1540         dma_set_coherent_mask(&pdev->dev, DMA_BIT_MASK(64));
1541         nvme_set_instance(dev);
1542         dev->entry[0].vector = pdev->irq;
1543
1544         result = nvme_setup_prp_pools(dev);
1545         if (result)
1546                 goto disable_msix;
1547
1548         dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
1549         if (!dev->bar) {
1550                 result = -ENOMEM;
1551                 goto disable_msix;
1552         }
1553
1554         result = nvme_configure_admin_queue(dev);
1555         if (result)
1556                 goto unmap;
1557         dev->queue_count++;
1558
1559         spin_lock(&dev_list_lock);
1560         list_add(&dev->node, &dev_list);
1561         spin_unlock(&dev_list_lock);
1562
1563         result = nvme_dev_add(dev);
1564         if (result)
1565                 goto delete;
1566
1567         return 0;
1568
1569  delete:
1570         spin_lock(&dev_list_lock);
1571         list_del(&dev->node);
1572         spin_unlock(&dev_list_lock);
1573
1574         nvme_free_queues(dev);
1575  unmap:
1576         iounmap(dev->bar);
1577  disable_msix:
1578         pci_disable_msix(pdev);
1579         nvme_release_instance(dev);
1580         nvme_release_prp_pools(dev);
1581  disable:
1582         pci_disable_device(pdev);
1583         pci_release_regions(pdev);
1584  free:
1585         kfree(dev->queues);
1586         kfree(dev->entry);
1587         kfree(dev);
1588         return result;
1589 }
1590
1591 static void __devexit nvme_remove(struct pci_dev *pdev)
1592 {
1593         struct nvme_dev *dev = pci_get_drvdata(pdev);
1594         nvme_dev_remove(dev);
1595         pci_disable_msix(pdev);
1596         iounmap(dev->bar);
1597         nvme_release_instance(dev);
1598         nvme_release_prp_pools(dev);
1599         pci_disable_device(pdev);
1600         pci_release_regions(pdev);
1601         kfree(dev->queues);
1602         kfree(dev->entry);
1603         kfree(dev);
1604 }
1605
1606 /* These functions are yet to be implemented */
1607 #define nvme_error_detected NULL
1608 #define nvme_dump_registers NULL
1609 #define nvme_link_reset NULL
1610 #define nvme_slot_reset NULL
1611 #define nvme_error_resume NULL
1612 #define nvme_suspend NULL
1613 #define nvme_resume NULL
1614
1615 static struct pci_error_handlers nvme_err_handler = {
1616         .error_detected = nvme_error_detected,
1617         .mmio_enabled   = nvme_dump_registers,
1618         .link_reset     = nvme_link_reset,
1619         .slot_reset     = nvme_slot_reset,
1620         .resume         = nvme_error_resume,
1621 };
1622
1623 /* Move to pci_ids.h later */
1624 #define PCI_CLASS_STORAGE_EXPRESS       0x010802
1625
1626 static DEFINE_PCI_DEVICE_TABLE(nvme_id_table) = {
1627         { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
1628         { 0, }
1629 };
1630 MODULE_DEVICE_TABLE(pci, nvme_id_table);
1631
1632 static struct pci_driver nvme_driver = {
1633         .name           = "nvme",
1634         .id_table       = nvme_id_table,
1635         .probe          = nvme_probe,
1636         .remove         = __devexit_p(nvme_remove),
1637         .suspend        = nvme_suspend,
1638         .resume         = nvme_resume,
1639         .err_handler    = &nvme_err_handler,
1640 };
1641
1642 static int __init nvme_init(void)
1643 {
1644         int result = -EBUSY;
1645
1646         nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
1647         if (IS_ERR(nvme_thread))
1648                 return PTR_ERR(nvme_thread);
1649
1650         nvme_major = register_blkdev(nvme_major, "nvme");
1651         if (nvme_major <= 0)
1652                 goto kill_kthread;
1653
1654         result = pci_register_driver(&nvme_driver);
1655         if (result)
1656                 goto unregister_blkdev;
1657         return 0;
1658
1659  unregister_blkdev:
1660         unregister_blkdev(nvme_major, "nvme");
1661  kill_kthread:
1662         kthread_stop(nvme_thread);
1663         return result;
1664 }
1665
1666 static void __exit nvme_exit(void)
1667 {
1668         pci_unregister_driver(&nvme_driver);
1669         unregister_blkdev(nvme_major, "nvme");
1670         kthread_stop(nvme_thread);
1671 }
1672
1673 MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
1674 MODULE_LICENSE("GPL");
1675 MODULE_VERSION("0.5");
1676 module_init(nvme_init);
1677 module_exit(nvme_exit);