Home | History | Annotate | Line # | Download | only in ic
nvme.c revision 1.34
      1 /*	$NetBSD: nvme.c,v 1.34 2018/03/16 23:31:19 jdolecek Exp $	*/
      2 /*	$OpenBSD: nvme.c,v 1.49 2016/04/18 05:59:50 dlg Exp $ */
      3 
      4 /*
      5  * Copyright (c) 2014 David Gwynne <dlg (at) openbsd.org>
      6  *
      7  * Permission to use, copy, modify, and distribute this software for any
      8  * purpose with or without fee is hereby granted, provided that the above
      9  * copyright notice and this permission notice appear in all copies.
     10  *
     11  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
     12  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
     13  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
     14  * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
     15  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
     16  * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
     17  * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
     18  */
     19 
     20 #include <sys/cdefs.h>
     21 __KERNEL_RCSID(0, "$NetBSD: nvme.c,v 1.34 2018/03/16 23:31:19 jdolecek Exp $");
     22 
     23 #include <sys/param.h>
     24 #include <sys/systm.h>
     25 #include <sys/kernel.h>
     26 #include <sys/atomic.h>
     27 #include <sys/bus.h>
     28 #include <sys/buf.h>
     29 #include <sys/conf.h>
     30 #include <sys/device.h>
     31 #include <sys/kmem.h>
     32 #include <sys/once.h>
     33 #include <sys/proc.h>
     34 #include <sys/queue.h>
     35 #include <sys/mutex.h>
     36 
     37 #include <uvm/uvm_extern.h>
     38 
     39 #include <dev/ic/nvmereg.h>
     40 #include <dev/ic/nvmevar.h>
     41 #include <dev/ic/nvmeio.h>
     42 
     43 #include "ioconf.h"
     44 
     45 int nvme_adminq_size = 32;
     46 int nvme_ioq_size = 1024;
     47 
     48 static int	nvme_print(void *, const char *);
     49 
     50 static int	nvme_ready(struct nvme_softc *, uint32_t);
     51 static int	nvme_enable(struct nvme_softc *, u_int);
     52 static int	nvme_disable(struct nvme_softc *);
     53 static int	nvme_shutdown(struct nvme_softc *);
     54 
     55 #ifdef NVME_DEBUG
     56 static void	nvme_dumpregs(struct nvme_softc *);
     57 #endif
     58 static int	nvme_identify(struct nvme_softc *, u_int);
     59 static void	nvme_fill_identify(struct nvme_queue *, struct nvme_ccb *,
     60 		    void *);
     61 
     62 static int	nvme_ccbs_alloc(struct nvme_queue *, uint16_t);
     63 static void	nvme_ccbs_free(struct nvme_queue *);
     64 
     65 static struct nvme_ccb *
     66 		nvme_ccb_get(struct nvme_queue *, bool);
     67 static void	nvme_ccb_put(struct nvme_queue *, struct nvme_ccb *);
     68 
     69 static int	nvme_poll(struct nvme_softc *, struct nvme_queue *,
     70 		    struct nvme_ccb *, void (*)(struct nvme_queue *,
     71 		    struct nvme_ccb *, void *), int);
     72 static void	nvme_poll_fill(struct nvme_queue *, struct nvme_ccb *, void *);
     73 static void	nvme_poll_done(struct nvme_queue *, struct nvme_ccb *,
     74 		    struct nvme_cqe *);
     75 static void	nvme_sqe_fill(struct nvme_queue *, struct nvme_ccb *, void *);
     76 static void	nvme_empty_done(struct nvme_queue *, struct nvme_ccb *,
     77 		    struct nvme_cqe *);
     78 
     79 static struct nvme_queue *
     80 		nvme_q_alloc(struct nvme_softc *, uint16_t, u_int, u_int);
     81 static int	nvme_q_create(struct nvme_softc *, struct nvme_queue *);
     82 static int	nvme_q_delete(struct nvme_softc *, struct nvme_queue *);
     83 static void	nvme_q_submit(struct nvme_softc *, struct nvme_queue *,
     84 		    struct nvme_ccb *, void (*)(struct nvme_queue *,
     85 		    struct nvme_ccb *, void *));
     86 static int	nvme_q_complete(struct nvme_softc *, struct nvme_queue *q);
     87 static void	nvme_q_free(struct nvme_softc *, struct nvme_queue *);
     88 static void	nvme_q_wait_complete(struct nvme_softc *, struct nvme_queue *,
     89 		    bool (*)(void *), void *);
     90 
     91 static struct nvme_dmamem *
     92 		nvme_dmamem_alloc(struct nvme_softc *, size_t);
     93 static void	nvme_dmamem_free(struct nvme_softc *, struct nvme_dmamem *);
     94 static void	nvme_dmamem_sync(struct nvme_softc *, struct nvme_dmamem *,
     95 		    int);
     96 
     97 static void	nvme_ns_io_fill(struct nvme_queue *, struct nvme_ccb *,
     98 		    void *);
     99 static void	nvme_ns_io_done(struct nvme_queue *, struct nvme_ccb *,
    100 		    struct nvme_cqe *);
    101 static void	nvme_ns_sync_fill(struct nvme_queue *, struct nvme_ccb *,
    102 		    void *);
    103 static void	nvme_ns_sync_done(struct nvme_queue *, struct nvme_ccb *,
    104 		    struct nvme_cqe *);
    105 static void	nvme_getcache_fill(struct nvme_queue *, struct nvme_ccb *,
    106 		    void *);
    107 static void	nvme_getcache_done(struct nvme_queue *, struct nvme_ccb *,
    108 		    struct nvme_cqe *);
    109 
    110 static void	nvme_pt_fill(struct nvme_queue *, struct nvme_ccb *,
    111 		    void *);
    112 static void	nvme_pt_done(struct nvme_queue *, struct nvme_ccb *,
    113 		    struct nvme_cqe *);
    114 static int	nvme_command_passthrough(struct nvme_softc *,
    115 		    struct nvme_pt_command *, uint16_t, struct lwp *, bool);
    116 
    117 static int	nvme_get_number_of_queues(struct nvme_softc *, u_int *);
    118 
    119 #define NVME_TIMO_QOP		5	/* queue create and delete timeout */
    120 #define NVME_TIMO_IDENT		10	/* probe identify timeout */
    121 #define NVME_TIMO_PT		-1	/* passthrough cmd timeout */
    122 #define NVME_TIMO_SY		60	/* sync cache timeout */
    123 
    124 #define nvme_read4(_s, _r) \
    125 	bus_space_read_4((_s)->sc_iot, (_s)->sc_ioh, (_r))
    126 #define nvme_write4(_s, _r, _v) \
    127 	bus_space_write_4((_s)->sc_iot, (_s)->sc_ioh, (_r), (_v))
    128 /*
    129  * Some controllers, at least Apple NVMe, always require split
    130  * transfers, so don't use bus_space_{read,write}_8() on LP64.
    131  */
    132 static inline uint64_t
    133 nvme_read8(struct nvme_softc *sc, bus_size_t r)
    134 {
    135 	uint64_t v;
    136 	uint32_t *a = (uint32_t *)&v;
    137 
    138 #if _BYTE_ORDER == _LITTLE_ENDIAN
    139 	a[0] = nvme_read4(sc, r);
    140 	a[1] = nvme_read4(sc, r + 4);
    141 #else /* _BYTE_ORDER == _LITTLE_ENDIAN */
    142 	a[1] = nvme_read4(sc, r);
    143 	a[0] = nvme_read4(sc, r + 4);
    144 #endif
    145 
    146 	return v;
    147 }
    148 
    149 static inline void
    150 nvme_write8(struct nvme_softc *sc, bus_size_t r, uint64_t v)
    151 {
    152 	uint32_t *a = (uint32_t *)&v;
    153 
    154 #if _BYTE_ORDER == _LITTLE_ENDIAN
    155 	nvme_write4(sc, r, a[0]);
    156 	nvme_write4(sc, r + 4, a[1]);
    157 #else /* _BYTE_ORDER == _LITTLE_ENDIAN */
    158 	nvme_write4(sc, r, a[1]);
    159 	nvme_write4(sc, r + 4, a[0]);
    160 #endif
    161 }
    162 #define nvme_barrier(_s, _r, _l, _f) \
    163 	bus_space_barrier((_s)->sc_iot, (_s)->sc_ioh, (_r), (_l), (_f))
    164 
    165 #ifdef NVME_DEBUG
    166 static __used void
    167 nvme_dumpregs(struct nvme_softc *sc)
    168 {
    169 	uint64_t r8;
    170 	uint32_t r4;
    171 
    172 #define	DEVNAME(_sc) device_xname((_sc)->sc_dev)
    173 	r8 = nvme_read8(sc, NVME_CAP);
    174 	printf("%s: cap  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_CAP));
    175 	printf("%s:  mpsmax %u (%u)\n", DEVNAME(sc),
    176 	    (u_int)NVME_CAP_MPSMAX(r8), (1 << NVME_CAP_MPSMAX(r8)));
    177 	printf("%s:  mpsmin %u (%u)\n", DEVNAME(sc),
    178 	    (u_int)NVME_CAP_MPSMIN(r8), (1 << NVME_CAP_MPSMIN(r8)));
    179 	printf("%s:  css %"PRIu64"\n", DEVNAME(sc), NVME_CAP_CSS(r8));
    180 	printf("%s:  nssrs %"PRIu64"\n", DEVNAME(sc), NVME_CAP_NSSRS(r8));
    181 	printf("%s:  dstrd %"PRIu64"\n", DEVNAME(sc), NVME_CAP_DSTRD(r8));
    182 	printf("%s:  to %"PRIu64" msec\n", DEVNAME(sc), NVME_CAP_TO(r8));
    183 	printf("%s:  ams %"PRIu64"\n", DEVNAME(sc), NVME_CAP_AMS(r8));
    184 	printf("%s:  cqr %"PRIu64"\n", DEVNAME(sc), NVME_CAP_CQR(r8));
    185 	printf("%s:  mqes %"PRIu64"\n", DEVNAME(sc), NVME_CAP_MQES(r8));
    186 
    187 	printf("%s: vs   0x%04x\n", DEVNAME(sc), nvme_read4(sc, NVME_VS));
    188 
    189 	r4 = nvme_read4(sc, NVME_CC);
    190 	printf("%s: cc   0x%04x\n", DEVNAME(sc), r4);
    191 	printf("%s:  iocqes %u (%u)\n", DEVNAME(sc), NVME_CC_IOCQES_R(r4),
    192 	    (1 << NVME_CC_IOCQES_R(r4)));
    193 	printf("%s:  iosqes %u (%u)\n", DEVNAME(sc), NVME_CC_IOSQES_R(r4),
    194 	    (1 << NVME_CC_IOSQES_R(r4)));
    195 	printf("%s:  shn %u\n", DEVNAME(sc), NVME_CC_SHN_R(r4));
    196 	printf("%s:  ams %u\n", DEVNAME(sc), NVME_CC_AMS_R(r4));
    197 	printf("%s:  mps %u (%u)\n", DEVNAME(sc), NVME_CC_MPS_R(r4),
    198 	    (1 << NVME_CC_MPS_R(r4)));
    199 	printf("%s:  css %u\n", DEVNAME(sc), NVME_CC_CSS_R(r4));
    200 	printf("%s:  en %u\n", DEVNAME(sc), ISSET(r4, NVME_CC_EN) ? 1 : 0);
    201 
    202 	r4 = nvme_read4(sc, NVME_CSTS);
    203 	printf("%s: csts 0x%08x\n", DEVNAME(sc), r4);
    204 	printf("%s:  rdy %u\n", DEVNAME(sc), r4 & NVME_CSTS_RDY);
    205 	printf("%s:  cfs %u\n", DEVNAME(sc), r4 & NVME_CSTS_CFS);
    206 	printf("%s:  shst %x\n", DEVNAME(sc), r4 & NVME_CSTS_SHST_MASK);
    207 
    208 	r4 = nvme_read4(sc, NVME_AQA);
    209 	printf("%s: aqa  0x%08x\n", DEVNAME(sc), r4);
    210 	printf("%s:  acqs %u\n", DEVNAME(sc), NVME_AQA_ACQS_R(r4));
    211 	printf("%s:  asqs %u\n", DEVNAME(sc), NVME_AQA_ASQS_R(r4));
    212 
    213 	printf("%s: asq  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_ASQ));
    214 	printf("%s: acq  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_ACQ));
    215 #undef	DEVNAME
    216 }
    217 #endif	/* NVME_DEBUG */
    218 
    219 static int
    220 nvme_ready(struct nvme_softc *sc, uint32_t rdy)
    221 {
    222 	u_int i = 0;
    223 	uint32_t cc;
    224 
    225 	cc = nvme_read4(sc, NVME_CC);
    226 	if (((cc & NVME_CC_EN) != 0) != (rdy != 0)) {
    227 		aprint_error_dev(sc->sc_dev,
    228 		    "controller enabled status expected %d, found to be %d\n",
    229 		    (rdy != 0), ((cc & NVME_CC_EN) != 0));
    230 		return ENXIO;
    231 	}
    232 
    233 	while ((nvme_read4(sc, NVME_CSTS) & NVME_CSTS_RDY) != rdy) {
    234 		if (i++ > sc->sc_rdy_to)
    235 			return ENXIO;
    236 
    237 		delay(1000);
    238 		nvme_barrier(sc, NVME_CSTS, 4, BUS_SPACE_BARRIER_READ);
    239 	}
    240 
    241 	return 0;
    242 }
    243 
    244 static int
    245 nvme_enable(struct nvme_softc *sc, u_int mps)
    246 {
    247 	uint32_t cc, csts;
    248 
    249 	cc = nvme_read4(sc, NVME_CC);
    250 	csts = nvme_read4(sc, NVME_CSTS);
    251 
    252 	if (ISSET(cc, NVME_CC_EN)) {
    253 		aprint_error_dev(sc->sc_dev, "controller unexpectedly enabled, failed to stay disabled\n");
    254 
    255 		if (ISSET(csts, NVME_CSTS_RDY))
    256 			return 1;
    257 
    258 		goto waitready;
    259 	}
    260 
    261 	nvme_write8(sc, NVME_ASQ, NVME_DMA_DVA(sc->sc_admin_q->q_sq_dmamem));
    262 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    263 	delay(5000);
    264 	nvme_write8(sc, NVME_ACQ, NVME_DMA_DVA(sc->sc_admin_q->q_cq_dmamem));
    265 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    266 	delay(5000);
    267 
    268 	nvme_write4(sc, NVME_AQA, NVME_AQA_ACQS(sc->sc_admin_q->q_entries) |
    269 	    NVME_AQA_ASQS(sc->sc_admin_q->q_entries));
    270 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    271 	delay(5000);
    272 
    273 	CLR(cc, NVME_CC_IOCQES_MASK | NVME_CC_IOSQES_MASK | NVME_CC_SHN_MASK |
    274 	    NVME_CC_AMS_MASK | NVME_CC_MPS_MASK | NVME_CC_CSS_MASK);
    275 	SET(cc, NVME_CC_IOSQES(ffs(64) - 1) | NVME_CC_IOCQES(ffs(16) - 1));
    276 	SET(cc, NVME_CC_SHN(NVME_CC_SHN_NONE));
    277 	SET(cc, NVME_CC_CSS(NVME_CC_CSS_NVM));
    278 	SET(cc, NVME_CC_AMS(NVME_CC_AMS_RR));
    279 	SET(cc, NVME_CC_MPS(mps));
    280 	SET(cc, NVME_CC_EN);
    281 
    282 	nvme_write4(sc, NVME_CC, cc);
    283 	nvme_barrier(sc, 0, sc->sc_ios,
    284 	    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
    285 	delay(5000);
    286 
    287     waitready:
    288 	return nvme_ready(sc, NVME_CSTS_RDY);
    289 }
    290 
    291 static int
    292 nvme_disable(struct nvme_softc *sc)
    293 {
    294 	uint32_t cc, csts;
    295 
    296 	cc = nvme_read4(sc, NVME_CC);
    297 	csts = nvme_read4(sc, NVME_CSTS);
    298 
    299 	if (ISSET(cc, NVME_CC_EN) && !ISSET(csts, NVME_CSTS_RDY))
    300 		nvme_ready(sc, NVME_CSTS_RDY);
    301 
    302 	CLR(cc, NVME_CC_EN);
    303 
    304 	nvme_write4(sc, NVME_CC, cc);
    305 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_READ);
    306 
    307 	delay(5000);
    308 
    309 	return nvme_ready(sc, 0);
    310 }
    311 
    312 int
    313 nvme_attach(struct nvme_softc *sc)
    314 {
    315 	uint64_t cap;
    316 	uint32_t reg;
    317 	u_int dstrd;
    318 	u_int mps = PAGE_SHIFT;
    319 	u_int ioq_allocated;
    320 	uint16_t adminq_entries = nvme_adminq_size;
    321 	uint16_t ioq_entries = nvme_ioq_size;
    322 	int i;
    323 
    324 	reg = nvme_read4(sc, NVME_VS);
    325 	if (reg == 0xffffffff) {
    326 		aprint_error_dev(sc->sc_dev, "invalid mapping\n");
    327 		return 1;
    328 	}
    329 
    330 	if (NVME_VS_TER(reg) == 0)
    331 		aprint_normal_dev(sc->sc_dev, "NVMe %d.%d\n", NVME_VS_MJR(reg),
    332 		    NVME_VS_MNR(reg));
    333 	else
    334 		aprint_normal_dev(sc->sc_dev, "NVMe %d.%d.%d\n", NVME_VS_MJR(reg),
    335 		    NVME_VS_MNR(reg), NVME_VS_TER(reg));
    336 
    337 	cap = nvme_read8(sc, NVME_CAP);
    338 	dstrd = NVME_CAP_DSTRD(cap);
    339 	if (NVME_CAP_MPSMIN(cap) > PAGE_SHIFT) {
    340 		aprint_error_dev(sc->sc_dev, "NVMe minimum page size %u "
    341 		    "is greater than CPU page size %u\n",
    342 		    1 << NVME_CAP_MPSMIN(cap), 1 << PAGE_SHIFT);
    343 		return 1;
    344 	}
    345 	if (NVME_CAP_MPSMAX(cap) < mps)
    346 		mps = NVME_CAP_MPSMAX(cap);
    347 	if (ioq_entries > NVME_CAP_MQES(cap))
    348 		ioq_entries = NVME_CAP_MQES(cap);
    349 
    350 	/* set initial values to be used for admin queue during probe */
    351 	sc->sc_rdy_to = NVME_CAP_TO(cap);
    352 	sc->sc_mps = 1 << mps;
    353 	sc->sc_mdts = MAXPHYS;
    354 	sc->sc_max_sgl = 2;
    355 
    356 	if (nvme_disable(sc) != 0) {
    357 		aprint_error_dev(sc->sc_dev, "unable to disable controller\n");
    358 		return 1;
    359 	}
    360 
    361 	sc->sc_admin_q = nvme_q_alloc(sc, NVME_ADMIN_Q, adminq_entries, dstrd);
    362 	if (sc->sc_admin_q == NULL) {
    363 		aprint_error_dev(sc->sc_dev,
    364 		    "unable to allocate admin queue\n");
    365 		return 1;
    366 	}
    367 	if (sc->sc_intr_establish(sc, NVME_ADMIN_Q, sc->sc_admin_q))
    368 		goto free_admin_q;
    369 
    370 	if (nvme_enable(sc, mps) != 0) {
    371 		aprint_error_dev(sc->sc_dev, "unable to enable controller\n");
    372 		goto disestablish_admin_q;
    373 	}
    374 
    375 	if (nvme_identify(sc, NVME_CAP_MPSMIN(cap)) != 0) {
    376 		aprint_error_dev(sc->sc_dev, "unable to identify controller\n");
    377 		goto disable;
    378 	}
    379 
    380 	/* we know how big things are now */
    381 	sc->sc_max_sgl = sc->sc_mdts / sc->sc_mps;
    382 
    383 	/* reallocate ccbs of admin queue with new max sgl. */
    384 	nvme_ccbs_free(sc->sc_admin_q);
    385 	nvme_ccbs_alloc(sc->sc_admin_q, sc->sc_admin_q->q_entries);
    386 
    387 	if (sc->sc_use_mq) {
    388 		/* Limit the number of queues to the number allocated in HW */
    389 		if (nvme_get_number_of_queues(sc, &ioq_allocated) != 0) {
    390 			aprint_error_dev(sc->sc_dev,
    391 			    "unable to get number of queues\n");
    392 			goto disable;
    393 		}
    394 		if (sc->sc_nq > ioq_allocated)
    395 			sc->sc_nq = ioq_allocated;
    396 	}
    397 
    398 	sc->sc_q = kmem_zalloc(sizeof(*sc->sc_q) * sc->sc_nq, KM_SLEEP);
    399 	for (i = 0; i < sc->sc_nq; i++) {
    400 		sc->sc_q[i] = nvme_q_alloc(sc, i + 1, ioq_entries, dstrd);
    401 		if (sc->sc_q[i] == NULL) {
    402 			aprint_error_dev(sc->sc_dev,
    403 			    "unable to allocate io queue\n");
    404 			goto free_q;
    405 		}
    406 		if (nvme_q_create(sc, sc->sc_q[i]) != 0) {
    407 			aprint_error_dev(sc->sc_dev,
    408 			    "unable to create io queue\n");
    409 			nvme_q_free(sc, sc->sc_q[i]);
    410 			goto free_q;
    411 		}
    412 	}
    413 
    414 	if (!sc->sc_use_mq)
    415 		nvme_write4(sc, NVME_INTMC, 1);
    416 
    417 	/* probe subdevices */
    418 	sc->sc_namespaces = kmem_zalloc(sizeof(*sc->sc_namespaces) * sc->sc_nn,
    419 	    KM_SLEEP);
    420 	nvme_rescan(sc->sc_dev, "nvme", &i);
    421 
    422 	return 0;
    423 
    424 free_q:
    425 	while (--i >= 0) {
    426 		nvme_q_delete(sc, sc->sc_q[i]);
    427 		nvme_q_free(sc, sc->sc_q[i]);
    428 	}
    429 disable:
    430 	nvme_disable(sc);
    431 disestablish_admin_q:
    432 	sc->sc_intr_disestablish(sc, NVME_ADMIN_Q);
    433 free_admin_q:
    434 	nvme_q_free(sc, sc->sc_admin_q);
    435 
    436 	return 1;
    437 }
    438 
    439 int
    440 nvme_rescan(device_t self, const char *attr, const int *flags)
    441 {
    442 	struct nvme_softc *sc = device_private(self);
    443 	struct nvme_attach_args naa;
    444 	uint64_t cap;
    445 	int ioq_entries = nvme_ioq_size;
    446 	int i;
    447 
    448 	cap = nvme_read8(sc, NVME_CAP);
    449 	if (ioq_entries > NVME_CAP_MQES(cap))
    450 		ioq_entries = NVME_CAP_MQES(cap);
    451 
    452 	for (i = 0; i < sc->sc_nn; i++) {
    453 		if (sc->sc_namespaces[i].dev)
    454 			continue;
    455 		memset(&naa, 0, sizeof(naa));
    456 		naa.naa_nsid = i + 1;
    457 		naa.naa_qentries = (ioq_entries - 1) * sc->sc_nq;
    458 		naa.naa_maxphys = sc->sc_mdts;
    459 		sc->sc_namespaces[i].dev = config_found(sc->sc_dev, &naa,
    460 		    nvme_print);
    461 	}
    462 	return 0;
    463 }
    464 
    465 static int
    466 nvme_print(void *aux, const char *pnp)
    467 {
    468 	struct nvme_attach_args *naa = aux;
    469 
    470 	if (pnp)
    471 		aprint_normal("at %s", pnp);
    472 
    473 	if (naa->naa_nsid > 0)
    474 		aprint_normal(" nsid %d", naa->naa_nsid);
    475 
    476 	return UNCONF;
    477 }
    478 
    479 int
    480 nvme_detach(struct nvme_softc *sc, int flags)
    481 {
    482 	int i, error;
    483 
    484 	error = config_detach_children(sc->sc_dev, flags);
    485 	if (error)
    486 		return error;
    487 
    488 	error = nvme_shutdown(sc);
    489 	if (error)
    490 		return error;
    491 
    492 	/* from now on we are committed to detach, following will never fail */
    493 	for (i = 0; i < sc->sc_nq; i++)
    494 		nvme_q_free(sc, sc->sc_q[i]);
    495 	kmem_free(sc->sc_q, sizeof(*sc->sc_q) * sc->sc_nq);
    496 	nvme_q_free(sc, sc->sc_admin_q);
    497 
    498 	return 0;
    499 }
    500 
    501 static int
    502 nvme_shutdown(struct nvme_softc *sc)
    503 {
    504 	uint32_t cc, csts;
    505 	bool disabled = false;
    506 	int i;
    507 
    508 	if (!sc->sc_use_mq)
    509 		nvme_write4(sc, NVME_INTMS, 1);
    510 
    511 	for (i = 0; i < sc->sc_nq; i++) {
    512 		if (nvme_q_delete(sc, sc->sc_q[i]) != 0) {
    513 			aprint_error_dev(sc->sc_dev,
    514 			    "unable to delete io queue %d, disabling\n", i + 1);
    515 			disabled = true;
    516 		}
    517 	}
    518 	sc->sc_intr_disestablish(sc, NVME_ADMIN_Q);
    519 	if (disabled)
    520 		goto disable;
    521 
    522 	cc = nvme_read4(sc, NVME_CC);
    523 	CLR(cc, NVME_CC_SHN_MASK);
    524 	SET(cc, NVME_CC_SHN(NVME_CC_SHN_NORMAL));
    525 	nvme_write4(sc, NVME_CC, cc);
    526 
    527 	for (i = 0; i < 4000; i++) {
    528 		nvme_barrier(sc, 0, sc->sc_ios,
    529 		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
    530 		csts = nvme_read4(sc, NVME_CSTS);
    531 		if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_DONE)
    532 			return 0;
    533 
    534 		delay(1000);
    535 	}
    536 
    537 	aprint_error_dev(sc->sc_dev, "unable to shudown, disabling\n");
    538 
    539 disable:
    540 	nvme_disable(sc);
    541 	return 0;
    542 }
    543 
    544 void
    545 nvme_childdet(device_t self, device_t child)
    546 {
    547 	struct nvme_softc *sc = device_private(self);
    548 	int i;
    549 
    550 	for (i = 0; i < sc->sc_nn; i++) {
    551 		if (sc->sc_namespaces[i].dev == child) {
    552 			/* Already freed ns->ident. */
    553 			sc->sc_namespaces[i].dev = NULL;
    554 			break;
    555 		}
    556 	}
    557 }
    558 
    559 int
    560 nvme_ns_identify(struct nvme_softc *sc, uint16_t nsid)
    561 {
    562 	struct nvme_sqe sqe;
    563 	struct nvm_identify_namespace *identify;
    564 	struct nvme_dmamem *mem;
    565 	struct nvme_ccb *ccb;
    566 	struct nvme_namespace *ns;
    567 	int rv;
    568 
    569 	KASSERT(nsid > 0);
    570 
    571 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
    572 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
    573 
    574 	mem = nvme_dmamem_alloc(sc, sizeof(*identify));
    575 	if (mem == NULL) {
    576 		nvme_ccb_put(sc->sc_admin_q, ccb);
    577 		return ENOMEM;
    578 	}
    579 
    580 	memset(&sqe, 0, sizeof(sqe));
    581 	sqe.opcode = NVM_ADMIN_IDENTIFY;
    582 	htolem32(&sqe.nsid, nsid);
    583 	htolem64(&sqe.entry.prp[0], NVME_DMA_DVA(mem));
    584 	htolem32(&sqe.cdw10, 0);
    585 
    586 	ccb->ccb_done = nvme_empty_done;
    587 	ccb->ccb_cookie = &sqe;
    588 
    589 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_PREREAD);
    590 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_IDENT);
    591 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_POSTREAD);
    592 
    593 	nvme_ccb_put(sc->sc_admin_q, ccb);
    594 
    595 	if (rv != 0) {
    596 		rv = EIO;
    597 		goto done;
    598 	}
    599 
    600 	/* commit */
    601 
    602 	identify = kmem_zalloc(sizeof(*identify), KM_SLEEP);
    603 	*identify = *((volatile struct nvm_identify_namespace *)NVME_DMA_KVA(mem));
    604 	//memcpy(identify, NVME_DMA_KVA(mem), sizeof(*identify));
    605 
    606 	ns = nvme_ns_get(sc, nsid);
    607 	KASSERT(ns);
    608 	KASSERT(ns->ident == NULL);
    609 	ns->ident = identify;
    610 
    611 done:
    612 	nvme_dmamem_free(sc, mem);
    613 
    614 	return rv;
    615 }
    616 
    617 int
    618 nvme_ns_dobio(struct nvme_softc *sc, uint16_t nsid, void *cookie,
    619     struct buf *bp, void *data, size_t datasize,
    620     int secsize, daddr_t blkno, int flags, nvme_nnc_done nnc_done)
    621 {
    622 	struct nvme_queue *q = nvme_get_q(sc);
    623 	struct nvme_ccb *ccb;
    624 	bus_dmamap_t dmap;
    625 	int i, error;
    626 
    627 	ccb = nvme_ccb_get(q, false);
    628 	if (ccb == NULL)
    629 		return EAGAIN;
    630 
    631 	ccb->ccb_done = nvme_ns_io_done;
    632 	ccb->ccb_cookie = cookie;
    633 
    634 	/* namespace context */
    635 	ccb->nnc_nsid = nsid;
    636 	ccb->nnc_flags = flags;
    637 	ccb->nnc_buf = bp;
    638 	ccb->nnc_datasize = datasize;
    639 	ccb->nnc_secsize = secsize;
    640 	ccb->nnc_blkno = blkno;
    641 	ccb->nnc_done = nnc_done;
    642 
    643 	dmap = ccb->ccb_dmamap;
    644 	error = bus_dmamap_load(sc->sc_dmat, dmap, data,
    645 	    datasize, NULL,
    646 	    (ISSET(flags, NVME_NS_CTX_F_POLL) ?
    647 	      BUS_DMA_NOWAIT : BUS_DMA_WAITOK) |
    648 	    (ISSET(flags, NVME_NS_CTX_F_READ) ?
    649 	      BUS_DMA_READ : BUS_DMA_WRITE));
    650 	if (error) {
    651 		nvme_ccb_put(q, ccb);
    652 		return error;
    653 	}
    654 
    655 	bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
    656 	    ISSET(flags, NVME_NS_CTX_F_READ) ?
    657 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
    658 
    659 	if (dmap->dm_nsegs > 2) {
    660 		for (i = 1; i < dmap->dm_nsegs; i++) {
    661 			htolem64(&ccb->ccb_prpl[i - 1],
    662 			    dmap->dm_segs[i].ds_addr);
    663 		}
    664 		bus_dmamap_sync(sc->sc_dmat,
    665 		    NVME_DMA_MAP(q->q_ccb_prpls),
    666 		    ccb->ccb_prpl_off,
    667 		    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    668 		    BUS_DMASYNC_PREWRITE);
    669 	}
    670 
    671 	if (ISSET(flags, NVME_NS_CTX_F_POLL)) {
    672 		if (nvme_poll(sc, q, ccb, nvme_ns_io_fill, NVME_TIMO_PT) != 0)
    673 			return EIO;
    674 		return 0;
    675 	}
    676 
    677 	nvme_q_submit(sc, q, ccb, nvme_ns_io_fill);
    678 	return 0;
    679 }
    680 
    681 static void
    682 nvme_ns_io_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    683 {
    684 	struct nvme_sqe_io *sqe = slot;
    685 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    686 
    687 	sqe->opcode = ISSET(ccb->nnc_flags, NVME_NS_CTX_F_READ) ?
    688 	    NVM_CMD_READ : NVM_CMD_WRITE;
    689 	htolem32(&sqe->nsid, ccb->nnc_nsid);
    690 
    691 	htolem64(&sqe->entry.prp[0], dmap->dm_segs[0].ds_addr);
    692 	switch (dmap->dm_nsegs) {
    693 	case 1:
    694 		break;
    695 	case 2:
    696 		htolem64(&sqe->entry.prp[1], dmap->dm_segs[1].ds_addr);
    697 		break;
    698 	default:
    699 		/* the prp list is already set up and synced */
    700 		htolem64(&sqe->entry.prp[1], ccb->ccb_prpl_dva);
    701 		break;
    702 	}
    703 
    704 	htolem64(&sqe->slba, ccb->nnc_blkno);
    705 
    706 	if (ISSET(ccb->nnc_flags, NVME_NS_CTX_F_FUA))
    707 		htolem16(&sqe->ioflags, NVM_SQE_IO_FUA);
    708 
    709 	/* guaranteed by upper layers, but check just in case */
    710 	KASSERT((ccb->nnc_datasize % ccb->nnc_secsize) == 0);
    711 	htolem16(&sqe->nlb, (ccb->nnc_datasize / ccb->nnc_secsize) - 1);
    712 }
    713 
    714 static void
    715 nvme_ns_io_done(struct nvme_queue *q, struct nvme_ccb *ccb,
    716     struct nvme_cqe *cqe)
    717 {
    718 	struct nvme_softc *sc = q->q_sc;
    719 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    720 	void *nnc_cookie = ccb->ccb_cookie;
    721 	nvme_nnc_done nnc_done = ccb->nnc_done;
    722 	struct buf *bp = ccb->nnc_buf;
    723 
    724 	if (dmap->dm_nsegs > 2) {
    725 		bus_dmamap_sync(sc->sc_dmat,
    726 		    NVME_DMA_MAP(q->q_ccb_prpls),
    727 		    ccb->ccb_prpl_off,
    728 		    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    729 		    BUS_DMASYNC_POSTWRITE);
    730 	}
    731 
    732 	bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
    733 	    ISSET(ccb->nnc_flags, NVME_NS_CTX_F_READ) ?
    734 	    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
    735 
    736 	bus_dmamap_unload(sc->sc_dmat, dmap);
    737 	nvme_ccb_put(q, ccb);
    738 
    739 	nnc_done(nnc_cookie, bp, lemtoh16(&cqe->flags), lemtoh32(&cqe->cdw0));
    740 }
    741 
    742 /*
    743  * If there is no volatile write cache, it makes no sense to issue
    744  * flush commands or query for the status.
    745  */
    746 static bool
    747 nvme_has_volatile_write_cache(struct nvme_softc *sc)
    748 {
    749 	/* sc_identify is filled during attachment */
    750 	return  ((sc->sc_identify.vwc & NVME_ID_CTRLR_VWC_PRESENT) != 0);
    751 }
    752 
    753 static bool
    754 nvme_ns_sync_finished(void *cookie)
    755 {
    756 	int *result = cookie;
    757 
    758 	return (*result != 0);
    759 }
    760 
    761 int
    762 nvme_ns_sync(struct nvme_softc *sc, uint16_t nsid, int flags)
    763 {
    764 	struct nvme_queue *q = nvme_get_q(sc);
    765 	struct nvme_ccb *ccb;
    766 	int result = 0;
    767 
    768 	if (!nvme_has_volatile_write_cache(sc)) {
    769 		/* cache not present, no value in trying to flush it */
    770 		return 0;
    771 	}
    772 
    773 	ccb = nvme_ccb_get(q, true);
    774 	if (ccb == NULL)
    775 		return EAGAIN;
    776 
    777 	ccb->ccb_done = nvme_ns_sync_done;
    778 	ccb->ccb_cookie = &result;
    779 
    780 	/* namespace context */
    781 	ccb->nnc_nsid = nsid;
    782 	ccb->nnc_flags = flags;
    783 	ccb->nnc_done = NULL;
    784 
    785 	if (ISSET(flags, NVME_NS_CTX_F_POLL)) {
    786 		if (nvme_poll(sc, q, ccb, nvme_ns_sync_fill, NVME_TIMO_SY) != 0)
    787 			return EIO;
    788 		return 0;
    789 	}
    790 
    791 	nvme_q_submit(sc, q, ccb, nvme_ns_sync_fill);
    792 
    793 	/* wait for completion */
    794 	nvme_q_wait_complete(sc, q, nvme_ns_sync_finished, &result);
    795 	KASSERT(result != 0);
    796 
    797 	return (result > 0) ? 0 : EIO;
    798 }
    799 
    800 static void
    801 nvme_ns_sync_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    802 {
    803 	struct nvme_sqe *sqe = slot;
    804 
    805 	sqe->opcode = NVM_CMD_FLUSH;
    806 	htolem32(&sqe->nsid, ccb->nnc_nsid);
    807 }
    808 
    809 static void
    810 nvme_ns_sync_done(struct nvme_queue *q, struct nvme_ccb *ccb,
    811     struct nvme_cqe *cqe)
    812 {
    813 	int *result = ccb->ccb_cookie;
    814 	uint16_t status = NVME_CQE_SC(lemtoh16(&cqe->flags));
    815 
    816 	if (status == NVME_CQE_SC_SUCCESS)
    817 		*result = 1;
    818 	else
    819 		*result = -1;
    820 
    821 	nvme_ccb_put(q, ccb);
    822 }
    823 
    824 static bool
    825 nvme_getcache_finished(void *xc)
    826 {
    827 	int *addr = xc;
    828 
    829 	return (*addr != 0);
    830 }
    831 
    832 /*
    833  * Get status of volatile write cache. Always asynchronous.
    834  */
    835 int
    836 nvme_admin_getcache(struct nvme_softc *sc, int *addr)
    837 {
    838 	struct nvme_ccb *ccb;
    839 	struct nvme_queue *q = sc->sc_admin_q;
    840 	int result = 0, error;
    841 
    842 	if (!nvme_has_volatile_write_cache(sc)) {
    843 		/* cache simply not present */
    844 		*addr = 0;
    845 		return 0;
    846 	}
    847 
    848 	ccb = nvme_ccb_get(q, true);
    849 	KASSERT(ccb != NULL);
    850 
    851 	ccb->ccb_done = nvme_getcache_done;
    852 	ccb->ccb_cookie = &result;
    853 
    854 	/* namespace context */
    855 	ccb->nnc_flags = 0;
    856 	ccb->nnc_done = NULL;
    857 
    858 	nvme_q_submit(sc, q, ccb, nvme_getcache_fill);
    859 
    860 	/* wait for completion */
    861 	nvme_q_wait_complete(sc, q, nvme_getcache_finished, &result);
    862 	KASSERT(result != 0);
    863 
    864 	if (result > 0) {
    865 		*addr = result;
    866 		error = 0;
    867 	} else
    868 		error = EINVAL;
    869 
    870 	return error;
    871 }
    872 
    873 static void
    874 nvme_getcache_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    875 {
    876 	struct nvme_sqe *sqe = slot;
    877 
    878 	sqe->opcode = NVM_ADMIN_GET_FEATURES;
    879 	sqe->cdw10 = NVM_FEATURE_VOLATILE_WRITE_CACHE;
    880 }
    881 
    882 static void
    883 nvme_getcache_done(struct nvme_queue *q, struct nvme_ccb *ccb,
    884     struct nvme_cqe *cqe)
    885 {
    886 	int *addr = ccb->ccb_cookie;
    887 	uint16_t status = NVME_CQE_SC(lemtoh16(&cqe->flags));
    888 	uint32_t cdw0 = lemtoh32(&cqe->cdw0);
    889 	int result;
    890 
    891 	if (status == NVME_CQE_SC_SUCCESS) {
    892 		result = 0;
    893 
    894 		/*
    895 		 * DPO not supported, Dataset Management (DSM) field doesn't
    896 		 * specify the same semantics. FUA is always supported.
    897 		 */
    898 		result = DKCACHE_FUA;
    899 
    900 		if (cdw0 & NVME_CQE_CDW0_VWC_WCE)
    901 			result |= DKCACHE_WRITE;
    902 
    903 		/*
    904 		 * If volatile write cache is present, the flag shall also be
    905 		 * settable.
    906 		 */
    907 		result |= DKCACHE_WCHANGE;
    908 	} else {
    909 		result = -1;
    910 	}
    911 
    912 	*addr = result;
    913 
    914 	nvme_ccb_put(q, ccb);
    915 }
    916 
    917 void
    918 nvme_ns_free(struct nvme_softc *sc, uint16_t nsid)
    919 {
    920 	struct nvme_namespace *ns;
    921 	struct nvm_identify_namespace *identify;
    922 
    923 	ns = nvme_ns_get(sc, nsid);
    924 	KASSERT(ns);
    925 
    926 	identify = ns->ident;
    927 	ns->ident = NULL;
    928 	if (identify != NULL)
    929 		kmem_free(identify, sizeof(*identify));
    930 }
    931 
    932 static void
    933 nvme_pt_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    934 {
    935 	struct nvme_softc *sc = q->q_sc;
    936 	struct nvme_sqe *sqe = slot;
    937 	struct nvme_pt_command *pt = ccb->ccb_cookie;
    938 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    939 	int i;
    940 
    941 	sqe->opcode = pt->cmd.opcode;
    942 	htolem32(&sqe->nsid, pt->cmd.nsid);
    943 
    944 	if (pt->buf != NULL && pt->len > 0) {
    945 		htolem64(&sqe->entry.prp[0], dmap->dm_segs[0].ds_addr);
    946 		switch (dmap->dm_nsegs) {
    947 		case 1:
    948 			break;
    949 		case 2:
    950 			htolem64(&sqe->entry.prp[1], dmap->dm_segs[1].ds_addr);
    951 			break;
    952 		default:
    953 			for (i = 1; i < dmap->dm_nsegs; i++) {
    954 				htolem64(&ccb->ccb_prpl[i - 1],
    955 				    dmap->dm_segs[i].ds_addr);
    956 			}
    957 			bus_dmamap_sync(sc->sc_dmat,
    958 			    NVME_DMA_MAP(q->q_ccb_prpls),
    959 			    ccb->ccb_prpl_off,
    960 			    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    961 			    BUS_DMASYNC_PREWRITE);
    962 			htolem64(&sqe->entry.prp[1], ccb->ccb_prpl_dva);
    963 			break;
    964 		}
    965 	}
    966 
    967 	htolem32(&sqe->cdw10, pt->cmd.cdw10);
    968 	htolem32(&sqe->cdw11, pt->cmd.cdw11);
    969 	htolem32(&sqe->cdw12, pt->cmd.cdw12);
    970 	htolem32(&sqe->cdw13, pt->cmd.cdw13);
    971 	htolem32(&sqe->cdw14, pt->cmd.cdw14);
    972 	htolem32(&sqe->cdw15, pt->cmd.cdw15);
    973 }
    974 
    975 static void
    976 nvme_pt_done(struct nvme_queue *q, struct nvme_ccb *ccb, struct nvme_cqe *cqe)
    977 {
    978 	struct nvme_softc *sc = q->q_sc;
    979 	struct nvme_pt_command *pt = ccb->ccb_cookie;
    980 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    981 
    982 	if (pt->buf != NULL && pt->len > 0) {
    983 		if (dmap->dm_nsegs > 2) {
    984 			bus_dmamap_sync(sc->sc_dmat,
    985 			    NVME_DMA_MAP(q->q_ccb_prpls),
    986 			    ccb->ccb_prpl_off,
    987 			    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    988 			    BUS_DMASYNC_POSTWRITE);
    989 		}
    990 
    991 		bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
    992 		    pt->is_read ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
    993 		bus_dmamap_unload(sc->sc_dmat, dmap);
    994 	}
    995 
    996 	pt->cpl.cdw0 = lemtoh32(&cqe->cdw0);
    997 	pt->cpl.flags = lemtoh16(&cqe->flags) & ~NVME_CQE_PHASE;
    998 }
    999 
   1000 static int
   1001 nvme_command_passthrough(struct nvme_softc *sc, struct nvme_pt_command *pt,
   1002     uint16_t nsid, struct lwp *l, bool is_adminq)
   1003 {
   1004 	struct nvme_queue *q;
   1005 	struct nvme_ccb *ccb;
   1006 	void *buf = NULL;
   1007 	int error;
   1008 
   1009 	/* limit command size to maximum data transfer size */
   1010 	if ((pt->buf == NULL && pt->len > 0) ||
   1011 	    (pt->buf != NULL && (pt->len == 0 || pt->len > sc->sc_mdts)))
   1012 		return EINVAL;
   1013 
   1014 	q = is_adminq ? sc->sc_admin_q : nvme_get_q(sc);
   1015 	ccb = nvme_ccb_get(q, true);
   1016 	KASSERT(ccb != NULL);
   1017 
   1018 	if (pt->buf != NULL) {
   1019 		KASSERT(pt->len > 0);
   1020 		buf = kmem_alloc(pt->len, KM_SLEEP);
   1021 		if (!pt->is_read) {
   1022 			error = copyin(pt->buf, buf, pt->len);
   1023 			if (error)
   1024 				goto kmem_free;
   1025 		}
   1026 		error = bus_dmamap_load(sc->sc_dmat, ccb->ccb_dmamap, buf,
   1027 		    pt->len, NULL,
   1028 		    BUS_DMA_WAITOK |
   1029 		      (pt->is_read ? BUS_DMA_READ : BUS_DMA_WRITE));
   1030 		if (error)
   1031 			goto kmem_free;
   1032 		bus_dmamap_sync(sc->sc_dmat, ccb->ccb_dmamap,
   1033 		    0, ccb->ccb_dmamap->dm_mapsize,
   1034 		    pt->is_read ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
   1035 	}
   1036 
   1037 	ccb->ccb_done = nvme_pt_done;
   1038 	ccb->ccb_cookie = pt;
   1039 
   1040 	pt->cmd.nsid = nsid;
   1041 	if (nvme_poll(sc, q, ccb, nvme_pt_fill, NVME_TIMO_PT)) {
   1042 		error = EIO;
   1043 		goto out;
   1044 	}
   1045 
   1046 	error = 0;
   1047 out:
   1048 	if (buf != NULL) {
   1049 		if (error == 0 && pt->is_read)
   1050 			error = copyout(buf, pt->buf, pt->len);
   1051 kmem_free:
   1052 		kmem_free(buf, pt->len);
   1053 	}
   1054 	nvme_ccb_put(q, ccb);
   1055 	return error;
   1056 }
   1057 
   1058 static void
   1059 nvme_q_submit(struct nvme_softc *sc, struct nvme_queue *q, struct nvme_ccb *ccb,
   1060     void (*fill)(struct nvme_queue *, struct nvme_ccb *, void *))
   1061 {
   1062 	struct nvme_sqe *sqe = NVME_DMA_KVA(q->q_sq_dmamem);
   1063 	uint32_t tail;
   1064 
   1065 	mutex_enter(&q->q_sq_mtx);
   1066 	tail = q->q_sq_tail;
   1067 	if (++q->q_sq_tail >= q->q_entries)
   1068 		q->q_sq_tail = 0;
   1069 
   1070 	sqe += tail;
   1071 
   1072 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(q->q_sq_dmamem),
   1073 	    sizeof(*sqe) * tail, sizeof(*sqe), BUS_DMASYNC_POSTWRITE);
   1074 	memset(sqe, 0, sizeof(*sqe));
   1075 	(*fill)(q, ccb, sqe);
   1076 	sqe->cid = ccb->ccb_id;
   1077 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(q->q_sq_dmamem),
   1078 	    sizeof(*sqe) * tail, sizeof(*sqe), BUS_DMASYNC_PREWRITE);
   1079 
   1080 	nvme_write4(sc, q->q_sqtdbl, q->q_sq_tail);
   1081 	mutex_exit(&q->q_sq_mtx);
   1082 }
   1083 
   1084 struct nvme_poll_state {
   1085 	struct nvme_sqe s;
   1086 	struct nvme_cqe c;
   1087 	void *cookie;
   1088 	void (*done)(struct nvme_queue *, struct nvme_ccb *, struct nvme_cqe *);
   1089 };
   1090 
   1091 static int
   1092 nvme_poll(struct nvme_softc *sc, struct nvme_queue *q, struct nvme_ccb *ccb,
   1093     void (*fill)(struct nvme_queue *, struct nvme_ccb *, void *), int timo_sec)
   1094 {
   1095 	struct nvme_poll_state state;
   1096 	uint16_t flags;
   1097 	int step = 10;
   1098 	int maxloop = timo_sec * 1000000 / step;
   1099 	int error = 0;
   1100 
   1101 	memset(&state, 0, sizeof(state));
   1102 	(*fill)(q, ccb, &state.s);
   1103 
   1104 	state.done = ccb->ccb_done;
   1105 	state.cookie = ccb->ccb_cookie;
   1106 
   1107 	ccb->ccb_done = nvme_poll_done;
   1108 	ccb->ccb_cookie = &state;
   1109 
   1110 	nvme_q_submit(sc, q, ccb, nvme_poll_fill);
   1111 	while (!ISSET(state.c.flags, htole16(NVME_CQE_PHASE))) {
   1112 		if (nvme_q_complete(sc, q) == 0)
   1113 			delay(step);
   1114 
   1115 		if (timo_sec >= 0 && --maxloop <= 0) {
   1116 			error = ETIMEDOUT;
   1117 			break;
   1118 		}
   1119 	}
   1120 
   1121 	if (error == 0) {
   1122 		flags = lemtoh16(&state.c.flags);
   1123 		return flags & ~NVME_CQE_PHASE;
   1124 	} else {
   1125 		/*
   1126 		 * If it succeds later, it would hit ccb which will have been
   1127 		 * already reused for something else. Not good. Cross
   1128 		 * fingers and hope for best. XXX do controller reset?
   1129 		 */
   1130 		aprint_error_dev(sc->sc_dev, "polled command timed out\n");
   1131 
   1132 		/* Invoke the callback to clean state anyway */
   1133 		struct nvme_cqe cqe;
   1134 		memset(&cqe, 0, sizeof(cqe));
   1135 		ccb->ccb_done(q, ccb, &cqe);
   1136 
   1137 		return 1;
   1138 	}
   1139 }
   1140 
   1141 static void
   1142 nvme_poll_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1143 {
   1144 	struct nvme_sqe *sqe = slot;
   1145 	struct nvme_poll_state *state = ccb->ccb_cookie;
   1146 
   1147 	*sqe = state->s;
   1148 }
   1149 
   1150 static void
   1151 nvme_poll_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1152     struct nvme_cqe *cqe)
   1153 {
   1154 	struct nvme_poll_state *state = ccb->ccb_cookie;
   1155 
   1156 	SET(cqe->flags, htole16(NVME_CQE_PHASE));
   1157 	state->c = *cqe;
   1158 
   1159 	ccb->ccb_cookie = state->cookie;
   1160 	state->done(q, ccb, &state->c);
   1161 }
   1162 
   1163 static void
   1164 nvme_sqe_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1165 {
   1166 	struct nvme_sqe *src = ccb->ccb_cookie;
   1167 	struct nvme_sqe *dst = slot;
   1168 
   1169 	*dst = *src;
   1170 }
   1171 
   1172 static void
   1173 nvme_empty_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1174     struct nvme_cqe *cqe)
   1175 {
   1176 }
   1177 
   1178 static int
   1179 nvme_q_complete(struct nvme_softc *sc, struct nvme_queue *q)
   1180 {
   1181 	struct nvme_ccb *ccb;
   1182 	struct nvme_cqe *ring = NVME_DMA_KVA(q->q_cq_dmamem), *cqe;
   1183 	uint16_t flags;
   1184 	int rv = 0;
   1185 
   1186 	mutex_enter(&q->q_cq_mtx);
   1187 
   1188 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_POSTREAD);
   1189 	for (;;) {
   1190 		cqe = &ring[q->q_cq_head];
   1191 		flags = lemtoh16(&cqe->flags);
   1192 		if ((flags & NVME_CQE_PHASE) != q->q_cq_phase)
   1193 			break;
   1194 
   1195 		ccb = &q->q_ccbs[cqe->cid];
   1196 
   1197 		if (++q->q_cq_head >= q->q_entries) {
   1198 			q->q_cq_head = 0;
   1199 			q->q_cq_phase ^= NVME_CQE_PHASE;
   1200 		}
   1201 
   1202 #ifdef DEBUG
   1203 		/*
   1204 		 * If we get spurious completion notification, something
   1205 		 * is seriously hosed up. Very likely DMA to some random
   1206 		 * memory place happened, so just bail out.
   1207 		 */
   1208 		if ((intptr_t)ccb->ccb_cookie == NVME_CCB_FREE) {
   1209 			panic("%s: invalid ccb detected",
   1210 			    device_xname(sc->sc_dev));
   1211 			/* NOTREACHED */
   1212 		}
   1213 #endif
   1214 
   1215 		rv++;
   1216 
   1217 		/*
   1218 		 * Unlock the mutex before calling the ccb_done callback
   1219 		 * and re-lock afterwards. The callback triggers lddone()
   1220 		 * which schedules another i/o, and also calls nvme_ccb_put().
   1221 		 * Unlock/relock avoids possibility of deadlock.
   1222 		 */
   1223 		mutex_exit(&q->q_cq_mtx);
   1224 		ccb->ccb_done(q, ccb, cqe);
   1225 		mutex_enter(&q->q_cq_mtx);
   1226 	}
   1227 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_PREREAD);
   1228 
   1229 	if (rv)
   1230 		nvme_write4(sc, q->q_cqhdbl, q->q_cq_head);
   1231 
   1232 	mutex_exit(&q->q_cq_mtx);
   1233 
   1234 	return rv;
   1235 }
   1236 
   1237 static void
   1238 nvme_q_wait_complete(struct nvme_softc *sc,
   1239     struct nvme_queue *q, bool (*finished)(void *), void *cookie)
   1240 {
   1241 	mutex_enter(&q->q_ccb_mtx);
   1242 	if (finished(cookie))
   1243 		goto out;
   1244 
   1245 	for(;;) {
   1246 		q->q_ccb_waiting = true;
   1247 		cv_wait(&q->q_ccb_wait, &q->q_ccb_mtx);
   1248 
   1249 		if (finished(cookie))
   1250 			break;
   1251 	}
   1252 
   1253 out:
   1254 	mutex_exit(&q->q_ccb_mtx);
   1255 }
   1256 
   1257 static int
   1258 nvme_identify(struct nvme_softc *sc, u_int mps)
   1259 {
   1260 	char sn[41], mn[81], fr[17];
   1261 	struct nvm_identify_controller *identify;
   1262 	struct nvme_dmamem *mem;
   1263 	struct nvme_ccb *ccb;
   1264 	u_int mdts;
   1265 	int rv = 1;
   1266 
   1267 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1268 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
   1269 
   1270 	mem = nvme_dmamem_alloc(sc, sizeof(*identify));
   1271 	if (mem == NULL)
   1272 		return 1;
   1273 
   1274 	ccb->ccb_done = nvme_empty_done;
   1275 	ccb->ccb_cookie = mem;
   1276 
   1277 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_PREREAD);
   1278 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_fill_identify,
   1279 	    NVME_TIMO_IDENT);
   1280 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_POSTREAD);
   1281 
   1282 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1283 
   1284 	if (rv != 0)
   1285 		goto done;
   1286 
   1287 	identify = NVME_DMA_KVA(mem);
   1288 
   1289 	strnvisx(sn, sizeof(sn), (const char *)identify->sn,
   1290 	    sizeof(identify->sn), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1291 	strnvisx(mn, sizeof(mn), (const char *)identify->mn,
   1292 	    sizeof(identify->mn), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1293 	strnvisx(fr, sizeof(fr), (const char *)identify->fr,
   1294 	    sizeof(identify->fr), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1295 	aprint_normal_dev(sc->sc_dev, "%s, firmware %s, serial %s\n", mn, fr,
   1296 	    sn);
   1297 
   1298 	if (identify->mdts > 0) {
   1299 		mdts = (1 << identify->mdts) * (1 << mps);
   1300 		if (mdts < sc->sc_mdts)
   1301 			sc->sc_mdts = mdts;
   1302 	}
   1303 
   1304 	sc->sc_nn = lemtoh32(&identify->nn);
   1305 
   1306 	memcpy(&sc->sc_identify, identify, sizeof(sc->sc_identify));
   1307 
   1308 done:
   1309 	nvme_dmamem_free(sc, mem);
   1310 
   1311 	return rv;
   1312 }
   1313 
   1314 static int
   1315 nvme_q_create(struct nvme_softc *sc, struct nvme_queue *q)
   1316 {
   1317 	struct nvme_sqe_q sqe;
   1318 	struct nvme_ccb *ccb;
   1319 	int rv;
   1320 
   1321 	if (sc->sc_use_mq && sc->sc_intr_establish(sc, q->q_id, q) != 0)
   1322 		return 1;
   1323 
   1324 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1325 	KASSERT(ccb != NULL);
   1326 
   1327 	ccb->ccb_done = nvme_empty_done;
   1328 	ccb->ccb_cookie = &sqe;
   1329 
   1330 	memset(&sqe, 0, sizeof(sqe));
   1331 	sqe.opcode = NVM_ADMIN_ADD_IOCQ;
   1332 	htolem64(&sqe.prp1, NVME_DMA_DVA(q->q_cq_dmamem));
   1333 	htolem16(&sqe.qsize, q->q_entries - 1);
   1334 	htolem16(&sqe.qid, q->q_id);
   1335 	sqe.qflags = NVM_SQE_CQ_IEN | NVM_SQE_Q_PC;
   1336 	if (sc->sc_use_mq)
   1337 		htolem16(&sqe.cqid, q->q_id);	/* qid == vector */
   1338 
   1339 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1340 	if (rv != 0)
   1341 		goto fail;
   1342 
   1343 	ccb->ccb_done = nvme_empty_done;
   1344 	ccb->ccb_cookie = &sqe;
   1345 
   1346 	memset(&sqe, 0, sizeof(sqe));
   1347 	sqe.opcode = NVM_ADMIN_ADD_IOSQ;
   1348 	htolem64(&sqe.prp1, NVME_DMA_DVA(q->q_sq_dmamem));
   1349 	htolem16(&sqe.qsize, q->q_entries - 1);
   1350 	htolem16(&sqe.qid, q->q_id);
   1351 	htolem16(&sqe.cqid, q->q_id);
   1352 	sqe.qflags = NVM_SQE_Q_PC;
   1353 
   1354 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1355 	if (rv != 0)
   1356 		goto fail;
   1357 
   1358 fail:
   1359 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1360 	return rv;
   1361 }
   1362 
   1363 static int
   1364 nvme_q_delete(struct nvme_softc *sc, struct nvme_queue *q)
   1365 {
   1366 	struct nvme_sqe_q sqe;
   1367 	struct nvme_ccb *ccb;
   1368 	int rv;
   1369 
   1370 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1371 	KASSERT(ccb != NULL);
   1372 
   1373 	ccb->ccb_done = nvme_empty_done;
   1374 	ccb->ccb_cookie = &sqe;
   1375 
   1376 	memset(&sqe, 0, sizeof(sqe));
   1377 	sqe.opcode = NVM_ADMIN_DEL_IOSQ;
   1378 	htolem16(&sqe.qid, q->q_id);
   1379 
   1380 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1381 	if (rv != 0)
   1382 		goto fail;
   1383 
   1384 	ccb->ccb_done = nvme_empty_done;
   1385 	ccb->ccb_cookie = &sqe;
   1386 
   1387 	memset(&sqe, 0, sizeof(sqe));
   1388 	sqe.opcode = NVM_ADMIN_DEL_IOCQ;
   1389 	htolem16(&sqe.qid, q->q_id);
   1390 
   1391 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1392 	if (rv != 0)
   1393 		goto fail;
   1394 
   1395 fail:
   1396 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1397 
   1398 	if (rv == 0 && sc->sc_use_mq) {
   1399 		if (sc->sc_intr_disestablish(sc, q->q_id))
   1400 			rv = 1;
   1401 	}
   1402 
   1403 	return rv;
   1404 }
   1405 
   1406 static void
   1407 nvme_fill_identify(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1408 {
   1409 	struct nvme_sqe *sqe = slot;
   1410 	struct nvme_dmamem *mem = ccb->ccb_cookie;
   1411 
   1412 	sqe->opcode = NVM_ADMIN_IDENTIFY;
   1413 	htolem64(&sqe->entry.prp[0], NVME_DMA_DVA(mem));
   1414 	htolem32(&sqe->cdw10, 1);
   1415 }
   1416 
   1417 static int
   1418 nvme_get_number_of_queues(struct nvme_softc *sc, u_int *nqap)
   1419 {
   1420 	struct nvme_pt_command pt;
   1421 	struct nvme_ccb *ccb;
   1422 	uint16_t ncqa, nsqa;
   1423 	int rv;
   1424 
   1425 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1426 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
   1427 
   1428 	memset(&pt, 0, sizeof(pt));
   1429 	pt.cmd.opcode = NVM_ADMIN_GET_FEATURES;
   1430 	pt.cmd.cdw10 = NVM_FEATURE_NUMBER_OF_QUEUES;
   1431 
   1432 	ccb->ccb_done = nvme_pt_done;
   1433 	ccb->ccb_cookie = &pt;
   1434 
   1435 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_pt_fill, NVME_TIMO_QOP);
   1436 
   1437 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1438 
   1439 	if (rv != 0) {
   1440 		*nqap = 0;
   1441 		return EIO;
   1442 	}
   1443 
   1444 	ncqa = pt.cpl.cdw0 >> 16;
   1445 	nsqa = pt.cpl.cdw0 & 0xffff;
   1446 	*nqap = MIN(ncqa, nsqa) + 1;
   1447 
   1448 	return 0;
   1449 }
   1450 
   1451 static int
   1452 nvme_ccbs_alloc(struct nvme_queue *q, uint16_t nccbs)
   1453 {
   1454 	struct nvme_softc *sc = q->q_sc;
   1455 	struct nvme_ccb *ccb;
   1456 	bus_addr_t off;
   1457 	uint64_t *prpl;
   1458 	u_int i;
   1459 
   1460 	mutex_init(&q->q_ccb_mtx, MUTEX_DEFAULT, IPL_BIO);
   1461 	cv_init(&q->q_ccb_wait, "nvmeqw");
   1462 	q->q_ccb_waiting = false;
   1463 	SIMPLEQ_INIT(&q->q_ccb_list);
   1464 
   1465 	q->q_ccbs = kmem_alloc(sizeof(*ccb) * nccbs, KM_SLEEP);
   1466 
   1467 	q->q_nccbs = nccbs;
   1468 	q->q_ccb_prpls = nvme_dmamem_alloc(sc,
   1469 	    sizeof(*prpl) * sc->sc_max_sgl * nccbs);
   1470 
   1471 	prpl = NVME_DMA_KVA(q->q_ccb_prpls);
   1472 	off = 0;
   1473 
   1474 	for (i = 0; i < nccbs; i++) {
   1475 		ccb = &q->q_ccbs[i];
   1476 
   1477 		if (bus_dmamap_create(sc->sc_dmat, sc->sc_mdts,
   1478 		    sc->sc_max_sgl + 1 /* we get a free prp in the sqe */,
   1479 		    sc->sc_mps, sc->sc_mps, BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW,
   1480 		    &ccb->ccb_dmamap) != 0)
   1481 			goto free_maps;
   1482 
   1483 		ccb->ccb_id = i;
   1484 		ccb->ccb_prpl = prpl;
   1485 		ccb->ccb_prpl_off = off;
   1486 		ccb->ccb_prpl_dva = NVME_DMA_DVA(q->q_ccb_prpls) + off;
   1487 
   1488 		SIMPLEQ_INSERT_TAIL(&q->q_ccb_list, ccb, ccb_entry);
   1489 
   1490 		prpl += sc->sc_max_sgl;
   1491 		off += sizeof(*prpl) * sc->sc_max_sgl;
   1492 	}
   1493 
   1494 	return 0;
   1495 
   1496 free_maps:
   1497 	nvme_ccbs_free(q);
   1498 	return 1;
   1499 }
   1500 
   1501 static struct nvme_ccb *
   1502 nvme_ccb_get(struct nvme_queue *q, bool wait)
   1503 {
   1504 	struct nvme_ccb *ccb = NULL;
   1505 
   1506 	mutex_enter(&q->q_ccb_mtx);
   1507 again:
   1508 	ccb = SIMPLEQ_FIRST(&q->q_ccb_list);
   1509 	if (ccb != NULL) {
   1510 		SIMPLEQ_REMOVE_HEAD(&q->q_ccb_list, ccb_entry);
   1511 #ifdef DEBUG
   1512 		ccb->ccb_cookie = NULL;
   1513 #endif
   1514 	} else {
   1515 		if (__predict_false(wait)) {
   1516 			q->q_ccb_waiting = true;
   1517 			cv_wait(&q->q_ccb_wait, &q->q_ccb_mtx);
   1518 			goto again;
   1519 		}
   1520 	}
   1521 	mutex_exit(&q->q_ccb_mtx);
   1522 
   1523 	return ccb;
   1524 }
   1525 
   1526 static void
   1527 nvme_ccb_put(struct nvme_queue *q, struct nvme_ccb *ccb)
   1528 {
   1529 
   1530 	mutex_enter(&q->q_ccb_mtx);
   1531 #ifdef DEBUG
   1532 	ccb->ccb_cookie = (void *)NVME_CCB_FREE;
   1533 #endif
   1534 	SIMPLEQ_INSERT_HEAD(&q->q_ccb_list, ccb, ccb_entry);
   1535 
   1536 	/* It's unlikely there are any waiters, it's not used for regular I/O */
   1537 	if (__predict_false(q->q_ccb_waiting)) {
   1538 		q->q_ccb_waiting = false;
   1539 		cv_broadcast(&q->q_ccb_wait);
   1540 	}
   1541 
   1542 	mutex_exit(&q->q_ccb_mtx);
   1543 }
   1544 
   1545 static void
   1546 nvme_ccbs_free(struct nvme_queue *q)
   1547 {
   1548 	struct nvme_softc *sc = q->q_sc;
   1549 	struct nvme_ccb *ccb;
   1550 
   1551 	mutex_enter(&q->q_ccb_mtx);
   1552 	while ((ccb = SIMPLEQ_FIRST(&q->q_ccb_list)) != NULL) {
   1553 		SIMPLEQ_REMOVE_HEAD(&q->q_ccb_list, ccb_entry);
   1554 		bus_dmamap_destroy(sc->sc_dmat, ccb->ccb_dmamap);
   1555 	}
   1556 	mutex_exit(&q->q_ccb_mtx);
   1557 
   1558 	nvme_dmamem_free(sc, q->q_ccb_prpls);
   1559 	kmem_free(q->q_ccbs, sizeof(*ccb) * q->q_nccbs);
   1560 	q->q_ccbs = NULL;
   1561 	cv_destroy(&q->q_ccb_wait);
   1562 	mutex_destroy(&q->q_ccb_mtx);
   1563 }
   1564 
   1565 static struct nvme_queue *
   1566 nvme_q_alloc(struct nvme_softc *sc, uint16_t id, u_int entries, u_int dstrd)
   1567 {
   1568 	struct nvme_queue *q;
   1569 
   1570 	q = kmem_alloc(sizeof(*q), KM_SLEEP);
   1571 	q->q_sc = sc;
   1572 	q->q_sq_dmamem = nvme_dmamem_alloc(sc,
   1573 	    sizeof(struct nvme_sqe) * entries);
   1574 	if (q->q_sq_dmamem == NULL)
   1575 		goto free;
   1576 
   1577 	q->q_cq_dmamem = nvme_dmamem_alloc(sc,
   1578 	    sizeof(struct nvme_cqe) * entries);
   1579 	if (q->q_cq_dmamem == NULL)
   1580 		goto free_sq;
   1581 
   1582 	memset(NVME_DMA_KVA(q->q_sq_dmamem), 0, NVME_DMA_LEN(q->q_sq_dmamem));
   1583 	memset(NVME_DMA_KVA(q->q_cq_dmamem), 0, NVME_DMA_LEN(q->q_cq_dmamem));
   1584 
   1585 	mutex_init(&q->q_sq_mtx, MUTEX_DEFAULT, IPL_BIO);
   1586 	mutex_init(&q->q_cq_mtx, MUTEX_DEFAULT, IPL_BIO);
   1587 	q->q_sqtdbl = NVME_SQTDBL(id, dstrd);
   1588 	q->q_cqhdbl = NVME_CQHDBL(id, dstrd);
   1589 	q->q_id = id;
   1590 	q->q_entries = entries;
   1591 	q->q_sq_tail = 0;
   1592 	q->q_cq_head = 0;
   1593 	q->q_cq_phase = NVME_CQE_PHASE;
   1594 
   1595 	nvme_dmamem_sync(sc, q->q_sq_dmamem, BUS_DMASYNC_PREWRITE);
   1596 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_PREREAD);
   1597 
   1598 	/*
   1599 	 * Due to definition of full and empty queue (queue is empty
   1600 	 * when head == tail, full when tail is one less then head),
   1601 	 * we can actually only have (entries - 1) in-flight commands.
   1602 	 */
   1603 	if (nvme_ccbs_alloc(q, entries - 1) != 0) {
   1604 		aprint_error_dev(sc->sc_dev, "unable to allocate ccbs\n");
   1605 		goto free_cq;
   1606 	}
   1607 
   1608 	return q;
   1609 
   1610 free_cq:
   1611 	nvme_dmamem_free(sc, q->q_cq_dmamem);
   1612 free_sq:
   1613 	nvme_dmamem_free(sc, q->q_sq_dmamem);
   1614 free:
   1615 	kmem_free(q, sizeof(*q));
   1616 
   1617 	return NULL;
   1618 }
   1619 
   1620 static void
   1621 nvme_q_free(struct nvme_softc *sc, struct nvme_queue *q)
   1622 {
   1623 	nvme_ccbs_free(q);
   1624 	mutex_destroy(&q->q_sq_mtx);
   1625 	mutex_destroy(&q->q_cq_mtx);
   1626 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_POSTREAD);
   1627 	nvme_dmamem_sync(sc, q->q_sq_dmamem, BUS_DMASYNC_POSTWRITE);
   1628 	nvme_dmamem_free(sc, q->q_cq_dmamem);
   1629 	nvme_dmamem_free(sc, q->q_sq_dmamem);
   1630 	kmem_free(q, sizeof(*q));
   1631 }
   1632 
   1633 int
   1634 nvme_intr(void *xsc)
   1635 {
   1636 	struct nvme_softc *sc = xsc;
   1637 
   1638 	/*
   1639 	 * INTx is level triggered, controller deasserts the interrupt only
   1640 	 * when we advance command queue head via write to the doorbell.
   1641 	 * Tell the controller to block the interrupts while we process
   1642 	 * the queue(s).
   1643 	 */
   1644 	nvme_write4(sc, NVME_INTMS, 1);
   1645 
   1646 	softint_schedule(sc->sc_softih[0]);
   1647 
   1648 	/* don't know, might not have been for us */
   1649 	return 1;
   1650 }
   1651 
   1652 void
   1653 nvme_softintr_intx(void *xq)
   1654 {
   1655 	struct nvme_queue *q = xq;
   1656 	struct nvme_softc *sc = q->q_sc;
   1657 
   1658 	nvme_q_complete(sc, sc->sc_admin_q);
   1659 	if (sc->sc_q != NULL)
   1660 	        nvme_q_complete(sc, sc->sc_q[0]);
   1661 
   1662 	/*
   1663 	 * Processing done, tell controller to issue interrupts again. There
   1664 	 * is no race, as NVMe spec requires the controller to maintain state,
   1665 	 * and assert the interrupt whenever there are unacknowledged
   1666 	 * completion queue entries.
   1667 	 */
   1668 	nvme_write4(sc, NVME_INTMC, 1);
   1669 }
   1670 
   1671 int
   1672 nvme_intr_msi(void *xq)
   1673 {
   1674 	struct nvme_queue *q = xq;
   1675 
   1676 	KASSERT(q && q->q_sc && q->q_sc->sc_softih
   1677 	    && q->q_sc->sc_softih[q->q_id]);
   1678 
   1679 	/*
   1680 	 * MSI/MSI-X are edge triggered, so can handover processing to softint
   1681 	 * without masking the interrupt.
   1682 	 */
   1683 	softint_schedule(q->q_sc->sc_softih[q->q_id]);
   1684 
   1685 	return 1;
   1686 }
   1687 
   1688 void
   1689 nvme_softintr_msi(void *xq)
   1690 {
   1691 	struct nvme_queue *q = xq;
   1692 	struct nvme_softc *sc = q->q_sc;
   1693 
   1694 	nvme_q_complete(sc, q);
   1695 }
   1696 
   1697 static struct nvme_dmamem *
   1698 nvme_dmamem_alloc(struct nvme_softc *sc, size_t size)
   1699 {
   1700 	struct nvme_dmamem *ndm;
   1701 	int nsegs;
   1702 
   1703 	ndm = kmem_zalloc(sizeof(*ndm), KM_SLEEP);
   1704 	if (ndm == NULL)
   1705 		return NULL;
   1706 
   1707 	ndm->ndm_size = size;
   1708 
   1709 	if (bus_dmamap_create(sc->sc_dmat, size, 1, size, 0,
   1710 	    BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, &ndm->ndm_map) != 0)
   1711 		goto ndmfree;
   1712 
   1713 	if (bus_dmamem_alloc(sc->sc_dmat, size, sc->sc_mps, 0, &ndm->ndm_seg,
   1714 	    1, &nsegs, BUS_DMA_WAITOK) != 0)
   1715 		goto destroy;
   1716 
   1717 	if (bus_dmamem_map(sc->sc_dmat, &ndm->ndm_seg, nsegs, size,
   1718 	    &ndm->ndm_kva, BUS_DMA_WAITOK) != 0)
   1719 		goto free;
   1720 	memset(ndm->ndm_kva, 0, size);
   1721 
   1722 	if (bus_dmamap_load(sc->sc_dmat, ndm->ndm_map, ndm->ndm_kva, size,
   1723 	    NULL, BUS_DMA_WAITOK) != 0)
   1724 		goto unmap;
   1725 
   1726 	return ndm;
   1727 
   1728 unmap:
   1729 	bus_dmamem_unmap(sc->sc_dmat, ndm->ndm_kva, size);
   1730 free:
   1731 	bus_dmamem_free(sc->sc_dmat, &ndm->ndm_seg, 1);
   1732 destroy:
   1733 	bus_dmamap_destroy(sc->sc_dmat, ndm->ndm_map);
   1734 ndmfree:
   1735 	kmem_free(ndm, sizeof(*ndm));
   1736 	return NULL;
   1737 }
   1738 
   1739 static void
   1740 nvme_dmamem_sync(struct nvme_softc *sc, struct nvme_dmamem *mem, int ops)
   1741 {
   1742 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(mem),
   1743 	    0, NVME_DMA_LEN(mem), ops);
   1744 }
   1745 
   1746 void
   1747 nvme_dmamem_free(struct nvme_softc *sc, struct nvme_dmamem *ndm)
   1748 {
   1749 	bus_dmamap_unload(sc->sc_dmat, ndm->ndm_map);
   1750 	bus_dmamem_unmap(sc->sc_dmat, ndm->ndm_kva, ndm->ndm_size);
   1751 	bus_dmamem_free(sc->sc_dmat, &ndm->ndm_seg, 1);
   1752 	bus_dmamap_destroy(sc->sc_dmat, ndm->ndm_map);
   1753 	kmem_free(ndm, sizeof(*ndm));
   1754 }
   1755 
   1756 /*
   1757  * ioctl
   1758  */
   1759 
   1760 dev_type_open(nvmeopen);
   1761 dev_type_close(nvmeclose);
   1762 dev_type_ioctl(nvmeioctl);
   1763 
   1764 const struct cdevsw nvme_cdevsw = {
   1765 	.d_open = nvmeopen,
   1766 	.d_close = nvmeclose,
   1767 	.d_read = noread,
   1768 	.d_write = nowrite,
   1769 	.d_ioctl = nvmeioctl,
   1770 	.d_stop = nostop,
   1771 	.d_tty = notty,
   1772 	.d_poll = nopoll,
   1773 	.d_mmap = nommap,
   1774 	.d_kqfilter = nokqfilter,
   1775 	.d_discard = nodiscard,
   1776 	.d_flag = D_OTHER,
   1777 };
   1778 
   1779 /*
   1780  * Accept an open operation on the control device.
   1781  */
   1782 int
   1783 nvmeopen(dev_t dev, int flag, int mode, struct lwp *l)
   1784 {
   1785 	struct nvme_softc *sc;
   1786 	int unit = minor(dev) / 0x10000;
   1787 	int nsid = minor(dev) & 0xffff;
   1788 	int nsidx;
   1789 
   1790 	if ((sc = device_lookup_private(&nvme_cd, unit)) == NULL)
   1791 		return ENXIO;
   1792 	if ((sc->sc_flags & NVME_F_ATTACHED) == 0)
   1793 		return ENXIO;
   1794 
   1795 	if (nsid == 0) {
   1796 		/* controller */
   1797 		if (ISSET(sc->sc_flags, NVME_F_OPEN))
   1798 			return EBUSY;
   1799 		SET(sc->sc_flags, NVME_F_OPEN);
   1800 	} else {
   1801 		/* namespace */
   1802 		nsidx = nsid - 1;
   1803 		if (nsidx >= sc->sc_nn || sc->sc_namespaces[nsidx].dev == NULL)
   1804 			return ENXIO;
   1805 		if (ISSET(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN))
   1806 			return EBUSY;
   1807 		SET(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN);
   1808 	}
   1809 	return 0;
   1810 }
   1811 
   1812 /*
   1813  * Accept the last close on the control device.
   1814  */
   1815 int
   1816 nvmeclose(dev_t dev, int flag, int mode, struct lwp *l)
   1817 {
   1818 	struct nvme_softc *sc;
   1819 	int unit = minor(dev) / 0x10000;
   1820 	int nsid = minor(dev) & 0xffff;
   1821 	int nsidx;
   1822 
   1823 	sc = device_lookup_private(&nvme_cd, unit);
   1824 	if (sc == NULL)
   1825 		return ENXIO;
   1826 
   1827 	if (nsid == 0) {
   1828 		/* controller */
   1829 		CLR(sc->sc_flags, NVME_F_OPEN);
   1830 	} else {
   1831 		/* namespace */
   1832 		nsidx = nsid - 1;
   1833 		if (nsidx >= sc->sc_nn)
   1834 			return ENXIO;
   1835 		CLR(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN);
   1836 	}
   1837 
   1838 	return 0;
   1839 }
   1840 
   1841 /*
   1842  * Handle control operations.
   1843  */
   1844 int
   1845 nvmeioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
   1846 {
   1847 	struct nvme_softc *sc;
   1848 	int unit = minor(dev) / 0x10000;
   1849 	int nsid = minor(dev) & 0xffff;
   1850 	struct nvme_pt_command *pt;
   1851 
   1852 	sc = device_lookup_private(&nvme_cd, unit);
   1853 	if (sc == NULL)
   1854 		return ENXIO;
   1855 
   1856 	switch (cmd) {
   1857 	case NVME_PASSTHROUGH_CMD:
   1858 		pt = data;
   1859 		return nvme_command_passthrough(sc, data,
   1860 		    nsid == 0 ? pt->cmd.nsid : nsid, l, nsid == 0);
   1861 	}
   1862 
   1863 	return ENOTTY;
   1864 }
   1865