]> git.proxmox.com Git - mirror_ubuntu-bionic-kernel.git/blame - drivers/nvme/host/core.c
nvme: send uevent for some asynchronous events
[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 30#include <asm/unaligned.h>
21d34711
CH
31
32#include "nvme.h"
038bd4cb 33#include "fabrics.h"
21d34711 34
f3ca80fc
CH
35#define NVME_MINORS (1U << MINORBITS)
36
8ae4e447
MO
37unsigned int admin_timeout = 60;
38module_param(admin_timeout, uint, 0644);
ba0ba7d3 39MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
576d55d6 40EXPORT_SYMBOL_GPL(admin_timeout);
ba0ba7d3 41
8ae4e447
MO
42unsigned int nvme_io_timeout = 30;
43module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
ba0ba7d3 44MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
576d55d6 45EXPORT_SYMBOL_GPL(nvme_io_timeout);
ba0ba7d3 46
b3b1b0b0 47static unsigned char shutdown_timeout = 5;
ba0ba7d3
ML
48module_param(shutdown_timeout, byte, 0644);
49MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
50
44e44b29
CH
51static u8 nvme_max_retries = 5;
52module_param_named(max_retries, nvme_max_retries, byte, 0644);
f80ec966 53MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
5bae7f73 54
9947d6a0 55static unsigned long default_ps_max_latency_us = 100000;
c5552fde
AL
56module_param(default_ps_max_latency_us, ulong, 0644);
57MODULE_PARM_DESC(default_ps_max_latency_us,
58 "max power saving latency for new devices; use PM QOS to change per device");
59
c35e30b4
AL
60static bool force_apst;
61module_param(force_apst, bool, 0644);
62MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
63
f5d11840
JA
64static bool streams;
65module_param(streams, bool, 0644);
66MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
67
9a6327d2
SG
68struct workqueue_struct *nvme_wq;
69EXPORT_SYMBOL_GPL(nvme_wq);
70
9843f685 71static DEFINE_IDA(nvme_instance_ida);
a6a5149b 72static dev_t nvme_chr_devt;
f3ca80fc
CH
73static struct class *nvme_class;
74
84fef62d
KB
75static void nvme_ns_remove(struct nvme_ns *ns);
76static int nvme_revalidate_disk(struct gendisk *disk);
77
b6dccf7f
AD
78static __le32 nvme_get_log_dw10(u8 lid, size_t size)
79{
80 return cpu_to_le32((((size / 4) - 1) << 16) | lid);
81}
82
d86c4d8e
CH
83int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
84{
85 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
86 return -EBUSY;
87 if (!queue_work(nvme_wq, &ctrl->reset_work))
88 return -EBUSY;
89 return 0;
90}
91EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
92
93static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
94{
95 int ret;
96
97 ret = nvme_reset_ctrl(ctrl);
98 if (!ret)
99 flush_work(&ctrl->reset_work);
100 return ret;
101}
102
c5017e85
CH
103static void nvme_delete_ctrl_work(struct work_struct *work)
104{
105 struct nvme_ctrl *ctrl =
106 container_of(work, struct nvme_ctrl, delete_work);
107
4054637c 108 flush_work(&ctrl->reset_work);
6cd53d14
CH
109 nvme_stop_ctrl(ctrl);
110 nvme_remove_namespaces(ctrl);
c5017e85 111 ctrl->ops->delete_ctrl(ctrl);
6cd53d14
CH
112 nvme_uninit_ctrl(ctrl);
113 nvme_put_ctrl(ctrl);
c5017e85
CH
114}
115
116int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
117{
118 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
119 return -EBUSY;
120 if (!queue_work(nvme_wq, &ctrl->delete_work))
121 return -EBUSY;
122 return 0;
123}
124EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
125
126int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
127{
128 int ret = 0;
129
130 /*
131 * Keep a reference until the work is flushed since ->delete_ctrl
132 * can free the controller.
133 */
134 nvme_get_ctrl(ctrl);
135 ret = nvme_delete_ctrl(ctrl);
136 if (!ret)
137 flush_work(&ctrl->delete_work);
138 nvme_put_ctrl(ctrl);
139 return ret;
140}
141EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
142
715ea9e0
CH
143static inline bool nvme_ns_has_pi(struct nvme_ns *ns)
144{
145 return ns->pi_type && ns->ms == sizeof(struct t10_pi_tuple);
146}
147
2a842aca 148static blk_status_t nvme_error_status(struct request *req)
27fa9bc5
CH
149{
150 switch (nvme_req(req)->status & 0x7ff) {
151 case NVME_SC_SUCCESS:
2a842aca 152 return BLK_STS_OK;
27fa9bc5 153 case NVME_SC_CAP_EXCEEDED:
2a842aca 154 return BLK_STS_NOSPC;
e02ab023 155 case NVME_SC_ONCS_NOT_SUPPORTED:
2a842aca 156 return BLK_STS_NOTSUPP;
e02ab023
JG
157 case NVME_SC_WRITE_FAULT:
158 case NVME_SC_READ_ERROR:
159 case NVME_SC_UNWRITTEN_BLOCK:
a751da33
CH
160 case NVME_SC_ACCESS_DENIED:
161 case NVME_SC_READ_ONLY:
2a842aca 162 return BLK_STS_MEDIUM;
a751da33
CH
163 case NVME_SC_GUARD_CHECK:
164 case NVME_SC_APPTAG_CHECK:
165 case NVME_SC_REFTAG_CHECK:
166 case NVME_SC_INVALID_PI:
167 return BLK_STS_PROTECTION;
168 case NVME_SC_RESERVATION_CONFLICT:
169 return BLK_STS_NEXUS;
2a842aca
CH
170 default:
171 return BLK_STS_IOERR;
27fa9bc5
CH
172 }
173}
27fa9bc5 174
f6324b1b 175static inline bool nvme_req_needs_retry(struct request *req)
77f02a7a 176{
f6324b1b
CH
177 if (blk_noretry_request(req))
178 return false;
27fa9bc5 179 if (nvme_req(req)->status & NVME_SC_DNR)
f6324b1b 180 return false;
44e44b29 181 if (nvme_req(req)->retries >= nvme_max_retries)
f6324b1b 182 return false;
e54b064c
CH
183 if (blk_queue_dying(req->q))
184 return false;
f6324b1b 185 return true;
77f02a7a
CH
186}
187
188void nvme_complete_rq(struct request *req)
189{
27fa9bc5
CH
190 if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
191 nvme_req(req)->retries++;
8d7b8faf 192 blk_mq_requeue_request(req, true);
27fa9bc5 193 return;
77f02a7a
CH
194 }
195
27fa9bc5 196 blk_mq_end_request(req, nvme_error_status(req));
77f02a7a
CH
197}
198EXPORT_SYMBOL_GPL(nvme_complete_rq);
199
c55a2fd4
ML
200void nvme_cancel_request(struct request *req, void *data, bool reserved)
201{
c55a2fd4
ML
202 if (!blk_mq_request_started(req))
203 return;
204
205 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
206 "Cancelling I/O %d", req->tag);
207
e54b064c 208 nvme_req(req)->status = NVME_SC_ABORT_REQ;
08e0029a 209 blk_mq_complete_request(req);
27fa9bc5 210
c55a2fd4
ML
211}
212EXPORT_SYMBOL_GPL(nvme_cancel_request);
213
bb8d261e
CH
214bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
215 enum nvme_ctrl_state new_state)
216{
f6b6a28e 217 enum nvme_ctrl_state old_state;
0a72bbba 218 unsigned long flags;
bb8d261e
CH
219 bool changed = false;
220
0a72bbba 221 spin_lock_irqsave(&ctrl->lock, flags);
f6b6a28e
GKB
222
223 old_state = ctrl->state;
bb8d261e
CH
224 switch (new_state) {
225 case NVME_CTRL_LIVE:
226 switch (old_state) {
7d2e8008 227 case NVME_CTRL_NEW:
bb8d261e 228 case NVME_CTRL_RESETTING:
def61eca 229 case NVME_CTRL_RECONNECTING:
bb8d261e
CH
230 changed = true;
231 /* FALLTHRU */
232 default:
233 break;
234 }
235 break;
236 case NVME_CTRL_RESETTING:
237 switch (old_state) {
238 case NVME_CTRL_NEW:
def61eca 239 case NVME_CTRL_LIVE:
def61eca
CH
240 changed = true;
241 /* FALLTHRU */
242 default:
243 break;
244 }
245 break;
246 case NVME_CTRL_RECONNECTING:
247 switch (old_state) {
bb8d261e 248 case NVME_CTRL_LIVE:
3cec7f9d 249 case NVME_CTRL_RESETTING:
bb8d261e
CH
250 changed = true;
251 /* FALLTHRU */
252 default:
253 break;
254 }
255 break;
256 case NVME_CTRL_DELETING:
257 switch (old_state) {
258 case NVME_CTRL_LIVE:
259 case NVME_CTRL_RESETTING:
def61eca 260 case NVME_CTRL_RECONNECTING:
bb8d261e
CH
261 changed = true;
262 /* FALLTHRU */
263 default:
264 break;
265 }
266 break;
0ff9d4e1
KB
267 case NVME_CTRL_DEAD:
268 switch (old_state) {
269 case NVME_CTRL_DELETING:
270 changed = true;
271 /* FALLTHRU */
272 default:
273 break;
274 }
275 break;
bb8d261e
CH
276 default:
277 break;
278 }
bb8d261e
CH
279
280 if (changed)
281 ctrl->state = new_state;
282
0a72bbba 283 spin_unlock_irqrestore(&ctrl->lock, flags);
f6b6a28e 284
bb8d261e
CH
285 return changed;
286}
287EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
288
1673f1f0
CH
289static void nvme_free_ns(struct kref *kref)
290{
291 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
292
b0b4e09c
MB
293 if (ns->ndev)
294 nvme_nvm_unregister(ns);
1673f1f0 295
1673f1f0 296 put_disk(ns->disk);
075790eb
KB
297 ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
298 nvme_put_ctrl(ns->ctrl);
1673f1f0
CH
299 kfree(ns);
300}
301
5bae7f73 302static void nvme_put_ns(struct nvme_ns *ns)
1673f1f0
CH
303{
304 kref_put(&ns->kref, nvme_free_ns);
305}
306
4160982e 307struct request *nvme_alloc_request(struct request_queue *q,
eb71f435 308 struct nvme_command *cmd, unsigned int flags, int qid)
21d34711 309{
aebf526b 310 unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
21d34711 311 struct request *req;
21d34711 312
eb71f435 313 if (qid == NVME_QID_ANY) {
aebf526b 314 req = blk_mq_alloc_request(q, op, flags);
eb71f435 315 } else {
aebf526b 316 req = blk_mq_alloc_request_hctx(q, op, flags,
eb71f435
CH
317 qid ? qid - 1 : 0);
318 }
21d34711 319 if (IS_ERR(req))
4160982e 320 return req;
21d34711 321
21d34711 322 req->cmd_flags |= REQ_FAILFAST_DRIVER;
d49187e9 323 nvme_req(req)->cmd = cmd;
21d34711 324
4160982e
CH
325 return req;
326}
576d55d6 327EXPORT_SYMBOL_GPL(nvme_alloc_request);
4160982e 328
f5d11840
JA
329static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
330{
331 struct nvme_command c;
332
333 memset(&c, 0, sizeof(c));
334
335 c.directive.opcode = nvme_admin_directive_send;
62346eae 336 c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
f5d11840
JA
337 c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
338 c.directive.dtype = NVME_DIR_IDENTIFY;
339 c.directive.tdtype = NVME_DIR_STREAMS;
340 c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
341
342 return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
343}
344
345static int nvme_disable_streams(struct nvme_ctrl *ctrl)
346{
347 return nvme_toggle_streams(ctrl, false);
348}
349
350static int nvme_enable_streams(struct nvme_ctrl *ctrl)
351{
352 return nvme_toggle_streams(ctrl, true);
353}
354
355static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
356 struct streams_directive_params *s, u32 nsid)
357{
358 struct nvme_command c;
359
360 memset(&c, 0, sizeof(c));
361 memset(s, 0, sizeof(*s));
362
363 c.directive.opcode = nvme_admin_directive_recv;
364 c.directive.nsid = cpu_to_le32(nsid);
a082b426 365 c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
f5d11840
JA
366 c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
367 c.directive.dtype = NVME_DIR_STREAMS;
368
369 return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
370}
371
372static int nvme_configure_directives(struct nvme_ctrl *ctrl)
373{
374 struct streams_directive_params s;
375 int ret;
376
377 if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
378 return 0;
379 if (!streams)
380 return 0;
381
382 ret = nvme_enable_streams(ctrl);
383 if (ret)
384 return ret;
385
62346eae 386 ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
f5d11840
JA
387 if (ret)
388 return ret;
389
390 ctrl->nssa = le16_to_cpu(s.nssa);
391 if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
392 dev_info(ctrl->device, "too few streams (%u) available\n",
393 ctrl->nssa);
394 nvme_disable_streams(ctrl);
395 return 0;
396 }
397
398 ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
399 dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
400 return 0;
401}
402
403/*
404 * Check if 'req' has a write hint associated with it. If it does, assign
405 * a valid namespace stream to the write.
406 */
407static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
408 struct request *req, u16 *control,
409 u32 *dsmgmt)
410{
411 enum rw_hint streamid = req->write_hint;
412
413 if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
414 streamid = 0;
415 else {
416 streamid--;
417 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
418 return;
419
420 *control |= NVME_RW_DTYPE_STREAMS;
421 *dsmgmt |= streamid << 16;
422 }
423
424 if (streamid < ARRAY_SIZE(req->q->write_hints))
425 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
426}
427
8093f7ca
ML
428static inline void nvme_setup_flush(struct nvme_ns *ns,
429 struct nvme_command *cmnd)
430{
431 memset(cmnd, 0, sizeof(*cmnd));
432 cmnd->common.opcode = nvme_cmd_flush;
433 cmnd->common.nsid = cpu_to_le32(ns->ns_id);
434}
435
fc17b653 436static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
8093f7ca
ML
437 struct nvme_command *cmnd)
438{
b35ba01e 439 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
8093f7ca 440 struct nvme_dsm_range *range;
b35ba01e 441 struct bio *bio;
8093f7ca 442
b35ba01e 443 range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
8093f7ca 444 if (!range)
fc17b653 445 return BLK_STS_RESOURCE;
8093f7ca 446
b35ba01e
CH
447 __rq_for_each_bio(bio, req) {
448 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
449 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
450
451 range[n].cattr = cpu_to_le32(0);
452 range[n].nlb = cpu_to_le32(nlb);
453 range[n].slba = cpu_to_le64(slba);
454 n++;
455 }
456
457 if (WARN_ON_ONCE(n != segments)) {
458 kfree(range);
fc17b653 459 return BLK_STS_IOERR;
b35ba01e 460 }
8093f7ca
ML
461
462 memset(cmnd, 0, sizeof(*cmnd));
463 cmnd->dsm.opcode = nvme_cmd_dsm;
464 cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
f1dd03a8 465 cmnd->dsm.nr = cpu_to_le32(segments - 1);
8093f7ca
ML
466 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
467
f9d03f96
CH
468 req->special_vec.bv_page = virt_to_page(range);
469 req->special_vec.bv_offset = offset_in_page(range);
b35ba01e 470 req->special_vec.bv_len = sizeof(*range) * segments;
f9d03f96 471 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
8093f7ca 472
fc17b653 473 return BLK_STS_OK;
8093f7ca 474}
8093f7ca 475
ebe6d874
CH
476static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
477 struct request *req, struct nvme_command *cmnd)
8093f7ca 478{
f5d11840 479 struct nvme_ctrl *ctrl = ns->ctrl;
8093f7ca
ML
480 u16 control = 0;
481 u32 dsmgmt = 0;
482
483 if (req->cmd_flags & REQ_FUA)
484 control |= NVME_RW_FUA;
485 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
486 control |= NVME_RW_LR;
487
488 if (req->cmd_flags & REQ_RAHEAD)
489 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
490
491 memset(cmnd, 0, sizeof(*cmnd));
492 cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
8093f7ca
ML
493 cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
494 cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
495 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
496
f5d11840
JA
497 if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
498 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
499
8093f7ca 500 if (ns->ms) {
715ea9e0
CH
501 /*
502 * If formated with metadata, the block layer always provides a
503 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
504 * we enable the PRACT bit for protection information or set the
505 * namespace capacity to zero to prevent any I/O.
506 */
507 if (!blk_integrity_rq(req)) {
508 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
509 return BLK_STS_NOTSUPP;
510 control |= NVME_RW_PRINFO_PRACT;
511 }
512
8093f7ca
ML
513 switch (ns->pi_type) {
514 case NVME_NS_DPS_PI_TYPE3:
515 control |= NVME_RW_PRINFO_PRCHK_GUARD;
516 break;
517 case NVME_NS_DPS_PI_TYPE1:
518 case NVME_NS_DPS_PI_TYPE2:
519 control |= NVME_RW_PRINFO_PRCHK_GUARD |
520 NVME_RW_PRINFO_PRCHK_REF;
521 cmnd->rw.reftag = cpu_to_le32(
522 nvme_block_nr(ns, blk_rq_pos(req)));
523 break;
524 }
8093f7ca
ML
525 }
526
527 cmnd->rw.control = cpu_to_le16(control);
528 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
ebe6d874 529 return 0;
8093f7ca
ML
530}
531
fc17b653 532blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
8093f7ca
ML
533 struct nvme_command *cmd)
534{
fc17b653 535 blk_status_t ret = BLK_STS_OK;
8093f7ca 536
987f699a 537 if (!(req->rq_flags & RQF_DONTPREP)) {
44e44b29 538 nvme_req(req)->retries = 0;
27fa9bc5 539 nvme_req(req)->flags = 0;
987f699a
CH
540 req->rq_flags |= RQF_DONTPREP;
541 }
542
aebf526b
CH
543 switch (req_op(req)) {
544 case REQ_OP_DRV_IN:
545 case REQ_OP_DRV_OUT:
d49187e9 546 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
aebf526b
CH
547 break;
548 case REQ_OP_FLUSH:
8093f7ca 549 nvme_setup_flush(ns, cmd);
aebf526b 550 break;
e850fd16
CH
551 case REQ_OP_WRITE_ZEROES:
552 /* currently only aliased to deallocate for a few ctrls: */
aebf526b 553 case REQ_OP_DISCARD:
8093f7ca 554 ret = nvme_setup_discard(ns, req, cmd);
aebf526b
CH
555 break;
556 case REQ_OP_READ:
557 case REQ_OP_WRITE:
ebe6d874 558 ret = nvme_setup_rw(ns, req, cmd);
aebf526b
CH
559 break;
560 default:
561 WARN_ON_ONCE(1);
fc17b653 562 return BLK_STS_IOERR;
aebf526b 563 }
8093f7ca 564
721b3917 565 cmd->common.command_id = req->tag;
8093f7ca
ML
566 return ret;
567}
568EXPORT_SYMBOL_GPL(nvme_setup_cmd);
569
4160982e
CH
570/*
571 * Returns 0 on success. If the result is negative, it's a Linux error code;
572 * if the result is positive, it's an NVM Express status code
573 */
574int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
d49187e9 575 union nvme_result *result, void *buffer, unsigned bufflen,
eb71f435 576 unsigned timeout, int qid, int at_head, int flags)
4160982e
CH
577{
578 struct request *req;
579 int ret;
580
eb71f435 581 req = nvme_alloc_request(q, cmd, flags, qid);
4160982e
CH
582 if (IS_ERR(req))
583 return PTR_ERR(req);
584
585 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
586
21d34711
CH
587 if (buffer && bufflen) {
588 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
589 if (ret)
590 goto out;
4160982e
CH
591 }
592
eb71f435 593 blk_execute_rq(req->q, NULL, req, at_head);
d49187e9
CH
594 if (result)
595 *result = nvme_req(req)->result;
27fa9bc5
CH
596 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
597 ret = -EINTR;
598 else
599 ret = nvme_req(req)->status;
4160982e
CH
600 out:
601 blk_mq_free_request(req);
602 return ret;
603}
eb71f435 604EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
4160982e
CH
605
606int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
607 void *buffer, unsigned bufflen)
608{
eb71f435
CH
609 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
610 NVME_QID_ANY, 0, 0);
4160982e 611}
576d55d6 612EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
4160982e 613
1cad6562
CH
614static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
615 unsigned len, u32 seed, bool write)
616{
617 struct bio_integrity_payload *bip;
618 int ret = -ENOMEM;
619 void *buf;
620
621 buf = kmalloc(len, GFP_KERNEL);
622 if (!buf)
623 goto out;
624
625 ret = -EFAULT;
626 if (write && copy_from_user(buf, ubuf, len))
627 goto out_free_meta;
628
629 bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
630 if (IS_ERR(bip)) {
631 ret = PTR_ERR(bip);
632 goto out_free_meta;
633 }
634
635 bip->bip_iter.bi_size = len;
636 bip->bip_iter.bi_sector = seed;
637 ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
638 offset_in_page(buf));
639 if (ret == len)
640 return buf;
641 ret = -ENOMEM;
642out_free_meta:
643 kfree(buf);
644out:
645 return ERR_PTR(ret);
646}
647
63263d60 648static int nvme_submit_user_cmd(struct request_queue *q,
485783ca
KB
649 struct nvme_command *cmd, void __user *ubuffer,
650 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
651 u32 meta_seed, u32 *result, unsigned timeout)
4160982e 652{
7a5abb4b 653 bool write = nvme_is_write(cmd);
0b7f1f26
KB
654 struct nvme_ns *ns = q->queuedata;
655 struct gendisk *disk = ns ? ns->disk : NULL;
4160982e 656 struct request *req;
0b7f1f26
KB
657 struct bio *bio = NULL;
658 void *meta = NULL;
4160982e
CH
659 int ret;
660
eb71f435 661 req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
4160982e
CH
662 if (IS_ERR(req))
663 return PTR_ERR(req);
664
665 req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
666
667 if (ubuffer && bufflen) {
21d34711
CH
668 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
669 GFP_KERNEL);
670 if (ret)
671 goto out;
672 bio = req->bio;
74d46992 673 bio->bi_disk = disk;
1cad6562
CH
674 if (disk && meta_buffer && meta_len) {
675 meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
676 meta_seed, write);
677 if (IS_ERR(meta)) {
678 ret = PTR_ERR(meta);
0b7f1f26
KB
679 goto out_unmap;
680 }
0b7f1f26
KB
681 }
682 }
1cad6562 683
0b7f1f26 684 blk_execute_rq(req->q, disk, req, 0);
27fa9bc5
CH
685 if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
686 ret = -EINTR;
687 else
688 ret = nvme_req(req)->status;
21d34711 689 if (result)
d49187e9 690 *result = le32_to_cpu(nvme_req(req)->result.u32);
0b7f1f26
KB
691 if (meta && !ret && !write) {
692 if (copy_to_user(meta_buffer, meta, meta_len))
693 ret = -EFAULT;
694 }
0b7f1f26
KB
695 kfree(meta);
696 out_unmap:
74d46992 697 if (bio)
0b7f1f26 698 blk_rq_unmap_user(bio);
21d34711
CH
699 out:
700 blk_mq_free_request(req);
701 return ret;
702}
703
2a842aca 704static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
038bd4cb
SG
705{
706 struct nvme_ctrl *ctrl = rq->end_io_data;
707
708 blk_mq_free_request(rq);
709
2a842aca 710 if (status) {
038bd4cb 711 dev_err(ctrl->device,
2a842aca
CH
712 "failed nvme_keep_alive_end_io error=%d\n",
713 status);
038bd4cb
SG
714 return;
715 }
716
717 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
718}
719
720static int nvme_keep_alive(struct nvme_ctrl *ctrl)
721{
722 struct nvme_command c;
723 struct request *rq;
724
725 memset(&c, 0, sizeof(c));
726 c.common.opcode = nvme_admin_keep_alive;
727
728 rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
729 NVME_QID_ANY);
730 if (IS_ERR(rq))
731 return PTR_ERR(rq);
732
733 rq->timeout = ctrl->kato * HZ;
734 rq->end_io_data = ctrl;
735
736 blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
737
738 return 0;
739}
740
741static void nvme_keep_alive_work(struct work_struct *work)
742{
743 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
744 struct nvme_ctrl, ka_work);
745
746 if (nvme_keep_alive(ctrl)) {
747 /* allocation failure, reset the controller */
748 dev_err(ctrl->device, "keep-alive failed\n");
39bdc590 749 nvme_reset_ctrl(ctrl);
038bd4cb
SG
750 return;
751 }
752}
753
754void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
755{
756 if (unlikely(ctrl->kato == 0))
757 return;
758
759 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
760 schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
761}
762EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
763
764void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
765{
766 if (unlikely(ctrl->kato == 0))
767 return;
768
769 cancel_delayed_work_sync(&ctrl->ka_work);
770}
771EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
772
3f7f25a9 773static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
21d34711
CH
774{
775 struct nvme_command c = { };
776 int error;
777
778 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
779 c.identify.opcode = nvme_admin_identify;
986994a2 780 c.identify.cns = NVME_ID_CNS_CTRL;
21d34711
CH
781
782 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
783 if (!*id)
784 return -ENOMEM;
785
786 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
787 sizeof(struct nvme_id_ctrl));
788 if (error)
789 kfree(*id);
790 return error;
791}
792
cdbff4f2
CH
793static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
794 u8 *eui64, u8 *nguid, uuid_t *uuid)
3b22ba26
JT
795{
796 struct nvme_command c = { };
797 int status;
798 void *data;
799 int pos;
800 int len;
801
802 c.identify.opcode = nvme_admin_identify;
803 c.identify.nsid = cpu_to_le32(nsid);
804 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
805
806 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
807 if (!data)
808 return -ENOMEM;
809
cdbff4f2 810 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
3b22ba26
JT
811 NVME_IDENTIFY_DATA_SIZE);
812 if (status)
813 goto free_data;
814
815 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
816 struct nvme_ns_id_desc *cur = data + pos;
817
818 if (cur->nidl == 0)
819 break;
820
821 switch (cur->nidt) {
822 case NVME_NIDT_EUI64:
823 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
cdbff4f2 824 dev_warn(ctrl->device,
3b22ba26
JT
825 "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
826 cur->nidl);
827 goto free_data;
828 }
829 len = NVME_NIDT_EUI64_LEN;
cdbff4f2 830 memcpy(eui64, data + pos + sizeof(*cur), len);
3b22ba26
JT
831 break;
832 case NVME_NIDT_NGUID:
833 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
cdbff4f2 834 dev_warn(ctrl->device,
3b22ba26
JT
835 "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
836 cur->nidl);
837 goto free_data;
838 }
839 len = NVME_NIDT_NGUID_LEN;
cdbff4f2 840 memcpy(nguid, data + pos + sizeof(*cur), len);
3b22ba26
JT
841 break;
842 case NVME_NIDT_UUID:
843 if (cur->nidl != NVME_NIDT_UUID_LEN) {
cdbff4f2 844 dev_warn(ctrl->device,
3b22ba26
JT
845 "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
846 cur->nidl);
847 goto free_data;
848 }
849 len = NVME_NIDT_UUID_LEN;
cdbff4f2 850 uuid_copy(uuid, data + pos + sizeof(*cur));
3b22ba26
JT
851 break;
852 default:
853 /* Skip unnkown types */
854 len = cur->nidl;
855 break;
856 }
857
858 len += sizeof(*cur);
859 }
860free_data:
861 kfree(data);
862 return status;
863}
864
540c801c
KB
865static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
866{
867 struct nvme_command c = { };
868
869 c.identify.opcode = nvme_admin_identify;
986994a2 870 c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
540c801c
KB
871 c.identify.nsid = cpu_to_le32(nsid);
872 return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
873}
874
cdbff4f2
CH
875static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
876 unsigned nsid)
21d34711 877{
cdbff4f2 878 struct nvme_id_ns *id;
21d34711
CH
879 struct nvme_command c = { };
880 int error;
881
882 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
778f067c
MG
883 c.identify.opcode = nvme_admin_identify;
884 c.identify.nsid = cpu_to_le32(nsid);
986994a2 885 c.identify.cns = NVME_ID_CNS_NS;
21d34711 886
cdbff4f2
CH
887 id = kmalloc(sizeof(*id), GFP_KERNEL);
888 if (!id)
889 return NULL;
21d34711 890
cdbff4f2
CH
891 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
892 if (error) {
893 dev_warn(ctrl->device, "Identify namespace failed\n");
894 kfree(id);
895 return NULL;
896 }
897
898 return id;
21d34711
CH
899}
900
3f7f25a9 901static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
1a6fe74d 902 void *buffer, size_t buflen, u32 *result)
21d34711
CH
903{
904 struct nvme_command c;
d49187e9 905 union nvme_result res;
1cb3cce5 906 int ret;
21d34711
CH
907
908 memset(&c, 0, sizeof(c));
909 c.features.opcode = nvme_admin_set_features;
21d34711
CH
910 c.features.fid = cpu_to_le32(fid);
911 c.features.dword11 = cpu_to_le32(dword11);
912
d49187e9 913 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1a6fe74d 914 buffer, buflen, 0, NVME_QID_ANY, 0, 0);
9b47f77a 915 if (ret >= 0 && result)
d49187e9 916 *result = le32_to_cpu(res.u32);
1cb3cce5 917 return ret;
21d34711
CH
918}
919
9a0be7ab
CH
920int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
921{
922 u32 q_count = (*count - 1) | ((*count - 1) << 16);
923 u32 result;
924 int status, nr_io_queues;
925
1a6fe74d 926 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
9a0be7ab 927 &result);
f5fa90dc 928 if (status < 0)
9a0be7ab
CH
929 return status;
930
f5fa90dc
CH
931 /*
932 * Degraded controllers might return an error when setting the queue
933 * count. We still want to be able to bring them online and offer
934 * access to the admin queue, as that might be only way to fix them up.
935 */
936 if (status > 0) {
f0425db0 937 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
f5fa90dc
CH
938 *count = 0;
939 } else {
940 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
941 *count = min(*count, nr_io_queues);
942 }
943
9a0be7ab
CH
944 return 0;
945}
576d55d6 946EXPORT_SYMBOL_GPL(nvme_set_queue_count);
9a0be7ab 947
1673f1f0
CH
948static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
949{
950 struct nvme_user_io io;
951 struct nvme_command c;
952 unsigned length, meta_len;
953 void __user *metadata;
954
955 if (copy_from_user(&io, uio, sizeof(io)))
956 return -EFAULT;
63088ec7
KB
957 if (io.flags)
958 return -EINVAL;
1673f1f0
CH
959
960 switch (io.opcode) {
961 case nvme_cmd_write:
962 case nvme_cmd_read:
963 case nvme_cmd_compare:
964 break;
965 default:
966 return -EINVAL;
967 }
968
969 length = (io.nblocks + 1) << ns->lba_shift;
970 meta_len = (io.nblocks + 1) * ns->ms;
971 metadata = (void __user *)(uintptr_t)io.metadata;
972
973 if (ns->ext) {
974 length += meta_len;
975 meta_len = 0;
976 } else if (meta_len) {
977 if ((io.metadata & 3) || !io.metadata)
978 return -EINVAL;
979 }
980
981 memset(&c, 0, sizeof(c));
982 c.rw.opcode = io.opcode;
983 c.rw.flags = io.flags;
984 c.rw.nsid = cpu_to_le32(ns->ns_id);
985 c.rw.slba = cpu_to_le64(io.slba);
986 c.rw.length = cpu_to_le16(io.nblocks);
987 c.rw.control = cpu_to_le16(io.control);
988 c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
989 c.rw.reftag = cpu_to_le32(io.reftag);
990 c.rw.apptag = cpu_to_le16(io.apptag);
991 c.rw.appmask = cpu_to_le16(io.appmask);
992
63263d60 993 return nvme_submit_user_cmd(ns->queue, &c,
1673f1f0
CH
994 (void __user *)(uintptr_t)io.addr, length,
995 metadata, meta_len, io.slba, NULL, 0);
996}
997
84fef62d
KB
998static u32 nvme_known_admin_effects(u8 opcode)
999{
1000 switch (opcode) {
1001 case nvme_admin_format_nvm:
1002 return NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC |
1003 NVME_CMD_EFFECTS_CSE_MASK;
1004 case nvme_admin_sanitize_nvm:
1005 return NVME_CMD_EFFECTS_CSE_MASK;
1006 default:
1007 break;
1008 }
1009 return 0;
1010}
1011
1012static u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1013 u8 opcode)
1014{
1015 u32 effects = 0;
1016
1017 if (ns) {
1018 if (ctrl->effects)
1019 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1020 if (effects & ~NVME_CMD_EFFECTS_CSUPP)
1021 dev_warn(ctrl->device,
1022 "IO command:%02x has unhandled effects:%08x\n",
1023 opcode, effects);
1024 return 0;
1025 }
1026
1027 if (ctrl->effects)
1028 effects = le32_to_cpu(ctrl->effects->iocs[opcode]);
1029 else
1030 effects = nvme_known_admin_effects(opcode);
1031
1032 /*
1033 * For simplicity, IO to all namespaces is quiesced even if the command
1034 * effects say only one namespace is affected.
1035 */
1036 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK)) {
1037 nvme_start_freeze(ctrl);
1038 nvme_wait_freeze(ctrl);
1039 }
1040 return effects;
1041}
1042
1043static void nvme_update_formats(struct nvme_ctrl *ctrl)
1044{
1045 struct nvme_ns *ns;
1046
1047 mutex_lock(&ctrl->namespaces_mutex);
1048 list_for_each_entry(ns, &ctrl->namespaces, list) {
1049 if (ns->disk && nvme_revalidate_disk(ns->disk))
1050 nvme_ns_remove(ns);
1051 }
1052 mutex_unlock(&ctrl->namespaces_mutex);
1053}
1054
1055static void nvme_passthru_end(struct nvme_ctrl *ctrl, u32 effects)
1056{
1057 /*
1058 * Revalidate LBA changes prior to unfreezing. This is necessary to
1059 * prevent memory corruption if a logical block size was changed by
1060 * this command.
1061 */
1062 if (effects & NVME_CMD_EFFECTS_LBCC)
1063 nvme_update_formats(ctrl);
1064 if (effects & (NVME_CMD_EFFECTS_LBCC | NVME_CMD_EFFECTS_CSE_MASK))
1065 nvme_unfreeze(ctrl);
1066 if (effects & NVME_CMD_EFFECTS_CCC)
1067 nvme_init_identify(ctrl);
1068 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC))
1069 nvme_queue_scan(ctrl);
1070}
1071
f3ca80fc 1072static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
1673f1f0
CH
1073 struct nvme_passthru_cmd __user *ucmd)
1074{
1075 struct nvme_passthru_cmd cmd;
1076 struct nvme_command c;
1077 unsigned timeout = 0;
84fef62d 1078 u32 effects;
1673f1f0
CH
1079 int status;
1080
1081 if (!capable(CAP_SYS_ADMIN))
1082 return -EACCES;
1083 if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1084 return -EFAULT;
63088ec7
KB
1085 if (cmd.flags)
1086 return -EINVAL;
1673f1f0
CH
1087
1088 memset(&c, 0, sizeof(c));
1089 c.common.opcode = cmd.opcode;
1090 c.common.flags = cmd.flags;
1091 c.common.nsid = cpu_to_le32(cmd.nsid);
1092 c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1093 c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1094 c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1095 c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1096 c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1097 c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1098 c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1099 c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1100
1101 if (cmd.timeout_ms)
1102 timeout = msecs_to_jiffies(cmd.timeout_ms);
1103
84fef62d 1104 effects = nvme_passthru_start(ctrl, ns, cmd.opcode);
1673f1f0 1105 status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
d1ea7be5 1106 (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
63263d60
KB
1107 (void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1108 0, &cmd.result, timeout);
84fef62d
KB
1109 nvme_passthru_end(ctrl, effects);
1110
1673f1f0
CH
1111 if (status >= 0) {
1112 if (put_user(cmd.result, &ucmd->result))
1113 return -EFAULT;
1114 }
1115
1116 return status;
1117}
1118
1119static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1120 unsigned int cmd, unsigned long arg)
1121{
1122 struct nvme_ns *ns = bdev->bd_disk->private_data;
1123
1124 switch (cmd) {
1125 case NVME_IOCTL_ID:
1126 force_successful_syscall_return();
1127 return ns->ns_id;
1128 case NVME_IOCTL_ADMIN_CMD:
1129 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1130 case NVME_IOCTL_IO_CMD:
1131 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1132 case NVME_IOCTL_SUBMIT_IO:
1133 return nvme_submit_io(ns, (void __user *)arg);
1673f1f0 1134 default:
84d4add7
MB
1135#ifdef CONFIG_NVM
1136 if (ns->ndev)
1137 return nvme_nvm_ioctl(ns, cmd, arg);
1138#endif
a98e58e5 1139 if (is_sed_ioctl(cmd))
4f1244c8 1140 return sed_ioctl(ns->ctrl->opal_dev, cmd,
e225c20e 1141 (void __user *) arg);
1673f1f0
CH
1142 return -ENOTTY;
1143 }
1144}
1145
1673f1f0
CH
1146static int nvme_open(struct block_device *bdev, fmode_t mode)
1147{
c6424a90
CH
1148 struct nvme_ns *ns = bdev->bd_disk->private_data;
1149
1150 if (!kref_get_unless_zero(&ns->kref))
1151 return -ENXIO;
c6424a90 1152 return 0;
1673f1f0
CH
1153}
1154
1155static void nvme_release(struct gendisk *disk, fmode_t mode)
1156{
a6a5149b 1157 nvme_put_ns(disk->private_data);
1673f1f0
CH
1158}
1159
1160static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1161{
1162 /* some standard values */
1163 geo->heads = 1 << 6;
1164 geo->sectors = 1 << 5;
1165 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1166 return 0;
1167}
1168
1169#ifdef CONFIG_BLK_DEV_INTEGRITY
39b7baa4 1170static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1673f1f0
CH
1171{
1172 struct blk_integrity integrity;
1173
fa9a89fc 1174 memset(&integrity, 0, sizeof(integrity));
39b7baa4 1175 switch (pi_type) {
1673f1f0
CH
1176 case NVME_NS_DPS_PI_TYPE3:
1177 integrity.profile = &t10_pi_type3_crc;
ba36c21b
NB
1178 integrity.tag_size = sizeof(u16) + sizeof(u32);
1179 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1673f1f0
CH
1180 break;
1181 case NVME_NS_DPS_PI_TYPE1:
1182 case NVME_NS_DPS_PI_TYPE2:
1183 integrity.profile = &t10_pi_type1_crc;
ba36c21b
NB
1184 integrity.tag_size = sizeof(u16);
1185 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1673f1f0
CH
1186 break;
1187 default:
1188 integrity.profile = NULL;
1189 break;
1190 }
39b7baa4
CH
1191 integrity.tuple_size = ms;
1192 blk_integrity_register(disk, &integrity);
1193 blk_queue_max_integrity_segments(disk->queue, 1);
1673f1f0
CH
1194}
1195#else
39b7baa4 1196static void nvme_init_integrity(struct gendisk *disk, u16 ms, u8 pi_type)
1673f1f0
CH
1197{
1198}
1199#endif /* CONFIG_BLK_DEV_INTEGRITY */
1200
6b8190d6
SB
1201static void nvme_set_chunk_size(struct nvme_ns *ns)
1202{
1203 u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1204 blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1205}
1206
30e5e929
CH
1207static void nvme_config_discard(struct nvme_ctrl *ctrl,
1208 unsigned stream_alignment, struct request_queue *queue)
1673f1f0 1209{
30e5e929
CH
1210 u32 size = queue_logical_block_size(queue);
1211
1212 if (stream_alignment)
1213 size *= stream_alignment;
08095e70 1214
b35ba01e
CH
1215 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1216 NVME_DSM_MAX_RANGES);
1217
30e5e929
CH
1218 queue->limits.discard_alignment = size;
1219 queue->limits.discard_granularity = size;
f5d11840 1220
30e5e929
CH
1221 blk_queue_max_discard_sectors(queue, UINT_MAX);
1222 blk_queue_max_discard_segments(queue, NVME_DSM_MAX_RANGES);
1223 queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, queue);
e850fd16
CH
1224
1225 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
30e5e929 1226 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1673f1f0
CH
1227}
1228
cdbff4f2
CH
1229static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1230 struct nvme_id_ns *id, u8 *eui64, u8 *nguid, uuid_t *uuid)
1673f1f0 1231{
cdbff4f2
CH
1232 if (ctrl->vs >= NVME_VS(1, 1, 0))
1233 memcpy(eui64, id->eui64, sizeof(id->eui64));
1234 if (ctrl->vs >= NVME_VS(1, 2, 0))
1235 memcpy(nguid, id->nguid, sizeof(id->nguid));
1236 if (ctrl->vs >= NVME_VS(1, 3, 0)) {
3b22ba26
JT
1237 /* Don't treat error as fatal we potentially
1238 * already have a NGUID or EUI-64
1239 */
cdbff4f2
CH
1240 if (nvme_identify_ns_descs(ctrl, nsid, eui64, nguid, uuid))
1241 dev_warn(ctrl->device,
3b22ba26
JT
1242 "%s: Identify Descriptors failed\n", __func__);
1243 }
ac81bfa9
MB
1244}
1245
24b0b58c
CH
1246static void nvme_update_disk_info(struct gendisk *disk,
1247 struct nvme_ns *ns, struct nvme_id_ns *id)
1248{
1249 sector_t capacity = le64_to_cpup(&id->nsze) << (ns->lba_shift - 9);
1250 unsigned stream_alignment = 0;
1251
1252 if (ns->ctrl->nr_streams && ns->sws && ns->sgs)
1253 stream_alignment = ns->sws * ns->sgs;
1254
1255 blk_mq_freeze_queue(disk->queue);
1256 blk_integrity_unregister(disk);
1257
1258 blk_queue_logical_block_size(disk->queue, 1 << ns->lba_shift);
1259 if (ns->ms && !ns->ext &&
1260 (ns->ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1261 nvme_init_integrity(disk, ns->ms, ns->pi_type);
715ea9e0 1262 if (ns->ms && !nvme_ns_has_pi(ns) && !blk_get_integrity(disk))
24b0b58c
CH
1263 capacity = 0;
1264 set_capacity(disk, capacity);
1265
1266 if (ns->ctrl->oncs & NVME_CTRL_ONCS_DSM)
1267 nvme_config_discard(ns->ctrl, stream_alignment, disk->queue);
1268 blk_mq_unfreeze_queue(disk->queue);
1269}
1270
ac81bfa9
MB
1271static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1272{
1273 struct nvme_ns *ns = disk->private_data;
1673f1f0
CH
1274
1275 /*
1276 * If identify namespace failed, use default 512 byte block size so
1277 * block layer can use before failing read/write for 0 capacity.
1278 */
c81bfba9 1279 ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1673f1f0
CH
1280 if (ns->lba_shift == 0)
1281 ns->lba_shift = 9;
6b8190d6 1282 ns->noiob = le16_to_cpu(id->noiob);
b5be3b39
CH
1283 ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1284 ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1285 /* the PI implementation requires metadata equal t10 pi tuple size */
1286 if (ns->ms == sizeof(struct t10_pi_tuple))
1287 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1288 else
1289 ns->pi_type = 0;
1673f1f0 1290
6e78f21a
CH
1291 if (ns->noiob)
1292 nvme_set_chunk_size(ns);
24b0b58c 1293 nvme_update_disk_info(disk, ns, id);
ac81bfa9 1294}
1673f1f0 1295
ac81bfa9
MB
1296static int nvme_revalidate_disk(struct gendisk *disk)
1297{
1298 struct nvme_ns *ns = disk->private_data;
cdbff4f2
CH
1299 struct nvme_ctrl *ctrl = ns->ctrl;
1300 struct nvme_id_ns *id;
1d5df6af
CH
1301 u8 eui64[8] = { 0 }, nguid[16] = { 0 };
1302 uuid_t uuid = uuid_null;
cdbff4f2 1303 int ret = 0;
ac81bfa9
MB
1304
1305 if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1306 set_capacity(disk, 0);
1307 return -ENODEV;
1308 }
1309
cdbff4f2
CH
1310 id = nvme_identify_ns(ctrl, ns->ns_id);
1311 if (!id)
1312 return -ENODEV;
ac81bfa9 1313
cdbff4f2
CH
1314 if (id->ncap == 0) {
1315 ret = -ENODEV;
1316 goto out;
1317 }
ac81bfa9 1318
1d5df6af
CH
1319 nvme_report_ns_ids(ctrl, ns->ns_id, id, eui64, nguid, &uuid);
1320 if (!uuid_equal(&ns->uuid, &uuid) ||
1321 memcmp(&ns->nguid, &nguid, sizeof(ns->nguid)) ||
1322 memcmp(&ns->eui, &eui64, sizeof(ns->eui))) {
1323 dev_err(ctrl->device,
1324 "identifiers changed for nsid %d\n", ns->ns_id);
1325 ret = -ENODEV;
1326 }
1327
cdbff4f2
CH
1328out:
1329 kfree(id);
1330 return ret;
1673f1f0
CH
1331}
1332
1333static char nvme_pr_type(enum pr_type type)
1334{
1335 switch (type) {
1336 case PR_WRITE_EXCLUSIVE:
1337 return 1;
1338 case PR_EXCLUSIVE_ACCESS:
1339 return 2;
1340 case PR_WRITE_EXCLUSIVE_REG_ONLY:
1341 return 3;
1342 case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1343 return 4;
1344 case PR_WRITE_EXCLUSIVE_ALL_REGS:
1345 return 5;
1346 case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1347 return 6;
1348 default:
1349 return 0;
1350 }
1351};
1352
1353static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1354 u64 key, u64 sa_key, u8 op)
1355{
1356 struct nvme_ns *ns = bdev->bd_disk->private_data;
1357 struct nvme_command c;
1358 u8 data[16] = { 0, };
1359
1360 put_unaligned_le64(key, &data[0]);
1361 put_unaligned_le64(sa_key, &data[8]);
1362
1363 memset(&c, 0, sizeof(c));
1364 c.common.opcode = op;
1365 c.common.nsid = cpu_to_le32(ns->ns_id);
1366 c.common.cdw10[0] = cpu_to_le32(cdw10);
1367
1368 return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1369}
1370
1371static int nvme_pr_register(struct block_device *bdev, u64 old,
1372 u64 new, unsigned flags)
1373{
1374 u32 cdw10;
1375
1376 if (flags & ~PR_FL_IGNORE_KEY)
1377 return -EOPNOTSUPP;
1378
1379 cdw10 = old ? 2 : 0;
1380 cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1381 cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1382 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1383}
1384
1385static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1386 enum pr_type type, unsigned flags)
1387{
1388 u32 cdw10;
1389
1390 if (flags & ~PR_FL_IGNORE_KEY)
1391 return -EOPNOTSUPP;
1392
1393 cdw10 = nvme_pr_type(type) << 8;
1394 cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1395 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1396}
1397
1398static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1399 enum pr_type type, bool abort)
1400{
1401 u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1402 return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1403}
1404
1405static int nvme_pr_clear(struct block_device *bdev, u64 key)
1406{
8c0b3915 1407 u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1673f1f0
CH
1408 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1409}
1410
1411static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1412{
1413 u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1414 return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1415}
1416
1417static const struct pr_ops nvme_pr_ops = {
1418 .pr_register = nvme_pr_register,
1419 .pr_reserve = nvme_pr_reserve,
1420 .pr_release = nvme_pr_release,
1421 .pr_preempt = nvme_pr_preempt,
1422 .pr_clear = nvme_pr_clear,
1423};
1424
a98e58e5 1425#ifdef CONFIG_BLK_SED_OPAL
4f1244c8
CH
1426int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1427 bool send)
a98e58e5 1428{
4f1244c8 1429 struct nvme_ctrl *ctrl = data;
a98e58e5 1430 struct nvme_command cmd;
a98e58e5
SB
1431
1432 memset(&cmd, 0, sizeof(cmd));
1433 if (send)
1434 cmd.common.opcode = nvme_admin_security_send;
1435 else
1436 cmd.common.opcode = nvme_admin_security_recv;
a98e58e5
SB
1437 cmd.common.nsid = 0;
1438 cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1439 cmd.common.cdw10[1] = cpu_to_le32(len);
1440
1441 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1442 ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1443}
1444EXPORT_SYMBOL_GPL(nvme_sec_submit);
1445#endif /* CONFIG_BLK_SED_OPAL */
1446
5bae7f73 1447static const struct block_device_operations nvme_fops = {
1673f1f0
CH
1448 .owner = THIS_MODULE,
1449 .ioctl = nvme_ioctl,
761f2e1e 1450 .compat_ioctl = nvme_ioctl,
1673f1f0
CH
1451 .open = nvme_open,
1452 .release = nvme_release,
1453 .getgeo = nvme_getgeo,
1454 .revalidate_disk= nvme_revalidate_disk,
1455 .pr_ops = &nvme_pr_ops,
1456};
1457
5fd4ce1b
CH
1458static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1459{
1460 unsigned long timeout =
1461 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1462 u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1463 int ret;
1464
1465 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
0df1e4f5
KB
1466 if (csts == ~0)
1467 return -ENODEV;
5fd4ce1b
CH
1468 if ((csts & NVME_CSTS_RDY) == bit)
1469 break;
1470
1471 msleep(100);
1472 if (fatal_signal_pending(current))
1473 return -EINTR;
1474 if (time_after(jiffies, timeout)) {
1b3c47c1 1475 dev_err(ctrl->device,
5fd4ce1b
CH
1476 "Device not ready; aborting %s\n", enabled ?
1477 "initialisation" : "reset");
1478 return -ENODEV;
1479 }
1480 }
1481
1482 return ret;
1483}
1484
1485/*
1486 * If the device has been passed off to us in an enabled state, just clear
1487 * the enabled bit. The spec says we should set the 'shutdown notification
1488 * bits', but doing so may cause the device to complete commands to the
1489 * admin queue ... and we don't know what memory that might be pointing at!
1490 */
1491int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1492{
1493 int ret;
1494
1495 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1496 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1497
1498 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1499 if (ret)
1500 return ret;
54adc010 1501
b5a10c5f 1502 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
54adc010
GP
1503 msleep(NVME_QUIRK_DELAY_AMOUNT);
1504
5fd4ce1b
CH
1505 return nvme_wait_ready(ctrl, cap, false);
1506}
576d55d6 1507EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
5fd4ce1b
CH
1508
1509int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1510{
1511 /*
1512 * Default to a 4K page size, with the intention to update this
1513 * path in the future to accomodate architectures with differing
1514 * kernel and IO page sizes.
1515 */
1516 unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1517 int ret;
1518
1519 if (page_shift < dev_page_min) {
1b3c47c1 1520 dev_err(ctrl->device,
5fd4ce1b
CH
1521 "Minimum device page size %u too large for host (%u)\n",
1522 1 << dev_page_min, 1 << page_shift);
1523 return -ENODEV;
1524 }
1525
1526 ctrl->page_size = 1 << page_shift;
1527
1528 ctrl->ctrl_config = NVME_CC_CSS_NVM;
1529 ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
60b43f62 1530 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
5fd4ce1b
CH
1531 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1532 ctrl->ctrl_config |= NVME_CC_ENABLE;
1533
1534 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1535 if (ret)
1536 return ret;
1537 return nvme_wait_ready(ctrl, cap, true);
1538}
576d55d6 1539EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
5fd4ce1b
CH
1540
1541int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1542{
07fbd32a 1543 unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
5fd4ce1b
CH
1544 u32 csts;
1545 int ret;
1546
1547 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1548 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1549
1550 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1551 if (ret)
1552 return ret;
1553
1554 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1555 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1556 break;
1557
1558 msleep(100);
1559 if (fatal_signal_pending(current))
1560 return -EINTR;
1561 if (time_after(jiffies, timeout)) {
1b3c47c1 1562 dev_err(ctrl->device,
5fd4ce1b
CH
1563 "Device shutdown incomplete; abort shutdown\n");
1564 return -ENODEV;
1565 }
1566 }
1567
1568 return ret;
1569}
576d55d6 1570EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
5fd4ce1b 1571
da35825d
CH
1572static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1573 struct request_queue *q)
1574{
7c88cb00
JA
1575 bool vwc = false;
1576
da35825d 1577 if (ctrl->max_hw_sectors) {
45686b61
CH
1578 u32 max_segments =
1579 (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1580
da35825d 1581 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
45686b61 1582 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
da35825d 1583 }
e6282aef
KB
1584 if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1585 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
da35825d 1586 blk_queue_virt_boundary(q, ctrl->page_size - 1);
7c88cb00
JA
1587 if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1588 vwc = true;
1589 blk_queue_write_cache(q, vwc, vwc);
da35825d
CH
1590}
1591
dbf86b39
JD
1592static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1593{
1594 __le64 ts;
1595 int ret;
1596
1597 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1598 return 0;
1599
1600 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1601 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1602 NULL);
1603 if (ret)
1604 dev_warn_once(ctrl->device,
1605 "could not set timestamp (%d)\n", ret);
1606 return ret;
1607}
1608
634b8325 1609static int nvme_configure_apst(struct nvme_ctrl *ctrl)
c5552fde
AL
1610{
1611 /*
1612 * APST (Autonomous Power State Transition) lets us program a
1613 * table of power state transitions that the controller will
1614 * perform automatically. We configure it with a simple
1615 * heuristic: we are willing to spend at most 2% of the time
1616 * transitioning between power states. Therefore, when running
1617 * in any given state, we will enter the next lower-power
76e4ad09 1618 * non-operational state after waiting 50 * (enlat + exlat)
da87591b 1619 * microseconds, as long as that state's exit latency is under
c5552fde
AL
1620 * the requested maximum latency.
1621 *
1622 * We will not autonomously enter any non-operational state for
1623 * which the total latency exceeds ps_max_latency_us. Users
1624 * can set ps_max_latency_us to zero to turn off APST.
1625 */
1626
1627 unsigned apste;
1628 struct nvme_feat_auto_pst *table;
fb0dc399
AL
1629 u64 max_lat_us = 0;
1630 int max_ps = -1;
c5552fde
AL
1631 int ret;
1632
1633 /*
1634 * If APST isn't supported or if we haven't been initialized yet,
1635 * then don't do anything.
1636 */
1637 if (!ctrl->apsta)
634b8325 1638 return 0;
c5552fde
AL
1639
1640 if (ctrl->npss > 31) {
1641 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
634b8325 1642 return 0;
c5552fde
AL
1643 }
1644
1645 table = kzalloc(sizeof(*table), GFP_KERNEL);
1646 if (!table)
634b8325 1647 return 0;
c5552fde 1648
76a5af84 1649 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
c5552fde
AL
1650 /* Turn off APST. */
1651 apste = 0;
fb0dc399 1652 dev_dbg(ctrl->device, "APST disabled\n");
c5552fde
AL
1653 } else {
1654 __le64 target = cpu_to_le64(0);
1655 int state;
1656
1657 /*
1658 * Walk through all states from lowest- to highest-power.
1659 * According to the spec, lower-numbered states use more
1660 * power. NPSS, despite the name, is the index of the
1661 * lowest-power state, not the number of states.
1662 */
1663 for (state = (int)ctrl->npss; state >= 0; state--) {
da87591b 1664 u64 total_latency_us, exit_latency_us, transition_ms;
c5552fde
AL
1665
1666 if (target)
1667 table->entries[state] = target;
1668
ff5350a8
AL
1669 /*
1670 * Don't allow transitions to the deepest state
1671 * if it's quirked off.
1672 */
1673 if (state == ctrl->npss &&
1674 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1675 continue;
1676
c5552fde
AL
1677 /*
1678 * Is this state a useful non-operational state for
1679 * higher-power states to autonomously transition to?
1680 */
1681 if (!(ctrl->psd[state].flags &
1682 NVME_PS_FLAGS_NON_OP_STATE))
1683 continue;
1684
da87591b
KHF
1685 exit_latency_us =
1686 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1687 if (exit_latency_us > ctrl->ps_max_latency_us)
c5552fde
AL
1688 continue;
1689
da87591b
KHF
1690 total_latency_us =
1691 exit_latency_us +
1692 le32_to_cpu(ctrl->psd[state].entry_lat);
1693
c5552fde
AL
1694 /*
1695 * This state is good. Use it as the APST idle
1696 * target for higher power states.
1697 */
1698 transition_ms = total_latency_us + 19;
1699 do_div(transition_ms, 20);
1700 if (transition_ms > (1 << 24) - 1)
1701 transition_ms = (1 << 24) - 1;
1702
1703 target = cpu_to_le64((state << 3) |
1704 (transition_ms << 8));
fb0dc399
AL
1705
1706 if (max_ps == -1)
1707 max_ps = state;
1708
1709 if (total_latency_us > max_lat_us)
1710 max_lat_us = total_latency_us;
c5552fde
AL
1711 }
1712
1713 apste = 1;
fb0dc399
AL
1714
1715 if (max_ps == -1) {
1716 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1717 } else {
1718 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1719 max_ps, max_lat_us, (int)sizeof(*table), table);
1720 }
c5552fde
AL
1721 }
1722
1723 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1724 table, sizeof(*table), NULL);
1725 if (ret)
1726 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1727
1728 kfree(table);
634b8325 1729 return ret;
c5552fde
AL
1730}
1731
1732static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1733{
1734 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1735 u64 latency;
1736
1737 switch (val) {
1738 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1739 case PM_QOS_LATENCY_ANY:
1740 latency = U64_MAX;
1741 break;
1742
1743 default:
1744 latency = val;
1745 }
1746
1747 if (ctrl->ps_max_latency_us != latency) {
1748 ctrl->ps_max_latency_us = latency;
1749 nvme_configure_apst(ctrl);
1750 }
1751}
1752
bd4da3ab
AL
1753struct nvme_core_quirk_entry {
1754 /*
1755 * NVMe model and firmware strings are padded with spaces. For
1756 * simplicity, strings in the quirk table are padded with NULLs
1757 * instead.
1758 */
1759 u16 vid;
1760 const char *mn;
1761 const char *fr;
1762 unsigned long quirks;
1763};
1764
1765static const struct nvme_core_quirk_entry core_quirks[] = {
c5552fde 1766 {
be56945c
AL
1767 /*
1768 * This Toshiba device seems to die using any APST states. See:
1769 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1770 */
1771 .vid = 0x1179,
1772 .mn = "THNSF5256GPUK TOSHIBA",
c5552fde 1773 .quirks = NVME_QUIRK_NO_APST,
be56945c 1774 }
bd4da3ab
AL
1775};
1776
1777/* match is null-terminated but idstr is space-padded. */
1778static bool string_matches(const char *idstr, const char *match, size_t len)
1779{
1780 size_t matchlen;
1781
1782 if (!match)
1783 return true;
1784
1785 matchlen = strlen(match);
1786 WARN_ON_ONCE(matchlen > len);
1787
1788 if (memcmp(idstr, match, matchlen))
1789 return false;
1790
1791 for (; matchlen < len; matchlen++)
1792 if (idstr[matchlen] != ' ')
1793 return false;
1794
1795 return true;
1796}
1797
1798static bool quirk_matches(const struct nvme_id_ctrl *id,
1799 const struct nvme_core_quirk_entry *q)
1800{
1801 return q->vid == le16_to_cpu(id->vid) &&
1802 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1803 string_matches(id->fr, q->fr, sizeof(id->fr));
1804}
1805
180de007
CH
1806static void nvme_init_subnqn(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1807{
1808 size_t nqnlen;
1809 int off;
1810
1811 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
1812 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
a47619b5 1813 strncpy(ctrl->subnqn, id->subnqn, NVMF_NQN_SIZE);
180de007
CH
1814 return;
1815 }
1816
1817 if (ctrl->vs >= NVME_VS(1, 2, 1))
1818 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
1819
1820 /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
1821 off = snprintf(ctrl->subnqn, NVMF_NQN_SIZE,
1822 "nqn.2014.08.org.nvmexpress:%4x%4x",
1823 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
1824 memcpy(ctrl->subnqn + off, id->sn, sizeof(id->sn));
1825 off += sizeof(id->sn);
1826 memcpy(ctrl->subnqn + off, id->mn, sizeof(id->mn));
1827 off += sizeof(id->mn);
1828 memset(ctrl->subnqn + off, 0, sizeof(ctrl->subnqn) - off);
1829}
1830
c627c487
KB
1831static int nvme_get_log(struct nvme_ctrl *ctrl, u8 log_page, void *log,
1832 size_t size)
1833{
1834 struct nvme_command c = { };
1835
1836 c.common.opcode = nvme_admin_get_log_page;
1837 c.common.nsid = cpu_to_le32(NVME_NSID_ALL);
1838 c.common.cdw10[0] = nvme_get_log_dw10(log_page, size);
1839
1840 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
1841}
1842
84fef62d
KB
1843static int nvme_get_effects_log(struct nvme_ctrl *ctrl)
1844{
1845 int ret;
1846
1847 if (!ctrl->effects)
1848 ctrl->effects = kzalloc(sizeof(*ctrl->effects), GFP_KERNEL);
1849
1850 if (!ctrl->effects)
1851 return 0;
1852
1853 ret = nvme_get_log(ctrl, NVME_LOG_CMD_EFFECTS, ctrl->effects,
1854 sizeof(*ctrl->effects));
1855 if (ret) {
1856 kfree(ctrl->effects);
1857 ctrl->effects = NULL;
1858 }
1859 return ret;
1860}
1861
7fd8930f
CH
1862/*
1863 * Initialize the cached copies of the Identify data and various controller
1864 * register in our nvme_ctrl structure. This should be called as soon as
1865 * the admin queue is fully up and running.
1866 */
1867int nvme_init_identify(struct nvme_ctrl *ctrl)
1868{
1869 struct nvme_id_ctrl *id;
1870 u64 cap;
1871 int ret, page_shift;
a229dbf6 1872 u32 max_hw_sectors;
76a5af84 1873 bool prev_apst_enabled;
7fd8930f 1874
f3ca80fc
CH
1875 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1876 if (ret) {
1b3c47c1 1877 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
f3ca80fc
CH
1878 return ret;
1879 }
1880
7fd8930f
CH
1881 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1882 if (ret) {
1b3c47c1 1883 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
7fd8930f
CH
1884 return ret;
1885 }
1886 page_shift = NVME_CAP_MPSMIN(cap) + 12;
1887
8ef2074d 1888 if (ctrl->vs >= NVME_VS(1, 1, 0))
f3ca80fc
CH
1889 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1890
7fd8930f
CH
1891 ret = nvme_identify_ctrl(ctrl, &id);
1892 if (ret) {
1b3c47c1 1893 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
7fd8930f
CH
1894 return -EIO;
1895 }
1896
84fef62d
KB
1897 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
1898 ret = nvme_get_effects_log(ctrl);
1899 if (ret < 0)
1900 return ret;
1901 }
1902
180de007
CH
1903 nvme_init_subnqn(ctrl, id);
1904
bd4da3ab
AL
1905 if (!ctrl->identified) {
1906 /*
1907 * Check for quirks. Quirk can depend on firmware version,
1908 * so, in principle, the set of quirks present can change
1909 * across a reset. As a possible future enhancement, we
1910 * could re-scan for quirks every time we reinitialize
1911 * the device, but we'd have to make sure that the driver
1912 * behaves intelligently if the quirks change.
1913 */
1914
1915 int i;
1916
1917 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1918 if (quirk_matches(id, &core_quirks[i]))
1919 ctrl->quirks |= core_quirks[i].quirks;
1920 }
1921 }
1922
c35e30b4 1923 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
f0425db0 1924 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
c35e30b4
AL
1925 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1926 }
1927
8a9ae523 1928 ctrl->oacs = le16_to_cpu(id->oacs);
118472ab 1929 ctrl->vid = le16_to_cpu(id->vid);
7fd8930f 1930 ctrl->oncs = le16_to_cpup(&id->oncs);
6bf25d16 1931 atomic_set(&ctrl->abort_limit, id->acl + 1);
7fd8930f 1932 ctrl->vwc = id->vwc;
931e1c22 1933 ctrl->cntlid = le16_to_cpup(&id->cntlid);
7fd8930f
CH
1934 memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1935 memcpy(ctrl->model, id->mn, sizeof(id->mn));
1936 memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1937 if (id->mdts)
a229dbf6 1938 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
7fd8930f 1939 else
a229dbf6
CH
1940 max_hw_sectors = UINT_MAX;
1941 ctrl->max_hw_sectors =
1942 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
7fd8930f 1943
da35825d 1944 nvme_set_queue_limits(ctrl, ctrl->admin_q);
07bfcd09 1945 ctrl->sgls = le32_to_cpu(id->sgls);
038bd4cb 1946 ctrl->kas = le16_to_cpu(id->kas);
07bfcd09 1947
07fbd32a
MP
1948 if (id->rtd3e) {
1949 /* us -> s */
1950 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
1951
1952 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
1953 shutdown_timeout, 60);
1954
1955 if (ctrl->shutdown_timeout != shutdown_timeout)
1956 dev_warn(ctrl->device,
1957 "Shutdown timeout set to %u seconds\n",
1958 ctrl->shutdown_timeout);
1959 } else
1960 ctrl->shutdown_timeout = shutdown_timeout;
1961
c5552fde 1962 ctrl->npss = id->npss;
76a5af84
KHF
1963 ctrl->apsta = id->apsta;
1964 prev_apst_enabled = ctrl->apst_enabled;
c35e30b4
AL
1965 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1966 if (force_apst && id->apsta) {
f0425db0 1967 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
76a5af84 1968 ctrl->apst_enabled = true;
c35e30b4 1969 } else {
76a5af84 1970 ctrl->apst_enabled = false;
c35e30b4
AL
1971 }
1972 } else {
76a5af84 1973 ctrl->apst_enabled = id->apsta;
c35e30b4 1974 }
c5552fde
AL
1975 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1976
d3d5b87d 1977 if (ctrl->ops->flags & NVME_F_FABRICS) {
07bfcd09
CH
1978 ctrl->icdoff = le16_to_cpu(id->icdoff);
1979 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1980 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1981 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1982
1983 /*
1984 * In fabrics we need to verify the cntlid matches the
1985 * admin connect
1986 */
634b8325 1987 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
07bfcd09 1988 ret = -EINVAL;
634b8325
KB
1989 goto out_free;
1990 }
038bd4cb
SG
1991
1992 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
f0425db0 1993 dev_err(ctrl->device,
038bd4cb
SG
1994 "keep-alive support is mandatory for fabrics\n");
1995 ret = -EINVAL;
634b8325 1996 goto out_free;
038bd4cb 1997 }
07bfcd09
CH
1998 } else {
1999 ctrl->cntlid = le16_to_cpu(id->cntlid);
fe6d53c9
CH
2000 ctrl->hmpre = le32_to_cpu(id->hmpre);
2001 ctrl->hmmin = le32_to_cpu(id->hmmin);
044a9df1
CH
2002 ctrl->hmminds = le32_to_cpu(id->hmminds);
2003 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
07bfcd09 2004 }
da35825d 2005
7fd8930f 2006 kfree(id);
bd4da3ab 2007
76a5af84 2008 if (ctrl->apst_enabled && !prev_apst_enabled)
c5552fde 2009 dev_pm_qos_expose_latency_tolerance(ctrl->device);
76a5af84 2010 else if (!ctrl->apst_enabled && prev_apst_enabled)
c5552fde
AL
2011 dev_pm_qos_hide_latency_tolerance(ctrl->device);
2012
634b8325
KB
2013 ret = nvme_configure_apst(ctrl);
2014 if (ret < 0)
2015 return ret;
dbf86b39
JD
2016
2017 ret = nvme_configure_timestamp(ctrl);
2018 if (ret < 0)
2019 return ret;
634b8325
KB
2020
2021 ret = nvme_configure_directives(ctrl);
2022 if (ret < 0)
2023 return ret;
c5552fde 2024
bd4da3ab 2025 ctrl->identified = true;
c5552fde 2026
634b8325
KB
2027 return 0;
2028
2029out_free:
2030 kfree(id);
07bfcd09 2031 return ret;
7fd8930f 2032}
576d55d6 2033EXPORT_SYMBOL_GPL(nvme_init_identify);
7fd8930f 2034
f3ca80fc 2035static int nvme_dev_open(struct inode *inode, struct file *file)
1673f1f0 2036{
a6a5149b
CH
2037 struct nvme_ctrl *ctrl =
2038 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
1673f1f0 2039
999ada28 2040 if (ctrl->state != NVME_CTRL_LIVE)
a6a5149b
CH
2041 return -EWOULDBLOCK;
2042 file->private_data = ctrl;
f3ca80fc
CH
2043 return 0;
2044}
2045
bfd89471
CH
2046static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
2047{
2048 struct nvme_ns *ns;
2049 int ret;
2050
2051 mutex_lock(&ctrl->namespaces_mutex);
2052 if (list_empty(&ctrl->namespaces)) {
2053 ret = -ENOTTY;
2054 goto out_unlock;
2055 }
2056
2057 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
2058 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1b3c47c1 2059 dev_warn(ctrl->device,
bfd89471
CH
2060 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
2061 ret = -EINVAL;
2062 goto out_unlock;
2063 }
2064
1b3c47c1 2065 dev_warn(ctrl->device,
bfd89471
CH
2066 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
2067 kref_get(&ns->kref);
2068 mutex_unlock(&ctrl->namespaces_mutex);
2069
2070 ret = nvme_user_cmd(ctrl, ns, argp);
2071 nvme_put_ns(ns);
2072 return ret;
2073
2074out_unlock:
2075 mutex_unlock(&ctrl->namespaces_mutex);
2076 return ret;
2077}
2078
f3ca80fc
CH
2079static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
2080 unsigned long arg)
2081{
2082 struct nvme_ctrl *ctrl = file->private_data;
2083 void __user *argp = (void __user *)arg;
f3ca80fc
CH
2084
2085 switch (cmd) {
2086 case NVME_IOCTL_ADMIN_CMD:
2087 return nvme_user_cmd(ctrl, NULL, argp);
2088 case NVME_IOCTL_IO_CMD:
bfd89471 2089 return nvme_dev_user_cmd(ctrl, argp);
f3ca80fc 2090 case NVME_IOCTL_RESET:
1b3c47c1 2091 dev_warn(ctrl->device, "resetting controller\n");
d86c4d8e 2092 return nvme_reset_ctrl_sync(ctrl);
f3ca80fc
CH
2093 case NVME_IOCTL_SUBSYS_RESET:
2094 return nvme_reset_subsystem(ctrl);
9ec3bb2f
KB
2095 case NVME_IOCTL_RESCAN:
2096 nvme_queue_scan(ctrl);
2097 return 0;
f3ca80fc
CH
2098 default:
2099 return -ENOTTY;
2100 }
2101}
2102
2103static const struct file_operations nvme_dev_fops = {
2104 .owner = THIS_MODULE,
2105 .open = nvme_dev_open,
f3ca80fc
CH
2106 .unlocked_ioctl = nvme_dev_ioctl,
2107 .compat_ioctl = nvme_dev_ioctl,
2108};
2109
2110static ssize_t nvme_sysfs_reset(struct device *dev,
2111 struct device_attribute *attr, const char *buf,
2112 size_t count)
2113{
2114 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2115 int ret;
2116
d86c4d8e 2117 ret = nvme_reset_ctrl_sync(ctrl);
f3ca80fc
CH
2118 if (ret < 0)
2119 return ret;
2120 return count;
1673f1f0 2121}
f3ca80fc 2122static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1673f1f0 2123
9ec3bb2f
KB
2124static ssize_t nvme_sysfs_rescan(struct device *dev,
2125 struct device_attribute *attr, const char *buf,
2126 size_t count)
2127{
2128 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2129
2130 nvme_queue_scan(ctrl);
2131 return count;
2132}
2133static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2134
118472ab
KB
2135static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2136 char *buf)
2137{
40267efd 2138 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
118472ab
KB
2139 struct nvme_ctrl *ctrl = ns->ctrl;
2140 int serial_len = sizeof(ctrl->serial);
2141 int model_len = sizeof(ctrl->model);
2142
6484f5d1
JT
2143 if (!uuid_is_null(&ns->uuid))
2144 return sprintf(buf, "uuid.%pU\n", &ns->uuid);
2145
90985b84
JT
2146 if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2147 return sprintf(buf, "eui.%16phN\n", ns->nguid);
118472ab
KB
2148
2149 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2150 return sprintf(buf, "eui.%8phN\n", ns->eui);
2151
758f3735
MW
2152 while (serial_len > 0 && (ctrl->serial[serial_len - 1] == ' ' ||
2153 ctrl->serial[serial_len - 1] == '\0'))
118472ab 2154 serial_len--;
758f3735
MW
2155 while (model_len > 0 && (ctrl->model[model_len - 1] == ' ' ||
2156 ctrl->model[model_len - 1] == '\0'))
118472ab
KB
2157 model_len--;
2158
2159 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
2160 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
2161}
2162static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
2163
d934f984
JT
2164static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2165 char *buf)
2166{
2167 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2168 return sprintf(buf, "%pU\n", ns->nguid);
2169}
2170static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
2171
2b9b6e86
KB
2172static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2173 char *buf)
2174{
40267efd 2175 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
d934f984
JT
2176
2177 /* For backward compatibility expose the NGUID to userspace if
2178 * we have no UUID set
2179 */
2180 if (uuid_is_null(&ns->uuid)) {
2181 printk_ratelimited(KERN_WARNING
2182 "No UUID available providing old NGUID\n");
2183 return sprintf(buf, "%pU\n", ns->nguid);
2184 }
2185 return sprintf(buf, "%pU\n", &ns->uuid);
2b9b6e86
KB
2186}
2187static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
2188
2189static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2190 char *buf)
2191{
40267efd 2192 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
ab083b11 2193 return sprintf(buf, "%8ph\n", ns->eui);
2b9b6e86
KB
2194}
2195static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
2196
2197static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2198 char *buf)
2199{
40267efd 2200 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
2201 return sprintf(buf, "%d\n", ns->ns_id);
2202}
2203static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
2204
2205static struct attribute *nvme_ns_attrs[] = {
118472ab 2206 &dev_attr_wwid.attr,
2b9b6e86 2207 &dev_attr_uuid.attr,
d934f984 2208 &dev_attr_nguid.attr,
2b9b6e86
KB
2209 &dev_attr_eui.attr,
2210 &dev_attr_nsid.attr,
2211 NULL,
2212};
2213
1a353d85 2214static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2b9b6e86
KB
2215 struct attribute *a, int n)
2216{
2217 struct device *dev = container_of(kobj, struct device, kobj);
40267efd 2218 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2b9b6e86
KB
2219
2220 if (a == &dev_attr_uuid.attr) {
d934f984
JT
2221 if (uuid_is_null(&ns->uuid) ||
2222 !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2223 return 0;
2224 }
2225 if (a == &dev_attr_nguid.attr) {
90985b84 2226 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2b9b6e86
KB
2227 return 0;
2228 }
2229 if (a == &dev_attr_eui.attr) {
2230 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2231 return 0;
2232 }
2233 return a->mode;
2234}
2235
2236static const struct attribute_group nvme_ns_attr_group = {
2237 .attrs = nvme_ns_attrs,
1a353d85 2238 .is_visible = nvme_ns_attrs_are_visible,
2b9b6e86
KB
2239};
2240
931e1c22 2241#define nvme_show_str_function(field) \
779ff756
KB
2242static ssize_t field##_show(struct device *dev, \
2243 struct device_attribute *attr, char *buf) \
2244{ \
2245 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2246 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
2247} \
2248static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2249
931e1c22
ML
2250#define nvme_show_int_function(field) \
2251static ssize_t field##_show(struct device *dev, \
2252 struct device_attribute *attr, char *buf) \
2253{ \
2254 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
2255 return sprintf(buf, "%d\n", ctrl->field); \
2256} \
2257static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2258
2259nvme_show_str_function(model);
2260nvme_show_str_function(serial);
2261nvme_show_str_function(firmware_rev);
2262nvme_show_int_function(cntlid);
779ff756 2263
1a353d85
ML
2264static ssize_t nvme_sysfs_delete(struct device *dev,
2265 struct device_attribute *attr, const char *buf,
2266 size_t count)
2267{
2268 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2269
2270 if (device_remove_file_self(dev, attr))
c5017e85 2271 nvme_delete_ctrl_sync(ctrl);
1a353d85
ML
2272 return count;
2273}
2274static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2275
2276static ssize_t nvme_sysfs_show_transport(struct device *dev,
2277 struct device_attribute *attr,
2278 char *buf)
2279{
2280 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2281
2282 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2283}
2284static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2285
8432bdb2
SG
2286static ssize_t nvme_sysfs_show_state(struct device *dev,
2287 struct device_attribute *attr,
2288 char *buf)
2289{
2290 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2291 static const char *const state_name[] = {
2292 [NVME_CTRL_NEW] = "new",
2293 [NVME_CTRL_LIVE] = "live",
2294 [NVME_CTRL_RESETTING] = "resetting",
2295 [NVME_CTRL_RECONNECTING]= "reconnecting",
2296 [NVME_CTRL_DELETING] = "deleting",
2297 [NVME_CTRL_DEAD] = "dead",
2298 };
2299
2300 if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2301 state_name[ctrl->state])
2302 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2303
2304 return sprintf(buf, "unknown state\n");
2305}
2306
2307static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2308
1a353d85
ML
2309static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2310 struct device_attribute *attr,
2311 char *buf)
2312{
2313 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2314
180de007 2315 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subnqn);
1a353d85
ML
2316}
2317static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2318
2319static ssize_t nvme_sysfs_show_address(struct device *dev,
2320 struct device_attribute *attr,
2321 char *buf)
2322{
2323 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2324
2325 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2326}
2327static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2328
779ff756
KB
2329static struct attribute *nvme_dev_attrs[] = {
2330 &dev_attr_reset_controller.attr,
9ec3bb2f 2331 &dev_attr_rescan_controller.attr,
779ff756
KB
2332 &dev_attr_model.attr,
2333 &dev_attr_serial.attr,
2334 &dev_attr_firmware_rev.attr,
931e1c22 2335 &dev_attr_cntlid.attr,
1a353d85
ML
2336 &dev_attr_delete_controller.attr,
2337 &dev_attr_transport.attr,
2338 &dev_attr_subsysnqn.attr,
2339 &dev_attr_address.attr,
8432bdb2 2340 &dev_attr_state.attr,
779ff756
KB
2341 NULL
2342};
2343
1a353d85
ML
2344static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2345 struct attribute *a, int n)
2346{
2347 struct device *dev = container_of(kobj, struct device, kobj);
2348 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2349
49d3d50b
CH
2350 if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2351 return 0;
2352 if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2353 return 0;
1a353d85
ML
2354
2355 return a->mode;
2356}
2357
779ff756 2358static struct attribute_group nvme_dev_attrs_group = {
1a353d85
ML
2359 .attrs = nvme_dev_attrs,
2360 .is_visible = nvme_dev_attrs_are_visible,
779ff756
KB
2361};
2362
2363static const struct attribute_group *nvme_dev_attr_groups[] = {
2364 &nvme_dev_attrs_group,
2365 NULL,
2366};
2367
5bae7f73
CH
2368static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2369{
2370 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2371 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2372
2373 return nsa->ns_id - nsb->ns_id;
2374}
2375
32f0c4af 2376static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
5bae7f73 2377{
32f0c4af 2378 struct nvme_ns *ns, *ret = NULL;
69d3b8ac 2379
32f0c4af 2380 mutex_lock(&ctrl->namespaces_mutex);
5bae7f73 2381 list_for_each_entry(ns, &ctrl->namespaces, list) {
32f0c4af 2382 if (ns->ns_id == nsid) {
2dd41228
CH
2383 if (!kref_get_unless_zero(&ns->kref))
2384 continue;
32f0c4af
KB
2385 ret = ns;
2386 break;
2387 }
5bae7f73
CH
2388 if (ns->ns_id > nsid)
2389 break;
2390 }
32f0c4af
KB
2391 mutex_unlock(&ctrl->namespaces_mutex);
2392 return ret;
5bae7f73
CH
2393}
2394
f5d11840
JA
2395static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2396{
2397 struct streams_directive_params s;
2398 int ret;
2399
2400 if (!ctrl->nr_streams)
2401 return 0;
2402
2403 ret = nvme_get_stream_params(ctrl, &s, ns->ns_id);
2404 if (ret)
2405 return ret;
2406
2407 ns->sws = le32_to_cpu(s.sws);
2408 ns->sgs = le16_to_cpu(s.sgs);
2409
2410 if (ns->sws) {
2411 unsigned int bs = 1 << ns->lba_shift;
2412
2413 blk_queue_io_min(ns->queue, bs * ns->sws);
2414 if (ns->sgs)
2415 blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2416 }
2417
2418 return 0;
2419}
2420
5bae7f73
CH
2421static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2422{
2423 struct nvme_ns *ns;
2424 struct gendisk *disk;
ac81bfa9
MB
2425 struct nvme_id_ns *id;
2426 char disk_name[DISK_NAME_LEN];
5bae7f73
CH
2427 int node = dev_to_node(ctrl->dev);
2428
2429 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2430 if (!ns)
2431 return;
2432
075790eb
KB
2433 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2434 if (ns->instance < 0)
2435 goto out_free_ns;
2436
5bae7f73
CH
2437 ns->queue = blk_mq_init_queue(ctrl->tagset);
2438 if (IS_ERR(ns->queue))
075790eb 2439 goto out_release_instance;
5bae7f73
CH
2440 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2441 ns->queue->queuedata = ns;
2442 ns->ctrl = ctrl;
2443
5bae7f73
CH
2444 kref_init(&ns->kref);
2445 ns->ns_id = nsid;
5bae7f73 2446 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
5bae7f73
CH
2447
2448 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
da35825d 2449 nvme_set_queue_limits(ctrl, ns->queue);
f5d11840 2450 nvme_setup_streams_ns(ctrl, ns);
5bae7f73 2451
ac81bfa9 2452 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
5bae7f73 2453
cdbff4f2
CH
2454 id = nvme_identify_ns(ctrl, nsid);
2455 if (!id)
ac81bfa9
MB
2456 goto out_free_queue;
2457
cdbff4f2
CH
2458 if (id->ncap == 0)
2459 goto out_free_id;
2460
2461 nvme_report_ns_ids(ctrl, ns->ns_id, id, ns->eui, ns->nguid, &ns->uuid);
2462
608cc4b1
CH
2463 if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
2464 if (nvme_nvm_register(ns, disk_name, node)) {
2465 dev_warn(ctrl->device, "LightNVM init failure\n");
2466 goto out_free_id;
2467 }
3dc87dd0 2468 }
ac81bfa9 2469
3dc87dd0
MB
2470 disk = alloc_disk_node(0, node);
2471 if (!disk)
2472 goto out_free_id;
ac81bfa9 2473
3dc87dd0
MB
2474 disk->fops = &nvme_fops;
2475 disk->private_data = ns;
2476 disk->queue = ns->queue;
2477 disk->flags = GENHD_FL_EXT_DEVT;
2478 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2479 ns->disk = disk;
2480
2481 __nvme_revalidate_disk(disk, id);
5bae7f73 2482
32f0c4af
KB
2483 mutex_lock(&ctrl->namespaces_mutex);
2484 list_add_tail(&ns->list, &ctrl->namespaces);
2485 mutex_unlock(&ctrl->namespaces_mutex);
2486
d22524a4 2487 nvme_get_ctrl(ctrl);
ac81bfa9
MB
2488
2489 kfree(id);
2490
0d52c756 2491 device_add_disk(ctrl->device, ns->disk);
2b9b6e86
KB
2492 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2493 &nvme_ns_attr_group))
2494 pr_warn("%s: failed to create sysfs group for identification\n",
2495 ns->disk->disk_name);
3dc87dd0
MB
2496 if (ns->ndev && nvme_nvm_register_sysfs(ns))
2497 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2498 ns->disk->disk_name);
5bae7f73 2499 return;
ac81bfa9
MB
2500 out_free_id:
2501 kfree(id);
5bae7f73
CH
2502 out_free_queue:
2503 blk_cleanup_queue(ns->queue);
075790eb
KB
2504 out_release_instance:
2505 ida_simple_remove(&ctrl->ns_ida, ns->instance);
5bae7f73
CH
2506 out_free_ns:
2507 kfree(ns);
2508}
2509
2510static void nvme_ns_remove(struct nvme_ns *ns)
2511{
646017a6
KB
2512 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2513 return;
69d3b8ac 2514
b0b4e09c 2515 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
5bae7f73
CH
2516 if (blk_get_integrity(ns->disk))
2517 blk_integrity_unregister(ns->disk);
2b9b6e86
KB
2518 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2519 &nvme_ns_attr_group);
3dc87dd0
MB
2520 if (ns->ndev)
2521 nvme_nvm_unregister_sysfs(ns);
5bae7f73 2522 del_gendisk(ns->disk);
5bae7f73
CH
2523 blk_cleanup_queue(ns->queue);
2524 }
32f0c4af
KB
2525
2526 mutex_lock(&ns->ctrl->namespaces_mutex);
5bae7f73 2527 list_del_init(&ns->list);
32f0c4af
KB
2528 mutex_unlock(&ns->ctrl->namespaces_mutex);
2529
5bae7f73
CH
2530 nvme_put_ns(ns);
2531}
2532
540c801c
KB
2533static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2534{
2535 struct nvme_ns *ns;
2536
32f0c4af 2537 ns = nvme_find_get_ns(ctrl, nsid);
540c801c 2538 if (ns) {
b0b4e09c 2539 if (ns->disk && revalidate_disk(ns->disk))
540c801c 2540 nvme_ns_remove(ns);
32f0c4af 2541 nvme_put_ns(ns);
540c801c
KB
2542 } else
2543 nvme_alloc_ns(ctrl, nsid);
2544}
2545
47b0e50a
SB
2546static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2547 unsigned nsid)
2548{
2549 struct nvme_ns *ns, *next;
2550
2551 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2552 if (ns->ns_id > nsid)
2553 nvme_ns_remove(ns);
2554 }
2555}
2556
540c801c
KB
2557static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2558{
2559 struct nvme_ns *ns;
2560 __le32 *ns_list;
2561 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2562 int ret = 0;
2563
2564 ns_list = kzalloc(0x1000, GFP_KERNEL);
2565 if (!ns_list)
2566 return -ENOMEM;
2567
2568 for (i = 0; i < num_lists; i++) {
2569 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2570 if (ret)
47b0e50a 2571 goto free;
540c801c
KB
2572
2573 for (j = 0; j < min(nn, 1024U); j++) {
2574 nsid = le32_to_cpu(ns_list[j]);
2575 if (!nsid)
2576 goto out;
2577
2578 nvme_validate_ns(ctrl, nsid);
2579
2580 while (++prev < nsid) {
32f0c4af
KB
2581 ns = nvme_find_get_ns(ctrl, prev);
2582 if (ns) {
540c801c 2583 nvme_ns_remove(ns);
32f0c4af
KB
2584 nvme_put_ns(ns);
2585 }
540c801c
KB
2586 }
2587 }
2588 nn -= j;
2589 }
2590 out:
47b0e50a
SB
2591 nvme_remove_invalid_namespaces(ctrl, prev);
2592 free:
540c801c
KB
2593 kfree(ns_list);
2594 return ret;
2595}
2596
5955be21 2597static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
5bae7f73 2598{
5bae7f73
CH
2599 unsigned i;
2600
540c801c
KB
2601 for (i = 1; i <= nn; i++)
2602 nvme_validate_ns(ctrl, i);
2603
47b0e50a 2604 nvme_remove_invalid_namespaces(ctrl, nn);
5bae7f73
CH
2605}
2606
5955be21 2607static void nvme_scan_work(struct work_struct *work)
5bae7f73 2608{
5955be21
CH
2609 struct nvme_ctrl *ctrl =
2610 container_of(work, struct nvme_ctrl, scan_work);
5bae7f73 2611 struct nvme_id_ctrl *id;
540c801c 2612 unsigned nn;
5bae7f73 2613
5955be21
CH
2614 if (ctrl->state != NVME_CTRL_LIVE)
2615 return;
2616
5bae7f73
CH
2617 if (nvme_identify_ctrl(ctrl, &id))
2618 return;
540c801c
KB
2619
2620 nn = le32_to_cpu(id->nn);
8ef2074d 2621 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
540c801c
KB
2622 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2623 if (!nvme_scan_ns_list(ctrl, nn))
2624 goto done;
2625 }
5955be21 2626 nvme_scan_ns_sequential(ctrl, nn);
540c801c 2627 done:
32f0c4af 2628 mutex_lock(&ctrl->namespaces_mutex);
540c801c 2629 list_sort(NULL, &ctrl->namespaces, ns_cmp);
69d3b8ac 2630 mutex_unlock(&ctrl->namespaces_mutex);
5bae7f73
CH
2631 kfree(id);
2632}
5955be21
CH
2633
2634void nvme_queue_scan(struct nvme_ctrl *ctrl)
2635{
2636 /*
2637 * Do not queue new scan work when a controller is reset during
2638 * removal.
2639 */
2640 if (ctrl->state == NVME_CTRL_LIVE)
c669ccdc 2641 queue_work(nvme_wq, &ctrl->scan_work);
5955be21
CH
2642}
2643EXPORT_SYMBOL_GPL(nvme_queue_scan);
5bae7f73 2644
32f0c4af
KB
2645/*
2646 * This function iterates the namespace list unlocked to allow recovery from
2647 * controller failure. It is up to the caller to ensure the namespace list is
2648 * not modified by scan work while this function is executing.
2649 */
5bae7f73
CH
2650void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2651{
2652 struct nvme_ns *ns, *next;
2653
0ff9d4e1
KB
2654 /*
2655 * The dead states indicates the controller was not gracefully
2656 * disconnected. In that case, we won't be able to flush any data while
2657 * removing the namespaces' disks; fail all the queues now to avoid
2658 * potentially having to clean up the failed sync later.
2659 */
2660 if (ctrl->state == NVME_CTRL_DEAD)
2661 nvme_kill_queues(ctrl);
2662
5bae7f73
CH
2663 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2664 nvme_ns_remove(ns);
2665}
576d55d6 2666EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
5bae7f73 2667
e3d7874d
KB
2668static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
2669{
2670 char *envp[2] = { NULL, NULL };
2671 u32 aen_result = ctrl->aen_result;
2672
2673 ctrl->aen_result = 0;
2674 if (!aen_result)
2675 return;
2676
2677 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
2678 if (!envp[0])
2679 return;
2680 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
2681 kfree(envp[0]);
2682}
2683
f866fc42
CH
2684static void nvme_async_event_work(struct work_struct *work)
2685{
2686 struct nvme_ctrl *ctrl =
2687 container_of(work, struct nvme_ctrl, async_event_work);
2688
e3d7874d 2689 nvme_aen_uevent(ctrl);
ad22c355 2690 ctrl->ops->submit_async_event(ctrl);
f866fc42
CH
2691}
2692
b6dccf7f
AD
2693static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
2694{
2695
2696 u32 csts;
2697
2698 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
2699 return false;
2700
2701 if (csts == ~0)
2702 return false;
2703
2704 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
2705}
2706
2707static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
2708{
b6dccf7f
AD
2709 struct nvme_fw_slot_info_log *log;
2710
2711 log = kmalloc(sizeof(*log), GFP_KERNEL);
2712 if (!log)
2713 return;
2714
c627c487 2715 if (nvme_get_log(ctrl, NVME_LOG_FW_SLOT, log, sizeof(*log)))
b6dccf7f
AD
2716 dev_warn(ctrl->device,
2717 "Get FW SLOT INFO log error\n");
2718 kfree(log);
2719}
2720
2721static void nvme_fw_act_work(struct work_struct *work)
2722{
2723 struct nvme_ctrl *ctrl = container_of(work,
2724 struct nvme_ctrl, fw_act_work);
2725 unsigned long fw_act_timeout;
2726
2727 if (ctrl->mtfa)
2728 fw_act_timeout = jiffies +
2729 msecs_to_jiffies(ctrl->mtfa * 100);
2730 else
2731 fw_act_timeout = jiffies +
2732 msecs_to_jiffies(admin_timeout * 1000);
2733
2734 nvme_stop_queues(ctrl);
2735 while (nvme_ctrl_pp_status(ctrl)) {
2736 if (time_after(jiffies, fw_act_timeout)) {
2737 dev_warn(ctrl->device,
2738 "Fw activation timeout, reset controller\n");
2739 nvme_reset_ctrl(ctrl);
2740 break;
2741 }
2742 msleep(100);
2743 }
2744
2745 if (ctrl->state != NVME_CTRL_LIVE)
2746 return;
2747
2748 nvme_start_queues(ctrl);
a806c6c8 2749 /* read FW slot information to clear the AER */
b6dccf7f
AD
2750 nvme_get_fw_slot_info(ctrl);
2751}
2752
7bf58533
CH
2753void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2754 union nvme_result *res)
f866fc42 2755{
7bf58533 2756 u32 result = le32_to_cpu(res->u32);
f866fc42 2757
ad22c355 2758 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
f866fc42
CH
2759 return;
2760
e3d7874d
KB
2761 switch (result & 0x7) {
2762 case NVME_AER_ERROR:
2763 case NVME_AER_SMART:
2764 case NVME_AER_CSS:
2765 case NVME_AER_VS:
2766 ctrl->aen_result = result;
2767 break;
2768 default:
2769 break;
2770 }
2771
f866fc42
CH
2772 switch (result & 0xff07) {
2773 case NVME_AER_NOTICE_NS_CHANGED:
2774 dev_info(ctrl->device, "rescanning\n");
2775 nvme_queue_scan(ctrl);
2776 break;
b6dccf7f 2777 case NVME_AER_NOTICE_FW_ACT_STARTING:
1a40d972 2778 queue_work(nvme_wq, &ctrl->fw_act_work);
b6dccf7f 2779 break;
f866fc42
CH
2780 default:
2781 dev_warn(ctrl->device, "async event result %08x\n", result);
2782 }
ad22c355 2783 queue_work(nvme_wq, &ctrl->async_event_work);
f866fc42
CH
2784}
2785EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2786
d09f2b45 2787void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
576d55d6 2788{
d09f2b45 2789 nvme_stop_keep_alive(ctrl);
f866fc42 2790 flush_work(&ctrl->async_event_work);
5955be21 2791 flush_work(&ctrl->scan_work);
b6dccf7f 2792 cancel_work_sync(&ctrl->fw_act_work);
d09f2b45
SG
2793}
2794EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
2795
2796void nvme_start_ctrl(struct nvme_ctrl *ctrl)
2797{
2798 if (ctrl->kato)
2799 nvme_start_keep_alive(ctrl);
2800
2801 if (ctrl->queue_count > 1) {
2802 nvme_queue_scan(ctrl);
d99ca609 2803 queue_work(nvme_wq, &ctrl->async_event_work);
d09f2b45
SG
2804 nvme_start_queues(ctrl);
2805 }
2806}
2807EXPORT_SYMBOL_GPL(nvme_start_ctrl);
5955be21 2808
d09f2b45
SG
2809void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2810{
a6a5149b 2811 cdev_device_del(&ctrl->cdev, ctrl->device);
53029b04 2812}
576d55d6 2813EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
53029b04 2814
d22524a4 2815static void nvme_free_ctrl(struct device *dev)
53029b04 2816{
d22524a4
CH
2817 struct nvme_ctrl *ctrl =
2818 container_of(dev, struct nvme_ctrl, ctrl_device);
f3ca80fc 2819
9843f685 2820 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
075790eb 2821 ida_destroy(&ctrl->ns_ida);
84fef62d 2822 kfree(ctrl->effects);
f3ca80fc
CH
2823
2824 ctrl->ops->free_ctrl(ctrl);
2825}
2826
f3ca80fc
CH
2827/*
2828 * Initialize a NVMe controller structures. This needs to be called during
2829 * earliest initialization so that we have the initialized structured around
2830 * during probing.
2831 */
2832int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2833 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2834{
2835 int ret;
2836
bb8d261e
CH
2837 ctrl->state = NVME_CTRL_NEW;
2838 spin_lock_init(&ctrl->lock);
f3ca80fc 2839 INIT_LIST_HEAD(&ctrl->namespaces);
69d3b8ac 2840 mutex_init(&ctrl->namespaces_mutex);
f3ca80fc
CH
2841 ctrl->dev = dev;
2842 ctrl->ops = ops;
2843 ctrl->quirks = quirks;
5955be21 2844 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
f866fc42 2845 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
b6dccf7f 2846 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
c5017e85 2847 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
f3ca80fc 2848
9843f685
CH
2849 ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
2850 if (ret < 0)
f3ca80fc 2851 goto out;
9843f685 2852 ctrl->instance = ret;
f3ca80fc 2853
d22524a4
CH
2854 device_initialize(&ctrl->ctrl_device);
2855 ctrl->device = &ctrl->ctrl_device;
a6a5149b 2856 ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
d22524a4
CH
2857 ctrl->device->class = nvme_class;
2858 ctrl->device->parent = ctrl->dev;
2859 ctrl->device->groups = nvme_dev_attr_groups;
2860 ctrl->device->release = nvme_free_ctrl;
2861 dev_set_drvdata(ctrl->device, ctrl);
2862 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
2863 if (ret)
f3ca80fc 2864 goto out_release_instance;
a6a5149b
CH
2865
2866 cdev_init(&ctrl->cdev, &nvme_dev_fops);
2867 ctrl->cdev.owner = ops->module;
2868 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
d22524a4
CH
2869 if (ret)
2870 goto out_free_name;
2871
075790eb 2872 ida_init(&ctrl->ns_ida);
f3ca80fc 2873
c5552fde
AL
2874 /*
2875 * Initialize latency tolerance controls. The sysfs files won't
2876 * be visible to userspace unless the device actually supports APST.
2877 */
2878 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2879 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2880 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2881
f3ca80fc 2882 return 0;
d22524a4
CH
2883out_free_name:
2884 kfree_const(dev->kobj.name);
f3ca80fc 2885out_release_instance:
9843f685 2886 ida_simple_remove(&nvme_instance_ida, ctrl->instance);
f3ca80fc
CH
2887out:
2888 return ret;
2889}
576d55d6 2890EXPORT_SYMBOL_GPL(nvme_init_ctrl);
f3ca80fc 2891
69d9a99c
KB
2892/**
2893 * nvme_kill_queues(): Ends all namespace queues
2894 * @ctrl: the dead controller that needs to end
2895 *
2896 * Call this function when the driver determines it is unable to get the
2897 * controller in a state capable of servicing IO.
2898 */
2899void nvme_kill_queues(struct nvme_ctrl *ctrl)
2900{
2901 struct nvme_ns *ns;
2902
32f0c4af 2903 mutex_lock(&ctrl->namespaces_mutex);
82654b6b 2904
443bd90f 2905 /* Forcibly unquiesce queues to avoid blocking dispatch */
7dd1ab16
SB
2906 if (ctrl->admin_q)
2907 blk_mq_unquiesce_queue(ctrl->admin_q);
443bd90f 2908
32f0c4af 2909 list_for_each_entry(ns, &ctrl->namespaces, list) {
69d9a99c
KB
2910 /*
2911 * Revalidating a dead namespace sets capacity to 0. This will
2912 * end buffered writers dirtying pages that can't be synced.
2913 */
f33447b9
KB
2914 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2915 continue;
2916 revalidate_disk(ns->disk);
69d9a99c 2917 blk_set_queue_dying(ns->queue);
806f026f 2918
443bd90f
ML
2919 /* Forcibly unquiesce queues to avoid blocking dispatch */
2920 blk_mq_unquiesce_queue(ns->queue);
69d9a99c 2921 }
32f0c4af 2922 mutex_unlock(&ctrl->namespaces_mutex);
69d9a99c 2923}
237045fc 2924EXPORT_SYMBOL_GPL(nvme_kill_queues);
69d9a99c 2925
302ad8cc
KB
2926void nvme_unfreeze(struct nvme_ctrl *ctrl)
2927{
2928 struct nvme_ns *ns;
2929
2930 mutex_lock(&ctrl->namespaces_mutex);
2931 list_for_each_entry(ns, &ctrl->namespaces, list)
2932 blk_mq_unfreeze_queue(ns->queue);
2933 mutex_unlock(&ctrl->namespaces_mutex);
2934}
2935EXPORT_SYMBOL_GPL(nvme_unfreeze);
2936
2937void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2938{
2939 struct nvme_ns *ns;
2940
2941 mutex_lock(&ctrl->namespaces_mutex);
2942 list_for_each_entry(ns, &ctrl->namespaces, list) {
2943 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2944 if (timeout <= 0)
2945 break;
2946 }
2947 mutex_unlock(&ctrl->namespaces_mutex);
2948}
2949EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2950
2951void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2952{
2953 struct nvme_ns *ns;
2954
2955 mutex_lock(&ctrl->namespaces_mutex);
2956 list_for_each_entry(ns, &ctrl->namespaces, list)
2957 blk_mq_freeze_queue_wait(ns->queue);
2958 mutex_unlock(&ctrl->namespaces_mutex);
2959}
2960EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2961
2962void nvme_start_freeze(struct nvme_ctrl *ctrl)
2963{
2964 struct nvme_ns *ns;
2965
2966 mutex_lock(&ctrl->namespaces_mutex);
2967 list_for_each_entry(ns, &ctrl->namespaces, list)
1671d522 2968 blk_freeze_queue_start(ns->queue);
302ad8cc
KB
2969 mutex_unlock(&ctrl->namespaces_mutex);
2970}
2971EXPORT_SYMBOL_GPL(nvme_start_freeze);
2972
25646264 2973void nvme_stop_queues(struct nvme_ctrl *ctrl)
363c9aac
SG
2974{
2975 struct nvme_ns *ns;
2976
32f0c4af 2977 mutex_lock(&ctrl->namespaces_mutex);
a6eaa884 2978 list_for_each_entry(ns, &ctrl->namespaces, list)
3174dd33 2979 blk_mq_quiesce_queue(ns->queue);
32f0c4af 2980 mutex_unlock(&ctrl->namespaces_mutex);
363c9aac 2981}
576d55d6 2982EXPORT_SYMBOL_GPL(nvme_stop_queues);
363c9aac 2983
25646264 2984void nvme_start_queues(struct nvme_ctrl *ctrl)
363c9aac
SG
2985{
2986 struct nvme_ns *ns;
2987
32f0c4af 2988 mutex_lock(&ctrl->namespaces_mutex);
8d7b8faf 2989 list_for_each_entry(ns, &ctrl->namespaces, list)
f660174e 2990 blk_mq_unquiesce_queue(ns->queue);
32f0c4af 2991 mutex_unlock(&ctrl->namespaces_mutex);
363c9aac 2992}
576d55d6 2993EXPORT_SYMBOL_GPL(nvme_start_queues);
363c9aac 2994
31b84460
SG
2995int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set)
2996{
2997 if (!ctrl->ops->reinit_request)
2998 return 0;
2999
3000 return blk_mq_tagset_iter(set, set->driver_data,
3001 ctrl->ops->reinit_request);
3002}
3003EXPORT_SYMBOL_GPL(nvme_reinit_tagset);
3004
5bae7f73
CH
3005int __init nvme_core_init(void)
3006{
3007 int result;
3008
9a6327d2
SG
3009 nvme_wq = alloc_workqueue("nvme-wq",
3010 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
3011 if (!nvme_wq)
3012 return -ENOMEM;
3013
a6a5149b 3014 result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
f3ca80fc 3015 if (result < 0)
9a6327d2 3016 goto destroy_wq;
f3ca80fc
CH
3017
3018 nvme_class = class_create(THIS_MODULE, "nvme");
3019 if (IS_ERR(nvme_class)) {
3020 result = PTR_ERR(nvme_class);
3021 goto unregister_chrdev;
3022 }
3023
5bae7f73 3024 return 0;
f3ca80fc 3025
9a6327d2 3026unregister_chrdev:
a6a5149b 3027 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
9a6327d2
SG
3028destroy_wq:
3029 destroy_workqueue(nvme_wq);
f3ca80fc 3030 return result;
5bae7f73
CH
3031}
3032
3033void nvme_core_exit(void)
3034{
f3ca80fc 3035 class_destroy(nvme_class);
a6a5149b 3036 unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
9a6327d2 3037 destroy_workqueue(nvme_wq);
5bae7f73 3038}
576d55d6
ML
3039
3040MODULE_LICENSE("GPL");
3041MODULE_VERSION("1.0");
3042module_init(nvme_core_init);
3043module_exit(nvme_core_exit);