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