Home | History | Annotate | Line # | Download | only in ic
nvme.c revision 1.67.4.1
      1 /*	$NetBSD: nvme.c,v 1.67.4.1 2024/03/12 09:58:26 martin 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.67.4.1 2024/03/12 09:58:26 martin 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 #include "locators.h"
     45 
     46 #define	B4_CHK_RDY_DELAY_MS	2300	/* workaround controller bug */
     47 
     48 int nvme_adminq_size = 32;
     49 int nvme_ioq_size = 1024;
     50 
     51 static int	nvme_print(void *, const char *);
     52 
     53 static int	nvme_ready(struct nvme_softc *, uint32_t);
     54 static int	nvme_enable(struct nvme_softc *, u_int);
     55 static int	nvme_disable(struct nvme_softc *);
     56 static int	nvme_shutdown(struct nvme_softc *);
     57 
     58 uint32_t	nvme_op_sq_enter(struct nvme_softc *,
     59 		    struct nvme_queue *, struct nvme_ccb *);
     60 void		nvme_op_sq_leave(struct nvme_softc *,
     61 		    struct nvme_queue *, struct nvme_ccb *);
     62 uint32_t	nvme_op_sq_enter_locked(struct nvme_softc *,
     63 		    struct nvme_queue *, struct nvme_ccb *);
     64 void		nvme_op_sq_leave_locked(struct nvme_softc *,
     65 		    struct nvme_queue *, struct nvme_ccb *);
     66 
     67 void		nvme_op_cq_done(struct nvme_softc *,
     68 		    struct nvme_queue *, struct nvme_ccb *);
     69 
     70 static const struct nvme_ops nvme_ops = {
     71 	.op_sq_enter		= nvme_op_sq_enter,
     72 	.op_sq_leave		= nvme_op_sq_leave,
     73 	.op_sq_enter_locked	= nvme_op_sq_enter_locked,
     74 	.op_sq_leave_locked	= nvme_op_sq_leave_locked,
     75 
     76 	.op_cq_done		= nvme_op_cq_done,
     77 };
     78 
     79 #ifdef NVME_DEBUG
     80 static void	nvme_dumpregs(struct nvme_softc *);
     81 #endif
     82 static int	nvme_identify(struct nvme_softc *, u_int);
     83 static void	nvme_fill_identify(struct nvme_queue *, struct nvme_ccb *,
     84 		    void *);
     85 
     86 static int	nvme_ccbs_alloc(struct nvme_queue *, uint16_t);
     87 static void	nvme_ccbs_free(struct nvme_queue *);
     88 
     89 static struct nvme_ccb *
     90 		nvme_ccb_get(struct nvme_queue *, bool);
     91 static struct nvme_ccb *
     92 		nvme_ccb_get_bio(struct nvme_softc *, struct buf *,
     93 		    struct nvme_queue **);
     94 static void	nvme_ccb_put(struct nvme_queue *, struct nvme_ccb *);
     95 
     96 static int	nvme_poll(struct nvme_softc *, struct nvme_queue *,
     97 		    struct nvme_ccb *, void (*)(struct nvme_queue *,
     98 		    struct nvme_ccb *, void *), int);
     99 static void	nvme_poll_fill(struct nvme_queue *, struct nvme_ccb *, void *);
    100 static void	nvme_poll_done(struct nvme_queue *, struct nvme_ccb *,
    101 		    struct nvme_cqe *);
    102 static void	nvme_sqe_fill(struct nvme_queue *, struct nvme_ccb *, void *);
    103 static void	nvme_empty_done(struct nvme_queue *, struct nvme_ccb *,
    104 		    struct nvme_cqe *);
    105 
    106 static struct nvme_queue *
    107 		nvme_q_alloc(struct nvme_softc *, uint16_t, u_int, u_int);
    108 static int	nvme_q_create(struct nvme_softc *, struct nvme_queue *);
    109 static void	nvme_q_reset(struct nvme_softc *, struct nvme_queue *);
    110 static int	nvme_q_delete(struct nvme_softc *, struct nvme_queue *);
    111 static void	nvme_q_submit(struct nvme_softc *, struct nvme_queue *,
    112 		    struct nvme_ccb *, void (*)(struct nvme_queue *,
    113 		    struct nvme_ccb *, void *));
    114 static int	nvme_q_complete(struct nvme_softc *, struct nvme_queue *q);
    115 static void	nvme_q_free(struct nvme_softc *, struct nvme_queue *);
    116 static void	nvme_q_wait_complete(struct nvme_softc *, struct nvme_queue *,
    117 		    bool (*)(void *), void *);
    118 
    119 static void	nvme_ns_io_fill(struct nvme_queue *, struct nvme_ccb *,
    120 		    void *);
    121 static void	nvme_ns_io_done(struct nvme_queue *, struct nvme_ccb *,
    122 		    struct nvme_cqe *);
    123 static void	nvme_ns_sync_fill(struct nvme_queue *, struct nvme_ccb *,
    124 		    void *);
    125 static void	nvme_ns_sync_done(struct nvme_queue *, struct nvme_ccb *,
    126 		    struct nvme_cqe *);
    127 static void	nvme_getcache_fill(struct nvme_queue *, struct nvme_ccb *,
    128 		    void *);
    129 static void	nvme_getcache_done(struct nvme_queue *, struct nvme_ccb *,
    130 		    struct nvme_cqe *);
    131 
    132 static void	nvme_pt_fill(struct nvme_queue *, struct nvme_ccb *,
    133 		    void *);
    134 static void	nvme_pt_done(struct nvme_queue *, struct nvme_ccb *,
    135 		    struct nvme_cqe *);
    136 static int	nvme_command_passthrough(struct nvme_softc *,
    137 		    struct nvme_pt_command *, uint32_t, struct lwp *, bool);
    138 
    139 static int	nvme_set_number_of_queues(struct nvme_softc *, u_int, u_int *,
    140 		    u_int *);
    141 
    142 #define NVME_TIMO_QOP		5	/* queue create and delete timeout */
    143 #define NVME_TIMO_IDENT		10	/* probe identify timeout */
    144 #define NVME_TIMO_PT		-1	/* passthrough cmd timeout */
    145 #define NVME_TIMO_SY		60	/* sync cache timeout */
    146 
    147 /*
    148  * Some controllers, at least Apple NVMe, always require split
    149  * transfers, so don't use bus_space_{read,write}_8() on LP64.
    150  */
    151 uint64_t
    152 nvme_read8(struct nvme_softc *sc, bus_size_t r)
    153 {
    154 	uint64_t v;
    155 	uint32_t *a = (uint32_t *)&v;
    156 
    157 #if _BYTE_ORDER == _LITTLE_ENDIAN
    158 	a[0] = nvme_read4(sc, r);
    159 	a[1] = nvme_read4(sc, r + 4);
    160 #else /* _BYTE_ORDER == _LITTLE_ENDIAN */
    161 	a[1] = nvme_read4(sc, r);
    162 	a[0] = nvme_read4(sc, r + 4);
    163 #endif
    164 
    165 	return v;
    166 }
    167 
    168 void
    169 nvme_write8(struct nvme_softc *sc, bus_size_t r, uint64_t v)
    170 {
    171 	uint32_t *a = (uint32_t *)&v;
    172 
    173 #if _BYTE_ORDER == _LITTLE_ENDIAN
    174 	nvme_write4(sc, r, a[0]);
    175 	nvme_write4(sc, r + 4, a[1]);
    176 #else /* _BYTE_ORDER == _LITTLE_ENDIAN */
    177 	nvme_write4(sc, r, a[1]);
    178 	nvme_write4(sc, r + 4, a[0]);
    179 #endif
    180 }
    181 
    182 #ifdef NVME_DEBUG
    183 static __used void
    184 nvme_dumpregs(struct nvme_softc *sc)
    185 {
    186 	uint64_t r8;
    187 	uint32_t r4;
    188 
    189 #define	DEVNAME(_sc) device_xname((_sc)->sc_dev)
    190 	r8 = nvme_read8(sc, NVME_CAP);
    191 	printf("%s: cap  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_CAP));
    192 	printf("%s:  mpsmax %u (%u)\n", DEVNAME(sc),
    193 	    (u_int)NVME_CAP_MPSMAX(r8), (1 << NVME_CAP_MPSMAX(r8)));
    194 	printf("%s:  mpsmin %u (%u)\n", DEVNAME(sc),
    195 	    (u_int)NVME_CAP_MPSMIN(r8), (1 << NVME_CAP_MPSMIN(r8)));
    196 	printf("%s:  css %"PRIu64"\n", DEVNAME(sc), NVME_CAP_CSS(r8));
    197 	printf("%s:  nssrs %"PRIu64"\n", DEVNAME(sc), NVME_CAP_NSSRS(r8));
    198 	printf("%s:  dstrd %"PRIu64"\n", DEVNAME(sc), NVME_CAP_DSTRD(r8));
    199 	printf("%s:  to %"PRIu64" msec\n", DEVNAME(sc), NVME_CAP_TO(r8));
    200 	printf("%s:  ams %"PRIu64"\n", DEVNAME(sc), NVME_CAP_AMS(r8));
    201 	printf("%s:  cqr %"PRIu64"\n", DEVNAME(sc), NVME_CAP_CQR(r8));
    202 	printf("%s:  mqes %"PRIu64"\n", DEVNAME(sc), NVME_CAP_MQES(r8));
    203 
    204 	printf("%s: vs   0x%04x\n", DEVNAME(sc), nvme_read4(sc, NVME_VS));
    205 
    206 	r4 = nvme_read4(sc, NVME_CC);
    207 	printf("%s: cc   0x%04x\n", DEVNAME(sc), r4);
    208 	printf("%s:  iocqes %u (%u)\n", DEVNAME(sc), NVME_CC_IOCQES_R(r4),
    209 	    (1 << NVME_CC_IOCQES_R(r4)));
    210 	printf("%s:  iosqes %u (%u)\n", DEVNAME(sc), NVME_CC_IOSQES_R(r4),
    211 	    (1 << NVME_CC_IOSQES_R(r4)));
    212 	printf("%s:  shn %u\n", DEVNAME(sc), NVME_CC_SHN_R(r4));
    213 	printf("%s:  ams %u\n", DEVNAME(sc), NVME_CC_AMS_R(r4));
    214 	printf("%s:  mps %u (%u)\n", DEVNAME(sc), NVME_CC_MPS_R(r4),
    215 	    (1 << NVME_CC_MPS_R(r4)));
    216 	printf("%s:  css %u\n", DEVNAME(sc), NVME_CC_CSS_R(r4));
    217 	printf("%s:  en %u\n", DEVNAME(sc), ISSET(r4, NVME_CC_EN) ? 1 : 0);
    218 
    219 	r4 = nvme_read4(sc, NVME_CSTS);
    220 	printf("%s: csts 0x%08x\n", DEVNAME(sc), r4);
    221 	printf("%s:  rdy %u\n", DEVNAME(sc), r4 & NVME_CSTS_RDY);
    222 	printf("%s:  cfs %u\n", DEVNAME(sc), r4 & NVME_CSTS_CFS);
    223 	printf("%s:  shst %x\n", DEVNAME(sc), r4 & NVME_CSTS_SHST_MASK);
    224 
    225 	r4 = nvme_read4(sc, NVME_AQA);
    226 	printf("%s: aqa  0x%08x\n", DEVNAME(sc), r4);
    227 	printf("%s:  acqs %u\n", DEVNAME(sc), NVME_AQA_ACQS_R(r4));
    228 	printf("%s:  asqs %u\n", DEVNAME(sc), NVME_AQA_ASQS_R(r4));
    229 
    230 	printf("%s: asq  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_ASQ));
    231 	printf("%s: acq  0x%016"PRIx64"\n", DEVNAME(sc), nvme_read8(sc, NVME_ACQ));
    232 #undef	DEVNAME
    233 }
    234 #endif	/* NVME_DEBUG */
    235 
    236 static int
    237 nvme_ready(struct nvme_softc *sc, uint32_t rdy)
    238 {
    239 	u_int i = 0;
    240 
    241 	while ((nvme_read4(sc, NVME_CSTS) & NVME_CSTS_RDY) != rdy) {
    242 		if (i++ > sc->sc_rdy_to)
    243 			return ENXIO;
    244 
    245 		delay(1000);
    246 		nvme_barrier(sc, NVME_CSTS, 4, BUS_SPACE_BARRIER_READ);
    247 	}
    248 
    249 	return 0;
    250 }
    251 
    252 static int
    253 nvme_enable(struct nvme_softc *sc, u_int mps)
    254 {
    255 	uint32_t cc, csts;
    256 	int error;
    257 
    258 	cc = nvme_read4(sc, NVME_CC);
    259 	csts = nvme_read4(sc, NVME_CSTS);
    260 
    261 	/*
    262 	 * See note in nvme_disable. Short circuit if we're already enabled.
    263 	 */
    264 	if (ISSET(cc, NVME_CC_EN)) {
    265 		if (ISSET(csts, NVME_CSTS_RDY))
    266 			return 0;
    267 
    268 		goto waitready;
    269 	} else {
    270 		/* EN == 0 already wait for RDY == 0 or fail */
    271 		error = nvme_ready(sc, 0);
    272 		if (error)
    273 			return error;
    274 	}
    275 
    276 	if (sc->sc_ops->op_enable != NULL)
    277 		sc->sc_ops->op_enable(sc);
    278 
    279 	nvme_write8(sc, NVME_ASQ, NVME_DMA_DVA(sc->sc_admin_q->q_sq_dmamem));
    280 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    281 	delay(5000);
    282 	nvme_write8(sc, NVME_ACQ, NVME_DMA_DVA(sc->sc_admin_q->q_cq_dmamem));
    283 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    284 	delay(5000);
    285 
    286 	nvme_write4(sc, NVME_AQA, NVME_AQA_ACQS(sc->sc_admin_q->q_entries) |
    287 	    NVME_AQA_ASQS(sc->sc_admin_q->q_entries));
    288 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_WRITE);
    289 	delay(5000);
    290 
    291 	CLR(cc, NVME_CC_IOCQES_MASK | NVME_CC_IOSQES_MASK | NVME_CC_SHN_MASK |
    292 	    NVME_CC_AMS_MASK | NVME_CC_MPS_MASK | NVME_CC_CSS_MASK);
    293 	SET(cc, NVME_CC_IOSQES(ffs(64) - 1) | NVME_CC_IOCQES(ffs(16) - 1));
    294 	SET(cc, NVME_CC_SHN(NVME_CC_SHN_NONE));
    295 	SET(cc, NVME_CC_CSS(NVME_CC_CSS_NVM));
    296 	SET(cc, NVME_CC_AMS(NVME_CC_AMS_RR));
    297 	SET(cc, NVME_CC_MPS(mps));
    298 	SET(cc, NVME_CC_EN);
    299 
    300 	nvme_write4(sc, NVME_CC, cc);
    301 	nvme_barrier(sc, 0, sc->sc_ios,
    302 	    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
    303 
    304     waitready:
    305 	return nvme_ready(sc, NVME_CSTS_RDY);
    306 }
    307 
    308 static int
    309 nvme_disable(struct nvme_softc *sc)
    310 {
    311 	uint32_t cc, csts;
    312 	int error;
    313 
    314 	cc = nvme_read4(sc, NVME_CC);
    315 	csts = nvme_read4(sc, NVME_CSTS);
    316 
    317 	/*
    318 	 * Per 3.1.5 in NVME 1.3 spec, transitioning CC.EN from 0 to 1
    319 	 * when CSTS.RDY is 1 or transitioning CC.EN from 1 to 0 when
    320 	 * CSTS.RDY is 0 "has undefined results" So make sure that CSTS.RDY
    321 	 * isn't the desired value. Short circuit if we're already disabled.
    322 	 */
    323 	if (ISSET(cc, NVME_CC_EN)) {
    324 		if (!ISSET(csts, NVME_CSTS_RDY)) {
    325 			/* EN == 1, wait for RDY == 1 or fail */
    326 			error = nvme_ready(sc, NVME_CSTS_RDY);
    327 			if (error)
    328 				return error;
    329 		}
    330 	} else {
    331 		/* EN == 0 already wait for RDY == 0 */
    332 		if (!ISSET(csts, NVME_CSTS_RDY))
    333 			return 0;
    334 
    335 		goto waitready;
    336 	}
    337 
    338 	CLR(cc, NVME_CC_EN);
    339 	nvme_write4(sc, NVME_CC, cc);
    340 	nvme_barrier(sc, 0, sc->sc_ios, BUS_SPACE_BARRIER_READ);
    341 
    342 	/*
    343 	 * Some drives have issues with accessing the mmio after we disable,
    344 	 * so delay for a bit after we write the bit to cope with these issues.
    345 	 */
    346 	if (ISSET(sc->sc_quirks, NVME_QUIRK_DELAY_B4_CHK_RDY))
    347 		delay(B4_CHK_RDY_DELAY_MS);
    348 
    349     waitready:
    350 	return nvme_ready(sc, 0);
    351 }
    352 
    353 int
    354 nvme_attach(struct nvme_softc *sc)
    355 {
    356 	uint64_t cap;
    357 	uint32_t reg;
    358 	u_int mps = PAGE_SHIFT;
    359 	u_int ncq, nsq;
    360 	uint16_t adminq_entries = nvme_adminq_size;
    361 	uint16_t ioq_entries = nvme_ioq_size;
    362 	int i;
    363 
    364 	if (sc->sc_ops == NULL)
    365 		sc->sc_ops = &nvme_ops;
    366 
    367 	reg = nvme_read4(sc, NVME_VS);
    368 	if (reg == 0xffffffff) {
    369 		aprint_error_dev(sc->sc_dev, "invalid mapping\n");
    370 		return 1;
    371 	}
    372 
    373 	if (NVME_VS_TER(reg) == 0)
    374 		aprint_normal_dev(sc->sc_dev, "NVMe %d.%d\n", NVME_VS_MJR(reg),
    375 		    NVME_VS_MNR(reg));
    376 	else
    377 		aprint_normal_dev(sc->sc_dev, "NVMe %d.%d.%d\n", NVME_VS_MJR(reg),
    378 		    NVME_VS_MNR(reg), NVME_VS_TER(reg));
    379 
    380 	cap = nvme_read8(sc, NVME_CAP);
    381 	sc->sc_dstrd = NVME_CAP_DSTRD(cap);
    382 	if (NVME_CAP_MPSMIN(cap) > PAGE_SHIFT) {
    383 		aprint_error_dev(sc->sc_dev, "NVMe minimum page size %u "
    384 		    "is greater than CPU page size %u\n",
    385 		    1 << NVME_CAP_MPSMIN(cap), 1 << PAGE_SHIFT);
    386 		return 1;
    387 	}
    388 	if (NVME_CAP_MPSMAX(cap) < mps)
    389 		mps = NVME_CAP_MPSMAX(cap);
    390 	if (ioq_entries > NVME_CAP_MQES(cap))
    391 		ioq_entries = NVME_CAP_MQES(cap);
    392 
    393 	/* set initial values to be used for admin queue during probe */
    394 	sc->sc_rdy_to = NVME_CAP_TO(cap);
    395 	sc->sc_mps = 1 << mps;
    396 	sc->sc_mdts = MAXPHYS;
    397 	sc->sc_max_sgl = btoc(round_page(sc->sc_mdts));
    398 
    399 	if (nvme_disable(sc) != 0) {
    400 		aprint_error_dev(sc->sc_dev, "unable to disable controller\n");
    401 		return 1;
    402 	}
    403 
    404 	sc->sc_admin_q = nvme_q_alloc(sc, NVME_ADMIN_Q, adminq_entries,
    405 	    sc->sc_dstrd);
    406 	if (sc->sc_admin_q == NULL) {
    407 		aprint_error_dev(sc->sc_dev,
    408 		    "unable to allocate admin queue\n");
    409 		return 1;
    410 	}
    411 	if (sc->sc_intr_establish(sc, NVME_ADMIN_Q, sc->sc_admin_q))
    412 		goto free_admin_q;
    413 
    414 	if (nvme_enable(sc, mps) != 0) {
    415 		aprint_error_dev(sc->sc_dev, "unable to enable controller\n");
    416 		goto disestablish_admin_q;
    417 	}
    418 
    419 	if (nvme_identify(sc, NVME_CAP_MPSMIN(cap)) != 0) {
    420 		aprint_error_dev(sc->sc_dev, "unable to identify controller\n");
    421 		goto disable;
    422 	}
    423 	if (sc->sc_nn == 0) {
    424 		aprint_error_dev(sc->sc_dev, "namespace not found\n");
    425 		goto disable;
    426 	}
    427 
    428 	/* we know how big things are now */
    429 	sc->sc_max_sgl = sc->sc_mdts / sc->sc_mps;
    430 
    431 	/* reallocate ccbs of admin queue with new max sgl. */
    432 	nvme_ccbs_free(sc->sc_admin_q);
    433 	nvme_ccbs_alloc(sc->sc_admin_q, sc->sc_admin_q->q_entries);
    434 
    435 	if (sc->sc_use_mq) {
    436 		/* Limit the number of queues to the number allocated in HW */
    437 		if (nvme_set_number_of_queues(sc, sc->sc_nq, &ncq, &nsq) != 0) {
    438 			aprint_error_dev(sc->sc_dev,
    439 			    "unable to get number of queues\n");
    440 			goto disable;
    441 		}
    442 		if (sc->sc_nq > ncq)
    443 			sc->sc_nq = ncq;
    444 		if (sc->sc_nq > nsq)
    445 			sc->sc_nq = nsq;
    446 	}
    447 
    448 	sc->sc_q = kmem_zalloc(sizeof(*sc->sc_q) * sc->sc_nq, KM_SLEEP);
    449 	for (i = 0; i < sc->sc_nq; i++) {
    450 		sc->sc_q[i] = nvme_q_alloc(sc, i + 1, ioq_entries,
    451 		    sc->sc_dstrd);
    452 		if (sc->sc_q[i] == NULL) {
    453 			aprint_error_dev(sc->sc_dev,
    454 			    "unable to allocate io queue\n");
    455 			goto free_q;
    456 		}
    457 		if (nvme_q_create(sc, sc->sc_q[i]) != 0) {
    458 			aprint_error_dev(sc->sc_dev,
    459 			    "unable to create io queue\n");
    460 			nvme_q_free(sc, sc->sc_q[i]);
    461 			goto free_q;
    462 		}
    463 	}
    464 
    465 	if (!sc->sc_use_mq)
    466 		nvme_write4(sc, NVME_INTMC, 1);
    467 
    468 	/* probe subdevices */
    469 	sc->sc_namespaces = kmem_zalloc(sizeof(*sc->sc_namespaces) * sc->sc_nn,
    470 	    KM_SLEEP);
    471 	nvme_rescan(sc->sc_dev, NULL, NULL);
    472 
    473 	return 0;
    474 
    475 free_q:
    476 	while (--i >= 0) {
    477 		nvme_q_delete(sc, sc->sc_q[i]);
    478 		nvme_q_free(sc, sc->sc_q[i]);
    479 	}
    480 disable:
    481 	nvme_disable(sc);
    482 disestablish_admin_q:
    483 	sc->sc_intr_disestablish(sc, NVME_ADMIN_Q);
    484 free_admin_q:
    485 	nvme_q_free(sc, sc->sc_admin_q);
    486 
    487 	return 1;
    488 }
    489 
    490 int
    491 nvme_rescan(device_t self, const char *ifattr, const int *locs)
    492 {
    493 	struct nvme_softc *sc = device_private(self);
    494 	struct nvme_attach_args naa;
    495 	struct nvm_namespace_format *f;
    496 	struct nvme_namespace *ns;
    497 	uint64_t cap;
    498 	int ioq_entries = nvme_ioq_size;
    499 	int i, mlocs[NVMECF_NLOCS];
    500 	int error;
    501 
    502 	cap = nvme_read8(sc, NVME_CAP);
    503 	if (ioq_entries > NVME_CAP_MQES(cap))
    504 		ioq_entries = NVME_CAP_MQES(cap);
    505 
    506 	for (i = 1; i <= sc->sc_nn; i++) {
    507 		if (sc->sc_namespaces[i - 1].dev)
    508 			continue;
    509 
    510 		/* identify to check for availability */
    511 		error = nvme_ns_identify(sc, i);
    512 		if (error) {
    513 			aprint_error_dev(self, "couldn't identify namespace #%d\n", i);
    514 			continue;
    515 		}
    516 
    517 		ns = nvme_ns_get(sc, i);
    518 		KASSERT(ns);
    519 
    520 		f = &ns->ident->lbaf[NVME_ID_NS_FLBAS(ns->ident->flbas)];
    521 
    522 		/*
    523 		 * NVME1.0e 6.11 Identify command
    524 		 *
    525 		 * LBADS values smaller than 9 are not supported, a value
    526 		 * of zero means that the format is not used.
    527 		 */
    528 		if (f->lbads < 9) {
    529 			if (f->lbads > 0)
    530 				aprint_error_dev(self,
    531 						 "unsupported logical data size %u\n", f->lbads);
    532 			continue;
    533 		}
    534 
    535 		mlocs[NVMECF_NSID] = i;
    536 
    537 		memset(&naa, 0, sizeof(naa));
    538 		naa.naa_nsid = i;
    539 		naa.naa_qentries = (ioq_entries - 1) * sc->sc_nq;
    540 		naa.naa_maxphys = sc->sc_mdts;
    541 		naa.naa_typename = sc->sc_modelname;
    542 		sc->sc_namespaces[i - 1].dev =
    543 		    config_found(sc->sc_dev, &naa, nvme_print,
    544 				 CFARGS(.submatch = config_stdsubmatch,
    545 					.locators = mlocs));
    546 	}
    547 	return 0;
    548 }
    549 
    550 static int
    551 nvme_print(void *aux, const char *pnp)
    552 {
    553 	struct nvme_attach_args *naa = aux;
    554 
    555 	if (pnp)
    556 		aprint_normal("ld at %s", pnp);
    557 
    558 	if (naa->naa_nsid > 0)
    559 		aprint_normal(" nsid %d", naa->naa_nsid);
    560 
    561 	return UNCONF;
    562 }
    563 
    564 int
    565 nvme_detach(struct nvme_softc *sc, int flags)
    566 {
    567 	int i, error;
    568 
    569 	error = config_detach_children(sc->sc_dev, flags);
    570 	if (error)
    571 		return error;
    572 
    573 	error = nvme_shutdown(sc);
    574 	if (error)
    575 		return error;
    576 
    577 	/* from now on we are committed to detach, following will never fail */
    578 	for (i = 0; i < sc->sc_nq; i++)
    579 		nvme_q_free(sc, sc->sc_q[i]);
    580 	kmem_free(sc->sc_q, sizeof(*sc->sc_q) * sc->sc_nq);
    581 	nvme_q_free(sc, sc->sc_admin_q);
    582 
    583 	return 0;
    584 }
    585 
    586 int
    587 nvme_suspend(struct nvme_softc *sc)
    588 {
    589 
    590 	return nvme_shutdown(sc);
    591 }
    592 
    593 int
    594 nvme_resume(struct nvme_softc *sc)
    595 {
    596 	int i, error;
    597 
    598 	error = nvme_disable(sc);
    599 	if (error) {
    600 		device_printf(sc->sc_dev, "unable to disable controller\n");
    601 		return error;
    602 	}
    603 
    604 	nvme_q_reset(sc, sc->sc_admin_q);
    605 	if (sc->sc_intr_establish(sc, NVME_ADMIN_Q, sc->sc_admin_q)) {
    606 		error = EIO;
    607 		device_printf(sc->sc_dev, "unable to establish admin q\n");
    608 		goto disable;
    609 	}
    610 
    611 	error = nvme_enable(sc, ffs(sc->sc_mps) - 1);
    612 	if (error) {
    613 		device_printf(sc->sc_dev, "unable to enable controller\n");
    614 		return error;
    615 	}
    616 
    617 	for (i = 0; i < sc->sc_nq; i++) {
    618 		nvme_q_reset(sc, sc->sc_q[i]);
    619 		if (nvme_q_create(sc, sc->sc_q[i]) != 0) {
    620 			error = EIO;
    621 			device_printf(sc->sc_dev, "unable to create io q %d"
    622 			    "\n", i);
    623 			goto disable;
    624 		}
    625 	}
    626 
    627 	nvme_write4(sc, NVME_INTMC, 1);
    628 
    629 	return 0;
    630 
    631 disable:
    632 	(void)nvme_disable(sc);
    633 
    634 	return error;
    635 }
    636 
    637 static int
    638 nvme_shutdown(struct nvme_softc *sc)
    639 {
    640 	uint32_t cc, csts;
    641 	bool disabled = false;
    642 	int i;
    643 
    644 	if (!sc->sc_use_mq)
    645 		nvme_write4(sc, NVME_INTMS, 1);
    646 
    647 	for (i = 0; i < sc->sc_nq; i++) {
    648 		if (nvme_q_delete(sc, sc->sc_q[i]) != 0) {
    649 			aprint_error_dev(sc->sc_dev,
    650 			    "unable to delete io queue %d, disabling\n", i + 1);
    651 			disabled = true;
    652 		}
    653 	}
    654 	if (disabled)
    655 		goto disable;
    656 
    657 	sc->sc_intr_disestablish(sc, NVME_ADMIN_Q);
    658 
    659 	cc = nvme_read4(sc, NVME_CC);
    660 	CLR(cc, NVME_CC_SHN_MASK);
    661 	SET(cc, NVME_CC_SHN(NVME_CC_SHN_NORMAL));
    662 	nvme_write4(sc, NVME_CC, cc);
    663 
    664 	for (i = 0; i < 4000; i++) {
    665 		nvme_barrier(sc, 0, sc->sc_ios,
    666 		    BUS_SPACE_BARRIER_READ | BUS_SPACE_BARRIER_WRITE);
    667 		csts = nvme_read4(sc, NVME_CSTS);
    668 		if ((csts & NVME_CSTS_SHST_MASK) == NVME_CSTS_SHST_DONE)
    669 			return 0;
    670 
    671 		delay(1000);
    672 	}
    673 
    674 	aprint_error_dev(sc->sc_dev, "unable to shudown, disabling\n");
    675 
    676 disable:
    677 	nvme_disable(sc);
    678 	return 0;
    679 }
    680 
    681 void
    682 nvme_childdet(device_t self, device_t child)
    683 {
    684 	struct nvme_softc *sc = device_private(self);
    685 	int i;
    686 
    687 	for (i = 0; i < sc->sc_nn; i++) {
    688 		if (sc->sc_namespaces[i].dev == child) {
    689 			/* Already freed ns->ident. */
    690 			sc->sc_namespaces[i].dev = NULL;
    691 			break;
    692 		}
    693 	}
    694 }
    695 
    696 int
    697 nvme_ns_identify(struct nvme_softc *sc, uint16_t nsid)
    698 {
    699 	struct nvme_sqe sqe;
    700 	struct nvm_identify_namespace *identify;
    701 	struct nvme_dmamem *mem;
    702 	struct nvme_ccb *ccb;
    703 	struct nvme_namespace *ns;
    704 	int rv;
    705 
    706 	KASSERT(nsid > 0);
    707 
    708 	ns = nvme_ns_get(sc, nsid);
    709 	KASSERT(ns);
    710 
    711 	if (ns->ident != NULL)
    712 		return 0;
    713 
    714 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
    715 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
    716 
    717 	mem = nvme_dmamem_alloc(sc, sizeof(*identify));
    718 	if (mem == NULL) {
    719 		nvme_ccb_put(sc->sc_admin_q, ccb);
    720 		return ENOMEM;
    721 	}
    722 
    723 	memset(&sqe, 0, sizeof(sqe));
    724 	sqe.opcode = NVM_ADMIN_IDENTIFY;
    725 	htolem32(&sqe.nsid, nsid);
    726 	htolem64(&sqe.entry.prp[0], NVME_DMA_DVA(mem));
    727 	htolem32(&sqe.cdw10, 0);
    728 
    729 	ccb->ccb_done = nvme_empty_done;
    730 	ccb->ccb_cookie = &sqe;
    731 
    732 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_PREREAD);
    733 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_IDENT);
    734 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_POSTREAD);
    735 
    736 	nvme_ccb_put(sc->sc_admin_q, ccb);
    737 
    738 	if (rv != 0) {
    739 		rv = EIO;
    740 		goto done;
    741 	}
    742 
    743 	/* commit */
    744 
    745 	identify = kmem_zalloc(sizeof(*identify), KM_SLEEP);
    746 	*identify = *((volatile struct nvm_identify_namespace *)NVME_DMA_KVA(mem));
    747 
    748 	/* Convert data to host endian */
    749 	nvme_identify_namespace_swapbytes(identify);
    750 
    751 	ns->ident = identify;
    752 
    753 done:
    754 	nvme_dmamem_free(sc, mem);
    755 
    756 	return rv;
    757 }
    758 
    759 int
    760 nvme_ns_dobio(struct nvme_softc *sc, uint16_t nsid, void *cookie,
    761     struct buf *bp, void *data, size_t datasize,
    762     int secsize, daddr_t blkno, int flags, nvme_nnc_done nnc_done)
    763 {
    764 	struct nvme_queue *q;
    765 	struct nvme_ccb *ccb;
    766 	bus_dmamap_t dmap;
    767 	int i, error;
    768 
    769 	ccb = nvme_ccb_get_bio(sc, bp, &q);
    770 	if (ccb == NULL)
    771 		return EAGAIN;
    772 
    773 	ccb->ccb_done = nvme_ns_io_done;
    774 	ccb->ccb_cookie = cookie;
    775 
    776 	/* namespace context */
    777 	ccb->nnc_nsid = nsid;
    778 	ccb->nnc_flags = flags;
    779 	ccb->nnc_buf = bp;
    780 	ccb->nnc_datasize = datasize;
    781 	ccb->nnc_secsize = secsize;
    782 	ccb->nnc_blkno = blkno;
    783 	ccb->nnc_done = nnc_done;
    784 
    785 	dmap = ccb->ccb_dmamap;
    786 	error = bus_dmamap_load(sc->sc_dmat, dmap, data,
    787 	    datasize, NULL,
    788 	    (ISSET(flags, NVME_NS_CTX_F_POLL) ?
    789 	      BUS_DMA_NOWAIT : BUS_DMA_WAITOK) |
    790 	    (ISSET(flags, NVME_NS_CTX_F_READ) ?
    791 	      BUS_DMA_READ : BUS_DMA_WRITE));
    792 	if (error) {
    793 		nvme_ccb_put(q, ccb);
    794 		return error;
    795 	}
    796 
    797 	bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
    798 	    ISSET(flags, NVME_NS_CTX_F_READ) ?
    799 	    BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
    800 
    801 	if (dmap->dm_nsegs > 2) {
    802 		for (i = 1; i < dmap->dm_nsegs; i++) {
    803 			htolem64(&ccb->ccb_prpl[i - 1],
    804 			    dmap->dm_segs[i].ds_addr);
    805 		}
    806 		bus_dmamap_sync(sc->sc_dmat,
    807 		    NVME_DMA_MAP(q->q_ccb_prpls),
    808 		    ccb->ccb_prpl_off,
    809 		    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    810 		    BUS_DMASYNC_PREWRITE);
    811 	}
    812 
    813 	if (ISSET(flags, NVME_NS_CTX_F_POLL)) {
    814 		if (nvme_poll(sc, q, ccb, nvme_ns_io_fill, NVME_TIMO_PT) != 0)
    815 			return EIO;
    816 		return 0;
    817 	}
    818 
    819 	nvme_q_submit(sc, q, ccb, nvme_ns_io_fill);
    820 	return 0;
    821 }
    822 
    823 static void
    824 nvme_ns_io_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    825 {
    826 	struct nvme_sqe_io *sqe = slot;
    827 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    828 
    829 	sqe->opcode = ISSET(ccb->nnc_flags, NVME_NS_CTX_F_READ) ?
    830 	    NVM_CMD_READ : NVM_CMD_WRITE;
    831 	htolem32(&sqe->nsid, ccb->nnc_nsid);
    832 
    833 	htolem64(&sqe->entry.prp[0], dmap->dm_segs[0].ds_addr);
    834 	switch (dmap->dm_nsegs) {
    835 	case 1:
    836 		break;
    837 	case 2:
    838 		htolem64(&sqe->entry.prp[1], dmap->dm_segs[1].ds_addr);
    839 		break;
    840 	default:
    841 		/* the prp list is already set up and synced */
    842 		htolem64(&sqe->entry.prp[1], ccb->ccb_prpl_dva);
    843 		break;
    844 	}
    845 
    846 	htolem64(&sqe->slba, ccb->nnc_blkno);
    847 
    848 	if (ISSET(ccb->nnc_flags, NVME_NS_CTX_F_FUA))
    849 		htolem16(&sqe->ioflags, NVM_SQE_IO_FUA);
    850 
    851 	/* guaranteed by upper layers, but check just in case */
    852 	KASSERT((ccb->nnc_datasize % ccb->nnc_secsize) == 0);
    853 	htolem16(&sqe->nlb, (ccb->nnc_datasize / ccb->nnc_secsize) - 1);
    854 }
    855 
    856 static void
    857 nvme_ns_io_done(struct nvme_queue *q, struct nvme_ccb *ccb,
    858     struct nvme_cqe *cqe)
    859 {
    860 	struct nvme_softc *sc = q->q_sc;
    861 	bus_dmamap_t dmap = ccb->ccb_dmamap;
    862 	void *nnc_cookie = ccb->ccb_cookie;
    863 	nvme_nnc_done nnc_done = ccb->nnc_done;
    864 	struct buf *bp = ccb->nnc_buf;
    865 
    866 	if (dmap->dm_nsegs > 2) {
    867 		bus_dmamap_sync(sc->sc_dmat,
    868 		    NVME_DMA_MAP(q->q_ccb_prpls),
    869 		    ccb->ccb_prpl_off,
    870 		    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
    871 		    BUS_DMASYNC_POSTWRITE);
    872 	}
    873 
    874 	bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
    875 	    ISSET(ccb->nnc_flags, NVME_NS_CTX_F_READ) ?
    876 	    BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
    877 
    878 	bus_dmamap_unload(sc->sc_dmat, dmap);
    879 	nvme_ccb_put(q, ccb);
    880 
    881 	nnc_done(nnc_cookie, bp, lemtoh16(&cqe->flags), lemtoh32(&cqe->cdw0));
    882 }
    883 
    884 /*
    885  * If there is no volatile write cache, it makes no sense to issue
    886  * flush commands or query for the status.
    887  */
    888 static bool
    889 nvme_has_volatile_write_cache(struct nvme_softc *sc)
    890 {
    891 	/* sc_identify is filled during attachment */
    892 	return  ((sc->sc_identify.vwc & NVME_ID_CTRLR_VWC_PRESENT) != 0);
    893 }
    894 
    895 static bool
    896 nvme_ns_sync_finished(void *cookie)
    897 {
    898 	int *result = cookie;
    899 
    900 	return (*result != 0);
    901 }
    902 
    903 int
    904 nvme_ns_sync(struct nvme_softc *sc, uint16_t nsid, int flags)
    905 {
    906 	struct nvme_queue *q = nvme_get_q(sc);
    907 	struct nvme_ccb *ccb;
    908 	int result = 0;
    909 
    910 	if (!nvme_has_volatile_write_cache(sc)) {
    911 		/* cache not present, no value in trying to flush it */
    912 		return 0;
    913 	}
    914 
    915 	ccb = nvme_ccb_get(q, true);
    916 	KASSERT(ccb != NULL);
    917 
    918 	ccb->ccb_done = nvme_ns_sync_done;
    919 	ccb->ccb_cookie = &result;
    920 
    921 	/* namespace context */
    922 	ccb->nnc_nsid = nsid;
    923 	ccb->nnc_flags = flags;
    924 	ccb->nnc_done = NULL;
    925 
    926 	if (ISSET(flags, NVME_NS_CTX_F_POLL)) {
    927 		if (nvme_poll(sc, q, ccb, nvme_ns_sync_fill, NVME_TIMO_SY) != 0)
    928 			return EIO;
    929 		return 0;
    930 	}
    931 
    932 	nvme_q_submit(sc, q, ccb, nvme_ns_sync_fill);
    933 
    934 	/* wait for completion */
    935 	nvme_q_wait_complete(sc, q, nvme_ns_sync_finished, &result);
    936 	KASSERT(result != 0);
    937 
    938 	return (result > 0) ? 0 : EIO;
    939 }
    940 
    941 static void
    942 nvme_ns_sync_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
    943 {
    944 	struct nvme_sqe *sqe = slot;
    945 
    946 	sqe->opcode = NVM_CMD_FLUSH;
    947 	htolem32(&sqe->nsid, ccb->nnc_nsid);
    948 }
    949 
    950 static void
    951 nvme_ns_sync_done(struct nvme_queue *q, struct nvme_ccb *ccb,
    952     struct nvme_cqe *cqe)
    953 {
    954 	int *result = ccb->ccb_cookie;
    955 	uint16_t status = NVME_CQE_SC(lemtoh16(&cqe->flags));
    956 
    957 	if (status == NVME_CQE_SC_SUCCESS)
    958 		*result = 1;
    959 	else
    960 		*result = -1;
    961 
    962 	nvme_ccb_put(q, ccb);
    963 }
    964 
    965 static bool
    966 nvme_getcache_finished(void *xc)
    967 {
    968 	int *addr = xc;
    969 
    970 	return (*addr != 0);
    971 }
    972 
    973 /*
    974  * Get status of volatile write cache. Always asynchronous.
    975  */
    976 int
    977 nvme_admin_getcache(struct nvme_softc *sc, int *addr)
    978 {
    979 	struct nvme_ccb *ccb;
    980 	struct nvme_queue *q = sc->sc_admin_q;
    981 	int result = 0, error;
    982 
    983 	if (!nvme_has_volatile_write_cache(sc)) {
    984 		/* cache simply not present */
    985 		*addr = 0;
    986 		return 0;
    987 	}
    988 
    989 	ccb = nvme_ccb_get(q, true);
    990 	KASSERT(ccb != NULL);
    991 
    992 	ccb->ccb_done = nvme_getcache_done;
    993 	ccb->ccb_cookie = &result;
    994 
    995 	/* namespace context */
    996 	ccb->nnc_flags = 0;
    997 	ccb->nnc_done = NULL;
    998 
    999 	nvme_q_submit(sc, q, ccb, nvme_getcache_fill);
   1000 
   1001 	/* wait for completion */
   1002 	nvme_q_wait_complete(sc, q, nvme_getcache_finished, &result);
   1003 	KASSERT(result != 0);
   1004 
   1005 	if (result > 0) {
   1006 		*addr = result;
   1007 		error = 0;
   1008 	} else
   1009 		error = EINVAL;
   1010 
   1011 	return error;
   1012 }
   1013 
   1014 static void
   1015 nvme_getcache_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1016 {
   1017 	struct nvme_sqe *sqe = slot;
   1018 
   1019 	sqe->opcode = NVM_ADMIN_GET_FEATURES;
   1020 	htolem32(&sqe->cdw10, NVM_FEATURE_VOLATILE_WRITE_CACHE);
   1021 	htolem32(&sqe->cdw11, NVM_VOLATILE_WRITE_CACHE_WCE);
   1022 }
   1023 
   1024 static void
   1025 nvme_getcache_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1026     struct nvme_cqe *cqe)
   1027 {
   1028 	int *addr = ccb->ccb_cookie;
   1029 	uint16_t status = NVME_CQE_SC(lemtoh16(&cqe->flags));
   1030 	uint32_t cdw0 = lemtoh32(&cqe->cdw0);
   1031 	int result;
   1032 
   1033 	if (status == NVME_CQE_SC_SUCCESS) {
   1034 		result = 0;
   1035 
   1036 		/*
   1037 		 * DPO not supported, Dataset Management (DSM) field doesn't
   1038 		 * specify the same semantics. FUA is always supported.
   1039 		 */
   1040 		result = DKCACHE_FUA;
   1041 
   1042 		if (cdw0 & NVM_VOLATILE_WRITE_CACHE_WCE)
   1043 			result |= DKCACHE_WRITE;
   1044 
   1045 		/*
   1046 		 * If volatile write cache is present, the flag shall also be
   1047 		 * settable.
   1048 		 */
   1049 		result |= DKCACHE_WCHANGE;
   1050 
   1051 		/*
   1052 		 * ONCS field indicates whether the optional SAVE is also
   1053 		 * supported for Set Features. According to spec v1.3,
   1054 		 * Volatile Write Cache however doesn't support persistency
   1055 		 * across power cycle/reset.
   1056 		 */
   1057 
   1058 	} else {
   1059 		result = -1;
   1060 	}
   1061 
   1062 	*addr = result;
   1063 
   1064 	nvme_ccb_put(q, ccb);
   1065 }
   1066 
   1067 struct nvme_setcache_state {
   1068 	int dkcache;
   1069 	int result;
   1070 };
   1071 
   1072 static bool
   1073 nvme_setcache_finished(void *xc)
   1074 {
   1075 	struct nvme_setcache_state *st = xc;
   1076 
   1077 	return (st->result != 0);
   1078 }
   1079 
   1080 static void
   1081 nvme_setcache_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1082 {
   1083 	struct nvme_sqe *sqe = slot;
   1084 	struct nvme_setcache_state *st = ccb->ccb_cookie;
   1085 
   1086 	sqe->opcode = NVM_ADMIN_SET_FEATURES;
   1087 	htolem32(&sqe->cdw10, NVM_FEATURE_VOLATILE_WRITE_CACHE);
   1088 	if (st->dkcache & DKCACHE_WRITE)
   1089 		htolem32(&sqe->cdw11, NVM_VOLATILE_WRITE_CACHE_WCE);
   1090 }
   1091 
   1092 static void
   1093 nvme_setcache_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1094     struct nvme_cqe *cqe)
   1095 {
   1096 	struct nvme_setcache_state *st = ccb->ccb_cookie;
   1097 	uint16_t status = NVME_CQE_SC(lemtoh16(&cqe->flags));
   1098 
   1099 	if (status == NVME_CQE_SC_SUCCESS) {
   1100 		st->result = 1;
   1101 	} else {
   1102 		st->result = -1;
   1103 	}
   1104 
   1105 	nvme_ccb_put(q, ccb);
   1106 }
   1107 
   1108 /*
   1109  * Set status of volatile write cache. Always asynchronous.
   1110  */
   1111 int
   1112 nvme_admin_setcache(struct nvme_softc *sc, int dkcache)
   1113 {
   1114 	struct nvme_ccb *ccb;
   1115 	struct nvme_queue *q = sc->sc_admin_q;
   1116 	int error;
   1117 	struct nvme_setcache_state st;
   1118 
   1119 	if (!nvme_has_volatile_write_cache(sc)) {
   1120 		/* cache simply not present */
   1121 		return EOPNOTSUPP;
   1122 	}
   1123 
   1124 	if (dkcache & ~(DKCACHE_WRITE)) {
   1125 		/* unsupported parameters */
   1126 		return EOPNOTSUPP;
   1127 	}
   1128 
   1129 	ccb = nvme_ccb_get(q, true);
   1130 	KASSERT(ccb != NULL);
   1131 
   1132 	memset(&st, 0, sizeof(st));
   1133 	st.dkcache = dkcache;
   1134 
   1135 	ccb->ccb_done = nvme_setcache_done;
   1136 	ccb->ccb_cookie = &st;
   1137 
   1138 	/* namespace context */
   1139 	ccb->nnc_flags = 0;
   1140 	ccb->nnc_done = NULL;
   1141 
   1142 	nvme_q_submit(sc, q, ccb, nvme_setcache_fill);
   1143 
   1144 	/* wait for completion */
   1145 	nvme_q_wait_complete(sc, q, nvme_setcache_finished, &st);
   1146 	KASSERT(st.result != 0);
   1147 
   1148 	if (st.result > 0)
   1149 		error = 0;
   1150 	else
   1151 		error = EINVAL;
   1152 
   1153 	return error;
   1154 }
   1155 
   1156 void
   1157 nvme_ns_free(struct nvme_softc *sc, uint16_t nsid)
   1158 {
   1159 	struct nvme_namespace *ns;
   1160 	struct nvm_identify_namespace *identify;
   1161 
   1162 	ns = nvme_ns_get(sc, nsid);
   1163 	KASSERT(ns);
   1164 
   1165 	identify = ns->ident;
   1166 	ns->ident = NULL;
   1167 	if (identify != NULL)
   1168 		kmem_free(identify, sizeof(*identify));
   1169 }
   1170 
   1171 struct nvme_pt_state {
   1172 	struct nvme_pt_command *pt;
   1173 	bool finished;
   1174 };
   1175 
   1176 static void
   1177 nvme_pt_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1178 {
   1179 	struct nvme_softc *sc = q->q_sc;
   1180 	struct nvme_sqe *sqe = slot;
   1181 	struct nvme_pt_state *state = ccb->ccb_cookie;
   1182 	struct nvme_pt_command *pt = state->pt;
   1183 	bus_dmamap_t dmap = ccb->ccb_dmamap;
   1184 	int i;
   1185 
   1186 	sqe->opcode = pt->cmd.opcode;
   1187 	htolem32(&sqe->nsid, pt->cmd.nsid);
   1188 
   1189 	if (pt->buf != NULL && pt->len > 0) {
   1190 		htolem64(&sqe->entry.prp[0], dmap->dm_segs[0].ds_addr);
   1191 		switch (dmap->dm_nsegs) {
   1192 		case 1:
   1193 			break;
   1194 		case 2:
   1195 			htolem64(&sqe->entry.prp[1], dmap->dm_segs[1].ds_addr);
   1196 			break;
   1197 		default:
   1198 			for (i = 1; i < dmap->dm_nsegs; i++) {
   1199 				htolem64(&ccb->ccb_prpl[i - 1],
   1200 				    dmap->dm_segs[i].ds_addr);
   1201 			}
   1202 			bus_dmamap_sync(sc->sc_dmat,
   1203 			    NVME_DMA_MAP(q->q_ccb_prpls),
   1204 			    ccb->ccb_prpl_off,
   1205 			    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
   1206 			    BUS_DMASYNC_PREWRITE);
   1207 			htolem64(&sqe->entry.prp[1], ccb->ccb_prpl_dva);
   1208 			break;
   1209 		}
   1210 	}
   1211 
   1212 	htolem32(&sqe->cdw10, pt->cmd.cdw10);
   1213 	htolem32(&sqe->cdw11, pt->cmd.cdw11);
   1214 	htolem32(&sqe->cdw12, pt->cmd.cdw12);
   1215 	htolem32(&sqe->cdw13, pt->cmd.cdw13);
   1216 	htolem32(&sqe->cdw14, pt->cmd.cdw14);
   1217 	htolem32(&sqe->cdw15, pt->cmd.cdw15);
   1218 }
   1219 
   1220 static void
   1221 nvme_pt_done(struct nvme_queue *q, struct nvme_ccb *ccb, struct nvme_cqe *cqe)
   1222 {
   1223 	struct nvme_softc *sc = q->q_sc;
   1224 	struct nvme_pt_state *state = ccb->ccb_cookie;
   1225 	struct nvme_pt_command *pt = state->pt;
   1226 	bus_dmamap_t dmap = ccb->ccb_dmamap;
   1227 
   1228 	if (pt->buf != NULL && pt->len > 0) {
   1229 		if (dmap->dm_nsegs > 2) {
   1230 			bus_dmamap_sync(sc->sc_dmat,
   1231 			    NVME_DMA_MAP(q->q_ccb_prpls),
   1232 			    ccb->ccb_prpl_off,
   1233 			    sizeof(*ccb->ccb_prpl) * (dmap->dm_nsegs - 1),
   1234 			    BUS_DMASYNC_POSTWRITE);
   1235 		}
   1236 
   1237 		bus_dmamap_sync(sc->sc_dmat, dmap, 0, dmap->dm_mapsize,
   1238 		    pt->is_read ? BUS_DMASYNC_POSTREAD : BUS_DMASYNC_POSTWRITE);
   1239 		bus_dmamap_unload(sc->sc_dmat, dmap);
   1240 	}
   1241 
   1242 	pt->cpl.cdw0 = lemtoh32(&cqe->cdw0);
   1243 	pt->cpl.flags = lemtoh16(&cqe->flags) & ~NVME_CQE_PHASE;
   1244 
   1245 	state->finished = true;
   1246 
   1247 	nvme_ccb_put(q, ccb);
   1248 }
   1249 
   1250 static bool
   1251 nvme_pt_finished(void *cookie)
   1252 {
   1253 	struct nvme_pt_state *state = cookie;
   1254 
   1255 	return state->finished;
   1256 }
   1257 
   1258 static int
   1259 nvme_command_passthrough(struct nvme_softc *sc, struct nvme_pt_command *pt,
   1260     uint32_t nsid, struct lwp *l, bool is_adminq)
   1261 {
   1262 	struct nvme_queue *q;
   1263 	struct nvme_ccb *ccb;
   1264 	void *buf = NULL;
   1265 	struct nvme_pt_state state;
   1266 	int error;
   1267 
   1268 	/* limit command size to maximum data transfer size */
   1269 	if ((pt->buf == NULL && pt->len > 0) ||
   1270 	    (pt->buf != NULL && (pt->len == 0 || pt->len > sc->sc_mdts)))
   1271 		return EINVAL;
   1272 
   1273 	q = is_adminq ? sc->sc_admin_q : nvme_get_q(sc);
   1274 	ccb = nvme_ccb_get(q, true);
   1275 	KASSERT(ccb != NULL);
   1276 
   1277 	if (pt->buf != NULL) {
   1278 		KASSERT(pt->len > 0);
   1279 		buf = kmem_alloc(pt->len, KM_SLEEP);
   1280 		if (!pt->is_read) {
   1281 			error = copyin(pt->buf, buf, pt->len);
   1282 			if (error)
   1283 				goto kmem_free;
   1284 		}
   1285 		error = bus_dmamap_load(sc->sc_dmat, ccb->ccb_dmamap, buf,
   1286 		    pt->len, NULL,
   1287 		    BUS_DMA_WAITOK |
   1288 		      (pt->is_read ? BUS_DMA_READ : BUS_DMA_WRITE));
   1289 		if (error)
   1290 			goto kmem_free;
   1291 		bus_dmamap_sync(sc->sc_dmat, ccb->ccb_dmamap,
   1292 		    0, ccb->ccb_dmamap->dm_mapsize,
   1293 		    pt->is_read ? BUS_DMASYNC_PREREAD : BUS_DMASYNC_PREWRITE);
   1294 	}
   1295 
   1296 	memset(&state, 0, sizeof(state));
   1297 	state.pt = pt;
   1298 	state.finished = false;
   1299 
   1300 	ccb->ccb_done = nvme_pt_done;
   1301 	ccb->ccb_cookie = &state;
   1302 
   1303 	pt->cmd.nsid = nsid;
   1304 
   1305 	nvme_q_submit(sc, q, ccb, nvme_pt_fill);
   1306 
   1307 	/* wait for completion */
   1308 	nvme_q_wait_complete(sc, q, nvme_pt_finished, &state);
   1309 	KASSERT(state.finished);
   1310 
   1311 	error = 0;
   1312 
   1313 	if (buf != NULL) {
   1314 		if (error == 0 && pt->is_read)
   1315 			error = copyout(buf, pt->buf, pt->len);
   1316 kmem_free:
   1317 		kmem_free(buf, pt->len);
   1318 	}
   1319 
   1320 	return error;
   1321 }
   1322 
   1323 uint32_t
   1324 nvme_op_sq_enter(struct nvme_softc *sc,
   1325     struct nvme_queue *q, struct nvme_ccb *ccb)
   1326 {
   1327 	mutex_enter(&q->q_sq_mtx);
   1328 
   1329 	return nvme_op_sq_enter_locked(sc, q, ccb);
   1330 }
   1331 
   1332 uint32_t
   1333 nvme_op_sq_enter_locked(struct nvme_softc *sc,
   1334     struct nvme_queue *q, struct nvme_ccb *ccb)
   1335 {
   1336 	return q->q_sq_tail;
   1337 }
   1338 
   1339 void
   1340 nvme_op_sq_leave_locked(struct nvme_softc *sc,
   1341     struct nvme_queue *q, struct nvme_ccb *ccb)
   1342 {
   1343 	uint32_t tail;
   1344 
   1345 	tail = ++q->q_sq_tail;
   1346 	if (tail >= q->q_entries)
   1347 		tail = 0;
   1348 	q->q_sq_tail = tail;
   1349 	nvme_write4(sc, q->q_sqtdbl, tail);
   1350 }
   1351 
   1352 void
   1353 nvme_op_sq_leave(struct nvme_softc *sc,
   1354     struct nvme_queue *q, struct nvme_ccb *ccb)
   1355 {
   1356 	nvme_op_sq_leave_locked(sc, q, ccb);
   1357 
   1358 	mutex_exit(&q->q_sq_mtx);
   1359 }
   1360 
   1361 static void
   1362 nvme_q_submit(struct nvme_softc *sc, struct nvme_queue *q, struct nvme_ccb *ccb,
   1363     void (*fill)(struct nvme_queue *, struct nvme_ccb *, void *))
   1364 {
   1365 	struct nvme_sqe *sqe = NVME_DMA_KVA(q->q_sq_dmamem);
   1366 	uint32_t tail;
   1367 
   1368 	tail = sc->sc_ops->op_sq_enter(sc, q, ccb);
   1369 
   1370 	sqe += tail;
   1371 
   1372 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(q->q_sq_dmamem),
   1373 	    sizeof(*sqe) * tail, sizeof(*sqe), BUS_DMASYNC_POSTWRITE);
   1374 	memset(sqe, 0, sizeof(*sqe));
   1375 	(*fill)(q, ccb, sqe);
   1376 	htolem16(&sqe->cid, ccb->ccb_id);
   1377 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(q->q_sq_dmamem),
   1378 	    sizeof(*sqe) * tail, sizeof(*sqe), BUS_DMASYNC_PREWRITE);
   1379 
   1380 	sc->sc_ops->op_sq_leave(sc, q, ccb);
   1381 }
   1382 
   1383 struct nvme_poll_state {
   1384 	struct nvme_sqe s;
   1385 	struct nvme_cqe c;
   1386 	void *cookie;
   1387 	void (*done)(struct nvme_queue *, struct nvme_ccb *, struct nvme_cqe *);
   1388 };
   1389 
   1390 static int
   1391 nvme_poll(struct nvme_softc *sc, struct nvme_queue *q, struct nvme_ccb *ccb,
   1392     void (*fill)(struct nvme_queue *, struct nvme_ccb *, void *), int timo_sec)
   1393 {
   1394 	struct nvme_poll_state state;
   1395 	uint16_t flags;
   1396 	int step = 10;
   1397 	int maxloop = timo_sec * 1000000 / step;
   1398 	int error = 0;
   1399 
   1400 	memset(&state, 0, sizeof(state));
   1401 	(*fill)(q, ccb, &state.s);
   1402 
   1403 	state.done = ccb->ccb_done;
   1404 	state.cookie = ccb->ccb_cookie;
   1405 
   1406 	ccb->ccb_done = nvme_poll_done;
   1407 	ccb->ccb_cookie = &state;
   1408 
   1409 	nvme_q_submit(sc, q, ccb, nvme_poll_fill);
   1410 	while (!ISSET(state.c.flags, htole16(NVME_CQE_PHASE))) {
   1411 		if (nvme_q_complete(sc, q) == 0)
   1412 			delay(step);
   1413 
   1414 		if (timo_sec >= 0 && --maxloop <= 0) {
   1415 			error = ETIMEDOUT;
   1416 			break;
   1417 		}
   1418 	}
   1419 
   1420 	if (error == 0) {
   1421 		flags = lemtoh16(&state.c.flags);
   1422 		return flags & ~NVME_CQE_PHASE;
   1423 	} else {
   1424 		/*
   1425 		 * If it succeds later, it would hit ccb which will have been
   1426 		 * already reused for something else. Not good. Cross
   1427 		 * fingers and hope for best. XXX do controller reset?
   1428 		 */
   1429 		aprint_error_dev(sc->sc_dev, "polled command timed out\n");
   1430 
   1431 		/* Invoke the callback to clean state anyway */
   1432 		struct nvme_cqe cqe;
   1433 		memset(&cqe, 0, sizeof(cqe));
   1434 		ccb->ccb_done(q, ccb, &cqe);
   1435 
   1436 		return 1;
   1437 	}
   1438 }
   1439 
   1440 static void
   1441 nvme_poll_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1442 {
   1443 	struct nvme_sqe *sqe = slot;
   1444 	struct nvme_poll_state *state = ccb->ccb_cookie;
   1445 
   1446 	*sqe = state->s;
   1447 }
   1448 
   1449 static void
   1450 nvme_poll_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1451     struct nvme_cqe *cqe)
   1452 {
   1453 	struct nvme_poll_state *state = ccb->ccb_cookie;
   1454 
   1455 	state->c = *cqe;
   1456 	SET(state->c.flags, htole16(NVME_CQE_PHASE));
   1457 
   1458 	ccb->ccb_cookie = state->cookie;
   1459 	state->done(q, ccb, &state->c);
   1460 }
   1461 
   1462 static void
   1463 nvme_sqe_fill(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1464 {
   1465 	struct nvme_sqe *src = ccb->ccb_cookie;
   1466 	struct nvme_sqe *dst = slot;
   1467 
   1468 	*dst = *src;
   1469 }
   1470 
   1471 static void
   1472 nvme_empty_done(struct nvme_queue *q, struct nvme_ccb *ccb,
   1473     struct nvme_cqe *cqe)
   1474 {
   1475 }
   1476 
   1477 void
   1478 nvme_op_cq_done(struct nvme_softc *sc,
   1479     struct nvme_queue *q, struct nvme_ccb *ccb)
   1480 {
   1481 	/* nop */
   1482 }
   1483 
   1484 static int
   1485 nvme_q_complete(struct nvme_softc *sc, struct nvme_queue *q)
   1486 {
   1487 	struct nvme_ccb *ccb;
   1488 	struct nvme_cqe *ring = NVME_DMA_KVA(q->q_cq_dmamem), *cqe;
   1489 	uint16_t flags;
   1490 	int rv = 0;
   1491 
   1492 	mutex_enter(&q->q_cq_mtx);
   1493 
   1494 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_POSTREAD);
   1495 	for (;;) {
   1496 		cqe = &ring[q->q_cq_head];
   1497 		flags = lemtoh16(&cqe->flags);
   1498 		if ((flags & NVME_CQE_PHASE) != q->q_cq_phase)
   1499 			break;
   1500 
   1501 		/*
   1502 		 * Make sure we have read the flags _before_ we read
   1503 		 * the cid.  Otherwise the CPU might speculatively read
   1504 		 * the cid before the entry has been assigned to our
   1505 		 * phase.
   1506 		 */
   1507 		nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_POSTREAD);
   1508 
   1509 		ccb = &q->q_ccbs[lemtoh16(&cqe->cid)];
   1510 
   1511 		if (++q->q_cq_head >= q->q_entries) {
   1512 			q->q_cq_head = 0;
   1513 			q->q_cq_phase ^= NVME_CQE_PHASE;
   1514 		}
   1515 
   1516 #ifdef DEBUG
   1517 		/*
   1518 		 * If we get spurious completion notification, something
   1519 		 * is seriously hosed up. Very likely DMA to some random
   1520 		 * memory place happened, so just bail out.
   1521 		 */
   1522 		if ((intptr_t)ccb->ccb_cookie == NVME_CCB_FREE) {
   1523 			panic("%s: invalid ccb detected",
   1524 			    device_xname(sc->sc_dev));
   1525 			/* NOTREACHED */
   1526 		}
   1527 #endif
   1528 
   1529 		rv++;
   1530 
   1531 		sc->sc_ops->op_cq_done(sc, q, ccb);
   1532 
   1533 		/*
   1534 		 * Unlock the mutex before calling the ccb_done callback
   1535 		 * and re-lock afterwards. The callback triggers lddone()
   1536 		 * which schedules another i/o, and also calls nvme_ccb_put().
   1537 		 * Unlock/relock avoids possibility of deadlock.
   1538 		 */
   1539 		mutex_exit(&q->q_cq_mtx);
   1540 		ccb->ccb_done(q, ccb, cqe);
   1541 		mutex_enter(&q->q_cq_mtx);
   1542 	}
   1543 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_PREREAD);
   1544 
   1545 	if (rv)
   1546 		nvme_write4(sc, q->q_cqhdbl, q->q_cq_head);
   1547 
   1548 	mutex_exit(&q->q_cq_mtx);
   1549 
   1550 	return rv;
   1551 }
   1552 
   1553 static void
   1554 nvme_q_wait_complete(struct nvme_softc *sc,
   1555     struct nvme_queue *q, bool (*finished)(void *), void *cookie)
   1556 {
   1557 	mutex_enter(&q->q_ccb_mtx);
   1558 	if (finished(cookie))
   1559 		goto out;
   1560 
   1561 	for(;;) {
   1562 		q->q_ccb_waiting = true;
   1563 		cv_wait(&q->q_ccb_wait, &q->q_ccb_mtx);
   1564 
   1565 		if (finished(cookie))
   1566 			break;
   1567 	}
   1568 
   1569 out:
   1570 	mutex_exit(&q->q_ccb_mtx);
   1571 }
   1572 
   1573 static int
   1574 nvme_identify(struct nvme_softc *sc, u_int mps)
   1575 {
   1576 	char sn[41], mn[81], fr[17];
   1577 	struct nvm_identify_controller *identify;
   1578 	struct nvme_dmamem *mem;
   1579 	struct nvme_ccb *ccb;
   1580 	u_int mdts;
   1581 	int rv = 1;
   1582 
   1583 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1584 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
   1585 
   1586 	mem = nvme_dmamem_alloc(sc, sizeof(*identify));
   1587 	if (mem == NULL)
   1588 		return 1;
   1589 
   1590 	ccb->ccb_done = nvme_empty_done;
   1591 	ccb->ccb_cookie = mem;
   1592 
   1593 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_PREREAD);
   1594 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_fill_identify,
   1595 	    NVME_TIMO_IDENT);
   1596 	nvme_dmamem_sync(sc, mem, BUS_DMASYNC_POSTREAD);
   1597 
   1598 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1599 
   1600 	if (rv != 0)
   1601 		goto done;
   1602 
   1603 	identify = NVME_DMA_KVA(mem);
   1604 	sc->sc_identify = *identify;
   1605 	identify = NULL;
   1606 
   1607 	/* Convert data to host endian */
   1608 	nvme_identify_controller_swapbytes(&sc->sc_identify);
   1609 
   1610 	strnvisx(sn, sizeof(sn), (const char *)sc->sc_identify.sn,
   1611 	    sizeof(sc->sc_identify.sn), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1612 	strnvisx(mn, sizeof(mn), (const char *)sc->sc_identify.mn,
   1613 	    sizeof(sc->sc_identify.mn), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1614 	strnvisx(fr, sizeof(fr), (const char *)sc->sc_identify.fr,
   1615 	    sizeof(sc->sc_identify.fr), VIS_TRIM|VIS_SAFE|VIS_OCTAL);
   1616 	aprint_normal_dev(sc->sc_dev, "%s, firmware %s, serial %s\n", mn, fr,
   1617 	    sn);
   1618 
   1619 	strlcpy(sc->sc_modelname, mn, sizeof(sc->sc_modelname));
   1620 
   1621 	if (sc->sc_identify.mdts > 0) {
   1622 		mdts = (1 << sc->sc_identify.mdts) * (1 << mps);
   1623 		if (mdts < sc->sc_mdts)
   1624 			sc->sc_mdts = mdts;
   1625 	}
   1626 
   1627 	sc->sc_nn = sc->sc_identify.nn;
   1628 
   1629 done:
   1630 	nvme_dmamem_free(sc, mem);
   1631 
   1632 	return rv;
   1633 }
   1634 
   1635 static int
   1636 nvme_q_create(struct nvme_softc *sc, struct nvme_queue *q)
   1637 {
   1638 	struct nvme_sqe_q sqe;
   1639 	struct nvme_ccb *ccb;
   1640 	int rv;
   1641 
   1642 	if (sc->sc_use_mq && sc->sc_intr_establish(sc, q->q_id, q) != 0)
   1643 		return 1;
   1644 
   1645 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1646 	KASSERT(ccb != NULL);
   1647 
   1648 	ccb->ccb_done = nvme_empty_done;
   1649 	ccb->ccb_cookie = &sqe;
   1650 
   1651 	memset(&sqe, 0, sizeof(sqe));
   1652 	sqe.opcode = NVM_ADMIN_ADD_IOCQ;
   1653 	htolem64(&sqe.prp1, NVME_DMA_DVA(q->q_cq_dmamem));
   1654 	htolem16(&sqe.qsize, q->q_entries - 1);
   1655 	htolem16(&sqe.qid, q->q_id);
   1656 	sqe.qflags = NVM_SQE_CQ_IEN | NVM_SQE_Q_PC;
   1657 	if (sc->sc_use_mq)
   1658 		htolem16(&sqe.cqid, q->q_id);	/* qid == vector */
   1659 
   1660 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1661 	if (rv != 0)
   1662 		goto fail;
   1663 
   1664 	ccb->ccb_done = nvme_empty_done;
   1665 	ccb->ccb_cookie = &sqe;
   1666 
   1667 	memset(&sqe, 0, sizeof(sqe));
   1668 	sqe.opcode = NVM_ADMIN_ADD_IOSQ;
   1669 	htolem64(&sqe.prp1, NVME_DMA_DVA(q->q_sq_dmamem));
   1670 	htolem16(&sqe.qsize, q->q_entries - 1);
   1671 	htolem16(&sqe.qid, q->q_id);
   1672 	htolem16(&sqe.cqid, q->q_id);
   1673 	sqe.qflags = NVM_SQE_Q_PC;
   1674 
   1675 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1676 	if (rv != 0)
   1677 		goto fail;
   1678 
   1679 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1680 	return 0;
   1681 
   1682 fail:
   1683 	if (sc->sc_use_mq)
   1684 		sc->sc_intr_disestablish(sc, q->q_id);
   1685 
   1686 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1687 	return rv;
   1688 }
   1689 
   1690 static int
   1691 nvme_q_delete(struct nvme_softc *sc, struct nvme_queue *q)
   1692 {
   1693 	struct nvme_sqe_q sqe;
   1694 	struct nvme_ccb *ccb;
   1695 	int rv;
   1696 
   1697 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1698 	KASSERT(ccb != NULL);
   1699 
   1700 	ccb->ccb_done = nvme_empty_done;
   1701 	ccb->ccb_cookie = &sqe;
   1702 
   1703 	memset(&sqe, 0, sizeof(sqe));
   1704 	sqe.opcode = NVM_ADMIN_DEL_IOSQ;
   1705 	htolem16(&sqe.qid, q->q_id);
   1706 
   1707 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1708 	if (rv != 0)
   1709 		goto fail;
   1710 
   1711 	ccb->ccb_done = nvme_empty_done;
   1712 	ccb->ccb_cookie = &sqe;
   1713 
   1714 	memset(&sqe, 0, sizeof(sqe));
   1715 	sqe.opcode = NVM_ADMIN_DEL_IOCQ;
   1716 	htolem16(&sqe.qid, q->q_id);
   1717 
   1718 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_sqe_fill, NVME_TIMO_QOP);
   1719 	if (rv != 0)
   1720 		goto fail;
   1721 
   1722 fail:
   1723 	nvme_ccb_put(sc->sc_admin_q, ccb);
   1724 
   1725 	if (rv == 0 && sc->sc_use_mq) {
   1726 		if (sc->sc_intr_disestablish(sc, q->q_id))
   1727 			rv = 1;
   1728 	}
   1729 
   1730 	return rv;
   1731 }
   1732 
   1733 static void
   1734 nvme_fill_identify(struct nvme_queue *q, struct nvme_ccb *ccb, void *slot)
   1735 {
   1736 	struct nvme_sqe *sqe = slot;
   1737 	struct nvme_dmamem *mem = ccb->ccb_cookie;
   1738 
   1739 	sqe->opcode = NVM_ADMIN_IDENTIFY;
   1740 	htolem64(&sqe->entry.prp[0], NVME_DMA_DVA(mem));
   1741 	htolem32(&sqe->cdw10, 1);
   1742 }
   1743 
   1744 static int
   1745 nvme_set_number_of_queues(struct nvme_softc *sc, u_int nq, u_int *ncqa,
   1746     u_int *nsqa)
   1747 {
   1748 	struct nvme_pt_state state;
   1749 	struct nvme_pt_command pt;
   1750 	struct nvme_ccb *ccb;
   1751 	int rv;
   1752 
   1753 	ccb = nvme_ccb_get(sc->sc_admin_q, false);
   1754 	KASSERT(ccb != NULL); /* it's a bug if we don't have spare ccb here */
   1755 
   1756 	memset(&pt, 0, sizeof(pt));
   1757 	pt.cmd.opcode = NVM_ADMIN_SET_FEATURES;
   1758 	pt.cmd.cdw10 = NVM_FEATURE_NUMBER_OF_QUEUES;
   1759 	pt.cmd.cdw11 = ((nq - 1) << 16) | (nq - 1);
   1760 
   1761 	memset(&state, 0, sizeof(state));
   1762 	state.pt = &pt;
   1763 	state.finished = false;
   1764 
   1765 	ccb->ccb_done = nvme_pt_done;
   1766 	ccb->ccb_cookie = &state;
   1767 
   1768 	rv = nvme_poll(sc, sc->sc_admin_q, ccb, nvme_pt_fill, NVME_TIMO_QOP);
   1769 
   1770 	if (rv != 0) {
   1771 		*ncqa = *nsqa = 0;
   1772 		return EIO;
   1773 	}
   1774 
   1775 	*ncqa = (pt.cpl.cdw0 >> 16) + 1;
   1776 	*nsqa = (pt.cpl.cdw0 & 0xffff) + 1;
   1777 
   1778 	return 0;
   1779 }
   1780 
   1781 static int
   1782 nvme_ccbs_alloc(struct nvme_queue *q, uint16_t nccbs)
   1783 {
   1784 	struct nvme_softc *sc = q->q_sc;
   1785 	struct nvme_ccb *ccb;
   1786 	bus_addr_t off;
   1787 	uint64_t *prpl;
   1788 	u_int i;
   1789 
   1790 	mutex_init(&q->q_ccb_mtx, MUTEX_DEFAULT, IPL_BIO);
   1791 	cv_init(&q->q_ccb_wait, "nvmeqw");
   1792 	q->q_ccb_waiting = false;
   1793 	SIMPLEQ_INIT(&q->q_ccb_list);
   1794 
   1795 	q->q_ccbs = kmem_alloc(sizeof(*ccb) * nccbs, KM_SLEEP);
   1796 
   1797 	q->q_nccbs = nccbs;
   1798 	q->q_ccb_prpls = nvme_dmamem_alloc(sc,
   1799 	    sizeof(*prpl) * sc->sc_max_sgl * nccbs);
   1800 
   1801 	prpl = NVME_DMA_KVA(q->q_ccb_prpls);
   1802 	off = 0;
   1803 
   1804 	for (i = 0; i < nccbs; i++) {
   1805 		ccb = &q->q_ccbs[i];
   1806 
   1807 		if (bus_dmamap_create(sc->sc_dmat, sc->sc_mdts,
   1808 		    sc->sc_max_sgl + 1 /* we get a free prp in the sqe */,
   1809 		    sc->sc_mps, sc->sc_mps, BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW,
   1810 		    &ccb->ccb_dmamap) != 0)
   1811 			goto free_maps;
   1812 
   1813 		ccb->ccb_id = i;
   1814 		ccb->ccb_prpl = prpl;
   1815 		ccb->ccb_prpl_off = off;
   1816 		ccb->ccb_prpl_dva = NVME_DMA_DVA(q->q_ccb_prpls) + off;
   1817 
   1818 		SIMPLEQ_INSERT_TAIL(&q->q_ccb_list, ccb, ccb_entry);
   1819 
   1820 		prpl += sc->sc_max_sgl;
   1821 		off += sizeof(*prpl) * sc->sc_max_sgl;
   1822 	}
   1823 
   1824 	return 0;
   1825 
   1826 free_maps:
   1827 	nvme_ccbs_free(q);
   1828 	return 1;
   1829 }
   1830 
   1831 static struct nvme_ccb *
   1832 nvme_ccb_get(struct nvme_queue *q, bool wait)
   1833 {
   1834 	struct nvme_ccb *ccb = NULL;
   1835 
   1836 	mutex_enter(&q->q_ccb_mtx);
   1837 again:
   1838 	ccb = SIMPLEQ_FIRST(&q->q_ccb_list);
   1839 	if (ccb != NULL) {
   1840 		SIMPLEQ_REMOVE_HEAD(&q->q_ccb_list, ccb_entry);
   1841 #ifdef DEBUG
   1842 		ccb->ccb_cookie = NULL;
   1843 #endif
   1844 	} else {
   1845 		if (__predict_false(wait)) {
   1846 			q->q_ccb_waiting = true;
   1847 			cv_wait(&q->q_ccb_wait, &q->q_ccb_mtx);
   1848 			goto again;
   1849 		}
   1850 	}
   1851 	mutex_exit(&q->q_ccb_mtx);
   1852 
   1853 	return ccb;
   1854 }
   1855 
   1856 static struct nvme_ccb *
   1857 nvme_ccb_get_bio(struct nvme_softc *sc, struct buf *bp,
   1858     struct nvme_queue **selq)
   1859 {
   1860 	u_int cpuindex = cpu_index((bp && bp->b_ci) ? bp->b_ci : curcpu());
   1861 
   1862 	/*
   1863 	 * Find a queue with available ccbs, preferring the originating
   1864 	 * CPU's queue.
   1865 	 */
   1866 
   1867 	for (u_int qoff = 0; qoff < sc->sc_nq; qoff++) {
   1868 		struct nvme_queue *q = sc->sc_q[(cpuindex + qoff) % sc->sc_nq];
   1869 		struct nvme_ccb *ccb;
   1870 
   1871 		mutex_enter(&q->q_ccb_mtx);
   1872 		ccb = SIMPLEQ_FIRST(&q->q_ccb_list);
   1873 		if (ccb != NULL) {
   1874 			SIMPLEQ_REMOVE_HEAD(&q->q_ccb_list, ccb_entry);
   1875 #ifdef DEBUG
   1876 			ccb->ccb_cookie = NULL;
   1877 #endif
   1878 		}
   1879 		mutex_exit(&q->q_ccb_mtx);
   1880 
   1881 		if (ccb != NULL) {
   1882 			*selq = q;
   1883 			return ccb;
   1884 		}
   1885 	}
   1886 
   1887 	return NULL;
   1888 }
   1889 
   1890 static void
   1891 nvme_ccb_put(struct nvme_queue *q, struct nvme_ccb *ccb)
   1892 {
   1893 
   1894 	mutex_enter(&q->q_ccb_mtx);
   1895 #ifdef DEBUG
   1896 	ccb->ccb_cookie = (void *)NVME_CCB_FREE;
   1897 #endif
   1898 	SIMPLEQ_INSERT_HEAD(&q->q_ccb_list, ccb, ccb_entry);
   1899 
   1900 	/* It's unlikely there are any waiters, it's not used for regular I/O */
   1901 	if (__predict_false(q->q_ccb_waiting)) {
   1902 		q->q_ccb_waiting = false;
   1903 		cv_broadcast(&q->q_ccb_wait);
   1904 	}
   1905 
   1906 	mutex_exit(&q->q_ccb_mtx);
   1907 }
   1908 
   1909 static void
   1910 nvme_ccbs_free(struct nvme_queue *q)
   1911 {
   1912 	struct nvme_softc *sc = q->q_sc;
   1913 	struct nvme_ccb *ccb;
   1914 
   1915 	mutex_enter(&q->q_ccb_mtx);
   1916 	while ((ccb = SIMPLEQ_FIRST(&q->q_ccb_list)) != NULL) {
   1917 		SIMPLEQ_REMOVE_HEAD(&q->q_ccb_list, ccb_entry);
   1918 		/*
   1919 		 * bus_dmamap_destroy() may call vm_map_lock() and rw_enter()
   1920 		 * internally. don't hold spin mutex
   1921 		 */
   1922 		mutex_exit(&q->q_ccb_mtx);
   1923 		bus_dmamap_destroy(sc->sc_dmat, ccb->ccb_dmamap);
   1924 		mutex_enter(&q->q_ccb_mtx);
   1925 	}
   1926 	mutex_exit(&q->q_ccb_mtx);
   1927 
   1928 	nvme_dmamem_free(sc, q->q_ccb_prpls);
   1929 	kmem_free(q->q_ccbs, sizeof(*ccb) * q->q_nccbs);
   1930 	q->q_ccbs = NULL;
   1931 	cv_destroy(&q->q_ccb_wait);
   1932 	mutex_destroy(&q->q_ccb_mtx);
   1933 }
   1934 
   1935 static struct nvme_queue *
   1936 nvme_q_alloc(struct nvme_softc *sc, uint16_t id, u_int entries, u_int dstrd)
   1937 {
   1938 	struct nvme_queue *q;
   1939 
   1940 	q = kmem_alloc(sizeof(*q), KM_SLEEP);
   1941 	q->q_sc = sc;
   1942 	q->q_sq_dmamem = nvme_dmamem_alloc(sc,
   1943 	    sizeof(struct nvme_sqe) * entries);
   1944 	if (q->q_sq_dmamem == NULL)
   1945 		goto free;
   1946 
   1947 	q->q_cq_dmamem = nvme_dmamem_alloc(sc,
   1948 	    sizeof(struct nvme_cqe) * entries);
   1949 	if (q->q_cq_dmamem == NULL)
   1950 		goto free_sq;
   1951 
   1952 	memset(NVME_DMA_KVA(q->q_sq_dmamem), 0, NVME_DMA_LEN(q->q_sq_dmamem));
   1953 	memset(NVME_DMA_KVA(q->q_cq_dmamem), 0, NVME_DMA_LEN(q->q_cq_dmamem));
   1954 
   1955 	mutex_init(&q->q_sq_mtx, MUTEX_DEFAULT, IPL_BIO);
   1956 	mutex_init(&q->q_cq_mtx, MUTEX_DEFAULT, IPL_BIO);
   1957 	q->q_sqtdbl = NVME_SQTDBL(id, dstrd);
   1958 	q->q_cqhdbl = NVME_CQHDBL(id, dstrd);
   1959 	q->q_id = id;
   1960 	q->q_entries = entries;
   1961 	q->q_sq_tail = 0;
   1962 	q->q_cq_head = 0;
   1963 	q->q_cq_phase = NVME_CQE_PHASE;
   1964 
   1965 	if (sc->sc_ops->op_q_alloc != NULL) {
   1966 		if (sc->sc_ops->op_q_alloc(sc, q) != 0)
   1967 			goto free_cq;
   1968 	}
   1969 
   1970 	nvme_dmamem_sync(sc, q->q_sq_dmamem, BUS_DMASYNC_PREWRITE);
   1971 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_PREREAD);
   1972 
   1973 	/*
   1974 	 * Due to definition of full and empty queue (queue is empty
   1975 	 * when head == tail, full when tail is one less then head),
   1976 	 * we can actually only have (entries - 1) in-flight commands.
   1977 	 */
   1978 	if (nvme_ccbs_alloc(q, entries - 1) != 0) {
   1979 		aprint_error_dev(sc->sc_dev, "unable to allocate ccbs\n");
   1980 		goto free_cq;
   1981 	}
   1982 
   1983 	return q;
   1984 
   1985 free_cq:
   1986 	nvme_dmamem_free(sc, q->q_cq_dmamem);
   1987 free_sq:
   1988 	nvme_dmamem_free(sc, q->q_sq_dmamem);
   1989 free:
   1990 	kmem_free(q, sizeof(*q));
   1991 
   1992 	return NULL;
   1993 }
   1994 
   1995 static void
   1996 nvme_q_reset(struct nvme_softc *sc, struct nvme_queue *q)
   1997 {
   1998 
   1999 	memset(NVME_DMA_KVA(q->q_sq_dmamem), 0, NVME_DMA_LEN(q->q_sq_dmamem));
   2000 	memset(NVME_DMA_KVA(q->q_cq_dmamem), 0, NVME_DMA_LEN(q->q_cq_dmamem));
   2001 
   2002 	q->q_sq_tail = 0;
   2003 	q->q_cq_head = 0;
   2004 	q->q_cq_phase = NVME_CQE_PHASE;
   2005 
   2006 	nvme_dmamem_sync(sc, q->q_sq_dmamem, BUS_DMASYNC_PREWRITE);
   2007 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_PREREAD);
   2008 }
   2009 
   2010 static void
   2011 nvme_q_free(struct nvme_softc *sc, struct nvme_queue *q)
   2012 {
   2013 	nvme_ccbs_free(q);
   2014 	mutex_destroy(&q->q_sq_mtx);
   2015 	mutex_destroy(&q->q_cq_mtx);
   2016 	nvme_dmamem_sync(sc, q->q_cq_dmamem, BUS_DMASYNC_POSTREAD);
   2017 	nvme_dmamem_sync(sc, q->q_sq_dmamem, BUS_DMASYNC_POSTWRITE);
   2018 
   2019 	if (sc->sc_ops->op_q_alloc != NULL)
   2020 		sc->sc_ops->op_q_free(sc, q);
   2021 
   2022 	nvme_dmamem_free(sc, q->q_cq_dmamem);
   2023 	nvme_dmamem_free(sc, q->q_sq_dmamem);
   2024 	kmem_free(q, sizeof(*q));
   2025 }
   2026 
   2027 int
   2028 nvme_intr(void *xsc)
   2029 {
   2030 	struct nvme_softc *sc = xsc;
   2031 
   2032 	/*
   2033 	 * INTx is level triggered, controller deasserts the interrupt only
   2034 	 * when we advance command queue head via write to the doorbell.
   2035 	 * Tell the controller to block the interrupts while we process
   2036 	 * the queue(s).
   2037 	 */
   2038 	nvme_write4(sc, NVME_INTMS, 1);
   2039 
   2040 	softint_schedule(sc->sc_softih[0]);
   2041 
   2042 	/* don't know, might not have been for us */
   2043 	return 1;
   2044 }
   2045 
   2046 void
   2047 nvme_softintr_intx(void *xq)
   2048 {
   2049 	struct nvme_queue *q = xq;
   2050 	struct nvme_softc *sc = q->q_sc;
   2051 
   2052 	nvme_q_complete(sc, sc->sc_admin_q);
   2053 	if (sc->sc_q != NULL)
   2054 	        nvme_q_complete(sc, sc->sc_q[0]);
   2055 
   2056 	/*
   2057 	 * Processing done, tell controller to issue interrupts again. There
   2058 	 * is no race, as NVMe spec requires the controller to maintain state,
   2059 	 * and assert the interrupt whenever there are unacknowledged
   2060 	 * completion queue entries.
   2061 	 */
   2062 	nvme_write4(sc, NVME_INTMC, 1);
   2063 }
   2064 
   2065 int
   2066 nvme_intr_msi(void *xq)
   2067 {
   2068 	struct nvme_queue *q = xq;
   2069 
   2070 	KASSERT(q);
   2071 	KASSERT(q->q_sc);
   2072 	KASSERT(q->q_sc->sc_softih);
   2073 	KASSERT(q->q_sc->sc_softih[q->q_id]);
   2074 
   2075 	/*
   2076 	 * MSI/MSI-X are edge triggered, so can handover processing to softint
   2077 	 * without masking the interrupt.
   2078 	 */
   2079 	softint_schedule(q->q_sc->sc_softih[q->q_id]);
   2080 
   2081 	return 1;
   2082 }
   2083 
   2084 void
   2085 nvme_softintr_msi(void *xq)
   2086 {
   2087 	struct nvme_queue *q = xq;
   2088 	struct nvme_softc *sc = q->q_sc;
   2089 
   2090 	nvme_q_complete(sc, q);
   2091 }
   2092 
   2093 struct nvme_dmamem *
   2094 nvme_dmamem_alloc(struct nvme_softc *sc, size_t size)
   2095 {
   2096 	struct nvme_dmamem *ndm;
   2097 	int nsegs;
   2098 
   2099 	ndm = kmem_zalloc(sizeof(*ndm), KM_SLEEP);
   2100 	if (ndm == NULL)
   2101 		return NULL;
   2102 
   2103 	ndm->ndm_size = size;
   2104 
   2105 	if (bus_dmamap_create(sc->sc_dmat, size, btoc(round_page(size)), size, 0,
   2106 	    BUS_DMA_WAITOK | BUS_DMA_ALLOCNOW, &ndm->ndm_map) != 0)
   2107 		goto ndmfree;
   2108 
   2109 	if (bus_dmamem_alloc(sc->sc_dmat, size, sc->sc_mps, 0, &ndm->ndm_seg,
   2110 	    1, &nsegs, BUS_DMA_WAITOK) != 0)
   2111 		goto destroy;
   2112 
   2113 	if (bus_dmamem_map(sc->sc_dmat, &ndm->ndm_seg, nsegs, size,
   2114 	    &ndm->ndm_kva, BUS_DMA_WAITOK) != 0)
   2115 		goto free;
   2116 
   2117 	if (bus_dmamap_load(sc->sc_dmat, ndm->ndm_map, ndm->ndm_kva, size,
   2118 	    NULL, BUS_DMA_WAITOK) != 0)
   2119 		goto unmap;
   2120 
   2121 	memset(ndm->ndm_kva, 0, size);
   2122 	bus_dmamap_sync(sc->sc_dmat, ndm->ndm_map, 0, size, BUS_DMASYNC_PREREAD);
   2123 
   2124 	return ndm;
   2125 
   2126 unmap:
   2127 	bus_dmamem_unmap(sc->sc_dmat, ndm->ndm_kva, size);
   2128 free:
   2129 	bus_dmamem_free(sc->sc_dmat, &ndm->ndm_seg, 1);
   2130 destroy:
   2131 	bus_dmamap_destroy(sc->sc_dmat, ndm->ndm_map);
   2132 ndmfree:
   2133 	kmem_free(ndm, sizeof(*ndm));
   2134 	return NULL;
   2135 }
   2136 
   2137 void
   2138 nvme_dmamem_sync(struct nvme_softc *sc, struct nvme_dmamem *mem, int ops)
   2139 {
   2140 	bus_dmamap_sync(sc->sc_dmat, NVME_DMA_MAP(mem),
   2141 	    0, NVME_DMA_LEN(mem), ops);
   2142 }
   2143 
   2144 void
   2145 nvme_dmamem_free(struct nvme_softc *sc, struct nvme_dmamem *ndm)
   2146 {
   2147 	bus_dmamap_unload(sc->sc_dmat, ndm->ndm_map);
   2148 	bus_dmamem_unmap(sc->sc_dmat, ndm->ndm_kva, ndm->ndm_size);
   2149 	bus_dmamem_free(sc->sc_dmat, &ndm->ndm_seg, 1);
   2150 	bus_dmamap_destroy(sc->sc_dmat, ndm->ndm_map);
   2151 	kmem_free(ndm, sizeof(*ndm));
   2152 }
   2153 
   2154 /*
   2155  * ioctl
   2156  */
   2157 
   2158 dev_type_open(nvmeopen);
   2159 dev_type_close(nvmeclose);
   2160 dev_type_ioctl(nvmeioctl);
   2161 
   2162 const struct cdevsw nvme_cdevsw = {
   2163 	.d_open = nvmeopen,
   2164 	.d_close = nvmeclose,
   2165 	.d_read = noread,
   2166 	.d_write = nowrite,
   2167 	.d_ioctl = nvmeioctl,
   2168 	.d_stop = nostop,
   2169 	.d_tty = notty,
   2170 	.d_poll = nopoll,
   2171 	.d_mmap = nommap,
   2172 	.d_kqfilter = nokqfilter,
   2173 	.d_discard = nodiscard,
   2174 	.d_flag = D_OTHER,
   2175 };
   2176 
   2177 /*
   2178  * Accept an open operation on the control device.
   2179  */
   2180 int
   2181 nvmeopen(dev_t dev, int flag, int mode, struct lwp *l)
   2182 {
   2183 	struct nvme_softc *sc;
   2184 	int unit = minor(dev) / 0x10000;
   2185 	int nsid = minor(dev) & 0xffff;
   2186 	int nsidx;
   2187 
   2188 	if ((sc = device_lookup_private(&nvme_cd, unit)) == NULL)
   2189 		return ENXIO;
   2190 	if ((sc->sc_flags & NVME_F_ATTACHED) == 0)
   2191 		return ENXIO;
   2192 
   2193 	if (nsid == 0) {
   2194 		/* controller */
   2195 		if (ISSET(sc->sc_flags, NVME_F_OPEN))
   2196 			return EBUSY;
   2197 		SET(sc->sc_flags, NVME_F_OPEN);
   2198 	} else {
   2199 		/* namespace */
   2200 		nsidx = nsid - 1;
   2201 		if (nsidx >= sc->sc_nn || sc->sc_namespaces[nsidx].dev == NULL)
   2202 			return ENXIO;
   2203 		if (ISSET(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN))
   2204 			return EBUSY;
   2205 		SET(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN);
   2206 	}
   2207 	return 0;
   2208 }
   2209 
   2210 /*
   2211  * Accept the last close on the control device.
   2212  */
   2213 int
   2214 nvmeclose(dev_t dev, int flag, int mode, struct lwp *l)
   2215 {
   2216 	struct nvme_softc *sc;
   2217 	int unit = minor(dev) / 0x10000;
   2218 	int nsid = minor(dev) & 0xffff;
   2219 	int nsidx;
   2220 
   2221 	sc = device_lookup_private(&nvme_cd, unit);
   2222 	if (sc == NULL)
   2223 		return ENXIO;
   2224 
   2225 	if (nsid == 0) {
   2226 		/* controller */
   2227 		CLR(sc->sc_flags, NVME_F_OPEN);
   2228 	} else {
   2229 		/* namespace */
   2230 		nsidx = nsid - 1;
   2231 		if (nsidx >= sc->sc_nn)
   2232 			return ENXIO;
   2233 		CLR(sc->sc_namespaces[nsidx].flags, NVME_NS_F_OPEN);
   2234 	}
   2235 
   2236 	return 0;
   2237 }
   2238 
   2239 /*
   2240  * Handle control operations.
   2241  */
   2242 int
   2243 nvmeioctl(dev_t dev, u_long cmd, void *data, int flag, struct lwp *l)
   2244 {
   2245 	struct nvme_softc *sc;
   2246 	int unit = minor(dev) / 0x10000;
   2247 	int nsid = minor(dev) & 0xffff;
   2248 	struct nvme_pt_command *pt;
   2249 
   2250 	sc = device_lookup_private(&nvme_cd, unit);
   2251 	if (sc == NULL)
   2252 		return ENXIO;
   2253 
   2254 	switch (cmd) {
   2255 	case NVME_PASSTHROUGH_CMD:
   2256 		pt = data;
   2257 		return nvme_command_passthrough(sc, data,
   2258 		    nsid == 0 ? pt->cmd.nsid : (uint32_t)nsid, l, nsid == 0);
   2259 	}
   2260 
   2261 	return ENOTTY;
   2262 }
   2263