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