Say hello to a sound system update from FreeBSD. This includes the long
[dragonfly.git] / sys / dev / sound / pci / ich.c
1 /*-
2  * Copyright (c) 2000 Katsurajima Naoto <raven@katsurajima.seya.yokohama.jp>
3  * Copyright (c) 2001 Cameron Grant <cg@freebsd.org>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: src/sys/dev/sound/pci/ich.c,v 1.53.2.8 2006/08/22 02:37:03 yongari Exp $
28  * $DragonFly: src/sys/dev/sound/pci/ich.c,v 1.13 2007/01/04 21:47:02 corecode Exp $
29  */
30
31 #include <dev/sound/pcm/sound.h>
32 #include <dev/sound/pcm/ac97.h>
33 #include <dev/sound/pci/ich.h>
34
35 #include <bus/pci/pcireg.h>
36 #include <bus/pci/pcivar.h>
37
38 SND_DECLARE_FILE("$DragonFly: src/sys/dev/sound/pci/ich.c,v 1.13 2007/01/04 21:47:02 corecode Exp $");
39
40 /* -------------------------------------------------------------------- */
41
42 #define ICH_TIMEOUT 1000 /* semaphore timeout polling count */
43 #define ICH_DTBL_LENGTH 32
44 #define ICH_DEFAULT_BUFSZ 16384
45 #define ICH_MAX_BUFSZ 65536
46
47 #define INTEL_VENDORID  0x8086
48 #define SIS_VENDORID    0x1039
49 #define NVIDIA_VENDORID 0x10de
50 #define AMD_VENDORID    0x1022
51
52 #define INTEL_82440MX   0x7195
53 #define INTEL_82801AA   0x2415
54 #define INTEL_82801AB   0x2425
55 #define INTEL_82801BA   0x2445
56 #define INTEL_82801CA   0x2485
57 #define INTEL_82801DB   0x24c5  /* ICH4 needs special handling */
58 #define INTEL_82801EB   0x24d5  /* ICH5 needs to be treated as ICH4 */
59 #define INTEL_6300ESB   0x25a6  /* 6300ESB needs to be treated as ICH4 */
60 #define INTEL_82801FB   0x266e  /* ICH6 needs to be treated as ICH4 */
61 #define INTEL_82801GB   0x27de  /* ICH7 needs to be treated as ICH4 */
62 #define SIS_7012        0x7012  /* SiS 7012 needs special handling */
63 #define NVIDIA_NFORCE   0x01b1
64 #define NVIDIA_NFORCE2  0x006a
65 #define NVIDIA_NFORCE2_400      0x008a
66 #define NVIDIA_NFORCE3  0x00da
67 #define NVIDIA_NFORCE3_250      0x00ea
68 #define NVIDIA_NFORCE4  0x0059
69 #define NVIDIA_NFORCE_410_MCP   0x026b
70 #define AMD_768         0x7445
71 #define AMD_8111        0x746d
72
73 #define ICH_LOCK(sc)            snd_mtxlock((sc)->ich_lock)
74 #define ICH_UNLOCK(sc)          snd_mtxunlock((sc)->ich_lock)
75 #define ICH_LOCK_ASSERT(sc)     snd_mtxassert((sc)->ich_lock)
76
77 static const struct ich_type {
78         uint16_t        vendor;
79         uint16_t        devid;
80         uint32_t        options;
81 #define PROBE_LOW       0x01
82         char            *name;
83 } ich_devs[] = {
84         { INTEL_VENDORID,       INTEL_82440MX,  0,
85                 "Intel 440MX" },
86         { INTEL_VENDORID,       INTEL_82801AA,  0,
87                 "Intel ICH (82801AA)" },
88         { INTEL_VENDORID,       INTEL_82801AB,  0,
89                 "Intel ICH (82801AB)" },
90         { INTEL_VENDORID,       INTEL_82801BA,  0,
91                 "Intel ICH2 (82801BA)" },
92         { INTEL_VENDORID,       INTEL_82801CA,  0,
93                 "Intel ICH3 (82801CA)" },
94         { INTEL_VENDORID,       INTEL_82801DB,  PROBE_LOW,
95                 "Intel ICH4 (82801DB)" },
96         { INTEL_VENDORID,       INTEL_82801EB,  PROBE_LOW,
97                 "Intel ICH5 (82801EB)" },
98         { INTEL_VENDORID,       INTEL_6300ESB,  PROBE_LOW,
99                 "Intel 6300ESB" },
100         { INTEL_VENDORID,       INTEL_82801FB,  PROBE_LOW,
101                 "Intel ICH6 (82801FB)" },
102         { INTEL_VENDORID,       INTEL_82801GB,  PROBE_LOW,
103                 "Intel ICH7 (82801GB)" },
104         { SIS_VENDORID,         SIS_7012,       0,
105                 "SiS 7012" },
106         { NVIDIA_VENDORID,      NVIDIA_NFORCE,  0,
107                 "nVidia nForce" },
108         { NVIDIA_VENDORID,      NVIDIA_NFORCE2, 0,
109                 "nVidia nForce2" },
110         { NVIDIA_VENDORID,      NVIDIA_NFORCE2_400,     0,
111                 "nVidia nForce2 400" },
112         { NVIDIA_VENDORID,      NVIDIA_NFORCE3, 0,
113                 "nVidia nForce3" },
114         { NVIDIA_VENDORID,      NVIDIA_NFORCE3_250,     0,
115                 "nVidia nForce3 250" },
116         { NVIDIA_VENDORID,      NVIDIA_NFORCE4, 0,
117                 "nVidia nForce4" },
118         { NVIDIA_VENDORID,      NVIDIA_NFORCE_410_MCP,  0,
119                 "nVidia nForce 410 MCP" },
120         { AMD_VENDORID,         AMD_768,        0,
121                 "AMD-768" },
122         { AMD_VENDORID,         AMD_8111,       0,
123                 "AMD-8111" }
124 };
125
126 /* buffer descriptor */
127 struct ich_desc {
128         volatile u_int32_t buffer;
129         volatile u_int32_t length;
130 };
131
132 struct sc_info;
133
134 /* channel registers */
135 struct sc_chinfo {
136         u_int32_t num:8, run:1, run_save:1;
137         u_int32_t blksz, blkcnt, spd;
138         u_int32_t regbase, spdreg;
139         u_int32_t imask;
140         u_int32_t civ;
141
142         struct snd_dbuf *buffer;
143         struct pcm_channel *channel;
144         struct sc_info *parent;
145
146         struct ich_desc *dtbl;
147         bus_addr_t desc_addr;
148 };
149
150 /* device private data */
151 struct sc_info {
152         device_t dev;
153         int hasvra, hasvrm, hasmic;
154         unsigned int chnum, bufsz;
155         int sample_size, swap_reg;
156
157         struct resource *nambar, *nabmbar, *irq;
158         int regtype, nambarid, nabmbarid, irqid;
159         bus_space_tag_t nambart, nabmbart;
160         bus_space_handle_t nambarh, nabmbarh;
161         bus_dma_tag_t dmat;
162         bus_dmamap_t dtmap;
163         void *ih;
164
165         struct ac97_info *codec;
166         struct sc_chinfo ch[3];
167         int ac97rate;
168         struct ich_desc *dtbl;
169         bus_addr_t desc_addr;
170         struct intr_config_hook intrhook;
171         int use_intrhook;
172         uint16_t vendor;
173         uint16_t devid;
174         uint32_t flags;
175 #define IGNORE_PCR      0x01
176         struct spinlock *ich_lock;
177 };
178
179 /* -------------------------------------------------------------------- */
180
181 static u_int32_t ich_fmt[] = {
182         AFMT_STEREO | AFMT_S16_LE,
183         0
184 };
185 static struct pcmchan_caps ich_vrcaps = {8000, 48000, ich_fmt, 0};
186 static struct pcmchan_caps ich_caps = {48000, 48000, ich_fmt, 0};
187
188 /* -------------------------------------------------------------------- */
189 /* Hardware */
190 static __inline u_int32_t
191 ich_rd(struct sc_info *sc, int regno, int size)
192 {
193         switch (size) {
194         case 1:
195                 return bus_space_read_1(sc->nabmbart, sc->nabmbarh, regno);
196         case 2:
197                 return bus_space_read_2(sc->nabmbart, sc->nabmbarh, regno);
198         case 4:
199                 return bus_space_read_4(sc->nabmbart, sc->nabmbarh, regno);
200         default:
201                 return 0xffffffff;
202         }
203 }
204
205 static __inline void
206 ich_wr(struct sc_info *sc, int regno, u_int32_t data, int size)
207 {
208         switch (size) {
209         case 1:
210                 bus_space_write_1(sc->nabmbart, sc->nabmbarh, regno, data);
211                 break;
212         case 2:
213                 bus_space_write_2(sc->nabmbart, sc->nabmbarh, regno, data);
214                 break;
215         case 4:
216                 bus_space_write_4(sc->nabmbart, sc->nabmbarh, regno, data);
217                 break;
218         }
219 }
220
221 /* ac97 codec */
222 static int
223 ich_waitcd(void *devinfo)
224 {
225         int i;
226         u_int32_t data;
227         struct sc_info *sc = (struct sc_info *)devinfo;
228
229         for (i = 0; i < ICH_TIMEOUT; i++) {
230                 data = ich_rd(sc, ICH_REG_ACC_SEMA, 1);
231                 if ((data & 0x01) == 0)
232                         return 0;
233                 DELAY(1);
234         }
235         if ((sc->flags & IGNORE_PCR) != 0)
236                 return (0);
237         device_printf(sc->dev, "CODEC semaphore timeout\n");
238         return ETIMEDOUT;
239 }
240
241 static int
242 ich_rdcd(kobj_t obj, void *devinfo, int regno)
243 {
244         struct sc_info *sc = (struct sc_info *)devinfo;
245
246         regno &= 0xff;
247         ich_waitcd(sc);
248
249         return bus_space_read_2(sc->nambart, sc->nambarh, regno);
250 }
251
252 static int
253 ich_wrcd(kobj_t obj, void *devinfo, int regno, u_int16_t data)
254 {
255         struct sc_info *sc = (struct sc_info *)devinfo;
256
257         regno &= 0xff;
258         ich_waitcd(sc);
259         bus_space_write_2(sc->nambart, sc->nambarh, regno, data);
260
261         return 0;
262 }
263
264 static kobj_method_t ich_ac97_methods[] = {
265         KOBJMETHOD(ac97_read,           ich_rdcd),
266         KOBJMETHOD(ac97_write,          ich_wrcd),
267         { 0, 0 }
268 };
269 AC97_DECLARE(ich_ac97);
270
271 /* -------------------------------------------------------------------- */
272 /* common routines */
273
274 static void
275 ich_filldtbl(struct sc_chinfo *ch)
276 {
277         struct sc_info *sc = ch->parent;
278         u_int32_t base;
279         int i;
280
281         base = sndbuf_getbufaddr(ch->buffer);
282         if (ch->blksz > sc->bufsz / ch->blkcnt)
283                 ch->blksz = sc->bufsz / ch->blkcnt;
284         sndbuf_resize(ch->buffer, ch->blkcnt, ch->blksz);
285         ch->blksz = sndbuf_getblksz(ch->buffer);
286
287         for (i = 0; i < ICH_DTBL_LENGTH; i++) {
288                 ch->dtbl[i].buffer = base + (ch->blksz * (i % ch->blkcnt));
289                 ch->dtbl[i].length = ICH_BDC_IOC
290                                    | (ch->blksz / ch->parent->sample_size);
291         }
292 }
293
294 static int
295 ich_resetchan(struct sc_info *sc, int num)
296 {
297         int i, cr, regbase;
298
299         if (num == 0)
300                 regbase = ICH_REG_PO_BASE;
301         else if (num == 1)
302                 regbase = ICH_REG_PI_BASE;
303         else if (num == 2)
304                 regbase = ICH_REG_MC_BASE;
305         else
306                 return ENXIO;
307
308         ich_wr(sc, regbase + ICH_REG_X_CR, 0, 1);
309 #if 1
310         /* This may result in no sound output on NForce 2 MBs, see PR 73987 */
311         DELAY(100);
312 #else
313         (void)ich_rd(sc, regbase + ICH_REG_X_CR, 1);
314 #endif
315         ich_wr(sc, regbase + ICH_REG_X_CR, ICH_X_CR_RR, 1);
316         for (i = 0; i < ICH_TIMEOUT; i++) {
317                 cr = ich_rd(sc, regbase + ICH_REG_X_CR, 1);
318                 if (cr == 0)
319                         return 0;
320         }
321
322         device_printf(sc->dev, "cannot reset channel %d\n", num);
323         return ENXIO;
324 }
325
326 /* -------------------------------------------------------------------- */
327 /* channel interface */
328
329 static void *
330 ichchan_init(kobj_t obj, void *devinfo, struct snd_dbuf *b, struct pcm_channel *c, int dir)
331 {
332         struct sc_info *sc = devinfo;
333         struct sc_chinfo *ch;
334         unsigned int num;
335
336         ICH_LOCK(sc);
337         num = sc->chnum++;
338         ch = &sc->ch[num];
339         ch->num = num;
340         ch->buffer = b;
341         ch->channel = c;
342         ch->parent = sc;
343         ch->run = 0;
344         ch->dtbl = sc->dtbl + (ch->num * ICH_DTBL_LENGTH);
345         ch->desc_addr = sc->desc_addr + (ch->num * ICH_DTBL_LENGTH) *
346                 sizeof(struct ich_desc);
347         ch->blkcnt = 2;
348         ch->blksz = sc->bufsz / ch->blkcnt;
349
350         switch(ch->num) {
351         case 0: /* play */
352                 KASSERT(dir == PCMDIR_PLAY, ("wrong direction"));
353                 ch->regbase = ICH_REG_PO_BASE;
354                 ch->spdreg = sc->hasvra? AC97_REGEXT_FDACRATE : 0;
355                 ch->imask = ICH_GLOB_STA_POINT;
356                 break;
357
358         case 1: /* record */
359                 KASSERT(dir == PCMDIR_REC, ("wrong direction"));
360                 ch->regbase = ICH_REG_PI_BASE;
361                 ch->spdreg = sc->hasvra? AC97_REGEXT_LADCRATE : 0;
362                 ch->imask = ICH_GLOB_STA_PIINT;
363                 break;
364
365         case 2: /* mic */
366                 KASSERT(dir == PCMDIR_REC, ("wrong direction"));
367                 ch->regbase = ICH_REG_MC_BASE;
368                 ch->spdreg = sc->hasvrm? AC97_REGEXT_MADCRATE : 0;
369                 ch->imask = ICH_GLOB_STA_MINT;
370                 break;
371
372         default:
373                 return NULL;
374         }
375
376         ICH_UNLOCK(sc);
377         if (sndbuf_alloc(ch->buffer, sc->dmat, sc->bufsz) != 0)
378                 return NULL;
379
380         ICH_LOCK(sc);
381         ich_wr(sc, ch->regbase + ICH_REG_X_BDBAR, (u_int32_t)(ch->desc_addr), 4);
382         ICH_UNLOCK(sc);
383
384         return ch;
385 }
386
387 static int
388 ichchan_setformat(kobj_t obj, void *data, u_int32_t format)
389 {
390         return 0;
391 }
392
393 static int
394 ichchan_setspeed(kobj_t obj, void *data, u_int32_t speed)
395 {
396         struct sc_chinfo *ch = data;
397         struct sc_info *sc = ch->parent;
398
399         if (ch->spdreg) {
400                 int r, ac97rate;
401
402                 ICH_LOCK(sc);
403                 if (sc->ac97rate <= 32000 || sc->ac97rate >= 64000)
404                         sc->ac97rate = 48000;
405                 ac97rate = sc->ac97rate;
406                 ICH_UNLOCK(sc);
407                 r = (speed * 48000) / ac97rate;
408                 /*
409                  * Cast the return value of ac97_setrate() to u_int so that
410                  * the math don't overflow into the negative range.
411                  */
412                 ch->spd = ((u_int)ac97_setrate(sc->codec, ch->spdreg, r) *
413                                 ac97rate) / 48000;
414         } else {
415                 ch->spd = 48000;
416         }
417         return ch->spd;
418 }
419
420 static int
421 ichchan_setblocksize(kobj_t obj, void *data, u_int32_t blocksize)
422 {
423         struct sc_chinfo *ch = data;
424         struct sc_info *sc = ch->parent;
425
426         ch->blksz = blocksize;
427         ich_filldtbl(ch);
428         ICH_LOCK(sc);
429         ich_wr(sc, ch->regbase + ICH_REG_X_LVI, ch->blkcnt - 1, 1);
430         ICH_UNLOCK(sc);
431
432         return ch->blksz;
433 }
434
435 static int
436 ichchan_trigger(kobj_t obj, void *data, int go)
437 {
438         struct sc_chinfo *ch = data;
439         struct sc_info *sc = ch->parent;
440
441         switch (go) {
442         case PCMTRIG_START:
443                 ch->run = 1;
444                 ICH_LOCK(sc);
445                 ich_wr(sc, ch->regbase + ICH_REG_X_BDBAR, (u_int32_t)(ch->desc_addr), 4);
446                 ich_wr(sc, ch->regbase + ICH_REG_X_CR, ICH_X_CR_RPBM | ICH_X_CR_LVBIE | ICH_X_CR_IOCE, 1);
447                 ICH_UNLOCK(sc);
448                 break;
449
450         case PCMTRIG_ABORT:
451                 ICH_LOCK(sc);
452                 ich_resetchan(sc, ch->num);
453                 ICH_UNLOCK(sc);
454                 ch->run = 0;
455                 break;
456         }
457         return 0;
458 }
459
460 static int
461 ichchan_getptr(kobj_t obj, void *data)
462 {
463         struct sc_chinfo *ch = data;
464         struct sc_info *sc = ch->parent;
465         u_int32_t pos;
466
467         ICH_LOCK(sc);
468         ch->civ = ich_rd(sc, ch->regbase + ICH_REG_X_CIV, 1) % ch->blkcnt;
469         ICH_UNLOCK(sc);
470
471         pos = ch->civ * ch->blksz;
472
473         return pos;
474 }
475
476 static struct pcmchan_caps *
477 ichchan_getcaps(kobj_t obj, void *data)
478 {
479         struct sc_chinfo *ch = data;
480
481         return ch->spdreg? &ich_vrcaps : &ich_caps;
482 }
483
484 static kobj_method_t ichchan_methods[] = {
485         KOBJMETHOD(channel_init,                ichchan_init),
486         KOBJMETHOD(channel_setformat,           ichchan_setformat),
487         KOBJMETHOD(channel_setspeed,            ichchan_setspeed),
488         KOBJMETHOD(channel_setblocksize,        ichchan_setblocksize),
489         KOBJMETHOD(channel_trigger,             ichchan_trigger),
490         KOBJMETHOD(channel_getptr,              ichchan_getptr),
491         KOBJMETHOD(channel_getcaps,             ichchan_getcaps),
492         { 0, 0 }
493 };
494 CHANNEL_DECLARE(ichchan);
495
496 /* -------------------------------------------------------------------- */
497 /* The interrupt handler */
498
499 static void
500 ich_intr(void *p)
501 {
502         struct sc_info *sc = (struct sc_info *)p;
503         struct sc_chinfo *ch;
504         u_int32_t cbi, lbi, lvi, st, gs;
505         int i;
506
507         ICH_LOCK(sc);
508         gs = ich_rd(sc, ICH_REG_GLOB_STA, 4) & ICH_GLOB_STA_IMASK;
509         if (gs & (ICH_GLOB_STA_PRES | ICH_GLOB_STA_SRES)) {
510                 /* Clear resume interrupt(s) - nothing doing with them */
511                 ich_wr(sc, ICH_REG_GLOB_STA, gs, 4);
512         }
513         gs &= ~(ICH_GLOB_STA_PRES | ICH_GLOB_STA_SRES);
514
515         for (i = 0; i < 3; i++) {
516                 ch = &sc->ch[i];
517                 if ((ch->imask & gs) == 0)
518                         continue;
519                 gs &= ~ch->imask;
520                 st = ich_rd(sc, ch->regbase +
521                                 (sc->swap_reg ? ICH_REG_X_PICB : ICH_REG_X_SR),
522                             2);
523                 st &= ICH_X_SR_FIFOE | ICH_X_SR_BCIS | ICH_X_SR_LVBCI;
524                 if (st & (ICH_X_SR_BCIS | ICH_X_SR_LVBCI)) {
525                                 /* block complete - update buffer */
526                         if (ch->run) {
527                                 ICH_UNLOCK(sc);
528                                 chn_intr(ch->channel);
529                                 ICH_LOCK(sc);
530                         }
531                         lvi = ich_rd(sc, ch->regbase + ICH_REG_X_LVI, 1);
532                         cbi = ch->civ % ch->blkcnt;
533                         if (cbi == 0)
534                                 cbi = ch->blkcnt - 1;
535                         else
536                                 cbi--;
537                         lbi = lvi % ch->blkcnt;
538                         if (cbi >= lbi)
539                                 lvi += cbi - lbi;
540                         else
541                                 lvi += cbi + ch->blkcnt - lbi;
542                         lvi %= ICH_DTBL_LENGTH;
543                         ich_wr(sc, ch->regbase + ICH_REG_X_LVI, lvi, 1);
544
545                 }
546                 /* clear status bit */
547                 ich_wr(sc, ch->regbase +
548                            (sc->swap_reg ? ICH_REG_X_PICB : ICH_REG_X_SR),
549                        st, 2);
550         }
551         ICH_UNLOCK(sc);
552         if (gs != 0) {
553                 device_printf(sc->dev,
554                               "Unhandled interrupt, gs_intr = %x\n", gs);
555         }
556 }
557
558 /* ------------------------------------------------------------------------- */
559 /* Sysctl to control ac97 speed (some boards appear to end up using
560  * XTAL_IN rather than BIT_CLK for link timing).
561  */
562
563 static int
564 ich_initsys(struct sc_info* sc)
565 {
566 #ifdef SND_DYNSYSCTL
567         SYSCTL_ADD_INT(snd_sysctl_tree(sc->dev),
568                        SYSCTL_CHILDREN(snd_sysctl_tree_top(sc->dev)),
569                        OID_AUTO, "ac97rate", CTLFLAG_RW,
570                        &sc->ac97rate, 48000,
571                        "AC97 link rate (default = 48000)");
572 #endif /* SND_DYNSYSCTL */
573         return 0;
574 }
575
576 /* -------------------------------------------------------------------- */
577 /* Calibrate card to determine the clock source.  The source maybe a
578  * function of the ac97 codec initialization code (to be investigated).
579  */
580
581 static
582 void ich_calibrate(void *arg)
583 {
584         struct sc_info *sc;
585         struct sc_chinfo *ch;
586         struct timeval t1, t2;
587         u_int8_t ociv, nciv;
588         u_int32_t wait_us, actual_48k_rate, bytes;
589
590         sc = (struct sc_info *)arg;
591         ch = &sc->ch[1];
592
593         if (sc->use_intrhook)
594                 config_intrhook_disestablish(&sc->intrhook);
595
596         /*
597          * Grab audio from input for fixed interval and compare how
598          * much we actually get with what we expect.  Interval needs
599          * to be sufficiently short that no interrupts are
600          * generated.
601          */
602
603         KASSERT(ch->regbase == ICH_REG_PI_BASE, ("wrong direction"));
604
605         bytes = sndbuf_getsize(ch->buffer) / 2;
606         ichchan_setblocksize(0, ch, bytes);
607
608         /*
609          * our data format is stereo, 16 bit so each sample is 4 bytes.
610          * assuming we get 48000 samples per second, we get 192000 bytes/sec.
611          * we're going to start recording with interrupts disabled and measure
612          * the time taken for one block to complete.  we know the block size,
613          * we know the time in microseconds, we calculate the sample rate:
614          *
615          * actual_rate [bps] = bytes / (time [s] * 4)
616          * actual_rate [bps] = (bytes * 1000000) / (time [us] * 4)
617          * actual_rate [Hz] = (bytes * 250000) / time [us]
618          */
619
620         /* prepare */
621         ociv = ich_rd(sc, ch->regbase + ICH_REG_X_CIV, 1);
622         nciv = ociv;
623         ich_wr(sc, ch->regbase + ICH_REG_X_BDBAR, (u_int32_t)(ch->desc_addr), 4);
624
625         /* start */
626         microtime(&t1);
627         ich_wr(sc, ch->regbase + ICH_REG_X_CR, ICH_X_CR_RPBM, 1);
628
629         /* wait */
630         while (nciv == ociv) {
631                 microtime(&t2);
632                 if (t2.tv_sec - t1.tv_sec > 1)
633                         break;
634                 nciv = ich_rd(sc, ch->regbase + ICH_REG_X_CIV, 1);
635         }
636         microtime(&t2);
637
638         /* stop */
639         ich_wr(sc, ch->regbase + ICH_REG_X_CR, 0, 1);
640
641         /* reset */
642         DELAY(100);
643         ich_wr(sc, ch->regbase + ICH_REG_X_CR, ICH_X_CR_RR, 1);
644
645         /* turn time delta into us */
646         wait_us = ((t2.tv_sec - t1.tv_sec) * 1000000) + t2.tv_usec - t1.tv_usec;
647
648         if (nciv == ociv) {
649                 device_printf(sc->dev, "ac97 link rate calibration timed out after %d us\n", wait_us);
650                 return;
651         }
652
653         actual_48k_rate = (bytes * 250000) / wait_us;
654
655         if (actual_48k_rate < 47500 || actual_48k_rate > 48500) {
656                 sc->ac97rate = actual_48k_rate;
657         } else {
658                 sc->ac97rate = 48000;
659         }
660
661         if (bootverbose || sc->ac97rate != 48000) {
662                 device_printf(sc->dev, "measured ac97 link rate at %d Hz", actual_48k_rate);
663                 if (sc->ac97rate != actual_48k_rate)
664                         kprintf(", will use %d Hz", sc->ac97rate);
665                 kprintf("\n");
666         }
667
668         return;
669 }
670
671 /* -------------------------------------------------------------------- */
672 /* Probe and attach the card */
673
674 static void
675 ich_setmap(void *arg, bus_dma_segment_t *segs, int nseg, int error)
676 {
677         struct sc_info *sc = (struct sc_info *)arg;
678         sc->desc_addr = segs->ds_addr;
679         return;
680 }
681
682 static int
683 ich_init(struct sc_info *sc)
684 {
685         u_int32_t stat;
686
687         ich_wr(sc, ICH_REG_GLOB_CNT, ICH_GLOB_CTL_COLD, 4);
688         DELAY(600000);
689         stat = ich_rd(sc, ICH_REG_GLOB_STA, 4);
690
691         if ((stat & ICH_GLOB_STA_PCR) == 0) {
692                 /* ICH4/ICH5 may fail when busmastering is enabled. Continue */
693                 if (sc->vendor == INTEL_VENDORID && (
694                     sc->devid == INTEL_82801DB || sc->devid == INTEL_82801EB ||
695                     sc->devid == INTEL_6300ESB || sc->devid == INTEL_82801FB ||
696                     sc->devid == INTEL_82801GB)) {
697                         sc->flags |= IGNORE_PCR;
698                         device_printf(sc->dev, "primary codec not ready!\n");
699                 }
700         }
701
702 #if 0
703         ich_wr(sc, ICH_REG_GLOB_CNT, ICH_GLOB_CTL_COLD | ICH_GLOB_CTL_PRES, 4);
704 #else
705         ich_wr(sc, ICH_REG_GLOB_CNT, ICH_GLOB_CTL_COLD, 4);
706 #endif
707
708         if (ich_resetchan(sc, 0) || ich_resetchan(sc, 1))
709                 return ENXIO;
710         if (sc->hasmic && ich_resetchan(sc, 2))
711                 return ENXIO;
712
713         return 0;
714 }
715
716 static int
717 ich_pci_probe(device_t dev)
718 {
719         int i;
720         uint16_t devid, vendor;
721
722         vendor = pci_get_vendor(dev);
723         devid = pci_get_device(dev);
724         for (i = 0; i < sizeof(ich_devs)/sizeof(ich_devs[0]); i++) {
725                 if (vendor == ich_devs[i].vendor &&
726                                 devid == ich_devs[i].devid) {
727                         device_set_desc(dev, ich_devs[i].name);
728                         /* allow a better driver to override us */
729                         if ((ich_devs[i].options & PROBE_LOW) != 0)
730                                 return (BUS_PROBE_LOW_PRIORITY);
731                         return (BUS_PROBE_DEFAULT);
732                 }
733         }
734         return (ENXIO);
735 }
736
737 static int
738 ich_pci_attach(device_t dev)
739 {
740         uint32_t                subdev;
741         u_int16_t               extcaps;
742         uint16_t                devid, vendor;
743         struct sc_info          *sc;
744         char                    status[SND_STATUSLEN];
745
746         if ((sc = kmalloc(sizeof(*sc), M_DEVBUF, M_NOWAIT | M_ZERO)) == NULL) {
747                 device_printf(dev, "cannot allocate softc\n");
748                 return ENXIO;
749         }
750
751         sc->ich_lock = snd_mtxcreate(device_get_nameunit(dev), "sound softc");
752         sc->dev = dev;
753
754         vendor = sc->vendor = pci_get_vendor(dev);
755         devid = sc->devid = pci_get_device(dev);
756         subdev = (pci_get_subdevice(dev) << 16) | pci_get_subvendor(dev);
757         /*
758          * The SiS 7012 register set isn't quite like the standard ich.
759          * There really should be a general "quirks" mechanism.
760          */
761         if (vendor == SIS_VENDORID && devid == SIS_7012) {
762                 sc->swap_reg = 1;
763                 sc->sample_size = 1;
764         } else {
765                 sc->swap_reg = 0;
766                 sc->sample_size = 2;
767         }
768
769         /*
770          * Enable bus master. On ich4/5 this may prevent the detection of
771          * the primary codec becoming ready in ich_init().
772          */
773         pci_enable_busmaster(dev);
774
775         /*
776          * By default, ich4 has NAMBAR and NABMBAR i/o spaces as
777          * read-only.  Need to enable "legacy support", by poking into
778          * pci config space.  The driver should use MMBAR and MBBAR,
779          * but doing so will mess things up here.  ich4 has enough new
780          * features it warrants it's own driver. 
781          */
782         if (vendor == INTEL_VENDORID && (devid == INTEL_82801DB ||
783             devid == INTEL_82801EB || devid == INTEL_6300ESB ||
784             devid == INTEL_82801FB || devid == INTEL_82801GB)) {
785                 sc->nambarid = PCIR_MMBAR;
786                 sc->nabmbarid = PCIR_MBBAR;
787                 sc->regtype = SYS_RES_MEMORY;
788                 pci_write_config(dev, PCIR_ICH_LEGACY, ICH_LEGACY_ENABLE, 1);
789         } else {
790                 sc->nambarid = PCIR_NAMBAR;
791                 sc->nabmbarid = PCIR_NABMBAR;
792                 sc->regtype = SYS_RES_IOPORT;
793         }
794
795         sc->nambar = bus_alloc_resource_any(dev, sc->regtype, 
796                 &sc->nambarid, RF_ACTIVE);
797         sc->nabmbar = bus_alloc_resource_any(dev, sc->regtype, 
798                 &sc->nabmbarid, RF_ACTIVE);
799
800         if (!sc->nambar || !sc->nabmbar) {
801                 device_printf(dev, "unable to map IO port space\n");
802                 goto bad;
803         }
804
805         sc->nambart = rman_get_bustag(sc->nambar);
806         sc->nambarh = rman_get_bushandle(sc->nambar);
807         sc->nabmbart = rman_get_bustag(sc->nabmbar);
808         sc->nabmbarh = rman_get_bushandle(sc->nabmbar);
809
810         sc->bufsz = pcm_getbuffersize(dev, 4096, ICH_DEFAULT_BUFSZ, ICH_MAX_BUFSZ);
811         if (bus_dma_tag_create(NULL, 8, 0, BUS_SPACE_MAXADDR_32BIT, BUS_SPACE_MAXADDR,
812                                NULL, NULL, sc->bufsz, 1, 0x3ffff, 0,
813                                &sc->dmat) != 0) {
814                 device_printf(dev, "unable to create dma tag\n");
815                 goto bad;
816         }
817
818         sc->irqid = 0;
819         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &sc->irqid,
820                 RF_ACTIVE | RF_SHAREABLE);
821         if (!sc->irq || snd_setup_intr(dev, sc->irq, INTR_MPSAFE, ich_intr, sc, &sc->ih)) {
822                 device_printf(dev, "unable to map interrupt\n");
823                 goto bad;
824         }
825
826         if (ich_init(sc)) {
827                 device_printf(dev, "unable to initialize the card\n");
828                 goto bad;
829         }
830
831         if (bus_dmamem_alloc(sc->dmat, (void **)&sc->dtbl,
832                     BUS_DMA_NOWAIT, &sc->dtmap))
833                 goto bad;
834
835         if (bus_dmamap_load(sc->dmat, sc->dtmap, sc->dtbl,
836                     sizeof(struct ich_desc) * ICH_DTBL_LENGTH * 3,
837                     ich_setmap, sc, 0))
838                 goto bad;
839
840         sc->codec = AC97_CREATE(dev, sc, ich_ac97);
841         if (sc->codec == NULL)
842                 goto bad;
843
844         /*
845          * Turn on inverted external amplifier sense flags for few
846          * 'special' boards.
847          */
848         switch (subdev) {
849         case 0x202f161f:        /* Gateway 7326GZ */
850         case 0x203a161f:        /* Gateway 4028GZ */
851         case 0x204c161f:        /* Kvazar-Micro Senator 3592XT */
852         case 0x8144104d:        /* Sony VAIO PCG-TR* */
853         case 0x8197104d:        /* Sony S1XP */
854         case 0x81c0104d:        /* Sony VAIO type T */
855         case 0x81c5104d:        /* Sony VAIO VGN B1VP/B1XP */
856         case 0x3089103c:        /* Compaq Presario B3800 */
857                 ac97_setflags(sc->codec, ac97_getflags(sc->codec) | AC97_F_EAPD_INV);
858                 break;
859         default:
860                 break;
861         }
862
863         mixer_init(dev, ac97_getmixerclass(), sc->codec);
864
865         /* check and set VRA function */
866         extcaps = ac97_getextcaps(sc->codec);
867         sc->hasvra = extcaps & AC97_EXTCAP_VRA;
868         sc->hasvrm = extcaps & AC97_EXTCAP_VRM;
869         sc->hasmic = ac97_getcaps(sc->codec) & AC97_CAP_MICCHANNEL;
870         ac97_setextmode(sc->codec, sc->hasvra | sc->hasvrm);
871
872         if (pcm_register(dev, sc, 1, sc->hasmic? 2 : 1))
873                 goto bad;
874
875         pcm_addchan(dev, PCMDIR_PLAY, &ichchan_class, sc);              /* play */
876         pcm_addchan(dev, PCMDIR_REC, &ichchan_class, sc);               /* record */
877         if (sc->hasmic)
878                 pcm_addchan(dev, PCMDIR_REC, &ichchan_class, sc);       /* record mic */
879
880         ksnprintf(status, SND_STATUSLEN, "at io 0x%lx, 0x%lx irq %ld bufsz %u %s",
881                  rman_get_start(sc->nambar), rman_get_start(sc->nabmbar), rman_get_start(sc->irq), sc->bufsz,PCM_KLDSTRING(snd_ich));
882
883         pcm_setstatus(dev, status);
884
885         ich_initsys(sc);
886
887         sc->intrhook.ich_func = ich_calibrate;
888         sc->intrhook.ich_arg = sc;
889         sc->use_intrhook = 1;
890         if (config_intrhook_establish(&sc->intrhook) != 0) {
891                 device_printf(dev, "Cannot establish calibration hook, will calibrate now\n");
892                 sc->use_intrhook = 0;
893                 ich_calibrate(sc);
894         }
895
896         return 0;
897
898 bad:
899         if (sc->codec)
900                 ac97_destroy(sc->codec);
901         if (sc->ih)
902                 bus_teardown_intr(dev, sc->irq, sc->ih);
903         if (sc->irq)
904                 bus_release_resource(dev, SYS_RES_IRQ, sc->irqid, sc->irq);
905         if (sc->nambar)
906                 bus_release_resource(dev, sc->regtype,
907                     sc->nambarid, sc->nambar);
908         if (sc->nabmbar)
909                 bus_release_resource(dev, sc->regtype,
910                     sc->nabmbarid, sc->nabmbar);
911         if (sc->dtmap)
912                 bus_dmamap_unload(sc->dmat, sc->dtmap);
913         if (sc->dmat)
914                 bus_dma_tag_destroy(sc->dmat);
915         if (sc->ich_lock)
916                 snd_mtxfree(sc->ich_lock);
917         kfree(sc, M_DEVBUF);
918         return ENXIO;
919 }
920
921 static int
922 ich_pci_detach(device_t dev)
923 {
924         struct sc_info *sc;
925         int r;
926
927         r = pcm_unregister(dev);
928         if (r)
929                 return r;
930         sc = pcm_getdevinfo(dev);
931
932         bus_teardown_intr(dev, sc->irq, sc->ih);
933         bus_release_resource(dev, SYS_RES_IRQ, sc->irqid, sc->irq);
934         bus_release_resource(dev, sc->regtype, sc->nambarid, sc->nambar);
935         bus_release_resource(dev, sc->regtype, sc->nabmbarid, sc->nabmbar);
936         bus_dmamap_unload(sc->dmat, sc->dtmap);
937         bus_dma_tag_destroy(sc->dmat);
938         snd_mtxfree(sc->ich_lock);
939         kfree(sc, M_DEVBUF);
940         return 0;
941 }
942
943 static void
944 ich_pci_codec_reset(struct sc_info *sc)
945 {
946         int i;
947         uint32_t control;
948
949         control = ich_rd(sc, ICH_REG_GLOB_CNT, 4); 
950         control &= ~(ICH_GLOB_CTL_SHUT);
951         control |= (control & ICH_GLOB_CTL_COLD) ?
952                     ICH_GLOB_CTL_WARM : ICH_GLOB_CTL_COLD;
953         ich_wr(sc, ICH_REG_GLOB_CNT, control, 4);
954
955         for (i = 500000; i; i--) {
956                 if (ich_rd(sc, ICH_REG_GLOB_STA, 4) & ICH_GLOB_STA_PCR)
957                         break;          /*              or ICH_SCR? */
958                 DELAY(1);
959         }
960
961         if (i <= 0)
962                 kprintf("%s: time out\n", __func__);
963 }
964
965 static int
966 ich_pci_suspend(device_t dev)
967 {
968         struct sc_info *sc;
969         int i;
970
971         sc = pcm_getdevinfo(dev);
972         ICH_LOCK(sc);
973         for (i = 0 ; i < 3; i++) {
974                 sc->ch[i].run_save = sc->ch[i].run;
975                 if (sc->ch[i].run) {
976                         ICH_UNLOCK(sc);
977                         ichchan_trigger(0, &sc->ch[i], PCMTRIG_ABORT);
978                         ICH_LOCK(sc);
979                 }
980         }
981         ICH_UNLOCK(sc);
982         return 0;
983 }
984
985 static int
986 ich_pci_resume(device_t dev)
987 {
988         struct sc_info *sc;
989         int i;
990
991         sc = pcm_getdevinfo(dev);
992
993         if (sc->regtype == SYS_RES_IOPORT)
994                 pci_enable_io(dev, SYS_RES_IOPORT);
995         else
996                 pci_enable_io(dev, SYS_RES_MEMORY);
997         pci_enable_busmaster(dev);
998
999         ICH_LOCK(sc);
1000         /* Reinit audio device */
1001         if (ich_init(sc) == -1) {
1002                 device_printf(dev, "unable to reinitialize the card\n");
1003                 ICH_UNLOCK(sc);
1004                 return ENXIO;
1005         }
1006         /* Reinit mixer */
1007         ich_pci_codec_reset(sc);
1008         ICH_UNLOCK(sc);
1009         ac97_setextmode(sc->codec, sc->hasvra | sc->hasvrm);
1010         if (mixer_reinit(dev) == -1) {
1011                 device_printf(dev, "unable to reinitialize the mixer\n");
1012                 return ENXIO;
1013         }
1014         /* Re-start DMA engines */
1015         for (i = 0 ; i < 3; i++) {
1016                 struct sc_chinfo *ch = &sc->ch[i];
1017                 if (sc->ch[i].run_save) {
1018                         ichchan_setblocksize(0, ch, ch->blksz);
1019                         ichchan_setspeed(0, ch, ch->spd);
1020                         ichchan_trigger(0, ch, PCMTRIG_START);
1021                 }
1022         }
1023         return 0;
1024 }
1025
1026 static device_method_t ich_methods[] = {
1027         /* Device interface */
1028         DEVMETHOD(device_probe,         ich_pci_probe),
1029         DEVMETHOD(device_attach,        ich_pci_attach),
1030         DEVMETHOD(device_detach,        ich_pci_detach),
1031         DEVMETHOD(device_suspend,       ich_pci_suspend),
1032         DEVMETHOD(device_resume,        ich_pci_resume),
1033         { 0, 0 }
1034 };
1035
1036 static driver_t ich_driver = {
1037         "pcm",
1038         ich_methods,
1039         PCM_SOFTC_SIZE,
1040 };
1041
1042 DRIVER_MODULE(snd_ich, pci, ich_driver, pcm_devclass, 0, 0);
1043 MODULE_DEPEND(snd_ich, sound, SOUND_MINVER, SOUND_PREFVER, SOUND_MAXVER);
1044 MODULE_VERSION(snd_ich, 1);