sound: Port to DragonFly - cdevsw to dev_ops semantics
[dragonfly.git] / sys / dev / sound / pci / emu10kx.c
1 /*-
2  * Copyright (c) 1999 Cameron Grant <cg@freebsd.org>
3  * Copyright (c) 2003-2007 Yuriy Tsibizov <yuriy.tsibizov@gfk.ru>
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 THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  *
27  * $FreeBSD: head/sys/dev/sound/pci/emu10kx.c 274035 2014-11-03 11:11:45Z bapt $
28  */
29
30 #include <sys/param.h>
31 #include <sys/types.h>
32 #include <sys/bus.h>
33 #include <sys/rman.h>
34 #include <sys/systm.h>
35 #include <sys/sbuf.h>
36 #include <sys/queue.h>
37 #include <sys/lock.h>
38 #include <sys/mutex.h>
39 #include <sys/sysctl.h>
40
41 #include <bus/pci/pcireg.h>
42 #include <bus/pci/pcivar.h>
43
44 #include <machine/clock.h>      /* for DELAY */
45
46 #ifdef HAVE_KERNEL_OPTION_HEADERS
47 #include "opt_snd.h"
48 #endif
49
50 #include <dev/sound/chip.h>
51 #include <dev/sound/pcm/sound.h>
52 #include <dev/sound/pcm/ac97.h>
53
54 #include <dev/sound/pci/emuxkireg.h>
55 #include <dev/sound/pci/emu10kx.h>
56
57 /* hw flags */
58 #define HAS_51          0x0001
59 #define HAS_71          0x0002
60 #define HAS_AC97        0x0004
61
62 #define IS_EMU10K1      0x0008
63 #define IS_EMU10K2      0x0010
64 #define IS_CA0102       0x0020
65 #define IS_CA0108       0x0040
66 #define IS_UNKNOWN      0x0080
67
68 #define BROKEN_DIGITAL  0x0100
69 #define DIGITAL_ONLY    0x0200
70
71 #define IS_CARDBUS      0x0400
72
73 #define MODE_ANALOG     1
74 #define MODE_DIGITAL    2
75 #define SPDIF_MODE_PCM  1
76 #define SPDIF_MODE_AC3  2
77
78 #define MACS    0x0
79 #define MACS1   0x1
80 #define MACW    0x2
81 #define MACW1   0x3
82 #define MACINTS 0x4
83 #define MACINTW 0x5
84 #define ACC3    0x6
85 #define MACMV   0x7
86 #define ANDXOR  0x8
87 #define TSTNEG  0x9
88 #define LIMIT   0xA
89 #define LIMIT1  0xB
90 #define LOG     0xC
91 #define EXP     0xD
92 #define INTERP  0xE
93 #define SKIP    0xF
94
95 #define GPR(i)  (sc->gpr_base+(i))
96 #define INP(i)  (sc->input_base+(i))
97 #define OUTP(i) (sc->output_base+(i))
98 #define FX(i)   (i)
99 #define FX2(i)  (sc->efxc_base+(i))
100 #define DSP_CONST(i) (sc->dsp_zero+(i))
101
102 #define COND_NORMALIZED DSP_CONST(0x1)
103 #define COND_BORROW     DSP_CONST(0x2)
104 #define COND_MINUS      DSP_CONST(0x3)
105 #define COND_LESS_ZERO  DSP_CONST(0x4)
106 #define COND_EQ_ZERO    DSP_CONST(0x5)
107 #define COND_SATURATION DSP_CONST(0x6)
108 #define COND_NEQ_ZERO   DSP_CONST(0x8)
109
110 #define DSP_ACCUM       DSP_CONST(0x16)
111 #define DSP_CCR         DSP_CONST(0x17)
112
113 /* Live! Inputs */
114 #define IN_AC97_L       0x00
115 #define IN_AC97_R       0x01
116 #define IN_AC97         IN_AC97_L
117 #define IN_SPDIF_CD_L   0x02
118 #define IN_SPDIF_CD_R   0x03
119 #define IN_SPDIF_CD     IN_SPDIF_CD_L
120 #define IN_ZOOM_L       0x04
121 #define IN_ZOOM_R       0x05
122 #define IN_ZOOM         IN_ZOOM_L
123 #define IN_TOSLINK_L    0x06
124 #define IN_TOSLINK_R    0x07
125 #define IN_TOSLINK      IN_TOSLINK_L
126 #define IN_LINE1_L      0x08
127 #define IN_LINE1_R      0x09
128 #define IN_LINE1        IN_LINE1_L
129 #define IN_COAX_SPDIF_L 0x0a
130 #define IN_COAX_SPDIF_R 0x0b
131 #define IN_COAX_SPDIF   IN_COAX_SPDIF_L
132 #define IN_LINE2_L      0x0c
133 #define IN_LINE2_R      0x0d
134 #define IN_LINE2        IN_LINE2_L
135 #define IN_0E           0x0e
136 #define IN_0F           0x0f
137
138 /* Outputs */
139 #define OUT_AC97_L      0x00
140 #define OUT_AC97_R      0x01
141 #define OUT_AC97        OUT_AC97_L
142 #define OUT_A_FRONT     OUT_AC97
143 #define OUT_TOSLINK_L   0x02
144 #define OUT_TOSLINK_R   0x03
145 #define OUT_TOSLINK     OUT_TOSLINK_L
146 #define OUT_D_CENTER    0x04
147 #define OUT_D_SUB       0x05
148 #define OUT_HEADPHONE_L 0x06
149 #define OUT_HEADPHONE_R 0x07
150 #define OUT_HEADPHONE   OUT_HEADPHONE_L
151 #define OUT_REAR_L      0x08
152 #define OUT_REAR_R      0x09
153 #define OUT_REAR        OUT_REAR_L
154 #define OUT_ADC_REC_L   0x0a
155 #define OUT_ADC_REC_R   0x0b
156 #define OUT_ADC_REC     OUT_ADC_REC_L
157 #define OUT_MIC_CAP     0x0c
158
159 /* Live! 5.1 Digital, non-standard 5.1 (center & sub) outputs */
160 #define OUT_A_CENTER    0x11
161 #define OUT_A_SUB       0x12
162
163 /* Audigy Inputs */
164 #define A_IN_AC97_L     0x00
165 #define A_IN_AC97_R     0x01
166 #define A_IN_AC97       A_IN_AC97_L
167 #define A_IN_SPDIF_CD_L 0x02
168 #define A_IN_SPDIF_CD_R 0x03
169 #define A_IN_SPDIF_CD   A_IN_SPDIF_CD_L
170 #define A_IN_O_SPDIF_L  0x04
171 #define A_IN_O_SPDIF_R  0x05
172 #define A_IN_O_SPDIF    A_IN_O_SPDIF_L
173 #define A_IN_LINE2_L    0x08
174 #define A_IN_LINE2_R    0x09
175 #define A_IN_LINE2      A_IN_LINE2_L
176 #define A_IN_R_SPDIF_L  0x0a
177 #define A_IN_R_SPDIF_R  0x0b
178 #define A_IN_R_SPDIF    A_IN_R_SPDIF_L
179 #define A_IN_AUX2_L     0x0c
180 #define A_IN_AUX2_R     0x0d
181 #define A_IN_AUX2       A_IN_AUX2_L
182
183 /* Audigy Outputs */
184 #define A_OUT_D_FRONT_L 0x00
185 #define A_OUT_D_FRONT_R 0x01
186 #define A_OUT_D_FRONT   A_OUT_D_FRONT_L
187 #define A_OUT_D_CENTER  0x02
188 #define A_OUT_D_SUB     0x03
189 #define A_OUT_D_SIDE_L  0x04
190 #define A_OUT_D_SIDE_R  0x05
191 #define A_OUT_D_SIDE    A_OUT_D_SIDE_L
192 #define A_OUT_D_REAR_L  0x06
193 #define A_OUT_D_REAR_R  0x07
194 #define A_OUT_D_REAR    A_OUT_D_REAR_L
195
196 /* on Audigy Platinum only */
197 #define A_OUT_HPHONE_L  0x04
198 #define A_OUT_HPHONE_R  0x05
199 #define A_OUT_HPHONE    A_OUT_HPHONE_L
200
201 #define A_OUT_A_FRONT_L 0x08
202 #define A_OUT_A_FRONT_R 0x09
203 #define A_OUT_A_FRONT   A_OUT_A_FRONT_L
204 #define A_OUT_A_CENTER  0x0a
205 #define A_OUT_A_SUB     0x0b
206 #define A_OUT_A_SIDE_L  0x0c
207 #define A_OUT_A_SIDE_R  0x0d
208 #define A_OUT_A_SIDE    A_OUT_A_SIDE_L
209 #define A_OUT_A_REAR_L  0x0e
210 #define A_OUT_A_REAR_R  0x0f
211 #define A_OUT_A_REAR    A_OUT_A_REAR_L
212 #define A_OUT_AC97_L    0x10
213 #define A_OUT_AC97_R    0x11
214 #define A_OUT_AC97      A_OUT_AC97_L
215 #define A_OUT_ADC_REC_L 0x16
216 #define A_OUT_ADC_REC_R 0x17
217 #define A_OUT_ADC_REC   A_OUT_ADC_REC_L
218
219 #define EMU_DATA2       0x24
220 #define EMU_IPR2        0x28
221 #define EMU_INTE2       0x2c
222 #define EMU_IPR3        0x38
223 #define EMU_INTE3       0x3c
224
225 #define EMU_A2_SRCSel           0x60
226 #define EMU_A2_SRCMULTI_ENABLE  0x6e
227
228 #define EMU_A_I2S_CAPTURE_96000 0x00000400
229
230 #define EMU_A2_MIXER_I2S_ENABLE           0x7B
231 #define EMU_A2_MIXER_SPDIF_ENABLE         0x7A
232
233 #define C_FRONT_L       0
234 #define C_FRONT_R       1
235 #define C_REC_L         2
236 #define C_REC_R         3
237 #define C_REAR_L        4
238 #define C_REAR_R        5
239 #define C_CENTER        6
240 #define C_SUB           7
241 #define C_SIDE_L        8
242 #define C_SIDE_R        9
243 #define NUM_CACHES      10
244
245 #define CDSPDIFMUTE     0
246 #define ANALOGMUTE      1
247 #define NUM_MUTE        2
248
249 #define EMU_MAX_GPR     512
250 #define EMU_MAX_IRQ_CONSUMERS 32
251
252 struct emu_voice {
253         int     vnum;
254         unsigned int    b16:1, stereo:1, busy:1, running:1, ismaster:1;
255         int     speed;
256         int     start;
257         int     end;
258         int     vol;
259         uint32_t buf;
260         void    *vbuf;
261         struct emu_voice *slave;
262         uint32_t sa;
263         uint32_t ea;
264         uint32_t routing[8];
265         uint32_t amounts[8];
266 };
267
268 struct emu_memblk {
269         SLIST_ENTRY(emu_memblk) link;
270         void            *buf;
271         char            owner[16];
272         bus_addr_t      buf_addr;
273         uint32_t        pte_start, pte_size;
274         bus_dmamap_t    buf_map;
275 };
276
277 struct emu_mem {
278         uint8_t         bmap[EMU_MAXPAGES / 8];
279         uint32_t        *ptb_pages;
280         void            *silent_page;
281         bus_addr_t      ptb_pages_addr;
282         bus_addr_t      silent_page_addr;
283         bus_dmamap_t    ptb_map;
284         bus_dmamap_t    silent_map;
285         bus_dma_tag_t   dmat;
286         struct emu_sc_info *card;
287         SLIST_HEAD(, emu_memblk) blocks;
288 };
289
290 /* rm */
291 struct emu_rm {
292         struct emu_sc_info *card;
293         struct lock     gpr_lock;
294         signed int      allocmap[EMU_MAX_GPR];
295         int             num_gprs;
296         int             last_free_gpr;
297         int             num_used;
298 };
299
300 struct emu_intr_handler {
301         void*           softc;
302         uint32_t        intr_mask;
303         uint32_t        inte_mask;
304         uint32_t(*irq_func) (void *softc, uint32_t irq);
305 };
306
307 struct emu_sc_info {
308         struct lock     lock;
309         struct lock     rw;             /* Hardware exclusive access lock */
310
311         /* Hardware and subdevices */
312         device_t        dev;
313         device_t        pcm[RT_COUNT];
314         device_t        midi[2];
315         uint32_t        type;
316         uint32_t        rev;
317
318         bus_space_tag_t st;
319         bus_space_handle_t sh;
320
321         struct cdev     *cdev;          /* /dev/emu10k character device */
322         struct lock     emu10kx_lock;
323         int             emu10kx_isopen;
324         struct sbuf     emu10kx_sbuf;
325         int             emu10kx_bufptr;
326
327
328         /* Resources */
329         struct resource *reg;
330         struct resource *irq;
331         void            *ih;
332
333         /* IRQ handlers */
334         struct emu_intr_handler ihandler[EMU_MAX_IRQ_CONSUMERS];
335
336         /* Card HW configuration */
337         unsigned int    mode;   /* analog / digital */
338         unsigned int    mchannel_fx;
339         unsigned int    dsp_zero;
340         unsigned int    code_base;
341         unsigned int    code_size;
342         unsigned int    gpr_base;
343         unsigned int    num_gprs;
344         unsigned int    input_base;
345         unsigned int    output_base;
346         unsigned int    efxc_base;
347         unsigned int    opcode_shift;
348         unsigned int    high_operand_shift;
349         unsigned int    address_mask;
350         uint32_t        is_emu10k1:1, is_emu10k2, is_ca0102, is_ca0108:1,
351                         has_ac97:1, has_51:1, has_71:1,
352                         enable_ir:1,
353                         broken_digital:1, is_cardbus:1;
354
355         signed int      mch_disabled, mch_rec, dbg_level;
356         signed int      num_inputs;
357         unsigned int    num_outputs;
358         unsigned int    num_fxbuses;
359         unsigned int    routing_code_start;
360         unsigned int    routing_code_end;
361
362         /* HW resources */
363         struct emu_voice voice[NUM_G];                  /* Hardware voices */
364         uint32_t        irq_mask[EMU_MAX_IRQ_CONSUMERS]; /* IRQ manager data */
365         int             timer[EMU_MAX_IRQ_CONSUMERS];   /* timer */
366         int             timerinterval;
367         struct          emu_rm *rm;
368         struct          emu_mem mem;                    /* memory */
369
370         /* Mixer */
371         int             mixer_gpr[NUM_MIXERS];
372         int             mixer_volcache[NUM_MIXERS];
373         int             cache_gpr[NUM_CACHES];
374         int             dummy_gpr;
375         int             mute_gpr[NUM_MUTE];
376         struct sysctl_ctx_list  *ctx;
377         struct sysctl_oid       *root;
378 };
379
380 static void     emu_setmap(void *arg, bus_dma_segment_t * segs, int nseg, int error);
381 static void*    emu_malloc(struct emu_mem *mem, uint32_t sz, bus_addr_t * addr, bus_dmamap_t *map);
382 static void     emu_free(struct emu_mem *mem, void *dmabuf, bus_dmamap_t map);
383 static void*    emu_memalloc(struct emu_mem *mem, uint32_t sz, bus_addr_t * addr, const char * owner);
384 static int      emu_memfree(struct emu_mem *mem, void *membuf);
385 static int      emu_memstart(struct emu_mem *mem, void *membuf);
386
387 /* /dev */
388 static int      emu10kx_dev_init(struct emu_sc_info *sc);
389 static int      emu10kx_dev_uninit(struct emu_sc_info *sc);
390 static int      emu10kx_prepare(struct emu_sc_info *sc, struct sbuf *s);
391
392 static void     emumix_set_mode(struct emu_sc_info *sc, int mode);
393 static void     emumix_set_spdif_mode(struct emu_sc_info *sc, int mode);
394 static void     emumix_set_fxvol(struct emu_sc_info *sc, unsigned gpr, int32_t vol);
395 static void     emumix_set_gpr(struct emu_sc_info *sc, unsigned gpr, int32_t val);
396 static int      sysctl_emu_mixer_control(SYSCTL_HANDLER_ARGS);
397
398 static int      emu_rm_init(struct emu_sc_info *sc);
399 static int      emu_rm_uninit(struct emu_sc_info *sc);
400 static int      emu_rm_gpr_alloc(struct emu_rm *rm, int count);
401
402 static unsigned int emu_getcard(device_t dev);
403 static uint32_t emu_rd_nolock(struct emu_sc_info *sc, unsigned int regno, unsigned int size);
404 static void     emu_wr_nolock(struct emu_sc_info *sc, unsigned int regno, uint32_t data, unsigned int size);
405 static void     emu_wr_cbptr(struct emu_sc_info *sc, uint32_t data);
406
407 static void     emu_vstop(struct emu_sc_info *sc, char channel, int enable);
408
409 static void     emu_intr(void *p);
410 static void     emu_wrefx(struct emu_sc_info *sc, unsigned int pc, unsigned int data);
411 static void     emu_addefxop(struct emu_sc_info *sc, unsigned int op, unsigned int z, unsigned int w, unsigned int x, unsigned int y, uint32_t * pc);
412 static void     emu_initefx(struct emu_sc_info *sc);
413
414 static int      emu_cardbus_init(struct emu_sc_info *sc);
415 static int      emu_init(struct emu_sc_info *sc);
416 static int      emu_uninit(struct emu_sc_info *sc);
417
418 static int      emu_read_ivar(device_t bus __unused, device_t dev, int ivar_index, uintptr_t * result);
419 static int      emu_write_ivar(device_t bus __unused, device_t dev __unused,
420     int ivar_index, uintptr_t value __unused);
421
422 static int      emu_pci_probe(device_t dev);
423 static int      emu_pci_attach(device_t dev);
424 static int      emu_pci_detach(device_t dev);
425 static int      emu_modevent(module_t mod __unused, int cmd, void *data __unused);
426
427 #ifdef  SND_EMU10KX_DEBUG
428
429 #define EMU_MTX_DEBUG() do {                                            \
430                 if (mtx_owned(&sc->rw)) {                               \
431                 printf("RW owned in %s line %d for %s\n", __func__,     \
432                         __LINE__ , device_get_nameunit(sc->dev));       \
433                 printf("rw lock owned: %d\n", mtx_owned(&sc->rw));      \
434                 printf("rw lock: value %x thread %x\n",                 \
435                         ((&sc->rw)->mtx_lock & ~MTX_FLAGMASK),          \
436                         (uintptr_t)curthread);                          \
437                 printf("rw lock: recursed %d\n", mtx_recursed(&sc->rw));\
438                 db_show_mtx(&sc->rw);                                   \
439                 }                                                       \
440         } while (0)
441 #else
442 #define EMU_MTX_DEBUG() do {                                            \
443         } while (0)
444 #endif
445
446 #define EMU_RWLOCK() do {               \
447         EMU_MTX_DEBUG();                \
448         lockmgr(&(sc->rw), LK_EXCLUSIVE);               \
449         } while (0)
450
451 #define EMU_RWUNLOCK() do {             \
452         lockmgr(&(sc->rw), LK_RELEASE);         \
453         EMU_MTX_DEBUG();                \
454         } while (0)
455
456 /* Supported cards */
457 struct emu_hwinfo {
458         uint16_t        vendor;
459         uint16_t        device;
460         uint16_t        subvendor;
461         uint16_t        subdevice;
462         char            SBcode[8];
463         char            desc[32];
464         int             flags;
465 };
466
467 static struct emu_hwinfo emu_cards[] = {
468         {0xffff, 0xffff, 0xffff, 0xffff, "BADCRD", "Not a compatible card", 0},
469         /* 0x0020..0x002f 4.0 EMU10K1 cards */
470         {0x1102, 0x0002, 0x1102, 0x0020, "CT4850", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
471         {0x1102, 0x0002, 0x1102, 0x0021, "CT4620", "SBLive!", HAS_AC97 | IS_EMU10K1},
472         {0x1102, 0x0002, 0x1102, 0x002f, "CT????", "SBLive! mainboard implementation", HAS_AC97 | IS_EMU10K1},
473
474         /* (range unknown) 5.1 EMU10K1 cards */
475         {0x1102, 0x0002, 0x1102, 0x100a, "CT????", "SBLive! 5.1", HAS_AC97 | HAS_51 | IS_EMU10K1},
476
477         /* 0x80??..0x805? 4.0 EMU10K1 cards */
478         {0x1102, 0x0002, 0x1102, 0x8022, "CT4780", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
479         {0x1102, 0x0002, 0x1102, 0x8023, "CT4790", "SB PCI512", HAS_AC97 | IS_EMU10K1},
480         {0x1102, 0x0002, 0x1102, 0x8024, "CT4760", "SBLive!", HAS_AC97 | IS_EMU10K1},
481         {0x1102, 0x0002, 0x1102, 0x8025, "CT????", "SBLive! Mainboard Implementation", HAS_AC97 | IS_EMU10K1},
482         {0x1102, 0x0002, 0x1102, 0x8026, "CT4830", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
483         {0x1102, 0x0002, 0x1102, 0x8027, "CT4832", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
484         {0x1102, 0x0002, 0x1102, 0x8028, "CT4760", "SBLive! OEM version", HAS_AC97 | IS_EMU10K1},
485         {0x1102, 0x0002, 0x1102, 0x8031, "CT4831", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
486         {0x1102, 0x0002, 0x1102, 0x8040, "CT4760", "SBLive!", HAS_AC97 | IS_EMU10K1},
487         {0x1102, 0x0002, 0x1102, 0x8051, "CT4850", "SBLive! Value", HAS_AC97 | IS_EMU10K1},
488
489         /* 0x8061..0x???? 5.1 EMU10K1  cards */
490         {0x1102, 0x0002, 0x1102, 0x8061, "SB????", "SBLive! Player 5.1", HAS_AC97 | HAS_51 | IS_EMU10K1},
491         {0x1102, 0x0002, 0x1102, 0x8062, "CT4830", "SBLive! 1024", HAS_AC97 | HAS_51 | IS_EMU10K1},
492         {0x1102, 0x0002, 0x1102, 0x8064, "SB????", "SBLive! 5.1", HAS_AC97 | HAS_51 | IS_EMU10K1},
493         {0x1102, 0x0002, 0x1102, 0x8065, "SB0220", "SBLive! 5.1 Digital", HAS_AC97 | HAS_51 | IS_EMU10K1},
494         {0x1102, 0x0002, 0x1102, 0x8066, "CT4780", "SBLive! 5.1 Digital", HAS_AC97 | HAS_51 | IS_EMU10K1},
495         {0x1102, 0x0002, 0x1102, 0x8067, "SB????", "SBLive!", HAS_AC97 | HAS_51 | IS_EMU10K1},
496
497         /* Generic SB Live! */
498         {0x1102, 0x0002, 0x1102, 0x0000, "SB????", "SBLive! (Unknown model)", HAS_AC97 | IS_EMU10K1},
499
500         /* 0x0041..0x0043 EMU10K2 (some kind of Audigy) cards */
501
502         /* 0x0051..0x0051 5.1 CA0100-IAF cards */
503         {0x1102, 0x0004, 0x1102, 0x0051, "SB0090", "Audigy", HAS_AC97 | HAS_51 | IS_EMU10K2},
504         /* ES is CA0100-IDF chip that don't work in digital mode */
505         {0x1102, 0x0004, 0x1102, 0x0052, "SB0160", "Audigy ES", HAS_AC97 | HAS_71 | IS_EMU10K2 | BROKEN_DIGITAL},
506         /* 0x0053..0x005C 5.1 CA0101-NAF cards */
507         {0x1102, 0x0004, 0x1102, 0x0053, "SB0090", "Audigy Player/OEM", HAS_AC97 | HAS_51 | IS_EMU10K2},
508         {0x1102, 0x0004, 0x1102, 0x0058, "SB0090", "Audigy Player/OEM", HAS_AC97 | HAS_51 | IS_EMU10K2},
509
510         /* 0x1002..0x1009 5.1 CA0102-IAT cards */
511         {0x1102, 0x0004, 0x1102, 0x1002, "SB????", "Audigy 2 Platinum", HAS_51 | IS_CA0102},
512         {0x1102, 0x0004, 0x1102, 0x1005, "SB????", "Audigy 2 Platinum EX", HAS_51 | IS_CA0102},
513         {0x1102, 0x0004, 0x1102, 0x1007, "SB0240", "Audigy 2", HAS_AC97 | HAS_51 | IS_CA0102},
514
515         /* 0x2001..0x2003 7.1 CA0102-ICT cards */
516         {0x1102, 0x0004, 0x1102, 0x2001, "SB0350", "Audigy 2 ZS", HAS_AC97 | HAS_71 | IS_CA0102},
517         {0x1102, 0x0004, 0x1102, 0x2002, "SB0350", "Audigy 2 ZS", HAS_AC97 | HAS_71 | IS_CA0102},
518         /* XXX No reports about 0x2003 & 0x2004 cards */
519         {0x1102, 0x0004, 0x1102, 0x2003, "SB0350", "Audigy 2 ZS", HAS_AC97 | HAS_71 | IS_CA0102},
520         {0x1102, 0x0004, 0x1102, 0x2004, "SB0350", "Audigy 2 ZS", HAS_AC97 | HAS_71 | IS_CA0102},
521         {0x1102, 0x0004, 0x1102, 0x2005, "SB0350", "Audigy 2 ZS", HAS_AC97 | HAS_71 | IS_CA0102},
522
523         /* (range unknown) 7.1 CA0102-xxx Audigy 4 cards */
524         {0x1102, 0x0004, 0x1102, 0x2007, "SB0380", "Audigy 4 Pro", HAS_AC97 | HAS_71 | IS_CA0102},
525
526         /* Generic Audigy or Audigy 2 */
527         {0x1102, 0x0004, 0x1102, 0x0000, "SB????", "Audigy (Unknown model)", HAS_AC97 | HAS_51 | IS_EMU10K2},
528
529         /* We don't support CA0103-DAT (Audigy LS) cards */
530         /* There is NO CA0104-xxx cards */
531         /* There is NO CA0105-xxx cards */
532         /* We don't support CA0106-DAT (SB Live! 24 bit) cards */
533         /* There is NO CA0107-xxx cards */
534
535         /* 0x1000..0x1001 7.1 CA0108-IAT cards */
536         {0x1102, 0x0008, 0x1102, 0x1000, "SB????", "Audigy 2 LS", HAS_AC97 | HAS_51 | IS_CA0108 | DIGITAL_ONLY},
537         {0x1102, 0x0008, 0x1102, 0x1001, "SB0400", "Audigy 2 Value", HAS_AC97 | HAS_71 | IS_CA0108 | DIGITAL_ONLY},
538         {0x1102, 0x0008, 0x1102, 0x1021, "SB0610", "Audigy 4", HAS_AC97 | HAS_71 | IS_CA0108 | DIGITAL_ONLY},
539
540         {0x1102, 0x0008, 0x1102, 0x2001, "SB0530", "Audigy 2 ZS CardBus", HAS_AC97 | HAS_71 | IS_CA0108 | IS_CARDBUS},
541
542         {0x1102, 0x0008, 0x0000, 0x0000, "SB????", "Audigy 2 Value (Unknown model)", HAS_AC97 | HAS_51 | IS_CA0108},
543 };
544 /* Unsupported cards */
545
546 static struct emu_hwinfo emu_bad_cards[] = {
547         /* APS cards should be possible to support */
548         {0x1102, 0x0002, 0x1102, 0x4001, "EMUAPS", "E-mu APS", 0},
549         {0x1102, 0x0002, 0x1102, 0x4002, "EMUAPS", "E-mu APS", 0},
550         {0x1102, 0x0004, 0x1102, 0x4001, "EMU???", "E-mu 1212m [4001]", 0},
551         /* Similar-named ("Live!" or "Audigy") cards on different chipsets */
552         {0x1102, 0x8064, 0x0000, 0x0000, "SB0100", "SBLive! 5.1 OEM", 0},
553         {0x1102, 0x0006, 0x0000, 0x0000, "SB0200", "DELL OEM SBLive! Value", 0},
554         {0x1102, 0x0007, 0x0000, 0x0000, "SB0310", "Audigy LS", 0},
555 };
556
557 /*
558  * Get best known information about device.
559  */
560 static unsigned int
561 emu_getcard(device_t dev)
562 {
563         uint16_t device;
564         uint16_t subdevice;
565         int n_cards;
566         unsigned int thiscard;
567         int i;
568
569         device = pci_read_config(dev, PCIR_DEVICE, /* bytes */ 2);
570         subdevice = pci_read_config(dev, PCIR_SUBDEV_0, /* bytes */ 2);
571
572         n_cards = sizeof(emu_cards) / sizeof(struct emu_hwinfo);
573         thiscard = 0;
574         for (i = 1; i < n_cards; i++) {
575                 if (device == emu_cards[i].device) {
576                         if (subdevice == emu_cards[i].subdevice) {
577                                 thiscard = i;
578                                 break;
579                         }
580                         if (0x0000 == emu_cards[i].subdevice) {
581                                 thiscard = i;
582                                 /*
583                                  * don't break, we can get more specific card
584                                  * later in the list.
585                                  */
586                         }
587                 }
588         }
589
590         n_cards = sizeof(emu_bad_cards) / sizeof(struct emu_hwinfo);
591         for (i = 0; i < n_cards; i++) {
592                 if (device == emu_bad_cards[i].device) {
593                         if (subdevice == emu_bad_cards[i].subdevice) {
594                                 thiscard = 0;
595                                 break;
596                         }
597                         if (0x0000 == emu_bad_cards[i].subdevice) {
598                                 thiscard = 0;
599                                 break;  /* we avoid all this cards */
600                         }
601                 }
602         }
603         return (thiscard);
604 }
605
606
607 /*
608  * Base hardware interface are 32 (Audigy) or 64 (Audigy2) registers.
609  * Some of them are used directly, some of them provide pointer / data pairs.
610  */
611 static uint32_t
612 emu_rd_nolock(struct emu_sc_info *sc, unsigned int regno, unsigned int size)
613 {
614
615         KASSERT(sc != NULL, ("emu_rd: NULL sc"));
616         switch (size) {
617         case 1:
618                 return (bus_space_read_1(sc->st, sc->sh, regno));
619         case 2:
620                 return (bus_space_read_2(sc->st, sc->sh, regno));
621         case 4:
622                 return (bus_space_read_4(sc->st, sc->sh, regno));
623         }
624         return (0xffffffff);
625 }
626
627 static void
628 emu_wr_nolock(struct emu_sc_info *sc, unsigned int regno, uint32_t data, unsigned int size)
629 {
630
631         KASSERT(sc != NULL, ("emu_rd: NULL sc"));
632         switch (size) {
633         case 1:
634                 bus_space_write_1(sc->st, sc->sh, regno, data);
635                 break;
636         case 2:
637                 bus_space_write_2(sc->st, sc->sh, regno, data);
638                 break;
639         case 4:
640                 bus_space_write_4(sc->st, sc->sh, regno, data);
641                 break;
642         }
643 }
644 /*
645  * EMU_PTR / EMU_DATA interface. Access to EMU10Kx is made
646  * via (channel, register) pair. Some registers are channel-specific,
647  * some not.
648  */
649 uint32_t
650 emu_rdptr(struct emu_sc_info *sc, unsigned int chn, unsigned int reg)
651 {
652         uint32_t ptr, val, mask, size, offset;
653
654         ptr = ((reg << 16) & sc->address_mask) | (chn & EMU_PTR_CHNO_MASK);
655
656         EMU_RWLOCK();
657         emu_wr_nolock(sc, EMU_PTR, ptr, 4);
658         val = emu_rd_nolock(sc, EMU_DATA, 4);
659         EMU_RWUNLOCK();
660
661         /*
662          * XXX Some register numbers has data size and offset encoded in
663          * it to get only part of 32bit register. This use is not described
664          * in register name, be careful!
665          */
666         if (reg & 0xff000000) {
667                 size = (reg >> 24) & 0x3f;
668                 offset = (reg >> 16) & 0x1f;
669                 mask = ((1 << size) - 1) << offset;
670                 val &= mask;
671                 val >>= offset;
672         }
673         return (val);
674 }
675
676 void
677 emu_wrptr(struct emu_sc_info *sc, unsigned int chn, unsigned int reg, uint32_t data)
678 {
679         uint32_t ptr, mask, size, offset;
680
681         ptr = ((reg << 16) & sc->address_mask) | (chn & EMU_PTR_CHNO_MASK);
682
683         EMU_RWLOCK();
684         emu_wr_nolock(sc, EMU_PTR, ptr, 4);
685         /*
686          * XXX Another kind of magic encoding in register number. This can
687          * give you side effect - it will read previous data from register
688          * and change only required bits.
689          */
690         if (reg & 0xff000000) {
691                 size = (reg >> 24) & 0x3f;
692                 offset = (reg >> 16) & 0x1f;
693                 mask = ((1 << size) - 1) << offset;
694                 data <<= offset;
695                 data &= mask;
696                 data |= emu_rd_nolock(sc, EMU_DATA, 4) & ~mask;
697         }
698         emu_wr_nolock(sc, EMU_DATA, data, 4);
699         EMU_RWUNLOCK();
700 }
701 /*
702  * EMU_A2_PTR / EMU_DATA2 interface. Access to P16v is made
703  * via (channel, register) pair. Some registers are channel-specific,
704  * some not. This interface is supported by CA0102 and CA0108 chips only.
705  */
706 uint32_t
707 emu_rd_p16vptr(struct emu_sc_info *sc, uint16_t chn, uint16_t reg)
708 {
709         uint32_t val;
710
711         /* XXX separate lock? */
712         EMU_RWLOCK();
713         emu_wr_nolock(sc, EMU_A2_PTR, (reg << 16) | chn, 4);
714         val = emu_rd_nolock(sc, EMU_DATA2, 4);
715
716         EMU_RWUNLOCK();
717
718         return (val);
719 }
720
721 void
722 emu_wr_p16vptr(struct emu_sc_info *sc, uint16_t chn, uint16_t reg, uint32_t data)
723 {
724
725         EMU_RWLOCK();
726         emu_wr_nolock(sc, EMU_A2_PTR, (reg << 16) | chn, 4);
727         emu_wr_nolock(sc, EMU_DATA2, data, 4);
728         EMU_RWUNLOCK();
729 }
730 /*
731  * XXX CardBus interface. Not tested on any real hardware.
732  */
733 static void
734 emu_wr_cbptr(struct emu_sc_info *sc, uint32_t data)
735 {
736         uint32_t val;
737
738         /*
739          * 0x38 is IPE3 (CD S/PDIF interrupt pending register) on CA0102. Seems
740          * to be some reg/value accessible kind of config register on CardBus
741          * CA0108, with value(?) in top 16 bit, address(?) in low 16
742          */
743
744         val = emu_rd_nolock(sc, 0x38, 4);
745         emu_wr_nolock(sc, 0x38, data, 4);
746         val = emu_rd_nolock(sc, 0x38, 4);
747
748 }
749
750 /*
751  * Direct hardware register access
752  * Assume that it is never used to access EMU_PTR-based registers and can run unlocked.
753  */
754 void
755 emu_wr(struct emu_sc_info *sc, unsigned int regno, uint32_t data, unsigned int size)
756 {
757         KASSERT(regno != EMU_PTR, ("emu_wr: attempt to write to EMU_PTR"));
758         KASSERT(regno != EMU_A2_PTR, ("emu_wr: attempt to write to EMU_A2_PTR"));
759
760         emu_wr_nolock(sc, regno, data, size);
761 }
762
763 uint32_t
764 emu_rd(struct emu_sc_info *sc, unsigned int regno, unsigned int size)
765 {
766         uint32_t rd;
767
768         KASSERT(regno != EMU_DATA, ("emu_rd: attempt to read DATA"));
769         KASSERT(regno != EMU_DATA2, ("emu_rd: attempt to read DATA2"));
770
771         rd = emu_rd_nolock(sc, regno, size);
772         return (rd);
773 }
774
775 /*
776  * Enabling IR MIDI messages is another kind of black magic. It just
777  * has to be made this way. It really do it.
778  */
779 void
780 emu_enable_ir(struct emu_sc_info *sc)
781 {
782         uint32_t iocfg;
783
784         if (sc->is_emu10k2 || sc->is_ca0102) {
785                 iocfg = emu_rd_nolock(sc, EMU_A_IOCFG, 2);
786                 emu_wr_nolock(sc, EMU_A_IOCFG, iocfg | EMU_A_IOCFG_GPOUT2, 2);
787                 DELAY(500);
788                 emu_wr_nolock(sc, EMU_A_IOCFG, iocfg | EMU_A_IOCFG_GPOUT1 | EMU_A_IOCFG_GPOUT2, 2);
789                 DELAY(500);
790                 emu_wr_nolock(sc, EMU_A_IOCFG, iocfg | EMU_A_IOCFG_GPOUT1, 2);
791                 DELAY(100);
792                 emu_wr_nolock(sc, EMU_A_IOCFG, iocfg, 2);
793                 device_printf(sc->dev, "Audigy IR MIDI events enabled.\n");
794                 sc->enable_ir = 1;
795         }
796         if (sc->is_emu10k1) {
797                 iocfg = emu_rd_nolock(sc, EMU_HCFG, 4);
798                 emu_wr_nolock(sc, EMU_HCFG, iocfg | EMU_HCFG_GPOUT2, 4);
799                 DELAY(500);
800                 emu_wr_nolock(sc, EMU_HCFG, iocfg | EMU_HCFG_GPOUT1 | EMU_HCFG_GPOUT2, 4);
801                 DELAY(100);
802                 emu_wr_nolock(sc, EMU_HCFG, iocfg, 4);
803                 device_printf(sc->dev, "SB Live! IR MIDI events enabled.\n");
804                 sc->enable_ir = 1;
805         }
806 }
807
808
809 /*
810  * emu_timer_ - HW timer management
811  */
812 int
813 emu_timer_create(struct emu_sc_info *sc)
814 {
815         int i, timer;
816
817         timer = -1;
818
819         lockmgr(&sc->lock, LK_EXCLUSIVE);
820         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++)
821                 if (sc->timer[i] == 0) {
822                         sc->timer[i] = -1;      /* disable it */
823                         timer = i;
824                         lockmgr(&sc->lock, LK_RELEASE);
825                         return (timer);
826                 }
827         lockmgr(&sc->lock, LK_RELEASE);
828
829         return (-1);
830 }
831
832 int
833 emu_timer_set(struct emu_sc_info *sc, int timer, int delay)
834 {
835         int i;
836
837         if (timer < 0)
838                 return (-1);
839
840         RANGE(delay, 16, 1024);
841         RANGE(timer, 0, EMU_MAX_IRQ_CONSUMERS-1);
842
843         lockmgr(&sc->lock, LK_EXCLUSIVE);
844         sc->timer[timer] = delay;
845         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++)
846                 if (sc->timerinterval > sc->timer[i])
847                         sc->timerinterval = sc->timer[i];
848
849         /* XXX */
850         emu_wr(sc, EMU_TIMER, sc->timerinterval & 0x03ff, 2);
851         lockmgr(&sc->lock, LK_RELEASE);
852
853         return (timer);
854 }
855
856 int
857 emu_timer_enable(struct emu_sc_info *sc, int timer, int go)
858 {
859         uint32_t x;
860         int ena_int;
861         int i;
862
863         if (timer < 0)
864                 return (-1);
865
866         RANGE(timer, 0, EMU_MAX_IRQ_CONSUMERS-1);
867
868         lockmgr(&sc->lock, LK_EXCLUSIVE);
869
870         if ((go == 1) && (sc->timer[timer] < 0))
871                 sc->timer[timer] = -sc->timer[timer];
872         if ((go == 0) && (sc->timer[timer] > 0))
873                 sc->timer[timer] = -sc->timer[timer];
874
875         ena_int = 0;
876         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++) {
877                 if (sc->timerinterval > sc->timer[i])
878                         sc->timerinterval = sc->timer[i];
879                 if (sc->timer[i] > 0)
880                         ena_int = 1;
881         }
882
883         emu_wr(sc, EMU_TIMER, sc->timerinterval & 0x03ff, 2);
884
885         if (ena_int == 1) {
886                 x = emu_rd(sc, EMU_INTE, 4);
887                 x |= EMU_INTE_INTERTIMERENB;
888                 emu_wr(sc, EMU_INTE, x, 4);
889         } else {
890                 x = emu_rd(sc, EMU_INTE, 4);
891                 x &= ~EMU_INTE_INTERTIMERENB;
892                 emu_wr(sc, EMU_INTE, x, 4);
893         }
894         lockmgr(&sc->lock, LK_RELEASE);
895         return (0);
896 }
897
898 int
899 emu_timer_clear(struct emu_sc_info *sc, int timer)
900 {
901         if (timer < 0)
902                 return (-1);
903
904         RANGE(timer, 0, EMU_MAX_IRQ_CONSUMERS-1);
905
906         emu_timer_enable(sc, timer, 0);
907
908         lockmgr(&sc->lock, LK_EXCLUSIVE);
909         if (sc->timer[timer] != 0)
910                 sc->timer[timer] = 0;
911         lockmgr(&sc->lock, LK_RELEASE);
912
913         return (timer);
914 }
915
916 /*
917  * emu_intr_ - HW interrupt handler management
918  */
919 int
920 emu_intr_register(struct emu_sc_info *sc, uint32_t inte_mask, uint32_t intr_mask, uint32_t(*func) (void *softc, uint32_t irq), void *isc)
921 {
922         int i;
923         uint32_t x;
924
925         lockmgr(&sc->lock, LK_EXCLUSIVE);
926         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++)
927                 if (sc->ihandler[i].inte_mask == 0) {
928                         sc->ihandler[i].inte_mask = inte_mask;
929                         sc->ihandler[i].intr_mask = intr_mask;
930                         sc->ihandler[i].softc = isc;
931                         sc->ihandler[i].irq_func = func;
932                         x = emu_rd(sc, EMU_INTE, 4);
933                         x |= inte_mask;
934                         emu_wr(sc, EMU_INTE, x, 4);
935                         lockmgr(&sc->lock, LK_RELEASE);
936                         if (sc->dbg_level > 1)
937                                 device_printf(sc->dev, "ihandle %d registered\n", i);
938
939                         return (i);
940                 }
941         lockmgr(&sc->lock, LK_RELEASE);
942         if (sc->dbg_level > 1)
943                 device_printf(sc->dev, "ihandle not registered\n");
944
945         return (-1);
946 }
947
948 int
949 emu_intr_unregister(struct emu_sc_info *sc, int hnumber)
950 {
951         uint32_t x;
952         int i;
953
954         lockmgr(&sc->lock, LK_EXCLUSIVE);
955
956         if (sc->ihandler[hnumber].inte_mask == 0) {
957                 lockmgr(&sc->lock, LK_RELEASE);
958                 return (-1);
959         }
960
961         x = emu_rd(sc, EMU_INTE, 4);
962         x &= ~sc->ihandler[hnumber].inte_mask;
963
964         sc->ihandler[hnumber].inte_mask = 0;
965         sc->ihandler[hnumber].intr_mask = 0;
966         sc->ihandler[hnumber].softc = NULL;
967         sc->ihandler[hnumber].irq_func = NULL;
968
969         /* other interrupt handlers may use this EMU_INTE value */
970         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++)
971                 if (sc->ihandler[i].inte_mask != 0)
972                         x |= sc->ihandler[i].inte_mask;
973
974         emu_wr(sc, EMU_INTE, x, 4);
975
976         lockmgr(&sc->lock, LK_RELEASE);
977         return (hnumber);
978 }
979
980 static void
981 emu_intr(void *p)
982 {
983         struct emu_sc_info *sc = (struct emu_sc_info *)p;
984         uint32_t stat, ack;
985         int i;
986
987         for (;;) {
988                 stat = emu_rd(sc, EMU_IPR, 4);
989                 ack = 0;
990                 if (stat == 0)
991                         break;
992                 emu_wr(sc, EMU_IPR, stat, 4);
993                 for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++) {
994                         if ((((sc->ihandler[i].intr_mask) & stat) != 0) &&
995                             (((void *)sc->ihandler[i].irq_func) != NULL)) {
996                                 ack |= sc->ihandler[i].irq_func(sc->ihandler[i].softc,
997                                     (sc->ihandler[i].intr_mask) & stat);
998                         }
999                 }
1000         if (sc->dbg_level > 1)
1001                 if (stat & (~ack))
1002                         device_printf(sc->dev, "Unhandled interrupt: %08x\n", stat & (~ack));
1003
1004         }
1005
1006         if ((sc->is_ca0102) || (sc->is_ca0108))
1007                 for (;;) {
1008                         stat = emu_rd(sc, EMU_IPR2, 4);
1009                         ack = 0;
1010                         if (stat == 0)
1011                                 break;
1012                         emu_wr(sc, EMU_IPR2, stat, 4);
1013                         if (sc->dbg_level > 1)
1014                                 device_printf(sc->dev, "EMU_IPR2: %08x\n", stat);
1015
1016                         break;  /* to avoid infinite loop. should be removed
1017                                  * after completion of P16V interface. */
1018                 }
1019
1020         if (sc->is_ca0102)
1021                 for (;;) {
1022                         stat = emu_rd(sc, EMU_IPR3, 4);
1023                         ack = 0;
1024                         if (stat == 0)
1025                                 break;
1026                         emu_wr(sc, EMU_IPR3, stat, 4);
1027                         if (sc->dbg_level > 1)
1028                                 device_printf(sc->dev, "EMU_IPR3: %08x\n", stat);
1029
1030                         break;  /* to avoid infinite loop. should be removed
1031                                  * after completion of S/PDIF interface */
1032                 }
1033 }
1034
1035
1036 /*
1037  * Get data from private emu10kx structure for PCM buffer allocation.
1038  * Used by PCM code only.
1039  */
1040 bus_dma_tag_t
1041 emu_gettag(struct emu_sc_info *sc)
1042 {
1043         return (sc->mem.dmat);
1044 }
1045
1046 static void
1047 emu_setmap(void *arg, bus_dma_segment_t * segs, int nseg, int error)
1048 {
1049         bus_addr_t *phys = (bus_addr_t *) arg;
1050
1051         *phys = error ? 0 : (bus_addr_t) segs->ds_addr;
1052
1053         if (bootverbose) {
1054                 kprintf("emu10kx: setmap (%lx, %lx), nseg=%d, error=%d\n",
1055                     (unsigned long)segs->ds_addr, (unsigned long)segs->ds_len,
1056                     nseg, error);
1057         }
1058 }
1059
1060 static void *
1061 emu_malloc(struct emu_mem *mem, uint32_t sz, bus_addr_t * addr,
1062     bus_dmamap_t *map)
1063 {
1064         void *dmabuf;
1065         int error;
1066
1067         *addr = 0;
1068         if ((error = bus_dmamem_alloc(mem->dmat, &dmabuf, BUS_DMA_NOWAIT, map))) {
1069                 if (mem->card->dbg_level > 2)
1070                         device_printf(mem->card->dev, "emu_malloc: failed to alloc DMA map: %d\n", error);
1071                 return (NULL);
1072                 }
1073         if ((error = bus_dmamap_load(mem->dmat, *map, dmabuf, sz, emu_setmap, addr, 0)) || !*addr) {
1074                 if (mem->card->dbg_level > 2)
1075                         device_printf(mem->card->dev, "emu_malloc: failed to load DMA memory: %d\n", error);
1076                 bus_dmamem_free(mem->dmat, dmabuf, *map);
1077                 return (NULL);
1078                 }
1079         return (dmabuf);
1080 }
1081
1082 static void
1083 emu_free(struct emu_mem *mem, void *dmabuf, bus_dmamap_t map)
1084 {
1085         bus_dmamap_unload(mem->dmat, map);
1086         bus_dmamem_free(mem->dmat, dmabuf, map);
1087 }
1088
1089 static void *
1090 emu_memalloc(struct emu_mem *mem, uint32_t sz, bus_addr_t * addr, const char *owner)
1091 {
1092         uint32_t blksz, start, idx, ofs, tmp, found;
1093         struct emu_memblk *blk;
1094         void *membuf;
1095
1096         blksz = sz / EMUPAGESIZE;
1097         if (sz > (blksz * EMUPAGESIZE))
1098                 blksz++;
1099         if (blksz > EMU_MAX_BUFSZ / EMUPAGESIZE) {
1100                 if (mem->card->dbg_level > 2)
1101                         device_printf(mem->card->dev, "emu_memalloc: memory request tool large\n");
1102                 return (NULL);
1103                 }
1104         /* find a free block in the bitmap */
1105         found = 0;
1106         start = 1;
1107         while (!found && start + blksz < EMU_MAXPAGES) {
1108                 found = 1;
1109                 for (idx = start; idx < start + blksz; idx++)
1110                         if (mem->bmap[idx >> 3] & (1 << (idx & 7)))
1111                                 found = 0;
1112                 if (!found)
1113                         start++;
1114         }
1115         if (!found) {
1116                 if (mem->card->dbg_level > 2)
1117                         device_printf(mem->card->dev, "emu_memalloc: no free space in bitmap\n");
1118                 return (NULL);
1119                 }
1120         blk = kmalloc(sizeof(*blk), M_DEVBUF, M_NOWAIT);
1121         if (blk == NULL) {
1122                 if (mem->card->dbg_level > 2)
1123                         device_printf(mem->card->dev, "emu_memalloc: buffer allocation failed\n");
1124                 return (NULL);
1125                 }
1126         bzero(blk, sizeof(*blk));
1127         membuf = emu_malloc(mem, sz, &blk->buf_addr, &blk->buf_map);
1128         *addr = blk->buf_addr;
1129         if (membuf == NULL) {
1130                 if (mem->card->dbg_level > 2)
1131                         device_printf(mem->card->dev, "emu_memalloc: can't setup HW memory\n");
1132                 kfree(blk, M_DEVBUF);
1133                 return (NULL);
1134         }
1135         blk->buf = membuf;
1136         blk->pte_start = start;
1137         blk->pte_size = blksz;
1138         strncpy(blk->owner, owner, 15);
1139         blk->owner[15] = '\0';
1140         ofs = 0;
1141         for (idx = start; idx < start + blksz; idx++) {
1142                 mem->bmap[idx >> 3] |= 1 << (idx & 7);
1143                 tmp = (uint32_t) (blk->buf_addr + ofs);
1144                 mem->ptb_pages[idx] = (tmp << 1) | idx;
1145                 ofs += EMUPAGESIZE;
1146         }
1147         SLIST_INSERT_HEAD(&mem->blocks, blk, link);
1148         return (membuf);
1149 }
1150
1151 static int
1152 emu_memfree(struct emu_mem *mem, void *membuf)
1153 {
1154         uint32_t idx, tmp;
1155         struct emu_memblk *blk, *i;
1156
1157         blk = NULL;
1158         SLIST_FOREACH(i, &mem->blocks, link) {
1159                 if (i->buf == membuf)
1160                         blk = i;
1161         }
1162         if (blk == NULL)
1163                 return (EINVAL);
1164         SLIST_REMOVE(&mem->blocks, blk, emu_memblk, link);
1165         emu_free(mem, membuf, blk->buf_map);
1166         tmp = (uint32_t) (mem->silent_page_addr) << 1;
1167         for (idx = blk->pte_start; idx < blk->pte_start + blk->pte_size; idx++) {
1168                 mem->bmap[idx >> 3] &= ~(1 << (idx & 7));
1169                 mem->ptb_pages[idx] = tmp | idx;
1170         }
1171         kfree(blk, M_DEVBUF);
1172         return (0);
1173 }
1174
1175 static int
1176 emu_memstart(struct emu_mem *mem, void *membuf)
1177 {
1178         struct emu_memblk *blk, *i;
1179
1180         blk = NULL;
1181         SLIST_FOREACH(i, &mem->blocks, link) {
1182                 if (i->buf == membuf)
1183                         blk = i;
1184         }
1185         if (blk == NULL)
1186                 return (-1);
1187         return (blk->pte_start);
1188 }
1189
1190
1191 static uint32_t
1192 emu_rate_to_pitch(uint32_t rate)
1193 {
1194         static uint32_t logMagTable[128] = {
1195                 0x00000, 0x02dfc, 0x05b9e, 0x088e6, 0x0b5d6, 0x0e26f, 0x10eb3, 0x13aa2,
1196                 0x1663f, 0x1918a, 0x1bc84, 0x1e72e, 0x2118b, 0x23b9a, 0x2655d, 0x28ed5,
1197                 0x2b803, 0x2e0e8, 0x30985, 0x331db, 0x359eb, 0x381b6, 0x3a93d, 0x3d081,
1198                 0x3f782, 0x41e42, 0x444c1, 0x46b01, 0x49101, 0x4b6c4, 0x4dc49, 0x50191,
1199                 0x5269e, 0x54b6f, 0x57006, 0x59463, 0x5b888, 0x5dc74, 0x60029, 0x623a7,
1200                 0x646ee, 0x66a00, 0x68cdd, 0x6af86, 0x6d1fa, 0x6f43c, 0x7164b, 0x73829,
1201                 0x759d4, 0x77b4f, 0x79c9a, 0x7bdb5, 0x7dea1, 0x7ff5e, 0x81fed, 0x8404e,
1202                 0x86082, 0x88089, 0x8a064, 0x8c014, 0x8df98, 0x8fef1, 0x91e20, 0x93d26,
1203                 0x95c01, 0x97ab4, 0x9993e, 0x9b79f, 0x9d5d9, 0x9f3ec, 0xa11d8, 0xa2f9d,
1204                 0xa4d3c, 0xa6ab5, 0xa8808, 0xaa537, 0xac241, 0xadf26, 0xafbe7, 0xb1885,
1205                 0xb3500, 0xb5157, 0xb6d8c, 0xb899f, 0xba58f, 0xbc15e, 0xbdd0c, 0xbf899,
1206                 0xc1404, 0xc2f50, 0xc4a7b, 0xc6587, 0xc8073, 0xc9b3f, 0xcb5ed, 0xcd07c,
1207                 0xceaec, 0xd053f, 0xd1f73, 0xd398a, 0xd5384, 0xd6d60, 0xd8720, 0xda0c3,
1208                 0xdba4a, 0xdd3b4, 0xded03, 0xe0636, 0xe1f4e, 0xe384a, 0xe512c, 0xe69f3,
1209                 0xe829f, 0xe9b31, 0xeb3a9, 0xecc08, 0xee44c, 0xefc78, 0xf148a, 0xf2c83,
1210                 0xf4463, 0xf5c2a, 0xf73da, 0xf8b71, 0xfa2f0, 0xfba57, 0xfd1a7, 0xfe8df
1211         };
1212         static char logSlopeTable[128] = {
1213                 0x5c, 0x5c, 0x5b, 0x5a, 0x5a, 0x59, 0x58, 0x58,
1214                 0x57, 0x56, 0x56, 0x55, 0x55, 0x54, 0x53, 0x53,
1215                 0x52, 0x52, 0x51, 0x51, 0x50, 0x50, 0x4f, 0x4f,
1216                 0x4e, 0x4d, 0x4d, 0x4d, 0x4c, 0x4c, 0x4b, 0x4b,
1217                 0x4a, 0x4a, 0x49, 0x49, 0x48, 0x48, 0x47, 0x47,
1218                 0x47, 0x46, 0x46, 0x45, 0x45, 0x45, 0x44, 0x44,
1219                 0x43, 0x43, 0x43, 0x42, 0x42, 0x42, 0x41, 0x41,
1220                 0x41, 0x40, 0x40, 0x40, 0x3f, 0x3f, 0x3f, 0x3e,
1221                 0x3e, 0x3e, 0x3d, 0x3d, 0x3d, 0x3c, 0x3c, 0x3c,
1222                 0x3b, 0x3b, 0x3b, 0x3b, 0x3a, 0x3a, 0x3a, 0x39,
1223                 0x39, 0x39, 0x39, 0x38, 0x38, 0x38, 0x38, 0x37,
1224                 0x37, 0x37, 0x37, 0x36, 0x36, 0x36, 0x36, 0x35,
1225                 0x35, 0x35, 0x35, 0x34, 0x34, 0x34, 0x34, 0x34,
1226                 0x33, 0x33, 0x33, 0x33, 0x32, 0x32, 0x32, 0x32,
1227                 0x32, 0x31, 0x31, 0x31, 0x31, 0x31, 0x30, 0x30,
1228                 0x30, 0x30, 0x30, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f
1229         };
1230         int i;
1231
1232         if (rate == 0)
1233                 return (0);
1234         rate *= 11185;          /* Scale 48000 to 0x20002380 */
1235         for (i = 31; i > 0; i--) {
1236                 if (rate & 0x80000000) {        /* Detect leading "1" */
1237                         return (((uint32_t) (i - 15) << 20) +
1238                             logMagTable[0x7f & (rate >> 24)] +
1239                             (0x7f & (rate >> 17)) *
1240                             logSlopeTable[0x7f & (rate >> 24)]);
1241                 }
1242                 rate <<= 1;
1243         }
1244         /* NOTREACHED */
1245         return (0);
1246 }
1247
1248 static uint32_t
1249 emu_rate_to_linearpitch(uint32_t rate)
1250 {
1251         rate = (rate << 8) / 375;
1252         return ((rate >> 1) + (rate & 1));
1253 }
1254
1255 struct emu_voice *
1256 emu_valloc(struct emu_sc_info *sc)
1257 {
1258         struct emu_voice *v;
1259         int i;
1260
1261         v = NULL;
1262         lockmgr(&sc->lock, LK_EXCLUSIVE);
1263         for (i = 0; i < NUM_G && sc->voice[i].busy; i++);
1264         if (i < NUM_G) {
1265                 v = &sc->voice[i];
1266                 v->busy = 1;
1267         }
1268         lockmgr(&sc->lock, LK_RELEASE);
1269         return (v);
1270 }
1271
1272 void
1273 emu_vfree(struct emu_sc_info *sc, struct emu_voice *v)
1274 {
1275         int i, r;
1276
1277         lockmgr(&sc->lock, LK_EXCLUSIVE);
1278         for (i = 0; i < NUM_G; i++) {
1279                 if (v == &sc->voice[i] && sc->voice[i].busy) {
1280                         v->busy = 0;
1281                         /*
1282                          * XXX What we should do with mono channels?
1283                          * See -pcm.c emupchan_init for other side of
1284                          * this problem
1285                          */
1286                         if (v->slave != NULL)
1287                                 r = emu_memfree(&sc->mem, v->vbuf);
1288                 }
1289         }
1290         lockmgr(&sc->lock, LK_RELEASE);
1291 }
1292
1293 int
1294 emu_vinit(struct emu_sc_info *sc, struct emu_voice *m, struct emu_voice *s,
1295     uint32_t sz, struct snd_dbuf *b)
1296 {
1297         void *vbuf;
1298         bus_addr_t tmp_addr;
1299
1300         vbuf = emu_memalloc(&sc->mem, sz, &tmp_addr, "vinit");
1301         if (vbuf == NULL) {
1302                 if(sc->dbg_level > 2)
1303                         device_printf(sc->dev, "emu_memalloc returns NULL in enu_vinit\n");
1304                 return (ENOMEM);
1305                 }
1306         if (b != NULL)
1307                 sndbuf_setup(b, vbuf, sz);
1308         m->start = emu_memstart(&sc->mem, vbuf) * EMUPAGESIZE;
1309         if (m->start < 0) {
1310                 if(sc->dbg_level > 2)
1311                         device_printf(sc->dev, "emu_memstart returns (-1) in enu_vinit\n");
1312                 emu_memfree(&sc->mem, vbuf);
1313                 return (ENOMEM);
1314         }
1315         m->end = m->start + sz;
1316         m->speed = 0;
1317         m->b16 = 0;
1318         m->stereo = 0;
1319         m->running = 0;
1320         m->ismaster = 1;
1321         m->vol = 0xff;
1322         m->buf = tmp_addr;
1323         m->vbuf = vbuf;
1324         m->slave = s;
1325         if (s != NULL) {
1326                 s->start = m->start;
1327                 s->end = m->end;
1328                 s->speed = 0;
1329                 s->b16 = 0;
1330                 s->stereo = 0;
1331                 s->running = 0;
1332                 s->ismaster = 0;
1333                 s->vol = m->vol;
1334                 s->buf = m->buf;
1335                 s->vbuf = NULL;
1336                 s->slave = NULL;
1337         }
1338         return (0);
1339 }
1340
1341 void
1342 emu_vsetup(struct emu_voice *v, int fmt, int spd)
1343 {
1344         if (fmt) {
1345                 v->b16 = (fmt & AFMT_16BIT) ? 1 : 0;
1346                 v->stereo = (AFMT_CHANNEL(fmt) > 1) ? 1 : 0;
1347                 if (v->slave != NULL) {
1348                         v->slave->b16 = v->b16;
1349                         v->slave->stereo = v->stereo;
1350                 }
1351         }
1352         if (spd) {
1353                 v->speed = spd;
1354                 if (v->slave != NULL)
1355                         v->slave->speed = v->speed;
1356         }
1357 }
1358
1359 void
1360 emu_vroute(struct emu_sc_info *sc, struct emu_route *rt,  struct emu_voice *v)
1361 {
1362         int i;
1363
1364         for (i = 0; i < 8; i++) {
1365                 v->routing[i] = rt->routing_left[i];
1366                 v->amounts[i] = rt->amounts_left[i];
1367         }
1368         if ((v->stereo) && (v->ismaster == 0))
1369                 for (i = 0; i < 8; i++) {
1370                         v->routing[i] = rt->routing_right[i];
1371                         v->amounts[i] = rt->amounts_right[i];
1372                 }
1373
1374         if ((v->stereo) && (v->slave != NULL))
1375                 emu_vroute(sc, rt, v->slave);
1376 }
1377
1378 void
1379 emu_vwrite(struct emu_sc_info *sc, struct emu_voice *v)
1380 {
1381         int s;
1382         uint32_t start, val, silent_page;
1383
1384         s = (v->stereo ? 1 : 0) + (v->b16 ? 1 : 0);
1385
1386         v->sa = v->start >> s;
1387         v->ea = v->end >> s;
1388
1389
1390         if (v->stereo) {
1391                 emu_wrptr(sc, v->vnum, EMU_CHAN_CPF, EMU_CHAN_CPF_STEREO_MASK);
1392         } else {
1393                 emu_wrptr(sc, v->vnum, EMU_CHAN_CPF, 0);
1394         }
1395         val = v->stereo ? 28 : 30;
1396         val *= v->b16 ? 1 : 2;
1397         start = v->sa + val;
1398
1399         if (sc->is_emu10k1) {
1400                 emu_wrptr(sc, v->vnum, EMU_CHAN_FXRT, ((v->routing[3] << 12) |
1401                     (v->routing[2] << 8) |
1402                     (v->routing[1] << 4) |
1403                     (v->routing[0] << 0)) << 16);
1404         } else {
1405                 emu_wrptr(sc, v->vnum, EMU_A_CHAN_FXRT1, (v->routing[3] << 24) |
1406                     (v->routing[2] << 16) |
1407                     (v->routing[1] << 8) |
1408                     (v->routing[0] << 0));
1409                 emu_wrptr(sc, v->vnum, EMU_A_CHAN_FXRT2, (v->routing[7] << 24) |
1410                     (v->routing[6] << 16) |
1411                     (v->routing[5] << 8) |
1412                     (v->routing[4] << 0));
1413                 emu_wrptr(sc, v->vnum, EMU_A_CHAN_SENDAMOUNTS, (v->amounts[7] << 24) |
1414                     (v->amounts[6] << 26) |
1415                     (v->amounts[5] << 8) |
1416                     (v->amounts[4] << 0));
1417         }
1418         emu_wrptr(sc, v->vnum, EMU_CHAN_PTRX, (v->amounts[0] << 8) | (v->amounts[1] << 0));
1419         emu_wrptr(sc, v->vnum, EMU_CHAN_DSL, v->ea | (v->amounts[3] << 24));
1420         emu_wrptr(sc, v->vnum, EMU_CHAN_PSST, v->sa | (v->amounts[2] << 24));
1421
1422         emu_wrptr(sc, v->vnum, EMU_CHAN_CCCA, start | (v->b16 ? 0 : EMU_CHAN_CCCA_8BITSELECT));
1423         emu_wrptr(sc, v->vnum, EMU_CHAN_Z1, 0);
1424         emu_wrptr(sc, v->vnum, EMU_CHAN_Z2, 0);
1425
1426         silent_page = ((uint32_t) (sc->mem.silent_page_addr) << 1) | EMU_CHAN_MAP_PTI_MASK;
1427         emu_wrptr(sc, v->vnum, EMU_CHAN_MAPA, silent_page);
1428         emu_wrptr(sc, v->vnum, EMU_CHAN_MAPB, silent_page);
1429
1430         emu_wrptr(sc, v->vnum, EMU_CHAN_CVCF, EMU_CHAN_CVCF_CURRFILTER_MASK);
1431         emu_wrptr(sc, v->vnum, EMU_CHAN_VTFT, EMU_CHAN_VTFT_FILTERTARGET_MASK);
1432         emu_wrptr(sc, v->vnum, EMU_CHAN_ATKHLDM, 0);
1433         emu_wrptr(sc, v->vnum, EMU_CHAN_DCYSUSM, EMU_CHAN_DCYSUSM_DECAYTIME_MASK);
1434         emu_wrptr(sc, v->vnum, EMU_CHAN_LFOVAL1, 0x8000);
1435         emu_wrptr(sc, v->vnum, EMU_CHAN_LFOVAL2, 0x8000);
1436         emu_wrptr(sc, v->vnum, EMU_CHAN_FMMOD, 0);
1437         emu_wrptr(sc, v->vnum, EMU_CHAN_TREMFRQ, 0);
1438         emu_wrptr(sc, v->vnum, EMU_CHAN_FM2FRQ2, 0);
1439         emu_wrptr(sc, v->vnum, EMU_CHAN_ENVVAL, 0x8000);
1440
1441         emu_wrptr(sc, v->vnum, EMU_CHAN_ATKHLDV, EMU_CHAN_ATKHLDV_HOLDTIME_MASK | EMU_CHAN_ATKHLDV_ATTACKTIME_MASK);
1442         emu_wrptr(sc, v->vnum, EMU_CHAN_ENVVOL, 0x8000);
1443
1444         emu_wrptr(sc, v->vnum, EMU_CHAN_PEFE_FILTERAMOUNT, 0x7f);
1445         emu_wrptr(sc, v->vnum, EMU_CHAN_PEFE_PITCHAMOUNT, 0);
1446         if ((v->stereo) && (v->slave != NULL))
1447                 emu_vwrite(sc, v->slave);
1448 }
1449
1450 static void
1451 emu_vstop(struct emu_sc_info *sc, char channel, int enable)
1452 {
1453         int reg;
1454
1455         reg = (channel & 0x20) ? EMU_SOLEH : EMU_SOLEL;
1456         channel &= 0x1f;
1457         reg |= 1 << 24;
1458         reg |= channel << 16;
1459         emu_wrptr(sc, 0, reg, enable);
1460 }
1461
1462 void
1463 emu_vtrigger(struct emu_sc_info *sc, struct emu_voice *v, int go)
1464 {
1465         uint32_t pitch_target, initial_pitch;
1466         uint32_t cra, cs, ccis;
1467         uint32_t sample, i;
1468
1469         if (go) {
1470                 cra = 64;
1471                 cs = v->stereo ? 4 : 2;
1472                 ccis = v->stereo ? 28 : 30;
1473                 ccis *= v->b16 ? 1 : 2;
1474                 sample = v->b16 ? 0x00000000 : 0x80808080;
1475                 for (i = 0; i < cs; i++)
1476                         emu_wrptr(sc, v->vnum, EMU_CHAN_CD0 + i, sample);
1477                 emu_wrptr(sc, v->vnum, EMU_CHAN_CCR_CACHEINVALIDSIZE, 0);
1478                 emu_wrptr(sc, v->vnum, EMU_CHAN_CCR_READADDRESS, cra);
1479                 emu_wrptr(sc, v->vnum, EMU_CHAN_CCR_CACHEINVALIDSIZE, ccis);
1480
1481                 emu_wrptr(sc, v->vnum, EMU_CHAN_IFATN, 0xff00);
1482                 emu_wrptr(sc, v->vnum, EMU_CHAN_VTFT, 0xffffffff);
1483                 emu_wrptr(sc, v->vnum, EMU_CHAN_CVCF, 0xffffffff);
1484                 emu_wrptr(sc, v->vnum, EMU_CHAN_DCYSUSV, 0x00007f7f);
1485                 emu_vstop(sc, v->vnum, 0);
1486
1487                 pitch_target = emu_rate_to_linearpitch(v->speed);
1488                 initial_pitch = emu_rate_to_pitch(v->speed) >> 8;
1489                 emu_wrptr(sc, v->vnum, EMU_CHAN_PTRX_PITCHTARGET, pitch_target);
1490                 emu_wrptr(sc, v->vnum, EMU_CHAN_CPF_PITCH, pitch_target);
1491                 emu_wrptr(sc, v->vnum, EMU_CHAN_IP, initial_pitch);
1492         } else {
1493                 emu_wrptr(sc, v->vnum, EMU_CHAN_PTRX_PITCHTARGET, 0);
1494                 emu_wrptr(sc, v->vnum, EMU_CHAN_CPF_PITCH, 0);
1495                 emu_wrptr(sc, v->vnum, EMU_CHAN_IFATN, 0xffff);
1496                 emu_wrptr(sc, v->vnum, EMU_CHAN_VTFT, 0x0000ffff);
1497                 emu_wrptr(sc, v->vnum, EMU_CHAN_CVCF, 0x0000ffff);
1498                 emu_wrptr(sc, v->vnum, EMU_CHAN_IP, 0);
1499                 emu_vstop(sc, v->vnum, 1);
1500         }
1501         if ((v->stereo) && (v->slave != NULL))
1502                 emu_vtrigger(sc, v->slave, go);
1503 }
1504
1505 int
1506 emu_vpos(struct emu_sc_info *sc, struct emu_voice *v)
1507 {
1508         int s, ptr;
1509
1510         s = (v->b16 ? 1 : 0) + (v->stereo ? 1 : 0);
1511         ptr = (emu_rdptr(sc, v->vnum, EMU_CHAN_CCCA_CURRADDR) - (v->start >> s)) << s;
1512         return (ptr & ~0x0000001f);
1513 }
1514
1515
1516 /* fx */
1517 static void
1518 emu_wrefx(struct emu_sc_info *sc, unsigned int pc, unsigned int data)
1519 {
1520         emu_wrptr(sc, 0, sc->code_base + pc, data);
1521 }
1522
1523
1524 static void
1525 emu_addefxop(struct emu_sc_info *sc, unsigned int op, unsigned int z, unsigned int w, unsigned int x, unsigned int y, uint32_t * pc)
1526 {
1527         if ((*pc) + 1 > sc->code_size) {
1528                 device_printf(sc->dev, "DSP CODE OVERRUN: attept to write past code_size (pc=%d)\n", (*pc));
1529                 return;
1530         }
1531         emu_wrefx(sc, (*pc) * 2, (x << sc->high_operand_shift) | y);
1532         emu_wrefx(sc, (*pc) * 2 + 1, (op << sc->opcode_shift) | (z << sc->high_operand_shift) | w);
1533         (*pc)++;
1534 }
1535
1536 static int
1537 sysctl_emu_mixer_control(SYSCTL_HANDLER_ARGS)
1538 {
1539         struct emu_sc_info *sc;
1540         int     mixer_id;
1541         int     new_vol;
1542         int     err;
1543
1544         sc = arg1;
1545         mixer_id = arg2;
1546
1547         new_vol = emumix_get_volume(sc, mixer_id);
1548         err = sysctl_handle_int(oidp, &new_vol, 0, req);
1549
1550         if (err || req->newptr == NULL)
1551                 return (err);
1552         if (new_vol < 0 || new_vol > 100)
1553                 return (EINVAL);
1554         emumix_set_volume(sc, mixer_id, new_vol);
1555
1556         return (0);
1557 }
1558
1559 static int
1560 emu_addefxmixer(struct emu_sc_info *sc, const char *mix_name, const int mix_id, uint32_t defvolume)
1561 {
1562         int volgpr;
1563         char    sysctl_name[32];
1564
1565         volgpr = emu_rm_gpr_alloc(sc->rm, 1);
1566         emumix_set_fxvol(sc, volgpr, defvolume);
1567         /*
1568          * Mixer controls with NULL mix_name are handled
1569          * by AC97 emulation code or PCM mixer.
1570          */
1571         if (mix_name != NULL) {
1572                 /*
1573                  * Temporary sysctls should start with underscore,
1574                  * see freebsd-current mailing list, emu10kx driver
1575                  * discussion around 2006-05-24.
1576                  */
1577                 ksnprintf(sysctl_name, 32, "_%s", mix_name);
1578                 SYSCTL_ADD_PROC(sc->ctx,
1579                         SYSCTL_CHILDREN(sc->root),
1580                         OID_AUTO, sysctl_name,
1581                         CTLTYPE_INT | CTLFLAG_RW, sc, mix_id,
1582                         sysctl_emu_mixer_control, "I", "");
1583         }
1584
1585         return (volgpr);
1586 }
1587
1588 static int
1589 sysctl_emu_digitalswitch_control(SYSCTL_HANDLER_ARGS)
1590 {
1591         struct emu_sc_info *sc;
1592         int     new_val;
1593         int     err;
1594
1595         sc = arg1;
1596
1597         new_val = (sc->mode == MODE_DIGITAL) ? 1 : 0;   
1598         err = sysctl_handle_int(oidp, &new_val, 0, req);
1599
1600         if (err || req->newptr == NULL)
1601                 return (err);
1602         if (new_val < 0 || new_val > 1)
1603                 return (EINVAL);
1604
1605         switch (new_val) {
1606                 case 0:
1607                         emumix_set_mode(sc, MODE_ANALOG);
1608                         break;
1609                 case 1:
1610                         emumix_set_mode(sc, MODE_DIGITAL);
1611                         break;
1612         }
1613         return (0);
1614 }
1615
1616 static void
1617 emu_digitalswitch(struct emu_sc_info *sc)
1618 {
1619         /* XXX temporary? */
1620         SYSCTL_ADD_PROC(sc->ctx,
1621                 SYSCTL_CHILDREN(sc->root),
1622                 OID_AUTO, "_digital",
1623                 CTLTYPE_INT | CTLFLAG_RW, sc, 0,
1624                 sysctl_emu_digitalswitch_control, "I", "Enable digital output");
1625
1626         return;
1627 }
1628
1629 /*
1630  * Allocate cache GPRs that will hold mixed output channels
1631  * and clear it on every DSP run.
1632  */
1633 #define EFX_CACHE(CACHE_IDX) do {                               \
1634         sc->cache_gpr[CACHE_IDX] = emu_rm_gpr_alloc(sc->rm, 1); \
1635         emu_addefxop(sc, ACC3,                                  \
1636                 GPR(sc->cache_gpr[CACHE_IDX]),                  \
1637                 DSP_CONST(0),                                   \
1638                 DSP_CONST(0),                                   \
1639                 DSP_CONST(0),                                   \
1640                 &pc);                                           \
1641 } while (0)
1642
1643 /* Allocate GPR for volume control and route sound: OUT = OUT + IN * VOL */
1644 #define EFX_ROUTE(TITLE, INP_NR, IN_GPR_IDX, OUT_CACHE_IDX, DEF) do {   \
1645         sc->mixer_gpr[IN_GPR_IDX] = emu_addefxmixer(sc, TITLE, IN_GPR_IDX,  DEF); \
1646         sc->mixer_volcache[IN_GPR_IDX] = DEF;                   \
1647         emu_addefxop(sc, MACS,                                  \
1648                 GPR(sc->cache_gpr[OUT_CACHE_IDX]),              \
1649                 GPR(sc->cache_gpr[OUT_CACHE_IDX]),              \
1650                 INP_NR,                                         \
1651                 GPR(sc->mixer_gpr[IN_GPR_IDX]),                 \
1652                 &pc);                                           \
1653 } while (0)
1654
1655 /* allocate GPR, OUT = IN * VOL */
1656 #define EFX_OUTPUT(TITLE, OUT_CACHE_IDX, OUT_GPR_IDX, OUTP_NR, DEF) do {        \
1657         sc->mixer_gpr[OUT_GPR_IDX] = emu_addefxmixer(sc, TITLE, OUT_GPR_IDX, DEF); \
1658         sc->mixer_volcache[OUT_GPR_IDX] = DEF;                  \
1659         emu_addefxop(sc, MACS,                                  \
1660                 OUTP(OUTP_NR),                                  \
1661                 DSP_CONST(0),                                   \
1662                 GPR(sc->cache_gpr[OUT_CACHE_IDX]),              \
1663                 GPR(sc->mixer_gpr[OUT_GPR_IDX]),                \
1664                 &pc);                                           \
1665 } while (0)
1666
1667 /* like EFX_OUTPUT, but don't allocate mixer gpr */
1668 #define EFX_OUTPUTD(OUT_CACHE_IDX, OUT_GPR_IDX, OUTP_NR) do {   \
1669         emu_addefxop(sc, MACS,                                  \
1670                 OUTP(OUTP_NR),                                  \
1671                 DSP_CONST(0),                                   \
1672                 GPR(sc->cache_gpr[OUT_CACHE_IDX]),              \
1673                 GPR(sc->mixer_gpr[OUT_GPR_IDX]),                \
1674                 &pc);                                           \
1675 } while (0)
1676
1677 /* skip next OPCOUNT instructions if FLAG != 0 */
1678 #define EFX_SKIP(OPCOUNT, FLAG_GPR) do {                        \
1679         emu_addefxop(sc, MACS,                                  \
1680                 DSP_CONST(0),                                   \
1681                 GPR(sc->mute_gpr[FLAG_GPR]),                                    \
1682                 DSP_CONST(0),                                   \
1683                 DSP_CONST(0),                                   \
1684                 &pc);                                           \
1685         emu_addefxop(sc, SKIP,                                  \
1686                 DSP_CCR,                                        \
1687                 DSP_CCR,                                        \
1688                 COND_NEQ_ZERO,                                  \
1689                 OPCOUNT,                                        \
1690                 &pc);                                           \
1691 } while (0)
1692
1693 #define EFX_COPY(TO, FROM) do {                                 \
1694         emu_addefxop(sc, ACC3,                                  \
1695                 TO,                                             \
1696                 DSP_CONST(0),                                   \
1697                 DSP_CONST(0),                                   \
1698                 FROM,                                           \
1699                 &pc);                                           \
1700 } while (0)
1701
1702
1703 static void
1704 emu_initefx(struct emu_sc_info *sc)
1705 {
1706         unsigned int i;
1707         uint32_t pc;
1708
1709         /* stop DSP */
1710         if (sc->is_emu10k1) {
1711                 emu_wrptr(sc, 0, EMU_DBG, EMU_DBG_SINGLE_STEP);
1712         } else {
1713                 emu_wrptr(sc, 0, EMU_A_DBG, EMU_A_DBG_SINGLE_STEP);
1714         }
1715
1716         /* code size is in instructions */
1717         pc = 0;
1718         for (i = 0; i < sc->code_size; i++) {
1719                 if (sc->is_emu10k1) {
1720                         emu_addefxop(sc, ACC3, DSP_CONST(0x0), DSP_CONST(0x0), DSP_CONST(0x0), DSP_CONST(0x0), &pc);
1721                 } else {
1722                         emu_addefxop(sc, SKIP, DSP_CONST(0x0), DSP_CONST(0x0), DSP_CONST(0xf), DSP_CONST(0x0), &pc);
1723                 }
1724         }
1725
1726         /* allocate GPRs for mute switches (EFX_SKIP). Mute by default */
1727         for (i = 0; i < NUM_MUTE; i++) {
1728                 sc->mute_gpr[i] = emu_rm_gpr_alloc(sc->rm, 1);
1729                 emumix_set_gpr(sc, sc->mute_gpr[i], 1);
1730         }
1731         emu_digitalswitch(sc);
1732
1733         pc = 0;
1734
1735         /*
1736          * DSP code below is not good, because:
1737          * 1. It can be written smaller, if it can use DSP accumulator register
1738          * instead of cache_gpr[].
1739          * 2. It can be more careful when volume is 100%, because in DSP
1740          * x*0x7fffffff may not be equal to x !
1741          */
1742
1743         /* clean outputs */
1744         for (i = 0; i < 16 ; i++) {
1745                 emu_addefxop(sc, ACC3, OUTP(i), DSP_CONST(0), DSP_CONST(0), DSP_CONST(0), &pc);
1746         }
1747
1748
1749         if (sc->is_emu10k1) {
1750                 EFX_CACHE(C_FRONT_L);
1751                 EFX_CACHE(C_FRONT_R);
1752                 EFX_CACHE(C_REC_L);
1753                 EFX_CACHE(C_REC_R);
1754
1755                 /* fx0 to front/record, 100%/muted by default */
1756                 EFX_ROUTE("pcm_front_l", FX(0), M_FX0_FRONT_L, C_FRONT_L, 100);
1757                 EFX_ROUTE("pcm_front_r", FX(1), M_FX1_FRONT_R, C_FRONT_R, 100);
1758                 EFX_ROUTE(NULL, FX(0), M_FX0_REC_L, C_REC_L, 0);
1759                 EFX_ROUTE(NULL, FX(1), M_FX1_REC_R, C_REC_R, 0);
1760
1761                 /* in0, from AC97 codec output */
1762                 EFX_ROUTE("ac97_front_l", INP(IN_AC97_L), M_IN0_FRONT_L, C_FRONT_L, 0);
1763                 EFX_ROUTE("ac97_front_r", INP(IN_AC97_R), M_IN0_FRONT_R, C_FRONT_R, 0);
1764                 EFX_ROUTE("ac97_rec_l", INP(IN_AC97_L), M_IN0_REC_L, C_REC_L, 0);
1765                 EFX_ROUTE("ac97_rec_r", INP(IN_AC97_R), M_IN0_REC_R, C_REC_R, 0);
1766
1767                 /* in1, from CD S/PDIF */
1768                 /* XXX EFX_SKIP 4 assumes that each EFX_ROUTE is one DSP op */
1769                 EFX_SKIP(4, CDSPDIFMUTE);
1770                 EFX_ROUTE(NULL, INP(IN_SPDIF_CD_L), M_IN1_FRONT_L, C_FRONT_L, 0);
1771                 EFX_ROUTE(NULL, INP(IN_SPDIF_CD_R), M_IN1_FRONT_R, C_FRONT_R, 0);
1772                 EFX_ROUTE(NULL, INP(IN_SPDIF_CD_L), M_IN1_REC_L, C_REC_L, 0);
1773                 EFX_ROUTE(NULL, INP(IN_SPDIF_CD_R), M_IN1_REC_R, C_REC_R, 0);
1774                 
1775                 if (sc->dbg_level > 0) {
1776                         /* in2, ZoomVide (???) */
1777                         EFX_ROUTE("zoom_front_l", INP(IN_ZOOM_L), M_IN2_FRONT_L, C_FRONT_L, 0);
1778                         EFX_ROUTE("zoom_front_r", INP(IN_ZOOM_R), M_IN2_FRONT_R, C_FRONT_R, 0);
1779                         EFX_ROUTE("zoom_rec_l", INP(IN_ZOOM_L), M_IN2_REC_L, C_REC_L, 0);
1780                         EFX_ROUTE("zoom_rec_r", INP(IN_ZOOM_R), M_IN2_REC_R, C_REC_R, 0);
1781                 }
1782
1783                 /* in3, TOSLink  */
1784                 EFX_ROUTE(NULL, INP(IN_TOSLINK_L), M_IN3_FRONT_L, C_FRONT_L, 0);
1785                 EFX_ROUTE(NULL, INP(IN_TOSLINK_R), M_IN3_FRONT_R, C_FRONT_R, 0);
1786                 EFX_ROUTE(NULL, INP(IN_TOSLINK_L), M_IN3_REC_L, C_REC_L, 0);
1787                 EFX_ROUTE(NULL, INP(IN_TOSLINK_R), M_IN3_REC_R, C_REC_R, 0);
1788                 /* in4, LineIn  */
1789                 EFX_ROUTE(NULL, INP(IN_LINE1_L), M_IN4_FRONT_L, C_FRONT_L, 0);
1790                 EFX_ROUTE(NULL, INP(IN_LINE1_R), M_IN4_FRONT_R, C_FRONT_R, 0);
1791                 EFX_ROUTE(NULL, INP(IN_LINE1_L), M_IN4_REC_L, C_REC_L, 0);
1792                 EFX_ROUTE(NULL, INP(IN_LINE1_R), M_IN4_REC_R, C_REC_R, 0);
1793
1794                 /* in5, on-card S/PDIF */
1795                 EFX_ROUTE(NULL, INP(IN_COAX_SPDIF_L), M_IN5_FRONT_L, C_FRONT_L, 0);
1796                 EFX_ROUTE(NULL, INP(IN_COAX_SPDIF_R), M_IN5_FRONT_R, C_FRONT_R, 0);
1797                 EFX_ROUTE(NULL, INP(IN_COAX_SPDIF_L), M_IN5_REC_L, C_REC_L, 0);
1798                 EFX_ROUTE(NULL, INP(IN_COAX_SPDIF_R), M_IN5_REC_R, C_REC_R, 0);
1799
1800                 /* in6, Line2 on Live!Drive */
1801                 EFX_ROUTE(NULL, INP(IN_LINE2_L), M_IN6_FRONT_L, C_FRONT_L, 0);
1802                 EFX_ROUTE(NULL, INP(IN_LINE2_R), M_IN6_FRONT_R, C_FRONT_R, 0);
1803                 EFX_ROUTE(NULL, INP(IN_LINE2_L), M_IN6_REC_L, C_REC_L, 0);
1804                 EFX_ROUTE(NULL, INP(IN_LINE2_R), M_IN6_REC_R, C_REC_R, 0);
1805
1806                 if (sc->dbg_level > 0) {
1807                         /* in7, unknown */
1808                         EFX_ROUTE("in7_front_l", INP(0xE), M_IN7_FRONT_L, C_FRONT_L, 0);
1809                         EFX_ROUTE("in7_front_r", INP(0xF), M_IN7_FRONT_R, C_FRONT_R, 0);
1810                         EFX_ROUTE("in7_rec_l", INP(0xE), M_IN7_REC_L, C_REC_L, 0);
1811                         EFX_ROUTE("in7_rec_r", INP(0xF), M_IN7_REC_R, C_REC_R, 0);
1812                 }
1813
1814                 /* analog and digital */
1815                 EFX_OUTPUT("master_front_l", C_FRONT_L, M_MASTER_FRONT_L, OUT_AC97_L, 100);
1816                 EFX_OUTPUT("master_front_r", C_FRONT_R, M_MASTER_FRONT_R, OUT_AC97_R, 100);
1817                 /* S/PDIF */
1818                 EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, OUT_TOSLINK_L);
1819                 EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, OUT_TOSLINK_R);
1820                 /* Headphones */
1821                 EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, OUT_HEADPHONE_L);
1822                 EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, OUT_HEADPHONE_R);
1823
1824                 /* rec output to "ADC" */
1825                 EFX_OUTPUT("master_rec_l", C_REC_L, M_MASTER_REC_L, OUT_ADC_REC_L, 100);
1826                 EFX_OUTPUT("master_rec_r", C_REC_R, M_MASTER_REC_R, OUT_ADC_REC_R, 100);
1827
1828                 if (!(sc->mch_disabled)) {
1829                         /*
1830                          * Additional channel volume is controlled by mixer in
1831                          * emu_dspmixer_set() in -pcm.c
1832                          */
1833
1834                         /* fx2/3 (pcm1) to rear */
1835                         EFX_CACHE(C_REAR_L);
1836                         EFX_CACHE(C_REAR_R);
1837                         EFX_ROUTE(NULL, FX(2), M_FX2_REAR_L, C_REAR_L, 100);
1838                         EFX_ROUTE(NULL, FX(3), M_FX3_REAR_R, C_REAR_R, 100);
1839
1840                         EFX_OUTPUT(NULL, C_REAR_L, M_MASTER_REAR_L, OUT_REAR_L, 100);
1841                         EFX_OUTPUT(NULL, C_REAR_R, M_MASTER_REAR_R, OUT_REAR_R, 100);
1842                         if (sc->has_51) {
1843                                 /* fx4 (pcm2) to center */
1844                                 EFX_CACHE(C_CENTER);
1845                                 EFX_ROUTE(NULL, FX(4), M_FX4_CENTER, C_CENTER, 100);
1846                                 EFX_OUTPUT(NULL, C_CENTER, M_MASTER_CENTER, OUT_D_CENTER, 100);
1847
1848                                 /* XXX in digital mode (default) this should be muted because
1849                                 this output is shared with digital out */
1850                                 EFX_SKIP(1, ANALOGMUTE);
1851                                 EFX_OUTPUTD(C_CENTER, M_MASTER_CENTER, OUT_A_CENTER);
1852
1853                                 /* fx5 (pcm3) to sub */
1854                                 EFX_CACHE(C_SUB);
1855                                 EFX_ROUTE(NULL, FX(5), M_FX5_SUBWOOFER, C_SUB, 100);
1856                                 EFX_OUTPUT(NULL, C_SUB, M_MASTER_SUBWOOFER, OUT_D_SUB, 100);
1857
1858                                 /* XXX in digital mode (default) this should be muted because
1859                                 this output is shared with digital out */
1860                                 EFX_SKIP(1, ANALOGMUTE);
1861                                 EFX_OUTPUTD(C_SUB, M_MASTER_SUBWOOFER, OUT_A_SUB);
1862
1863                         }
1864                 } else {
1865                         /* SND_EMU10KX_MULTICHANNEL_DISABLED */
1866                         EFX_OUTPUT(NULL, C_FRONT_L, M_MASTER_REAR_L, OUT_REAR_L, 57); /* 75%*75% */
1867                         EFX_OUTPUT(NULL, C_FRONT_R, M_MASTER_REAR_R, OUT_REAR_R, 57); /* 75%*75% */
1868
1869 #if 0
1870                         /* XXX 5.1 does not work */
1871
1872                         if (sc->has_51) {
1873                                 /* (fx0+fx1)/2 to center */
1874                                 EFX_CACHE(C_CENTER);
1875                                 emu_addefxop(sc, MACS,
1876                                         GPR(sc->cache_gpr[C_CENTER]),
1877                                         GPR(sc->cache_gpr[C_CENTER]),
1878                                         DSP_CONST(0xd), /* = 1/2 */
1879                                         GPR(sc->cache_gpr[C_FRONT_L]),
1880                                         &pc);
1881                                 emu_addefxop(sc, MACS,
1882                                         GPR(sc->cache_gpr[C_CENTER]),
1883                                         GPR(sc->cache_gpr[C_CENTER]),
1884                                         DSP_CONST(0xd), /* = 1/2 */
1885                                         GPR(sc->cache_gpr[C_FRONT_R]),
1886                                         &pc);
1887                                 EFX_OUTPUT(NULL, C_CENTER, M_MASTER_CENTER, OUT_D_CENTER, 100);
1888
1889                                 /* XXX in digital mode (default) this should be muted because
1890                                 this output is shared with digital out */
1891                                 EFX_SKIP(1, ANALOGMUTE);
1892                                 EFX_OUTPUTD(C_CENTER, M_MASTER_CENTER, OUT_A_CENTER);
1893
1894                                 /* (fx0+fx1)/2  to sub */
1895                                 EFX_CACHE(C_SUB);
1896                                 emu_addefxop(sc, MACS,
1897                                         GPR(sc->cache_gpr[C_CENTER]),
1898                                         GPR(sc->cache_gpr[C_CENTER]),
1899                                         DSP_CONST(0xd), /* = 1/2 */
1900                                         GPR(sc->cache_gpr[C_FRONT_L]),
1901                                         &pc);
1902                                 emu_addefxop(sc, MACS,
1903                                         GPR(sc->cache_gpr[C_CENTER]),
1904                                         GPR(sc->cache_gpr[C_CENTER]),
1905                                         DSP_CONST(0xd), /* = 1/2 */
1906                                         GPR(sc->cache_gpr[C_FRONT_R]),
1907                                         &pc);
1908                                 /* XXX add lowpass filter here */
1909
1910                                 EFX_OUTPUT(NULL, C_SUB, M_MASTER_SUBWOOFER, OUT_D_SUB, 100);
1911
1912                                 /* XXX in digital mode (default) this should be muted because
1913                                 this output is shared with digital out */
1914                                 EFX_SKIP(1, ANALOGMUTE);
1915                                 EFX_OUTPUTD(C_SUB, M_MASTER_SUBWOOFER, OUT_A_SUB);
1916                         }
1917 #endif
1918                 } /* !mch_disabled */
1919                 if (sc->mch_rec) {
1920                         /*
1921                          * MCH RECORDING , hight 16 slots. On 5.1 cards first 4 slots
1922                          * are used as outputs and already filled with data
1923                          */
1924                         /*
1925                          * XXX On Live! cards stream does not begin at zero offset.
1926                          * It can be HW, driver or sound buffering problem.
1927                          * Use sync substream (offset 0x3E) to let userland find
1928                          * correct data.
1929                          */
1930
1931                         /*
1932                          * Substream map (in byte offsets, each substream is 2 bytes):
1933                          *      0x00..0x1E - outputs
1934                          *      0x20..0x3E - FX, inputs and sync stream
1935                          */
1936
1937                         /* First 2 channels (offset 0x20,0x22) are empty */
1938                         for(i = (sc->has_51 ? 2 : 0); i < 2; i++)
1939                                 EFX_COPY(FX2(i), DSP_CONST(0));
1940
1941                         /* PCM Playback monitoring, offset 0x24..0x2A */
1942                         for(i = 0; i < 4; i++)
1943                                 EFX_COPY(FX2(i+2), FX(i));
1944
1945                         /* Copy of some inputs, offset 0x2C..0x3C */
1946                         for(i = 0; i < 9; i++)
1947                                 EFX_COPY(FX2(i+8), INP(i));
1948
1949                         /* sync data (0xc0de, offset 0x3E) */
1950                         sc->dummy_gpr = emu_rm_gpr_alloc(sc->rm, 1);
1951                         emumix_set_gpr(sc, sc->dummy_gpr, 0xc0de0000);
1952
1953                         EFX_COPY(FX2(15), GPR(sc->dummy_gpr));
1954                 } /* mch_rec */
1955         } else /* emu10k2 and later */ {
1956                 EFX_CACHE(C_FRONT_L);
1957                 EFX_CACHE(C_FRONT_R);
1958                 EFX_CACHE(C_REC_L);
1959                 EFX_CACHE(C_REC_R);
1960
1961                 /* fx0 to front/record, 100%/muted by default */
1962                 /*
1963                  * FRONT_[L|R] is controlled by AC97 emulation in
1964                  * emu_ac97_[read|write]_emulation in -pcm.c
1965                  */
1966                 EFX_ROUTE(NULL, FX(0), M_FX0_FRONT_L, C_FRONT_L, 100);
1967                 EFX_ROUTE(NULL, FX(1), M_FX1_FRONT_R, C_FRONT_R, 100);
1968                 EFX_ROUTE(NULL, FX(0), M_FX0_REC_L, C_REC_L, 0);
1969                 EFX_ROUTE(NULL, FX(1), M_FX1_REC_R, C_REC_R, 0);
1970
1971                 /* in0, from AC97 codec output */
1972                 EFX_ROUTE(NULL, INP(A_IN_AC97_L), M_IN0_FRONT_L, C_FRONT_L, 100);
1973                 EFX_ROUTE(NULL, INP(A_IN_AC97_R), M_IN0_FRONT_R, C_FRONT_R, 100);
1974                 EFX_ROUTE(NULL, INP(A_IN_AC97_L), M_IN0_REC_L, C_REC_L, 0);
1975                 EFX_ROUTE(NULL, INP(A_IN_AC97_R), M_IN0_REC_R, C_REC_R, 0);
1976
1977                 /* in1, from CD S/PDIF */
1978                 EFX_ROUTE(NULL, INP(A_IN_SPDIF_CD_L), M_IN1_FRONT_L, C_FRONT_L, 0);
1979                 EFX_ROUTE(NULL, INP(A_IN_SPDIF_CD_R), M_IN1_FRONT_R, C_FRONT_R, 0);
1980                 EFX_ROUTE(NULL, INP(A_IN_SPDIF_CD_L), M_IN1_REC_L, C_REC_L, 0);
1981                 EFX_ROUTE(NULL, INP(A_IN_SPDIF_CD_R), M_IN1_REC_R, C_REC_R, 0);
1982
1983                 /* in2, optical & coax S/PDIF on AudigyDrive*/
1984                 /* XXX Should be muted when GPRSCS valid stream == 0 */
1985                 EFX_ROUTE(NULL, INP(A_IN_O_SPDIF_L), M_IN2_FRONT_L, C_FRONT_L, 0);
1986                 EFX_ROUTE(NULL, INP(A_IN_O_SPDIF_R), M_IN2_FRONT_R, C_FRONT_R, 0);
1987                 EFX_ROUTE(NULL, INP(A_IN_O_SPDIF_L), M_IN2_REC_L, C_REC_L, 0);
1988                 EFX_ROUTE(NULL, INP(A_IN_O_SPDIF_R), M_IN2_REC_R, C_REC_R, 0);
1989
1990                 if (sc->dbg_level > 0) {
1991                         /* in3, unknown */
1992                         EFX_ROUTE("in3_front_l", INP(0x6), M_IN3_FRONT_L, C_FRONT_L, 0);
1993                         EFX_ROUTE("in3_front_r", INP(0x7), M_IN3_FRONT_R, C_FRONT_R, 0);
1994                         EFX_ROUTE("in3_rec_l", INP(0x6), M_IN3_REC_L, C_REC_L, 0);
1995                         EFX_ROUTE("in3_rec_r", INP(0x7), M_IN3_REC_R, C_REC_R, 0);
1996                 }
1997
1998                 /* in4, LineIn 2 on AudigyDrive */
1999                 EFX_ROUTE(NULL, INP(A_IN_LINE2_L), M_IN4_FRONT_L, C_FRONT_L, 0);
2000                 EFX_ROUTE(NULL, INP(A_IN_LINE2_R), M_IN4_FRONT_R, C_FRONT_R, 0);
2001                 EFX_ROUTE(NULL, INP(A_IN_LINE2_L), M_IN4_REC_L, C_REC_L, 0);
2002                 EFX_ROUTE(NULL, INP(A_IN_LINE2_R), M_IN4_REC_R, C_REC_R, 0);
2003
2004                 /* in5, on-card S/PDIF */
2005                 EFX_ROUTE(NULL, INP(A_IN_R_SPDIF_L), M_IN5_FRONT_L, C_FRONT_L, 0);
2006                 EFX_ROUTE(NULL, INP(A_IN_R_SPDIF_R), M_IN5_FRONT_R, C_FRONT_R, 0);
2007                 EFX_ROUTE(NULL, INP(A_IN_R_SPDIF_L), M_IN5_REC_L, C_REC_L, 0);
2008                 EFX_ROUTE(NULL, INP(A_IN_R_SPDIF_R), M_IN5_REC_R, C_REC_R, 0);
2009
2010                 /* in6, AUX2 on AudigyDrive */
2011                 EFX_ROUTE(NULL, INP(A_IN_AUX2_L), M_IN6_FRONT_L, C_FRONT_L, 0);
2012                 EFX_ROUTE(NULL, INP(A_IN_AUX2_R), M_IN6_FRONT_R, C_FRONT_R, 0);
2013                 EFX_ROUTE(NULL, INP(A_IN_AUX2_L), M_IN6_REC_L, C_REC_L, 0);
2014                 EFX_ROUTE(NULL, INP(A_IN_AUX2_R), M_IN6_REC_R, C_REC_R, 0);
2015
2016                 if (sc->dbg_level > 0) {
2017                         /* in7, unknown */
2018                         EFX_ROUTE("in7_front_l", INP(0xE), M_IN7_FRONT_L, C_FRONT_L, 0);
2019                         EFX_ROUTE("in7_front_r", INP(0xF), M_IN7_FRONT_R, C_FRONT_R, 0);
2020                         EFX_ROUTE("in7_rec_l", INP(0xE), M_IN7_REC_L, C_REC_L, 0);
2021                         EFX_ROUTE("in7_rec_r", INP(0xF), M_IN7_REC_R, C_REC_R, 0);
2022                 }
2023
2024                 /* front output to headphones and  alog and digital *front */
2025                 /* volume controlled by AC97 emulation */
2026                 EFX_OUTPUT(NULL, C_FRONT_L, M_MASTER_FRONT_L, A_OUT_A_FRONT_L, 100);
2027                 EFX_OUTPUT(NULL, C_FRONT_R, M_MASTER_FRONT_R, A_OUT_A_FRONT_R, 100);
2028                 EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, A_OUT_D_FRONT_L);
2029                 EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, A_OUT_D_FRONT_R);
2030                 EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, A_OUT_HPHONE_L);
2031                 EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, A_OUT_HPHONE_R);
2032
2033                 /* rec output to "ADC" */
2034                 /* volume controlled by AC97 emulation */
2035                 EFX_OUTPUT(NULL, C_REC_L, M_MASTER_REC_L, A_OUT_ADC_REC_L, 100);
2036                 EFX_OUTPUT(NULL, C_REC_R, M_MASTER_REC_R, A_OUT_ADC_REC_R, 100);
2037
2038                 if (!(sc->mch_disabled)) {
2039                         /*
2040                          * Additional channel volume is controlled by mixer in
2041                          * emu_dspmixer_set() in -pcm.c
2042                          */
2043
2044                         /* fx2/3 (pcm1) to rear */
2045                         EFX_CACHE(C_REAR_L);
2046                         EFX_CACHE(C_REAR_R);
2047                         EFX_ROUTE(NULL, FX(2), M_FX2_REAR_L, C_REAR_L, 100);
2048                         EFX_ROUTE(NULL, FX(3), M_FX3_REAR_R, C_REAR_R, 100);
2049
2050                         EFX_OUTPUT(NULL, C_REAR_L, M_MASTER_REAR_L, A_OUT_A_REAR_L, 100);
2051                         EFX_OUTPUT(NULL, C_REAR_R, M_MASTER_REAR_R, A_OUT_A_REAR_R, 100);
2052                         EFX_OUTPUTD(C_REAR_L, M_MASTER_REAR_L, A_OUT_D_REAR_L);
2053                         EFX_OUTPUTD(C_REAR_R, M_MASTER_REAR_R, A_OUT_D_REAR_R);
2054
2055                         /* fx4 (pcm2) to center */
2056                         EFX_CACHE(C_CENTER);
2057                         EFX_ROUTE(NULL, FX(4), M_FX4_CENTER, C_CENTER, 100);
2058                         EFX_OUTPUT(NULL, C_CENTER, M_MASTER_CENTER, A_OUT_D_CENTER, 100);
2059 #if 0
2060                         /*
2061                          * XXX in digital mode (default) this should be muted
2062                          * because this output is shared with digital out
2063                          */
2064                         EFX_OUTPUTD(C_CENTER, M_MASTER_CENTER, A_OUT_A_CENTER);
2065 #endif
2066                         /* fx5 (pcm3) to sub */
2067                         EFX_CACHE(C_SUB);
2068                         EFX_ROUTE(NULL, FX(5), M_FX5_SUBWOOFER, C_SUB, 100);
2069                         EFX_OUTPUT(NULL, C_SUB, M_MASTER_SUBWOOFER, A_OUT_D_SUB, 100);
2070 #if 0
2071                         /*
2072                          * XXX in digital mode (default) this should be muted
2073                          * because this output is shared with digital out
2074                          */
2075                         EFX_OUTPUTD(C_SUB, M_MASTER_SUBWOOFER, A_OUT_A_SUB);
2076 #endif
2077                         if (sc->has_71) {
2078                                 /* XXX this will broke headphones on AudigyDrive */
2079                                 /* fx6/7 (pcm4) to side */
2080                                 EFX_CACHE(C_SIDE_L);
2081                                 EFX_CACHE(C_SIDE_R);
2082                                 EFX_ROUTE(NULL, FX(6), M_FX6_SIDE_L, C_SIDE_L, 100);
2083                                 EFX_ROUTE(NULL, FX(7), M_FX7_SIDE_R, C_SIDE_R, 100);
2084                                 EFX_OUTPUT(NULL, C_SIDE_L, M_MASTER_SIDE_L, A_OUT_A_SIDE_L, 100);
2085                                 EFX_OUTPUT(NULL, C_SIDE_R, M_MASTER_SIDE_R, A_OUT_A_SIDE_R, 100);
2086                                 EFX_OUTPUTD(C_SIDE_L, M_MASTER_SIDE_L, A_OUT_D_SIDE_L);
2087                                 EFX_OUTPUTD(C_SIDE_R, M_MASTER_SIDE_R, A_OUT_D_SIDE_R);
2088                         }
2089                 } else {        /* mch_disabled */
2090                         EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, A_OUT_A_REAR_L);
2091                         EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, A_OUT_A_REAR_R);
2092
2093                         EFX_OUTPUTD(C_FRONT_L, M_MASTER_FRONT_L, A_OUT_D_REAR_L);
2094                         EFX_OUTPUTD(C_FRONT_R, M_MASTER_FRONT_R, A_OUT_D_REAR_R);
2095
2096                         if (sc->has_51) {
2097                                 /* (fx0+fx1)/2 to center */
2098                                 EFX_CACHE(C_CENTER);
2099                                 emu_addefxop(sc, MACS,
2100                                         GPR(sc->cache_gpr[C_CENTER]),
2101                                         GPR(sc->cache_gpr[C_CENTER]),
2102                                         DSP_CONST(0xd), /* = 1/2 */
2103                                         GPR(sc->cache_gpr[C_FRONT_L]),
2104                                         &pc);
2105                                 emu_addefxop(sc, MACS,
2106                                         GPR(sc->cache_gpr[C_CENTER]),
2107                                         GPR(sc->cache_gpr[C_CENTER]),
2108                                         DSP_CONST(0xd), /* = 1/2 */
2109                                         GPR(sc->cache_gpr[C_FRONT_R]),
2110                                         &pc);
2111                                 EFX_OUTPUT(NULL, C_CENTER, M_MASTER_CENTER, A_OUT_D_CENTER, 100);
2112
2113                                 /* XXX in digital mode (default) this should be muted because
2114                                 this output is shared with digital out */
2115                                 EFX_SKIP(1, ANALOGMUTE);
2116                                 EFX_OUTPUTD(C_CENTER, M_MASTER_CENTER, A_OUT_A_CENTER);
2117
2118                                 /* (fx0+fx1)/2  to sub */
2119                                 EFX_CACHE(C_SUB);
2120                                 emu_addefxop(sc, MACS,
2121                                         GPR(sc->cache_gpr[C_SUB]),
2122                                         GPR(sc->cache_gpr[C_SUB]),
2123                                         DSP_CONST(0xd), /* = 1/2 */
2124                                         GPR(sc->cache_gpr[C_FRONT_L]),
2125                                         &pc);
2126                                 emu_addefxop(sc, MACS,
2127                                         GPR(sc->cache_gpr[C_SUB]),
2128                                         GPR(sc->cache_gpr[C_SUB]),
2129                                         DSP_CONST(0xd), /* = 1/2 */
2130                                         GPR(sc->cache_gpr[C_FRONT_R]),
2131                                         &pc);
2132                                 /* XXX add lowpass filter here */
2133
2134                                 EFX_OUTPUT(NULL, C_SUB, M_MASTER_SUBWOOFER, A_OUT_D_SUB, 100);
2135
2136                                 /* XXX in digital mode (default) this should be muted because
2137                                 this output is shared with digital out */
2138                                 EFX_SKIP(1, ANALOGMUTE);
2139                                 EFX_OUTPUTD(C_SUB, M_MASTER_SUBWOOFER, A_OUT_A_SUB);
2140                         }
2141                 } /* mch_disabled */
2142                 if (sc->mch_rec) {
2143                         /* MCH RECORDING, high 32 slots */
2144
2145                         /*
2146                          * Stream map (in byte offsets):
2147                          *      0x00..0x3E - outputs
2148                          *      0x40..0x7E - FX, inputs
2149                          *      each substream is 2 bytes.
2150                          */
2151                         /*
2152                          * XXX Audigy 2 Value cards (and, possibly,
2153                          * Audigy 4) write some unknown data in place of
2154                          * some outputs (offsets 0x20..0x3F) and one
2155                          * input (offset 0x7E).
2156                          */
2157
2158                         /* PCM Playback monitoring, offsets 0x40..0x5E */
2159                         for(i = 0; i < 16; i++)
2160                                 EFX_COPY(FX2(i), FX(i));
2161
2162                         /* Copy of all inputs, offsets 0x60..0x7E */
2163                         for(i = 0; i < 16; i++)
2164                                 EFX_COPY(FX2(i+16), INP(i));
2165 #if 0
2166                         /* XXX Audigy seems to work correct and does not need this */
2167                         /* sync data (0xc0de), offset 0x7E */
2168                         sc->dummy_gpr = emu_rm_gpr_alloc(sc->rm, 1);
2169                         emumix_set_gpr(sc, sc->dummy_gpr, 0xc0de0000);
2170                         EFX_COPY(FX2(31), GPR(sc->dummy_gpr));
2171 #endif
2172                 } /* mch_rec */
2173         }
2174
2175         sc->routing_code_end = pc;
2176
2177         /* start DSP */
2178         if (sc->is_emu10k1) {
2179                 emu_wrptr(sc, 0, EMU_DBG, 0);
2180         } else {
2181                 emu_wrptr(sc, 0, EMU_A_DBG, 0);
2182         }
2183 }
2184
2185 /* /dev/em10kx */
2186 static d_open_t         emu10kx_open;
2187 static d_close_t        emu10kx_close;
2188 static d_read_t         emu10kx_read;
2189
2190 static struct dev_ops emu10kx_ops = {
2191         .d_open =       emu10kx_open,
2192         .d_close =      emu10kx_close,
2193         .d_read =       emu10kx_read,
2194 };
2195
2196
2197 static int
2198 emu10kx_open(struct dev_open_args *ap)
2199 {
2200         struct cdev *i_dev = ap->a_head.a_dev;
2201         int error;
2202         struct emu_sc_info *sc;
2203
2204         sc = i_dev->si_drv1;
2205         lockmgr(&sc->emu10kx_lock, LK_EXCLUSIVE);
2206         if (sc->emu10kx_isopen) {
2207                 lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2208                 return (EBUSY);
2209         }
2210         sc->emu10kx_isopen = 1;
2211         lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2212         if (sbuf_new(&sc->emu10kx_sbuf, NULL, 4096, 0) == NULL) {
2213                 error = ENXIO;
2214                 goto out;
2215         }
2216         sc->emu10kx_bufptr = 0;
2217         error = (emu10kx_prepare(sc, &sc->emu10kx_sbuf) > 0) ? 0 : ENOMEM;
2218 out:
2219         if (error) {
2220                 lockmgr(&sc->emu10kx_lock, LK_EXCLUSIVE);
2221                 sc->emu10kx_isopen = 0;
2222                 lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2223         }
2224         return (error);
2225 }
2226
2227 static int
2228 emu10kx_close(struct dev_close_args *ap)
2229 {
2230         struct cdev *i_dev = ap->a_head.a_dev;
2231         struct emu_sc_info *sc;
2232
2233         sc = i_dev->si_drv1;
2234
2235         lockmgr(&sc->emu10kx_lock, LK_EXCLUSIVE);
2236         if (!(sc->emu10kx_isopen)) {
2237                 lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2238                 return (EBADF);
2239         }
2240         sbuf_delete(&sc->emu10kx_sbuf);
2241         sc->emu10kx_isopen = 0;
2242         lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2243
2244         return (0);
2245 }
2246
2247 static int
2248 emu10kx_read(struct dev_read_args *ap)
2249 {
2250         struct cdev *i_dev = ap->a_head.a_dev;
2251         struct uio *buf = ap->a_uio;
2252         int l, err;
2253         struct emu_sc_info *sc;
2254
2255         sc = i_dev->si_drv1;
2256         lockmgr(&sc->emu10kx_lock, LK_EXCLUSIVE);
2257         if (!(sc->emu10kx_isopen)) {
2258                 lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2259                 return (EBADF);
2260         }
2261         lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2262
2263         l = min(buf->uio_resid, sbuf_len(&sc->emu10kx_sbuf) - sc->emu10kx_bufptr);
2264         err = (l > 0) ? uiomove(sbuf_data(&sc->emu10kx_sbuf) + sc->emu10kx_bufptr, l, buf) : 0;
2265         sc->emu10kx_bufptr += l;
2266
2267         return (err);
2268 }
2269
2270 static int
2271 emu10kx_prepare(struct emu_sc_info *sc, struct sbuf *s)
2272 {
2273         int i;
2274
2275         sbuf_printf(s, "FreeBSD EMU10Kx Audio Driver\n");
2276         sbuf_printf(s, "\nHardware resource usage:\n");
2277         sbuf_printf(s, "DSP General Purpose Registers: %d used, %d total\n", sc->rm->num_used, sc->rm->num_gprs);
2278         sbuf_printf(s, "DSP Instruction Registers: %d used, %d total\n", sc->routing_code_end, sc->code_size);
2279         sbuf_printf(s, "Card supports");
2280         if (sc->has_ac97) {
2281                 sbuf_printf(s, " AC97 codec");
2282         } else {
2283                 sbuf_printf(s, " NO AC97 codec");
2284         }
2285         if (sc->has_51) {
2286                 if (sc->has_71)
2287                         sbuf_printf(s, " and 7.1 output");
2288                 else
2289                         sbuf_printf(s, " and 5.1 output");
2290         }
2291         if (sc->is_emu10k1)
2292                 sbuf_printf(s, ", SBLive! DSP code");
2293         if (sc->is_emu10k2)
2294                 sbuf_printf(s, ", Audigy DSP code");
2295         if (sc->is_ca0102)
2296                 sbuf_printf(s, ", Audigy DSP code with Audigy2 hacks");
2297         if (sc->is_ca0108)
2298                 sbuf_printf(s, ", Audigy DSP code with Audigy2Value hacks");
2299         sbuf_printf(s, "\n");
2300         if (sc->broken_digital)
2301                 sbuf_printf(s, "Digital mode unsupported\n");
2302         sbuf_printf(s, "\nInstalled devices:\n");
2303         for (i = 0; i < RT_COUNT; i++)
2304                 if (sc->pcm[i] != NULL)
2305                         if (device_is_attached(sc->pcm[i])) {
2306                                 sbuf_printf(s, "%s on %s\n", device_get_desc(sc->pcm[i]), device_get_nameunit(sc->pcm[i]));
2307                         }
2308         if (sc->midi[0] != NULL)
2309                 if (device_is_attached(sc->midi[0])) {
2310                         sbuf_printf(s, "EMU10Kx MIDI Interface\n");
2311                         sbuf_printf(s, "\tOn-card connector on %s\n", device_get_nameunit(sc->midi[0]));
2312                 }
2313         if (sc->midi[1] != NULL)
2314                 if (device_is_attached(sc->midi[1])) {
2315                         sbuf_printf(s, "\tOn-Drive connector on %s\n", device_get_nameunit(sc->midi[1]));
2316                 }
2317         if (sc->midi[0] != NULL)
2318                 if (device_is_attached(sc->midi[0])) {
2319                         sbuf_printf(s, "\tIR reciever MIDI events %s\n", sc->enable_ir ? "enabled" : "disabled");
2320                 }
2321         sbuf_printf(s, "Card is in %s mode\n", (sc->mode == MODE_ANALOG) ? "analog" : "digital");
2322
2323         sbuf_finish(s);
2324         return (sbuf_len(s));
2325 }
2326
2327 /* INIT & UNINIT */
2328 static int
2329 emu10kx_dev_init(struct emu_sc_info *sc)
2330 {
2331         int unit;
2332
2333         lockinit(&sc->emu10kx_lock, device_get_nameunit(sc->dev), 0,
2334                  LK_CANRECURSE);
2335         unit = device_get_unit(sc->dev);
2336
2337         sc->cdev = make_dev(&emu10kx_ops, PCMMINOR(unit), UID_ROOT, GID_WHEEL, 0640, "emu10kx%d", unit);
2338         if (sc->cdev != NULL) {
2339                 sc->cdev->si_drv1 = sc;
2340                 return (0);
2341         }
2342         return (ENXIO);
2343 }
2344
2345 static int
2346 emu10kx_dev_uninit(struct emu_sc_info *sc)
2347 {
2348         lockmgr(&sc->emu10kx_lock, LK_EXCLUSIVE);
2349         if (sc->emu10kx_isopen) {
2350                 lockmgr(&sc->emu10kx_lock, LK_RELEASE);
2351                 return (EBUSY);
2352         }
2353         if (sc->cdev)
2354                 destroy_dev(sc->cdev);
2355         sc->cdev = 0;
2356
2357         lockuninit(&sc->emu10kx_lock);
2358         return (0);
2359 }
2360
2361 /* resource manager */
2362 int
2363 emu_rm_init(struct emu_sc_info *sc)
2364 {
2365         int i;
2366         int maxcount;
2367         struct emu_rm *rm;
2368
2369         rm = kmalloc(sizeof(struct emu_rm), M_DEVBUF, M_NOWAIT | M_ZERO);
2370         if (rm == NULL) {
2371                 return (ENOMEM);
2372         }
2373         sc->rm = rm;
2374         rm->card = sc;
2375         maxcount = sc->num_gprs;
2376         rm->num_used = 0;
2377         lockinit(&(rm->gpr_lock), device_get_nameunit(sc->dev), 0,
2378                  LK_CANRECURSE);
2379         rm->num_gprs = (maxcount < EMU_MAX_GPR ? maxcount : EMU_MAX_GPR);
2380         for (i = 0; i < rm->num_gprs; i++)
2381                 rm->allocmap[i] = 0;
2382         /* pre-allocate gpr[0] */
2383         rm->allocmap[0] = 1;
2384         rm->last_free_gpr = 1;
2385
2386         return (0);
2387 }
2388
2389 int
2390 emu_rm_uninit(struct emu_sc_info *sc)
2391 {
2392         int i;
2393
2394         if (sc->dbg_level > 1) {
2395                 lockmgr(&(sc->rm->gpr_lock), LK_EXCLUSIVE);
2396                 for (i = 1; i < sc->rm->last_free_gpr; i++)
2397                         if (sc->rm->allocmap[i] > 0)
2398                                 device_printf(sc->dev, "rm: gpr %d not free before uninit\n", i);
2399                 lockmgr(&(sc->rm->gpr_lock), LK_RELEASE);
2400         }
2401
2402         lockuninit(&(sc->rm->gpr_lock));
2403         kfree(sc->rm, M_DEVBUF);
2404         return (0);
2405 }
2406
2407 static int
2408 emu_rm_gpr_alloc(struct emu_rm *rm, int count)
2409 {
2410         int i, j;
2411         int allocated_gpr;
2412
2413         allocated_gpr = rm->num_gprs;
2414         /* try fast way first */
2415         lockmgr(&(rm->gpr_lock), LK_EXCLUSIVE);
2416         if (rm->last_free_gpr + count <= rm->num_gprs) {
2417                 allocated_gpr = rm->last_free_gpr;
2418                 rm->last_free_gpr += count;
2419                 rm->allocmap[allocated_gpr] = count;
2420                 for (i = 1; i < count; i++)
2421                         rm->allocmap[allocated_gpr + i] = -(count - i);
2422         } else {
2423                 /* longer */
2424                 i = 0;
2425                 allocated_gpr = rm->num_gprs;
2426                 while (i < rm->last_free_gpr - count) {
2427                         if (rm->allocmap[i] > 0) {
2428                                 i += rm->allocmap[i];
2429                         } else {
2430                                 allocated_gpr = i;
2431                                 for (j = 1; j < count; j++) {
2432                                         if (rm->allocmap[i + j] != 0)
2433                                                 allocated_gpr = rm->num_gprs;
2434                                 }
2435                                 if (allocated_gpr == i)
2436                                         break;
2437                         }
2438                 }
2439                 if (allocated_gpr + count < rm->last_free_gpr) {
2440                         rm->allocmap[allocated_gpr] = count;
2441                         for (i = 1; i < count; i++)
2442                                 rm->allocmap[allocated_gpr + i] = -(count - i);
2443
2444                 }
2445         }
2446         if (allocated_gpr == rm->num_gprs)
2447                 allocated_gpr = (-1);
2448         if (allocated_gpr >= 0)
2449                 rm->num_used += count;
2450         lockmgr(&(rm->gpr_lock), LK_RELEASE);
2451         return (allocated_gpr);
2452 }
2453
2454 /* mixer */
2455 void
2456 emumix_set_mode(struct emu_sc_info *sc, int mode)
2457 {
2458         uint32_t a_iocfg;
2459         uint32_t hcfg;
2460         uint32_t tmp;
2461
2462         switch (mode) {
2463         case MODE_DIGITAL:
2464                 /* FALLTHROUGH */
2465         case MODE_ANALOG:
2466                 break;
2467         default:
2468                 return;
2469         }
2470
2471         hcfg = EMU_HCFG_AUDIOENABLE | EMU_HCFG_AUTOMUTE;
2472         a_iocfg = 0;
2473
2474         if (sc->rev >= 6)
2475                 hcfg |= EMU_HCFG_JOYENABLE;
2476
2477         if (sc->is_emu10k1)
2478                 hcfg |= EMU_HCFG_LOCKTANKCACHE_MASK;
2479         else
2480                 hcfg |= EMU_HCFG_CODECFMT_I2S | EMU_HCFG_JOYENABLE;
2481
2482
2483         if (mode == MODE_DIGITAL) {
2484                 if (sc->broken_digital) {
2485                         device_printf(sc->dev, "Digital mode is reported as broken on this card.\n");
2486                 }
2487                 a_iocfg |= EMU_A_IOCFG_GPOUT1;
2488                 hcfg |= EMU_HCFG_GPOUT0;
2489         }
2490
2491         if (mode == MODE_ANALOG)
2492                 emumix_set_spdif_mode(sc, SPDIF_MODE_PCM);
2493
2494         if (sc->is_emu10k2)
2495                 a_iocfg |= 0x80; /* XXX */
2496
2497         if ((sc->is_ca0102) || (sc->is_ca0108))
2498                 /*
2499                  * Setting EMU_A_IOCFG_DISABLE_ANALOG will do opposite things
2500                  * on diffrerent cards.
2501                  * "don't disable analog outs" on Audigy 2 (ca0102/ca0108)
2502                  * "disable analog outs" on Audigy (emu10k2)
2503                  */
2504                 a_iocfg |= EMU_A_IOCFG_DISABLE_ANALOG;
2505
2506         if (sc->is_ca0108)
2507                 a_iocfg |= 0x20; /* XXX */
2508
2509         /* Mute analog center & subwoofer before mode change */
2510         if (mode == MODE_DIGITAL)
2511                 emumix_set_gpr(sc, sc->mute_gpr[ANALOGMUTE], 1);
2512
2513         emu_wr(sc, EMU_HCFG, hcfg, 4);
2514
2515         if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108)) {
2516                 tmp = emu_rd(sc, EMU_A_IOCFG, 2);
2517                 tmp = a_iocfg;
2518                 emu_wr(sc, EMU_A_IOCFG, tmp, 2);
2519         }
2520
2521         /* Unmute if we have changed mode to analog. */
2522
2523         if (mode == MODE_ANALOG)
2524                 emumix_set_gpr(sc, sc->mute_gpr[ANALOGMUTE], 0);
2525
2526         sc->mode = mode;
2527 }
2528
2529 void
2530 emumix_set_spdif_mode(struct emu_sc_info *sc, int mode)
2531 {
2532         uint32_t spcs;
2533
2534         switch (mode) {
2535         case SPDIF_MODE_PCM:
2536                 break;
2537         case SPDIF_MODE_AC3:
2538                 device_printf(sc->dev, "AC3 mode does not work and disabled\n");
2539                 return;
2540         default:
2541                 return;
2542         }
2543
2544         spcs = EMU_SPCS_CLKACCY_1000PPM | EMU_SPCS_SAMPLERATE_48 |
2545             EMU_SPCS_CHANNELNUM_LEFT | EMU_SPCS_SOURCENUM_UNSPEC |
2546             EMU_SPCS_GENERATIONSTATUS | 0x00001200 | 0x00000000 |
2547             EMU_SPCS_EMPHASIS_NONE | EMU_SPCS_COPYRIGHT;
2548
2549         mode = SPDIF_MODE_PCM;
2550
2551         emu_wrptr(sc, 0, EMU_SPCS0, spcs);
2552         emu_wrptr(sc, 0, EMU_SPCS1, spcs);
2553         emu_wrptr(sc, 0, EMU_SPCS2, spcs);
2554 }
2555
2556 #define L2L_POINTS      10
2557
2558 static int l2l_df[L2L_POINTS] = {
2559         0x572C5CA,              /* 100..90 */
2560         0x3211625,              /* 90..80 */
2561         0x1CC1A76,              /* 80..70 */
2562         0x108428F,              /* 70..60 */
2563         0x097C70A,              /* 60..50 */
2564         0x0572C5C,              /* 50..40 */
2565         0x0321162,              /* 40..30 */
2566         0x01CC1A7,              /* 30..20 */
2567         0x0108428,              /* 20..10 */
2568         0x016493D               /* 10..0 */
2569 };
2570
2571 static int l2l_f[L2L_POINTS] = {
2572         0x4984461A,             /* 90 */
2573         0x2A3968A7,             /* 80 */
2574         0x18406003,             /* 70 */
2575         0x0DEDC66D,             /* 60 */
2576         0x07FFFFFF,             /* 50 */
2577         0x04984461,             /* 40 */
2578         0x02A3968A,             /* 30 */
2579         0x01840600,             /* 20 */
2580         0x00DEDC66,             /* 10 */
2581         0x00000000              /* 0 */
2582 };
2583
2584
2585 static int
2586 log2lin(int log_t)
2587 {
2588         int lin_t;
2589         int idx, lin;
2590
2591         if (log_t <= 0) {
2592                 lin_t = 0x00000000;
2593                 return (lin_t);
2594         }
2595
2596         if (log_t >= 100) {
2597                 lin_t = 0x7fffffff;
2598                 return (lin_t);
2599         }
2600
2601         idx = (L2L_POINTS - 1) - log_t / (L2L_POINTS);
2602         lin = log_t % (L2L_POINTS);
2603         lin_t = l2l_df[idx] * lin + l2l_f[idx];
2604         return (lin_t);
2605 }
2606
2607
2608 void
2609 emumix_set_fxvol(struct emu_sc_info *sc, unsigned gpr, int32_t vol)
2610 {
2611
2612         vol = log2lin(vol);
2613         emumix_set_gpr(sc, gpr, vol);
2614 }
2615
2616 void
2617 emumix_set_gpr(struct emu_sc_info *sc, unsigned gpr, int32_t val)
2618 {
2619         if (sc->dbg_level > 1)
2620                 if (gpr == 0) {
2621                         device_printf(sc->dev, "Zero gpr write access\n");
2622 #ifdef KDB
2623                         kdb_backtrace();
2624 #endif
2625                         return;
2626                         }
2627
2628         emu_wrptr(sc, 0, GPR(gpr), val);
2629 }
2630
2631 void
2632 emumix_set_volume(struct emu_sc_info *sc, int mixer_idx, int volume)
2633 {
2634
2635         RANGE(volume, 0, 100);
2636         if (mixer_idx < NUM_MIXERS) {
2637                 sc->mixer_volcache[mixer_idx] = volume;
2638                 emumix_set_fxvol(sc, sc->mixer_gpr[mixer_idx], volume);
2639         }
2640 }
2641
2642 int
2643 emumix_get_volume(struct emu_sc_info *sc, int mixer_idx)
2644 {
2645         if ((mixer_idx < NUM_MIXERS) && (mixer_idx >= 0))
2646                 return (sc->mixer_volcache[mixer_idx]);
2647         return (-1);
2648 }
2649
2650 /* Init CardBus part */
2651 static int
2652 emu_cardbus_init(struct emu_sc_info *sc)
2653 {
2654
2655         /*
2656          * XXX May not need this if we have EMU_IPR3 handler.
2657          * Is it a real init calls, or EMU_IPR3 interrupt acknowledgments?
2658          * Looks much like "(data << 16) | register".
2659          */
2660         emu_wr_cbptr(sc, (0x00d0 << 16) | 0x0000);
2661         emu_wr_cbptr(sc, (0x00d0 << 16) | 0x0001);
2662         emu_wr_cbptr(sc, (0x00d0 << 16) | 0x005f);
2663         emu_wr_cbptr(sc, (0x00d0 << 16) | 0x007f);
2664
2665         emu_wr_cbptr(sc, (0x0090 << 16) | 0x007f);
2666
2667         return (0);
2668 }
2669
2670 /* Probe and attach the card */
2671 static int
2672 emu_init(struct emu_sc_info *sc)
2673 {
2674         uint32_t ch, tmp;
2675         uint32_t spdif_sr;
2676         uint32_t ac97slot;
2677         int def_mode;
2678         int i;
2679
2680         /* disable audio and lock cache */
2681         emu_wr(sc, EMU_HCFG, EMU_HCFG_LOCKSOUNDCACHE | EMU_HCFG_LOCKTANKCACHE_MASK | EMU_HCFG_MUTEBUTTONENABLE, 4);
2682
2683         /* reset recording buffers */
2684         emu_wrptr(sc, 0, EMU_MICBS, EMU_RECBS_BUFSIZE_NONE);
2685         emu_wrptr(sc, 0, EMU_MICBA, 0);
2686         emu_wrptr(sc, 0, EMU_FXBS, EMU_RECBS_BUFSIZE_NONE);
2687         emu_wrptr(sc, 0, EMU_FXBA, 0);
2688         emu_wrptr(sc, 0, EMU_ADCBS, EMU_RECBS_BUFSIZE_NONE);
2689         emu_wrptr(sc, 0, EMU_ADCBA, 0);
2690
2691         /* disable channel interrupt */
2692         emu_wr(sc, EMU_INTE, EMU_INTE_INTERTIMERENB | EMU_INTE_SAMPLERATER | EMU_INTE_PCIERRENABLE, 4);
2693         emu_wrptr(sc, 0, EMU_CLIEL, 0);
2694         emu_wrptr(sc, 0, EMU_CLIEH, 0);
2695         emu_wrptr(sc, 0, EMU_SOLEL, 0);
2696         emu_wrptr(sc, 0, EMU_SOLEH, 0);
2697
2698         /* disable P16V and S/PDIF interrupts */
2699         if ((sc->is_ca0102) || (sc->is_ca0108))
2700                 emu_wr(sc, EMU_INTE2, 0, 4);
2701
2702         if (sc->is_ca0102)
2703                 emu_wr(sc, EMU_INTE3, 0, 4);
2704
2705         /* init phys inputs and outputs */
2706         ac97slot = 0;
2707         if (sc->has_51)
2708                 ac97slot = EMU_AC97SLOT_CENTER | EMU_AC97SLOT_LFE;
2709         if (sc->has_71)
2710                 ac97slot = EMU_AC97SLOT_CENTER | EMU_AC97SLOT_LFE | EMU_AC97SLOT_REAR_LEFT | EMU_AC97SLOT_REAR_RIGHT;
2711         if (sc->is_emu10k2)
2712                 ac97slot |= 0x40;
2713         emu_wrptr(sc, 0, EMU_AC97SLOT, ac97slot);
2714
2715         if (sc->is_emu10k2)     /* XXX for later cards? */
2716                 emu_wrptr(sc, 0, EMU_SPBYPASS, 0xf00);  /* What will happen if
2717                                                          * we write 1 here? */
2718
2719         if (bus_dma_tag_create( /* parent */ bus_get_dma_tag(sc->dev),
2720              /* alignment */ 2, /* boundary */ 0,
2721              /* lowaddr */ (1U << 31) - 1,      /* can only access 0-2gb */
2722              /* highaddr */ BUS_SPACE_MAXADDR,
2723              /* filter */ NULL, /* filterarg */ NULL,
2724              /* maxsize */ EMU_MAX_BUFSZ, /* nsegments */ 1, /* maxsegz */ 0x3ffff,
2725              /* flags */ 0,
2726              &(sc->mem.dmat)) != 0) {
2727                 device_printf(sc->dev, "unable to create dma tag\n");
2728                 bus_dma_tag_destroy(sc->mem.dmat);
2729                 return (ENOMEM);
2730         }
2731
2732         sc->mem.card = sc;
2733         SLIST_INIT(&sc->mem.blocks);
2734         sc->mem.ptb_pages = emu_malloc(&sc->mem, EMU_MAXPAGES * sizeof(uint32_t), &sc->mem.ptb_pages_addr, &sc->mem.ptb_map);
2735         if (sc->mem.ptb_pages == NULL)
2736                 return (ENOMEM);
2737
2738         sc->mem.silent_page = emu_malloc(&sc->mem, EMUPAGESIZE, &sc->mem.silent_page_addr, &sc->mem.silent_map);
2739         if (sc->mem.silent_page == NULL) {
2740                 emu_free(&sc->mem, sc->mem.ptb_pages, sc->mem.ptb_map);
2741                 return (ENOMEM);
2742         }
2743         /* Clear page with silence & setup all pointers to this page */
2744         bzero(sc->mem.silent_page, EMUPAGESIZE);
2745         tmp = (uint32_t) (sc->mem.silent_page_addr) << 1;
2746         for (i = 0; i < EMU_MAXPAGES; i++)
2747                 sc->mem.ptb_pages[i] = tmp | i;
2748
2749         for (ch = 0; ch < NUM_G; ch++) {
2750                 emu_wrptr(sc, ch, EMU_CHAN_MAPA, tmp | EMU_CHAN_MAP_PTI_MASK);
2751                 emu_wrptr(sc, ch, EMU_CHAN_MAPB, tmp | EMU_CHAN_MAP_PTI_MASK);
2752         }
2753         emu_wrptr(sc, 0, EMU_PTB, (sc->mem.ptb_pages_addr));
2754         emu_wrptr(sc, 0, EMU_TCB, 0);   /* taken from original driver */
2755         emu_wrptr(sc, 0, EMU_TCBS, 0);  /* taken from original driver */
2756
2757         /* init envelope engine */
2758         for (ch = 0; ch < NUM_G; ch++) {
2759                 emu_wrptr(sc, ch, EMU_CHAN_DCYSUSV, 0);
2760                 emu_wrptr(sc, ch, EMU_CHAN_IP, 0);
2761                 emu_wrptr(sc, ch, EMU_CHAN_VTFT, 0xffff);
2762                 emu_wrptr(sc, ch, EMU_CHAN_CVCF, 0xffff);
2763                 emu_wrptr(sc, ch, EMU_CHAN_PTRX, 0);
2764                 emu_wrptr(sc, ch, EMU_CHAN_CPF, 0);
2765                 emu_wrptr(sc, ch, EMU_CHAN_CCR, 0);
2766
2767                 emu_wrptr(sc, ch, EMU_CHAN_PSST, 0);
2768                 emu_wrptr(sc, ch, EMU_CHAN_DSL, 0x10);
2769                 emu_wrptr(sc, ch, EMU_CHAN_CCCA, 0);
2770                 emu_wrptr(sc, ch, EMU_CHAN_Z1, 0);
2771                 emu_wrptr(sc, ch, EMU_CHAN_Z2, 0);
2772                 emu_wrptr(sc, ch, EMU_CHAN_FXRT, 0xd01c0000);
2773
2774                 emu_wrptr(sc, ch, EMU_CHAN_ATKHLDM, 0);
2775                 emu_wrptr(sc, ch, EMU_CHAN_DCYSUSM, 0);
2776                 emu_wrptr(sc, ch, EMU_CHAN_IFATN, 0xffff);
2777                 emu_wrptr(sc, ch, EMU_CHAN_PEFE, 0);
2778                 emu_wrptr(sc, ch, EMU_CHAN_FMMOD, 0);
2779                 emu_wrptr(sc, ch, EMU_CHAN_TREMFRQ, 24);        /* 1 Hz */
2780                 emu_wrptr(sc, ch, EMU_CHAN_FM2FRQ2, 24);        /* 1 Hz */
2781                 emu_wrptr(sc, ch, EMU_CHAN_TEMPENV, 0);
2782
2783                 /*** these are last so OFF prevents writing ***/
2784                 emu_wrptr(sc, ch, EMU_CHAN_LFOVAL2, 0);
2785                 emu_wrptr(sc, ch, EMU_CHAN_LFOVAL1, 0);
2786                 emu_wrptr(sc, ch, EMU_CHAN_ATKHLDV, 0);
2787                 emu_wrptr(sc, ch, EMU_CHAN_ENVVOL, 0);
2788                 emu_wrptr(sc, ch, EMU_CHAN_ENVVAL, 0);
2789
2790                 if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108)) {
2791                         emu_wrptr(sc, ch, 0x4c, 0x0);
2792                         emu_wrptr(sc, ch, 0x4d, 0x0);
2793                         emu_wrptr(sc, ch, 0x4e, 0x0);
2794                         emu_wrptr(sc, ch, 0x4f, 0x0);
2795                         emu_wrptr(sc, ch, EMU_A_CHAN_FXRT1, 0x3f3f3f3f);
2796                         emu_wrptr(sc, ch, EMU_A_CHAN_FXRT2, 0x3f3f3f3f);
2797                         emu_wrptr(sc, ch, EMU_A_CHAN_SENDAMOUNTS, 0x0);
2798                 }
2799         }
2800
2801         emumix_set_spdif_mode(sc, SPDIF_MODE_PCM);
2802
2803         if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108))
2804                 emu_wrptr(sc, 0, EMU_A_SPDIF_SAMPLERATE, EMU_A_SPDIF_48000);
2805
2806         /*
2807          * CAxxxx cards needs additional setup:
2808          * 1. Set I2S capture sample rate to 96000
2809          * 2. Disable P16v / P17v proceesing
2810          * 3. Allow EMU10K DSP inputs
2811          */
2812         if ((sc->is_ca0102) || (sc->is_ca0108)) {
2813
2814                 spdif_sr = emu_rdptr(sc, 0, EMU_A_SPDIF_SAMPLERATE);
2815                 spdif_sr &= 0xfffff1ff;
2816                 spdif_sr |= EMU_A_I2S_CAPTURE_96000;
2817                 emu_wrptr(sc, 0, EMU_A_SPDIF_SAMPLERATE, spdif_sr);
2818
2819                 /* Disable P16v processing */
2820                 emu_wr_p16vptr(sc, 0, EMU_A2_SRCSel, 0x14);
2821
2822                 /* Setup P16v/P17v sound routing */
2823                 if (sc->is_ca0102)
2824                         emu_wr_p16vptr(sc, 0, EMU_A2_SRCMULTI_ENABLE, 0xFF00FF00);
2825                 else {
2826                         emu_wr_p16vptr(sc, 0, EMU_A2_MIXER_I2S_ENABLE, 0xFF000000);
2827                         emu_wr_p16vptr(sc, 0, EMU_A2_MIXER_SPDIF_ENABLE, 0xFF000000);
2828
2829                         tmp = emu_rd(sc, EMU_A_IOCFG, 2);
2830                         emu_wr(sc, EMU_A_IOCFG, tmp & ~0x8, 2);
2831                 }
2832         }
2833         emu_initefx(sc);
2834
2835         def_mode = MODE_ANALOG;
2836         if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108))
2837                 def_mode = MODE_DIGITAL;
2838         if (((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108)) && (sc->broken_digital)) {
2839                 device_printf(sc->dev, "Audigy card initialized in analog mode.\n");
2840                 def_mode = MODE_ANALOG;
2841         }
2842         emumix_set_mode(sc, def_mode);
2843
2844         if (bootverbose) {
2845                 tmp = emu_rd(sc, EMU_HCFG, 4);
2846                 device_printf(sc->dev, "Card Configuration (   0x%08x )\n", tmp);
2847                 device_printf(sc->dev, "Card Configuration ( & 0xff000000 ) : %s%s%s%s%s%s%s%s\n",
2848                     (tmp & 0x80000000 ? "[Legacy MPIC] " : ""),
2849                     (tmp & 0x40000000 ? "[0x40] " : ""),
2850                     (tmp & 0x20000000 ? "[0x20] " : ""),
2851                     (tmp & 0x10000000 ? "[0x10] " : ""),
2852                     (tmp & 0x08000000 ? "[0x08] " : ""),
2853                     (tmp & 0x04000000 ? "[0x04] " : ""),
2854                     (tmp & 0x02000000 ? "[0x02] " : ""),
2855                     (tmp & 0x01000000 ? "[0x01]" : " "));
2856                 device_printf(sc->dev, "Card Configuration ( & 0x00ff0000 ) : %s%s%s%s%s%s%s%s\n",
2857                     (tmp & 0x00800000 ? "[0x80] " : ""),
2858                     (tmp & 0x00400000 ? "[0x40] " : ""),
2859                     (tmp & 0x00200000 ? "[Legacy INT] " : ""),
2860                     (tmp & 0x00100000 ? "[0x10] " : ""),
2861                     (tmp & 0x00080000 ? "[0x08] " : ""),
2862                     (tmp & 0x00040000 ? "[Codec4] " : ""),
2863                     (tmp & 0x00020000 ? "[Codec2] " : ""),
2864                     (tmp & 0x00010000 ? "[I2S Codec]" : " "));
2865                 device_printf(sc->dev, "Card Configuration ( & 0x0000ff00 ) : %s%s%s%s%s%s%s%s\n",
2866                     (tmp & 0x00008000 ? "[0x80] " : ""),
2867                     (tmp & 0x00004000 ? "[GPINPUT0] " : ""),
2868                     (tmp & 0x00002000 ? "[GPINPUT1] " : ""),
2869                     (tmp & 0x00001000 ? "[GPOUT0] " : ""),
2870                     (tmp & 0x00000800 ? "[GPOUT1] " : ""),
2871                     (tmp & 0x00000400 ? "[GPOUT2] " : ""),
2872                     (tmp & 0x00000200 ? "[Joystick] " : ""),
2873                     (tmp & 0x00000100 ? "[0x01]" : " "));
2874                 device_printf(sc->dev, "Card Configuration ( & 0x000000ff ) : %s%s%s%s%s%s%s%s\n",
2875                     (tmp & 0x00000080 ? "[0x80] " : ""),
2876                     (tmp & 0x00000040 ? "[0x40] " : ""),
2877                     (tmp & 0x00000020 ? "[0x20] " : ""),
2878                     (tmp & 0x00000010 ? "[AUTOMUTE] " : ""),
2879                     (tmp & 0x00000008 ? "[LOCKSOUNDCACHE] " : ""),
2880                     (tmp & 0x00000004 ? "[LOCKTANKCACHE] " : ""),
2881                     (tmp & 0x00000002 ? "[MUTEBUTTONENABLE] " : ""),
2882                     (tmp & 0x00000001 ? "[AUDIOENABLE]" : " "));
2883
2884                 if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108)) {
2885                         tmp = emu_rd(sc, EMU_A_IOCFG, 2);
2886                         device_printf(sc->dev, "Audigy Card Configuration (    0x%04x )\n", tmp);
2887                         device_printf(sc->dev, "Audigy Card Configuration (  & 0xff00 )");
2888                         kprintf(" : %s%s%s%s%s%s%s%s\n",
2889                             (tmp & 0x8000 ? "[Rear Speakers] " : ""),
2890                             (tmp & 0x4000 ? "[Front Speakers] " : ""),
2891                             (tmp & 0x2000 ? "[0x20] " : ""),
2892                             (tmp & 0x1000 ? "[0x10] " : ""),
2893                             (tmp & 0x0800 ? "[0x08] " : ""),
2894                             (tmp & 0x0400 ? "[0x04] " : ""),
2895                             (tmp & 0x0200 ? "[0x02] " : ""),
2896                             (tmp & 0x0100 ? "[AudigyDrive Phones]" : " "));
2897                         device_printf(sc->dev, "Audigy Card Configuration (  & 0x00ff )");
2898                         kprintf(" : %s%s%s%s%s%s%s%s\n",
2899                             (tmp & 0x0080 ? "[0x80] " : ""),
2900                             (tmp & 0x0040 ? "[Mute AnalogOut] " : ""),
2901                             (tmp & 0x0020 ? "[0x20] " : ""),
2902                             (tmp & 0x0010 ? "[0x10] " : ""),
2903                             (tmp & 0x0008 ? "[0x08] " : ""),
2904                             (tmp & 0x0004 ? "[GPOUT0] " : ""),
2905                             (tmp & 0x0002 ? "[GPOUT1] " : ""),
2906                             (tmp & 0x0001 ? "[GPOUT2]" : " "));
2907                 }               /* is_emu10k2 or ca* */
2908         }                       /* bootverbose */
2909         return (0);
2910 }
2911
2912 static int
2913 emu_uninit(struct emu_sc_info *sc)
2914 {
2915         uint32_t ch;
2916         struct emu_memblk *blk;
2917
2918         emu_wr(sc, EMU_INTE, 0, 4);
2919         for (ch = 0; ch < NUM_G; ch++)
2920                 emu_wrptr(sc, ch, EMU_CHAN_DCYSUSV, 0);
2921         for (ch = 0; ch < NUM_G; ch++) {
2922                 emu_wrptr(sc, ch, EMU_CHAN_VTFT, 0);
2923                 emu_wrptr(sc, ch, EMU_CHAN_CVCF, 0);
2924                 emu_wrptr(sc, ch, EMU_CHAN_PTRX, 0);
2925                 emu_wrptr(sc, ch, EMU_CHAN_CPF, 0);
2926         }
2927
2928         /* disable audio and lock cache */
2929         emu_wr(sc, EMU_HCFG, EMU_HCFG_LOCKSOUNDCACHE | EMU_HCFG_LOCKTANKCACHE_MASK | EMU_HCFG_MUTEBUTTONENABLE, 4);
2930
2931         emu_wrptr(sc, 0, EMU_PTB, 0);
2932         /* reset recording buffers */
2933         emu_wrptr(sc, 0, EMU_MICBS, EMU_RECBS_BUFSIZE_NONE);
2934         emu_wrptr(sc, 0, EMU_MICBA, 0);
2935         emu_wrptr(sc, 0, EMU_FXBS, EMU_RECBS_BUFSIZE_NONE);
2936         emu_wrptr(sc, 0, EMU_FXBA, 0);
2937         emu_wrptr(sc, 0, EMU_FXWC, 0);
2938         emu_wrptr(sc, 0, EMU_ADCBS, EMU_RECBS_BUFSIZE_NONE);
2939         emu_wrptr(sc, 0, EMU_ADCBA, 0);
2940         emu_wrptr(sc, 0, EMU_TCB, 0);
2941         emu_wrptr(sc, 0, EMU_TCBS, 0);
2942
2943         /* disable channel interrupt */
2944         emu_wrptr(sc, 0, EMU_CLIEL, 0);
2945         emu_wrptr(sc, 0, EMU_CLIEH, 0);
2946         emu_wrptr(sc, 0, EMU_SOLEL, 0);
2947         emu_wrptr(sc, 0, EMU_SOLEH, 0);
2948
2949         if (!SLIST_EMPTY(&sc->mem.blocks))
2950                 device_printf(sc->dev, "warning: memblock list not empty\n");
2951
2952         SLIST_FOREACH(blk, &sc->mem.blocks, link)
2953                 if (blk != NULL)
2954                 device_printf(sc->dev, "lost %d for %s\n", blk->pte_size, blk->owner);
2955
2956         emu_free(&sc->mem, sc->mem.ptb_pages, sc->mem.ptb_map);
2957         emu_free(&sc->mem, sc->mem.silent_page, sc->mem.silent_map);
2958
2959         return (0);
2960 }
2961
2962 static int
2963 emu_read_ivar(device_t bus, device_t dev, int ivar_index, uintptr_t * result)
2964 {
2965         struct sndcard_func *func = device_get_ivars(dev);
2966         struct emu_sc_info *sc = device_get_softc(bus);
2967
2968         if (func==NULL)
2969                 return (ENOMEM);
2970         if (sc == NULL)
2971                 return (ENOMEM);
2972
2973         switch (ivar_index) {
2974         case EMU_VAR_FUNC:
2975                 *result = func->func;
2976                 break;
2977         case EMU_VAR_ROUTE:
2978                 if (func->varinfo == NULL)
2979                         return (ENOMEM);
2980                 *result = ((struct emu_pcminfo *)func->varinfo)->route;
2981                 break;
2982         case EMU_VAR_ISEMU10K1:
2983                 *result = sc->is_emu10k1;
2984                 break;
2985         case EMU_VAR_MCH_DISABLED:
2986                 *result = sc->mch_disabled;
2987                 break;
2988         case EMU_VAR_MCH_REC:
2989                 *result = sc->mch_rec;
2990                 break;
2991         default:
2992                 return (ENOENT);
2993         }
2994
2995         return (0);
2996 }
2997
2998 static int
2999 emu_write_ivar(device_t bus __unused, device_t dev __unused,
3000     int ivar_index, uintptr_t value __unused)
3001 {
3002
3003         switch (ivar_index) {
3004                 case 0:
3005                 return (EINVAL);
3006
3007         default:
3008                 return (ENOENT);
3009         }
3010 }
3011
3012 static int
3013 emu_pci_probe(device_t dev)
3014 {
3015         struct sbuf *s;
3016         unsigned int thiscard = 0;
3017         uint16_t vendor;
3018
3019         vendor = pci_read_config(dev, PCIR_DEVVENDOR, /* bytes */ 2);
3020         if (vendor != 0x1102)
3021                 return (ENXIO); /* Not Creative */
3022
3023         thiscard = emu_getcard(dev);
3024         if (thiscard == 0)
3025                 return (ENXIO);
3026
3027         s = sbuf_new(NULL, NULL, 4096, 0);
3028         if (s == NULL)
3029                 return (ENOMEM);
3030         sbuf_printf(s, "Creative %s [%s]", emu_cards[thiscard].desc, emu_cards[thiscard].SBcode);
3031         sbuf_finish(s);
3032
3033         device_set_desc_copy(dev, sbuf_data(s));
3034
3035         sbuf_delete(s);
3036
3037         return (BUS_PROBE_DEFAULT);
3038 }
3039
3040
3041 static int
3042 emu_pci_attach(device_t dev)
3043 {
3044         struct sndcard_func *func;
3045         struct emu_sc_info *sc;
3046         struct emu_pcminfo *pcminfo;
3047 #if 0
3048         struct emu_midiinfo *midiinfo;
3049 #endif
3050         int i;
3051         int device_flags;
3052         char status[255];
3053         int error = ENXIO;
3054         int unit;
3055
3056         sc = device_get_softc(dev);
3057         unit = device_get_unit(dev);
3058
3059         /* Get configuration */
3060
3061         sc->ctx = device_get_sysctl_ctx(dev);
3062         if (sc->ctx == NULL)
3063                 goto bad;
3064         sc->root = device_get_sysctl_tree(dev);
3065         if (sc->root == NULL)
3066                 goto bad;
3067
3068         if (resource_int_value("emu10kx", unit, "multichannel_disabled", &(sc->mch_disabled)))
3069                 RANGE(sc->mch_disabled, 0, 1);
3070         SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3071             SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
3072             OID_AUTO, "multichannel_disabled", CTLFLAG_RD, &(sc->mch_disabled), 0, "Multichannel playback setting");
3073
3074         if (resource_int_value("emu10kx", unit, "multichannel_recording", &(sc->mch_rec)))
3075                 RANGE(sc->mch_rec, 0, 1);
3076         SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3077             SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
3078             OID_AUTO, "multichannel_recording", CTLFLAG_RD,  &(sc->mch_rec), 0, "Multichannel recording setting");
3079
3080         if (resource_int_value("emu10kx", unit, "debug", &(sc->dbg_level)))
3081                 RANGE(sc->mch_rec, 0, 2);
3082         SYSCTL_ADD_INT(device_get_sysctl_ctx(dev),
3083             SYSCTL_CHILDREN(device_get_sysctl_tree(dev)),
3084             OID_AUTO, "debug", CTLFLAG_RW, &(sc->dbg_level), 0, "Debug level");
3085
3086         /* Fill in the softc. */
3087         lockinit(&sc->lock, device_get_nameunit(dev), 0, LK_CANRECURSE);
3088         lockinit(&sc->rw, device_get_nameunit(dev), 0, LK_CANRECURSE);
3089         sc->dev = dev;
3090         sc->type = pci_get_devid(dev);
3091         sc->rev = pci_get_revid(dev);
3092         sc->enable_ir = 0;
3093         sc->has_ac97 = 0;
3094         sc->has_51 = 0;
3095         sc->has_71 = 0;
3096         sc->broken_digital = 0;
3097         sc->is_emu10k1 = 0;
3098         sc->is_emu10k2 = 0;
3099         sc->is_ca0102 = 0;
3100         sc->is_ca0108 = 0;
3101         sc->is_cardbus = 0;
3102
3103         device_flags = emu_cards[emu_getcard(dev)].flags;
3104         if (device_flags & HAS_51)
3105                 sc->has_51 = 1;
3106         if (device_flags & HAS_71) {
3107                 sc->has_51 = 1;
3108                 sc->has_71 = 1;
3109         }
3110         if (device_flags & IS_EMU10K1)
3111                 sc->is_emu10k1 = 1;
3112         if (device_flags & IS_EMU10K2)
3113                 sc->is_emu10k2 = 1;
3114         if (device_flags & IS_CA0102)
3115                 sc->is_ca0102 = 1;
3116         if (device_flags & IS_CA0108)
3117                 sc->is_ca0108 = 1;
3118         if ((sc->is_emu10k2) && (sc->rev == 4)) {
3119                 sc->is_emu10k2 = 0;
3120                 sc->is_ca0102 = 1;      /* for unknown Audigy 2 cards */
3121         }
3122         if ((sc->is_ca0102 == 1) || (sc->is_ca0108 == 1))
3123                 if (device_flags & IS_CARDBUS)
3124                         sc->is_cardbus = 1;
3125
3126         if ((sc->is_emu10k1 + sc->is_emu10k2 + sc->is_ca0102 + sc->is_ca0108) != 1) {
3127                 device_printf(sc->dev, "Unable to detect HW chipset\n");
3128                 goto bad;
3129         }
3130         if (device_flags & BROKEN_DIGITAL)
3131                 sc->broken_digital = 1;
3132         if (device_flags & HAS_AC97)
3133                 sc->has_ac97 = 1;
3134
3135         sc->opcode_shift = 0;
3136         if ((sc->is_emu10k2) || (sc->is_ca0102) || (sc->is_ca0108)) {
3137                 sc->opcode_shift = 24;
3138                 sc->high_operand_shift = 12;
3139
3140         /*      DSP map                         */
3141         /*      sc->fx_base = 0x0               */
3142                 sc->input_base = 0x40;
3143         /*      sc->p16vinput_base = 0x50;      */
3144                 sc->output_base = 0x60;
3145                 sc->efxc_base = 0x80;
3146         /*      sc->output32h_base = 0xa0;      */
3147         /*      sc->output32l_base = 0xb0;      */
3148                 sc->dsp_zero = 0xc0;
3149         /*      0xe0...0x100 are unknown        */
3150         /*      sc->tram_base = 0x200           */
3151         /*      sc->tram_addr_base = 0x300      */
3152                 sc->gpr_base = EMU_A_FXGPREGBASE;
3153                 sc->num_gprs = 0x200;
3154                 sc->code_base = EMU_A_MICROCODEBASE;
3155                 sc->code_size = 0x800 / 2;      /* 0x600-0xdff,  2048 words,
3156                                                  * 1024 instructions */
3157
3158                 sc->mchannel_fx = 8;
3159                 sc->num_fxbuses = 16;
3160                 sc->num_inputs = 8;
3161                 sc->num_outputs = 16;
3162                 sc->address_mask = EMU_A_PTR_ADDR_MASK;
3163         }
3164         if (sc->is_emu10k1) {
3165                 sc->has_51 = 0; /* We don't support 5.1 sound on SB Live! 5.1 */
3166                 sc->opcode_shift = 20;
3167                 sc->high_operand_shift = 10;
3168                 sc->code_base = EMU_MICROCODEBASE;
3169                 sc->code_size = 0x400 / 2;      /* 0x400-0x7ff,  1024 words,
3170                                                  * 512 instructions */
3171                 sc->gpr_base = EMU_FXGPREGBASE;
3172                 sc->num_gprs = 0x100;
3173                 sc->input_base = 0x10;
3174                 sc->output_base = 0x20;
3175                 /*
3176                  * XXX 5.1 Analog outputs are inside efxc address space!
3177                  * They use output+0x11/+0x12 (=efxc+1/+2).
3178                  * Don't use this efx registers for recording on SB Live! 5.1!
3179                  */
3180                 sc->efxc_base = 0x30;
3181                 sc->dsp_zero = 0x40;
3182                 sc->mchannel_fx = 0;
3183                 sc->num_fxbuses = 8;
3184                 sc->num_inputs = 8;
3185                 sc->num_outputs = 16;
3186                 sc->address_mask = EMU_PTR_ADDR_MASK;
3187         }
3188         if (sc->opcode_shift == 0)
3189                 goto bad;
3190
3191         pci_enable_busmaster(dev);
3192
3193         i = PCIR_BAR(0);
3194         sc->reg = bus_alloc_resource_any(dev, SYS_RES_IOPORT, &i, RF_ACTIVE);
3195         if (sc->reg == NULL) {
3196                 device_printf(dev, "unable to map register space\n");
3197                 goto bad;
3198         }
3199         sc->st = rman_get_bustag(sc->reg);
3200         sc->sh = rman_get_bushandle(sc->reg);
3201
3202         for (i = 0; i < EMU_MAX_IRQ_CONSUMERS; i++)
3203                 sc->timer[i] = 0;       /* disable it */
3204
3205         i = 0;
3206         sc->irq = bus_alloc_resource_any(dev, SYS_RES_IRQ, &i, RF_ACTIVE | RF_SHAREABLE);
3207         if ((sc->irq == NULL) || bus_setup_intr(dev, sc->irq, INTR_MPSAFE,
3208             emu_intr, sc, &sc->ih, NULL)) {
3209                 device_printf(dev, "unable to map interrupt\n");
3210                 goto bad;
3211         }
3212         if (emu_rm_init(sc) != 0) {
3213                 device_printf(dev, "unable to create resource manager\n");
3214                 goto bad;
3215         }
3216         if (sc->is_cardbus)
3217                 if (emu_cardbus_init(sc) != 0) {
3218                         device_printf(dev, "unable to initialize CardBus interface\n");
3219                         goto bad;
3220                 }
3221         if (emu_init(sc) != 0) {
3222                 device_printf(dev, "unable to initialize the card\n");
3223                 goto bad;
3224         }
3225         if (emu10kx_dev_init(sc) != 0) {
3226                 device_printf(dev, "unable to create control device\n");
3227                 goto bad;
3228         }
3229         ksnprintf(status, 255, "rev %d at io 0x%lx irq %ld", sc->rev, rman_get_start(sc->reg), rman_get_start(sc->irq));
3230
3231         /* Voices */
3232         for (i = 0; i < NUM_G; i++) {
3233                 sc->voice[i].vnum = i;
3234                 sc->voice[i].slave = NULL;
3235                 sc->voice[i].busy = 0;
3236                 sc->voice[i].ismaster = 0;
3237                 sc->voice[i].running = 0;
3238                 sc->voice[i].b16 = 0;
3239                 sc->voice[i].stereo = 0;
3240                 sc->voice[i].speed = 0;
3241                 sc->voice[i].start = 0;
3242                 sc->voice[i].end = 0;
3243         }
3244
3245         /* PCM Audio */
3246         for (i = 0; i < RT_COUNT; i++)
3247                 sc->pcm[i] = NULL;
3248
3249         /* FRONT */
3250         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3251                        M_NOWAIT | M_ZERO);
3252         if (func == NULL) {
3253                 error = ENOMEM;
3254                 goto bad;
3255         }
3256         pcminfo = kmalloc(sizeof(struct emu_pcminfo), M_DEVBUF,
3257                           M_NOWAIT | M_ZERO);
3258         if (pcminfo == NULL) {
3259                 error = ENOMEM;
3260                 goto bad;
3261         }
3262         pcminfo->card = sc;
3263         pcminfo->route = RT_FRONT;
3264
3265         func->func = SCF_PCM;
3266         func->varinfo = pcminfo;
3267         sc->pcm[RT_FRONT] = device_add_child(dev, "pcm", -1);
3268         device_set_ivars(sc->pcm[RT_FRONT], func);
3269
3270         if (!(sc->mch_disabled)) {
3271                 /* REAR */
3272                 func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3273                                M_NOWAIT | M_ZERO);
3274                 if (func == NULL) {
3275                         error = ENOMEM;
3276                         goto bad;
3277                 }
3278                 pcminfo = kmalloc(sizeof(struct emu_pcminfo), M_DEVBUF,
3279                                   M_NOWAIT | M_ZERO);
3280                 if (pcminfo == NULL) {
3281                         error = ENOMEM;
3282                         goto bad;
3283                 }
3284                 pcminfo->card = sc;
3285                 pcminfo->route = RT_REAR;
3286
3287                 func->func = SCF_PCM;
3288                 func->varinfo = pcminfo;
3289                 sc->pcm[RT_REAR] = device_add_child(dev, "pcm", -1);
3290                 device_set_ivars(sc->pcm[RT_REAR], func);
3291                 if (sc->has_51) {
3292                         /* CENTER */
3293                         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3294                                        M_NOWAIT | M_ZERO);
3295                         if (func == NULL) {
3296                                 error = ENOMEM;
3297                                 goto bad;
3298                         }
3299                         pcminfo = kmalloc(sizeof(struct emu_pcminfo),
3300                                           M_DEVBUF, M_NOWAIT | M_ZERO);
3301                         if (pcminfo == NULL) {
3302                                 error = ENOMEM;
3303                                 goto bad;
3304                         }
3305                         pcminfo->card = sc;
3306                         pcminfo->route = RT_CENTER;
3307
3308                         func->func = SCF_PCM;
3309                         func->varinfo = pcminfo;
3310                         sc->pcm[RT_CENTER] = device_add_child(dev, "pcm", -1);
3311                         device_set_ivars(sc->pcm[RT_CENTER], func);
3312                         /* SUB */
3313                         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3314                                        M_NOWAIT | M_ZERO);
3315                         if (func == NULL) {
3316                                 error = ENOMEM;
3317                                 goto bad;
3318                         }
3319                         pcminfo = kmalloc(sizeof(struct emu_pcminfo),
3320                                           M_DEVBUF, M_NOWAIT | M_ZERO);
3321                         if (pcminfo == NULL) {
3322                                 error = ENOMEM;
3323                                 goto bad;
3324                         }
3325                         pcminfo->card = sc;
3326                         pcminfo->route = RT_SUB;
3327
3328                         func->func = SCF_PCM;
3329                         func->varinfo = pcminfo;
3330                         sc->pcm[RT_SUB] = device_add_child(dev, "pcm", -1);
3331                         device_set_ivars(sc->pcm[RT_SUB], func);
3332                 }
3333                 if (sc->has_71) {
3334                         /* SIDE */
3335                         func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3336                                        M_NOWAIT | M_ZERO);
3337                         if (func == NULL) {
3338                                 error = ENOMEM;
3339                                 goto bad;
3340                         }
3341                         pcminfo = kmalloc(sizeof(struct emu_pcminfo),
3342                                           M_DEVBUF, M_NOWAIT | M_ZERO);
3343                         if (pcminfo == NULL) {
3344                                 error = ENOMEM;
3345                                 goto bad;
3346                         }
3347                         pcminfo->card = sc;
3348                         pcminfo->route = RT_SIDE;
3349
3350                         func->func = SCF_PCM;
3351                         func->varinfo = pcminfo;
3352                         sc->pcm[RT_SIDE] = device_add_child(dev, "pcm", -1);
3353                         device_set_ivars(sc->pcm[RT_SIDE], func);
3354                 }
3355         } /* mch_disabled */
3356
3357         if (sc->mch_rec) {
3358                 func = kmalloc(sizeof(struct sndcard_func), M_DEVBUF,
3359                                M_NOWAIT | M_ZERO);
3360                 if (func == NULL) {
3361                         error = ENOMEM;
3362                         goto bad;
3363                 }
3364                 pcminfo = kmalloc(sizeof(struct emu_pcminfo), M_DEVBUF,
3365                                   M_NOWAIT | M_ZERO);
3366                 if (pcminfo == NULL) {
3367                         error = ENOMEM;
3368                         goto bad;
3369                 }
3370                 pcminfo->card = sc;
3371                 pcminfo->route = RT_MCHRECORD;
3372
3373                 func->func = SCF_PCM;
3374                 func->varinfo = pcminfo;
3375                 sc->pcm[RT_MCHRECORD] = device_add_child(dev, "pcm", -1);
3376                 device_set_ivars(sc->pcm[RT_MCHRECORD], func);
3377         } /*mch_rec */
3378
3379         for (i = 0; i < 2; i++)
3380                 sc->midi[i] = NULL;
3381
3382         /* MIDI has some memory mangament and (possible) locking problems */
3383 #if 0
3384         /* Midi Interface 1: Live!, Audigy, Audigy 2 */
3385         if ((sc->is_emu10k1) || (sc->is_emu10k2) || (sc->is_ca0102)) {
3386                 func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO);
3387                 if (func == NULL) {
3388                         error = ENOMEM;
3389                         goto bad;
3390                 }
3391                 midiinfo = malloc(sizeof(struct emu_midiinfo), M_DEVBUF, M_NOWAIT | M_ZERO);
3392                 if (midiinfo == NULL) {
3393                         error = ENOMEM;
3394                         goto bad;
3395                 }
3396                 midiinfo->card = sc;
3397                 if (sc->is_emu10k2 || (sc->is_ca0102)) {
3398                         midiinfo->port = EMU_A_MUDATA1;
3399                         midiinfo->portnr = 1;
3400                 }
3401                 if (sc->is_emu10k1) {
3402                         midiinfo->port = MUDATA;
3403                         midiinfo->portnr = 1;
3404                 }
3405                 func->func = SCF_MIDI;
3406                 func->varinfo = midiinfo;
3407                 sc->midi[0] = device_add_child(dev, "midi", -1);
3408                 device_set_ivars(sc->midi[0], func);
3409         }
3410         /* Midi Interface 2: Audigy, Audigy 2 (on AudigyDrive) */
3411         if (sc->is_emu10k2 || (sc->is_ca0102)) {
3412                 func = malloc(sizeof(struct sndcard_func), M_DEVBUF, M_NOWAIT | M_ZERO);
3413                 if (func == NULL) {
3414                         error = ENOMEM;
3415                         goto bad;
3416                 }
3417                 midiinfo = malloc(sizeof(struct emu_midiinfo), M_DEVBUF, M_NOWAIT | M_ZERO);
3418                 if (midiinfo == NULL) {
3419                         error = ENOMEM;
3420                         goto bad;
3421                 }
3422                 midiinfo->card = sc;
3423
3424                 midiinfo->port = EMU_A_MUDATA2;
3425                 midiinfo->portnr = 2;
3426
3427                 func->func = SCF_MIDI;
3428                 func->varinfo = midiinfo;
3429                 sc->midi[1] = device_add_child(dev, "midi", -1);
3430                 device_set_ivars(sc->midi[1], func);
3431         }
3432 #endif
3433         return (bus_generic_attach(dev));
3434
3435 bad:
3436         /* XXX can we just call emu_pci_detach here? */
3437         if (sc->cdev)
3438                 emu10kx_dev_uninit(sc);
3439         if (sc->rm != NULL)
3440                 emu_rm_uninit(sc);
3441         if (sc->reg)
3442                 bus_release_resource(dev, SYS_RES_IOPORT, PCIR_BAR(0), sc->reg);
3443         if (sc->ih)
3444                 bus_teardown_intr(dev, sc->irq, sc->ih);
3445         if (sc->irq)
3446                 bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
3447         lockuninit(&sc->rw);
3448         lockuninit(&sc->lock);
3449         return (error);
3450 }
3451
3452 static int
3453 emu_pci_detach(device_t dev)
3454 {
3455         struct emu_sc_info *sc;
3456         struct sndcard_func *func;
3457         int devcount, i;
3458         device_t *childlist;
3459         int r = 0;
3460
3461         sc = device_get_softc(dev);
3462         
3463         for (i = 0; i < RT_COUNT; i++) {
3464                 if (sc->pcm[i] != NULL) {
3465                         func = device_get_ivars(sc->pcm[i]);
3466                         if (func != NULL && func->func == SCF_PCM) {
3467                                 device_set_ivars(sc->pcm[i], NULL);
3468                                 kfree(func->varinfo, M_DEVBUF);
3469                                 kfree(func, M_DEVBUF);
3470                         }
3471                         r = device_delete_child(dev, sc->pcm[i]);
3472                         if (r)  return (r);
3473                 }
3474         }
3475
3476         if (sc->midi[0] != NULL) {
3477                 func = device_get_ivars(sc->midi[0]);
3478                 if (func != NULL && func->func == SCF_MIDI) {
3479                         device_set_ivars(sc->midi[0], NULL);
3480                         kfree(func->varinfo, M_DEVBUF);
3481                         kfree(func, M_DEVBUF);
3482                 }
3483                 r = device_delete_child(dev, sc->midi[0]);
3484                 if (r)  return (r);
3485         }
3486
3487         if (sc->midi[1] != NULL) {
3488                 func = device_get_ivars(sc->midi[1]);
3489                 if (func != NULL && func->func == SCF_MIDI) {
3490                         device_set_ivars(sc->midi[1], NULL);
3491                         kfree(func->varinfo, M_DEVBUF);
3492                         kfree(func, M_DEVBUF);
3493                 }
3494                 r = device_delete_child(dev, sc->midi[1]);
3495                 if (r)  return (r);
3496         }
3497
3498         if (device_get_children(dev, &childlist, &devcount) == 0)
3499                 for (i = 0; i < devcount - 1; i++) {
3500                         device_printf(dev, "removing stale child %d (unit %d)\n", i, device_get_unit(childlist[i]));
3501                         func = device_get_ivars(childlist[i]);
3502                         if (func != NULL && (func->func == SCF_MIDI || func->func == SCF_PCM)) {
3503                                 device_set_ivars(childlist[i], NULL);
3504                                 kfree(func->varinfo, M_DEVBUF);
3505                                 kfree(func, M_DEVBUF);
3506                         }
3507                         device_delete_child(dev, childlist[i]);
3508                 }
3509         if (childlist != NULL)
3510                 kfree(childlist, M_TEMP);
3511
3512         r = emu10kx_dev_uninit(sc);
3513         if (r)
3514                 return (r);
3515
3516         /* shutdown chip */
3517         emu_uninit(sc);
3518         emu_rm_uninit(sc);
3519
3520         if (sc->mem.dmat)
3521                 bus_dma_tag_destroy(sc->mem.dmat);
3522
3523         if (sc->reg)
3524                 bus_release_resource(dev, SYS_RES_IOPORT, PCIR_BAR(0), sc->reg);
3525         bus_teardown_intr(dev, sc->irq, sc->ih);
3526         bus_release_resource(dev, SYS_RES_IRQ, 0, sc->irq);
3527         lockuninit(&sc->rw);
3528         lockuninit(&sc->lock);
3529
3530         return (bus_generic_detach(dev));
3531 }
3532 /* add suspend, resume */
3533 static device_method_t emu_methods[] = {
3534         /* Device interface */
3535         DEVMETHOD(device_probe, emu_pci_probe),
3536         DEVMETHOD(device_attach, emu_pci_attach),
3537         DEVMETHOD(device_detach, emu_pci_detach),
3538         /* Bus methods */
3539         DEVMETHOD(bus_read_ivar, emu_read_ivar),
3540         DEVMETHOD(bus_write_ivar, emu_write_ivar),
3541
3542         DEVMETHOD_END
3543 };
3544
3545
3546 static driver_t emu_driver = {
3547         "emu10kx",
3548         emu_methods,
3549         sizeof(struct emu_sc_info),
3550         NULL,
3551         0,
3552         NULL
3553 };
3554
3555 static int
3556 emu_modevent(module_t mod __unused, int cmd, void *data __unused)
3557 {
3558         int err = 0;
3559
3560         switch (cmd) {
3561         case MOD_LOAD:
3562                 break;          /* Success */
3563
3564         case MOD_UNLOAD:
3565         case MOD_SHUTDOWN:
3566
3567                 /* XXX  Should we check state of pcm & midi subdevices here? */
3568
3569                 break;          /* Success */
3570
3571         default:
3572                 err = EINVAL;
3573                 break;
3574         }
3575
3576         return (err);
3577
3578 }
3579
3580 static devclass_t emu_devclass;
3581
3582 DRIVER_MODULE(snd_emu10kx, pci, emu_driver, emu_devclass, emu_modevent, NULL);
3583 MODULE_VERSION(snd_emu10kx, SND_EMU10KX_PREFVER);