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