xref: /freebsd/sys/dev/nvme/nvme_ctrlr.c (revision c4fde87a3236b500246d4fce76dbca2a3d64f73a)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (C) 2012-2016 Intel Corporation
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26  * SUCH DAMAGE.
27  */
28 
29 #include "opt_nvme.h"
30 
31 #include <sys/param.h>
32 #include <sys/systm.h>
33 #include <sys/buf.h>
34 #include <sys/bus.h>
35 #include <sys/conf.h>
36 #include <sys/ioccom.h>
37 #include <sys/proc.h>
38 #include <sys/smp.h>
39 #include <sys/uio.h>
40 #include <sys/sbuf.h>
41 #include <sys/endian.h>
42 #include <sys/stdarg.h>
43 #include <vm/vm.h>
44 #include <vm/vm_page.h>
45 #include <vm/vm_extern.h>
46 #include <vm/vm_map.h>
47 
48 #include <dev/pci/pcivar.h>
49 
50 #include "nvme_private.h"
51 #include "nvme_linux.h"
52 
53 #include "nvme_if.h"
54 
55 #define B4_CHK_RDY_DELAY_MS	2300		/* work around controller bug */
56 
57 static void nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
58     struct nvme_async_event_request *aer);
59 
60 static void
61 nvme_ctrlr_barrier(struct nvme_controller *ctrlr, int flags)
62 {
63 	bus_barrier(ctrlr->resource, 0, rman_get_size(ctrlr->resource), flags);
64 }
65 
66 static void
67 nvme_ctrlr_devctl_va(struct nvme_controller *ctrlr, const char *type,
68     const char *msg, va_list ap)
69 {
70 	struct sbuf sb;
71 	int error;
72 
73 	if (sbuf_new(&sb, NULL, 0, SBUF_AUTOEXTEND | SBUF_NOWAIT) == NULL)
74 		return;
75 	sbuf_printf(&sb, "name=\"%s\" ", device_get_nameunit(ctrlr->dev));
76 	sbuf_vprintf(&sb, msg, ap);
77 	error = sbuf_finish(&sb);
78 	if (error == 0)
79 		devctl_notify("nvme", "controller", type, sbuf_data(&sb));
80 	sbuf_delete(&sb);
81 }
82 
83 static void
84 nvme_ctrlr_devctl(struct nvme_controller *ctrlr, const char *type, const char *msg, ...)
85 {
86 	va_list ap;
87 
88 	va_start(ap, msg);
89 	nvme_ctrlr_devctl_va(ctrlr, type, msg, ap);
90 	va_end(ap);
91 }
92 
93 static void
94 nvme_ctrlr_devctl_log(struct nvme_controller *ctrlr, const char *type, const char *msg, ...)
95 {
96 	struct sbuf sb;
97 	va_list ap;
98 	int error;
99 
100 	if (sbuf_new(&sb, NULL, 0, SBUF_AUTOEXTEND | SBUF_NOWAIT) == NULL)
101 		return;
102 	sbuf_printf(&sb, "%s: ", device_get_nameunit(ctrlr->dev));
103 	va_start(ap, msg);
104 	sbuf_vprintf(&sb, msg, ap);
105 	va_end(ap);
106 	error = sbuf_finish(&sb);
107 	if (error == 0)
108 		printf("%s\n", sbuf_data(&sb));
109 	sbuf_delete(&sb);
110 	va_start(ap, msg);
111 	nvme_ctrlr_devctl_va(ctrlr, type, msg, ap);
112 	va_end(ap);
113 }
114 
115 static int
116 nvme_ctrlr_construct_admin_qpair(struct nvme_controller *ctrlr)
117 {
118 	struct nvme_qpair	*qpair;
119 	uint32_t		num_entries;
120 	int			error;
121 
122 	qpair = &ctrlr->adminq;
123 	qpair->id = 0;
124 	qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
125 	qpair->domain = ctrlr->domain;
126 
127 	num_entries = NVME_ADMIN_ENTRIES;
128 	TUNABLE_INT_FETCH("hw.nvme.admin_entries", &num_entries);
129 	/*
130 	 * If admin_entries was overridden to an invalid value, revert it
131 	 *  back to our default value.
132 	 */
133 	if (num_entries < NVME_MIN_ADMIN_ENTRIES ||
134 	    num_entries > NVME_MAX_ADMIN_ENTRIES) {
135 		nvme_printf(ctrlr, "invalid hw.nvme.admin_entries=%d "
136 		    "specified\n", num_entries);
137 		num_entries = NVME_ADMIN_ENTRIES;
138 	}
139 
140 	/*
141 	 * The admin queue's max xfer size is treated differently than the
142 	 *  max I/O xfer size.  16KB is sufficient here - maybe even less?
143 	 */
144 	error = nvme_qpair_construct(qpair, num_entries, NVME_ADMIN_TRACKERS,
145 	     ctrlr);
146 	return (error);
147 }
148 
149 #define QP(ctrlr, c)	((c) * (ctrlr)->num_io_queues / mp_ncpus)
150 
151 static int
152 nvme_ctrlr_construct_io_qpairs(struct nvme_controller *ctrlr)
153 {
154 	struct nvme_qpair	*qpair;
155 	uint32_t		cap_lo;
156 	uint16_t		mqes;
157 	int			c, error, i, n;
158 	int			num_entries, num_trackers, max_entries;
159 
160 	/*
161 	 * NVMe spec sets a hard limit of 64K max entries, but devices may
162 	 * specify a smaller limit, so we need to check the MQES field in the
163 	 * capabilities register. We have to cap the number of entries to the
164 	 * current stride allows for in BAR 0/1, otherwise the remainder entries
165 	 * are inaccessible. MQES should reflect this, and this is just a
166 	 * fail-safe.
167 	 */
168 	max_entries =
169 	    (rman_get_size(ctrlr->resource) - nvme_mmio_offsetof(doorbell[0])) /
170 	    (1 << (ctrlr->dstrd + 1));
171 	num_entries = NVME_IO_ENTRIES;
172 	TUNABLE_INT_FETCH("hw.nvme.io_entries", &num_entries);
173 	cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
174 	mqes = NVME_CAP_LO_MQES(cap_lo);
175 	num_entries = min(num_entries, mqes + 1);
176 	num_entries = min(num_entries, max_entries);
177 
178 	/* SHARED_CID_SPACE: IO CIDs must fit within the shared CID table. */
179 	if (ctrlr->quirks & QUIRK_APPLE_SHARED_CID_SPACE)
180 		num_entries = min(num_entries, NVME_ADMIN_ENTRIES);
181 
182 	num_trackers = NVME_IO_TRACKERS;
183 	TUNABLE_INT_FETCH("hw.nvme.io_trackers", &num_trackers);
184 
185 	num_trackers = max(num_trackers, NVME_MIN_IO_TRACKERS);
186 	num_trackers = min(num_trackers, NVME_MAX_IO_TRACKERS);
187 	/*
188 	 * No need to have more trackers than entries in the submit queue.  Note
189 	 * also that for a queue size of N, we can only have (N-1) commands
190 	 * outstanding, hence the "-1" here.
191 	 */
192 	num_trackers = min(num_trackers, (num_entries-1));
193 
194 	if (ctrlr->cdata.maxcmd != 0 && num_trackers > ctrlr->cdata.maxcmd) {
195 		nvme_printf(ctrlr,
196 		    "limiting trackers per I/O queue to MAXCMD (%u -> %u)\n",
197 		    num_trackers, ctrlr->cdata.maxcmd);
198 		num_trackers = ctrlr->cdata.maxcmd;
199 	}
200 
201 	if (ctrlr->quirks & QUIRK_APPLE_SHARED_CID_SPACE)
202 		num_trackers = min(num_trackers,
203 		    NVME_ADMIN_ENTRIES - ctrlr->adminq.num_trackers);
204 	if (ctrlr->quirks & QUIRK_APPLE_S3X_SERIALIZE)
205 		num_trackers = 1;
206 
207 	/*
208 	 * Our best estimate for the maximum number of I/Os that we should
209 	 * normally have in flight at one time. This should be viewed as a hint,
210 	 * not a hard limit and will need to be revisited when the upper layers
211 	 * of the storage system grows multi-queue support.
212 	 */
213 	ctrlr->max_hw_pend_io = max(1,
214 	    num_trackers * ctrlr->num_io_queues * 3 / 4);
215 
216 	ctrlr->ioq = malloc(ctrlr->num_io_queues * sizeof(struct nvme_qpair),
217 	    M_NVME, M_ZERO | M_WAITOK);
218 
219 	for (i = c = n = 0; i < ctrlr->num_io_queues; i++, c += n) {
220 		qpair = &ctrlr->ioq[i];
221 
222 		/*
223 		 * Admin queue has ID=0. IO queues start at ID=1 -
224 		 *  hence the 'i+1' here.
225 		 */
226 		qpair->id = i + 1;
227 		if (ctrlr->num_io_queues > 1) {
228 			/* Find number of CPUs served by this queue. */
229 			for (n = 1; QP(ctrlr, c + n) == i; n++)
230 				;
231 			/* Shuffle multiple NVMe devices between CPUs. */
232 			qpair->cpu = c + (device_get_unit(ctrlr->dev)+n/2) % n;
233 			qpair->domain = pcpu_find(qpair->cpu)->pc_domain;
234 		} else {
235 			qpair->cpu = CPU_FFS(&cpuset_domain[ctrlr->domain]) - 1;
236 			qpair->domain = ctrlr->domain;
237 		}
238 
239 		/*
240 		 * For I/O queues, use the controller-wide max_xfer_size
241 		 *  calculated in nvme_attach().
242 		 */
243 		error = nvme_qpair_construct(qpair, num_entries, num_trackers,
244 		    ctrlr);
245 		if (error)
246 			return (error);
247 
248 		/*
249 		 * Do not bother binding interrupts if we only have one I/O
250 		 *  interrupt thread for this controller.
251 		 */
252 		if (ctrlr->num_io_queues > 1)
253 			bus_bind_intr(ctrlr->dev, qpair->res, qpair->cpu);
254 	}
255 
256 	return (0);
257 }
258 
259 static void
260 nvme_ctrlr_fail(struct nvme_controller *ctrlr, bool admin_also)
261 {
262 	int i;
263 
264 	/*
265 	 * No need to disable queues before failing them. Failing is a superet
266 	 * of disabling (though pedantically we'd abort the AERs silently with
267 	 * a different error, though when we fail, that hardly matters).
268 	 */
269 	ctrlr->is_failed = true;
270 	if (admin_also) {
271 		ctrlr->is_failed_admin = true;
272 		nvme_qpair_fail(&ctrlr->adminq);
273 	}
274 	if (ctrlr->ioq != NULL) {
275 		for (i = 0; i < ctrlr->num_io_queues; i++) {
276 			nvme_qpair_fail(&ctrlr->ioq[i]);
277 		}
278 	}
279 	nvme_notify_fail(ctrlr);
280 }
281 
282 /*
283  * Wait for RDY to change.
284  *
285  * Starts sleeping for 1us and geometrically increases it the longer we wait,
286  * capped at 1ms.
287  */
288 static int
289 nvme_ctrlr_wait_for_ready(struct nvme_controller *ctrlr, int desired_val)
290 {
291 	int timeout = ticks + MSEC_2_TICKS(ctrlr->ready_timeout_in_ms);
292 	sbintime_t delta_t = SBT_1US;
293 	uint32_t csts;
294 
295 	while (1) {
296 		csts = nvme_mmio_read_4(ctrlr, csts);
297 		if (csts == NVME_GONE)		/* Hot unplug. */
298 			return (ENXIO);
299 		if (NVMEV(NVME_CSTS_REG_RDY, csts) == desired_val)
300 			break;
301 		if (timeout - ticks < 0) {
302 			nvme_printf(ctrlr, "controller ready did not become %d "
303 			    "within %d ms\n", desired_val, ctrlr->ready_timeout_in_ms);
304 			return (ENXIO);
305 		}
306 
307 		pause_sbt("nvmerdy", delta_t, 0, C_PREL(1));
308 		delta_t = min(SBT_1MS, delta_t * 3 / 2);
309 	}
310 
311 	return (0);
312 }
313 
314 static int
315 nvme_ctrlr_disable(struct nvme_controller *ctrlr)
316 {
317 	uint32_t cc;
318 	uint32_t csts;
319 	uint8_t  en, rdy;
320 	int err;
321 
322 	cc = nvme_mmio_read_4(ctrlr, cc);
323 	csts = nvme_mmio_read_4(ctrlr, csts);
324 
325 	en = NVMEV(NVME_CC_REG_EN, cc);
326 	rdy = NVMEV(NVME_CSTS_REG_RDY, csts);
327 
328 	/*
329 	 * Per 3.1.5 in NVME 1.3 spec, transitioning CC.EN from 0 to 1
330 	 * when CSTS.RDY is 1 or transitioning CC.EN from 1 to 0 when
331 	 * CSTS.RDY is 0 "has undefined results" So make sure that CSTS.RDY
332 	 * isn't the desired value. Short circuit if we're already disabled.
333 	 */
334 	if (en == 0) {
335 		/* Wait for RDY == 0 or timeout & fail */
336 		if (rdy == 0)
337 			return (0);
338 		return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
339 	}
340 	if (rdy == 0) {
341 		/* EN == 1, wait for  RDY == 1 or timeout & fail */
342 		err = nvme_ctrlr_wait_for_ready(ctrlr, 1);
343 		if (err != 0)
344 			return (err);
345 	}
346 
347 	cc &= ~NVMEM(NVME_CC_REG_EN);
348 	nvme_mmio_write_4(ctrlr, cc, cc);
349 
350 	/*
351 	 * A few drives have firmware bugs that freeze the drive if we access
352 	 * the mmio too soon after we disable.
353 	 */
354 	if (ctrlr->quirks & QUIRK_DELAY_B4_CHK_RDY)
355 		pause("nvmeR", MSEC_2_TICKS(B4_CHK_RDY_DELAY_MS));
356 	return (nvme_ctrlr_wait_for_ready(ctrlr, 0));
357 }
358 
359 static int
360 nvme_ctrlr_enable(struct nvme_controller *ctrlr)
361 {
362 	uint32_t	cc;
363 	uint32_t	csts;
364 	uint32_t	aqa;
365 	uint32_t	qsize;
366 	uint8_t		css, en, rdy;
367 	int		err;
368 
369 	cc = nvme_mmio_read_4(ctrlr, cc);
370 	csts = nvme_mmio_read_4(ctrlr, csts);
371 
372 	en = NVMEV(NVME_CC_REG_EN, cc);
373 	rdy = NVMEV(NVME_CSTS_REG_RDY, csts);
374 
375 	/*
376 	 * See note in nvme_ctrlr_disable. Short circuit if we're already enabled.
377 	 */
378 	if (en == 1) {
379 		if (rdy == 1)
380 			return (0);
381 		return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
382 	}
383 
384 	/* EN == 0 already wait for RDY == 0 or timeout & fail */
385 	err = nvme_ctrlr_wait_for_ready(ctrlr, 0);
386 	if (err != 0)
387 		return (err);
388 
389 	nvme_mmio_write_8(ctrlr, asq, ctrlr->adminq.cmd_bus_addr);
390 	nvme_mmio_write_8(ctrlr, acq, ctrlr->adminq.cpl_bus_addr);
391 
392 	/* acqs and asqs are 0-based. */
393 	qsize = ctrlr->adminq.num_entries - 1;
394 
395 	aqa = 0;
396 	aqa |= NVMEF(NVME_AQA_REG_ACQS, qsize);
397 	aqa |= NVMEF(NVME_AQA_REG_ASQS, qsize);
398 	nvme_mmio_write_4(ctrlr, aqa, aqa);
399 
400 	/* Initialization values for CC */
401 	cc = 0;
402 	cc |= NVMEF(NVME_CC_REG_EN, 1);
403 	/* No CSI support; prefer the NVM command set when present. */
404 	css = NVME_CAP_HI_CSS(ctrlr->cap_hi);
405 	if ((css & NVME_CAP_CSS_NVM) != 0)
406 		cc |= NVMEF(NVME_CC_REG_CSS, NVME_CC_CSS_NVM);
407 	else if ((css & NVME_CAP_CSS_NOIOCSS) != 0)
408 		cc |= NVMEF(NVME_CC_REG_CSS, NVME_CC_CSS_ADMIN);
409 	else if ((css & NVME_CAP_CSS_IOCSS) != 0)
410 		cc |= NVMEF(NVME_CC_REG_CSS, NVME_CC_CSS_IOCSS);
411 	else
412 		cc |= NVMEF(NVME_CC_REG_CSS, NVME_CC_CSS_NVM);
413 	cc |= NVMEF(NVME_CC_REG_AMS, 0);
414 	cc |= NVMEF(NVME_CC_REG_SHN, 0);
415 	cc |= NVMEF(NVME_CC_REG_IOSQES, ctrlr->io_sqes);
416 	cc |= NVMEF(NVME_CC_REG_IOCQES, 4); /* CQ entry size == 16 == 2^4 */
417 
418 	/*
419 	 * Use the Memory Page Size selected during device initialization.  Note
420 	 * that value stored in mps is suitable to use here without adjusting by
421 	 * NVME_MPS_SHIFT.
422 	 */
423 	cc |= NVMEF(NVME_CC_REG_MPS, ctrlr->mps);
424 
425 	nvme_ctrlr_barrier(ctrlr, BUS_SPACE_BARRIER_WRITE);
426 	nvme_mmio_write_4(ctrlr, cc, cc);
427 
428 	return (nvme_ctrlr_wait_for_ready(ctrlr, 1));
429 }
430 
431 static void
432 nvme_ctrlr_disable_qpairs(struct nvme_controller *ctrlr)
433 {
434 	int i;
435 
436 	nvme_admin_qpair_disable(&ctrlr->adminq);
437 	/*
438 	 * I/O queues are not allocated before the initial HW
439 	 *  reset, so do not try to disable them.  Use is_initialized
440 	 *  to determine if this is the initial HW reset.
441 	 */
442 	if (ctrlr->is_initialized) {
443 		for (i = 0; i < ctrlr->num_io_queues; i++)
444 			nvme_io_qpair_disable(&ctrlr->ioq[i]);
445 	}
446 }
447 
448 static int
449 nvme_ctrlr_pcie_flr(struct nvme_controller *ctrlr, uint32_t csts)
450 {
451 	nvme_printf(ctrlr,
452 	    "fatal status; attempting PCIe function level reset\n");
453 	pci_save_state(ctrlr->dev);
454 	if (!pcie_flr(ctrlr->dev, 1000, true)) {
455 		pci_restore_state(ctrlr->dev);
456 		nvme_printf(ctrlr, "PCIe function level reset failed\n");
457 		nvme_ctrlr_devctl(ctrlr, "FLR_FAILED", "csts=0x%08x", csts);
458 		return (ENXIO);
459 	}
460 	pci_restore_state(ctrlr->dev);
461 	nvme_printf(ctrlr, "PCIe function level reset completed\n");
462 	nvme_ctrlr_devctl(ctrlr, "FLR_COMPLETED", "csts=0x%08x", csts);
463 	return (0);
464 }
465 
466 static int
467 nvme_ctrlr_hw_reset(struct nvme_controller *ctrlr)
468 {
469 	uint32_t csts;
470 	int err;
471 
472 	TSENTER();
473 
474 	ctrlr->is_failed_admin = true;
475 	nvme_ctrlr_disable_qpairs(ctrlr);
476 
477 	csts = nvme_mmio_read_4(ctrlr, csts);
478 	if ((ctrlr->quirks & QUIRK_PCIE_FLR_ON_FATAL) != 0 &&
479 	    csts != NVME_GONE && NVMEV(NVME_CSTS_REG_CFS, csts) != 0) {
480 		err = nvme_ctrlr_pcie_flr(ctrlr, csts);
481 		if (err != 0)
482 			goto out;
483 	}
484 
485 	err = nvme_ctrlr_disable(ctrlr);
486 	if (err != 0)
487 		goto out;
488 
489 	err = nvme_ctrlr_enable(ctrlr);
490 out:
491 	if (err == 0)
492 		ctrlr->is_failed_admin = false;
493 
494 	TSEXIT();
495 	return (err);
496 }
497 
498 void
499 nvme_ctrlr_reset(struct nvme_controller *ctrlr)
500 {
501 	int cmpset;
502 
503 	cmpset = atomic_cmpset_32(&ctrlr->is_resetting, 0, 1);
504 
505 	if (cmpset == 0)
506 		/*
507 		 * Controller is already resetting.  Return immediately since
508 		 * there is no need to kick off another reset.
509 		 */
510 		return;
511 
512 	if (!ctrlr->is_dying)
513 		taskqueue_enqueue(ctrlr->taskqueue, &ctrlr->reset_task);
514 }
515 
516 static int
517 nvme_ctrlr_identify(struct nvme_controller *ctrlr)
518 {
519 	struct nvme_completion_poll_status	status;
520 
521 	status.done = 0;
522 	nvme_ctrlr_cmd_identify_controller(ctrlr, &ctrlr->cdata,
523 	    nvme_completion_poll_cb, &status);
524 	nvme_completion_poll(&status);
525 	if (nvme_completion_is_error(&status.cpl)) {
526 		nvme_printf(ctrlr, "nvme_identify_controller failed!\n");
527 		return (ENXIO);
528 	}
529 
530 	/* Convert data to host endian */
531 	nvme_controller_data_swapbytes(&ctrlr->cdata);
532 
533 	/*
534 	 * Use MDTS to ensure our default max_xfer_size doesn't exceed what the
535 	 *  controller supports.
536 	 */
537 	if (ctrlr->cdata.mdts > 0)
538 		ctrlr->max_xfer_size = min(ctrlr->max_xfer_size,
539 		    1 << (ctrlr->cdata.mdts + NVME_MPS_SHIFT +
540 			NVME_CAP_HI_MPSMIN(ctrlr->cap_hi)));
541 	if (ctrlr->quirks & QUIRK_APPLE_S3X_SERIALIZE)
542 		ctrlr->max_xfer_size = min(ctrlr->max_xfer_size, 8192U);
543 
544 	return (0);
545 }
546 
547 static int
548 nvme_ctrlr_set_num_qpairs(struct nvme_controller *ctrlr)
549 {
550 	struct nvme_completion_poll_status	status;
551 	int					cq_allocated, sq_allocated;
552 
553 	status.done = 0;
554 	nvme_ctrlr_cmd_set_num_queues(ctrlr, ctrlr->num_io_queues,
555 	    nvme_completion_poll_cb, &status);
556 	nvme_completion_poll(&status);
557 	if (nvme_completion_is_error(&status.cpl)) {
558 		nvme_printf(ctrlr, "nvme_ctrlr_set_num_qpairs failed!\n");
559 		return (ENXIO);
560 	}
561 
562 	/*
563 	 * Data in cdw0 is 0-based.
564 	 * Lower 16-bits indicate number of submission queues allocated.
565 	 * Upper 16-bits indicate number of completion queues allocated.
566 	 */
567 	sq_allocated = (status.cpl.cdw0 & 0xFFFF) + 1;
568 	cq_allocated = (status.cpl.cdw0 >> 16) + 1;
569 
570 	/*
571 	 * Controller may allocate more queues than we requested,
572 	 *  so use the minimum of the number requested and what was
573 	 *  actually allocated.
574 	 */
575 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, sq_allocated);
576 	ctrlr->num_io_queues = min(ctrlr->num_io_queues, cq_allocated);
577 	if (ctrlr->num_io_queues > vm_ndomains)
578 		ctrlr->num_io_queues -= ctrlr->num_io_queues % vm_ndomains;
579 
580 	return (0);
581 }
582 
583 static int
584 nvme_ctrlr_create_qpairs(struct nvme_controller *ctrlr)
585 {
586 	struct nvme_completion_poll_status	status;
587 	struct nvme_qpair			*qpair;
588 	int					i;
589 
590 	for (i = 0; i < ctrlr->num_io_queues; i++) {
591 		qpair = &ctrlr->ioq[i];
592 
593 		status.done = 0;
594 		nvme_ctrlr_cmd_create_io_cq(ctrlr, qpair,
595 		    nvme_completion_poll_cb, &status);
596 		nvme_completion_poll(&status);
597 		if (nvme_completion_is_error(&status.cpl)) {
598 			nvme_printf(ctrlr, "nvme_create_io_cq failed!\n");
599 			return (ENXIO);
600 		}
601 
602 		status.done = 0;
603 		nvme_ctrlr_cmd_create_io_sq(ctrlr, qpair,
604 		    nvme_completion_poll_cb, &status);
605 		nvme_completion_poll(&status);
606 		if (nvme_completion_is_error(&status.cpl)) {
607 			nvme_printf(ctrlr, "nvme_create_io_sq failed!\n");
608 			return (ENXIO);
609 		}
610 	}
611 
612 	return (0);
613 }
614 
615 int
616 nvme_ctrlr_delete_qpairs(struct nvme_controller *ctrlr)
617 {
618 	struct nvme_completion_poll_status	status;
619 	struct nvme_qpair			*qpair;
620 
621 	for (int i = 0; i < ctrlr->num_io_queues; i++) {
622 		qpair = &ctrlr->ioq[i];
623 
624 		status.done = 0;
625 		nvme_ctrlr_cmd_delete_io_sq(ctrlr, qpair,
626 		    nvme_completion_poll_cb, &status);
627 		nvme_completion_poll(&status);
628 		if (nvme_completion_is_error(&status.cpl)) {
629 			nvme_printf(ctrlr, "nvme_destroy_io_sq failed!\n");
630 			return (ENXIO);
631 		}
632 
633 		status.done = 0;
634 		nvme_ctrlr_cmd_delete_io_cq(ctrlr, qpair,
635 		    nvme_completion_poll_cb, &status);
636 		nvme_completion_poll(&status);
637 		if (nvme_completion_is_error(&status.cpl)) {
638 			nvme_printf(ctrlr, "nvme_destroy_io_cq failed!\n");
639 			return (ENXIO);
640 		}
641 	}
642 
643 	return (0);
644 }
645 
646 static int
647 nvme_ctrlr_construct_namespaces(struct nvme_controller *ctrlr)
648 {
649 	struct nvme_namespace	*ns;
650 	uint32_t 		i;
651 
652 	for (i = 0; i < nvme_ctrlr_num_namespaces(ctrlr); i++) {
653 		ns = &ctrlr->ns[i];
654 		nvme_ns_construct(ns, i+1, ctrlr);
655 	}
656 
657 	return (0);
658 }
659 
660 static bool
661 is_log_page_id_valid(uint8_t page_id)
662 {
663 	switch (page_id) {
664 	case NVME_LOG_ERROR:
665 	case NVME_LOG_HEALTH_INFORMATION:
666 	case NVME_LOG_FIRMWARE_SLOT:
667 	case NVME_LOG_CHANGED_NAMESPACE:
668 	case NVME_LOG_COMMAND_EFFECT:
669 	case NVME_LOG_RES_NOTIFICATION:
670 	case NVME_LOG_SANITIZE_STATUS:
671 		return (true);
672 	}
673 
674 	return (false);
675 }
676 
677 static uint32_t
678 nvme_ctrlr_get_log_page_size(struct nvme_controller *ctrlr, uint8_t page_id)
679 {
680 	uint32_t	log_page_size;
681 
682 	switch (page_id) {
683 	case NVME_LOG_ERROR:
684 		log_page_size = min(
685 		    sizeof(struct nvme_error_information_entry) *
686 		    (ctrlr->cdata.elpe + 1), NVME_MAX_AER_LOG_SIZE);
687 		break;
688 	case NVME_LOG_HEALTH_INFORMATION:
689 		log_page_size = sizeof(struct nvme_health_information_page);
690 		break;
691 	case NVME_LOG_FIRMWARE_SLOT:
692 		log_page_size = sizeof(struct nvme_firmware_page);
693 		break;
694 	case NVME_LOG_CHANGED_NAMESPACE:
695 		log_page_size = sizeof(struct nvme_ns_list);
696 		break;
697 	case NVME_LOG_COMMAND_EFFECT:
698 		log_page_size = sizeof(struct nvme_command_effects_page);
699 		break;
700 	case NVME_LOG_RES_NOTIFICATION:
701 		log_page_size = sizeof(struct nvme_res_notification_page);
702 		break;
703 	case NVME_LOG_SANITIZE_STATUS:
704 		log_page_size = sizeof(struct nvme_sanitize_status_page);
705 		break;
706 	default:
707 		log_page_size = 0;
708 		break;
709 	}
710 
711 	return (log_page_size);
712 }
713 
714 static void
715 nvme_ctrlr_log_critical_warnings(struct nvme_controller *ctrlr,
716     uint8_t state)
717 {
718 	if (state & NVME_CRIT_WARN_ST_AVAILABLE_SPARE)
719 		nvme_printf(ctrlr, "SMART WARNING: available spare space below threshold\n");
720 
721 	if (state & NVME_CRIT_WARN_ST_TEMPERATURE)
722 		nvme_printf(ctrlr, "SMART WARNING: temperature above threshold\n");
723 
724 	if (state & NVME_CRIT_WARN_ST_DEVICE_RELIABILITY)
725 		nvme_printf(ctrlr, "SMART WARNING: device reliability degraded\n");
726 
727 	if (state & NVME_CRIT_WARN_ST_READ_ONLY)
728 		nvme_printf(ctrlr, "SMART WARNING: media placed in read only mode\n");
729 
730 	if (state & NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP)
731 		nvme_printf(ctrlr, "SMART WARNING: volatile memory backup device failed\n");
732 
733 	if (state & NVME_CRIT_WARN_ST_PERSISTENT_MEMORY_REGION)
734 		nvme_printf(ctrlr, "SMART WARNING: persistent memory read only or unreliable\n");
735 
736 	if (state & NVME_CRIT_WARN_ST_RESERVED_MASK)
737 		nvme_printf(ctrlr, "SMART WARNING: unknown critical warning(s): state = 0x%02x\n",
738 		    state & NVME_CRIT_WARN_ST_RESERVED_MASK);
739 
740 	nvme_ctrlr_devctl(ctrlr, "SMART_ERROR", "state=0x%02x", state);
741 }
742 
743 static void
744 nvme_ctrlr_async_event_cb(void *arg, const struct nvme_completion *cpl)
745 {
746 	struct nvme_async_event_request	*aer = arg;
747 
748 	if (nvme_completion_is_error(cpl)) {
749 		/*
750 		 *  Do not retry failed async event requests.  This avoids
751 		 *  infinite loops where a new async event request is submitted
752 		 *  to replace the one just failed, only to fail again and
753 		 *  perpetuate the loop.
754 		 */
755 		return;
756 	}
757 
758 	/*
759 	 * Save the completion status and associated log page is in bits 23:16
760 	 * of completion entry dw0. Print a message and queue it for further
761 	 * processing.
762 	 */
763 	memcpy(&aer->cpl, cpl, sizeof(*cpl));
764 	aer->log_page_id = NVMEV(NVME_ASYNC_EVENT_LOG_PAGE_ID, cpl->cdw0);
765 	nvme_printf(aer->ctrlr, "async event occurred (type 0x%x, info 0x%02x,"
766 	    " page 0x%02x)\n", NVMEV(NVME_ASYNC_EVENT_TYPE, cpl->cdw0),
767 	    NVMEV(NVME_ASYNC_EVENT_INFO, cpl->cdw0),
768 	    aer->log_page_id);
769 	taskqueue_enqueue(aer->ctrlr->taskqueue, &aer->task);
770 }
771 
772 static void
773 nvme_ctrlr_construct_and_submit_aer(struct nvme_controller *ctrlr,
774     struct nvme_async_event_request *aer)
775 {
776 	struct nvme_request *req;
777 
778 	/*
779 	 * We're racing the reset thread, so let that process submit this again.
780 	 * XXX does this really solve that race? And is that race even possible
781 	 * since we only reset when we've no theard from the card in a long
782 	 * time. Why would we get an AER in the middle of that just before we
783 	 * kick off the reset?
784 	 */
785 	if (ctrlr->is_resetting)
786 		return;
787 
788 	aer->ctrlr = ctrlr;
789 	req = nvme_allocate_request_null(M_WAITOK, nvme_ctrlr_async_event_cb,
790 	    aer);
791 	aer->req = req;
792 	aer->log_page_id = 0;		/* Not a valid page */
793 
794 	/*
795 	 * Disable timeout here, since asynchronous event requests should by
796 	 *  nature never be timed out.
797 	 */
798 	req->timeout = false;
799 	req->cmd.opc = NVME_OPC_ASYNC_EVENT_REQUEST;
800 	nvme_ctrlr_submit_admin_request(ctrlr, req);
801 }
802 
803 static void
804 nvme_ctrlr_configure_aer(struct nvme_controller *ctrlr)
805 {
806 	struct nvme_completion_poll_status	status;
807 	struct nvme_async_event_request		*aer;
808 	uint32_t				i;
809 
810 	if (ctrlr->quirks & QUIRK_APPLE_NO_ASYNC_EVENT) {
811 		ctrlr->num_aers = 0;
812 		return;
813 	}
814 
815 	ctrlr->async_event_config = NVME_CRIT_WARN_ST_AVAILABLE_SPARE |
816 	    NVME_CRIT_WARN_ST_DEVICE_RELIABILITY |
817 	    NVME_CRIT_WARN_ST_READ_ONLY |
818 	    NVME_CRIT_WARN_ST_VOLATILE_MEMORY_BACKUP;
819 	if (ctrlr->cdata.ver >= NVME_REV(1, 2))
820 		ctrlr->async_event_config |=
821 		    ctrlr->cdata.oaes & (NVME_ASYNC_EVENT_NS_ATTRIBUTE |
822 			NVME_ASYNC_EVENT_FW_ACTIVATE);
823 
824 	status.done = 0;
825 	nvme_ctrlr_cmd_get_feature(ctrlr, NVME_FEAT_TEMPERATURE_THRESHOLD,
826 	    0, NULL, 0, nvme_completion_poll_cb, &status);
827 	nvme_completion_poll(&status);
828 	if (nvme_completion_is_error(&status.cpl) ||
829 	    (status.cpl.cdw0 & 0xFFFF) == 0xFFFF ||
830 	    (status.cpl.cdw0 & 0xFFFF) == 0x0000) {
831 		nvme_printf(ctrlr, "temperature threshold not supported\n");
832 	} else
833 		ctrlr->async_event_config |= NVME_CRIT_WARN_ST_TEMPERATURE;
834 
835 	nvme_ctrlr_cmd_set_async_event_config(ctrlr,
836 	    ctrlr->async_event_config, NULL, NULL);
837 
838 	/* aerl is a zero-based value, so we need to add 1 here. */
839 	ctrlr->num_aers = min(NVME_MAX_ASYNC_EVENTS, (ctrlr->cdata.aerl+1));
840 
841 	for (i = 0; i < ctrlr->num_aers; i++) {
842 		aer = &ctrlr->aer[i];
843 		nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
844 	}
845 }
846 
847 static void
848 nvme_ctrlr_configure_apst(struct nvme_controller *ctrlr)
849 {
850 	struct nvme_completion_poll_status status;
851 	uint64_t *data;
852 	int data_size, i, read_size;
853 	bool enable, error = true;
854 
855 	if (TUNABLE_BOOL_FETCH("hw.nvme.apst_enable", &enable) == 0 ||
856 	    ctrlr->cdata.apsta == 0)
857 		return;
858 
859 	data_size = 32 * sizeof(*data);
860 	data = malloc(data_size, M_NVME, M_WAITOK | M_ZERO);
861 
862 	if (getenv_array("hw.nvme.apst_data", data, data_size,
863 	    &read_size, sizeof(*data), GETENV_UNSIGNED) != 0) {
864 		for (i = 0; i < read_size / sizeof(*data); ++i)
865 			data[i] = htole64(data[i]);
866 	} else {
867 		status.done = 0;
868 		nvme_ctrlr_cmd_get_feature(ctrlr,
869 		    NVME_FEAT_AUTONOMOUS_POWER_STATE_TRANSITION, 0,
870 		    data, data_size, nvme_completion_poll_cb, &status);
871 		nvme_completion_poll(&status);
872 		if (nvme_completion_is_error(&status.cpl))
873 			goto out;
874 	}
875 
876 	status.done = 0;
877 	nvme_ctrlr_cmd_set_feature(ctrlr,
878 	    NVME_FEAT_AUTONOMOUS_POWER_STATE_TRANSITION, enable, 0, 0,
879 	    0, 0, data, data_size, nvme_completion_poll_cb, &status);
880 	nvme_completion_poll(&status);
881 	error = nvme_completion_is_error(&status.cpl);
882 out:
883 	if (error && bootverbose)
884 		nvme_printf(ctrlr, "failed to configure APST\n");
885 	free(data, M_NVME);
886 }
887 
888 /* XXX revisit the ordering if the clock ever comes up earlier. */
889 static void
890 nvme_ctrlr_set_timestamp(struct nvme_controller *ctrlr)
891 {
892 	struct nvme_completion_poll_status status;
893 	struct nvme_timestamp_data *ts;
894 	struct timespec now;
895 	uint64_t ms;
896 	int i;
897 
898 	ts = malloc(sizeof(*ts), M_NVME, M_WAITOK | M_ZERO);
899 	getnanotime(&now);
900 	ms = (uint64_t)now.tv_sec * 1000 + now.tv_nsec / 1000000;
901 	for (i = 0; i < nitems(ts->tstmp); i++)
902 		ts->tstmp[i] = (ms >> (i * 8)) & 0xff;
903 
904 	status.done = 0;
905 	nvme_ctrlr_cmd_set_feature(ctrlr, NVME_FEAT_TIMESTAMP, 0, 0, 0, 0, 0,
906 	    ts, sizeof(*ts), nvme_completion_poll_cb, &status);
907 	nvme_completion_poll(&status);
908 	if (nvme_completion_is_error(&status.cpl) && bootverbose)
909 		nvme_printf(ctrlr, "failed to set the timestamp\n");
910 	free(ts, M_NVME);
911 }
912 
913 static void
914 nvme_ctrlr_timestamp_mountroot(void *arg)
915 {
916 	struct nvme_controller *ctrlr = arg;
917 
918 	if (ctrlr->is_failed || ctrlr->is_failed_admin || ctrlr->is_dying)
919 		return;
920 	nvme_ctrlr_set_timestamp(ctrlr);
921 }
922 
923 static void
924 nvme_ctrlr_configure_timestamp(struct nvme_controller *ctrlr)
925 {
926 	if (NVMEV(NVME_CTRLR_DATA_ONCS_TIMESTAMP, ctrlr->cdata.oncs) == 0)
927 		return;
928 
929 	/* The mountroot handler registered at attach does the initial set. */
930 	if (!root_mounted())
931 		return;
932 
933 	nvme_ctrlr_set_timestamp(ctrlr);
934 }
935 
936 static void
937 nvme_ctrlr_configure_int_coalescing(struct nvme_controller *ctrlr)
938 {
939 	ctrlr->int_coal_time = 0;
940 	TUNABLE_INT_FETCH("hw.nvme.int_coal_time",
941 	    &ctrlr->int_coal_time);
942 
943 	ctrlr->int_coal_threshold = 0;
944 	TUNABLE_INT_FETCH("hw.nvme.int_coal_threshold",
945 	    &ctrlr->int_coal_threshold);
946 
947 	nvme_ctrlr_cmd_set_interrupt_coalescing(ctrlr, ctrlr->int_coal_time,
948 	    ctrlr->int_coal_threshold, NULL, NULL);
949 }
950 
951 static void
952 nvme_ctrlr_hmb_free(struct nvme_controller *ctrlr)
953 {
954 	struct nvme_hmb_chunk *hmbc;
955 	int i;
956 
957 	if (ctrlr->hmb_desc_paddr) {
958 		bus_dmamap_unload(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map);
959 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
960 		    ctrlr->hmb_desc_map);
961 		ctrlr->hmb_desc_paddr = 0;
962 	}
963 	if (ctrlr->hmb_desc_tag) {
964 		bus_dma_tag_destroy(ctrlr->hmb_desc_tag);
965 		ctrlr->hmb_desc_tag = NULL;
966 	}
967 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
968 		hmbc = &ctrlr->hmb_chunks[i];
969 		bus_dmamap_unload(ctrlr->hmb_tag, hmbc->hmbc_map);
970 		bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
971 		    hmbc->hmbc_map);
972 	}
973 	ctrlr->hmb_nchunks = 0;
974 	if (ctrlr->hmb_tag) {
975 		bus_dma_tag_destroy(ctrlr->hmb_tag);
976 		ctrlr->hmb_tag = NULL;
977 	}
978 	if (ctrlr->hmb_chunks) {
979 		free(ctrlr->hmb_chunks, M_NVME);
980 		ctrlr->hmb_chunks = NULL;
981 	}
982 }
983 
984 static void
985 nvme_ctrlr_hmb_alloc(struct nvme_controller *ctrlr)
986 {
987 	struct nvme_hmb_chunk *hmbc;
988 	size_t pref, min, minc, size;
989 	int err, i;
990 	uint64_t max;
991 
992 	/* Limit HMB to 5% of RAM size per device by default. */
993 	max = (uint64_t)physmem * PAGE_SIZE / 20;
994 	TUNABLE_UINT64_FETCH("hw.nvme.hmb_max", &max);
995 
996 	/*
997 	 * Units of Host Memory Buffer in the Identify info are always in terms
998 	 * of 4k units.
999 	 */
1000 	min = (long long unsigned)ctrlr->cdata.hmmin * NVME_HMB_UNITS;
1001 	if (max == 0 || max < min)
1002 		return;
1003 	pref = MIN((long long unsigned)ctrlr->cdata.hmpre * NVME_HMB_UNITS, max);
1004 	minc = MAX(ctrlr->cdata.hmminds * NVME_HMB_UNITS, ctrlr->page_size);
1005 	if (min > 0 && ctrlr->cdata.hmmaxd > 0)
1006 		minc = MAX(minc, min / ctrlr->cdata.hmmaxd);
1007 	ctrlr->hmb_chunk = pref;
1008 
1009 again:
1010 	/*
1011 	 * However, the chunk sizes, number of chunks, and alignment of chunks
1012 	 * are all based on the current MPS (ctrlr->page_size).
1013 	 */
1014 	ctrlr->hmb_chunk = roundup2(ctrlr->hmb_chunk, ctrlr->page_size);
1015 	ctrlr->hmb_nchunks = howmany(pref, ctrlr->hmb_chunk);
1016 	if (ctrlr->cdata.hmmaxd > 0 && ctrlr->hmb_nchunks > ctrlr->cdata.hmmaxd)
1017 		ctrlr->hmb_nchunks = ctrlr->cdata.hmmaxd;
1018 	ctrlr->hmb_chunks = malloc(sizeof(struct nvme_hmb_chunk) *
1019 	    ctrlr->hmb_nchunks, M_NVME, M_WAITOK);
1020 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
1021 	    ctrlr->page_size, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1022 	    ctrlr->hmb_chunk, 1, ctrlr->hmb_chunk, 0, NULL, NULL, &ctrlr->hmb_tag);
1023 	if (err != 0) {
1024 		nvme_printf(ctrlr, "HMB tag create failed %d\n", err);
1025 		nvme_ctrlr_hmb_free(ctrlr);
1026 		return;
1027 	}
1028 
1029 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
1030 		hmbc = &ctrlr->hmb_chunks[i];
1031 		if (bus_dmamem_alloc(ctrlr->hmb_tag,
1032 		    (void **)&hmbc->hmbc_vaddr, BUS_DMA_NOWAIT,
1033 		    &hmbc->hmbc_map)) {
1034 			nvme_printf(ctrlr, "failed to alloc HMB\n");
1035 			break;
1036 		}
1037 		if (bus_dmamap_load(ctrlr->hmb_tag, hmbc->hmbc_map,
1038 		    hmbc->hmbc_vaddr, ctrlr->hmb_chunk, nvme_single_map,
1039 		    &hmbc->hmbc_paddr, BUS_DMA_NOWAIT) != 0) {
1040 			bus_dmamem_free(ctrlr->hmb_tag, hmbc->hmbc_vaddr,
1041 			    hmbc->hmbc_map);
1042 			nvme_printf(ctrlr, "failed to load HMB\n");
1043 			break;
1044 		}
1045 		bus_dmamap_sync(ctrlr->hmb_tag, hmbc->hmbc_map,
1046 		    BUS_DMASYNC_PREREAD | BUS_DMASYNC_PREWRITE);
1047 	}
1048 
1049 	if (i < ctrlr->hmb_nchunks && i * ctrlr->hmb_chunk < min &&
1050 	    ctrlr->hmb_chunk / 2 >= minc) {
1051 		ctrlr->hmb_nchunks = i;
1052 		nvme_ctrlr_hmb_free(ctrlr);
1053 		ctrlr->hmb_chunk /= 2;
1054 		goto again;
1055 	}
1056 	ctrlr->hmb_nchunks = i;
1057 	if (ctrlr->hmb_nchunks * ctrlr->hmb_chunk < min) {
1058 		nvme_ctrlr_hmb_free(ctrlr);
1059 		return;
1060 	}
1061 
1062 	size = sizeof(struct nvme_hmb_desc) * ctrlr->hmb_nchunks;
1063 	err = bus_dma_tag_create(bus_get_dma_tag(ctrlr->dev),
1064 	    PAGE_SIZE, 0, BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
1065 	    size, 1, size, 0, NULL, NULL, &ctrlr->hmb_desc_tag);
1066 	if (err != 0) {
1067 		nvme_printf(ctrlr, "HMB desc tag create failed %d\n", err);
1068 		nvme_ctrlr_hmb_free(ctrlr);
1069 		return;
1070 	}
1071 	if (bus_dmamem_alloc(ctrlr->hmb_desc_tag,
1072 	    (void **)&ctrlr->hmb_desc_vaddr, BUS_DMA_WAITOK,
1073 	    &ctrlr->hmb_desc_map)) {
1074 		nvme_printf(ctrlr, "failed to alloc HMB desc\n");
1075 		nvme_ctrlr_hmb_free(ctrlr);
1076 		return;
1077 	}
1078 	if (bus_dmamap_load(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
1079 	    ctrlr->hmb_desc_vaddr, size, nvme_single_map,
1080 	    &ctrlr->hmb_desc_paddr, BUS_DMA_NOWAIT) != 0) {
1081 		bus_dmamem_free(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_vaddr,
1082 		    ctrlr->hmb_desc_map);
1083 		nvme_printf(ctrlr, "failed to load HMB desc\n");
1084 		nvme_ctrlr_hmb_free(ctrlr);
1085 		return;
1086 	}
1087 
1088 	for (i = 0; i < ctrlr->hmb_nchunks; i++) {
1089 		memset(&ctrlr->hmb_desc_vaddr[i], 0,
1090 		    sizeof(struct nvme_hmb_desc));
1091 		ctrlr->hmb_desc_vaddr[i].addr =
1092 		    htole64(ctrlr->hmb_chunks[i].hmbc_paddr);
1093 		ctrlr->hmb_desc_vaddr[i].size = htole32(ctrlr->hmb_chunk / ctrlr->page_size);
1094 	}
1095 	bus_dmamap_sync(ctrlr->hmb_desc_tag, ctrlr->hmb_desc_map,
1096 	    BUS_DMASYNC_PREWRITE);
1097 
1098 	nvme_printf(ctrlr, "Allocated %lluMB host memory buffer\n",
1099 	    (long long unsigned)ctrlr->hmb_nchunks * ctrlr->hmb_chunk
1100 	    / 1024 / 1024);
1101 }
1102 
1103 static void
1104 nvme_ctrlr_hmb_enable(struct nvme_controller *ctrlr, bool enable, bool memret)
1105 {
1106 	struct nvme_completion_poll_status	status;
1107 	uint32_t cdw11;
1108 
1109 	cdw11 = 0;
1110 	if (enable)
1111 		cdw11 |= 1;
1112 	if (memret)
1113 		cdw11 |= 2;
1114 	status.done = 0;
1115 	nvme_ctrlr_cmd_set_feature(ctrlr, NVME_FEAT_HOST_MEMORY_BUFFER, cdw11,
1116 	    ctrlr->hmb_nchunks * ctrlr->hmb_chunk / ctrlr->page_size,
1117 	    ctrlr->hmb_desc_paddr, ctrlr->hmb_desc_paddr >> 32,
1118 	    ctrlr->hmb_nchunks, NULL, 0,
1119 	    nvme_completion_poll_cb, &status);
1120 	nvme_completion_poll(&status);
1121 	if (nvme_completion_is_error(&status.cpl))
1122 		nvme_printf(ctrlr, "nvme_ctrlr_hmb_enable failed!\n");
1123 }
1124 
1125 static void
1126 nvme_ctrlr_start(void *ctrlr_arg, bool resetting)
1127 {
1128 	struct nvme_controller *ctrlr = ctrlr_arg;
1129 	uint32_t old_num_io_queues;
1130 	int i;
1131 
1132 	TSENTER();
1133 
1134 	/*
1135 	 * Only reset adminq here when we are restarting the
1136 	 *  controller after a reset.  During initialization,
1137 	 *  we have already submitted admin commands to get
1138 	 *  the number of I/O queues supported, so cannot reset
1139 	 *  the adminq again here.
1140 	 */
1141 	if (resetting) {
1142 		nvme_qpair_reset(&ctrlr->adminq);
1143 		nvme_admin_qpair_enable(&ctrlr->adminq);
1144 	}
1145 
1146 	if (ctrlr->ioq != NULL) {
1147 		for (i = 0; i < ctrlr->num_io_queues; i++)
1148 			nvme_qpair_reset(&ctrlr->ioq[i]);
1149 	}
1150 
1151 	/*
1152 	 * If it was a reset on initialization command timeout, just
1153 	 * return here, letting initialization code fail gracefully.
1154 	 */
1155 	if (resetting && !ctrlr->is_initialized)
1156 		return;
1157 
1158 	if (resetting && nvme_ctrlr_identify(ctrlr) != 0) {
1159 		nvme_ctrlr_fail(ctrlr, false);
1160 		return;
1161 	}
1162 
1163 	/*
1164 	 * The number of qpairs are determined during controller initialization,
1165 	 *  including using NVMe SET_FEATURES/NUMBER_OF_QUEUES to determine the
1166 	 *  HW limit.  We call SET_FEATURES again here so that it gets called
1167 	 *  after any reset for controllers that depend on the driver to
1168 	 *  explicit specify how many queues it will use.  This value should
1169 	 *  never change between resets, so panic if somehow that does happen.
1170 	 */
1171 	if (resetting) {
1172 		old_num_io_queues = ctrlr->num_io_queues;
1173 		if (nvme_ctrlr_set_num_qpairs(ctrlr) != 0) {
1174 			nvme_ctrlr_fail(ctrlr, false);
1175 			return;
1176 		}
1177 
1178 		if (old_num_io_queues != ctrlr->num_io_queues) {
1179 			panic("num_io_queues changed from %u to %u",
1180 			      old_num_io_queues, ctrlr->num_io_queues);
1181 		}
1182 	}
1183 
1184 	if (ctrlr->cdata.hmpre > 0 && ctrlr->hmb_nchunks == 0) {
1185 		nvme_ctrlr_hmb_alloc(ctrlr);
1186 		if (ctrlr->hmb_nchunks > 0)
1187 			nvme_ctrlr_hmb_enable(ctrlr, true, false);
1188 	} else if (ctrlr->hmb_nchunks > 0)
1189 		nvme_ctrlr_hmb_enable(ctrlr, true, true);
1190 
1191 	if (nvme_ctrlr_create_qpairs(ctrlr) != 0) {
1192 		nvme_ctrlr_fail(ctrlr, false);
1193 		return;
1194 	}
1195 
1196 	if (nvme_ctrlr_construct_namespaces(ctrlr) != 0) {
1197 		nvme_ctrlr_fail(ctrlr, false);
1198 		return;
1199 	}
1200 
1201 	nvme_ctrlr_configure_aer(ctrlr);
1202 	nvme_ctrlr_configure_apst(ctrlr);
1203 	nvme_ctrlr_configure_int_coalescing(ctrlr);
1204 	nvme_ctrlr_configure_timestamp(ctrlr);
1205 
1206 	for (i = 0; i < ctrlr->num_io_queues; i++)
1207 		nvme_io_qpair_enable(&ctrlr->ioq[i]);
1208 	TSEXIT();
1209 }
1210 
1211 void
1212 nvme_ctrlr_start_config_hook(void *arg)
1213 {
1214 	struct nvme_controller *ctrlr = arg;
1215 
1216 	TSENTER();
1217 
1218 	if (nvme_ctrlr_hw_reset(ctrlr) != 0 || ctrlr->fail_on_reset != 0) {
1219 		nvme_ctrlr_fail(ctrlr, true);
1220 		config_intrhook_disestablish(&ctrlr->config_hook);
1221 		return;
1222 	}
1223 
1224 	nvme_qpair_reset(&ctrlr->adminq);
1225 	nvme_admin_qpair_enable(&ctrlr->adminq);
1226 
1227 	if (nvme_ctrlr_identify(ctrlr) == 0 &&
1228 	    nvme_ctrlr_set_num_qpairs(ctrlr) == 0 &&
1229 	    nvme_ctrlr_construct_io_qpairs(ctrlr) == 0)
1230 		nvme_ctrlr_start(ctrlr, false);
1231 	else
1232 		nvme_ctrlr_fail(ctrlr, false);
1233 
1234 	nvme_sysctl_initialize_ctrlr(ctrlr);
1235 	config_intrhook_disestablish(&ctrlr->config_hook);
1236 
1237 	if (!ctrlr->is_failed) {
1238 		device_t child;
1239 
1240 		if (bootverbose &&
1241 		    (ctrlr->quirks & QUIRK_APPLE_S3X_NS1_ONLY) != 0 &&
1242 		    ctrlr->cdata.nn > nvme_ctrlr_num_namespaces(ctrlr))
1243 			nvme_printf(ctrlr,
1244 			    "ignoring Apple-internal namespaces above NSID 1\n");
1245 
1246 		if (!root_mounted() &&
1247 		    NVMEV(NVME_CTRLR_DATA_ONCS_TIMESTAMP, ctrlr->cdata.oncs) != 0)
1248 			ctrlr->timestamp_tag = EVENTHANDLER_REGISTER(mountroot,
1249 			    nvme_ctrlr_timestamp_mountroot, ctrlr,
1250 			    EVENTHANDLER_PRI_ANY);
1251 
1252 		ctrlr->is_initialized = true;
1253 		child = device_add_child(ctrlr->dev, NULL, DEVICE_UNIT_ANY);
1254 		device_set_ivars(child, ctrlr);
1255 		bus_attach_children(ctrlr->dev);
1256 
1257 		/*
1258 		 * Now notify the child of all the known namepsaces
1259 		 */
1260 		for (int i = 0; i < nvme_ctrlr_num_namespaces(ctrlr); i++) {
1261 			struct nvme_namespace	*ns = &ctrlr->ns[i];
1262 
1263 			if (ns->data.nsze == 0)
1264 				continue;
1265 			NVME_NS_ADDED(child, ns);
1266 		}
1267 	}
1268 	TSEXIT();
1269 }
1270 
1271 static void
1272 nvme_ctrlr_reset_task(void *arg, int pending)
1273 {
1274 	struct nvme_controller	*ctrlr = arg;
1275 	int			status;
1276 
1277 	nvme_ctrlr_devctl_log(ctrlr, "RESET", "event=\"start\"");
1278 	status = nvme_ctrlr_hw_reset(ctrlr);
1279 	if (status == 0) {
1280 		nvme_ctrlr_devctl_log(ctrlr, "RESET", "event=\"success\"");
1281 		nvme_ctrlr_start(ctrlr, true);
1282 	} else {
1283 		nvme_ctrlr_devctl_log(ctrlr, "RESET", "event=\"timed_out\"");
1284 		nvme_ctrlr_fail(ctrlr, true);
1285 	}
1286 
1287 	atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
1288 }
1289 
1290 static void
1291 nvme_ctrlr_aer_done(void *arg,  const struct nvme_completion *cpl)
1292 {
1293 	struct nvme_async_event_request	*aer = arg;
1294 
1295 	mtx_lock(&aer->mtx);
1296 	if (nvme_completion_is_error(cpl))
1297 		aer->log_page_size = (uint32_t)-1;
1298 	else
1299 		aer->log_page_size = nvme_ctrlr_get_log_page_size(
1300 		    aer->ctrlr, aer->log_page_id);
1301 	wakeup(aer);
1302 	mtx_unlock(&aer->mtx);
1303 }
1304 
1305 static void
1306 nvme_ctrlr_aer_task(void *arg, int pending)
1307 {
1308 	struct nvme_async_event_request	*aer = arg;
1309 	struct nvme_controller	*ctrlr = aer->ctrlr;
1310 	uint32_t len;
1311 
1312 	/*
1313 	 * We're resetting, so just punt.
1314 	 */
1315 	if (ctrlr->is_resetting)
1316 		return;
1317 
1318 	if (!is_log_page_id_valid(aer->log_page_id)) {
1319 		/*
1320 		 * Repost another asynchronous event request to replace the one
1321 		 * that just completed.
1322 		 */
1323 		nvme_notify_async(ctrlr, &aer->cpl, aer->log_page_id, NULL, 0);
1324 		nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
1325 		goto out;
1326 	}
1327 
1328 	nvme_ctrlr_devctl(ctrlr, "aen", "type=0x%x info=0x%x page=0x%x",
1329 	    NVMEV(NVME_ASYNC_EVENT_TYPE, aer->cpl.cdw0),
1330 	    NVMEV(NVME_ASYNC_EVENT_INFO, aer->cpl.cdw0), aer->log_page_id);
1331 
1332 	aer->log_page_size = 0;
1333 	len = nvme_ctrlr_get_log_page_size(aer->ctrlr, aer->log_page_id);
1334 	nvme_ctrlr_cmd_get_log_page(aer->ctrlr, aer->log_page_id,
1335 	    NVME_GLOBAL_NAMESPACE_TAG, aer->log_page_buffer, len,
1336 	    nvme_ctrlr_aer_done, aer);
1337 	mtx_lock(&aer->mtx);
1338 	while (aer->log_page_size == 0)
1339 		mtx_sleep(aer, &aer->mtx, PRIBIO, "nvme_pt", 0);
1340 	mtx_unlock(&aer->mtx);
1341 
1342 	if (aer->log_page_size == (uint32_t)-1) {
1343 		/*
1344 		 * If the log page fetch for some reason completed with an
1345 		 * error, don't pass log page data to the consumers.  In
1346 		 * practice, this case should never happen.
1347 		 */
1348 		nvme_notify_async(aer->ctrlr, &aer->cpl, aer->log_page_id,
1349 		    NULL, 0);
1350 		goto out;
1351 	}
1352 
1353 	/* Convert data to host endian */
1354 	switch (aer->log_page_id) {
1355 	case NVME_LOG_ERROR: {
1356 		struct nvme_error_information_entry *err =
1357 		    (struct nvme_error_information_entry *)aer->log_page_buffer;
1358 		for (uint32_t i = 0; i < aer->log_page_size / sizeof(*err); i++)
1359 			nvme_error_information_entry_swapbytes(err++);
1360 		break;
1361 	}
1362 	case NVME_LOG_HEALTH_INFORMATION:
1363 		nvme_health_information_page_swapbytes(
1364 			(struct nvme_health_information_page *)aer->log_page_buffer);
1365 		break;
1366 	case NVME_LOG_CHANGED_NAMESPACE:
1367 		nvme_ns_list_swapbytes(
1368 			(struct nvme_ns_list *)aer->log_page_buffer);
1369 		break;
1370 	case NVME_LOG_COMMAND_EFFECT:
1371 		nvme_command_effects_page_swapbytes(
1372 			(struct nvme_command_effects_page *)aer->log_page_buffer);
1373 		break;
1374 	case NVME_LOG_RES_NOTIFICATION:
1375 		nvme_res_notification_page_swapbytes(
1376 			(struct nvme_res_notification_page *)aer->log_page_buffer);
1377 		break;
1378 	case NVME_LOG_SANITIZE_STATUS:
1379 		nvme_sanitize_status_page_swapbytes(
1380 			(struct nvme_sanitize_status_page *)aer->log_page_buffer);
1381 		break;
1382 	default:
1383 		break;
1384 	}
1385 
1386 	if (aer->log_page_id == NVME_LOG_HEALTH_INFORMATION) {
1387 		struct nvme_health_information_page *health_info =
1388 		    (struct nvme_health_information_page *)aer->log_page_buffer;
1389 
1390 		/*
1391 		 * Critical warnings reported through the SMART/health log page
1392 		 * are persistent, so clear the associated bits in the async
1393 		 * event config so that we do not receive repeated notifications
1394 		 * for the same event.
1395 		 */
1396 		nvme_ctrlr_log_critical_warnings(aer->ctrlr,
1397 		    health_info->critical_warning);
1398 		aer->ctrlr->async_event_config &=
1399 		    ~health_info->critical_warning;
1400 		nvme_ctrlr_cmd_set_async_event_config(aer->ctrlr,
1401 		    aer->ctrlr->async_event_config, NULL, NULL);
1402 	} else if (aer->log_page_id == NVME_LOG_CHANGED_NAMESPACE) {
1403 		device_t *children;
1404 		int n_children;
1405 		struct nvme_ns_list *nsl;
1406 
1407 		if (device_get_children(aer->ctrlr->dev, &children, &n_children) != 0) {
1408 			children = NULL;
1409 			n_children = 0;
1410 		}
1411 		nsl = (struct nvme_ns_list *)aer->log_page_buffer;
1412 		for (int i = 0; i < nitems(nsl->ns) && nsl->ns[i] != 0; i++) {
1413 			if (!nvme_ctrlr_nsid_visible(ctrlr, nsl->ns[i]))
1414 				continue;
1415 			/*
1416 			 * I think we need to query the name space here and see
1417 			 * if it went away, arrived, or changed in size and call
1418 			 * the nuanced routine (after constructing or before
1419 			 * destructing the namespace). XXX needs more work XXX.
1420 			 */
1421 			for (int j = 0; j < n_children; j++)
1422 				NVME_NS_CHANGED(children[j], nsl->ns[i]);
1423 		}
1424 		if (nsl->ns[0] == 0 && ctrlr->quirks & QUIRK_EMPTY_NAMESPACE_CHANGED_LOG) {
1425 			for (int i = 0; i < nvme_ctrlr_num_namespaces(ctrlr); i++)
1426 				for (int j = 0; j < n_children; j++)
1427 					NVME_NS_CHANGED(children[j], i + 1);
1428 		}
1429 		free(children, M_TEMP);
1430 	}
1431 
1432 	/*
1433 	 * Pass the cpl data from the original async event completion, not the
1434 	 * log page fetch.
1435 	 */
1436 	nvme_notify_async(aer->ctrlr, &aer->cpl, aer->log_page_id,
1437 	    aer->log_page_buffer, aer->log_page_size);
1438 
1439 	/*
1440 	 * Repost another asynchronous event request to replace the one
1441 	 *  that just completed.
1442 	 */
1443 out:
1444 	nvme_ctrlr_construct_and_submit_aer(ctrlr, aer);
1445 }
1446 
1447 /*
1448  * Poll all the queues enabled on the device for completion.
1449  */
1450 void
1451 nvme_ctrlr_poll(struct nvme_controller *ctrlr)
1452 {
1453 	int i;
1454 
1455 	nvme_qpair_process_completions(&ctrlr->adminq);
1456 
1457 	for (i = 0; i < ctrlr->num_io_queues; i++)
1458 		if (ctrlr->ioq && ctrlr->ioq[i].cpl)
1459 			nvme_qpair_process_completions(&ctrlr->ioq[i]);
1460 }
1461 
1462 /*
1463  * Poll the single-vector interrupt case: num_io_queues will be 1 and
1464  * there's only a single vector. While we're polling, we mask further
1465  * interrupts in the controller.
1466  */
1467 void
1468 nvme_ctrlr_shared_handler(void *arg)
1469 {
1470 	struct nvme_controller *ctrlr = arg;
1471 
1472 	/* INTMS/INTMC are undefined when configured for MSI-X. */
1473 	if (!ctrlr->is_msix)
1474 		nvme_mmio_write_4(ctrlr, intms, 1);
1475 	nvme_ctrlr_poll(ctrlr);
1476 	if (!ctrlr->is_msix)
1477 		nvme_mmio_write_4(ctrlr, intmc, 1);
1478 }
1479 
1480 #define NVME_MAX_PAGES  (int)(1024 / sizeof(vm_page_t))
1481 
1482 static int
1483 nvme_page_count(vm_offset_t start, size_t len)
1484 {
1485 	return atop(round_page(start + len) - trunc_page(start));
1486 }
1487 
1488 static int
1489 nvme_user_ioctl_req(vm_offset_t addr, size_t len, bool is_read,
1490     vm_page_t **upages, int max_pages, int *npagesp, struct nvme_request **req,
1491     nvme_cb_fn_t cb_fn, void *cb_arg)
1492 {
1493 	vm_prot_t prot = VM_PROT_READ;
1494 	int err, npages;
1495 	vm_page_t *upages_us;
1496 
1497 	upages_us = *upages;
1498 	npages = nvme_page_count(addr, len);
1499 	if (npages > atop(maxphys))
1500 		return (EINVAL);
1501 	if (npages > max_pages)
1502 		upages_us = malloc(npages * sizeof(vm_page_t), M_NVME,
1503 		    M_ZERO | M_WAITOK);
1504 
1505 	if (is_read)
1506 		prot |= VM_PROT_WRITE;	/* Device will write to host memory */
1507 	err = vm_fault_hold_pages(&curproc->p_vmspace->vm_map,
1508 	    addr, len, prot, upages_us, npages, npagesp);
1509 	if (err != 0) {
1510 		if (*upages != upages_us)
1511 			free(upages_us, M_NVME);
1512 		return (err);
1513 	}
1514 	*req = nvme_allocate_request_null(M_WAITOK, cb_fn, cb_arg);
1515 	(*req)->payload = memdesc_vmpages(upages_us, len, addr & PAGE_MASK);
1516 	(*req)->payload_valid = true;
1517 	if (*upages != upages_us)
1518 		*upages = upages_us;
1519 	return (0);
1520 }
1521 
1522 static void
1523 nvme_user_ioctl_free(vm_page_t *pages, int npage, bool freeit)
1524 {
1525 	vm_page_unhold_pages(pages, npage);
1526 	if (freeit)
1527 		free(pages, M_NVME);
1528 }
1529 
1530 static void
1531 nvme_pt_done(void *arg, const struct nvme_completion *cpl)
1532 {
1533 	struct nvme_pt_command *pt = arg;
1534 	struct mtx *mtx = pt->driver_lock;
1535 	uint16_t status;
1536 
1537 	bzero(&pt->cpl, sizeof(pt->cpl));
1538 	pt->cpl.cdw0 = cpl->cdw0;
1539 
1540 	status = cpl->status;
1541 	status &= ~NVMEM(NVME_STATUS_P);
1542 	pt->cpl.status = status;
1543 
1544 	mtx_lock(mtx);
1545 	pt->driver_lock = NULL;
1546 	wakeup(pt);
1547 	mtx_unlock(mtx);
1548 }
1549 
1550 int
1551 nvme_ctrlr_passthrough_cmd(struct nvme_controller *ctrlr,
1552     struct nvme_pt_command *pt, uint32_t nsid, int is_user,
1553     int is_admin_cmd)
1554 {
1555 	struct nvme_request *req;
1556 	struct mtx *mtx;
1557 	int ret = 0;
1558 	int npages = 0;
1559 	vm_page_t upages_small[NVME_MAX_PAGES];
1560 	vm_page_t *upages = upages_small;
1561 
1562 	if (pt->len > 0) {
1563 		if (pt->len > ctrlr->max_xfer_size) {
1564 			nvme_printf(ctrlr,
1565 			    "len (%d) exceeds max_xfer_size (%d)\n",
1566 			    pt->len, ctrlr->max_xfer_size);
1567 			return (EIO);
1568 		}
1569 		if (is_user) {
1570 			ret = nvme_user_ioctl_req((vm_offset_t)pt->buf, pt->len,
1571 			    pt->is_read, &upages, nitems(upages_small), &npages, &req,
1572 			    nvme_pt_done, pt);
1573 			if (ret != 0)
1574 				return (ret);
1575 		} else
1576 			req = nvme_allocate_request_vaddr(pt->buf, pt->len,
1577 			    M_WAITOK, nvme_pt_done, pt);
1578 	} else
1579 		req = nvme_allocate_request_null(M_WAITOK, nvme_pt_done, pt);
1580 
1581 	/* Assume user space already converted to little-endian */
1582 	req->cmd.opc = pt->cmd.opc;
1583 	req->cmd.fuse = pt->cmd.fuse;
1584 	req->cmd.rsvd2 = pt->cmd.rsvd2;
1585 	req->cmd.rsvd3 = pt->cmd.rsvd3;
1586 	req->cmd.cdw10 = pt->cmd.cdw10;
1587 	req->cmd.cdw11 = pt->cmd.cdw11;
1588 	req->cmd.cdw12 = pt->cmd.cdw12;
1589 	req->cmd.cdw13 = pt->cmd.cdw13;
1590 	req->cmd.cdw14 = pt->cmd.cdw14;
1591 	req->cmd.cdw15 = pt->cmd.cdw15;
1592 
1593 	req->cmd.nsid = htole32(nsid);
1594 
1595 	mtx = mtx_pool_find(mtxpool_sleep, pt);
1596 	pt->driver_lock = mtx;
1597 
1598 	if (is_admin_cmd)
1599 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1600 	else
1601 		nvme_ctrlr_submit_io_request(ctrlr, req);
1602 
1603 	mtx_lock(mtx);
1604 	while (pt->driver_lock != NULL)
1605 		mtx_sleep(pt, mtx, PRIBIO, "nvme_pt", 0);
1606 	mtx_unlock(mtx);
1607 
1608 	if (npages > 0)
1609 		nvme_user_ioctl_free(upages, npages, upages != upages_small);
1610 
1611 	return (ret);
1612 }
1613 
1614 static void
1615 nvme_npc_done(void *arg, const struct nvme_completion *cpl)
1616 {
1617 	struct nvme_passthru_cmd *npc = arg;
1618 	struct mtx *mtx = (void *)(uintptr_t)npc->metadata;
1619 
1620 	npc->result = cpl->cdw0;	/* cpl in host order by now */
1621 	mtx_lock(mtx);
1622 	npc->metadata = 0;
1623 	wakeup(npc);
1624 	mtx_unlock(mtx);
1625 }
1626 
1627 /* XXX refactor? */
1628 
1629 int
1630 nvme_ctrlr_linux_passthru_cmd(struct nvme_controller *ctrlr,
1631     struct nvme_passthru_cmd *npc, uint32_t nsid, bool is_user, bool is_admin)
1632 {
1633 	struct nvme_request	*req;
1634 	struct mtx		*mtx;
1635 	int			ret = 0;
1636 	int			npages = 0;
1637 	vm_page_t		upages_small[NVME_MAX_PAGES];
1638 	vm_page_t		*upages = upages_small;
1639 
1640 	/*
1641 	 * We don't support metadata.
1642 	 */
1643 	if (npc->metadata != 0 || npc->metadata_len != 0)
1644 		return (EIO);
1645 
1646 	if (npc->data_len > 0 && npc->addr != 0) {
1647 		if (npc->data_len > ctrlr->max_xfer_size) {
1648 			nvme_printf(ctrlr,
1649 			    "data_len (%d) exceeds max_xfer_size (%d)\n",
1650 			    npc->data_len, ctrlr->max_xfer_size);
1651 			return (EIO);
1652 		}
1653 		if (is_user) {
1654 			ret = nvme_user_ioctl_req(npc->addr, npc->data_len,
1655 			    npc->opcode & 0x1, &upages, nitems(upages_small),
1656 			    &npages, &req, nvme_npc_done, npc);
1657 			if (ret != 0)
1658 				return (ret);
1659 		} else
1660 			req = nvme_allocate_request_vaddr(
1661 			    (void *)(uintptr_t)npc->addr, npc->data_len,
1662 			    M_WAITOK, nvme_npc_done, npc);
1663 	} else
1664 		req = nvme_allocate_request_null(M_WAITOK, nvme_npc_done, npc);
1665 
1666 	req->cmd.opc = npc->opcode;
1667 	req->cmd.fuse = npc->flags;
1668 	req->cmd.rsvd2 = htole32(npc->cdw2);
1669 	req->cmd.rsvd3 = htole32(npc->cdw3);
1670 	req->cmd.cdw10 = htole32(npc->cdw10);
1671 	req->cmd.cdw11 = htole32(npc->cdw11);
1672 	req->cmd.cdw12 = htole32(npc->cdw12);
1673 	req->cmd.cdw13 = htole32(npc->cdw13);
1674 	req->cmd.cdw14 = htole32(npc->cdw14);
1675 	req->cmd.cdw15 = htole32(npc->cdw15);
1676 
1677 	req->cmd.nsid = htole32(nsid);
1678 
1679 	mtx = mtx_pool_find(mtxpool_sleep, npc);
1680 	npc->metadata = (uintptr_t) mtx;
1681 
1682 	/* XXX no timeout passed down */
1683 	if (is_admin)
1684 		nvme_ctrlr_submit_admin_request(ctrlr, req);
1685 	else
1686 		nvme_ctrlr_submit_io_request(ctrlr, req);
1687 
1688 	mtx_lock(mtx);
1689 	while (npc->metadata != 0)
1690 		mtx_sleep(npc, mtx, PRIBIO, "nvme_npc", 0);
1691 	mtx_unlock(mtx);
1692 
1693 	if (npages > 0)
1694 		nvme_user_ioctl_free(upages, npages, upages != upages_small);
1695 
1696 	return (ret);
1697 }
1698 
1699 static int
1700 nvme_ctrlr_ioctl(struct cdev *cdev, u_long cmd, caddr_t arg, int flag,
1701     struct thread *td)
1702 {
1703 	struct nvme_controller			*ctrlr;
1704 	struct nvme_pt_command			*pt;
1705 
1706 	ctrlr = cdev->si_drv1;
1707 
1708 	switch (cmd) {
1709 	case NVME_IOCTL_RESET: /* Linux compat */
1710 	case NVME_RESET_CONTROLLER:
1711 		nvme_ctrlr_reset(ctrlr);
1712 		break;
1713 	case NVME_PASSTHROUGH_CMD:
1714 		pt = (struct nvme_pt_command *)arg;
1715 		return (nvme_ctrlr_passthrough_cmd(ctrlr, pt, le32toh(pt->cmd.nsid),
1716 		    1 /* is_user_buffer */, 1 /* is_admin_cmd */));
1717 	case NVME_GET_NSID:
1718 	{
1719 		struct nvme_get_nsid *gnsid = (struct nvme_get_nsid *)arg;
1720 		strlcpy(gnsid->cdev, device_get_nameunit(ctrlr->dev),
1721 		    sizeof(gnsid->cdev));
1722 		gnsid->nsid = 0;
1723 		break;
1724 	}
1725 	case NVME_GET_MAX_XFER_SIZE:
1726 		*(uint64_t *)arg = ctrlr->max_xfer_size;
1727 		break;
1728 	case NVME_GET_CONTROLLER_DATA:
1729 		memcpy(arg, &ctrlr->cdata, sizeof(ctrlr->cdata));
1730 		break;
1731 	case DIOCGIDENT: {
1732 		uint8_t *sn = arg;
1733 		nvme_cdata_get_disk_ident(&ctrlr->cdata, sn);
1734 		break;
1735 	}
1736 	/* Linux Compatible (see nvme_linux.h) */
1737 	case NVME_IOCTL_ID:
1738 		td->td_retval[0] = 0xfffffffful;
1739 		return (0);
1740 
1741 	case NVME_IOCTL_ADMIN_CMD:
1742 	case NVME_IOCTL_IO_CMD: {
1743 		struct nvme_passthru_cmd *npc = (struct nvme_passthru_cmd *)arg;
1744 
1745 		return (nvme_ctrlr_linux_passthru_cmd(ctrlr, npc, npc->nsid, true,
1746 		    cmd == NVME_IOCTL_ADMIN_CMD));
1747 	}
1748 
1749 	default:
1750 		return (ENOTTY);
1751 	}
1752 
1753 	return (0);
1754 }
1755 
1756 static struct cdevsw nvme_ctrlr_cdevsw = {
1757 	.d_version =	D_VERSION,
1758 	.d_flags =	0,
1759 	.d_ioctl =	nvme_ctrlr_ioctl
1760 };
1761 
1762 int
1763 nvme_ctrlr_construct(struct nvme_controller *ctrlr, device_t dev)
1764 {
1765 	struct make_dev_args	md_args;
1766 	uint32_t	cap_lo;
1767 	uint32_t	cap_hi;
1768 	uint32_t	to, vs, pmrcap;
1769 	int		status, timeout_period;
1770 
1771 	ctrlr->dev = dev;
1772 	ctrlr->io_sqes =
1773 	    (ctrlr->quirks & QUIRK_APPLE_128_BYTE_SQES) != 0 ?
1774 	    NVME_IOSQES_128 : NVME_IOSQES_64;
1775 
1776 	mtx_init(&ctrlr->lock, "nvme ctrlr lock", NULL, MTX_DEF);
1777 	if (bus_get_domain(dev, &ctrlr->domain) != 0)
1778 		ctrlr->domain = 0;
1779 
1780 	ctrlr->cap_lo = cap_lo = nvme_mmio_read_4(ctrlr, cap_lo);
1781 	if (bootverbose) {
1782 		device_printf(dev, "CapLo: 0x%08x: MQES %u%s%s%s%s, TO %u\n",
1783 		    cap_lo, NVME_CAP_LO_MQES(cap_lo),
1784 		    NVME_CAP_LO_CQR(cap_lo) ? ", CQR" : "",
1785 		    NVME_CAP_LO_AMS(cap_lo) ? ", AMS" : "",
1786 		    (NVME_CAP_LO_AMS(cap_lo) & 0x1) ? " WRRwUPC" : "",
1787 		    (NVME_CAP_LO_AMS(cap_lo) & 0x2) ? " VS" : "",
1788 		    NVME_CAP_LO_TO(cap_lo));
1789 	}
1790 	ctrlr->cap_hi = cap_hi = nvme_mmio_read_4(ctrlr, cap_hi);
1791 	if (bootverbose) {
1792 		device_printf(dev, "CapHi: 0x%08x: DSTRD %u%s, CSS %x%s, "
1793 		    "CPS %x, MPSMIN %u, MPSMAX %u%s%s%s%s%s\n", cap_hi,
1794 		    NVME_CAP_HI_DSTRD(cap_hi),
1795 		    NVME_CAP_HI_NSSRS(cap_hi) ? ", NSSRS" : "",
1796 		    NVME_CAP_HI_CSS(cap_hi),
1797 		    NVME_CAP_HI_BPS(cap_hi) ? ", BPS" : "",
1798 		    NVME_CAP_HI_CPS(cap_hi),
1799 		    NVME_CAP_HI_MPSMIN(cap_hi),
1800 		    NVME_CAP_HI_MPSMAX(cap_hi),
1801 		    NVME_CAP_HI_PMRS(cap_hi) ? ", PMRS" : "",
1802 		    NVME_CAP_HI_CMBS(cap_hi) ? ", CMBS" : "",
1803 		    NVME_CAP_HI_NSSS(cap_hi) ? ", NSSS" : "",
1804 		    NVME_CAP_HI_CRWMS(cap_hi) ? ", CRWMS" : "",
1805 		    NVME_CAP_HI_CRIMS(cap_hi) ? ", CRIMS" : "");
1806 	}
1807 	if (bootverbose) {
1808 		vs = nvme_mmio_read_4(ctrlr, vs);
1809 		device_printf(dev, "Version: 0x%08x: %d.%d\n", vs,
1810 		    NVME_MAJOR(vs), NVME_MINOR(vs));
1811 	}
1812 	if (bootverbose && NVME_CAP_HI_PMRS(cap_hi)) {
1813 		pmrcap = nvme_mmio_read_4(ctrlr, pmrcap);
1814 		device_printf(dev, "PMRCap: 0x%08x: BIR %u%s%s, PMRTU %u, "
1815 		    "PMRWBM %x, PMRTO %u%s\n", pmrcap,
1816 		    NVME_PMRCAP_BIR(pmrcap),
1817 		    NVME_PMRCAP_RDS(pmrcap) ? ", RDS" : "",
1818 		    NVME_PMRCAP_WDS(pmrcap) ? ", WDS" : "",
1819 		    NVME_PMRCAP_PMRTU(pmrcap),
1820 		    NVME_PMRCAP_PMRWBM(pmrcap),
1821 		    NVME_PMRCAP_PMRTO(pmrcap),
1822 		    NVME_PMRCAP_CMSS(pmrcap) ? ", CMSS" : "");
1823 	}
1824 
1825 	ctrlr->dstrd = NVME_CAP_HI_DSTRD(cap_hi) + 2;
1826 
1827 	ctrlr->mps = NVME_CAP_HI_MPSMIN(cap_hi);
1828 	ctrlr->page_size = 1 << (NVME_MPS_SHIFT + ctrlr->mps);
1829 
1830 	/* Get ready timeout value from controller, in units of 500ms. */
1831 	to = NVME_CAP_LO_TO(cap_lo) + 1;
1832 	ctrlr->ready_timeout_in_ms = to * 500;
1833 
1834 	timeout_period = NVME_ADMIN_TIMEOUT_PERIOD;
1835 	TUNABLE_INT_FETCH("hw.nvme.admin_timeout_period", &timeout_period);
1836 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1837 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1838 	ctrlr->admin_timeout_period = timeout_period;
1839 
1840 	timeout_period = NVME_DEFAULT_TIMEOUT_PERIOD;
1841 	TUNABLE_INT_FETCH("hw.nvme.timeout_period", &timeout_period);
1842 	timeout_period = min(timeout_period, NVME_MAX_TIMEOUT_PERIOD);
1843 	timeout_period = max(timeout_period, NVME_MIN_TIMEOUT_PERIOD);
1844 	ctrlr->timeout_period = timeout_period;
1845 
1846 	nvme_retry_count = NVME_DEFAULT_RETRY_COUNT;
1847 	TUNABLE_INT_FETCH("hw.nvme.retry_count", &nvme_retry_count);
1848 
1849 	ctrlr->enable_aborts = 0;
1850 	TUNABLE_INT_FETCH("hw.nvme.enable_aborts", &ctrlr->enable_aborts);
1851 
1852 	ctrlr->alignment_splits = counter_u64_alloc(M_WAITOK);
1853 
1854 	/* Cap transfers by the maximum addressable by page-sized PRP (4KB pages -> 2MB). */
1855 	ctrlr->max_xfer_size = MIN(maxphys, (ctrlr->page_size / 8 * ctrlr->page_size));
1856 	if (nvme_ctrlr_construct_admin_qpair(ctrlr) != 0)
1857 		return (ENXIO);
1858 
1859 	/*
1860 	 * Create 2 threads for the taskqueue. The reset thread will block when
1861 	 * it detects that the controller has failed until all I/O has been
1862 	 * failed up the stack. The second thread is used for AER events, which
1863 	 * can block, but only briefly for memory and log page fetching.
1864 	 */
1865 	ctrlr->taskqueue = taskqueue_create("nvme_taskq", M_WAITOK,
1866 	    taskqueue_thread_enqueue, &ctrlr->taskqueue);
1867 	taskqueue_start_threads(&ctrlr->taskqueue, 2, PI_DISK, "nvme taskq");
1868 
1869 	ctrlr->is_resetting = 0;
1870 	ctrlr->is_initialized = false;
1871 	TASK_INIT(&ctrlr->reset_task, 0, nvme_ctrlr_reset_task, ctrlr);
1872 	for (int i = 0; i < NVME_MAX_ASYNC_EVENTS; i++) {
1873 		struct nvme_async_event_request *aer = &ctrlr->aer[i];
1874 
1875 		TASK_INIT(&aer->task, 0, nvme_ctrlr_aer_task, aer);
1876 		mtx_init(&aer->mtx, "AER mutex", NULL, MTX_DEF);
1877 	}
1878 	ctrlr->is_failed = false;
1879 
1880 	make_dev_args_init(&md_args);
1881 	md_args.mda_devsw = &nvme_ctrlr_cdevsw;
1882 	md_args.mda_uid = UID_ROOT;
1883 	md_args.mda_gid = GID_WHEEL;
1884 	md_args.mda_mode = 0600;
1885 	md_args.mda_unit = device_get_unit(dev);
1886 	md_args.mda_si_drv1 = (void *)ctrlr;
1887 	status = make_dev_s(&md_args, &ctrlr->cdev, "%s",
1888 	    device_get_nameunit(dev));
1889 	if (status != 0)
1890 		return (ENXIO);
1891 
1892 	return (0);
1893 }
1894 
1895 /*
1896  * Called on detach, or on error on attach. The nvme_controller won't be used
1897  * again once we return, so we have to tear everything down (so nothing
1898  * references this, no callbacks, etc), but don't need to reset all the state
1899  * since nvme_controller will be freed soon.
1900  */
1901 void
1902 nvme_ctrlr_destruct(struct nvme_controller *ctrlr, device_t dev)
1903 {
1904 	int	i;
1905 	bool	gone;
1906 
1907 	ctrlr->is_dying = true;
1908 
1909 	if (ctrlr->timestamp_tag != NULL) {
1910 		EVENTHANDLER_DEREGISTER(mountroot, ctrlr->timestamp_tag);
1911 		ctrlr->timestamp_tag = NULL;
1912 	}
1913 
1914 	if (ctrlr->resource == NULL)
1915 		goto nores;
1916 	if (!mtx_initialized(&ctrlr->adminq.lock))
1917 		goto noadminq;
1918 
1919 	/*
1920 	 * Check whether it is a hot unplug or a clean driver detach.  If device
1921 	 * is not there any more, skip any shutdown commands.  Some hotplug
1922 	 * bridges will return zeros instead of ff's when the device is
1923 	 * departing, so ask the bridge if the device is gone. Some systems can
1924 	 * remove the drive w/o the bridge knowing its gone (they don't really
1925 	 * do hotplug), so failsafe with detecting all ff's (impossible with
1926 	 * this hardware) as the device being gone.
1927 	 */
1928 	gone = bus_child_present(dev) == 0 ||
1929 	    (nvme_mmio_read_4(ctrlr, csts) == NVME_GONE);
1930 	if (gone)
1931 		nvme_ctrlr_fail(ctrlr, true);
1932 	else
1933 		nvme_notify_fail(ctrlr);
1934 
1935 	for (i = 0; i < NVME_MAX_NAMESPACES; i++)
1936 		nvme_ns_destruct(&ctrlr->ns[i]);
1937 
1938 	if (ctrlr->cdev)
1939 		destroy_dev(ctrlr->cdev);
1940 
1941 	if (ctrlr->is_initialized) {
1942 		if (!gone) {
1943 			if (ctrlr->hmb_nchunks > 0)
1944 				nvme_ctrlr_hmb_enable(ctrlr, false, false);
1945 			nvme_ctrlr_delete_qpairs(ctrlr);
1946 		}
1947 		nvme_ctrlr_hmb_free(ctrlr);
1948 	}
1949 	if (ctrlr->ioq != NULL) {
1950 		for (i = 0; i < ctrlr->num_io_queues; i++)
1951 			nvme_io_qpair_destroy(&ctrlr->ioq[i]);
1952 		free(ctrlr->ioq, M_NVME);
1953 	}
1954 	nvme_admin_qpair_destroy(&ctrlr->adminq);
1955 
1956 	/*
1957 	 * Notify the controller of a shutdown, even though this is due to a
1958 	 * driver unload, not a system shutdown (this path is not invoked uring
1959 	 * shutdown).  This ensures the controller receives a shutdown
1960 	 * notification in case the system is shutdown before reloading the
1961 	 * driver. Some NVMe drives need this to flush their cache to stable
1962 	 * media and consider it a safe shutdown in SMART stats.
1963 	 */
1964 	if (!gone) {
1965 		nvme_ctrlr_shutdown(ctrlr);
1966 		nvme_ctrlr_disable(ctrlr);
1967 	}
1968 
1969 noadminq:
1970 	if (ctrlr->taskqueue) {
1971 		taskqueue_free(ctrlr->taskqueue);
1972 		for (int i = 0; i < NVME_MAX_ASYNC_EVENTS; i++) {
1973 			struct nvme_async_event_request *aer = &ctrlr->aer[i];
1974 
1975 			mtx_destroy(&aer->mtx);
1976 		}
1977 	}
1978 
1979 	if (ctrlr->tag)
1980 		bus_teardown_intr(ctrlr->dev, ctrlr->res, ctrlr->tag);
1981 
1982 	if (ctrlr->res)
1983 		bus_release_resource(ctrlr->dev, SYS_RES_IRQ,
1984 		    rman_get_rid(ctrlr->res), ctrlr->res);
1985 
1986 	if (ctrlr->msix_table_resource != NULL) {
1987 		bus_release_resource(dev, SYS_RES_MEMORY,
1988 		    ctrlr->msix_table_resource_id, ctrlr->msix_table_resource);
1989 	}
1990 
1991 	if (ctrlr->msix_pba_resource != NULL) {
1992 		bus_release_resource(dev, SYS_RES_MEMORY,
1993 		    ctrlr->msix_pba_resource_id, ctrlr->msix_pba_resource);
1994 	}
1995 
1996 	bus_release_resource(dev, SYS_RES_MEMORY,
1997 	    ctrlr->resource_id, ctrlr->resource);
1998 
1999 nores:
2000 	if (ctrlr->alignment_splits)
2001 		counter_u64_free(ctrlr->alignment_splits);
2002 
2003 	mtx_destroy(&ctrlr->lock);
2004 }
2005 
2006 void
2007 nvme_ctrlr_shutdown(struct nvme_controller *ctrlr)
2008 {
2009 	uint32_t	cc;
2010 	uint32_t	csts;
2011 	int		timeout;
2012 
2013 	cc = nvme_mmio_read_4(ctrlr, cc);
2014 	cc &= ~NVMEM(NVME_CC_REG_SHN);
2015 	cc |= NVMEF(NVME_CC_REG_SHN, NVME_SHN_NORMAL);
2016 	nvme_mmio_write_4(ctrlr, cc, cc);
2017 
2018 	timeout = ticks + (ctrlr->cdata.rtd3e == 0 ? 5 * hz :
2019 	    ((uint64_t)ctrlr->cdata.rtd3e * hz + 999999) / 1000000);
2020 	while (1) {
2021 		csts = nvme_mmio_read_4(ctrlr, csts);
2022 		if (csts == NVME_GONE)		/* Hot unplug. */
2023 			break;
2024 		if (NVME_CSTS_GET_SHST(csts) == NVME_SHST_COMPLETE)
2025 			break;
2026 		if (timeout - ticks < 0) {
2027 			nvme_printf(ctrlr, "shutdown timeout\n");
2028 			break;
2029 		}
2030 		pause("nvmeshut", 1);
2031 	}
2032 }
2033 
2034 void
2035 nvme_ctrlr_submit_admin_request(struct nvme_controller *ctrlr,
2036     struct nvme_request *req)
2037 {
2038 	nvme_qpair_submit_request(&ctrlr->adminq, req);
2039 }
2040 
2041 void
2042 nvme_ctrlr_submit_io_request(struct nvme_controller *ctrlr,
2043     struct nvme_request *req)
2044 {
2045 	struct nvme_qpair       *qpair;
2046 	int32_t			ioq;
2047 
2048 	ioq = req->ioq == NVME_IOQ_DEFAULT ? QP(ctrlr, curcpu) : req->ioq;
2049 	qpair = &ctrlr->ioq[ioq];
2050 	nvme_qpair_submit_request(qpair, req);
2051 }
2052 
2053 device_t
2054 nvme_ctrlr_get_device(struct nvme_controller *ctrlr)
2055 {
2056 	return (ctrlr->dev);
2057 }
2058 
2059 const struct nvme_controller_data *
2060 nvme_ctrlr_get_data(struct nvme_controller *ctrlr)
2061 {
2062 	return (&ctrlr->cdata);
2063 }
2064 
2065 int
2066 nvme_ctrlr_suspend(struct nvme_controller *ctrlr)
2067 {
2068 	int to = hz;
2069 
2070 	/*
2071 	 * Can't touch failed controllers, so it's already suspended. User will
2072 	 * need to do an explicit reset to bring it back, if that's even
2073 	 * possible.
2074 	 */
2075 	if (ctrlr->is_failed)
2076 		return (0);
2077 
2078 	/*
2079 	 * We don't want the reset taskqueue running, since it does similar
2080 	 * things, so prevent it from running after we start. Wait for any reset
2081 	 * that may have been started to complete. The reset process we follow
2082 	 * will ensure that any new I/O will queue and be given to the hardware
2083 	 * after we resume (though there should be none).
2084 	 */
2085 	while (atomic_cmpset_32(&ctrlr->is_resetting, 0, 1) == 0 && to-- > 0)
2086 		pause("nvmesusp", 1);
2087 	if (to <= 0) {
2088 		nvme_printf(ctrlr,
2089 		    "Competing reset task didn't finish. Try again later.\n");
2090 		return (EWOULDBLOCK);
2091 	}
2092 
2093 	if (ctrlr->hmb_nchunks > 0)
2094 		nvme_ctrlr_hmb_enable(ctrlr, false, false);
2095 
2096 	/*
2097 	 * Per Section 7.6.2 of NVMe spec 1.4, to properly suspend, we need to
2098 	 * delete the hardware I/O queues, and then shutdown. This properly
2099 	 * flushes any metadata the drive may have stored so it can survive
2100 	 * having its power removed and prevents the unsafe shutdown count from
2101 	 * incriminating. Once we delete the qpairs, we have to disable them
2102 	 * before shutting down.
2103 	 */
2104 	nvme_ctrlr_delete_qpairs(ctrlr);
2105 	nvme_ctrlr_disable_qpairs(ctrlr);
2106 	nvme_ctrlr_shutdown(ctrlr);
2107 
2108 	return (0);
2109 }
2110 
2111 int
2112 nvme_ctrlr_resume(struct nvme_controller *ctrlr)
2113 {
2114 	/*
2115 	 * Can't touch failed controllers, so nothing to do to resume.
2116 	 */
2117 	if (ctrlr->is_failed)
2118 		return (0);
2119 
2120 	if (nvme_ctrlr_hw_reset(ctrlr) != 0)
2121 		goto fail;
2122 
2123 	/*
2124 	 * Now that we've reset the hardware, we can restart the controller. Any
2125 	 * I/O that was pending is requeued. Any admin commands are aborted with
2126 	 * an error. Once we've restarted, stop flagging the controller as being
2127 	 * in the reset phase.
2128 	 */
2129 	nvme_ctrlr_start(ctrlr, true);
2130 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
2131 
2132 	return (0);
2133 fail:
2134 	/*
2135 	 * Since we can't bring the controller out of reset, announce and fail
2136 	 * the controller. However, we have to return success for the resume
2137 	 * itself, due to questionable APIs.
2138 	 */
2139 	nvme_printf(ctrlr, "Failed to reset on resume, failing.\n");
2140 	nvme_ctrlr_fail(ctrlr, true);
2141 	(void)atomic_cmpset_32(&ctrlr->is_resetting, 1, 0);
2142 	return (0);
2143 }
2144