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