xref: /freebsd/sys/dev/sound/pci/hda/hdac.c (revision a3557ef0)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause-FreeBSD
3  *
4  * Copyright (c) 2006 Stephane E. Potvin <sepotvin@videotron.ca>
5  * Copyright (c) 2006 Ariff Abdullah <ariff@FreeBSD.org>
6  * Copyright (c) 2008-2012 Alexander Motin <mav@FreeBSD.org>
7  * All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  * 1. Redistributions of source code must retain the above copyright
13  *    notice, this list of conditions and the following disclaimer.
14  * 2. Redistributions in binary form must reproduce the above copyright
15  *    notice, this list of conditions and the following disclaimer in the
16  *    documentation and/or other materials provided with the distribution.
17  *
18  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
19  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
22  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
23  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
24  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
26  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
27  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
28  * SUCH DAMAGE.
29  */
30 
31 /*
32  * Intel High Definition Audio (Controller) driver for FreeBSD.
33  */
34 
35 #ifdef HAVE_KERNEL_OPTION_HEADERS
36 #include "opt_snd.h"
37 #endif
38 
39 #include <dev/sound/pcm/sound.h>
40 #include <dev/pci/pcireg.h>
41 #include <dev/pci/pcivar.h>
42 
43 #include <sys/ctype.h>
44 #include <sys/endian.h>
45 #include <sys/taskqueue.h>
46 
47 #include <dev/sound/pci/hda/hdac_private.h>
48 #include <dev/sound/pci/hda/hdac_reg.h>
49 #include <dev/sound/pci/hda/hda_reg.h>
50 #include <dev/sound/pci/hda/hdac.h>
51 
52 #define HDA_DRV_TEST_REV	"20120126_0002"
53 
54 SND_DECLARE_FILE("$FreeBSD$");
55 
56 #define hdac_lock(sc)		snd_mtxlock((sc)->lock)
57 #define hdac_unlock(sc)		snd_mtxunlock((sc)->lock)
58 #define hdac_lockassert(sc)	snd_mtxassert((sc)->lock)
59 
60 #define HDAC_QUIRK_64BIT	(1 << 0)
61 #define HDAC_QUIRK_DMAPOS	(1 << 1)
62 #define HDAC_QUIRK_MSI		(1 << 2)
63 
64 static const struct {
65 	const char *key;
66 	uint32_t value;
67 } hdac_quirks_tab[] = {
68 	{ "64bit", HDAC_QUIRK_64BIT },
69 	{ "dmapos", HDAC_QUIRK_DMAPOS },
70 	{ "msi", HDAC_QUIRK_MSI },
71 };
72 
73 MALLOC_DEFINE(M_HDAC, "hdac", "HDA Controller");
74 
75 static const struct {
76 	uint32_t	model;
77 	const char	*desc;
78 	char		quirks_on;
79 	char		quirks_off;
80 } hdac_devices[] = {
81 	{ HDA_INTEL_OAK,     "Intel Oaktrail",	0, 0 },
82 	{ HDA_INTEL_CMLKLP,  "Intel Comet Lake-LP",	0, 0 },
83 	{ HDA_INTEL_CMLKH,   "Intel Comet Lake-H",	0, 0 },
84 	{ HDA_INTEL_BAY,     "Intel BayTrail",	0, 0 },
85 	{ HDA_INTEL_HSW1,    "Intel Haswell",	0, 0 },
86 	{ HDA_INTEL_HSW2,    "Intel Haswell",	0, 0 },
87 	{ HDA_INTEL_HSW3,    "Intel Haswell",	0, 0 },
88 	{ HDA_INTEL_BDW1,    "Intel Broadwell",	0, 0 },
89 	{ HDA_INTEL_BDW2,    "Intel Broadwell",	0, 0 },
90 	{ HDA_INTEL_BXTNT,   "Intel Broxton-T",	0, 0 },
91 	{ HDA_INTEL_CPT,     "Intel Cougar Point",	0, 0 },
92 	{ HDA_INTEL_PATSBURG,"Intel Patsburg",  0, 0 },
93 	{ HDA_INTEL_PPT1,    "Intel Panther Point",	0, 0 },
94 	{ HDA_INTEL_BR,      "Intel Braswell",	0, 0 },
95 	{ HDA_INTEL_LPT1,    "Intel Lynx Point",	0, 0 },
96 	{ HDA_INTEL_LPT2,    "Intel Lynx Point",	0, 0 },
97 	{ HDA_INTEL_WCPT,    "Intel Wildcat Point",	0, 0 },
98 	{ HDA_INTEL_WELLS1,  "Intel Wellsburg",	0, 0 },
99 	{ HDA_INTEL_WELLS2,  "Intel Wellsburg",	0, 0 },
100 	{ HDA_INTEL_LPTLP1,  "Intel Lynx Point-LP",	0, 0 },
101 	{ HDA_INTEL_LPTLP2,  "Intel Lynx Point-LP",	0, 0 },
102 	{ HDA_INTEL_SRPTLP,  "Intel Sunrise Point-LP",	0, 0 },
103 	{ HDA_INTEL_KBLKLP,  "Intel Kaby Lake-LP",	0, 0 },
104 	{ HDA_INTEL_SRPT,    "Intel Sunrise Point",	0, 0 },
105 	{ HDA_INTEL_KBLK,    "Intel Kaby Lake",	0, 0 },
106 	{ HDA_INTEL_KBLKH,   "Intel Kaby Lake-H",	0, 0 },
107 	{ HDA_INTEL_CFLK,    "Intel Coffee Lake",	0, 0 },
108 	{ HDA_INTEL_CMLKS,   "Intel Comet Lake-S",	0, 0 },
109 	{ HDA_INTEL_CNLK,    "Intel Cannon Lake",	0, 0 },
110 	{ HDA_INTEL_ICLK,    "Intel Ice Lake",		0, 0 },
111 	{ HDA_INTEL_CMLKLP,  "Intel Comet Lake-LP",	0, 0 },
112 	{ HDA_INTEL_CMLKH,   "Intel Comet Lake-H",	0, 0 },
113 	{ HDA_INTEL_TGLK,    "Intel Tiger Lake",	0, 0 },
114 	{ HDA_INTEL_GMLK,    "Intel Gemini Lake",	0, 0 },
115 	{ HDA_INTEL_82801F,  "Intel 82801F",	0, 0 },
116 	{ HDA_INTEL_63XXESB, "Intel 631x/632xESB",	0, 0 },
117 	{ HDA_INTEL_82801G,  "Intel 82801G",	0, 0 },
118 	{ HDA_INTEL_82801H,  "Intel 82801H",	0, 0 },
119 	{ HDA_INTEL_82801I,  "Intel 82801I",	0, 0 },
120 	{ HDA_INTEL_JLK,     "Intel Jasper Lake",	0, 0 },
121 	{ HDA_INTEL_82801JI, "Intel 82801JI",	0, 0 },
122 	{ HDA_INTEL_82801JD, "Intel 82801JD",	0, 0 },
123 	{ HDA_INTEL_PCH,     "Intel Ibex Peak",	0, 0 },
124 	{ HDA_INTEL_PCH2,    "Intel Ibex Peak",	0, 0 },
125 	{ HDA_INTEL_ELLK,    "Intel Elkhart Lake",	0, 0 },
126 	{ HDA_INTEL_JLK2,    "Intel Jasper Lake",	0, 0 },
127 	{ HDA_INTEL_BXTNP,   "Intel Broxton-P",	0, 0 },
128 	{ HDA_INTEL_SCH,     "Intel SCH",	0, 0 },
129 	{ HDA_NVIDIA_MCP51,  "NVIDIA MCP51",	0, HDAC_QUIRK_MSI },
130 	{ HDA_NVIDIA_MCP55,  "NVIDIA MCP55",	0, HDAC_QUIRK_MSI },
131 	{ HDA_NVIDIA_MCP61_1, "NVIDIA MCP61",	0, 0 },
132 	{ HDA_NVIDIA_MCP61_2, "NVIDIA MCP61",	0, 0 },
133 	{ HDA_NVIDIA_MCP65_1, "NVIDIA MCP65",	0, 0 },
134 	{ HDA_NVIDIA_MCP65_2, "NVIDIA MCP65",	0, 0 },
135 	{ HDA_NVIDIA_MCP67_1, "NVIDIA MCP67",	0, 0 },
136 	{ HDA_NVIDIA_MCP67_2, "NVIDIA MCP67",	0, 0 },
137 	{ HDA_NVIDIA_MCP73_1, "NVIDIA MCP73",	0, 0 },
138 	{ HDA_NVIDIA_MCP73_2, "NVIDIA MCP73",	0, 0 },
139 	{ HDA_NVIDIA_MCP78_1, "NVIDIA MCP78",	0, HDAC_QUIRK_64BIT },
140 	{ HDA_NVIDIA_MCP78_2, "NVIDIA MCP78",	0, HDAC_QUIRK_64BIT },
141 	{ HDA_NVIDIA_MCP78_3, "NVIDIA MCP78",	0, HDAC_QUIRK_64BIT },
142 	{ HDA_NVIDIA_MCP78_4, "NVIDIA MCP78",	0, HDAC_QUIRK_64BIT },
143 	{ HDA_NVIDIA_MCP79_1, "NVIDIA MCP79",	0, 0 },
144 	{ HDA_NVIDIA_MCP79_2, "NVIDIA MCP79",	0, 0 },
145 	{ HDA_NVIDIA_MCP79_3, "NVIDIA MCP79",	0, 0 },
146 	{ HDA_NVIDIA_MCP79_4, "NVIDIA MCP79",	0, 0 },
147 	{ HDA_NVIDIA_MCP89_1, "NVIDIA MCP89",	0, 0 },
148 	{ HDA_NVIDIA_MCP89_2, "NVIDIA MCP89",	0, 0 },
149 	{ HDA_NVIDIA_MCP89_3, "NVIDIA MCP89",	0, 0 },
150 	{ HDA_NVIDIA_MCP89_4, "NVIDIA MCP89",	0, 0 },
151 	{ HDA_NVIDIA_0BE2,   "NVIDIA (0x0be2)",	0, HDAC_QUIRK_MSI },
152 	{ HDA_NVIDIA_0BE3,   "NVIDIA (0x0be3)",	0, HDAC_QUIRK_MSI },
153 	{ HDA_NVIDIA_0BE4,   "NVIDIA (0x0be4)",	0, HDAC_QUIRK_MSI },
154 	{ HDA_NVIDIA_GT100,  "NVIDIA GT100",	0, HDAC_QUIRK_MSI },
155 	{ HDA_NVIDIA_GT104,  "NVIDIA GT104",	0, HDAC_QUIRK_MSI },
156 	{ HDA_NVIDIA_GT106,  "NVIDIA GT106",	0, HDAC_QUIRK_MSI },
157 	{ HDA_NVIDIA_GT108,  "NVIDIA GT108",	0, HDAC_QUIRK_MSI },
158 	{ HDA_NVIDIA_GT116,  "NVIDIA GT116",	0, HDAC_QUIRK_MSI },
159 	{ HDA_NVIDIA_GF119,  "NVIDIA GF119",	0, 0 },
160 	{ HDA_NVIDIA_GF110_1, "NVIDIA GF110",	0, HDAC_QUIRK_MSI },
161 	{ HDA_NVIDIA_GF110_2, "NVIDIA GF110",	0, HDAC_QUIRK_MSI },
162 	{ HDA_ATI_SB450,     "ATI SB450",	0, 0 },
163 	{ HDA_ATI_SB600,     "ATI SB600",	0, 0 },
164 	{ HDA_ATI_RS600,     "ATI RS600",	0, 0 },
165 	{ HDA_ATI_RS690,     "ATI RS690",	0, 0 },
166 	{ HDA_ATI_RS780,     "ATI RS780",	0, 0 },
167 	{ HDA_ATI_R600,      "ATI R600",	0, 0 },
168 	{ HDA_ATI_RV610,     "ATI RV610",	0, 0 },
169 	{ HDA_ATI_RV620,     "ATI RV620",	0, 0 },
170 	{ HDA_ATI_RV630,     "ATI RV630",	0, 0 },
171 	{ HDA_ATI_RV635,     "ATI RV635",	0, 0 },
172 	{ HDA_ATI_RV710,     "ATI RV710",	0, 0 },
173 	{ HDA_ATI_RV730,     "ATI RV730",	0, 0 },
174 	{ HDA_ATI_RV740,     "ATI RV740",	0, 0 },
175 	{ HDA_ATI_RV770,     "ATI RV770",	0, 0 },
176 	{ HDA_ATI_RV810,     "ATI RV810",	0, 0 },
177 	{ HDA_ATI_RV830,     "ATI RV830",	0, 0 },
178 	{ HDA_ATI_RV840,     "ATI RV840",	0, 0 },
179 	{ HDA_ATI_RV870,     "ATI RV870",	0, 0 },
180 	{ HDA_ATI_RV910,     "ATI RV910",	0, 0 },
181 	{ HDA_ATI_RV930,     "ATI RV930",	0, 0 },
182 	{ HDA_ATI_RV940,     "ATI RV940",	0, 0 },
183 	{ HDA_ATI_RV970,     "ATI RV970",	0, 0 },
184 	{ HDA_ATI_R1000,     "ATI R1000",	0, 0 },
185 	{ HDA_AMD_X370,      "AMD X370",	0, 0 },
186 	{ HDA_AMD_X570,      "AMD X570",	0, 0 },
187 	{ HDA_AMD_STONEY,    "AMD Stoney",	0, 0 },
188 	{ HDA_AMD_RAVEN,     "AMD Raven",	0, 0 },
189 	{ HDA_AMD_HUDSON2,   "AMD Hudson-2",	0, 0 },
190 	{ HDA_RDC_M3010,     "RDC M3010",	0, 0 },
191 	{ HDA_VIA_VT82XX,    "VIA VT8251/8237A",0, 0 },
192 	{ HDA_SIS_966,       "SiS 966/968",	0, 0 },
193 	{ HDA_ULI_M5461,     "ULI M5461",	0, 0 },
194 	/* Unknown */
195 	{ HDA_INTEL_ALL,  "Intel",		0, 0 },
196 	{ HDA_NVIDIA_ALL, "NVIDIA",		0, 0 },
197 	{ HDA_ATI_ALL,    "ATI",		0, 0 },
198 	{ HDA_AMD_ALL,    "AMD",		0, 0 },
199 	{ HDA_CREATIVE_ALL,    "Creative",	0, 0 },
200 	{ HDA_VIA_ALL,    "VIA",		0, 0 },
201 	{ HDA_SIS_ALL,    "SiS",		0, 0 },
202 	{ HDA_ULI_ALL,    "ULI",		0, 0 },
203 };
204 
205 static const struct {
206 	uint16_t vendor;
207 	uint8_t reg;
208 	uint8_t mask;
209 	uint8_t enable;
210 } hdac_pcie_snoop[] = {
211 	{  INTEL_VENDORID, 0x00, 0x00, 0x00 },
212 	{    ATI_VENDORID, 0x42, 0xf8, 0x02 },
213 	{    AMD_VENDORID, 0x42, 0xf8, 0x02 },
214 	{ NVIDIA_VENDORID, 0x4e, 0xf0, 0x0f },
215 };
216 
217 /****************************************************************************
218  * Function prototypes
219  ****************************************************************************/
220 static void	hdac_intr_handler(void *);
221 static int	hdac_reset(struct hdac_softc *, bool);
222 static int	hdac_get_capabilities(struct hdac_softc *);
223 static void	hdac_dma_cb(void *, bus_dma_segment_t *, int, int);
224 static int	hdac_dma_alloc(struct hdac_softc *,
225 					struct hdac_dma *, bus_size_t);
226 static void	hdac_dma_free(struct hdac_softc *, struct hdac_dma *);
227 static int	hdac_mem_alloc(struct hdac_softc *);
228 static void	hdac_mem_free(struct hdac_softc *);
229 static int	hdac_irq_alloc(struct hdac_softc *);
230 static void	hdac_irq_free(struct hdac_softc *);
231 static void	hdac_corb_init(struct hdac_softc *);
232 static void	hdac_rirb_init(struct hdac_softc *);
233 static void	hdac_corb_start(struct hdac_softc *);
234 static void	hdac_rirb_start(struct hdac_softc *);
235 
236 static void	hdac_attach2(void *);
237 
238 static uint32_t	hdac_send_command(struct hdac_softc *, nid_t, uint32_t);
239 
240 static int	hdac_probe(device_t);
241 static int	hdac_attach(device_t);
242 static int	hdac_detach(device_t);
243 static int	hdac_suspend(device_t);
244 static int	hdac_resume(device_t);
245 
246 static int	hdac_rirb_flush(struct hdac_softc *sc);
247 static int	hdac_unsolq_flush(struct hdac_softc *sc);
248 
249 /* This function surely going to make its way into upper level someday. */
250 static void
251 hdac_config_fetch(struct hdac_softc *sc, uint32_t *on, uint32_t *off)
252 {
253 	const char *res = NULL;
254 	int i = 0, j, k, len, inv;
255 
256 	if (resource_string_value(device_get_name(sc->dev),
257 	    device_get_unit(sc->dev), "config", &res) != 0)
258 		return;
259 	if (!(res != NULL && strlen(res) > 0))
260 		return;
261 	HDA_BOOTVERBOSE(
262 		device_printf(sc->dev, "Config options:");
263 	);
264 	for (;;) {
265 		while (res[i] != '\0' &&
266 		    (res[i] == ',' || isspace(res[i]) != 0))
267 			i++;
268 		if (res[i] == '\0') {
269 			HDA_BOOTVERBOSE(
270 				printf("\n");
271 			);
272 			return;
273 		}
274 		j = i;
275 		while (res[j] != '\0' &&
276 		    !(res[j] == ',' || isspace(res[j]) != 0))
277 			j++;
278 		len = j - i;
279 		if (len > 2 && strncmp(res + i, "no", 2) == 0)
280 			inv = 2;
281 		else
282 			inv = 0;
283 		for (k = 0; len > inv && k < nitems(hdac_quirks_tab); k++) {
284 			if (strncmp(res + i + inv,
285 			    hdac_quirks_tab[k].key, len - inv) != 0)
286 				continue;
287 			if (len - inv != strlen(hdac_quirks_tab[k].key))
288 				continue;
289 			HDA_BOOTVERBOSE(
290 				printf(" %s%s", (inv != 0) ? "no" : "",
291 				    hdac_quirks_tab[k].key);
292 			);
293 			if (inv == 0) {
294 				*on |= hdac_quirks_tab[k].value;
295 				*off &= ~hdac_quirks_tab[k].value;
296 			} else if (inv != 0) {
297 				*off |= hdac_quirks_tab[k].value;
298 				*on &= ~hdac_quirks_tab[k].value;
299 			}
300 			break;
301 		}
302 		i = j;
303 	}
304 }
305 
306 /****************************************************************************
307  * void hdac_intr_handler(void *)
308  *
309  * Interrupt handler. Processes interrupts received from the hdac.
310  ****************************************************************************/
311 static void
312 hdac_intr_handler(void *context)
313 {
314 	struct hdac_softc *sc;
315 	device_t dev;
316 	uint32_t intsts;
317 	uint8_t rirbsts;
318 	int i;
319 
320 	sc = (struct hdac_softc *)context;
321 	hdac_lock(sc);
322 
323 	/* Do we have anything to do? */
324 	intsts = HDAC_READ_4(&sc->mem, HDAC_INTSTS);
325 	if ((intsts & HDAC_INTSTS_GIS) == 0) {
326 		hdac_unlock(sc);
327 		return;
328 	}
329 
330 	/* Was this a controller interrupt? */
331 	if (intsts & HDAC_INTSTS_CIS) {
332 		rirbsts = HDAC_READ_1(&sc->mem, HDAC_RIRBSTS);
333 		/* Get as many responses that we can */
334 		while (rirbsts & HDAC_RIRBSTS_RINTFL) {
335 			HDAC_WRITE_1(&sc->mem,
336 			    HDAC_RIRBSTS, HDAC_RIRBSTS_RINTFL);
337 			hdac_rirb_flush(sc);
338 			rirbsts = HDAC_READ_1(&sc->mem, HDAC_RIRBSTS);
339 		}
340 		if (sc->unsolq_rp != sc->unsolq_wp)
341 			taskqueue_enqueue(taskqueue_thread, &sc->unsolq_task);
342 	}
343 
344 	if (intsts & HDAC_INTSTS_SIS_MASK) {
345 		for (i = 0; i < sc->num_ss; i++) {
346 			if ((intsts & (1 << i)) == 0)
347 				continue;
348 			HDAC_WRITE_1(&sc->mem, (i << 5) + HDAC_SDSTS,
349 			    HDAC_SDSTS_DESE | HDAC_SDSTS_FIFOE | HDAC_SDSTS_BCIS );
350 			if ((dev = sc->streams[i].dev) != NULL) {
351 				HDAC_STREAM_INTR(dev,
352 				    sc->streams[i].dir, sc->streams[i].stream);
353 			}
354 		}
355 	}
356 
357 	HDAC_WRITE_4(&sc->mem, HDAC_INTSTS, intsts);
358 	hdac_unlock(sc);
359 }
360 
361 static void
362 hdac_poll_callback(void *arg)
363 {
364 	struct hdac_softc *sc = arg;
365 
366 	if (sc == NULL)
367 		return;
368 
369 	hdac_lock(sc);
370 	if (sc->polling == 0) {
371 		hdac_unlock(sc);
372 		return;
373 	}
374 	callout_reset(&sc->poll_callout, sc->poll_ival, hdac_poll_callback, sc);
375 	hdac_unlock(sc);
376 
377 	hdac_intr_handler(sc);
378 }
379 
380 /****************************************************************************
381  * int hdac_reset(hdac_softc *, bool)
382  *
383  * Reset the hdac to a quiescent and known state.
384  ****************************************************************************/
385 static int
386 hdac_reset(struct hdac_softc *sc, bool wakeup)
387 {
388 	uint32_t gctl;
389 	int count, i;
390 
391 	/*
392 	 * Stop all Streams DMA engine
393 	 */
394 	for (i = 0; i < sc->num_iss; i++)
395 		HDAC_WRITE_4(&sc->mem, HDAC_ISDCTL(sc, i), 0x0);
396 	for (i = 0; i < sc->num_oss; i++)
397 		HDAC_WRITE_4(&sc->mem, HDAC_OSDCTL(sc, i), 0x0);
398 	for (i = 0; i < sc->num_bss; i++)
399 		HDAC_WRITE_4(&sc->mem, HDAC_BSDCTL(sc, i), 0x0);
400 
401 	/*
402 	 * Stop Control DMA engines.
403 	 */
404 	HDAC_WRITE_1(&sc->mem, HDAC_CORBCTL, 0x0);
405 	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL, 0x0);
406 
407 	/*
408 	 * Reset DMA position buffer.
409 	 */
410 	HDAC_WRITE_4(&sc->mem, HDAC_DPIBLBASE, 0x0);
411 	HDAC_WRITE_4(&sc->mem, HDAC_DPIBUBASE, 0x0);
412 
413 	/*
414 	 * Reset the controller. The reset must remain asserted for
415 	 * a minimum of 100us.
416 	 */
417 	gctl = HDAC_READ_4(&sc->mem, HDAC_GCTL);
418 	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, gctl & ~HDAC_GCTL_CRST);
419 	count = 10000;
420 	do {
421 		gctl = HDAC_READ_4(&sc->mem, HDAC_GCTL);
422 		if (!(gctl & HDAC_GCTL_CRST))
423 			break;
424 		DELAY(10);
425 	} while (--count);
426 	if (gctl & HDAC_GCTL_CRST) {
427 		device_printf(sc->dev, "Unable to put hdac in reset\n");
428 		return (ENXIO);
429 	}
430 
431 	/* If wakeup is not requested - leave the controller in reset state. */
432 	if (!wakeup)
433 		return (0);
434 
435 	DELAY(100);
436 	gctl = HDAC_READ_4(&sc->mem, HDAC_GCTL);
437 	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, gctl | HDAC_GCTL_CRST);
438 	count = 10000;
439 	do {
440 		gctl = HDAC_READ_4(&sc->mem, HDAC_GCTL);
441 		if (gctl & HDAC_GCTL_CRST)
442 			break;
443 		DELAY(10);
444 	} while (--count);
445 	if (!(gctl & HDAC_GCTL_CRST)) {
446 		device_printf(sc->dev, "Device stuck in reset\n");
447 		return (ENXIO);
448 	}
449 
450 	/*
451 	 * Wait for codecs to finish their own reset sequence. The delay here
452 	 * must be at least 521us (HDA 1.0a section 4.3 Codec Discovery).
453 	 */
454 	DELAY(1000);
455 
456 	return (0);
457 }
458 
459 /****************************************************************************
460  * int hdac_get_capabilities(struct hdac_softc *);
461  *
462  * Retreive the general capabilities of the hdac;
463  *	Number of Input Streams
464  *	Number of Output Streams
465  *	Number of bidirectional Streams
466  *	64bit ready
467  *	CORB and RIRB sizes
468  ****************************************************************************/
469 static int
470 hdac_get_capabilities(struct hdac_softc *sc)
471 {
472 	uint16_t gcap;
473 	uint8_t corbsize, rirbsize;
474 
475 	gcap = HDAC_READ_2(&sc->mem, HDAC_GCAP);
476 	sc->num_iss = HDAC_GCAP_ISS(gcap);
477 	sc->num_oss = HDAC_GCAP_OSS(gcap);
478 	sc->num_bss = HDAC_GCAP_BSS(gcap);
479 	sc->num_ss = sc->num_iss + sc->num_oss + sc->num_bss;
480 	sc->num_sdo = HDAC_GCAP_NSDO(gcap);
481 	sc->support_64bit = (gcap & HDAC_GCAP_64OK) != 0;
482 	if (sc->quirks_on & HDAC_QUIRK_64BIT)
483 		sc->support_64bit = 1;
484 	else if (sc->quirks_off & HDAC_QUIRK_64BIT)
485 		sc->support_64bit = 0;
486 
487 	corbsize = HDAC_READ_1(&sc->mem, HDAC_CORBSIZE);
488 	if ((corbsize & HDAC_CORBSIZE_CORBSZCAP_256) ==
489 	    HDAC_CORBSIZE_CORBSZCAP_256)
490 		sc->corb_size = 256;
491 	else if ((corbsize & HDAC_CORBSIZE_CORBSZCAP_16) ==
492 	    HDAC_CORBSIZE_CORBSZCAP_16)
493 		sc->corb_size = 16;
494 	else if ((corbsize & HDAC_CORBSIZE_CORBSZCAP_2) ==
495 	    HDAC_CORBSIZE_CORBSZCAP_2)
496 		sc->corb_size = 2;
497 	else {
498 		device_printf(sc->dev, "%s: Invalid corb size (%x)\n",
499 		    __func__, corbsize);
500 		return (ENXIO);
501 	}
502 
503 	rirbsize = HDAC_READ_1(&sc->mem, HDAC_RIRBSIZE);
504 	if ((rirbsize & HDAC_RIRBSIZE_RIRBSZCAP_256) ==
505 	    HDAC_RIRBSIZE_RIRBSZCAP_256)
506 		sc->rirb_size = 256;
507 	else if ((rirbsize & HDAC_RIRBSIZE_RIRBSZCAP_16) ==
508 	    HDAC_RIRBSIZE_RIRBSZCAP_16)
509 		sc->rirb_size = 16;
510 	else if ((rirbsize & HDAC_RIRBSIZE_RIRBSZCAP_2) ==
511 	    HDAC_RIRBSIZE_RIRBSZCAP_2)
512 		sc->rirb_size = 2;
513 	else {
514 		device_printf(sc->dev, "%s: Invalid rirb size (%x)\n",
515 		    __func__, rirbsize);
516 		return (ENXIO);
517 	}
518 
519 	HDA_BOOTVERBOSE(
520 		device_printf(sc->dev, "Caps: OSS %d, ISS %d, BSS %d, "
521 		    "NSDO %d%s, CORB %d, RIRB %d\n",
522 		    sc->num_oss, sc->num_iss, sc->num_bss, 1 << sc->num_sdo,
523 		    sc->support_64bit ? ", 64bit" : "",
524 		    sc->corb_size, sc->rirb_size);
525 	);
526 
527 	return (0);
528 }
529 
530 
531 /****************************************************************************
532  * void hdac_dma_cb
533  *
534  * This function is called by bus_dmamap_load when the mapping has been
535  * established. We just record the physical address of the mapping into
536  * the struct hdac_dma passed in.
537  ****************************************************************************/
538 static void
539 hdac_dma_cb(void *callback_arg, bus_dma_segment_t *segs, int nseg, int error)
540 {
541 	struct hdac_dma *dma;
542 
543 	if (error == 0) {
544 		dma = (struct hdac_dma *)callback_arg;
545 		dma->dma_paddr = segs[0].ds_addr;
546 	}
547 }
548 
549 
550 /****************************************************************************
551  * int hdac_dma_alloc
552  *
553  * This function allocate and setup a dma region (struct hdac_dma).
554  * It must be freed by a corresponding hdac_dma_free.
555  ****************************************************************************/
556 static int
557 hdac_dma_alloc(struct hdac_softc *sc, struct hdac_dma *dma, bus_size_t size)
558 {
559 	bus_size_t roundsz;
560 	int result;
561 
562 	roundsz = roundup2(size, HDA_DMA_ALIGNMENT);
563 	bzero(dma, sizeof(*dma));
564 
565 	/*
566 	 * Create a DMA tag
567 	 */
568 	result = bus_dma_tag_create(
569 	    bus_get_dma_tag(sc->dev),		/* parent */
570 	    HDA_DMA_ALIGNMENT,			/* alignment */
571 	    0,					/* boundary */
572 	    (sc->support_64bit) ? BUS_SPACE_MAXADDR :
573 		BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
574 	    BUS_SPACE_MAXADDR,			/* highaddr */
575 	    NULL,				/* filtfunc */
576 	    NULL,				/* fistfuncarg */
577 	    roundsz, 				/* maxsize */
578 	    1,					/* nsegments */
579 	    roundsz, 				/* maxsegsz */
580 	    0,					/* flags */
581 	    NULL,				/* lockfunc */
582 	    NULL,				/* lockfuncarg */
583 	    &dma->dma_tag);			/* dmat */
584 	if (result != 0) {
585 		device_printf(sc->dev, "%s: bus_dma_tag_create failed (%d)\n",
586 		    __func__, result);
587 		goto hdac_dma_alloc_fail;
588 	}
589 
590 	/*
591 	 * Allocate DMA memory
592 	 */
593 	result = bus_dmamem_alloc(dma->dma_tag, (void **)&dma->dma_vaddr,
594 	    BUS_DMA_NOWAIT | BUS_DMA_ZERO |
595 	    ((sc->flags & HDAC_F_DMA_NOCACHE) ? BUS_DMA_NOCACHE :
596 	     BUS_DMA_COHERENT),
597 	    &dma->dma_map);
598 	if (result != 0) {
599 		device_printf(sc->dev, "%s: bus_dmamem_alloc failed (%d)\n",
600 		    __func__, result);
601 		goto hdac_dma_alloc_fail;
602 	}
603 
604 	dma->dma_size = roundsz;
605 
606 	/*
607 	 * Map the memory
608 	 */
609 	result = bus_dmamap_load(dma->dma_tag, dma->dma_map,
610 	    (void *)dma->dma_vaddr, roundsz, hdac_dma_cb, (void *)dma, 0);
611 	if (result != 0 || dma->dma_paddr == 0) {
612 		if (result == 0)
613 			result = ENOMEM;
614 		device_printf(sc->dev, "%s: bus_dmamem_load failed (%d)\n",
615 		    __func__, result);
616 		goto hdac_dma_alloc_fail;
617 	}
618 
619 	HDA_BOOTHVERBOSE(
620 		device_printf(sc->dev, "%s: size=%ju -> roundsz=%ju\n",
621 		    __func__, (uintmax_t)size, (uintmax_t)roundsz);
622 	);
623 
624 	return (0);
625 
626 hdac_dma_alloc_fail:
627 	hdac_dma_free(sc, dma);
628 
629 	return (result);
630 }
631 
632 /****************************************************************************
633  * void hdac_dma_free(struct hdac_softc *, struct hdac_dma *)
634  *
635  * Free a struct hdac_dma that has been previously allocated via the
636  * hdac_dma_alloc function.
637  ****************************************************************************/
638 static void
639 hdac_dma_free(struct hdac_softc *sc, struct hdac_dma *dma)
640 {
641 	if (dma->dma_paddr != 0) {
642 		/* Flush caches */
643 		bus_dmamap_sync(dma->dma_tag, dma->dma_map,
644 		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
645 		bus_dmamap_unload(dma->dma_tag, dma->dma_map);
646 		dma->dma_paddr = 0;
647 	}
648 	if (dma->dma_vaddr != NULL) {
649 		bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
650 		dma->dma_vaddr = NULL;
651 	}
652 	if (dma->dma_tag != NULL) {
653 		bus_dma_tag_destroy(dma->dma_tag);
654 		dma->dma_tag = NULL;
655 	}
656 	dma->dma_size = 0;
657 }
658 
659 /****************************************************************************
660  * int hdac_mem_alloc(struct hdac_softc *)
661  *
662  * Allocate all the bus resources necessary to speak with the physical
663  * controller.
664  ****************************************************************************/
665 static int
666 hdac_mem_alloc(struct hdac_softc *sc)
667 {
668 	struct hdac_mem *mem;
669 
670 	mem = &sc->mem;
671 	mem->mem_rid = PCIR_BAR(0);
672 	mem->mem_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
673 	    &mem->mem_rid, RF_ACTIVE);
674 	if (mem->mem_res == NULL) {
675 		device_printf(sc->dev,
676 		    "%s: Unable to allocate memory resource\n", __func__);
677 		return (ENOMEM);
678 	}
679 	mem->mem_tag = rman_get_bustag(mem->mem_res);
680 	mem->mem_handle = rman_get_bushandle(mem->mem_res);
681 
682 	return (0);
683 }
684 
685 /****************************************************************************
686  * void hdac_mem_free(struct hdac_softc *)
687  *
688  * Free up resources previously allocated by hdac_mem_alloc.
689  ****************************************************************************/
690 static void
691 hdac_mem_free(struct hdac_softc *sc)
692 {
693 	struct hdac_mem *mem;
694 
695 	mem = &sc->mem;
696 	if (mem->mem_res != NULL)
697 		bus_release_resource(sc->dev, SYS_RES_MEMORY, mem->mem_rid,
698 		    mem->mem_res);
699 	mem->mem_res = NULL;
700 }
701 
702 /****************************************************************************
703  * int hdac_irq_alloc(struct hdac_softc *)
704  *
705  * Allocate and setup the resources necessary for interrupt handling.
706  ****************************************************************************/
707 static int
708 hdac_irq_alloc(struct hdac_softc *sc)
709 {
710 	struct hdac_irq *irq;
711 	int result;
712 
713 	irq = &sc->irq;
714 	irq->irq_rid = 0x0;
715 
716 	if ((sc->quirks_off & HDAC_QUIRK_MSI) == 0 &&
717 	    (result = pci_msi_count(sc->dev)) == 1 &&
718 	    pci_alloc_msi(sc->dev, &result) == 0)
719 		irq->irq_rid = 0x1;
720 
721 	irq->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
722 	    &irq->irq_rid, RF_SHAREABLE | RF_ACTIVE);
723 	if (irq->irq_res == NULL) {
724 		device_printf(sc->dev, "%s: Unable to allocate irq\n",
725 		    __func__);
726 		goto hdac_irq_alloc_fail;
727 	}
728 	result = bus_setup_intr(sc->dev, irq->irq_res, INTR_MPSAFE | INTR_TYPE_AV,
729 	    NULL, hdac_intr_handler, sc, &irq->irq_handle);
730 	if (result != 0) {
731 		device_printf(sc->dev,
732 		    "%s: Unable to setup interrupt handler (%d)\n",
733 		    __func__, result);
734 		goto hdac_irq_alloc_fail;
735 	}
736 
737 	return (0);
738 
739 hdac_irq_alloc_fail:
740 	hdac_irq_free(sc);
741 
742 	return (ENXIO);
743 }
744 
745 /****************************************************************************
746  * void hdac_irq_free(struct hdac_softc *)
747  *
748  * Free up resources previously allocated by hdac_irq_alloc.
749  ****************************************************************************/
750 static void
751 hdac_irq_free(struct hdac_softc *sc)
752 {
753 	struct hdac_irq *irq;
754 
755 	irq = &sc->irq;
756 	if (irq->irq_res != NULL && irq->irq_handle != NULL)
757 		bus_teardown_intr(sc->dev, irq->irq_res, irq->irq_handle);
758 	if (irq->irq_res != NULL)
759 		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->irq_rid,
760 		    irq->irq_res);
761 	if (irq->irq_rid == 0x1)
762 		pci_release_msi(sc->dev);
763 	irq->irq_handle = NULL;
764 	irq->irq_res = NULL;
765 	irq->irq_rid = 0x0;
766 }
767 
768 /****************************************************************************
769  * void hdac_corb_init(struct hdac_softc *)
770  *
771  * Initialize the corb registers for operations but do not start it up yet.
772  * The CORB engine must not be running when this function is called.
773  ****************************************************************************/
774 static void
775 hdac_corb_init(struct hdac_softc *sc)
776 {
777 	uint8_t corbsize;
778 	uint64_t corbpaddr;
779 
780 	/* Setup the CORB size. */
781 	switch (sc->corb_size) {
782 	case 256:
783 		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_256);
784 		break;
785 	case 16:
786 		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_16);
787 		break;
788 	case 2:
789 		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_2);
790 		break;
791 	default:
792 		panic("%s: Invalid CORB size (%x)\n", __func__, sc->corb_size);
793 	}
794 	HDAC_WRITE_1(&sc->mem, HDAC_CORBSIZE, corbsize);
795 
796 	/* Setup the CORB Address in the hdac */
797 	corbpaddr = (uint64_t)sc->corb_dma.dma_paddr;
798 	HDAC_WRITE_4(&sc->mem, HDAC_CORBLBASE, (uint32_t)corbpaddr);
799 	HDAC_WRITE_4(&sc->mem, HDAC_CORBUBASE, (uint32_t)(corbpaddr >> 32));
800 
801 	/* Set the WP and RP */
802 	sc->corb_wp = 0;
803 	HDAC_WRITE_2(&sc->mem, HDAC_CORBWP, sc->corb_wp);
804 	HDAC_WRITE_2(&sc->mem, HDAC_CORBRP, HDAC_CORBRP_CORBRPRST);
805 	/*
806 	 * The HDA specification indicates that the CORBRPRST bit will always
807 	 * read as zero. Unfortunately, it seems that at least the 82801G
808 	 * doesn't reset the bit to zero, which stalls the corb engine.
809 	 * manually reset the bit to zero before continuing.
810 	 */
811 	HDAC_WRITE_2(&sc->mem, HDAC_CORBRP, 0x0);
812 
813 	/* Enable CORB error reporting */
814 #if 0
815 	HDAC_WRITE_1(&sc->mem, HDAC_CORBCTL, HDAC_CORBCTL_CMEIE);
816 #endif
817 }
818 
819 /****************************************************************************
820  * void hdac_rirb_init(struct hdac_softc *)
821  *
822  * Initialize the rirb registers for operations but do not start it up yet.
823  * The RIRB engine must not be running when this function is called.
824  ****************************************************************************/
825 static void
826 hdac_rirb_init(struct hdac_softc *sc)
827 {
828 	uint8_t rirbsize;
829 	uint64_t rirbpaddr;
830 
831 	/* Setup the RIRB size. */
832 	switch (sc->rirb_size) {
833 	case 256:
834 		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_256);
835 		break;
836 	case 16:
837 		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_16);
838 		break;
839 	case 2:
840 		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_2);
841 		break;
842 	default:
843 		panic("%s: Invalid RIRB size (%x)\n", __func__, sc->rirb_size);
844 	}
845 	HDAC_WRITE_1(&sc->mem, HDAC_RIRBSIZE, rirbsize);
846 
847 	/* Setup the RIRB Address in the hdac */
848 	rirbpaddr = (uint64_t)sc->rirb_dma.dma_paddr;
849 	HDAC_WRITE_4(&sc->mem, HDAC_RIRBLBASE, (uint32_t)rirbpaddr);
850 	HDAC_WRITE_4(&sc->mem, HDAC_RIRBUBASE, (uint32_t)(rirbpaddr >> 32));
851 
852 	/* Setup the WP and RP */
853 	sc->rirb_rp = 0;
854 	HDAC_WRITE_2(&sc->mem, HDAC_RIRBWP, HDAC_RIRBWP_RIRBWPRST);
855 
856 	/* Setup the interrupt threshold */
857 	HDAC_WRITE_2(&sc->mem, HDAC_RINTCNT, sc->rirb_size / 2);
858 
859 	/* Enable Overrun and response received reporting */
860 #if 0
861 	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL,
862 	    HDAC_RIRBCTL_RIRBOIC | HDAC_RIRBCTL_RINTCTL);
863 #else
864 	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL, HDAC_RIRBCTL_RINTCTL);
865 #endif
866 
867 	/*
868 	 * Make sure that the Host CPU cache doesn't contain any dirty
869 	 * cache lines that falls in the rirb. If I understood correctly, it
870 	 * should be sufficient to do this only once as the rirb is purely
871 	 * read-only from now on.
872 	 */
873 	bus_dmamap_sync(sc->rirb_dma.dma_tag, sc->rirb_dma.dma_map,
874 	    BUS_DMASYNC_PREREAD);
875 }
876 
877 /****************************************************************************
878  * void hdac_corb_start(hdac_softc *)
879  *
880  * Startup the corb DMA engine
881  ****************************************************************************/
882 static void
883 hdac_corb_start(struct hdac_softc *sc)
884 {
885 	uint32_t corbctl;
886 
887 	corbctl = HDAC_READ_1(&sc->mem, HDAC_CORBCTL);
888 	corbctl |= HDAC_CORBCTL_CORBRUN;
889 	HDAC_WRITE_1(&sc->mem, HDAC_CORBCTL, corbctl);
890 }
891 
892 /****************************************************************************
893  * void hdac_rirb_start(hdac_softc *)
894  *
895  * Startup the rirb DMA engine
896  ****************************************************************************/
897 static void
898 hdac_rirb_start(struct hdac_softc *sc)
899 {
900 	uint32_t rirbctl;
901 
902 	rirbctl = HDAC_READ_1(&sc->mem, HDAC_RIRBCTL);
903 	rirbctl |= HDAC_RIRBCTL_RIRBDMAEN;
904 	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL, rirbctl);
905 }
906 
907 static int
908 hdac_rirb_flush(struct hdac_softc *sc)
909 {
910 	struct hdac_rirb *rirb_base, *rirb;
911 	nid_t cad;
912 	uint32_t resp, resp_ex;
913 	uint8_t rirbwp;
914 	int ret;
915 
916 	rirb_base = (struct hdac_rirb *)sc->rirb_dma.dma_vaddr;
917 	rirbwp = HDAC_READ_1(&sc->mem, HDAC_RIRBWP);
918 	bus_dmamap_sync(sc->rirb_dma.dma_tag, sc->rirb_dma.dma_map,
919 	    BUS_DMASYNC_POSTREAD);
920 
921 	ret = 0;
922 	while (sc->rirb_rp != rirbwp) {
923 		sc->rirb_rp++;
924 		sc->rirb_rp %= sc->rirb_size;
925 		rirb = &rirb_base[sc->rirb_rp];
926 		resp = le32toh(rirb->response);
927 		resp_ex = le32toh(rirb->response_ex);
928 		cad = HDAC_RIRB_RESPONSE_EX_SDATA_IN(resp_ex);
929 		if (resp_ex & HDAC_RIRB_RESPONSE_EX_UNSOLICITED) {
930 			sc->unsolq[sc->unsolq_wp++] = resp;
931 			sc->unsolq_wp %= HDAC_UNSOLQ_MAX;
932 			sc->unsolq[sc->unsolq_wp++] = cad;
933 			sc->unsolq_wp %= HDAC_UNSOLQ_MAX;
934 		} else if (sc->codecs[cad].pending <= 0) {
935 			device_printf(sc->dev, "Unexpected unsolicited "
936 			    "response from address %d: %08x\n", cad, resp);
937 		} else {
938 			sc->codecs[cad].response = resp;
939 			sc->codecs[cad].pending--;
940 		}
941 		ret++;
942 	}
943 
944 	bus_dmamap_sync(sc->rirb_dma.dma_tag, sc->rirb_dma.dma_map,
945 	    BUS_DMASYNC_PREREAD);
946 	return (ret);
947 }
948 
949 static int
950 hdac_unsolq_flush(struct hdac_softc *sc)
951 {
952 	device_t child;
953 	nid_t cad;
954 	uint32_t resp;
955 	int ret = 0;
956 
957 	if (sc->unsolq_st == HDAC_UNSOLQ_READY) {
958 		sc->unsolq_st = HDAC_UNSOLQ_BUSY;
959 		while (sc->unsolq_rp != sc->unsolq_wp) {
960 			resp = sc->unsolq[sc->unsolq_rp++];
961 			sc->unsolq_rp %= HDAC_UNSOLQ_MAX;
962 			cad = sc->unsolq[sc->unsolq_rp++];
963 			sc->unsolq_rp %= HDAC_UNSOLQ_MAX;
964 			if ((child = sc->codecs[cad].dev) != NULL)
965 				HDAC_UNSOL_INTR(child, resp);
966 			ret++;
967 		}
968 		sc->unsolq_st = HDAC_UNSOLQ_READY;
969 	}
970 
971 	return (ret);
972 }
973 
974 /****************************************************************************
975  * uint32_t hdac_send_command
976  *
977  * Wrapper function that sends only one command to a given codec
978  ****************************************************************************/
979 static uint32_t
980 hdac_send_command(struct hdac_softc *sc, nid_t cad, uint32_t verb)
981 {
982 	int timeout;
983 	uint32_t *corb;
984 
985 	hdac_lockassert(sc);
986 	verb &= ~HDA_CMD_CAD_MASK;
987 	verb |= ((uint32_t)cad) << HDA_CMD_CAD_SHIFT;
988 	sc->codecs[cad].response = HDA_INVALID;
989 
990 	sc->codecs[cad].pending++;
991 	sc->corb_wp++;
992 	sc->corb_wp %= sc->corb_size;
993 	corb = (uint32_t *)sc->corb_dma.dma_vaddr;
994 	bus_dmamap_sync(sc->corb_dma.dma_tag,
995 	    sc->corb_dma.dma_map, BUS_DMASYNC_PREWRITE);
996 	corb[sc->corb_wp] = htole32(verb);
997 	bus_dmamap_sync(sc->corb_dma.dma_tag,
998 	    sc->corb_dma.dma_map, BUS_DMASYNC_POSTWRITE);
999 	HDAC_WRITE_2(&sc->mem, HDAC_CORBWP, sc->corb_wp);
1000 
1001 	timeout = 10000;
1002 	do {
1003 		if (hdac_rirb_flush(sc) == 0)
1004 			DELAY(10);
1005 	} while (sc->codecs[cad].pending != 0 && --timeout);
1006 
1007 	if (sc->codecs[cad].pending != 0) {
1008 		device_printf(sc->dev, "Command 0x%08x timeout on address %d\n",
1009 		    verb, cad);
1010 		sc->codecs[cad].pending = 0;
1011 	}
1012 
1013 	if (sc->unsolq_rp != sc->unsolq_wp)
1014 		taskqueue_enqueue(taskqueue_thread, &sc->unsolq_task);
1015 	return (sc->codecs[cad].response);
1016 }
1017 
1018 /****************************************************************************
1019  * Device Methods
1020  ****************************************************************************/
1021 
1022 /****************************************************************************
1023  * int hdac_probe(device_t)
1024  *
1025  * Probe for the presence of an hdac. If none is found, check for a generic
1026  * match using the subclass of the device.
1027  ****************************************************************************/
1028 static int
1029 hdac_probe(device_t dev)
1030 {
1031 	int i, result;
1032 	uint32_t model;
1033 	uint16_t class, subclass;
1034 	char desc[64];
1035 
1036 	model = (uint32_t)pci_get_device(dev) << 16;
1037 	model |= (uint32_t)pci_get_vendor(dev) & 0x0000ffff;
1038 	class = pci_get_class(dev);
1039 	subclass = pci_get_subclass(dev);
1040 
1041 	bzero(desc, sizeof(desc));
1042 	result = ENXIO;
1043 	for (i = 0; i < nitems(hdac_devices); i++) {
1044 		if (hdac_devices[i].model == model) {
1045 			strlcpy(desc, hdac_devices[i].desc, sizeof(desc));
1046 			result = BUS_PROBE_DEFAULT;
1047 			break;
1048 		}
1049 		if (HDA_DEV_MATCH(hdac_devices[i].model, model) &&
1050 		    class == PCIC_MULTIMEDIA &&
1051 		    subclass == PCIS_MULTIMEDIA_HDA) {
1052 			snprintf(desc, sizeof(desc), "%s (0x%04x)",
1053 			    hdac_devices[i].desc, pci_get_device(dev));
1054 			result = BUS_PROBE_GENERIC;
1055 			break;
1056 		}
1057 	}
1058 	if (result == ENXIO && class == PCIC_MULTIMEDIA &&
1059 	    subclass == PCIS_MULTIMEDIA_HDA) {
1060 		snprintf(desc, sizeof(desc), "Generic (0x%08x)", model);
1061 		result = BUS_PROBE_GENERIC;
1062 	}
1063 	if (result != ENXIO) {
1064 		strlcat(desc, " HDA Controller", sizeof(desc));
1065 		device_set_desc_copy(dev, desc);
1066 	}
1067 
1068 	return (result);
1069 }
1070 
1071 static void
1072 hdac_unsolq_task(void *context, int pending)
1073 {
1074 	struct hdac_softc *sc;
1075 
1076 	sc = (struct hdac_softc *)context;
1077 
1078 	hdac_lock(sc);
1079 	hdac_unsolq_flush(sc);
1080 	hdac_unlock(sc);
1081 }
1082 
1083 /****************************************************************************
1084  * int hdac_attach(device_t)
1085  *
1086  * Attach the device into the kernel. Interrupts usually won't be enabled
1087  * when this function is called. Setup everything that doesn't require
1088  * interrupts and defer probing of codecs until interrupts are enabled.
1089  ****************************************************************************/
1090 static int
1091 hdac_attach(device_t dev)
1092 {
1093 	struct hdac_softc *sc;
1094 	int result;
1095 	int i, devid = -1;
1096 	uint32_t model;
1097 	uint16_t class, subclass;
1098 	uint16_t vendor;
1099 	uint8_t v;
1100 
1101 	sc = device_get_softc(dev);
1102 	HDA_BOOTVERBOSE(
1103 		device_printf(dev, "PCI card vendor: 0x%04x, device: 0x%04x\n",
1104 		    pci_get_subvendor(dev), pci_get_subdevice(dev));
1105 		device_printf(dev, "HDA Driver Revision: %s\n",
1106 		    HDA_DRV_TEST_REV);
1107 	);
1108 
1109 	model = (uint32_t)pci_get_device(dev) << 16;
1110 	model |= (uint32_t)pci_get_vendor(dev) & 0x0000ffff;
1111 	class = pci_get_class(dev);
1112 	subclass = pci_get_subclass(dev);
1113 
1114 	for (i = 0; i < nitems(hdac_devices); i++) {
1115 		if (hdac_devices[i].model == model) {
1116 			devid = i;
1117 			break;
1118 		}
1119 		if (HDA_DEV_MATCH(hdac_devices[i].model, model) &&
1120 		    class == PCIC_MULTIMEDIA &&
1121 		    subclass == PCIS_MULTIMEDIA_HDA) {
1122 			devid = i;
1123 			break;
1124 		}
1125 	}
1126 
1127 	sc->lock = snd_mtxcreate(device_get_nameunit(dev), "HDA driver mutex");
1128 	sc->dev = dev;
1129 	TASK_INIT(&sc->unsolq_task, 0, hdac_unsolq_task, sc);
1130 	callout_init(&sc->poll_callout, 1);
1131 	for (i = 0; i < HDAC_CODEC_MAX; i++)
1132 		sc->codecs[i].dev = NULL;
1133 	if (devid >= 0) {
1134 		sc->quirks_on = hdac_devices[devid].quirks_on;
1135 		sc->quirks_off = hdac_devices[devid].quirks_off;
1136 	} else {
1137 		sc->quirks_on = 0;
1138 		sc->quirks_off = 0;
1139 	}
1140 	if (resource_int_value(device_get_name(dev),
1141 	    device_get_unit(dev), "msi", &i) == 0) {
1142 		if (i == 0)
1143 			sc->quirks_off |= HDAC_QUIRK_MSI;
1144 		else {
1145 			sc->quirks_on |= HDAC_QUIRK_MSI;
1146 			sc->quirks_off |= ~HDAC_QUIRK_MSI;
1147 		}
1148 	}
1149 	hdac_config_fetch(sc, &sc->quirks_on, &sc->quirks_off);
1150 	HDA_BOOTVERBOSE(
1151 		device_printf(sc->dev,
1152 		    "Config options: on=0x%08x off=0x%08x\n",
1153 		    sc->quirks_on, sc->quirks_off);
1154 	);
1155 	sc->poll_ival = hz;
1156 	if (resource_int_value(device_get_name(dev),
1157 	    device_get_unit(dev), "polling", &i) == 0 && i != 0)
1158 		sc->polling = 1;
1159 	else
1160 		sc->polling = 0;
1161 
1162 	pci_enable_busmaster(dev);
1163 
1164 	vendor = pci_get_vendor(dev);
1165 	if (vendor == INTEL_VENDORID) {
1166 		/* TCSEL -> TC0 */
1167 		v = pci_read_config(dev, 0x44, 1);
1168 		pci_write_config(dev, 0x44, v & 0xf8, 1);
1169 		HDA_BOOTHVERBOSE(
1170 			device_printf(dev, "TCSEL: 0x%02d -> 0x%02d\n", v,
1171 			    pci_read_config(dev, 0x44, 1));
1172 		);
1173 	}
1174 
1175 #if defined(__i386__) || defined(__amd64__)
1176 	sc->flags |= HDAC_F_DMA_NOCACHE;
1177 
1178 	if (resource_int_value(device_get_name(dev),
1179 	    device_get_unit(dev), "snoop", &i) == 0 && i != 0) {
1180 #else
1181 	sc->flags &= ~HDAC_F_DMA_NOCACHE;
1182 #endif
1183 		/*
1184 		 * Try to enable PCIe snoop to avoid messing around with
1185 		 * uncacheable DMA attribute. Since PCIe snoop register
1186 		 * config is pretty much vendor specific, there are no
1187 		 * general solutions on how to enable it, forcing us (even
1188 		 * Microsoft) to enable uncacheable or write combined DMA
1189 		 * by default.
1190 		 *
1191 		 * http://msdn2.microsoft.com/en-us/library/ms790324.aspx
1192 		 */
1193 		for (i = 0; i < nitems(hdac_pcie_snoop); i++) {
1194 			if (hdac_pcie_snoop[i].vendor != vendor)
1195 				continue;
1196 			sc->flags &= ~HDAC_F_DMA_NOCACHE;
1197 			if (hdac_pcie_snoop[i].reg == 0x00)
1198 				break;
1199 			v = pci_read_config(dev, hdac_pcie_snoop[i].reg, 1);
1200 			if ((v & hdac_pcie_snoop[i].enable) ==
1201 			    hdac_pcie_snoop[i].enable)
1202 				break;
1203 			v &= hdac_pcie_snoop[i].mask;
1204 			v |= hdac_pcie_snoop[i].enable;
1205 			pci_write_config(dev, hdac_pcie_snoop[i].reg, v, 1);
1206 			v = pci_read_config(dev, hdac_pcie_snoop[i].reg, 1);
1207 			if ((v & hdac_pcie_snoop[i].enable) !=
1208 			    hdac_pcie_snoop[i].enable) {
1209 				HDA_BOOTVERBOSE(
1210 					device_printf(dev,
1211 					    "WARNING: Failed to enable PCIe "
1212 					    "snoop!\n");
1213 				);
1214 #if defined(__i386__) || defined(__amd64__)
1215 				sc->flags |= HDAC_F_DMA_NOCACHE;
1216 #endif
1217 			}
1218 			break;
1219 		}
1220 #if defined(__i386__) || defined(__amd64__)
1221 	}
1222 #endif
1223 
1224 	HDA_BOOTHVERBOSE(
1225 		device_printf(dev, "DMA Coherency: %s / vendor=0x%04x\n",
1226 		    (sc->flags & HDAC_F_DMA_NOCACHE) ?
1227 		    "Uncacheable" : "PCIe snoop", vendor);
1228 	);
1229 
1230 	/* Allocate resources */
1231 	result = hdac_mem_alloc(sc);
1232 	if (result != 0)
1233 		goto hdac_attach_fail;
1234 	result = hdac_irq_alloc(sc);
1235 	if (result != 0)
1236 		goto hdac_attach_fail;
1237 
1238 	/* Get Capabilities */
1239 	result = hdac_get_capabilities(sc);
1240 	if (result != 0)
1241 		goto hdac_attach_fail;
1242 
1243 	/* Allocate CORB, RIRB, POS and BDLs dma memory */
1244 	result = hdac_dma_alloc(sc, &sc->corb_dma,
1245 	    sc->corb_size * sizeof(uint32_t));
1246 	if (result != 0)
1247 		goto hdac_attach_fail;
1248 	result = hdac_dma_alloc(sc, &sc->rirb_dma,
1249 	    sc->rirb_size * sizeof(struct hdac_rirb));
1250 	if (result != 0)
1251 		goto hdac_attach_fail;
1252 	sc->streams = malloc(sizeof(struct hdac_stream) * sc->num_ss,
1253 	    M_HDAC, M_ZERO | M_WAITOK);
1254 	for (i = 0; i < sc->num_ss; i++) {
1255 		result = hdac_dma_alloc(sc, &sc->streams[i].bdl,
1256 		    sizeof(struct hdac_bdle) * HDA_BDL_MAX);
1257 		if (result != 0)
1258 			goto hdac_attach_fail;
1259 	}
1260 	if (sc->quirks_on & HDAC_QUIRK_DMAPOS) {
1261 		if (hdac_dma_alloc(sc, &sc->pos_dma, (sc->num_ss) * 8) != 0) {
1262 			HDA_BOOTVERBOSE(
1263 				device_printf(dev, "Failed to "
1264 				    "allocate DMA pos buffer "
1265 				    "(non-fatal)\n");
1266 			);
1267 		} else {
1268 			uint64_t addr = sc->pos_dma.dma_paddr;
1269 
1270 			HDAC_WRITE_4(&sc->mem, HDAC_DPIBUBASE, addr >> 32);
1271 			HDAC_WRITE_4(&sc->mem, HDAC_DPIBLBASE,
1272 			    (addr & HDAC_DPLBASE_DPLBASE_MASK) |
1273 			    HDAC_DPLBASE_DPLBASE_DMAPBE);
1274 		}
1275 	}
1276 
1277 	result = bus_dma_tag_create(
1278 	    bus_get_dma_tag(sc->dev),		/* parent */
1279 	    HDA_DMA_ALIGNMENT,			/* alignment */
1280 	    0,					/* boundary */
1281 	    (sc->support_64bit) ? BUS_SPACE_MAXADDR :
1282 		BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1283 	    BUS_SPACE_MAXADDR,			/* highaddr */
1284 	    NULL,				/* filtfunc */
1285 	    NULL,				/* fistfuncarg */
1286 	    HDA_BUFSZ_MAX, 			/* maxsize */
1287 	    1,					/* nsegments */
1288 	    HDA_BUFSZ_MAX, 			/* maxsegsz */
1289 	    0,					/* flags */
1290 	    NULL,				/* lockfunc */
1291 	    NULL,				/* lockfuncarg */
1292 	    &sc->chan_dmat);			/* dmat */
1293 	if (result != 0) {
1294 		device_printf(dev, "%s: bus_dma_tag_create failed (%d)\n",
1295 		     __func__, result);
1296 		goto hdac_attach_fail;
1297 	}
1298 
1299 	/* Quiesce everything */
1300 	HDA_BOOTHVERBOSE(
1301 		device_printf(dev, "Reset controller...\n");
1302 	);
1303 	hdac_reset(sc, true);
1304 
1305 	/* Initialize the CORB and RIRB */
1306 	hdac_corb_init(sc);
1307 	hdac_rirb_init(sc);
1308 
1309 	/* Defer remaining of initialization until interrupts are enabled */
1310 	sc->intrhook.ich_func = hdac_attach2;
1311 	sc->intrhook.ich_arg = (void *)sc;
1312 	if (cold == 0 || config_intrhook_establish(&sc->intrhook) != 0) {
1313 		sc->intrhook.ich_func = NULL;
1314 		hdac_attach2((void *)sc);
1315 	}
1316 
1317 	return (0);
1318 
1319 hdac_attach_fail:
1320 	hdac_irq_free(sc);
1321 	if (sc->streams != NULL)
1322 		for (i = 0; i < sc->num_ss; i++)
1323 			hdac_dma_free(sc, &sc->streams[i].bdl);
1324 	free(sc->streams, M_HDAC);
1325 	hdac_dma_free(sc, &sc->rirb_dma);
1326 	hdac_dma_free(sc, &sc->corb_dma);
1327 	hdac_mem_free(sc);
1328 	snd_mtxfree(sc->lock);
1329 
1330 	return (ENXIO);
1331 }
1332 
1333 static int
1334 sysctl_hdac_pindump(SYSCTL_HANDLER_ARGS)
1335 {
1336 	struct hdac_softc *sc;
1337 	device_t *devlist;
1338 	device_t dev;
1339 	int devcount, i, err, val;
1340 
1341 	dev = oidp->oid_arg1;
1342 	sc = device_get_softc(dev);
1343 	if (sc == NULL)
1344 		return (EINVAL);
1345 	val = 0;
1346 	err = sysctl_handle_int(oidp, &val, 0, req);
1347 	if (err != 0 || req->newptr == NULL || val == 0)
1348 		return (err);
1349 
1350 	/* XXX: Temporary. For debugging. */
1351 	if (val == 100) {
1352 		hdac_suspend(dev);
1353 		return (0);
1354 	} else if (val == 101) {
1355 		hdac_resume(dev);
1356 		return (0);
1357 	}
1358 
1359 	if ((err = device_get_children(dev, &devlist, &devcount)) != 0)
1360 		return (err);
1361 	hdac_lock(sc);
1362 	for (i = 0; i < devcount; i++)
1363 		HDAC_PINDUMP(devlist[i]);
1364 	hdac_unlock(sc);
1365 	free(devlist, M_TEMP);
1366 	return (0);
1367 }
1368 
1369 static int
1370 hdac_mdata_rate(uint16_t fmt)
1371 {
1372 	static const int mbits[8] = { 8, 16, 32, 32, 32, 32, 32, 32 };
1373 	int rate, bits;
1374 
1375 	if (fmt & (1 << 14))
1376 		rate = 44100;
1377 	else
1378 		rate = 48000;
1379 	rate *= ((fmt >> 11) & 0x07) + 1;
1380 	rate /= ((fmt >> 8) & 0x07) + 1;
1381 	bits = mbits[(fmt >> 4) & 0x03];
1382 	bits *= (fmt & 0x0f) + 1;
1383 	return (rate * bits);
1384 }
1385 
1386 static int
1387 hdac_bdata_rate(uint16_t fmt, int output)
1388 {
1389 	static const int bbits[8] = { 8, 16, 20, 24, 32, 32, 32, 32 };
1390 	int rate, bits;
1391 
1392 	rate = 48000;
1393 	rate *= ((fmt >> 11) & 0x07) + 1;
1394 	bits = bbits[(fmt >> 4) & 0x03];
1395 	bits *= (fmt & 0x0f) + 1;
1396 	if (!output)
1397 		bits = ((bits + 7) & ~0x07) + 10;
1398 	return (rate * bits);
1399 }
1400 
1401 static void
1402 hdac_poll_reinit(struct hdac_softc *sc)
1403 {
1404 	int i, pollticks, min = 1000000;
1405 	struct hdac_stream *s;
1406 
1407 	if (sc->polling == 0)
1408 		return;
1409 	if (sc->unsol_registered > 0)
1410 		min = hz / 2;
1411 	for (i = 0; i < sc->num_ss; i++) {
1412 		s = &sc->streams[i];
1413 		if (s->running == 0)
1414 			continue;
1415 		pollticks = ((uint64_t)hz * s->blksz) /
1416 		    (hdac_mdata_rate(s->format) / 8);
1417 		pollticks >>= 1;
1418 		if (pollticks > hz)
1419 			pollticks = hz;
1420 		if (pollticks < 1)
1421 			pollticks = 1;
1422 		if (min > pollticks)
1423 			min = pollticks;
1424 	}
1425 	sc->poll_ival = min;
1426 	if (min == 1000000)
1427 		callout_stop(&sc->poll_callout);
1428 	else
1429 		callout_reset(&sc->poll_callout, 1, hdac_poll_callback, sc);
1430 }
1431 
1432 static int
1433 sysctl_hdac_polling(SYSCTL_HANDLER_ARGS)
1434 {
1435 	struct hdac_softc *sc;
1436 	device_t dev;
1437 	uint32_t ctl;
1438 	int err, val;
1439 
1440 	dev = oidp->oid_arg1;
1441 	sc = device_get_softc(dev);
1442 	if (sc == NULL)
1443 		return (EINVAL);
1444 	hdac_lock(sc);
1445 	val = sc->polling;
1446 	hdac_unlock(sc);
1447 	err = sysctl_handle_int(oidp, &val, 0, req);
1448 
1449 	if (err != 0 || req->newptr == NULL)
1450 		return (err);
1451 	if (val < 0 || val > 1)
1452 		return (EINVAL);
1453 
1454 	hdac_lock(sc);
1455 	if (val != sc->polling) {
1456 		if (val == 0) {
1457 			callout_stop(&sc->poll_callout);
1458 			hdac_unlock(sc);
1459 			callout_drain(&sc->poll_callout);
1460 			hdac_lock(sc);
1461 			sc->polling = 0;
1462 			ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1463 			ctl |= HDAC_INTCTL_GIE;
1464 			HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1465 		} else {
1466 			ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1467 			ctl &= ~HDAC_INTCTL_GIE;
1468 			HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1469 			sc->polling = 1;
1470 			hdac_poll_reinit(sc);
1471 		}
1472 	}
1473 	hdac_unlock(sc);
1474 
1475 	return (err);
1476 }
1477 
1478 static void
1479 hdac_attach2(void *arg)
1480 {
1481 	struct hdac_softc *sc;
1482 	device_t child;
1483 	uint32_t vendorid, revisionid;
1484 	int i;
1485 	uint16_t statests;
1486 
1487 	sc = (struct hdac_softc *)arg;
1488 
1489 	hdac_lock(sc);
1490 
1491 	/* Remove ourselves from the config hooks */
1492 	if (sc->intrhook.ich_func != NULL) {
1493 		config_intrhook_disestablish(&sc->intrhook);
1494 		sc->intrhook.ich_func = NULL;
1495 	}
1496 
1497 	HDA_BOOTHVERBOSE(
1498 		device_printf(sc->dev, "Starting CORB Engine...\n");
1499 	);
1500 	hdac_corb_start(sc);
1501 	HDA_BOOTHVERBOSE(
1502 		device_printf(sc->dev, "Starting RIRB Engine...\n");
1503 	);
1504 	hdac_rirb_start(sc);
1505 	HDA_BOOTHVERBOSE(
1506 		device_printf(sc->dev,
1507 		    "Enabling controller interrupt...\n");
1508 	);
1509 	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, HDAC_READ_4(&sc->mem, HDAC_GCTL) |
1510 	    HDAC_GCTL_UNSOL);
1511 	if (sc->polling == 0) {
1512 		HDAC_WRITE_4(&sc->mem, HDAC_INTCTL,
1513 		    HDAC_INTCTL_CIE | HDAC_INTCTL_GIE);
1514 	}
1515 	DELAY(1000);
1516 
1517 	HDA_BOOTHVERBOSE(
1518 		device_printf(sc->dev, "Scanning HDA codecs ...\n");
1519 	);
1520 	statests = HDAC_READ_2(&sc->mem, HDAC_STATESTS);
1521 	hdac_unlock(sc);
1522 	for (i = 0; i < HDAC_CODEC_MAX; i++) {
1523 		if (HDAC_STATESTS_SDIWAKE(statests, i)) {
1524 			HDA_BOOTHVERBOSE(
1525 				device_printf(sc->dev,
1526 				    "Found CODEC at address %d\n", i);
1527 			);
1528 			hdac_lock(sc);
1529 			vendorid = hdac_send_command(sc, i,
1530 			    HDA_CMD_GET_PARAMETER(0, 0x0, HDA_PARAM_VENDOR_ID));
1531 			revisionid = hdac_send_command(sc, i,
1532 			    HDA_CMD_GET_PARAMETER(0, 0x0, HDA_PARAM_REVISION_ID));
1533 			hdac_unlock(sc);
1534 			if (vendorid == HDA_INVALID &&
1535 			    revisionid == HDA_INVALID) {
1536 				device_printf(sc->dev,
1537 				    "CODEC at address %d not responding!\n", i);
1538 				continue;
1539 			}
1540 			sc->codecs[i].vendor_id =
1541 			    HDA_PARAM_VENDOR_ID_VENDOR_ID(vendorid);
1542 			sc->codecs[i].device_id =
1543 			    HDA_PARAM_VENDOR_ID_DEVICE_ID(vendorid);
1544 			sc->codecs[i].revision_id =
1545 			    HDA_PARAM_REVISION_ID_REVISION_ID(revisionid);
1546 			sc->codecs[i].stepping_id =
1547 			    HDA_PARAM_REVISION_ID_STEPPING_ID(revisionid);
1548 			child = device_add_child(sc->dev, "hdacc", -1);
1549 			if (child == NULL) {
1550 				device_printf(sc->dev,
1551 				    "Failed to add CODEC device\n");
1552 				continue;
1553 			}
1554 			device_set_ivars(child, (void *)(intptr_t)i);
1555 			sc->codecs[i].dev = child;
1556 		}
1557 	}
1558 	bus_generic_attach(sc->dev);
1559 
1560 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1561 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO,
1562 	    "pindump", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, sc->dev,
1563 	    sizeof(sc->dev), sysctl_hdac_pindump, "I", "Dump pin states/data");
1564 	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1565 	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO,
1566 	    "polling", CTLTYPE_INT | CTLFLAG_RW | CTLFLAG_NEEDGIANT, sc->dev,
1567 	    sizeof(sc->dev), sysctl_hdac_polling, "I", "Enable polling mode");
1568 }
1569 
1570 /****************************************************************************
1571  * int hdac_suspend(device_t)
1572  *
1573  * Suspend and power down HDA bus and codecs.
1574  ****************************************************************************/
1575 static int
1576 hdac_suspend(device_t dev)
1577 {
1578 	struct hdac_softc *sc = device_get_softc(dev);
1579 
1580 	HDA_BOOTHVERBOSE(
1581 		device_printf(dev, "Suspend...\n");
1582 	);
1583 	bus_generic_suspend(dev);
1584 
1585 	hdac_lock(sc);
1586 	HDA_BOOTHVERBOSE(
1587 		device_printf(dev, "Reset controller...\n");
1588 	);
1589 	callout_stop(&sc->poll_callout);
1590 	hdac_reset(sc, false);
1591 	hdac_unlock(sc);
1592 	callout_drain(&sc->poll_callout);
1593 	taskqueue_drain(taskqueue_thread, &sc->unsolq_task);
1594 	HDA_BOOTHVERBOSE(
1595 		device_printf(dev, "Suspend done\n");
1596 	);
1597 	return (0);
1598 }
1599 
1600 /****************************************************************************
1601  * int hdac_resume(device_t)
1602  *
1603  * Powerup and restore HDA bus and codecs state.
1604  ****************************************************************************/
1605 static int
1606 hdac_resume(device_t dev)
1607 {
1608 	struct hdac_softc *sc = device_get_softc(dev);
1609 	int error;
1610 
1611 	HDA_BOOTHVERBOSE(
1612 		device_printf(dev, "Resume...\n");
1613 	);
1614 	hdac_lock(sc);
1615 
1616 	/* Quiesce everything */
1617 	HDA_BOOTHVERBOSE(
1618 		device_printf(dev, "Reset controller...\n");
1619 	);
1620 	hdac_reset(sc, true);
1621 
1622 	/* Initialize the CORB and RIRB */
1623 	hdac_corb_init(sc);
1624 	hdac_rirb_init(sc);
1625 
1626 	HDA_BOOTHVERBOSE(
1627 		device_printf(dev, "Starting CORB Engine...\n");
1628 	);
1629 	hdac_corb_start(sc);
1630 	HDA_BOOTHVERBOSE(
1631 		device_printf(dev, "Starting RIRB Engine...\n");
1632 	);
1633 	hdac_rirb_start(sc);
1634 	HDA_BOOTHVERBOSE(
1635 		device_printf(dev, "Enabling controller interrupt...\n");
1636 	);
1637 	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, HDAC_READ_4(&sc->mem, HDAC_GCTL) |
1638 	    HDAC_GCTL_UNSOL);
1639 	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, HDAC_INTCTL_CIE | HDAC_INTCTL_GIE);
1640 	DELAY(1000);
1641 	hdac_poll_reinit(sc);
1642 	hdac_unlock(sc);
1643 
1644 	error = bus_generic_resume(dev);
1645 	HDA_BOOTHVERBOSE(
1646 		device_printf(dev, "Resume done\n");
1647 	);
1648 	return (error);
1649 }
1650 
1651 /****************************************************************************
1652  * int hdac_detach(device_t)
1653  *
1654  * Detach and free up resources utilized by the hdac device.
1655  ****************************************************************************/
1656 static int
1657 hdac_detach(device_t dev)
1658 {
1659 	struct hdac_softc *sc = device_get_softc(dev);
1660 	device_t *devlist;
1661 	int cad, i, devcount, error;
1662 
1663 	if ((error = device_get_children(dev, &devlist, &devcount)) != 0)
1664 		return (error);
1665 	for (i = 0; i < devcount; i++) {
1666 		cad = (intptr_t)device_get_ivars(devlist[i]);
1667 		if ((error = device_delete_child(dev, devlist[i])) != 0) {
1668 			free(devlist, M_TEMP);
1669 			return (error);
1670 		}
1671 		sc->codecs[cad].dev = NULL;
1672 	}
1673 	free(devlist, M_TEMP);
1674 
1675 	hdac_lock(sc);
1676 	hdac_reset(sc, false);
1677 	hdac_unlock(sc);
1678 	taskqueue_drain(taskqueue_thread, &sc->unsolq_task);
1679 	hdac_irq_free(sc);
1680 
1681 	for (i = 0; i < sc->num_ss; i++)
1682 		hdac_dma_free(sc, &sc->streams[i].bdl);
1683 	free(sc->streams, M_HDAC);
1684 	hdac_dma_free(sc, &sc->pos_dma);
1685 	hdac_dma_free(sc, &sc->rirb_dma);
1686 	hdac_dma_free(sc, &sc->corb_dma);
1687 	if (sc->chan_dmat != NULL) {
1688 		bus_dma_tag_destroy(sc->chan_dmat);
1689 		sc->chan_dmat = NULL;
1690 	}
1691 	hdac_mem_free(sc);
1692 	snd_mtxfree(sc->lock);
1693 	return (0);
1694 }
1695 
1696 static bus_dma_tag_t
1697 hdac_get_dma_tag(device_t dev, device_t child)
1698 {
1699 	struct hdac_softc *sc = device_get_softc(dev);
1700 
1701 	return (sc->chan_dmat);
1702 }
1703 
1704 static int
1705 hdac_print_child(device_t dev, device_t child)
1706 {
1707 	int retval;
1708 
1709 	retval = bus_print_child_header(dev, child);
1710 	retval += printf(" at cad %d", (int)(intptr_t)device_get_ivars(child));
1711 	retval += bus_print_child_footer(dev, child);
1712 
1713 	return (retval);
1714 }
1715 
1716 static int
1717 hdac_child_location_str(device_t dev, device_t child, char *buf, size_t buflen)
1718 {
1719 
1720 	snprintf(buf, buflen, "cad=%d", (int)(intptr_t)device_get_ivars(child));
1721 	return (0);
1722 }
1723 
1724 static int
1725 hdac_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
1726     size_t buflen)
1727 {
1728 	struct hdac_softc *sc = device_get_softc(dev);
1729 	nid_t cad = (uintptr_t)device_get_ivars(child);
1730 
1731 	snprintf(buf, buflen,
1732 	    "vendor=0x%04x device=0x%04x revision=0x%02x stepping=0x%02x",
1733 	    sc->codecs[cad].vendor_id, sc->codecs[cad].device_id,
1734 	    sc->codecs[cad].revision_id, sc->codecs[cad].stepping_id);
1735 	return (0);
1736 }
1737 
1738 static int
1739 hdac_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1740 {
1741 	struct hdac_softc *sc = device_get_softc(dev);
1742 	nid_t cad = (uintptr_t)device_get_ivars(child);
1743 
1744 	switch (which) {
1745 	case HDA_IVAR_CODEC_ID:
1746 		*result = cad;
1747 		break;
1748 	case HDA_IVAR_VENDOR_ID:
1749 		*result = sc->codecs[cad].vendor_id;
1750 		break;
1751 	case HDA_IVAR_DEVICE_ID:
1752 		*result = sc->codecs[cad].device_id;
1753 		break;
1754 	case HDA_IVAR_REVISION_ID:
1755 		*result = sc->codecs[cad].revision_id;
1756 		break;
1757 	case HDA_IVAR_STEPPING_ID:
1758 		*result = sc->codecs[cad].stepping_id;
1759 		break;
1760 	case HDA_IVAR_SUBVENDOR_ID:
1761 		*result = pci_get_subvendor(dev);
1762 		break;
1763 	case HDA_IVAR_SUBDEVICE_ID:
1764 		*result = pci_get_subdevice(dev);
1765 		break;
1766 	case HDA_IVAR_DMA_NOCACHE:
1767 		*result = (sc->flags & HDAC_F_DMA_NOCACHE) != 0;
1768 		break;
1769 	case HDA_IVAR_STRIPES_MASK:
1770 		*result = (1 << (1 << sc->num_sdo)) - 1;
1771 		break;
1772 	default:
1773 		return (ENOENT);
1774 	}
1775 	return (0);
1776 }
1777 
1778 static struct mtx *
1779 hdac_get_mtx(device_t dev, device_t child)
1780 {
1781 	struct hdac_softc *sc = device_get_softc(dev);
1782 
1783 	return (sc->lock);
1784 }
1785 
1786 static uint32_t
1787 hdac_codec_command(device_t dev, device_t child, uint32_t verb)
1788 {
1789 
1790 	return (hdac_send_command(device_get_softc(dev),
1791 	    (intptr_t)device_get_ivars(child), verb));
1792 }
1793 
1794 static int
1795 hdac_find_stream(struct hdac_softc *sc, int dir, int stream)
1796 {
1797 	int i, ss;
1798 
1799 	ss = -1;
1800 	/* Allocate ISS/OSS first. */
1801 	if (dir == 0) {
1802 		for (i = 0; i < sc->num_iss; i++) {
1803 			if (sc->streams[i].stream == stream) {
1804 				ss = i;
1805 				break;
1806 			}
1807 		}
1808 	} else {
1809 		for (i = 0; i < sc->num_oss; i++) {
1810 			if (sc->streams[i + sc->num_iss].stream == stream) {
1811 				ss = i + sc->num_iss;
1812 				break;
1813 			}
1814 		}
1815 	}
1816 	/* Fallback to BSS. */
1817 	if (ss == -1) {
1818 		for (i = 0; i < sc->num_bss; i++) {
1819 			if (sc->streams[i + sc->num_iss + sc->num_oss].stream
1820 			    == stream) {
1821 				ss = i + sc->num_iss + sc->num_oss;
1822 				break;
1823 			}
1824 		}
1825 	}
1826 	return (ss);
1827 }
1828 
1829 static int
1830 hdac_stream_alloc(device_t dev, device_t child, int dir, int format, int stripe,
1831     uint32_t **dmapos)
1832 {
1833 	struct hdac_softc *sc = device_get_softc(dev);
1834 	nid_t cad = (uintptr_t)device_get_ivars(child);
1835 	int stream, ss, bw, maxbw, prevbw;
1836 
1837 	/* Look for empty stream. */
1838 	ss = hdac_find_stream(sc, dir, 0);
1839 
1840 	/* Return if found nothing. */
1841 	if (ss < 0)
1842 		return (0);
1843 
1844 	/* Check bus bandwidth. */
1845 	bw = hdac_bdata_rate(format, dir);
1846 	if (dir == 1) {
1847 		bw *= 1 << (sc->num_sdo - stripe);
1848 		prevbw = sc->sdo_bw_used;
1849 		maxbw = 48000 * 960 * (1 << sc->num_sdo);
1850 	} else {
1851 		prevbw = sc->codecs[cad].sdi_bw_used;
1852 		maxbw = 48000 * 464;
1853 	}
1854 	HDA_BOOTHVERBOSE(
1855 		device_printf(dev, "%dKbps of %dKbps bandwidth used%s\n",
1856 		    (bw + prevbw) / 1000, maxbw / 1000,
1857 		    bw + prevbw > maxbw ? " -- OVERFLOW!" : "");
1858 	);
1859 	if (bw + prevbw > maxbw)
1860 		return (0);
1861 	if (dir == 1)
1862 		sc->sdo_bw_used += bw;
1863 	else
1864 		sc->codecs[cad].sdi_bw_used += bw;
1865 
1866 	/* Allocate stream number */
1867 	if (ss >= sc->num_iss + sc->num_oss)
1868 		stream = 15 - (ss - sc->num_iss - sc->num_oss);
1869 	else if (ss >= sc->num_iss)
1870 		stream = ss - sc->num_iss + 1;
1871 	else
1872 		stream = ss + 1;
1873 
1874 	sc->streams[ss].dev = child;
1875 	sc->streams[ss].dir = dir;
1876 	sc->streams[ss].stream = stream;
1877 	sc->streams[ss].bw = bw;
1878 	sc->streams[ss].format = format;
1879 	sc->streams[ss].stripe = stripe;
1880 	if (dmapos != NULL) {
1881 		if (sc->pos_dma.dma_vaddr != NULL)
1882 			*dmapos = (uint32_t *)(sc->pos_dma.dma_vaddr + ss * 8);
1883 		else
1884 			*dmapos = NULL;
1885 	}
1886 	return (stream);
1887 }
1888 
1889 static void
1890 hdac_stream_free(device_t dev, device_t child, int dir, int stream)
1891 {
1892 	struct hdac_softc *sc = device_get_softc(dev);
1893 	nid_t cad = (uintptr_t)device_get_ivars(child);
1894 	int ss;
1895 
1896 	ss = hdac_find_stream(sc, dir, stream);
1897 	KASSERT(ss >= 0,
1898 	    ("Free for not allocated stream (%d/%d)\n", dir, stream));
1899 	if (dir == 1)
1900 		sc->sdo_bw_used -= sc->streams[ss].bw;
1901 	else
1902 		sc->codecs[cad].sdi_bw_used -= sc->streams[ss].bw;
1903 	sc->streams[ss].stream = 0;
1904 	sc->streams[ss].dev = NULL;
1905 }
1906 
1907 static int
1908 hdac_stream_start(device_t dev, device_t child, int dir, int stream,
1909     bus_addr_t buf, int blksz, int blkcnt)
1910 {
1911 	struct hdac_softc *sc = device_get_softc(dev);
1912 	struct hdac_bdle *bdle;
1913 	uint64_t addr;
1914 	int i, ss, off;
1915 	uint32_t ctl;
1916 
1917 	ss = hdac_find_stream(sc, dir, stream);
1918 	KASSERT(ss >= 0,
1919 	    ("Start for not allocated stream (%d/%d)\n", dir, stream));
1920 
1921 	addr = (uint64_t)buf;
1922 	bdle = (struct hdac_bdle *)sc->streams[ss].bdl.dma_vaddr;
1923 	for (i = 0; i < blkcnt; i++, bdle++) {
1924 		bdle->addrl = htole32((uint32_t)addr);
1925 		bdle->addrh = htole32((uint32_t)(addr >> 32));
1926 		bdle->len = htole32(blksz);
1927 		bdle->ioc = htole32(1);
1928 		addr += blksz;
1929 	}
1930 
1931 	bus_dmamap_sync(sc->streams[ss].bdl.dma_tag,
1932 	    sc->streams[ss].bdl.dma_map, BUS_DMASYNC_PREWRITE);
1933 
1934 	off = ss << 5;
1935 	HDAC_WRITE_4(&sc->mem, off + HDAC_SDCBL, blksz * blkcnt);
1936 	HDAC_WRITE_2(&sc->mem, off + HDAC_SDLVI, blkcnt - 1);
1937 	addr = sc->streams[ss].bdl.dma_paddr;
1938 	HDAC_WRITE_4(&sc->mem, off + HDAC_SDBDPL, (uint32_t)addr);
1939 	HDAC_WRITE_4(&sc->mem, off + HDAC_SDBDPU, (uint32_t)(addr >> 32));
1940 
1941 	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL2);
1942 	if (dir)
1943 		ctl |= HDAC_SDCTL2_DIR;
1944 	else
1945 		ctl &= ~HDAC_SDCTL2_DIR;
1946 	ctl &= ~HDAC_SDCTL2_STRM_MASK;
1947 	ctl |= stream << HDAC_SDCTL2_STRM_SHIFT;
1948 	ctl &= ~HDAC_SDCTL2_STRIPE_MASK;
1949 	ctl |= sc->streams[ss].stripe << HDAC_SDCTL2_STRIPE_SHIFT;
1950 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL2, ctl);
1951 
1952 	HDAC_WRITE_2(&sc->mem, off + HDAC_SDFMT, sc->streams[ss].format);
1953 
1954 	ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1955 	ctl |= 1 << ss;
1956 	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1957 
1958 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDSTS,
1959 	    HDAC_SDSTS_DESE | HDAC_SDSTS_FIFOE | HDAC_SDSTS_BCIS);
1960 	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
1961 	ctl |= HDAC_SDCTL_IOCE | HDAC_SDCTL_FEIE | HDAC_SDCTL_DEIE |
1962 	    HDAC_SDCTL_RUN;
1963 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
1964 
1965 	sc->streams[ss].blksz = blksz;
1966 	sc->streams[ss].running = 1;
1967 	hdac_poll_reinit(sc);
1968 	return (0);
1969 }
1970 
1971 static void
1972 hdac_stream_stop(device_t dev, device_t child, int dir, int stream)
1973 {
1974 	struct hdac_softc *sc = device_get_softc(dev);
1975 	int ss, off;
1976 	uint32_t ctl;
1977 
1978 	ss = hdac_find_stream(sc, dir, stream);
1979 	KASSERT(ss >= 0,
1980 	    ("Stop for not allocated stream (%d/%d)\n", dir, stream));
1981 
1982 	bus_dmamap_sync(sc->streams[ss].bdl.dma_tag,
1983 	    sc->streams[ss].bdl.dma_map, BUS_DMASYNC_POSTWRITE);
1984 
1985 	off = ss << 5;
1986 	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
1987 	ctl &= ~(HDAC_SDCTL_IOCE | HDAC_SDCTL_FEIE | HDAC_SDCTL_DEIE |
1988 	    HDAC_SDCTL_RUN);
1989 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
1990 
1991 	ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1992 	ctl &= ~(1 << ss);
1993 	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1994 
1995 	sc->streams[ss].running = 0;
1996 	hdac_poll_reinit(sc);
1997 }
1998 
1999 static void
2000 hdac_stream_reset(device_t dev, device_t child, int dir, int stream)
2001 {
2002 	struct hdac_softc *sc = device_get_softc(dev);
2003 	int timeout = 1000;
2004 	int to = timeout;
2005 	int ss, off;
2006 	uint32_t ctl;
2007 
2008 	ss = hdac_find_stream(sc, dir, stream);
2009 	KASSERT(ss >= 0,
2010 	    ("Reset for not allocated stream (%d/%d)\n", dir, stream));
2011 
2012 	off = ss << 5;
2013 	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
2014 	ctl |= HDAC_SDCTL_SRST;
2015 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
2016 	do {
2017 		ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
2018 		if (ctl & HDAC_SDCTL_SRST)
2019 			break;
2020 		DELAY(10);
2021 	} while (--to);
2022 	if (!(ctl & HDAC_SDCTL_SRST))
2023 		device_printf(dev, "Reset setting timeout\n");
2024 	ctl &= ~HDAC_SDCTL_SRST;
2025 	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
2026 	to = timeout;
2027 	do {
2028 		ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
2029 		if (!(ctl & HDAC_SDCTL_SRST))
2030 			break;
2031 		DELAY(10);
2032 	} while (--to);
2033 	if (ctl & HDAC_SDCTL_SRST)
2034 		device_printf(dev, "Reset timeout!\n");
2035 }
2036 
2037 static uint32_t
2038 hdac_stream_getptr(device_t dev, device_t child, int dir, int stream)
2039 {
2040 	struct hdac_softc *sc = device_get_softc(dev);
2041 	int ss, off;
2042 
2043 	ss = hdac_find_stream(sc, dir, stream);
2044 	KASSERT(ss >= 0,
2045 	    ("Reset for not allocated stream (%d/%d)\n", dir, stream));
2046 
2047 	off = ss << 5;
2048 	return (HDAC_READ_4(&sc->mem, off + HDAC_SDLPIB));
2049 }
2050 
2051 static int
2052 hdac_unsol_alloc(device_t dev, device_t child, int tag)
2053 {
2054 	struct hdac_softc *sc = device_get_softc(dev);
2055 
2056 	sc->unsol_registered++;
2057 	hdac_poll_reinit(sc);
2058 	return (tag);
2059 }
2060 
2061 static void
2062 hdac_unsol_free(device_t dev, device_t child, int tag)
2063 {
2064 	struct hdac_softc *sc = device_get_softc(dev);
2065 
2066 	sc->unsol_registered--;
2067 	hdac_poll_reinit(sc);
2068 }
2069 
2070 static device_method_t hdac_methods[] = {
2071 	/* device interface */
2072 	DEVMETHOD(device_probe,		hdac_probe),
2073 	DEVMETHOD(device_attach,	hdac_attach),
2074 	DEVMETHOD(device_detach,	hdac_detach),
2075 	DEVMETHOD(device_suspend,	hdac_suspend),
2076 	DEVMETHOD(device_resume,	hdac_resume),
2077 	/* Bus interface */
2078 	DEVMETHOD(bus_get_dma_tag,	hdac_get_dma_tag),
2079 	DEVMETHOD(bus_print_child,	hdac_print_child),
2080 	DEVMETHOD(bus_child_location_str, hdac_child_location_str),
2081 	DEVMETHOD(bus_child_pnpinfo_str, hdac_child_pnpinfo_str_method),
2082 	DEVMETHOD(bus_read_ivar,	hdac_read_ivar),
2083 	DEVMETHOD(hdac_get_mtx,		hdac_get_mtx),
2084 	DEVMETHOD(hdac_codec_command,	hdac_codec_command),
2085 	DEVMETHOD(hdac_stream_alloc,	hdac_stream_alloc),
2086 	DEVMETHOD(hdac_stream_free,	hdac_stream_free),
2087 	DEVMETHOD(hdac_stream_start,	hdac_stream_start),
2088 	DEVMETHOD(hdac_stream_stop,	hdac_stream_stop),
2089 	DEVMETHOD(hdac_stream_reset,	hdac_stream_reset),
2090 	DEVMETHOD(hdac_stream_getptr,	hdac_stream_getptr),
2091 	DEVMETHOD(hdac_unsol_alloc,	hdac_unsol_alloc),
2092 	DEVMETHOD(hdac_unsol_free,	hdac_unsol_free),
2093 	DEVMETHOD_END
2094 };
2095 
2096 static driver_t hdac_driver = {
2097 	"hdac",
2098 	hdac_methods,
2099 	sizeof(struct hdac_softc),
2100 };
2101 
2102 static devclass_t hdac_devclass;
2103 
2104 DRIVER_MODULE(snd_hda, pci, hdac_driver, hdac_devclass, NULL, NULL);
2105