hdac.c revision 275101
1/*-
2 * Copyright (c) 2006 Stephane E. Potvin <sepotvin@videotron.ca>
3 * Copyright (c) 2006 Ariff Abdullah <ariff@FreeBSD.org>
4 * Copyright (c) 2008-2012 Alexander Motin <mav@FreeBSD.org>
5 * All rights reserved.
6 *
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 *    notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 *    notice, this list of conditions and the following disclaimer in the
14 *    documentation and/or other materials provided with the distribution.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26 * SUCH DAMAGE.
27 */
28
29/*
30 * Intel High Definition Audio (Controller) driver for FreeBSD.
31 */
32
33#ifdef HAVE_KERNEL_OPTION_HEADERS
34#include "opt_snd.h"
35#endif
36
37#include <dev/sound/pcm/sound.h>
38#include <dev/pci/pcireg.h>
39#include <dev/pci/pcivar.h>
40
41#include <sys/ctype.h>
42#include <sys/taskqueue.h>
43
44#include <dev/sound/pci/hda/hdac_private.h>
45#include <dev/sound/pci/hda/hdac_reg.h>
46#include <dev/sound/pci/hda/hda_reg.h>
47#include <dev/sound/pci/hda/hdac.h>
48
49#define HDA_DRV_TEST_REV	"20120126_0002"
50
51SND_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)	mtx_owned((sc)->lock)
57
58#define HDAC_QUIRK_64BIT	(1 << 0)
59#define HDAC_QUIRK_DMAPOS	(1 << 1)
60#define HDAC_QUIRK_MSI		(1 << 2)
61
62static 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
71MALLOC_DEFINE(M_HDAC, "hdac", "HDA Controller");
72
73static 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
173static 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 ****************************************************************************/
187static void	hdac_intr_handler(void *);
188static int	hdac_reset(struct hdac_softc *, int);
189static int	hdac_get_capabilities(struct hdac_softc *);
190static void	hdac_dma_cb(void *, bus_dma_segment_t *, int, int);
191static int	hdac_dma_alloc(struct hdac_softc *,
192					struct hdac_dma *, bus_size_t);
193static void	hdac_dma_free(struct hdac_softc *, struct hdac_dma *);
194static int	hdac_mem_alloc(struct hdac_softc *);
195static void	hdac_mem_free(struct hdac_softc *);
196static int	hdac_irq_alloc(struct hdac_softc *);
197static void	hdac_irq_free(struct hdac_softc *);
198static void	hdac_corb_init(struct hdac_softc *);
199static void	hdac_rirb_init(struct hdac_softc *);
200static void	hdac_corb_start(struct hdac_softc *);
201static void	hdac_rirb_start(struct hdac_softc *);
202
203static void	hdac_attach2(void *);
204
205static uint32_t	hdac_send_command(struct hdac_softc *, nid_t, uint32_t);
206
207static int	hdac_probe(device_t);
208static int	hdac_attach(device_t);
209static int	hdac_detach(device_t);
210static int	hdac_suspend(device_t);
211static int	hdac_resume(device_t);
212
213static int	hdac_rirb_flush(struct hdac_softc *sc);
214static 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. */
220static void
221hdac_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				printf("\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				printf(" %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 ****************************************************************************/
281static void
282hdac_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, &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
331static void
332hdac_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 ****************************************************************************/
356static int
357hdac_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 ****************************************************************************/
443static int
444hdac_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 ****************************************************************************/
512static void
513hdac_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 ****************************************************************************/
530static int
531hdac_dma_alloc(struct hdac_softc *sc, struct hdac_dma *dma, bus_size_t size)
532{
533	bus_size_t roundsz;
534	int result;
535
536	roundsz = roundup2(size, HDA_DMA_ALIGNMENT);
537	bzero(dma, sizeof(*dma));
538
539	/*
540	 * Create a DMA tag
541	 */
542	result = bus_dma_tag_create(
543	    bus_get_dma_tag(sc->dev),		/* parent */
544	    HDA_DMA_ALIGNMENT,			/* alignment */
545	    0,					/* boundary */
546	    (sc->support_64bit) ? BUS_SPACE_MAXADDR :
547		BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
548	    BUS_SPACE_MAXADDR,			/* highaddr */
549	    NULL,				/* filtfunc */
550	    NULL,				/* fistfuncarg */
551	    roundsz, 				/* maxsize */
552	    1,					/* nsegments */
553	    roundsz, 				/* maxsegsz */
554	    0,					/* flags */
555	    NULL,				/* lockfunc */
556	    NULL,				/* lockfuncarg */
557	    &dma->dma_tag);			/* dmat */
558	if (result != 0) {
559		device_printf(sc->dev, "%s: bus_dma_tag_create failed (%x)\n",
560		    __func__, result);
561		goto hdac_dma_alloc_fail;
562	}
563
564	/*
565	 * Allocate DMA memory
566	 */
567	result = bus_dmamem_alloc(dma->dma_tag, (void **)&dma->dma_vaddr,
568	    BUS_DMA_NOWAIT | BUS_DMA_ZERO |
569	    ((sc->flags & HDAC_F_DMA_NOCACHE) ? BUS_DMA_NOCACHE : 0),
570	    &dma->dma_map);
571	if (result != 0) {
572		device_printf(sc->dev, "%s: bus_dmamem_alloc failed (%x)\n",
573		    __func__, result);
574		goto hdac_dma_alloc_fail;
575	}
576
577	dma->dma_size = roundsz;
578
579	/*
580	 * Map the memory
581	 */
582	result = bus_dmamap_load(dma->dma_tag, dma->dma_map,
583	    (void *)dma->dma_vaddr, roundsz, hdac_dma_cb, (void *)dma, 0);
584	if (result != 0 || dma->dma_paddr == 0) {
585		if (result == 0)
586			result = ENOMEM;
587		device_printf(sc->dev, "%s: bus_dmamem_load failed (%x)\n",
588		    __func__, result);
589		goto hdac_dma_alloc_fail;
590	}
591
592	HDA_BOOTHVERBOSE(
593		device_printf(sc->dev, "%s: size=%ju -> roundsz=%ju\n",
594		    __func__, (uintmax_t)size, (uintmax_t)roundsz);
595	);
596
597	return (0);
598
599hdac_dma_alloc_fail:
600	hdac_dma_free(sc, dma);
601
602	return (result);
603}
604
605
606/****************************************************************************
607 * void hdac_dma_free(struct hdac_softc *, struct hdac_dma *)
608 *
609 * Free a struct dhac_dma that has been previously allocated via the
610 * hdac_dma_alloc function.
611 ****************************************************************************/
612static void
613hdac_dma_free(struct hdac_softc *sc, struct hdac_dma *dma)
614{
615	if (dma->dma_paddr != 0) {
616#if 0
617		/* Flush caches */
618		bus_dmamap_sync(dma->dma_tag, dma->dma_map,
619		    BUS_DMASYNC_POSTREAD | BUS_DMASYNC_POSTWRITE);
620#endif
621		bus_dmamap_unload(dma->dma_tag, dma->dma_map);
622		dma->dma_paddr = 0;
623	}
624	if (dma->dma_vaddr != NULL) {
625		bus_dmamem_free(dma->dma_tag, dma->dma_vaddr, dma->dma_map);
626		dma->dma_vaddr = NULL;
627	}
628	if (dma->dma_tag != NULL) {
629		bus_dma_tag_destroy(dma->dma_tag);
630		dma->dma_tag = NULL;
631	}
632	dma->dma_size = 0;
633}
634
635/****************************************************************************
636 * int hdac_mem_alloc(struct hdac_softc *)
637 *
638 * Allocate all the bus resources necessary to speak with the physical
639 * controller.
640 ****************************************************************************/
641static int
642hdac_mem_alloc(struct hdac_softc *sc)
643{
644	struct hdac_mem *mem;
645
646	mem = &sc->mem;
647	mem->mem_rid = PCIR_BAR(0);
648	mem->mem_res = bus_alloc_resource_any(sc->dev, SYS_RES_MEMORY,
649	    &mem->mem_rid, RF_ACTIVE);
650	if (mem->mem_res == NULL) {
651		device_printf(sc->dev,
652		    "%s: Unable to allocate memory resource\n", __func__);
653		return (ENOMEM);
654	}
655	mem->mem_tag = rman_get_bustag(mem->mem_res);
656	mem->mem_handle = rman_get_bushandle(mem->mem_res);
657
658	return (0);
659}
660
661/****************************************************************************
662 * void hdac_mem_free(struct hdac_softc *)
663 *
664 * Free up resources previously allocated by hdac_mem_alloc.
665 ****************************************************************************/
666static void
667hdac_mem_free(struct hdac_softc *sc)
668{
669	struct hdac_mem *mem;
670
671	mem = &sc->mem;
672	if (mem->mem_res != NULL)
673		bus_release_resource(sc->dev, SYS_RES_MEMORY, mem->mem_rid,
674		    mem->mem_res);
675	mem->mem_res = NULL;
676}
677
678/****************************************************************************
679 * int hdac_irq_alloc(struct hdac_softc *)
680 *
681 * Allocate and setup the resources necessary for interrupt handling.
682 ****************************************************************************/
683static int
684hdac_irq_alloc(struct hdac_softc *sc)
685{
686	struct hdac_irq *irq;
687	int result;
688
689	irq = &sc->irq;
690	irq->irq_rid = 0x0;
691
692	if ((sc->quirks_off & HDAC_QUIRK_MSI) == 0 &&
693	    (result = pci_msi_count(sc->dev)) == 1 &&
694	    pci_alloc_msi(sc->dev, &result) == 0)
695		irq->irq_rid = 0x1;
696
697	irq->irq_res = bus_alloc_resource_any(sc->dev, SYS_RES_IRQ,
698	    &irq->irq_rid, RF_SHAREABLE | RF_ACTIVE);
699	if (irq->irq_res == NULL) {
700		device_printf(sc->dev, "%s: Unable to allocate irq\n",
701		    __func__);
702		goto hdac_irq_alloc_fail;
703	}
704	result = bus_setup_intr(sc->dev, irq->irq_res, INTR_MPSAFE | INTR_TYPE_AV,
705	    NULL, hdac_intr_handler, sc, &irq->irq_handle);
706	if (result != 0) {
707		device_printf(sc->dev,
708		    "%s: Unable to setup interrupt handler (%x)\n",
709		    __func__, result);
710		goto hdac_irq_alloc_fail;
711	}
712
713	return (0);
714
715hdac_irq_alloc_fail:
716	hdac_irq_free(sc);
717
718	return (ENXIO);
719}
720
721/****************************************************************************
722 * void hdac_irq_free(struct hdac_softc *)
723 *
724 * Free up resources previously allocated by hdac_irq_alloc.
725 ****************************************************************************/
726static void
727hdac_irq_free(struct hdac_softc *sc)
728{
729	struct hdac_irq *irq;
730
731	irq = &sc->irq;
732	if (irq->irq_res != NULL && irq->irq_handle != NULL)
733		bus_teardown_intr(sc->dev, irq->irq_res, irq->irq_handle);
734	if (irq->irq_res != NULL)
735		bus_release_resource(sc->dev, SYS_RES_IRQ, irq->irq_rid,
736		    irq->irq_res);
737	if (irq->irq_rid == 0x1)
738		pci_release_msi(sc->dev);
739	irq->irq_handle = NULL;
740	irq->irq_res = NULL;
741	irq->irq_rid = 0x0;
742}
743
744/****************************************************************************
745 * void hdac_corb_init(struct hdac_softc *)
746 *
747 * Initialize the corb registers for operations but do not start it up yet.
748 * The CORB engine must not be running when this function is called.
749 ****************************************************************************/
750static void
751hdac_corb_init(struct hdac_softc *sc)
752{
753	uint8_t corbsize;
754	uint64_t corbpaddr;
755
756	/* Setup the CORB size. */
757	switch (sc->corb_size) {
758	case 256:
759		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_256);
760		break;
761	case 16:
762		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_16);
763		break;
764	case 2:
765		corbsize = HDAC_CORBSIZE_CORBSIZE(HDAC_CORBSIZE_CORBSIZE_2);
766		break;
767	default:
768		panic("%s: Invalid CORB size (%x)\n", __func__, sc->corb_size);
769	}
770	HDAC_WRITE_1(&sc->mem, HDAC_CORBSIZE, corbsize);
771
772	/* Setup the CORB Address in the hdac */
773	corbpaddr = (uint64_t)sc->corb_dma.dma_paddr;
774	HDAC_WRITE_4(&sc->mem, HDAC_CORBLBASE, (uint32_t)corbpaddr);
775	HDAC_WRITE_4(&sc->mem, HDAC_CORBUBASE, (uint32_t)(corbpaddr >> 32));
776
777	/* Set the WP and RP */
778	sc->corb_wp = 0;
779	HDAC_WRITE_2(&sc->mem, HDAC_CORBWP, sc->corb_wp);
780	HDAC_WRITE_2(&sc->mem, HDAC_CORBRP, HDAC_CORBRP_CORBRPRST);
781	/*
782	 * The HDA specification indicates that the CORBRPRST bit will always
783	 * read as zero. Unfortunately, it seems that at least the 82801G
784	 * doesn't reset the bit to zero, which stalls the corb engine.
785	 * manually reset the bit to zero before continuing.
786	 */
787	HDAC_WRITE_2(&sc->mem, HDAC_CORBRP, 0x0);
788
789	/* Enable CORB error reporting */
790#if 0
791	HDAC_WRITE_1(&sc->mem, HDAC_CORBCTL, HDAC_CORBCTL_CMEIE);
792#endif
793}
794
795/****************************************************************************
796 * void hdac_rirb_init(struct hdac_softc *)
797 *
798 * Initialize the rirb registers for operations but do not start it up yet.
799 * The RIRB engine must not be running when this function is called.
800 ****************************************************************************/
801static void
802hdac_rirb_init(struct hdac_softc *sc)
803{
804	uint8_t rirbsize;
805	uint64_t rirbpaddr;
806
807	/* Setup the RIRB size. */
808	switch (sc->rirb_size) {
809	case 256:
810		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_256);
811		break;
812	case 16:
813		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_16);
814		break;
815	case 2:
816		rirbsize = HDAC_RIRBSIZE_RIRBSIZE(HDAC_RIRBSIZE_RIRBSIZE_2);
817		break;
818	default:
819		panic("%s: Invalid RIRB size (%x)\n", __func__, sc->rirb_size);
820	}
821	HDAC_WRITE_1(&sc->mem, HDAC_RIRBSIZE, rirbsize);
822
823	/* Setup the RIRB Address in the hdac */
824	rirbpaddr = (uint64_t)sc->rirb_dma.dma_paddr;
825	HDAC_WRITE_4(&sc->mem, HDAC_RIRBLBASE, (uint32_t)rirbpaddr);
826	HDAC_WRITE_4(&sc->mem, HDAC_RIRBUBASE, (uint32_t)(rirbpaddr >> 32));
827
828	/* Setup the WP and RP */
829	sc->rirb_rp = 0;
830	HDAC_WRITE_2(&sc->mem, HDAC_RIRBWP, HDAC_RIRBWP_RIRBWPRST);
831
832	/* Setup the interrupt threshold */
833	HDAC_WRITE_2(&sc->mem, HDAC_RINTCNT, sc->rirb_size / 2);
834
835	/* Enable Overrun and response received reporting */
836#if 0
837	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL,
838	    HDAC_RIRBCTL_RIRBOIC | HDAC_RIRBCTL_RINTCTL);
839#else
840	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL, HDAC_RIRBCTL_RINTCTL);
841#endif
842
843#if 0
844	/*
845	 * Make sure that the Host CPU cache doesn't contain any dirty
846	 * cache lines that falls in the rirb. If I understood correctly, it
847	 * should be sufficient to do this only once as the rirb is purely
848	 * read-only from now on.
849	 */
850	bus_dmamap_sync(sc->rirb_dma.dma_tag, sc->rirb_dma.dma_map,
851	    BUS_DMASYNC_PREREAD);
852#endif
853}
854
855/****************************************************************************
856 * void hdac_corb_start(hdac_softc *)
857 *
858 * Startup the corb DMA engine
859 ****************************************************************************/
860static void
861hdac_corb_start(struct hdac_softc *sc)
862{
863	uint32_t corbctl;
864
865	corbctl = HDAC_READ_1(&sc->mem, HDAC_CORBCTL);
866	corbctl |= HDAC_CORBCTL_CORBRUN;
867	HDAC_WRITE_1(&sc->mem, HDAC_CORBCTL, corbctl);
868}
869
870/****************************************************************************
871 * void hdac_rirb_start(hdac_softc *)
872 *
873 * Startup the rirb DMA engine
874 ****************************************************************************/
875static void
876hdac_rirb_start(struct hdac_softc *sc)
877{
878	uint32_t rirbctl;
879
880	rirbctl = HDAC_READ_1(&sc->mem, HDAC_RIRBCTL);
881	rirbctl |= HDAC_RIRBCTL_RIRBDMAEN;
882	HDAC_WRITE_1(&sc->mem, HDAC_RIRBCTL, rirbctl);
883}
884
885static int
886hdac_rirb_flush(struct hdac_softc *sc)
887{
888	struct hdac_rirb *rirb_base, *rirb;
889	nid_t cad;
890	uint32_t resp;
891	uint8_t rirbwp;
892	int ret;
893
894	rirb_base = (struct hdac_rirb *)sc->rirb_dma.dma_vaddr;
895	rirbwp = HDAC_READ_1(&sc->mem, HDAC_RIRBWP);
896#if 0
897	bus_dmamap_sync(sc->rirb_dma.dma_tag, sc->rirb_dma.dma_map,
898	    BUS_DMASYNC_POSTREAD);
899#endif
900
901	ret = 0;
902	while (sc->rirb_rp != rirbwp) {
903		sc->rirb_rp++;
904		sc->rirb_rp %= sc->rirb_size;
905		rirb = &rirb_base[sc->rirb_rp];
906		cad = HDAC_RIRB_RESPONSE_EX_SDATA_IN(rirb->response_ex);
907		resp = rirb->response;
908		if (rirb->response_ex & HDAC_RIRB_RESPONSE_EX_UNSOLICITED) {
909			sc->unsolq[sc->unsolq_wp++] = resp;
910			sc->unsolq_wp %= HDAC_UNSOLQ_MAX;
911			sc->unsolq[sc->unsolq_wp++] = cad;
912			sc->unsolq_wp %= HDAC_UNSOLQ_MAX;
913		} else if (sc->codecs[cad].pending <= 0) {
914			device_printf(sc->dev, "Unexpected unsolicited "
915			    "response from address %d: %08x\n", cad, resp);
916		} else {
917			sc->codecs[cad].response = resp;
918			sc->codecs[cad].pending--;
919		}
920		ret++;
921	}
922	return (ret);
923}
924
925static int
926hdac_unsolq_flush(struct hdac_softc *sc)
927{
928	device_t child;
929	nid_t cad;
930	uint32_t resp;
931	int ret = 0;
932
933	if (sc->unsolq_st == HDAC_UNSOLQ_READY) {
934		sc->unsolq_st = HDAC_UNSOLQ_BUSY;
935		while (sc->unsolq_rp != sc->unsolq_wp) {
936			resp = sc->unsolq[sc->unsolq_rp++];
937			sc->unsolq_rp %= HDAC_UNSOLQ_MAX;
938			cad = sc->unsolq[sc->unsolq_rp++];
939			sc->unsolq_rp %= HDAC_UNSOLQ_MAX;
940			if ((child = sc->codecs[cad].dev) != NULL)
941				HDAC_UNSOL_INTR(child, resp);
942			ret++;
943		}
944		sc->unsolq_st = HDAC_UNSOLQ_READY;
945	}
946
947	return (ret);
948}
949
950/****************************************************************************
951 * uint32_t hdac_command_sendone_internal
952 *
953 * Wrapper function that sends only one command to a given codec
954 ****************************************************************************/
955static uint32_t
956hdac_send_command(struct hdac_softc *sc, nid_t cad, uint32_t verb)
957{
958	int timeout;
959	uint32_t *corb;
960
961	if (!hdac_lockowned(sc))
962		device_printf(sc->dev, "WARNING!!!! mtx not owned!!!!\n");
963	verb &= ~HDA_CMD_CAD_MASK;
964	verb |= ((uint32_t)cad) << HDA_CMD_CAD_SHIFT;
965	sc->codecs[cad].response = HDA_INVALID;
966
967	sc->codecs[cad].pending++;
968	sc->corb_wp++;
969	sc->corb_wp %= sc->corb_size;
970	corb = (uint32_t *)sc->corb_dma.dma_vaddr;
971#if 0
972	bus_dmamap_sync(sc->corb_dma.dma_tag,
973	    sc->corb_dma.dma_map, BUS_DMASYNC_PREWRITE);
974#endif
975	corb[sc->corb_wp] = verb;
976#if 0
977	bus_dmamap_sync(sc->corb_dma.dma_tag,
978	    sc->corb_dma.dma_map, BUS_DMASYNC_POSTWRITE);
979#endif
980	HDAC_WRITE_2(&sc->mem, HDAC_CORBWP, sc->corb_wp);
981
982	timeout = 10000;
983	do {
984		if (hdac_rirb_flush(sc) == 0)
985			DELAY(10);
986	} while (sc->codecs[cad].pending != 0 && --timeout);
987
988	if (sc->codecs[cad].pending != 0) {
989		device_printf(sc->dev, "Command timeout on address %d\n", cad);
990		sc->codecs[cad].pending = 0;
991	}
992
993	if (sc->unsolq_rp != sc->unsolq_wp)
994		taskqueue_enqueue(taskqueue_thread, &sc->unsolq_task);
995	return (sc->codecs[cad].response);
996}
997
998/****************************************************************************
999 * Device Methods
1000 ****************************************************************************/
1001
1002/****************************************************************************
1003 * int hdac_probe(device_t)
1004 *
1005 * Probe for the presence of an hdac. If none is found, check for a generic
1006 * match using the subclass of the device.
1007 ****************************************************************************/
1008static int
1009hdac_probe(device_t dev)
1010{
1011	int i, result;
1012	uint32_t model;
1013	uint16_t class, subclass;
1014	char desc[64];
1015
1016	model = (uint32_t)pci_get_device(dev) << 16;
1017	model |= (uint32_t)pci_get_vendor(dev) & 0x0000ffff;
1018	class = pci_get_class(dev);
1019	subclass = pci_get_subclass(dev);
1020
1021	bzero(desc, sizeof(desc));
1022	result = ENXIO;
1023	for (i = 0; i < nitems(hdac_devices); i++) {
1024		if (hdac_devices[i].model == model) {
1025			strlcpy(desc, hdac_devices[i].desc, sizeof(desc));
1026			result = BUS_PROBE_DEFAULT;
1027			break;
1028		}
1029		if (HDA_DEV_MATCH(hdac_devices[i].model, model) &&
1030		    class == PCIC_MULTIMEDIA &&
1031		    subclass == PCIS_MULTIMEDIA_HDA) {
1032			snprintf(desc, sizeof(desc),
1033			    "%s (0x%04x)",
1034			    hdac_devices[i].desc, pci_get_device(dev));
1035			result = BUS_PROBE_GENERIC;
1036			break;
1037		}
1038	}
1039	if (result == ENXIO && class == PCIC_MULTIMEDIA &&
1040	    subclass == PCIS_MULTIMEDIA_HDA) {
1041		snprintf(desc, sizeof(desc), "Generic (0x%08x)", model);
1042		result = BUS_PROBE_GENERIC;
1043	}
1044	if (result != ENXIO) {
1045		strlcat(desc, " HDA Controller", sizeof(desc));
1046		device_set_desc_copy(dev, desc);
1047	}
1048
1049	return (result);
1050}
1051
1052static void
1053hdac_unsolq_task(void *context, int pending)
1054{
1055	struct hdac_softc *sc;
1056
1057	sc = (struct hdac_softc *)context;
1058
1059	hdac_lock(sc);
1060	hdac_unsolq_flush(sc);
1061	hdac_unlock(sc);
1062}
1063
1064/****************************************************************************
1065 * int hdac_attach(device_t)
1066 *
1067 * Attach the device into the kernel. Interrupts usually won't be enabled
1068 * when this function is called. Setup everything that doesn't require
1069 * interrupts and defer probing of codecs until interrupts are enabled.
1070 ****************************************************************************/
1071static int
1072hdac_attach(device_t dev)
1073{
1074	struct hdac_softc *sc;
1075	int result;
1076	int i, devid = -1;
1077	uint32_t model;
1078	uint16_t class, subclass;
1079	uint16_t vendor;
1080	uint8_t v;
1081
1082	sc = device_get_softc(dev);
1083	HDA_BOOTVERBOSE(
1084		device_printf(dev, "PCI card vendor: 0x%04x, device: 0x%04x\n",
1085		    pci_get_subvendor(dev), pci_get_subdevice(dev));
1086		device_printf(dev, "HDA Driver Revision: %s\n",
1087		    HDA_DRV_TEST_REV);
1088	);
1089
1090	model = (uint32_t)pci_get_device(dev) << 16;
1091	model |= (uint32_t)pci_get_vendor(dev) & 0x0000ffff;
1092	class = pci_get_class(dev);
1093	subclass = pci_get_subclass(dev);
1094
1095	for (i = 0; i < nitems(hdac_devices); i++) {
1096		if (hdac_devices[i].model == model) {
1097			devid = i;
1098			break;
1099		}
1100		if (HDA_DEV_MATCH(hdac_devices[i].model, model) &&
1101		    class == PCIC_MULTIMEDIA &&
1102		    subclass == PCIS_MULTIMEDIA_HDA) {
1103			devid = i;
1104			break;
1105		}
1106	}
1107
1108	sc->lock = snd_mtxcreate(device_get_nameunit(dev), "HDA driver mutex");
1109	sc->dev = dev;
1110	TASK_INIT(&sc->unsolq_task, 0, hdac_unsolq_task, sc);
1111	callout_init(&sc->poll_callout, CALLOUT_MPSAFE);
1112	for (i = 0; i < HDAC_CODEC_MAX; i++)
1113		sc->codecs[i].dev = NULL;
1114	if (devid >= 0) {
1115		sc->quirks_on = hdac_devices[devid].quirks_on;
1116		sc->quirks_off = hdac_devices[devid].quirks_off;
1117	} else {
1118		sc->quirks_on = 0;
1119		sc->quirks_off = 0;
1120	}
1121	if (resource_int_value(device_get_name(dev),
1122	    device_get_unit(dev), "msi", &i) == 0) {
1123		if (i == 0)
1124			sc->quirks_off |= HDAC_QUIRK_MSI;
1125		else {
1126			sc->quirks_on |= HDAC_QUIRK_MSI;
1127			sc->quirks_off |= ~HDAC_QUIRK_MSI;
1128		}
1129	}
1130	hdac_config_fetch(sc, &sc->quirks_on, &sc->quirks_off);
1131	HDA_BOOTVERBOSE(
1132		device_printf(sc->dev,
1133		    "Config options: on=0x%08x off=0x%08x\n",
1134		    sc->quirks_on, sc->quirks_off);
1135	);
1136	sc->poll_ival = hz;
1137	if (resource_int_value(device_get_name(dev),
1138	    device_get_unit(dev), "polling", &i) == 0 && i != 0)
1139		sc->polling = 1;
1140	else
1141		sc->polling = 0;
1142
1143	pci_enable_busmaster(dev);
1144
1145	vendor = pci_get_vendor(dev);
1146	if (vendor == INTEL_VENDORID) {
1147		/* TCSEL -> TC0 */
1148		v = pci_read_config(dev, 0x44, 1);
1149		pci_write_config(dev, 0x44, v & 0xf8, 1);
1150		HDA_BOOTHVERBOSE(
1151			device_printf(dev, "TCSEL: 0x%02d -> 0x%02d\n", v,
1152			    pci_read_config(dev, 0x44, 1));
1153		);
1154	}
1155
1156#if defined(__i386__) || defined(__amd64__)
1157	sc->flags |= HDAC_F_DMA_NOCACHE;
1158
1159	if (resource_int_value(device_get_name(dev),
1160	    device_get_unit(dev), "snoop", &i) == 0 && i != 0) {
1161#else
1162	sc->flags &= ~HDAC_F_DMA_NOCACHE;
1163#endif
1164		/*
1165		 * Try to enable PCIe snoop to avoid messing around with
1166		 * uncacheable DMA attribute. Since PCIe snoop register
1167		 * config is pretty much vendor specific, there are no
1168		 * general solutions on how to enable it, forcing us (even
1169		 * Microsoft) to enable uncacheable or write combined DMA
1170		 * by default.
1171		 *
1172		 * http://msdn2.microsoft.com/en-us/library/ms790324.aspx
1173		 */
1174		for (i = 0; i < nitems(hdac_pcie_snoop); i++) {
1175			if (hdac_pcie_snoop[i].vendor != vendor)
1176				continue;
1177			sc->flags &= ~HDAC_F_DMA_NOCACHE;
1178			if (hdac_pcie_snoop[i].reg == 0x00)
1179				break;
1180			v = pci_read_config(dev, hdac_pcie_snoop[i].reg, 1);
1181			if ((v & hdac_pcie_snoop[i].enable) ==
1182			    hdac_pcie_snoop[i].enable)
1183				break;
1184			v &= hdac_pcie_snoop[i].mask;
1185			v |= hdac_pcie_snoop[i].enable;
1186			pci_write_config(dev, hdac_pcie_snoop[i].reg, v, 1);
1187			v = pci_read_config(dev, hdac_pcie_snoop[i].reg, 1);
1188			if ((v & hdac_pcie_snoop[i].enable) !=
1189			    hdac_pcie_snoop[i].enable) {
1190				HDA_BOOTVERBOSE(
1191					device_printf(dev,
1192					    "WARNING: Failed to enable PCIe "
1193					    "snoop!\n");
1194				);
1195#if defined(__i386__) || defined(__amd64__)
1196				sc->flags |= HDAC_F_DMA_NOCACHE;
1197#endif
1198			}
1199			break;
1200		}
1201#if defined(__i386__) || defined(__amd64__)
1202	}
1203#endif
1204
1205	HDA_BOOTHVERBOSE(
1206		device_printf(dev, "DMA Coherency: %s / vendor=0x%04x\n",
1207		    (sc->flags & HDAC_F_DMA_NOCACHE) ?
1208		    "Uncacheable" : "PCIe snoop", vendor);
1209	);
1210
1211	/* Allocate resources */
1212	result = hdac_mem_alloc(sc);
1213	if (result != 0)
1214		goto hdac_attach_fail;
1215	result = hdac_irq_alloc(sc);
1216	if (result != 0)
1217		goto hdac_attach_fail;
1218
1219	/* Get Capabilities */
1220	result = hdac_get_capabilities(sc);
1221	if (result != 0)
1222		goto hdac_attach_fail;
1223
1224	/* Allocate CORB, RIRB, POS and BDLs dma memory */
1225	result = hdac_dma_alloc(sc, &sc->corb_dma,
1226	    sc->corb_size * sizeof(uint32_t));
1227	if (result != 0)
1228		goto hdac_attach_fail;
1229	result = hdac_dma_alloc(sc, &sc->rirb_dma,
1230	    sc->rirb_size * sizeof(struct hdac_rirb));
1231	if (result != 0)
1232		goto hdac_attach_fail;
1233	sc->streams = malloc(sizeof(struct hdac_stream) * sc->num_ss,
1234	    M_HDAC, M_ZERO | M_WAITOK);
1235	for (i = 0; i < sc->num_ss; i++) {
1236		result = hdac_dma_alloc(sc, &sc->streams[i].bdl,
1237		    sizeof(struct hdac_bdle) * HDA_BDL_MAX);
1238		if (result != 0)
1239			goto hdac_attach_fail;
1240	}
1241	if (sc->quirks_on & HDAC_QUIRK_DMAPOS) {
1242		if (hdac_dma_alloc(sc, &sc->pos_dma, (sc->num_ss) * 8) != 0) {
1243			HDA_BOOTVERBOSE(
1244				device_printf(dev, "Failed to "
1245				    "allocate DMA pos buffer "
1246				    "(non-fatal)\n");
1247			);
1248		} else {
1249			uint64_t addr = sc->pos_dma.dma_paddr;
1250
1251			HDAC_WRITE_4(&sc->mem, HDAC_DPIBUBASE, addr >> 32);
1252			HDAC_WRITE_4(&sc->mem, HDAC_DPIBLBASE,
1253			    (addr & HDAC_DPLBASE_DPLBASE_MASK) |
1254			    HDAC_DPLBASE_DPLBASE_DMAPBE);
1255		}
1256	}
1257
1258	result = bus_dma_tag_create(
1259	    bus_get_dma_tag(sc->dev),		/* parent */
1260	    HDA_DMA_ALIGNMENT,			/* alignment */
1261	    0,					/* boundary */
1262	    (sc->support_64bit) ? BUS_SPACE_MAXADDR :
1263		BUS_SPACE_MAXADDR_32BIT,	/* lowaddr */
1264	    BUS_SPACE_MAXADDR,			/* highaddr */
1265	    NULL,				/* filtfunc */
1266	    NULL,				/* fistfuncarg */
1267	    HDA_BUFSZ_MAX, 			/* maxsize */
1268	    1,					/* nsegments */
1269	    HDA_BUFSZ_MAX, 			/* maxsegsz */
1270	    0,					/* flags */
1271	    NULL,				/* lockfunc */
1272	    NULL,				/* lockfuncarg */
1273	    &sc->chan_dmat);			/* dmat */
1274	if (result != 0) {
1275		device_printf(dev, "%s: bus_dma_tag_create failed (%x)\n",
1276		     __func__, result);
1277		goto hdac_attach_fail;
1278	}
1279
1280	/* Quiesce everything */
1281	HDA_BOOTHVERBOSE(
1282		device_printf(dev, "Reset controller...\n");
1283	);
1284	hdac_reset(sc, 1);
1285
1286	/* Initialize the CORB and RIRB */
1287	hdac_corb_init(sc);
1288	hdac_rirb_init(sc);
1289
1290	/* Defer remaining of initialization until interrupts are enabled */
1291	sc->intrhook.ich_func = hdac_attach2;
1292	sc->intrhook.ich_arg = (void *)sc;
1293	if (cold == 0 || config_intrhook_establish(&sc->intrhook) != 0) {
1294		sc->intrhook.ich_func = NULL;
1295		hdac_attach2((void *)sc);
1296	}
1297
1298	return (0);
1299
1300hdac_attach_fail:
1301	hdac_irq_free(sc);
1302	for (i = 0; i < sc->num_ss; i++)
1303		hdac_dma_free(sc, &sc->streams[i].bdl);
1304	free(sc->streams, M_HDAC);
1305	hdac_dma_free(sc, &sc->rirb_dma);
1306	hdac_dma_free(sc, &sc->corb_dma);
1307	hdac_mem_free(sc);
1308	snd_mtxfree(sc->lock);
1309
1310	return (ENXIO);
1311}
1312
1313static int
1314sysctl_hdac_pindump(SYSCTL_HANDLER_ARGS)
1315{
1316	struct hdac_softc *sc;
1317	device_t *devlist;
1318	device_t dev;
1319	int devcount, i, err, val;
1320
1321	dev = oidp->oid_arg1;
1322	sc = device_get_softc(dev);
1323	if (sc == NULL)
1324		return (EINVAL);
1325	val = 0;
1326	err = sysctl_handle_int(oidp, &val, 0, req);
1327	if (err != 0 || req->newptr == NULL || val == 0)
1328		return (err);
1329
1330	/* XXX: Temporary. For debugging. */
1331	if (val == 100) {
1332		hdac_suspend(dev);
1333		return (0);
1334	} else if (val == 101) {
1335		hdac_resume(dev);
1336		return (0);
1337	}
1338
1339	if ((err = device_get_children(dev, &devlist, &devcount)) != 0)
1340		return (err);
1341	hdac_lock(sc);
1342	for (i = 0; i < devcount; i++)
1343		HDAC_PINDUMP(devlist[i]);
1344	hdac_unlock(sc);
1345	free(devlist, M_TEMP);
1346	return (0);
1347}
1348
1349static int
1350hdac_mdata_rate(uint16_t fmt)
1351{
1352	static const int mbits[8] = { 8, 16, 32, 32, 32, 32, 32, 32 };
1353	int rate, bits;
1354
1355	if (fmt & (1 << 14))
1356		rate = 44100;
1357	else
1358		rate = 48000;
1359	rate *= ((fmt >> 11) & 0x07) + 1;
1360	rate /= ((fmt >> 8) & 0x07) + 1;
1361	bits = mbits[(fmt >> 4) & 0x03];
1362	bits *= (fmt & 0x0f) + 1;
1363	return (rate * bits);
1364}
1365
1366static int
1367hdac_bdata_rate(uint16_t fmt, int output)
1368{
1369	static const int bbits[8] = { 8, 16, 20, 24, 32, 32, 32, 32 };
1370	int rate, bits;
1371
1372	rate = 48000;
1373	rate *= ((fmt >> 11) & 0x07) + 1;
1374	bits = bbits[(fmt >> 4) & 0x03];
1375	bits *= (fmt & 0x0f) + 1;
1376	if (!output)
1377		bits = ((bits + 7) & ~0x07) + 10;
1378	return (rate * bits);
1379}
1380
1381static void
1382hdac_poll_reinit(struct hdac_softc *sc)
1383{
1384	int i, pollticks, min = 1000000;
1385	struct hdac_stream *s;
1386
1387	if (sc->polling == 0)
1388		return;
1389	if (sc->unsol_registered > 0)
1390		min = hz / 2;
1391	for (i = 0; i < sc->num_ss; i++) {
1392		s = &sc->streams[i];
1393		if (s->running == 0)
1394			continue;
1395		pollticks = ((uint64_t)hz * s->blksz) /
1396		    (hdac_mdata_rate(s->format) / 8);
1397		pollticks >>= 1;
1398		if (pollticks > hz)
1399			pollticks = hz;
1400		if (pollticks < 1) {
1401			HDA_BOOTVERBOSE(
1402				device_printf(sc->dev,
1403				    "poll interval < 1 tick !\n");
1404			);
1405			pollticks = 1;
1406		}
1407		if (min > pollticks)
1408			min = pollticks;
1409	}
1410	HDA_BOOTVERBOSE(
1411		device_printf(sc->dev,
1412		    "poll interval %d -> %d ticks\n",
1413		    sc->poll_ival, min);
1414	);
1415	sc->poll_ival = min;
1416	if (min == 1000000)
1417		callout_stop(&sc->poll_callout);
1418	else
1419		callout_reset(&sc->poll_callout, 1, hdac_poll_callback, sc);
1420}
1421
1422static int
1423sysctl_hdac_polling(SYSCTL_HANDLER_ARGS)
1424{
1425	struct hdac_softc *sc;
1426	device_t dev;
1427	uint32_t ctl;
1428	int err, val;
1429
1430	dev = oidp->oid_arg1;
1431	sc = device_get_softc(dev);
1432	if (sc == NULL)
1433		return (EINVAL);
1434	hdac_lock(sc);
1435	val = sc->polling;
1436	hdac_unlock(sc);
1437	err = sysctl_handle_int(oidp, &val, 0, req);
1438
1439	if (err != 0 || req->newptr == NULL)
1440		return (err);
1441	if (val < 0 || val > 1)
1442		return (EINVAL);
1443
1444	hdac_lock(sc);
1445	if (val != sc->polling) {
1446		if (val == 0) {
1447			callout_stop(&sc->poll_callout);
1448			hdac_unlock(sc);
1449			callout_drain(&sc->poll_callout);
1450			hdac_lock(sc);
1451			sc->polling = 0;
1452			ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1453			ctl |= HDAC_INTCTL_GIE;
1454			HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1455		} else {
1456			ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1457			ctl &= ~HDAC_INTCTL_GIE;
1458			HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1459			sc->polling = 1;
1460			hdac_poll_reinit(sc);
1461		}
1462	}
1463	hdac_unlock(sc);
1464
1465	return (err);
1466}
1467
1468static void
1469hdac_attach2(void *arg)
1470{
1471	struct hdac_softc *sc;
1472	device_t child;
1473	uint32_t vendorid, revisionid;
1474	int i;
1475	uint16_t statests;
1476
1477	sc = (struct hdac_softc *)arg;
1478
1479	hdac_lock(sc);
1480
1481	/* Remove ourselves from the config hooks */
1482	if (sc->intrhook.ich_func != NULL) {
1483		config_intrhook_disestablish(&sc->intrhook);
1484		sc->intrhook.ich_func = NULL;
1485	}
1486
1487	HDA_BOOTHVERBOSE(
1488		device_printf(sc->dev, "Starting CORB Engine...\n");
1489	);
1490	hdac_corb_start(sc);
1491	HDA_BOOTHVERBOSE(
1492		device_printf(sc->dev, "Starting RIRB Engine...\n");
1493	);
1494	hdac_rirb_start(sc);
1495	HDA_BOOTHVERBOSE(
1496		device_printf(sc->dev,
1497		    "Enabling controller interrupt...\n");
1498	);
1499	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, HDAC_READ_4(&sc->mem, HDAC_GCTL) |
1500	    HDAC_GCTL_UNSOL);
1501	if (sc->polling == 0) {
1502		HDAC_WRITE_4(&sc->mem, HDAC_INTCTL,
1503		    HDAC_INTCTL_CIE | HDAC_INTCTL_GIE);
1504	}
1505	DELAY(1000);
1506
1507	HDA_BOOTHVERBOSE(
1508		device_printf(sc->dev, "Scanning HDA codecs ...\n");
1509	);
1510	statests = HDAC_READ_2(&sc->mem, HDAC_STATESTS);
1511	hdac_unlock(sc);
1512	for (i = 0; i < HDAC_CODEC_MAX; i++) {
1513		if (HDAC_STATESTS_SDIWAKE(statests, i)) {
1514			HDA_BOOTHVERBOSE(
1515				device_printf(sc->dev,
1516				    "Found CODEC at address %d\n", i);
1517			);
1518			hdac_lock(sc);
1519			vendorid = hdac_send_command(sc, i,
1520			    HDA_CMD_GET_PARAMETER(0, 0x0, HDA_PARAM_VENDOR_ID));
1521			revisionid = hdac_send_command(sc, i,
1522			    HDA_CMD_GET_PARAMETER(0, 0x0, HDA_PARAM_REVISION_ID));
1523			hdac_unlock(sc);
1524			if (vendorid == HDA_INVALID &&
1525			    revisionid == HDA_INVALID) {
1526				device_printf(sc->dev,
1527				    "CODEC is not responding!\n");
1528				continue;
1529			}
1530			sc->codecs[i].vendor_id =
1531			    HDA_PARAM_VENDOR_ID_VENDOR_ID(vendorid);
1532			sc->codecs[i].device_id =
1533			    HDA_PARAM_VENDOR_ID_DEVICE_ID(vendorid);
1534			sc->codecs[i].revision_id =
1535			    HDA_PARAM_REVISION_ID_REVISION_ID(revisionid);
1536			sc->codecs[i].stepping_id =
1537			    HDA_PARAM_REVISION_ID_STEPPING_ID(revisionid);
1538			child = device_add_child(sc->dev, "hdacc", -1);
1539			if (child == NULL) {
1540				device_printf(sc->dev,
1541				    "Failed to add CODEC device\n");
1542				continue;
1543			}
1544			device_set_ivars(child, (void *)(intptr_t)i);
1545			sc->codecs[i].dev = child;
1546		}
1547	}
1548	bus_generic_attach(sc->dev);
1549
1550	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1551	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO,
1552	    "pindump", CTLTYPE_INT | CTLFLAG_RW, sc->dev, sizeof(sc->dev),
1553	    sysctl_hdac_pindump, "I", "Dump pin states/data");
1554	SYSCTL_ADD_PROC(device_get_sysctl_ctx(sc->dev),
1555	    SYSCTL_CHILDREN(device_get_sysctl_tree(sc->dev)), OID_AUTO,
1556	    "polling", CTLTYPE_INT | CTLFLAG_RW, sc->dev, sizeof(sc->dev),
1557	    sysctl_hdac_polling, "I", "Enable polling mode");
1558}
1559
1560/****************************************************************************
1561 * int hdac_suspend(device_t)
1562 *
1563 * Suspend and power down HDA bus and codecs.
1564 ****************************************************************************/
1565static int
1566hdac_suspend(device_t dev)
1567{
1568	struct hdac_softc *sc = device_get_softc(dev);
1569
1570	HDA_BOOTHVERBOSE(
1571		device_printf(dev, "Suspend...\n");
1572	);
1573	bus_generic_suspend(dev);
1574
1575	hdac_lock(sc);
1576	HDA_BOOTHVERBOSE(
1577		device_printf(dev, "Reset controller...\n");
1578	);
1579	callout_stop(&sc->poll_callout);
1580	hdac_reset(sc, 0);
1581	hdac_unlock(sc);
1582	callout_drain(&sc->poll_callout);
1583	taskqueue_drain(taskqueue_thread, &sc->unsolq_task);
1584	HDA_BOOTHVERBOSE(
1585		device_printf(dev, "Suspend done\n");
1586	);
1587	return (0);
1588}
1589
1590/****************************************************************************
1591 * int hdac_resume(device_t)
1592 *
1593 * Powerup and restore HDA bus and codecs state.
1594 ****************************************************************************/
1595static int
1596hdac_resume(device_t dev)
1597{
1598	struct hdac_softc *sc = device_get_softc(dev);
1599	int error;
1600
1601	HDA_BOOTHVERBOSE(
1602		device_printf(dev, "Resume...\n");
1603	);
1604	hdac_lock(sc);
1605
1606	/* Quiesce everything */
1607	HDA_BOOTHVERBOSE(
1608		device_printf(dev, "Reset controller...\n");
1609	);
1610	hdac_reset(sc, 1);
1611
1612	/* Initialize the CORB and RIRB */
1613	hdac_corb_init(sc);
1614	hdac_rirb_init(sc);
1615
1616	HDA_BOOTHVERBOSE(
1617		device_printf(dev, "Starting CORB Engine...\n");
1618	);
1619	hdac_corb_start(sc);
1620	HDA_BOOTHVERBOSE(
1621		device_printf(dev, "Starting RIRB Engine...\n");
1622	);
1623	hdac_rirb_start(sc);
1624	HDA_BOOTHVERBOSE(
1625		device_printf(dev, "Enabling controller interrupt...\n");
1626	);
1627	HDAC_WRITE_4(&sc->mem, HDAC_GCTL, HDAC_READ_4(&sc->mem, HDAC_GCTL) |
1628	    HDAC_GCTL_UNSOL);
1629	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, HDAC_INTCTL_CIE | HDAC_INTCTL_GIE);
1630	DELAY(1000);
1631	hdac_poll_reinit(sc);
1632	hdac_unlock(sc);
1633
1634	error = bus_generic_resume(dev);
1635	HDA_BOOTHVERBOSE(
1636		device_printf(dev, "Resume done\n");
1637	);
1638	return (error);
1639}
1640
1641/****************************************************************************
1642 * int hdac_detach(device_t)
1643 *
1644 * Detach and free up resources utilized by the hdac device.
1645 ****************************************************************************/
1646static int
1647hdac_detach(device_t dev)
1648{
1649	struct hdac_softc *sc = device_get_softc(dev);
1650	device_t *devlist;
1651	int cad, i, devcount, error;
1652
1653	if ((error = device_get_children(dev, &devlist, &devcount)) != 0)
1654		return (error);
1655	for (i = 0; i < devcount; i++) {
1656		cad = (intptr_t)device_get_ivars(devlist[i]);
1657		if ((error = device_delete_child(dev, devlist[i])) != 0) {
1658			free(devlist, M_TEMP);
1659			return (error);
1660		}
1661		sc->codecs[cad].dev = NULL;
1662	}
1663	free(devlist, M_TEMP);
1664
1665	hdac_lock(sc);
1666	hdac_reset(sc, 0);
1667	hdac_unlock(sc);
1668	taskqueue_drain(taskqueue_thread, &sc->unsolq_task);
1669	hdac_irq_free(sc);
1670
1671	for (i = 0; i < sc->num_ss; i++)
1672		hdac_dma_free(sc, &sc->streams[i].bdl);
1673	free(sc->streams, M_HDAC);
1674	hdac_dma_free(sc, &sc->pos_dma);
1675	hdac_dma_free(sc, &sc->rirb_dma);
1676	hdac_dma_free(sc, &sc->corb_dma);
1677	if (sc->chan_dmat != NULL) {
1678		bus_dma_tag_destroy(sc->chan_dmat);
1679		sc->chan_dmat = NULL;
1680	}
1681	hdac_mem_free(sc);
1682	snd_mtxfree(sc->lock);
1683	return (0);
1684}
1685
1686static bus_dma_tag_t
1687hdac_get_dma_tag(device_t dev, device_t child)
1688{
1689	struct hdac_softc *sc = device_get_softc(dev);
1690
1691	return (sc->chan_dmat);
1692}
1693
1694static int
1695hdac_print_child(device_t dev, device_t child)
1696{
1697	int retval;
1698
1699	retval = bus_print_child_header(dev, child);
1700	retval += printf(" at cad %d",
1701	    (int)(intptr_t)device_get_ivars(child));
1702	retval += bus_print_child_footer(dev, child);
1703
1704	return (retval);
1705}
1706
1707static int
1708hdac_child_location_str(device_t dev, device_t child, char *buf,
1709    size_t buflen)
1710{
1711
1712	snprintf(buf, buflen, "cad=%d",
1713	    (int)(intptr_t)device_get_ivars(child));
1714	return (0);
1715}
1716
1717static int
1718hdac_child_pnpinfo_str_method(device_t dev, device_t child, char *buf,
1719    size_t buflen)
1720{
1721	struct hdac_softc *sc = device_get_softc(dev);
1722	nid_t cad = (uintptr_t)device_get_ivars(child);
1723
1724	snprintf(buf, buflen, "vendor=0x%04x device=0x%04x revision=0x%02x "
1725	    "stepping=0x%02x",
1726	    sc->codecs[cad].vendor_id, sc->codecs[cad].device_id,
1727	    sc->codecs[cad].revision_id, sc->codecs[cad].stepping_id);
1728	return (0);
1729}
1730
1731static int
1732hdac_read_ivar(device_t dev, device_t child, int which, uintptr_t *result)
1733{
1734	struct hdac_softc *sc = device_get_softc(dev);
1735	nid_t cad = (uintptr_t)device_get_ivars(child);
1736
1737	switch (which) {
1738	case HDA_IVAR_CODEC_ID:
1739		*result = cad;
1740		break;
1741	case HDA_IVAR_VENDOR_ID:
1742		*result = sc->codecs[cad].vendor_id;
1743		break;
1744	case HDA_IVAR_DEVICE_ID:
1745		*result = sc->codecs[cad].device_id;
1746		break;
1747	case HDA_IVAR_REVISION_ID:
1748		*result = sc->codecs[cad].revision_id;
1749		break;
1750	case HDA_IVAR_STEPPING_ID:
1751		*result = sc->codecs[cad].stepping_id;
1752		break;
1753	case HDA_IVAR_SUBVENDOR_ID:
1754		*result = pci_get_subvendor(dev);
1755		break;
1756	case HDA_IVAR_SUBDEVICE_ID:
1757		*result = pci_get_subdevice(dev);
1758		break;
1759	case HDA_IVAR_DMA_NOCACHE:
1760		*result = (sc->flags & HDAC_F_DMA_NOCACHE) != 0;
1761		break;
1762	default:
1763		return (ENOENT);
1764	}
1765	return (0);
1766}
1767
1768static struct mtx *
1769hdac_get_mtx(device_t dev, device_t child)
1770{
1771	struct hdac_softc *sc = device_get_softc(dev);
1772
1773	return (sc->lock);
1774}
1775
1776static uint32_t
1777hdac_codec_command(device_t dev, device_t child, uint32_t verb)
1778{
1779
1780	return (hdac_send_command(device_get_softc(dev),
1781	    (intptr_t)device_get_ivars(child), verb));
1782}
1783
1784static int
1785hdac_find_stream(struct hdac_softc *sc, int dir, int stream)
1786{
1787	int i, ss;
1788
1789	ss = -1;
1790	/* Allocate ISS/BSS first. */
1791	if (dir == 0) {
1792		for (i = 0; i < sc->num_iss; i++) {
1793			if (sc->streams[i].stream == stream) {
1794				ss = i;
1795				break;
1796			}
1797		}
1798	} else {
1799		for (i = 0; i < sc->num_oss; i++) {
1800			if (sc->streams[i + sc->num_iss].stream == stream) {
1801				ss = i + sc->num_iss;
1802				break;
1803			}
1804		}
1805	}
1806	/* Fallback to BSS. */
1807	if (ss == -1) {
1808		for (i = 0; i < sc->num_bss; i++) {
1809			if (sc->streams[i + sc->num_iss + sc->num_oss].stream
1810			    == stream) {
1811				ss = i + sc->num_iss + sc->num_oss;
1812				break;
1813			}
1814		}
1815	}
1816	return (ss);
1817}
1818
1819static int
1820hdac_stream_alloc(device_t dev, device_t child, int dir, int format, int stripe,
1821    uint32_t **dmapos)
1822{
1823	struct hdac_softc *sc = device_get_softc(dev);
1824	nid_t cad = (uintptr_t)device_get_ivars(child);
1825	int stream, ss, bw, maxbw, prevbw;
1826
1827	/* Look for empty stream. */
1828	ss = hdac_find_stream(sc, dir, 0);
1829
1830	/* Return if found nothing. */
1831	if (ss < 0)
1832		return (0);
1833
1834	/* Check bus bandwidth. */
1835	bw = hdac_bdata_rate(format, dir);
1836	if (dir == 1) {
1837		bw *= 1 << (sc->num_sdo - stripe);
1838		prevbw = sc->sdo_bw_used;
1839		maxbw = 48000 * 960 * (1 << sc->num_sdo);
1840	} else {
1841		prevbw = sc->codecs[cad].sdi_bw_used;
1842		maxbw = 48000 * 464;
1843	}
1844	HDA_BOOTHVERBOSE(
1845		device_printf(dev, "%dKbps of %dKbps bandwidth used%s\n",
1846		    (bw + prevbw) / 1000, maxbw / 1000,
1847		    bw + prevbw > maxbw ? " -- OVERFLOW!" : "");
1848	);
1849	if (bw + prevbw > maxbw)
1850		return (0);
1851	if (dir == 1)
1852		sc->sdo_bw_used += bw;
1853	else
1854		sc->codecs[cad].sdi_bw_used += bw;
1855
1856	/* Allocate stream number */
1857	if (ss >= sc->num_iss + sc->num_oss)
1858		stream = 15 - (ss - sc->num_iss + sc->num_oss);
1859	else if (ss >= sc->num_iss)
1860		stream = ss - sc->num_iss + 1;
1861	else
1862		stream = ss + 1;
1863
1864	sc->streams[ss].dev = child;
1865	sc->streams[ss].dir = dir;
1866	sc->streams[ss].stream = stream;
1867	sc->streams[ss].bw = bw;
1868	sc->streams[ss].format = format;
1869	sc->streams[ss].stripe = stripe;
1870	if (dmapos != NULL) {
1871		if (sc->pos_dma.dma_vaddr != NULL)
1872			*dmapos = (uint32_t *)(sc->pos_dma.dma_vaddr + ss * 8);
1873		else
1874			*dmapos = NULL;
1875	}
1876	return (stream);
1877}
1878
1879static void
1880hdac_stream_free(device_t dev, device_t child, int dir, int stream)
1881{
1882	struct hdac_softc *sc = device_get_softc(dev);
1883	nid_t cad = (uintptr_t)device_get_ivars(child);
1884	int ss;
1885
1886	ss = hdac_find_stream(sc, dir, stream);
1887	KASSERT(ss >= 0,
1888	    ("Free for not allocated stream (%d/%d)\n", dir, stream));
1889	if (dir == 1)
1890		sc->sdo_bw_used -= sc->streams[ss].bw;
1891	else
1892		sc->codecs[cad].sdi_bw_used -= sc->streams[ss].bw;
1893	sc->streams[ss].stream = 0;
1894	sc->streams[ss].dev = NULL;
1895}
1896
1897static int
1898hdac_stream_start(device_t dev, device_t child,
1899    int dir, int stream, bus_addr_t buf, int blksz, int blkcnt)
1900{
1901	struct hdac_softc *sc = device_get_softc(dev);
1902	struct hdac_bdle *bdle;
1903	uint64_t addr;
1904	int i, ss, off;
1905	uint32_t ctl;
1906
1907	ss = hdac_find_stream(sc, dir, stream);
1908	KASSERT(ss >= 0,
1909	    ("Start for not allocated stream (%d/%d)\n", dir, stream));
1910
1911	addr = (uint64_t)buf;
1912	bdle = (struct hdac_bdle *)sc->streams[ss].bdl.dma_vaddr;
1913	for (i = 0; i < blkcnt; i++, bdle++) {
1914		bdle->addrl = (uint32_t)addr;
1915		bdle->addrh = (uint32_t)(addr >> 32);
1916		bdle->len = blksz;
1917		bdle->ioc = 1;
1918		addr += blksz;
1919	}
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
1958static void
1959hdac_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	off = ss << 5;
1970	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
1971	ctl &= ~(HDAC_SDCTL_IOCE | HDAC_SDCTL_FEIE | HDAC_SDCTL_DEIE |
1972	    HDAC_SDCTL_RUN);
1973	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
1974
1975	ctl = HDAC_READ_4(&sc->mem, HDAC_INTCTL);
1976	ctl &= ~(1 << ss);
1977	HDAC_WRITE_4(&sc->mem, HDAC_INTCTL, ctl);
1978
1979	sc->streams[ss].running = 0;
1980	hdac_poll_reinit(sc);
1981}
1982
1983static void
1984hdac_stream_reset(device_t dev, device_t child, int dir, int stream)
1985{
1986	struct hdac_softc *sc = device_get_softc(dev);
1987	int timeout = 1000;
1988	int to = timeout;
1989	int ss, off;
1990	uint32_t ctl;
1991
1992	ss = hdac_find_stream(sc, dir, stream);
1993	KASSERT(ss >= 0,
1994	    ("Reset for not allocated stream (%d/%d)\n", dir, stream));
1995
1996	off = ss << 5;
1997	ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
1998	ctl |= HDAC_SDCTL_SRST;
1999	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
2000	do {
2001		ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
2002		if (ctl & HDAC_SDCTL_SRST)
2003			break;
2004		DELAY(10);
2005	} while (--to);
2006	if (!(ctl & HDAC_SDCTL_SRST))
2007		device_printf(dev, "Reset setting timeout\n");
2008	ctl &= ~HDAC_SDCTL_SRST;
2009	HDAC_WRITE_1(&sc->mem, off + HDAC_SDCTL0, ctl);
2010	to = timeout;
2011	do {
2012		ctl = HDAC_READ_1(&sc->mem, off + HDAC_SDCTL0);
2013		if (!(ctl & HDAC_SDCTL_SRST))
2014			break;
2015		DELAY(10);
2016	} while (--to);
2017	if (ctl & HDAC_SDCTL_SRST)
2018		device_printf(dev, "Reset timeout!\n");
2019}
2020
2021static uint32_t
2022hdac_stream_getptr(device_t dev, device_t child, int dir, int stream)
2023{
2024	struct hdac_softc *sc = device_get_softc(dev);
2025	int ss, off;
2026
2027	ss = hdac_find_stream(sc, dir, stream);
2028	KASSERT(ss >= 0,
2029	    ("Reset for not allocated stream (%d/%d)\n", dir, stream));
2030
2031	off = ss << 5;
2032	return (HDAC_READ_4(&sc->mem, off + HDAC_SDLPIB));
2033}
2034
2035static int
2036hdac_unsol_alloc(device_t dev, device_t child, int tag)
2037{
2038	struct hdac_softc *sc = device_get_softc(dev);
2039
2040	sc->unsol_registered++;
2041	hdac_poll_reinit(sc);
2042	return (tag);
2043}
2044
2045static void
2046hdac_unsol_free(device_t dev, device_t child, int tag)
2047{
2048	struct hdac_softc *sc = device_get_softc(dev);
2049
2050	sc->unsol_registered--;
2051	hdac_poll_reinit(sc);
2052}
2053
2054static device_method_t hdac_methods[] = {
2055	/* device interface */
2056	DEVMETHOD(device_probe,		hdac_probe),
2057	DEVMETHOD(device_attach,	hdac_attach),
2058	DEVMETHOD(device_detach,	hdac_detach),
2059	DEVMETHOD(device_suspend,	hdac_suspend),
2060	DEVMETHOD(device_resume,	hdac_resume),
2061	/* Bus interface */
2062	DEVMETHOD(bus_get_dma_tag,	hdac_get_dma_tag),
2063	DEVMETHOD(bus_print_child,	hdac_print_child),
2064	DEVMETHOD(bus_child_location_str, hdac_child_location_str),
2065	DEVMETHOD(bus_child_pnpinfo_str, hdac_child_pnpinfo_str_method),
2066	DEVMETHOD(bus_read_ivar,	hdac_read_ivar),
2067	DEVMETHOD(hdac_get_mtx,		hdac_get_mtx),
2068	DEVMETHOD(hdac_codec_command,	hdac_codec_command),
2069	DEVMETHOD(hdac_stream_alloc,	hdac_stream_alloc),
2070	DEVMETHOD(hdac_stream_free,	hdac_stream_free),
2071	DEVMETHOD(hdac_stream_start,	hdac_stream_start),
2072	DEVMETHOD(hdac_stream_stop,	hdac_stream_stop),
2073	DEVMETHOD(hdac_stream_reset,	hdac_stream_reset),
2074	DEVMETHOD(hdac_stream_getptr,	hdac_stream_getptr),
2075	DEVMETHOD(hdac_unsol_alloc,	hdac_unsol_alloc),
2076	DEVMETHOD(hdac_unsol_free,	hdac_unsol_free),
2077	DEVMETHOD_END
2078};
2079
2080static driver_t hdac_driver = {
2081	"hdac",
2082	hdac_methods,
2083	sizeof(struct hdac_softc),
2084};
2085
2086static devclass_t hdac_devclass;
2087
2088DRIVER_MODULE(snd_hda, pci, hdac_driver, hdac_devclass, NULL, NULL);
2089