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