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