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