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