]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - drivers/nvme/host/core.c
nvme: use blk_mq_start_hw_queues() in nvme_kill_queues()
[mirror_ubuntu-bionic-kernel.git] / drivers / nvme / host / core.c
CommitLineData
21d34711
CH
1/*
2 * NVM Express device driver
3 * Copyright (c) 2011-2014, Intel Corporation.
4 *
5 * This program is free software; you can redistribute it and/or modify it
6 * under the terms and conditions of the GNU General Public License,
7 * version 2, as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope it will be useful, but WITHOUT
10 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 * more details.
13 */
14
15#include <linux/blkdev.h>
16#include <linux/blk-mq.h>
5fd4ce1b 17#include <linux/delay.h>
21d34711 18#include <linux/errno.h>
1673f1f0 19#include <linux/hdreg.h>
21d34711 20#include <linux/kernel.h>
5bae7f73
CH
21#include <linux/module.h>
22#include <linux/list_sort.h>
21d34711
CH
23#include <linux/slab.h>
24#include <linux/types.h>
1673f1f0
CH
25#include <linux/pr.h>
26#include <linux/ptrace.h>
27#include <linux/nvme_ioctl.h>
28#include <linux/t10-pi.h>
c5552fde 29#include <linux/pm_qos.h>
1673f1f0
CH
30#include <scsi/sg.h>
31#include <asm/unaligned.h>
21d34711
CH
32
33#include "nvme.h"
038bd4cb 34#include "fabrics.h"
21d34711 35
f3ca80fc
CH
36#define NVME_MINORS (1U << MINORBITS)
37
ba0ba7d3
ML
38unsigned char admin_timeout = 60;
39module_param(admin_timeout, byte, 0644);
40MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
576d55d6 41EXPORT_SYMBOL_GPL(admin_timeout);
ba0ba7d3
ML
42
43unsigned char nvme_io_timeout = 30;
44module_param_named(io_timeout, nvme_io_timeout, byte, 0644);
45MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
576d55d6 46EXPORT_SYMBOL_GPL(nvme_io_timeout);
ba0ba7d3
ML
47
48unsigned char shutdown_timeout = 5;
49module_param(shutdown_timeout, byte, 0644);
50MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
51
44e44b29
CH
52static u8 nvme_max_retries = 5;
53module_param_named(max_retries, nvme_max_retries, byte, 0644);
f80ec966 54MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
5bae7f73 55
f3ca80fc
CH
56static int nvme_char_major;
57module_param(nvme_char_major, int, 0);
58
c5552fde
AL
59static unsigned long default_ps_max_latency_us = 25000;
60module_param(default_ps_max_latency_us, ulong, 0644);
61MODULE_PARM_DESC(default_ps_max_latency_us,
62 "max power saving latency for new devices; use PM QOS to change per device");
63
c35e30b4
AL
64static bool force_apst;
65module_param(force_apst, bool, 0644);
66MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
67
f3ca80fc 68static LIST_HEAD(nvme_ctrl_list);
9f2482b9 69static DEFINE_SPINLOCK(dev_list_lock);
1673f1f0 70
f3ca80fc
CH
71static struct class *nvme_class;
72
65ba6b54 73static int nvme_error_status(struct request *req)
27fa9bc5
CH
74{
75 switch (nvme_req(req)->status & 0x7ff) {
76 case NVME_SC_SUCCESS:
77 return 0;
78 case NVME_SC_CAP_EXCEEDED:
79 return -ENOSPC;
80 default:
81 return -EIO;
e02ab023
JG
82
83 /*
84 * XXX: these errors are a nasty side-band protocol to
85 * drivers/md/dm-mpath.c:noretry_error() that aren't documented
86 * anywhere..
87 */
88 case NVME_SC_CMD_SEQ_ERROR:
89 return -EILSEQ;
90 case NVME_SC_ONCS_NOT_SUPPORTED:
91 return -EOPNOTSUPP;
92 case NVME_SC_WRITE_FAULT:
93 case NVME_SC_READ_ERROR:
94 case NVME_SC_UNWRITTEN_BLOCK:
95 return -ENODATA;
27fa9bc5
CH
96 }
97}
27fa9bc5 98
f6324b1b 99static inline bool nvme_req_needs_retry(struct request *req)
77f02a7a 100{
f6324b1b
CH
101 if (blk_noretry_request(req))
102 return false;
27fa9bc5 103 if (nvme_req(req)->status & NVME_SC_DNR)
f6324b1b
CH
104 return false;
105 if (jiffies - req->start_time >= req->timeout)
106 return false;
44e44b29 107 if (nvme_req(req)->retries >= nvme_max_retries)
f6324b1b
CH
108 return false;
109 return true;
77f02a7a
CH
110}
111
112void nvme_complete_rq(struct request *req)
113{
27fa9bc5
CH
114 if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
115 nvme_req(req)->retries++;
116 blk_mq_requeue_request(req, !blk_mq_queue_stopped(req->q));
117 return;
77f02a7a
CH
118 }
119
27fa9bc5 120 blk_mq_end_request(req, nvme_error_status(req));
77f02a7a
CH
121}
122EXPORT_SYMBOL_GPL(nvme_complete_rq);
123
c55a2fd4
ML
124void nvme_cancel_request(struct request *req, void *data, bool reserved)
125{
126 int status;
127
128 if (!blk_mq_request_started(req))
129 return;
130
131 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
132 "Cancelling I/O %d", req->tag);
133
134 status = NVME_SC_ABORT_REQ;
135 if (blk_queue_dying(req->q))
136 status |= NVME_SC_DNR;
27fa9bc5 137 nvme_req(req)->status = status;
08e0029a 138 blk_mq_complete_request(req);
27fa9bc5 139
c55a2fd4
ML
140}
141EXPORT_SYMBOL_GPL(nvme_cancel_request);
142
bb8d261e
CH
143bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
144 enum nvme_ctrl_state new_state)
145{
f6b6a28e 146 enum nvme_ctrl_state old_state;
bb8d261e
CH
147 bool changed = false;
148
149 spin_lock_irq(&ctrl->lock);
f6b6a28e
GKB
150
151 old_state = ctrl->state;
bb8d261e
CH
152 switch (new_state) {
153 case NVME_CTRL_LIVE:
154 switch (old_state) {
7d2e8008 155 case NVME_CTRL_NEW:
bb8d261e 156 case NVME_CTRL_RESETTING:
def61eca 157 case NVME_CTRL_RECONNECTING:
bb8d261e
CH
158 changed = true;
159 /* FALLTHRU */
160 default:
161 break;
162 }
163 break;
164 case NVME_CTRL_RESETTING:
165 switch (old_state) {
166 case NVME_CTRL_NEW:
def61eca
CH
167 case NVME_CTRL_LIVE:
168 case NVME_CTRL_RECONNECTING:
169 changed = true;
170 /* FALLTHRU */
171 default:
172 break;
173 }
174 break;
175 case NVME_CTRL_RECONNECTING:
176 switch (old_state) {
bb8d261e
CH
177 case NVME_CTRL_LIVE:
178 changed = true;
179 /* FALLTHRU */
180 default:
181 break;
182 }
183 break;
184 case NVME_CTRL_DELETING:
185 switch (old_state) {
186 case NVME_CTRL_LIVE:
187 case NVME_CTRL_RESETTING:
def61eca 188 case NVME_CTRL_RECONNECTING:
bb8d261e
CH
189 changed = true;
190 /* FALLTHRU */
191 default:
192 break;
193 }
194 break;
0ff9d4e1
KB
195 case NVME_CTRL_DEAD:
196 switch (old_state) {
197 case NVME_CTRL_DELETING:
198 changed = true;
199 /* FALLTHRU */
200 default:
201 break;
202 }
203 break;
bb8d261e
CH
204 default:
205 break;
206 }
bb8d261e
CH
207
208 if (changed)
209 ctrl->state = new_state;
210
f6b6a28e
GKB
211 spin_unlock_irq(&ctrl->lock);
212
bb8d261e
CH
213 return changed;
214}
215EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
216
1673f1f0
CH
217static void nvme_free_ns(struct kref *kref)
218{
219 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
220
b0b4e09c
MB
221 if (ns->ndev)
222 nvme_nvm_unregister(ns);
1673f1f0 223
b0b4e09c
MB
224 if (ns->disk) {
225 spin_lock(&dev_list_lock);
226 ns->disk->private_data = NULL;
227 spin_unlock(&dev_list_lock);
228 }
1673f1f0 229
1673f1f0 230 put_disk(ns->disk);
075790eb
KB
231 ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
232 nvme_put_ctrl(ns->ctrl);
1673f1f0
CH
233 kfree(ns);
234}
235
5bae7f73 236static void nvme_put_ns(struct nvme_ns *ns)
1673f1f0
CH
237{
238 kref_put(&ns->kref, nvme_free_ns);
239}
240
241static struct nvme_ns *nvme_get_ns_from_disk(struct gendisk *disk)
242{
243 struct nvme_ns *ns;
244
245 spin_lock(&dev_list_lock);
246 ns = disk->private_data;
e439bb12
SG
247 if (ns) {
248 if (!kref_get_unless_zero(&ns->kref))
249 goto fail;
250 if (!try_module_get(ns->ctrl->ops->module))
251 goto fail_put_ns;
252 }
1673f1f0
CH
253 spin_unlock(&dev_list_lock);
254
255 return ns;
e439bb12
SG
256
257fail_put_ns:
258 kref_put(&ns->kref, nvme_free_ns);
259fail:
260 spin_unlock(&dev_list_lock);
261 return NULL;
1673f1f0
CH
262}
263
4160982e 264struct request *nvme_alloc_request(struct request_queue *q,
eb71f435 265 struct nvme_command *cmd, unsigned int flags, int qid)
21d34711 266{
aebf526b 267 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
21d34711 268 struct request *req;
21d34711 269
eb71f435 270 if (qid == NVME_QID_ANY) {
aebf526b 271 req = blk_mq_alloc_request(q, op, flags);
eb71f435 272 } else {
aebf526b 273 req = blk_mq_alloc_request_hctx(q, op, flags,
eb71f435
CH
274 qid ? qid - 1 : 0);
275 }
21d34711 276 if (IS_ERR(req))
4160982e 277 return req;
21d34711 278
21d34711 279 req->cmd_flags |= REQ_FAILFAST_DRIVER;
d49187e9 280 nvme_req(req)->cmd = cmd;
21d34711 281
4160982e
CH
282 return req;
283}
576d55d6 284EXPORT_SYMBOL_GPL(nvme_alloc_request);
4160982e 285
8093f7ca
ML
286static inline void nvme_setup_flush(struct nvme_ns *ns,
287 struct nvme_command *cmnd)
288{
289 memset(cmnd, 0, sizeof(*cmnd));
290 cmnd->common.opcode = nvme_cmd_flush;
291 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
292}
293
294static inline int nvme_setup_discard(struct nvme_ns *ns, struct request *req,
295 struct nvme_command *cmnd)
296{
b35ba01e 297 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
8093f7ca 298 struct nvme_dsm_range *range;
b35ba01e 299 struct bio *bio;
8093f7ca 300
b35ba01e 301 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
8093f7ca
ML
302 if (!range)
303 return BLK_MQ_RQ_QUEUE_BUSY;
304
b35ba01e
CH
305 __rq_for_each_bio(bio, req) {
306 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
307 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
308
309 range[n].cattr = cpu_to_le32(0);
310 range[n].nlb = cpu_to_le32(nlb);
311 range[n].slba = cpu_to_le64(slba);
312 n++;
313 }
314
315 if (WARN_ON_ONCE(n != segments)) {
316 kfree(range);
317 return BLK_MQ_RQ_QUEUE_ERROR;
318 }
8093f7ca
ML
319
320 memset(cmnd, 0, sizeof(*cmnd));
321 cmnd->dsm.opcode = nvme_cmd_dsm;
322 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
f1dd03a8 323 cmnd->dsm.nr = cpu_to_le32(segments - 1);
8093f7ca
ML
324 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
325
f9d03f96
CH
326 req->special_vec.bv_page = virt_to_page(range);
327 req->special_vec.bv_offset = offset_in_page(range);
b35ba01e 328 req->special_vec.bv_len = sizeof(*range) * segments;
f9d03f96 329 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
8093f7ca 330
bac0000a 331 return BLK_MQ_RQ_QUEUE_OK;
8093f7ca 332}
8093f7ca 333
8093f7ca
ML
334static inline void nvme_setup_rw(struct nvme_ns *ns, struct request *req,
335 struct nvme_command *cmnd)
336{
337 u16 control = 0;
338 u32 dsmgmt = 0;
339
340 if (req->cmd_flags & REQ_FUA)
341 control |= NVME_RW_FUA;
342 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
343 control |= NVME_RW_LR;
344
345 if (req->cmd_flags & REQ_RAHEAD)
346 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
347
348 memset(cmnd, 0, sizeof(*cmnd));
349 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
8093f7ca
ML
350 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
351 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
352 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
353
354 if (ns->ms) {
355 switch (ns->pi_type) {
356 case NVME_NS_DPS_PI_TYPE3:
357 control |= NVME_RW_PRINFO_PRCHK_GUARD;
358 break;
359 case NVME_NS_DPS_PI_TYPE1:
360 case NVME_NS_DPS_PI_TYPE2:
361 control |= NVME_RW_PRINFO_PRCHK_GUARD |
362 NVME_RW_PRINFO_PRCHK_REF;
363 cmnd->rw.reftag = cpu_to_le32(
364 nvme_block_nr(ns, blk_rq_pos(req)));
365 break;
366 }
367 if (!blk_integrity_rq(req))
368 control |= NVME_RW_PRINFO_PRACT;
369 }
370
371 cmnd->rw.control = cpu_to_le16(control);
372 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
373}
374
375int nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
376 struct nvme_command *cmd)
377{
bac0000a 378 int ret = BLK_MQ_RQ_QUEUE_OK;
8093f7ca 379
987f699a 380 if (!(req->rq_flags & RQF_DONTPREP)) {
44e44b29 381 nvme_req(req)->retries = 0;
27fa9bc5 382 nvme_req(req)->flags = 0;
987f699a
CH
383 req->rq_flags |= RQF_DONTPREP;
384 }
385
aebf526b
CH
386 switch (req_op(req)) {
387 case REQ_OP_DRV_IN:
388 case REQ_OP_DRV_OUT:
d49187e9 389 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
aebf526b
CH
390 break;
391 case REQ_OP_FLUSH:
8093f7ca 392 nvme_setup_flush(ns, cmd);
aebf526b 393 break;
e850fd16
CH
394 case REQ_OP_WRITE_ZEROES:
395 /* currently only aliased to deallocate for a few ctrls: */
aebf526b 396 case REQ_OP_DISCARD:
8093f7ca 397 ret = nvme_setup_discard(ns, req, cmd);
aebf526b
CH
398 break;
399 case REQ_OP_READ:
400 case REQ_OP_WRITE:
8093f7ca 401 nvme_setup_rw(ns, req, cmd);
aebf526b
CH
402 break;
403 default:
404 WARN_ON_ONCE(1);
405 return BLK_MQ_RQ_QUEUE_ERROR;
406 }
8093f7ca 407
721b3917 408 cmd->common.command_id = req->tag;
8093f7ca
ML
409 return ret;
410}
411EXPORT_SYMBOL_GPL(nvme_setup_cmd);
412
4160982e
CH
413/*
414 * Returns 0 on success. If the result is negative, it's a Linux error code;
415 * if the result is positive, it's an NVM Express status code
416 */
417int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
d49187e9 418 union nvme_result *result, void *buffer, unsigned bufflen,
eb71f435 419 unsigned timeout, int qid, int at_head, int flags)
4160982e
CH
420{
421 struct request *req;
422 int ret;
423
eb71f435 424 req = nvme_alloc_request(q, cmd, flags, qid);
4160982e
CH
425 if (IS_ERR(req))
426 return PTR_ERR(req);
427
428 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
429
21d34711
CH
430 if (buffer && bufflen) {
431 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
432 if (ret)
433 goto out;
4160982e
CH
434 }
435
eb71f435 436 blk_execute_rq(req->q, NULL, req, at_head);
d49187e9
CH
437 if (result)
438 *result = nvme_req(req)->result;
27fa9bc5
CH
439 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
440 ret = -EINTR;
441 else
442 ret = nvme_req(req)->status;
4160982e
CH
443 out:
444 blk_mq_free_request(req);
445 return ret;
446}
eb71f435 447EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
4160982e
CH
448
449int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
450 void *buffer, unsigned bufflen)
451{
eb71f435
CH
452 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
453 NVME_QID_ANY, 0, 0);
4160982e 454}
576d55d6 455EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
4160982e 456
0b7f1f26
KB
457int __nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
458 void __user *ubuffer, unsigned bufflen,
459 void __user *meta_buffer, unsigned meta_len, u32 meta_seed,
460 u32 *result, unsigned timeout)
4160982e 461{
7a5abb4b 462 bool write = nvme_is_write(cmd);
0b7f1f26
KB
463 struct nvme_ns *ns = q->queuedata;
464 struct gendisk *disk = ns ? ns->disk : NULL;
4160982e 465 struct request *req;
0b7f1f26
KB
466 struct bio *bio = NULL;
467 void *meta = NULL;
4160982e
CH
468 int ret;
469
eb71f435 470 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
4160982e
CH
471 if (IS_ERR(req))
472 return PTR_ERR(req);
473
474 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
475
476 if (ubuffer && bufflen) {
21d34711
CH
477 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
478 GFP_KERNEL);
479 if (ret)
480 goto out;
481 bio = req->bio;
21d34711 482
0b7f1f26
KB
483 if (!disk)
484 goto submit;
485 bio->bi_bdev = bdget_disk(disk, 0);
486 if (!bio->bi_bdev) {
487 ret = -ENODEV;
488 goto out_unmap;
489 }
490
e9fc63d6 491 if (meta_buffer && meta_len) {
0b7f1f26
KB
492 struct bio_integrity_payload *bip;
493
494 meta = kmalloc(meta_len, GFP_KERNEL);
495 if (!meta) {
496 ret = -ENOMEM;
497 goto out_unmap;
498 }
499
500 if (write) {
501 if (copy_from_user(meta, meta_buffer,
502 meta_len)) {
503 ret = -EFAULT;
504 goto out_free_meta;
505 }
506 }
507
508 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
06c1e390
KB
509 if (IS_ERR(bip)) {
510 ret = PTR_ERR(bip);
0b7f1f26
KB
511 goto out_free_meta;
512 }
513
514 bip->bip_iter.bi_size = meta_len;
515 bip->bip_iter.bi_sector = meta_seed;
516
517 ret = bio_integrity_add_page(bio, virt_to_page(meta),
518 meta_len, offset_in_page(meta));
519 if (ret != meta_len) {
520 ret = -ENOMEM;
521 goto out_free_meta;
522 }
523 }
524 }
525 submit:
526 blk_execute_rq(req->q, disk, req, 0);
27fa9bc5
CH
527 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
528 ret = -EINTR;
529 else
530 ret = nvme_req(req)->status;
21d34711 531 if (result)
d49187e9 532 *result = le32_to_cpu(nvme_req(req)->result.u32);
0b7f1f26
KB
533 if (meta && !ret && !write) {
534 if (copy_to_user(meta_buffer, meta, meta_len))
535 ret = -EFAULT;
536 }
537 out_free_meta:
538 kfree(meta);
539 out_unmap:
540 if (bio) {
541 if (disk && bio->bi_bdev)
542 bdput(bio->bi_bdev);
543 blk_rq_unmap_user(bio);
544 }
21d34711
CH
545 out:
546 blk_mq_free_request(req);
547 return ret;
548}
549
0b7f1f26
KB
550int nvme_submit_user_cmd(struct request_queue *q, struct nvme_command *cmd,
551 void __user *ubuffer, unsigned bufflen, u32 *result,
552 unsigned timeout)
553{
554 return __nvme_submit_user_cmd(q, cmd, ubuffer, bufflen, NULL, 0, 0,
555 result, timeout);
556}
557
038bd4cb
SG
558static void nvme_keep_alive_end_io(struct request *rq, int error)
559{
560 struct nvme_ctrl *ctrl = rq->end_io_data;
561
562 blk_mq_free_request(rq);
563
564 if (error) {
565 dev_err(ctrl->device,
566 "failed nvme_keep_alive_end_io error=%d\n", error);
567 return;
568 }
569
570 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
571}
572
573static int nvme_keep_alive(struct nvme_ctrl *ctrl)
574{
575 struct nvme_command c;
576 struct request *rq;
577
578 memset(&c, 0, sizeof(c));
579 c.common.opcode = nvme_admin_keep_alive;
580
581 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
582 NVME_QID_ANY);
583 if (IS_ERR(rq))
584 return PTR_ERR(rq);
585
586 rq->timeout = ctrl->kato * HZ;
587 rq->end_io_data = ctrl;
588
589 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
590
591 return 0;
592}
593
594static void nvme_keep_alive_work(struct work_struct *work)
595{
596 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
597 struct nvme_ctrl, ka_work);
598
599 if (nvme_keep_alive(ctrl)) {
600 /* allocation failure, reset the controller */
601 dev_err(ctrl->device, "keep-alive failed\n");
602 ctrl->ops->reset_ctrl(ctrl);
603 return;
604 }
605}
606
607void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
608{
609 if (unlikely(ctrl->kato == 0))
610 return;
611
612 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
613 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
614}
615EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
616
617void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
618{
619 if (unlikely(ctrl->kato == 0))
620 return;
621
622 cancel_delayed_work_sync(&ctrl->ka_work);
623}
624EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
625
1c63dc66 626int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
21d34711
CH
627{
628 struct nvme_command c = { };
629 int error;
630
631 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
632 c.identify.opcode = nvme_admin_identify;
986994a2 633 c.identify.cns = NVME_ID_CNS_CTRL;
21d34711
CH
634
635 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
636 if (!*id)
637 return -ENOMEM;
638
639 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
640 sizeof(struct nvme_id_ctrl));
641 if (error)
642 kfree(*id);
643 return error;
644}
645
540c801c
KB
646static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
647{
648 struct nvme_command c = { };
649
650 c.identify.opcode = nvme_admin_identify;
986994a2 651 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
540c801c
KB
652 c.identify.nsid = cpu_to_le32(nsid);
653 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
654}
655
1c63dc66 656int nvme_identify_ns(struct nvme_ctrl *dev, unsigned nsid,
21d34711
CH
657 struct nvme_id_ns **id)
658{
659 struct nvme_command c = { };
660 int error;
661
662 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
778f067c
MG
663 c.identify.opcode = nvme_admin_identify;
664 c.identify.nsid = cpu_to_le32(nsid);
986994a2 665 c.identify.cns = NVME_ID_CNS_NS;
21d34711
CH
666
667 *id = kmalloc(sizeof(struct nvme_id_ns), GFP_KERNEL);
668 if (!*id)
669 return -ENOMEM;
670
671 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
672 sizeof(struct nvme_id_ns));
673 if (error)
674 kfree(*id);
675 return error;
676}
677
1c63dc66 678int nvme_get_features(struct nvme_ctrl *dev, unsigned fid, unsigned nsid,
1a6fe74d 679 void *buffer, size_t buflen, u32 *result)
21d34711
CH
680{
681 struct nvme_command c;
d49187e9 682 union nvme_result res;
1cb3cce5 683 int ret;
21d34711
CH
684
685 memset(&c, 0, sizeof(c));
686 c.features.opcode = nvme_admin_get_features;
687 c.features.nsid = cpu_to_le32(nsid);
21d34711
CH
688 c.features.fid = cpu_to_le32(fid);
689
d49187e9 690 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res, buffer, buflen, 0,
eb71f435 691 NVME_QID_ANY, 0, 0);
9b47f77a 692 if (ret >= 0 && result)
d49187e9 693 *result = le32_to_cpu(res.u32);
1cb3cce5 694 return ret;
21d34711
CH
695}
696
1c63dc66 697int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
1a6fe74d 698 void *buffer, size_t buflen, u32 *result)
21d34711
CH
699{
700 struct nvme_command c;
d49187e9 701 union nvme_result res;
1cb3cce5 702 int ret;
21d34711
CH
703
704 memset(&c, 0, sizeof(c));
705 c.features.opcode = nvme_admin_set_features;
21d34711
CH
706 c.features.fid = cpu_to_le32(fid);
707 c.features.dword11 = cpu_to_le32(dword11);
708
d49187e9 709 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1a6fe74d 710 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
9b47f77a 711 if (ret >= 0 && result)
d49187e9 712 *result = le32_to_cpu(res.u32);
1cb3cce5 713 return ret;
21d34711
CH
714}
715
1c63dc66 716int nvme_get_log_page(struct nvme_ctrl *dev, struct nvme_smart_log **log)
21d34711
CH
717{
718 struct nvme_command c = { };
719 int error;
720
721 c.common.opcode = nvme_admin_get_log_page,
722 c.common.nsid = cpu_to_le32(0xFFFFFFFF),
723 c.common.cdw10[0] = cpu_to_le32(
724 (((sizeof(struct nvme_smart_log) / 4) - 1) << 16) |
725 NVME_LOG_SMART),
726
727 *log = kmalloc(sizeof(struct nvme_smart_log), GFP_KERNEL);
728 if (!*log)
729 return -ENOMEM;
730
731 error = nvme_submit_sync_cmd(dev->admin_q, &c, *log,
732 sizeof(struct nvme_smart_log));
733 if (error)
734 kfree(*log);
735 return error;
736}
1673f1f0 737
9a0be7ab
CH
738int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
739{
740 u32 q_count = (*count - 1) | ((*count - 1) << 16);
741 u32 result;
742 int status, nr_io_queues;
743
1a6fe74d 744 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
9a0be7ab 745 &result);
f5fa90dc 746 if (status < 0)
9a0be7ab
CH
747 return status;
748
f5fa90dc
CH
749 /*
750 * Degraded controllers might return an error when setting the queue
751 * count. We still want to be able to bring them online and offer
752 * access to the admin queue, as that might be only way to fix them up.
753 */
754 if (status > 0) {
755 dev_err(ctrl->dev, "Could not set queue count (%d)\n", status);
756 *count = 0;
757 } else {
758 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
759 *count = min(*count, nr_io_queues);
760 }
761
9a0be7ab
CH
762 return 0;
763}
576d55d6 764EXPORT_SYMBOL_GPL(nvme_set_queue_count);
9a0be7ab 765
1673f1f0
CH
766static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
767{
768 struct nvme_user_io io;
769 struct nvme_command c;
770 unsigned length, meta_len;
771 void __user *metadata;
772
773 if (copy_from_user(&io, uio, sizeof(io)))
774 return -EFAULT;
63088ec7
KB
775 if (io.flags)
776 return -EINVAL;
1673f1f0
CH
777
778 switch (io.opcode) {
779 case nvme_cmd_write:
780 case nvme_cmd_read:
781 case nvme_cmd_compare:
782 break;
783 default:
784 return -EINVAL;
785 }
786
787 length = (io.nblocks + 1) << ns->lba_shift;
788 meta_len = (io.nblocks + 1) * ns->ms;
789 metadata = (void __user *)(uintptr_t)io.metadata;
790
791 if (ns->ext) {
792 length += meta_len;
793 meta_len = 0;
794 } else if (meta_len) {
795 if ((io.metadata & 3) || !io.metadata)
796 return -EINVAL;
797 }
798
799 memset(&c, 0, sizeof(c));
800 c.rw.opcode = io.opcode;
801 c.rw.flags = io.flags;
802 c.rw.nsid = cpu_to_le32(ns->ns_id);
803 c.rw.slba = cpu_to_le64(io.slba);
804 c.rw.length = cpu_to_le16(io.nblocks);
805 c.rw.control = cpu_to_le16(io.control);
806 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
807 c.rw.reftag = cpu_to_le32(io.reftag);
808 c.rw.apptag = cpu_to_le16(io.apptag);
809 c.rw.appmask = cpu_to_le16(io.appmask);
810
811 return __nvme_submit_user_cmd(ns->queue, &c,
812 (void __user *)(uintptr_t)io.addr, length,
813 metadata, meta_len, io.slba, NULL, 0);
814}
815
f3ca80fc 816static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1673f1f0
CH
817 struct nvme_passthru_cmd __user *ucmd)
818{
819 struct nvme_passthru_cmd cmd;
820 struct nvme_command c;
821 unsigned timeout = 0;
822 int status;
823
824 if (!capable(CAP_SYS_ADMIN))
825 return -EACCES;
826 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
827 return -EFAULT;
63088ec7
KB
828 if (cmd.flags)
829 return -EINVAL;
1673f1f0
CH
830
831 memset(&c, 0, sizeof(c));
832 c.common.opcode = cmd.opcode;
833 c.common.flags = cmd.flags;
834 c.common.nsid = cpu_to_le32(cmd.nsid);
835 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
836 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
837 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
838 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
839 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
840 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
841 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
842 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
843
844 if (cmd.timeout_ms)
845 timeout = msecs_to_jiffies(cmd.timeout_ms);
846
847 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
d1ea7be5 848 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1673f1f0
CH
849 &cmd.result, timeout);
850 if (status >= 0) {
851 if (put_user(cmd.result, &ucmd->result))
852 return -EFAULT;
853 }
854
855 return status;
856}
857
858static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
859 unsigned int cmd, unsigned long arg)
860{
861 struct nvme_ns *ns = bdev->bd_disk->private_data;
862
863 switch (cmd) {
864 case NVME_IOCTL_ID:
865 force_successful_syscall_return();
866 return ns->ns_id;
867 case NVME_IOCTL_ADMIN_CMD:
868 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
869 case NVME_IOCTL_IO_CMD:
870 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
871 case NVME_IOCTL_SUBMIT_IO:
872 return nvme_submit_io(ns, (void __user *)arg);
44907332 873#ifdef CONFIG_BLK_DEV_NVME_SCSI
1673f1f0
CH
874 case SG_GET_VERSION_NUM:
875 return nvme_sg_get_version_num((void __user *)arg);
876 case SG_IO:
877 return nvme_sg_io(ns, (void __user *)arg);
44907332 878#endif
1673f1f0 879 default:
84d4add7
MB
880#ifdef CONFIG_NVM
881 if (ns->ndev)
882 return nvme_nvm_ioctl(ns, cmd, arg);
883#endif
a98e58e5 884 if (is_sed_ioctl(cmd))
4f1244c8 885 return sed_ioctl(ns->ctrl->opal_dev, cmd,
e225c20e 886 (void __user *) arg);
1673f1f0
CH
887 return -ENOTTY;
888 }
889}
890
891#ifdef CONFIG_COMPAT
892static int nvme_compat_ioctl(struct block_device *bdev, fmode_t mode,
893 unsigned int cmd, unsigned long arg)
894{
895 switch (cmd) {
896 case SG_IO:
897 return -ENOIOCTLCMD;
898 }
899 return nvme_ioctl(bdev, mode, cmd, arg);
900}
901#else
902#define nvme_compat_ioctl NULL
903#endif
904
905static int nvme_open(struct block_device *bdev, fmode_t mode)
906{
907 return nvme_get_ns_from_disk(bdev->bd_disk) ? 0 : -ENXIO;
908}
909
910static void nvme_release(struct gendisk *disk, fmode_t mode)
911{
e439bb12
SG
912 struct nvme_ns *ns = disk->private_data;
913
914 module_put(ns->ctrl->ops->module);
915 nvme_put_ns(ns);
1673f1f0
CH
916}
917
918static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
919{
920 /* some standard values */
921 geo->heads = 1 << 6;
922 geo->sectors = 1 << 5;
923 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
924 return 0;
925}
926
927#ifdef CONFIG_BLK_DEV_INTEGRITY
928static void nvme_init_integrity(struct nvme_ns *ns)
929{
930 struct blk_integrity integrity;
931
fa9a89fc 932 memset(&integrity, 0, sizeof(integrity));
1673f1f0
CH
933 switch (ns->pi_type) {
934 case NVME_NS_DPS_PI_TYPE3:
935 integrity.profile = &t10_pi_type3_crc;
ba36c21b
NB
936 integrity.tag_size = sizeof(u16) + sizeof(u32);
937 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1673f1f0
CH
938 break;
939 case NVME_NS_DPS_PI_TYPE1:
940 case NVME_NS_DPS_PI_TYPE2:
941 integrity.profile = &t10_pi_type1_crc;
ba36c21b
NB
942 integrity.tag_size = sizeof(u16);
943 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1673f1f0
CH
944 break;
945 default:
946 integrity.profile = NULL;
947 break;
948 }
949 integrity.tuple_size = ns->ms;
950 blk_integrity_register(ns->disk, &integrity);
951 blk_queue_max_integrity_segments(ns->queue, 1);
952}
953#else
954static void nvme_init_integrity(struct nvme_ns *ns)
955{
956}
957#endif /* CONFIG_BLK_DEV_INTEGRITY */
958
959static void nvme_config_discard(struct nvme_ns *ns)
960{
08095e70 961 struct nvme_ctrl *ctrl = ns->ctrl;
1673f1f0 962 u32 logical_block_size = queue_logical_block_size(ns->queue);
08095e70 963
b35ba01e
CH
964 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
965 NVME_DSM_MAX_RANGES);
966
1673f1f0
CH
967 ns->queue->limits.discard_alignment = logical_block_size;
968 ns->queue->limits.discard_granularity = logical_block_size;
bd0fc288 969 blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
b35ba01e 970 blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1673f1f0 971 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
e850fd16
CH
972
973 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
974 blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1673f1f0
CH
975}
976
ac81bfa9 977static int nvme_revalidate_ns(struct nvme_ns *ns, struct nvme_id_ns **id)
1673f1f0 978{
ac81bfa9 979 if (nvme_identify_ns(ns->ctrl, ns->ns_id, id)) {
b0b4e09c 980 dev_warn(ns->ctrl->dev, "%s: Identify failure\n", __func__);
1673f1f0
CH
981 return -ENODEV;
982 }
1673f1f0 983
ac81bfa9
MB
984 if ((*id)->ncap == 0) {
985 kfree(*id);
986 return -ENODEV;
1673f1f0
CH
987 }
988
8ef2074d 989 if (ns->ctrl->vs >= NVME_VS(1, 1, 0))
ac81bfa9 990 memcpy(ns->eui, (*id)->eui64, sizeof(ns->eui));
8ef2074d 991 if (ns->ctrl->vs >= NVME_VS(1, 2, 0))
ac81bfa9
MB
992 memcpy(ns->uuid, (*id)->nguid, sizeof(ns->uuid));
993
994 return 0;
995}
996
997static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
998{
999 struct nvme_ns *ns = disk->private_data;
1000 u8 lbaf, pi_type;
1001 u16 old_ms;
1002 unsigned short bs;
2b9b6e86 1003
1673f1f0
CH
1004 old_ms = ns->ms;
1005 lbaf = id->flbas & NVME_NS_FLBAS_LBA_MASK;
1006 ns->lba_shift = id->lbaf[lbaf].ds;
1007 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1008 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1009
1010 /*
1011 * If identify namespace failed, use default 512 byte block size so
1012 * block layer can use before failing read/write for 0 capacity.
1013 */
1014 if (ns->lba_shift == 0)
1015 ns->lba_shift = 9;
1016 bs = 1 << ns->lba_shift;
1673f1f0
CH
1017 /* XXX: PI implementation requires metadata equal t10 pi tuple size */
1018 pi_type = ns->ms == sizeof(struct t10_pi_tuple) ?
1019 id->dps & NVME_NS_DPS_PI_MASK : 0;
1020
1021 blk_mq_freeze_queue(disk->queue);
1022 if (blk_get_integrity(disk) && (ns->pi_type != pi_type ||
1023 ns->ms != old_ms ||
1024 bs != queue_logical_block_size(disk->queue) ||
1025 (ns->ms && ns->ext)))
1026 blk_integrity_unregister(disk);
1027
1028 ns->pi_type = pi_type;
1029 blk_queue_logical_block_size(ns->queue, bs);
1030
4b9d5b15 1031 if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1673f1f0 1032 nvme_init_integrity(ns);
1673f1f0
CH
1033 if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1034 set_capacity(disk, 0);
1035 else
1036 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1037
1038 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
1039 nvme_config_discard(ns);
1040 blk_mq_unfreeze_queue(disk->queue);
ac81bfa9 1041}
1673f1f0 1042
ac81bfa9
MB
1043static int nvme_revalidate_disk(struct gendisk *disk)
1044{
1045 struct nvme_ns *ns = disk->private_data;
1046 struct nvme_id_ns *id = NULL;
1047 int ret;
1048
1049 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1050 set_capacity(disk, 0);
1051 return -ENODEV;
1052 }
1053
1054 ret = nvme_revalidate_ns(ns, &id);
1055 if (ret)
1056 return ret;
1057
1058 __nvme_revalidate_disk(disk, id);
1673f1f0 1059 kfree(id);
ac81bfa9 1060
1673f1f0
CH
1061 return 0;
1062}
1063
1064static char nvme_pr_type(enum pr_type type)
1065{
1066 switch (type) {
1067 case PR_WRITE_EXCLUSIVE:
1068 return 1;
1069 case PR_EXCLUSIVE_ACCESS:
1070 return 2;
1071 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1072 return 3;
1073 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1074 return 4;
1075 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1076 return 5;
1077 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1078 return 6;
1079 default:
1080 return 0;
1081 }
1082};
1083
1084static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1085 u64 key, u64 sa_key, u8 op)
1086{
1087 struct nvme_ns *ns = bdev->bd_disk->private_data;
1088 struct nvme_command c;
1089 u8 data[16] = { 0, };
1090
1091 put_unaligned_le64(key, &data[0]);
1092 put_unaligned_le64(sa_key, &data[8]);
1093
1094 memset(&c, 0, sizeof(c));
1095 c.common.opcode = op;
1096 c.common.nsid = cpu_to_le32(ns->ns_id);
1097 c.common.cdw10[0] = cpu_to_le32(cdw10);
1098
1099 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1100}
1101
1102static int nvme_pr_register(struct block_device *bdev, u64 old,
1103 u64 new, unsigned flags)
1104{
1105 u32 cdw10;
1106
1107 if (flags & ~PR_FL_IGNORE_KEY)
1108 return -EOPNOTSUPP;
1109
1110 cdw10 = old ? 2 : 0;
1111 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1112 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1113 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1114}
1115
1116static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1117 enum pr_type type, unsigned flags)
1118{
1119 u32 cdw10;
1120
1121 if (flags & ~PR_FL_IGNORE_KEY)
1122 return -EOPNOTSUPP;
1123
1124 cdw10 = nvme_pr_type(type) << 8;
1125 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1126 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1127}
1128
1129static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1130 enum pr_type type, bool abort)
1131{
1132 u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1133 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1134}
1135
1136static int nvme_pr_clear(struct block_device *bdev, u64 key)
1137{
8c0b3915 1138 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1673f1f0
CH
1139 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1140}
1141
1142static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1143{
1144 u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1145 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1146}
1147
1148static const struct pr_ops nvme_pr_ops = {
1149 .pr_register = nvme_pr_register,
1150 .pr_reserve = nvme_pr_reserve,
1151 .pr_release = nvme_pr_release,
1152 .pr_preempt = nvme_pr_preempt,
1153 .pr_clear = nvme_pr_clear,
1154};
1155
a98e58e5 1156#ifdef CONFIG_BLK_SED_OPAL
4f1244c8
CH
1157int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1158 bool send)
a98e58e5 1159{
4f1244c8 1160 struct nvme_ctrl *ctrl = data;
a98e58e5 1161 struct nvme_command cmd;
a98e58e5
SB
1162
1163 memset(&cmd, 0, sizeof(cmd));
1164 if (send)
1165 cmd.common.opcode = nvme_admin_security_send;
1166 else
1167 cmd.common.opcode = nvme_admin_security_recv;
a98e58e5
SB
1168 cmd.common.nsid = 0;
1169 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1170 cmd.common.cdw10[1] = cpu_to_le32(len);
1171
1172 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1173 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1174}
1175EXPORT_SYMBOL_GPL(nvme_sec_submit);
1176#endif /* CONFIG_BLK_SED_OPAL */
1177
5bae7f73 1178static const struct block_device_operations nvme_fops = {
1673f1f0
CH
1179 .owner = THIS_MODULE,
1180 .ioctl = nvme_ioctl,
1181 .compat_ioctl = nvme_compat_ioctl,
1182 .open = nvme_open,
1183 .release = nvme_release,
1184 .getgeo = nvme_getgeo,
1185 .revalidate_disk= nvme_revalidate_disk,
1186 .pr_ops = &nvme_pr_ops,
1187};
1188
5fd4ce1b
CH
1189static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1190{
1191 unsigned long timeout =
1192 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1193 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1194 int ret;
1195
1196 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
0df1e4f5
KB
1197 if (csts == ~0)
1198 return -ENODEV;
5fd4ce1b
CH
1199 if ((csts & NVME_CSTS_RDY) == bit)
1200 break;
1201
1202 msleep(100);
1203 if (fatal_signal_pending(current))
1204 return -EINTR;
1205 if (time_after(jiffies, timeout)) {
1b3c47c1 1206 dev_err(ctrl->device,
5fd4ce1b
CH
1207 "Device not ready; aborting %s\n", enabled ?
1208 "initialisation" : "reset");
1209 return -ENODEV;
1210 }
1211 }
1212
1213 return ret;
1214}
1215
1216/*
1217 * If the device has been passed off to us in an enabled state, just clear
1218 * the enabled bit. The spec says we should set the 'shutdown notification
1219 * bits', but doing so may cause the device to complete commands to the
1220 * admin queue ... and we don't know what memory that might be pointing at!
1221 */
1222int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1223{
1224 int ret;
1225
1226 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1227 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1228
1229 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1230 if (ret)
1231 return ret;
54adc010 1232
b5a10c5f 1233 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
54adc010
GP
1234 msleep(NVME_QUIRK_DELAY_AMOUNT);
1235
5fd4ce1b
CH
1236 return nvme_wait_ready(ctrl, cap, false);
1237}
576d55d6 1238EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
5fd4ce1b
CH
1239
1240int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1241{
1242 /*
1243 * Default to a 4K page size, with the intention to update this
1244 * path in the future to accomodate architectures with differing
1245 * kernel and IO page sizes.
1246 */
1247 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1248 int ret;
1249
1250 if (page_shift < dev_page_min) {
1b3c47c1 1251 dev_err(ctrl->device,
5fd4ce1b
CH
1252 "Minimum device page size %u too large for host (%u)\n",
1253 1 << dev_page_min, 1 << page_shift);
1254 return -ENODEV;
1255 }
1256
1257 ctrl->page_size = 1 << page_shift;
1258
1259 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1260 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1261 ctrl->ctrl_config |= NVME_CC_ARB_RR | NVME_CC_SHN_NONE;
1262 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1263 ctrl->ctrl_config |= NVME_CC_ENABLE;
1264
1265 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1266 if (ret)
1267 return ret;
1268 return nvme_wait_ready(ctrl, cap, true);
1269}
576d55d6 1270EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
5fd4ce1b
CH
1271
1272int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1273{
1274 unsigned long timeout = SHUTDOWN_TIMEOUT + jiffies;
1275 u32 csts;
1276 int ret;
1277
1278 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1279 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1280
1281 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1282 if (ret)
1283 return ret;
1284
1285 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1286 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1287 break;
1288
1289 msleep(100);
1290 if (fatal_signal_pending(current))
1291 return -EINTR;
1292 if (time_after(jiffies, timeout)) {
1b3c47c1 1293 dev_err(ctrl->device,
5fd4ce1b
CH
1294 "Device shutdown incomplete; abort shutdown\n");
1295 return -ENODEV;
1296 }
1297 }
1298
1299 return ret;
1300}
576d55d6 1301EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
5fd4ce1b 1302
da35825d
CH
1303static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1304 struct request_queue *q)
1305{
7c88cb00
JA
1306 bool vwc = false;
1307
da35825d 1308 if (ctrl->max_hw_sectors) {
45686b61
CH
1309 u32 max_segments =
1310 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1311
da35825d 1312 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
45686b61 1313 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
da35825d 1314 }
e6282aef
KB
1315 if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1316 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
da35825d 1317 blk_queue_virt_boundary(q, ctrl->page_size - 1);
7c88cb00
JA
1318 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1319 vwc = true;
1320 blk_queue_write_cache(q, vwc, vwc);
da35825d
CH
1321}
1322
c5552fde
AL
1323static void nvme_configure_apst(struct nvme_ctrl *ctrl)
1324{
1325 /*
1326 * APST (Autonomous Power State Transition) lets us program a
1327 * table of power state transitions that the controller will
1328 * perform automatically. We configure it with a simple
1329 * heuristic: we are willing to spend at most 2% of the time
1330 * transitioning between power states. Therefore, when running
1331 * in any given state, we will enter the next lower-power
76e4ad09 1332 * non-operational state after waiting 50 * (enlat + exlat)
c5552fde
AL
1333 * microseconds, as long as that state's total latency is under
1334 * the requested maximum latency.
1335 *
1336 * We will not autonomously enter any non-operational state for
1337 * which the total latency exceeds ps_max_latency_us. Users
1338 * can set ps_max_latency_us to zero to turn off APST.
1339 */
1340
1341 unsigned apste;
1342 struct nvme_feat_auto_pst *table;
fb0dc399
AL
1343 u64 max_lat_us = 0;
1344 int max_ps = -1;
c5552fde
AL
1345 int ret;
1346
1347 /*
1348 * If APST isn't supported or if we haven't been initialized yet,
1349 * then don't do anything.
1350 */
1351 if (!ctrl->apsta)
1352 return;
1353
1354 if (ctrl->npss > 31) {
1355 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1356 return;
1357 }
1358
1359 table = kzalloc(sizeof(*table), GFP_KERNEL);
1360 if (!table)
1361 return;
1362
1363 if (ctrl->ps_max_latency_us == 0) {
1364 /* Turn off APST. */
1365 apste = 0;
fb0dc399 1366 dev_dbg(ctrl->device, "APST disabled\n");
c5552fde
AL
1367 } else {
1368 __le64 target = cpu_to_le64(0);
1369 int state;
1370
1371 /*
1372 * Walk through all states from lowest- to highest-power.
1373 * According to the spec, lower-numbered states use more
1374 * power. NPSS, despite the name, is the index of the
1375 * lowest-power state, not the number of states.
1376 */
1377 for (state = (int)ctrl->npss; state >= 0; state--) {
1378 u64 total_latency_us, transition_ms;
1379
1380 if (target)
1381 table->entries[state] = target;
1382
ff5350a8
AL
1383 /*
1384 * Don't allow transitions to the deepest state
1385 * if it's quirked off.
1386 */
1387 if (state == ctrl->npss &&
1388 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1389 continue;
1390
c5552fde
AL
1391 /*
1392 * Is this state a useful non-operational state for
1393 * higher-power states to autonomously transition to?
1394 */
1395 if (!(ctrl->psd[state].flags &
1396 NVME_PS_FLAGS_NON_OP_STATE))
1397 continue;
1398
1399 total_latency_us =
1400 (u64)le32_to_cpu(ctrl->psd[state].entry_lat) +
1401 + le32_to_cpu(ctrl->psd[state].exit_lat);
1402 if (total_latency_us > ctrl->ps_max_latency_us)
1403 continue;
1404
1405 /*
1406 * This state is good. Use it as the APST idle
1407 * target for higher power states.
1408 */
1409 transition_ms = total_latency_us + 19;
1410 do_div(transition_ms, 20);
1411 if (transition_ms > (1 << 24) - 1)
1412 transition_ms = (1 << 24) - 1;
1413
1414 target = cpu_to_le64((state << 3) |
1415 (transition_ms << 8));
fb0dc399
AL
1416
1417 if (max_ps == -1)
1418 max_ps = state;
1419
1420 if (total_latency_us > max_lat_us)
1421 max_lat_us = total_latency_us;
c5552fde
AL
1422 }
1423
1424 apste = 1;
fb0dc399
AL
1425
1426 if (max_ps == -1) {
1427 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1428 } else {
1429 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1430 max_ps, max_lat_us, (int)sizeof(*table), table);
1431 }
c5552fde
AL
1432 }
1433
1434 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1435 table, sizeof(*table), NULL);
1436 if (ret)
1437 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1438
1439 kfree(table);
1440}
1441
1442static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1443{
1444 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1445 u64 latency;
1446
1447 switch (val) {
1448 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1449 case PM_QOS_LATENCY_ANY:
1450 latency = U64_MAX;
1451 break;
1452
1453 default:
1454 latency = val;
1455 }
1456
1457 if (ctrl->ps_max_latency_us != latency) {
1458 ctrl->ps_max_latency_us = latency;
1459 nvme_configure_apst(ctrl);
1460 }
1461}
1462
bd4da3ab
AL
1463struct nvme_core_quirk_entry {
1464 /*
1465 * NVMe model and firmware strings are padded with spaces. For
1466 * simplicity, strings in the quirk table are padded with NULLs
1467 * instead.
1468 */
1469 u16 vid;
1470 const char *mn;
1471 const char *fr;
1472 unsigned long quirks;
1473};
1474
1475static const struct nvme_core_quirk_entry core_quirks[] = {
c5552fde 1476 {
be56945c
AL
1477 /*
1478 * This Toshiba device seems to die using any APST states. See:
1479 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1480 */
1481 .vid = 0x1179,
1482 .mn = "THNSF5256GPUK TOSHIBA",
c5552fde 1483 .quirks = NVME_QUIRK_NO_APST,
be56945c 1484 }
bd4da3ab
AL
1485};
1486
1487/* match is null-terminated but idstr is space-padded. */
1488static bool string_matches(const char *idstr, const char *match, size_t len)
1489{
1490 size_t matchlen;
1491
1492 if (!match)
1493 return true;
1494
1495 matchlen = strlen(match);
1496 WARN_ON_ONCE(matchlen > len);
1497
1498 if (memcmp(idstr, match, matchlen))
1499 return false;
1500
1501 for (; matchlen < len; matchlen++)
1502 if (idstr[matchlen] != ' ')
1503 return false;
1504
1505 return true;
1506}
1507
1508static bool quirk_matches(const struct nvme_id_ctrl *id,
1509 const struct nvme_core_quirk_entry *q)
1510{
1511 return q->vid == le16_to_cpu(id->vid) &&
1512 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1513 string_matches(id->fr, q->fr, sizeof(id->fr));
1514}
1515
7fd8930f
CH
1516/*
1517 * Initialize the cached copies of the Identify data and various controller
1518 * register in our nvme_ctrl structure. This should be called as soon as
1519 * the admin queue is fully up and running.
1520 */
1521int nvme_init_identify(struct nvme_ctrl *ctrl)
1522{
1523 struct nvme_id_ctrl *id;
1524 u64 cap;
1525 int ret, page_shift;
a229dbf6 1526 u32 max_hw_sectors;
c5552fde 1527 u8 prev_apsta;
7fd8930f 1528
f3ca80fc
CH
1529 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1530 if (ret) {
1b3c47c1 1531 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
f3ca80fc
CH
1532 return ret;
1533 }
1534
7fd8930f
CH
1535 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1536 if (ret) {
1b3c47c1 1537 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
7fd8930f
CH
1538 return ret;
1539 }
1540 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1541
8ef2074d 1542 if (ctrl->vs >= NVME_VS(1, 1, 0))
f3ca80fc
CH
1543 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1544
7fd8930f
CH
1545 ret = nvme_identify_ctrl(ctrl, &id);
1546 if (ret) {
1b3c47c1 1547 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
7fd8930f
CH
1548 return -EIO;
1549 }
1550
bd4da3ab
AL
1551 if (!ctrl->identified) {
1552 /*
1553 * Check for quirks. Quirk can depend on firmware version,
1554 * so, in principle, the set of quirks present can change
1555 * across a reset. As a possible future enhancement, we
1556 * could re-scan for quirks every time we reinitialize
1557 * the device, but we'd have to make sure that the driver
1558 * behaves intelligently if the quirks change.
1559 */
1560
1561 int i;
1562
1563 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1564 if (quirk_matches(id, &core_quirks[i]))
1565 ctrl->quirks |= core_quirks[i].quirks;
1566 }
1567 }
1568
c35e30b4
AL
1569 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1570 dev_warn(ctrl->dev, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1571 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1572 }
1573
8a9ae523 1574 ctrl->oacs = le16_to_cpu(id->oacs);
118472ab 1575 ctrl->vid = le16_to_cpu(id->vid);
7fd8930f 1576 ctrl->oncs = le16_to_cpup(&id->oncs);
6bf25d16 1577 atomic_set(&ctrl->abort_limit, id->acl + 1);
7fd8930f 1578 ctrl->vwc = id->vwc;
931e1c22 1579 ctrl->cntlid = le16_to_cpup(&id->cntlid);
7fd8930f
CH
1580 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1581 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1582 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1583 if (id->mdts)
a229dbf6 1584 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
7fd8930f 1585 else
a229dbf6
CH
1586 max_hw_sectors = UINT_MAX;
1587 ctrl->max_hw_sectors =
1588 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
7fd8930f 1589
da35825d 1590 nvme_set_queue_limits(ctrl, ctrl->admin_q);
07bfcd09 1591 ctrl->sgls = le32_to_cpu(id->sgls);
038bd4cb 1592 ctrl->kas = le16_to_cpu(id->kas);
07bfcd09 1593
c5552fde
AL
1594 ctrl->npss = id->npss;
1595 prev_apsta = ctrl->apsta;
c35e30b4
AL
1596 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1597 if (force_apst && id->apsta) {
1598 dev_warn(ctrl->dev, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1599 ctrl->apsta = 1;
1600 } else {
1601 ctrl->apsta = 0;
1602 }
1603 } else {
1604 ctrl->apsta = id->apsta;
1605 }
c5552fde
AL
1606 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1607
07bfcd09
CH
1608 if (ctrl->ops->is_fabrics) {
1609 ctrl->icdoff = le16_to_cpu(id->icdoff);
1610 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1611 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1612 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1613
1614 /*
1615 * In fabrics we need to verify the cntlid matches the
1616 * admin connect
1617 */
1618 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1619 ret = -EINVAL;
038bd4cb
SG
1620
1621 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1622 dev_err(ctrl->dev,
1623 "keep-alive support is mandatory for fabrics\n");
1624 ret = -EINVAL;
1625 }
07bfcd09
CH
1626 } else {
1627 ctrl->cntlid = le16_to_cpu(id->cntlid);
1628 }
da35825d 1629
7fd8930f 1630 kfree(id);
bd4da3ab 1631
c5552fde
AL
1632 if (ctrl->apsta && !prev_apsta)
1633 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1634 else if (!ctrl->apsta && prev_apsta)
1635 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1636
1637 nvme_configure_apst(ctrl);
1638
bd4da3ab 1639 ctrl->identified = true;
c5552fde 1640
07bfcd09 1641 return ret;
7fd8930f 1642}
576d55d6 1643EXPORT_SYMBOL_GPL(nvme_init_identify);
7fd8930f 1644
f3ca80fc 1645static int nvme_dev_open(struct inode *inode, struct file *file)
1673f1f0 1646{
f3ca80fc
CH
1647 struct nvme_ctrl *ctrl;
1648 int instance = iminor(inode);
1649 int ret = -ENODEV;
1673f1f0 1650
f3ca80fc
CH
1651 spin_lock(&dev_list_lock);
1652 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1653 if (ctrl->instance != instance)
1654 continue;
1655
1656 if (!ctrl->admin_q) {
1657 ret = -EWOULDBLOCK;
1658 break;
1659 }
1660 if (!kref_get_unless_zero(&ctrl->kref))
1661 break;
1662 file->private_data = ctrl;
1663 ret = 0;
1664 break;
1665 }
1666 spin_unlock(&dev_list_lock);
1667
1668 return ret;
1673f1f0
CH
1669}
1670
f3ca80fc 1671static int nvme_dev_release(struct inode *inode, struct file *file)
1673f1f0 1672{
f3ca80fc
CH
1673 nvme_put_ctrl(file->private_data);
1674 return 0;
1675}
1676
bfd89471
CH
1677static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1678{
1679 struct nvme_ns *ns;
1680 int ret;
1681
1682 mutex_lock(&ctrl->namespaces_mutex);
1683 if (list_empty(&ctrl->namespaces)) {
1684 ret = -ENOTTY;
1685 goto out_unlock;
1686 }
1687
1688 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1689 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1b3c47c1 1690 dev_warn(ctrl->device,
bfd89471
CH
1691 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1692 ret = -EINVAL;
1693 goto out_unlock;
1694 }
1695
1b3c47c1 1696 dev_warn(ctrl->device,
bfd89471
CH
1697 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1698 kref_get(&ns->kref);
1699 mutex_unlock(&ctrl->namespaces_mutex);
1700
1701 ret = nvme_user_cmd(ctrl, ns, argp);
1702 nvme_put_ns(ns);
1703 return ret;
1704
1705out_unlock:
1706 mutex_unlock(&ctrl->namespaces_mutex);
1707 return ret;
1708}
1709
f3ca80fc
CH
1710static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1711 unsigned long arg)
1712{
1713 struct nvme_ctrl *ctrl = file->private_data;
1714 void __user *argp = (void __user *)arg;
f3ca80fc
CH
1715
1716 switch (cmd) {
1717 case NVME_IOCTL_ADMIN_CMD:
1718 return nvme_user_cmd(ctrl, NULL, argp);
1719 case NVME_IOCTL_IO_CMD:
bfd89471 1720 return nvme_dev_user_cmd(ctrl, argp);
f3ca80fc 1721 case NVME_IOCTL_RESET:
1b3c47c1 1722 dev_warn(ctrl->device, "resetting controller\n");
f3ca80fc
CH
1723 return ctrl->ops->reset_ctrl(ctrl);
1724 case NVME_IOCTL_SUBSYS_RESET:
1725 return nvme_reset_subsystem(ctrl);
9ec3bb2f
KB
1726 case NVME_IOCTL_RESCAN:
1727 nvme_queue_scan(ctrl);
1728 return 0;
f3ca80fc
CH
1729 default:
1730 return -ENOTTY;
1731 }
1732}
1733
1734static const struct file_operations nvme_dev_fops = {
1735 .owner = THIS_MODULE,
1736 .open = nvme_dev_open,
1737 .release = nvme_dev_release,
1738 .unlocked_ioctl = nvme_dev_ioctl,
1739 .compat_ioctl = nvme_dev_ioctl,
1740};
1741
1742static ssize_t nvme_sysfs_reset(struct device *dev,
1743 struct device_attribute *attr, const char *buf,
1744 size_t count)
1745{
1746 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1747 int ret;
1748
1749 ret = ctrl->ops->reset_ctrl(ctrl);
1750 if (ret < 0)
1751 return ret;
1752 return count;
1673f1f0 1753}
f3ca80fc 1754static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1673f1f0 1755
9ec3bb2f
KB
1756static ssize_t nvme_sysfs_rescan(struct device *dev,
1757 struct device_attribute *attr, const char *buf,
1758 size_t count)
1759{
1760 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1761
1762 nvme_queue_scan(ctrl);
1763 return count;
1764}
1765static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1766
118472ab
KB
1767static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1768 char *buf)
1769{
40267efd 1770 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
118472ab
KB
1771 struct nvme_ctrl *ctrl = ns->ctrl;
1772 int serial_len = sizeof(ctrl->serial);
1773 int model_len = sizeof(ctrl->model);
1774
1775 if (memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1776 return sprintf(buf, "eui.%16phN\n", ns->uuid);
1777
1778 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1779 return sprintf(buf, "eui.%8phN\n", ns->eui);
1780
1781 while (ctrl->serial[serial_len - 1] == ' ')
1782 serial_len--;
1783 while (ctrl->model[model_len - 1] == ' ')
1784 model_len--;
1785
1786 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1787 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1788}
1789static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1790
2b9b6e86
KB
1791static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1792 char *buf)
1793{
40267efd 1794 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
1795 return sprintf(buf, "%pU\n", ns->uuid);
1796}
1797static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1798
1799static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1800 char *buf)
1801{
40267efd 1802 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
1803 return sprintf(buf, "%8phd\n", ns->eui);
1804}
1805static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1806
1807static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1808 char *buf)
1809{
40267efd 1810 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
1811 return sprintf(buf, "%d\n", ns->ns_id);
1812}
1813static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1814
1815static struct attribute *nvme_ns_attrs[] = {
118472ab 1816 &dev_attr_wwid.attr,
2b9b6e86
KB
1817 &dev_attr_uuid.attr,
1818 &dev_attr_eui.attr,
1819 &dev_attr_nsid.attr,
1820 NULL,
1821};
1822
1a353d85 1823static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2b9b6e86
KB
1824 struct attribute *a, int n)
1825{
1826 struct device *dev = container_of(kobj, struct device, kobj);
40267efd 1827 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
1828
1829 if (a == &dev_attr_uuid.attr) {
1830 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1831 return 0;
1832 }
1833 if (a == &dev_attr_eui.attr) {
1834 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1835 return 0;
1836 }
1837 return a->mode;
1838}
1839
1840static const struct attribute_group nvme_ns_attr_group = {
1841 .attrs = nvme_ns_attrs,
1a353d85 1842 .is_visible = nvme_ns_attrs_are_visible,
2b9b6e86
KB
1843};
1844
931e1c22 1845#define nvme_show_str_function(field) \
779ff756
KB
1846static ssize_t field##_show(struct device *dev, \
1847 struct device_attribute *attr, char *buf) \
1848{ \
1849 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1850 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
1851} \
1852static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1853
931e1c22
ML
1854#define nvme_show_int_function(field) \
1855static ssize_t field##_show(struct device *dev, \
1856 struct device_attribute *attr, char *buf) \
1857{ \
1858 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1859 return sprintf(buf, "%d\n", ctrl->field); \
1860} \
1861static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1862
1863nvme_show_str_function(model);
1864nvme_show_str_function(serial);
1865nvme_show_str_function(firmware_rev);
1866nvme_show_int_function(cntlid);
779ff756 1867
1a353d85
ML
1868static ssize_t nvme_sysfs_delete(struct device *dev,
1869 struct device_attribute *attr, const char *buf,
1870 size_t count)
1871{
1872 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1873
1874 if (device_remove_file_self(dev, attr))
1875 ctrl->ops->delete_ctrl(ctrl);
1876 return count;
1877}
1878static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1879
1880static ssize_t nvme_sysfs_show_transport(struct device *dev,
1881 struct device_attribute *attr,
1882 char *buf)
1883{
1884 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1885
1886 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
1887}
1888static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
1889
8432bdb2
SG
1890static ssize_t nvme_sysfs_show_state(struct device *dev,
1891 struct device_attribute *attr,
1892 char *buf)
1893{
1894 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1895 static const char *const state_name[] = {
1896 [NVME_CTRL_NEW] = "new",
1897 [NVME_CTRL_LIVE] = "live",
1898 [NVME_CTRL_RESETTING] = "resetting",
1899 [NVME_CTRL_RECONNECTING]= "reconnecting",
1900 [NVME_CTRL_DELETING] = "deleting",
1901 [NVME_CTRL_DEAD] = "dead",
1902 };
1903
1904 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
1905 state_name[ctrl->state])
1906 return sprintf(buf, "%s\n", state_name[ctrl->state]);
1907
1908 return sprintf(buf, "unknown state\n");
1909}
1910
1911static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
1912
1a353d85
ML
1913static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
1914 struct device_attribute *attr,
1915 char *buf)
1916{
1917 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1918
1919 return snprintf(buf, PAGE_SIZE, "%s\n",
1920 ctrl->ops->get_subsysnqn(ctrl));
1921}
1922static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
1923
1924static ssize_t nvme_sysfs_show_address(struct device *dev,
1925 struct device_attribute *attr,
1926 char *buf)
1927{
1928 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1929
1930 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
1931}
1932static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
1933
779ff756
KB
1934static struct attribute *nvme_dev_attrs[] = {
1935 &dev_attr_reset_controller.attr,
9ec3bb2f 1936 &dev_attr_rescan_controller.attr,
779ff756
KB
1937 &dev_attr_model.attr,
1938 &dev_attr_serial.attr,
1939 &dev_attr_firmware_rev.attr,
931e1c22 1940 &dev_attr_cntlid.attr,
1a353d85
ML
1941 &dev_attr_delete_controller.attr,
1942 &dev_attr_transport.attr,
1943 &dev_attr_subsysnqn.attr,
1944 &dev_attr_address.attr,
8432bdb2 1945 &dev_attr_state.attr,
779ff756
KB
1946 NULL
1947};
1948
1a353d85
ML
1949#define CHECK_ATTR(ctrl, a, name) \
1950 if ((a) == &dev_attr_##name.attr && \
1951 !(ctrl)->ops->get_##name) \
1952 return 0
1953
1954static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
1955 struct attribute *a, int n)
1956{
1957 struct device *dev = container_of(kobj, struct device, kobj);
1958 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1959
1960 if (a == &dev_attr_delete_controller.attr) {
1961 if (!ctrl->ops->delete_ctrl)
1962 return 0;
1963 }
1964
1965 CHECK_ATTR(ctrl, a, subsysnqn);
1966 CHECK_ATTR(ctrl, a, address);
1967
1968 return a->mode;
1969}
1970
779ff756 1971static struct attribute_group nvme_dev_attrs_group = {
1a353d85
ML
1972 .attrs = nvme_dev_attrs,
1973 .is_visible = nvme_dev_attrs_are_visible,
779ff756
KB
1974};
1975
1976static const struct attribute_group *nvme_dev_attr_groups[] = {
1977 &nvme_dev_attrs_group,
1978 NULL,
1979};
1980
5bae7f73
CH
1981static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1982{
1983 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1984 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1985
1986 return nsa->ns_id - nsb->ns_id;
1987}
1988
32f0c4af 1989static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
5bae7f73 1990{
32f0c4af 1991 struct nvme_ns *ns, *ret = NULL;
69d3b8ac 1992
32f0c4af 1993 mutex_lock(&ctrl->namespaces_mutex);
5bae7f73 1994 list_for_each_entry(ns, &ctrl->namespaces, list) {
32f0c4af
KB
1995 if (ns->ns_id == nsid) {
1996 kref_get(&ns->kref);
1997 ret = ns;
1998 break;
1999 }
5bae7f73
CH
2000 if (ns->ns_id > nsid)
2001 break;
2002 }
32f0c4af
KB
2003 mutex_unlock(&ctrl->namespaces_mutex);
2004 return ret;
5bae7f73
CH
2005}
2006
2007static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2008{
2009 struct nvme_ns *ns;
2010 struct gendisk *disk;
ac81bfa9
MB
2011 struct nvme_id_ns *id;
2012 char disk_name[DISK_NAME_LEN];
5bae7f73
CH
2013 int node = dev_to_node(ctrl->dev);
2014
2015 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2016 if (!ns)
2017 return;
2018
075790eb
KB
2019 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2020 if (ns->instance < 0)
2021 goto out_free_ns;
2022
5bae7f73
CH
2023 ns->queue = blk_mq_init_queue(ctrl->tagset);
2024 if (IS_ERR(ns->queue))
075790eb 2025 goto out_release_instance;
5bae7f73
CH
2026 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2027 ns->queue->queuedata = ns;
2028 ns->ctrl = ctrl;
2029
5bae7f73
CH
2030 kref_init(&ns->kref);
2031 ns->ns_id = nsid;
5bae7f73 2032 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
5bae7f73
CH
2033
2034 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
da35825d 2035 nvme_set_queue_limits(ctrl, ns->queue);
5bae7f73 2036
ac81bfa9 2037 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
5bae7f73 2038
ac81bfa9
MB
2039 if (nvme_revalidate_ns(ns, &id))
2040 goto out_free_queue;
2041
3dc87dd0
MB
2042 if (nvme_nvm_ns_supported(ns, id) &&
2043 nvme_nvm_register(ns, disk_name, node)) {
2044 dev_warn(ctrl->dev, "%s: LightNVM init failure\n", __func__);
2045 goto out_free_id;
2046 }
ac81bfa9 2047
3dc87dd0
MB
2048 disk = alloc_disk_node(0, node);
2049 if (!disk)
2050 goto out_free_id;
ac81bfa9 2051
3dc87dd0
MB
2052 disk->fops = &nvme_fops;
2053 disk->private_data = ns;
2054 disk->queue = ns->queue;
2055 disk->flags = GENHD_FL_EXT_DEVT;
2056 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2057 ns->disk = disk;
2058
2059 __nvme_revalidate_disk(disk, id);
5bae7f73 2060
32f0c4af
KB
2061 mutex_lock(&ctrl->namespaces_mutex);
2062 list_add_tail(&ns->list, &ctrl->namespaces);
2063 mutex_unlock(&ctrl->namespaces_mutex);
2064
5bae7f73 2065 kref_get(&ctrl->kref);
ac81bfa9
MB
2066
2067 kfree(id);
2068
0d52c756 2069 device_add_disk(ctrl->device, ns->disk);
2b9b6e86
KB
2070 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2071 &nvme_ns_attr_group))
2072 pr_warn("%s: failed to create sysfs group for identification\n",
2073 ns->disk->disk_name);
3dc87dd0
MB
2074 if (ns->ndev && nvme_nvm_register_sysfs(ns))
2075 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2076 ns->disk->disk_name);
5bae7f73 2077 return;
ac81bfa9
MB
2078 out_free_id:
2079 kfree(id);
5bae7f73
CH
2080 out_free_queue:
2081 blk_cleanup_queue(ns->queue);
075790eb
KB
2082 out_release_instance:
2083 ida_simple_remove(&ctrl->ns_ida, ns->instance);
5bae7f73
CH
2084 out_free_ns:
2085 kfree(ns);
2086}
2087
2088static void nvme_ns_remove(struct nvme_ns *ns)
2089{
646017a6
KB
2090 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2091 return;
69d3b8ac 2092
b0b4e09c 2093 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
5bae7f73
CH
2094 if (blk_get_integrity(ns->disk))
2095 blk_integrity_unregister(ns->disk);
2b9b6e86
KB
2096 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2097 &nvme_ns_attr_group);
3dc87dd0
MB
2098 if (ns->ndev)
2099 nvme_nvm_unregister_sysfs(ns);
5bae7f73 2100 del_gendisk(ns->disk);
5bae7f73
CH
2101 blk_mq_abort_requeue_list(ns->queue);
2102 blk_cleanup_queue(ns->queue);
2103 }
32f0c4af
KB
2104
2105 mutex_lock(&ns->ctrl->namespaces_mutex);
5bae7f73 2106 list_del_init(&ns->list);
32f0c4af
KB
2107 mutex_unlock(&ns->ctrl->namespaces_mutex);
2108
5bae7f73
CH
2109 nvme_put_ns(ns);
2110}
2111
540c801c
KB
2112static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2113{
2114 struct nvme_ns *ns;
2115
32f0c4af 2116 ns = nvme_find_get_ns(ctrl, nsid);
540c801c 2117 if (ns) {
b0b4e09c 2118 if (ns->disk && revalidate_disk(ns->disk))
540c801c 2119 nvme_ns_remove(ns);
32f0c4af 2120 nvme_put_ns(ns);
540c801c
KB
2121 } else
2122 nvme_alloc_ns(ctrl, nsid);
2123}
2124
47b0e50a
SB
2125static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2126 unsigned nsid)
2127{
2128 struct nvme_ns *ns, *next;
2129
2130 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2131 if (ns->ns_id > nsid)
2132 nvme_ns_remove(ns);
2133 }
2134}
2135
540c801c
KB
2136static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2137{
2138 struct nvme_ns *ns;
2139 __le32 *ns_list;
2140 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2141 int ret = 0;
2142
2143 ns_list = kzalloc(0x1000, GFP_KERNEL);
2144 if (!ns_list)
2145 return -ENOMEM;
2146
2147 for (i = 0; i < num_lists; i++) {
2148 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2149 if (ret)
47b0e50a 2150 goto free;
540c801c
KB
2151
2152 for (j = 0; j < min(nn, 1024U); j++) {
2153 nsid = le32_to_cpu(ns_list[j]);
2154 if (!nsid)
2155 goto out;
2156
2157 nvme_validate_ns(ctrl, nsid);
2158
2159 while (++prev < nsid) {
32f0c4af
KB
2160 ns = nvme_find_get_ns(ctrl, prev);
2161 if (ns) {
540c801c 2162 nvme_ns_remove(ns);
32f0c4af
KB
2163 nvme_put_ns(ns);
2164 }
540c801c
KB
2165 }
2166 }
2167 nn -= j;
2168 }
2169 out:
47b0e50a
SB
2170 nvme_remove_invalid_namespaces(ctrl, prev);
2171 free:
540c801c
KB
2172 kfree(ns_list);
2173 return ret;
2174}
2175
5955be21 2176static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
5bae7f73 2177{
5bae7f73
CH
2178 unsigned i;
2179
540c801c
KB
2180 for (i = 1; i <= nn; i++)
2181 nvme_validate_ns(ctrl, i);
2182
47b0e50a 2183 nvme_remove_invalid_namespaces(ctrl, nn);
5bae7f73
CH
2184}
2185
5955be21 2186static void nvme_scan_work(struct work_struct *work)
5bae7f73 2187{
5955be21
CH
2188 struct nvme_ctrl *ctrl =
2189 container_of(work, struct nvme_ctrl, scan_work);
5bae7f73 2190 struct nvme_id_ctrl *id;
540c801c 2191 unsigned nn;
5bae7f73 2192
5955be21
CH
2193 if (ctrl->state != NVME_CTRL_LIVE)
2194 return;
2195
5bae7f73
CH
2196 if (nvme_identify_ctrl(ctrl, &id))
2197 return;
540c801c
KB
2198
2199 nn = le32_to_cpu(id->nn);
8ef2074d 2200 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
540c801c
KB
2201 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2202 if (!nvme_scan_ns_list(ctrl, nn))
2203 goto done;
2204 }
5955be21 2205 nvme_scan_ns_sequential(ctrl, nn);
540c801c 2206 done:
32f0c4af 2207 mutex_lock(&ctrl->namespaces_mutex);
540c801c 2208 list_sort(NULL, &ctrl->namespaces, ns_cmp);
69d3b8ac 2209 mutex_unlock(&ctrl->namespaces_mutex);
5bae7f73
CH
2210 kfree(id);
2211}
5955be21
CH
2212
2213void nvme_queue_scan(struct nvme_ctrl *ctrl)
2214{
2215 /*
2216 * Do not queue new scan work when a controller is reset during
2217 * removal.
2218 */
2219 if (ctrl->state == NVME_CTRL_LIVE)
2220 schedule_work(&ctrl->scan_work);
2221}
2222EXPORT_SYMBOL_GPL(nvme_queue_scan);
5bae7f73 2223
32f0c4af
KB
2224/*
2225 * This function iterates the namespace list unlocked to allow recovery from
2226 * controller failure. It is up to the caller to ensure the namespace list is
2227 * not modified by scan work while this function is executing.
2228 */
5bae7f73
CH
2229void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2230{
2231 struct nvme_ns *ns, *next;
2232
0ff9d4e1
KB
2233 /*
2234 * The dead states indicates the controller was not gracefully
2235 * disconnected. In that case, we won't be able to flush any data while
2236 * removing the namespaces' disks; fail all the queues now to avoid
2237 * potentially having to clean up the failed sync later.
2238 */
2239 if (ctrl->state == NVME_CTRL_DEAD)
2240 nvme_kill_queues(ctrl);
2241
5bae7f73
CH
2242 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2243 nvme_ns_remove(ns);
2244}
576d55d6 2245EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
5bae7f73 2246
f866fc42
CH
2247static void nvme_async_event_work(struct work_struct *work)
2248{
2249 struct nvme_ctrl *ctrl =
2250 container_of(work, struct nvme_ctrl, async_event_work);
2251
2252 spin_lock_irq(&ctrl->lock);
2253 while (ctrl->event_limit > 0) {
2254 int aer_idx = --ctrl->event_limit;
2255
2256 spin_unlock_irq(&ctrl->lock);
2257 ctrl->ops->submit_async_event(ctrl, aer_idx);
2258 spin_lock_irq(&ctrl->lock);
2259 }
2260 spin_unlock_irq(&ctrl->lock);
2261}
2262
7bf58533
CH
2263void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2264 union nvme_result *res)
f866fc42 2265{
7bf58533
CH
2266 u32 result = le32_to_cpu(res->u32);
2267 bool done = true;
f866fc42 2268
7bf58533
CH
2269 switch (le16_to_cpu(status) >> 1) {
2270 case NVME_SC_SUCCESS:
2271 done = false;
2272 /*FALLTHRU*/
2273 case NVME_SC_ABORT_REQ:
f866fc42
CH
2274 ++ctrl->event_limit;
2275 schedule_work(&ctrl->async_event_work);
7bf58533
CH
2276 break;
2277 default:
2278 break;
f866fc42
CH
2279 }
2280
7bf58533 2281 if (done)
f866fc42
CH
2282 return;
2283
2284 switch (result & 0xff07) {
2285 case NVME_AER_NOTICE_NS_CHANGED:
2286 dev_info(ctrl->device, "rescanning\n");
2287 nvme_queue_scan(ctrl);
2288 break;
2289 default:
2290 dev_warn(ctrl->device, "async event result %08x\n", result);
2291 }
2292}
2293EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2294
2295void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2296{
2297 ctrl->event_limit = NVME_NR_AERS;
2298 schedule_work(&ctrl->async_event_work);
2299}
2300EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2301
f3ca80fc
CH
2302static DEFINE_IDA(nvme_instance_ida);
2303
2304static int nvme_set_instance(struct nvme_ctrl *ctrl)
2305{
2306 int instance, error;
2307
2308 do {
2309 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2310 return -ENODEV;
2311
2312 spin_lock(&dev_list_lock);
2313 error = ida_get_new(&nvme_instance_ida, &instance);
2314 spin_unlock(&dev_list_lock);
2315 } while (error == -EAGAIN);
2316
2317 if (error)
2318 return -ENODEV;
2319
2320 ctrl->instance = instance;
2321 return 0;
2322}
2323
2324static void nvme_release_instance(struct nvme_ctrl *ctrl)
2325{
2326 spin_lock(&dev_list_lock);
2327 ida_remove(&nvme_instance_ida, ctrl->instance);
2328 spin_unlock(&dev_list_lock);
2329}
2330
53029b04 2331void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
576d55d6 2332{
f866fc42 2333 flush_work(&ctrl->async_event_work);
5955be21
CH
2334 flush_work(&ctrl->scan_work);
2335 nvme_remove_namespaces(ctrl);
2336
53029b04 2337 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
f3ca80fc
CH
2338
2339 spin_lock(&dev_list_lock);
2340 list_del(&ctrl->node);
2341 spin_unlock(&dev_list_lock);
53029b04 2342}
576d55d6 2343EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
53029b04
KB
2344
2345static void nvme_free_ctrl(struct kref *kref)
2346{
2347 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
f3ca80fc
CH
2348
2349 put_device(ctrl->device);
2350 nvme_release_instance(ctrl);
075790eb 2351 ida_destroy(&ctrl->ns_ida);
f3ca80fc
CH
2352
2353 ctrl->ops->free_ctrl(ctrl);
2354}
2355
2356void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2357{
2358 kref_put(&ctrl->kref, nvme_free_ctrl);
2359}
576d55d6 2360EXPORT_SYMBOL_GPL(nvme_put_ctrl);
f3ca80fc
CH
2361
2362/*
2363 * Initialize a NVMe controller structures. This needs to be called during
2364 * earliest initialization so that we have the initialized structured around
2365 * during probing.
2366 */
2367int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2368 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2369{
2370 int ret;
2371
bb8d261e
CH
2372 ctrl->state = NVME_CTRL_NEW;
2373 spin_lock_init(&ctrl->lock);
f3ca80fc 2374 INIT_LIST_HEAD(&ctrl->namespaces);
69d3b8ac 2375 mutex_init(&ctrl->namespaces_mutex);
f3ca80fc
CH
2376 kref_init(&ctrl->kref);
2377 ctrl->dev = dev;
2378 ctrl->ops = ops;
2379 ctrl->quirks = quirks;
5955be21 2380 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
f866fc42 2381 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
f3ca80fc
CH
2382
2383 ret = nvme_set_instance(ctrl);
2384 if (ret)
2385 goto out;
2386
779ff756 2387 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
f3ca80fc 2388 MKDEV(nvme_char_major, ctrl->instance),
f4f0f63e 2389 ctrl, nvme_dev_attr_groups,
779ff756 2390 "nvme%d", ctrl->instance);
f3ca80fc
CH
2391 if (IS_ERR(ctrl->device)) {
2392 ret = PTR_ERR(ctrl->device);
2393 goto out_release_instance;
2394 }
2395 get_device(ctrl->device);
075790eb 2396 ida_init(&ctrl->ns_ida);
f3ca80fc 2397
f3ca80fc
CH
2398 spin_lock(&dev_list_lock);
2399 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2400 spin_unlock(&dev_list_lock);
2401
c5552fde
AL
2402 /*
2403 * Initialize latency tolerance controls. The sysfs files won't
2404 * be visible to userspace unless the device actually supports APST.
2405 */
2406 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2407 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2408 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2409
f3ca80fc 2410 return 0;
f3ca80fc
CH
2411out_release_instance:
2412 nvme_release_instance(ctrl);
2413out:
2414 return ret;
2415}
576d55d6 2416EXPORT_SYMBOL_GPL(nvme_init_ctrl);
f3ca80fc 2417
69d9a99c
KB
2418/**
2419 * nvme_kill_queues(): Ends all namespace queues
2420 * @ctrl: the dead controller that needs to end
2421 *
2422 * Call this function when the driver determines it is unable to get the
2423 * controller in a state capable of servicing IO.
2424 */
2425void nvme_kill_queues(struct nvme_ctrl *ctrl)
2426{
2427 struct nvme_ns *ns;
2428
32f0c4af
KB
2429 mutex_lock(&ctrl->namespaces_mutex);
2430 list_for_each_entry(ns, &ctrl->namespaces, list) {
69d9a99c
KB
2431 /*
2432 * Revalidating a dead namespace sets capacity to 0. This will
2433 * end buffered writers dirtying pages that can't be synced.
2434 */
f33447b9
KB
2435 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2436 continue;
2437 revalidate_disk(ns->disk);
69d9a99c
KB
2438 blk_set_queue_dying(ns->queue);
2439 blk_mq_abort_requeue_list(ns->queue);
806f026f
ML
2440
2441 /*
2442 * Forcibly start all queues to avoid having stuck requests.
2443 * Note that we must ensure the queues are not stopped
2444 * when the final removal happens.
2445 */
2446 blk_mq_start_hw_queues(ns->queue);
69d9a99c 2447 }
32f0c4af 2448 mutex_unlock(&ctrl->namespaces_mutex);
69d9a99c 2449}
237045fc 2450EXPORT_SYMBOL_GPL(nvme_kill_queues);
69d9a99c 2451
302ad8cc
KB
2452void nvme_unfreeze(struct nvme_ctrl *ctrl)
2453{
2454 struct nvme_ns *ns;
2455
2456 mutex_lock(&ctrl->namespaces_mutex);
2457 list_for_each_entry(ns, &ctrl->namespaces, list)
2458 blk_mq_unfreeze_queue(ns->queue);
2459 mutex_unlock(&ctrl->namespaces_mutex);
2460}
2461EXPORT_SYMBOL_GPL(nvme_unfreeze);
2462
2463void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2464{
2465 struct nvme_ns *ns;
2466
2467 mutex_lock(&ctrl->namespaces_mutex);
2468 list_for_each_entry(ns, &ctrl->namespaces, list) {
2469 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2470 if (timeout <= 0)
2471 break;
2472 }
2473 mutex_unlock(&ctrl->namespaces_mutex);
2474}
2475EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2476
2477void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2478{
2479 struct nvme_ns *ns;
2480
2481 mutex_lock(&ctrl->namespaces_mutex);
2482 list_for_each_entry(ns, &ctrl->namespaces, list)
2483 blk_mq_freeze_queue_wait(ns->queue);
2484 mutex_unlock(&ctrl->namespaces_mutex);
2485}
2486EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2487
2488void nvme_start_freeze(struct nvme_ctrl *ctrl)
2489{
2490 struct nvme_ns *ns;
2491
2492 mutex_lock(&ctrl->namespaces_mutex);
2493 list_for_each_entry(ns, &ctrl->namespaces, list)
1671d522 2494 blk_freeze_queue_start(ns->queue);
302ad8cc
KB
2495 mutex_unlock(&ctrl->namespaces_mutex);
2496}
2497EXPORT_SYMBOL_GPL(nvme_start_freeze);
2498
25646264 2499void nvme_stop_queues(struct nvme_ctrl *ctrl)
363c9aac
SG
2500{
2501 struct nvme_ns *ns;
2502
32f0c4af 2503 mutex_lock(&ctrl->namespaces_mutex);
a6eaa884 2504 list_for_each_entry(ns, &ctrl->namespaces, list)
3174dd33 2505 blk_mq_quiesce_queue(ns->queue);
32f0c4af 2506 mutex_unlock(&ctrl->namespaces_mutex);
363c9aac 2507}
576d55d6 2508EXPORT_SYMBOL_GPL(nvme_stop_queues);
363c9aac 2509
25646264 2510void nvme_start_queues(struct nvme_ctrl *ctrl)
363c9aac
SG
2511{
2512 struct nvme_ns *ns;
2513
32f0c4af
KB
2514 mutex_lock(&ctrl->namespaces_mutex);
2515 list_for_each_entry(ns, &ctrl->namespaces, list) {
363c9aac
SG
2516 blk_mq_start_stopped_hw_queues(ns->queue, true);
2517 blk_mq_kick_requeue_list(ns->queue);
2518 }
32f0c4af 2519 mutex_unlock(&ctrl->namespaces_mutex);
363c9aac 2520}
576d55d6 2521EXPORT_SYMBOL_GPL(nvme_start_queues);
363c9aac 2522
5bae7f73
CH
2523int __init nvme_core_init(void)
2524{
2525 int result;
2526
f3ca80fc
CH
2527 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2528 &nvme_dev_fops);
2529 if (result < 0)
b09dcf58 2530 return result;
f3ca80fc
CH
2531 else if (result > 0)
2532 nvme_char_major = result;
2533
2534 nvme_class = class_create(THIS_MODULE, "nvme");
2535 if (IS_ERR(nvme_class)) {
2536 result = PTR_ERR(nvme_class);
2537 goto unregister_chrdev;
2538 }
2539
5bae7f73 2540 return 0;
f3ca80fc
CH
2541
2542 unregister_chrdev:
2543 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
f3ca80fc 2544 return result;
5bae7f73
CH
2545}
2546
2547void nvme_core_exit(void)
2548{
f3ca80fc
CH
2549 class_destroy(nvme_class);
2550 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
5bae7f73 2551}
576d55d6
ML
2552
2553MODULE_LICENSE("GPL");
2554MODULE_VERSION("1.0");
2555module_init(nvme_core_init);
2556module_exit(nvme_core_exit);