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