xref: /freebsd/sys/dev/ioat/ioat.c (revision abac203368a6069d3d557a71a60a843707694d65)
1 /*-
2  * Copyright (C) 2012 Intel Corporation
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 #include <sys/cdefs.h>
28 __FBSDID("$FreeBSD$");
29 
30 #include <sys/param.h>
31 #include <sys/systm.h>
32 #include <sys/bus.h>
33 #include <sys/conf.h>
34 #include <sys/ioccom.h>
35 #include <sys/kernel.h>
36 #include <sys/lock.h>
37 #include <sys/malloc.h>
38 #include <sys/module.h>
39 #include <sys/mutex.h>
40 #include <sys/rman.h>
41 #include <sys/sbuf.h>
42 #include <sys/sysctl.h>
43 #include <sys/time.h>
44 #include <dev/pci/pcireg.h>
45 #include <dev/pci/pcivar.h>
46 #include <machine/bus.h>
47 #include <machine/resource.h>
48 #include <machine/stdarg.h>
49 
50 #include "ioat.h"
51 #include "ioat_hw.h"
52 #include "ioat_internal.h"
53 
54 #define	IOAT_INTR_TIMO	(hz / 10)
55 #define	IOAT_REFLK	(&ioat->submit_lock)
56 
57 static int ioat_probe(device_t device);
58 static int ioat_attach(device_t device);
59 static int ioat_detach(device_t device);
60 static int ioat_setup_intr(struct ioat_softc *ioat);
61 static int ioat_teardown_intr(struct ioat_softc *ioat);
62 static int ioat3_attach(device_t device);
63 static int ioat_start_channel(struct ioat_softc *ioat);
64 static int ioat_map_pci_bar(struct ioat_softc *ioat);
65 static void ioat_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg,
66     int error);
67 static void ioat_interrupt_handler(void *arg);
68 static boolean_t ioat_model_resets_msix(struct ioat_softc *ioat);
69 static int chanerr_to_errno(uint32_t);
70 static void ioat_process_events(struct ioat_softc *ioat);
71 static inline uint32_t ioat_get_active(struct ioat_softc *ioat);
72 static inline uint32_t ioat_get_ring_space(struct ioat_softc *ioat);
73 static void ioat_free_ring(struct ioat_softc *, uint32_t size,
74     struct ioat_descriptor **);
75 static void ioat_free_ring_entry(struct ioat_softc *ioat,
76     struct ioat_descriptor *desc);
77 static struct ioat_descriptor *ioat_alloc_ring_entry(struct ioat_softc *,
78     int mflags);
79 static int ioat_reserve_space(struct ioat_softc *, uint32_t, int mflags);
80 static struct ioat_descriptor *ioat_get_ring_entry(struct ioat_softc *ioat,
81     uint32_t index);
82 static struct ioat_descriptor **ioat_prealloc_ring(struct ioat_softc *,
83     uint32_t size, boolean_t need_dscr, int mflags);
84 static int ring_grow(struct ioat_softc *, uint32_t oldorder,
85     struct ioat_descriptor **);
86 static int ring_shrink(struct ioat_softc *, uint32_t oldorder,
87     struct ioat_descriptor **);
88 static void ioat_halted_debug(struct ioat_softc *, uint32_t);
89 static void ioat_timer_callback(void *arg);
90 static void dump_descriptor(void *hw_desc);
91 static void ioat_submit_single(struct ioat_softc *ioat);
92 static void ioat_comp_update_map(void *arg, bus_dma_segment_t *seg, int nseg,
93     int error);
94 static int ioat_reset_hw(struct ioat_softc *ioat);
95 static void ioat_setup_sysctl(device_t device);
96 static int sysctl_handle_reset(SYSCTL_HANDLER_ARGS);
97 static inline struct ioat_softc *ioat_get(struct ioat_softc *,
98     enum ioat_ref_kind);
99 static inline void ioat_put(struct ioat_softc *, enum ioat_ref_kind);
100 static inline void _ioat_putn(struct ioat_softc *, uint32_t,
101     enum ioat_ref_kind, boolean_t);
102 static inline void ioat_putn(struct ioat_softc *, uint32_t,
103     enum ioat_ref_kind);
104 static inline void ioat_putn_locked(struct ioat_softc *, uint32_t,
105     enum ioat_ref_kind);
106 static void ioat_drain_locked(struct ioat_softc *);
107 
108 #define	ioat_log_message(v, ...) do {					\
109 	if ((v) <= g_ioat_debug_level) {				\
110 		device_printf(ioat->device, __VA_ARGS__);		\
111 	}								\
112 } while (0)
113 
114 MALLOC_DEFINE(M_IOAT, "ioat", "ioat driver memory allocations");
115 SYSCTL_NODE(_hw, OID_AUTO, ioat, CTLFLAG_RD, 0, "ioat node");
116 
117 static int g_force_legacy_interrupts;
118 SYSCTL_INT(_hw_ioat, OID_AUTO, force_legacy_interrupts, CTLFLAG_RDTUN,
119     &g_force_legacy_interrupts, 0, "Set to non-zero to force MSI-X disabled");
120 
121 int g_ioat_debug_level = 0;
122 SYSCTL_INT(_hw_ioat, OID_AUTO, debug_level, CTLFLAG_RWTUN, &g_ioat_debug_level,
123     0, "Set log level (0-3) for ioat(4). Higher is more verbose.");
124 
125 /*
126  * OS <-> Driver interface structures
127  */
128 static device_method_t ioat_pci_methods[] = {
129 	/* Device interface */
130 	DEVMETHOD(device_probe,     ioat_probe),
131 	DEVMETHOD(device_attach,    ioat_attach),
132 	DEVMETHOD(device_detach,    ioat_detach),
133 	{ 0, 0 }
134 };
135 
136 static driver_t ioat_pci_driver = {
137 	"ioat",
138 	ioat_pci_methods,
139 	sizeof(struct ioat_softc),
140 };
141 
142 static devclass_t ioat_devclass;
143 DRIVER_MODULE(ioat, pci, ioat_pci_driver, ioat_devclass, 0, 0);
144 MODULE_VERSION(ioat, 1);
145 
146 /*
147  * Private data structures
148  */
149 static struct ioat_softc *ioat_channel[IOAT_MAX_CHANNELS];
150 static int ioat_channel_index = 0;
151 SYSCTL_INT(_hw_ioat, OID_AUTO, channels, CTLFLAG_RD, &ioat_channel_index, 0,
152     "Number of IOAT channels attached");
153 
154 static struct _pcsid
155 {
156 	u_int32_t   type;
157 	const char  *desc;
158 } pci_ids[] = {
159 	{ 0x34308086, "TBG IOAT Ch0" },
160 	{ 0x34318086, "TBG IOAT Ch1" },
161 	{ 0x34328086, "TBG IOAT Ch2" },
162 	{ 0x34338086, "TBG IOAT Ch3" },
163 	{ 0x34298086, "TBG IOAT Ch4" },
164 	{ 0x342a8086, "TBG IOAT Ch5" },
165 	{ 0x342b8086, "TBG IOAT Ch6" },
166 	{ 0x342c8086, "TBG IOAT Ch7" },
167 
168 	{ 0x37108086, "JSF IOAT Ch0" },
169 	{ 0x37118086, "JSF IOAT Ch1" },
170 	{ 0x37128086, "JSF IOAT Ch2" },
171 	{ 0x37138086, "JSF IOAT Ch3" },
172 	{ 0x37148086, "JSF IOAT Ch4" },
173 	{ 0x37158086, "JSF IOAT Ch5" },
174 	{ 0x37168086, "JSF IOAT Ch6" },
175 	{ 0x37178086, "JSF IOAT Ch7" },
176 	{ 0x37188086, "JSF IOAT Ch0 (RAID)" },
177 	{ 0x37198086, "JSF IOAT Ch1 (RAID)" },
178 
179 	{ 0x3c208086, "SNB IOAT Ch0" },
180 	{ 0x3c218086, "SNB IOAT Ch1" },
181 	{ 0x3c228086, "SNB IOAT Ch2" },
182 	{ 0x3c238086, "SNB IOAT Ch3" },
183 	{ 0x3c248086, "SNB IOAT Ch4" },
184 	{ 0x3c258086, "SNB IOAT Ch5" },
185 	{ 0x3c268086, "SNB IOAT Ch6" },
186 	{ 0x3c278086, "SNB IOAT Ch7" },
187 	{ 0x3c2e8086, "SNB IOAT Ch0 (RAID)" },
188 	{ 0x3c2f8086, "SNB IOAT Ch1 (RAID)" },
189 
190 	{ 0x0e208086, "IVB IOAT Ch0" },
191 	{ 0x0e218086, "IVB IOAT Ch1" },
192 	{ 0x0e228086, "IVB IOAT Ch2" },
193 	{ 0x0e238086, "IVB IOAT Ch3" },
194 	{ 0x0e248086, "IVB IOAT Ch4" },
195 	{ 0x0e258086, "IVB IOAT Ch5" },
196 	{ 0x0e268086, "IVB IOAT Ch6" },
197 	{ 0x0e278086, "IVB IOAT Ch7" },
198 	{ 0x0e2e8086, "IVB IOAT Ch0 (RAID)" },
199 	{ 0x0e2f8086, "IVB IOAT Ch1 (RAID)" },
200 
201 	{ 0x2f208086, "HSW IOAT Ch0" },
202 	{ 0x2f218086, "HSW IOAT Ch1" },
203 	{ 0x2f228086, "HSW IOAT Ch2" },
204 	{ 0x2f238086, "HSW IOAT Ch3" },
205 	{ 0x2f248086, "HSW IOAT Ch4" },
206 	{ 0x2f258086, "HSW IOAT Ch5" },
207 	{ 0x2f268086, "HSW IOAT Ch6" },
208 	{ 0x2f278086, "HSW IOAT Ch7" },
209 	{ 0x2f2e8086, "HSW IOAT Ch0 (RAID)" },
210 	{ 0x2f2f8086, "HSW IOAT Ch1 (RAID)" },
211 
212 	{ 0x0c508086, "BWD IOAT Ch0" },
213 	{ 0x0c518086, "BWD IOAT Ch1" },
214 	{ 0x0c528086, "BWD IOAT Ch2" },
215 	{ 0x0c538086, "BWD IOAT Ch3" },
216 
217 	{ 0x6f508086, "BDXDE IOAT Ch0" },
218 	{ 0x6f518086, "BDXDE IOAT Ch1" },
219 	{ 0x6f528086, "BDXDE IOAT Ch2" },
220 	{ 0x6f538086, "BDXDE IOAT Ch3" },
221 
222 	{ 0x6f208086, "BDX IOAT Ch0" },
223 	{ 0x6f218086, "BDX IOAT Ch1" },
224 	{ 0x6f228086, "BDX IOAT Ch2" },
225 	{ 0x6f238086, "BDX IOAT Ch3" },
226 	{ 0x6f248086, "BDX IOAT Ch4" },
227 	{ 0x6f258086, "BDX IOAT Ch5" },
228 	{ 0x6f268086, "BDX IOAT Ch6" },
229 	{ 0x6f278086, "BDX IOAT Ch7" },
230 	{ 0x6f2e8086, "BDX IOAT Ch0 (RAID)" },
231 	{ 0x6f2f8086, "BDX IOAT Ch1 (RAID)" },
232 
233 	{ 0x00000000, NULL           }
234 };
235 
236 /*
237  * OS <-> Driver linkage functions
238  */
239 static int
240 ioat_probe(device_t device)
241 {
242 	struct _pcsid *ep;
243 	u_int32_t type;
244 
245 	type = pci_get_devid(device);
246 	for (ep = pci_ids; ep->type; ep++) {
247 		if (ep->type == type) {
248 			device_set_desc(device, ep->desc);
249 			return (0);
250 		}
251 	}
252 	return (ENXIO);
253 }
254 
255 static int
256 ioat_attach(device_t device)
257 {
258 	struct ioat_softc *ioat;
259 	int error;
260 
261 	ioat = DEVICE2SOFTC(device);
262 	ioat->device = device;
263 
264 	error = ioat_map_pci_bar(ioat);
265 	if (error != 0)
266 		goto err;
267 
268 	ioat->version = ioat_read_cbver(ioat);
269 	if (ioat->version < IOAT_VER_3_0) {
270 		error = ENODEV;
271 		goto err;
272 	}
273 
274 	error = ioat3_attach(device);
275 	if (error != 0)
276 		goto err;
277 
278 	error = pci_enable_busmaster(device);
279 	if (error != 0)
280 		goto err;
281 
282 	error = ioat_setup_intr(ioat);
283 	if (error != 0)
284 		goto err;
285 
286 	error = ioat_reset_hw(ioat);
287 	if (error != 0)
288 		goto err;
289 
290 	ioat_process_events(ioat);
291 	ioat_setup_sysctl(device);
292 
293 	ioat->chan_idx = ioat_channel_index;
294 	ioat_channel[ioat_channel_index++] = ioat;
295 	ioat_test_attach();
296 
297 err:
298 	if (error != 0)
299 		ioat_detach(device);
300 	return (error);
301 }
302 
303 static int
304 ioat_detach(device_t device)
305 {
306 	struct ioat_softc *ioat;
307 
308 	ioat = DEVICE2SOFTC(device);
309 
310 	ioat_test_detach();
311 
312 	mtx_lock(IOAT_REFLK);
313 	ioat->quiescing = TRUE;
314 	ioat_channel[ioat->chan_idx] = NULL;
315 
316 	ioat_drain_locked(ioat);
317 	mtx_unlock(IOAT_REFLK);
318 
319 	ioat_teardown_intr(ioat);
320 	callout_drain(&ioat->timer);
321 
322 	pci_disable_busmaster(device);
323 
324 	if (ioat->pci_resource != NULL)
325 		bus_release_resource(device, SYS_RES_MEMORY,
326 		    ioat->pci_resource_id, ioat->pci_resource);
327 
328 	if (ioat->ring != NULL)
329 		ioat_free_ring(ioat, 1 << ioat->ring_size_order, ioat->ring);
330 
331 	if (ioat->comp_update != NULL) {
332 		bus_dmamap_unload(ioat->comp_update_tag, ioat->comp_update_map);
333 		bus_dmamem_free(ioat->comp_update_tag, ioat->comp_update,
334 		    ioat->comp_update_map);
335 		bus_dma_tag_destroy(ioat->comp_update_tag);
336 	}
337 
338 	bus_dma_tag_destroy(ioat->hw_desc_tag);
339 
340 	return (0);
341 }
342 
343 static int
344 ioat_teardown_intr(struct ioat_softc *ioat)
345 {
346 
347 	if (ioat->tag != NULL)
348 		bus_teardown_intr(ioat->device, ioat->res, ioat->tag);
349 
350 	if (ioat->res != NULL)
351 		bus_release_resource(ioat->device, SYS_RES_IRQ,
352 		    rman_get_rid(ioat->res), ioat->res);
353 
354 	pci_release_msi(ioat->device);
355 	return (0);
356 }
357 
358 static int
359 ioat_start_channel(struct ioat_softc *ioat)
360 {
361 	uint64_t status;
362 	uint32_t chanerr;
363 	int i;
364 
365 	ioat_acquire(&ioat->dmaengine);
366 	ioat_null(&ioat->dmaengine, NULL, NULL, 0);
367 	ioat_release(&ioat->dmaengine);
368 
369 	for (i = 0; i < 100; i++) {
370 		DELAY(1);
371 		status = ioat_get_chansts(ioat);
372 		if (is_ioat_idle(status))
373 			return (0);
374 	}
375 
376 	chanerr = ioat_read_4(ioat, IOAT_CHANERR_OFFSET);
377 	ioat_log_message(0, "could not start channel: "
378 	    "status = %#jx error = %b\n", (uintmax_t)status, (int)chanerr,
379 	    IOAT_CHANERR_STR);
380 	return (ENXIO);
381 }
382 
383 /*
384  * Initialize Hardware
385  */
386 static int
387 ioat3_attach(device_t device)
388 {
389 	struct ioat_softc *ioat;
390 	struct ioat_descriptor **ring;
391 	struct ioat_descriptor *next;
392 	struct ioat_dma_hw_descriptor *dma_hw_desc;
393 	int i, num_descriptors;
394 	int error;
395 	uint8_t xfercap;
396 
397 	error = 0;
398 	ioat = DEVICE2SOFTC(device);
399 	ioat->capabilities = ioat_read_dmacapability(ioat);
400 
401 	ioat_log_message(1, "Capabilities: %b\n", (int)ioat->capabilities,
402 	    IOAT_DMACAP_STR);
403 
404 	xfercap = ioat_read_xfercap(ioat);
405 	ioat->max_xfer_size = 1 << xfercap;
406 
407 	ioat->intrdelay_supported = (ioat_read_2(ioat, IOAT_INTRDELAY_OFFSET) &
408 	    IOAT_INTRDELAY_SUPPORTED) != 0;
409 	if (ioat->intrdelay_supported)
410 		ioat->intrdelay_max = IOAT_INTRDELAY_US_MASK;
411 
412 	/* TODO: need to check DCA here if we ever do XOR/PQ */
413 
414 	mtx_init(&ioat->submit_lock, "ioat_submit", NULL, MTX_DEF);
415 	mtx_init(&ioat->cleanup_lock, "ioat_cleanup", NULL, MTX_DEF);
416 	callout_init(&ioat->timer, 1);
417 
418 	/* Establish lock order for Witness */
419 	mtx_lock(&ioat->submit_lock);
420 	mtx_lock(&ioat->cleanup_lock);
421 	mtx_unlock(&ioat->cleanup_lock);
422 	mtx_unlock(&ioat->submit_lock);
423 
424 	ioat->is_resize_pending = FALSE;
425 	ioat->is_completion_pending = FALSE;
426 	ioat->is_reset_pending = FALSE;
427 	ioat->is_channel_running = FALSE;
428 
429 	bus_dma_tag_create(bus_get_dma_tag(ioat->device), sizeof(uint64_t), 0x0,
430 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
431 	    sizeof(uint64_t), 1, sizeof(uint64_t), 0, NULL, NULL,
432 	    &ioat->comp_update_tag);
433 
434 	error = bus_dmamem_alloc(ioat->comp_update_tag,
435 	    (void **)&ioat->comp_update, BUS_DMA_ZERO, &ioat->comp_update_map);
436 	if (ioat->comp_update == NULL)
437 		return (ENOMEM);
438 
439 	error = bus_dmamap_load(ioat->comp_update_tag, ioat->comp_update_map,
440 	    ioat->comp_update, sizeof(uint64_t), ioat_comp_update_map, ioat,
441 	    0);
442 	if (error != 0)
443 		return (error);
444 
445 	ioat->ring_size_order = IOAT_MIN_ORDER;
446 
447 	num_descriptors = 1 << ioat->ring_size_order;
448 
449 	bus_dma_tag_create(bus_get_dma_tag(ioat->device), 0x40, 0x0,
450 	    BUS_SPACE_MAXADDR, BUS_SPACE_MAXADDR, NULL, NULL,
451 	    sizeof(struct ioat_dma_hw_descriptor), 1,
452 	    sizeof(struct ioat_dma_hw_descriptor), 0, NULL, NULL,
453 	    &ioat->hw_desc_tag);
454 
455 	ioat->ring = malloc(num_descriptors * sizeof(*ring), M_IOAT,
456 	    M_ZERO | M_WAITOK);
457 	if (ioat->ring == NULL)
458 		return (ENOMEM);
459 
460 	ring = ioat->ring;
461 	for (i = 0; i < num_descriptors; i++) {
462 		ring[i] = ioat_alloc_ring_entry(ioat, M_WAITOK);
463 		if (ring[i] == NULL)
464 			return (ENOMEM);
465 
466 		ring[i]->id = i;
467 	}
468 
469 	for (i = 0; i < num_descriptors - 1; i++) {
470 		next = ring[i + 1];
471 		dma_hw_desc = ring[i]->u.dma;
472 
473 		dma_hw_desc->next = next->hw_desc_bus_addr;
474 	}
475 
476 	ring[i]->u.dma->next = ring[0]->hw_desc_bus_addr;
477 
478 	ioat->head = ioat->hw_head = 0;
479 	ioat->tail = 0;
480 	ioat->last_seen = 0;
481 	return (0);
482 }
483 
484 static int
485 ioat_map_pci_bar(struct ioat_softc *ioat)
486 {
487 
488 	ioat->pci_resource_id = PCIR_BAR(0);
489 	ioat->pci_resource = bus_alloc_resource_any(ioat->device,
490 	    SYS_RES_MEMORY, &ioat->pci_resource_id, RF_ACTIVE);
491 
492 	if (ioat->pci_resource == NULL) {
493 		ioat_log_message(0, "unable to allocate pci resource\n");
494 		return (ENODEV);
495 	}
496 
497 	ioat->pci_bus_tag = rman_get_bustag(ioat->pci_resource);
498 	ioat->pci_bus_handle = rman_get_bushandle(ioat->pci_resource);
499 	return (0);
500 }
501 
502 static void
503 ioat_comp_update_map(void *arg, bus_dma_segment_t *seg, int nseg, int error)
504 {
505 	struct ioat_softc *ioat = arg;
506 
507 	KASSERT(error == 0, ("%s: error:%d", __func__, error));
508 	ioat->comp_update_bus_addr = seg[0].ds_addr;
509 }
510 
511 static void
512 ioat_dmamap_cb(void *arg, bus_dma_segment_t *segs, int nseg, int error)
513 {
514 	bus_addr_t *baddr;
515 
516 	KASSERT(error == 0, ("%s: error:%d", __func__, error));
517 	baddr = arg;
518 	*baddr = segs->ds_addr;
519 }
520 
521 /*
522  * Interrupt setup and handlers
523  */
524 static int
525 ioat_setup_intr(struct ioat_softc *ioat)
526 {
527 	uint32_t num_vectors;
528 	int error;
529 	boolean_t use_msix;
530 	boolean_t force_legacy_interrupts;
531 
532 	use_msix = FALSE;
533 	force_legacy_interrupts = FALSE;
534 
535 	if (!g_force_legacy_interrupts && pci_msix_count(ioat->device) >= 1) {
536 		num_vectors = 1;
537 		pci_alloc_msix(ioat->device, &num_vectors);
538 		if (num_vectors == 1)
539 			use_msix = TRUE;
540 	}
541 
542 	if (use_msix) {
543 		ioat->rid = 1;
544 		ioat->res = bus_alloc_resource_any(ioat->device, SYS_RES_IRQ,
545 		    &ioat->rid, RF_ACTIVE);
546 	} else {
547 		ioat->rid = 0;
548 		ioat->res = bus_alloc_resource_any(ioat->device, SYS_RES_IRQ,
549 		    &ioat->rid, RF_SHAREABLE | RF_ACTIVE);
550 	}
551 	if (ioat->res == NULL) {
552 		ioat_log_message(0, "bus_alloc_resource failed\n");
553 		return (ENOMEM);
554 	}
555 
556 	ioat->tag = NULL;
557 	error = bus_setup_intr(ioat->device, ioat->res, INTR_MPSAFE |
558 	    INTR_TYPE_MISC, NULL, ioat_interrupt_handler, ioat, &ioat->tag);
559 	if (error != 0) {
560 		ioat_log_message(0, "bus_setup_intr failed\n");
561 		return (error);
562 	}
563 
564 	ioat_write_intrctrl(ioat, IOAT_INTRCTRL_MASTER_INT_EN);
565 	return (0);
566 }
567 
568 static boolean_t
569 ioat_model_resets_msix(struct ioat_softc *ioat)
570 {
571 	u_int32_t pciid;
572 
573 	pciid = pci_get_devid(ioat->device);
574 	switch (pciid) {
575 		/* BWD: */
576 	case 0x0c508086:
577 	case 0x0c518086:
578 	case 0x0c528086:
579 	case 0x0c538086:
580 		/* BDXDE: */
581 	case 0x6f508086:
582 	case 0x6f518086:
583 	case 0x6f528086:
584 	case 0x6f538086:
585 		return (TRUE);
586 	}
587 
588 	return (FALSE);
589 }
590 
591 static void
592 ioat_interrupt_handler(void *arg)
593 {
594 	struct ioat_softc *ioat = arg;
595 
596 	ioat->stats.interrupts++;
597 	ioat_process_events(ioat);
598 }
599 
600 static int
601 chanerr_to_errno(uint32_t chanerr)
602 {
603 
604 	if (chanerr == 0)
605 		return (0);
606 	if ((chanerr & (IOAT_CHANERR_XSADDERR | IOAT_CHANERR_XDADDERR)) != 0)
607 		return (EFAULT);
608 	if ((chanerr & (IOAT_CHANERR_RDERR | IOAT_CHANERR_WDERR)) != 0)
609 		return (EIO);
610 	/* This one is probably our fault: */
611 	if ((chanerr & IOAT_CHANERR_NDADDERR) != 0)
612 		return (EIO);
613 	return (EIO);
614 }
615 
616 static void
617 ioat_process_events(struct ioat_softc *ioat)
618 {
619 	struct ioat_descriptor *desc;
620 	struct bus_dmadesc *dmadesc;
621 	uint64_t comp_update, status;
622 	uint32_t completed, chanerr;
623 	int error;
624 
625 	mtx_lock(&ioat->cleanup_lock);
626 
627 	completed = 0;
628 	comp_update = *ioat->comp_update;
629 	status = comp_update & IOAT_CHANSTS_COMPLETED_DESCRIPTOR_MASK;
630 
631 	CTR0(KTR_IOAT, __func__);
632 
633 	if (status == ioat->last_seen)
634 		goto out;
635 
636 	while (1) {
637 		desc = ioat_get_ring_entry(ioat, ioat->tail);
638 		dmadesc = &desc->bus_dmadesc;
639 		CTR1(KTR_IOAT, "completing desc %d", ioat->tail);
640 
641 		if (dmadesc->callback_fn != NULL)
642 			dmadesc->callback_fn(dmadesc->callback_arg, 0);
643 
644 		completed++;
645 		ioat->tail++;
646 		if (desc->hw_desc_bus_addr == status)
647 			break;
648 	}
649 
650 	ioat->last_seen = desc->hw_desc_bus_addr;
651 
652 	if (ioat->head == ioat->tail) {
653 		ioat->is_completion_pending = FALSE;
654 		callout_reset(&ioat->timer, IOAT_INTR_TIMO,
655 		    ioat_timer_callback, ioat);
656 	}
657 
658 	ioat->stats.descriptors_processed += completed;
659 
660 out:
661 	ioat_write_chanctrl(ioat, IOAT_CHANCTRL_RUN);
662 	mtx_unlock(&ioat->cleanup_lock);
663 
664 	ioat_putn(ioat, completed, IOAT_ACTIVE_DESCR_REF);
665 	wakeup(&ioat->tail);
666 
667 	if (!is_ioat_halted(comp_update))
668 		return;
669 
670 	ioat->stats.channel_halts++;
671 
672 	/*
673 	 * Fatal programming error on this DMA channel.  Flush any outstanding
674 	 * work with error status and restart the engine.
675 	 */
676 	ioat_log_message(0, "Channel halted due to fatal programming error\n");
677 	mtx_lock(&ioat->submit_lock);
678 	mtx_lock(&ioat->cleanup_lock);
679 	ioat->quiescing = TRUE;
680 
681 	chanerr = ioat_read_4(ioat, IOAT_CHANERR_OFFSET);
682 	ioat_halted_debug(ioat, chanerr);
683 	ioat->stats.last_halt_chanerr = chanerr;
684 
685 	while (ioat_get_active(ioat) > 0) {
686 		desc = ioat_get_ring_entry(ioat, ioat->tail);
687 		dmadesc = &desc->bus_dmadesc;
688 		CTR1(KTR_IOAT, "completing err desc %d", ioat->tail);
689 
690 		if (dmadesc->callback_fn != NULL)
691 			dmadesc->callback_fn(dmadesc->callback_arg,
692 			    chanerr_to_errno(chanerr));
693 
694 		ioat_putn_locked(ioat, 1, IOAT_ACTIVE_DESCR_REF);
695 		ioat->tail++;
696 		ioat->stats.descriptors_processed++;
697 		ioat->stats.descriptors_error++;
698 	}
699 
700 	/* Clear error status */
701 	ioat_write_4(ioat, IOAT_CHANERR_OFFSET, chanerr);
702 
703 	mtx_unlock(&ioat->cleanup_lock);
704 	mtx_unlock(&ioat->submit_lock);
705 
706 	ioat_log_message(0, "Resetting channel to recover from error\n");
707 	error = ioat_reset_hw(ioat);
708 	KASSERT(error == 0, ("%s: reset failed: %d", __func__, error));
709 }
710 
711 /*
712  * User API functions
713  */
714 bus_dmaengine_t
715 ioat_get_dmaengine(uint32_t index)
716 {
717 	struct ioat_softc *sc;
718 
719 	if (index >= ioat_channel_index)
720 		return (NULL);
721 
722 	sc = ioat_channel[index];
723 	if (sc == NULL || sc->quiescing)
724 		return (NULL);
725 
726 	return (&ioat_get(sc, IOAT_DMAENGINE_REF)->dmaengine);
727 }
728 
729 void
730 ioat_put_dmaengine(bus_dmaengine_t dmaengine)
731 {
732 	struct ioat_softc *ioat;
733 
734 	ioat = to_ioat_softc(dmaengine);
735 	ioat_put(ioat, IOAT_DMAENGINE_REF);
736 }
737 
738 int
739 ioat_get_hwversion(bus_dmaengine_t dmaengine)
740 {
741 	struct ioat_softc *ioat;
742 
743 	ioat = to_ioat_softc(dmaengine);
744 	return (ioat->version);
745 }
746 
747 size_t
748 ioat_get_max_io_size(bus_dmaengine_t dmaengine)
749 {
750 	struct ioat_softc *ioat;
751 
752 	ioat = to_ioat_softc(dmaengine);
753 	return (ioat->max_xfer_size);
754 }
755 
756 int
757 ioat_set_interrupt_coalesce(bus_dmaengine_t dmaengine, uint16_t delay)
758 {
759 	struct ioat_softc *ioat;
760 
761 	ioat = to_ioat_softc(dmaengine);
762 	if (!ioat->intrdelay_supported)
763 		return (ENODEV);
764 	if (delay > ioat->intrdelay_max)
765 		return (ERANGE);
766 
767 	ioat_write_2(ioat, IOAT_INTRDELAY_OFFSET, delay);
768 	ioat->cached_intrdelay =
769 	    ioat_read_2(ioat, IOAT_INTRDELAY_OFFSET) & IOAT_INTRDELAY_US_MASK;
770 	return (0);
771 }
772 
773 uint16_t
774 ioat_get_max_coalesce_period(bus_dmaengine_t dmaengine)
775 {
776 	struct ioat_softc *ioat;
777 
778 	ioat = to_ioat_softc(dmaengine);
779 	return (ioat->intrdelay_max);
780 }
781 
782 void
783 ioat_acquire(bus_dmaengine_t dmaengine)
784 {
785 	struct ioat_softc *ioat;
786 
787 	ioat = to_ioat_softc(dmaengine);
788 	mtx_lock(&ioat->submit_lock);
789 	CTR0(KTR_IOAT, __func__);
790 }
791 
792 int
793 ioat_acquire_reserve(bus_dmaengine_t dmaengine, unsigned n, int mflags)
794 {
795 	struct ioat_softc *ioat;
796 	int error;
797 
798 	ioat = to_ioat_softc(dmaengine);
799 	ioat_acquire(dmaengine);
800 
801 	error = ioat_reserve_space(ioat, n, mflags);
802 	if (error != 0)
803 		ioat_release(dmaengine);
804 	return (error);
805 }
806 
807 void
808 ioat_release(bus_dmaengine_t dmaengine)
809 {
810 	struct ioat_softc *ioat;
811 
812 	ioat = to_ioat_softc(dmaengine);
813 	CTR0(KTR_IOAT, __func__);
814 	ioat_write_2(ioat, IOAT_DMACOUNT_OFFSET, (uint16_t)ioat->hw_head);
815 	mtx_unlock(&ioat->submit_lock);
816 }
817 
818 static struct ioat_descriptor *
819 ioat_op_generic(struct ioat_softc *ioat, uint8_t op,
820     uint32_t size, uint64_t src, uint64_t dst,
821     bus_dmaengine_callback_t callback_fn, void *callback_arg,
822     uint32_t flags)
823 {
824 	struct ioat_generic_hw_descriptor *hw_desc;
825 	struct ioat_descriptor *desc;
826 	int mflags;
827 
828 	mtx_assert(&ioat->submit_lock, MA_OWNED);
829 
830 	KASSERT((flags & ~DMA_ALL_FLAGS) == 0, ("Unrecognized flag(s): %#x",
831 		flags & ~DMA_ALL_FLAGS));
832 	if ((flags & DMA_NO_WAIT) != 0)
833 		mflags = M_NOWAIT;
834 	else
835 		mflags = M_WAITOK;
836 
837 	if (size > ioat->max_xfer_size) {
838 		ioat_log_message(0, "%s: max_xfer_size = %d, requested = %u\n",
839 		    __func__, ioat->max_xfer_size, (unsigned)size);
840 		return (NULL);
841 	}
842 
843 	if (ioat_reserve_space(ioat, 1, mflags) != 0)
844 		return (NULL);
845 
846 	desc = ioat_get_ring_entry(ioat, ioat->head);
847 	hw_desc = desc->u.generic;
848 
849 	hw_desc->u.control_raw = 0;
850 	hw_desc->u.control_generic.op = op;
851 	hw_desc->u.control_generic.completion_update = 1;
852 
853 	if ((flags & DMA_INT_EN) != 0)
854 		hw_desc->u.control_generic.int_enable = 1;
855 	if ((flags & DMA_FENCE) != 0)
856 		hw_desc->u.control_generic.fence = 1;
857 
858 	hw_desc->size = size;
859 	hw_desc->src_addr = src;
860 	hw_desc->dest_addr = dst;
861 
862 	desc->bus_dmadesc.callback_fn = callback_fn;
863 	desc->bus_dmadesc.callback_arg = callback_arg;
864 	return (desc);
865 }
866 
867 struct bus_dmadesc *
868 ioat_null(bus_dmaengine_t dmaengine, bus_dmaengine_callback_t callback_fn,
869     void *callback_arg, uint32_t flags)
870 {
871 	struct ioat_dma_hw_descriptor *hw_desc;
872 	struct ioat_descriptor *desc;
873 	struct ioat_softc *ioat;
874 
875 	CTR0(KTR_IOAT, __func__);
876 	ioat = to_ioat_softc(dmaengine);
877 
878 	desc = ioat_op_generic(ioat, IOAT_OP_COPY, 8, 0, 0, callback_fn,
879 	    callback_arg, flags);
880 	if (desc == NULL)
881 		return (NULL);
882 
883 	hw_desc = desc->u.dma;
884 	hw_desc->u.control.null = 1;
885 	ioat_submit_single(ioat);
886 	return (&desc->bus_dmadesc);
887 }
888 
889 struct bus_dmadesc *
890 ioat_copy(bus_dmaengine_t dmaengine, bus_addr_t dst,
891     bus_addr_t src, bus_size_t len, bus_dmaengine_callback_t callback_fn,
892     void *callback_arg, uint32_t flags)
893 {
894 	struct ioat_dma_hw_descriptor *hw_desc;
895 	struct ioat_descriptor *desc;
896 	struct ioat_softc *ioat;
897 
898 	CTR0(KTR_IOAT, __func__);
899 	ioat = to_ioat_softc(dmaengine);
900 
901 	if (((src | dst) & (0xffffull << 48)) != 0) {
902 		ioat_log_message(0, "%s: High 16 bits of src/dst invalid\n",
903 		    __func__);
904 		return (NULL);
905 	}
906 
907 	desc = ioat_op_generic(ioat, IOAT_OP_COPY, len, src, dst, callback_fn,
908 	    callback_arg, flags);
909 	if (desc == NULL)
910 		return (NULL);
911 
912 	hw_desc = desc->u.dma;
913 	if (g_ioat_debug_level >= 3)
914 		dump_descriptor(hw_desc);
915 
916 	ioat_submit_single(ioat);
917 	return (&desc->bus_dmadesc);
918 }
919 
920 struct bus_dmadesc *
921 ioat_copy_8k_aligned(bus_dmaengine_t dmaengine, bus_addr_t dst1,
922     bus_addr_t dst2, bus_addr_t src1, bus_addr_t src2,
923     bus_dmaengine_callback_t callback_fn, void *callback_arg, uint32_t flags)
924 {
925 	struct ioat_dma_hw_descriptor *hw_desc;
926 	struct ioat_descriptor *desc;
927 	struct ioat_softc *ioat;
928 
929 	CTR0(KTR_IOAT, __func__);
930 	ioat = to_ioat_softc(dmaengine);
931 
932 	if (((src1 | src2 | dst1 | dst2) & (0xffffull << 48)) != 0) {
933 		ioat_log_message(0, "%s: High 16 bits of src/dst invalid\n",
934 		    __func__);
935 		return (NULL);
936 	}
937 	if (((src1 | src2 | dst1 | dst2) & PAGE_MASK) != 0) {
938 		ioat_log_message(0, "%s: Addresses must be page-aligned\n",
939 		    __func__);
940 		return (NULL);
941 	}
942 
943 	desc = ioat_op_generic(ioat, IOAT_OP_COPY, 2 * PAGE_SIZE, src1, dst1,
944 	    callback_fn, callback_arg, flags);
945 	if (desc == NULL)
946 		return (NULL);
947 
948 	hw_desc = desc->u.dma;
949 	if (src2 != src1 + PAGE_SIZE) {
950 		hw_desc->u.control.src_page_break = 1;
951 		hw_desc->next_src_addr = src2;
952 	}
953 	if (dst2 != dst1 + PAGE_SIZE) {
954 		hw_desc->u.control.dest_page_break = 1;
955 		hw_desc->next_dest_addr = dst2;
956 	}
957 
958 	if (g_ioat_debug_level >= 3)
959 		dump_descriptor(hw_desc);
960 
961 	ioat_submit_single(ioat);
962 	return (&desc->bus_dmadesc);
963 }
964 
965 struct bus_dmadesc *
966 ioat_blockfill(bus_dmaengine_t dmaengine, bus_addr_t dst, uint64_t fillpattern,
967     bus_size_t len, bus_dmaengine_callback_t callback_fn, void *callback_arg,
968     uint32_t flags)
969 {
970 	struct ioat_fill_hw_descriptor *hw_desc;
971 	struct ioat_descriptor *desc;
972 	struct ioat_softc *ioat;
973 
974 	CTR0(KTR_IOAT, __func__);
975 	ioat = to_ioat_softc(dmaengine);
976 
977 	if ((ioat->capabilities & IOAT_DMACAP_BFILL) == 0) {
978 		ioat_log_message(0, "%s: Device lacks BFILL capability\n",
979 		    __func__);
980 		return (NULL);
981 	}
982 
983 	if ((dst & (0xffffull << 48)) != 0) {
984 		ioat_log_message(0, "%s: High 16 bits of dst invalid\n",
985 		    __func__);
986 		return (NULL);
987 	}
988 
989 	desc = ioat_op_generic(ioat, IOAT_OP_FILL, len, fillpattern, dst,
990 	    callback_fn, callback_arg, flags);
991 	if (desc == NULL)
992 		return (NULL);
993 
994 	hw_desc = desc->u.fill;
995 	if (g_ioat_debug_level >= 3)
996 		dump_descriptor(hw_desc);
997 
998 	ioat_submit_single(ioat);
999 	return (&desc->bus_dmadesc);
1000 }
1001 
1002 /*
1003  * Ring Management
1004  */
1005 static inline uint32_t
1006 ioat_get_active(struct ioat_softc *ioat)
1007 {
1008 
1009 	return ((ioat->head - ioat->tail) & ((1 << ioat->ring_size_order) - 1));
1010 }
1011 
1012 static inline uint32_t
1013 ioat_get_ring_space(struct ioat_softc *ioat)
1014 {
1015 
1016 	return ((1 << ioat->ring_size_order) - ioat_get_active(ioat) - 1);
1017 }
1018 
1019 static struct ioat_descriptor *
1020 ioat_alloc_ring_entry(struct ioat_softc *ioat, int mflags)
1021 {
1022 	struct ioat_generic_hw_descriptor *hw_desc;
1023 	struct ioat_descriptor *desc;
1024 	int error, busdmaflag;
1025 
1026 	error = ENOMEM;
1027 	hw_desc = NULL;
1028 
1029 	if ((mflags & M_WAITOK) != 0)
1030 		busdmaflag = BUS_DMA_WAITOK;
1031 	else
1032 		busdmaflag = BUS_DMA_NOWAIT;
1033 
1034 	desc = malloc(sizeof(*desc), M_IOAT, mflags);
1035 	if (desc == NULL)
1036 		goto out;
1037 
1038 	bus_dmamem_alloc(ioat->hw_desc_tag, (void **)&hw_desc,
1039 	    BUS_DMA_ZERO | busdmaflag, &ioat->hw_desc_map);
1040 	if (hw_desc == NULL)
1041 		goto out;
1042 
1043 	memset(&desc->bus_dmadesc, 0, sizeof(desc->bus_dmadesc));
1044 	desc->u.generic = hw_desc;
1045 
1046 	error = bus_dmamap_load(ioat->hw_desc_tag, ioat->hw_desc_map, hw_desc,
1047 	    sizeof(*hw_desc), ioat_dmamap_cb, &desc->hw_desc_bus_addr,
1048 	    busdmaflag);
1049 	if (error)
1050 		goto out;
1051 
1052 out:
1053 	if (error) {
1054 		ioat_free_ring_entry(ioat, desc);
1055 		return (NULL);
1056 	}
1057 	return (desc);
1058 }
1059 
1060 static void
1061 ioat_free_ring_entry(struct ioat_softc *ioat, struct ioat_descriptor *desc)
1062 {
1063 
1064 	if (desc == NULL)
1065 		return;
1066 
1067 	if (desc->u.generic)
1068 		bus_dmamem_free(ioat->hw_desc_tag, desc->u.generic,
1069 		    ioat->hw_desc_map);
1070 	free(desc, M_IOAT);
1071 }
1072 
1073 /*
1074  * Reserves space in this IOAT descriptor ring by ensuring enough slots remain
1075  * for 'num_descs'.
1076  *
1077  * If mflags contains M_WAITOK, blocks until enough space is available.
1078  *
1079  * Returns zero on success, or an errno on error.  If num_descs is beyond the
1080  * maximum ring size, returns EINVAl; if allocation would block and mflags
1081  * contains M_NOWAIT, returns EAGAIN.
1082  *
1083  * Must be called with the submit_lock held; returns with the lock held.  The
1084  * lock may be dropped to allocate the ring.
1085  *
1086  * (The submit_lock is needed to add any entries to the ring, so callers are
1087  * assured enough room is available.)
1088  */
1089 static int
1090 ioat_reserve_space(struct ioat_softc *ioat, uint32_t num_descs, int mflags)
1091 {
1092 	struct ioat_descriptor **new_ring;
1093 	uint32_t order;
1094 	int error;
1095 
1096 	mtx_assert(&ioat->submit_lock, MA_OWNED);
1097 	error = 0;
1098 
1099 	if (num_descs < 1 || num_descs > (1 << IOAT_MAX_ORDER)) {
1100 		error = EINVAL;
1101 		goto out;
1102 	}
1103 	if (ioat->quiescing) {
1104 		error = ENXIO;
1105 		goto out;
1106 	}
1107 
1108 	for (;;) {
1109 		if (ioat_get_ring_space(ioat) >= num_descs)
1110 			goto out;
1111 
1112 		order = ioat->ring_size_order;
1113 		if (ioat->is_resize_pending || order == IOAT_MAX_ORDER) {
1114 			if ((mflags & M_WAITOK) != 0) {
1115 				msleep(&ioat->tail, &ioat->submit_lock, 0,
1116 				    "ioat_rsz", 0);
1117 				continue;
1118 			}
1119 
1120 			error = EAGAIN;
1121 			break;
1122 		}
1123 
1124 		ioat->is_resize_pending = TRUE;
1125 		for (;;) {
1126 			mtx_unlock(&ioat->submit_lock);
1127 
1128 			new_ring = ioat_prealloc_ring(ioat, 1 << (order + 1),
1129 			    TRUE, mflags);
1130 
1131 			mtx_lock(&ioat->submit_lock);
1132 			KASSERT(ioat->ring_size_order == order,
1133 			    ("is_resize_pending should protect order"));
1134 
1135 			if (new_ring == NULL) {
1136 				KASSERT((mflags & M_WAITOK) == 0,
1137 				    ("allocation failed"));
1138 				error = EAGAIN;
1139 				break;
1140 			}
1141 
1142 			error = ring_grow(ioat, order, new_ring);
1143 			if (error == 0)
1144 				break;
1145 		}
1146 		ioat->is_resize_pending = FALSE;
1147 		wakeup(&ioat->tail);
1148 		if (error)
1149 			break;
1150 	}
1151 
1152 out:
1153 	mtx_assert(&ioat->submit_lock, MA_OWNED);
1154 	return (error);
1155 }
1156 
1157 static struct ioat_descriptor **
1158 ioat_prealloc_ring(struct ioat_softc *ioat, uint32_t size, boolean_t need_dscr,
1159     int mflags)
1160 {
1161 	struct ioat_descriptor **ring;
1162 	uint32_t i;
1163 	int error;
1164 
1165 	KASSERT(size > 0 && powerof2(size), ("bogus size"));
1166 
1167 	ring = malloc(size * sizeof(*ring), M_IOAT, M_ZERO | mflags);
1168 	if (ring == NULL)
1169 		return (NULL);
1170 
1171 	if (need_dscr) {
1172 		error = ENOMEM;
1173 		for (i = size / 2; i < size; i++) {
1174 			ring[i] = ioat_alloc_ring_entry(ioat, mflags);
1175 			if (ring[i] == NULL)
1176 				goto out;
1177 			ring[i]->id = i;
1178 		}
1179 	}
1180 	error = 0;
1181 
1182 out:
1183 	if (error != 0 && ring != NULL) {
1184 		ioat_free_ring(ioat, size, ring);
1185 		ring = NULL;
1186 	}
1187 	return (ring);
1188 }
1189 
1190 static void
1191 ioat_free_ring(struct ioat_softc *ioat, uint32_t size,
1192     struct ioat_descriptor **ring)
1193 {
1194 	uint32_t i;
1195 
1196 	for (i = 0; i < size; i++) {
1197 		if (ring[i] != NULL)
1198 			ioat_free_ring_entry(ioat, ring[i]);
1199 	}
1200 	free(ring, M_IOAT);
1201 }
1202 
1203 static struct ioat_descriptor *
1204 ioat_get_ring_entry(struct ioat_softc *ioat, uint32_t index)
1205 {
1206 
1207 	return (ioat->ring[index % (1 << ioat->ring_size_order)]);
1208 }
1209 
1210 static int
1211 ring_grow(struct ioat_softc *ioat, uint32_t oldorder,
1212     struct ioat_descriptor **newring)
1213 {
1214 	struct ioat_descriptor *tmp, *next;
1215 	struct ioat_dma_hw_descriptor *hw;
1216 	uint32_t oldsize, newsize, head, tail, i, end;
1217 	int error;
1218 
1219 	CTR0(KTR_IOAT, __func__);
1220 
1221 	mtx_assert(&ioat->submit_lock, MA_OWNED);
1222 
1223 	if (oldorder != ioat->ring_size_order || oldorder >= IOAT_MAX_ORDER) {
1224 		error = EINVAL;
1225 		goto out;
1226 	}
1227 
1228 	oldsize = (1 << oldorder);
1229 	newsize = (1 << (oldorder + 1));
1230 
1231 	mtx_lock(&ioat->cleanup_lock);
1232 
1233 	head = ioat->head & (oldsize - 1);
1234 	tail = ioat->tail & (oldsize - 1);
1235 
1236 	/* Copy old descriptors to new ring */
1237 	for (i = 0; i < oldsize; i++)
1238 		newring[i] = ioat->ring[i];
1239 
1240 	/*
1241 	 * If head has wrapped but tail hasn't, we must swap some descriptors
1242 	 * around so that tail can increment directly to head.
1243 	 */
1244 	if (head < tail) {
1245 		for (i = 0; i <= head; i++) {
1246 			tmp = newring[oldsize + i];
1247 
1248 			newring[oldsize + i] = newring[i];
1249 			newring[oldsize + i]->id = oldsize + i;
1250 
1251 			newring[i] = tmp;
1252 			newring[i]->id = i;
1253 		}
1254 		head += oldsize;
1255 	}
1256 
1257 	KASSERT(head >= tail, ("invariants"));
1258 
1259 	/* Head didn't wrap; we only need to link in oldsize..newsize */
1260 	if (head < oldsize) {
1261 		i = oldsize - 1;
1262 		end = newsize;
1263 	} else {
1264 		/* Head did wrap; link newhead..newsize and 0..oldhead */
1265 		i = head;
1266 		end = newsize + (head - oldsize) + 1;
1267 	}
1268 
1269 	/*
1270 	 * Fix up hardware ring, being careful not to trample the active
1271 	 * section (tail -> head).
1272 	 */
1273 	for (; i < end; i++) {
1274 		KASSERT((i & (newsize - 1)) < tail ||
1275 		    (i & (newsize - 1)) >= head, ("trampling snake"));
1276 
1277 		next = newring[(i + 1) & (newsize - 1)];
1278 		hw = newring[i & (newsize - 1)]->u.dma;
1279 		hw->next = next->hw_desc_bus_addr;
1280 	}
1281 
1282 	free(ioat->ring, M_IOAT);
1283 	ioat->ring = newring;
1284 	ioat->ring_size_order = oldorder + 1;
1285 	ioat->tail = tail;
1286 	ioat->head = head;
1287 	error = 0;
1288 
1289 	mtx_unlock(&ioat->cleanup_lock);
1290 out:
1291 	if (error)
1292 		ioat_free_ring(ioat, (1 << (oldorder + 1)), newring);
1293 	return (error);
1294 }
1295 
1296 static int
1297 ring_shrink(struct ioat_softc *ioat, uint32_t oldorder,
1298     struct ioat_descriptor **newring)
1299 {
1300 	struct ioat_dma_hw_descriptor *hw;
1301 	struct ioat_descriptor *ent, *next;
1302 	uint32_t oldsize, newsize, current_idx, new_idx, i;
1303 	int error;
1304 
1305 	CTR0(KTR_IOAT, __func__);
1306 
1307 	mtx_assert(&ioat->submit_lock, MA_OWNED);
1308 
1309 	if (oldorder != ioat->ring_size_order || oldorder <= IOAT_MIN_ORDER) {
1310 		error = EINVAL;
1311 		goto out_unlocked;
1312 	}
1313 
1314 	oldsize = (1 << oldorder);
1315 	newsize = (1 << (oldorder - 1));
1316 
1317 	mtx_lock(&ioat->cleanup_lock);
1318 
1319 	/* Can't shrink below current active set! */
1320 	if (ioat_get_active(ioat) >= newsize) {
1321 		error = ENOMEM;
1322 		goto out;
1323 	}
1324 
1325 	/*
1326 	 * Copy current descriptors to the new ring, dropping the removed
1327 	 * descriptors.
1328 	 */
1329 	for (i = 0; i < newsize; i++) {
1330 		current_idx = (ioat->tail + i) & (oldsize - 1);
1331 		new_idx = (ioat->tail + i) & (newsize - 1);
1332 
1333 		newring[new_idx] = ioat->ring[current_idx];
1334 		newring[new_idx]->id = new_idx;
1335 	}
1336 
1337 	/* Free deleted descriptors */
1338 	for (i = newsize; i < oldsize; i++) {
1339 		ent = ioat_get_ring_entry(ioat, ioat->tail + i);
1340 		ioat_free_ring_entry(ioat, ent);
1341 	}
1342 
1343 	/* Fix up hardware ring. */
1344 	hw = newring[(ioat->tail + newsize - 1) & (newsize - 1)]->u.dma;
1345 	next = newring[(ioat->tail + newsize) & (newsize - 1)];
1346 	hw->next = next->hw_desc_bus_addr;
1347 
1348 	free(ioat->ring, M_IOAT);
1349 	ioat->ring = newring;
1350 	ioat->ring_size_order = oldorder - 1;
1351 	error = 0;
1352 
1353 out:
1354 	mtx_unlock(&ioat->cleanup_lock);
1355 out_unlocked:
1356 	if (error)
1357 		ioat_free_ring(ioat, (1 << (oldorder - 1)), newring);
1358 	return (error);
1359 }
1360 
1361 static void
1362 ioat_halted_debug(struct ioat_softc *ioat, uint32_t chanerr)
1363 {
1364 	struct ioat_descriptor *desc;
1365 
1366 	ioat_log_message(0, "Channel halted (%b)\n", (int)chanerr,
1367 	    IOAT_CHANERR_STR);
1368 	if (chanerr == 0)
1369 		return;
1370 
1371 	mtx_assert(&ioat->cleanup_lock, MA_OWNED);
1372 
1373 	desc = ioat_get_ring_entry(ioat, ioat->tail + 0);
1374 	dump_descriptor(desc->u.raw);
1375 
1376 	desc = ioat_get_ring_entry(ioat, ioat->tail + 1);
1377 	dump_descriptor(desc->u.raw);
1378 }
1379 
1380 static void
1381 ioat_timer_callback(void *arg)
1382 {
1383 	struct ioat_descriptor **newring;
1384 	struct ioat_softc *ioat;
1385 	uint32_t order;
1386 
1387 	ioat = arg;
1388 	ioat_log_message(1, "%s\n", __func__);
1389 
1390 	if (ioat->is_completion_pending) {
1391 		ioat_process_events(ioat);
1392 		return;
1393 	}
1394 
1395 	/* Slowly scale the ring down if idle. */
1396 	mtx_lock(&ioat->submit_lock);
1397 	order = ioat->ring_size_order;
1398 	if (ioat->is_resize_pending || order == IOAT_MIN_ORDER) {
1399 		mtx_unlock(&ioat->submit_lock);
1400 		goto out;
1401 	}
1402 	ioat->is_resize_pending = TRUE;
1403 	mtx_unlock(&ioat->submit_lock);
1404 
1405 	newring = ioat_prealloc_ring(ioat, 1 << (order - 1), FALSE,
1406 	    M_NOWAIT);
1407 
1408 	mtx_lock(&ioat->submit_lock);
1409 	KASSERT(ioat->ring_size_order == order,
1410 	    ("resize_pending protects order"));
1411 
1412 	if (newring != NULL)
1413 		ring_shrink(ioat, order, newring);
1414 
1415 	ioat->is_resize_pending = FALSE;
1416 	mtx_unlock(&ioat->submit_lock);
1417 
1418 out:
1419 	if (ioat->ring_size_order > IOAT_MIN_ORDER)
1420 		callout_reset(&ioat->timer, 10 * hz,
1421 		    ioat_timer_callback, ioat);
1422 }
1423 
1424 /*
1425  * Support Functions
1426  */
1427 static void
1428 ioat_submit_single(struct ioat_softc *ioat)
1429 {
1430 
1431 	ioat_get(ioat, IOAT_ACTIVE_DESCR_REF);
1432 	atomic_add_rel_int(&ioat->head, 1);
1433 	atomic_add_rel_int(&ioat->hw_head, 1);
1434 
1435 	if (!ioat->is_completion_pending) {
1436 		ioat->is_completion_pending = TRUE;
1437 		callout_reset(&ioat->timer, IOAT_INTR_TIMO,
1438 		    ioat_timer_callback, ioat);
1439 	}
1440 
1441 	ioat->stats.descriptors_submitted++;
1442 }
1443 
1444 static int
1445 ioat_reset_hw(struct ioat_softc *ioat)
1446 {
1447 	uint64_t status;
1448 	uint32_t chanerr;
1449 	unsigned timeout;
1450 	int error;
1451 
1452 	mtx_lock(IOAT_REFLK);
1453 	ioat->quiescing = TRUE;
1454 	ioat_drain_locked(ioat);
1455 	mtx_unlock(IOAT_REFLK);
1456 
1457 	status = ioat_get_chansts(ioat);
1458 	if (is_ioat_active(status) || is_ioat_idle(status))
1459 		ioat_suspend(ioat);
1460 
1461 	/* Wait at most 20 ms */
1462 	for (timeout = 0; (is_ioat_active(status) || is_ioat_idle(status)) &&
1463 	    timeout < 20; timeout++) {
1464 		DELAY(1000);
1465 		status = ioat_get_chansts(ioat);
1466 	}
1467 	if (timeout == 20) {
1468 		error = ETIMEDOUT;
1469 		goto out;
1470 	}
1471 
1472 	KASSERT(ioat_get_active(ioat) == 0, ("active after quiesce"));
1473 
1474 	chanerr = ioat_read_4(ioat, IOAT_CHANERR_OFFSET);
1475 	ioat_write_4(ioat, IOAT_CHANERR_OFFSET, chanerr);
1476 
1477 	/*
1478 	 * IOAT v3 workaround - CHANERRMSK_INT with 3E07h to masks out errors
1479 	 *  that can cause stability issues for IOAT v3.
1480 	 */
1481 	pci_write_config(ioat->device, IOAT_CFG_CHANERRMASK_INT_OFFSET, 0x3e07,
1482 	    4);
1483 	chanerr = pci_read_config(ioat->device, IOAT_CFG_CHANERR_INT_OFFSET, 4);
1484 	pci_write_config(ioat->device, IOAT_CFG_CHANERR_INT_OFFSET, chanerr, 4);
1485 
1486 	/*
1487 	 * BDXDE and BWD models reset MSI-X registers on device reset.
1488 	 * Save/restore their contents manually.
1489 	 */
1490 	if (ioat_model_resets_msix(ioat)) {
1491 		ioat_log_message(1, "device resets MSI-X registers; saving\n");
1492 		pci_save_state(ioat->device);
1493 	}
1494 
1495 	ioat_reset(ioat);
1496 
1497 	/* Wait at most 20 ms */
1498 	for (timeout = 0; ioat_reset_pending(ioat) && timeout < 20; timeout++)
1499 		DELAY(1000);
1500 	if (timeout == 20) {
1501 		error = ETIMEDOUT;
1502 		goto out;
1503 	}
1504 
1505 	if (ioat_model_resets_msix(ioat)) {
1506 		ioat_log_message(1, "device resets registers; restored\n");
1507 		pci_restore_state(ioat->device);
1508 	}
1509 
1510 	/* Reset attempts to return the hardware to "halted." */
1511 	status = ioat_get_chansts(ioat);
1512 	if (is_ioat_active(status) || is_ioat_idle(status)) {
1513 		/* So this really shouldn't happen... */
1514 		ioat_log_message(0, "Device is active after a reset?\n");
1515 		ioat_write_chanctrl(ioat, IOAT_CHANCTRL_RUN);
1516 		error = 0;
1517 		goto out;
1518 	}
1519 
1520 	chanerr = ioat_read_4(ioat, IOAT_CHANERR_OFFSET);
1521 	if (chanerr != 0) {
1522 		mtx_lock(&ioat->cleanup_lock);
1523 		ioat_halted_debug(ioat, chanerr);
1524 		mtx_unlock(&ioat->cleanup_lock);
1525 		error = EIO;
1526 		goto out;
1527 	}
1528 
1529 	/*
1530 	 * Bring device back online after reset.  Writing CHAINADDR brings the
1531 	 * device back to active.
1532 	 *
1533 	 * The internal ring counter resets to zero, so we have to start over
1534 	 * at zero as well.
1535 	 */
1536 	ioat->tail = ioat->head = ioat->hw_head = 0;
1537 	ioat->last_seen = 0;
1538 
1539 	ioat_write_chanctrl(ioat, IOAT_CHANCTRL_RUN);
1540 	ioat_write_chancmp(ioat, ioat->comp_update_bus_addr);
1541 	ioat_write_chainaddr(ioat, ioat->ring[0]->hw_desc_bus_addr);
1542 	error = 0;
1543 
1544 out:
1545 	mtx_lock(IOAT_REFLK);
1546 	ioat->quiescing = FALSE;
1547 	mtx_unlock(IOAT_REFLK);
1548 
1549 	if (error == 0)
1550 		error = ioat_start_channel(ioat);
1551 
1552 	return (error);
1553 }
1554 
1555 static int
1556 sysctl_handle_chansts(SYSCTL_HANDLER_ARGS)
1557 {
1558 	struct ioat_softc *ioat;
1559 	struct sbuf sb;
1560 	uint64_t status;
1561 	int error;
1562 
1563 	ioat = arg1;
1564 
1565 	status = ioat_get_chansts(ioat) & IOAT_CHANSTS_STATUS;
1566 
1567 	sbuf_new_for_sysctl(&sb, NULL, 256, req);
1568 	switch (status) {
1569 	case IOAT_CHANSTS_ACTIVE:
1570 		sbuf_printf(&sb, "ACTIVE");
1571 		break;
1572 	case IOAT_CHANSTS_IDLE:
1573 		sbuf_printf(&sb, "IDLE");
1574 		break;
1575 	case IOAT_CHANSTS_SUSPENDED:
1576 		sbuf_printf(&sb, "SUSPENDED");
1577 		break;
1578 	case IOAT_CHANSTS_HALTED:
1579 		sbuf_printf(&sb, "HALTED");
1580 		break;
1581 	case IOAT_CHANSTS_ARMED:
1582 		sbuf_printf(&sb, "ARMED");
1583 		break;
1584 	default:
1585 		sbuf_printf(&sb, "UNKNOWN");
1586 		break;
1587 	}
1588 	error = sbuf_finish(&sb);
1589 	sbuf_delete(&sb);
1590 
1591 	if (error != 0 || req->newptr == NULL)
1592 		return (error);
1593 	return (EINVAL);
1594 }
1595 
1596 static int
1597 sysctl_handle_dpi(SYSCTL_HANDLER_ARGS)
1598 {
1599 	struct ioat_softc *ioat;
1600 	struct sbuf sb;
1601 #define	PRECISION	"1"
1602 	const uintmax_t factor = 10;
1603 	uintmax_t rate;
1604 	int error;
1605 
1606 	ioat = arg1;
1607 	sbuf_new_for_sysctl(&sb, NULL, 16, req);
1608 
1609 	if (ioat->stats.interrupts == 0) {
1610 		sbuf_printf(&sb, "NaN");
1611 		goto out;
1612 	}
1613 	rate = ioat->stats.descriptors_processed * factor /
1614 	    ioat->stats.interrupts;
1615 	sbuf_printf(&sb, "%ju.%." PRECISION "ju", rate / factor,
1616 	    rate % factor);
1617 #undef	PRECISION
1618 out:
1619 	error = sbuf_finish(&sb);
1620 	sbuf_delete(&sb);
1621 	if (error != 0 || req->newptr == NULL)
1622 		return (error);
1623 	return (EINVAL);
1624 }
1625 
1626 static int
1627 sysctl_handle_error(SYSCTL_HANDLER_ARGS)
1628 {
1629 	struct ioat_descriptor *desc;
1630 	struct ioat_softc *ioat;
1631 	int error, arg;
1632 
1633 	ioat = arg1;
1634 
1635 	arg = 0;
1636 	error = SYSCTL_OUT(req, &arg, sizeof(arg));
1637 	if (error != 0 || req->newptr == NULL)
1638 		return (error);
1639 
1640 	error = SYSCTL_IN(req, &arg, sizeof(arg));
1641 	if (error != 0)
1642 		return (error);
1643 
1644 	if (arg != 0) {
1645 		ioat_acquire(&ioat->dmaengine);
1646 		desc = ioat_op_generic(ioat, IOAT_OP_COPY, 1,
1647 		    0xffff000000000000ull, 0xffff000000000000ull, NULL, NULL,
1648 		    0);
1649 		if (desc == NULL)
1650 			error = ENOMEM;
1651 		else
1652 			ioat_submit_single(ioat);
1653 		ioat_release(&ioat->dmaengine);
1654 	}
1655 	return (error);
1656 }
1657 
1658 static int
1659 sysctl_handle_reset(SYSCTL_HANDLER_ARGS)
1660 {
1661 	struct ioat_softc *ioat;
1662 	int error, arg;
1663 
1664 	ioat = arg1;
1665 
1666 	arg = 0;
1667 	error = SYSCTL_OUT(req, &arg, sizeof(arg));
1668 	if (error != 0 || req->newptr == NULL)
1669 		return (error);
1670 
1671 	error = SYSCTL_IN(req, &arg, sizeof(arg));
1672 	if (error != 0)
1673 		return (error);
1674 
1675 	if (arg != 0)
1676 		error = ioat_reset_hw(ioat);
1677 
1678 	return (error);
1679 }
1680 
1681 static void
1682 dump_descriptor(void *hw_desc)
1683 {
1684 	int i, j;
1685 
1686 	for (i = 0; i < 2; i++) {
1687 		for (j = 0; j < 8; j++)
1688 			printf("%08x ", ((uint32_t *)hw_desc)[i * 8 + j]);
1689 		printf("\n");
1690 	}
1691 }
1692 
1693 static void
1694 ioat_setup_sysctl(device_t device)
1695 {
1696 	struct sysctl_oid_list *par, *statpar, *state, *hammer;
1697 	struct sysctl_ctx_list *ctx;
1698 	struct sysctl_oid *tree, *tmp;
1699 	struct ioat_softc *ioat;
1700 
1701 	ioat = DEVICE2SOFTC(device);
1702 	ctx = device_get_sysctl_ctx(device);
1703 	tree = device_get_sysctl_tree(device);
1704 	par = SYSCTL_CHILDREN(tree);
1705 
1706 	SYSCTL_ADD_INT(ctx, par, OID_AUTO, "version", CTLFLAG_RD,
1707 	    &ioat->version, 0, "HW version (0xMM form)");
1708 	SYSCTL_ADD_UINT(ctx, par, OID_AUTO, "max_xfer_size", CTLFLAG_RD,
1709 	    &ioat->max_xfer_size, 0, "HW maximum transfer size");
1710 	SYSCTL_ADD_INT(ctx, par, OID_AUTO, "intrdelay_supported", CTLFLAG_RD,
1711 	    &ioat->intrdelay_supported, 0, "Is INTRDELAY supported");
1712 	SYSCTL_ADD_U16(ctx, par, OID_AUTO, "intrdelay_max", CTLFLAG_RD,
1713 	    &ioat->intrdelay_max, 0,
1714 	    "Maximum configurable INTRDELAY on this channel (microseconds)");
1715 
1716 	tmp = SYSCTL_ADD_NODE(ctx, par, OID_AUTO, "state", CTLFLAG_RD, NULL,
1717 	    "IOAT channel internal state");
1718 	state = SYSCTL_CHILDREN(tmp);
1719 
1720 	SYSCTL_ADD_UINT(ctx, state, OID_AUTO, "ring_size_order", CTLFLAG_RD,
1721 	    &ioat->ring_size_order, 0, "SW descriptor ring size order");
1722 	SYSCTL_ADD_UINT(ctx, state, OID_AUTO, "head", CTLFLAG_RD, &ioat->head,
1723 	    0, "SW descriptor head pointer index");
1724 	SYSCTL_ADD_UINT(ctx, state, OID_AUTO, "tail", CTLFLAG_RD, &ioat->tail,
1725 	    0, "SW descriptor tail pointer index");
1726 	SYSCTL_ADD_UINT(ctx, state, OID_AUTO, "hw_head", CTLFLAG_RD,
1727 	    &ioat->hw_head, 0, "HW DMACOUNT");
1728 
1729 	SYSCTL_ADD_UQUAD(ctx, state, OID_AUTO, "last_completion", CTLFLAG_RD,
1730 	    ioat->comp_update, "HW addr of last completion");
1731 
1732 	SYSCTL_ADD_INT(ctx, state, OID_AUTO, "is_resize_pending", CTLFLAG_RD,
1733 	    &ioat->is_resize_pending, 0, "resize pending");
1734 	SYSCTL_ADD_INT(ctx, state, OID_AUTO, "is_completion_pending",
1735 	    CTLFLAG_RD, &ioat->is_completion_pending, 0, "completion pending");
1736 	SYSCTL_ADD_INT(ctx, state, OID_AUTO, "is_reset_pending", CTLFLAG_RD,
1737 	    &ioat->is_reset_pending, 0, "reset pending");
1738 	SYSCTL_ADD_INT(ctx, state, OID_AUTO, "is_channel_running", CTLFLAG_RD,
1739 	    &ioat->is_channel_running, 0, "channel running");
1740 
1741 	SYSCTL_ADD_PROC(ctx, state, OID_AUTO, "chansts",
1742 	    CTLTYPE_STRING | CTLFLAG_RD, ioat, 0, sysctl_handle_chansts, "A",
1743 	    "String of the channel status");
1744 
1745 	SYSCTL_ADD_U16(ctx, state, OID_AUTO, "intrdelay", CTLFLAG_RD,
1746 	    &ioat->cached_intrdelay, 0,
1747 	    "Current INTRDELAY on this channel (cached, microseconds)");
1748 
1749 	tmp = SYSCTL_ADD_NODE(ctx, par, OID_AUTO, "hammer", CTLFLAG_RD, NULL,
1750 	    "Big hammers (mostly for testing)");
1751 	hammer = SYSCTL_CHILDREN(tmp);
1752 
1753 	SYSCTL_ADD_PROC(ctx, hammer, OID_AUTO, "force_hw_reset",
1754 	    CTLTYPE_INT | CTLFLAG_RW, ioat, 0, sysctl_handle_reset, "I",
1755 	    "Set to non-zero to reset the hardware");
1756 	SYSCTL_ADD_PROC(ctx, hammer, OID_AUTO, "force_hw_error",
1757 	    CTLTYPE_INT | CTLFLAG_RW, ioat, 0, sysctl_handle_error, "I",
1758 	    "Set to non-zero to inject a recoverable hardware error");
1759 
1760 	tmp = SYSCTL_ADD_NODE(ctx, par, OID_AUTO, "stats", CTLFLAG_RD, NULL,
1761 	    "IOAT channel statistics");
1762 	statpar = SYSCTL_CHILDREN(tmp);
1763 
1764 	SYSCTL_ADD_UQUAD(ctx, statpar, OID_AUTO, "interrupts", CTLFLAG_RW,
1765 	    &ioat->stats.interrupts,
1766 	    "Number of interrupts processed on this channel");
1767 	SYSCTL_ADD_UQUAD(ctx, statpar, OID_AUTO, "descriptors", CTLFLAG_RW,
1768 	    &ioat->stats.descriptors_processed,
1769 	    "Number of descriptors processed on this channel");
1770 	SYSCTL_ADD_UQUAD(ctx, statpar, OID_AUTO, "submitted", CTLFLAG_RW,
1771 	    &ioat->stats.descriptors_submitted,
1772 	    "Number of descriptors submitted to this channel");
1773 	SYSCTL_ADD_UQUAD(ctx, statpar, OID_AUTO, "errored", CTLFLAG_RW,
1774 	    &ioat->stats.descriptors_error,
1775 	    "Number of descriptors failed by channel errors");
1776 	SYSCTL_ADD_U32(ctx, statpar, OID_AUTO, "halts", CTLFLAG_RW,
1777 	    &ioat->stats.channel_halts, 0,
1778 	    "Number of times the channel has halted");
1779 	SYSCTL_ADD_U32(ctx, statpar, OID_AUTO, "last_halt_chanerr", CTLFLAG_RW,
1780 	    &ioat->stats.last_halt_chanerr, 0,
1781 	    "The raw CHANERR when the channel was last halted");
1782 
1783 	SYSCTL_ADD_PROC(ctx, statpar, OID_AUTO, "desc_per_interrupt",
1784 	    CTLTYPE_STRING | CTLFLAG_RD, ioat, 0, sysctl_handle_dpi, "A",
1785 	    "Descriptors per interrupt");
1786 }
1787 
1788 static inline struct ioat_softc *
1789 ioat_get(struct ioat_softc *ioat, enum ioat_ref_kind kind)
1790 {
1791 	uint32_t old;
1792 
1793 	KASSERT(kind < IOAT_NUM_REF_KINDS, ("bogus"));
1794 
1795 	old = atomic_fetchadd_32(&ioat->refcnt, 1);
1796 	KASSERT(old < UINT32_MAX, ("refcnt overflow"));
1797 
1798 #ifdef INVARIANTS
1799 	old = atomic_fetchadd_32(&ioat->refkinds[kind], 1);
1800 	KASSERT(old < UINT32_MAX, ("refcnt kind overflow"));
1801 #endif
1802 
1803 	return (ioat);
1804 }
1805 
1806 static inline void
1807 ioat_putn(struct ioat_softc *ioat, uint32_t n, enum ioat_ref_kind kind)
1808 {
1809 
1810 	_ioat_putn(ioat, n, kind, FALSE);
1811 }
1812 
1813 static inline void
1814 ioat_putn_locked(struct ioat_softc *ioat, uint32_t n, enum ioat_ref_kind kind)
1815 {
1816 
1817 	_ioat_putn(ioat, n, kind, TRUE);
1818 }
1819 
1820 static inline void
1821 _ioat_putn(struct ioat_softc *ioat, uint32_t n, enum ioat_ref_kind kind,
1822     boolean_t locked)
1823 {
1824 	uint32_t old;
1825 
1826 	KASSERT(kind < IOAT_NUM_REF_KINDS, ("bogus"));
1827 
1828 	if (n == 0)
1829 		return;
1830 
1831 #ifdef INVARIANTS
1832 	old = atomic_fetchadd_32(&ioat->refkinds[kind], -n);
1833 	KASSERT(old >= n, ("refcnt kind underflow"));
1834 #endif
1835 
1836 	/* Skip acquiring the lock if resulting refcnt > 0. */
1837 	for (;;) {
1838 		old = ioat->refcnt;
1839 		if (old <= n)
1840 			break;
1841 		if (atomic_cmpset_32(&ioat->refcnt, old, old - n))
1842 			return;
1843 	}
1844 
1845 	if (locked)
1846 		mtx_assert(IOAT_REFLK, MA_OWNED);
1847 	else
1848 		mtx_lock(IOAT_REFLK);
1849 
1850 	old = atomic_fetchadd_32(&ioat->refcnt, -n);
1851 	KASSERT(old >= n, ("refcnt error"));
1852 
1853 	if (old == n)
1854 		wakeup(IOAT_REFLK);
1855 	if (!locked)
1856 		mtx_unlock(IOAT_REFLK);
1857 }
1858 
1859 static inline void
1860 ioat_put(struct ioat_softc *ioat, enum ioat_ref_kind kind)
1861 {
1862 
1863 	ioat_putn(ioat, 1, kind);
1864 }
1865 
1866 static void
1867 ioat_drain_locked(struct ioat_softc *ioat)
1868 {
1869 
1870 	mtx_assert(IOAT_REFLK, MA_OWNED);
1871 	while (ioat->refcnt > 0)
1872 		msleep(IOAT_REFLK, IOAT_REFLK, 0, "ioat_drain", 0);
1873 }
1874