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