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