1 // SPDX-License-Identifier: GPL-2.0
2 /*
3 * NVM Express device driver
4 * Copyright (c) 2011-2014, Intel Corporation.
5 */
6
7 #include <linux/blkdev.h>
8 #include <linux/blk-mq.h>
9 #include <linux/blk-integrity.h>
10 #include <linux/compat.h>
11 #include <linux/delay.h>
12 #include <linux/errno.h>
13 #include <linux/hdreg.h>
14 #include <linux/kernel.h>
15 #include <linux/module.h>
16 #include <linux/backing-dev.h>
17 #include <linux/slab.h>
18 #include <linux/types.h>
19 #include <linux/pr.h>
20 #include <linux/ptrace.h>
21 #include <linux/nvme_ioctl.h>
22 #include <linux/pm_qos.h>
23 #include <asm/unaligned.h>
24
25 #include "nvme.h"
26 #include "fabrics.h"
27 #include <linux/nvme-auth.h>
28
29 #define CREATE_TRACE_POINTS
30 #include "trace.h"
31
32 #define NVME_MINORS (1U << MINORBITS)
33
34 struct nvme_ns_info {
35 struct nvme_ns_ids ids;
36 u32 nsid;
37 __le32 anagrpid;
38 bool is_shared;
39 bool is_readonly;
40 bool is_ready;
41 bool is_removed;
42 };
43
44 unsigned int admin_timeout = 60;
45 module_param(admin_timeout, uint, 0644);
46 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
47 EXPORT_SYMBOL_GPL(admin_timeout);
48
49 unsigned int nvme_io_timeout = 30;
50 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
51 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
52 EXPORT_SYMBOL_GPL(nvme_io_timeout);
53
54 static unsigned char shutdown_timeout = 5;
55 module_param(shutdown_timeout, byte, 0644);
56 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
57
58 static u8 nvme_max_retries = 5;
59 module_param_named(max_retries, nvme_max_retries, byte, 0644);
60 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
61
62 static unsigned long default_ps_max_latency_us = 100000;
63 module_param(default_ps_max_latency_us, ulong, 0644);
64 MODULE_PARM_DESC(default_ps_max_latency_us,
65 "max power saving latency for new devices; use PM QOS to change per device");
66
67 static bool force_apst;
68 module_param(force_apst, bool, 0644);
69 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
70
71 static unsigned long apst_primary_timeout_ms = 100;
72 module_param(apst_primary_timeout_ms, ulong, 0644);
73 MODULE_PARM_DESC(apst_primary_timeout_ms,
74 "primary APST timeout in ms");
75
76 static unsigned long apst_secondary_timeout_ms = 2000;
77 module_param(apst_secondary_timeout_ms, ulong, 0644);
78 MODULE_PARM_DESC(apst_secondary_timeout_ms,
79 "secondary APST timeout in ms");
80
81 static unsigned long apst_primary_latency_tol_us = 15000;
82 module_param(apst_primary_latency_tol_us, ulong, 0644);
83 MODULE_PARM_DESC(apst_primary_latency_tol_us,
84 "primary APST latency tolerance in us");
85
86 static unsigned long apst_secondary_latency_tol_us = 100000;
87 module_param(apst_secondary_latency_tol_us, ulong, 0644);
88 MODULE_PARM_DESC(apst_secondary_latency_tol_us,
89 "secondary APST latency tolerance in us");
90
91 /*
92 * nvme_wq - hosts nvme related works that are not reset or delete
93 * nvme_reset_wq - hosts nvme reset works
94 * nvme_delete_wq - hosts nvme delete works
95 *
96 * nvme_wq will host works such as scan, aen handling, fw activation,
97 * keep-alive, periodic reconnects etc. nvme_reset_wq
98 * runs reset works which also flush works hosted on nvme_wq for
99 * serialization purposes. nvme_delete_wq host controller deletion
100 * works which flush reset works for serialization.
101 */
102 struct workqueue_struct *nvme_wq;
103 EXPORT_SYMBOL_GPL(nvme_wq);
104
105 struct workqueue_struct *nvme_reset_wq;
106 EXPORT_SYMBOL_GPL(nvme_reset_wq);
107
108 struct workqueue_struct *nvme_delete_wq;
109 EXPORT_SYMBOL_GPL(nvme_delete_wq);
110
111 static LIST_HEAD(nvme_subsystems);
112 DEFINE_MUTEX(nvme_subsystems_lock);
113
114 static DEFINE_IDA(nvme_instance_ida);
115 static dev_t nvme_ctrl_base_chr_devt;
116 static struct class *nvme_class;
117 static struct class *nvme_subsys_class;
118
119 static DEFINE_IDA(nvme_ns_chr_minor_ida);
120 static dev_t nvme_ns_chr_devt;
121 static struct class *nvme_ns_chr_class;
122
123 static void nvme_put_subsystem(struct nvme_subsystem *subsys);
124 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
125 unsigned nsid);
126 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
127 struct nvme_command *cmd);
128
nvme_queue_scan(struct nvme_ctrl * ctrl)129 void nvme_queue_scan(struct nvme_ctrl *ctrl)
130 {
131 /*
132 * Only new queue scan work when admin and IO queues are both alive
133 */
134 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE && ctrl->tagset)
135 queue_work(nvme_wq, &ctrl->scan_work);
136 }
137
138 /*
139 * Use this function to proceed with scheduling reset_work for a controller
140 * that had previously been set to the resetting state. This is intended for
141 * code paths that can't be interrupted by other reset attempts. A hot removal
142 * may prevent this from succeeding.
143 */
nvme_try_sched_reset(struct nvme_ctrl * ctrl)144 int nvme_try_sched_reset(struct nvme_ctrl *ctrl)
145 {
146 if (nvme_ctrl_state(ctrl) != NVME_CTRL_RESETTING)
147 return -EBUSY;
148 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
149 return -EBUSY;
150 return 0;
151 }
152 EXPORT_SYMBOL_GPL(nvme_try_sched_reset);
153
nvme_failfast_work(struct work_struct * work)154 static void nvme_failfast_work(struct work_struct *work)
155 {
156 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
157 struct nvme_ctrl, failfast_work);
158
159 if (nvme_ctrl_state(ctrl) != NVME_CTRL_CONNECTING)
160 return;
161
162 set_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
163 dev_info(ctrl->device, "failfast expired\n");
164 nvme_kick_requeue_lists(ctrl);
165 }
166
nvme_start_failfast_work(struct nvme_ctrl * ctrl)167 static inline void nvme_start_failfast_work(struct nvme_ctrl *ctrl)
168 {
169 if (!ctrl->opts || ctrl->opts->fast_io_fail_tmo == -1)
170 return;
171
172 schedule_delayed_work(&ctrl->failfast_work,
173 ctrl->opts->fast_io_fail_tmo * HZ);
174 }
175
nvme_stop_failfast_work(struct nvme_ctrl * ctrl)176 static inline void nvme_stop_failfast_work(struct nvme_ctrl *ctrl)
177 {
178 if (!ctrl->opts)
179 return;
180
181 cancel_delayed_work_sync(&ctrl->failfast_work);
182 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
183 }
184
185
nvme_reset_ctrl(struct nvme_ctrl * ctrl)186 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
187 {
188 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
189 return -EBUSY;
190 if (!queue_work(nvme_reset_wq, &ctrl->reset_work))
191 return -EBUSY;
192 return 0;
193 }
194 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
195
nvme_reset_ctrl_sync(struct nvme_ctrl * ctrl)196 int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
197 {
198 int ret;
199
200 ret = nvme_reset_ctrl(ctrl);
201 if (!ret) {
202 flush_work(&ctrl->reset_work);
203 if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE)
204 ret = -ENETRESET;
205 }
206
207 return ret;
208 }
209
nvme_do_delete_ctrl(struct nvme_ctrl * ctrl)210 static void nvme_do_delete_ctrl(struct nvme_ctrl *ctrl)
211 {
212 dev_info(ctrl->device,
213 "Removing ctrl: NQN \"%s\"\n", nvmf_ctrl_subsysnqn(ctrl));
214
215 flush_work(&ctrl->reset_work);
216 nvme_stop_ctrl(ctrl);
217 nvme_remove_namespaces(ctrl);
218 ctrl->ops->delete_ctrl(ctrl);
219 nvme_uninit_ctrl(ctrl);
220 }
221
nvme_delete_ctrl_work(struct work_struct * work)222 static void nvme_delete_ctrl_work(struct work_struct *work)
223 {
224 struct nvme_ctrl *ctrl =
225 container_of(work, struct nvme_ctrl, delete_work);
226
227 nvme_do_delete_ctrl(ctrl);
228 }
229
nvme_delete_ctrl(struct nvme_ctrl * ctrl)230 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
231 {
232 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
233 return -EBUSY;
234 if (!queue_work(nvme_delete_wq, &ctrl->delete_work))
235 return -EBUSY;
236 return 0;
237 }
238 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
239
nvme_delete_ctrl_sync(struct nvme_ctrl * ctrl)240 void nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
241 {
242 /*
243 * Keep a reference until nvme_do_delete_ctrl() complete,
244 * since ->delete_ctrl can free the controller.
245 */
246 nvme_get_ctrl(ctrl);
247 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
248 nvme_do_delete_ctrl(ctrl);
249 nvme_put_ctrl(ctrl);
250 }
251
nvme_error_status(u16 status)252 static blk_status_t nvme_error_status(u16 status)
253 {
254 switch (status & 0x7ff) {
255 case NVME_SC_SUCCESS:
256 return BLK_STS_OK;
257 case NVME_SC_CAP_EXCEEDED:
258 return BLK_STS_NOSPC;
259 case NVME_SC_LBA_RANGE:
260 case NVME_SC_CMD_INTERRUPTED:
261 case NVME_SC_NS_NOT_READY:
262 return BLK_STS_TARGET;
263 case NVME_SC_BAD_ATTRIBUTES:
264 case NVME_SC_ONCS_NOT_SUPPORTED:
265 case NVME_SC_INVALID_OPCODE:
266 case NVME_SC_INVALID_FIELD:
267 case NVME_SC_INVALID_NS:
268 return BLK_STS_NOTSUPP;
269 case NVME_SC_WRITE_FAULT:
270 case NVME_SC_READ_ERROR:
271 case NVME_SC_UNWRITTEN_BLOCK:
272 case NVME_SC_ACCESS_DENIED:
273 case NVME_SC_READ_ONLY:
274 case NVME_SC_COMPARE_FAILED:
275 return BLK_STS_MEDIUM;
276 case NVME_SC_GUARD_CHECK:
277 case NVME_SC_APPTAG_CHECK:
278 case NVME_SC_REFTAG_CHECK:
279 case NVME_SC_INVALID_PI:
280 return BLK_STS_PROTECTION;
281 case NVME_SC_RESERVATION_CONFLICT:
282 return BLK_STS_RESV_CONFLICT;
283 case NVME_SC_HOST_PATH_ERROR:
284 return BLK_STS_TRANSPORT;
285 case NVME_SC_ZONE_TOO_MANY_ACTIVE:
286 return BLK_STS_ZONE_ACTIVE_RESOURCE;
287 case NVME_SC_ZONE_TOO_MANY_OPEN:
288 return BLK_STS_ZONE_OPEN_RESOURCE;
289 default:
290 return BLK_STS_IOERR;
291 }
292 }
293
nvme_retry_req(struct request * req)294 static void nvme_retry_req(struct request *req)
295 {
296 unsigned long delay = 0;
297 u16 crd;
298
299 /* The mask and shift result must be <= 3 */
300 crd = (nvme_req(req)->status & NVME_SC_CRD) >> 11;
301 if (crd)
302 delay = nvme_req(req)->ctrl->crdt[crd - 1] * 100;
303
304 nvme_req(req)->retries++;
305 blk_mq_requeue_request(req, false);
306 blk_mq_delay_kick_requeue_list(req->q, delay);
307 }
308
nvme_log_error(struct request * req)309 static void nvme_log_error(struct request *req)
310 {
311 struct nvme_ns *ns = req->q->queuedata;
312 struct nvme_request *nr = nvme_req(req);
313
314 if (ns) {
315 pr_err_ratelimited("%s: %s(0x%x) @ LBA %llu, %llu blocks, %s (sct 0x%x / sc 0x%x) %s%s\n",
316 ns->disk ? ns->disk->disk_name : "?",
317 nvme_get_opcode_str(nr->cmd->common.opcode),
318 nr->cmd->common.opcode,
319 (unsigned long long)nvme_sect_to_lba(ns, blk_rq_pos(req)),
320 (unsigned long long)blk_rq_bytes(req) >> ns->lba_shift,
321 nvme_get_error_status_str(nr->status),
322 nr->status >> 8 & 7, /* Status Code Type */
323 nr->status & 0xff, /* Status Code */
324 nr->status & NVME_SC_MORE ? "MORE " : "",
325 nr->status & NVME_SC_DNR ? "DNR " : "");
326 return;
327 }
328
329 pr_err_ratelimited("%s: %s(0x%x), %s (sct 0x%x / sc 0x%x) %s%s\n",
330 dev_name(nr->ctrl->device),
331 nvme_get_admin_opcode_str(nr->cmd->common.opcode),
332 nr->cmd->common.opcode,
333 nvme_get_error_status_str(nr->status),
334 nr->status >> 8 & 7, /* Status Code Type */
335 nr->status & 0xff, /* Status Code */
336 nr->status & NVME_SC_MORE ? "MORE " : "",
337 nr->status & NVME_SC_DNR ? "DNR " : "");
338 }
339
340 enum nvme_disposition {
341 COMPLETE,
342 RETRY,
343 FAILOVER,
344 AUTHENTICATE,
345 };
346
nvme_decide_disposition(struct request * req)347 static inline enum nvme_disposition nvme_decide_disposition(struct request *req)
348 {
349 if (likely(nvme_req(req)->status == 0))
350 return COMPLETE;
351
352 if ((nvme_req(req)->status & 0x7ff) == NVME_SC_AUTH_REQUIRED)
353 return AUTHENTICATE;
354
355 if (blk_noretry_request(req) ||
356 (nvme_req(req)->status & NVME_SC_DNR) ||
357 nvme_req(req)->retries >= nvme_max_retries)
358 return COMPLETE;
359
360 if (req->cmd_flags & REQ_NVME_MPATH) {
361 if (nvme_is_path_error(nvme_req(req)->status) ||
362 blk_queue_dying(req->q))
363 return FAILOVER;
364 } else {
365 if (blk_queue_dying(req->q))
366 return COMPLETE;
367 }
368
369 return RETRY;
370 }
371
nvme_end_req_zoned(struct request * req)372 static inline void nvme_end_req_zoned(struct request *req)
373 {
374 if (IS_ENABLED(CONFIG_BLK_DEV_ZONED) &&
375 req_op(req) == REQ_OP_ZONE_APPEND)
376 req->__sector = nvme_lba_to_sect(req->q->queuedata,
377 le64_to_cpu(nvme_req(req)->result.u64));
378 }
379
nvme_end_req(struct request * req)380 void nvme_end_req(struct request *req)
381 {
382 blk_status_t status = nvme_error_status(nvme_req(req)->status);
383
384 if (unlikely(nvme_req(req)->status && !(req->rq_flags & RQF_QUIET)))
385 nvme_log_error(req);
386 nvme_end_req_zoned(req);
387 nvme_trace_bio_complete(req);
388 if (req->cmd_flags & REQ_NVME_MPATH)
389 nvme_mpath_end_request(req);
390 blk_mq_end_request(req, status);
391 }
392
nvme_complete_rq(struct request * req)393 void nvme_complete_rq(struct request *req)
394 {
395 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
396
397 trace_nvme_complete_rq(req);
398 nvme_cleanup_cmd(req);
399
400 /*
401 * Completions of long-running commands should not be able to
402 * defer sending of periodic keep alives, since the controller
403 * may have completed processing such commands a long time ago
404 * (arbitrarily close to command submission time).
405 * req->deadline - req->timeout is the command submission time
406 * in jiffies.
407 */
408 if (ctrl->kas &&
409 req->deadline - req->timeout >= ctrl->ka_last_check_time)
410 ctrl->comp_seen = true;
411
412 switch (nvme_decide_disposition(req)) {
413 case COMPLETE:
414 nvme_end_req(req);
415 return;
416 case RETRY:
417 nvme_retry_req(req);
418 return;
419 case FAILOVER:
420 nvme_failover_req(req);
421 return;
422 case AUTHENTICATE:
423 #ifdef CONFIG_NVME_AUTH
424 queue_work(nvme_wq, &ctrl->dhchap_auth_work);
425 nvme_retry_req(req);
426 #else
427 nvme_end_req(req);
428 #endif
429 return;
430 }
431 }
432 EXPORT_SYMBOL_GPL(nvme_complete_rq);
433
nvme_complete_batch_req(struct request * req)434 void nvme_complete_batch_req(struct request *req)
435 {
436 trace_nvme_complete_rq(req);
437 nvme_cleanup_cmd(req);
438 nvme_end_req_zoned(req);
439 }
440 EXPORT_SYMBOL_GPL(nvme_complete_batch_req);
441
442 /*
443 * Called to unwind from ->queue_rq on a failed command submission so that the
444 * multipathing code gets called to potentially failover to another path.
445 * The caller needs to unwind all transport specific resource allocations and
446 * must return propagate the return value.
447 */
nvme_host_path_error(struct request * req)448 blk_status_t nvme_host_path_error(struct request *req)
449 {
450 nvme_req(req)->status = NVME_SC_HOST_PATH_ERROR;
451 blk_mq_set_request_complete(req);
452 nvme_complete_rq(req);
453 return BLK_STS_OK;
454 }
455 EXPORT_SYMBOL_GPL(nvme_host_path_error);
456
nvme_cancel_request(struct request * req,void * data)457 bool nvme_cancel_request(struct request *req, void *data)
458 {
459 dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
460 "Cancelling I/O %d", req->tag);
461
462 /* don't abort one completed or idle request */
463 if (blk_mq_rq_state(req) != MQ_RQ_IN_FLIGHT)
464 return true;
465
466 nvme_req(req)->status = NVME_SC_HOST_ABORTED_CMD;
467 nvme_req(req)->flags |= NVME_REQ_CANCELLED;
468 blk_mq_complete_request(req);
469 return true;
470 }
471 EXPORT_SYMBOL_GPL(nvme_cancel_request);
472
nvme_cancel_tagset(struct nvme_ctrl * ctrl)473 void nvme_cancel_tagset(struct nvme_ctrl *ctrl)
474 {
475 if (ctrl->tagset) {
476 blk_mq_tagset_busy_iter(ctrl->tagset,
477 nvme_cancel_request, ctrl);
478 blk_mq_tagset_wait_completed_request(ctrl->tagset);
479 }
480 }
481 EXPORT_SYMBOL_GPL(nvme_cancel_tagset);
482
nvme_cancel_admin_tagset(struct nvme_ctrl * ctrl)483 void nvme_cancel_admin_tagset(struct nvme_ctrl *ctrl)
484 {
485 if (ctrl->admin_tagset) {
486 blk_mq_tagset_busy_iter(ctrl->admin_tagset,
487 nvme_cancel_request, ctrl);
488 blk_mq_tagset_wait_completed_request(ctrl->admin_tagset);
489 }
490 }
491 EXPORT_SYMBOL_GPL(nvme_cancel_admin_tagset);
492
nvme_change_ctrl_state(struct nvme_ctrl * ctrl,enum nvme_ctrl_state new_state)493 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
494 enum nvme_ctrl_state new_state)
495 {
496 enum nvme_ctrl_state old_state;
497 unsigned long flags;
498 bool changed = false;
499
500 spin_lock_irqsave(&ctrl->lock, flags);
501
502 old_state = nvme_ctrl_state(ctrl);
503 switch (new_state) {
504 case NVME_CTRL_LIVE:
505 switch (old_state) {
506 case NVME_CTRL_CONNECTING:
507 changed = true;
508 fallthrough;
509 default:
510 break;
511 }
512 break;
513 case NVME_CTRL_RESETTING:
514 switch (old_state) {
515 case NVME_CTRL_NEW:
516 case NVME_CTRL_LIVE:
517 changed = true;
518 fallthrough;
519 default:
520 break;
521 }
522 break;
523 case NVME_CTRL_CONNECTING:
524 switch (old_state) {
525 case NVME_CTRL_NEW:
526 case NVME_CTRL_RESETTING:
527 changed = true;
528 fallthrough;
529 default:
530 break;
531 }
532 break;
533 case NVME_CTRL_DELETING:
534 switch (old_state) {
535 case NVME_CTRL_LIVE:
536 case NVME_CTRL_RESETTING:
537 case NVME_CTRL_CONNECTING:
538 changed = true;
539 fallthrough;
540 default:
541 break;
542 }
543 break;
544 case NVME_CTRL_DELETING_NOIO:
545 switch (old_state) {
546 case NVME_CTRL_DELETING:
547 case NVME_CTRL_DEAD:
548 changed = true;
549 fallthrough;
550 default:
551 break;
552 }
553 break;
554 case NVME_CTRL_DEAD:
555 switch (old_state) {
556 case NVME_CTRL_DELETING:
557 changed = true;
558 fallthrough;
559 default:
560 break;
561 }
562 break;
563 default:
564 break;
565 }
566
567 if (changed) {
568 WRITE_ONCE(ctrl->state, new_state);
569 wake_up_all(&ctrl->state_wq);
570 }
571
572 spin_unlock_irqrestore(&ctrl->lock, flags);
573 if (!changed)
574 return false;
575
576 if (new_state == NVME_CTRL_LIVE) {
577 if (old_state == NVME_CTRL_CONNECTING)
578 nvme_stop_failfast_work(ctrl);
579 nvme_kick_requeue_lists(ctrl);
580 } else if (new_state == NVME_CTRL_CONNECTING &&
581 old_state == NVME_CTRL_RESETTING) {
582 nvme_start_failfast_work(ctrl);
583 }
584 return changed;
585 }
586 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
587
588 /*
589 * Waits for the controller state to be resetting, or returns false if it is
590 * not possible to ever transition to that state.
591 */
nvme_wait_reset(struct nvme_ctrl * ctrl)592 bool nvme_wait_reset(struct nvme_ctrl *ctrl)
593 {
594 wait_event(ctrl->state_wq,
595 nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING) ||
596 nvme_state_terminal(ctrl));
597 return nvme_ctrl_state(ctrl) == NVME_CTRL_RESETTING;
598 }
599 EXPORT_SYMBOL_GPL(nvme_wait_reset);
600
nvme_free_ns_head(struct kref * ref)601 static void nvme_free_ns_head(struct kref *ref)
602 {
603 struct nvme_ns_head *head =
604 container_of(ref, struct nvme_ns_head, ref);
605
606 nvme_mpath_remove_disk(head);
607 ida_free(&head->subsys->ns_ida, head->instance);
608 cleanup_srcu_struct(&head->srcu);
609 nvme_put_subsystem(head->subsys);
610 kfree(head);
611 }
612
nvme_tryget_ns_head(struct nvme_ns_head * head)613 bool nvme_tryget_ns_head(struct nvme_ns_head *head)
614 {
615 return kref_get_unless_zero(&head->ref);
616 }
617
nvme_put_ns_head(struct nvme_ns_head * head)618 void nvme_put_ns_head(struct nvme_ns_head *head)
619 {
620 kref_put(&head->ref, nvme_free_ns_head);
621 }
622
nvme_free_ns(struct kref * kref)623 static void nvme_free_ns(struct kref *kref)
624 {
625 struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
626
627 put_disk(ns->disk);
628 nvme_put_ns_head(ns->head);
629 nvme_put_ctrl(ns->ctrl);
630 kfree(ns);
631 }
632
nvme_get_ns(struct nvme_ns * ns)633 bool nvme_get_ns(struct nvme_ns *ns)
634 {
635 return kref_get_unless_zero(&ns->kref);
636 }
637
nvme_put_ns(struct nvme_ns * ns)638 void nvme_put_ns(struct nvme_ns *ns)
639 {
640 kref_put(&ns->kref, nvme_free_ns);
641 }
642 EXPORT_SYMBOL_NS_GPL(nvme_put_ns, NVME_TARGET_PASSTHRU);
643
nvme_clear_nvme_request(struct request * req)644 static inline void nvme_clear_nvme_request(struct request *req)
645 {
646 nvme_req(req)->status = 0;
647 nvme_req(req)->retries = 0;
648 nvme_req(req)->flags = 0;
649 req->rq_flags |= RQF_DONTPREP;
650 }
651
652 /* initialize a passthrough request */
nvme_init_request(struct request * req,struct nvme_command * cmd)653 void nvme_init_request(struct request *req, struct nvme_command *cmd)
654 {
655 if (req->q->queuedata)
656 req->timeout = NVME_IO_TIMEOUT;
657 else /* no queuedata implies admin queue */
658 req->timeout = NVME_ADMIN_TIMEOUT;
659
660 /* passthru commands should let the driver set the SGL flags */
661 cmd->common.flags &= ~NVME_CMD_SGL_ALL;
662
663 req->cmd_flags |= REQ_FAILFAST_DRIVER;
664 if (req->mq_hctx->type == HCTX_TYPE_POLL)
665 req->cmd_flags |= REQ_POLLED;
666 nvme_clear_nvme_request(req);
667 req->rq_flags |= RQF_QUIET;
668 memcpy(nvme_req(req)->cmd, cmd, sizeof(*cmd));
669 }
670 EXPORT_SYMBOL_GPL(nvme_init_request);
671
672 /*
673 * For something we're not in a state to send to the device the default action
674 * is to busy it and retry it after the controller state is recovered. However,
675 * if the controller is deleting or if anything is marked for failfast or
676 * nvme multipath it is immediately failed.
677 *
678 * Note: commands used to initialize the controller will be marked for failfast.
679 * Note: nvme cli/ioctl commands are marked for failfast.
680 */
nvme_fail_nonready_command(struct nvme_ctrl * ctrl,struct request * rq)681 blk_status_t nvme_fail_nonready_command(struct nvme_ctrl *ctrl,
682 struct request *rq)
683 {
684 enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
685
686 if (state != NVME_CTRL_DELETING_NOIO &&
687 state != NVME_CTRL_DELETING &&
688 state != NVME_CTRL_DEAD &&
689 !test_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags) &&
690 !blk_noretry_request(rq) && !(rq->cmd_flags & REQ_NVME_MPATH))
691 return BLK_STS_RESOURCE;
692
693 if (!(rq->rq_flags & RQF_DONTPREP))
694 nvme_clear_nvme_request(rq);
695
696 return nvme_host_path_error(rq);
697 }
698 EXPORT_SYMBOL_GPL(nvme_fail_nonready_command);
699
__nvme_check_ready(struct nvme_ctrl * ctrl,struct request * rq,bool queue_live)700 bool __nvme_check_ready(struct nvme_ctrl *ctrl, struct request *rq,
701 bool queue_live)
702 {
703 struct nvme_request *req = nvme_req(rq);
704
705 /*
706 * currently we have a problem sending passthru commands
707 * on the admin_q if the controller is not LIVE because we can't
708 * make sure that they are going out after the admin connect,
709 * controller enable and/or other commands in the initialization
710 * sequence. until the controller will be LIVE, fail with
711 * BLK_STS_RESOURCE so that they will be rescheduled.
712 */
713 if (rq->q == ctrl->admin_q && (req->flags & NVME_REQ_USERCMD))
714 return false;
715
716 if (ctrl->ops->flags & NVME_F_FABRICS) {
717 /*
718 * Only allow commands on a live queue, except for the connect
719 * command, which is require to set the queue live in the
720 * appropinquate states.
721 */
722 switch (nvme_ctrl_state(ctrl)) {
723 case NVME_CTRL_CONNECTING:
724 if (blk_rq_is_passthrough(rq) && nvme_is_fabrics(req->cmd) &&
725 (req->cmd->fabrics.fctype == nvme_fabrics_type_connect ||
726 req->cmd->fabrics.fctype == nvme_fabrics_type_auth_send ||
727 req->cmd->fabrics.fctype == nvme_fabrics_type_auth_receive))
728 return true;
729 break;
730 default:
731 break;
732 case NVME_CTRL_DEAD:
733 return false;
734 }
735 }
736
737 return queue_live;
738 }
739 EXPORT_SYMBOL_GPL(__nvme_check_ready);
740
nvme_setup_flush(struct nvme_ns * ns,struct nvme_command * cmnd)741 static inline void nvme_setup_flush(struct nvme_ns *ns,
742 struct nvme_command *cmnd)
743 {
744 memset(cmnd, 0, sizeof(*cmnd));
745 cmnd->common.opcode = nvme_cmd_flush;
746 cmnd->common.nsid = cpu_to_le32(ns->head->ns_id);
747 }
748
nvme_setup_discard(struct nvme_ns * ns,struct request * req,struct nvme_command * cmnd)749 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
750 struct nvme_command *cmnd)
751 {
752 unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
753 struct nvme_dsm_range *range;
754 struct bio *bio;
755
756 /*
757 * Some devices do not consider the DSM 'Number of Ranges' field when
758 * determining how much data to DMA. Always allocate memory for maximum
759 * number of segments to prevent device reading beyond end of buffer.
760 */
761 static const size_t alloc_size = sizeof(*range) * NVME_DSM_MAX_RANGES;
762
763 range = kzalloc(alloc_size, GFP_ATOMIC | __GFP_NOWARN);
764 if (!range) {
765 /*
766 * If we fail allocation our range, fallback to the controller
767 * discard page. If that's also busy, it's safe to return
768 * busy, as we know we can make progress once that's freed.
769 */
770 if (test_and_set_bit_lock(0, &ns->ctrl->discard_page_busy))
771 return BLK_STS_RESOURCE;
772
773 range = page_address(ns->ctrl->discard_page);
774 }
775
776 if (queue_max_discard_segments(req->q) == 1) {
777 u64 slba = nvme_sect_to_lba(ns, blk_rq_pos(req));
778 u32 nlb = blk_rq_sectors(req) >> (ns->lba_shift - 9);
779
780 range[0].cattr = cpu_to_le32(0);
781 range[0].nlb = cpu_to_le32(nlb);
782 range[0].slba = cpu_to_le64(slba);
783 n = 1;
784 } else {
785 __rq_for_each_bio(bio, req) {
786 u64 slba = nvme_sect_to_lba(ns, bio->bi_iter.bi_sector);
787 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
788
789 if (n < segments) {
790 range[n].cattr = cpu_to_le32(0);
791 range[n].nlb = cpu_to_le32(nlb);
792 range[n].slba = cpu_to_le64(slba);
793 }
794 n++;
795 }
796 }
797
798 if (WARN_ON_ONCE(n != segments)) {
799 if (virt_to_page(range) == ns->ctrl->discard_page)
800 clear_bit_unlock(0, &ns->ctrl->discard_page_busy);
801 else
802 kfree(range);
803 return BLK_STS_IOERR;
804 }
805
806 memset(cmnd, 0, sizeof(*cmnd));
807 cmnd->dsm.opcode = nvme_cmd_dsm;
808 cmnd->dsm.nsid = cpu_to_le32(ns->head->ns_id);
809 cmnd->dsm.nr = cpu_to_le32(segments - 1);
810 cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
811
812 bvec_set_virt(&req->special_vec, range, alloc_size);
813 req->rq_flags |= RQF_SPECIAL_PAYLOAD;
814
815 return BLK_STS_OK;
816 }
817
nvme_set_ref_tag(struct nvme_ns * ns,struct nvme_command * cmnd,struct request * req)818 static void nvme_set_ref_tag(struct nvme_ns *ns, struct nvme_command *cmnd,
819 struct request *req)
820 {
821 u32 upper, lower;
822 u64 ref48;
823
824 /* both rw and write zeroes share the same reftag format */
825 switch (ns->guard_type) {
826 case NVME_NVM_NS_16B_GUARD:
827 cmnd->rw.reftag = cpu_to_le32(t10_pi_ref_tag(req));
828 break;
829 case NVME_NVM_NS_64B_GUARD:
830 ref48 = ext_pi_ref_tag(req);
831 lower = lower_32_bits(ref48);
832 upper = upper_32_bits(ref48);
833
834 cmnd->rw.reftag = cpu_to_le32(lower);
835 cmnd->rw.cdw3 = cpu_to_le32(upper);
836 break;
837 default:
838 break;
839 }
840 }
841
nvme_setup_write_zeroes(struct nvme_ns * ns,struct request * req,struct nvme_command * cmnd)842 static inline blk_status_t nvme_setup_write_zeroes(struct nvme_ns *ns,
843 struct request *req, struct nvme_command *cmnd)
844 {
845 memset(cmnd, 0, sizeof(*cmnd));
846
847 if (ns->ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
848 return nvme_setup_discard(ns, req, cmnd);
849
850 cmnd->write_zeroes.opcode = nvme_cmd_write_zeroes;
851 cmnd->write_zeroes.nsid = cpu_to_le32(ns->head->ns_id);
852 cmnd->write_zeroes.slba =
853 cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
854 cmnd->write_zeroes.length =
855 cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
856
857 if (!(req->cmd_flags & REQ_NOUNMAP) && (ns->features & NVME_NS_DEAC))
858 cmnd->write_zeroes.control |= cpu_to_le16(NVME_WZ_DEAC);
859
860 if (nvme_ns_has_pi(ns)) {
861 cmnd->write_zeroes.control |= cpu_to_le16(NVME_RW_PRINFO_PRACT);
862
863 switch (ns->pi_type) {
864 case NVME_NS_DPS_PI_TYPE1:
865 case NVME_NS_DPS_PI_TYPE2:
866 nvme_set_ref_tag(ns, cmnd, req);
867 break;
868 }
869 }
870
871 return BLK_STS_OK;
872 }
873
nvme_setup_rw(struct nvme_ns * ns,struct request * req,struct nvme_command * cmnd,enum nvme_opcode op)874 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
875 struct request *req, struct nvme_command *cmnd,
876 enum nvme_opcode op)
877 {
878 u16 control = 0;
879 u32 dsmgmt = 0;
880
881 if (req->cmd_flags & REQ_FUA)
882 control |= NVME_RW_FUA;
883 if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
884 control |= NVME_RW_LR;
885
886 if (req->cmd_flags & REQ_RAHEAD)
887 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
888
889 cmnd->rw.opcode = op;
890 cmnd->rw.flags = 0;
891 cmnd->rw.nsid = cpu_to_le32(ns->head->ns_id);
892 cmnd->rw.cdw2 = 0;
893 cmnd->rw.cdw3 = 0;
894 cmnd->rw.metadata = 0;
895 cmnd->rw.slba = cpu_to_le64(nvme_sect_to_lba(ns, blk_rq_pos(req)));
896 cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
897 cmnd->rw.reftag = 0;
898 cmnd->rw.apptag = 0;
899 cmnd->rw.appmask = 0;
900
901 if (ns->ms) {
902 /*
903 * If formated with metadata, the block layer always provides a
904 * metadata buffer if CONFIG_BLK_DEV_INTEGRITY is enabled. Else
905 * we enable the PRACT bit for protection information or set the
906 * namespace capacity to zero to prevent any I/O.
907 */
908 if (!blk_integrity_rq(req)) {
909 if (WARN_ON_ONCE(!nvme_ns_has_pi(ns)))
910 return BLK_STS_NOTSUPP;
911 control |= NVME_RW_PRINFO_PRACT;
912 }
913
914 switch (ns->pi_type) {
915 case NVME_NS_DPS_PI_TYPE3:
916 control |= NVME_RW_PRINFO_PRCHK_GUARD;
917 break;
918 case NVME_NS_DPS_PI_TYPE1:
919 case NVME_NS_DPS_PI_TYPE2:
920 control |= NVME_RW_PRINFO_PRCHK_GUARD |
921 NVME_RW_PRINFO_PRCHK_REF;
922 if (op == nvme_cmd_zone_append)
923 control |= NVME_RW_APPEND_PIREMAP;
924 nvme_set_ref_tag(ns, cmnd, req);
925 break;
926 }
927 }
928
929 cmnd->rw.control = cpu_to_le16(control);
930 cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
931 return 0;
932 }
933
nvme_cleanup_cmd(struct request * req)934 void nvme_cleanup_cmd(struct request *req)
935 {
936 if (req->rq_flags & RQF_SPECIAL_PAYLOAD) {
937 struct nvme_ctrl *ctrl = nvme_req(req)->ctrl;
938
939 if (req->special_vec.bv_page == ctrl->discard_page)
940 clear_bit_unlock(0, &ctrl->discard_page_busy);
941 else
942 kfree(bvec_virt(&req->special_vec));
943 req->rq_flags &= ~RQF_SPECIAL_PAYLOAD;
944 }
945 }
946 EXPORT_SYMBOL_GPL(nvme_cleanup_cmd);
947
nvme_setup_cmd(struct nvme_ns * ns,struct request * req)948 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req)
949 {
950 struct nvme_command *cmd = nvme_req(req)->cmd;
951 blk_status_t ret = BLK_STS_OK;
952
953 if (!(req->rq_flags & RQF_DONTPREP))
954 nvme_clear_nvme_request(req);
955
956 switch (req_op(req)) {
957 case REQ_OP_DRV_IN:
958 case REQ_OP_DRV_OUT:
959 /* these are setup prior to execution in nvme_init_request() */
960 break;
961 case REQ_OP_FLUSH:
962 nvme_setup_flush(ns, cmd);
963 break;
964 case REQ_OP_ZONE_RESET_ALL:
965 case REQ_OP_ZONE_RESET:
966 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_RESET);
967 break;
968 case REQ_OP_ZONE_OPEN:
969 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_OPEN);
970 break;
971 case REQ_OP_ZONE_CLOSE:
972 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_CLOSE);
973 break;
974 case REQ_OP_ZONE_FINISH:
975 ret = nvme_setup_zone_mgmt_send(ns, req, cmd, NVME_ZONE_FINISH);
976 break;
977 case REQ_OP_WRITE_ZEROES:
978 ret = nvme_setup_write_zeroes(ns, req, cmd);
979 break;
980 case REQ_OP_DISCARD:
981 ret = nvme_setup_discard(ns, req, cmd);
982 break;
983 case REQ_OP_READ:
984 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_read);
985 break;
986 case REQ_OP_WRITE:
987 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_write);
988 break;
989 case REQ_OP_ZONE_APPEND:
990 ret = nvme_setup_rw(ns, req, cmd, nvme_cmd_zone_append);
991 break;
992 default:
993 WARN_ON_ONCE(1);
994 return BLK_STS_IOERR;
995 }
996
997 cmd->common.command_id = nvme_cid(req);
998 trace_nvme_setup_cmd(req, cmd);
999 return ret;
1000 }
1001 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
1002
1003 /*
1004 * Return values:
1005 * 0: success
1006 * >0: nvme controller's cqe status response
1007 * <0: kernel error in lieu of controller response
1008 */
nvme_execute_rq(struct request * rq,bool at_head)1009 int nvme_execute_rq(struct request *rq, bool at_head)
1010 {
1011 blk_status_t status;
1012
1013 status = blk_execute_rq(rq, at_head);
1014 if (nvme_req(rq)->flags & NVME_REQ_CANCELLED)
1015 return -EINTR;
1016 if (nvme_req(rq)->status)
1017 return nvme_req(rq)->status;
1018 return blk_status_to_errno(status);
1019 }
1020 EXPORT_SYMBOL_NS_GPL(nvme_execute_rq, NVME_TARGET_PASSTHRU);
1021
1022 /*
1023 * Returns 0 on success. If the result is negative, it's a Linux error code;
1024 * if the result is positive, it's an NVM Express status code
1025 */
__nvme_submit_sync_cmd(struct request_queue * q,struct nvme_command * cmd,union nvme_result * result,void * buffer,unsigned bufflen,int qid,int at_head,blk_mq_req_flags_t flags)1026 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1027 union nvme_result *result, void *buffer, unsigned bufflen,
1028 int qid, int at_head, blk_mq_req_flags_t flags)
1029 {
1030 struct request *req;
1031 int ret;
1032
1033 if (qid == NVME_QID_ANY)
1034 req = blk_mq_alloc_request(q, nvme_req_op(cmd), flags);
1035 else
1036 req = blk_mq_alloc_request_hctx(q, nvme_req_op(cmd), flags,
1037 qid - 1);
1038
1039 if (IS_ERR(req))
1040 return PTR_ERR(req);
1041 nvme_init_request(req, cmd);
1042
1043 if (buffer && bufflen) {
1044 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
1045 if (ret)
1046 goto out;
1047 }
1048
1049 ret = nvme_execute_rq(req, at_head);
1050 if (result && ret >= 0)
1051 *result = nvme_req(req)->result;
1052 out:
1053 blk_mq_free_request(req);
1054 return ret;
1055 }
1056 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
1057
nvme_submit_sync_cmd(struct request_queue * q,struct nvme_command * cmd,void * buffer,unsigned bufflen)1058 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
1059 void *buffer, unsigned bufflen)
1060 {
1061 return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen,
1062 NVME_QID_ANY, 0, 0);
1063 }
1064 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
1065
nvme_command_effects(struct nvme_ctrl * ctrl,struct nvme_ns * ns,u8 opcode)1066 u32 nvme_command_effects(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1067 {
1068 u32 effects = 0;
1069
1070 if (ns) {
1071 effects = le32_to_cpu(ns->head->effects->iocs[opcode]);
1072 if (effects & ~(NVME_CMD_EFFECTS_CSUPP | NVME_CMD_EFFECTS_LBCC))
1073 dev_warn_once(ctrl->device,
1074 "IO command:%02x has unusual effects:%08x\n",
1075 opcode, effects);
1076
1077 /*
1078 * NVME_CMD_EFFECTS_CSE_MASK causes a freeze all I/O queues,
1079 * which would deadlock when done on an I/O command. Note that
1080 * We already warn about an unusual effect above.
1081 */
1082 effects &= ~NVME_CMD_EFFECTS_CSE_MASK;
1083 } else {
1084 effects = le32_to_cpu(ctrl->effects->acs[opcode]);
1085 }
1086
1087 return effects;
1088 }
1089 EXPORT_SYMBOL_NS_GPL(nvme_command_effects, NVME_TARGET_PASSTHRU);
1090
nvme_passthru_start(struct nvme_ctrl * ctrl,struct nvme_ns * ns,u8 opcode)1091 u32 nvme_passthru_start(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u8 opcode)
1092 {
1093 u32 effects = nvme_command_effects(ctrl, ns, opcode);
1094
1095 /*
1096 * For simplicity, IO to all namespaces is quiesced even if the command
1097 * effects say only one namespace is affected.
1098 */
1099 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1100 mutex_lock(&ctrl->scan_lock);
1101 mutex_lock(&ctrl->subsys->lock);
1102 nvme_mpath_start_freeze(ctrl->subsys);
1103 nvme_mpath_wait_freeze(ctrl->subsys);
1104 nvme_start_freeze(ctrl);
1105 nvme_wait_freeze(ctrl);
1106 }
1107 return effects;
1108 }
1109 EXPORT_SYMBOL_NS_GPL(nvme_passthru_start, NVME_TARGET_PASSTHRU);
1110
nvme_passthru_end(struct nvme_ctrl * ctrl,struct nvme_ns * ns,u32 effects,struct nvme_command * cmd,int status)1111 void nvme_passthru_end(struct nvme_ctrl *ctrl, struct nvme_ns *ns, u32 effects,
1112 struct nvme_command *cmd, int status)
1113 {
1114 if (effects & NVME_CMD_EFFECTS_CSE_MASK) {
1115 nvme_unfreeze(ctrl);
1116 nvme_mpath_unfreeze(ctrl->subsys);
1117 mutex_unlock(&ctrl->subsys->lock);
1118 mutex_unlock(&ctrl->scan_lock);
1119 }
1120 if (effects & NVME_CMD_EFFECTS_CCC) {
1121 if (!test_and_set_bit(NVME_CTRL_DIRTY_CAPABILITY,
1122 &ctrl->flags)) {
1123 dev_info(ctrl->device,
1124 "controller capabilities changed, reset may be required to take effect.\n");
1125 }
1126 }
1127 if (effects & (NVME_CMD_EFFECTS_NIC | NVME_CMD_EFFECTS_NCC)) {
1128 nvme_queue_scan(ctrl);
1129 flush_work(&ctrl->scan_work);
1130 }
1131 if (ns)
1132 return;
1133
1134 switch (cmd->common.opcode) {
1135 case nvme_admin_set_features:
1136 switch (le32_to_cpu(cmd->common.cdw10) & 0xFF) {
1137 case NVME_FEAT_KATO:
1138 /*
1139 * Keep alive commands interval on the host should be
1140 * updated when KATO is modified by Set Features
1141 * commands.
1142 */
1143 if (!status)
1144 nvme_update_keep_alive(ctrl, cmd);
1145 break;
1146 default:
1147 break;
1148 }
1149 break;
1150 default:
1151 break;
1152 }
1153 }
1154 EXPORT_SYMBOL_NS_GPL(nvme_passthru_end, NVME_TARGET_PASSTHRU);
1155
1156 /*
1157 * Recommended frequency for KATO commands per NVMe 1.4 section 7.12.1:
1158 *
1159 * The host should send Keep Alive commands at half of the Keep Alive Timeout
1160 * accounting for transport roundtrip times [..].
1161 */
nvme_keep_alive_work_period(struct nvme_ctrl * ctrl)1162 static unsigned long nvme_keep_alive_work_period(struct nvme_ctrl *ctrl)
1163 {
1164 unsigned long delay = ctrl->kato * HZ / 2;
1165
1166 /*
1167 * When using Traffic Based Keep Alive, we need to run
1168 * nvme_keep_alive_work at twice the normal frequency, as one
1169 * command completion can postpone sending a keep alive command
1170 * by up to twice the delay between runs.
1171 */
1172 if (ctrl->ctratt & NVME_CTRL_ATTR_TBKAS)
1173 delay /= 2;
1174 return delay;
1175 }
1176
nvme_queue_keep_alive_work(struct nvme_ctrl * ctrl)1177 static void nvme_queue_keep_alive_work(struct nvme_ctrl *ctrl)
1178 {
1179 queue_delayed_work(nvme_wq, &ctrl->ka_work,
1180 nvme_keep_alive_work_period(ctrl));
1181 }
1182
nvme_keep_alive_end_io(struct request * rq,blk_status_t status)1183 static enum rq_end_io_ret nvme_keep_alive_end_io(struct request *rq,
1184 blk_status_t status)
1185 {
1186 struct nvme_ctrl *ctrl = rq->end_io_data;
1187 unsigned long rtt = jiffies - (rq->deadline - rq->timeout);
1188 unsigned long delay = nvme_keep_alive_work_period(ctrl);
1189 enum nvme_ctrl_state state = nvme_ctrl_state(ctrl);
1190
1191 /*
1192 * Subtract off the keepalive RTT so nvme_keep_alive_work runs
1193 * at the desired frequency.
1194 */
1195 if (rtt <= delay) {
1196 delay -= rtt;
1197 } else {
1198 dev_warn(ctrl->device, "long keepalive RTT (%u ms)\n",
1199 jiffies_to_msecs(rtt));
1200 delay = 0;
1201 }
1202
1203 blk_mq_free_request(rq);
1204
1205 if (status) {
1206 dev_err(ctrl->device,
1207 "failed nvme_keep_alive_end_io error=%d\n",
1208 status);
1209 return RQ_END_IO_NONE;
1210 }
1211
1212 ctrl->ka_last_check_time = jiffies;
1213 ctrl->comp_seen = false;
1214 if (state == NVME_CTRL_LIVE || state == NVME_CTRL_CONNECTING)
1215 queue_delayed_work(nvme_wq, &ctrl->ka_work, delay);
1216 return RQ_END_IO_NONE;
1217 }
1218
nvme_keep_alive_work(struct work_struct * work)1219 static void nvme_keep_alive_work(struct work_struct *work)
1220 {
1221 struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
1222 struct nvme_ctrl, ka_work);
1223 bool comp_seen = ctrl->comp_seen;
1224 struct request *rq;
1225
1226 ctrl->ka_last_check_time = jiffies;
1227
1228 if ((ctrl->ctratt & NVME_CTRL_ATTR_TBKAS) && comp_seen) {
1229 dev_dbg(ctrl->device,
1230 "reschedule traffic based keep-alive timer\n");
1231 ctrl->comp_seen = false;
1232 nvme_queue_keep_alive_work(ctrl);
1233 return;
1234 }
1235
1236 rq = blk_mq_alloc_request(ctrl->admin_q, nvme_req_op(&ctrl->ka_cmd),
1237 BLK_MQ_REQ_RESERVED | BLK_MQ_REQ_NOWAIT);
1238 if (IS_ERR(rq)) {
1239 /* allocation failure, reset the controller */
1240 dev_err(ctrl->device, "keep-alive failed: %ld\n", PTR_ERR(rq));
1241 nvme_reset_ctrl(ctrl);
1242 return;
1243 }
1244 nvme_init_request(rq, &ctrl->ka_cmd);
1245
1246 rq->timeout = ctrl->kato * HZ;
1247 rq->end_io = nvme_keep_alive_end_io;
1248 rq->end_io_data = ctrl;
1249 blk_execute_rq_nowait(rq, false);
1250 }
1251
nvme_start_keep_alive(struct nvme_ctrl * ctrl)1252 static void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
1253 {
1254 if (unlikely(ctrl->kato == 0))
1255 return;
1256
1257 nvme_queue_keep_alive_work(ctrl);
1258 }
1259
nvme_stop_keep_alive(struct nvme_ctrl * ctrl)1260 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
1261 {
1262 if (unlikely(ctrl->kato == 0))
1263 return;
1264
1265 cancel_delayed_work_sync(&ctrl->ka_work);
1266 }
1267 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
1268
nvme_update_keep_alive(struct nvme_ctrl * ctrl,struct nvme_command * cmd)1269 static void nvme_update_keep_alive(struct nvme_ctrl *ctrl,
1270 struct nvme_command *cmd)
1271 {
1272 unsigned int new_kato =
1273 DIV_ROUND_UP(le32_to_cpu(cmd->common.cdw11), 1000);
1274
1275 dev_info(ctrl->device,
1276 "keep alive interval updated from %u ms to %u ms\n",
1277 ctrl->kato * 1000 / 2, new_kato * 1000 / 2);
1278
1279 nvme_stop_keep_alive(ctrl);
1280 ctrl->kato = new_kato;
1281 nvme_start_keep_alive(ctrl);
1282 }
1283
1284 /*
1285 * In NVMe 1.0 the CNS field was just a binary controller or namespace
1286 * flag, thus sending any new CNS opcodes has a big chance of not working.
1287 * Qemu unfortunately had that bug after reporting a 1.1 version compliance
1288 * (but not for any later version).
1289 */
nvme_ctrl_limited_cns(struct nvme_ctrl * ctrl)1290 static bool nvme_ctrl_limited_cns(struct nvme_ctrl *ctrl)
1291 {
1292 if (ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)
1293 return ctrl->vs < NVME_VS(1, 2, 0);
1294 return ctrl->vs < NVME_VS(1, 1, 0);
1295 }
1296
nvme_identify_ctrl(struct nvme_ctrl * dev,struct nvme_id_ctrl ** id)1297 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
1298 {
1299 struct nvme_command c = { };
1300 int error;
1301
1302 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1303 c.identify.opcode = nvme_admin_identify;
1304 c.identify.cns = NVME_ID_CNS_CTRL;
1305
1306 *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
1307 if (!*id)
1308 return -ENOMEM;
1309
1310 error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
1311 sizeof(struct nvme_id_ctrl));
1312 if (error) {
1313 kfree(*id);
1314 *id = NULL;
1315 }
1316 return error;
1317 }
1318
nvme_process_ns_desc(struct nvme_ctrl * ctrl,struct nvme_ns_ids * ids,struct nvme_ns_id_desc * cur,bool * csi_seen)1319 static int nvme_process_ns_desc(struct nvme_ctrl *ctrl, struct nvme_ns_ids *ids,
1320 struct nvme_ns_id_desc *cur, bool *csi_seen)
1321 {
1322 const char *warn_str = "ctrl returned bogus length:";
1323 void *data = cur;
1324
1325 switch (cur->nidt) {
1326 case NVME_NIDT_EUI64:
1327 if (cur->nidl != NVME_NIDT_EUI64_LEN) {
1328 dev_warn(ctrl->device, "%s %d for NVME_NIDT_EUI64\n",
1329 warn_str, cur->nidl);
1330 return -1;
1331 }
1332 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1333 return NVME_NIDT_EUI64_LEN;
1334 memcpy(ids->eui64, data + sizeof(*cur), NVME_NIDT_EUI64_LEN);
1335 return NVME_NIDT_EUI64_LEN;
1336 case NVME_NIDT_NGUID:
1337 if (cur->nidl != NVME_NIDT_NGUID_LEN) {
1338 dev_warn(ctrl->device, "%s %d for NVME_NIDT_NGUID\n",
1339 warn_str, cur->nidl);
1340 return -1;
1341 }
1342 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1343 return NVME_NIDT_NGUID_LEN;
1344 memcpy(ids->nguid, data + sizeof(*cur), NVME_NIDT_NGUID_LEN);
1345 return NVME_NIDT_NGUID_LEN;
1346 case NVME_NIDT_UUID:
1347 if (cur->nidl != NVME_NIDT_UUID_LEN) {
1348 dev_warn(ctrl->device, "%s %d for NVME_NIDT_UUID\n",
1349 warn_str, cur->nidl);
1350 return -1;
1351 }
1352 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID)
1353 return NVME_NIDT_UUID_LEN;
1354 uuid_copy(&ids->uuid, data + sizeof(*cur));
1355 return NVME_NIDT_UUID_LEN;
1356 case NVME_NIDT_CSI:
1357 if (cur->nidl != NVME_NIDT_CSI_LEN) {
1358 dev_warn(ctrl->device, "%s %d for NVME_NIDT_CSI\n",
1359 warn_str, cur->nidl);
1360 return -1;
1361 }
1362 memcpy(&ids->csi, data + sizeof(*cur), NVME_NIDT_CSI_LEN);
1363 *csi_seen = true;
1364 return NVME_NIDT_CSI_LEN;
1365 default:
1366 /* Skip unknown types */
1367 return cur->nidl;
1368 }
1369 }
1370
nvme_identify_ns_descs(struct nvme_ctrl * ctrl,struct nvme_ns_info * info)1371 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl,
1372 struct nvme_ns_info *info)
1373 {
1374 struct nvme_command c = { };
1375 bool csi_seen = false;
1376 int status, pos, len;
1377 void *data;
1378
1379 if (ctrl->vs < NVME_VS(1, 3, 0) && !nvme_multi_css(ctrl))
1380 return 0;
1381 if (ctrl->quirks & NVME_QUIRK_NO_NS_DESC_LIST)
1382 return 0;
1383
1384 c.identify.opcode = nvme_admin_identify;
1385 c.identify.nsid = cpu_to_le32(info->nsid);
1386 c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
1387
1388 data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
1389 if (!data)
1390 return -ENOMEM;
1391
1392 status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
1393 NVME_IDENTIFY_DATA_SIZE);
1394 if (status) {
1395 dev_warn(ctrl->device,
1396 "Identify Descriptors failed (nsid=%u, status=0x%x)\n",
1397 info->nsid, status);
1398 goto free_data;
1399 }
1400
1401 for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
1402 struct nvme_ns_id_desc *cur = data + pos;
1403
1404 if (cur->nidl == 0)
1405 break;
1406
1407 len = nvme_process_ns_desc(ctrl, &info->ids, cur, &csi_seen);
1408 if (len < 0)
1409 break;
1410
1411 len += sizeof(*cur);
1412 }
1413
1414 if (nvme_multi_css(ctrl) && !csi_seen) {
1415 dev_warn(ctrl->device, "Command set not reported for nsid:%d\n",
1416 info->nsid);
1417 status = -EINVAL;
1418 }
1419
1420 free_data:
1421 kfree(data);
1422 return status;
1423 }
1424
nvme_identify_ns(struct nvme_ctrl * ctrl,unsigned nsid,struct nvme_id_ns ** id)1425 static int nvme_identify_ns(struct nvme_ctrl *ctrl, unsigned nsid,
1426 struct nvme_id_ns **id)
1427 {
1428 struct nvme_command c = { };
1429 int error;
1430
1431 /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
1432 c.identify.opcode = nvme_admin_identify;
1433 c.identify.nsid = cpu_to_le32(nsid);
1434 c.identify.cns = NVME_ID_CNS_NS;
1435
1436 *id = kmalloc(sizeof(**id), GFP_KERNEL);
1437 if (!*id)
1438 return -ENOMEM;
1439
1440 error = nvme_submit_sync_cmd(ctrl->admin_q, &c, *id, sizeof(**id));
1441 if (error) {
1442 dev_warn(ctrl->device, "Identify namespace failed (%d)\n", error);
1443 kfree(*id);
1444 *id = NULL;
1445 }
1446 return error;
1447 }
1448
nvme_ns_info_from_identify(struct nvme_ctrl * ctrl,struct nvme_ns_info * info)1449 static int nvme_ns_info_from_identify(struct nvme_ctrl *ctrl,
1450 struct nvme_ns_info *info)
1451 {
1452 struct nvme_ns_ids *ids = &info->ids;
1453 struct nvme_id_ns *id;
1454 int ret;
1455
1456 ret = nvme_identify_ns(ctrl, info->nsid, &id);
1457 if (ret)
1458 return ret;
1459
1460 if (id->ncap == 0) {
1461 /* namespace not allocated or attached */
1462 info->is_removed = true;
1463 ret = -ENODEV;
1464 goto error;
1465 }
1466
1467 info->anagrpid = id->anagrpid;
1468 info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
1469 info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
1470 info->is_ready = true;
1471 if (ctrl->quirks & NVME_QUIRK_BOGUS_NID) {
1472 dev_info(ctrl->device,
1473 "Ignoring bogus Namespace Identifiers\n");
1474 } else {
1475 if (ctrl->vs >= NVME_VS(1, 1, 0) &&
1476 !memchr_inv(ids->eui64, 0, sizeof(ids->eui64)))
1477 memcpy(ids->eui64, id->eui64, sizeof(ids->eui64));
1478 if (ctrl->vs >= NVME_VS(1, 2, 0) &&
1479 !memchr_inv(ids->nguid, 0, sizeof(ids->nguid)))
1480 memcpy(ids->nguid, id->nguid, sizeof(ids->nguid));
1481 }
1482
1483 error:
1484 kfree(id);
1485 return ret;
1486 }
1487
nvme_ns_info_from_id_cs_indep(struct nvme_ctrl * ctrl,struct nvme_ns_info * info)1488 static int nvme_ns_info_from_id_cs_indep(struct nvme_ctrl *ctrl,
1489 struct nvme_ns_info *info)
1490 {
1491 struct nvme_id_ns_cs_indep *id;
1492 struct nvme_command c = {
1493 .identify.opcode = nvme_admin_identify,
1494 .identify.nsid = cpu_to_le32(info->nsid),
1495 .identify.cns = NVME_ID_CNS_NS_CS_INDEP,
1496 };
1497 int ret;
1498
1499 id = kmalloc(sizeof(*id), GFP_KERNEL);
1500 if (!id)
1501 return -ENOMEM;
1502
1503 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
1504 if (!ret) {
1505 info->anagrpid = id->anagrpid;
1506 info->is_shared = id->nmic & NVME_NS_NMIC_SHARED;
1507 info->is_readonly = id->nsattr & NVME_NS_ATTR_RO;
1508 info->is_ready = id->nstat & NVME_NSTAT_NRDY;
1509 }
1510 kfree(id);
1511 return ret;
1512 }
1513
nvme_features(struct nvme_ctrl * dev,u8 op,unsigned int fid,unsigned int dword11,void * buffer,size_t buflen,u32 * result)1514 static int nvme_features(struct nvme_ctrl *dev, u8 op, unsigned int fid,
1515 unsigned int dword11, void *buffer, size_t buflen, u32 *result)
1516 {
1517 union nvme_result res = { 0 };
1518 struct nvme_command c = { };
1519 int ret;
1520
1521 c.features.opcode = op;
1522 c.features.fid = cpu_to_le32(fid);
1523 c.features.dword11 = cpu_to_le32(dword11);
1524
1525 ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
1526 buffer, buflen, NVME_QID_ANY, 0, 0);
1527 if (ret >= 0 && result)
1528 *result = le32_to_cpu(res.u32);
1529 return ret;
1530 }
1531
nvme_set_features(struct nvme_ctrl * dev,unsigned int fid,unsigned int dword11,void * buffer,size_t buflen,u32 * result)1532 int nvme_set_features(struct nvme_ctrl *dev, unsigned int fid,
1533 unsigned int dword11, void *buffer, size_t buflen,
1534 u32 *result)
1535 {
1536 return nvme_features(dev, nvme_admin_set_features, fid, dword11, buffer,
1537 buflen, result);
1538 }
1539 EXPORT_SYMBOL_GPL(nvme_set_features);
1540
nvme_get_features(struct nvme_ctrl * dev,unsigned int fid,unsigned int dword11,void * buffer,size_t buflen,u32 * result)1541 int nvme_get_features(struct nvme_ctrl *dev, unsigned int fid,
1542 unsigned int dword11, void *buffer, size_t buflen,
1543 u32 *result)
1544 {
1545 return nvme_features(dev, nvme_admin_get_features, fid, dword11, buffer,
1546 buflen, result);
1547 }
1548 EXPORT_SYMBOL_GPL(nvme_get_features);
1549
nvme_set_queue_count(struct nvme_ctrl * ctrl,int * count)1550 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
1551 {
1552 u32 q_count = (*count - 1) | ((*count - 1) << 16);
1553 u32 result;
1554 int status, nr_io_queues;
1555
1556 status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
1557 &result);
1558
1559 /*
1560 * It's either a kernel error or the host observed a connection
1561 * lost. In either case it's not possible communicate with the
1562 * controller and thus enter the error code path.
1563 */
1564 if (status < 0 || status == NVME_SC_HOST_PATH_ERROR)
1565 return status;
1566
1567 /*
1568 * Degraded controllers might return an error when setting the queue
1569 * count. We still want to be able to bring them online and offer
1570 * access to the admin queue, as that might be only way to fix them up.
1571 */
1572 if (status > 0) {
1573 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
1574 *count = 0;
1575 } else {
1576 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
1577 *count = min(*count, nr_io_queues);
1578 }
1579
1580 return 0;
1581 }
1582 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
1583
1584 #define NVME_AEN_SUPPORTED \
1585 (NVME_AEN_CFG_NS_ATTR | NVME_AEN_CFG_FW_ACT | \
1586 NVME_AEN_CFG_ANA_CHANGE | NVME_AEN_CFG_DISC_CHANGE)
1587
nvme_enable_aen(struct nvme_ctrl * ctrl)1588 static void nvme_enable_aen(struct nvme_ctrl *ctrl)
1589 {
1590 u32 result, supported_aens = ctrl->oaes & NVME_AEN_SUPPORTED;
1591 int status;
1592
1593 if (!supported_aens)
1594 return;
1595
1596 status = nvme_set_features(ctrl, NVME_FEAT_ASYNC_EVENT, supported_aens,
1597 NULL, 0, &result);
1598 if (status)
1599 dev_warn(ctrl->device, "Failed to configure AEN (cfg %x)\n",
1600 supported_aens);
1601
1602 queue_work(nvme_wq, &ctrl->async_event_work);
1603 }
1604
nvme_ns_open(struct nvme_ns * ns)1605 static int nvme_ns_open(struct nvme_ns *ns)
1606 {
1607
1608 /* should never be called due to GENHD_FL_HIDDEN */
1609 if (WARN_ON_ONCE(nvme_ns_head_multipath(ns->head)))
1610 goto fail;
1611 if (!nvme_get_ns(ns))
1612 goto fail;
1613 if (!try_module_get(ns->ctrl->ops->module))
1614 goto fail_put_ns;
1615
1616 return 0;
1617
1618 fail_put_ns:
1619 nvme_put_ns(ns);
1620 fail:
1621 return -ENXIO;
1622 }
1623
nvme_ns_release(struct nvme_ns * ns)1624 static void nvme_ns_release(struct nvme_ns *ns)
1625 {
1626
1627 module_put(ns->ctrl->ops->module);
1628 nvme_put_ns(ns);
1629 }
1630
nvme_open(struct gendisk * disk,blk_mode_t mode)1631 static int nvme_open(struct gendisk *disk, blk_mode_t mode)
1632 {
1633 return nvme_ns_open(disk->private_data);
1634 }
1635
nvme_release(struct gendisk * disk)1636 static void nvme_release(struct gendisk *disk)
1637 {
1638 nvme_ns_release(disk->private_data);
1639 }
1640
nvme_getgeo(struct block_device * bdev,struct hd_geometry * geo)1641 int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1642 {
1643 /* some standard values */
1644 geo->heads = 1 << 6;
1645 geo->sectors = 1 << 5;
1646 geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1647 return 0;
1648 }
1649
1650 #ifdef CONFIG_BLK_DEV_INTEGRITY
nvme_init_integrity(struct gendisk * disk,struct nvme_ns * ns,u32 max_integrity_segments)1651 static void nvme_init_integrity(struct gendisk *disk, struct nvme_ns *ns,
1652 u32 max_integrity_segments)
1653 {
1654 struct blk_integrity integrity = { };
1655
1656 switch (ns->pi_type) {
1657 case NVME_NS_DPS_PI_TYPE3:
1658 switch (ns->guard_type) {
1659 case NVME_NVM_NS_16B_GUARD:
1660 integrity.profile = &t10_pi_type3_crc;
1661 integrity.tag_size = sizeof(u16) + sizeof(u32);
1662 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1663 break;
1664 case NVME_NVM_NS_64B_GUARD:
1665 integrity.profile = &ext_pi_type3_crc64;
1666 integrity.tag_size = sizeof(u16) + 6;
1667 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1668 break;
1669 default:
1670 integrity.profile = NULL;
1671 break;
1672 }
1673 break;
1674 case NVME_NS_DPS_PI_TYPE1:
1675 case NVME_NS_DPS_PI_TYPE2:
1676 switch (ns->guard_type) {
1677 case NVME_NVM_NS_16B_GUARD:
1678 integrity.profile = &t10_pi_type1_crc;
1679 integrity.tag_size = sizeof(u16);
1680 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1681 break;
1682 case NVME_NVM_NS_64B_GUARD:
1683 integrity.profile = &ext_pi_type1_crc64;
1684 integrity.tag_size = sizeof(u16);
1685 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1686 break;
1687 default:
1688 integrity.profile = NULL;
1689 break;
1690 }
1691 break;
1692 default:
1693 integrity.profile = NULL;
1694 break;
1695 }
1696
1697 integrity.tuple_size = ns->ms;
1698 blk_integrity_register(disk, &integrity);
1699 blk_queue_max_integrity_segments(disk->queue, max_integrity_segments);
1700 }
1701 #else
nvme_init_integrity(struct gendisk * disk,struct nvme_ns * ns,u32 max_integrity_segments)1702 static void nvme_init_integrity(struct gendisk *disk, struct nvme_ns *ns,
1703 u32 max_integrity_segments)
1704 {
1705 }
1706 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1707
nvme_config_discard(struct gendisk * disk,struct nvme_ns * ns)1708 static void nvme_config_discard(struct gendisk *disk, struct nvme_ns *ns)
1709 {
1710 struct nvme_ctrl *ctrl = ns->ctrl;
1711 struct request_queue *queue = disk->queue;
1712 u32 size = queue_logical_block_size(queue);
1713
1714 if (ctrl->dmrsl && ctrl->dmrsl <= nvme_sect_to_lba(ns, UINT_MAX))
1715 ctrl->max_discard_sectors = nvme_lba_to_sect(ns, ctrl->dmrsl);
1716
1717 if (ctrl->max_discard_sectors == 0) {
1718 blk_queue_max_discard_sectors(queue, 0);
1719 return;
1720 }
1721
1722 BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1723 NVME_DSM_MAX_RANGES);
1724
1725 queue->limits.discard_granularity = size;
1726
1727 /* If discard is already enabled, don't reset queue limits */
1728 if (queue->limits.max_discard_sectors)
1729 return;
1730
1731 blk_queue_max_discard_sectors(queue, ctrl->max_discard_sectors);
1732 blk_queue_max_discard_segments(queue, ctrl->max_discard_segments);
1733
1734 if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1735 blk_queue_max_write_zeroes_sectors(queue, UINT_MAX);
1736 }
1737
nvme_ns_ids_equal(struct nvme_ns_ids * a,struct nvme_ns_ids * b)1738 static bool nvme_ns_ids_equal(struct nvme_ns_ids *a, struct nvme_ns_ids *b)
1739 {
1740 return uuid_equal(&a->uuid, &b->uuid) &&
1741 memcmp(&a->nguid, &b->nguid, sizeof(a->nguid)) == 0 &&
1742 memcmp(&a->eui64, &b->eui64, sizeof(a->eui64)) == 0 &&
1743 a->csi == b->csi;
1744 }
1745
nvme_init_ms(struct nvme_ns * ns,struct nvme_id_ns * id)1746 static int nvme_init_ms(struct nvme_ns *ns, struct nvme_id_ns *id)
1747 {
1748 bool first = id->dps & NVME_NS_DPS_PI_FIRST;
1749 unsigned lbaf = nvme_lbaf_index(id->flbas);
1750 struct nvme_ctrl *ctrl = ns->ctrl;
1751 struct nvme_command c = { };
1752 struct nvme_id_ns_nvm *nvm;
1753 int ret = 0;
1754 u32 elbaf;
1755
1756 ns->pi_size = 0;
1757 ns->ms = le16_to_cpu(id->lbaf[lbaf].ms);
1758 if (!(ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)) {
1759 ns->pi_size = sizeof(struct t10_pi_tuple);
1760 ns->guard_type = NVME_NVM_NS_16B_GUARD;
1761 goto set_pi;
1762 }
1763
1764 nvm = kzalloc(sizeof(*nvm), GFP_KERNEL);
1765 if (!nvm)
1766 return -ENOMEM;
1767
1768 c.identify.opcode = nvme_admin_identify;
1769 c.identify.nsid = cpu_to_le32(ns->head->ns_id);
1770 c.identify.cns = NVME_ID_CNS_CS_NS;
1771 c.identify.csi = NVME_CSI_NVM;
1772
1773 ret = nvme_submit_sync_cmd(ns->ctrl->admin_q, &c, nvm, sizeof(*nvm));
1774 if (ret)
1775 goto free_data;
1776
1777 elbaf = le32_to_cpu(nvm->elbaf[lbaf]);
1778
1779 /* no support for storage tag formats right now */
1780 if (nvme_elbaf_sts(elbaf))
1781 goto free_data;
1782
1783 ns->guard_type = nvme_elbaf_guard_type(elbaf);
1784 switch (ns->guard_type) {
1785 case NVME_NVM_NS_64B_GUARD:
1786 ns->pi_size = sizeof(struct crc64_pi_tuple);
1787 break;
1788 case NVME_NVM_NS_16B_GUARD:
1789 ns->pi_size = sizeof(struct t10_pi_tuple);
1790 break;
1791 default:
1792 break;
1793 }
1794
1795 free_data:
1796 kfree(nvm);
1797 set_pi:
1798 if (ns->pi_size && (first || ns->ms == ns->pi_size))
1799 ns->pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1800 else
1801 ns->pi_type = 0;
1802
1803 return ret;
1804 }
1805
nvme_configure_metadata(struct nvme_ns * ns,struct nvme_id_ns * id)1806 static int nvme_configure_metadata(struct nvme_ns *ns, struct nvme_id_ns *id)
1807 {
1808 struct nvme_ctrl *ctrl = ns->ctrl;
1809 int ret;
1810
1811 ret = nvme_init_ms(ns, id);
1812 if (ret)
1813 return ret;
1814
1815 ns->features &= ~(NVME_NS_METADATA_SUPPORTED | NVME_NS_EXT_LBAS);
1816 if (!ns->ms || !(ctrl->ops->flags & NVME_F_METADATA_SUPPORTED))
1817 return 0;
1818
1819 if (ctrl->ops->flags & NVME_F_FABRICS) {
1820 /*
1821 * The NVMe over Fabrics specification only supports metadata as
1822 * part of the extended data LBA. We rely on HCA/HBA support to
1823 * remap the separate metadata buffer from the block layer.
1824 */
1825 if (WARN_ON_ONCE(!(id->flbas & NVME_NS_FLBAS_META_EXT)))
1826 return 0;
1827
1828 ns->features |= NVME_NS_EXT_LBAS;
1829
1830 /*
1831 * The current fabrics transport drivers support namespace
1832 * metadata formats only if nvme_ns_has_pi() returns true.
1833 * Suppress support for all other formats so the namespace will
1834 * have a 0 capacity and not be usable through the block stack.
1835 *
1836 * Note, this check will need to be modified if any drivers
1837 * gain the ability to use other metadata formats.
1838 */
1839 if (ctrl->max_integrity_segments && nvme_ns_has_pi(ns))
1840 ns->features |= NVME_NS_METADATA_SUPPORTED;
1841 } else {
1842 /*
1843 * For PCIe controllers, we can't easily remap the separate
1844 * metadata buffer from the block layer and thus require a
1845 * separate metadata buffer for block layer metadata/PI support.
1846 * We allow extended LBAs for the passthrough interface, though.
1847 */
1848 if (id->flbas & NVME_NS_FLBAS_META_EXT)
1849 ns->features |= NVME_NS_EXT_LBAS;
1850 else
1851 ns->features |= NVME_NS_METADATA_SUPPORTED;
1852 }
1853 return 0;
1854 }
1855
nvme_set_queue_limits(struct nvme_ctrl * ctrl,struct request_queue * q)1856 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1857 struct request_queue *q)
1858 {
1859 bool vwc = ctrl->vwc & NVME_CTRL_VWC_PRESENT;
1860
1861 if (ctrl->max_hw_sectors) {
1862 u32 max_segments =
1863 (ctrl->max_hw_sectors / (NVME_CTRL_PAGE_SIZE >> 9)) + 1;
1864
1865 max_segments = min_not_zero(max_segments, ctrl->max_segments);
1866 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1867 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1868 }
1869 blk_queue_virt_boundary(q, NVME_CTRL_PAGE_SIZE - 1);
1870 blk_queue_dma_alignment(q, 3);
1871 blk_queue_write_cache(q, vwc, vwc);
1872 }
1873
nvme_update_disk_info(struct gendisk * disk,struct nvme_ns * ns,struct nvme_id_ns * id)1874 static void nvme_update_disk_info(struct gendisk *disk,
1875 struct nvme_ns *ns, struct nvme_id_ns *id)
1876 {
1877 sector_t capacity = nvme_lba_to_sect(ns, le64_to_cpu(id->nsze));
1878 u32 bs = 1U << ns->lba_shift;
1879 u32 atomic_bs, phys_bs, io_opt = 0;
1880
1881 /*
1882 * The block layer can't support LBA sizes larger than the page size
1883 * or smaller than a sector size yet, so catch this early and don't
1884 * allow block I/O.
1885 */
1886 if (ns->lba_shift > PAGE_SHIFT || ns->lba_shift < SECTOR_SHIFT) {
1887 capacity = 0;
1888 bs = (1 << 9);
1889 }
1890
1891 blk_integrity_unregister(disk);
1892
1893 atomic_bs = phys_bs = bs;
1894 if (id->nabo == 0) {
1895 /*
1896 * Bit 1 indicates whether NAWUPF is defined for this namespace
1897 * and whether it should be used instead of AWUPF. If NAWUPF ==
1898 * 0 then AWUPF must be used instead.
1899 */
1900 if (id->nsfeat & NVME_NS_FEAT_ATOMICS && id->nawupf)
1901 atomic_bs = (1 + le16_to_cpu(id->nawupf)) * bs;
1902 else
1903 atomic_bs = (1 + ns->ctrl->subsys->awupf) * bs;
1904 }
1905
1906 if (id->nsfeat & NVME_NS_FEAT_IO_OPT) {
1907 /* NPWG = Namespace Preferred Write Granularity */
1908 phys_bs = bs * (1 + le16_to_cpu(id->npwg));
1909 /* NOWS = Namespace Optimal Write Size */
1910 io_opt = bs * (1 + le16_to_cpu(id->nows));
1911 }
1912
1913 blk_queue_logical_block_size(disk->queue, bs);
1914 /*
1915 * Linux filesystems assume writing a single physical block is
1916 * an atomic operation. Hence limit the physical block size to the
1917 * value of the Atomic Write Unit Power Fail parameter.
1918 */
1919 blk_queue_physical_block_size(disk->queue, min(phys_bs, atomic_bs));
1920 blk_queue_io_min(disk->queue, phys_bs);
1921 blk_queue_io_opt(disk->queue, io_opt);
1922
1923 /*
1924 * Register a metadata profile for PI, or the plain non-integrity NVMe
1925 * metadata masquerading as Type 0 if supported, otherwise reject block
1926 * I/O to namespaces with metadata except when the namespace supports
1927 * PI, as it can strip/insert in that case.
1928 */
1929 if (ns->ms) {
1930 if (IS_ENABLED(CONFIG_BLK_DEV_INTEGRITY) &&
1931 (ns->features & NVME_NS_METADATA_SUPPORTED))
1932 nvme_init_integrity(disk, ns,
1933 ns->ctrl->max_integrity_segments);
1934 else if (!nvme_ns_has_pi(ns))
1935 capacity = 0;
1936 }
1937
1938 set_capacity_and_notify(disk, capacity);
1939
1940 nvme_config_discard(disk, ns);
1941 blk_queue_max_write_zeroes_sectors(disk->queue,
1942 ns->ctrl->max_zeroes_sectors);
1943 }
1944
nvme_ns_is_readonly(struct nvme_ns * ns,struct nvme_ns_info * info)1945 static bool nvme_ns_is_readonly(struct nvme_ns *ns, struct nvme_ns_info *info)
1946 {
1947 return info->is_readonly || test_bit(NVME_NS_FORCE_RO, &ns->flags);
1948 }
1949
nvme_first_scan(struct gendisk * disk)1950 static inline bool nvme_first_scan(struct gendisk *disk)
1951 {
1952 /* nvme_alloc_ns() scans the disk prior to adding it */
1953 return !disk_live(disk);
1954 }
1955
nvme_set_chunk_sectors(struct nvme_ns * ns,struct nvme_id_ns * id)1956 static void nvme_set_chunk_sectors(struct nvme_ns *ns, struct nvme_id_ns *id)
1957 {
1958 struct nvme_ctrl *ctrl = ns->ctrl;
1959 u32 iob;
1960
1961 if ((ctrl->quirks & NVME_QUIRK_STRIPE_SIZE) &&
1962 is_power_of_2(ctrl->max_hw_sectors))
1963 iob = ctrl->max_hw_sectors;
1964 else
1965 iob = nvme_lba_to_sect(ns, le16_to_cpu(id->noiob));
1966
1967 if (!iob)
1968 return;
1969
1970 if (!is_power_of_2(iob)) {
1971 if (nvme_first_scan(ns->disk))
1972 pr_warn("%s: ignoring unaligned IO boundary:%u\n",
1973 ns->disk->disk_name, iob);
1974 return;
1975 }
1976
1977 if (blk_queue_is_zoned(ns->disk->queue)) {
1978 if (nvme_first_scan(ns->disk))
1979 pr_warn("%s: ignoring zoned namespace IO boundary\n",
1980 ns->disk->disk_name);
1981 return;
1982 }
1983
1984 blk_queue_chunk_sectors(ns->queue, iob);
1985 }
1986
nvme_update_ns_info_generic(struct nvme_ns * ns,struct nvme_ns_info * info)1987 static int nvme_update_ns_info_generic(struct nvme_ns *ns,
1988 struct nvme_ns_info *info)
1989 {
1990 blk_mq_freeze_queue(ns->disk->queue);
1991 nvme_set_queue_limits(ns->ctrl, ns->queue);
1992 set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
1993 blk_mq_unfreeze_queue(ns->disk->queue);
1994
1995 if (nvme_ns_head_multipath(ns->head)) {
1996 blk_mq_freeze_queue(ns->head->disk->queue);
1997 set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info));
1998 nvme_mpath_revalidate_paths(ns);
1999 blk_stack_limits(&ns->head->disk->queue->limits,
2000 &ns->queue->limits, 0);
2001 ns->head->disk->flags |= GENHD_FL_HIDDEN;
2002 blk_mq_unfreeze_queue(ns->head->disk->queue);
2003 }
2004
2005 /* Hide the block-interface for these devices */
2006 ns->disk->flags |= GENHD_FL_HIDDEN;
2007 set_bit(NVME_NS_READY, &ns->flags);
2008
2009 return 0;
2010 }
2011
nvme_update_ns_info_block(struct nvme_ns * ns,struct nvme_ns_info * info)2012 static int nvme_update_ns_info_block(struct nvme_ns *ns,
2013 struct nvme_ns_info *info)
2014 {
2015 struct nvme_id_ns *id;
2016 unsigned lbaf;
2017 int ret;
2018
2019 ret = nvme_identify_ns(ns->ctrl, info->nsid, &id);
2020 if (ret)
2021 return ret;
2022
2023 if (id->ncap == 0) {
2024 /* namespace not allocated or attached */
2025 info->is_removed = true;
2026 ret = -ENODEV;
2027 goto error;
2028 }
2029
2030 blk_mq_freeze_queue(ns->disk->queue);
2031 lbaf = nvme_lbaf_index(id->flbas);
2032 ns->lba_shift = id->lbaf[lbaf].ds;
2033 nvme_set_queue_limits(ns->ctrl, ns->queue);
2034
2035 ret = nvme_configure_metadata(ns, id);
2036 if (ret < 0) {
2037 blk_mq_unfreeze_queue(ns->disk->queue);
2038 goto out;
2039 }
2040 nvme_set_chunk_sectors(ns, id);
2041 nvme_update_disk_info(ns->disk, ns, id);
2042
2043 if (ns->head->ids.csi == NVME_CSI_ZNS) {
2044 ret = nvme_update_zone_info(ns, lbaf);
2045 if (ret) {
2046 blk_mq_unfreeze_queue(ns->disk->queue);
2047 goto out;
2048 }
2049 }
2050
2051 /*
2052 * Only set the DEAC bit if the device guarantees that reads from
2053 * deallocated data return zeroes. While the DEAC bit does not
2054 * require that, it must be a no-op if reads from deallocated data
2055 * do not return zeroes.
2056 */
2057 if ((id->dlfeat & 0x7) == 0x1 && (id->dlfeat & (1 << 3)))
2058 ns->features |= NVME_NS_DEAC;
2059 set_disk_ro(ns->disk, nvme_ns_is_readonly(ns, info));
2060 set_bit(NVME_NS_READY, &ns->flags);
2061 blk_mq_unfreeze_queue(ns->disk->queue);
2062
2063 if (blk_queue_is_zoned(ns->queue)) {
2064 ret = nvme_revalidate_zones(ns);
2065 if (ret && !nvme_first_scan(ns->disk))
2066 goto out;
2067 }
2068
2069 if (nvme_ns_head_multipath(ns->head)) {
2070 blk_mq_freeze_queue(ns->head->disk->queue);
2071 nvme_update_disk_info(ns->head->disk, ns, id);
2072 set_disk_ro(ns->head->disk, nvme_ns_is_readonly(ns, info));
2073 nvme_mpath_revalidate_paths(ns);
2074 blk_stack_limits(&ns->head->disk->queue->limits,
2075 &ns->queue->limits, 0);
2076 disk_update_readahead(ns->head->disk);
2077 blk_mq_unfreeze_queue(ns->head->disk->queue);
2078 }
2079
2080 ret = 0;
2081 out:
2082 /*
2083 * If probing fails due an unsupported feature, hide the block device,
2084 * but still allow other access.
2085 */
2086 if (ret == -ENODEV) {
2087 ns->disk->flags |= GENHD_FL_HIDDEN;
2088 set_bit(NVME_NS_READY, &ns->flags);
2089 ret = 0;
2090 }
2091
2092 error:
2093 kfree(id);
2094 return ret;
2095 }
2096
nvme_update_ns_info(struct nvme_ns * ns,struct nvme_ns_info * info)2097 static int nvme_update_ns_info(struct nvme_ns *ns, struct nvme_ns_info *info)
2098 {
2099 switch (info->ids.csi) {
2100 case NVME_CSI_ZNS:
2101 if (!IS_ENABLED(CONFIG_BLK_DEV_ZONED)) {
2102 dev_info(ns->ctrl->device,
2103 "block device for nsid %u not supported without CONFIG_BLK_DEV_ZONED\n",
2104 info->nsid);
2105 return nvme_update_ns_info_generic(ns, info);
2106 }
2107 return nvme_update_ns_info_block(ns, info);
2108 case NVME_CSI_NVM:
2109 return nvme_update_ns_info_block(ns, info);
2110 default:
2111 dev_info(ns->ctrl->device,
2112 "block device for nsid %u not supported (csi %u)\n",
2113 info->nsid, info->ids.csi);
2114 return nvme_update_ns_info_generic(ns, info);
2115 }
2116 }
2117
2118 #ifdef CONFIG_BLK_SED_OPAL
nvme_sec_submit(void * data,u16 spsp,u8 secp,void * buffer,size_t len,bool send)2119 static int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
2120 bool send)
2121 {
2122 struct nvme_ctrl *ctrl = data;
2123 struct nvme_command cmd = { };
2124
2125 if (send)
2126 cmd.common.opcode = nvme_admin_security_send;
2127 else
2128 cmd.common.opcode = nvme_admin_security_recv;
2129 cmd.common.nsid = 0;
2130 cmd.common.cdw10 = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
2131 cmd.common.cdw11 = cpu_to_le32(len);
2132
2133 return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
2134 NVME_QID_ANY, 1, 0);
2135 }
2136
nvme_configure_opal(struct nvme_ctrl * ctrl,bool was_suspended)2137 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
2138 {
2139 if (ctrl->oacs & NVME_CTRL_OACS_SEC_SUPP) {
2140 if (!ctrl->opal_dev)
2141 ctrl->opal_dev = init_opal_dev(ctrl, &nvme_sec_submit);
2142 else if (was_suspended)
2143 opal_unlock_from_suspend(ctrl->opal_dev);
2144 } else {
2145 free_opal_dev(ctrl->opal_dev);
2146 ctrl->opal_dev = NULL;
2147 }
2148 }
2149 #else
nvme_configure_opal(struct nvme_ctrl * ctrl,bool was_suspended)2150 static void nvme_configure_opal(struct nvme_ctrl *ctrl, bool was_suspended)
2151 {
2152 }
2153 #endif /* CONFIG_BLK_SED_OPAL */
2154
2155 #ifdef CONFIG_BLK_DEV_ZONED
nvme_report_zones(struct gendisk * disk,sector_t sector,unsigned int nr_zones,report_zones_cb cb,void * data)2156 static int nvme_report_zones(struct gendisk *disk, sector_t sector,
2157 unsigned int nr_zones, report_zones_cb cb, void *data)
2158 {
2159 return nvme_ns_report_zones(disk->private_data, sector, nr_zones, cb,
2160 data);
2161 }
2162 #else
2163 #define nvme_report_zones NULL
2164 #endif /* CONFIG_BLK_DEV_ZONED */
2165
2166 const struct block_device_operations nvme_bdev_ops = {
2167 .owner = THIS_MODULE,
2168 .ioctl = nvme_ioctl,
2169 .compat_ioctl = blkdev_compat_ptr_ioctl,
2170 .open = nvme_open,
2171 .release = nvme_release,
2172 .getgeo = nvme_getgeo,
2173 .report_zones = nvme_report_zones,
2174 .pr_ops = &nvme_pr_ops,
2175 };
2176
nvme_wait_ready(struct nvme_ctrl * ctrl,u32 mask,u32 val,u32 timeout,const char * op)2177 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u32 mask, u32 val,
2178 u32 timeout, const char *op)
2179 {
2180 unsigned long timeout_jiffies = jiffies + timeout * HZ;
2181 u32 csts;
2182 int ret;
2183
2184 while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
2185 if (csts == ~0)
2186 return -ENODEV;
2187 if ((csts & mask) == val)
2188 break;
2189
2190 usleep_range(1000, 2000);
2191 if (fatal_signal_pending(current))
2192 return -EINTR;
2193 if (time_after(jiffies, timeout_jiffies)) {
2194 dev_err(ctrl->device,
2195 "Device not ready; aborting %s, CSTS=0x%x\n",
2196 op, csts);
2197 return -ENODEV;
2198 }
2199 }
2200
2201 return ret;
2202 }
2203
nvme_disable_ctrl(struct nvme_ctrl * ctrl,bool shutdown)2204 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, bool shutdown)
2205 {
2206 int ret;
2207
2208 ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
2209 if (shutdown)
2210 ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
2211 else
2212 ctrl->ctrl_config &= ~NVME_CC_ENABLE;
2213
2214 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2215 if (ret)
2216 return ret;
2217
2218 if (shutdown) {
2219 return nvme_wait_ready(ctrl, NVME_CSTS_SHST_MASK,
2220 NVME_CSTS_SHST_CMPLT,
2221 ctrl->shutdown_timeout, "shutdown");
2222 }
2223 if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
2224 msleep(NVME_QUIRK_DELAY_AMOUNT);
2225 return nvme_wait_ready(ctrl, NVME_CSTS_RDY, 0,
2226 (NVME_CAP_TIMEOUT(ctrl->cap) + 1) / 2, "reset");
2227 }
2228 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
2229
nvme_enable_ctrl(struct nvme_ctrl * ctrl)2230 int nvme_enable_ctrl(struct nvme_ctrl *ctrl)
2231 {
2232 unsigned dev_page_min;
2233 u32 timeout;
2234 int ret;
2235
2236 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2237 if (ret) {
2238 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
2239 return ret;
2240 }
2241 dev_page_min = NVME_CAP_MPSMIN(ctrl->cap) + 12;
2242
2243 if (NVME_CTRL_PAGE_SHIFT < dev_page_min) {
2244 dev_err(ctrl->device,
2245 "Minimum device page size %u too large for host (%u)\n",
2246 1 << dev_page_min, 1 << NVME_CTRL_PAGE_SHIFT);
2247 return -ENODEV;
2248 }
2249
2250 if (NVME_CAP_CSS(ctrl->cap) & NVME_CAP_CSS_CSI)
2251 ctrl->ctrl_config = NVME_CC_CSS_CSI;
2252 else
2253 ctrl->ctrl_config = NVME_CC_CSS_NVM;
2254
2255 /*
2256 * Setting CRIME results in CSTS.RDY before the media is ready. This
2257 * makes it possible for media related commands to return the error
2258 * NVME_SC_ADMIN_COMMAND_MEDIA_NOT_READY. Until the driver is
2259 * restructured to handle retries, disable CC.CRIME.
2260 */
2261 ctrl->ctrl_config &= ~NVME_CC_CRIME;
2262
2263 ctrl->ctrl_config |= (NVME_CTRL_PAGE_SHIFT - 12) << NVME_CC_MPS_SHIFT;
2264 ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
2265 ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
2266 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2267 if (ret)
2268 return ret;
2269
2270 /* Flush write to device (required if transport is PCI) */
2271 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CC, &ctrl->ctrl_config);
2272 if (ret)
2273 return ret;
2274
2275 /* CAP value may change after initial CC write */
2276 ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &ctrl->cap);
2277 if (ret)
2278 return ret;
2279
2280 timeout = NVME_CAP_TIMEOUT(ctrl->cap);
2281 if (ctrl->cap & NVME_CAP_CRMS_CRWMS) {
2282 u32 crto, ready_timeout;
2283
2284 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CRTO, &crto);
2285 if (ret) {
2286 dev_err(ctrl->device, "Reading CRTO failed (%d)\n",
2287 ret);
2288 return ret;
2289 }
2290
2291 /*
2292 * CRTO should always be greater or equal to CAP.TO, but some
2293 * devices are known to get this wrong. Use the larger of the
2294 * two values.
2295 */
2296 ready_timeout = NVME_CRTO_CRWMT(crto);
2297
2298 if (ready_timeout < timeout)
2299 dev_warn_once(ctrl->device, "bad crto:%x cap:%llx\n",
2300 crto, ctrl->cap);
2301 else
2302 timeout = ready_timeout;
2303 }
2304
2305 ctrl->ctrl_config |= NVME_CC_ENABLE;
2306 ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
2307 if (ret)
2308 return ret;
2309 return nvme_wait_ready(ctrl, NVME_CSTS_RDY, NVME_CSTS_RDY,
2310 (timeout + 1) / 2, "initialisation");
2311 }
2312 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
2313
nvme_configure_timestamp(struct nvme_ctrl * ctrl)2314 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
2315 {
2316 __le64 ts;
2317 int ret;
2318
2319 if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
2320 return 0;
2321
2322 ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
2323 ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
2324 NULL);
2325 if (ret)
2326 dev_warn_once(ctrl->device,
2327 "could not set timestamp (%d)\n", ret);
2328 return ret;
2329 }
2330
nvme_configure_host_options(struct nvme_ctrl * ctrl)2331 static int nvme_configure_host_options(struct nvme_ctrl *ctrl)
2332 {
2333 struct nvme_feat_host_behavior *host;
2334 u8 acre = 0, lbafee = 0;
2335 int ret;
2336
2337 /* Don't bother enabling the feature if retry delay is not reported */
2338 if (ctrl->crdt[0])
2339 acre = NVME_ENABLE_ACRE;
2340 if (ctrl->ctratt & NVME_CTRL_ATTR_ELBAS)
2341 lbafee = NVME_ENABLE_LBAFEE;
2342
2343 if (!acre && !lbafee)
2344 return 0;
2345
2346 host = kzalloc(sizeof(*host), GFP_KERNEL);
2347 if (!host)
2348 return 0;
2349
2350 host->acre = acre;
2351 host->lbafee = lbafee;
2352 ret = nvme_set_features(ctrl, NVME_FEAT_HOST_BEHAVIOR, 0,
2353 host, sizeof(*host), NULL);
2354 kfree(host);
2355 return ret;
2356 }
2357
2358 /*
2359 * The function checks whether the given total (exlat + enlat) latency of
2360 * a power state allows the latter to be used as an APST transition target.
2361 * It does so by comparing the latency to the primary and secondary latency
2362 * tolerances defined by module params. If there's a match, the corresponding
2363 * timeout value is returned and the matching tolerance index (1 or 2) is
2364 * reported.
2365 */
nvme_apst_get_transition_time(u64 total_latency,u64 * transition_time,unsigned * last_index)2366 static bool nvme_apst_get_transition_time(u64 total_latency,
2367 u64 *transition_time, unsigned *last_index)
2368 {
2369 if (total_latency <= apst_primary_latency_tol_us) {
2370 if (*last_index == 1)
2371 return false;
2372 *last_index = 1;
2373 *transition_time = apst_primary_timeout_ms;
2374 return true;
2375 }
2376 if (apst_secondary_timeout_ms &&
2377 total_latency <= apst_secondary_latency_tol_us) {
2378 if (*last_index <= 2)
2379 return false;
2380 *last_index = 2;
2381 *transition_time = apst_secondary_timeout_ms;
2382 return true;
2383 }
2384 return false;
2385 }
2386
2387 /*
2388 * APST (Autonomous Power State Transition) lets us program a table of power
2389 * state transitions that the controller will perform automatically.
2390 *
2391 * Depending on module params, one of the two supported techniques will be used:
2392 *
2393 * - If the parameters provide explicit timeouts and tolerances, they will be
2394 * used to build a table with up to 2 non-operational states to transition to.
2395 * The default parameter values were selected based on the values used by
2396 * Microsoft's and Intel's NVMe drivers. Yet, since we don't implement dynamic
2397 * regeneration of the APST table in the event of switching between external
2398 * and battery power, the timeouts and tolerances reflect a compromise
2399 * between values used by Microsoft for AC and battery scenarios.
2400 * - If not, we'll configure the table with a simple heuristic: we are willing
2401 * to spend at most 2% of the time transitioning between power states.
2402 * Therefore, when running in any given state, we will enter the next
2403 * lower-power non-operational state after waiting 50 * (enlat + exlat)
2404 * microseconds, as long as that state's exit latency is under the requested
2405 * maximum latency.
2406 *
2407 * We will not autonomously enter any non-operational state for which the total
2408 * latency exceeds ps_max_latency_us.
2409 *
2410 * Users can set ps_max_latency_us to zero to turn off APST.
2411 */
nvme_configure_apst(struct nvme_ctrl * ctrl)2412 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
2413 {
2414 struct nvme_feat_auto_pst *table;
2415 unsigned apste = 0;
2416 u64 max_lat_us = 0;
2417 __le64 target = 0;
2418 int max_ps = -1;
2419 int state;
2420 int ret;
2421 unsigned last_lt_index = UINT_MAX;
2422
2423 /*
2424 * If APST isn't supported or if we haven't been initialized yet,
2425 * then don't do anything.
2426 */
2427 if (!ctrl->apsta)
2428 return 0;
2429
2430 if (ctrl->npss > 31) {
2431 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
2432 return 0;
2433 }
2434
2435 table = kzalloc(sizeof(*table), GFP_KERNEL);
2436 if (!table)
2437 return 0;
2438
2439 if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
2440 /* Turn off APST. */
2441 dev_dbg(ctrl->device, "APST disabled\n");
2442 goto done;
2443 }
2444
2445 /*
2446 * Walk through all states from lowest- to highest-power.
2447 * According to the spec, lower-numbered states use more power. NPSS,
2448 * despite the name, is the index of the lowest-power state, not the
2449 * number of states.
2450 */
2451 for (state = (int)ctrl->npss; state >= 0; state--) {
2452 u64 total_latency_us, exit_latency_us, transition_ms;
2453
2454 if (target)
2455 table->entries[state] = target;
2456
2457 /*
2458 * Don't allow transitions to the deepest state if it's quirked
2459 * off.
2460 */
2461 if (state == ctrl->npss &&
2462 (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
2463 continue;
2464
2465 /*
2466 * Is this state a useful non-operational state for higher-power
2467 * states to autonomously transition to?
2468 */
2469 if (!(ctrl->psd[state].flags & NVME_PS_FLAGS_NON_OP_STATE))
2470 continue;
2471
2472 exit_latency_us = (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
2473 if (exit_latency_us > ctrl->ps_max_latency_us)
2474 continue;
2475
2476 total_latency_us = exit_latency_us +
2477 le32_to_cpu(ctrl->psd[state].entry_lat);
2478
2479 /*
2480 * This state is good. It can be used as the APST idle target
2481 * for higher power states.
2482 */
2483 if (apst_primary_timeout_ms && apst_primary_latency_tol_us) {
2484 if (!nvme_apst_get_transition_time(total_latency_us,
2485 &transition_ms, &last_lt_index))
2486 continue;
2487 } else {
2488 transition_ms = total_latency_us + 19;
2489 do_div(transition_ms, 20);
2490 if (transition_ms > (1 << 24) - 1)
2491 transition_ms = (1 << 24) - 1;
2492 }
2493
2494 target = cpu_to_le64((state << 3) | (transition_ms << 8));
2495 if (max_ps == -1)
2496 max_ps = state;
2497 if (total_latency_us > max_lat_us)
2498 max_lat_us = total_latency_us;
2499 }
2500
2501 if (max_ps == -1)
2502 dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
2503 else
2504 dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
2505 max_ps, max_lat_us, (int)sizeof(*table), table);
2506 apste = 1;
2507
2508 done:
2509 ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
2510 table, sizeof(*table), NULL);
2511 if (ret)
2512 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
2513 kfree(table);
2514 return ret;
2515 }
2516
nvme_set_latency_tolerance(struct device * dev,s32 val)2517 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
2518 {
2519 struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2520 u64 latency;
2521
2522 switch (val) {
2523 case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
2524 case PM_QOS_LATENCY_ANY:
2525 latency = U64_MAX;
2526 break;
2527
2528 default:
2529 latency = val;
2530 }
2531
2532 if (ctrl->ps_max_latency_us != latency) {
2533 ctrl->ps_max_latency_us = latency;
2534 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
2535 nvme_configure_apst(ctrl);
2536 }
2537 }
2538
2539 struct nvme_core_quirk_entry {
2540 /*
2541 * NVMe model and firmware strings are padded with spaces. For
2542 * simplicity, strings in the quirk table are padded with NULLs
2543 * instead.
2544 */
2545 u16 vid;
2546 const char *mn;
2547 const char *fr;
2548 unsigned long quirks;
2549 };
2550
2551 static const struct nvme_core_quirk_entry core_quirks[] = {
2552 {
2553 /*
2554 * This Toshiba device seems to die using any APST states. See:
2555 * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
2556 */
2557 .vid = 0x1179,
2558 .mn = "THNSF5256GPUK TOSHIBA",
2559 .quirks = NVME_QUIRK_NO_APST,
2560 },
2561 {
2562 /*
2563 * This LiteON CL1-3D*-Q11 firmware version has a race
2564 * condition associated with actions related to suspend to idle
2565 * LiteON has resolved the problem in future firmware
2566 */
2567 .vid = 0x14a4,
2568 .fr = "22301111",
2569 .quirks = NVME_QUIRK_SIMPLE_SUSPEND,
2570 },
2571 {
2572 /*
2573 * This Kioxia CD6-V Series / HPE PE8030 device times out and
2574 * aborts I/O during any load, but more easily reproducible
2575 * with discards (fstrim).
2576 *
2577 * The device is left in a state where it is also not possible
2578 * to use "nvme set-feature" to disable APST, but booting with
2579 * nvme_core.default_ps_max_latency=0 works.
2580 */
2581 .vid = 0x1e0f,
2582 .mn = "KCD6XVUL6T40",
2583 .quirks = NVME_QUIRK_NO_APST,
2584 },
2585 {
2586 /*
2587 * The external Samsung X5 SSD fails initialization without a
2588 * delay before checking if it is ready and has a whole set of
2589 * other problems. To make this even more interesting, it
2590 * shares the PCI ID with internal Samsung 970 Evo Plus that
2591 * does not need or want these quirks.
2592 */
2593 .vid = 0x144d,
2594 .mn = "Samsung Portable SSD X5",
2595 .quirks = NVME_QUIRK_DELAY_BEFORE_CHK_RDY |
2596 NVME_QUIRK_NO_DEEPEST_PS |
2597 NVME_QUIRK_IGNORE_DEV_SUBNQN,
2598 }
2599 };
2600
2601 /* match is null-terminated but idstr is space-padded. */
string_matches(const char * idstr,const char * match,size_t len)2602 static bool string_matches(const char *idstr, const char *match, size_t len)
2603 {
2604 size_t matchlen;
2605
2606 if (!match)
2607 return true;
2608
2609 matchlen = strlen(match);
2610 WARN_ON_ONCE(matchlen > len);
2611
2612 if (memcmp(idstr, match, matchlen))
2613 return false;
2614
2615 for (; matchlen < len; matchlen++)
2616 if (idstr[matchlen] != ' ')
2617 return false;
2618
2619 return true;
2620 }
2621
quirk_matches(const struct nvme_id_ctrl * id,const struct nvme_core_quirk_entry * q)2622 static bool quirk_matches(const struct nvme_id_ctrl *id,
2623 const struct nvme_core_quirk_entry *q)
2624 {
2625 return q->vid == le16_to_cpu(id->vid) &&
2626 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
2627 string_matches(id->fr, q->fr, sizeof(id->fr));
2628 }
2629
nvme_init_subnqn(struct nvme_subsystem * subsys,struct nvme_ctrl * ctrl,struct nvme_id_ctrl * id)2630 static void nvme_init_subnqn(struct nvme_subsystem *subsys, struct nvme_ctrl *ctrl,
2631 struct nvme_id_ctrl *id)
2632 {
2633 size_t nqnlen;
2634 int off;
2635
2636 if(!(ctrl->quirks & NVME_QUIRK_IGNORE_DEV_SUBNQN)) {
2637 nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
2638 if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
2639 strscpy(subsys->subnqn, id->subnqn, NVMF_NQN_SIZE);
2640 return;
2641 }
2642
2643 if (ctrl->vs >= NVME_VS(1, 2, 1))
2644 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
2645 }
2646
2647 /*
2648 * Generate a "fake" NQN similar to the one in Section 4.5 of the NVMe
2649 * Base Specification 2.0. It is slightly different from the format
2650 * specified there due to historic reasons, and we can't change it now.
2651 */
2652 off = snprintf(subsys->subnqn, NVMF_NQN_SIZE,
2653 "nqn.2014.08.org.nvmexpress:%04x%04x",
2654 le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
2655 memcpy(subsys->subnqn + off, id->sn, sizeof(id->sn));
2656 off += sizeof(id->sn);
2657 memcpy(subsys->subnqn + off, id->mn, sizeof(id->mn));
2658 off += sizeof(id->mn);
2659 memset(subsys->subnqn + off, 0, sizeof(subsys->subnqn) - off);
2660 }
2661
nvme_release_subsystem(struct device * dev)2662 static void nvme_release_subsystem(struct device *dev)
2663 {
2664 struct nvme_subsystem *subsys =
2665 container_of(dev, struct nvme_subsystem, dev);
2666
2667 if (subsys->instance >= 0)
2668 ida_free(&nvme_instance_ida, subsys->instance);
2669 kfree(subsys);
2670 }
2671
nvme_destroy_subsystem(struct kref * ref)2672 static void nvme_destroy_subsystem(struct kref *ref)
2673 {
2674 struct nvme_subsystem *subsys =
2675 container_of(ref, struct nvme_subsystem, ref);
2676
2677 mutex_lock(&nvme_subsystems_lock);
2678 list_del(&subsys->entry);
2679 mutex_unlock(&nvme_subsystems_lock);
2680
2681 ida_destroy(&subsys->ns_ida);
2682 device_del(&subsys->dev);
2683 put_device(&subsys->dev);
2684 }
2685
nvme_put_subsystem(struct nvme_subsystem * subsys)2686 static void nvme_put_subsystem(struct nvme_subsystem *subsys)
2687 {
2688 kref_put(&subsys->ref, nvme_destroy_subsystem);
2689 }
2690
__nvme_find_get_subsystem(const char * subsysnqn)2691 static struct nvme_subsystem *__nvme_find_get_subsystem(const char *subsysnqn)
2692 {
2693 struct nvme_subsystem *subsys;
2694
2695 lockdep_assert_held(&nvme_subsystems_lock);
2696
2697 /*
2698 * Fail matches for discovery subsystems. This results
2699 * in each discovery controller bound to a unique subsystem.
2700 * This avoids issues with validating controller values
2701 * that can only be true when there is a single unique subsystem.
2702 * There may be multiple and completely independent entities
2703 * that provide discovery controllers.
2704 */
2705 if (!strcmp(subsysnqn, NVME_DISC_SUBSYS_NAME))
2706 return NULL;
2707
2708 list_for_each_entry(subsys, &nvme_subsystems, entry) {
2709 if (strcmp(subsys->subnqn, subsysnqn))
2710 continue;
2711 if (!kref_get_unless_zero(&subsys->ref))
2712 continue;
2713 return subsys;
2714 }
2715
2716 return NULL;
2717 }
2718
nvme_discovery_ctrl(struct nvme_ctrl * ctrl)2719 static inline bool nvme_discovery_ctrl(struct nvme_ctrl *ctrl)
2720 {
2721 return ctrl->opts && ctrl->opts->discovery_nqn;
2722 }
2723
nvme_validate_cntlid(struct nvme_subsystem * subsys,struct nvme_ctrl * ctrl,struct nvme_id_ctrl * id)2724 static bool nvme_validate_cntlid(struct nvme_subsystem *subsys,
2725 struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2726 {
2727 struct nvme_ctrl *tmp;
2728
2729 lockdep_assert_held(&nvme_subsystems_lock);
2730
2731 list_for_each_entry(tmp, &subsys->ctrls, subsys_entry) {
2732 if (nvme_state_terminal(tmp))
2733 continue;
2734
2735 if (tmp->cntlid == ctrl->cntlid) {
2736 dev_err(ctrl->device,
2737 "Duplicate cntlid %u with %s, subsys %s, rejecting\n",
2738 ctrl->cntlid, dev_name(tmp->device),
2739 subsys->subnqn);
2740 return false;
2741 }
2742
2743 if ((id->cmic & NVME_CTRL_CMIC_MULTI_CTRL) ||
2744 nvme_discovery_ctrl(ctrl))
2745 continue;
2746
2747 dev_err(ctrl->device,
2748 "Subsystem does not support multiple controllers\n");
2749 return false;
2750 }
2751
2752 return true;
2753 }
2754
nvme_init_subsystem(struct nvme_ctrl * ctrl,struct nvme_id_ctrl * id)2755 static int nvme_init_subsystem(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
2756 {
2757 struct nvme_subsystem *subsys, *found;
2758 int ret;
2759
2760 subsys = kzalloc(sizeof(*subsys), GFP_KERNEL);
2761 if (!subsys)
2762 return -ENOMEM;
2763
2764 subsys->instance = -1;
2765 mutex_init(&subsys->lock);
2766 kref_init(&subsys->ref);
2767 INIT_LIST_HEAD(&subsys->ctrls);
2768 INIT_LIST_HEAD(&subsys->nsheads);
2769 nvme_init_subnqn(subsys, ctrl, id);
2770 memcpy(subsys->serial, id->sn, sizeof(subsys->serial));
2771 memcpy(subsys->model, id->mn, sizeof(subsys->model));
2772 subsys->vendor_id = le16_to_cpu(id->vid);
2773 subsys->cmic = id->cmic;
2774
2775 /* Versions prior to 1.4 don't necessarily report a valid type */
2776 if (id->cntrltype == NVME_CTRL_DISC ||
2777 !strcmp(subsys->subnqn, NVME_DISC_SUBSYS_NAME))
2778 subsys->subtype = NVME_NQN_DISC;
2779 else
2780 subsys->subtype = NVME_NQN_NVME;
2781
2782 if (nvme_discovery_ctrl(ctrl) && subsys->subtype != NVME_NQN_DISC) {
2783 dev_err(ctrl->device,
2784 "Subsystem %s is not a discovery controller",
2785 subsys->subnqn);
2786 kfree(subsys);
2787 return -EINVAL;
2788 }
2789 subsys->awupf = le16_to_cpu(id->awupf);
2790 nvme_mpath_default_iopolicy(subsys);
2791
2792 subsys->dev.class = nvme_subsys_class;
2793 subsys->dev.release = nvme_release_subsystem;
2794 subsys->dev.groups = nvme_subsys_attrs_groups;
2795 dev_set_name(&subsys->dev, "nvme-subsys%d", ctrl->instance);
2796 device_initialize(&subsys->dev);
2797
2798 mutex_lock(&nvme_subsystems_lock);
2799 found = __nvme_find_get_subsystem(subsys->subnqn);
2800 if (found) {
2801 put_device(&subsys->dev);
2802 subsys = found;
2803
2804 if (!nvme_validate_cntlid(subsys, ctrl, id)) {
2805 ret = -EINVAL;
2806 goto out_put_subsystem;
2807 }
2808 } else {
2809 ret = device_add(&subsys->dev);
2810 if (ret) {
2811 dev_err(ctrl->device,
2812 "failed to register subsystem device.\n");
2813 put_device(&subsys->dev);
2814 goto out_unlock;
2815 }
2816 ida_init(&subsys->ns_ida);
2817 list_add_tail(&subsys->entry, &nvme_subsystems);
2818 }
2819
2820 ret = sysfs_create_link(&subsys->dev.kobj, &ctrl->device->kobj,
2821 dev_name(ctrl->device));
2822 if (ret) {
2823 dev_err(ctrl->device,
2824 "failed to create sysfs link from subsystem.\n");
2825 goto out_put_subsystem;
2826 }
2827
2828 if (!found)
2829 subsys->instance = ctrl->instance;
2830 ctrl->subsys = subsys;
2831 list_add_tail(&ctrl->subsys_entry, &subsys->ctrls);
2832 mutex_unlock(&nvme_subsystems_lock);
2833 return 0;
2834
2835 out_put_subsystem:
2836 nvme_put_subsystem(subsys);
2837 out_unlock:
2838 mutex_unlock(&nvme_subsystems_lock);
2839 return ret;
2840 }
2841
nvme_get_log(struct nvme_ctrl * ctrl,u32 nsid,u8 log_page,u8 lsp,u8 csi,void * log,size_t size,u64 offset)2842 int nvme_get_log(struct nvme_ctrl *ctrl, u32 nsid, u8 log_page, u8 lsp, u8 csi,
2843 void *log, size_t size, u64 offset)
2844 {
2845 struct nvme_command c = { };
2846 u32 dwlen = nvme_bytes_to_numd(size);
2847
2848 c.get_log_page.opcode = nvme_admin_get_log_page;
2849 c.get_log_page.nsid = cpu_to_le32(nsid);
2850 c.get_log_page.lid = log_page;
2851 c.get_log_page.lsp = lsp;
2852 c.get_log_page.numdl = cpu_to_le16(dwlen & ((1 << 16) - 1));
2853 c.get_log_page.numdu = cpu_to_le16(dwlen >> 16);
2854 c.get_log_page.lpol = cpu_to_le32(lower_32_bits(offset));
2855 c.get_log_page.lpou = cpu_to_le32(upper_32_bits(offset));
2856 c.get_log_page.csi = csi;
2857
2858 return nvme_submit_sync_cmd(ctrl->admin_q, &c, log, size);
2859 }
2860
nvme_get_effects_log(struct nvme_ctrl * ctrl,u8 csi,struct nvme_effects_log ** log)2861 static int nvme_get_effects_log(struct nvme_ctrl *ctrl, u8 csi,
2862 struct nvme_effects_log **log)
2863 {
2864 struct nvme_effects_log *old, *cel = xa_load(&ctrl->cels, csi);
2865 int ret;
2866
2867 if (cel)
2868 goto out;
2869
2870 cel = kzalloc(sizeof(*cel), GFP_KERNEL);
2871 if (!cel)
2872 return -ENOMEM;
2873
2874 ret = nvme_get_log(ctrl, 0x00, NVME_LOG_CMD_EFFECTS, 0, csi,
2875 cel, sizeof(*cel), 0);
2876 if (ret) {
2877 kfree(cel);
2878 return ret;
2879 }
2880
2881 old = xa_store(&ctrl->cels, csi, cel, GFP_KERNEL);
2882 if (xa_is_err(old)) {
2883 kfree(cel);
2884 return xa_err(old);
2885 }
2886 out:
2887 *log = cel;
2888 return 0;
2889 }
2890
nvme_mps_to_sectors(struct nvme_ctrl * ctrl,u32 units)2891 static inline u32 nvme_mps_to_sectors(struct nvme_ctrl *ctrl, u32 units)
2892 {
2893 u32 page_shift = NVME_CAP_MPSMIN(ctrl->cap) + 12, val;
2894
2895 if (check_shl_overflow(1U, units + page_shift - 9, &val))
2896 return UINT_MAX;
2897 return val;
2898 }
2899
nvme_init_non_mdts_limits(struct nvme_ctrl * ctrl)2900 static int nvme_init_non_mdts_limits(struct nvme_ctrl *ctrl)
2901 {
2902 struct nvme_command c = { };
2903 struct nvme_id_ctrl_nvm *id;
2904 int ret;
2905
2906 if (ctrl->oncs & NVME_CTRL_ONCS_DSM) {
2907 ctrl->max_discard_sectors = UINT_MAX;
2908 ctrl->max_discard_segments = NVME_DSM_MAX_RANGES;
2909 } else {
2910 ctrl->max_discard_sectors = 0;
2911 ctrl->max_discard_segments = 0;
2912 }
2913
2914 /*
2915 * Even though NVMe spec explicitly states that MDTS is not applicable
2916 * to the write-zeroes, we are cautious and limit the size to the
2917 * controllers max_hw_sectors value, which is based on the MDTS field
2918 * and possibly other limiting factors.
2919 */
2920 if ((ctrl->oncs & NVME_CTRL_ONCS_WRITE_ZEROES) &&
2921 !(ctrl->quirks & NVME_QUIRK_DISABLE_WRITE_ZEROES))
2922 ctrl->max_zeroes_sectors = ctrl->max_hw_sectors;
2923 else
2924 ctrl->max_zeroes_sectors = 0;
2925
2926 if (ctrl->subsys->subtype != NVME_NQN_NVME ||
2927 nvme_ctrl_limited_cns(ctrl) ||
2928 test_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags))
2929 return 0;
2930
2931 id = kzalloc(sizeof(*id), GFP_KERNEL);
2932 if (!id)
2933 return -ENOMEM;
2934
2935 c.identify.opcode = nvme_admin_identify;
2936 c.identify.cns = NVME_ID_CNS_CS_CTRL;
2937 c.identify.csi = NVME_CSI_NVM;
2938
2939 ret = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
2940 if (ret)
2941 goto free_data;
2942
2943 if (id->dmrl)
2944 ctrl->max_discard_segments = id->dmrl;
2945 ctrl->dmrsl = le32_to_cpu(id->dmrsl);
2946 if (id->wzsl)
2947 ctrl->max_zeroes_sectors = nvme_mps_to_sectors(ctrl, id->wzsl);
2948
2949 free_data:
2950 if (ret > 0)
2951 set_bit(NVME_CTRL_SKIP_ID_CNS_CS, &ctrl->flags);
2952 kfree(id);
2953 return ret;
2954 }
2955
nvme_init_effects_log(struct nvme_ctrl * ctrl,u8 csi,struct nvme_effects_log ** log)2956 static int nvme_init_effects_log(struct nvme_ctrl *ctrl,
2957 u8 csi, struct nvme_effects_log **log)
2958 {
2959 struct nvme_effects_log *effects, *old;
2960
2961 effects = kzalloc(sizeof(*effects), GFP_KERNEL);
2962 if (!effects)
2963 return -ENOMEM;
2964
2965 old = xa_store(&ctrl->cels, csi, effects, GFP_KERNEL);
2966 if (xa_is_err(old)) {
2967 kfree(effects);
2968 return xa_err(old);
2969 }
2970
2971 *log = effects;
2972 return 0;
2973 }
2974
nvme_init_known_nvm_effects(struct nvme_ctrl * ctrl)2975 static void nvme_init_known_nvm_effects(struct nvme_ctrl *ctrl)
2976 {
2977 struct nvme_effects_log *log = ctrl->effects;
2978
2979 log->acs[nvme_admin_format_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
2980 NVME_CMD_EFFECTS_NCC |
2981 NVME_CMD_EFFECTS_CSE_MASK);
2982 log->acs[nvme_admin_sanitize_nvm] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC |
2983 NVME_CMD_EFFECTS_CSE_MASK);
2984
2985 /*
2986 * The spec says the result of a security receive command depends on
2987 * the previous security send command. As such, many vendors log this
2988 * command as one to submitted only when no other commands to the same
2989 * namespace are outstanding. The intention is to tell the host to
2990 * prevent mixing security send and receive.
2991 *
2992 * This driver can only enforce such exclusive access against IO
2993 * queues, though. We are not readily able to enforce such a rule for
2994 * two commands to the admin queue, which is the only queue that
2995 * matters for this command.
2996 *
2997 * Rather than blindly freezing the IO queues for this effect that
2998 * doesn't even apply to IO, mask it off.
2999 */
3000 log->acs[nvme_admin_security_recv] &= cpu_to_le32(~NVME_CMD_EFFECTS_CSE_MASK);
3001
3002 log->iocs[nvme_cmd_write] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3003 log->iocs[nvme_cmd_write_zeroes] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3004 log->iocs[nvme_cmd_write_uncor] |= cpu_to_le32(NVME_CMD_EFFECTS_LBCC);
3005 }
3006
nvme_init_effects(struct nvme_ctrl * ctrl,struct nvme_id_ctrl * id)3007 static int nvme_init_effects(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
3008 {
3009 int ret = 0;
3010
3011 if (ctrl->effects)
3012 return 0;
3013
3014 if (id->lpa & NVME_CTRL_LPA_CMD_EFFECTS_LOG) {
3015 ret = nvme_get_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3016 if (ret < 0)
3017 return ret;
3018 }
3019
3020 if (!ctrl->effects) {
3021 ret = nvme_init_effects_log(ctrl, NVME_CSI_NVM, &ctrl->effects);
3022 if (ret < 0)
3023 return ret;
3024 }
3025
3026 nvme_init_known_nvm_effects(ctrl);
3027 return 0;
3028 }
3029
nvme_init_identify(struct nvme_ctrl * ctrl)3030 static int nvme_init_identify(struct nvme_ctrl *ctrl)
3031 {
3032 struct nvme_id_ctrl *id;
3033 u32 max_hw_sectors;
3034 bool prev_apst_enabled;
3035 int ret;
3036
3037 ret = nvme_identify_ctrl(ctrl, &id);
3038 if (ret) {
3039 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
3040 return -EIO;
3041 }
3042
3043 if (!(ctrl->ops->flags & NVME_F_FABRICS))
3044 ctrl->cntlid = le16_to_cpu(id->cntlid);
3045
3046 if (!ctrl->identified) {
3047 unsigned int i;
3048
3049 /*
3050 * Check for quirks. Quirk can depend on firmware version,
3051 * so, in principle, the set of quirks present can change
3052 * across a reset. As a possible future enhancement, we
3053 * could re-scan for quirks every time we reinitialize
3054 * the device, but we'd have to make sure that the driver
3055 * behaves intelligently if the quirks change.
3056 */
3057 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
3058 if (quirk_matches(id, &core_quirks[i]))
3059 ctrl->quirks |= core_quirks[i].quirks;
3060 }
3061
3062 ret = nvme_init_subsystem(ctrl, id);
3063 if (ret)
3064 goto out_free;
3065
3066 ret = nvme_init_effects(ctrl, id);
3067 if (ret)
3068 goto out_free;
3069 }
3070 memcpy(ctrl->subsys->firmware_rev, id->fr,
3071 sizeof(ctrl->subsys->firmware_rev));
3072
3073 if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
3074 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
3075 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
3076 }
3077
3078 ctrl->crdt[0] = le16_to_cpu(id->crdt1);
3079 ctrl->crdt[1] = le16_to_cpu(id->crdt2);
3080 ctrl->crdt[2] = le16_to_cpu(id->crdt3);
3081
3082 ctrl->oacs = le16_to_cpu(id->oacs);
3083 ctrl->oncs = le16_to_cpu(id->oncs);
3084 ctrl->mtfa = le16_to_cpu(id->mtfa);
3085 ctrl->oaes = le32_to_cpu(id->oaes);
3086 ctrl->wctemp = le16_to_cpu(id->wctemp);
3087 ctrl->cctemp = le16_to_cpu(id->cctemp);
3088
3089 atomic_set(&ctrl->abort_limit, id->acl + 1);
3090 ctrl->vwc = id->vwc;
3091 if (id->mdts)
3092 max_hw_sectors = nvme_mps_to_sectors(ctrl, id->mdts);
3093 else
3094 max_hw_sectors = UINT_MAX;
3095 ctrl->max_hw_sectors =
3096 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
3097
3098 nvme_set_queue_limits(ctrl, ctrl->admin_q);
3099 ctrl->sgls = le32_to_cpu(id->sgls);
3100 ctrl->kas = le16_to_cpu(id->kas);
3101 ctrl->max_namespaces = le32_to_cpu(id->mnan);
3102 ctrl->ctratt = le32_to_cpu(id->ctratt);
3103
3104 ctrl->cntrltype = id->cntrltype;
3105 ctrl->dctype = id->dctype;
3106
3107 if (id->rtd3e) {
3108 /* us -> s */
3109 u32 transition_time = le32_to_cpu(id->rtd3e) / USEC_PER_SEC;
3110
3111 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
3112 shutdown_timeout, 60);
3113
3114 if (ctrl->shutdown_timeout != shutdown_timeout)
3115 dev_info(ctrl->device,
3116 "Shutdown timeout set to %u seconds\n",
3117 ctrl->shutdown_timeout);
3118 } else
3119 ctrl->shutdown_timeout = shutdown_timeout;
3120
3121 ctrl->npss = id->npss;
3122 ctrl->apsta = id->apsta;
3123 prev_apst_enabled = ctrl->apst_enabled;
3124 if (ctrl->quirks & NVME_QUIRK_NO_APST) {
3125 if (force_apst && id->apsta) {
3126 dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
3127 ctrl->apst_enabled = true;
3128 } else {
3129 ctrl->apst_enabled = false;
3130 }
3131 } else {
3132 ctrl->apst_enabled = id->apsta;
3133 }
3134 memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
3135
3136 if (ctrl->ops->flags & NVME_F_FABRICS) {
3137 ctrl->icdoff = le16_to_cpu(id->icdoff);
3138 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
3139 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
3140 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
3141
3142 /*
3143 * In fabrics we need to verify the cntlid matches the
3144 * admin connect
3145 */
3146 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
3147 dev_err(ctrl->device,
3148 "Mismatching cntlid: Connect %u vs Identify "
3149 "%u, rejecting\n",
3150 ctrl->cntlid, le16_to_cpu(id->cntlid));
3151 ret = -EINVAL;
3152 goto out_free;
3153 }
3154
3155 if (!nvme_discovery_ctrl(ctrl) && !ctrl->kas) {
3156 dev_err(ctrl->device,
3157 "keep-alive support is mandatory for fabrics\n");
3158 ret = -EINVAL;
3159 goto out_free;
3160 }
3161 } else {
3162 ctrl->hmpre = le32_to_cpu(id->hmpre);
3163 ctrl->hmmin = le32_to_cpu(id->hmmin);
3164 ctrl->hmminds = le32_to_cpu(id->hmminds);
3165 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
3166 }
3167
3168 ret = nvme_mpath_init_identify(ctrl, id);
3169 if (ret < 0)
3170 goto out_free;
3171
3172 if (ctrl->apst_enabled && !prev_apst_enabled)
3173 dev_pm_qos_expose_latency_tolerance(ctrl->device);
3174 else if (!ctrl->apst_enabled && prev_apst_enabled)
3175 dev_pm_qos_hide_latency_tolerance(ctrl->device);
3176
3177 out_free:
3178 kfree(id);
3179 return ret;
3180 }
3181
3182 /*
3183 * Initialize the cached copies of the Identify data and various controller
3184 * register in our nvme_ctrl structure. This should be called as soon as
3185 * the admin queue is fully up and running.
3186 */
nvme_init_ctrl_finish(struct nvme_ctrl * ctrl,bool was_suspended)3187 int nvme_init_ctrl_finish(struct nvme_ctrl *ctrl, bool was_suspended)
3188 {
3189 int ret;
3190
3191 ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
3192 if (ret) {
3193 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
3194 return ret;
3195 }
3196
3197 ctrl->sqsize = min_t(u16, NVME_CAP_MQES(ctrl->cap), ctrl->sqsize);
3198
3199 if (ctrl->vs >= NVME_VS(1, 1, 0))
3200 ctrl->subsystem = NVME_CAP_NSSRC(ctrl->cap);
3201
3202 ret = nvme_init_identify(ctrl);
3203 if (ret)
3204 return ret;
3205
3206 ret = nvme_configure_apst(ctrl);
3207 if (ret < 0)
3208 return ret;
3209
3210 ret = nvme_configure_timestamp(ctrl);
3211 if (ret < 0)
3212 return ret;
3213
3214 ret = nvme_configure_host_options(ctrl);
3215 if (ret < 0)
3216 return ret;
3217
3218 nvme_configure_opal(ctrl, was_suspended);
3219
3220 if (!ctrl->identified && !nvme_discovery_ctrl(ctrl)) {
3221 /*
3222 * Do not return errors unless we are in a controller reset,
3223 * the controller works perfectly fine without hwmon.
3224 */
3225 ret = nvme_hwmon_init(ctrl);
3226 if (ret == -EINTR)
3227 return ret;
3228 }
3229
3230 clear_bit(NVME_CTRL_DIRTY_CAPABILITY, &ctrl->flags);
3231 ctrl->identified = true;
3232
3233 return 0;
3234 }
3235 EXPORT_SYMBOL_GPL(nvme_init_ctrl_finish);
3236
nvme_dev_open(struct inode * inode,struct file * file)3237 static int nvme_dev_open(struct inode *inode, struct file *file)
3238 {
3239 struct nvme_ctrl *ctrl =
3240 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3241
3242 switch (nvme_ctrl_state(ctrl)) {
3243 case NVME_CTRL_LIVE:
3244 break;
3245 default:
3246 return -EWOULDBLOCK;
3247 }
3248
3249 nvme_get_ctrl(ctrl);
3250 if (!try_module_get(ctrl->ops->module)) {
3251 nvme_put_ctrl(ctrl);
3252 return -EINVAL;
3253 }
3254
3255 file->private_data = ctrl;
3256 return 0;
3257 }
3258
nvme_dev_release(struct inode * inode,struct file * file)3259 static int nvme_dev_release(struct inode *inode, struct file *file)
3260 {
3261 struct nvme_ctrl *ctrl =
3262 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
3263
3264 module_put(ctrl->ops->module);
3265 nvme_put_ctrl(ctrl);
3266 return 0;
3267 }
3268
3269 static const struct file_operations nvme_dev_fops = {
3270 .owner = THIS_MODULE,
3271 .open = nvme_dev_open,
3272 .release = nvme_dev_release,
3273 .unlocked_ioctl = nvme_dev_ioctl,
3274 .compat_ioctl = compat_ptr_ioctl,
3275 .uring_cmd = nvme_dev_uring_cmd,
3276 };
3277
nvme_find_ns_head(struct nvme_ctrl * ctrl,unsigned nsid)3278 static struct nvme_ns_head *nvme_find_ns_head(struct nvme_ctrl *ctrl,
3279 unsigned nsid)
3280 {
3281 struct nvme_ns_head *h;
3282
3283 lockdep_assert_held(&ctrl->subsys->lock);
3284
3285 list_for_each_entry(h, &ctrl->subsys->nsheads, entry) {
3286 /*
3287 * Private namespaces can share NSIDs under some conditions.
3288 * In that case we can't use the same ns_head for namespaces
3289 * with the same NSID.
3290 */
3291 if (h->ns_id != nsid || !nvme_is_unique_nsid(ctrl, h))
3292 continue;
3293 if (!list_empty(&h->list) && nvme_tryget_ns_head(h))
3294 return h;
3295 }
3296
3297 return NULL;
3298 }
3299
nvme_subsys_check_duplicate_ids(struct nvme_subsystem * subsys,struct nvme_ns_ids * ids)3300 static int nvme_subsys_check_duplicate_ids(struct nvme_subsystem *subsys,
3301 struct nvme_ns_ids *ids)
3302 {
3303 bool has_uuid = !uuid_is_null(&ids->uuid);
3304 bool has_nguid = memchr_inv(ids->nguid, 0, sizeof(ids->nguid));
3305 bool has_eui64 = memchr_inv(ids->eui64, 0, sizeof(ids->eui64));
3306 struct nvme_ns_head *h;
3307
3308 lockdep_assert_held(&subsys->lock);
3309
3310 list_for_each_entry(h, &subsys->nsheads, entry) {
3311 if (has_uuid && uuid_equal(&ids->uuid, &h->ids.uuid))
3312 return -EINVAL;
3313 if (has_nguid &&
3314 memcmp(&ids->nguid, &h->ids.nguid, sizeof(ids->nguid)) == 0)
3315 return -EINVAL;
3316 if (has_eui64 &&
3317 memcmp(&ids->eui64, &h->ids.eui64, sizeof(ids->eui64)) == 0)
3318 return -EINVAL;
3319 }
3320
3321 return 0;
3322 }
3323
nvme_cdev_rel(struct device * dev)3324 static void nvme_cdev_rel(struct device *dev)
3325 {
3326 ida_free(&nvme_ns_chr_minor_ida, MINOR(dev->devt));
3327 }
3328
nvme_cdev_del(struct cdev * cdev,struct device * cdev_device)3329 void nvme_cdev_del(struct cdev *cdev, struct device *cdev_device)
3330 {
3331 cdev_device_del(cdev, cdev_device);
3332 put_device(cdev_device);
3333 }
3334
nvme_cdev_add(struct cdev * cdev,struct device * cdev_device,const struct file_operations * fops,struct module * owner)3335 int nvme_cdev_add(struct cdev *cdev, struct device *cdev_device,
3336 const struct file_operations *fops, struct module *owner)
3337 {
3338 int minor, ret;
3339
3340 minor = ida_alloc(&nvme_ns_chr_minor_ida, GFP_KERNEL);
3341 if (minor < 0)
3342 return minor;
3343 cdev_device->devt = MKDEV(MAJOR(nvme_ns_chr_devt), minor);
3344 cdev_device->class = nvme_ns_chr_class;
3345 cdev_device->release = nvme_cdev_rel;
3346 device_initialize(cdev_device);
3347 cdev_init(cdev, fops);
3348 cdev->owner = owner;
3349 ret = cdev_device_add(cdev, cdev_device);
3350 if (ret)
3351 put_device(cdev_device);
3352
3353 return ret;
3354 }
3355
nvme_ns_chr_open(struct inode * inode,struct file * file)3356 static int nvme_ns_chr_open(struct inode *inode, struct file *file)
3357 {
3358 return nvme_ns_open(container_of(inode->i_cdev, struct nvme_ns, cdev));
3359 }
3360
nvme_ns_chr_release(struct inode * inode,struct file * file)3361 static int nvme_ns_chr_release(struct inode *inode, struct file *file)
3362 {
3363 nvme_ns_release(container_of(inode->i_cdev, struct nvme_ns, cdev));
3364 return 0;
3365 }
3366
3367 static const struct file_operations nvme_ns_chr_fops = {
3368 .owner = THIS_MODULE,
3369 .open = nvme_ns_chr_open,
3370 .release = nvme_ns_chr_release,
3371 .unlocked_ioctl = nvme_ns_chr_ioctl,
3372 .compat_ioctl = compat_ptr_ioctl,
3373 .uring_cmd = nvme_ns_chr_uring_cmd,
3374 .uring_cmd_iopoll = nvme_ns_chr_uring_cmd_iopoll,
3375 };
3376
nvme_add_ns_cdev(struct nvme_ns * ns)3377 static int nvme_add_ns_cdev(struct nvme_ns *ns)
3378 {
3379 int ret;
3380
3381 ns->cdev_device.parent = ns->ctrl->device;
3382 ret = dev_set_name(&ns->cdev_device, "ng%dn%d",
3383 ns->ctrl->instance, ns->head->instance);
3384 if (ret)
3385 return ret;
3386
3387 return nvme_cdev_add(&ns->cdev, &ns->cdev_device, &nvme_ns_chr_fops,
3388 ns->ctrl->ops->module);
3389 }
3390
nvme_alloc_ns_head(struct nvme_ctrl * ctrl,struct nvme_ns_info * info)3391 static struct nvme_ns_head *nvme_alloc_ns_head(struct nvme_ctrl *ctrl,
3392 struct nvme_ns_info *info)
3393 {
3394 struct nvme_ns_head *head;
3395 size_t size = sizeof(*head);
3396 int ret = -ENOMEM;
3397
3398 #ifdef CONFIG_NVME_MULTIPATH
3399 size += num_possible_nodes() * sizeof(struct nvme_ns *);
3400 #endif
3401
3402 head = kzalloc(size, GFP_KERNEL);
3403 if (!head)
3404 goto out;
3405 ret = ida_alloc_min(&ctrl->subsys->ns_ida, 1, GFP_KERNEL);
3406 if (ret < 0)
3407 goto out_free_head;
3408 head->instance = ret;
3409 INIT_LIST_HEAD(&head->list);
3410 ret = init_srcu_struct(&head->srcu);
3411 if (ret)
3412 goto out_ida_remove;
3413 head->subsys = ctrl->subsys;
3414 head->ns_id = info->nsid;
3415 head->ids = info->ids;
3416 head->shared = info->is_shared;
3417 kref_init(&head->ref);
3418
3419 if (head->ids.csi) {
3420 ret = nvme_get_effects_log(ctrl, head->ids.csi, &head->effects);
3421 if (ret)
3422 goto out_cleanup_srcu;
3423 } else
3424 head->effects = ctrl->effects;
3425
3426 ret = nvme_mpath_alloc_disk(ctrl, head);
3427 if (ret)
3428 goto out_cleanup_srcu;
3429
3430 list_add_tail(&head->entry, &ctrl->subsys->nsheads);
3431
3432 kref_get(&ctrl->subsys->ref);
3433
3434 return head;
3435 out_cleanup_srcu:
3436 cleanup_srcu_struct(&head->srcu);
3437 out_ida_remove:
3438 ida_free(&ctrl->subsys->ns_ida, head->instance);
3439 out_free_head:
3440 kfree(head);
3441 out:
3442 if (ret > 0)
3443 ret = blk_status_to_errno(nvme_error_status(ret));
3444 return ERR_PTR(ret);
3445 }
3446
nvme_global_check_duplicate_ids(struct nvme_subsystem * this,struct nvme_ns_ids * ids)3447 static int nvme_global_check_duplicate_ids(struct nvme_subsystem *this,
3448 struct nvme_ns_ids *ids)
3449 {
3450 struct nvme_subsystem *s;
3451 int ret = 0;
3452
3453 /*
3454 * Note that this check is racy as we try to avoid holding the global
3455 * lock over the whole ns_head creation. But it is only intended as
3456 * a sanity check anyway.
3457 */
3458 mutex_lock(&nvme_subsystems_lock);
3459 list_for_each_entry(s, &nvme_subsystems, entry) {
3460 if (s == this)
3461 continue;
3462 mutex_lock(&s->lock);
3463 ret = nvme_subsys_check_duplicate_ids(s, ids);
3464 mutex_unlock(&s->lock);
3465 if (ret)
3466 break;
3467 }
3468 mutex_unlock(&nvme_subsystems_lock);
3469
3470 return ret;
3471 }
3472
nvme_init_ns_head(struct nvme_ns * ns,struct nvme_ns_info * info)3473 static int nvme_init_ns_head(struct nvme_ns *ns, struct nvme_ns_info *info)
3474 {
3475 struct nvme_ctrl *ctrl = ns->ctrl;
3476 struct nvme_ns_head *head = NULL;
3477 int ret;
3478
3479 ret = nvme_global_check_duplicate_ids(ctrl->subsys, &info->ids);
3480 if (ret) {
3481 /*
3482 * We've found two different namespaces on two different
3483 * subsystems that report the same ID. This is pretty nasty
3484 * for anything that actually requires unique device
3485 * identification. In the kernel we need this for multipathing,
3486 * and in user space the /dev/disk/by-id/ links rely on it.
3487 *
3488 * If the device also claims to be multi-path capable back off
3489 * here now and refuse the probe the second device as this is a
3490 * recipe for data corruption. If not this is probably a
3491 * cheap consumer device if on the PCIe bus, so let the user
3492 * proceed and use the shiny toy, but warn that with changing
3493 * probing order (which due to our async probing could just be
3494 * device taking longer to startup) the other device could show
3495 * up at any time.
3496 */
3497 nvme_print_device_info(ctrl);
3498 if ((ns->ctrl->ops->flags & NVME_F_FABRICS) || /* !PCIe */
3499 ((ns->ctrl->subsys->cmic & NVME_CTRL_CMIC_MULTI_CTRL) &&
3500 info->is_shared)) {
3501 dev_err(ctrl->device,
3502 "ignoring nsid %d because of duplicate IDs\n",
3503 info->nsid);
3504 return ret;
3505 }
3506
3507 dev_err(ctrl->device,
3508 "clearing duplicate IDs for nsid %d\n", info->nsid);
3509 dev_err(ctrl->device,
3510 "use of /dev/disk/by-id/ may cause data corruption\n");
3511 memset(&info->ids.nguid, 0, sizeof(info->ids.nguid));
3512 memset(&info->ids.uuid, 0, sizeof(info->ids.uuid));
3513 memset(&info->ids.eui64, 0, sizeof(info->ids.eui64));
3514 ctrl->quirks |= NVME_QUIRK_BOGUS_NID;
3515 }
3516
3517 mutex_lock(&ctrl->subsys->lock);
3518 head = nvme_find_ns_head(ctrl, info->nsid);
3519 if (!head) {
3520 ret = nvme_subsys_check_duplicate_ids(ctrl->subsys, &info->ids);
3521 if (ret) {
3522 dev_err(ctrl->device,
3523 "duplicate IDs in subsystem for nsid %d\n",
3524 info->nsid);
3525 goto out_unlock;
3526 }
3527 head = nvme_alloc_ns_head(ctrl, info);
3528 if (IS_ERR(head)) {
3529 ret = PTR_ERR(head);
3530 goto out_unlock;
3531 }
3532 } else {
3533 ret = -EINVAL;
3534 if (!info->is_shared || !head->shared) {
3535 dev_err(ctrl->device,
3536 "Duplicate unshared namespace %d\n",
3537 info->nsid);
3538 goto out_put_ns_head;
3539 }
3540 if (!nvme_ns_ids_equal(&head->ids, &info->ids)) {
3541 dev_err(ctrl->device,
3542 "IDs don't match for shared namespace %d\n",
3543 info->nsid);
3544 goto out_put_ns_head;
3545 }
3546
3547 if (!multipath) {
3548 dev_warn(ctrl->device,
3549 "Found shared namespace %d, but multipathing not supported.\n",
3550 info->nsid);
3551 dev_warn_once(ctrl->device,
3552 "Support for shared namespaces without CONFIG_NVME_MULTIPATH is deprecated and will be removed in Linux 6.0.\n");
3553 }
3554 }
3555
3556 list_add_tail_rcu(&ns->siblings, &head->list);
3557 ns->head = head;
3558 mutex_unlock(&ctrl->subsys->lock);
3559 return 0;
3560
3561 out_put_ns_head:
3562 nvme_put_ns_head(head);
3563 out_unlock:
3564 mutex_unlock(&ctrl->subsys->lock);
3565 return ret;
3566 }
3567
nvme_find_get_ns(struct nvme_ctrl * ctrl,unsigned nsid)3568 struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3569 {
3570 struct nvme_ns *ns, *ret = NULL;
3571 int srcu_idx;
3572
3573 srcu_idx = srcu_read_lock(&ctrl->srcu);
3574 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
3575 srcu_read_lock_held(&ctrl->srcu)) {
3576 if (ns->head->ns_id == nsid) {
3577 if (!nvme_get_ns(ns))
3578 continue;
3579 ret = ns;
3580 break;
3581 }
3582 if (ns->head->ns_id > nsid)
3583 break;
3584 }
3585 srcu_read_unlock(&ctrl->srcu, srcu_idx);
3586 return ret;
3587 }
3588 EXPORT_SYMBOL_NS_GPL(nvme_find_get_ns, NVME_TARGET_PASSTHRU);
3589
3590 /*
3591 * Add the namespace to the controller list while keeping the list ordered.
3592 */
nvme_ns_add_to_ctrl_list(struct nvme_ns * ns)3593 static void nvme_ns_add_to_ctrl_list(struct nvme_ns *ns)
3594 {
3595 struct nvme_ns *tmp;
3596
3597 list_for_each_entry_reverse(tmp, &ns->ctrl->namespaces, list) {
3598 if (tmp->head->ns_id < ns->head->ns_id) {
3599 list_add_rcu(&ns->list, &tmp->list);
3600 return;
3601 }
3602 }
3603 list_add_rcu(&ns->list, &ns->ctrl->namespaces);
3604 }
3605
nvme_alloc_ns(struct nvme_ctrl * ctrl,struct nvme_ns_info * info)3606 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, struct nvme_ns_info *info)
3607 {
3608 struct nvme_ns *ns;
3609 struct gendisk *disk;
3610 int node = ctrl->numa_node;
3611
3612 ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
3613 if (!ns)
3614 return;
3615
3616 disk = blk_mq_alloc_disk(ctrl->tagset, ns);
3617 if (IS_ERR(disk))
3618 goto out_free_ns;
3619 disk->fops = &nvme_bdev_ops;
3620 disk->private_data = ns;
3621
3622 ns->disk = disk;
3623 ns->queue = disk->queue;
3624
3625 if (ctrl->opts && ctrl->opts->data_digest)
3626 blk_queue_flag_set(QUEUE_FLAG_STABLE_WRITES, ns->queue);
3627
3628 blk_queue_flag_set(QUEUE_FLAG_NONROT, ns->queue);
3629 if (ctrl->ops->supports_pci_p2pdma &&
3630 ctrl->ops->supports_pci_p2pdma(ctrl))
3631 blk_queue_flag_set(QUEUE_FLAG_PCI_P2PDMA, ns->queue);
3632
3633 ns->ctrl = ctrl;
3634 kref_init(&ns->kref);
3635
3636 if (nvme_init_ns_head(ns, info))
3637 goto out_cleanup_disk;
3638
3639 /*
3640 * If multipathing is enabled, the device name for all disks and not
3641 * just those that represent shared namespaces needs to be based on the
3642 * subsystem instance. Using the controller instance for private
3643 * namespaces could lead to naming collisions between shared and private
3644 * namespaces if they don't use a common numbering scheme.
3645 *
3646 * If multipathing is not enabled, disk names must use the controller
3647 * instance as shared namespaces will show up as multiple block
3648 * devices.
3649 */
3650 if (nvme_ns_head_multipath(ns->head)) {
3651 sprintf(disk->disk_name, "nvme%dc%dn%d", ctrl->subsys->instance,
3652 ctrl->instance, ns->head->instance);
3653 disk->flags |= GENHD_FL_HIDDEN;
3654 } else if (multipath) {
3655 sprintf(disk->disk_name, "nvme%dn%d", ctrl->subsys->instance,
3656 ns->head->instance);
3657 } else {
3658 sprintf(disk->disk_name, "nvme%dn%d", ctrl->instance,
3659 ns->head->instance);
3660 }
3661
3662 if (nvme_update_ns_info(ns, info))
3663 goto out_unlink_ns;
3664
3665 mutex_lock(&ctrl->namespaces_lock);
3666 /*
3667 * Ensure that no namespaces are added to the ctrl list after the queues
3668 * are frozen, thereby avoiding a deadlock between scan and reset.
3669 */
3670 if (test_bit(NVME_CTRL_FROZEN, &ctrl->flags)) {
3671 mutex_unlock(&ctrl->namespaces_lock);
3672 goto out_unlink_ns;
3673 }
3674 nvme_ns_add_to_ctrl_list(ns);
3675 mutex_unlock(&ctrl->namespaces_lock);
3676 synchronize_srcu(&ctrl->srcu);
3677 nvme_get_ctrl(ctrl);
3678
3679 if (device_add_disk(ctrl->device, ns->disk, nvme_ns_id_attr_groups))
3680 goto out_cleanup_ns_from_list;
3681
3682 if (!nvme_ns_head_multipath(ns->head))
3683 nvme_add_ns_cdev(ns);
3684
3685 nvme_mpath_add_disk(ns, info->anagrpid);
3686 nvme_fault_inject_init(&ns->fault_inject, ns->disk->disk_name);
3687
3688 return;
3689
3690 out_cleanup_ns_from_list:
3691 nvme_put_ctrl(ctrl);
3692 mutex_lock(&ctrl->namespaces_lock);
3693 list_del_rcu(&ns->list);
3694 mutex_unlock(&ctrl->namespaces_lock);
3695 synchronize_srcu(&ctrl->srcu);
3696 out_unlink_ns:
3697 mutex_lock(&ctrl->subsys->lock);
3698 list_del_rcu(&ns->siblings);
3699 if (list_empty(&ns->head->list))
3700 list_del_init(&ns->head->entry);
3701 mutex_unlock(&ctrl->subsys->lock);
3702 nvme_put_ns_head(ns->head);
3703 out_cleanup_disk:
3704 put_disk(disk);
3705 out_free_ns:
3706 kfree(ns);
3707 }
3708
nvme_ns_remove(struct nvme_ns * ns)3709 static void nvme_ns_remove(struct nvme_ns *ns)
3710 {
3711 bool last_path = false;
3712
3713 if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
3714 return;
3715
3716 clear_bit(NVME_NS_READY, &ns->flags);
3717 set_capacity(ns->disk, 0);
3718 nvme_fault_inject_fini(&ns->fault_inject);
3719
3720 /*
3721 * Ensure that !NVME_NS_READY is seen by other threads to prevent
3722 * this ns going back into current_path.
3723 */
3724 synchronize_srcu(&ns->head->srcu);
3725
3726 /* wait for concurrent submissions */
3727 if (nvme_mpath_clear_current_path(ns))
3728 synchronize_srcu(&ns->head->srcu);
3729
3730 mutex_lock(&ns->ctrl->subsys->lock);
3731 list_del_rcu(&ns->siblings);
3732 if (list_empty(&ns->head->list)) {
3733 list_del_init(&ns->head->entry);
3734 last_path = true;
3735 }
3736 mutex_unlock(&ns->ctrl->subsys->lock);
3737
3738 /* guarantee not available in head->list */
3739 synchronize_srcu(&ns->head->srcu);
3740
3741 if (!nvme_ns_head_multipath(ns->head))
3742 nvme_cdev_del(&ns->cdev, &ns->cdev_device);
3743 del_gendisk(ns->disk);
3744
3745 mutex_lock(&ns->ctrl->namespaces_lock);
3746 list_del_rcu(&ns->list);
3747 mutex_unlock(&ns->ctrl->namespaces_lock);
3748 synchronize_srcu(&ns->ctrl->srcu);
3749
3750 if (last_path)
3751 nvme_mpath_shutdown_disk(ns->head);
3752 nvme_put_ns(ns);
3753 }
3754
nvme_ns_remove_by_nsid(struct nvme_ctrl * ctrl,u32 nsid)3755 static void nvme_ns_remove_by_nsid(struct nvme_ctrl *ctrl, u32 nsid)
3756 {
3757 struct nvme_ns *ns = nvme_find_get_ns(ctrl, nsid);
3758
3759 if (ns) {
3760 nvme_ns_remove(ns);
3761 nvme_put_ns(ns);
3762 }
3763 }
3764
nvme_validate_ns(struct nvme_ns * ns,struct nvme_ns_info * info)3765 static void nvme_validate_ns(struct nvme_ns *ns, struct nvme_ns_info *info)
3766 {
3767 int ret = NVME_SC_INVALID_NS | NVME_SC_DNR;
3768
3769 if (!nvme_ns_ids_equal(&ns->head->ids, &info->ids)) {
3770 dev_err(ns->ctrl->device,
3771 "identifiers changed for nsid %d\n", ns->head->ns_id);
3772 goto out;
3773 }
3774
3775 ret = nvme_update_ns_info(ns, info);
3776 out:
3777 /*
3778 * Only remove the namespace if we got a fatal error back from the
3779 * device, otherwise ignore the error and just move on.
3780 *
3781 * TODO: we should probably schedule a delayed retry here.
3782 */
3783 if (ret > 0 && (ret & NVME_SC_DNR))
3784 nvme_ns_remove(ns);
3785 }
3786
nvme_scan_ns(struct nvme_ctrl * ctrl,unsigned nsid)3787 static void nvme_scan_ns(struct nvme_ctrl *ctrl, unsigned nsid)
3788 {
3789 struct nvme_ns_info info = { .nsid = nsid };
3790 struct nvme_ns *ns;
3791 int ret;
3792
3793 if (nvme_identify_ns_descs(ctrl, &info))
3794 return;
3795
3796 if (info.ids.csi != NVME_CSI_NVM && !nvme_multi_css(ctrl)) {
3797 dev_warn(ctrl->device,
3798 "command set not reported for nsid: %d\n", nsid);
3799 return;
3800 }
3801
3802 /*
3803 * If available try to use the Command Set Idependent Identify Namespace
3804 * data structure to find all the generic information that is needed to
3805 * set up a namespace. If not fall back to the legacy version.
3806 */
3807 if ((ctrl->cap & NVME_CAP_CRMS_CRIMS) ||
3808 (info.ids.csi != NVME_CSI_NVM && info.ids.csi != NVME_CSI_ZNS))
3809 ret = nvme_ns_info_from_id_cs_indep(ctrl, &info);
3810 else
3811 ret = nvme_ns_info_from_identify(ctrl, &info);
3812
3813 if (info.is_removed)
3814 nvme_ns_remove_by_nsid(ctrl, nsid);
3815
3816 /*
3817 * Ignore the namespace if it is not ready. We will get an AEN once it
3818 * becomes ready and restart the scan.
3819 */
3820 if (ret || !info.is_ready)
3821 return;
3822
3823 ns = nvme_find_get_ns(ctrl, nsid);
3824 if (ns) {
3825 nvme_validate_ns(ns, &info);
3826 nvme_put_ns(ns);
3827 } else {
3828 nvme_alloc_ns(ctrl, &info);
3829 }
3830 }
3831
nvme_remove_invalid_namespaces(struct nvme_ctrl * ctrl,unsigned nsid)3832 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
3833 unsigned nsid)
3834 {
3835 struct nvme_ns *ns, *next;
3836 LIST_HEAD(rm_list);
3837
3838 mutex_lock(&ctrl->namespaces_lock);
3839 list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
3840 if (ns->head->ns_id > nsid) {
3841 list_del_rcu(&ns->list);
3842 synchronize_srcu(&ctrl->srcu);
3843 list_add_tail_rcu(&ns->list, &rm_list);
3844 }
3845 }
3846 mutex_unlock(&ctrl->namespaces_lock);
3847
3848 list_for_each_entry_safe(ns, next, &rm_list, list)
3849 nvme_ns_remove(ns);
3850 }
3851
nvme_scan_ns_list(struct nvme_ctrl * ctrl)3852 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl)
3853 {
3854 const int nr_entries = NVME_IDENTIFY_DATA_SIZE / sizeof(__le32);
3855 __le32 *ns_list;
3856 u32 prev = 0;
3857 int ret = 0, i;
3858
3859 ns_list = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
3860 if (!ns_list)
3861 return -ENOMEM;
3862
3863 for (;;) {
3864 struct nvme_command cmd = {
3865 .identify.opcode = nvme_admin_identify,
3866 .identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST,
3867 .identify.nsid = cpu_to_le32(prev),
3868 };
3869
3870 ret = nvme_submit_sync_cmd(ctrl->admin_q, &cmd, ns_list,
3871 NVME_IDENTIFY_DATA_SIZE);
3872 if (ret) {
3873 dev_warn(ctrl->device,
3874 "Identify NS List failed (status=0x%x)\n", ret);
3875 goto free;
3876 }
3877
3878 for (i = 0; i < nr_entries; i++) {
3879 u32 nsid = le32_to_cpu(ns_list[i]);
3880
3881 if (!nsid) /* end of the list? */
3882 goto out;
3883 nvme_scan_ns(ctrl, nsid);
3884 while (++prev < nsid)
3885 nvme_ns_remove_by_nsid(ctrl, prev);
3886 }
3887 }
3888 out:
3889 nvme_remove_invalid_namespaces(ctrl, prev);
3890 free:
3891 kfree(ns_list);
3892 return ret;
3893 }
3894
nvme_scan_ns_sequential(struct nvme_ctrl * ctrl)3895 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl)
3896 {
3897 struct nvme_id_ctrl *id;
3898 u32 nn, i;
3899
3900 if (nvme_identify_ctrl(ctrl, &id))
3901 return;
3902 nn = le32_to_cpu(id->nn);
3903 kfree(id);
3904
3905 for (i = 1; i <= nn; i++)
3906 nvme_scan_ns(ctrl, i);
3907
3908 nvme_remove_invalid_namespaces(ctrl, nn);
3909 }
3910
nvme_clear_changed_ns_log(struct nvme_ctrl * ctrl)3911 static void nvme_clear_changed_ns_log(struct nvme_ctrl *ctrl)
3912 {
3913 size_t log_size = NVME_MAX_CHANGED_NAMESPACES * sizeof(__le32);
3914 __le32 *log;
3915 int error;
3916
3917 log = kzalloc(log_size, GFP_KERNEL);
3918 if (!log)
3919 return;
3920
3921 /*
3922 * We need to read the log to clear the AEN, but we don't want to rely
3923 * on it for the changed namespace information as userspace could have
3924 * raced with us in reading the log page, which could cause us to miss
3925 * updates.
3926 */
3927 error = nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_CHANGED_NS, 0,
3928 NVME_CSI_NVM, log, log_size, 0);
3929 if (error)
3930 dev_warn(ctrl->device,
3931 "reading changed ns log failed: %d\n", error);
3932
3933 kfree(log);
3934 }
3935
nvme_scan_work(struct work_struct * work)3936 static void nvme_scan_work(struct work_struct *work)
3937 {
3938 struct nvme_ctrl *ctrl =
3939 container_of(work, struct nvme_ctrl, scan_work);
3940 int ret;
3941
3942 /* No tagset on a live ctrl means IO queues could not created */
3943 if (nvme_ctrl_state(ctrl) != NVME_CTRL_LIVE || !ctrl->tagset)
3944 return;
3945
3946 /*
3947 * Identify controller limits can change at controller reset due to
3948 * new firmware download, even though it is not common we cannot ignore
3949 * such scenario. Controller's non-mdts limits are reported in the unit
3950 * of logical blocks that is dependent on the format of attached
3951 * namespace. Hence re-read the limits at the time of ns allocation.
3952 */
3953 ret = nvme_init_non_mdts_limits(ctrl);
3954 if (ret < 0) {
3955 dev_warn(ctrl->device,
3956 "reading non-mdts-limits failed: %d\n", ret);
3957 return;
3958 }
3959
3960 if (test_and_clear_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events)) {
3961 dev_info(ctrl->device, "rescanning namespaces.\n");
3962 nvme_clear_changed_ns_log(ctrl);
3963 }
3964
3965 mutex_lock(&ctrl->scan_lock);
3966 if (nvme_ctrl_limited_cns(ctrl)) {
3967 nvme_scan_ns_sequential(ctrl);
3968 } else {
3969 /*
3970 * Fall back to sequential scan if DNR is set to handle broken
3971 * devices which should support Identify NS List (as per the VS
3972 * they report) but don't actually support it.
3973 */
3974 ret = nvme_scan_ns_list(ctrl);
3975 if (ret > 0 && ret & NVME_SC_DNR)
3976 nvme_scan_ns_sequential(ctrl);
3977 }
3978 mutex_unlock(&ctrl->scan_lock);
3979
3980 /* Requeue if we have missed AENs */
3981 if (test_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events))
3982 nvme_queue_scan(ctrl);
3983 #ifdef CONFIG_NVME_MULTIPATH
3984 else if (ctrl->ana_log_buf)
3985 /* Re-read the ANA log page to not miss updates */
3986 queue_work(nvme_wq, &ctrl->ana_work);
3987 #endif
3988 }
3989
3990 /*
3991 * This function iterates the namespace list unlocked to allow recovery from
3992 * controller failure. It is up to the caller to ensure the namespace list is
3993 * not modified by scan work while this function is executing.
3994 */
nvme_remove_namespaces(struct nvme_ctrl * ctrl)3995 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
3996 {
3997 struct nvme_ns *ns, *next;
3998 LIST_HEAD(ns_list);
3999
4000 /*
4001 * make sure to requeue I/O to all namespaces as these
4002 * might result from the scan itself and must complete
4003 * for the scan_work to make progress
4004 */
4005 nvme_mpath_clear_ctrl_paths(ctrl);
4006
4007 /*
4008 * Unquiesce io queues so any pending IO won't hang, especially
4009 * those submitted from scan work
4010 */
4011 nvme_unquiesce_io_queues(ctrl);
4012
4013 /* prevent racing with ns scanning */
4014 flush_work(&ctrl->scan_work);
4015
4016 /*
4017 * The dead states indicates the controller was not gracefully
4018 * disconnected. In that case, we won't be able to flush any data while
4019 * removing the namespaces' disks; fail all the queues now to avoid
4020 * potentially having to clean up the failed sync later.
4021 */
4022 if (nvme_ctrl_state(ctrl) == NVME_CTRL_DEAD)
4023 nvme_mark_namespaces_dead(ctrl);
4024
4025 /* this is a no-op when called from the controller reset handler */
4026 nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING_NOIO);
4027
4028 mutex_lock(&ctrl->namespaces_lock);
4029 list_splice_init_rcu(&ctrl->namespaces, &ns_list, synchronize_rcu);
4030 mutex_unlock(&ctrl->namespaces_lock);
4031 synchronize_srcu(&ctrl->srcu);
4032
4033 list_for_each_entry_safe(ns, next, &ns_list, list)
4034 nvme_ns_remove(ns);
4035 }
4036 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
4037
nvme_class_uevent(const struct device * dev,struct kobj_uevent_env * env)4038 static int nvme_class_uevent(const struct device *dev, struct kobj_uevent_env *env)
4039 {
4040 const struct nvme_ctrl *ctrl =
4041 container_of(dev, struct nvme_ctrl, ctrl_device);
4042 struct nvmf_ctrl_options *opts = ctrl->opts;
4043 int ret;
4044
4045 ret = add_uevent_var(env, "NVME_TRTYPE=%s", ctrl->ops->name);
4046 if (ret)
4047 return ret;
4048
4049 if (opts) {
4050 ret = add_uevent_var(env, "NVME_TRADDR=%s", opts->traddr);
4051 if (ret)
4052 return ret;
4053
4054 ret = add_uevent_var(env, "NVME_TRSVCID=%s",
4055 opts->trsvcid ?: "none");
4056 if (ret)
4057 return ret;
4058
4059 ret = add_uevent_var(env, "NVME_HOST_TRADDR=%s",
4060 opts->host_traddr ?: "none");
4061 if (ret)
4062 return ret;
4063
4064 ret = add_uevent_var(env, "NVME_HOST_IFACE=%s",
4065 opts->host_iface ?: "none");
4066 }
4067 return ret;
4068 }
4069
nvme_change_uevent(struct nvme_ctrl * ctrl,char * envdata)4070 static void nvme_change_uevent(struct nvme_ctrl *ctrl, char *envdata)
4071 {
4072 char *envp[2] = { envdata, NULL };
4073
4074 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4075 }
4076
nvme_aen_uevent(struct nvme_ctrl * ctrl)4077 static void nvme_aen_uevent(struct nvme_ctrl *ctrl)
4078 {
4079 char *envp[2] = { NULL, NULL };
4080 u32 aen_result = ctrl->aen_result;
4081
4082 ctrl->aen_result = 0;
4083 if (!aen_result)
4084 return;
4085
4086 envp[0] = kasprintf(GFP_KERNEL, "NVME_AEN=%#08x", aen_result);
4087 if (!envp[0])
4088 return;
4089 kobject_uevent_env(&ctrl->device->kobj, KOBJ_CHANGE, envp);
4090 kfree(envp[0]);
4091 }
4092
nvme_async_event_work(struct work_struct * work)4093 static void nvme_async_event_work(struct work_struct *work)
4094 {
4095 struct nvme_ctrl *ctrl =
4096 container_of(work, struct nvme_ctrl, async_event_work);
4097
4098 nvme_aen_uevent(ctrl);
4099
4100 /*
4101 * The transport drivers must guarantee AER submission here is safe by
4102 * flushing ctrl async_event_work after changing the controller state
4103 * from LIVE and before freeing the admin queue.
4104 */
4105 if (nvme_ctrl_state(ctrl) == NVME_CTRL_LIVE)
4106 ctrl->ops->submit_async_event(ctrl);
4107 }
4108
nvme_ctrl_pp_status(struct nvme_ctrl * ctrl)4109 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
4110 {
4111
4112 u32 csts;
4113
4114 if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
4115 return false;
4116
4117 if (csts == ~0)
4118 return false;
4119
4120 return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
4121 }
4122
nvme_get_fw_slot_info(struct nvme_ctrl * ctrl)4123 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
4124 {
4125 struct nvme_fw_slot_info_log *log;
4126
4127 log = kmalloc(sizeof(*log), GFP_KERNEL);
4128 if (!log)
4129 return;
4130
4131 if (nvme_get_log(ctrl, NVME_NSID_ALL, NVME_LOG_FW_SLOT, 0, NVME_CSI_NVM,
4132 log, sizeof(*log), 0))
4133 dev_warn(ctrl->device, "Get FW SLOT INFO log error\n");
4134 kfree(log);
4135 }
4136
nvme_fw_act_work(struct work_struct * work)4137 static void nvme_fw_act_work(struct work_struct *work)
4138 {
4139 struct nvme_ctrl *ctrl = container_of(work,
4140 struct nvme_ctrl, fw_act_work);
4141 unsigned long fw_act_timeout;
4142
4143 nvme_auth_stop(ctrl);
4144
4145 if (ctrl->mtfa)
4146 fw_act_timeout = jiffies +
4147 msecs_to_jiffies(ctrl->mtfa * 100);
4148 else
4149 fw_act_timeout = jiffies +
4150 msecs_to_jiffies(admin_timeout * 1000);
4151
4152 nvme_quiesce_io_queues(ctrl);
4153 while (nvme_ctrl_pp_status(ctrl)) {
4154 if (time_after(jiffies, fw_act_timeout)) {
4155 dev_warn(ctrl->device,
4156 "Fw activation timeout, reset controller\n");
4157 nvme_try_sched_reset(ctrl);
4158 return;
4159 }
4160 msleep(100);
4161 }
4162
4163 if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_CONNECTING) ||
4164 !nvme_change_ctrl_state(ctrl, NVME_CTRL_LIVE))
4165 return;
4166
4167 nvme_unquiesce_io_queues(ctrl);
4168 /* read FW slot information to clear the AER */
4169 nvme_get_fw_slot_info(ctrl);
4170
4171 queue_work(nvme_wq, &ctrl->async_event_work);
4172 }
4173
nvme_aer_type(u32 result)4174 static u32 nvme_aer_type(u32 result)
4175 {
4176 return result & 0x7;
4177 }
4178
nvme_aer_subtype(u32 result)4179 static u32 nvme_aer_subtype(u32 result)
4180 {
4181 return (result & 0xff00) >> 8;
4182 }
4183
nvme_handle_aen_notice(struct nvme_ctrl * ctrl,u32 result)4184 static bool nvme_handle_aen_notice(struct nvme_ctrl *ctrl, u32 result)
4185 {
4186 u32 aer_notice_type = nvme_aer_subtype(result);
4187 bool requeue = true;
4188
4189 switch (aer_notice_type) {
4190 case NVME_AER_NOTICE_NS_CHANGED:
4191 set_bit(NVME_AER_NOTICE_NS_CHANGED, &ctrl->events);
4192 nvme_queue_scan(ctrl);
4193 break;
4194 case NVME_AER_NOTICE_FW_ACT_STARTING:
4195 /*
4196 * We are (ab)using the RESETTING state to prevent subsequent
4197 * recovery actions from interfering with the controller's
4198 * firmware activation.
4199 */
4200 if (nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING)) {
4201 requeue = false;
4202 queue_work(nvme_wq, &ctrl->fw_act_work);
4203 }
4204 break;
4205 #ifdef CONFIG_NVME_MULTIPATH
4206 case NVME_AER_NOTICE_ANA:
4207 if (!ctrl->ana_log_buf)
4208 break;
4209 queue_work(nvme_wq, &ctrl->ana_work);
4210 break;
4211 #endif
4212 case NVME_AER_NOTICE_DISC_CHANGED:
4213 ctrl->aen_result = result;
4214 break;
4215 default:
4216 dev_warn(ctrl->device, "async event result %08x\n", result);
4217 }
4218 return requeue;
4219 }
4220
nvme_handle_aer_persistent_error(struct nvme_ctrl * ctrl)4221 static void nvme_handle_aer_persistent_error(struct nvme_ctrl *ctrl)
4222 {
4223 dev_warn(ctrl->device, "resetting controller due to AER\n");
4224 nvme_reset_ctrl(ctrl);
4225 }
4226
nvme_complete_async_event(struct nvme_ctrl * ctrl,__le16 status,volatile union nvme_result * res)4227 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
4228 volatile union nvme_result *res)
4229 {
4230 u32 result = le32_to_cpu(res->u32);
4231 u32 aer_type = nvme_aer_type(result);
4232 u32 aer_subtype = nvme_aer_subtype(result);
4233 bool requeue = true;
4234
4235 if (le16_to_cpu(status) >> 1 != NVME_SC_SUCCESS)
4236 return;
4237
4238 trace_nvme_async_event(ctrl, result);
4239 switch (aer_type) {
4240 case NVME_AER_NOTICE:
4241 requeue = nvme_handle_aen_notice(ctrl, result);
4242 break;
4243 case NVME_AER_ERROR:
4244 /*
4245 * For a persistent internal error, don't run async_event_work
4246 * to submit a new AER. The controller reset will do it.
4247 */
4248 if (aer_subtype == NVME_AER_ERROR_PERSIST_INT_ERR) {
4249 nvme_handle_aer_persistent_error(ctrl);
4250 return;
4251 }
4252 fallthrough;
4253 case NVME_AER_SMART:
4254 case NVME_AER_CSS:
4255 case NVME_AER_VS:
4256 ctrl->aen_result = result;
4257 break;
4258 default:
4259 break;
4260 }
4261
4262 if (requeue)
4263 queue_work(nvme_wq, &ctrl->async_event_work);
4264 }
4265 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
4266
nvme_alloc_admin_tag_set(struct nvme_ctrl * ctrl,struct blk_mq_tag_set * set,const struct blk_mq_ops * ops,unsigned int cmd_size)4267 int nvme_alloc_admin_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
4268 const struct blk_mq_ops *ops, unsigned int cmd_size)
4269 {
4270 int ret;
4271
4272 memset(set, 0, sizeof(*set));
4273 set->ops = ops;
4274 set->queue_depth = NVME_AQ_MQ_TAG_DEPTH;
4275 if (ctrl->ops->flags & NVME_F_FABRICS)
4276 /* Reserved for fabric connect and keep alive */
4277 set->reserved_tags = 2;
4278 set->numa_node = ctrl->numa_node;
4279 set->flags = BLK_MQ_F_NO_SCHED;
4280 if (ctrl->ops->flags & NVME_F_BLOCKING)
4281 set->flags |= BLK_MQ_F_BLOCKING;
4282 set->cmd_size = cmd_size;
4283 set->driver_data = ctrl;
4284 set->nr_hw_queues = 1;
4285 set->timeout = NVME_ADMIN_TIMEOUT;
4286 ret = blk_mq_alloc_tag_set(set);
4287 if (ret)
4288 return ret;
4289
4290 ctrl->admin_q = blk_mq_init_queue(set);
4291 if (IS_ERR(ctrl->admin_q)) {
4292 ret = PTR_ERR(ctrl->admin_q);
4293 goto out_free_tagset;
4294 }
4295
4296 if (ctrl->ops->flags & NVME_F_FABRICS) {
4297 ctrl->fabrics_q = blk_mq_init_queue(set);
4298 if (IS_ERR(ctrl->fabrics_q)) {
4299 ret = PTR_ERR(ctrl->fabrics_q);
4300 goto out_cleanup_admin_q;
4301 }
4302 }
4303
4304 ctrl->admin_tagset = set;
4305 return 0;
4306
4307 out_cleanup_admin_q:
4308 blk_mq_destroy_queue(ctrl->admin_q);
4309 blk_put_queue(ctrl->admin_q);
4310 out_free_tagset:
4311 blk_mq_free_tag_set(set);
4312 ctrl->admin_q = NULL;
4313 ctrl->fabrics_q = NULL;
4314 return ret;
4315 }
4316 EXPORT_SYMBOL_GPL(nvme_alloc_admin_tag_set);
4317
nvme_remove_admin_tag_set(struct nvme_ctrl * ctrl)4318 void nvme_remove_admin_tag_set(struct nvme_ctrl *ctrl)
4319 {
4320 blk_mq_destroy_queue(ctrl->admin_q);
4321 blk_put_queue(ctrl->admin_q);
4322 if (ctrl->ops->flags & NVME_F_FABRICS) {
4323 blk_mq_destroy_queue(ctrl->fabrics_q);
4324 blk_put_queue(ctrl->fabrics_q);
4325 }
4326 blk_mq_free_tag_set(ctrl->admin_tagset);
4327 }
4328 EXPORT_SYMBOL_GPL(nvme_remove_admin_tag_set);
4329
nvme_alloc_io_tag_set(struct nvme_ctrl * ctrl,struct blk_mq_tag_set * set,const struct blk_mq_ops * ops,unsigned int nr_maps,unsigned int cmd_size)4330 int nvme_alloc_io_tag_set(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set,
4331 const struct blk_mq_ops *ops, unsigned int nr_maps,
4332 unsigned int cmd_size)
4333 {
4334 int ret;
4335
4336 memset(set, 0, sizeof(*set));
4337 set->ops = ops;
4338 set->queue_depth = min_t(unsigned, ctrl->sqsize, BLK_MQ_MAX_DEPTH - 1);
4339 /*
4340 * Some Apple controllers requires tags to be unique across admin and
4341 * the (only) I/O queue, so reserve the first 32 tags of the I/O queue.
4342 */
4343 if (ctrl->quirks & NVME_QUIRK_SHARED_TAGS)
4344 set->reserved_tags = NVME_AQ_DEPTH;
4345 else if (ctrl->ops->flags & NVME_F_FABRICS)
4346 /* Reserved for fabric connect */
4347 set->reserved_tags = 1;
4348 set->numa_node = ctrl->numa_node;
4349 set->flags = BLK_MQ_F_SHOULD_MERGE;
4350 if (ctrl->ops->flags & NVME_F_BLOCKING)
4351 set->flags |= BLK_MQ_F_BLOCKING;
4352 set->cmd_size = cmd_size,
4353 set->driver_data = ctrl;
4354 set->nr_hw_queues = ctrl->queue_count - 1;
4355 set->timeout = NVME_IO_TIMEOUT;
4356 set->nr_maps = nr_maps;
4357 ret = blk_mq_alloc_tag_set(set);
4358 if (ret)
4359 return ret;
4360
4361 if (ctrl->ops->flags & NVME_F_FABRICS) {
4362 ctrl->connect_q = blk_mq_init_queue(set);
4363 if (IS_ERR(ctrl->connect_q)) {
4364 ret = PTR_ERR(ctrl->connect_q);
4365 goto out_free_tag_set;
4366 }
4367 blk_queue_flag_set(QUEUE_FLAG_SKIP_TAGSET_QUIESCE,
4368 ctrl->connect_q);
4369 }
4370
4371 ctrl->tagset = set;
4372 return 0;
4373
4374 out_free_tag_set:
4375 blk_mq_free_tag_set(set);
4376 ctrl->connect_q = NULL;
4377 return ret;
4378 }
4379 EXPORT_SYMBOL_GPL(nvme_alloc_io_tag_set);
4380
nvme_remove_io_tag_set(struct nvme_ctrl * ctrl)4381 void nvme_remove_io_tag_set(struct nvme_ctrl *ctrl)
4382 {
4383 if (ctrl->ops->flags & NVME_F_FABRICS) {
4384 blk_mq_destroy_queue(ctrl->connect_q);
4385 blk_put_queue(ctrl->connect_q);
4386 }
4387 blk_mq_free_tag_set(ctrl->tagset);
4388 }
4389 EXPORT_SYMBOL_GPL(nvme_remove_io_tag_set);
4390
nvme_stop_ctrl(struct nvme_ctrl * ctrl)4391 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
4392 {
4393 nvme_mpath_stop(ctrl);
4394 nvme_auth_stop(ctrl);
4395 nvme_stop_keep_alive(ctrl);
4396 nvme_stop_failfast_work(ctrl);
4397 flush_work(&ctrl->async_event_work);
4398 cancel_work_sync(&ctrl->fw_act_work);
4399 if (ctrl->ops->stop_ctrl)
4400 ctrl->ops->stop_ctrl(ctrl);
4401 }
4402 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
4403
nvme_start_ctrl(struct nvme_ctrl * ctrl)4404 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
4405 {
4406 nvme_start_keep_alive(ctrl);
4407
4408 nvme_enable_aen(ctrl);
4409
4410 /*
4411 * persistent discovery controllers need to send indication to userspace
4412 * to re-read the discovery log page to learn about possible changes
4413 * that were missed. We identify persistent discovery controllers by
4414 * checking that they started once before, hence are reconnecting back.
4415 */
4416 if (test_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags) &&
4417 nvme_discovery_ctrl(ctrl))
4418 nvme_change_uevent(ctrl, "NVME_EVENT=rediscover");
4419
4420 if (ctrl->queue_count > 1) {
4421 nvme_queue_scan(ctrl);
4422 nvme_unquiesce_io_queues(ctrl);
4423 nvme_mpath_update(ctrl);
4424 }
4425
4426 nvme_change_uevent(ctrl, "NVME_EVENT=connected");
4427 set_bit(NVME_CTRL_STARTED_ONCE, &ctrl->flags);
4428 }
4429 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
4430
nvme_uninit_ctrl(struct nvme_ctrl * ctrl)4431 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
4432 {
4433 nvme_hwmon_exit(ctrl);
4434 nvme_fault_inject_fini(&ctrl->fault_inject);
4435 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4436 cdev_device_del(&ctrl->cdev, ctrl->device);
4437 nvme_put_ctrl(ctrl);
4438 }
4439 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
4440
nvme_free_cels(struct nvme_ctrl * ctrl)4441 static void nvme_free_cels(struct nvme_ctrl *ctrl)
4442 {
4443 struct nvme_effects_log *cel;
4444 unsigned long i;
4445
4446 xa_for_each(&ctrl->cels, i, cel) {
4447 xa_erase(&ctrl->cels, i);
4448 kfree(cel);
4449 }
4450
4451 xa_destroy(&ctrl->cels);
4452 }
4453
nvme_free_ctrl(struct device * dev)4454 static void nvme_free_ctrl(struct device *dev)
4455 {
4456 struct nvme_ctrl *ctrl =
4457 container_of(dev, struct nvme_ctrl, ctrl_device);
4458 struct nvme_subsystem *subsys = ctrl->subsys;
4459
4460 if (!subsys || ctrl->instance != subsys->instance)
4461 ida_free(&nvme_instance_ida, ctrl->instance);
4462
4463 nvme_free_cels(ctrl);
4464 nvme_mpath_uninit(ctrl);
4465 cleanup_srcu_struct(&ctrl->srcu);
4466 nvme_auth_stop(ctrl);
4467 nvme_auth_free(ctrl);
4468 __free_page(ctrl->discard_page);
4469 free_opal_dev(ctrl->opal_dev);
4470
4471 if (subsys) {
4472 mutex_lock(&nvme_subsystems_lock);
4473 list_del(&ctrl->subsys_entry);
4474 sysfs_remove_link(&subsys->dev.kobj, dev_name(ctrl->device));
4475 mutex_unlock(&nvme_subsystems_lock);
4476 }
4477
4478 ctrl->ops->free_ctrl(ctrl);
4479
4480 if (subsys)
4481 nvme_put_subsystem(subsys);
4482 }
4483
4484 /*
4485 * Initialize a NVMe controller structures. This needs to be called during
4486 * earliest initialization so that we have the initialized structured around
4487 * during probing.
4488 */
nvme_init_ctrl(struct nvme_ctrl * ctrl,struct device * dev,const struct nvme_ctrl_ops * ops,unsigned long quirks)4489 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
4490 const struct nvme_ctrl_ops *ops, unsigned long quirks)
4491 {
4492 int ret;
4493
4494 WRITE_ONCE(ctrl->state, NVME_CTRL_NEW);
4495 clear_bit(NVME_CTRL_FAILFAST_EXPIRED, &ctrl->flags);
4496 spin_lock_init(&ctrl->lock);
4497 mutex_init(&ctrl->namespaces_lock);
4498
4499 ret = init_srcu_struct(&ctrl->srcu);
4500 if (ret)
4501 return ret;
4502
4503 mutex_init(&ctrl->scan_lock);
4504 INIT_LIST_HEAD(&ctrl->namespaces);
4505 xa_init(&ctrl->cels);
4506 ctrl->dev = dev;
4507 ctrl->ops = ops;
4508 ctrl->quirks = quirks;
4509 ctrl->numa_node = NUMA_NO_NODE;
4510 INIT_WORK(&ctrl->scan_work, nvme_scan_work);
4511 INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
4512 INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
4513 INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
4514 init_waitqueue_head(&ctrl->state_wq);
4515
4516 INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
4517 INIT_DELAYED_WORK(&ctrl->failfast_work, nvme_failfast_work);
4518 memset(&ctrl->ka_cmd, 0, sizeof(ctrl->ka_cmd));
4519 ctrl->ka_cmd.common.opcode = nvme_admin_keep_alive;
4520
4521 BUILD_BUG_ON(NVME_DSM_MAX_RANGES * sizeof(struct nvme_dsm_range) >
4522 PAGE_SIZE);
4523 ctrl->discard_page = alloc_page(GFP_KERNEL);
4524 if (!ctrl->discard_page) {
4525 ret = -ENOMEM;
4526 goto out;
4527 }
4528
4529 ret = ida_alloc(&nvme_instance_ida, GFP_KERNEL);
4530 if (ret < 0)
4531 goto out;
4532 ctrl->instance = ret;
4533
4534 device_initialize(&ctrl->ctrl_device);
4535 ctrl->device = &ctrl->ctrl_device;
4536 ctrl->device->devt = MKDEV(MAJOR(nvme_ctrl_base_chr_devt),
4537 ctrl->instance);
4538 ctrl->device->class = nvme_class;
4539 ctrl->device->parent = ctrl->dev;
4540 if (ops->dev_attr_groups)
4541 ctrl->device->groups = ops->dev_attr_groups;
4542 else
4543 ctrl->device->groups = nvme_dev_attr_groups;
4544 ctrl->device->release = nvme_free_ctrl;
4545 dev_set_drvdata(ctrl->device, ctrl);
4546 ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
4547 if (ret)
4548 goto out_release_instance;
4549
4550 nvme_get_ctrl(ctrl);
4551 cdev_init(&ctrl->cdev, &nvme_dev_fops);
4552 ctrl->cdev.owner = ops->module;
4553 ret = cdev_device_add(&ctrl->cdev, ctrl->device);
4554 if (ret)
4555 goto out_free_name;
4556
4557 /*
4558 * Initialize latency tolerance controls. The sysfs files won't
4559 * be visible to userspace unless the device actually supports APST.
4560 */
4561 ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
4562 dev_pm_qos_update_user_latency_tolerance(ctrl->device,
4563 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
4564
4565 nvme_fault_inject_init(&ctrl->fault_inject, dev_name(ctrl->device));
4566 nvme_mpath_init_ctrl(ctrl);
4567 ret = nvme_auth_init_ctrl(ctrl);
4568 if (ret)
4569 goto out_free_cdev;
4570
4571 return 0;
4572 out_free_cdev:
4573 nvme_fault_inject_fini(&ctrl->fault_inject);
4574 dev_pm_qos_hide_latency_tolerance(ctrl->device);
4575 cdev_device_del(&ctrl->cdev, ctrl->device);
4576 out_free_name:
4577 nvme_put_ctrl(ctrl);
4578 kfree_const(ctrl->device->kobj.name);
4579 out_release_instance:
4580 ida_free(&nvme_instance_ida, ctrl->instance);
4581 out:
4582 if (ctrl->discard_page)
4583 __free_page(ctrl->discard_page);
4584 cleanup_srcu_struct(&ctrl->srcu);
4585 return ret;
4586 }
4587 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
4588
4589 /* let I/O to all namespaces fail in preparation for surprise removal */
nvme_mark_namespaces_dead(struct nvme_ctrl * ctrl)4590 void nvme_mark_namespaces_dead(struct nvme_ctrl *ctrl)
4591 {
4592 struct nvme_ns *ns;
4593 int srcu_idx;
4594
4595 srcu_idx = srcu_read_lock(&ctrl->srcu);
4596 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4597 srcu_read_lock_held(&ctrl->srcu))
4598 blk_mark_disk_dead(ns->disk);
4599 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4600 }
4601 EXPORT_SYMBOL_GPL(nvme_mark_namespaces_dead);
4602
nvme_unfreeze(struct nvme_ctrl * ctrl)4603 void nvme_unfreeze(struct nvme_ctrl *ctrl)
4604 {
4605 struct nvme_ns *ns;
4606 int srcu_idx;
4607
4608 srcu_idx = srcu_read_lock(&ctrl->srcu);
4609 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4610 srcu_read_lock_held(&ctrl->srcu))
4611 blk_mq_unfreeze_queue(ns->queue);
4612 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4613 clear_bit(NVME_CTRL_FROZEN, &ctrl->flags);
4614 }
4615 EXPORT_SYMBOL_GPL(nvme_unfreeze);
4616
nvme_wait_freeze_timeout(struct nvme_ctrl * ctrl,long timeout)4617 int nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
4618 {
4619 struct nvme_ns *ns;
4620 int srcu_idx;
4621
4622 srcu_idx = srcu_read_lock(&ctrl->srcu);
4623 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4624 srcu_read_lock_held(&ctrl->srcu)) {
4625 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
4626 if (timeout <= 0)
4627 break;
4628 }
4629 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4630 return timeout;
4631 }
4632 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
4633
nvme_wait_freeze(struct nvme_ctrl * ctrl)4634 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
4635 {
4636 struct nvme_ns *ns;
4637 int srcu_idx;
4638
4639 srcu_idx = srcu_read_lock(&ctrl->srcu);
4640 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4641 srcu_read_lock_held(&ctrl->srcu))
4642 blk_mq_freeze_queue_wait(ns->queue);
4643 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4644 }
4645 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
4646
nvme_start_freeze(struct nvme_ctrl * ctrl)4647 void nvme_start_freeze(struct nvme_ctrl *ctrl)
4648 {
4649 struct nvme_ns *ns;
4650 int srcu_idx;
4651
4652 set_bit(NVME_CTRL_FROZEN, &ctrl->flags);
4653 srcu_idx = srcu_read_lock(&ctrl->srcu);
4654 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4655 srcu_read_lock_held(&ctrl->srcu))
4656 blk_freeze_queue_start(ns->queue);
4657 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4658 }
4659 EXPORT_SYMBOL_GPL(nvme_start_freeze);
4660
nvme_quiesce_io_queues(struct nvme_ctrl * ctrl)4661 void nvme_quiesce_io_queues(struct nvme_ctrl *ctrl)
4662 {
4663 if (!ctrl->tagset)
4664 return;
4665 if (!test_and_set_bit(NVME_CTRL_STOPPED, &ctrl->flags))
4666 blk_mq_quiesce_tagset(ctrl->tagset);
4667 else
4668 blk_mq_wait_quiesce_done(ctrl->tagset);
4669 }
4670 EXPORT_SYMBOL_GPL(nvme_quiesce_io_queues);
4671
nvme_unquiesce_io_queues(struct nvme_ctrl * ctrl)4672 void nvme_unquiesce_io_queues(struct nvme_ctrl *ctrl)
4673 {
4674 if (!ctrl->tagset)
4675 return;
4676 if (test_and_clear_bit(NVME_CTRL_STOPPED, &ctrl->flags))
4677 blk_mq_unquiesce_tagset(ctrl->tagset);
4678 }
4679 EXPORT_SYMBOL_GPL(nvme_unquiesce_io_queues);
4680
nvme_quiesce_admin_queue(struct nvme_ctrl * ctrl)4681 void nvme_quiesce_admin_queue(struct nvme_ctrl *ctrl)
4682 {
4683 if (!test_and_set_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
4684 blk_mq_quiesce_queue(ctrl->admin_q);
4685 else
4686 blk_mq_wait_quiesce_done(ctrl->admin_q->tag_set);
4687 }
4688 EXPORT_SYMBOL_GPL(nvme_quiesce_admin_queue);
4689
nvme_unquiesce_admin_queue(struct nvme_ctrl * ctrl)4690 void nvme_unquiesce_admin_queue(struct nvme_ctrl *ctrl)
4691 {
4692 if (test_and_clear_bit(NVME_CTRL_ADMIN_Q_STOPPED, &ctrl->flags))
4693 blk_mq_unquiesce_queue(ctrl->admin_q);
4694 }
4695 EXPORT_SYMBOL_GPL(nvme_unquiesce_admin_queue);
4696
nvme_sync_io_queues(struct nvme_ctrl * ctrl)4697 void nvme_sync_io_queues(struct nvme_ctrl *ctrl)
4698 {
4699 struct nvme_ns *ns;
4700 int srcu_idx;
4701
4702 srcu_idx = srcu_read_lock(&ctrl->srcu);
4703 list_for_each_entry_srcu(ns, &ctrl->namespaces, list,
4704 srcu_read_lock_held(&ctrl->srcu))
4705 blk_sync_queue(ns->queue);
4706 srcu_read_unlock(&ctrl->srcu, srcu_idx);
4707 }
4708 EXPORT_SYMBOL_GPL(nvme_sync_io_queues);
4709
nvme_sync_queues(struct nvme_ctrl * ctrl)4710 void nvme_sync_queues(struct nvme_ctrl *ctrl)
4711 {
4712 nvme_sync_io_queues(ctrl);
4713 if (ctrl->admin_q)
4714 blk_sync_queue(ctrl->admin_q);
4715 }
4716 EXPORT_SYMBOL_GPL(nvme_sync_queues);
4717
nvme_ctrl_from_file(struct file * file)4718 struct nvme_ctrl *nvme_ctrl_from_file(struct file *file)
4719 {
4720 if (file->f_op != &nvme_dev_fops)
4721 return NULL;
4722 return file->private_data;
4723 }
4724 EXPORT_SYMBOL_NS_GPL(nvme_ctrl_from_file, NVME_TARGET_PASSTHRU);
4725
4726 /*
4727 * Check we didn't inadvertently grow the command structure sizes:
4728 */
_nvme_check_size(void)4729 static inline void _nvme_check_size(void)
4730 {
4731 BUILD_BUG_ON(sizeof(struct nvme_common_command) != 64);
4732 BUILD_BUG_ON(sizeof(struct nvme_rw_command) != 64);
4733 BUILD_BUG_ON(sizeof(struct nvme_identify) != 64);
4734 BUILD_BUG_ON(sizeof(struct nvme_features) != 64);
4735 BUILD_BUG_ON(sizeof(struct nvme_download_firmware) != 64);
4736 BUILD_BUG_ON(sizeof(struct nvme_format_cmd) != 64);
4737 BUILD_BUG_ON(sizeof(struct nvme_dsm_cmd) != 64);
4738 BUILD_BUG_ON(sizeof(struct nvme_write_zeroes_cmd) != 64);
4739 BUILD_BUG_ON(sizeof(struct nvme_abort_cmd) != 64);
4740 BUILD_BUG_ON(sizeof(struct nvme_get_log_page_command) != 64);
4741 BUILD_BUG_ON(sizeof(struct nvme_command) != 64);
4742 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl) != NVME_IDENTIFY_DATA_SIZE);
4743 BUILD_BUG_ON(sizeof(struct nvme_id_ns) != NVME_IDENTIFY_DATA_SIZE);
4744 BUILD_BUG_ON(sizeof(struct nvme_id_ns_cs_indep) !=
4745 NVME_IDENTIFY_DATA_SIZE);
4746 BUILD_BUG_ON(sizeof(struct nvme_id_ns_zns) != NVME_IDENTIFY_DATA_SIZE);
4747 BUILD_BUG_ON(sizeof(struct nvme_id_ns_nvm) != NVME_IDENTIFY_DATA_SIZE);
4748 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_zns) != NVME_IDENTIFY_DATA_SIZE);
4749 BUILD_BUG_ON(sizeof(struct nvme_id_ctrl_nvm) != NVME_IDENTIFY_DATA_SIZE);
4750 BUILD_BUG_ON(sizeof(struct nvme_lba_range_type) != 64);
4751 BUILD_BUG_ON(sizeof(struct nvme_smart_log) != 512);
4752 BUILD_BUG_ON(sizeof(struct nvme_dbbuf) != 64);
4753 BUILD_BUG_ON(sizeof(struct nvme_directive_cmd) != 64);
4754 BUILD_BUG_ON(sizeof(struct nvme_feat_host_behavior) != 512);
4755 }
4756
4757
nvme_core_init(void)4758 static int __init nvme_core_init(void)
4759 {
4760 int result = -ENOMEM;
4761
4762 _nvme_check_size();
4763
4764 nvme_wq = alloc_workqueue("nvme-wq",
4765 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4766 if (!nvme_wq)
4767 goto out;
4768
4769 nvme_reset_wq = alloc_workqueue("nvme-reset-wq",
4770 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4771 if (!nvme_reset_wq)
4772 goto destroy_wq;
4773
4774 nvme_delete_wq = alloc_workqueue("nvme-delete-wq",
4775 WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
4776 if (!nvme_delete_wq)
4777 goto destroy_reset_wq;
4778
4779 result = alloc_chrdev_region(&nvme_ctrl_base_chr_devt, 0,
4780 NVME_MINORS, "nvme");
4781 if (result < 0)
4782 goto destroy_delete_wq;
4783
4784 nvme_class = class_create("nvme");
4785 if (IS_ERR(nvme_class)) {
4786 result = PTR_ERR(nvme_class);
4787 goto unregister_chrdev;
4788 }
4789 nvme_class->dev_uevent = nvme_class_uevent;
4790
4791 nvme_subsys_class = class_create("nvme-subsystem");
4792 if (IS_ERR(nvme_subsys_class)) {
4793 result = PTR_ERR(nvme_subsys_class);
4794 goto destroy_class;
4795 }
4796
4797 result = alloc_chrdev_region(&nvme_ns_chr_devt, 0, NVME_MINORS,
4798 "nvme-generic");
4799 if (result < 0)
4800 goto destroy_subsys_class;
4801
4802 nvme_ns_chr_class = class_create("nvme-generic");
4803 if (IS_ERR(nvme_ns_chr_class)) {
4804 result = PTR_ERR(nvme_ns_chr_class);
4805 goto unregister_generic_ns;
4806 }
4807
4808 result = nvme_init_auth();
4809 if (result)
4810 goto destroy_ns_chr;
4811 return 0;
4812
4813 destroy_ns_chr:
4814 class_destroy(nvme_ns_chr_class);
4815 unregister_generic_ns:
4816 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4817 destroy_subsys_class:
4818 class_destroy(nvme_subsys_class);
4819 destroy_class:
4820 class_destroy(nvme_class);
4821 unregister_chrdev:
4822 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4823 destroy_delete_wq:
4824 destroy_workqueue(nvme_delete_wq);
4825 destroy_reset_wq:
4826 destroy_workqueue(nvme_reset_wq);
4827 destroy_wq:
4828 destroy_workqueue(nvme_wq);
4829 out:
4830 return result;
4831 }
4832
nvme_core_exit(void)4833 static void __exit nvme_core_exit(void)
4834 {
4835 nvme_exit_auth();
4836 class_destroy(nvme_ns_chr_class);
4837 class_destroy(nvme_subsys_class);
4838 class_destroy(nvme_class);
4839 unregister_chrdev_region(nvme_ns_chr_devt, NVME_MINORS);
4840 unregister_chrdev_region(nvme_ctrl_base_chr_devt, NVME_MINORS);
4841 destroy_workqueue(nvme_delete_wq);
4842 destroy_workqueue(nvme_reset_wq);
4843 destroy_workqueue(nvme_wq);
4844 ida_destroy(&nvme_ns_chr_minor_ida);
4845 ida_destroy(&nvme_instance_ida);
4846 }
4847
4848 MODULE_LICENSE("GPL");
4849 MODULE_VERSION("1.0");
4850 module_init(nvme_core_init);
4851 module_exit(nvme_core_exit);
4852