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