]> asedeno.scripts.mit.edu Git - linux.git/blob - drivers/nvme/host/core.c
nvme: allow controller RESETTING to RECONNECTING transition
[linux.git] / drivers / nvme / host / core.c
1 /*
2  * NVM Express device driver
3  * Copyright (c) 2011-2014, Intel Corporation.
4  *
5  * This program is free software; you can redistribute it and/or modify it
6  * under the terms and conditions of the GNU General Public License,
7  * version 2, as published by the Free Software Foundation.
8  *
9  * This program is distributed in the hope it will be useful, but WITHOUT
10  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for
12  * more details.
13  */
14
15 #include <linux/blkdev.h>
16 #include <linux/blk-mq.h>
17 #include <linux/delay.h>
18 #include <linux/errno.h>
19 #include <linux/hdreg.h>
20 #include <linux/kernel.h>
21 #include <linux/module.h>
22 #include <linux/list_sort.h>
23 #include <linux/slab.h>
24 #include <linux/types.h>
25 #include <linux/pr.h>
26 #include <linux/ptrace.h>
27 #include <linux/nvme_ioctl.h>
28 #include <linux/t10-pi.h>
29 #include <linux/pm_qos.h>
30 #include <asm/unaligned.h>
31
32 #include "nvme.h"
33 #include "fabrics.h"
34
35 #define NVME_MINORS             (1U << MINORBITS)
36
37 unsigned int admin_timeout = 60;
38 module_param(admin_timeout, uint, 0644);
39 MODULE_PARM_DESC(admin_timeout, "timeout in seconds for admin commands");
40 EXPORT_SYMBOL_GPL(admin_timeout);
41
42 unsigned int nvme_io_timeout = 30;
43 module_param_named(io_timeout, nvme_io_timeout, uint, 0644);
44 MODULE_PARM_DESC(io_timeout, "timeout in seconds for I/O");
45 EXPORT_SYMBOL_GPL(nvme_io_timeout);
46
47 static unsigned char shutdown_timeout = 5;
48 module_param(shutdown_timeout, byte, 0644);
49 MODULE_PARM_DESC(shutdown_timeout, "timeout in seconds for controller shutdown");
50
51 static u8 nvme_max_retries = 5;
52 module_param_named(max_retries, nvme_max_retries, byte, 0644);
53 MODULE_PARM_DESC(max_retries, "max number of retries a command may have");
54
55 static unsigned long default_ps_max_latency_us = 100000;
56 module_param(default_ps_max_latency_us, ulong, 0644);
57 MODULE_PARM_DESC(default_ps_max_latency_us,
58                  "max power saving latency for new devices; use PM QOS to change per device");
59
60 static bool force_apst;
61 module_param(force_apst, bool, 0644);
62 MODULE_PARM_DESC(force_apst, "allow APST for newly enumerated devices even if quirked off");
63
64 static bool streams;
65 module_param(streams, bool, 0644);
66 MODULE_PARM_DESC(streams, "turn on support for Streams write directives");
67
68 struct workqueue_struct *nvme_wq;
69 EXPORT_SYMBOL_GPL(nvme_wq);
70
71 static DEFINE_IDA(nvme_instance_ida);
72 static dev_t nvme_chr_devt;
73 static struct class *nvme_class;
74
75 static __le32 nvme_get_log_dw10(u8 lid, size_t size)
76 {
77         return cpu_to_le32((((size / 4) - 1) << 16) | lid);
78 }
79
80 int nvme_reset_ctrl(struct nvme_ctrl *ctrl)
81 {
82         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_RESETTING))
83                 return -EBUSY;
84         if (!queue_work(nvme_wq, &ctrl->reset_work))
85                 return -EBUSY;
86         return 0;
87 }
88 EXPORT_SYMBOL_GPL(nvme_reset_ctrl);
89
90 static int nvme_reset_ctrl_sync(struct nvme_ctrl *ctrl)
91 {
92         int ret;
93
94         ret = nvme_reset_ctrl(ctrl);
95         if (!ret)
96                 flush_work(&ctrl->reset_work);
97         return ret;
98 }
99
100 static void nvme_delete_ctrl_work(struct work_struct *work)
101 {
102         struct nvme_ctrl *ctrl =
103                 container_of(work, struct nvme_ctrl, delete_work);
104
105         flush_work(&ctrl->reset_work);
106         nvme_stop_ctrl(ctrl);
107         nvme_remove_namespaces(ctrl);
108         ctrl->ops->delete_ctrl(ctrl);
109         nvme_uninit_ctrl(ctrl);
110         nvme_put_ctrl(ctrl);
111 }
112
113 int nvme_delete_ctrl(struct nvme_ctrl *ctrl)
114 {
115         if (!nvme_change_ctrl_state(ctrl, NVME_CTRL_DELETING))
116                 return -EBUSY;
117         if (!queue_work(nvme_wq, &ctrl->delete_work))
118                 return -EBUSY;
119         return 0;
120 }
121 EXPORT_SYMBOL_GPL(nvme_delete_ctrl);
122
123 int nvme_delete_ctrl_sync(struct nvme_ctrl *ctrl)
124 {
125         int ret = 0;
126
127         /*
128          * Keep a reference until the work is flushed since ->delete_ctrl
129          * can free the controller.
130          */
131         nvme_get_ctrl(ctrl);
132         ret = nvme_delete_ctrl(ctrl);
133         if (!ret)
134                 flush_work(&ctrl->delete_work);
135         nvme_put_ctrl(ctrl);
136         return ret;
137 }
138 EXPORT_SYMBOL_GPL(nvme_delete_ctrl_sync);
139
140 static blk_status_t nvme_error_status(struct request *req)
141 {
142         switch (nvme_req(req)->status & 0x7ff) {
143         case NVME_SC_SUCCESS:
144                 return BLK_STS_OK;
145         case NVME_SC_CAP_EXCEEDED:
146                 return BLK_STS_NOSPC;
147         case NVME_SC_ONCS_NOT_SUPPORTED:
148                 return BLK_STS_NOTSUPP;
149         case NVME_SC_WRITE_FAULT:
150         case NVME_SC_READ_ERROR:
151         case NVME_SC_UNWRITTEN_BLOCK:
152         case NVME_SC_ACCESS_DENIED:
153         case NVME_SC_READ_ONLY:
154                 return BLK_STS_MEDIUM;
155         case NVME_SC_GUARD_CHECK:
156         case NVME_SC_APPTAG_CHECK:
157         case NVME_SC_REFTAG_CHECK:
158         case NVME_SC_INVALID_PI:
159                 return BLK_STS_PROTECTION;
160         case NVME_SC_RESERVATION_CONFLICT:
161                 return BLK_STS_NEXUS;
162         default:
163                 return BLK_STS_IOERR;
164         }
165 }
166
167 static inline bool nvme_req_needs_retry(struct request *req)
168 {
169         if (blk_noretry_request(req))
170                 return false;
171         if (nvme_req(req)->status & NVME_SC_DNR)
172                 return false;
173         if (nvme_req(req)->retries >= nvme_max_retries)
174                 return false;
175         return true;
176 }
177
178 void nvme_complete_rq(struct request *req)
179 {
180         if (unlikely(nvme_req(req)->status && nvme_req_needs_retry(req))) {
181                 nvme_req(req)->retries++;
182                 blk_mq_requeue_request(req, true);
183                 return;
184         }
185
186         blk_mq_end_request(req, nvme_error_status(req));
187 }
188 EXPORT_SYMBOL_GPL(nvme_complete_rq);
189
190 void nvme_cancel_request(struct request *req, void *data, bool reserved)
191 {
192         int status;
193
194         if (!blk_mq_request_started(req))
195                 return;
196
197         dev_dbg_ratelimited(((struct nvme_ctrl *) data)->device,
198                                 "Cancelling I/O %d", req->tag);
199
200         status = NVME_SC_ABORT_REQ;
201         if (blk_queue_dying(req->q))
202                 status |= NVME_SC_DNR;
203         nvme_req(req)->status = status;
204         blk_mq_complete_request(req);
205
206 }
207 EXPORT_SYMBOL_GPL(nvme_cancel_request);
208
209 bool nvme_change_ctrl_state(struct nvme_ctrl *ctrl,
210                 enum nvme_ctrl_state new_state)
211 {
212         enum nvme_ctrl_state old_state;
213         unsigned long flags;
214         bool changed = false;
215
216         spin_lock_irqsave(&ctrl->lock, flags);
217
218         old_state = ctrl->state;
219         switch (new_state) {
220         case NVME_CTRL_LIVE:
221                 switch (old_state) {
222                 case NVME_CTRL_NEW:
223                 case NVME_CTRL_RESETTING:
224                 case NVME_CTRL_RECONNECTING:
225                         changed = true;
226                         /* FALLTHRU */
227                 default:
228                         break;
229                 }
230                 break;
231         case NVME_CTRL_RESETTING:
232                 switch (old_state) {
233                 case NVME_CTRL_NEW:
234                 case NVME_CTRL_LIVE:
235                         changed = true;
236                         /* FALLTHRU */
237                 default:
238                         break;
239                 }
240                 break;
241         case NVME_CTRL_RECONNECTING:
242                 switch (old_state) {
243                 case NVME_CTRL_LIVE:
244                 case NVME_CTRL_RESETTING:
245                         changed = true;
246                         /* FALLTHRU */
247                 default:
248                         break;
249                 }
250                 break;
251         case NVME_CTRL_DELETING:
252                 switch (old_state) {
253                 case NVME_CTRL_LIVE:
254                 case NVME_CTRL_RESETTING:
255                 case NVME_CTRL_RECONNECTING:
256                         changed = true;
257                         /* FALLTHRU */
258                 default:
259                         break;
260                 }
261                 break;
262         case NVME_CTRL_DEAD:
263                 switch (old_state) {
264                 case NVME_CTRL_DELETING:
265                         changed = true;
266                         /* FALLTHRU */
267                 default:
268                         break;
269                 }
270                 break;
271         default:
272                 break;
273         }
274
275         if (changed)
276                 ctrl->state = new_state;
277
278         spin_unlock_irqrestore(&ctrl->lock, flags);
279
280         return changed;
281 }
282 EXPORT_SYMBOL_GPL(nvme_change_ctrl_state);
283
284 static void nvme_free_ns(struct kref *kref)
285 {
286         struct nvme_ns *ns = container_of(kref, struct nvme_ns, kref);
287
288         if (ns->ndev)
289                 nvme_nvm_unregister(ns);
290
291         put_disk(ns->disk);
292         ida_simple_remove(&ns->ctrl->ns_ida, ns->instance);
293         nvme_put_ctrl(ns->ctrl);
294         kfree(ns);
295 }
296
297 static void nvme_put_ns(struct nvme_ns *ns)
298 {
299         kref_put(&ns->kref, nvme_free_ns);
300 }
301
302 struct request *nvme_alloc_request(struct request_queue *q,
303                 struct nvme_command *cmd, unsigned int flags, int qid)
304 {
305         unsigned op = nvme_is_write(cmd) ? REQ_OP_DRV_OUT : REQ_OP_DRV_IN;
306         struct request *req;
307
308         if (qid == NVME_QID_ANY) {
309                 req = blk_mq_alloc_request(q, op, flags);
310         } else {
311                 req = blk_mq_alloc_request_hctx(q, op, flags,
312                                 qid ? qid - 1 : 0);
313         }
314         if (IS_ERR(req))
315                 return req;
316
317         req->cmd_flags |= REQ_FAILFAST_DRIVER;
318         nvme_req(req)->cmd = cmd;
319
320         return req;
321 }
322 EXPORT_SYMBOL_GPL(nvme_alloc_request);
323
324 static int nvme_toggle_streams(struct nvme_ctrl *ctrl, bool enable)
325 {
326         struct nvme_command c;
327
328         memset(&c, 0, sizeof(c));
329
330         c.directive.opcode = nvme_admin_directive_send;
331         c.directive.nsid = cpu_to_le32(NVME_NSID_ALL);
332         c.directive.doper = NVME_DIR_SND_ID_OP_ENABLE;
333         c.directive.dtype = NVME_DIR_IDENTIFY;
334         c.directive.tdtype = NVME_DIR_STREAMS;
335         c.directive.endir = enable ? NVME_DIR_ENDIR : 0;
336
337         return nvme_submit_sync_cmd(ctrl->admin_q, &c, NULL, 0);
338 }
339
340 static int nvme_disable_streams(struct nvme_ctrl *ctrl)
341 {
342         return nvme_toggle_streams(ctrl, false);
343 }
344
345 static int nvme_enable_streams(struct nvme_ctrl *ctrl)
346 {
347         return nvme_toggle_streams(ctrl, true);
348 }
349
350 static int nvme_get_stream_params(struct nvme_ctrl *ctrl,
351                                   struct streams_directive_params *s, u32 nsid)
352 {
353         struct nvme_command c;
354
355         memset(&c, 0, sizeof(c));
356         memset(s, 0, sizeof(*s));
357
358         c.directive.opcode = nvme_admin_directive_recv;
359         c.directive.nsid = cpu_to_le32(nsid);
360         c.directive.numd = cpu_to_le32((sizeof(*s) >> 2) - 1);
361         c.directive.doper = NVME_DIR_RCV_ST_OP_PARAM;
362         c.directive.dtype = NVME_DIR_STREAMS;
363
364         return nvme_submit_sync_cmd(ctrl->admin_q, &c, s, sizeof(*s));
365 }
366
367 static int nvme_configure_directives(struct nvme_ctrl *ctrl)
368 {
369         struct streams_directive_params s;
370         int ret;
371
372         if (!(ctrl->oacs & NVME_CTRL_OACS_DIRECTIVES))
373                 return 0;
374         if (!streams)
375                 return 0;
376
377         ret = nvme_enable_streams(ctrl);
378         if (ret)
379                 return ret;
380
381         ret = nvme_get_stream_params(ctrl, &s, NVME_NSID_ALL);
382         if (ret)
383                 return ret;
384
385         ctrl->nssa = le16_to_cpu(s.nssa);
386         if (ctrl->nssa < BLK_MAX_WRITE_HINTS - 1) {
387                 dev_info(ctrl->device, "too few streams (%u) available\n",
388                                         ctrl->nssa);
389                 nvme_disable_streams(ctrl);
390                 return 0;
391         }
392
393         ctrl->nr_streams = min_t(unsigned, ctrl->nssa, BLK_MAX_WRITE_HINTS - 1);
394         dev_info(ctrl->device, "Using %u streams\n", ctrl->nr_streams);
395         return 0;
396 }
397
398 /*
399  * Check if 'req' has a write hint associated with it. If it does, assign
400  * a valid namespace stream to the write.
401  */
402 static void nvme_assign_write_stream(struct nvme_ctrl *ctrl,
403                                      struct request *req, u16 *control,
404                                      u32 *dsmgmt)
405 {
406         enum rw_hint streamid = req->write_hint;
407
408         if (streamid == WRITE_LIFE_NOT_SET || streamid == WRITE_LIFE_NONE)
409                 streamid = 0;
410         else {
411                 streamid--;
412                 if (WARN_ON_ONCE(streamid > ctrl->nr_streams))
413                         return;
414
415                 *control |= NVME_RW_DTYPE_STREAMS;
416                 *dsmgmt |= streamid << 16;
417         }
418
419         if (streamid < ARRAY_SIZE(req->q->write_hints))
420                 req->q->write_hints[streamid] += blk_rq_bytes(req) >> 9;
421 }
422
423 static inline void nvme_setup_flush(struct nvme_ns *ns,
424                 struct nvme_command *cmnd)
425 {
426         memset(cmnd, 0, sizeof(*cmnd));
427         cmnd->common.opcode = nvme_cmd_flush;
428         cmnd->common.nsid = cpu_to_le32(ns->ns_id);
429 }
430
431 static blk_status_t nvme_setup_discard(struct nvme_ns *ns, struct request *req,
432                 struct nvme_command *cmnd)
433 {
434         unsigned short segments = blk_rq_nr_discard_segments(req), n = 0;
435         struct nvme_dsm_range *range;
436         struct bio *bio;
437
438         range = kmalloc_array(segments, sizeof(*range), GFP_ATOMIC);
439         if (!range)
440                 return BLK_STS_RESOURCE;
441
442         __rq_for_each_bio(bio, req) {
443                 u64 slba = nvme_block_nr(ns, bio->bi_iter.bi_sector);
444                 u32 nlb = bio->bi_iter.bi_size >> ns->lba_shift;
445
446                 range[n].cattr = cpu_to_le32(0);
447                 range[n].nlb = cpu_to_le32(nlb);
448                 range[n].slba = cpu_to_le64(slba);
449                 n++;
450         }
451
452         if (WARN_ON_ONCE(n != segments)) {
453                 kfree(range);
454                 return BLK_STS_IOERR;
455         }
456
457         memset(cmnd, 0, sizeof(*cmnd));
458         cmnd->dsm.opcode = nvme_cmd_dsm;
459         cmnd->dsm.nsid = cpu_to_le32(ns->ns_id);
460         cmnd->dsm.nr = cpu_to_le32(segments - 1);
461         cmnd->dsm.attributes = cpu_to_le32(NVME_DSMGMT_AD);
462
463         req->special_vec.bv_page = virt_to_page(range);
464         req->special_vec.bv_offset = offset_in_page(range);
465         req->special_vec.bv_len = sizeof(*range) * segments;
466         req->rq_flags |= RQF_SPECIAL_PAYLOAD;
467
468         return BLK_STS_OK;
469 }
470
471 static inline blk_status_t nvme_setup_rw(struct nvme_ns *ns,
472                 struct request *req, struct nvme_command *cmnd)
473 {
474         struct nvme_ctrl *ctrl = ns->ctrl;
475         u16 control = 0;
476         u32 dsmgmt = 0;
477
478         /*
479          * If formated with metadata, require the block layer provide a buffer
480          * unless this namespace is formated such that the metadata can be
481          * stripped/generated by the controller with PRACT=1.
482          */
483         if (ns && ns->ms &&
484             (!ns->pi_type || ns->ms != sizeof(struct t10_pi_tuple)) &&
485             !blk_integrity_rq(req) && !blk_rq_is_passthrough(req))
486                 return BLK_STS_NOTSUPP;
487
488         if (req->cmd_flags & REQ_FUA)
489                 control |= NVME_RW_FUA;
490         if (req->cmd_flags & (REQ_FAILFAST_DEV | REQ_RAHEAD))
491                 control |= NVME_RW_LR;
492
493         if (req->cmd_flags & REQ_RAHEAD)
494                 dsmgmt |= NVME_RW_DSM_FREQ_PREFETCH;
495
496         memset(cmnd, 0, sizeof(*cmnd));
497         cmnd->rw.opcode = (rq_data_dir(req) ? nvme_cmd_write : nvme_cmd_read);
498         cmnd->rw.nsid = cpu_to_le32(ns->ns_id);
499         cmnd->rw.slba = cpu_to_le64(nvme_block_nr(ns, blk_rq_pos(req)));
500         cmnd->rw.length = cpu_to_le16((blk_rq_bytes(req) >> ns->lba_shift) - 1);
501
502         if (req_op(req) == REQ_OP_WRITE && ctrl->nr_streams)
503                 nvme_assign_write_stream(ctrl, req, &control, &dsmgmt);
504
505         if (ns->ms) {
506                 switch (ns->pi_type) {
507                 case NVME_NS_DPS_PI_TYPE3:
508                         control |= NVME_RW_PRINFO_PRCHK_GUARD;
509                         break;
510                 case NVME_NS_DPS_PI_TYPE1:
511                 case NVME_NS_DPS_PI_TYPE2:
512                         control |= NVME_RW_PRINFO_PRCHK_GUARD |
513                                         NVME_RW_PRINFO_PRCHK_REF;
514                         cmnd->rw.reftag = cpu_to_le32(
515                                         nvme_block_nr(ns, blk_rq_pos(req)));
516                         break;
517                 }
518                 if (!blk_integrity_rq(req))
519                         control |= NVME_RW_PRINFO_PRACT;
520         }
521
522         cmnd->rw.control = cpu_to_le16(control);
523         cmnd->rw.dsmgmt = cpu_to_le32(dsmgmt);
524         return 0;
525 }
526
527 blk_status_t nvme_setup_cmd(struct nvme_ns *ns, struct request *req,
528                 struct nvme_command *cmd)
529 {
530         blk_status_t ret = BLK_STS_OK;
531
532         if (!(req->rq_flags & RQF_DONTPREP)) {
533                 nvme_req(req)->retries = 0;
534                 nvme_req(req)->flags = 0;
535                 req->rq_flags |= RQF_DONTPREP;
536         }
537
538         switch (req_op(req)) {
539         case REQ_OP_DRV_IN:
540         case REQ_OP_DRV_OUT:
541                 memcpy(cmd, nvme_req(req)->cmd, sizeof(*cmd));
542                 break;
543         case REQ_OP_FLUSH:
544                 nvme_setup_flush(ns, cmd);
545                 break;
546         case REQ_OP_WRITE_ZEROES:
547                 /* currently only aliased to deallocate for a few ctrls: */
548         case REQ_OP_DISCARD:
549                 ret = nvme_setup_discard(ns, req, cmd);
550                 break;
551         case REQ_OP_READ:
552         case REQ_OP_WRITE:
553                 ret = nvme_setup_rw(ns, req, cmd);
554                 break;
555         default:
556                 WARN_ON_ONCE(1);
557                 return BLK_STS_IOERR;
558         }
559
560         cmd->common.command_id = req->tag;
561         return ret;
562 }
563 EXPORT_SYMBOL_GPL(nvme_setup_cmd);
564
565 /*
566  * Returns 0 on success.  If the result is negative, it's a Linux error code;
567  * if the result is positive, it's an NVM Express status code
568  */
569 int __nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
570                 union nvme_result *result, void *buffer, unsigned bufflen,
571                 unsigned timeout, int qid, int at_head, int flags)
572 {
573         struct request *req;
574         int ret;
575
576         req = nvme_alloc_request(q, cmd, flags, qid);
577         if (IS_ERR(req))
578                 return PTR_ERR(req);
579
580         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
581
582         if (buffer && bufflen) {
583                 ret = blk_rq_map_kern(q, req, buffer, bufflen, GFP_KERNEL);
584                 if (ret)
585                         goto out;
586         }
587
588         blk_execute_rq(req->q, NULL, req, at_head);
589         if (result)
590                 *result = nvme_req(req)->result;
591         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
592                 ret = -EINTR;
593         else
594                 ret = nvme_req(req)->status;
595  out:
596         blk_mq_free_request(req);
597         return ret;
598 }
599 EXPORT_SYMBOL_GPL(__nvme_submit_sync_cmd);
600
601 int nvme_submit_sync_cmd(struct request_queue *q, struct nvme_command *cmd,
602                 void *buffer, unsigned bufflen)
603 {
604         return __nvme_submit_sync_cmd(q, cmd, NULL, buffer, bufflen, 0,
605                         NVME_QID_ANY, 0, 0);
606 }
607 EXPORT_SYMBOL_GPL(nvme_submit_sync_cmd);
608
609 static void *nvme_add_user_metadata(struct bio *bio, void __user *ubuf,
610                 unsigned len, u32 seed, bool write)
611 {
612         struct bio_integrity_payload *bip;
613         int ret = -ENOMEM;
614         void *buf;
615
616         buf = kmalloc(len, GFP_KERNEL);
617         if (!buf)
618                 goto out;
619
620         ret = -EFAULT;
621         if (write && copy_from_user(buf, ubuf, len))
622                 goto out_free_meta;
623
624         bip = bio_integrity_alloc(bio, GFP_KERNEL, 1);
625         if (IS_ERR(bip)) {
626                 ret = PTR_ERR(bip);
627                 goto out_free_meta;
628         }
629
630         bip->bip_iter.bi_size = len;
631         bip->bip_iter.bi_sector = seed;
632         ret = bio_integrity_add_page(bio, virt_to_page(buf), len,
633                         offset_in_page(buf));
634         if (ret == len)
635                 return buf;
636         ret = -ENOMEM;
637 out_free_meta:
638         kfree(buf);
639 out:
640         return ERR_PTR(ret);
641 }
642
643 static int nvme_submit_user_cmd(struct request_queue *q,
644                 struct nvme_command *cmd, void __user *ubuffer,
645                 unsigned bufflen, void __user *meta_buffer, unsigned meta_len,
646                 u32 meta_seed, u32 *result, unsigned timeout)
647 {
648         bool write = nvme_is_write(cmd);
649         struct nvme_ns *ns = q->queuedata;
650         struct gendisk *disk = ns ? ns->disk : NULL;
651         struct request *req;
652         struct bio *bio = NULL;
653         void *meta = NULL;
654         int ret;
655
656         req = nvme_alloc_request(q, cmd, 0, NVME_QID_ANY);
657         if (IS_ERR(req))
658                 return PTR_ERR(req);
659
660         req->timeout = timeout ? timeout : ADMIN_TIMEOUT;
661
662         if (ubuffer && bufflen) {
663                 ret = blk_rq_map_user(q, req, NULL, ubuffer, bufflen,
664                                 GFP_KERNEL);
665                 if (ret)
666                         goto out;
667                 bio = req->bio;
668                 bio->bi_disk = disk;
669                 if (disk && meta_buffer && meta_len) {
670                         meta = nvme_add_user_metadata(bio, meta_buffer, meta_len,
671                                         meta_seed, write);
672                         if (IS_ERR(meta)) {
673                                 ret = PTR_ERR(meta);
674                                 goto out_unmap;
675                         }
676                 }
677         }
678
679         blk_execute_rq(req->q, disk, req, 0);
680         if (nvme_req(req)->flags & NVME_REQ_CANCELLED)
681                 ret = -EINTR;
682         else
683                 ret = nvme_req(req)->status;
684         if (result)
685                 *result = le32_to_cpu(nvme_req(req)->result.u32);
686         if (meta && !ret && !write) {
687                 if (copy_to_user(meta_buffer, meta, meta_len))
688                         ret = -EFAULT;
689         }
690         kfree(meta);
691  out_unmap:
692         if (bio)
693                 blk_rq_unmap_user(bio);
694  out:
695         blk_mq_free_request(req);
696         return ret;
697 }
698
699 static void nvme_keep_alive_end_io(struct request *rq, blk_status_t status)
700 {
701         struct nvme_ctrl *ctrl = rq->end_io_data;
702
703         blk_mq_free_request(rq);
704
705         if (status) {
706                 dev_err(ctrl->device,
707                         "failed nvme_keep_alive_end_io error=%d\n",
708                                 status);
709                 return;
710         }
711
712         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
713 }
714
715 static int nvme_keep_alive(struct nvme_ctrl *ctrl)
716 {
717         struct nvme_command c;
718         struct request *rq;
719
720         memset(&c, 0, sizeof(c));
721         c.common.opcode = nvme_admin_keep_alive;
722
723         rq = nvme_alloc_request(ctrl->admin_q, &c, BLK_MQ_REQ_RESERVED,
724                         NVME_QID_ANY);
725         if (IS_ERR(rq))
726                 return PTR_ERR(rq);
727
728         rq->timeout = ctrl->kato * HZ;
729         rq->end_io_data = ctrl;
730
731         blk_execute_rq_nowait(rq->q, NULL, rq, 0, nvme_keep_alive_end_io);
732
733         return 0;
734 }
735
736 static void nvme_keep_alive_work(struct work_struct *work)
737 {
738         struct nvme_ctrl *ctrl = container_of(to_delayed_work(work),
739                         struct nvme_ctrl, ka_work);
740
741         if (nvme_keep_alive(ctrl)) {
742                 /* allocation failure, reset the controller */
743                 dev_err(ctrl->device, "keep-alive failed\n");
744                 nvme_reset_ctrl(ctrl);
745                 return;
746         }
747 }
748
749 void nvme_start_keep_alive(struct nvme_ctrl *ctrl)
750 {
751         if (unlikely(ctrl->kato == 0))
752                 return;
753
754         INIT_DELAYED_WORK(&ctrl->ka_work, nvme_keep_alive_work);
755         schedule_delayed_work(&ctrl->ka_work, ctrl->kato * HZ);
756 }
757 EXPORT_SYMBOL_GPL(nvme_start_keep_alive);
758
759 void nvme_stop_keep_alive(struct nvme_ctrl *ctrl)
760 {
761         if (unlikely(ctrl->kato == 0))
762                 return;
763
764         cancel_delayed_work_sync(&ctrl->ka_work);
765 }
766 EXPORT_SYMBOL_GPL(nvme_stop_keep_alive);
767
768 static int nvme_identify_ctrl(struct nvme_ctrl *dev, struct nvme_id_ctrl **id)
769 {
770         struct nvme_command c = { };
771         int error;
772
773         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
774         c.identify.opcode = nvme_admin_identify;
775         c.identify.cns = NVME_ID_CNS_CTRL;
776
777         *id = kmalloc(sizeof(struct nvme_id_ctrl), GFP_KERNEL);
778         if (!*id)
779                 return -ENOMEM;
780
781         error = nvme_submit_sync_cmd(dev->admin_q, &c, *id,
782                         sizeof(struct nvme_id_ctrl));
783         if (error)
784                 kfree(*id);
785         return error;
786 }
787
788 static int nvme_identify_ns_descs(struct nvme_ctrl *ctrl, unsigned nsid,
789                 u8 *eui64, u8 *nguid, uuid_t *uuid)
790 {
791         struct nvme_command c = { };
792         int status;
793         void *data;
794         int pos;
795         int len;
796
797         c.identify.opcode = nvme_admin_identify;
798         c.identify.nsid = cpu_to_le32(nsid);
799         c.identify.cns = NVME_ID_CNS_NS_DESC_LIST;
800
801         data = kzalloc(NVME_IDENTIFY_DATA_SIZE, GFP_KERNEL);
802         if (!data)
803                 return -ENOMEM;
804
805         status = nvme_submit_sync_cmd(ctrl->admin_q, &c, data,
806                                       NVME_IDENTIFY_DATA_SIZE);
807         if (status)
808                 goto free_data;
809
810         for (pos = 0; pos < NVME_IDENTIFY_DATA_SIZE; pos += len) {
811                 struct nvme_ns_id_desc *cur = data + pos;
812
813                 if (cur->nidl == 0)
814                         break;
815
816                 switch (cur->nidt) {
817                 case NVME_NIDT_EUI64:
818                         if (cur->nidl != NVME_NIDT_EUI64_LEN) {
819                                 dev_warn(ctrl->device,
820                                          "ctrl returned bogus length: %d for NVME_NIDT_EUI64\n",
821                                          cur->nidl);
822                                 goto free_data;
823                         }
824                         len = NVME_NIDT_EUI64_LEN;
825                         memcpy(eui64, data + pos + sizeof(*cur), len);
826                         break;
827                 case NVME_NIDT_NGUID:
828                         if (cur->nidl != NVME_NIDT_NGUID_LEN) {
829                                 dev_warn(ctrl->device,
830                                          "ctrl returned bogus length: %d for NVME_NIDT_NGUID\n",
831                                          cur->nidl);
832                                 goto free_data;
833                         }
834                         len = NVME_NIDT_NGUID_LEN;
835                         memcpy(nguid, data + pos + sizeof(*cur), len);
836                         break;
837                 case NVME_NIDT_UUID:
838                         if (cur->nidl != NVME_NIDT_UUID_LEN) {
839                                 dev_warn(ctrl->device,
840                                          "ctrl returned bogus length: %d for NVME_NIDT_UUID\n",
841                                          cur->nidl);
842                                 goto free_data;
843                         }
844                         len = NVME_NIDT_UUID_LEN;
845                         uuid_copy(uuid, data + pos + sizeof(*cur));
846                         break;
847                 default:
848                         /* Skip unnkown types */
849                         len = cur->nidl;
850                         break;
851                 }
852
853                 len += sizeof(*cur);
854         }
855 free_data:
856         kfree(data);
857         return status;
858 }
859
860 static int nvme_identify_ns_list(struct nvme_ctrl *dev, unsigned nsid, __le32 *ns_list)
861 {
862         struct nvme_command c = { };
863
864         c.identify.opcode = nvme_admin_identify;
865         c.identify.cns = NVME_ID_CNS_NS_ACTIVE_LIST;
866         c.identify.nsid = cpu_to_le32(nsid);
867         return nvme_submit_sync_cmd(dev->admin_q, &c, ns_list, 0x1000);
868 }
869
870 static struct nvme_id_ns *nvme_identify_ns(struct nvme_ctrl *ctrl,
871                 unsigned nsid)
872 {
873         struct nvme_id_ns *id;
874         struct nvme_command c = { };
875         int error;
876
877         /* gcc-4.4.4 (at least) has issues with initializers and anon unions */
878         c.identify.opcode = nvme_admin_identify;
879         c.identify.nsid = cpu_to_le32(nsid);
880         c.identify.cns = NVME_ID_CNS_NS;
881
882         id = kmalloc(sizeof(*id), GFP_KERNEL);
883         if (!id)
884                 return NULL;
885
886         error = nvme_submit_sync_cmd(ctrl->admin_q, &c, id, sizeof(*id));
887         if (error) {
888                 dev_warn(ctrl->device, "Identify namespace failed\n");
889                 kfree(id);
890                 return NULL;
891         }
892
893         return id;
894 }
895
896 static int nvme_set_features(struct nvme_ctrl *dev, unsigned fid, unsigned dword11,
897                       void *buffer, size_t buflen, u32 *result)
898 {
899         struct nvme_command c;
900         union nvme_result res;
901         int ret;
902
903         memset(&c, 0, sizeof(c));
904         c.features.opcode = nvme_admin_set_features;
905         c.features.fid = cpu_to_le32(fid);
906         c.features.dword11 = cpu_to_le32(dword11);
907
908         ret = __nvme_submit_sync_cmd(dev->admin_q, &c, &res,
909                         buffer, buflen, 0, NVME_QID_ANY, 0, 0);
910         if (ret >= 0 && result)
911                 *result = le32_to_cpu(res.u32);
912         return ret;
913 }
914
915 int nvme_set_queue_count(struct nvme_ctrl *ctrl, int *count)
916 {
917         u32 q_count = (*count - 1) | ((*count - 1) << 16);
918         u32 result;
919         int status, nr_io_queues;
920
921         status = nvme_set_features(ctrl, NVME_FEAT_NUM_QUEUES, q_count, NULL, 0,
922                         &result);
923         if (status < 0)
924                 return status;
925
926         /*
927          * Degraded controllers might return an error when setting the queue
928          * count.  We still want to be able to bring them online and offer
929          * access to the admin queue, as that might be only way to fix them up.
930          */
931         if (status > 0) {
932                 dev_err(ctrl->device, "Could not set queue count (%d)\n", status);
933                 *count = 0;
934         } else {
935                 nr_io_queues = min(result & 0xffff, result >> 16) + 1;
936                 *count = min(*count, nr_io_queues);
937         }
938
939         return 0;
940 }
941 EXPORT_SYMBOL_GPL(nvme_set_queue_count);
942
943 static int nvme_submit_io(struct nvme_ns *ns, struct nvme_user_io __user *uio)
944 {
945         struct nvme_user_io io;
946         struct nvme_command c;
947         unsigned length, meta_len;
948         void __user *metadata;
949
950         if (copy_from_user(&io, uio, sizeof(io)))
951                 return -EFAULT;
952         if (io.flags)
953                 return -EINVAL;
954
955         switch (io.opcode) {
956         case nvme_cmd_write:
957         case nvme_cmd_read:
958         case nvme_cmd_compare:
959                 break;
960         default:
961                 return -EINVAL;
962         }
963
964         length = (io.nblocks + 1) << ns->lba_shift;
965         meta_len = (io.nblocks + 1) * ns->ms;
966         metadata = (void __user *)(uintptr_t)io.metadata;
967
968         if (ns->ext) {
969                 length += meta_len;
970                 meta_len = 0;
971         } else if (meta_len) {
972                 if ((io.metadata & 3) || !io.metadata)
973                         return -EINVAL;
974         }
975
976         memset(&c, 0, sizeof(c));
977         c.rw.opcode = io.opcode;
978         c.rw.flags = io.flags;
979         c.rw.nsid = cpu_to_le32(ns->ns_id);
980         c.rw.slba = cpu_to_le64(io.slba);
981         c.rw.length = cpu_to_le16(io.nblocks);
982         c.rw.control = cpu_to_le16(io.control);
983         c.rw.dsmgmt = cpu_to_le32(io.dsmgmt);
984         c.rw.reftag = cpu_to_le32(io.reftag);
985         c.rw.apptag = cpu_to_le16(io.apptag);
986         c.rw.appmask = cpu_to_le16(io.appmask);
987
988         return nvme_submit_user_cmd(ns->queue, &c,
989                         (void __user *)(uintptr_t)io.addr, length,
990                         metadata, meta_len, io.slba, NULL, 0);
991 }
992
993 static int nvme_user_cmd(struct nvme_ctrl *ctrl, struct nvme_ns *ns,
994                         struct nvme_passthru_cmd __user *ucmd)
995 {
996         struct nvme_passthru_cmd cmd;
997         struct nvme_command c;
998         unsigned timeout = 0;
999         int status;
1000
1001         if (!capable(CAP_SYS_ADMIN))
1002                 return -EACCES;
1003         if (copy_from_user(&cmd, ucmd, sizeof(cmd)))
1004                 return -EFAULT;
1005         if (cmd.flags)
1006                 return -EINVAL;
1007
1008         memset(&c, 0, sizeof(c));
1009         c.common.opcode = cmd.opcode;
1010         c.common.flags = cmd.flags;
1011         c.common.nsid = cpu_to_le32(cmd.nsid);
1012         c.common.cdw2[0] = cpu_to_le32(cmd.cdw2);
1013         c.common.cdw2[1] = cpu_to_le32(cmd.cdw3);
1014         c.common.cdw10[0] = cpu_to_le32(cmd.cdw10);
1015         c.common.cdw10[1] = cpu_to_le32(cmd.cdw11);
1016         c.common.cdw10[2] = cpu_to_le32(cmd.cdw12);
1017         c.common.cdw10[3] = cpu_to_le32(cmd.cdw13);
1018         c.common.cdw10[4] = cpu_to_le32(cmd.cdw14);
1019         c.common.cdw10[5] = cpu_to_le32(cmd.cdw15);
1020
1021         if (cmd.timeout_ms)
1022                 timeout = msecs_to_jiffies(cmd.timeout_ms);
1023
1024         status = nvme_submit_user_cmd(ns ? ns->queue : ctrl->admin_q, &c,
1025                         (void __user *)(uintptr_t)cmd.addr, cmd.data_len,
1026                         (void __user *)(uintptr_t)cmd.metadata, cmd.metadata,
1027                         0, &cmd.result, timeout);
1028         if (status >= 0) {
1029                 if (put_user(cmd.result, &ucmd->result))
1030                         return -EFAULT;
1031         }
1032
1033         return status;
1034 }
1035
1036 static int nvme_ioctl(struct block_device *bdev, fmode_t mode,
1037                 unsigned int cmd, unsigned long arg)
1038 {
1039         struct nvme_ns *ns = bdev->bd_disk->private_data;
1040
1041         switch (cmd) {
1042         case NVME_IOCTL_ID:
1043                 force_successful_syscall_return();
1044                 return ns->ns_id;
1045         case NVME_IOCTL_ADMIN_CMD:
1046                 return nvme_user_cmd(ns->ctrl, NULL, (void __user *)arg);
1047         case NVME_IOCTL_IO_CMD:
1048                 return nvme_user_cmd(ns->ctrl, ns, (void __user *)arg);
1049         case NVME_IOCTL_SUBMIT_IO:
1050                 return nvme_submit_io(ns, (void __user *)arg);
1051         default:
1052 #ifdef CONFIG_NVM
1053                 if (ns->ndev)
1054                         return nvme_nvm_ioctl(ns, cmd, arg);
1055 #endif
1056                 if (is_sed_ioctl(cmd))
1057                         return sed_ioctl(ns->ctrl->opal_dev, cmd,
1058                                          (void __user *) arg);
1059                 return -ENOTTY;
1060         }
1061 }
1062
1063 static int nvme_open(struct block_device *bdev, fmode_t mode)
1064 {
1065         struct nvme_ns *ns = bdev->bd_disk->private_data;
1066
1067         if (!kref_get_unless_zero(&ns->kref))
1068                 return -ENXIO;
1069         return 0;
1070 }
1071
1072 static void nvme_release(struct gendisk *disk, fmode_t mode)
1073 {
1074         nvme_put_ns(disk->private_data);
1075 }
1076
1077 static int nvme_getgeo(struct block_device *bdev, struct hd_geometry *geo)
1078 {
1079         /* some standard values */
1080         geo->heads = 1 << 6;
1081         geo->sectors = 1 << 5;
1082         geo->cylinders = get_capacity(bdev->bd_disk) >> 11;
1083         return 0;
1084 }
1085
1086 #ifdef CONFIG_BLK_DEV_INTEGRITY
1087 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1088                 u16 bs)
1089 {
1090         struct nvme_ns *ns = disk->private_data;
1091         u16 old_ms = ns->ms;
1092         u8 pi_type = 0;
1093
1094         ns->ms = le16_to_cpu(id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ms);
1095         ns->ext = ns->ms && (id->flbas & NVME_NS_FLBAS_META_EXT);
1096
1097         /* PI implementation requires metadata equal t10 pi tuple size */
1098         if (ns->ms == sizeof(struct t10_pi_tuple))
1099                 pi_type = id->dps & NVME_NS_DPS_PI_MASK;
1100
1101         if (blk_get_integrity(disk) &&
1102             (ns->pi_type != pi_type || ns->ms != old_ms ||
1103              bs != queue_logical_block_size(disk->queue) ||
1104              (ns->ms && ns->ext)))
1105                 blk_integrity_unregister(disk);
1106
1107         ns->pi_type = pi_type;
1108 }
1109
1110 static void nvme_init_integrity(struct nvme_ns *ns)
1111 {
1112         struct blk_integrity integrity;
1113
1114         memset(&integrity, 0, sizeof(integrity));
1115         switch (ns->pi_type) {
1116         case NVME_NS_DPS_PI_TYPE3:
1117                 integrity.profile = &t10_pi_type3_crc;
1118                 integrity.tag_size = sizeof(u16) + sizeof(u32);
1119                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1120                 break;
1121         case NVME_NS_DPS_PI_TYPE1:
1122         case NVME_NS_DPS_PI_TYPE2:
1123                 integrity.profile = &t10_pi_type1_crc;
1124                 integrity.tag_size = sizeof(u16);
1125                 integrity.flags |= BLK_INTEGRITY_DEVICE_CAPABLE;
1126                 break;
1127         default:
1128                 integrity.profile = NULL;
1129                 break;
1130         }
1131         integrity.tuple_size = ns->ms;
1132         blk_integrity_register(ns->disk, &integrity);
1133         blk_queue_max_integrity_segments(ns->queue, 1);
1134 }
1135 #else
1136 static void nvme_prep_integrity(struct gendisk *disk, struct nvme_id_ns *id,
1137                 u16 bs)
1138 {
1139 }
1140 static void nvme_init_integrity(struct nvme_ns *ns)
1141 {
1142 }
1143 #endif /* CONFIG_BLK_DEV_INTEGRITY */
1144
1145 static void nvme_set_chunk_size(struct nvme_ns *ns)
1146 {
1147         u32 chunk_size = (((u32)ns->noiob) << (ns->lba_shift - 9));
1148         blk_queue_chunk_sectors(ns->queue, rounddown_pow_of_two(chunk_size));
1149 }
1150
1151 static void nvme_config_discard(struct nvme_ns *ns)
1152 {
1153         struct nvme_ctrl *ctrl = ns->ctrl;
1154         u32 logical_block_size = queue_logical_block_size(ns->queue);
1155
1156         BUILD_BUG_ON(PAGE_SIZE / sizeof(struct nvme_dsm_range) <
1157                         NVME_DSM_MAX_RANGES);
1158
1159         if (ctrl->nr_streams && ns->sws && ns->sgs) {
1160                 unsigned int sz = logical_block_size * ns->sws * ns->sgs;
1161
1162                 ns->queue->limits.discard_alignment = sz;
1163                 ns->queue->limits.discard_granularity = sz;
1164         } else {
1165                 ns->queue->limits.discard_alignment = logical_block_size;
1166                 ns->queue->limits.discard_granularity = logical_block_size;
1167         }
1168         blk_queue_max_discard_sectors(ns->queue, UINT_MAX);
1169         blk_queue_max_discard_segments(ns->queue, NVME_DSM_MAX_RANGES);
1170         queue_flag_set_unlocked(QUEUE_FLAG_DISCARD, ns->queue);
1171
1172         if (ctrl->quirks & NVME_QUIRK_DEALLOCATE_ZEROES)
1173                 blk_queue_max_write_zeroes_sectors(ns->queue, UINT_MAX);
1174 }
1175
1176 static void nvme_report_ns_ids(struct nvme_ctrl *ctrl, unsigned int nsid,
1177                 struct nvme_id_ns *id, u8 *eui64, u8 *nguid, uuid_t *uuid)
1178 {
1179         if (ctrl->vs >= NVME_VS(1, 1, 0))
1180                 memcpy(eui64, id->eui64, sizeof(id->eui64));
1181         if (ctrl->vs >= NVME_VS(1, 2, 0))
1182                 memcpy(nguid, id->nguid, sizeof(id->nguid));
1183         if (ctrl->vs >= NVME_VS(1, 3, 0)) {
1184                  /* Don't treat error as fatal we potentially
1185                   * already have a NGUID or EUI-64
1186                   */
1187                 if (nvme_identify_ns_descs(ctrl, nsid, eui64, nguid, uuid))
1188                         dev_warn(ctrl->device,
1189                                  "%s: Identify Descriptors failed\n", __func__);
1190         }
1191 }
1192
1193 static void __nvme_revalidate_disk(struct gendisk *disk, struct nvme_id_ns *id)
1194 {
1195         struct nvme_ns *ns = disk->private_data;
1196         struct nvme_ctrl *ctrl = ns->ctrl;
1197         u16 bs;
1198
1199         /*
1200          * If identify namespace failed, use default 512 byte block size so
1201          * block layer can use before failing read/write for 0 capacity.
1202          */
1203         ns->lba_shift = id->lbaf[id->flbas & NVME_NS_FLBAS_LBA_MASK].ds;
1204         if (ns->lba_shift == 0)
1205                 ns->lba_shift = 9;
1206         bs = 1 << ns->lba_shift;
1207         ns->noiob = le16_to_cpu(id->noiob);
1208
1209         blk_mq_freeze_queue(disk->queue);
1210
1211         if (ctrl->ops->flags & NVME_F_METADATA_SUPPORTED)
1212                 nvme_prep_integrity(disk, id, bs);
1213         blk_queue_logical_block_size(ns->queue, bs);
1214         if (ns->noiob)
1215                 nvme_set_chunk_size(ns);
1216         if (ns->ms && !blk_get_integrity(disk) && !ns->ext)
1217                 nvme_init_integrity(ns);
1218         if (ns->ms && !(ns->ms == 8 && ns->pi_type) && !blk_get_integrity(disk))
1219                 set_capacity(disk, 0);
1220         else
1221                 set_capacity(disk, le64_to_cpup(&id->nsze) << (ns->lba_shift - 9));
1222
1223         if (ctrl->oncs & NVME_CTRL_ONCS_DSM)
1224                 nvme_config_discard(ns);
1225         blk_mq_unfreeze_queue(disk->queue);
1226 }
1227
1228 static int nvme_revalidate_disk(struct gendisk *disk)
1229 {
1230         struct nvme_ns *ns = disk->private_data;
1231         struct nvme_ctrl *ctrl = ns->ctrl;
1232         struct nvme_id_ns *id;
1233         u8 eui64[8] = { 0 }, nguid[16] = { 0 };
1234         uuid_t uuid = uuid_null;
1235         int ret = 0;
1236
1237         if (test_bit(NVME_NS_DEAD, &ns->flags)) {
1238                 set_capacity(disk, 0);
1239                 return -ENODEV;
1240         }
1241
1242         id = nvme_identify_ns(ctrl, ns->ns_id);
1243         if (!id)
1244                 return -ENODEV;
1245
1246         if (id->ncap == 0) {
1247                 ret = -ENODEV;
1248                 goto out;
1249         }
1250
1251         nvme_report_ns_ids(ctrl, ns->ns_id, id, eui64, nguid, &uuid);
1252         if (!uuid_equal(&ns->uuid, &uuid) ||
1253             memcmp(&ns->nguid, &nguid, sizeof(ns->nguid)) ||
1254             memcmp(&ns->eui, &eui64, sizeof(ns->eui))) {
1255                 dev_err(ctrl->device,
1256                         "identifiers changed for nsid %d\n", ns->ns_id);
1257                 ret = -ENODEV;
1258         }
1259
1260 out:
1261         kfree(id);
1262         return ret;
1263 }
1264
1265 static char nvme_pr_type(enum pr_type type)
1266 {
1267         switch (type) {
1268         case PR_WRITE_EXCLUSIVE:
1269                 return 1;
1270         case PR_EXCLUSIVE_ACCESS:
1271                 return 2;
1272         case PR_WRITE_EXCLUSIVE_REG_ONLY:
1273                 return 3;
1274         case PR_EXCLUSIVE_ACCESS_REG_ONLY:
1275                 return 4;
1276         case PR_WRITE_EXCLUSIVE_ALL_REGS:
1277                 return 5;
1278         case PR_EXCLUSIVE_ACCESS_ALL_REGS:
1279                 return 6;
1280         default:
1281                 return 0;
1282         }
1283 };
1284
1285 static int nvme_pr_command(struct block_device *bdev, u32 cdw10,
1286                                 u64 key, u64 sa_key, u8 op)
1287 {
1288         struct nvme_ns *ns = bdev->bd_disk->private_data;
1289         struct nvme_command c;
1290         u8 data[16] = { 0, };
1291
1292         put_unaligned_le64(key, &data[0]);
1293         put_unaligned_le64(sa_key, &data[8]);
1294
1295         memset(&c, 0, sizeof(c));
1296         c.common.opcode = op;
1297         c.common.nsid = cpu_to_le32(ns->ns_id);
1298         c.common.cdw10[0] = cpu_to_le32(cdw10);
1299
1300         return nvme_submit_sync_cmd(ns->queue, &c, data, 16);
1301 }
1302
1303 static int nvme_pr_register(struct block_device *bdev, u64 old,
1304                 u64 new, unsigned flags)
1305 {
1306         u32 cdw10;
1307
1308         if (flags & ~PR_FL_IGNORE_KEY)
1309                 return -EOPNOTSUPP;
1310
1311         cdw10 = old ? 2 : 0;
1312         cdw10 |= (flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0;
1313         cdw10 |= (1 << 30) | (1 << 31); /* PTPL=1 */
1314         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_register);
1315 }
1316
1317 static int nvme_pr_reserve(struct block_device *bdev, u64 key,
1318                 enum pr_type type, unsigned flags)
1319 {
1320         u32 cdw10;
1321
1322         if (flags & ~PR_FL_IGNORE_KEY)
1323                 return -EOPNOTSUPP;
1324
1325         cdw10 = nvme_pr_type(type) << 8;
1326         cdw10 |= ((flags & PR_FL_IGNORE_KEY) ? 1 << 3 : 0);
1327         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_acquire);
1328 }
1329
1330 static int nvme_pr_preempt(struct block_device *bdev, u64 old, u64 new,
1331                 enum pr_type type, bool abort)
1332 {
1333         u32 cdw10 = nvme_pr_type(type) << 8 | abort ? 2 : 1;
1334         return nvme_pr_command(bdev, cdw10, old, new, nvme_cmd_resv_acquire);
1335 }
1336
1337 static int nvme_pr_clear(struct block_device *bdev, u64 key)
1338 {
1339         u32 cdw10 = 1 | (key ? 1 << 3 : 0);
1340         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_register);
1341 }
1342
1343 static int nvme_pr_release(struct block_device *bdev, u64 key, enum pr_type type)
1344 {
1345         u32 cdw10 = nvme_pr_type(type) << 8 | key ? 1 << 3 : 0;
1346         return nvme_pr_command(bdev, cdw10, key, 0, nvme_cmd_resv_release);
1347 }
1348
1349 static const struct pr_ops nvme_pr_ops = {
1350         .pr_register    = nvme_pr_register,
1351         .pr_reserve     = nvme_pr_reserve,
1352         .pr_release     = nvme_pr_release,
1353         .pr_preempt     = nvme_pr_preempt,
1354         .pr_clear       = nvme_pr_clear,
1355 };
1356
1357 #ifdef CONFIG_BLK_SED_OPAL
1358 int nvme_sec_submit(void *data, u16 spsp, u8 secp, void *buffer, size_t len,
1359                 bool send)
1360 {
1361         struct nvme_ctrl *ctrl = data;
1362         struct nvme_command cmd;
1363
1364         memset(&cmd, 0, sizeof(cmd));
1365         if (send)
1366                 cmd.common.opcode = nvme_admin_security_send;
1367         else
1368                 cmd.common.opcode = nvme_admin_security_recv;
1369         cmd.common.nsid = 0;
1370         cmd.common.cdw10[0] = cpu_to_le32(((u32)secp) << 24 | ((u32)spsp) << 8);
1371         cmd.common.cdw10[1] = cpu_to_le32(len);
1372
1373         return __nvme_submit_sync_cmd(ctrl->admin_q, &cmd, NULL, buffer, len,
1374                                       ADMIN_TIMEOUT, NVME_QID_ANY, 1, 0);
1375 }
1376 EXPORT_SYMBOL_GPL(nvme_sec_submit);
1377 #endif /* CONFIG_BLK_SED_OPAL */
1378
1379 static const struct block_device_operations nvme_fops = {
1380         .owner          = THIS_MODULE,
1381         .ioctl          = nvme_ioctl,
1382         .compat_ioctl   = nvme_ioctl,
1383         .open           = nvme_open,
1384         .release        = nvme_release,
1385         .getgeo         = nvme_getgeo,
1386         .revalidate_disk= nvme_revalidate_disk,
1387         .pr_ops         = &nvme_pr_ops,
1388 };
1389
1390 static int nvme_wait_ready(struct nvme_ctrl *ctrl, u64 cap, bool enabled)
1391 {
1392         unsigned long timeout =
1393                 ((NVME_CAP_TIMEOUT(cap) + 1) * HZ / 2) + jiffies;
1394         u32 csts, bit = enabled ? NVME_CSTS_RDY : 0;
1395         int ret;
1396
1397         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1398                 if (csts == ~0)
1399                         return -ENODEV;
1400                 if ((csts & NVME_CSTS_RDY) == bit)
1401                         break;
1402
1403                 msleep(100);
1404                 if (fatal_signal_pending(current))
1405                         return -EINTR;
1406                 if (time_after(jiffies, timeout)) {
1407                         dev_err(ctrl->device,
1408                                 "Device not ready; aborting %s\n", enabled ?
1409                                                 "initialisation" : "reset");
1410                         return -ENODEV;
1411                 }
1412         }
1413
1414         return ret;
1415 }
1416
1417 /*
1418  * If the device has been passed off to us in an enabled state, just clear
1419  * the enabled bit.  The spec says we should set the 'shutdown notification
1420  * bits', but doing so may cause the device to complete commands to the
1421  * admin queue ... and we don't know what memory that might be pointing at!
1422  */
1423 int nvme_disable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1424 {
1425         int ret;
1426
1427         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1428         ctrl->ctrl_config &= ~NVME_CC_ENABLE;
1429
1430         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1431         if (ret)
1432                 return ret;
1433
1434         if (ctrl->quirks & NVME_QUIRK_DELAY_BEFORE_CHK_RDY)
1435                 msleep(NVME_QUIRK_DELAY_AMOUNT);
1436
1437         return nvme_wait_ready(ctrl, cap, false);
1438 }
1439 EXPORT_SYMBOL_GPL(nvme_disable_ctrl);
1440
1441 int nvme_enable_ctrl(struct nvme_ctrl *ctrl, u64 cap)
1442 {
1443         /*
1444          * Default to a 4K page size, with the intention to update this
1445          * path in the future to accomodate architectures with differing
1446          * kernel and IO page sizes.
1447          */
1448         unsigned dev_page_min = NVME_CAP_MPSMIN(cap) + 12, page_shift = 12;
1449         int ret;
1450
1451         if (page_shift < dev_page_min) {
1452                 dev_err(ctrl->device,
1453                         "Minimum device page size %u too large for host (%u)\n",
1454                         1 << dev_page_min, 1 << page_shift);
1455                 return -ENODEV;
1456         }
1457
1458         ctrl->page_size = 1 << page_shift;
1459
1460         ctrl->ctrl_config = NVME_CC_CSS_NVM;
1461         ctrl->ctrl_config |= (page_shift - 12) << NVME_CC_MPS_SHIFT;
1462         ctrl->ctrl_config |= NVME_CC_AMS_RR | NVME_CC_SHN_NONE;
1463         ctrl->ctrl_config |= NVME_CC_IOSQES | NVME_CC_IOCQES;
1464         ctrl->ctrl_config |= NVME_CC_ENABLE;
1465
1466         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1467         if (ret)
1468                 return ret;
1469         return nvme_wait_ready(ctrl, cap, true);
1470 }
1471 EXPORT_SYMBOL_GPL(nvme_enable_ctrl);
1472
1473 int nvme_shutdown_ctrl(struct nvme_ctrl *ctrl)
1474 {
1475         unsigned long timeout = jiffies + (ctrl->shutdown_timeout * HZ);
1476         u32 csts;
1477         int ret;
1478
1479         ctrl->ctrl_config &= ~NVME_CC_SHN_MASK;
1480         ctrl->ctrl_config |= NVME_CC_SHN_NORMAL;
1481
1482         ret = ctrl->ops->reg_write32(ctrl, NVME_REG_CC, ctrl->ctrl_config);
1483         if (ret)
1484                 return ret;
1485
1486         while ((ret = ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts)) == 0) {
1487                 if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_CMPLT)
1488                         break;
1489
1490                 msleep(100);
1491                 if (fatal_signal_pending(current))
1492                         return -EINTR;
1493                 if (time_after(jiffies, timeout)) {
1494                         dev_err(ctrl->device,
1495                                 "Device shutdown incomplete; abort shutdown\n");
1496                         return -ENODEV;
1497                 }
1498         }
1499
1500         return ret;
1501 }
1502 EXPORT_SYMBOL_GPL(nvme_shutdown_ctrl);
1503
1504 static void nvme_set_queue_limits(struct nvme_ctrl *ctrl,
1505                 struct request_queue *q)
1506 {
1507         bool vwc = false;
1508
1509         if (ctrl->max_hw_sectors) {
1510                 u32 max_segments =
1511                         (ctrl->max_hw_sectors / (ctrl->page_size >> 9)) + 1;
1512
1513                 blk_queue_max_hw_sectors(q, ctrl->max_hw_sectors);
1514                 blk_queue_max_segments(q, min_t(u32, max_segments, USHRT_MAX));
1515         }
1516         if (ctrl->quirks & NVME_QUIRK_STRIPE_SIZE)
1517                 blk_queue_chunk_sectors(q, ctrl->max_hw_sectors);
1518         blk_queue_virt_boundary(q, ctrl->page_size - 1);
1519         if (ctrl->vwc & NVME_CTRL_VWC_PRESENT)
1520                 vwc = true;
1521         blk_queue_write_cache(q, vwc, vwc);
1522 }
1523
1524 static int nvme_configure_timestamp(struct nvme_ctrl *ctrl)
1525 {
1526         __le64 ts;
1527         int ret;
1528
1529         if (!(ctrl->oncs & NVME_CTRL_ONCS_TIMESTAMP))
1530                 return 0;
1531
1532         ts = cpu_to_le64(ktime_to_ms(ktime_get_real()));
1533         ret = nvme_set_features(ctrl, NVME_FEAT_TIMESTAMP, 0, &ts, sizeof(ts),
1534                         NULL);
1535         if (ret)
1536                 dev_warn_once(ctrl->device,
1537                         "could not set timestamp (%d)\n", ret);
1538         return ret;
1539 }
1540
1541 static int nvme_configure_apst(struct nvme_ctrl *ctrl)
1542 {
1543         /*
1544          * APST (Autonomous Power State Transition) lets us program a
1545          * table of power state transitions that the controller will
1546          * perform automatically.  We configure it with a simple
1547          * heuristic: we are willing to spend at most 2% of the time
1548          * transitioning between power states.  Therefore, when running
1549          * in any given state, we will enter the next lower-power
1550          * non-operational state after waiting 50 * (enlat + exlat)
1551          * microseconds, as long as that state's exit latency is under
1552          * the requested maximum latency.
1553          *
1554          * We will not autonomously enter any non-operational state for
1555          * which the total latency exceeds ps_max_latency_us.  Users
1556          * can set ps_max_latency_us to zero to turn off APST.
1557          */
1558
1559         unsigned apste;
1560         struct nvme_feat_auto_pst *table;
1561         u64 max_lat_us = 0;
1562         int max_ps = -1;
1563         int ret;
1564
1565         /*
1566          * If APST isn't supported or if we haven't been initialized yet,
1567          * then don't do anything.
1568          */
1569         if (!ctrl->apsta)
1570                 return 0;
1571
1572         if (ctrl->npss > 31) {
1573                 dev_warn(ctrl->device, "NPSS is invalid; not using APST\n");
1574                 return 0;
1575         }
1576
1577         table = kzalloc(sizeof(*table), GFP_KERNEL);
1578         if (!table)
1579                 return 0;
1580
1581         if (!ctrl->apst_enabled || ctrl->ps_max_latency_us == 0) {
1582                 /* Turn off APST. */
1583                 apste = 0;
1584                 dev_dbg(ctrl->device, "APST disabled\n");
1585         } else {
1586                 __le64 target = cpu_to_le64(0);
1587                 int state;
1588
1589                 /*
1590                  * Walk through all states from lowest- to highest-power.
1591                  * According to the spec, lower-numbered states use more
1592                  * power.  NPSS, despite the name, is the index of the
1593                  * lowest-power state, not the number of states.
1594                  */
1595                 for (state = (int)ctrl->npss; state >= 0; state--) {
1596                         u64 total_latency_us, exit_latency_us, transition_ms;
1597
1598                         if (target)
1599                                 table->entries[state] = target;
1600
1601                         /*
1602                          * Don't allow transitions to the deepest state
1603                          * if it's quirked off.
1604                          */
1605                         if (state == ctrl->npss &&
1606                             (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS))
1607                                 continue;
1608
1609                         /*
1610                          * Is this state a useful non-operational state for
1611                          * higher-power states to autonomously transition to?
1612                          */
1613                         if (!(ctrl->psd[state].flags &
1614                               NVME_PS_FLAGS_NON_OP_STATE))
1615                                 continue;
1616
1617                         exit_latency_us =
1618                                 (u64)le32_to_cpu(ctrl->psd[state].exit_lat);
1619                         if (exit_latency_us > ctrl->ps_max_latency_us)
1620                                 continue;
1621
1622                         total_latency_us =
1623                                 exit_latency_us +
1624                                 le32_to_cpu(ctrl->psd[state].entry_lat);
1625
1626                         /*
1627                          * This state is good.  Use it as the APST idle
1628                          * target for higher power states.
1629                          */
1630                         transition_ms = total_latency_us + 19;
1631                         do_div(transition_ms, 20);
1632                         if (transition_ms > (1 << 24) - 1)
1633                                 transition_ms = (1 << 24) - 1;
1634
1635                         target = cpu_to_le64((state << 3) |
1636                                              (transition_ms << 8));
1637
1638                         if (max_ps == -1)
1639                                 max_ps = state;
1640
1641                         if (total_latency_us > max_lat_us)
1642                                 max_lat_us = total_latency_us;
1643                 }
1644
1645                 apste = 1;
1646
1647                 if (max_ps == -1) {
1648                         dev_dbg(ctrl->device, "APST enabled but no non-operational states are available\n");
1649                 } else {
1650                         dev_dbg(ctrl->device, "APST enabled: max PS = %d, max round-trip latency = %lluus, table = %*phN\n",
1651                                 max_ps, max_lat_us, (int)sizeof(*table), table);
1652                 }
1653         }
1654
1655         ret = nvme_set_features(ctrl, NVME_FEAT_AUTO_PST, apste,
1656                                 table, sizeof(*table), NULL);
1657         if (ret)
1658                 dev_err(ctrl->device, "failed to set APST feature (%d)\n", ret);
1659
1660         kfree(table);
1661         return ret;
1662 }
1663
1664 static void nvme_set_latency_tolerance(struct device *dev, s32 val)
1665 {
1666         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
1667         u64 latency;
1668
1669         switch (val) {
1670         case PM_QOS_LATENCY_TOLERANCE_NO_CONSTRAINT:
1671         case PM_QOS_LATENCY_ANY:
1672                 latency = U64_MAX;
1673                 break;
1674
1675         default:
1676                 latency = val;
1677         }
1678
1679         if (ctrl->ps_max_latency_us != latency) {
1680                 ctrl->ps_max_latency_us = latency;
1681                 nvme_configure_apst(ctrl);
1682         }
1683 }
1684
1685 struct nvme_core_quirk_entry {
1686         /*
1687          * NVMe model and firmware strings are padded with spaces.  For
1688          * simplicity, strings in the quirk table are padded with NULLs
1689          * instead.
1690          */
1691         u16 vid;
1692         const char *mn;
1693         const char *fr;
1694         unsigned long quirks;
1695 };
1696
1697 static const struct nvme_core_quirk_entry core_quirks[] = {
1698         {
1699                 /*
1700                  * This Toshiba device seems to die using any APST states.  See:
1701                  * https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1678184/comments/11
1702                  */
1703                 .vid = 0x1179,
1704                 .mn = "THNSF5256GPUK TOSHIBA",
1705                 .quirks = NVME_QUIRK_NO_APST,
1706         }
1707 };
1708
1709 /* match is null-terminated but idstr is space-padded. */
1710 static bool string_matches(const char *idstr, const char *match, size_t len)
1711 {
1712         size_t matchlen;
1713
1714         if (!match)
1715                 return true;
1716
1717         matchlen = strlen(match);
1718         WARN_ON_ONCE(matchlen > len);
1719
1720         if (memcmp(idstr, match, matchlen))
1721                 return false;
1722
1723         for (; matchlen < len; matchlen++)
1724                 if (idstr[matchlen] != ' ')
1725                         return false;
1726
1727         return true;
1728 }
1729
1730 static bool quirk_matches(const struct nvme_id_ctrl *id,
1731                           const struct nvme_core_quirk_entry *q)
1732 {
1733         return q->vid == le16_to_cpu(id->vid) &&
1734                 string_matches(id->mn, q->mn, sizeof(id->mn)) &&
1735                 string_matches(id->fr, q->fr, sizeof(id->fr));
1736 }
1737
1738 static void nvme_init_subnqn(struct nvme_ctrl *ctrl, struct nvme_id_ctrl *id)
1739 {
1740         size_t nqnlen;
1741         int off;
1742
1743         nqnlen = strnlen(id->subnqn, NVMF_NQN_SIZE);
1744         if (nqnlen > 0 && nqnlen < NVMF_NQN_SIZE) {
1745                 strcpy(ctrl->subnqn, id->subnqn);
1746                 return;
1747         }
1748
1749         if (ctrl->vs >= NVME_VS(1, 2, 1))
1750                 dev_warn(ctrl->device, "missing or invalid SUBNQN field.\n");
1751
1752         /* Generate a "fake" NQN per Figure 254 in NVMe 1.3 + ECN 001 */
1753         off = snprintf(ctrl->subnqn, NVMF_NQN_SIZE,
1754                         "nqn.2014.08.org.nvmexpress:%4x%4x",
1755                         le16_to_cpu(id->vid), le16_to_cpu(id->ssvid));
1756         memcpy(ctrl->subnqn + off, id->sn, sizeof(id->sn));
1757         off += sizeof(id->sn);
1758         memcpy(ctrl->subnqn + off, id->mn, sizeof(id->mn));
1759         off += sizeof(id->mn);
1760         memset(ctrl->subnqn + off, 0, sizeof(ctrl->subnqn) - off);
1761 }
1762
1763 /*
1764  * Initialize the cached copies of the Identify data and various controller
1765  * register in our nvme_ctrl structure.  This should be called as soon as
1766  * the admin queue is fully up and running.
1767  */
1768 int nvme_init_identify(struct nvme_ctrl *ctrl)
1769 {
1770         struct nvme_id_ctrl *id;
1771         u64 cap;
1772         int ret, page_shift;
1773         u32 max_hw_sectors;
1774         bool prev_apst_enabled;
1775
1776         ret = ctrl->ops->reg_read32(ctrl, NVME_REG_VS, &ctrl->vs);
1777         if (ret) {
1778                 dev_err(ctrl->device, "Reading VS failed (%d)\n", ret);
1779                 return ret;
1780         }
1781
1782         ret = ctrl->ops->reg_read64(ctrl, NVME_REG_CAP, &cap);
1783         if (ret) {
1784                 dev_err(ctrl->device, "Reading CAP failed (%d)\n", ret);
1785                 return ret;
1786         }
1787         page_shift = NVME_CAP_MPSMIN(cap) + 12;
1788
1789         if (ctrl->vs >= NVME_VS(1, 1, 0))
1790                 ctrl->subsystem = NVME_CAP_NSSRC(cap);
1791
1792         ret = nvme_identify_ctrl(ctrl, &id);
1793         if (ret) {
1794                 dev_err(ctrl->device, "Identify Controller failed (%d)\n", ret);
1795                 return -EIO;
1796         }
1797
1798         nvme_init_subnqn(ctrl, id);
1799
1800         if (!ctrl->identified) {
1801                 /*
1802                  * Check for quirks.  Quirk can depend on firmware version,
1803                  * so, in principle, the set of quirks present can change
1804                  * across a reset.  As a possible future enhancement, we
1805                  * could re-scan for quirks every time we reinitialize
1806                  * the device, but we'd have to make sure that the driver
1807                  * behaves intelligently if the quirks change.
1808                  */
1809
1810                 int i;
1811
1812                 for (i = 0; i < ARRAY_SIZE(core_quirks); i++) {
1813                         if (quirk_matches(id, &core_quirks[i]))
1814                                 ctrl->quirks |= core_quirks[i].quirks;
1815                 }
1816         }
1817
1818         if (force_apst && (ctrl->quirks & NVME_QUIRK_NO_DEEPEST_PS)) {
1819                 dev_warn(ctrl->device, "forcibly allowing all power states due to nvme_core.force_apst -- use at your own risk\n");
1820                 ctrl->quirks &= ~NVME_QUIRK_NO_DEEPEST_PS;
1821         }
1822
1823         ctrl->oacs = le16_to_cpu(id->oacs);
1824         ctrl->vid = le16_to_cpu(id->vid);
1825         ctrl->oncs = le16_to_cpup(&id->oncs);
1826         atomic_set(&ctrl->abort_limit, id->acl + 1);
1827         ctrl->vwc = id->vwc;
1828         ctrl->cntlid = le16_to_cpup(&id->cntlid);
1829         memcpy(ctrl->serial, id->sn, sizeof(id->sn));
1830         memcpy(ctrl->model, id->mn, sizeof(id->mn));
1831         memcpy(ctrl->firmware_rev, id->fr, sizeof(id->fr));
1832         if (id->mdts)
1833                 max_hw_sectors = 1 << (id->mdts + page_shift - 9);
1834         else
1835                 max_hw_sectors = UINT_MAX;
1836         ctrl->max_hw_sectors =
1837                 min_not_zero(ctrl->max_hw_sectors, max_hw_sectors);
1838
1839         nvme_set_queue_limits(ctrl, ctrl->admin_q);
1840         ctrl->sgls = le32_to_cpu(id->sgls);
1841         ctrl->kas = le16_to_cpu(id->kas);
1842
1843         if (id->rtd3e) {
1844                 /* us -> s */
1845                 u32 transition_time = le32_to_cpu(id->rtd3e) / 1000000;
1846
1847                 ctrl->shutdown_timeout = clamp_t(unsigned int, transition_time,
1848                                                  shutdown_timeout, 60);
1849
1850                 if (ctrl->shutdown_timeout != shutdown_timeout)
1851                         dev_warn(ctrl->device,
1852                                  "Shutdown timeout set to %u seconds\n",
1853                                  ctrl->shutdown_timeout);
1854         } else
1855                 ctrl->shutdown_timeout = shutdown_timeout;
1856
1857         ctrl->npss = id->npss;
1858         ctrl->apsta = id->apsta;
1859         prev_apst_enabled = ctrl->apst_enabled;
1860         if (ctrl->quirks & NVME_QUIRK_NO_APST) {
1861                 if (force_apst && id->apsta) {
1862                         dev_warn(ctrl->device, "forcibly allowing APST due to nvme_core.force_apst -- use at your own risk\n");
1863                         ctrl->apst_enabled = true;
1864                 } else {
1865                         ctrl->apst_enabled = false;
1866                 }
1867         } else {
1868                 ctrl->apst_enabled = id->apsta;
1869         }
1870         memcpy(ctrl->psd, id->psd, sizeof(ctrl->psd));
1871
1872         if (ctrl->ops->flags & NVME_F_FABRICS) {
1873                 ctrl->icdoff = le16_to_cpu(id->icdoff);
1874                 ctrl->ioccsz = le32_to_cpu(id->ioccsz);
1875                 ctrl->iorcsz = le32_to_cpu(id->iorcsz);
1876                 ctrl->maxcmd = le16_to_cpu(id->maxcmd);
1877
1878                 /*
1879                  * In fabrics we need to verify the cntlid matches the
1880                  * admin connect
1881                  */
1882                 if (ctrl->cntlid != le16_to_cpu(id->cntlid)) {
1883                         ret = -EINVAL;
1884                         goto out_free;
1885                 }
1886
1887                 if (!ctrl->opts->discovery_nqn && !ctrl->kas) {
1888                         dev_err(ctrl->device,
1889                                 "keep-alive support is mandatory for fabrics\n");
1890                         ret = -EINVAL;
1891                         goto out_free;
1892                 }
1893         } else {
1894                 ctrl->cntlid = le16_to_cpu(id->cntlid);
1895                 ctrl->hmpre = le32_to_cpu(id->hmpre);
1896                 ctrl->hmmin = le32_to_cpu(id->hmmin);
1897                 ctrl->hmminds = le32_to_cpu(id->hmminds);
1898                 ctrl->hmmaxd = le16_to_cpu(id->hmmaxd);
1899         }
1900
1901         kfree(id);
1902
1903         if (ctrl->apst_enabled && !prev_apst_enabled)
1904                 dev_pm_qos_expose_latency_tolerance(ctrl->device);
1905         else if (!ctrl->apst_enabled && prev_apst_enabled)
1906                 dev_pm_qos_hide_latency_tolerance(ctrl->device);
1907
1908         ret = nvme_configure_apst(ctrl);
1909         if (ret < 0)
1910                 return ret;
1911         
1912         ret = nvme_configure_timestamp(ctrl);
1913         if (ret < 0)
1914                 return ret;
1915
1916         ret = nvme_configure_directives(ctrl);
1917         if (ret < 0)
1918                 return ret;
1919
1920         ctrl->identified = true;
1921
1922         return 0;
1923
1924 out_free:
1925         kfree(id);
1926         return ret;
1927 }
1928 EXPORT_SYMBOL_GPL(nvme_init_identify);
1929
1930 static int nvme_dev_open(struct inode *inode, struct file *file)
1931 {
1932         struct nvme_ctrl *ctrl =
1933                 container_of(inode->i_cdev, struct nvme_ctrl, cdev);
1934
1935         if (ctrl->state != NVME_CTRL_LIVE)
1936                 return -EWOULDBLOCK;
1937         file->private_data = ctrl;
1938         return 0;
1939 }
1940
1941 static int nvme_dev_user_cmd(struct nvme_ctrl *ctrl, void __user *argp)
1942 {
1943         struct nvme_ns *ns;
1944         int ret;
1945
1946         mutex_lock(&ctrl->namespaces_mutex);
1947         if (list_empty(&ctrl->namespaces)) {
1948                 ret = -ENOTTY;
1949                 goto out_unlock;
1950         }
1951
1952         ns = list_first_entry(&ctrl->namespaces, struct nvme_ns, list);
1953         if (ns != list_last_entry(&ctrl->namespaces, struct nvme_ns, list)) {
1954                 dev_warn(ctrl->device,
1955                         "NVME_IOCTL_IO_CMD not supported when multiple namespaces present!\n");
1956                 ret = -EINVAL;
1957                 goto out_unlock;
1958         }
1959
1960         dev_warn(ctrl->device,
1961                 "using deprecated NVME_IOCTL_IO_CMD ioctl on the char device!\n");
1962         kref_get(&ns->kref);
1963         mutex_unlock(&ctrl->namespaces_mutex);
1964
1965         ret = nvme_user_cmd(ctrl, ns, argp);
1966         nvme_put_ns(ns);
1967         return ret;
1968
1969 out_unlock:
1970         mutex_unlock(&ctrl->namespaces_mutex);
1971         return ret;
1972 }
1973
1974 static long nvme_dev_ioctl(struct file *file, unsigned int cmd,
1975                 unsigned long arg)
1976 {
1977         struct nvme_ctrl *ctrl = file->private_data;
1978         void __user *argp = (void __user *)arg;
1979
1980         switch (cmd) {
1981         case NVME_IOCTL_ADMIN_CMD:
1982                 return nvme_user_cmd(ctrl, NULL, argp);
1983         case NVME_IOCTL_IO_CMD:
1984                 return nvme_dev_user_cmd(ctrl, argp);
1985         case NVME_IOCTL_RESET:
1986                 dev_warn(ctrl->device, "resetting controller\n");
1987                 return nvme_reset_ctrl_sync(ctrl);
1988         case NVME_IOCTL_SUBSYS_RESET:
1989                 return nvme_reset_subsystem(ctrl);
1990         case NVME_IOCTL_RESCAN:
1991                 nvme_queue_scan(ctrl);
1992                 return 0;
1993         default:
1994                 return -ENOTTY;
1995         }
1996 }
1997
1998 static const struct file_operations nvme_dev_fops = {
1999         .owner          = THIS_MODULE,
2000         .open           = nvme_dev_open,
2001         .unlocked_ioctl = nvme_dev_ioctl,
2002         .compat_ioctl   = nvme_dev_ioctl,
2003 };
2004
2005 static ssize_t nvme_sysfs_reset(struct device *dev,
2006                                 struct device_attribute *attr, const char *buf,
2007                                 size_t count)
2008 {
2009         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2010         int ret;
2011
2012         ret = nvme_reset_ctrl_sync(ctrl);
2013         if (ret < 0)
2014                 return ret;
2015         return count;
2016 }
2017 static DEVICE_ATTR(reset_controller, S_IWUSR, NULL, nvme_sysfs_reset);
2018
2019 static ssize_t nvme_sysfs_rescan(struct device *dev,
2020                                 struct device_attribute *attr, const char *buf,
2021                                 size_t count)
2022 {
2023         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2024
2025         nvme_queue_scan(ctrl);
2026         return count;
2027 }
2028 static DEVICE_ATTR(rescan_controller, S_IWUSR, NULL, nvme_sysfs_rescan);
2029
2030 static ssize_t wwid_show(struct device *dev, struct device_attribute *attr,
2031                                                                 char *buf)
2032 {
2033         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2034         struct nvme_ctrl *ctrl = ns->ctrl;
2035         int serial_len = sizeof(ctrl->serial);
2036         int model_len = sizeof(ctrl->model);
2037
2038         if (!uuid_is_null(&ns->uuid))
2039                 return sprintf(buf, "uuid.%pU\n", &ns->uuid);
2040
2041         if (memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2042                 return sprintf(buf, "eui.%16phN\n", ns->nguid);
2043
2044         if (memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2045                 return sprintf(buf, "eui.%8phN\n", ns->eui);
2046
2047         while (serial_len > 0 && (ctrl->serial[serial_len - 1] == ' ' ||
2048                                   ctrl->serial[serial_len - 1] == '\0'))
2049                 serial_len--;
2050         while (model_len > 0 && (ctrl->model[model_len - 1] == ' ' ||
2051                                  ctrl->model[model_len - 1] == '\0'))
2052                 model_len--;
2053
2054         return sprintf(buf, "nvme.%04x-%*phN-%*phN-%08x\n", ctrl->vid,
2055                 serial_len, ctrl->serial, model_len, ctrl->model, ns->ns_id);
2056 }
2057 static DEVICE_ATTR(wwid, S_IRUGO, wwid_show, NULL);
2058
2059 static ssize_t nguid_show(struct device *dev, struct device_attribute *attr,
2060                           char *buf)
2061 {
2062         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2063         return sprintf(buf, "%pU\n", ns->nguid);
2064 }
2065 static DEVICE_ATTR(nguid, S_IRUGO, nguid_show, NULL);
2066
2067 static ssize_t uuid_show(struct device *dev, struct device_attribute *attr,
2068                                                                 char *buf)
2069 {
2070         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2071
2072         /* For backward compatibility expose the NGUID to userspace if
2073          * we have no UUID set
2074          */
2075         if (uuid_is_null(&ns->uuid)) {
2076                 printk_ratelimited(KERN_WARNING
2077                                    "No UUID available providing old NGUID\n");
2078                 return sprintf(buf, "%pU\n", ns->nguid);
2079         }
2080         return sprintf(buf, "%pU\n", &ns->uuid);
2081 }
2082 static DEVICE_ATTR(uuid, S_IRUGO, uuid_show, NULL);
2083
2084 static ssize_t eui_show(struct device *dev, struct device_attribute *attr,
2085                                                                 char *buf)
2086 {
2087         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2088         return sprintf(buf, "%8phd\n", ns->eui);
2089 }
2090 static DEVICE_ATTR(eui, S_IRUGO, eui_show, NULL);
2091
2092 static ssize_t nsid_show(struct device *dev, struct device_attribute *attr,
2093                                                                 char *buf)
2094 {
2095         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2096         return sprintf(buf, "%d\n", ns->ns_id);
2097 }
2098 static DEVICE_ATTR(nsid, S_IRUGO, nsid_show, NULL);
2099
2100 static struct attribute *nvme_ns_attrs[] = {
2101         &dev_attr_wwid.attr,
2102         &dev_attr_uuid.attr,
2103         &dev_attr_nguid.attr,
2104         &dev_attr_eui.attr,
2105         &dev_attr_nsid.attr,
2106         NULL,
2107 };
2108
2109 static umode_t nvme_ns_attrs_are_visible(struct kobject *kobj,
2110                 struct attribute *a, int n)
2111 {
2112         struct device *dev = container_of(kobj, struct device, kobj);
2113         struct nvme_ns *ns = nvme_get_ns_from_dev(dev);
2114
2115         if (a == &dev_attr_uuid.attr) {
2116                 if (uuid_is_null(&ns->uuid) ||
2117                     !memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2118                         return 0;
2119         }
2120         if (a == &dev_attr_nguid.attr) {
2121                 if (!memchr_inv(ns->nguid, 0, sizeof(ns->nguid)))
2122                         return 0;
2123         }
2124         if (a == &dev_attr_eui.attr) {
2125                 if (!memchr_inv(ns->eui, 0, sizeof(ns->eui)))
2126                         return 0;
2127         }
2128         return a->mode;
2129 }
2130
2131 static const struct attribute_group nvme_ns_attr_group = {
2132         .attrs          = nvme_ns_attrs,
2133         .is_visible     = nvme_ns_attrs_are_visible,
2134 };
2135
2136 #define nvme_show_str_function(field)                                           \
2137 static ssize_t  field##_show(struct device *dev,                                \
2138                             struct device_attribute *attr, char *buf)           \
2139 {                                                                               \
2140         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
2141         return sprintf(buf, "%.*s\n", (int)sizeof(ctrl->field), ctrl->field);   \
2142 }                                                                               \
2143 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2144
2145 #define nvme_show_int_function(field)                                           \
2146 static ssize_t  field##_show(struct device *dev,                                \
2147                             struct device_attribute *attr, char *buf)           \
2148 {                                                                               \
2149         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);                          \
2150         return sprintf(buf, "%d\n", ctrl->field);       \
2151 }                                                                               \
2152 static DEVICE_ATTR(field, S_IRUGO, field##_show, NULL);
2153
2154 nvme_show_str_function(model);
2155 nvme_show_str_function(serial);
2156 nvme_show_str_function(firmware_rev);
2157 nvme_show_int_function(cntlid);
2158
2159 static ssize_t nvme_sysfs_delete(struct device *dev,
2160                                 struct device_attribute *attr, const char *buf,
2161                                 size_t count)
2162 {
2163         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2164
2165         if (device_remove_file_self(dev, attr))
2166                 nvme_delete_ctrl_sync(ctrl);
2167         return count;
2168 }
2169 static DEVICE_ATTR(delete_controller, S_IWUSR, NULL, nvme_sysfs_delete);
2170
2171 static ssize_t nvme_sysfs_show_transport(struct device *dev,
2172                                          struct device_attribute *attr,
2173                                          char *buf)
2174 {
2175         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2176
2177         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->ops->name);
2178 }
2179 static DEVICE_ATTR(transport, S_IRUGO, nvme_sysfs_show_transport, NULL);
2180
2181 static ssize_t nvme_sysfs_show_state(struct device *dev,
2182                                      struct device_attribute *attr,
2183                                      char *buf)
2184 {
2185         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2186         static const char *const state_name[] = {
2187                 [NVME_CTRL_NEW]         = "new",
2188                 [NVME_CTRL_LIVE]        = "live",
2189                 [NVME_CTRL_RESETTING]   = "resetting",
2190                 [NVME_CTRL_RECONNECTING]= "reconnecting",
2191                 [NVME_CTRL_DELETING]    = "deleting",
2192                 [NVME_CTRL_DEAD]        = "dead",
2193         };
2194
2195         if ((unsigned)ctrl->state < ARRAY_SIZE(state_name) &&
2196             state_name[ctrl->state])
2197                 return sprintf(buf, "%s\n", state_name[ctrl->state]);
2198
2199         return sprintf(buf, "unknown state\n");
2200 }
2201
2202 static DEVICE_ATTR(state, S_IRUGO, nvme_sysfs_show_state, NULL);
2203
2204 static ssize_t nvme_sysfs_show_subsysnqn(struct device *dev,
2205                                          struct device_attribute *attr,
2206                                          char *buf)
2207 {
2208         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2209
2210         return snprintf(buf, PAGE_SIZE, "%s\n", ctrl->subnqn);
2211 }
2212 static DEVICE_ATTR(subsysnqn, S_IRUGO, nvme_sysfs_show_subsysnqn, NULL);
2213
2214 static ssize_t nvme_sysfs_show_address(struct device *dev,
2215                                          struct device_attribute *attr,
2216                                          char *buf)
2217 {
2218         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2219
2220         return ctrl->ops->get_address(ctrl, buf, PAGE_SIZE);
2221 }
2222 static DEVICE_ATTR(address, S_IRUGO, nvme_sysfs_show_address, NULL);
2223
2224 static struct attribute *nvme_dev_attrs[] = {
2225         &dev_attr_reset_controller.attr,
2226         &dev_attr_rescan_controller.attr,
2227         &dev_attr_model.attr,
2228         &dev_attr_serial.attr,
2229         &dev_attr_firmware_rev.attr,
2230         &dev_attr_cntlid.attr,
2231         &dev_attr_delete_controller.attr,
2232         &dev_attr_transport.attr,
2233         &dev_attr_subsysnqn.attr,
2234         &dev_attr_address.attr,
2235         &dev_attr_state.attr,
2236         NULL
2237 };
2238
2239 static umode_t nvme_dev_attrs_are_visible(struct kobject *kobj,
2240                 struct attribute *a, int n)
2241 {
2242         struct device *dev = container_of(kobj, struct device, kobj);
2243         struct nvme_ctrl *ctrl = dev_get_drvdata(dev);
2244
2245         if (a == &dev_attr_delete_controller.attr && !ctrl->ops->delete_ctrl)
2246                 return 0;
2247         if (a == &dev_attr_address.attr && !ctrl->ops->get_address)
2248                 return 0;
2249
2250         return a->mode;
2251 }
2252
2253 static struct attribute_group nvme_dev_attrs_group = {
2254         .attrs          = nvme_dev_attrs,
2255         .is_visible     = nvme_dev_attrs_are_visible,
2256 };
2257
2258 static const struct attribute_group *nvme_dev_attr_groups[] = {
2259         &nvme_dev_attrs_group,
2260         NULL,
2261 };
2262
2263 static int ns_cmp(void *priv, struct list_head *a, struct list_head *b)
2264 {
2265         struct nvme_ns *nsa = container_of(a, struct nvme_ns, list);
2266         struct nvme_ns *nsb = container_of(b, struct nvme_ns, list);
2267
2268         return nsa->ns_id - nsb->ns_id;
2269 }
2270
2271 static struct nvme_ns *nvme_find_get_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2272 {
2273         struct nvme_ns *ns, *ret = NULL;
2274
2275         mutex_lock(&ctrl->namespaces_mutex);
2276         list_for_each_entry(ns, &ctrl->namespaces, list) {
2277                 if (ns->ns_id == nsid) {
2278                         if (!kref_get_unless_zero(&ns->kref))
2279                                 continue;
2280                         ret = ns;
2281                         break;
2282                 }
2283                 if (ns->ns_id > nsid)
2284                         break;
2285         }
2286         mutex_unlock(&ctrl->namespaces_mutex);
2287         return ret;
2288 }
2289
2290 static int nvme_setup_streams_ns(struct nvme_ctrl *ctrl, struct nvme_ns *ns)
2291 {
2292         struct streams_directive_params s;
2293         int ret;
2294
2295         if (!ctrl->nr_streams)
2296                 return 0;
2297
2298         ret = nvme_get_stream_params(ctrl, &s, ns->ns_id);
2299         if (ret)
2300                 return ret;
2301
2302         ns->sws = le32_to_cpu(s.sws);
2303         ns->sgs = le16_to_cpu(s.sgs);
2304
2305         if (ns->sws) {
2306                 unsigned int bs = 1 << ns->lba_shift;
2307
2308                 blk_queue_io_min(ns->queue, bs * ns->sws);
2309                 if (ns->sgs)
2310                         blk_queue_io_opt(ns->queue, bs * ns->sws * ns->sgs);
2311         }
2312
2313         return 0;
2314 }
2315
2316 static void nvme_alloc_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2317 {
2318         struct nvme_ns *ns;
2319         struct gendisk *disk;
2320         struct nvme_id_ns *id;
2321         char disk_name[DISK_NAME_LEN];
2322         int node = dev_to_node(ctrl->dev);
2323
2324         ns = kzalloc_node(sizeof(*ns), GFP_KERNEL, node);
2325         if (!ns)
2326                 return;
2327
2328         ns->instance = ida_simple_get(&ctrl->ns_ida, 1, 0, GFP_KERNEL);
2329         if (ns->instance < 0)
2330                 goto out_free_ns;
2331
2332         ns->queue = blk_mq_init_queue(ctrl->tagset);
2333         if (IS_ERR(ns->queue))
2334                 goto out_release_instance;
2335         queue_flag_set_unlocked(QUEUE_FLAG_NONROT, ns->queue);
2336         ns->queue->queuedata = ns;
2337         ns->ctrl = ctrl;
2338
2339         kref_init(&ns->kref);
2340         ns->ns_id = nsid;
2341         ns->lba_shift = 9; /* set to a default value for 512 until disk is validated */
2342
2343         blk_queue_logical_block_size(ns->queue, 1 << ns->lba_shift);
2344         nvme_set_queue_limits(ctrl, ns->queue);
2345         nvme_setup_streams_ns(ctrl, ns);
2346
2347         sprintf(disk_name, "nvme%dn%d", ctrl->instance, ns->instance);
2348
2349         id = nvme_identify_ns(ctrl, nsid);
2350         if (!id)
2351                 goto out_free_queue;
2352
2353         if (id->ncap == 0)
2354                 goto out_free_id;
2355
2356         nvme_report_ns_ids(ctrl, ns->ns_id, id, ns->eui, ns->nguid, &ns->uuid);
2357
2358         if ((ctrl->quirks & NVME_QUIRK_LIGHTNVM) && id->vs[0] == 0x1) {
2359                 if (nvme_nvm_register(ns, disk_name, node)) {
2360                         dev_warn(ctrl->device, "LightNVM init failure\n");
2361                         goto out_free_id;
2362                 }
2363         }
2364
2365         disk = alloc_disk_node(0, node);
2366         if (!disk)
2367                 goto out_free_id;
2368
2369         disk->fops = &nvme_fops;
2370         disk->private_data = ns;
2371         disk->queue = ns->queue;
2372         disk->flags = GENHD_FL_EXT_DEVT;
2373         memcpy(disk->disk_name, disk_name, DISK_NAME_LEN);
2374         ns->disk = disk;
2375
2376         __nvme_revalidate_disk(disk, id);
2377
2378         mutex_lock(&ctrl->namespaces_mutex);
2379         list_add_tail(&ns->list, &ctrl->namespaces);
2380         mutex_unlock(&ctrl->namespaces_mutex);
2381
2382         nvme_get_ctrl(ctrl);
2383
2384         kfree(id);
2385
2386         device_add_disk(ctrl->device, ns->disk);
2387         if (sysfs_create_group(&disk_to_dev(ns->disk)->kobj,
2388                                         &nvme_ns_attr_group))
2389                 pr_warn("%s: failed to create sysfs group for identification\n",
2390                         ns->disk->disk_name);
2391         if (ns->ndev && nvme_nvm_register_sysfs(ns))
2392                 pr_warn("%s: failed to register lightnvm sysfs group for identification\n",
2393                         ns->disk->disk_name);
2394         return;
2395  out_free_id:
2396         kfree(id);
2397  out_free_queue:
2398         blk_cleanup_queue(ns->queue);
2399  out_release_instance:
2400         ida_simple_remove(&ctrl->ns_ida, ns->instance);
2401  out_free_ns:
2402         kfree(ns);
2403 }
2404
2405 static void nvme_ns_remove(struct nvme_ns *ns)
2406 {
2407         if (test_and_set_bit(NVME_NS_REMOVING, &ns->flags))
2408                 return;
2409
2410         if (ns->disk && ns->disk->flags & GENHD_FL_UP) {
2411                 if (blk_get_integrity(ns->disk))
2412                         blk_integrity_unregister(ns->disk);
2413                 sysfs_remove_group(&disk_to_dev(ns->disk)->kobj,
2414                                         &nvme_ns_attr_group);
2415                 if (ns->ndev)
2416                         nvme_nvm_unregister_sysfs(ns);
2417                 del_gendisk(ns->disk);
2418                 blk_cleanup_queue(ns->queue);
2419         }
2420
2421         mutex_lock(&ns->ctrl->namespaces_mutex);
2422         list_del_init(&ns->list);
2423         mutex_unlock(&ns->ctrl->namespaces_mutex);
2424
2425         nvme_put_ns(ns);
2426 }
2427
2428 static void nvme_validate_ns(struct nvme_ctrl *ctrl, unsigned nsid)
2429 {
2430         struct nvme_ns *ns;
2431
2432         ns = nvme_find_get_ns(ctrl, nsid);
2433         if (ns) {
2434                 if (ns->disk && revalidate_disk(ns->disk))
2435                         nvme_ns_remove(ns);
2436                 nvme_put_ns(ns);
2437         } else
2438                 nvme_alloc_ns(ctrl, nsid);
2439 }
2440
2441 static void nvme_remove_invalid_namespaces(struct nvme_ctrl *ctrl,
2442                                         unsigned nsid)
2443 {
2444         struct nvme_ns *ns, *next;
2445
2446         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list) {
2447                 if (ns->ns_id > nsid)
2448                         nvme_ns_remove(ns);
2449         }
2450 }
2451
2452 static int nvme_scan_ns_list(struct nvme_ctrl *ctrl, unsigned nn)
2453 {
2454         struct nvme_ns *ns;
2455         __le32 *ns_list;
2456         unsigned i, j, nsid, prev = 0, num_lists = DIV_ROUND_UP(nn, 1024);
2457         int ret = 0;
2458
2459         ns_list = kzalloc(0x1000, GFP_KERNEL);
2460         if (!ns_list)
2461                 return -ENOMEM;
2462
2463         for (i = 0; i < num_lists; i++) {
2464                 ret = nvme_identify_ns_list(ctrl, prev, ns_list);
2465                 if (ret)
2466                         goto free;
2467
2468                 for (j = 0; j < min(nn, 1024U); j++) {
2469                         nsid = le32_to_cpu(ns_list[j]);
2470                         if (!nsid)
2471                                 goto out;
2472
2473                         nvme_validate_ns(ctrl, nsid);
2474
2475                         while (++prev < nsid) {
2476                                 ns = nvme_find_get_ns(ctrl, prev);
2477                                 if (ns) {
2478                                         nvme_ns_remove(ns);
2479                                         nvme_put_ns(ns);
2480                                 }
2481                         }
2482                 }
2483                 nn -= j;
2484         }
2485  out:
2486         nvme_remove_invalid_namespaces(ctrl, prev);
2487  free:
2488         kfree(ns_list);
2489         return ret;
2490 }
2491
2492 static void nvme_scan_ns_sequential(struct nvme_ctrl *ctrl, unsigned nn)
2493 {
2494         unsigned i;
2495
2496         for (i = 1; i <= nn; i++)
2497                 nvme_validate_ns(ctrl, i);
2498
2499         nvme_remove_invalid_namespaces(ctrl, nn);
2500 }
2501
2502 static void nvme_scan_work(struct work_struct *work)
2503 {
2504         struct nvme_ctrl *ctrl =
2505                 container_of(work, struct nvme_ctrl, scan_work);
2506         struct nvme_id_ctrl *id;
2507         unsigned nn;
2508
2509         if (ctrl->state != NVME_CTRL_LIVE)
2510                 return;
2511
2512         if (nvme_identify_ctrl(ctrl, &id))
2513                 return;
2514
2515         nn = le32_to_cpu(id->nn);
2516         if (ctrl->vs >= NVME_VS(1, 1, 0) &&
2517             !(ctrl->quirks & NVME_QUIRK_IDENTIFY_CNS)) {
2518                 if (!nvme_scan_ns_list(ctrl, nn))
2519                         goto done;
2520         }
2521         nvme_scan_ns_sequential(ctrl, nn);
2522  done:
2523         mutex_lock(&ctrl->namespaces_mutex);
2524         list_sort(NULL, &ctrl->namespaces, ns_cmp);
2525         mutex_unlock(&ctrl->namespaces_mutex);
2526         kfree(id);
2527 }
2528
2529 void nvme_queue_scan(struct nvme_ctrl *ctrl)
2530 {
2531         /*
2532          * Do not queue new scan work when a controller is reset during
2533          * removal.
2534          */
2535         if (ctrl->state == NVME_CTRL_LIVE)
2536                 queue_work(nvme_wq, &ctrl->scan_work);
2537 }
2538 EXPORT_SYMBOL_GPL(nvme_queue_scan);
2539
2540 /*
2541  * This function iterates the namespace list unlocked to allow recovery from
2542  * controller failure. It is up to the caller to ensure the namespace list is
2543  * not modified by scan work while this function is executing.
2544  */
2545 void nvme_remove_namespaces(struct nvme_ctrl *ctrl)
2546 {
2547         struct nvme_ns *ns, *next;
2548
2549         /*
2550          * The dead states indicates the controller was not gracefully
2551          * disconnected. In that case, we won't be able to flush any data while
2552          * removing the namespaces' disks; fail all the queues now to avoid
2553          * potentially having to clean up the failed sync later.
2554          */
2555         if (ctrl->state == NVME_CTRL_DEAD)
2556                 nvme_kill_queues(ctrl);
2557
2558         list_for_each_entry_safe(ns, next, &ctrl->namespaces, list)
2559                 nvme_ns_remove(ns);
2560 }
2561 EXPORT_SYMBOL_GPL(nvme_remove_namespaces);
2562
2563 static void nvme_async_event_work(struct work_struct *work)
2564 {
2565         struct nvme_ctrl *ctrl =
2566                 container_of(work, struct nvme_ctrl, async_event_work);
2567
2568         spin_lock_irq(&ctrl->lock);
2569         while (ctrl->state == NVME_CTRL_LIVE && ctrl->event_limit > 0) {
2570                 int aer_idx = --ctrl->event_limit;
2571
2572                 spin_unlock_irq(&ctrl->lock);
2573                 ctrl->ops->submit_async_event(ctrl, aer_idx);
2574                 spin_lock_irq(&ctrl->lock);
2575         }
2576         spin_unlock_irq(&ctrl->lock);
2577 }
2578
2579 static bool nvme_ctrl_pp_status(struct nvme_ctrl *ctrl)
2580 {
2581
2582         u32 csts;
2583
2584         if (ctrl->ops->reg_read32(ctrl, NVME_REG_CSTS, &csts))
2585                 return false;
2586
2587         if (csts == ~0)
2588                 return false;
2589
2590         return ((ctrl->ctrl_config & NVME_CC_ENABLE) && (csts & NVME_CSTS_PP));
2591 }
2592
2593 static void nvme_get_fw_slot_info(struct nvme_ctrl *ctrl)
2594 {
2595         struct nvme_command c = { };
2596         struct nvme_fw_slot_info_log *log;
2597
2598         log = kmalloc(sizeof(*log), GFP_KERNEL);
2599         if (!log)
2600                 return;
2601
2602         c.common.opcode = nvme_admin_get_log_page;
2603         c.common.nsid = cpu_to_le32(NVME_NSID_ALL);
2604         c.common.cdw10[0] = nvme_get_log_dw10(NVME_LOG_FW_SLOT, sizeof(*log));
2605
2606         if (!nvme_submit_sync_cmd(ctrl->admin_q, &c, log, sizeof(*log)))
2607                 dev_warn(ctrl->device,
2608                                 "Get FW SLOT INFO log error\n");
2609         kfree(log);
2610 }
2611
2612 static void nvme_fw_act_work(struct work_struct *work)
2613 {
2614         struct nvme_ctrl *ctrl = container_of(work,
2615                                 struct nvme_ctrl, fw_act_work);
2616         unsigned long fw_act_timeout;
2617
2618         if (ctrl->mtfa)
2619                 fw_act_timeout = jiffies +
2620                                 msecs_to_jiffies(ctrl->mtfa * 100);
2621         else
2622                 fw_act_timeout = jiffies +
2623                                 msecs_to_jiffies(admin_timeout * 1000);
2624
2625         nvme_stop_queues(ctrl);
2626         while (nvme_ctrl_pp_status(ctrl)) {
2627                 if (time_after(jiffies, fw_act_timeout)) {
2628                         dev_warn(ctrl->device,
2629                                 "Fw activation timeout, reset controller\n");
2630                         nvme_reset_ctrl(ctrl);
2631                         break;
2632                 }
2633                 msleep(100);
2634         }
2635
2636         if (ctrl->state != NVME_CTRL_LIVE)
2637                 return;
2638
2639         nvme_start_queues(ctrl);
2640         /* read FW slot informationi to clear the AER*/
2641         nvme_get_fw_slot_info(ctrl);
2642 }
2643
2644 void nvme_complete_async_event(struct nvme_ctrl *ctrl, __le16 status,
2645                 union nvme_result *res)
2646 {
2647         u32 result = le32_to_cpu(res->u32);
2648         bool done = true;
2649
2650         switch (le16_to_cpu(status) >> 1) {
2651         case NVME_SC_SUCCESS:
2652                 done = false;
2653                 /*FALLTHRU*/
2654         case NVME_SC_ABORT_REQ:
2655                 ++ctrl->event_limit;
2656                 if (ctrl->state == NVME_CTRL_LIVE)
2657                         queue_work(nvme_wq, &ctrl->async_event_work);
2658                 break;
2659         default:
2660                 break;
2661         }
2662
2663         if (done)
2664                 return;
2665
2666         switch (result & 0xff07) {
2667         case NVME_AER_NOTICE_NS_CHANGED:
2668                 dev_info(ctrl->device, "rescanning\n");
2669                 nvme_queue_scan(ctrl);
2670                 break;
2671         case NVME_AER_NOTICE_FW_ACT_STARTING:
2672                 queue_work(nvme_wq, &ctrl->fw_act_work);
2673                 break;
2674         default:
2675                 dev_warn(ctrl->device, "async event result %08x\n", result);
2676         }
2677 }
2678 EXPORT_SYMBOL_GPL(nvme_complete_async_event);
2679
2680 void nvme_queue_async_events(struct nvme_ctrl *ctrl)
2681 {
2682         ctrl->event_limit = NVME_NR_AERS;
2683         queue_work(nvme_wq, &ctrl->async_event_work);
2684 }
2685 EXPORT_SYMBOL_GPL(nvme_queue_async_events);
2686
2687 void nvme_stop_ctrl(struct nvme_ctrl *ctrl)
2688 {
2689         nvme_stop_keep_alive(ctrl);
2690         flush_work(&ctrl->async_event_work);
2691         flush_work(&ctrl->scan_work);
2692         cancel_work_sync(&ctrl->fw_act_work);
2693 }
2694 EXPORT_SYMBOL_GPL(nvme_stop_ctrl);
2695
2696 void nvme_start_ctrl(struct nvme_ctrl *ctrl)
2697 {
2698         if (ctrl->kato)
2699                 nvme_start_keep_alive(ctrl);
2700
2701         if (ctrl->queue_count > 1) {
2702                 nvme_queue_scan(ctrl);
2703                 nvme_queue_async_events(ctrl);
2704                 nvme_start_queues(ctrl);
2705         }
2706 }
2707 EXPORT_SYMBOL_GPL(nvme_start_ctrl);
2708
2709 void nvme_uninit_ctrl(struct nvme_ctrl *ctrl)
2710 {
2711         cdev_device_del(&ctrl->cdev, ctrl->device);
2712 }
2713 EXPORT_SYMBOL_GPL(nvme_uninit_ctrl);
2714
2715 static void nvme_free_ctrl(struct device *dev)
2716 {
2717         struct nvme_ctrl *ctrl =
2718                 container_of(dev, struct nvme_ctrl, ctrl_device);
2719
2720         ida_simple_remove(&nvme_instance_ida, ctrl->instance);
2721         ida_destroy(&ctrl->ns_ida);
2722
2723         ctrl->ops->free_ctrl(ctrl);
2724 }
2725
2726 /*
2727  * Initialize a NVMe controller structures.  This needs to be called during
2728  * earliest initialization so that we have the initialized structured around
2729  * during probing.
2730  */
2731 int nvme_init_ctrl(struct nvme_ctrl *ctrl, struct device *dev,
2732                 const struct nvme_ctrl_ops *ops, unsigned long quirks)
2733 {
2734         int ret;
2735
2736         ctrl->state = NVME_CTRL_NEW;
2737         spin_lock_init(&ctrl->lock);
2738         INIT_LIST_HEAD(&ctrl->namespaces);
2739         mutex_init(&ctrl->namespaces_mutex);
2740         ctrl->dev = dev;
2741         ctrl->ops = ops;
2742         ctrl->quirks = quirks;
2743         INIT_WORK(&ctrl->scan_work, nvme_scan_work);
2744         INIT_WORK(&ctrl->async_event_work, nvme_async_event_work);
2745         INIT_WORK(&ctrl->fw_act_work, nvme_fw_act_work);
2746         INIT_WORK(&ctrl->delete_work, nvme_delete_ctrl_work);
2747
2748         ret = ida_simple_get(&nvme_instance_ida, 0, 0, GFP_KERNEL);
2749         if (ret < 0)
2750                 goto out;
2751         ctrl->instance = ret;
2752
2753         device_initialize(&ctrl->ctrl_device);
2754         ctrl->device = &ctrl->ctrl_device;
2755         ctrl->device->devt = MKDEV(MAJOR(nvme_chr_devt), ctrl->instance);
2756         ctrl->device->class = nvme_class;
2757         ctrl->device->parent = ctrl->dev;
2758         ctrl->device->groups = nvme_dev_attr_groups;
2759         ctrl->device->release = nvme_free_ctrl;
2760         dev_set_drvdata(ctrl->device, ctrl);
2761         ret = dev_set_name(ctrl->device, "nvme%d", ctrl->instance);
2762         if (ret)
2763                 goto out_release_instance;
2764
2765         cdev_init(&ctrl->cdev, &nvme_dev_fops);
2766         ctrl->cdev.owner = ops->module;
2767         ret = cdev_device_add(&ctrl->cdev, ctrl->device);
2768         if (ret)
2769                 goto out_free_name;
2770
2771         ida_init(&ctrl->ns_ida);
2772
2773         /*
2774          * Initialize latency tolerance controls.  The sysfs files won't
2775          * be visible to userspace unless the device actually supports APST.
2776          */
2777         ctrl->device->power.set_latency_tolerance = nvme_set_latency_tolerance;
2778         dev_pm_qos_update_user_latency_tolerance(ctrl->device,
2779                 min(default_ps_max_latency_us, (unsigned long)S32_MAX));
2780
2781         return 0;
2782 out_free_name:
2783         kfree_const(dev->kobj.name);
2784 out_release_instance:
2785         ida_simple_remove(&nvme_instance_ida, ctrl->instance);
2786 out:
2787         return ret;
2788 }
2789 EXPORT_SYMBOL_GPL(nvme_init_ctrl);
2790
2791 /**
2792  * nvme_kill_queues(): Ends all namespace queues
2793  * @ctrl: the dead controller that needs to end
2794  *
2795  * Call this function when the driver determines it is unable to get the
2796  * controller in a state capable of servicing IO.
2797  */
2798 void nvme_kill_queues(struct nvme_ctrl *ctrl)
2799 {
2800         struct nvme_ns *ns;
2801
2802         mutex_lock(&ctrl->namespaces_mutex);
2803
2804         /* Forcibly unquiesce queues to avoid blocking dispatch */
2805         if (ctrl->admin_q)
2806                 blk_mq_unquiesce_queue(ctrl->admin_q);
2807
2808         list_for_each_entry(ns, &ctrl->namespaces, list) {
2809                 /*
2810                  * Revalidating a dead namespace sets capacity to 0. This will
2811                  * end buffered writers dirtying pages that can't be synced.
2812                  */
2813                 if (!ns->disk || test_and_set_bit(NVME_NS_DEAD, &ns->flags))
2814                         continue;
2815                 revalidate_disk(ns->disk);
2816                 blk_set_queue_dying(ns->queue);
2817
2818                 /* Forcibly unquiesce queues to avoid blocking dispatch */
2819                 blk_mq_unquiesce_queue(ns->queue);
2820         }
2821         mutex_unlock(&ctrl->namespaces_mutex);
2822 }
2823 EXPORT_SYMBOL_GPL(nvme_kill_queues);
2824
2825 void nvme_unfreeze(struct nvme_ctrl *ctrl)
2826 {
2827         struct nvme_ns *ns;
2828
2829         mutex_lock(&ctrl->namespaces_mutex);
2830         list_for_each_entry(ns, &ctrl->namespaces, list)
2831                 blk_mq_unfreeze_queue(ns->queue);
2832         mutex_unlock(&ctrl->namespaces_mutex);
2833 }
2834 EXPORT_SYMBOL_GPL(nvme_unfreeze);
2835
2836 void nvme_wait_freeze_timeout(struct nvme_ctrl *ctrl, long timeout)
2837 {
2838         struct nvme_ns *ns;
2839
2840         mutex_lock(&ctrl->namespaces_mutex);
2841         list_for_each_entry(ns, &ctrl->namespaces, list) {
2842                 timeout = blk_mq_freeze_queue_wait_timeout(ns->queue, timeout);
2843                 if (timeout <= 0)
2844                         break;
2845         }
2846         mutex_unlock(&ctrl->namespaces_mutex);
2847 }
2848 EXPORT_SYMBOL_GPL(nvme_wait_freeze_timeout);
2849
2850 void nvme_wait_freeze(struct nvme_ctrl *ctrl)
2851 {
2852         struct nvme_ns *ns;
2853
2854         mutex_lock(&ctrl->namespaces_mutex);
2855         list_for_each_entry(ns, &ctrl->namespaces, list)
2856                 blk_mq_freeze_queue_wait(ns->queue);
2857         mutex_unlock(&ctrl->namespaces_mutex);
2858 }
2859 EXPORT_SYMBOL_GPL(nvme_wait_freeze);
2860
2861 void nvme_start_freeze(struct nvme_ctrl *ctrl)
2862 {
2863         struct nvme_ns *ns;
2864
2865         mutex_lock(&ctrl->namespaces_mutex);
2866         list_for_each_entry(ns, &ctrl->namespaces, list)
2867                 blk_freeze_queue_start(ns->queue);
2868         mutex_unlock(&ctrl->namespaces_mutex);
2869 }
2870 EXPORT_SYMBOL_GPL(nvme_start_freeze);
2871
2872 void nvme_stop_queues(struct nvme_ctrl *ctrl)
2873 {
2874         struct nvme_ns *ns;
2875
2876         mutex_lock(&ctrl->namespaces_mutex);
2877         list_for_each_entry(ns, &ctrl->namespaces, list)
2878                 blk_mq_quiesce_queue(ns->queue);
2879         mutex_unlock(&ctrl->namespaces_mutex);
2880 }
2881 EXPORT_SYMBOL_GPL(nvme_stop_queues);
2882
2883 void nvme_start_queues(struct nvme_ctrl *ctrl)
2884 {
2885         struct nvme_ns *ns;
2886
2887         mutex_lock(&ctrl->namespaces_mutex);
2888         list_for_each_entry(ns, &ctrl->namespaces, list)
2889                 blk_mq_unquiesce_queue(ns->queue);
2890         mutex_unlock(&ctrl->namespaces_mutex);
2891 }
2892 EXPORT_SYMBOL_GPL(nvme_start_queues);
2893
2894 int nvme_reinit_tagset(struct nvme_ctrl *ctrl, struct blk_mq_tag_set *set)
2895 {
2896         if (!ctrl->ops->reinit_request)
2897                 return 0;
2898
2899         return blk_mq_tagset_iter(set, set->driver_data,
2900                         ctrl->ops->reinit_request);
2901 }
2902 EXPORT_SYMBOL_GPL(nvme_reinit_tagset);
2903
2904 int __init nvme_core_init(void)
2905 {
2906         int result;
2907
2908         nvme_wq = alloc_workqueue("nvme-wq",
2909                         WQ_UNBOUND | WQ_MEM_RECLAIM | WQ_SYSFS, 0);
2910         if (!nvme_wq)
2911                 return -ENOMEM;
2912
2913         result = alloc_chrdev_region(&nvme_chr_devt, 0, NVME_MINORS, "nvme");
2914         if (result < 0)
2915                 goto destroy_wq;
2916
2917         nvme_class = class_create(THIS_MODULE, "nvme");
2918         if (IS_ERR(nvme_class)) {
2919                 result = PTR_ERR(nvme_class);
2920                 goto unregister_chrdev;
2921         }
2922
2923         return 0;
2924
2925 unregister_chrdev:
2926         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
2927 destroy_wq:
2928         destroy_workqueue(nvme_wq);
2929         return result;
2930 }
2931
2932 void nvme_core_exit(void)
2933 {
2934         class_destroy(nvme_class);
2935         unregister_chrdev_region(nvme_chr_devt, NVME_MINORS);
2936         destroy_workqueue(nvme_wq);
2937 }
2938
2939 MODULE_LICENSE("GPL");
2940 MODULE_VERSION("1.0");
2941 module_init(nvme_core_init);
2942 module_exit(nvme_core_exit);