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