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