NVMe: Add revalidate_disk callback
[linux-2.6-block.git] / drivers / block / nvme-core.c
CommitLineData
b60503ba
MW
1/*
2 * NVM Express device driver
6eb0d698 3 * Copyright (c) 2011-2014, Intel Corporation.
b60503ba
MW
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.
b60503ba
MW
13 */
14
15#include <linux/nvme.h>
16#include <linux/bio.h>
8de05535 17#include <linux/bitops.h>
b60503ba 18#include <linux/blkdev.h>
42f61420 19#include <linux/cpu.h>
fd63e9ce 20#include <linux/delay.h>
b60503ba
MW
21#include <linux/errno.h>
22#include <linux/fs.h>
23#include <linux/genhd.h>
4cc09e2d 24#include <linux/hdreg.h>
5aff9382 25#include <linux/idr.h>
b60503ba
MW
26#include <linux/init.h>
27#include <linux/interrupt.h>
28#include <linux/io.h>
29#include <linux/kdev_t.h>
1fa6aead 30#include <linux/kthread.h>
b60503ba
MW
31#include <linux/kernel.h>
32#include <linux/mm.h>
33#include <linux/module.h>
34#include <linux/moduleparam.h>
35#include <linux/pci.h>
42f61420 36#include <linux/percpu.h>
be7b6275 37#include <linux/poison.h>
c3bfe717 38#include <linux/ptrace.h>
b60503ba
MW
39#include <linux/sched.h>
40#include <linux/slab.h>
41#include <linux/types.h>
5d0f6131 42#include <scsi/sg.h>
797a796a
HM
43#include <asm-generic/io-64-nonatomic-lo-hi.h>
44
3291fa57
KB
45#include <trace/events/block.h>
46
9d43cf64 47#define NVME_Q_DEPTH 1024
b60503ba
MW
48#define SQ_SIZE(depth) (depth * sizeof(struct nvme_command))
49#define CQ_SIZE(depth) (depth * sizeof(struct nvme_completion))
9d43cf64 50#define ADMIN_TIMEOUT (admin_timeout * HZ)
2484f407 51#define SHUTDOWN_TIMEOUT (shutdown_timeout * HZ)
9d43cf64
KB
52#define IOD_TIMEOUT (retry_time * HZ)
53
54static unsigned char admin_timeout = 60;
55module_param(admin_timeout, byte, 0644);
56MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
b60503ba 57
bd67608a
MW
58unsigned char nvme_io_timeout = 30;
59module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
b355084a 60MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
b60503ba 61
61e4ce08
KB
62static unsigned char retry_time = 30;
63module_param(retry_time, byte, 0644);
64MODULE_PARM_DESC(retry_time, "time in seconds to retry failed I/O");
65
2484f407
DM
66static unsigned char shutdown_timeout = 5;
67module_param(shutdown_timeout, byte, 0644);
68MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
69
b60503ba
MW
70static int nvme_major;
71module_param(nvme_major, int, 0);
72
58ffacb5
MW
73static int use_threaded_interrupts;
74module_param(use_threaded_interrupts, int, 0);
75
1fa6aead
MW
76static DEFINE_SPINLOCK(dev_list_lock);
77static LIST_HEAD(dev_list);
78static struct task_struct *nvme_thread;
9a6b9458 79static struct workqueue_struct *nvme_workq;
b9afca3e 80static wait_queue_head_t nvme_kthread_wait;
f3db22fe 81static struct notifier_block nvme_nb;
1fa6aead 82
d4b4ff8e
KB
83static void nvme_reset_failed_dev(struct work_struct *ws);
84
4d115420
KB
85struct async_cmd_info {
86 struct kthread_work work;
87 struct kthread_worker *worker;
88 u32 result;
89 int status;
90 void *ctx;
91};
1fa6aead 92
b60503ba
MW
93/*
94 * An NVM Express queue. Each device has at least two (one for admin
95 * commands and one for I/O commands).
96 */
97struct nvme_queue {
f435c282 98 struct llist_node node;
b60503ba 99 struct device *q_dmadev;
091b6092 100 struct nvme_dev *dev;
3193f07b 101 char irqname[24]; /* nvme4294967295-65535\0 */
b60503ba
MW
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;
1fa6aead 108 wait_queue_t sq_cong_wait;
b60503ba 109 struct bio_list sq_cong;
edd10d33 110 struct list_head iod_bio;
b60503ba
MW
111 u32 __iomem *q_db;
112 u16 q_depth;
113 u16 cq_vector;
114 u16 sq_head;
115 u16 sq_tail;
116 u16 cq_head;
c30341dc 117 u16 qid;
e9539f47
MW
118 u8 cq_phase;
119 u8 cqe_seen;
22404274 120 u8 q_suspended;
42f61420 121 cpumask_var_t cpu_mask;
4d115420 122 struct async_cmd_info cmdinfo;
b60503ba
MW
123 unsigned long cmdid_data[];
124};
125
126/*
127 * Check we didin't inadvertently grow the command struct
128 */
129static inline void _nvme_check_size(void)
130{
131 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
132 BUILD_BUG_ON(sizeof(struct nvme_create_cq) != 64);
133 BUILD_BUG_ON(sizeof(struct nvme_create_sq) != 64);
134 BUILD_BUG_ON(sizeof(struct nvme_delete_queue) != 64);
135 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
f8ebf840 136 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
c30341dc 137 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
b60503ba
MW
138 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
139 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != 4096);
140 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != 4096);
141 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
6ecec745 142 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
b60503ba
MW
143}
144
edd10d33 145typedef void (*nvme_completion_fn)(struct nvme_queue *, void *,
c2f5b650
MW
146 struct nvme_completion *);
147
e85248e5 148struct nvme_cmd_info {
c2f5b650
MW
149 nvme_completion_fn fn;
150 void *ctx;
e85248e5 151 unsigned long timeout;
c30341dc 152 int aborted;
e85248e5
MW
153};
154
155static struct nvme_cmd_info *nvme_cmd_info(struct nvme_queue *nvmeq)
156{
157 return (void *)&nvmeq->cmdid_data[BITS_TO_LONGS(nvmeq->q_depth)];
158}
159
22404274
KB
160static unsigned nvme_queue_extra(int depth)
161{
162 return DIV_ROUND_UP(depth, 8) + (depth * sizeof(struct nvme_cmd_info));
163}
164
b60503ba 165/**
714a7a22
MW
166 * alloc_cmdid() - Allocate a Command ID
167 * @nvmeq: The queue that will be used for this command
168 * @ctx: A pointer that will be passed to the handler
c2f5b650 169 * @handler: The function to call on completion
b60503ba
MW
170 *
171 * Allocate a Command ID for a queue. The data passed in will
172 * be passed to the completion handler. This is implemented by using
173 * the bottom two bits of the ctx pointer to store the handler ID.
174 * Passing in a pointer that's not 4-byte aligned will cause a BUG.
175 * We can change this if it becomes a problem.
184d2944
MW
176 *
177 * May be called with local interrupts disabled and the q_lock held,
178 * or with interrupts enabled and no locks held.
b60503ba 179 */
c2f5b650
MW
180static int alloc_cmdid(struct nvme_queue *nvmeq, void *ctx,
181 nvme_completion_fn handler, unsigned timeout)
b60503ba 182{
e6d15f79 183 int depth = nvmeq->q_depth - 1;
e85248e5 184 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
b60503ba
MW
185 int cmdid;
186
b60503ba
MW
187 do {
188 cmdid = find_first_zero_bit(nvmeq->cmdid_data, depth);
189 if (cmdid >= depth)
190 return -EBUSY;
191 } while (test_and_set_bit(cmdid, nvmeq->cmdid_data));
192
c2f5b650
MW
193 info[cmdid].fn = handler;
194 info[cmdid].ctx = ctx;
e85248e5 195 info[cmdid].timeout = jiffies + timeout;
c30341dc 196 info[cmdid].aborted = 0;
b60503ba
MW
197 return cmdid;
198}
199
200static int alloc_cmdid_killable(struct nvme_queue *nvmeq, void *ctx,
c2f5b650 201 nvme_completion_fn handler, unsigned timeout)
b60503ba
MW
202{
203 int cmdid;
204 wait_event_killable(nvmeq->sq_full,
e85248e5 205 (cmdid = alloc_cmdid(nvmeq, ctx, handler, timeout)) >= 0);
b60503ba
MW
206 return (cmdid < 0) ? -EINTR : cmdid;
207}
208
c2f5b650
MW
209/* Special values must be less than 0x1000 */
210#define CMD_CTX_BASE ((void *)POISON_POINTER_DELTA)
d2d87034
MW
211#define CMD_CTX_CANCELLED (0x30C + CMD_CTX_BASE)
212#define CMD_CTX_COMPLETED (0x310 + CMD_CTX_BASE)
213#define CMD_CTX_INVALID (0x314 + CMD_CTX_BASE)
53562be7 214#define CMD_CTX_ABORT (0x318 + CMD_CTX_BASE)
6fccf938 215#define CMD_CTX_ASYNC (0x31C + CMD_CTX_BASE)
be7b6275 216
edd10d33 217static void special_completion(struct nvme_queue *nvmeq, void *ctx,
c2f5b650
MW
218 struct nvme_completion *cqe)
219{
220 if (ctx == CMD_CTX_CANCELLED)
221 return;
c30341dc 222 if (ctx == CMD_CTX_ABORT) {
edd10d33 223 ++nvmeq->dev->abort_limit;
c30341dc
KB
224 return;
225 }
c2f5b650 226 if (ctx == CMD_CTX_COMPLETED) {
edd10d33 227 dev_warn(nvmeq->q_dmadev,
c2f5b650
MW
228 "completed id %d twice on queue %d\n",
229 cqe->command_id, le16_to_cpup(&cqe->sq_id));
230 return;
231 }
232 if (ctx == CMD_CTX_INVALID) {
edd10d33 233 dev_warn(nvmeq->q_dmadev,
c2f5b650
MW
234 "invalid id %d completed on queue %d\n",
235 cqe->command_id, le16_to_cpup(&cqe->sq_id));
236 return;
237 }
6fccf938
KB
238 if (ctx == CMD_CTX_ASYNC) {
239 u32 result = le32_to_cpup(&cqe->result);
240 u16 status = le16_to_cpup(&cqe->status) >> 1;
241
242 if (status == NVME_SC_SUCCESS || status == NVME_SC_ABORT_REQ)
243 ++nvmeq->dev->event_limit;
244 if (status == NVME_SC_SUCCESS)
245 dev_warn(nvmeq->q_dmadev,
246 "async event result %08x\n", result);
247 return;
248 }
c2f5b650 249
edd10d33 250 dev_warn(nvmeq->q_dmadev, "Unknown special completion %p\n", ctx);
c2f5b650
MW
251}
252
edd10d33 253static void async_completion(struct nvme_queue *nvmeq, void *ctx,
4d115420
KB
254 struct nvme_completion *cqe)
255{
256 struct async_cmd_info *cmdinfo = ctx;
257 cmdinfo->result = le32_to_cpup(&cqe->result);
258 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
259 queue_kthread_work(cmdinfo->worker, &cmdinfo->work);
260}
261
184d2944
MW
262/*
263 * Called with local interrupts disabled and the q_lock held. May not sleep.
264 */
c2f5b650
MW
265static void *free_cmdid(struct nvme_queue *nvmeq, int cmdid,
266 nvme_completion_fn *fn)
b60503ba 267{
c2f5b650 268 void *ctx;
e85248e5 269 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
b60503ba 270
94bbac40
KB
271 if (cmdid >= nvmeq->q_depth || !info[cmdid].fn) {
272 if (fn)
273 *fn = special_completion;
48e3d398 274 return CMD_CTX_INVALID;
c2f5b650 275 }
859361a2
KB
276 if (fn)
277 *fn = info[cmdid].fn;
c2f5b650
MW
278 ctx = info[cmdid].ctx;
279 info[cmdid].fn = special_completion;
e85248e5 280 info[cmdid].ctx = CMD_CTX_COMPLETED;
b60503ba
MW
281 clear_bit(cmdid, nvmeq->cmdid_data);
282 wake_up(&nvmeq->sq_full);
c2f5b650 283 return ctx;
b60503ba
MW
284}
285
c2f5b650
MW
286static void *cancel_cmdid(struct nvme_queue *nvmeq, int cmdid,
287 nvme_completion_fn *fn)
3c0cf138 288{
c2f5b650 289 void *ctx;
e85248e5 290 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
c2f5b650
MW
291 if (fn)
292 *fn = info[cmdid].fn;
293 ctx = info[cmdid].ctx;
294 info[cmdid].fn = special_completion;
e85248e5 295 info[cmdid].ctx = CMD_CTX_CANCELLED;
c2f5b650 296 return ctx;
3c0cf138
MW
297}
298
5a92e700 299static struct nvme_queue *raw_nvmeq(struct nvme_dev *dev, int qid)
b60503ba 300{
5a92e700 301 return rcu_dereference_raw(dev->queues[qid]);
b60503ba
MW
302}
303
4f5099af 304static struct nvme_queue *get_nvmeq(struct nvme_dev *dev) __acquires(RCU)
5a92e700 305{
a51afb54 306 struct nvme_queue *nvmeq;
42f61420 307 unsigned queue_id = get_cpu_var(*dev->io_queue);
a51afb54 308
5a92e700 309 rcu_read_lock();
a51afb54
KB
310 nvmeq = rcu_dereference(dev->queues[queue_id]);
311 if (nvmeq)
312 return nvmeq;
313
314 rcu_read_unlock();
315 put_cpu_var(*dev->io_queue);
316 return NULL;
5a92e700
KB
317}
318
4f5099af 319static void put_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
b60503ba 320{
5a92e700 321 rcu_read_unlock();
42f61420 322 put_cpu_var(nvmeq->dev->io_queue);
b60503ba
MW
323}
324
4f5099af
KB
325static struct nvme_queue *lock_nvmeq(struct nvme_dev *dev, int q_idx)
326 __acquires(RCU)
b60503ba 327{
a51afb54
KB
328 struct nvme_queue *nvmeq;
329
4f5099af 330 rcu_read_lock();
a51afb54
KB
331 nvmeq = rcu_dereference(dev->queues[q_idx]);
332 if (nvmeq)
333 return nvmeq;
334
335 rcu_read_unlock();
336 return NULL;
4f5099af
KB
337}
338
339static void unlock_nvmeq(struct nvme_queue *nvmeq) __releases(RCU)
340{
341 rcu_read_unlock();
b60503ba
MW
342}
343
344/**
714a7a22 345 * nvme_submit_cmd() - Copy a command into a queue and ring the doorbell
b60503ba
MW
346 * @nvmeq: The queue to use
347 * @cmd: The command to send
348 *
349 * Safe to use from interrupt context
350 */
351static int nvme_submit_cmd(struct nvme_queue *nvmeq, struct nvme_command *cmd)
352{
353 unsigned long flags;
354 u16 tail;
b60503ba 355 spin_lock_irqsave(&nvmeq->q_lock, flags);
4f5099af
KB
356 if (nvmeq->q_suspended) {
357 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
358 return -EBUSY;
359 }
b60503ba
MW
360 tail = nvmeq->sq_tail;
361 memcpy(&nvmeq->sq_cmds[tail], cmd, sizeof(*cmd));
b60503ba
MW
362 if (++tail == nvmeq->q_depth)
363 tail = 0;
7547881d 364 writel(tail, nvmeq->q_db);
b60503ba
MW
365 nvmeq->sq_tail = tail;
366 spin_unlock_irqrestore(&nvmeq->q_lock, flags);
367
368 return 0;
369}
370
eca18b23 371static __le64 **iod_list(struct nvme_iod *iod)
e025344c 372{
eca18b23 373 return ((void *)iod) + iod->offset;
e025344c
SMM
374}
375
eca18b23
MW
376/*
377 * Will slightly overestimate the number of pages needed. This is OK
378 * as it only leads to a small amount of wasted memory for the lifetime of
379 * the I/O.
380 */
1d090624 381static int nvme_npages(unsigned size, struct nvme_dev *dev)
eca18b23 382{
1d090624
KB
383 unsigned nprps = DIV_ROUND_UP(size + dev->page_size, dev->page_size);
384 return DIV_ROUND_UP(8 * nprps, dev->page_size - 8);
eca18b23 385}
b60503ba 386
eca18b23 387static struct nvme_iod *
1d090624 388nvme_alloc_iod(unsigned nseg, unsigned nbytes, struct nvme_dev *dev, gfp_t gfp)
b60503ba 389{
eca18b23 390 struct nvme_iod *iod = kmalloc(sizeof(struct nvme_iod) +
1d090624 391 sizeof(__le64 *) * nvme_npages(nbytes, dev) +
eca18b23
MW
392 sizeof(struct scatterlist) * nseg, gfp);
393
394 if (iod) {
395 iod->offset = offsetof(struct nvme_iod, sg[nseg]);
396 iod->npages = -1;
397 iod->length = nbytes;
2b196034 398 iod->nents = 0;
edd10d33 399 iod->first_dma = 0ULL;
6198221f 400 iod->start_time = jiffies;
eca18b23
MW
401 }
402
403 return iod;
b60503ba
MW
404}
405
5d0f6131 406void nvme_free_iod(struct nvme_dev *dev, struct nvme_iod *iod)
b60503ba 407{
1d090624 408 const int last_prp = dev->page_size / 8 - 1;
eca18b23
MW
409 int i;
410 __le64 **list = iod_list(iod);
411 dma_addr_t prp_dma = iod->first_dma;
412
413 if (iod->npages == 0)
414 dma_pool_free(dev->prp_small_pool, list[0], prp_dma);
415 for (i = 0; i < iod->npages; i++) {
416 __le64 *prp_list = list[i];
417 dma_addr_t next_prp_dma = le64_to_cpu(prp_list[last_prp]);
418 dma_pool_free(dev->prp_page_pool, prp_list, prp_dma);
419 prp_dma = next_prp_dma;
420 }
421 kfree(iod);
b60503ba
MW
422}
423
6198221f
KB
424static void nvme_start_io_acct(struct bio *bio)
425{
426 struct gendisk *disk = bio->bi_bdev->bd_disk;
b4e75cbf
SB
427 if (blk_queue_io_stat(disk->queue)) {
428 const int rw = bio_data_dir(bio);
429 int cpu = part_stat_lock();
430 part_round_stats(cpu, &disk->part0);
431 part_stat_inc(cpu, &disk->part0, ios[rw]);
432 part_stat_add(cpu, &disk->part0, sectors[rw],
433 bio_sectors(bio));
434 part_inc_in_flight(&disk->part0, rw);
435 part_stat_unlock();
436 }
6198221f
KB
437}
438
439static void nvme_end_io_acct(struct bio *bio, unsigned long start_time)
440{
441 struct gendisk *disk = bio->bi_bdev->bd_disk;
b4e75cbf
SB
442 if (blk_queue_io_stat(disk->queue)) {
443 const int rw = bio_data_dir(bio);
444 unsigned long duration = jiffies - start_time;
445 int cpu = part_stat_lock();
446 part_stat_add(cpu, &disk->part0, ticks[rw], duration);
447 part_round_stats(cpu, &disk->part0);
448 part_dec_in_flight(&disk->part0, rw);
449 part_stat_unlock();
450 }
6198221f
KB
451}
452
b4ff9c8d
KB
453static int nvme_error_status(u16 status)
454{
455 switch (status & 0x7ff) {
456 case NVME_SC_SUCCESS:
457 return 0;
458 case NVME_SC_CAP_EXCEEDED:
459 return -ENOSPC;
460 default:
461 return -EIO;
462 }
463}
464
edd10d33 465static void bio_completion(struct nvme_queue *nvmeq, void *ctx,
b60503ba
MW
466 struct nvme_completion *cqe)
467{
eca18b23
MW
468 struct nvme_iod *iod = ctx;
469 struct bio *bio = iod->private;
b60503ba 470 u16 status = le16_to_cpup(&cqe->status) >> 1;
3291fa57 471 int error = 0;
b60503ba 472
edd10d33
KB
473 if (unlikely(status)) {
474 if (!(status & NVME_SC_DNR ||
475 bio->bi_rw & REQ_FAILFAST_MASK) &&
476 (jiffies - iod->start_time) < IOD_TIMEOUT) {
477 if (!waitqueue_active(&nvmeq->sq_full))
478 add_wait_queue(&nvmeq->sq_full,
479 &nvmeq->sq_cong_wait);
480 list_add_tail(&iod->node, &nvmeq->iod_bio);
481 wake_up(&nvmeq->sq_full);
482 return;
483 }
b4ff9c8d 484 error = nvme_error_status(status);
edd10d33 485 }
9e59d091 486 if (iod->nents) {
edd10d33 487 dma_unmap_sg(nvmeq->q_dmadev, iod->sg, iod->nents,
b60503ba 488 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
9e59d091
KB
489 nvme_end_io_acct(bio, iod->start_time);
490 }
edd10d33 491 nvme_free_iod(nvmeq->dev, iod);
3291fa57
KB
492
493 trace_block_bio_complete(bdev_get_queue(bio->bi_bdev), bio, error);
494 bio_endio(bio, error);
b60503ba
MW
495}
496
184d2944 497/* length is in bytes. gfp flags indicates whether we may sleep. */
edd10d33
KB
498int nvme_setup_prps(struct nvme_dev *dev, struct nvme_iod *iod, int total_len,
499 gfp_t gfp)
ff22b54f 500{
99802a7a 501 struct dma_pool *pool;
eca18b23
MW
502 int length = total_len;
503 struct scatterlist *sg = iod->sg;
ff22b54f
MW
504 int dma_len = sg_dma_len(sg);
505 u64 dma_addr = sg_dma_address(sg);
506 int offset = offset_in_page(dma_addr);
e025344c 507 __le64 *prp_list;
eca18b23 508 __le64 **list = iod_list(iod);
e025344c 509 dma_addr_t prp_dma;
eca18b23 510 int nprps, i;
1d090624 511 u32 page_size = dev->page_size;
ff22b54f 512
1d090624 513 length -= (page_size - offset);
ff22b54f 514 if (length <= 0)
eca18b23 515 return total_len;
ff22b54f 516
1d090624 517 dma_len -= (page_size - offset);
ff22b54f 518 if (dma_len) {
1d090624 519 dma_addr += (page_size - offset);
ff22b54f
MW
520 } else {
521 sg = sg_next(sg);
522 dma_addr = sg_dma_address(sg);
523 dma_len = sg_dma_len(sg);
524 }
525
1d090624 526 if (length <= page_size) {
edd10d33 527 iod->first_dma = dma_addr;
eca18b23 528 return total_len;
e025344c
SMM
529 }
530
1d090624 531 nprps = DIV_ROUND_UP(length, page_size);
99802a7a
MW
532 if (nprps <= (256 / 8)) {
533 pool = dev->prp_small_pool;
eca18b23 534 iod->npages = 0;
99802a7a
MW
535 } else {
536 pool = dev->prp_page_pool;
eca18b23 537 iod->npages = 1;
99802a7a
MW
538 }
539
b77954cb
MW
540 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
541 if (!prp_list) {
edd10d33 542 iod->first_dma = dma_addr;
eca18b23 543 iod->npages = -1;
1d090624 544 return (total_len - length) + page_size;
b77954cb 545 }
eca18b23
MW
546 list[0] = prp_list;
547 iod->first_dma = prp_dma;
e025344c
SMM
548 i = 0;
549 for (;;) {
1d090624 550 if (i == page_size >> 3) {
e025344c 551 __le64 *old_prp_list = prp_list;
b77954cb 552 prp_list = dma_pool_alloc(pool, gfp, &prp_dma);
eca18b23
MW
553 if (!prp_list)
554 return total_len - length;
555 list[iod->npages++] = prp_list;
7523d834
MW
556 prp_list[0] = old_prp_list[i - 1];
557 old_prp_list[i - 1] = cpu_to_le64(prp_dma);
558 i = 1;
e025344c
SMM
559 }
560 prp_list[i++] = cpu_to_le64(dma_addr);
1d090624
KB
561 dma_len -= page_size;
562 dma_addr += page_size;
563 length -= page_size;
e025344c
SMM
564 if (length <= 0)
565 break;
566 if (dma_len > 0)
567 continue;
568 BUG_ON(dma_len < 0);
569 sg = sg_next(sg);
570 dma_addr = sg_dma_address(sg);
571 dma_len = sg_dma_len(sg);
ff22b54f
MW
572 }
573
eca18b23 574 return total_len;
ff22b54f
MW
575}
576
427e9708 577static int nvme_split_and_submit(struct bio *bio, struct nvme_queue *nvmeq,
20d0189b 578 int len)
427e9708 579{
20d0189b
KO
580 struct bio *split = bio_split(bio, len >> 9, GFP_ATOMIC, NULL);
581 if (!split)
427e9708
KB
582 return -ENOMEM;
583
3291fa57
KB
584 trace_block_split(bdev_get_queue(bio->bi_bdev), bio,
585 split->bi_iter.bi_sector);
20d0189b
KO
586 bio_chain(split, bio);
587
edd10d33 588 if (!waitqueue_active(&nvmeq->sq_full))
427e9708 589 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
20d0189b
KO
590 bio_list_add(&nvmeq->sq_cong, split);
591 bio_list_add(&nvmeq->sq_cong, bio);
edd10d33 592 wake_up(&nvmeq->sq_full);
427e9708
KB
593
594 return 0;
595}
596
1ad2f893
MW
597/* NVMe scatterlists require no holes in the virtual address */
598#define BIOVEC_NOT_VIRT_MERGEABLE(vec1, vec2) ((vec2)->bv_offset || \
599 (((vec1)->bv_offset + (vec1)->bv_len) % PAGE_SIZE))
600
427e9708 601static int nvme_map_bio(struct nvme_queue *nvmeq, struct nvme_iod *iod,
b60503ba
MW
602 struct bio *bio, enum dma_data_direction dma_dir, int psegs)
603{
7988613b
KO
604 struct bio_vec bvec, bvprv;
605 struct bvec_iter iter;
76830840 606 struct scatterlist *sg = NULL;
7988613b
KO
607 int length = 0, nsegs = 0, split_len = bio->bi_iter.bi_size;
608 int first = 1;
159b67d7
KB
609
610 if (nvmeq->dev->stripe_size)
611 split_len = nvmeq->dev->stripe_size -
4f024f37
KO
612 ((bio->bi_iter.bi_sector << 9) &
613 (nvmeq->dev->stripe_size - 1));
b60503ba 614
eca18b23 615 sg_init_table(iod->sg, psegs);
7988613b
KO
616 bio_for_each_segment(bvec, bio, iter) {
617 if (!first && BIOVEC_PHYS_MERGEABLE(&bvprv, &bvec)) {
618 sg->length += bvec.bv_len;
76830840 619 } else {
7988613b
KO
620 if (!first && BIOVEC_NOT_VIRT_MERGEABLE(&bvprv, &bvec))
621 return nvme_split_and_submit(bio, nvmeq,
20d0189b 622 length);
427e9708 623
eca18b23 624 sg = sg ? sg + 1 : iod->sg;
7988613b
KO
625 sg_set_page(sg, bvec.bv_page,
626 bvec.bv_len, bvec.bv_offset);
76830840
MW
627 nsegs++;
628 }
159b67d7 629
7988613b 630 if (split_len - length < bvec.bv_len)
20d0189b 631 return nvme_split_and_submit(bio, nvmeq, split_len);
7988613b 632 length += bvec.bv_len;
76830840 633 bvprv = bvec;
7988613b 634 first = 0;
b60503ba 635 }
eca18b23 636 iod->nents = nsegs;
76830840 637 sg_mark_end(sg);
427e9708 638 if (dma_map_sg(nvmeq->q_dmadev, iod->sg, iod->nents, dma_dir) == 0)
1ad2f893 639 return -ENOMEM;
427e9708 640
4f024f37 641 BUG_ON(length != bio->bi_iter.bi_size);
1ad2f893 642 return length;
b60503ba
MW
643}
644
0e5e4f0e
KB
645static int nvme_submit_discard(struct nvme_queue *nvmeq, struct nvme_ns *ns,
646 struct bio *bio, struct nvme_iod *iod, int cmdid)
647{
edd10d33
KB
648 struct nvme_dsm_range *range =
649 (struct nvme_dsm_range *)iod_list(iod)[0];
0e5e4f0e
KB
650 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
651
0e5e4f0e 652 range->cattr = cpu_to_le32(0);
4f024f37
KO
653 range->nlb = cpu_to_le32(bio->bi_iter.bi_size >> ns->lba_shift);
654 range->slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
0e5e4f0e
KB
655
656 memset(cmnd, 0, sizeof(*cmnd));
657 cmnd->dsm.opcode = nvme_cmd_dsm;
658 cmnd->dsm.command_id = cmdid;
659 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
660 cmnd->dsm.prp1 = cpu_to_le64(iod->first_dma);
661 cmnd->dsm.nr = 0;
662 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
663
664 if (++nvmeq->sq_tail == nvmeq->q_depth)
665 nvmeq->sq_tail = 0;
666 writel(nvmeq->sq_tail, nvmeq->q_db);
667
668 return 0;
669}
670
00df5cb4
MW
671static int nvme_submit_flush(struct nvme_queue *nvmeq, struct nvme_ns *ns,
672 int cmdid)
673{
674 struct nvme_command *cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
675
676 memset(cmnd, 0, sizeof(*cmnd));
677 cmnd->common.opcode = nvme_cmd_flush;
678 cmnd->common.command_id = cmdid;
679 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
680
681 if (++nvmeq->sq_tail == nvmeq->q_depth)
682 nvmeq->sq_tail = 0;
683 writel(nvmeq->sq_tail, nvmeq->q_db);
684
685 return 0;
686}
687
edd10d33 688static int nvme_submit_iod(struct nvme_queue *nvmeq, struct nvme_iod *iod)
b60503ba 689{
edd10d33
KB
690 struct bio *bio = iod->private;
691 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
ff22b54f 692 struct nvme_command *cmnd;
edd10d33 693 int cmdid;
b60503ba
MW
694 u16 control;
695 u32 dsmgmt;
00df5cb4 696
ff976d72 697 cmdid = alloc_cmdid(nvmeq, iod, bio_completion, NVME_IO_TIMEOUT);
b60503ba 698 if (unlikely(cmdid < 0))
edd10d33 699 return cmdid;
b60503ba 700
edd10d33
KB
701 if (bio->bi_rw & REQ_DISCARD)
702 return nvme_submit_discard(nvmeq, ns, bio, iod, cmdid);
53562be7 703 if (bio->bi_rw & REQ_FLUSH)
00df5cb4
MW
704 return nvme_submit_flush(nvmeq, ns, cmdid);
705
b60503ba
MW
706 control = 0;
707 if (bio->bi_rw & REQ_FUA)
708 control |= NVME_RW_FUA;
709 if (bio->bi_rw & (REQ_FAILFAST_DEV | REQ_RAHEAD))
710 control |= NVME_RW_LR;
711
712 dsmgmt = 0;
713 if (bio->bi_rw & REQ_RAHEAD)
714 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
715
ff22b54f 716 cmnd = &nvmeq->sq_cmds[nvmeq->sq_tail];
b8deb62c 717 memset(cmnd, 0, sizeof(*cmnd));
b60503ba 718
edd10d33 719 cmnd->rw.opcode = bio_data_dir(bio) ? nvme_cmd_write : nvme_cmd_read;
ff22b54f
MW
720 cmnd->rw.command_id = cmdid;
721 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
edd10d33
KB
722 cmnd->rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
723 cmnd->rw.prp2 = cpu_to_le64(iod->first_dma);
4f024f37 724 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, bio->bi_iter.bi_sector));
edd10d33
KB
725 cmnd->rw.length =
726 cpu_to_le16((bio->bi_iter.bi_size >> ns->lba_shift) - 1);
ff22b54f
MW
727 cmnd->rw.control = cpu_to_le16(control);
728 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
b60503ba 729
b60503ba
MW
730 if (++nvmeq->sq_tail == nvmeq->q_depth)
731 nvmeq->sq_tail = 0;
7547881d 732 writel(nvmeq->sq_tail, nvmeq->q_db);
b60503ba 733
1974b1ae 734 return 0;
edd10d33
KB
735}
736
53562be7
KB
737static int nvme_split_flush_data(struct nvme_queue *nvmeq, struct bio *bio)
738{
739 struct bio *split = bio_clone(bio, GFP_ATOMIC);
740 if (!split)
741 return -ENOMEM;
742
743 split->bi_iter.bi_size = 0;
744 split->bi_phys_segments = 0;
745 bio->bi_rw &= ~REQ_FLUSH;
746 bio_chain(split, bio);
747
748 if (!waitqueue_active(&nvmeq->sq_full))
749 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
750 bio_list_add(&nvmeq->sq_cong, split);
751 bio_list_add(&nvmeq->sq_cong, bio);
752 wake_up_process(nvme_thread);
753
754 return 0;
755}
756
edd10d33
KB
757/*
758 * Called with local interrupts disabled and the q_lock held. May not sleep.
759 */
760static int nvme_submit_bio_queue(struct nvme_queue *nvmeq, struct nvme_ns *ns,
761 struct bio *bio)
762{
763 struct nvme_iod *iod;
764 int psegs = bio_phys_segments(ns->queue, bio);
765 int result;
766
53562be7
KB
767 if ((bio->bi_rw & REQ_FLUSH) && psegs)
768 return nvme_split_flush_data(nvmeq, bio);
edd10d33 769
1d090624 770 iod = nvme_alloc_iod(psegs, bio->bi_iter.bi_size, ns->dev, GFP_ATOMIC);
edd10d33
KB
771 if (!iod)
772 return -ENOMEM;
773
774 iod->private = bio;
775 if (bio->bi_rw & REQ_DISCARD) {
776 void *range;
777 /*
778 * We reuse the small pool to allocate the 16-byte range here
779 * as it is not worth having a special pool for these or
780 * additional cases to handle freeing the iod.
781 */
782 range = dma_pool_alloc(nvmeq->dev->prp_small_pool,
783 GFP_ATOMIC,
784 &iod->first_dma);
785 if (!range) {
786 result = -ENOMEM;
787 goto free_iod;
788 }
789 iod_list(iod)[0] = (__le64 *)range;
790 iod->npages = 0;
791 } else if (psegs) {
792 result = nvme_map_bio(nvmeq, iod, bio,
793 bio_data_dir(bio) ? DMA_TO_DEVICE : DMA_FROM_DEVICE,
794 psegs);
795 if (result <= 0)
796 goto free_iod;
797 if (nvme_setup_prps(nvmeq->dev, iod, result, GFP_ATOMIC) !=
798 result) {
799 result = -ENOMEM;
800 goto free_iod;
801 }
802 nvme_start_io_acct(bio);
803 }
804 if (unlikely(nvme_submit_iod(nvmeq, iod))) {
805 if (!waitqueue_active(&nvmeq->sq_full))
806 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
807 list_add_tail(&iod->node, &nvmeq->iod_bio);
808 }
809 return 0;
1974b1ae 810
eca18b23
MW
811 free_iod:
812 nvme_free_iod(nvmeq->dev, iod);
eeee3226 813 return result;
b60503ba
MW
814}
815
e9539f47 816static int nvme_process_cq(struct nvme_queue *nvmeq)
b60503ba 817{
82123460 818 u16 head, phase;
b60503ba 819
b60503ba 820 head = nvmeq->cq_head;
82123460 821 phase = nvmeq->cq_phase;
b60503ba
MW
822
823 for (;;) {
c2f5b650
MW
824 void *ctx;
825 nvme_completion_fn fn;
b60503ba 826 struct nvme_completion cqe = nvmeq->cqes[head];
82123460 827 if ((le16_to_cpu(cqe.status) & 1) != phase)
b60503ba
MW
828 break;
829 nvmeq->sq_head = le16_to_cpu(cqe.sq_head);
830 if (++head == nvmeq->q_depth) {
831 head = 0;
82123460 832 phase = !phase;
b60503ba
MW
833 }
834
c2f5b650 835 ctx = free_cmdid(nvmeq, cqe.command_id, &fn);
edd10d33 836 fn(nvmeq, ctx, &cqe);
b60503ba
MW
837 }
838
839 /* If the controller ignores the cq head doorbell and continuously
840 * writes to the queue, it is theoretically possible to wrap around
841 * the queue twice and mistakenly return IRQ_NONE. Linux only
842 * requires that 0.1% of your interrupts are handled, so this isn't
843 * a big problem.
844 */
82123460 845 if (head == nvmeq->cq_head && phase == nvmeq->cq_phase)
e9539f47 846 return 0;
b60503ba 847
b80d5ccc 848 writel(head, nvmeq->q_db + nvmeq->dev->db_stride);
b60503ba 849 nvmeq->cq_head = head;
82123460 850 nvmeq->cq_phase = phase;
b60503ba 851
e9539f47
MW
852 nvmeq->cqe_seen = 1;
853 return 1;
b60503ba
MW
854}
855
7d822457
MW
856static void nvme_make_request(struct request_queue *q, struct bio *bio)
857{
858 struct nvme_ns *ns = q->queuedata;
859 struct nvme_queue *nvmeq = get_nvmeq(ns->dev);
860 int result = -EBUSY;
861
cd638946 862 if (!nvmeq) {
cd638946
KB
863 bio_endio(bio, -EIO);
864 return;
865 }
866
7d822457 867 spin_lock_irq(&nvmeq->q_lock);
22404274 868 if (!nvmeq->q_suspended && bio_list_empty(&nvmeq->sq_cong))
7d822457
MW
869 result = nvme_submit_bio_queue(nvmeq, ns, bio);
870 if (unlikely(result)) {
edd10d33 871 if (!waitqueue_active(&nvmeq->sq_full))
7d822457
MW
872 add_wait_queue(&nvmeq->sq_full, &nvmeq->sq_cong_wait);
873 bio_list_add(&nvmeq->sq_cong, bio);
874 }
875
876 nvme_process_cq(nvmeq);
877 spin_unlock_irq(&nvmeq->q_lock);
878 put_nvmeq(nvmeq);
879}
880
b60503ba 881static irqreturn_t nvme_irq(int irq, void *data)
58ffacb5
MW
882{
883 irqreturn_t result;
884 struct nvme_queue *nvmeq = data;
885 spin_lock(&nvmeq->q_lock);
e9539f47
MW
886 nvme_process_cq(nvmeq);
887 result = nvmeq->cqe_seen ? IRQ_HANDLED : IRQ_NONE;
888 nvmeq->cqe_seen = 0;
58ffacb5
MW
889 spin_unlock(&nvmeq->q_lock);
890 return result;
891}
892
893static irqreturn_t nvme_irq_check(int irq, void *data)
894{
895 struct nvme_queue *nvmeq = data;
896 struct nvme_completion cqe = nvmeq->cqes[nvmeq->cq_head];
897 if ((le16_to_cpu(cqe.status) & 1) != nvmeq->cq_phase)
898 return IRQ_NONE;
899 return IRQ_WAKE_THREAD;
900}
901
3c0cf138
MW
902static void nvme_abort_command(struct nvme_queue *nvmeq, int cmdid)
903{
904 spin_lock_irq(&nvmeq->q_lock);
c2f5b650 905 cancel_cmdid(nvmeq, cmdid, NULL);
3c0cf138
MW
906 spin_unlock_irq(&nvmeq->q_lock);
907}
908
c2f5b650
MW
909struct sync_cmd_info {
910 struct task_struct *task;
911 u32 result;
912 int status;
913};
914
edd10d33 915static void sync_completion(struct nvme_queue *nvmeq, void *ctx,
c2f5b650
MW
916 struct nvme_completion *cqe)
917{
918 struct sync_cmd_info *cmdinfo = ctx;
919 cmdinfo->result = le32_to_cpup(&cqe->result);
920 cmdinfo->status = le16_to_cpup(&cqe->status) >> 1;
921 wake_up_process(cmdinfo->task);
922}
923
b60503ba
MW
924/*
925 * Returns 0 on success. If the result is negative, it's a Linux error code;
926 * if the result is positive, it's an NVM Express status code
927 */
4f5099af
KB
928static int nvme_submit_sync_cmd(struct nvme_dev *dev, int q_idx,
929 struct nvme_command *cmd,
5d0f6131 930 u32 *result, unsigned timeout)
b60503ba 931{
4f5099af 932 int cmdid, ret;
b60503ba 933 struct sync_cmd_info cmdinfo;
4f5099af
KB
934 struct nvme_queue *nvmeq;
935
936 nvmeq = lock_nvmeq(dev, q_idx);
a51afb54 937 if (!nvmeq)
4f5099af 938 return -ENODEV;
b60503ba
MW
939
940 cmdinfo.task = current;
941 cmdinfo.status = -EINTR;
942
4f5099af
KB
943 cmdid = alloc_cmdid(nvmeq, &cmdinfo, sync_completion, timeout);
944 if (cmdid < 0) {
945 unlock_nvmeq(nvmeq);
b60503ba 946 return cmdid;
4f5099af 947 }
b60503ba
MW
948 cmd->common.command_id = cmdid;
949
3c0cf138 950 set_current_state(TASK_KILLABLE);
4f5099af
KB
951 ret = nvme_submit_cmd(nvmeq, cmd);
952 if (ret) {
953 free_cmdid(nvmeq, cmdid, NULL);
954 unlock_nvmeq(nvmeq);
955 set_current_state(TASK_RUNNING);
956 return ret;
957 }
958 unlock_nvmeq(nvmeq);
78f8d257 959 schedule_timeout(timeout);
b60503ba 960
3c0cf138 961 if (cmdinfo.status == -EINTR) {
4f5099af 962 nvmeq = lock_nvmeq(dev, q_idx);
a51afb54 963 if (nvmeq) {
4f5099af 964 nvme_abort_command(nvmeq, cmdid);
a51afb54
KB
965 unlock_nvmeq(nvmeq);
966 }
3c0cf138
MW
967 return -EINTR;
968 }
969
b60503ba
MW
970 if (result)
971 *result = cmdinfo.result;
972
973 return cmdinfo.status;
974}
975
4d115420
KB
976static int nvme_submit_async_cmd(struct nvme_queue *nvmeq,
977 struct nvme_command *cmd,
978 struct async_cmd_info *cmdinfo, unsigned timeout)
979{
980 int cmdid;
981
982 cmdid = alloc_cmdid_killable(nvmeq, cmdinfo, async_completion, timeout);
983 if (cmdid < 0)
984 return cmdid;
985 cmdinfo->status = -EINTR;
986 cmd->common.command_id = cmdid;
4f5099af 987 return nvme_submit_cmd(nvmeq, cmd);
4d115420
KB
988}
989
5d0f6131 990int nvme_submit_admin_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
b60503ba
MW
991 u32 *result)
992{
4f5099af
KB
993 return nvme_submit_sync_cmd(dev, 0, cmd, result, ADMIN_TIMEOUT);
994}
995
996int nvme_submit_io_cmd(struct nvme_dev *dev, struct nvme_command *cmd,
997 u32 *result)
998{
59055356
SB
999 return nvme_submit_sync_cmd(dev, this_cpu_read(*dev->io_queue), cmd,
1000 result, NVME_IO_TIMEOUT);
b60503ba
MW
1001}
1002
4d115420
KB
1003static int nvme_submit_admin_cmd_async(struct nvme_dev *dev,
1004 struct nvme_command *cmd, struct async_cmd_info *cmdinfo)
1005{
5a92e700 1006 return nvme_submit_async_cmd(raw_nvmeq(dev, 0), cmd, cmdinfo,
4d115420
KB
1007 ADMIN_TIMEOUT);
1008}
1009
b60503ba
MW
1010static int adapter_delete_queue(struct nvme_dev *dev, u8 opcode, u16 id)
1011{
1012 int status;
1013 struct nvme_command c;
1014
1015 memset(&c, 0, sizeof(c));
1016 c.delete_queue.opcode = opcode;
1017 c.delete_queue.qid = cpu_to_le16(id);
1018
1019 status = nvme_submit_admin_cmd(dev, &c, NULL);
1020 if (status)
1021 return -EIO;
1022 return 0;
1023}
1024
1025static int adapter_alloc_cq(struct nvme_dev *dev, u16 qid,
1026 struct nvme_queue *nvmeq)
1027{
1028 int status;
1029 struct nvme_command c;
1030 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_CQ_IRQ_ENABLED;
1031
1032 memset(&c, 0, sizeof(c));
1033 c.create_cq.opcode = nvme_admin_create_cq;
1034 c.create_cq.prp1 = cpu_to_le64(nvmeq->cq_dma_addr);
1035 c.create_cq.cqid = cpu_to_le16(qid);
1036 c.create_cq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1037 c.create_cq.cq_flags = cpu_to_le16(flags);
1038 c.create_cq.irq_vector = cpu_to_le16(nvmeq->cq_vector);
1039
1040 status = nvme_submit_admin_cmd(dev, &c, NULL);
1041 if (status)
1042 return -EIO;
1043 return 0;
1044}
1045
1046static int adapter_alloc_sq(struct nvme_dev *dev, u16 qid,
1047 struct nvme_queue *nvmeq)
1048{
1049 int status;
1050 struct nvme_command c;
1051 int flags = NVME_QUEUE_PHYS_CONTIG | NVME_SQ_PRIO_MEDIUM;
1052
1053 memset(&c, 0, sizeof(c));
1054 c.create_sq.opcode = nvme_admin_create_sq;
1055 c.create_sq.prp1 = cpu_to_le64(nvmeq->sq_dma_addr);
1056 c.create_sq.sqid = cpu_to_le16(qid);
1057 c.create_sq.qsize = cpu_to_le16(nvmeq->q_depth - 1);
1058 c.create_sq.sq_flags = cpu_to_le16(flags);
1059 c.create_sq.cqid = cpu_to_le16(qid);
1060
1061 status = nvme_submit_admin_cmd(dev, &c, NULL);
1062 if (status)
1063 return -EIO;
1064 return 0;
1065}
1066
1067static int adapter_delete_cq(struct nvme_dev *dev, u16 cqid)
1068{
1069 return adapter_delete_queue(dev, nvme_admin_delete_cq, cqid);
1070}
1071
1072static int adapter_delete_sq(struct nvme_dev *dev, u16 sqid)
1073{
1074 return adapter_delete_queue(dev, nvme_admin_delete_sq, sqid);
1075}
1076
5d0f6131 1077int nvme_identify(struct nvme_dev *dev, unsigned nsid, unsigned cns,
bc5fc7e4
MW
1078 dma_addr_t dma_addr)
1079{
1080 struct nvme_command c;
1081
1082 memset(&c, 0, sizeof(c));
1083 c.identify.opcode = nvme_admin_identify;
1084 c.identify.nsid = cpu_to_le32(nsid);
1085 c.identify.prp1 = cpu_to_le64(dma_addr);
1086 c.identify.cns = cpu_to_le32(cns);
1087
1088 return nvme_submit_admin_cmd(dev, &c, NULL);
1089}
1090
5d0f6131 1091int nvme_get_features(struct nvme_dev *dev, unsigned fid, unsigned nsid,
08df1e05 1092 dma_addr_t dma_addr, u32 *result)
bc5fc7e4
MW
1093{
1094 struct nvme_command c;
1095
1096 memset(&c, 0, sizeof(c));
1097 c.features.opcode = nvme_admin_get_features;
a42cecce 1098 c.features.nsid = cpu_to_le32(nsid);
bc5fc7e4
MW
1099 c.features.prp1 = cpu_to_le64(dma_addr);
1100 c.features.fid = cpu_to_le32(fid);
bc5fc7e4 1101
08df1e05 1102 return nvme_submit_admin_cmd(dev, &c, result);
df348139
MW
1103}
1104
5d0f6131
VV
1105int nvme_set_features(struct nvme_dev *dev, unsigned fid, unsigned dword11,
1106 dma_addr_t dma_addr, u32 *result)
df348139
MW
1107{
1108 struct nvme_command c;
1109
1110 memset(&c, 0, sizeof(c));
1111 c.features.opcode = nvme_admin_set_features;
1112 c.features.prp1 = cpu_to_le64(dma_addr);
1113 c.features.fid = cpu_to_le32(fid);
1114 c.features.dword11 = cpu_to_le32(dword11);
1115
bc5fc7e4
MW
1116 return nvme_submit_admin_cmd(dev, &c, result);
1117}
1118
c30341dc
KB
1119/**
1120 * nvme_abort_cmd - Attempt aborting a command
1121 * @cmdid: Command id of a timed out IO
1122 * @queue: The queue with timed out IO
1123 *
1124 * Schedule controller reset if the command was already aborted once before and
1125 * still hasn't been returned to the driver, or if this is the admin queue.
1126 */
1127static void nvme_abort_cmd(int cmdid, struct nvme_queue *nvmeq)
1128{
1129 int a_cmdid;
1130 struct nvme_command cmd;
1131 struct nvme_dev *dev = nvmeq->dev;
1132 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
5a92e700 1133 struct nvme_queue *adminq;
c30341dc
KB
1134
1135 if (!nvmeq->qid || info[cmdid].aborted) {
1136 if (work_busy(&dev->reset_work))
1137 return;
1138 list_del_init(&dev->node);
1139 dev_warn(&dev->pci_dev->dev,
1140 "I/O %d QID %d timeout, reset controller\n", cmdid,
1141 nvmeq->qid);
9ca97374 1142 dev->reset_workfn = nvme_reset_failed_dev;
c30341dc
KB
1143 queue_work(nvme_workq, &dev->reset_work);
1144 return;
1145 }
1146
1147 if (!dev->abort_limit)
1148 return;
1149
5a92e700
KB
1150 adminq = rcu_dereference(dev->queues[0]);
1151 a_cmdid = alloc_cmdid(adminq, CMD_CTX_ABORT, special_completion,
c30341dc
KB
1152 ADMIN_TIMEOUT);
1153 if (a_cmdid < 0)
1154 return;
1155
1156 memset(&cmd, 0, sizeof(cmd));
1157 cmd.abort.opcode = nvme_admin_abort_cmd;
1158 cmd.abort.cid = cmdid;
1159 cmd.abort.sqid = cpu_to_le16(nvmeq->qid);
1160 cmd.abort.command_id = a_cmdid;
1161
1162 --dev->abort_limit;
1163 info[cmdid].aborted = 1;
1164 info[cmdid].timeout = jiffies + ADMIN_TIMEOUT;
1165
1166 dev_warn(nvmeq->q_dmadev, "Aborting I/O %d QID %d\n", cmdid,
1167 nvmeq->qid);
5a92e700 1168 nvme_submit_cmd(adminq, &cmd);
c30341dc
KB
1169}
1170
a09115b2
MW
1171/**
1172 * nvme_cancel_ios - Cancel outstanding I/Os
1173 * @queue: The queue to cancel I/Os on
1174 * @timeout: True to only cancel I/Os which have timed out
1175 */
1176static void nvme_cancel_ios(struct nvme_queue *nvmeq, bool timeout)
1177{
1178 int depth = nvmeq->q_depth - 1;
1179 struct nvme_cmd_info *info = nvme_cmd_info(nvmeq);
1180 unsigned long now = jiffies;
1181 int cmdid;
1182
1183 for_each_set_bit(cmdid, nvmeq->cmdid_data, depth) {
1184 void *ctx;
1185 nvme_completion_fn fn;
1186 static struct nvme_completion cqe = {
af2d9ca7 1187 .status = cpu_to_le16(NVME_SC_ABORT_REQ << 1),
a09115b2
MW
1188 };
1189
1190 if (timeout && !time_after(now, info[cmdid].timeout))
1191 continue;
053ab702
KB
1192 if (info[cmdid].ctx == CMD_CTX_CANCELLED)
1193 continue;
6fccf938
KB
1194 if (timeout && info[cmdid].ctx == CMD_CTX_ASYNC)
1195 continue;
c30341dc
KB
1196 if (timeout && nvmeq->dev->initialized) {
1197 nvme_abort_cmd(cmdid, nvmeq);
1198 continue;
1199 }
1200 dev_warn(nvmeq->q_dmadev, "Cancelling I/O %d QID %d\n", cmdid,
1201 nvmeq->qid);
a09115b2 1202 ctx = cancel_cmdid(nvmeq, cmdid, &fn);
edd10d33 1203 fn(nvmeq, ctx, &cqe);
a09115b2
MW
1204 }
1205}
1206
f435c282 1207static void nvme_free_queue(struct nvme_queue *nvmeq)
9e866774 1208{
22404274
KB
1209 spin_lock_irq(&nvmeq->q_lock);
1210 while (bio_list_peek(&nvmeq->sq_cong)) {
1211 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1212 bio_endio(bio, -EIO);
1213 }
edd10d33
KB
1214 while (!list_empty(&nvmeq->iod_bio)) {
1215 static struct nvme_completion cqe = {
1216 .status = cpu_to_le16(
1217 (NVME_SC_ABORT_REQ | NVME_SC_DNR) << 1),
1218 };
1219 struct nvme_iod *iod = list_first_entry(&nvmeq->iod_bio,
1220 struct nvme_iod,
1221 node);
1222 list_del(&iod->node);
1223 bio_completion(nvmeq, iod, &cqe);
1224 }
22404274
KB
1225 spin_unlock_irq(&nvmeq->q_lock);
1226
9e866774
MW
1227 dma_free_coherent(nvmeq->q_dmadev, CQ_SIZE(nvmeq->q_depth),
1228 (void *)nvmeq->cqes, nvmeq->cq_dma_addr);
1229 dma_free_coherent(nvmeq->q_dmadev, SQ_SIZE(nvmeq->q_depth),
1230 nvmeq->sq_cmds, nvmeq->sq_dma_addr);
42f61420
KB
1231 if (nvmeq->qid)
1232 free_cpumask_var(nvmeq->cpu_mask);
9e866774
MW
1233 kfree(nvmeq);
1234}
1235
a1a5ef99 1236static void nvme_free_queues(struct nvme_dev *dev, int lowest)
22404274 1237{
f435c282
KB
1238 LLIST_HEAD(q_list);
1239 struct nvme_queue *nvmeq, *next;
1240 struct llist_node *entry;
22404274
KB
1241 int i;
1242
a1a5ef99 1243 for (i = dev->queue_count - 1; i >= lowest; i--) {
f435c282 1244 nvmeq = raw_nvmeq(dev, i);
062261be 1245 RCU_INIT_POINTER(dev->queues[i], NULL);
f435c282 1246 llist_add(&nvmeq->node, &q_list);
22404274 1247 dev->queue_count--;
22404274 1248 }
f435c282
KB
1249 synchronize_rcu();
1250 entry = llist_del_all(&q_list);
1251 llist_for_each_entry_safe(nvmeq, next, entry, node)
1252 nvme_free_queue(nvmeq);
22404274
KB
1253}
1254
4d115420
KB
1255/**
1256 * nvme_suspend_queue - put queue into suspended state
1257 * @nvmeq - queue to suspend
1258 *
1259 * Returns 1 if already suspended, 0 otherwise.
1260 */
1261static int nvme_suspend_queue(struct nvme_queue *nvmeq)
b60503ba 1262{
4d115420 1263 int vector = nvmeq->dev->entry[nvmeq->cq_vector].vector;
b60503ba 1264
a09115b2 1265 spin_lock_irq(&nvmeq->q_lock);
22404274
KB
1266 if (nvmeq->q_suspended) {
1267 spin_unlock_irq(&nvmeq->q_lock);
4d115420 1268 return 1;
3295874b 1269 }
22404274 1270 nvmeq->q_suspended = 1;
42f61420 1271 nvmeq->dev->online_queues--;
a09115b2
MW
1272 spin_unlock_irq(&nvmeq->q_lock);
1273
aba2080f
MW
1274 irq_set_affinity_hint(vector, NULL);
1275 free_irq(vector, nvmeq);
b60503ba 1276
4d115420
KB
1277 return 0;
1278}
b60503ba 1279
4d115420
KB
1280static void nvme_clear_queue(struct nvme_queue *nvmeq)
1281{
22404274
KB
1282 spin_lock_irq(&nvmeq->q_lock);
1283 nvme_process_cq(nvmeq);
1284 nvme_cancel_ios(nvmeq, false);
1285 spin_unlock_irq(&nvmeq->q_lock);
b60503ba
MW
1286}
1287
4d115420
KB
1288static void nvme_disable_queue(struct nvme_dev *dev, int qid)
1289{
5a92e700 1290 struct nvme_queue *nvmeq = raw_nvmeq(dev, qid);
4d115420
KB
1291
1292 if (!nvmeq)
1293 return;
1294 if (nvme_suspend_queue(nvmeq))
1295 return;
1296
0e53d180
KB
1297 /* Don't tell the adapter to delete the admin queue.
1298 * Don't tell a removed adapter to delete IO queues. */
1299 if (qid && readl(&dev->bar->csts) != -1) {
b60503ba
MW
1300 adapter_delete_sq(dev, qid);
1301 adapter_delete_cq(dev, qid);
1302 }
4d115420 1303 nvme_clear_queue(nvmeq);
b60503ba
MW
1304}
1305
1306static struct nvme_queue *nvme_alloc_queue(struct nvme_dev *dev, int qid,
1307 int depth, int vector)
1308{
1309 struct device *dmadev = &dev->pci_dev->dev;
22404274 1310 unsigned extra = nvme_queue_extra(depth);
b60503ba
MW
1311 struct nvme_queue *nvmeq = kzalloc(sizeof(*nvmeq) + extra, GFP_KERNEL);
1312 if (!nvmeq)
1313 return NULL;
1314
4d51abf9
JP
1315 nvmeq->cqes = dma_zalloc_coherent(dmadev, CQ_SIZE(depth),
1316 &nvmeq->cq_dma_addr, GFP_KERNEL);
b60503ba
MW
1317 if (!nvmeq->cqes)
1318 goto free_nvmeq;
b60503ba
MW
1319
1320 nvmeq->sq_cmds = dma_alloc_coherent(dmadev, SQ_SIZE(depth),
1321 &nvmeq->sq_dma_addr, GFP_KERNEL);
1322 if (!nvmeq->sq_cmds)
1323 goto free_cqdma;
1324
42f61420
KB
1325 if (qid && !zalloc_cpumask_var(&nvmeq->cpu_mask, GFP_KERNEL))
1326 goto free_sqdma;
1327
b60503ba 1328 nvmeq->q_dmadev = dmadev;
091b6092 1329 nvmeq->dev = dev;
3193f07b
MW
1330 snprintf(nvmeq->irqname, sizeof(nvmeq->irqname), "nvme%dq%d",
1331 dev->instance, qid);
b60503ba
MW
1332 spin_lock_init(&nvmeq->q_lock);
1333 nvmeq->cq_head = 0;
82123460 1334 nvmeq->cq_phase = 1;
b60503ba
MW
1335 init_waitqueue_head(&nvmeq->sq_full);
1336 bio_list_init(&nvmeq->sq_cong);
edd10d33 1337 INIT_LIST_HEAD(&nvmeq->iod_bio);
b80d5ccc 1338 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
b60503ba
MW
1339 nvmeq->q_depth = depth;
1340 nvmeq->cq_vector = vector;
c30341dc 1341 nvmeq->qid = qid;
22404274
KB
1342 nvmeq->q_suspended = 1;
1343 dev->queue_count++;
5a92e700 1344 rcu_assign_pointer(dev->queues[qid], nvmeq);
b60503ba
MW
1345
1346 return nvmeq;
1347
42f61420
KB
1348 free_sqdma:
1349 dma_free_coherent(dmadev, SQ_SIZE(depth), (void *)nvmeq->sq_cmds,
1350 nvmeq->sq_dma_addr);
b60503ba 1351 free_cqdma:
68b8eca5 1352 dma_free_coherent(dmadev, CQ_SIZE(depth), (void *)nvmeq->cqes,
b60503ba
MW
1353 nvmeq->cq_dma_addr);
1354 free_nvmeq:
1355 kfree(nvmeq);
1356 return NULL;
1357}
1358
3001082c
MW
1359static int queue_request_irq(struct nvme_dev *dev, struct nvme_queue *nvmeq,
1360 const char *name)
1361{
58ffacb5
MW
1362 if (use_threaded_interrupts)
1363 return request_threaded_irq(dev->entry[nvmeq->cq_vector].vector,
481e5bad 1364 nvme_irq_check, nvme_irq, IRQF_SHARED,
58ffacb5 1365 name, nvmeq);
3001082c 1366 return request_irq(dev->entry[nvmeq->cq_vector].vector, nvme_irq,
481e5bad 1367 IRQF_SHARED, name, nvmeq);
3001082c
MW
1368}
1369
22404274 1370static void nvme_init_queue(struct nvme_queue *nvmeq, u16 qid)
b60503ba 1371{
22404274
KB
1372 struct nvme_dev *dev = nvmeq->dev;
1373 unsigned extra = nvme_queue_extra(nvmeq->q_depth);
b60503ba 1374
7be50e93
KB
1375 spin_lock_irq(&nvmeq->q_lock);
1376 init_waitqueue_entry(&nvmeq->sq_cong_wait, nvme_thread);
22404274
KB
1377 nvmeq->sq_tail = 0;
1378 nvmeq->cq_head = 0;
1379 nvmeq->cq_phase = 1;
b80d5ccc 1380 nvmeq->q_db = &dev->dbs[qid * 2 * dev->db_stride];
22404274
KB
1381 memset(nvmeq->cmdid_data, 0, extra);
1382 memset((void *)nvmeq->cqes, 0, CQ_SIZE(nvmeq->q_depth));
1383 nvme_cancel_ios(nvmeq, false);
1384 nvmeq->q_suspended = 0;
42f61420 1385 dev->online_queues++;
7be50e93 1386 spin_unlock_irq(&nvmeq->q_lock);
22404274
KB
1387}
1388
1389static int nvme_create_queue(struct nvme_queue *nvmeq, int qid)
1390{
1391 struct nvme_dev *dev = nvmeq->dev;
1392 int result;
3f85d50b 1393
b60503ba
MW
1394 result = adapter_alloc_cq(dev, qid, nvmeq);
1395 if (result < 0)
22404274 1396 return result;
b60503ba
MW
1397
1398 result = adapter_alloc_sq(dev, qid, nvmeq);
1399 if (result < 0)
1400 goto release_cq;
1401
3193f07b 1402 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
b60503ba
MW
1403 if (result < 0)
1404 goto release_sq;
1405
22404274 1406 nvme_init_queue(nvmeq, qid);
22404274 1407 return result;
b60503ba
MW
1408
1409 release_sq:
1410 adapter_delete_sq(dev, qid);
1411 release_cq:
1412 adapter_delete_cq(dev, qid);
22404274 1413 return result;
b60503ba
MW
1414}
1415
ba47e386
MW
1416static int nvme_wait_ready(struct nvme_dev *dev, u64 cap, bool enabled)
1417{
1418 unsigned long timeout;
1419 u32 bit = enabled ? NVME_CSTS_RDY : 0;
1420
1421 timeout = ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1422
1423 while ((readl(&dev->bar->csts) & NVME_CSTS_RDY) != bit) {
1424 msleep(100);
1425 if (fatal_signal_pending(current))
1426 return -EINTR;
1427 if (time_after(jiffies, timeout)) {
1428 dev_err(&dev->pci_dev->dev,
27e8166c
MW
1429 "Device not ready; aborting %s\n", enabled ?
1430 "initialisation" : "reset");
ba47e386
MW
1431 return -ENODEV;
1432 }
1433 }
1434
1435 return 0;
1436}
1437
1438/*
1439 * If the device has been passed off to us in an enabled state, just clear
1440 * the enabled bit. The spec says we should set the 'shutdown notification
1441 * bits', but doing so may cause the device to complete commands to the
1442 * admin queue ... and we don't know what memory that might be pointing at!
1443 */
1444static int nvme_disable_ctrl(struct nvme_dev *dev, u64 cap)
1445{
01079522
DM
1446 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1447 dev->ctrl_config &= ~NVME_CC_ENABLE;
1448 writel(dev->ctrl_config, &dev->bar->cc);
44af146a 1449
ba47e386
MW
1450 return nvme_wait_ready(dev, cap, false);
1451}
1452
1453static int nvme_enable_ctrl(struct nvme_dev *dev, u64 cap)
1454{
01079522
DM
1455 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1456 dev->ctrl_config |= NVME_CC_ENABLE;
1457 writel(dev->ctrl_config, &dev->bar->cc);
1458
ba47e386
MW
1459 return nvme_wait_ready(dev, cap, true);
1460}
1461
1894d8f1
KB
1462static int nvme_shutdown_ctrl(struct nvme_dev *dev)
1463{
1464 unsigned long timeout;
1894d8f1 1465
01079522
DM
1466 dev->ctrl_config &= ~NVME_CC_SHN_MASK;
1467 dev->ctrl_config |= NVME_CC_SHN_NORMAL;
1468
1469 writel(dev->ctrl_config, &dev->bar->cc);
1894d8f1 1470
2484f407 1471 timeout = SHUTDOWN_TIMEOUT + jiffies;
1894d8f1
KB
1472 while ((readl(&dev->bar->csts) & NVME_CSTS_SHST_MASK) !=
1473 NVME_CSTS_SHST_CMPLT) {
1474 msleep(100);
1475 if (fatal_signal_pending(current))
1476 return -EINTR;
1477 if (time_after(jiffies, timeout)) {
1478 dev_err(&dev->pci_dev->dev,
1479 "Device shutdown incomplete; abort shutdown\n");
1480 return -ENODEV;
1481 }
1482 }
1483
1484 return 0;
1485}
1486
8d85fce7 1487static int nvme_configure_admin_queue(struct nvme_dev *dev)
b60503ba 1488{
ba47e386 1489 int result;
b60503ba 1490 u32 aqa;
ba47e386 1491 u64 cap = readq(&dev->bar->cap);
b60503ba 1492 struct nvme_queue *nvmeq;
1d090624
KB
1493 unsigned page_shift = PAGE_SHIFT;
1494 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12;
1495 unsigned dev_page_max = NVME_CAP_MPSMAX(cap) + 12;
1496
1497 if (page_shift < dev_page_min) {
1498 dev_err(&dev->pci_dev->dev,
1499 "Minimum device page size (%u) too large for "
1500 "host (%u)\n", 1 << dev_page_min,
1501 1 << page_shift);
1502 return -ENODEV;
1503 }
1504 if (page_shift > dev_page_max) {
1505 dev_info(&dev->pci_dev->dev,
1506 "Device maximum page size (%u) smaller than "
1507 "host (%u); enabling work-around\n",
1508 1 << dev_page_max, 1 << page_shift);
1509 page_shift = dev_page_max;
1510 }
b60503ba 1511
ba47e386
MW
1512 result = nvme_disable_ctrl(dev, cap);
1513 if (result < 0)
1514 return result;
b60503ba 1515
5a92e700 1516 nvmeq = raw_nvmeq(dev, 0);
cd638946
KB
1517 if (!nvmeq) {
1518 nvmeq = nvme_alloc_queue(dev, 0, 64, 0);
1519 if (!nvmeq)
1520 return -ENOMEM;
cd638946 1521 }
b60503ba
MW
1522
1523 aqa = nvmeq->q_depth - 1;
1524 aqa |= aqa << 16;
1525
1d090624
KB
1526 dev->page_size = 1 << page_shift;
1527
01079522 1528 dev->ctrl_config = NVME_CC_CSS_NVM;
1d090624 1529 dev->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
b60503ba 1530 dev->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
7f53f9d2 1531 dev->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
b60503ba
MW
1532
1533 writel(aqa, &dev->bar->aqa);
1534 writeq(nvmeq->sq_dma_addr, &dev->bar->asq);
1535 writeq(nvmeq->cq_dma_addr, &dev->bar->acq);
b60503ba 1536
ba47e386 1537 result = nvme_enable_ctrl(dev, cap);
025c557a 1538 if (result)
cd638946 1539 return result;
9e866774 1540
3193f07b 1541 result = queue_request_irq(dev, nvmeq, nvmeq->irqname);
025c557a 1542 if (result)
cd638946 1543 return result;
025c557a 1544
b60503ba
MW
1545 return result;
1546}
1547
5d0f6131 1548struct nvme_iod *nvme_map_user_pages(struct nvme_dev *dev, int write,
eca18b23 1549 unsigned long addr, unsigned length)
b60503ba 1550{
36c14ed9 1551 int i, err, count, nents, offset;
7fc3cdab
MW
1552 struct scatterlist *sg;
1553 struct page **pages;
eca18b23 1554 struct nvme_iod *iod;
36c14ed9
MW
1555
1556 if (addr & 3)
eca18b23 1557 return ERR_PTR(-EINVAL);
5460fc03 1558 if (!length || length > INT_MAX - PAGE_SIZE)
eca18b23 1559 return ERR_PTR(-EINVAL);
7fc3cdab 1560
36c14ed9 1561 offset = offset_in_page(addr);
7fc3cdab
MW
1562 count = DIV_ROUND_UP(offset + length, PAGE_SIZE);
1563 pages = kcalloc(count, sizeof(*pages), GFP_KERNEL);
22fff826
DC
1564 if (!pages)
1565 return ERR_PTR(-ENOMEM);
36c14ed9
MW
1566
1567 err = get_user_pages_fast(addr, count, 1, pages);
1568 if (err < count) {
1569 count = err;
1570 err = -EFAULT;
1571 goto put_pages;
1572 }
7fc3cdab 1573
6808c5fb 1574 err = -ENOMEM;
1d090624 1575 iod = nvme_alloc_iod(count, length, dev, GFP_KERNEL);
6808c5fb
S
1576 if (!iod)
1577 goto put_pages;
1578
eca18b23 1579 sg = iod->sg;
36c14ed9 1580 sg_init_table(sg, count);
d0ba1e49
MW
1581 for (i = 0; i < count; i++) {
1582 sg_set_page(&sg[i], pages[i],
5460fc03
DC
1583 min_t(unsigned, length, PAGE_SIZE - offset),
1584 offset);
d0ba1e49
MW
1585 length -= (PAGE_SIZE - offset);
1586 offset = 0;
7fc3cdab 1587 }
fe304c43 1588 sg_mark_end(&sg[i - 1]);
1c2ad9fa 1589 iod->nents = count;
7fc3cdab 1590
7fc3cdab
MW
1591 nents = dma_map_sg(&dev->pci_dev->dev, sg, count,
1592 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
36c14ed9 1593 if (!nents)
eca18b23 1594 goto free_iod;
b60503ba 1595
7fc3cdab 1596 kfree(pages);
eca18b23 1597 return iod;
b60503ba 1598
eca18b23
MW
1599 free_iod:
1600 kfree(iod);
7fc3cdab
MW
1601 put_pages:
1602 for (i = 0; i < count; i++)
1603 put_page(pages[i]);
1604 kfree(pages);
eca18b23 1605 return ERR_PTR(err);
7fc3cdab 1606}
b60503ba 1607
5d0f6131 1608void nvme_unmap_user_pages(struct nvme_dev *dev, int write,
1c2ad9fa 1609 struct nvme_iod *iod)
7fc3cdab 1610{
1c2ad9fa 1611 int i;
b60503ba 1612
1c2ad9fa
MW
1613 dma_unmap_sg(&dev->pci_dev->dev, iod->sg, iod->nents,
1614 write ? DMA_TO_DEVICE : DMA_FROM_DEVICE);
7fc3cdab 1615
1c2ad9fa
MW
1616 for (i = 0; i < iod->nents; i++)
1617 put_page(sg_page(&iod->sg[i]));
7fc3cdab 1618}
b60503ba 1619
a53295b6
MW
1620static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
1621{
1622 struct nvme_dev *dev = ns->dev;
a53295b6
MW
1623 struct nvme_user_io io;
1624 struct nvme_command c;
f410c680
KB
1625 unsigned length, meta_len;
1626 int status, i;
1627 struct nvme_iod *iod, *meta_iod = NULL;
1628 dma_addr_t meta_dma_addr;
1629 void *meta, *uninitialized_var(meta_mem);
a53295b6
MW
1630
1631 if (copy_from_user(&io, uio, sizeof(io)))
1632 return -EFAULT;
6c7d4945 1633 length = (io.nblocks + 1) << ns->lba_shift;
f410c680
KB
1634 meta_len = (io.nblocks + 1) * ns->ms;
1635
1636 if (meta_len && ((io.metadata & 3) || !io.metadata))
1637 return -EINVAL;
6c7d4945
MW
1638
1639 switch (io.opcode) {
1640 case nvme_cmd_write:
1641 case nvme_cmd_read:
6bbf1acd 1642 case nvme_cmd_compare:
eca18b23 1643 iod = nvme_map_user_pages(dev, io.opcode & 1, io.addr, length);
6413214c 1644 break;
6c7d4945 1645 default:
6bbf1acd 1646 return -EINVAL;
6c7d4945
MW
1647 }
1648
eca18b23
MW
1649 if (IS_ERR(iod))
1650 return PTR_ERR(iod);
a53295b6
MW
1651
1652 memset(&c, 0, sizeof(c));
1653 c.rw.opcode = io.opcode;
1654 c.rw.flags = io.flags;
6c7d4945 1655 c.rw.nsid = cpu_to_le32(ns->ns_id);
a53295b6 1656 c.rw.slba = cpu_to_le64(io.slba);
6c7d4945 1657 c.rw.length = cpu_to_le16(io.nblocks);
a53295b6 1658 c.rw.control = cpu_to_le16(io.control);
1c9b5265
MW
1659 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
1660 c.rw.reftag = cpu_to_le32(io.reftag);
1661 c.rw.apptag = cpu_to_le16(io.apptag);
1662 c.rw.appmask = cpu_to_le16(io.appmask);
f410c680
KB
1663
1664 if (meta_len) {
1b56749e
KB
1665 meta_iod = nvme_map_user_pages(dev, io.opcode & 1, io.metadata,
1666 meta_len);
f410c680
KB
1667 if (IS_ERR(meta_iod)) {
1668 status = PTR_ERR(meta_iod);
1669 meta_iod = NULL;
1670 goto unmap;
1671 }
1672
1673 meta_mem = dma_alloc_coherent(&dev->pci_dev->dev, meta_len,
1674 &meta_dma_addr, GFP_KERNEL);
1675 if (!meta_mem) {
1676 status = -ENOMEM;
1677 goto unmap;
1678 }
1679
1680 if (io.opcode & 1) {
1681 int meta_offset = 0;
1682
1683 for (i = 0; i < meta_iod->nents; i++) {
1684 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1685 meta_iod->sg[i].offset;
1686 memcpy(meta_mem + meta_offset, meta,
1687 meta_iod->sg[i].length);
1688 kunmap_atomic(meta);
1689 meta_offset += meta_iod->sg[i].length;
1690 }
1691 }
1692
1693 c.rw.metadata = cpu_to_le64(meta_dma_addr);
1694 }
1695
edd10d33
KB
1696 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1697 c.rw.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1698 c.rw.prp2 = cpu_to_le64(iod->first_dma);
a53295b6 1699
b77954cb
MW
1700 if (length != (io.nblocks + 1) << ns->lba_shift)
1701 status = -ENOMEM;
1702 else
4f5099af 1703 status = nvme_submit_io_cmd(dev, &c, NULL);
a53295b6 1704
f410c680
KB
1705 if (meta_len) {
1706 if (status == NVME_SC_SUCCESS && !(io.opcode & 1)) {
1707 int meta_offset = 0;
1708
1709 for (i = 0; i < meta_iod->nents; i++) {
1710 meta = kmap_atomic(sg_page(&meta_iod->sg[i])) +
1711 meta_iod->sg[i].offset;
1712 memcpy(meta, meta_mem + meta_offset,
1713 meta_iod->sg[i].length);
1714 kunmap_atomic(meta);
1715 meta_offset += meta_iod->sg[i].length;
1716 }
1717 }
1718
1719 dma_free_coherent(&dev->pci_dev->dev, meta_len, meta_mem,
1720 meta_dma_addr);
1721 }
1722
1723 unmap:
1c2ad9fa 1724 nvme_unmap_user_pages(dev, io.opcode & 1, iod);
eca18b23 1725 nvme_free_iod(dev, iod);
f410c680
KB
1726
1727 if (meta_iod) {
1728 nvme_unmap_user_pages(dev, io.opcode & 1, meta_iod);
1729 nvme_free_iod(dev, meta_iod);
1730 }
1731
a53295b6
MW
1732 return status;
1733}
1734
50af8bae 1735static int nvme_user_admin_cmd(struct nvme_dev *dev,
6bbf1acd 1736 struct nvme_admin_cmd __user *ucmd)
6ee44cdc 1737{
6bbf1acd 1738 struct nvme_admin_cmd cmd;
6ee44cdc 1739 struct nvme_command c;
eca18b23 1740 int status, length;
c7d36ab8 1741 struct nvme_iod *uninitialized_var(iod);
94f370ca 1742 unsigned timeout;
6ee44cdc 1743
6bbf1acd
MW
1744 if (!capable(CAP_SYS_ADMIN))
1745 return -EACCES;
1746 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
6ee44cdc 1747 return -EFAULT;
6ee44cdc
MW
1748
1749 memset(&c, 0, sizeof(c));
6bbf1acd
MW
1750 c.common.opcode = cmd.opcode;
1751 c.common.flags = cmd.flags;
1752 c.common.nsid = cpu_to_le32(cmd.nsid);
1753 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1754 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1755 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1756 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1757 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1758 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1759 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1760 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1761
1762 length = cmd.data_len;
1763 if (cmd.data_len) {
49742188
MW
1764 iod = nvme_map_user_pages(dev, cmd.opcode & 1, cmd.addr,
1765 length);
eca18b23
MW
1766 if (IS_ERR(iod))
1767 return PTR_ERR(iod);
edd10d33
KB
1768 length = nvme_setup_prps(dev, iod, length, GFP_KERNEL);
1769 c.common.prp1 = cpu_to_le64(sg_dma_address(iod->sg));
1770 c.common.prp2 = cpu_to_le64(iod->first_dma);
6bbf1acd
MW
1771 }
1772
94f370ca
KB
1773 timeout = cmd.timeout_ms ? msecs_to_jiffies(cmd.timeout_ms) :
1774 ADMIN_TIMEOUT;
6bbf1acd 1775 if (length != cmd.data_len)
b77954cb
MW
1776 status = -ENOMEM;
1777 else
4f5099af 1778 status = nvme_submit_sync_cmd(dev, 0, &c, &cmd.result, timeout);
eca18b23 1779
6bbf1acd 1780 if (cmd.data_len) {
1c2ad9fa 1781 nvme_unmap_user_pages(dev, cmd.opcode & 1, iod);
eca18b23 1782 nvme_free_iod(dev, iod);
6bbf1acd 1783 }
f4f117f6 1784
cf90bc48 1785 if ((status >= 0) && copy_to_user(&ucmd->result, &cmd.result,
f4f117f6
KB
1786 sizeof(cmd.result)))
1787 status = -EFAULT;
1788
6ee44cdc
MW
1789 return status;
1790}
1791
b60503ba
MW
1792static int nvme_ioctl(struct block_device *bdev, fmode_t mode, unsigned int cmd,
1793 unsigned long arg)
1794{
1795 struct nvme_ns *ns = bdev->bd_disk->private_data;
1796
1797 switch (cmd) {
6bbf1acd 1798 case NVME_IOCTL_ID:
c3bfe717 1799 force_successful_syscall_return();
6bbf1acd
MW
1800 return ns->ns_id;
1801 case NVME_IOCTL_ADMIN_CMD:
50af8bae 1802 return nvme_user_admin_cmd(ns->dev, (void __user *)arg);
a53295b6
MW
1803 case NVME_IOCTL_SUBMIT_IO:
1804 return nvme_submit_io(ns, (void __user *)arg);
5d0f6131
VV
1805 case SG_GET_VERSION_NUM:
1806 return nvme_sg_get_version_num((void __user *)arg);
1807 case SG_IO:
1808 return nvme_sg_io(ns, (void __user *)arg);
b60503ba
MW
1809 default:
1810 return -ENOTTY;
1811 }
1812}
1813
320a3827
KB
1814#ifdef CONFIG_COMPAT
1815static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
1816 unsigned int cmd, unsigned long arg)
1817{
320a3827
KB
1818 switch (cmd) {
1819 case SG_IO:
e179729a 1820 return -ENOIOCTLCMD;
320a3827
KB
1821 }
1822 return nvme_ioctl(bdev, mode, cmd, arg);
1823}
1824#else
1825#define nvme_compat_ioctl NULL
1826#endif
1827
9ac27090
KB
1828static int nvme_open(struct block_device *bdev, fmode_t mode)
1829{
1830 struct nvme_ns *ns = bdev->bd_disk->private_data;
1831 struct nvme_dev *dev = ns->dev;
1832
1833 kref_get(&dev->kref);
1834 return 0;
1835}
1836
1837static void nvme_free_dev(struct kref *kref);
1838
1839static void nvme_release(struct gendisk *disk, fmode_t mode)
1840{
1841 struct nvme_ns *ns = disk->private_data;
1842 struct nvme_dev *dev = ns->dev;
1843
1844 kref_put(&dev->kref, nvme_free_dev);
1845}
1846
4cc09e2d
KB
1847static int nvme_getgeo(struct block_device *bd, struct hd_geometry *geo)
1848{
1849 /* some standard values */
1850 geo->heads = 1 << 6;
1851 geo->sectors = 1 << 5;
1852 geo->cylinders = get_capacity(bd->bd_disk) >> 11;
1853 return 0;
1854}
1855
1b9dbf7f
KB
1856static int nvme_revalidate_disk(struct gendisk *disk)
1857{
1858 struct nvme_ns *ns = disk->private_data;
1859 struct nvme_dev *dev = ns->dev;
1860 struct nvme_id_ns *id;
1861 dma_addr_t dma_addr;
1862 int lbaf;
1863
1864 id = dma_alloc_coherent(&dev->pci_dev->dev, 4096, &dma_addr,
1865 GFP_KERNEL);
1866 if (!id) {
1867 dev_warn(&dev->pci_dev->dev, "%s: Memory alocation failure\n",
1868 __func__);
1869 return 0;
1870 }
1871
1872 if (nvme_identify(dev, ns->ns_id, 0, dma_addr))
1873 goto free;
1874
1875 lbaf = id->flbas & 0xf;
1876 ns->lba_shift = id->lbaf[lbaf].ds;
1877
1878 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1879 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1880 free:
1881 dma_free_coherent(&dev->pci_dev->dev, 4096, id, dma_addr);
1882 return 0;
1883}
1884
b60503ba
MW
1885static const struct block_device_operations nvme_fops = {
1886 .owner = THIS_MODULE,
1887 .ioctl = nvme_ioctl,
320a3827 1888 .compat_ioctl = nvme_compat_ioctl,
9ac27090
KB
1889 .open = nvme_open,
1890 .release = nvme_release,
4cc09e2d 1891 .getgeo = nvme_getgeo,
1b9dbf7f 1892 .revalidate_disk= nvme_revalidate_disk,
b60503ba
MW
1893};
1894
edd10d33
KB
1895static void nvme_resubmit_iods(struct nvme_queue *nvmeq)
1896{
1897 struct nvme_iod *iod, *next;
1898
1899 list_for_each_entry_safe(iod, next, &nvmeq->iod_bio, node) {
1900 if (unlikely(nvme_submit_iod(nvmeq, iod)))
1901 break;
1902 list_del(&iod->node);
1903 if (bio_list_empty(&nvmeq->sq_cong) &&
1904 list_empty(&nvmeq->iod_bio))
1905 remove_wait_queue(&nvmeq->sq_full,
1906 &nvmeq->sq_cong_wait);
1907 }
1908}
1909
1fa6aead
MW
1910static void nvme_resubmit_bios(struct nvme_queue *nvmeq)
1911{
1912 while (bio_list_peek(&nvmeq->sq_cong)) {
1913 struct bio *bio = bio_list_pop(&nvmeq->sq_cong);
1914 struct nvme_ns *ns = bio->bi_bdev->bd_disk->private_data;
427e9708 1915
edd10d33
KB
1916 if (bio_list_empty(&nvmeq->sq_cong) &&
1917 list_empty(&nvmeq->iod_bio))
427e9708
KB
1918 remove_wait_queue(&nvmeq->sq_full,
1919 &nvmeq->sq_cong_wait);
1fa6aead 1920 if (nvme_submit_bio_queue(nvmeq, ns, bio)) {
edd10d33 1921 if (!waitqueue_active(&nvmeq->sq_full))
427e9708
KB
1922 add_wait_queue(&nvmeq->sq_full,
1923 &nvmeq->sq_cong_wait);
1fa6aead
MW
1924 bio_list_add_head(&nvmeq->sq_cong, bio);
1925 break;
1926 }
1927 }
1928}
1929
6fccf938
KB
1930static int nvme_submit_async_req(struct nvme_queue *nvmeq)
1931{
1932 struct nvme_command *c;
1933 int cmdid;
1934
1935 cmdid = alloc_cmdid(nvmeq, CMD_CTX_ASYNC, special_completion, 0);
1936 if (cmdid < 0)
1937 return cmdid;
1938
1939 c = &nvmeq->sq_cmds[nvmeq->sq_tail];
1940 memset(c, 0, sizeof(*c));
1941 c->common.opcode = nvme_admin_async_event;
1942 c->common.command_id = cmdid;
1943
1944 if (++nvmeq->sq_tail == nvmeq->q_depth)
1945 nvmeq->sq_tail = 0;
1946 writel(nvmeq->sq_tail, nvmeq->q_db);
1947
1948 return 0;
1949}
1950
1fa6aead
MW
1951static int nvme_kthread(void *data)
1952{
d4b4ff8e 1953 struct nvme_dev *dev, *next;
1fa6aead
MW
1954
1955 while (!kthread_should_stop()) {
564a232c 1956 set_current_state(TASK_INTERRUPTIBLE);
1fa6aead 1957 spin_lock(&dev_list_lock);
d4b4ff8e 1958 list_for_each_entry_safe(dev, next, &dev_list, node) {
1fa6aead 1959 int i;
d4b4ff8e
KB
1960 if (readl(&dev->bar->csts) & NVME_CSTS_CFS &&
1961 dev->initialized) {
1962 if (work_busy(&dev->reset_work))
1963 continue;
1964 list_del_init(&dev->node);
1965 dev_warn(&dev->pci_dev->dev,
1966 "Failed status, reset controller\n");
9ca97374 1967 dev->reset_workfn = nvme_reset_failed_dev;
d4b4ff8e
KB
1968 queue_work(nvme_workq, &dev->reset_work);
1969 continue;
1970 }
5a92e700 1971 rcu_read_lock();
1fa6aead 1972 for (i = 0; i < dev->queue_count; i++) {
5a92e700
KB
1973 struct nvme_queue *nvmeq =
1974 rcu_dereference(dev->queues[i]);
740216fc
MW
1975 if (!nvmeq)
1976 continue;
1fa6aead 1977 spin_lock_irq(&nvmeq->q_lock);
22404274
KB
1978 if (nvmeq->q_suspended)
1979 goto unlock;
bc57a0f7 1980 nvme_process_cq(nvmeq);
a09115b2 1981 nvme_cancel_ios(nvmeq, true);
1fa6aead 1982 nvme_resubmit_bios(nvmeq);
edd10d33 1983 nvme_resubmit_iods(nvmeq);
6fccf938
KB
1984
1985 while ((i == 0) && (dev->event_limit > 0)) {
1986 if (nvme_submit_async_req(nvmeq))
1987 break;
1988 dev->event_limit--;
1989 }
22404274 1990 unlock:
1fa6aead
MW
1991 spin_unlock_irq(&nvmeq->q_lock);
1992 }
5a92e700 1993 rcu_read_unlock();
1fa6aead
MW
1994 }
1995 spin_unlock(&dev_list_lock);
acb7aa0d 1996 schedule_timeout(round_jiffies_relative(HZ));
1fa6aead
MW
1997 }
1998 return 0;
1999}
2000
0e5e4f0e
KB
2001static void nvme_config_discard(struct nvme_ns *ns)
2002{
2003 u32 logical_block_size = queue_logical_block_size(ns->queue);
2004 ns->queue->limits.discard_zeroes_data = 0;
2005 ns->queue->limits.discard_alignment = logical_block_size;
2006 ns->queue->limits.discard_granularity = logical_block_size;
2007 ns->queue->limits.max_discard_sectors = 0xffffffff;
2008 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
2009}
2010
c3bfe717 2011static struct nvme_ns *nvme_alloc_ns(struct nvme_dev *dev, unsigned nsid,
b60503ba
MW
2012 struct nvme_id_ns *id, struct nvme_lba_range_type *rt)
2013{
2014 struct nvme_ns *ns;
2015 struct gendisk *disk;
2016 int lbaf;
2017
2018 if (rt->attributes & NVME_LBART_ATTRIB_HIDE)
2019 return NULL;
2020
2021 ns = kzalloc(sizeof(*ns), GFP_KERNEL);
2022 if (!ns)
2023 return NULL;
2024 ns->queue = blk_alloc_queue(GFP_KERNEL);
2025 if (!ns->queue)
2026 goto out_free_ns;
4eeb9215
MW
2027 ns->queue->queue_flags = QUEUE_FLAG_DEFAULT;
2028 queue_flag_set_unlocked(QUEUE_FLAG_NOMERGES, ns->queue);
2029 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
b277da0a 2030 queue_flag_clear_unlocked(QUEUE_FLAG_ADD_RANDOM, ns->queue);
b60503ba
MW
2031 blk_queue_make_request(ns->queue, nvme_make_request);
2032 ns->dev = dev;
2033 ns->queue->queuedata = ns;
2034
469071a3 2035 disk = alloc_disk(0);
b60503ba
MW
2036 if (!disk)
2037 goto out_free_queue;
5aff9382 2038 ns->ns_id = nsid;
b60503ba
MW
2039 ns->disk = disk;
2040 lbaf = id->flbas & 0xf;
2041 ns->lba_shift = id->lbaf[lbaf].ds;
f410c680 2042 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
e9ef4636 2043 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
8fc23e03
KB
2044 if (dev->max_hw_sectors)
2045 blk_queue_max_hw_sectors(ns->queue, dev->max_hw_sectors);
a7d2ce28
KB
2046 if (dev->vwc & NVME_CTRL_VWC_PRESENT)
2047 blk_queue_flush(ns->queue, REQ_FLUSH | REQ_FUA);
b60503ba
MW
2048
2049 disk->major = nvme_major;
469071a3 2050 disk->first_minor = 0;
b60503ba
MW
2051 disk->fops = &nvme_fops;
2052 disk->private_data = ns;
2053 disk->queue = ns->queue;
388f037f 2054 disk->driverfs_dev = &dev->pci_dev->dev;
469071a3 2055 disk->flags = GENHD_FL_EXT_DEVT;
5aff9382 2056 sprintf(disk->disk_name, "nvme%dn%d", dev->instance, nsid);
b60503ba
MW
2057 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
2058
0e5e4f0e
KB
2059 if (dev->oncs & NVME_CTRL_ONCS_DSM)
2060 nvme_config_discard(ns);
2061
b60503ba
MW
2062 return ns;
2063
2064 out_free_queue:
2065 blk_cleanup_queue(ns->queue);
2066 out_free_ns:
2067 kfree(ns);
2068 return NULL;
2069}
2070
42f61420
KB
2071static int nvme_find_closest_node(int node)
2072{
2073 int n, val, min_val = INT_MAX, best_node = node;
2074
2075 for_each_online_node(n) {
2076 if (n == node)
2077 continue;
2078 val = node_distance(node, n);
2079 if (val < min_val) {
2080 min_val = val;
2081 best_node = n;
2082 }
2083 }
2084 return best_node;
2085}
2086
2087static void nvme_set_queue_cpus(cpumask_t *qmask, struct nvme_queue *nvmeq,
2088 int count)
2089{
2090 int cpu;
2091 for_each_cpu(cpu, qmask) {
2092 if (cpumask_weight(nvmeq->cpu_mask) >= count)
2093 break;
2094 if (!cpumask_test_and_set_cpu(cpu, nvmeq->cpu_mask))
2095 *per_cpu_ptr(nvmeq->dev->io_queue, cpu) = nvmeq->qid;
2096 }
2097}
2098
2099static void nvme_add_cpus(cpumask_t *mask, const cpumask_t *unassigned_cpus,
2100 const cpumask_t *new_mask, struct nvme_queue *nvmeq, int cpus_per_queue)
2101{
2102 int next_cpu;
2103 for_each_cpu(next_cpu, new_mask) {
2104 cpumask_or(mask, mask, get_cpu_mask(next_cpu));
2105 cpumask_or(mask, mask, topology_thread_cpumask(next_cpu));
2106 cpumask_and(mask, mask, unassigned_cpus);
2107 nvme_set_queue_cpus(mask, nvmeq, cpus_per_queue);
2108 }
2109}
2110
2111static void nvme_create_io_queues(struct nvme_dev *dev)
2112{
2113 unsigned i, max;
2114
2115 max = min(dev->max_qid, num_online_cpus());
2116 for (i = dev->queue_count; i <= max; i++)
2117 if (!nvme_alloc_queue(dev, i, dev->q_depth, i - 1))
2118 break;
2119
2120 max = min(dev->queue_count - 1, num_online_cpus());
2121 for (i = dev->online_queues; i <= max; i++)
2122 if (nvme_create_queue(raw_nvmeq(dev, i), i))
2123 break;
2124}
2125
2126/*
2127 * If there are fewer queues than online cpus, this will try to optimally
2128 * assign a queue to multiple cpus by grouping cpus that are "close" together:
2129 * thread siblings, core, socket, closest node, then whatever else is
2130 * available.
2131 */
2132static void nvme_assign_io_queues(struct nvme_dev *dev)
2133{
2134 unsigned cpu, cpus_per_queue, queues, remainder, i;
2135 cpumask_var_t unassigned_cpus;
2136
2137 nvme_create_io_queues(dev);
2138
2139 queues = min(dev->online_queues - 1, num_online_cpus());
2140 if (!queues)
2141 return;
2142
2143 cpus_per_queue = num_online_cpus() / queues;
2144 remainder = queues - (num_online_cpus() - queues * cpus_per_queue);
2145
2146 if (!alloc_cpumask_var(&unassigned_cpus, GFP_KERNEL))
2147 return;
2148
2149 cpumask_copy(unassigned_cpus, cpu_online_mask);
2150 cpu = cpumask_first(unassigned_cpus);
2151 for (i = 1; i <= queues; i++) {
2152 struct nvme_queue *nvmeq = lock_nvmeq(dev, i);
2153 cpumask_t mask;
2154
2155 cpumask_clear(nvmeq->cpu_mask);
2156 if (!cpumask_weight(unassigned_cpus)) {
2157 unlock_nvmeq(nvmeq);
2158 break;
2159 }
2160
2161 mask = *get_cpu_mask(cpu);
2162 nvme_set_queue_cpus(&mask, nvmeq, cpus_per_queue);
2163 if (cpus_weight(mask) < cpus_per_queue)
2164 nvme_add_cpus(&mask, unassigned_cpus,
2165 topology_thread_cpumask(cpu),
2166 nvmeq, cpus_per_queue);
2167 if (cpus_weight(mask) < cpus_per_queue)
2168 nvme_add_cpus(&mask, unassigned_cpus,
2169 topology_core_cpumask(cpu),
2170 nvmeq, cpus_per_queue);
2171 if (cpus_weight(mask) < cpus_per_queue)
2172 nvme_add_cpus(&mask, unassigned_cpus,
2173 cpumask_of_node(cpu_to_node(cpu)),
2174 nvmeq, cpus_per_queue);
2175 if (cpus_weight(mask) < cpus_per_queue)
2176 nvme_add_cpus(&mask, unassigned_cpus,
2177 cpumask_of_node(
2178 nvme_find_closest_node(
2179 cpu_to_node(cpu))),
2180 nvmeq, cpus_per_queue);
2181 if (cpus_weight(mask) < cpus_per_queue)
2182 nvme_add_cpus(&mask, unassigned_cpus,
2183 unassigned_cpus,
2184 nvmeq, cpus_per_queue);
2185
2186 WARN(cpumask_weight(nvmeq->cpu_mask) != cpus_per_queue,
2187 "nvme%d qid:%d mis-matched queue-to-cpu assignment\n",
2188 dev->instance, i);
2189
2190 irq_set_affinity_hint(dev->entry[nvmeq->cq_vector].vector,
2191 nvmeq->cpu_mask);
2192 cpumask_andnot(unassigned_cpus, unassigned_cpus,
2193 nvmeq->cpu_mask);
2194 cpu = cpumask_next(cpu, unassigned_cpus);
2195 if (remainder && !--remainder)
2196 cpus_per_queue++;
2197 unlock_nvmeq(nvmeq);
2198 }
2199 WARN(cpumask_weight(unassigned_cpus), "nvme%d unassigned online cpus\n",
2200 dev->instance);
2201 i = 0;
2202 cpumask_andnot(unassigned_cpus, cpu_possible_mask, cpu_online_mask);
2203 for_each_cpu(cpu, unassigned_cpus)
2204 *per_cpu_ptr(dev->io_queue, cpu) = (i++ % queues) + 1;
2205 free_cpumask_var(unassigned_cpus);
2206}
2207
b3b06812 2208static int set_queue_count(struct nvme_dev *dev, int count)
b60503ba
MW
2209{
2210 int status;
2211 u32 result;
b3b06812 2212 u32 q_count = (count - 1) | ((count - 1) << 16);
b60503ba 2213
df348139 2214 status = nvme_set_features(dev, NVME_FEAT_NUM_QUEUES, q_count, 0,
bc5fc7e4 2215 &result);
27e8166c
MW
2216 if (status < 0)
2217 return status;
2218 if (status > 0) {
2219 dev_err(&dev->pci_dev->dev, "Could not set queue count (%d)\n",
2220 status);
badc34d4 2221 return 0;
27e8166c 2222 }
b60503ba
MW
2223 return min(result & 0xffff, result >> 16) + 1;
2224}
2225
9d713c2b
KB
2226static size_t db_bar_size(struct nvme_dev *dev, unsigned nr_io_queues)
2227{
b80d5ccc 2228 return 4096 + ((nr_io_queues + 1) * 8 * dev->db_stride);
9d713c2b
KB
2229}
2230
f3db22fe
KB
2231static void nvme_cpu_workfn(struct work_struct *work)
2232{
2233 struct nvme_dev *dev = container_of(work, struct nvme_dev, cpu_work);
2234 if (dev->initialized)
2235 nvme_assign_io_queues(dev);
2236}
2237
33b1e95c
KB
2238static int nvme_cpu_notify(struct notifier_block *self,
2239 unsigned long action, void *hcpu)
2240{
f3db22fe
KB
2241 struct nvme_dev *dev;
2242
33b1e95c
KB
2243 switch (action) {
2244 case CPU_ONLINE:
2245 case CPU_DEAD:
f3db22fe
KB
2246 spin_lock(&dev_list_lock);
2247 list_for_each_entry(dev, &dev_list, node)
2248 schedule_work(&dev->cpu_work);
2249 spin_unlock(&dev_list_lock);
33b1e95c
KB
2250 break;
2251 }
2252 return NOTIFY_OK;
2253}
2254
8d85fce7 2255static int nvme_setup_io_queues(struct nvme_dev *dev)
b60503ba 2256{
5a92e700 2257 struct nvme_queue *adminq = raw_nvmeq(dev, 0);
fa08a396 2258 struct pci_dev *pdev = dev->pci_dev;
42f61420 2259 int result, i, vecs, nr_io_queues, size;
b60503ba 2260
42f61420 2261 nr_io_queues = num_possible_cpus();
b348b7d5 2262 result = set_queue_count(dev, nr_io_queues);
badc34d4 2263 if (result <= 0)
1b23484b 2264 return result;
b348b7d5
MW
2265 if (result < nr_io_queues)
2266 nr_io_queues = result;
b60503ba 2267
9d713c2b
KB
2268 size = db_bar_size(dev, nr_io_queues);
2269 if (size > 8192) {
f1938f6e 2270 iounmap(dev->bar);
9d713c2b
KB
2271 do {
2272 dev->bar = ioremap(pci_resource_start(pdev, 0), size);
2273 if (dev->bar)
2274 break;
2275 if (!--nr_io_queues)
2276 return -ENOMEM;
2277 size = db_bar_size(dev, nr_io_queues);
2278 } while (1);
f1938f6e 2279 dev->dbs = ((void __iomem *)dev->bar) + 4096;
5a92e700 2280 adminq->q_db = dev->dbs;
f1938f6e
MW
2281 }
2282
9d713c2b 2283 /* Deregister the admin queue's interrupt */
3193f07b 2284 free_irq(dev->entry[0].vector, adminq);
9d713c2b 2285
be577fab 2286 for (i = 0; i < nr_io_queues; i++)
1b23484b 2287 dev->entry[i].entry = i;
be577fab
AG
2288 vecs = pci_enable_msix_range(pdev, dev->entry, 1, nr_io_queues);
2289 if (vecs < 0) {
2290 vecs = pci_enable_msi_range(pdev, 1, min(nr_io_queues, 32));
2291 if (vecs < 0) {
2292 vecs = 1;
2293 } else {
2294 for (i = 0; i < vecs; i++)
2295 dev->entry[i].vector = i + pdev->irq;
fa08a396
RRG
2296 }
2297 }
2298
063a8096
MW
2299 /*
2300 * Should investigate if there's a performance win from allocating
2301 * more queues than interrupt vectors; it might allow the submission
2302 * path to scale better, even if the receive path is limited by the
2303 * number of interrupts.
2304 */
2305 nr_io_queues = vecs;
42f61420 2306 dev->max_qid = nr_io_queues;
063a8096 2307
3193f07b 2308 result = queue_request_irq(dev, adminq, adminq->irqname);
9d713c2b 2309 if (result) {
3193f07b 2310 adminq->q_suspended = 1;
22404274 2311 goto free_queues;
9d713c2b 2312 }
1b23484b 2313
cd638946 2314 /* Free previously allocated queues that are no longer usable */
42f61420
KB
2315 nvme_free_queues(dev, nr_io_queues + 1);
2316 nvme_assign_io_queues(dev);
9ecdc946 2317
22404274 2318 return 0;
b60503ba 2319
22404274 2320 free_queues:
a1a5ef99 2321 nvme_free_queues(dev, 1);
22404274 2322 return result;
b60503ba
MW
2323}
2324
422ef0c7
MW
2325/*
2326 * Return: error value if an error occurred setting up the queues or calling
2327 * Identify Device. 0 if these succeeded, even if adding some of the
2328 * namespaces failed. At the moment, these failures are silent. TBD which
2329 * failures should be reported.
2330 */
8d85fce7 2331static int nvme_dev_add(struct nvme_dev *dev)
b60503ba 2332{
68608c26 2333 struct pci_dev *pdev = dev->pci_dev;
c3bfe717
MW
2334 int res;
2335 unsigned nn, i;
cbb6218f 2336 struct nvme_ns *ns;
51814232 2337 struct nvme_id_ctrl *ctrl;
bc5fc7e4
MW
2338 struct nvme_id_ns *id_ns;
2339 void *mem;
b60503ba 2340 dma_addr_t dma_addr;
159b67d7 2341 int shift = NVME_CAP_MPSMIN(readq(&dev->bar->cap)) + 12;
b60503ba 2342
68608c26 2343 mem = dma_alloc_coherent(&pdev->dev, 8192, &dma_addr, GFP_KERNEL);
a9ef4343
KB
2344 if (!mem)
2345 return -ENOMEM;
b60503ba 2346
bc5fc7e4 2347 res = nvme_identify(dev, 0, 1, dma_addr);
b60503ba 2348 if (res) {
27e8166c 2349 dev_err(&pdev->dev, "Identify Controller failed (%d)\n", res);
b60503ba 2350 res = -EIO;
cbb6218f 2351 goto out;
b60503ba
MW
2352 }
2353
bc5fc7e4 2354 ctrl = mem;
51814232 2355 nn = le32_to_cpup(&ctrl->nn);
0e5e4f0e 2356 dev->oncs = le16_to_cpup(&ctrl->oncs);
c30341dc 2357 dev->abort_limit = ctrl->acl + 1;
a7d2ce28 2358 dev->vwc = ctrl->vwc;
6fccf938 2359 dev->event_limit = min(ctrl->aerl + 1, 8);
51814232
MW
2360 memcpy(dev->serial, ctrl->sn, sizeof(ctrl->sn));
2361 memcpy(dev->model, ctrl->mn, sizeof(ctrl->mn));
2362 memcpy(dev->firmware_rev, ctrl->fr, sizeof(ctrl->fr));
159b67d7 2363 if (ctrl->mdts)
8fc23e03 2364 dev->max_hw_sectors = 1 << (ctrl->mdts + shift - 9);
68608c26
MW
2365 if ((pdev->vendor == PCI_VENDOR_ID_INTEL) &&
2366 (pdev->device == 0x0953) && ctrl->vs[3])
159b67d7 2367 dev->stripe_size = 1 << (ctrl->vs[3] + shift);
b60503ba 2368
bc5fc7e4 2369 id_ns = mem;
2b2c1896 2370 for (i = 1; i <= nn; i++) {
bc5fc7e4 2371 res = nvme_identify(dev, i, 0, dma_addr);
b60503ba
MW
2372 if (res)
2373 continue;
2374
bc5fc7e4 2375 if (id_ns->ncap == 0)
b60503ba
MW
2376 continue;
2377
bc5fc7e4 2378 res = nvme_get_features(dev, NVME_FEAT_LBA_RANGE, i,
08df1e05 2379 dma_addr + 4096, NULL);
b60503ba 2380 if (res)
12209036 2381 memset(mem + 4096, 0, 4096);
b60503ba 2382
bc5fc7e4 2383 ns = nvme_alloc_ns(dev, i, mem, mem + 4096);
b60503ba
MW
2384 if (ns)
2385 list_add_tail(&ns->list, &dev->namespaces);
2386 }
2387 list_for_each_entry(ns, &dev->namespaces, list)
2388 add_disk(ns->disk);
422ef0c7 2389 res = 0;
b60503ba 2390
bc5fc7e4 2391 out:
684f5c20 2392 dma_free_coherent(&dev->pci_dev->dev, 8192, mem, dma_addr);
b60503ba
MW
2393 return res;
2394}
2395
0877cb0d
KB
2396static int nvme_dev_map(struct nvme_dev *dev)
2397{
42f61420 2398 u64 cap;
0877cb0d
KB
2399 int bars, result = -ENOMEM;
2400 struct pci_dev *pdev = dev->pci_dev;
2401
2402 if (pci_enable_device_mem(pdev))
2403 return result;
2404
2405 dev->entry[0].vector = pdev->irq;
2406 pci_set_master(pdev);
2407 bars = pci_select_bars(pdev, IORESOURCE_MEM);
2408 if (pci_request_selected_regions(pdev, bars, "nvme"))
2409 goto disable_pci;
2410
052d0efa
RK
2411 if (dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(64)) &&
2412 dma_set_mask_and_coherent(&pdev->dev, DMA_BIT_MASK(32)))
2413 goto disable;
0877cb0d 2414
0877cb0d
KB
2415 dev->bar = ioremap(pci_resource_start(pdev, 0), 8192);
2416 if (!dev->bar)
2417 goto disable;
0e53d180
KB
2418 if (readl(&dev->bar->csts) == -1) {
2419 result = -ENODEV;
2420 goto unmap;
2421 }
42f61420
KB
2422 cap = readq(&dev->bar->cap);
2423 dev->q_depth = min_t(int, NVME_CAP_MQES(cap) + 1, NVME_Q_DEPTH);
2424 dev->db_stride = 1 << NVME_CAP_STRIDE(cap);
0877cb0d
KB
2425 dev->dbs = ((void __iomem *)dev->bar) + 4096;
2426
2427 return 0;
2428
0e53d180
KB
2429 unmap:
2430 iounmap(dev->bar);
2431 dev->bar = NULL;
0877cb0d
KB
2432 disable:
2433 pci_release_regions(pdev);
2434 disable_pci:
2435 pci_disable_device(pdev);
2436 return result;
2437}
2438
2439static void nvme_dev_unmap(struct nvme_dev *dev)
2440{
2441 if (dev->pci_dev->msi_enabled)
2442 pci_disable_msi(dev->pci_dev);
2443 else if (dev->pci_dev->msix_enabled)
2444 pci_disable_msix(dev->pci_dev);
2445
2446 if (dev->bar) {
2447 iounmap(dev->bar);
2448 dev->bar = NULL;
9a6b9458 2449 pci_release_regions(dev->pci_dev);
0877cb0d
KB
2450 }
2451
0877cb0d
KB
2452 if (pci_is_enabled(dev->pci_dev))
2453 pci_disable_device(dev->pci_dev);
2454}
2455
4d115420
KB
2456struct nvme_delq_ctx {
2457 struct task_struct *waiter;
2458 struct kthread_worker *worker;
2459 atomic_t refcount;
2460};
2461
2462static void nvme_wait_dq(struct nvme_delq_ctx *dq, struct nvme_dev *dev)
2463{
2464 dq->waiter = current;
2465 mb();
2466
2467 for (;;) {
2468 set_current_state(TASK_KILLABLE);
2469 if (!atomic_read(&dq->refcount))
2470 break;
2471 if (!schedule_timeout(ADMIN_TIMEOUT) ||
2472 fatal_signal_pending(current)) {
2473 set_current_state(TASK_RUNNING);
2474
2475 nvme_disable_ctrl(dev, readq(&dev->bar->cap));
2476 nvme_disable_queue(dev, 0);
2477
2478 send_sig(SIGKILL, dq->worker->task, 1);
2479 flush_kthread_worker(dq->worker);
2480 return;
2481 }
2482 }
2483 set_current_state(TASK_RUNNING);
2484}
2485
2486static void nvme_put_dq(struct nvme_delq_ctx *dq)
2487{
2488 atomic_dec(&dq->refcount);
2489 if (dq->waiter)
2490 wake_up_process(dq->waiter);
2491}
2492
2493static struct nvme_delq_ctx *nvme_get_dq(struct nvme_delq_ctx *dq)
2494{
2495 atomic_inc(&dq->refcount);
2496 return dq;
2497}
2498
2499static void nvme_del_queue_end(struct nvme_queue *nvmeq)
2500{
2501 struct nvme_delq_ctx *dq = nvmeq->cmdinfo.ctx;
2502
2503 nvme_clear_queue(nvmeq);
2504 nvme_put_dq(dq);
2505}
2506
2507static int adapter_async_del_queue(struct nvme_queue *nvmeq, u8 opcode,
2508 kthread_work_func_t fn)
2509{
2510 struct nvme_command c;
2511
2512 memset(&c, 0, sizeof(c));
2513 c.delete_queue.opcode = opcode;
2514 c.delete_queue.qid = cpu_to_le16(nvmeq->qid);
2515
2516 init_kthread_work(&nvmeq->cmdinfo.work, fn);
2517 return nvme_submit_admin_cmd_async(nvmeq->dev, &c, &nvmeq->cmdinfo);
2518}
2519
2520static void nvme_del_cq_work_handler(struct kthread_work *work)
2521{
2522 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2523 cmdinfo.work);
2524 nvme_del_queue_end(nvmeq);
2525}
2526
2527static int nvme_delete_cq(struct nvme_queue *nvmeq)
2528{
2529 return adapter_async_del_queue(nvmeq, nvme_admin_delete_cq,
2530 nvme_del_cq_work_handler);
2531}
2532
2533static void nvme_del_sq_work_handler(struct kthread_work *work)
2534{
2535 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2536 cmdinfo.work);
2537 int status = nvmeq->cmdinfo.status;
2538
2539 if (!status)
2540 status = nvme_delete_cq(nvmeq);
2541 if (status)
2542 nvme_del_queue_end(nvmeq);
2543}
2544
2545static int nvme_delete_sq(struct nvme_queue *nvmeq)
2546{
2547 return adapter_async_del_queue(nvmeq, nvme_admin_delete_sq,
2548 nvme_del_sq_work_handler);
2549}
2550
2551static void nvme_del_queue_start(struct kthread_work *work)
2552{
2553 struct nvme_queue *nvmeq = container_of(work, struct nvme_queue,
2554 cmdinfo.work);
2555 allow_signal(SIGKILL);
2556 if (nvme_delete_sq(nvmeq))
2557 nvme_del_queue_end(nvmeq);
2558}
2559
2560static void nvme_disable_io_queues(struct nvme_dev *dev)
2561{
2562 int i;
2563 DEFINE_KTHREAD_WORKER_ONSTACK(worker);
2564 struct nvme_delq_ctx dq;
2565 struct task_struct *kworker_task = kthread_run(kthread_worker_fn,
2566 &worker, "nvme%d", dev->instance);
2567
2568 if (IS_ERR(kworker_task)) {
2569 dev_err(&dev->pci_dev->dev,
2570 "Failed to create queue del task\n");
2571 for (i = dev->queue_count - 1; i > 0; i--)
2572 nvme_disable_queue(dev, i);
2573 return;
2574 }
2575
2576 dq.waiter = NULL;
2577 atomic_set(&dq.refcount, 0);
2578 dq.worker = &worker;
2579 for (i = dev->queue_count - 1; i > 0; i--) {
5a92e700 2580 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
4d115420
KB
2581
2582 if (nvme_suspend_queue(nvmeq))
2583 continue;
2584 nvmeq->cmdinfo.ctx = nvme_get_dq(&dq);
2585 nvmeq->cmdinfo.worker = dq.worker;
2586 init_kthread_work(&nvmeq->cmdinfo.work, nvme_del_queue_start);
2587 queue_kthread_work(dq.worker, &nvmeq->cmdinfo.work);
2588 }
2589 nvme_wait_dq(&dq, dev);
2590 kthread_stop(kworker_task);
2591}
2592
b9afca3e
DM
2593/*
2594* Remove the node from the device list and check
2595* for whether or not we need to stop the nvme_thread.
2596*/
2597static void nvme_dev_list_remove(struct nvme_dev *dev)
2598{
2599 struct task_struct *tmp = NULL;
2600
2601 spin_lock(&dev_list_lock);
2602 list_del_init(&dev->node);
2603 if (list_empty(&dev_list) && !IS_ERR_OR_NULL(nvme_thread)) {
2604 tmp = nvme_thread;
2605 nvme_thread = NULL;
2606 }
2607 spin_unlock(&dev_list_lock);
2608
2609 if (tmp)
2610 kthread_stop(tmp);
2611}
2612
f0b50732 2613static void nvme_dev_shutdown(struct nvme_dev *dev)
b60503ba 2614{
22404274 2615 int i;
7c1b2450 2616 u32 csts = -1;
22404274 2617
d4b4ff8e 2618 dev->initialized = 0;
b9afca3e 2619 nvme_dev_list_remove(dev);
1fa6aead 2620
7c1b2450
KB
2621 if (dev->bar)
2622 csts = readl(&dev->bar->csts);
2623 if (csts & NVME_CSTS_CFS || !(csts & NVME_CSTS_RDY)) {
4d115420 2624 for (i = dev->queue_count - 1; i >= 0; i--) {
5a92e700 2625 struct nvme_queue *nvmeq = raw_nvmeq(dev, i);
4d115420
KB
2626 nvme_suspend_queue(nvmeq);
2627 nvme_clear_queue(nvmeq);
2628 }
2629 } else {
2630 nvme_disable_io_queues(dev);
1894d8f1 2631 nvme_shutdown_ctrl(dev);
4d115420
KB
2632 nvme_disable_queue(dev, 0);
2633 }
f0b50732
KB
2634 nvme_dev_unmap(dev);
2635}
2636
2637static void nvme_dev_remove(struct nvme_dev *dev)
2638{
9ac27090 2639 struct nvme_ns *ns;
f0b50732 2640
9ac27090
KB
2641 list_for_each_entry(ns, &dev->namespaces, list) {
2642 if (ns->disk->flags & GENHD_FL_UP)
2643 del_gendisk(ns->disk);
2644 if (!blk_queue_dying(ns->queue))
2645 blk_cleanup_queue(ns->queue);
b60503ba 2646 }
b60503ba
MW
2647}
2648
091b6092
MW
2649static int nvme_setup_prp_pools(struct nvme_dev *dev)
2650{
2651 struct device *dmadev = &dev->pci_dev->dev;
2652 dev->prp_page_pool = dma_pool_create("prp list page", dmadev,
2653 PAGE_SIZE, PAGE_SIZE, 0);
2654 if (!dev->prp_page_pool)
2655 return -ENOMEM;
2656
99802a7a
MW
2657 /* Optimisation for I/Os between 4k and 128k */
2658 dev->prp_small_pool = dma_pool_create("prp list 256", dmadev,
2659 256, 256, 0);
2660 if (!dev->prp_small_pool) {
2661 dma_pool_destroy(dev->prp_page_pool);
2662 return -ENOMEM;
2663 }
091b6092
MW
2664 return 0;
2665}
2666
2667static void nvme_release_prp_pools(struct nvme_dev *dev)
2668{
2669 dma_pool_destroy(dev->prp_page_pool);
99802a7a 2670 dma_pool_destroy(dev->prp_small_pool);
091b6092
MW
2671}
2672
cd58ad7d
QSA
2673static DEFINE_IDA(nvme_instance_ida);
2674
2675static int nvme_set_instance(struct nvme_dev *dev)
b60503ba 2676{
cd58ad7d
QSA
2677 int instance, error;
2678
2679 do {
2680 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2681 return -ENODEV;
2682
2683 spin_lock(&dev_list_lock);
2684 error = ida_get_new(&nvme_instance_ida, &instance);
2685 spin_unlock(&dev_list_lock);
2686 } while (error == -EAGAIN);
2687
2688 if (error)
2689 return -ENODEV;
2690
2691 dev->instance = instance;
2692 return 0;
b60503ba
MW
2693}
2694
2695static void nvme_release_instance(struct nvme_dev *dev)
2696{
cd58ad7d
QSA
2697 spin_lock(&dev_list_lock);
2698 ida_remove(&nvme_instance_ida, dev->instance);
2699 spin_unlock(&dev_list_lock);
b60503ba
MW
2700}
2701
9ac27090
KB
2702static void nvme_free_namespaces(struct nvme_dev *dev)
2703{
2704 struct nvme_ns *ns, *next;
2705
2706 list_for_each_entry_safe(ns, next, &dev->namespaces, list) {
2707 list_del(&ns->list);
2708 put_disk(ns->disk);
2709 kfree(ns);
2710 }
2711}
2712
5e82e952
KB
2713static void nvme_free_dev(struct kref *kref)
2714{
2715 struct nvme_dev *dev = container_of(kref, struct nvme_dev, kref);
9ac27090 2716
a96d4f5c 2717 pci_dev_put(dev->pci_dev);
9ac27090 2718 nvme_free_namespaces(dev);
42f61420 2719 free_percpu(dev->io_queue);
5e82e952
KB
2720 kfree(dev->queues);
2721 kfree(dev->entry);
2722 kfree(dev);
2723}
2724
2725static int nvme_dev_open(struct inode *inode, struct file *f)
2726{
2727 struct nvme_dev *dev = container_of(f->private_data, struct nvme_dev,
2728 miscdev);
2729 kref_get(&dev->kref);
2730 f->private_data = dev;
2731 return 0;
2732}
2733
2734static int nvme_dev_release(struct inode *inode, struct file *f)
2735{
2736 struct nvme_dev *dev = f->private_data;
2737 kref_put(&dev->kref, nvme_free_dev);
2738 return 0;
2739}
2740
2741static long nvme_dev_ioctl(struct file *f, unsigned int cmd, unsigned long arg)
2742{
2743 struct nvme_dev *dev = f->private_data;
2744 switch (cmd) {
2745 case NVME_IOCTL_ADMIN_CMD:
2746 return nvme_user_admin_cmd(dev, (void __user *)arg);
2747 default:
2748 return -ENOTTY;
2749 }
2750}
2751
2752static const struct file_operations nvme_dev_fops = {
2753 .owner = THIS_MODULE,
2754 .open = nvme_dev_open,
2755 .release = nvme_dev_release,
2756 .unlocked_ioctl = nvme_dev_ioctl,
2757 .compat_ioctl = nvme_dev_ioctl,
2758};
2759
f0b50732
KB
2760static int nvme_dev_start(struct nvme_dev *dev)
2761{
2762 int result;
b9afca3e 2763 bool start_thread = false;
f0b50732
KB
2764
2765 result = nvme_dev_map(dev);
2766 if (result)
2767 return result;
2768
2769 result = nvme_configure_admin_queue(dev);
2770 if (result)
2771 goto unmap;
2772
2773 spin_lock(&dev_list_lock);
b9afca3e
DM
2774 if (list_empty(&dev_list) && IS_ERR_OR_NULL(nvme_thread)) {
2775 start_thread = true;
2776 nvme_thread = NULL;
2777 }
f0b50732
KB
2778 list_add(&dev->node, &dev_list);
2779 spin_unlock(&dev_list_lock);
2780
b9afca3e
DM
2781 if (start_thread) {
2782 nvme_thread = kthread_run(nvme_kthread, NULL, "nvme");
2783 wake_up(&nvme_kthread_wait);
2784 } else
2785 wait_event_killable(nvme_kthread_wait, nvme_thread);
2786
2787 if (IS_ERR_OR_NULL(nvme_thread)) {
2788 result = nvme_thread ? PTR_ERR(nvme_thread) : -EINTR;
2789 goto disable;
2790 }
7be50e93 2791 nvme_init_queue(raw_nvmeq(dev, 0), 0);
b9afca3e 2792
f0b50732 2793 result = nvme_setup_io_queues(dev);
badc34d4 2794 if (result)
f0b50732
KB
2795 goto disable;
2796
d82e8bfd 2797 return result;
f0b50732
KB
2798
2799 disable:
a1a5ef99 2800 nvme_disable_queue(dev, 0);
b9afca3e 2801 nvme_dev_list_remove(dev);
f0b50732
KB
2802 unmap:
2803 nvme_dev_unmap(dev);
2804 return result;
2805}
2806
9a6b9458
KB
2807static int nvme_remove_dead_ctrl(void *arg)
2808{
2809 struct nvme_dev *dev = (struct nvme_dev *)arg;
2810 struct pci_dev *pdev = dev->pci_dev;
2811
2812 if (pci_get_drvdata(pdev))
c81f4975 2813 pci_stop_and_remove_bus_device_locked(pdev);
9a6b9458
KB
2814 kref_put(&dev->kref, nvme_free_dev);
2815 return 0;
2816}
2817
2818static void nvme_remove_disks(struct work_struct *ws)
2819{
9a6b9458
KB
2820 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2821
5a92e700 2822 nvme_free_queues(dev, 1);
302c6727 2823 nvme_dev_remove(dev);
9a6b9458
KB
2824}
2825
2826static int nvme_dev_resume(struct nvme_dev *dev)
2827{
2828 int ret;
2829
2830 ret = nvme_dev_start(dev);
badc34d4 2831 if (ret)
9a6b9458 2832 return ret;
badc34d4 2833 if (dev->online_queues < 2) {
9a6b9458 2834 spin_lock(&dev_list_lock);
9ca97374 2835 dev->reset_workfn = nvme_remove_disks;
9a6b9458
KB
2836 queue_work(nvme_workq, &dev->reset_work);
2837 spin_unlock(&dev_list_lock);
2838 }
d4b4ff8e 2839 dev->initialized = 1;
9a6b9458
KB
2840 return 0;
2841}
2842
2843static void nvme_dev_reset(struct nvme_dev *dev)
2844{
2845 nvme_dev_shutdown(dev);
2846 if (nvme_dev_resume(dev)) {
2847 dev_err(&dev->pci_dev->dev, "Device failed to resume\n");
2848 kref_get(&dev->kref);
2849 if (IS_ERR(kthread_run(nvme_remove_dead_ctrl, dev, "nvme%d",
2850 dev->instance))) {
2851 dev_err(&dev->pci_dev->dev,
2852 "Failed to start controller remove task\n");
2853 kref_put(&dev->kref, nvme_free_dev);
2854 }
2855 }
2856}
2857
2858static void nvme_reset_failed_dev(struct work_struct *ws)
2859{
2860 struct nvme_dev *dev = container_of(ws, struct nvme_dev, reset_work);
2861 nvme_dev_reset(dev);
2862}
2863
9ca97374
TH
2864static void nvme_reset_workfn(struct work_struct *work)
2865{
2866 struct nvme_dev *dev = container_of(work, struct nvme_dev, reset_work);
2867 dev->reset_workfn(work);
2868}
2869
8d85fce7 2870static int nvme_probe(struct pci_dev *pdev, const struct pci_device_id *id)
b60503ba 2871{
0877cb0d 2872 int result = -ENOMEM;
b60503ba
MW
2873 struct nvme_dev *dev;
2874
2875 dev = kzalloc(sizeof(*dev), GFP_KERNEL);
2876 if (!dev)
2877 return -ENOMEM;
2878 dev->entry = kcalloc(num_possible_cpus(), sizeof(*dev->entry),
2879 GFP_KERNEL);
2880 if (!dev->entry)
2881 goto free;
1b23484b
MW
2882 dev->queues = kcalloc(num_possible_cpus() + 1, sizeof(void *),
2883 GFP_KERNEL);
b60503ba
MW
2884 if (!dev->queues)
2885 goto free;
42f61420
KB
2886 dev->io_queue = alloc_percpu(unsigned short);
2887 if (!dev->io_queue)
2888 goto free;
b60503ba
MW
2889
2890 INIT_LIST_HEAD(&dev->namespaces);
9ca97374
TH
2891 dev->reset_workfn = nvme_reset_failed_dev;
2892 INIT_WORK(&dev->reset_work, nvme_reset_workfn);
f3db22fe 2893 INIT_WORK(&dev->cpu_work, nvme_cpu_workfn);
a96d4f5c 2894 dev->pci_dev = pci_dev_get(pdev);
9a6b9458 2895 pci_set_drvdata(pdev, dev);
cd58ad7d
QSA
2896 result = nvme_set_instance(dev);
2897 if (result)
a96d4f5c 2898 goto put_pci;
b60503ba 2899
091b6092
MW
2900 result = nvme_setup_prp_pools(dev);
2901 if (result)
0877cb0d 2902 goto release;
091b6092 2903
fb35e914 2904 kref_init(&dev->kref);
f0b50732 2905 result = nvme_dev_start(dev);
badc34d4 2906 if (result)
0877cb0d 2907 goto release_pools;
b60503ba 2908
badc34d4
KB
2909 if (dev->online_queues > 1)
2910 result = nvme_dev_add(dev);
d82e8bfd 2911 if (result)
f0b50732 2912 goto shutdown;
740216fc 2913
5e82e952
KB
2914 scnprintf(dev->name, sizeof(dev->name), "nvme%d", dev->instance);
2915 dev->miscdev.minor = MISC_DYNAMIC_MINOR;
2916 dev->miscdev.parent = &pdev->dev;
2917 dev->miscdev.name = dev->name;
2918 dev->miscdev.fops = &nvme_dev_fops;
2919 result = misc_register(&dev->miscdev);
2920 if (result)
2921 goto remove;
2922
d4b4ff8e 2923 dev->initialized = 1;
b60503ba
MW
2924 return 0;
2925
5e82e952
KB
2926 remove:
2927 nvme_dev_remove(dev);
9ac27090 2928 nvme_free_namespaces(dev);
f0b50732
KB
2929 shutdown:
2930 nvme_dev_shutdown(dev);
0877cb0d 2931 release_pools:
a1a5ef99 2932 nvme_free_queues(dev, 0);
091b6092 2933 nvme_release_prp_pools(dev);
0877cb0d
KB
2934 release:
2935 nvme_release_instance(dev);
a96d4f5c
KB
2936 put_pci:
2937 pci_dev_put(dev->pci_dev);
b60503ba 2938 free:
42f61420 2939 free_percpu(dev->io_queue);
b60503ba
MW
2940 kfree(dev->queues);
2941 kfree(dev->entry);
2942 kfree(dev);
2943 return result;
2944}
2945
f0d54a54
KB
2946static void nvme_reset_notify(struct pci_dev *pdev, bool prepare)
2947{
a6739479 2948 struct nvme_dev *dev = pci_get_drvdata(pdev);
f0d54a54 2949
a6739479
KB
2950 if (prepare)
2951 nvme_dev_shutdown(dev);
2952 else
2953 nvme_dev_resume(dev);
f0d54a54
KB
2954}
2955
09ece142
KB
2956static void nvme_shutdown(struct pci_dev *pdev)
2957{
2958 struct nvme_dev *dev = pci_get_drvdata(pdev);
2959 nvme_dev_shutdown(dev);
2960}
2961
8d85fce7 2962static void nvme_remove(struct pci_dev *pdev)
b60503ba
MW
2963{
2964 struct nvme_dev *dev = pci_get_drvdata(pdev);
9a6b9458
KB
2965
2966 spin_lock(&dev_list_lock);
2967 list_del_init(&dev->node);
2968 spin_unlock(&dev_list_lock);
2969
2970 pci_set_drvdata(pdev, NULL);
2971 flush_work(&dev->reset_work);
f3db22fe 2972 flush_work(&dev->cpu_work);
5e82e952 2973 misc_deregister(&dev->miscdev);
9a6b9458 2974 nvme_dev_shutdown(dev);
a1a5ef99 2975 nvme_free_queues(dev, 0);
302c6727 2976 nvme_dev_remove(dev);
9a6b9458
KB
2977 nvme_release_instance(dev);
2978 nvme_release_prp_pools(dev);
5e82e952 2979 kref_put(&dev->kref, nvme_free_dev);
b60503ba
MW
2980}
2981
2982/* These functions are yet to be implemented */
2983#define nvme_error_detected NULL
2984#define nvme_dump_registers NULL
2985#define nvme_link_reset NULL
2986#define nvme_slot_reset NULL
2987#define nvme_error_resume NULL
cd638946 2988
671a6018 2989#ifdef CONFIG_PM_SLEEP
cd638946
KB
2990static int nvme_suspend(struct device *dev)
2991{
2992 struct pci_dev *pdev = to_pci_dev(dev);
2993 struct nvme_dev *ndev = pci_get_drvdata(pdev);
2994
2995 nvme_dev_shutdown(ndev);
2996 return 0;
2997}
2998
2999static int nvme_resume(struct device *dev)
3000{
3001 struct pci_dev *pdev = to_pci_dev(dev);
3002 struct nvme_dev *ndev = pci_get_drvdata(pdev);
cd638946 3003
9a6b9458 3004 if (nvme_dev_resume(ndev) && !work_busy(&ndev->reset_work)) {
9ca97374 3005 ndev->reset_workfn = nvme_reset_failed_dev;
9a6b9458
KB
3006 queue_work(nvme_workq, &ndev->reset_work);
3007 }
3008 return 0;
cd638946 3009}
671a6018 3010#endif
cd638946
KB
3011
3012static SIMPLE_DEV_PM_OPS(nvme_dev_pm_ops, nvme_suspend, nvme_resume);
b60503ba 3013
1d352035 3014static const struct pci_error_handlers nvme_err_handler = {
b60503ba
MW
3015 .error_detected = nvme_error_detected,
3016 .mmio_enabled = nvme_dump_registers,
3017 .link_reset = nvme_link_reset,
3018 .slot_reset = nvme_slot_reset,
3019 .resume = nvme_error_resume,
f0d54a54 3020 .reset_notify = nvme_reset_notify,
b60503ba
MW
3021};
3022
3023/* Move to pci_ids.h later */
3024#define PCI_CLASS_STORAGE_EXPRESS 0x010802
3025
6eb0d698 3026static const struct pci_device_id nvme_id_table[] = {
b60503ba
MW
3027 { PCI_DEVICE_CLASS(PCI_CLASS_STORAGE_EXPRESS, 0xffffff) },
3028 { 0, }
3029};
3030MODULE_DEVICE_TABLE(pci, nvme_id_table);
3031
3032static struct pci_driver nvme_driver = {
3033 .name = "nvme",
3034 .id_table = nvme_id_table,
3035 .probe = nvme_probe,
8d85fce7 3036 .remove = nvme_remove,
09ece142 3037 .shutdown = nvme_shutdown,
cd638946
KB
3038 .driver = {
3039 .pm = &nvme_dev_pm_ops,
3040 },
b60503ba
MW
3041 .err_handler = &nvme_err_handler,
3042};
3043
3044static int __init nvme_init(void)
3045{
0ac13140 3046 int result;
1fa6aead 3047
b9afca3e 3048 init_waitqueue_head(&nvme_kthread_wait);
b60503ba 3049
9a6b9458
KB
3050 nvme_workq = create_singlethread_workqueue("nvme");
3051 if (!nvme_workq)
b9afca3e 3052 return -ENOMEM;
9a6b9458 3053
5c42ea16
KB
3054 result = register_blkdev(nvme_major, "nvme");
3055 if (result < 0)
9a6b9458 3056 goto kill_workq;
5c42ea16 3057 else if (result > 0)
0ac13140 3058 nvme_major = result;
b60503ba 3059
f3db22fe
KB
3060 nvme_nb.notifier_call = &nvme_cpu_notify;
3061 result = register_hotcpu_notifier(&nvme_nb);
1fa6aead
MW
3062 if (result)
3063 goto unregister_blkdev;
f3db22fe
KB
3064
3065 result = pci_register_driver(&nvme_driver);
3066 if (result)
3067 goto unregister_hotcpu;
1fa6aead 3068 return 0;
b60503ba 3069
f3db22fe
KB
3070 unregister_hotcpu:
3071 unregister_hotcpu_notifier(&nvme_nb);
1fa6aead 3072 unregister_blkdev:
b60503ba 3073 unregister_blkdev(nvme_major, "nvme");
9a6b9458
KB
3074 kill_workq:
3075 destroy_workqueue(nvme_workq);
b60503ba
MW
3076 return result;
3077}
3078
3079static void __exit nvme_exit(void)
3080{
3081 pci_unregister_driver(&nvme_driver);
f3db22fe 3082 unregister_hotcpu_notifier(&nvme_nb);
b60503ba 3083 unregister_blkdev(nvme_major, "nvme");
9a6b9458 3084 destroy_workqueue(nvme_workq);
b9afca3e 3085 BUG_ON(nvme_thread && !IS_ERR(nvme_thread));
21bd78bc 3086 _nvme_check_size();
b60503ba
MW
3087}
3088
3089MODULE_AUTHOR("Matthew Wilcox <willy@linux.intel.com>");
3090MODULE_LICENSE("GPL");
6eb0d698 3091MODULE_VERSION("0.9");
b60503ba
MW
3092module_init(nvme_init);
3093module_exit(nvme_exit);