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