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