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