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