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