]> git.proxmox.com Git - mirror_ubuntu-zesty-kernel.git/blob - drivers/nvme/host/core.c
cdda12bd1676294e27c7261731443a77573d6b9c
[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->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 u8 prev_apsta;
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 prev_apsta = ctrl->apsta;
1481 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1482 if (force_apst && id->apsta) {
1483 dev_warn(ctrl->dev, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1484 ctrl->apsta = 1;
1485 } else {
1486 ctrl->apsta = 0;
1487 }
1488 } else {
1489 ctrl->apsta = id->apsta;
1490 }
1491 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1492
1493 if (ctrl->ops->is_fabrics) {
1494 ctrl->icdoff = le16_to_cpu(id->icdoff);
1495 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1496 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1497 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1498
1499 /*
1500 * In fabrics we need to verify the cntlid matches the
1501 * admin connect
1502 */
1503 if (ctrl->cntlid != le16_to_cpu(id->cntlid))
1504 ret = -EINVAL;
1505
1506 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1507 dev_err(ctrl->dev,
1508 "keep-alive support is mandatory for fabrics\n");
1509 ret = -EINVAL;
1510 }
1511 } else {
1512 ctrl->cntlid = le16_to_cpu(id->cntlid);
1513 }
1514
1515 kfree(id);
1516
1517 if (ctrl->apsta && !prev_apsta)
1518 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1519 else if (!ctrl->apsta && prev_apsta)
1520 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1521
1522 nvme_configure_apst(ctrl);
1523
1524 ctrl->identified = true;
1525
1526 return ret;
1527 }
1528 EXPORT_SYMBOL_GPL(nvme_init_identify);
1529
1530 static int nvme_dev_open(struct inode *inode, struct file *file)
1531 {
1532 struct nvme_ctrl *ctrl;
1533 int instance = iminor(inode);
1534 int ret = -ENODEV;
1535
1536 spin_lock(&dev_list_lock);
1537 list_for_each_entry(ctrl, &nvme_ctrl_list, node) {
1538 if (ctrl->instance != instance)
1539 continue;
1540
1541 if (!ctrl->admin_q) {
1542 ret = -EWOULDBLOCK;
1543 break;
1544 }
1545 if (!kref_get_unless_zero(&ctrl->kref))
1546 break;
1547 file->private_data = ctrl;
1548 ret = 0;
1549 break;
1550 }
1551 spin_unlock(&dev_list_lock);
1552
1553 return ret;
1554 }
1555
1556 static int nvme_dev_release(struct inode *inode, struct file *file)
1557 {
1558 nvme_put_ctrl(file->private_data);
1559 return 0;
1560 }
1561
1562 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1563 {
1564 struct nvme_ns *ns;
1565 int ret;
1566
1567 mutex_lock(&ctrl->namespaces_mutex);
1568 if (list_empty(&ctrl->namespaces)) {
1569 ret = -ENOTTY;
1570 goto out_unlock;
1571 }
1572
1573 ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1574 if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1575 dev_warn(ctrl->device,
1576 "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1577 ret = -EINVAL;
1578 goto out_unlock;
1579 }
1580
1581 dev_warn(ctrl->device,
1582 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1583 kref_get(&ns->kref);
1584 mutex_unlock(&ctrl->namespaces_mutex);
1585
1586 ret = nvme_user_cmd(ctrl, ns, argp);
1587 nvme_put_ns(ns);
1588 return ret;
1589
1590 out_unlock:
1591 mutex_unlock(&ctrl->namespaces_mutex);
1592 return ret;
1593 }
1594
1595 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1596 unsigned long arg)
1597 {
1598 struct nvme_ctrl *ctrl = file->private_data;
1599 void __user *argp = (void __user *)arg;
1600
1601 switch (cmd) {
1602 case NVME_IOCTL_ADMIN_CMD:
1603 return nvme_user_cmd(ctrl, NULL, argp);
1604 case NVME_IOCTL_IO_CMD:
1605 return nvme_dev_user_cmd(ctrl, argp);
1606 case NVME_IOCTL_RESET:
1607 dev_warn(ctrl->device, "resetting controller\n");
1608 return ctrl->ops->reset_ctrl(ctrl);
1609 case NVME_IOCTL_SUBSYS_RESET:
1610 return nvme_reset_subsystem(ctrl);
1611 case NVME_IOCTL_RESCAN:
1612 nvme_queue_scan(ctrl);
1613 return 0;
1614 default:
1615 return -ENOTTY;
1616 }
1617 }
1618
1619 static const struct file_operations nvme_dev_fops = {
1620 .owner = THIS_MODULE,
1621 .open = nvme_dev_open,
1622 .release = nvme_dev_release,
1623 .unlocked_ioctl = nvme_dev_ioctl,
1624 .compat_ioctl = nvme_dev_ioctl,
1625 };
1626
1627 static ssize_t nvme_sysfs_reset(struct device *dev,
1628 struct device_attribute *attr, const char *buf,
1629 size_t count)
1630 {
1631 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1632 int ret;
1633
1634 ret = ctrl->ops->reset_ctrl(ctrl);
1635 if (ret < 0)
1636 return ret;
1637 return count;
1638 }
1639 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
1640
1641 static ssize_t nvme_sysfs_rescan(struct device *dev,
1642 struct device_attribute *attr, const char *buf,
1643 size_t count)
1644 {
1645 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1646
1647 nvme_queue_scan(ctrl);
1648 return count;
1649 }
1650 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
1651
1652 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
1653 char *buf)
1654 {
1655 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1656 struct nvme_ctrl *ctrl = ns->ctrl;
1657 int serial_len = sizeof(ctrl->serial);
1658 int model_len = sizeof(ctrl->model);
1659
1660 if (memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1661 return sprintf(buf, "eui.%16phN\n", ns->uuid);
1662
1663 if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1664 return sprintf(buf, "eui.%8phN\n", ns->eui);
1665
1666 while (ctrl->serial[serial_len - 1] == ' ')
1667 serial_len--;
1668 while (ctrl->model[model_len - 1] == ' ')
1669 model_len--;
1670
1671 return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
1672 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
1673 }
1674 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
1675
1676 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
1677 char *buf)
1678 {
1679 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1680 return sprintf(buf, "%pU\n", ns->uuid);
1681 }
1682 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
1683
1684 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
1685 char *buf)
1686 {
1687 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1688 return sprintf(buf, "%8phd\n", ns->eui);
1689 }
1690 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
1691
1692 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
1693 char *buf)
1694 {
1695 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1696 return sprintf(buf, "%d\n", ns->ns_id);
1697 }
1698 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
1699
1700 static struct attribute *nvme_ns_attrs[] = {
1701 &dev_attr_wwid.attr,
1702 &dev_attr_uuid.attr,
1703 &dev_attr_eui.attr,
1704 &dev_attr_nsid.attr,
1705 NULL,
1706 };
1707
1708 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
1709 struct attribute *a, int n)
1710 {
1711 struct device *dev = container_of(kobj, struct device, kobj);
1712 struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
1713
1714 if (a == &dev_attr_uuid.attr) {
1715 if (!memchr_inv(ns->uuid, 0, sizeof(ns->uuid)))
1716 return 0;
1717 }
1718 if (a == &dev_attr_eui.attr) {
1719 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
1720 return 0;
1721 }
1722 return a->mode;
1723 }
1724
1725 static const struct attribute_group nvme_ns_attr_group = {
1726 .attrs = nvme_ns_attrs,
1727 .is_visible = nvme_ns_attrs_are_visible,
1728 };
1729
1730 #define nvme_show_str_function(field) \
1731 static ssize_t field##_show(struct device *dev, \
1732 struct device_attribute *attr, char *buf) \
1733 { \
1734 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1735 return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field); \
1736 } \
1737 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1738
1739 #define nvme_show_int_function(field) \
1740 static ssize_t field##_show(struct device *dev, \
1741 struct device_attribute *attr, char *buf) \
1742 { \
1743 struct nvme_ctrl *ctrl = dev_get_drvdata(dev); \
1744 return sprintf(buf, "%d\n", ctrl->field); \
1745 } \
1746 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
1747
1748 nvme_show_str_function(model);
1749 nvme_show_str_function(serial);
1750 nvme_show_str_function(firmware_rev);
1751 nvme_show_int_function(cntlid);
1752
1753 static ssize_t nvme_sysfs_delete(struct device *dev,
1754 struct device_attribute *attr, const char *buf,
1755 size_t count)
1756 {
1757 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1758
1759 if (device_remove_file_self(dev, attr))
1760 ctrl->ops->delete_ctrl(ctrl);
1761 return count;
1762 }
1763 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
1764
1765 static ssize_t nvme_sysfs_show_transport(struct device *dev,
1766 struct device_attribute *attr,
1767 char *buf)
1768 {
1769 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1770
1771 return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
1772 }
1773 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
1774
1775 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
1776 struct device_attribute *attr,
1777 char *buf)
1778 {
1779 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1780
1781 return snprintf(buf, PAGE_SIZE, "%s\n",
1782 ctrl->ops->get_subsysnqn(ctrl));
1783 }
1784 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
1785
1786 static ssize_t nvme_sysfs_show_address(struct device *dev,
1787 struct device_attribute *attr,
1788 char *buf)
1789 {
1790 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1791
1792 return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
1793 }
1794 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
1795
1796 static struct attribute *nvme_dev_attrs[] = {
1797 &dev_attr_reset_controller.attr,
1798 &dev_attr_rescan_controller.attr,
1799 &dev_attr_model.attr,
1800 &dev_attr_serial.attr,
1801 &dev_attr_firmware_rev.attr,
1802 &dev_attr_cntlid.attr,
1803 &dev_attr_delete_controller.attr,
1804 &dev_attr_transport.attr,
1805 &dev_attr_subsysnqn.attr,
1806 &dev_attr_address.attr,
1807 NULL
1808 };
1809
1810 #define CHECK_ATTR(ctrl, a, name) \
1811 if ((a) == &dev_attr_##name.attr && \
1812 !(ctrl)->ops->get_##name) \
1813 return 0
1814
1815 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
1816 struct attribute *a, int n)
1817 {
1818 struct device *dev = container_of(kobj, struct device, kobj);
1819 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1820
1821 if (a == &dev_attr_delete_controller.attr) {
1822 if (!ctrl->ops->delete_ctrl)
1823 return 0;
1824 }
1825
1826 CHECK_ATTR(ctrl, a, subsysnqn);
1827 CHECK_ATTR(ctrl, a, address);
1828
1829 return a->mode;
1830 }
1831
1832 static struct attribute_group nvme_dev_attrs_group = {
1833 .attrs = nvme_dev_attrs,
1834 .is_visible = nvme_dev_attrs_are_visible,
1835 };
1836
1837 static const struct attribute_group *nvme_dev_attr_groups[] = {
1838 &nvme_dev_attrs_group,
1839 NULL,
1840 };
1841
1842 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
1843 {
1844 struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
1845 struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
1846
1847 return nsa->ns_id - nsb->ns_id;
1848 }
1849
1850 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1851 {
1852 struct nvme_ns *ns, *ret = NULL;
1853
1854 mutex_lock(&ctrl->namespaces_mutex);
1855 list_for_each_entry(ns, &ctrl->namespaces, list) {
1856 if (ns->ns_id == nsid) {
1857 kref_get(&ns->kref);
1858 ret = ns;
1859 break;
1860 }
1861 if (ns->ns_id > nsid)
1862 break;
1863 }
1864 mutex_unlock(&ctrl->namespaces_mutex);
1865 return ret;
1866 }
1867
1868 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1869 {
1870 struct nvme_ns *ns;
1871 struct gendisk *disk;
1872 struct nvme_id_ns *id;
1873 char disk_name[DISK_NAME_LEN];
1874 int node = dev_to_node(ctrl->dev);
1875
1876 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
1877 if (!ns)
1878 return;
1879
1880 ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
1881 if (ns->instance < 0)
1882 goto out_free_ns;
1883
1884 ns->queue = blk_mq_init_queue(ctrl->tagset);
1885 if (IS_ERR(ns->queue))
1886 goto out_release_instance;
1887 queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
1888 ns->queue->queuedata = ns;
1889 ns->ctrl = ctrl;
1890
1891 kref_init(&ns->kref);
1892 ns->ns_id = nsid;
1893 ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
1894
1895 blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
1896 nvme_set_queue_limits(ctrl, ns->queue);
1897
1898 sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
1899
1900 if (nvme_revalidate_ns(ns, &id))
1901 goto out_free_queue;
1902
1903 if (nvme_nvm_ns_supported(ns, id) &&
1904 nvme_nvm_register(ns, disk_name, node)) {
1905 dev_warn(ctrl->dev, "%s: LightNVM init failure\n", __func__);
1906 goto out_free_id;
1907 }
1908
1909 disk = alloc_disk_node(0, node);
1910 if (!disk)
1911 goto out_free_id;
1912
1913 disk->fops = &nvme_fops;
1914 disk->private_data = ns;
1915 disk->queue = ns->queue;
1916 disk->flags = GENHD_FL_EXT_DEVT;
1917 memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
1918 ns->disk = disk;
1919
1920 __nvme_revalidate_disk(disk, id);
1921
1922 mutex_lock(&ctrl->namespaces_mutex);
1923 list_add_tail(&ns->list, &ctrl->namespaces);
1924 mutex_unlock(&ctrl->namespaces_mutex);
1925
1926 kref_get(&ctrl->kref);
1927
1928 kfree(id);
1929
1930 device_add_disk(ctrl->device, ns->disk);
1931 if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
1932 &nvme_ns_attr_group))
1933 pr_warn("%s: failed to create sysfs group for identification\n",
1934 ns->disk->disk_name);
1935 if (ns->ndev && nvme_nvm_register_sysfs(ns))
1936 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
1937 ns->disk->disk_name);
1938 return;
1939 out_free_id:
1940 kfree(id);
1941 out_free_queue:
1942 blk_cleanup_queue(ns->queue);
1943 out_release_instance:
1944 ida_simple_remove(&ctrl->ns_ida, ns->instance);
1945 out_free_ns:
1946 kfree(ns);
1947 }
1948
1949 static void nvme_ns_remove(struct nvme_ns *ns)
1950 {
1951 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
1952 return;
1953
1954 if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
1955 if (blk_get_integrity(ns->disk))
1956 blk_integrity_unregister(ns->disk);
1957 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
1958 &nvme_ns_attr_group);
1959 if (ns->ndev)
1960 nvme_nvm_unregister_sysfs(ns);
1961 del_gendisk(ns->disk);
1962 blk_mq_abort_requeue_list(ns->queue);
1963 blk_cleanup_queue(ns->queue);
1964 }
1965
1966 mutex_lock(&ns->ctrl->namespaces_mutex);
1967 list_del_init(&ns->list);
1968 mutex_unlock(&ns->ctrl->namespaces_mutex);
1969
1970 nvme_put_ns(ns);
1971 }
1972
1973 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
1974 {
1975 struct nvme_ns *ns;
1976
1977 ns = nvme_find_get_ns(ctrl, nsid);
1978 if (ns) {
1979 if (ns->disk && revalidate_disk(ns->disk))
1980 nvme_ns_remove(ns);
1981 nvme_put_ns(ns);
1982 } else
1983 nvme_alloc_ns(ctrl, nsid);
1984 }
1985
1986 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
1987 unsigned nsid)
1988 {
1989 struct nvme_ns *ns, *next;
1990
1991 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
1992 if (ns->ns_id > nsid)
1993 nvme_ns_remove(ns);
1994 }
1995 }
1996
1997 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
1998 {
1999 struct nvme_ns *ns;
2000 __le32 *ns_list;
2001 unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2002 int ret = 0;
2003
2004 ns_list = kzalloc(0x1000, GFP_KERNEL);
2005 if (!ns_list)
2006 return -ENOMEM;
2007
2008 for (i = 0; i < num_lists; i++) {
2009 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2010 if (ret)
2011 goto free;
2012
2013 for (j = 0; j < min(nn, 1024U); j++) {
2014 nsid = le32_to_cpu(ns_list[j]);
2015 if (!nsid)
2016 goto out;
2017
2018 nvme_validate_ns(ctrl, nsid);
2019
2020 while (++prev < nsid) {
2021 ns = nvme_find_get_ns(ctrl, prev);
2022 if (ns) {
2023 nvme_ns_remove(ns);
2024 nvme_put_ns(ns);
2025 }
2026 }
2027 }
2028 nn -= j;
2029 }
2030 out:
2031 nvme_remove_invalid_namespaces(ctrl, prev);
2032 free:
2033 kfree(ns_list);
2034 return ret;
2035 }
2036
2037 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2038 {
2039 unsigned i;
2040
2041 for (i = 1; i <= nn; i++)
2042 nvme_validate_ns(ctrl, i);
2043
2044 nvme_remove_invalid_namespaces(ctrl, nn);
2045 }
2046
2047 static void nvme_scan_work(struct work_struct *work)
2048 {
2049 struct nvme_ctrl *ctrl =
2050 container_of(work, struct nvme_ctrl, scan_work);
2051 struct nvme_id_ctrl *id;
2052 unsigned nn;
2053
2054 if (ctrl->state != NVME_CTRL_LIVE)
2055 return;
2056
2057 if (nvme_identify_ctrl(ctrl, &id))
2058 return;
2059
2060 nn = le32_to_cpu(id->nn);
2061 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2062 !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2063 if (!nvme_scan_ns_list(ctrl, nn))
2064 goto done;
2065 }
2066 nvme_scan_ns_sequential(ctrl, nn);
2067 done:
2068 mutex_lock(&ctrl->namespaces_mutex);
2069 list_sort(NULL, &ctrl->namespaces, ns_cmp);
2070 mutex_unlock(&ctrl->namespaces_mutex);
2071 kfree(id);
2072 }
2073
2074 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2075 {
2076 /*
2077 * Do not queue new scan work when a controller is reset during
2078 * removal.
2079 */
2080 if (ctrl->state == NVME_CTRL_LIVE)
2081 schedule_work(&ctrl->scan_work);
2082 }
2083 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2084
2085 /*
2086 * This function iterates the namespace list unlocked to allow recovery from
2087 * controller failure. It is up to the caller to ensure the namespace list is
2088 * not modified by scan work while this function is executing.
2089 */
2090 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2091 {
2092 struct nvme_ns *ns, *next;
2093
2094 /*
2095 * The dead states indicates the controller was not gracefully
2096 * disconnected. In that case, we won't be able to flush any data while
2097 * removing the namespaces' disks; fail all the queues now to avoid
2098 * potentially having to clean up the failed sync later.
2099 */
2100 if (ctrl->state == NVME_CTRL_DEAD)
2101 nvme_kill_queues(ctrl);
2102
2103 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2104 nvme_ns_remove(ns);
2105 }
2106 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2107
2108 static void nvme_async_event_work(struct work_struct *work)
2109 {
2110 struct nvme_ctrl *ctrl =
2111 container_of(work, struct nvme_ctrl, async_event_work);
2112
2113 spin_lock_irq(&ctrl->lock);
2114 while (ctrl->event_limit > 0) {
2115 int aer_idx = --ctrl->event_limit;
2116
2117 spin_unlock_irq(&ctrl->lock);
2118 ctrl->ops->submit_async_event(ctrl, aer_idx);
2119 spin_lock_irq(&ctrl->lock);
2120 }
2121 spin_unlock_irq(&ctrl->lock);
2122 }
2123
2124 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2125 union nvme_result *res)
2126 {
2127 u32 result = le32_to_cpu(res->u32);
2128 bool done = true;
2129
2130 switch (le16_to_cpu(status) >> 1) {
2131 case NVME_SC_SUCCESS:
2132 done = false;
2133 /*FALLTHRU*/
2134 case NVME_SC_ABORT_REQ:
2135 ++ctrl->event_limit;
2136 schedule_work(&ctrl->async_event_work);
2137 break;
2138 default:
2139 break;
2140 }
2141
2142 if (done)
2143 return;
2144
2145 switch (result & 0xff07) {
2146 case NVME_AER_NOTICE_NS_CHANGED:
2147 dev_info(ctrl->device, "rescanning\n");
2148 nvme_queue_scan(ctrl);
2149 break;
2150 default:
2151 dev_warn(ctrl->device, "async event result %08x\n", result);
2152 }
2153 }
2154 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2155
2156 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2157 {
2158 ctrl->event_limit = NVME_NR_AERS;
2159 schedule_work(&ctrl->async_event_work);
2160 }
2161 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2162
2163 static DEFINE_IDA(nvme_instance_ida);
2164
2165 static int nvme_set_instance(struct nvme_ctrl *ctrl)
2166 {
2167 int instance, error;
2168
2169 do {
2170 if (!ida_pre_get(&nvme_instance_ida, GFP_KERNEL))
2171 return -ENODEV;
2172
2173 spin_lock(&dev_list_lock);
2174 error = ida_get_new(&nvme_instance_ida, &instance);
2175 spin_unlock(&dev_list_lock);
2176 } while (error == -EAGAIN);
2177
2178 if (error)
2179 return -ENODEV;
2180
2181 ctrl->instance = instance;
2182 return 0;
2183 }
2184
2185 static void nvme_release_instance(struct nvme_ctrl *ctrl)
2186 {
2187 spin_lock(&dev_list_lock);
2188 ida_remove(&nvme_instance_ida, ctrl->instance);
2189 spin_unlock(&dev_list_lock);
2190 }
2191
2192 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2193 {
2194 flush_work(&ctrl->async_event_work);
2195 flush_work(&ctrl->scan_work);
2196 nvme_remove_namespaces(ctrl);
2197
2198 device_destroy(nvme_class, MKDEV(nvme_char_major, ctrl->instance));
2199
2200 spin_lock(&dev_list_lock);
2201 list_del(&ctrl->node);
2202 spin_unlock(&dev_list_lock);
2203 }
2204 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2205
2206 static void nvme_free_ctrl(struct kref *kref)
2207 {
2208 struct nvme_ctrl *ctrl = container_of(kref, struct nvme_ctrl, kref);
2209
2210 put_device(ctrl->device);
2211 nvme_release_instance(ctrl);
2212 ida_destroy(&ctrl->ns_ida);
2213
2214 ctrl->ops->free_ctrl(ctrl);
2215 }
2216
2217 void nvme_put_ctrl(struct nvme_ctrl *ctrl)
2218 {
2219 kref_put(&ctrl->kref, nvme_free_ctrl);
2220 }
2221 EXPORT_SYMBOL_GPL(nvme_put_ctrl);
2222
2223 /*
2224 * Initialize a NVMe controller structures. This needs to be called during
2225 * earliest initialization so that we have the initialized structured around
2226 * during probing.
2227 */
2228 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2229 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2230 {
2231 int ret;
2232
2233 ctrl->state = NVME_CTRL_NEW;
2234 spin_lock_init(&ctrl->lock);
2235 INIT_LIST_HEAD(&ctrl->namespaces);
2236 mutex_init(&ctrl->namespaces_mutex);
2237 kref_init(&ctrl->kref);
2238 ctrl->dev = dev;
2239 ctrl->ops = ops;
2240 ctrl->quirks = quirks;
2241 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2242 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2243
2244 ret = nvme_set_instance(ctrl);
2245 if (ret)
2246 goto out;
2247
2248 ctrl->device = device_create_with_groups(nvme_class, ctrl->dev,
2249 MKDEV(nvme_char_major, ctrl->instance),
2250 ctrl, nvme_dev_attr_groups,
2251 "nvme%d", ctrl->instance);
2252 if (IS_ERR(ctrl->device)) {
2253 ret = PTR_ERR(ctrl->device);
2254 goto out_release_instance;
2255 }
2256 get_device(ctrl->device);
2257 ida_init(&ctrl->ns_ida);
2258
2259 spin_lock(&dev_list_lock);
2260 list_add_tail(&ctrl->node, &nvme_ctrl_list);
2261 spin_unlock(&dev_list_lock);
2262
2263 /*
2264 * Initialize latency tolerance controls. The sysfs files won't
2265 * be visible to userspace unless the device actually supports APST.
2266 */
2267 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2268 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2269 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2270
2271 return 0;
2272 out_release_instance:
2273 nvme_release_instance(ctrl);
2274 out:
2275 return ret;
2276 }
2277 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2278
2279 /**
2280 * nvme_kill_queues(): Ends all namespace queues
2281 * @ctrl: the dead controller that needs to end
2282 *
2283 * Call this function when the driver determines it is unable to get the
2284 * controller in a state capable of servicing IO.
2285 */
2286 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2287 {
2288 struct nvme_ns *ns;
2289
2290 mutex_lock(&ctrl->namespaces_mutex);
2291 list_for_each_entry(ns, &ctrl->namespaces, list) {
2292 /*
2293 * Revalidating a dead namespace sets capacity to 0. This will
2294 * end buffered writers dirtying pages that can't be synced.
2295 */
2296 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2297 continue;
2298 revalidate_disk(ns->disk);
2299 blk_set_queue_dying(ns->queue);
2300 blk_mq_abort_requeue_list(ns->queue);
2301 blk_mq_start_stopped_hw_queues(ns->queue, true);
2302 }
2303 mutex_unlock(&ctrl->namespaces_mutex);
2304 }
2305 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2306
2307 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2308 {
2309 struct nvme_ns *ns;
2310
2311 mutex_lock(&ctrl->namespaces_mutex);
2312 list_for_each_entry(ns, &ctrl->namespaces, list)
2313 blk_mq_quiesce_queue(ns->queue);
2314 mutex_unlock(&ctrl->namespaces_mutex);
2315 }
2316 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2317
2318 void nvme_start_queues(struct nvme_ctrl *ctrl)
2319 {
2320 struct nvme_ns *ns;
2321
2322 mutex_lock(&ctrl->namespaces_mutex);
2323 list_for_each_entry(ns, &ctrl->namespaces, list) {
2324 blk_mq_start_stopped_hw_queues(ns->queue, true);
2325 blk_mq_kick_requeue_list(ns->queue);
2326 }
2327 mutex_unlock(&ctrl->namespaces_mutex);
2328 }
2329 EXPORT_SYMBOL_GPL(nvme_start_queues);
2330
2331 int __init nvme_core_init(void)
2332 {
2333 int result;
2334
2335 result = __register_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme",
2336 &nvme_dev_fops);
2337 if (result < 0)
2338 return result;
2339 else if (result > 0)
2340 nvme_char_major = result;
2341
2342 nvme_class = class_create(THIS_MODULE, "nvme");
2343 if (IS_ERR(nvme_class)) {
2344 result = PTR_ERR(nvme_class);
2345 goto unregister_chrdev;
2346 }
2347
2348 return 0;
2349
2350 unregister_chrdev:
2351 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2352 return result;
2353 }
2354
2355 void nvme_core_exit(void)
2356 {
2357 class_destroy(nvme_class);
2358 __unregister_chrdev(nvme_char_major, 0, NVME_MINORS, "nvme");
2359 }
2360
2361 MODULE_LICENSE("GPL");
2362 MODULE_VERSION("1.0");
2363 module_init(nvme_core_init);
2364 module_exit(nvme_core_exit);