qemu/hw/block/nvme.c
<<
>>
Prefs
   1/*
   2 * QEMU NVM Express Controller
   3 *
   4 * Copyright (c) 2012, Intel Corporation
   5 *
   6 * Written by Keith Busch <keith.busch@intel.com>
   7 *
   8 * This code is licensed under the GNU GPL v2 or later.
   9 */
  10
  11/**
  12 * Reference Specs: http://www.nvmexpress.org, 1.1, 1.0e
  13 *
  14 *  http://www.nvmexpress.org/resources/
  15 */
  16
  17/**
  18 * Usage: add options:
  19 *      -drive file=<file>,if=none,id=<drive_id>
  20 *      -device nvme,drive=<drive_id>,serial=<serial>,id=<id[optional]>
  21 */
  22
  23#include "qemu/osdep.h"
  24#include "hw/block/block.h"
  25#include "hw/hw.h"
  26#include "hw/pci/msix.h"
  27#include "hw/pci/pci.h"
  28#include "sysemu/sysemu.h"
  29#include "qapi/error.h"
  30#include "qapi/visitor.h"
  31#include "sysemu/block-backend.h"
  32
  33#include "nvme.h"
  34
  35static void nvme_process_sq(void *opaque);
  36
  37static int nvme_check_sqid(NvmeCtrl *n, uint16_t sqid)
  38{
  39    return sqid < n->num_queues && n->sq[sqid] != NULL ? 0 : -1;
  40}
  41
  42static int nvme_check_cqid(NvmeCtrl *n, uint16_t cqid)
  43{
  44    return cqid < n->num_queues && n->cq[cqid] != NULL ? 0 : -1;
  45}
  46
  47static void nvme_inc_cq_tail(NvmeCQueue *cq)
  48{
  49    cq->tail++;
  50    if (cq->tail >= cq->size) {
  51        cq->tail = 0;
  52        cq->phase = !cq->phase;
  53    }
  54}
  55
  56static void nvme_inc_sq_head(NvmeSQueue *sq)
  57{
  58    sq->head = (sq->head + 1) % sq->size;
  59}
  60
  61static uint8_t nvme_cq_full(NvmeCQueue *cq)
  62{
  63    return (cq->tail + 1) % cq->size == cq->head;
  64}
  65
  66static uint8_t nvme_sq_empty(NvmeSQueue *sq)
  67{
  68    return sq->head == sq->tail;
  69}
  70
  71static void nvme_isr_notify(NvmeCtrl *n, NvmeCQueue *cq)
  72{
  73    if (cq->irq_enabled) {
  74        if (msix_enabled(&(n->parent_obj))) {
  75            msix_notify(&(n->parent_obj), cq->vector);
  76        } else {
  77            pci_irq_pulse(&n->parent_obj);
  78        }
  79    }
  80}
  81
  82static uint16_t nvme_map_prp(QEMUSGList *qsg, uint64_t prp1, uint64_t prp2,
  83    uint32_t len, NvmeCtrl *n)
  84{
  85    hwaddr trans_len = n->page_size - (prp1 % n->page_size);
  86    trans_len = MIN(len, trans_len);
  87    int num_prps = (len >> n->page_bits) + 1;
  88
  89    if (!prp1) {
  90        return NVME_INVALID_FIELD | NVME_DNR;
  91    }
  92
  93    pci_dma_sglist_init(qsg, &n->parent_obj, num_prps);
  94    qemu_sglist_add(qsg, prp1, trans_len);
  95    len -= trans_len;
  96    if (len) {
  97        if (!prp2) {
  98            goto unmap;
  99        }
 100        if (len > n->page_size) {
 101            uint64_t prp_list[n->max_prp_ents];
 102            uint32_t nents, prp_trans;
 103            int i = 0;
 104
 105            nents = (len + n->page_size - 1) >> n->page_bits;
 106            prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
 107            pci_dma_read(&n->parent_obj, prp2, (void *)prp_list, prp_trans);
 108            while (len != 0) {
 109                uint64_t prp_ent = le64_to_cpu(prp_list[i]);
 110
 111                if (i == n->max_prp_ents - 1 && len > n->page_size) {
 112                    if (!prp_ent || prp_ent & (n->page_size - 1)) {
 113                        goto unmap;
 114                    }
 115
 116                    i = 0;
 117                    nents = (len + n->page_size - 1) >> n->page_bits;
 118                    prp_trans = MIN(n->max_prp_ents, nents) * sizeof(uint64_t);
 119                    pci_dma_read(&n->parent_obj, prp_ent, (void *)prp_list,
 120                        prp_trans);
 121                    prp_ent = le64_to_cpu(prp_list[i]);
 122                }
 123
 124                if (!prp_ent || prp_ent & (n->page_size - 1)) {
 125                    goto unmap;
 126                }
 127
 128                trans_len = MIN(len, n->page_size);
 129                qemu_sglist_add(qsg, prp_ent, trans_len);
 130                len -= trans_len;
 131                i++;
 132            }
 133        } else {
 134            if (prp2 & (n->page_size - 1)) {
 135                goto unmap;
 136            }
 137            qemu_sglist_add(qsg, prp2, len);
 138        }
 139    }
 140    return NVME_SUCCESS;
 141
 142 unmap:
 143    qemu_sglist_destroy(qsg);
 144    return NVME_INVALID_FIELD | NVME_DNR;
 145}
 146
 147static uint16_t nvme_dma_read_prp(NvmeCtrl *n, uint8_t *ptr, uint32_t len,
 148    uint64_t prp1, uint64_t prp2)
 149{
 150    QEMUSGList qsg;
 151
 152    if (nvme_map_prp(&qsg, prp1, prp2, len, n)) {
 153        return NVME_INVALID_FIELD | NVME_DNR;
 154    }
 155    if (dma_buf_read(ptr, len, &qsg)) {
 156        qemu_sglist_destroy(&qsg);
 157        return NVME_INVALID_FIELD | NVME_DNR;
 158    }
 159    qemu_sglist_destroy(&qsg);
 160    return NVME_SUCCESS;
 161}
 162
 163static void nvme_post_cqes(void *opaque)
 164{
 165    NvmeCQueue *cq = opaque;
 166    NvmeCtrl *n = cq->ctrl;
 167    NvmeRequest *req, *next;
 168
 169    QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
 170        NvmeSQueue *sq;
 171        hwaddr addr;
 172
 173        if (nvme_cq_full(cq)) {
 174            break;
 175        }
 176
 177        QTAILQ_REMOVE(&cq->req_list, req, entry);
 178        sq = req->sq;
 179        req->cqe.status = cpu_to_le16((req->status << 1) | cq->phase);
 180        req->cqe.sq_id = cpu_to_le16(sq->sqid);
 181        req->cqe.sq_head = cpu_to_le16(sq->head);
 182        addr = cq->dma_addr + cq->tail * n->cqe_size;
 183        nvme_inc_cq_tail(cq);
 184        pci_dma_write(&n->parent_obj, addr, (void *)&req->cqe,
 185            sizeof(req->cqe));
 186        QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
 187    }
 188    nvme_isr_notify(n, cq);
 189}
 190
 191static void nvme_enqueue_req_completion(NvmeCQueue *cq, NvmeRequest *req)
 192{
 193    assert(cq->cqid == req->sq->cqid);
 194    QTAILQ_REMOVE(&req->sq->out_req_list, req, entry);
 195    QTAILQ_INSERT_TAIL(&cq->req_list, req, entry);
 196    timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
 197}
 198
 199static void nvme_rw_cb(void *opaque, int ret)
 200{
 201    NvmeRequest *req = opaque;
 202    NvmeSQueue *sq = req->sq;
 203    NvmeCtrl *n = sq->ctrl;
 204    NvmeCQueue *cq = n->cq[sq->cqid];
 205
 206    if (!ret) {
 207        block_acct_done(blk_get_stats(n->conf.blk), &req->acct);
 208        req->status = NVME_SUCCESS;
 209    } else {
 210        block_acct_failed(blk_get_stats(n->conf.blk), &req->acct);
 211        req->status = NVME_INTERNAL_DEV_ERROR;
 212    }
 213    if (req->has_sg) {
 214        qemu_sglist_destroy(&req->qsg);
 215    }
 216    nvme_enqueue_req_completion(cq, req);
 217}
 218
 219static uint16_t nvme_flush(NvmeCtrl *n, NvmeNamespace *ns, NvmeCmd *cmd,
 220    NvmeRequest *req)
 221{
 222    req->has_sg = false;
 223    block_acct_start(blk_get_stats(n->conf.blk), &req->acct, 0,
 224         BLOCK_ACCT_FLUSH);
 225    req->aiocb = blk_aio_flush(n->conf.blk, nvme_rw_cb, req);
 226
 227    return NVME_NO_COMPLETE;
 228}
 229
 230static uint16_t nvme_rw(NvmeCtrl *n, NvmeNamespace *ns, NvmeCmd *cmd,
 231    NvmeRequest *req)
 232{
 233    NvmeRwCmd *rw = (NvmeRwCmd *)cmd;
 234    uint32_t nlb  = le32_to_cpu(rw->nlb) + 1;
 235    uint64_t slba = le64_to_cpu(rw->slba);
 236    uint64_t prp1 = le64_to_cpu(rw->prp1);
 237    uint64_t prp2 = le64_to_cpu(rw->prp2);
 238
 239    uint8_t lba_index  = NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas);
 240    uint8_t data_shift = ns->id_ns.lbaf[lba_index].ds;
 241    uint64_t data_size = (uint64_t)nlb << data_shift;
 242    uint64_t data_offset = slba << data_shift;
 243    int is_write = rw->opcode == NVME_CMD_WRITE ? 1 : 0;
 244    enum BlockAcctType acct = is_write ? BLOCK_ACCT_WRITE : BLOCK_ACCT_READ;
 245
 246    if ((slba + nlb) > ns->id_ns.nsze) {
 247        block_acct_invalid(blk_get_stats(n->conf.blk), acct);
 248        return NVME_LBA_RANGE | NVME_DNR;
 249    }
 250
 251    if (nvme_map_prp(&req->qsg, prp1, prp2, data_size, n)) {
 252        block_acct_invalid(blk_get_stats(n->conf.blk), acct);
 253        return NVME_INVALID_FIELD | NVME_DNR;
 254    }
 255
 256    assert((nlb << data_shift) == req->qsg.size);
 257
 258    req->has_sg = true;
 259    dma_acct_start(n->conf.blk, &req->acct, &req->qsg, acct);
 260    req->aiocb = is_write ?
 261        dma_blk_write(n->conf.blk, &req->qsg, data_offset, BDRV_SECTOR_SIZE,
 262                      nvme_rw_cb, req) :
 263        dma_blk_read(n->conf.blk, &req->qsg, data_offset, BDRV_SECTOR_SIZE,
 264                     nvme_rw_cb, req);
 265
 266    return NVME_NO_COMPLETE;
 267}
 268
 269static uint16_t nvme_io_cmd(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)
 270{
 271    NvmeNamespace *ns;
 272    uint32_t nsid = le32_to_cpu(cmd->nsid);
 273
 274    if (nsid == 0 || nsid > n->num_namespaces) {
 275        return NVME_INVALID_NSID | NVME_DNR;
 276    }
 277
 278    ns = &n->namespaces[nsid - 1];
 279    switch (cmd->opcode) {
 280    case NVME_CMD_FLUSH:
 281        return nvme_flush(n, ns, cmd, req);
 282    case NVME_CMD_WRITE:
 283    case NVME_CMD_READ:
 284        return nvme_rw(n, ns, cmd, req);
 285    default:
 286        return NVME_INVALID_OPCODE | NVME_DNR;
 287    }
 288}
 289
 290static void nvme_free_sq(NvmeSQueue *sq, NvmeCtrl *n)
 291{
 292    n->sq[sq->sqid] = NULL;
 293    timer_del(sq->timer);
 294    timer_free(sq->timer);
 295    g_free(sq->io_req);
 296    if (sq->sqid) {
 297        g_free(sq);
 298    }
 299}
 300
 301static uint16_t nvme_del_sq(NvmeCtrl *n, NvmeCmd *cmd)
 302{
 303    NvmeDeleteQ *c = (NvmeDeleteQ *)cmd;
 304    NvmeRequest *req, *next;
 305    NvmeSQueue *sq;
 306    NvmeCQueue *cq;
 307    uint16_t qid = le16_to_cpu(c->qid);
 308
 309    if (!qid || nvme_check_sqid(n, qid)) {
 310        return NVME_INVALID_QID | NVME_DNR;
 311    }
 312
 313    sq = n->sq[qid];
 314    while (!QTAILQ_EMPTY(&sq->out_req_list)) {
 315        req = QTAILQ_FIRST(&sq->out_req_list);
 316        assert(req->aiocb);
 317        blk_aio_cancel(req->aiocb);
 318    }
 319    if (!nvme_check_cqid(n, sq->cqid)) {
 320        cq = n->cq[sq->cqid];
 321        QTAILQ_REMOVE(&cq->sq_list, sq, entry);
 322
 323        nvme_post_cqes(cq);
 324        QTAILQ_FOREACH_SAFE(req, &cq->req_list, entry, next) {
 325            if (req->sq == sq) {
 326                QTAILQ_REMOVE(&cq->req_list, req, entry);
 327                QTAILQ_INSERT_TAIL(&sq->req_list, req, entry);
 328            }
 329        }
 330    }
 331
 332    nvme_free_sq(sq, n);
 333    return NVME_SUCCESS;
 334}
 335
 336static void nvme_init_sq(NvmeSQueue *sq, NvmeCtrl *n, uint64_t dma_addr,
 337    uint16_t sqid, uint16_t cqid, uint16_t size)
 338{
 339    int i;
 340    NvmeCQueue *cq;
 341
 342    sq->ctrl = n;
 343    sq->dma_addr = dma_addr;
 344    sq->sqid = sqid;
 345    sq->size = size;
 346    sq->cqid = cqid;
 347    sq->head = sq->tail = 0;
 348    sq->io_req = g_new(NvmeRequest, sq->size);
 349
 350    QTAILQ_INIT(&sq->req_list);
 351    QTAILQ_INIT(&sq->out_req_list);
 352    for (i = 0; i < sq->size; i++) {
 353        sq->io_req[i].sq = sq;
 354        QTAILQ_INSERT_TAIL(&(sq->req_list), &sq->io_req[i], entry);
 355    }
 356    sq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_process_sq, sq);
 357
 358    assert(n->cq[cqid]);
 359    cq = n->cq[cqid];
 360    QTAILQ_INSERT_TAIL(&(cq->sq_list), sq, entry);
 361    n->sq[sqid] = sq;
 362}
 363
 364static uint16_t nvme_create_sq(NvmeCtrl *n, NvmeCmd *cmd)
 365{
 366    NvmeSQueue *sq;
 367    NvmeCreateSq *c = (NvmeCreateSq *)cmd;
 368
 369    uint16_t cqid = le16_to_cpu(c->cqid);
 370    uint16_t sqid = le16_to_cpu(c->sqid);
 371    uint16_t qsize = le16_to_cpu(c->qsize);
 372    uint16_t qflags = le16_to_cpu(c->sq_flags);
 373    uint64_t prp1 = le64_to_cpu(c->prp1);
 374
 375    if (!cqid || nvme_check_cqid(n, cqid)) {
 376        return NVME_INVALID_CQID | NVME_DNR;
 377    }
 378    if (!sqid || !nvme_check_sqid(n, sqid)) {
 379        return NVME_INVALID_QID | NVME_DNR;
 380    }
 381    if (!qsize || qsize > NVME_CAP_MQES(n->bar.cap)) {
 382        return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
 383    }
 384    if (!prp1 || prp1 & (n->page_size - 1)) {
 385        return NVME_INVALID_FIELD | NVME_DNR;
 386    }
 387    if (!(NVME_SQ_FLAGS_PC(qflags))) {
 388        return NVME_INVALID_FIELD | NVME_DNR;
 389    }
 390    sq = g_malloc0(sizeof(*sq));
 391    nvme_init_sq(sq, n, prp1, sqid, cqid, qsize + 1);
 392    return NVME_SUCCESS;
 393}
 394
 395static void nvme_free_cq(NvmeCQueue *cq, NvmeCtrl *n)
 396{
 397    n->cq[cq->cqid] = NULL;
 398    timer_del(cq->timer);
 399    timer_free(cq->timer);
 400    msix_vector_unuse(&n->parent_obj, cq->vector);
 401    if (cq->cqid) {
 402        g_free(cq);
 403    }
 404}
 405
 406static uint16_t nvme_del_cq(NvmeCtrl *n, NvmeCmd *cmd)
 407{
 408    NvmeDeleteQ *c = (NvmeDeleteQ *)cmd;
 409    NvmeCQueue *cq;
 410    uint16_t qid = le16_to_cpu(c->qid);
 411
 412    if (!qid || nvme_check_cqid(n, qid)) {
 413        return NVME_INVALID_CQID | NVME_DNR;
 414    }
 415
 416    cq = n->cq[qid];
 417    if (!QTAILQ_EMPTY(&cq->sq_list)) {
 418        return NVME_INVALID_QUEUE_DEL;
 419    }
 420    nvme_free_cq(cq, n);
 421    return NVME_SUCCESS;
 422}
 423
 424static void nvme_init_cq(NvmeCQueue *cq, NvmeCtrl *n, uint64_t dma_addr,
 425    uint16_t cqid, uint16_t vector, uint16_t size, uint16_t irq_enabled)
 426{
 427    cq->ctrl = n;
 428    cq->cqid = cqid;
 429    cq->size = size;
 430    cq->dma_addr = dma_addr;
 431    cq->phase = 1;
 432    cq->irq_enabled = irq_enabled;
 433    cq->vector = vector;
 434    cq->head = cq->tail = 0;
 435    QTAILQ_INIT(&cq->req_list);
 436    QTAILQ_INIT(&cq->sq_list);
 437    msix_vector_use(&n->parent_obj, cq->vector);
 438    n->cq[cqid] = cq;
 439    cq->timer = timer_new_ns(QEMU_CLOCK_VIRTUAL, nvme_post_cqes, cq);
 440}
 441
 442static uint16_t nvme_create_cq(NvmeCtrl *n, NvmeCmd *cmd)
 443{
 444    NvmeCQueue *cq;
 445    NvmeCreateCq *c = (NvmeCreateCq *)cmd;
 446    uint16_t cqid = le16_to_cpu(c->cqid);
 447    uint16_t vector = le16_to_cpu(c->irq_vector);
 448    uint16_t qsize = le16_to_cpu(c->qsize);
 449    uint16_t qflags = le16_to_cpu(c->cq_flags);
 450    uint64_t prp1 = le64_to_cpu(c->prp1);
 451
 452    if (!cqid || !nvme_check_cqid(n, cqid)) {
 453        return NVME_INVALID_CQID | NVME_DNR;
 454    }
 455    if (!qsize || qsize > NVME_CAP_MQES(n->bar.cap)) {
 456        return NVME_MAX_QSIZE_EXCEEDED | NVME_DNR;
 457    }
 458    if (!prp1) {
 459        return NVME_INVALID_FIELD | NVME_DNR;
 460    }
 461    if (vector > n->num_queues) {
 462        return NVME_INVALID_IRQ_VECTOR | NVME_DNR;
 463    }
 464    if (!(NVME_CQ_FLAGS_PC(qflags))) {
 465        return NVME_INVALID_FIELD | NVME_DNR;
 466    }
 467
 468    cq = g_malloc0(sizeof(*cq));
 469    nvme_init_cq(cq, n, prp1, cqid, vector, qsize + 1,
 470        NVME_CQ_FLAGS_IEN(qflags));
 471    return NVME_SUCCESS;
 472}
 473
 474static uint16_t nvme_identify_ctrl(NvmeCtrl *n, NvmeIdentify *c)
 475{
 476    uint64_t prp1 = le64_to_cpu(c->prp1);
 477    uint64_t prp2 = le64_to_cpu(c->prp2);
 478
 479    return nvme_dma_read_prp(n, (uint8_t *)&n->id_ctrl, sizeof(n->id_ctrl),
 480        prp1, prp2);
 481}
 482
 483static uint16_t nvme_identify_ns(NvmeCtrl *n, NvmeIdentify *c)
 484{
 485    NvmeNamespace *ns;
 486    uint32_t nsid = le32_to_cpu(c->nsid);
 487    uint64_t prp1 = le64_to_cpu(c->prp1);
 488    uint64_t prp2 = le64_to_cpu(c->prp2);
 489
 490    if (nsid == 0 || nsid > n->num_namespaces) {
 491        return NVME_INVALID_NSID | NVME_DNR;
 492    }
 493
 494    ns = &n->namespaces[nsid - 1];
 495    return nvme_dma_read_prp(n, (uint8_t *)&ns->id_ns, sizeof(ns->id_ns),
 496        prp1, prp2);
 497}
 498
 499static uint16_t nvme_identify_nslist(NvmeCtrl *n, NvmeIdentify *c)
 500{
 501    static const int data_len = 4096;
 502    uint32_t min_nsid = le32_to_cpu(c->nsid);
 503    uint64_t prp1 = le64_to_cpu(c->prp1);
 504    uint64_t prp2 = le64_to_cpu(c->prp2);
 505    uint32_t *list;
 506    uint16_t ret;
 507    int i, j = 0;
 508
 509    list = g_malloc0(data_len);
 510    for (i = 0; i < n->num_namespaces; i++) {
 511        if (i < min_nsid) {
 512            continue;
 513        }
 514        list[j++] = cpu_to_le32(i + 1);
 515        if (j == data_len / sizeof(uint32_t)) {
 516            break;
 517        }
 518    }
 519    ret = nvme_dma_read_prp(n, (uint8_t *)list, data_len, prp1, prp2);
 520    g_free(list);
 521    return ret;
 522}
 523
 524
 525static uint16_t nvme_identify(NvmeCtrl *n, NvmeCmd *cmd)
 526{
 527    NvmeIdentify *c = (NvmeIdentify *)cmd;
 528
 529    switch (le32_to_cpu(c->cns)) {
 530    case 0x00:
 531        return nvme_identify_ns(n, c);
 532    case 0x01:
 533        return nvme_identify_ctrl(n, c);
 534    case 0x02:
 535        return nvme_identify_nslist(n, c);
 536    default:
 537        return NVME_INVALID_FIELD | NVME_DNR;
 538    }
 539}
 540
 541static uint16_t nvme_get_feature(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)
 542{
 543    uint32_t dw10 = le32_to_cpu(cmd->cdw10);
 544    uint32_t result;
 545
 546    switch (dw10) {
 547    case NVME_VOLATILE_WRITE_CACHE:
 548        result = blk_enable_write_cache(n->conf.blk);
 549        break;
 550    case NVME_NUMBER_OF_QUEUES:
 551        result = cpu_to_le32((n->num_queues - 1) | ((n->num_queues - 1) << 16));
 552        break;
 553    default:
 554        return NVME_INVALID_FIELD | NVME_DNR;
 555    }
 556
 557    req->cqe.result = result;
 558    return NVME_SUCCESS;
 559}
 560
 561static uint16_t nvme_set_feature(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)
 562{
 563    uint32_t dw10 = le32_to_cpu(cmd->cdw10);
 564    uint32_t dw11 = le32_to_cpu(cmd->cdw11);
 565
 566    switch (dw10) {
 567    case NVME_VOLATILE_WRITE_CACHE:
 568        blk_set_enable_write_cache(n->conf.blk, dw11 & 1);
 569        break;
 570    case NVME_NUMBER_OF_QUEUES:
 571        req->cqe.result =
 572            cpu_to_le32((n->num_queues - 1) | ((n->num_queues - 1) << 16));
 573        break;
 574    default:
 575        return NVME_INVALID_FIELD | NVME_DNR;
 576    }
 577    return NVME_SUCCESS;
 578}
 579
 580static uint16_t nvme_admin_cmd(NvmeCtrl *n, NvmeCmd *cmd, NvmeRequest *req)
 581{
 582    switch (cmd->opcode) {
 583    case NVME_ADM_CMD_DELETE_SQ:
 584        return nvme_del_sq(n, cmd);
 585    case NVME_ADM_CMD_CREATE_SQ:
 586        return nvme_create_sq(n, cmd);
 587    case NVME_ADM_CMD_DELETE_CQ:
 588        return nvme_del_cq(n, cmd);
 589    case NVME_ADM_CMD_CREATE_CQ:
 590        return nvme_create_cq(n, cmd);
 591    case NVME_ADM_CMD_IDENTIFY:
 592        return nvme_identify(n, cmd);
 593    case NVME_ADM_CMD_SET_FEATURES:
 594        return nvme_set_feature(n, cmd, req);
 595    case NVME_ADM_CMD_GET_FEATURES:
 596        return nvme_get_feature(n, cmd, req);
 597    default:
 598        return NVME_INVALID_OPCODE | NVME_DNR;
 599    }
 600}
 601
 602static void nvme_process_sq(void *opaque)
 603{
 604    NvmeSQueue *sq = opaque;
 605    NvmeCtrl *n = sq->ctrl;
 606    NvmeCQueue *cq = n->cq[sq->cqid];
 607
 608    uint16_t status;
 609    hwaddr addr;
 610    NvmeCmd cmd;
 611    NvmeRequest *req;
 612
 613    while (!(nvme_sq_empty(sq) || QTAILQ_EMPTY(&sq->req_list))) {
 614        addr = sq->dma_addr + sq->head * n->sqe_size;
 615        pci_dma_read(&n->parent_obj, addr, (void *)&cmd, sizeof(cmd));
 616        nvme_inc_sq_head(sq);
 617
 618        req = QTAILQ_FIRST(&sq->req_list);
 619        QTAILQ_REMOVE(&sq->req_list, req, entry);
 620        QTAILQ_INSERT_TAIL(&sq->out_req_list, req, entry);
 621        memset(&req->cqe, 0, sizeof(req->cqe));
 622        req->cqe.cid = cmd.cid;
 623
 624        status = sq->sqid ? nvme_io_cmd(n, &cmd, req) :
 625            nvme_admin_cmd(n, &cmd, req);
 626        if (status != NVME_NO_COMPLETE) {
 627            req->status = status;
 628            nvme_enqueue_req_completion(cq, req);
 629        }
 630    }
 631}
 632
 633static void nvme_clear_ctrl(NvmeCtrl *n)
 634{
 635    int i;
 636
 637    for (i = 0; i < n->num_queues; i++) {
 638        if (n->sq[i] != NULL) {
 639            nvme_free_sq(n->sq[i], n);
 640        }
 641    }
 642    for (i = 0; i < n->num_queues; i++) {
 643        if (n->cq[i] != NULL) {
 644            nvme_free_cq(n->cq[i], n);
 645        }
 646    }
 647
 648    blk_flush(n->conf.blk);
 649    n->bar.cc = 0;
 650}
 651
 652static int nvme_start_ctrl(NvmeCtrl *n)
 653{
 654    uint32_t page_bits = NVME_CC_MPS(n->bar.cc) + 12;
 655    uint32_t page_size = 1 << page_bits;
 656
 657    if (n->cq[0] || n->sq[0] || !n->bar.asq || !n->bar.acq ||
 658            n->bar.asq & (page_size - 1) || n->bar.acq & (page_size - 1) ||
 659            NVME_CC_MPS(n->bar.cc) < NVME_CAP_MPSMIN(n->bar.cap) ||
 660            NVME_CC_MPS(n->bar.cc) > NVME_CAP_MPSMAX(n->bar.cap) ||
 661            NVME_CC_IOCQES(n->bar.cc) < NVME_CTRL_CQES_MIN(n->id_ctrl.cqes) ||
 662            NVME_CC_IOCQES(n->bar.cc) > NVME_CTRL_CQES_MAX(n->id_ctrl.cqes) ||
 663            NVME_CC_IOSQES(n->bar.cc) < NVME_CTRL_SQES_MIN(n->id_ctrl.sqes) ||
 664            NVME_CC_IOSQES(n->bar.cc) > NVME_CTRL_SQES_MAX(n->id_ctrl.sqes) ||
 665            !NVME_AQA_ASQS(n->bar.aqa) || !NVME_AQA_ACQS(n->bar.aqa)) {
 666        return -1;
 667    }
 668
 669    n->page_bits = page_bits;
 670    n->page_size = page_size;
 671    n->max_prp_ents = n->page_size / sizeof(uint64_t);
 672    n->cqe_size = 1 << NVME_CC_IOCQES(n->bar.cc);
 673    n->sqe_size = 1 << NVME_CC_IOSQES(n->bar.cc);
 674    nvme_init_cq(&n->admin_cq, n, n->bar.acq, 0, 0,
 675        NVME_AQA_ACQS(n->bar.aqa) + 1, 1);
 676    nvme_init_sq(&n->admin_sq, n, n->bar.asq, 0, 0,
 677        NVME_AQA_ASQS(n->bar.aqa) + 1);
 678
 679    return 0;
 680}
 681
 682static void nvme_write_bar(NvmeCtrl *n, hwaddr offset, uint64_t data,
 683    unsigned size)
 684{
 685    switch (offset) {
 686    case 0xc:
 687        n->bar.intms |= data & 0xffffffff;
 688        n->bar.intmc = n->bar.intms;
 689        break;
 690    case 0x10:
 691        n->bar.intms &= ~(data & 0xffffffff);
 692        n->bar.intmc = n->bar.intms;
 693        break;
 694    case 0x14:
 695        /* Windows first sends data, then sends enable bit */
 696        if (!NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc) &&
 697            !NVME_CC_SHN(data) && !NVME_CC_SHN(n->bar.cc))
 698        {
 699            n->bar.cc = data;
 700        }
 701
 702        if (NVME_CC_EN(data) && !NVME_CC_EN(n->bar.cc)) {
 703            n->bar.cc = data;
 704            if (nvme_start_ctrl(n)) {
 705                n->bar.csts = NVME_CSTS_FAILED;
 706            } else {
 707                n->bar.csts = NVME_CSTS_READY;
 708            }
 709        } else if (!NVME_CC_EN(data) && NVME_CC_EN(n->bar.cc)) {
 710            nvme_clear_ctrl(n);
 711            n->bar.csts &= ~NVME_CSTS_READY;
 712        }
 713        if (NVME_CC_SHN(data) && !(NVME_CC_SHN(n->bar.cc))) {
 714                nvme_clear_ctrl(n);
 715                n->bar.cc = data;
 716                n->bar.csts |= NVME_CSTS_SHST_COMPLETE;
 717        } else if (!NVME_CC_SHN(data) && NVME_CC_SHN(n->bar.cc)) {
 718                n->bar.csts &= ~NVME_CSTS_SHST_COMPLETE;
 719                n->bar.cc = data;
 720        }
 721        break;
 722    case 0x24:
 723        n->bar.aqa = data & 0xffffffff;
 724        break;
 725    case 0x28:
 726        n->bar.asq = data;
 727        break;
 728    case 0x2c:
 729        n->bar.asq |= data << 32;
 730        break;
 731    case 0x30:
 732        n->bar.acq = data;
 733        break;
 734    case 0x34:
 735        n->bar.acq |= data << 32;
 736        break;
 737    default:
 738        break;
 739    }
 740}
 741
 742static uint64_t nvme_mmio_read(void *opaque, hwaddr addr, unsigned size)
 743{
 744    NvmeCtrl *n = (NvmeCtrl *)opaque;
 745    uint8_t *ptr = (uint8_t *)&n->bar;
 746    uint64_t val = 0;
 747
 748    if (addr < sizeof(n->bar)) {
 749        memcpy(&val, ptr + addr, size);
 750    }
 751    return val;
 752}
 753
 754static void nvme_process_db(NvmeCtrl *n, hwaddr addr, int val)
 755{
 756    uint32_t qid;
 757
 758    if (addr & ((1 << 2) - 1)) {
 759        return;
 760    }
 761
 762    if (((addr - 0x1000) >> 2) & 1) {
 763        uint16_t new_head = val & 0xffff;
 764        int start_sqs;
 765        NvmeCQueue *cq;
 766
 767        qid = (addr - (0x1000 + (1 << 2))) >> 3;
 768        if (nvme_check_cqid(n, qid)) {
 769            return;
 770        }
 771
 772        cq = n->cq[qid];
 773        if (new_head >= cq->size) {
 774            return;
 775        }
 776
 777        start_sqs = nvme_cq_full(cq) ? 1 : 0;
 778        cq->head = new_head;
 779        if (start_sqs) {
 780            NvmeSQueue *sq;
 781            QTAILQ_FOREACH(sq, &cq->sq_list, entry) {
 782                timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
 783            }
 784            timer_mod(cq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
 785        }
 786
 787        if (cq->tail != cq->head) {
 788            nvme_isr_notify(n, cq);
 789        }
 790    } else {
 791        uint16_t new_tail = val & 0xffff;
 792        NvmeSQueue *sq;
 793
 794        qid = (addr - 0x1000) >> 3;
 795        if (nvme_check_sqid(n, qid)) {
 796            return;
 797        }
 798
 799        sq = n->sq[qid];
 800        if (new_tail >= sq->size) {
 801            return;
 802        }
 803
 804        sq->tail = new_tail;
 805        timer_mod(sq->timer, qemu_clock_get_ns(QEMU_CLOCK_VIRTUAL) + 500);
 806    }
 807}
 808
 809static void nvme_mmio_write(void *opaque, hwaddr addr, uint64_t data,
 810    unsigned size)
 811{
 812    NvmeCtrl *n = (NvmeCtrl *)opaque;
 813    if (addr < sizeof(n->bar)) {
 814        nvme_write_bar(n, addr, data, size);
 815    } else if (addr >= 0x1000) {
 816        nvme_process_db(n, addr, data);
 817    }
 818}
 819
 820static const MemoryRegionOps nvme_mmio_ops = {
 821    .read = nvme_mmio_read,
 822    .write = nvme_mmio_write,
 823    .endianness = DEVICE_LITTLE_ENDIAN,
 824    .impl = {
 825        .min_access_size = 2,
 826        .max_access_size = 8,
 827    },
 828};
 829
 830static int nvme_init(PCIDevice *pci_dev)
 831{
 832    NvmeCtrl *n = NVME(pci_dev);
 833    NvmeIdCtrl *id = &n->id_ctrl;
 834
 835    int i;
 836    int64_t bs_size;
 837    uint8_t *pci_conf;
 838
 839    if (!n->conf.blk) {
 840        return -1;
 841    }
 842
 843    bs_size = blk_getlength(n->conf.blk);
 844    if (bs_size < 0) {
 845        return -1;
 846    }
 847
 848    blkconf_serial(&n->conf, &n->serial);
 849    if (!n->serial) {
 850        return -1;
 851    }
 852    blkconf_blocksizes(&n->conf);
 853    blkconf_apply_backend_options(&n->conf);
 854
 855    pci_conf = pci_dev->config;
 856    pci_conf[PCI_INTERRUPT_PIN] = 1;
 857    pci_config_set_prog_interface(pci_dev->config, 0x2);
 858    pci_config_set_class(pci_dev->config, PCI_CLASS_STORAGE_EXPRESS);
 859    pcie_endpoint_cap_init(&n->parent_obj, 0x80);
 860
 861    n->num_namespaces = 1;
 862    n->num_queues = 64;
 863    n->reg_size = pow2ceil(0x1004 + 2 * (n->num_queues + 1) * 4);
 864    n->ns_size = bs_size / (uint64_t)n->num_namespaces;
 865
 866    n->namespaces = g_new0(NvmeNamespace, n->num_namespaces);
 867    n->sq = g_new0(NvmeSQueue *, n->num_queues);
 868    n->cq = g_new0(NvmeCQueue *, n->num_queues);
 869
 870    memory_region_init_io(&n->iomem, OBJECT(n), &nvme_mmio_ops, n,
 871                          "nvme", n->reg_size);
 872    pci_register_bar(&n->parent_obj, 0,
 873        PCI_BASE_ADDRESS_SPACE_MEMORY | PCI_BASE_ADDRESS_MEM_TYPE_64,
 874        &n->iomem);
 875    msix_init_exclusive_bar(&n->parent_obj, n->num_queues, 4);
 876
 877    id->vid = cpu_to_le16(pci_get_word(pci_conf + PCI_VENDOR_ID));
 878    id->ssvid = cpu_to_le16(pci_get_word(pci_conf + PCI_SUBSYSTEM_VENDOR_ID));
 879    strpadcpy((char *)id->mn, sizeof(id->mn), "QEMU NVMe Ctrl", ' ');
 880    strpadcpy((char *)id->fr, sizeof(id->fr), "1.0", ' ');
 881    strpadcpy((char *)id->sn, sizeof(id->sn), n->serial, ' ');
 882    id->rab = 6;
 883    id->ieee[0] = 0x00;
 884    id->ieee[1] = 0x02;
 885    id->ieee[2] = 0xb3;
 886    id->oacs = cpu_to_le16(0);
 887    id->frmw = 7 << 1;
 888    id->lpa = 1 << 0;
 889    id->sqes = (0x6 << 4) | 0x6;
 890    id->cqes = (0x4 << 4) | 0x4;
 891    id->nn = cpu_to_le32(n->num_namespaces);
 892    id->psd[0].mp = cpu_to_le16(0x9c4);
 893    id->psd[0].enlat = cpu_to_le32(0x10);
 894    id->psd[0].exlat = cpu_to_le32(0x4);
 895    if (blk_enable_write_cache(n->conf.blk)) {
 896        id->vwc = 1;
 897    }
 898
 899    n->bar.cap = 0;
 900    NVME_CAP_SET_MQES(n->bar.cap, 0x7ff);
 901    NVME_CAP_SET_CQR(n->bar.cap, 1);
 902    NVME_CAP_SET_AMS(n->bar.cap, 1);
 903    NVME_CAP_SET_TO(n->bar.cap, 0xf);
 904    NVME_CAP_SET_CSS(n->bar.cap, 1);
 905    NVME_CAP_SET_MPSMAX(n->bar.cap, 4);
 906
 907    n->bar.vs = 0x00010100;
 908    n->bar.intmc = n->bar.intms = 0;
 909
 910    for (i = 0; i < n->num_namespaces; i++) {
 911        NvmeNamespace *ns = &n->namespaces[i];
 912        NvmeIdNs *id_ns = &ns->id_ns;
 913        id_ns->nsfeat = 0;
 914        id_ns->nlbaf = 0;
 915        id_ns->flbas = 0;
 916        id_ns->mc = 0;
 917        id_ns->dpc = 0;
 918        id_ns->dps = 0;
 919        id_ns->lbaf[0].ds = BDRV_SECTOR_BITS;
 920        id_ns->ncap  = id_ns->nuse = id_ns->nsze =
 921            cpu_to_le64(n->ns_size >>
 922                id_ns->lbaf[NVME_ID_NS_FLBAS_INDEX(ns->id_ns.flbas)].ds);
 923    }
 924    return 0;
 925}
 926
 927static void nvme_exit(PCIDevice *pci_dev)
 928{
 929    NvmeCtrl *n = NVME(pci_dev);
 930
 931    nvme_clear_ctrl(n);
 932    g_free(n->namespaces);
 933    g_free(n->cq);
 934    g_free(n->sq);
 935    msix_uninit_exclusive_bar(pci_dev);
 936}
 937
 938static Property nvme_props[] = {
 939    DEFINE_BLOCK_PROPERTIES(NvmeCtrl, conf),
 940    DEFINE_PROP_STRING("serial", NvmeCtrl, serial),
 941    DEFINE_PROP_END_OF_LIST(),
 942};
 943
 944static const VMStateDescription nvme_vmstate = {
 945    .name = "nvme",
 946    .unmigratable = 1,
 947};
 948
 949static void nvme_class_init(ObjectClass *oc, void *data)
 950{
 951    DeviceClass *dc = DEVICE_CLASS(oc);
 952    PCIDeviceClass *pc = PCI_DEVICE_CLASS(oc);
 953
 954    pc->init = nvme_init;
 955    pc->exit = nvme_exit;
 956    pc->class_id = PCI_CLASS_STORAGE_EXPRESS;
 957    pc->vendor_id = PCI_VENDOR_ID_INTEL;
 958    pc->device_id = 0x5845;
 959    pc->revision = 2;
 960    pc->is_express = 1;
 961
 962    set_bit(DEVICE_CATEGORY_STORAGE, dc->categories);
 963    dc->desc = "Non-Volatile Memory Express";
 964    dc->props = nvme_props;
 965    dc->vmsd = &nvme_vmstate;
 966}
 967
 968static void nvme_instance_init(Object *obj)
 969{
 970    NvmeCtrl *s = NVME(obj);
 971
 972    device_add_bootindex_property(obj, &s->conf.bootindex,
 973                                  "bootindex", "/namespace@1,0",
 974                                  DEVICE(obj), &error_abort);
 975}
 976
 977static const TypeInfo nvme_info = {
 978    .name          = "nvme",
 979    .parent        = TYPE_PCI_DEVICE,
 980    .instance_size = sizeof(NvmeCtrl),
 981    .class_init    = nvme_class_init,
 982    .instance_init = nvme_instance_init,
 983};
 984
 985static void nvme_register_types(void)
 986{
 987    type_register_static(&nvme_info);
 988}
 989
 990type_init(nvme_register_types)
 991