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