xref: /netbsd-src/sys/dev/pci/emuxki.c (revision bdc22b2e01993381dcefeff2bc9b56ca75a4235c)
1 /*	$NetBSD: emuxki.c,v 1.65 2017/06/01 02:45:11 chs Exp $	*/
2 
3 /*-
4  * Copyright (c) 2001, 2007 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Yannick Montulet, and by Andrew Doran.
9  *
10  * Redistribution and use in source and binary forms, with or without
11  * modification, are permitted provided that the following conditions
12  * are met:
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer.
15  * 2. Redistributions in binary form must reproduce the above copyright
16  *    notice, this list of conditions and the following disclaimer in the
17  *    documentation and/or other materials provided with the distribution.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
21  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
22  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
23  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
24  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
25  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
26  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
27  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
28  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
29  * POSSIBILITY OF SUCH DAMAGE.
30  */
31 
32 /*
33  * Driver for Creative Labs SBLive! series and probably PCI512.
34  *
35  * Known bugs:
36  * - inversed stereo at ac97 codec level
37  *   (XXX jdolecek - don't see the problem? maybe because auvia(4) has
38  *    it swapped too?)
39  * - bass disappear when you plug rear jack-in on Cambridge FPS2000 speakers
40  *   (and presumably all speakers that support front and rear jack-in)
41  *
42  * TODO:
43  * - Digital Outputs
44  * - (midi/mpu),joystick support
45  * - Multiple voices play (problem with /dev/audio architecture)
46  * - Multiple sources recording (Pb with audio(4))
47  * - Independent modification of each channel's parameters (via mixer ?)
48  * - DSP FX patches (to make fx like chipmunk)
49  */
50 
51 #include <sys/cdefs.h>
52 __KERNEL_RCSID(0, "$NetBSD: emuxki.c,v 1.65 2017/06/01 02:45:11 chs Exp $");
53 
54 #include <sys/param.h>
55 #include <sys/device.h>
56 #include <sys/errno.h>
57 #include <sys/systm.h>
58 #include <sys/audioio.h>
59 #include <sys/select.h>
60 #include <sys/mutex.h>
61 #include <sys/kmem.h>
62 #include <sys/malloc.h>
63 
64 #include <dev/audio_if.h>
65 #include <dev/audiovar.h>
66 #include <dev/auconv.h>
67 #include <dev/mulaw.h>
68 
69 #include <dev/ic/ac97reg.h>
70 #include <dev/ic/ac97var.h>
71 
72 #include <dev/pci/pcireg.h>
73 #include <dev/pci/pcivar.h>
74 #include <dev/pci/pcidevs.h>
75 #include <dev/pci/emuxkireg.h>
76 #include <dev/pci/emuxkivar.h>
77 
78 /* autoconf goo */
79 static int	emuxki_match(device_t, cfdata_t, void *);
80 static void	emuxki_attach(device_t, device_t, void *);
81 static int	emuxki_detach(device_t, int);
82 
83 /* DMA mem mgmt */
84 static struct dmamem *dmamem_alloc(bus_dma_tag_t, size_t, bus_size_t,
85 		int);
86 static void	dmamem_free(struct dmamem *);
87 
88 /* Emu10k1 init & shutdown */
89 static int	emuxki_init(struct emuxki_softc *);
90 static void	emuxki_shutdown(struct emuxki_softc *);
91 
92 /* Emu10k1 mem mgmt */
93 static void	*emuxki_pmem_alloc(struct emuxki_softc *, size_t);
94 static void	*emuxki_rmem_alloc(struct emuxki_softc *, size_t);
95 
96 /*
97  * Emu10k1 channels funcs : There is no direct access to channels, everything
98  * is done through voices I will at least provide channel based fx params
99  * modification, later...
100  */
101 
102 /* Emu10k1 voice mgmt */
103 static struct emuxki_voice *emuxki_voice_new(struct emuxki_softc *,
104 		uint8_t);
105 static void	emuxki_voice_delete(struct emuxki_voice *);
106 static int	emuxki_voice_set_audioparms(struct emuxki_softc *,
107 					    struct emuxki_voice *, uint8_t,
108 					    uint8_t, uint32_t);
109 /* emuxki_voice_set_fxparms will come later, it'll need channel distinction */
110 static int	emuxki_voice_set_bufparms(struct emuxki_voice *,
111 		void *, uint32_t, uint16_t);
112 static void	emuxki_voice_commit_parms(struct emuxki_voice *);
113 static int	emuxki_voice_adc_rate(struct emuxki_voice *);
114 static uint32_t	emuxki_voice_curaddr(struct emuxki_voice *);
115 static void	emuxki_voice_start(struct emuxki_voice *,
116 		void (*) (void *), void *);
117 static void	emuxki_voice_halt(struct emuxki_voice *);
118 
119 /*
120  * Emu10k1 stream mgmt : not done yet
121  */
122 #if 0
123 static struct emuxki_stream *emuxki_stream_new(struct emu10k1 *);
124 static void	emuxki_stream_delete(struct emuxki_stream *);
125 static int	emuxki_stream_set_audio_params(struct emuxki_stream *,
126 		uint8_t, uint8_t, uint8_t, uint16_t);
127 static void	emuxki_stream_start(struct emuxki_stream *);
128 static void	emuxki_stream_halt(struct emuxki_stream *);
129 #endif
130 
131 /* audio interface callbacks */
132 
133 static int	emuxki_open(void *, int);
134 static void	emuxki_close(void *);
135 
136 static int	emuxki_query_encoding(void *, struct audio_encoding *);
137 static int	emuxki_set_params(void *, int, int, audio_params_t *,
138 		audio_params_t *, stream_filter_list_t *,
139 		stream_filter_list_t *);
140 
141 static int	emuxki_round_blocksize(void *, int, int, const audio_params_t *);
142 static size_t	emuxki_round_buffersize(void *, int, size_t);
143 
144 static int	emuxki_trigger_output(void *, void *, void *, int,
145 		void (*)(void *), void *, const audio_params_t *);
146 static int	emuxki_trigger_input(void *, void *, void *, int,
147 		void (*) (void *), void *, const audio_params_t *);
148 static int	emuxki_halt_output(void *);
149 static int	emuxki_halt_input(void *);
150 
151 static int	emuxki_getdev(void *, struct audio_device *);
152 static int	emuxki_set_port(void *, mixer_ctrl_t *);
153 static int	emuxki_get_port(void *, mixer_ctrl_t *);
154 static int	emuxki_query_devinfo(void *, mixer_devinfo_t *);
155 
156 static void    *emuxki_allocm(void *, int, size_t);
157 static void	emuxki_freem(void *, void *, size_t);
158 
159 static paddr_t	emuxki_mappage(void *, void *, off_t, int);
160 static int	emuxki_get_props(void *);
161 static void	emuxki_get_locks(void *, kmutex_t **, kmutex_t **);
162 
163 /* Interrupt handler */
164 static int	emuxki_intr(void *);
165 
166 /* Emu10k1 AC97 interface callbacks */
167 static int	emuxki_ac97_attach(void *, struct ac97_codec_if *);
168 static int	emuxki_ac97_read(void *, uint8_t, uint16_t *);
169 static int	emuxki_ac97_write(void *, uint8_t, uint16_t);
170 static int	emuxki_ac97_reset(void *);
171 static enum ac97_host_flags emuxki_ac97_flags(void *);
172 
173 /*
174  * Autoconfig goo.
175  */
176 CFATTACH_DECL_NEW(emuxki, sizeof(struct emuxki_softc),
177     emuxki_match, emuxki_attach, emuxki_detach, NULL);
178 
179 static const struct audio_hw_if emuxki_hw_if = {
180 	emuxki_open,
181 	emuxki_close,
182 	NULL,			/* drain */
183 	emuxki_query_encoding,
184 	emuxki_set_params,
185 	emuxki_round_blocksize,
186 	NULL,			/* commit settings */
187 	NULL,			/* init_output */
188 	NULL,			/* init_input */
189 	NULL,			/* start_output */
190 	NULL,			/* start_input */
191 	emuxki_halt_output,
192 	emuxki_halt_input,
193 	NULL,			/* speaker_ctl */
194 	emuxki_getdev,
195 	NULL,			/* setfd */
196 	emuxki_set_port,
197 	emuxki_get_port,
198 	emuxki_query_devinfo,
199 	emuxki_allocm,
200 	emuxki_freem,
201 	emuxki_round_buffersize,
202 	emuxki_mappage,
203 	emuxki_get_props,
204 	emuxki_trigger_output,
205 	emuxki_trigger_input,
206 	NULL,			/* dev_ioctl */
207 	emuxki_get_locks,
208 };
209 
210 #if 0
211 static const int emuxki_recsrc_intrmasks[EMU_NUMRECSRCS] =
212     { EMU_INTE_MICBUFENABLE, EMU_INTE_ADCBUFENABLE, EMU_INTE_EFXBUFENABLE };
213 #endif
214 static const uint32_t emuxki_recsrc_bufaddrreg[EMU_NUMRECSRCS] =
215     { EMU_MICBA, EMU_ADCBA, EMU_FXBA };
216 static const uint32_t emuxki_recsrc_szreg[EMU_NUMRECSRCS] =
217     { EMU_MICBS, EMU_ADCBS, EMU_FXBS };
218 static const int emuxki_recbuf_sz[] = {
219 	0, 384, 448, 512, 640, 768, 896, 1024, 1280, 1536, 1792,
220 	2048, 2560, 3072, 3584, 4096, 5120, 6144, 7168, 8192, 10240,
221 	12288, 14366, 16384, 20480, 24576, 28672, 32768, 40960, 49152,
222 	57344, 65536
223 };
224 
225 #define EMUXKI_NFORMATS	4
226 static const struct audio_format emuxki_formats[EMUXKI_NFORMATS] = {
227 	{NULL, AUMODE_PLAY | AUMODE_RECORD, AUDIO_ENCODING_SLINEAR_LE, 16, 16,
228 	 2, AUFMT_STEREO, 0, {4000, 48000}},
229 	{NULL, AUMODE_PLAY | AUMODE_RECORD, AUDIO_ENCODING_SLINEAR_LE, 16, 16,
230 	 1, AUFMT_MONAURAL, 0, {4000, 48000}},
231 	{NULL, AUMODE_PLAY, AUDIO_ENCODING_ULINEAR_LE, 8, 8,
232 	 2, AUFMT_STEREO, 0, {4000, 48000}},
233 	{NULL, AUMODE_PLAY, AUDIO_ENCODING_ULINEAR_LE, 8, 8,
234 	 1, AUFMT_MONAURAL, 0, {4000, 48000}},
235 };
236 
237 /*
238  * DMA memory mgmt
239  */
240 
241 static void
242 dmamem_delete(struct dmamem *mem)
243 {
244 
245 	kmem_free(mem->segs, mem->nsegs * sizeof(*(mem->segs)));
246 	kmem_free(mem, sizeof(*mem));
247 }
248 
249 static struct dmamem *
250 dmamem_alloc(bus_dma_tag_t dmat, size_t size, bus_size_t align, int nsegs)
251 {
252 	struct dmamem	*mem;
253 
254 	/* Allocate memory for structure */
255 	mem = kmem_alloc(sizeof(*mem), KM_SLEEP);
256 	mem->dmat = dmat;
257 	mem->size = size;
258 	mem->align = align;
259 	mem->nsegs = nsegs;
260 	mem->bound = 0;
261 
262 	mem->segs = kmem_alloc(mem->nsegs * sizeof(*(mem->segs)), KM_SLEEP);
263 
264 	if (bus_dmamem_alloc(dmat, mem->size, mem->align, mem->bound,
265 			     mem->segs, mem->nsegs, &(mem->rsegs),
266 			     BUS_DMA_WAITOK)) {
267 		dmamem_delete(mem);
268 		return NULL;
269 	}
270 
271 	if (bus_dmamem_map(dmat, mem->segs, mem->nsegs, mem->size,
272 			   &(mem->kaddr), BUS_DMA_WAITOK | BUS_DMA_COHERENT)) {
273 		bus_dmamem_free(dmat, mem->segs, mem->nsegs);
274 		dmamem_delete(mem);
275 		return NULL;
276 	}
277 
278 	if (bus_dmamap_create(dmat, mem->size, mem->nsegs, mem->size,
279 			      mem->bound, BUS_DMA_WAITOK, &(mem->map))) {
280 		bus_dmamem_unmap(dmat, mem->kaddr, mem->size);
281 		bus_dmamem_free(dmat, mem->segs, mem->nsegs);
282 		dmamem_delete(mem);
283 		return NULL;
284 	}
285 
286 	if (bus_dmamap_load(dmat, mem->map, mem->kaddr,
287 			    mem->size, NULL, BUS_DMA_WAITOK)) {
288 		bus_dmamap_destroy(dmat, mem->map);
289 		bus_dmamem_unmap(dmat, mem->kaddr, mem->size);
290 		bus_dmamem_free(dmat, mem->segs, mem->nsegs);
291 		dmamem_delete(mem);
292 		return NULL;
293 	}
294 
295 	return mem;
296 }
297 
298 static void
299 dmamem_free(struct dmamem *mem)
300 {
301 
302 	bus_dmamap_unload(mem->dmat, mem->map);
303 	bus_dmamap_destroy(mem->dmat, mem->map);
304 	bus_dmamem_unmap(mem->dmat, mem->kaddr, mem->size);
305 	bus_dmamem_free(mem->dmat, mem->segs, mem->nsegs);
306 	dmamem_delete(mem);
307 }
308 
309 
310 /*
311  * Autoconf device callbacks : attach and detach
312  */
313 
314 static void
315 emuxki_pci_shutdown(struct emuxki_softc *sc)
316 {
317 
318 	if (sc->sc_ih != NULL)
319 		pci_intr_disestablish(sc->sc_pc, sc->sc_ih);
320 	if (sc->sc_ios)
321 		bus_space_unmap(sc->sc_iot, sc->sc_ioh, sc->sc_ios);
322 }
323 
324 static int
325 emuxki_scinit(struct emuxki_softc *sc)
326 {
327 	int err;
328 
329 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_HCFG,
330 		EMU_HCFG_LOCKSOUNDCACHE | EMU_HCFG_LOCKTANKCACHE_MASK |
331 		EMU_HCFG_MUTEBUTTONENABLE);
332 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_INTE,
333 		EMU_INTE_SAMPLERATER | EMU_INTE_PCIERRENABLE);
334 
335 	if ((err = emuxki_init(sc)))
336 		return err;
337 
338 	if (sc->sc_type & EMUXKI_AUDIGY2) {
339 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_HCFG,
340 			EMU_HCFG_AUDIOENABLE | EMU_HCFG_AC3ENABLE_CDSPDIF |
341 			EMU_HCFG_AC3ENABLE_GPSPDIF | EMU_HCFG_AUTOMUTE);
342 	} else if (sc->sc_type & EMUXKI_AUDIGY) {
343 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_HCFG,
344 			EMU_HCFG_AUDIOENABLE | EMU_HCFG_AUTOMUTE);
345 	} else {
346 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_HCFG,
347 			EMU_HCFG_AUDIOENABLE | EMU_HCFG_JOYENABLE |
348 			EMU_HCFG_LOCKTANKCACHE_MASK | EMU_HCFG_AUTOMUTE);
349 	}
350 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_INTE,
351 		bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_INTE) |
352 		EMU_INTE_VOLINCRENABLE | EMU_INTE_VOLDECRENABLE |
353 		EMU_INTE_MUTEENABLE);
354 	if (sc->sc_type & EMUXKI_AUDIGY2) {
355 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_A_IOCFG,
356 			EMU_A_IOCFG_GPOUT0 |
357 			bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_A_IOCFG));
358 	}
359 
360 	/* No multiple voice support for now */
361 	sc->pvoice = sc->rvoice = NULL;
362 
363 	return 0;
364 }
365 
366 static int
367 emuxki_ac97_init(struct emuxki_softc *sc)
368 {
369 	sc->hostif.arg = sc;
370 	sc->hostif.attach = emuxki_ac97_attach;
371 	sc->hostif.read = emuxki_ac97_read;
372 	sc->hostif.write = emuxki_ac97_write;
373 	sc->hostif.reset = emuxki_ac97_reset;
374 	sc->hostif.flags = emuxki_ac97_flags;
375 	return ac97_attach(&sc->hostif, sc->sc_dev, &sc->sc_lock);
376 }
377 
378 static int
379 emuxki_match(device_t parent, cfdata_t match, void *aux)
380 {
381 	struct pci_attach_args *pa;
382 
383 	pa = aux;
384 	if (PCI_VENDOR(pa->pa_id) != PCI_VENDOR_CREATIVELABS)
385 		return 0;
386 
387 	switch (PCI_PRODUCT(pa->pa_id)) {
388 	case PCI_PRODUCT_CREATIVELABS_SBLIVE:
389 	case PCI_PRODUCT_CREATIVELABS_SBLIVE2:
390 	case PCI_PRODUCT_CREATIVELABS_AUDIGY:
391 		return 1;
392 	default:
393 		return 0;
394 	}
395 }
396 
397 static void
398 emuxki_attach(device_t parent, device_t self, void *aux)
399 {
400 	struct emuxki_softc *sc;
401 	struct pci_attach_args *pa;
402 	pci_intr_handle_t ih;
403 	const char *intrstr;
404 	char intrbuf[PCI_INTRSTR_LEN];
405 
406 	sc = device_private(self);
407 	sc->sc_dev = self;
408 	pa = aux;
409 
410 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
411 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_AUDIO);
412 	mutex_init(&sc->sc_index_lock, MUTEX_DEFAULT, IPL_AUDIO);
413 	mutex_init(&sc->sc_ac97_index_lock, MUTEX_DEFAULT, IPL_AUDIO);
414 
415 	if (pci_mapreg_map(pa, EMU_PCI_CBIO, PCI_MAPREG_TYPE_IO, 0,
416 	    &(sc->sc_iot), &(sc->sc_ioh), &(sc->sc_iob),
417 			   &(sc->sc_ios))) {
418 		aprint_error(": can't map iospace\n");
419 		return;
420 	}
421 
422 	pci_aprint_devinfo(pa, "Audio controller");
423 
424 	sc->sc_pc   = pa->pa_pc;
425 	sc->sc_dmat = pa->pa_dmat;
426 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
427 		pci_conf_read(pa->pa_pc, pa->pa_tag,
428 		(PCI_COMMAND_STATUS_REG) | PCI_COMMAND_MASTER_ENABLE));
429 
430 	if (pci_intr_map(pa, &ih)) {
431 		aprint_error_dev(self, "couldn't map interrupt\n");
432 		bus_space_unmap(sc->sc_iot, sc->sc_ioh, sc->sc_ios);
433 		return;
434 	}
435 
436 	intrstr = pci_intr_string(pa->pa_pc, ih, intrbuf, sizeof(intrbuf));
437 	sc->sc_ih = pci_intr_establish(pa->pa_pc, ih, IPL_AUDIO, emuxki_intr,
438 		sc);
439 	if (sc->sc_ih == NULL) {
440 		aprint_error_dev(self, "couldn't establish interrupt");
441 		if (intrstr != NULL)
442 			aprint_error(" at %s", intrstr);
443 		aprint_error("\n");
444 		bus_space_unmap(sc->sc_iot, sc->sc_ioh, sc->sc_ios);
445 		return;
446 	}
447 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
448 
449  /* XXX it's unknown whether APS is made from Audigy as well */
450 	if (PCI_PRODUCT(pa->pa_id) == PCI_PRODUCT_CREATIVELABS_AUDIGY) {
451 		sc->sc_type = EMUXKI_AUDIGY;
452 		if (PCI_REVISION(pa->pa_class) == 0x04) {
453 			sc->sc_type |= EMUXKI_AUDIGY2;
454 			strlcpy(sc->sc_audv.name, "Audigy2",
455 			    sizeof sc->sc_audv.name);
456 		} else {
457 			strlcpy(sc->sc_audv.name, "Audigy",
458 			    sizeof sc->sc_audv.name);
459 		}
460 	} else if (pci_conf_read(pa->pa_pc, pa->pa_tag,
461 	    PCI_SUBSYS_ID_REG) == EMU_SUBSYS_APS) {
462 		sc->sc_type = EMUXKI_APS;
463 		strlcpy(sc->sc_audv.name, "E-mu APS", sizeof sc->sc_audv.name);
464 	} else {
465 		sc->sc_type = EMUXKI_SBLIVE;
466 		strlcpy(sc->sc_audv.name, "SB Live!", sizeof sc->sc_audv.name);
467 	}
468 	snprintf(sc->sc_audv.version, sizeof sc->sc_audv.version, "0x%02x",
469 		 PCI_REVISION(pa->pa_class));
470 	strlcpy(sc->sc_audv.config, "emuxki", sizeof sc->sc_audv.config);
471 
472 	if (emuxki_scinit(sc) || emuxki_ac97_init(sc) ||
473 	    (sc->sc_audev = audio_attach_mi(&emuxki_hw_if, sc, self)) == NULL) {
474 		emuxki_pci_shutdown(sc);
475 		return;
476 	}
477 #if 0
478 	mutex_enter(&sc->lock);
479 	sc->rsourcectl.dev =
480 	    sc->codecif->vtbl->get_portnum_by_name(sc->codec_if, AudioCrecord,
481 						   AudioNsource, NULL);
482 	sc->rsourcectl.cp = AUDIO_MIXER_ENUM;
483 	mutex_exit(&sc->lock);
484 #endif
485 }
486 
487 static int
488 emuxki_detach(device_t self, int flags)
489 {
490 	struct emuxki_softc *sc;
491 
492 	sc = device_private(self);
493 	if (sc->sc_audev != NULL) /* Test in case audio didn't attach */
494 		config_detach(sc->sc_audev, 0);
495 
496 	/* All voices should be stopped now but add some code here if not */
497 
498 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_HCFG,
499 		EMU_HCFG_LOCKSOUNDCACHE | EMU_HCFG_LOCKTANKCACHE_MASK |
500 		EMU_HCFG_MUTEBUTTONENABLE);
501 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_INTE, 0);
502 
503 	mutex_enter(&sc->sc_lock);
504 	emuxki_shutdown(sc);
505 	mutex_exit(&sc->sc_lock);
506 
507 	emuxki_pci_shutdown(sc);
508 
509 	mutex_destroy(&sc->sc_lock);
510 	mutex_destroy(&sc->sc_intr_lock);
511 	mutex_destroy(&sc->sc_index_lock);
512 	mutex_destroy(&sc->sc_ac97_index_lock);
513 
514 	return 0;
515 }
516 
517 
518 /* Misc stuff relative to emu10k1 */
519 
520 static uint32_t
521 emuxki_rate_to_pitch(uint32_t rate)
522 {
523 	static const uint32_t logMagTable[128] = {
524 		0x00000, 0x02dfc, 0x05b9e, 0x088e6, 0x0b5d6, 0x0e26f, 0x10eb3,
525 		0x13aa2, 0x1663f, 0x1918a, 0x1bc84, 0x1e72e, 0x2118b, 0x23b9a,
526 		0x2655d, 0x28ed5, 0x2b803, 0x2e0e8, 0x30985, 0x331db, 0x359eb,
527 		0x381b6, 0x3a93d, 0x3d081, 0x3f782, 0x41e42, 0x444c1, 0x46b01,
528 		0x49101, 0x4b6c4, 0x4dc49, 0x50191, 0x5269e, 0x54b6f, 0x57006,
529 		0x59463, 0x5b888, 0x5dc74, 0x60029, 0x623a7, 0x646ee, 0x66a00,
530 		0x68cdd, 0x6af86, 0x6d1fa, 0x6f43c, 0x7164b, 0x73829, 0x759d4,
531 		0x77b4f, 0x79c9a, 0x7bdb5, 0x7dea1, 0x7ff5e, 0x81fed, 0x8404e,
532 		0x86082, 0x88089, 0x8a064, 0x8c014, 0x8df98, 0x8fef1, 0x91e20,
533 		0x93d26, 0x95c01, 0x97ab4, 0x9993e, 0x9b79f, 0x9d5d9, 0x9f3ec,
534 		0xa11d8, 0xa2f9d, 0xa4d3c, 0xa6ab5, 0xa8808, 0xaa537, 0xac241,
535 		0xadf26, 0xafbe7, 0xb1885, 0xb3500, 0xb5157, 0xb6d8c, 0xb899f,
536 		0xba58f, 0xbc15e, 0xbdd0c, 0xbf899, 0xc1404, 0xc2f50, 0xc4a7b,
537 		0xc6587, 0xc8073, 0xc9b3f, 0xcb5ed, 0xcd07c, 0xceaec, 0xd053f,
538 		0xd1f73, 0xd398a, 0xd5384, 0xd6d60, 0xd8720, 0xda0c3, 0xdba4a,
539 		0xdd3b4, 0xded03, 0xe0636, 0xe1f4e, 0xe384a, 0xe512c, 0xe69f3,
540 		0xe829f, 0xe9b31, 0xeb3a9, 0xecc08, 0xee44c, 0xefc78, 0xf148a,
541 		0xf2c83, 0xf4463, 0xf5c2a, 0xf73da, 0xf8b71, 0xfa2f0, 0xfba57,
542 		0xfd1a7, 0xfe8df
543 	};
544 	static const uint8_t logSlopeTable[128] = {
545 		0x5c, 0x5c, 0x5b, 0x5a, 0x5a, 0x59, 0x58, 0x58,
546 		0x57, 0x56, 0x56, 0x55, 0x55, 0x54, 0x53, 0x53,
547 		0x52, 0x52, 0x51, 0x51, 0x50, 0x50, 0x4f, 0x4f,
548 		0x4e, 0x4d, 0x4d, 0x4d, 0x4c, 0x4c, 0x4b, 0x4b,
549 		0x4a, 0x4a, 0x49, 0x49, 0x48, 0x48, 0x47, 0x47,
550 		0x47, 0x46, 0x46, 0x45, 0x45, 0x45, 0x44, 0x44,
551 		0x43, 0x43, 0x43, 0x42, 0x42, 0x42, 0x41, 0x41,
552 		0x41, 0x40, 0x40, 0x40, 0x3f, 0x3f, 0x3f, 0x3e,
553 		0x3e, 0x3e, 0x3d, 0x3d, 0x3d, 0x3c, 0x3c, 0x3c,
554 		0x3b, 0x3b, 0x3b, 0x3b, 0x3a, 0x3a, 0x3a, 0x39,
555 		0x39, 0x39, 0x39, 0x38, 0x38, 0x38, 0x38, 0x37,
556 		0x37, 0x37, 0x37, 0x36, 0x36, 0x36, 0x36, 0x35,
557 		0x35, 0x35, 0x35, 0x34, 0x34, 0x34, 0x34, 0x34,
558 		0x33, 0x33, 0x33, 0x33, 0x32, 0x32, 0x32, 0x32,
559 		0x32, 0x31, 0x31, 0x31, 0x31, 0x31, 0x30, 0x30,
560 		0x30, 0x30, 0x30, 0x2f, 0x2f, 0x2f, 0x2f, 0x2f
561 	};
562 	int8_t i;
563 
564 	if (rate == 0)
565 		return 0;	/* Bail out if no leading "1" */
566 	rate *= 11185;		/* Scale 48000 to 0x20002380 */
567 	for (i = 31; i > 0; i--) {
568 		if (rate & 0x80000000) {	/* Detect leading "1" */
569 			return (((uint32_t) (i - 15) << 20) +
570 				logMagTable[0x7f & (rate >> 24)] +
571 				(0x7f & (rate >> 17)) *
572 				logSlopeTable[0x7f & (rate >> 24)]);
573 		}
574 		rate <<= 1;
575 	}
576 
577 	return 0;		/* Should never reach this point */
578 }
579 
580 /* Emu10k1 Low level */
581 
582 static uint32_t
583 emuxki_read(struct emuxki_softc *sc, uint16_t chano, uint32_t reg)
584 {
585 	uint32_t ptr, mask;
586 	uint8_t  size, offset;
587 
588 	mask = 0xffffffff;
589 	offset = 0;
590 	ptr = ((((u_int32_t) reg) << 16) &
591 		(sc->sc_type & EMUXKI_AUDIGY ?
592 			EMU_A_PTR_ADDR_MASK : EMU_PTR_ADDR_MASK)) |
593 		(chano & EMU_PTR_CHNO_MASK);
594 	if (reg & 0xff000000) {
595 		size = (reg >> 24) & 0x3f;
596 		offset = (reg >> 16) & 0x1f;
597 		mask = ((1 << size) - 1) << offset;
598 	}
599 
600 	mutex_spin_enter(&sc->sc_index_lock);
601 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_PTR, ptr);
602 	ptr = (bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_DATA) & mask)
603 		>> offset;
604 	mutex_spin_exit(&sc->sc_index_lock);
605 
606 	return ptr;
607 }
608 
609 static void
610 emuxki_write(struct emuxki_softc *sc, uint16_t chano,
611 	      uint32_t reg, uint32_t data)
612 {
613 	uint32_t ptr, mask;
614 	uint8_t size, offset;
615 
616 	ptr = ((((u_int32_t) reg) << 16) &
617 		(sc->sc_type & EMUXKI_AUDIGY ?
618 			EMU_A_PTR_ADDR_MASK : EMU_PTR_ADDR_MASK)) |
619 		(chano & EMU_PTR_CHNO_MASK);
620 	if (reg & 0xff000000) {
621 		size = (reg >> 24) & 0x3f;
622 		offset = (reg >> 16) & 0x1f;
623 		mask = ((1 << size) - 1) << offset;
624 		data = ((data << offset) & mask) |
625 			(emuxki_read(sc, chano, reg & 0xffff) & ~mask);
626 	}
627 
628 	mutex_spin_enter(&sc->sc_index_lock);
629 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_PTR, ptr);
630 	bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_DATA, data);
631 	mutex_spin_exit(&sc->sc_index_lock);
632 }
633 
634 /* Microcode should this go in /sys/dev/microcode ? */
635 
636 static void
637 emuxki_write_micro(struct emuxki_softc *sc, uint32_t pc, uint32_t data)
638 {
639 
640 	emuxki_write(sc, 0,
641 		(sc->sc_type & EMUXKI_AUDIGY ?
642 			EMU_A_MICROCODEBASE : EMU_MICROCODEBASE) + pc,
643 		 data);
644 }
645 
646 static void
647 emuxki_dsp_addop(struct emuxki_softc *sc, uint16_t *pc, uint8_t op,
648 		  uint16_t r, uint16_t a, uint16_t x, uint16_t y)
649 {
650 
651 	if (sc->sc_type & EMUXKI_AUDIGY) {
652 		emuxki_write_micro(sc, *pc << 1,
653 			((x << 12) & EMU_A_DSP_LOWORD_OPX_MASK) |
654 			(y & EMU_A_DSP_LOWORD_OPY_MASK));
655 		emuxki_write_micro(sc, (*pc << 1) + 1,
656 			((op << 24) & EMU_A_DSP_HIWORD_OPCODE_MASK) |
657 			((r << 12) & EMU_A_DSP_HIWORD_RESULT_MASK) |
658 			(a & EMU_A_DSP_HIWORD_OPA_MASK));
659 	} else {
660 		emuxki_write_micro(sc, *pc << 1,
661 			((x << 10) & EMU_DSP_LOWORD_OPX_MASK) |
662 			(y & EMU_DSP_LOWORD_OPY_MASK));
663 		emuxki_write_micro(sc, (*pc << 1) + 1,
664 			((op << 20) & EMU_DSP_HIWORD_OPCODE_MASK) |
665 			((r << 10) & EMU_DSP_HIWORD_RESULT_MASK) |
666 			(a & EMU_DSP_HIWORD_OPA_MASK));
667 	}
668 	(*pc)++;
669 }
670 
671 /* init and shutdown */
672 
673 static void
674 emuxki_initfx(struct emuxki_softc *sc)
675 {
676 	uint16_t pc;
677 
678 	/* Set all GPRs to 0 */
679 	for (pc = 0; pc < 256; pc++)
680 		emuxki_write(sc, 0, EMU_DSP_GPR(pc), 0);
681 	for (pc = 0; pc < 160; pc++) {
682 		emuxki_write(sc, 0, EMU_TANKMEMDATAREGBASE + pc, 0);
683 		emuxki_write(sc, 0, EMU_TANKMEMADDRREGBASE + pc, 0);
684 	}
685 	pc = 0;
686 
687 	if (sc->sc_type & EMUXKI_AUDIGY) {
688 		/* AC97 Out (l/r) = AC97 In (l/r) + FX[0/1] * 4 */
689 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
690 				  EMU_A_DSP_OUTL(EMU_A_DSP_OUT_A_FRONT),
691 				  EMU_A_DSP_CST(0),
692 				  EMU_DSP_FX(0), EMU_A_DSP_CST(4));
693 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
694 				  EMU_A_DSP_OUTR(EMU_A_DSP_OUT_A_FRONT),
695 				  EMU_A_DSP_CST(0),
696 				  EMU_DSP_FX(1), EMU_A_DSP_CST(4));
697 
698 		/* Rear channel OUT (l/r) = FX[2/3] * 4 */
699 #if 0
700 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
701 				  EMU_A_DSP_OUTL(EMU_A_DSP_OUT_A_REAR),
702 				  EMU_A_DSP_OUTL(EMU_A_DSP_OUT_A_FRONT),
703 				  EMU_DSP_FX(0), EMU_A_DSP_CST(4));
704 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
705 				  EMU_A_DSP_OUTR(EMU_A_DSP_OUT_A_REAR),
706 				  EMU_A_DSP_OUTR(EMU_A_DSP_OUT_A_FRONT),
707 				  EMU_DSP_FX(1), EMU_A_DSP_CST(4));
708 #endif
709 		/* ADC recording (l/r) = AC97 In (l/r) */
710 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
711 				  EMU_A_DSP_OUTL(EMU_A_DSP_OUT_ADC),
712 				  EMU_A_DSP_INL(EMU_DSP_IN_AC97),
713 				  EMU_A_DSP_CST(0), EMU_A_DSP_CST(0));
714 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
715 				  EMU_A_DSP_OUTR(EMU_A_DSP_OUT_ADC),
716 				  EMU_A_DSP_INR(EMU_DSP_IN_AC97),
717 				  EMU_A_DSP_CST(0), EMU_A_DSP_CST(0));
718 
719 		/* zero out the rest of the microcode */
720 		while (pc < 512)
721 			emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
722 					  EMU_A_DSP_CST(0), EMU_A_DSP_CST(0),
723 					  EMU_A_DSP_CST(0), EMU_A_DSP_CST(0));
724 
725 		emuxki_write(sc, 0, EMU_A_DBG, 0);	/* Is it really necessary ? */
726 	} else {
727 		/* AC97 Out (l/r) = AC97 In (l/r) + FX[0/1] * 4 */
728 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
729 				  EMU_DSP_OUTL(EMU_DSP_OUT_A_FRONT),
730 				  EMU_DSP_CST(0),
731 				  EMU_DSP_FX(0), EMU_DSP_CST(4));
732 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
733 				  EMU_DSP_OUTR(EMU_DSP_OUT_A_FRONT),
734 				  EMU_DSP_CST(0),
735 				  EMU_DSP_FX(1), EMU_DSP_CST(4));
736 
737 		/* Rear channel OUT (l/r) = FX[2/3] * 4 */
738 #if 0
739 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
740 				  EMU_DSP_OUTL(EMU_DSP_OUT_AD_REAR),
741 				  EMU_DSP_OUTL(EMU_DSP_OUT_A_FRONT),
742 				  EMU_DSP_FX(0), EMU_DSP_CST(4));
743 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_MACINTS,
744 				  EMU_DSP_OUTR(EMU_DSP_OUT_AD_REAR),
745 				  EMU_DSP_OUTR(EMU_DSP_OUT_A_FRONT),
746 				  EMU_DSP_FX(1), EMU_DSP_CST(4));
747 #endif
748 		/* ADC recording (l/r) = AC97 In (l/r) */
749 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
750 				  EMU_DSP_OUTL(EMU_DSP_OUT_ADC),
751 				  EMU_DSP_INL(EMU_DSP_IN_AC97),
752 				  EMU_DSP_CST(0), EMU_DSP_CST(0));
753 		emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
754 				  EMU_DSP_OUTR(EMU_DSP_OUT_ADC),
755 				  EMU_DSP_INR(EMU_DSP_IN_AC97),
756 				  EMU_DSP_CST(0), EMU_DSP_CST(0));
757 
758 		/* zero out the rest of the microcode */
759 		while (pc < 512)
760 			emuxki_dsp_addop(sc, &pc, EMU_DSP_OP_ACC3,
761 					  EMU_DSP_CST(0), EMU_DSP_CST(0),
762 					  EMU_DSP_CST(0), EMU_DSP_CST(0));
763 
764 		emuxki_write(sc, 0, EMU_DBG, 0);	/* Is it really necessary ? */
765 	}
766 }
767 
768 static int
769 emuxki_init(struct emuxki_softc *sc)
770 {
771 	uint16_t i;
772 	uint32_t spcs, *ptb;
773 	bus_addr_t silentpage;
774 
775 	/* disable any channel interrupt */
776 	emuxki_write(sc, 0, EMU_CLIEL, 0);
777 	emuxki_write(sc, 0, EMU_CLIEH, 0);
778 	emuxki_write(sc, 0, EMU_SOLEL, 0);
779 	emuxki_write(sc, 0, EMU_SOLEH, 0);
780 
781 	/* Set recording buffers sizes to zero */
782 	emuxki_write(sc, 0, EMU_MICBS, EMU_RECBS_BUFSIZE_NONE);
783 	emuxki_write(sc, 0, EMU_MICBA, 0);
784 	emuxki_write(sc, 0, EMU_FXBS, EMU_RECBS_BUFSIZE_NONE);
785 	emuxki_write(sc, 0, EMU_FXBA, 0);
786 	emuxki_write(sc, 0, EMU_ADCBS, EMU_RECBS_BUFSIZE_NONE);
787 	emuxki_write(sc, 0, EMU_ADCBA, 0);
788 
789 	if(sc->sc_type & EMUXKI_AUDIGY) {
790 		emuxki_write(sc, 0, EMU_SPBYPASS, EMU_SPBYPASS_24_BITS);
791 		emuxki_write(sc, 0, EMU_AC97SLOT, EMU_AC97SLOT_CENTER | EMU_AC97SLOT_LFE);
792 	}
793 
794 	/* Initialize all channels to stopped and no effects */
795 	for (i = 0; i < EMU_NUMCHAN; i++) {
796 		emuxki_write(sc, i, EMU_CHAN_DCYSUSV, 0);
797 		emuxki_write(sc, i, EMU_CHAN_IP, 0);
798 		emuxki_write(sc, i, EMU_CHAN_VTFT, 0xffff);
799 		emuxki_write(sc, i, EMU_CHAN_CVCF, 0xffff);
800 		emuxki_write(sc, i, EMU_CHAN_PTRX, 0);
801 		emuxki_write(sc, i, EMU_CHAN_CPF, 0);
802 		emuxki_write(sc, i, EMU_CHAN_CCR, 0);
803 		emuxki_write(sc, i, EMU_CHAN_PSST, 0);
804 		emuxki_write(sc, i, EMU_CHAN_DSL, 0x10);	/* Why 16 ? */
805 		emuxki_write(sc, i, EMU_CHAN_CCCA, 0);
806 		emuxki_write(sc, i, EMU_CHAN_Z1, 0);
807 		emuxki_write(sc, i, EMU_CHAN_Z2, 0);
808 		emuxki_write(sc, i, EMU_CHAN_FXRT, 0x32100000);
809 		emuxki_write(sc, i, EMU_CHAN_ATKHLDM, 0);
810 		emuxki_write(sc, i, EMU_CHAN_DCYSUSM, 0);
811 		emuxki_write(sc, i, EMU_CHAN_IFATN, 0xffff);
812 		emuxki_write(sc, i, EMU_CHAN_PEFE, 0);
813 		emuxki_write(sc, i, EMU_CHAN_FMMOD, 0);
814 		emuxki_write(sc, i, EMU_CHAN_TREMFRQ, 24);
815 		emuxki_write(sc, i, EMU_CHAN_FM2FRQ2, 24);
816 		emuxki_write(sc, i, EMU_CHAN_TEMPENV, 0);
817 
818 		/* these are last so OFF prevents writing */
819 		emuxki_write(sc, i, EMU_CHAN_LFOVAL2, 0);
820 		emuxki_write(sc, i, EMU_CHAN_LFOVAL1, 0);
821 		emuxki_write(sc, i, EMU_CHAN_ATKHLDV, 0);
822 		emuxki_write(sc, i, EMU_CHAN_ENVVOL, 0);
823 		emuxki_write(sc, i, EMU_CHAN_ENVVAL, 0);
824 	}
825 
826 	/* set digital outputs format */
827 	spcs = (EMU_SPCS_CLKACCY_1000PPM | EMU_SPCS_SAMPLERATE_48 |
828 	      EMU_SPCS_CHANNELNUM_LEFT | EMU_SPCS_SOURCENUM_UNSPEC |
829 		EMU_SPCS_GENERATIONSTATUS | 0x00001200 /* Cat code. */ |
830 		0x00000000 /* IEC-958 Mode */ | EMU_SPCS_EMPHASIS_NONE |
831 		EMU_SPCS_COPYRIGHT);
832 	emuxki_write(sc, 0, EMU_SPCS0, spcs);
833 	emuxki_write(sc, 0, EMU_SPCS1, spcs);
834 	emuxki_write(sc, 0, EMU_SPCS2, spcs);
835 
836 	if(sc->sc_type & EMUXKI_AUDIGY2) {
837 		emuxki_write(sc, 0, EMU_A2_SPDIF_SAMPLERATE, EMU_A2_SPDIF_UNKNOWN);
838 
839 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_A2_PTR, EMU_A2_SRCSEL);
840 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_A2_DATA,
841 			EMU_A2_SRCSEL_ENABLE_SPDIF | EMU_A2_SRCSEL_ENABLE_SRCMULTI);
842 
843 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_A2_PTR, EMU_A2_SRCMULTI);
844 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_A2_DATA, EMU_A2_SRCMULTI_ENABLE_INPUT);
845 	}
846 
847 
848 	/* Let's play with sound processor */
849 	emuxki_initfx(sc);
850 
851 	/* Here is our Page Table */
852 	if ((sc->ptb = dmamem_alloc(sc->sc_dmat,
853 	    EMU_MAXPTE * sizeof(u_int32_t),
854 	    EMU_DMA_ALIGN, EMU_DMAMEM_NSEG)) == NULL)
855 		return ENOMEM;
856 
857 	/* This is necessary unless you like Metallic noise... */
858 	if ((sc->silentpage = dmamem_alloc(sc->sc_dmat, EMU_PTESIZE,
859 	    EMU_DMA_ALIGN, EMU_DMAMEM_NSEG))==NULL){
860 		dmamem_free(sc->ptb);
861 		return ENOMEM;
862 	}
863 
864 	/* Zero out the silent page */
865 	/* This might not be always true, it might be 128 for 8bit channels */
866 	memset(KERNADDR(sc->silentpage), 0, DMASIZE(sc->silentpage));
867 
868 	/*
869 	 * Set all the PTB Entries to the silent page We shift the physical
870 	 * address by one and OR it with the page number. I don't know what
871 	 * the ORed index is for, might be a very useful unused feature...
872 	 */
873 	silentpage = DMAADDR(sc->silentpage) << 1;
874 	ptb = KERNADDR(sc->ptb);
875 	for (i = 0; i < EMU_MAXPTE; i++)
876 		ptb[i] = htole32(silentpage | i);
877 
878 	/* Write PTB address and set TCB to none */
879 	emuxki_write(sc, 0, EMU_PTB, DMAADDR(sc->ptb));
880 	emuxki_write(sc, 0, EMU_TCBS, 0);	/* This means 16K TCB */
881 	emuxki_write(sc, 0, EMU_TCB, 0);	/* No TCB use for now */
882 
883 	/*
884 	 * Set channels MAPs to the silent page.
885 	 * I don't know what MAPs are for.
886 	 */
887 	silentpage |= EMU_CHAN_MAP_PTI_MASK;
888 	for (i = 0; i < EMU_NUMCHAN; i++) {
889 		emuxki_write(sc, i, EMU_CHAN_MAPA, silentpage);
890 		emuxki_write(sc, i, EMU_CHAN_MAPB, silentpage);
891 		sc->channel[i] = NULL;
892 	}
893 
894 	/* Init voices list */
895 	LIST_INIT(&(sc->voices));
896 
897 	/* Timer is stopped */
898 	sc->timerstate &= ~EMU_TIMER_STATE_ENABLED;
899 	return 0;
900 }
901 
902 static void
903 emuxki_shutdown(struct emuxki_softc *sc)
904 {
905 	uint32_t i;
906 
907 	/* Disable any Channels interrupts */
908 	emuxki_write(sc, 0, EMU_CLIEL, 0);
909 	emuxki_write(sc, 0, EMU_CLIEH, 0);
910 	emuxki_write(sc, 0, EMU_SOLEL, 0);
911 	emuxki_write(sc, 0, EMU_SOLEH, 0);
912 
913 	/*
914 	 * Should do some voice(stream) stopping stuff here, that's what will
915 	 * stop and deallocate all channels.
916 	 */
917 
918 	/* Stop all channels */
919 	/* XXX This shouldn't be necessary, I'll remove once everything works */
920 	for (i = 0; i < EMU_NUMCHAN; i++)
921 		emuxki_write(sc, i, EMU_CHAN_DCYSUSV, 0);
922 	for (i = 0; i < EMU_NUMCHAN; i++) {
923 		emuxki_write(sc, i, EMU_CHAN_VTFT, 0);
924 		emuxki_write(sc, i, EMU_CHAN_CVCF, 0);
925 		emuxki_write(sc, i, EMU_CHAN_PTRX, 0);
926 		emuxki_write(sc, i, EMU_CHAN_CPF, 0);
927 	}
928 
929 	/*
930 	 * Deallocate Emu10k1 caches and recording buffers. Again it will be
931 	 * removed because it will be done in voice shutdown.
932 	 */
933 	emuxki_write(sc, 0, EMU_MICBS, EMU_RECBS_BUFSIZE_NONE);
934 	emuxki_write(sc, 0, EMU_MICBA, 0);
935 	emuxki_write(sc, 0, EMU_FXBS, EMU_RECBS_BUFSIZE_NONE);
936 	emuxki_write(sc, 0, EMU_FXBA, 0);
937 	if(sc->sc_type & EMUXKI_AUDIGY) {
938 		emuxki_write(sc, 0, EMU_A_FXWC1, 0);
939 		emuxki_write(sc, 0, EMU_A_FXWC2, 0);
940 	} else {
941 		emuxki_write(sc, 0, EMU_FXWC, 0);
942 	}
943 	emuxki_write(sc, 0, EMU_ADCBS, EMU_RECBS_BUFSIZE_NONE);
944 	emuxki_write(sc, 0, EMU_ADCBA, 0);
945 
946 	/*
947 	 * XXX I don't know yet how I will handle tank cache buffer,
948 	 * I don't even clearly  know what it is for.
949 	 */
950 	emuxki_write(sc, 0, EMU_TCB, 0);	/* 16K again */
951 	emuxki_write(sc, 0, EMU_TCBS, 0);
952 
953 	emuxki_write(sc, 0, EMU_DBG, 0x8000);	/* necessary ? */
954 
955 	dmamem_free(sc->silentpage);
956 	dmamem_free(sc->ptb);
957 }
958 
959 /* Emu10k1 Memory management */
960 
961 static struct emuxki_mem *
962 emuxki_mem_new(struct emuxki_softc *sc, int ptbidx, size_t size)
963 {
964 	struct emuxki_mem *mem;
965 
966 	mem = kmem_alloc(sizeof(*mem), KM_SLEEP);
967 	mem->ptbidx = ptbidx;
968 	if ((mem->dmamem = dmamem_alloc(sc->sc_dmat, size, EMU_DMA_ALIGN,
969 	    EMU_DMAMEM_NSEG)) == NULL) {
970 		kmem_free(mem, sizeof(*mem));
971 		return NULL;
972 	}
973 	return mem;
974 }
975 
976 static void
977 emuxki_mem_delete(struct emuxki_mem *mem, size_t size)
978 {
979 
980 	dmamem_free(mem->dmamem);
981 	kmem_free(mem, sizeof(*mem));
982 }
983 
984 static void *
985 emuxki_pmem_alloc(struct emuxki_softc *sc, size_t size)
986 {
987 	int i, j;
988 	size_t numblocks;
989 	struct emuxki_mem *mem;
990 	uint32_t *ptb, silentpage;
991 
992 	ptb = KERNADDR(sc->ptb);
993 	silentpage = DMAADDR(sc->silentpage) << 1;
994 	numblocks = size / EMU_PTESIZE;
995 	if (size % EMU_PTESIZE)
996 		numblocks++;
997 
998 	for (i = 0; i < EMU_MAXPTE; i++) {
999 		mutex_spin_enter(&sc->sc_intr_lock);
1000 		if ((le32toh(ptb[i]) & EMU_CHAN_MAP_PTE_MASK) == silentpage) {
1001 			/* We look for a free PTE */
1002 			for (j = 0; j < numblocks; j++)
1003 				if ((le32toh(ptb[i + j])
1004 				    & EMU_CHAN_MAP_PTE_MASK) != silentpage)
1005 					break;
1006 			if (j == numblocks) {
1007 				mutex_spin_exit(&sc->sc_intr_lock);
1008 				if ((mem = emuxki_mem_new(sc, i,
1009 						size)) == NULL) {
1010 					return NULL;
1011 				}
1012 				mutex_spin_enter(&sc->sc_intr_lock);
1013 				for (j = 0; j < numblocks; j++)
1014 					ptb[i + j] =
1015 					    htole32((((DMAADDR(mem->dmamem) +
1016 					    j * EMU_PTESIZE)) << 1) | (i + j));
1017 				LIST_INSERT_HEAD(&(sc->mem), mem, next);
1018 				mutex_spin_exit(&sc->sc_intr_lock);
1019 				return (KERNADDR(mem->dmamem));
1020 			} else
1021 				i += j;
1022 		}
1023 		mutex_spin_exit(&sc->sc_intr_lock);
1024 	}
1025 	return NULL;
1026 }
1027 
1028 static void *
1029 emuxki_rmem_alloc(struct emuxki_softc *sc, size_t size)
1030 {
1031 	struct emuxki_mem *mem;
1032 
1033 	mem = emuxki_mem_new(sc, EMU_RMEM, size);
1034 	if (mem == NULL)
1035 		return NULL;
1036 
1037 	mutex_spin_enter(&sc->sc_intr_lock);
1038 	LIST_INSERT_HEAD(&(sc->mem), mem, next);
1039 	mutex_spin_exit(&sc->sc_intr_lock);
1040 
1041 	return KERNADDR(mem->dmamem);
1042 }
1043 
1044 /*
1045  * emuxki_channel_* : Channel management functions
1046  * emuxki_chanparms_* : Channel parameters modification functions
1047  */
1048 
1049 /*
1050  * is splaudio necessary here, can the same voice be manipulated by two
1051  * different threads at a time ?
1052  */
1053 static void
1054 emuxki_chanparms_set_defaults(struct emuxki_channel *chan)
1055 {
1056 
1057 	chan->fxsend.a.level = chan->fxsend.b.level =
1058 	chan->fxsend.c.level = chan->fxsend.d.level =
1059 	/* for audigy */
1060 	chan->fxsend.e.level = chan->fxsend.f.level =
1061 	chan->fxsend.g.level = chan->fxsend.h.level =
1062 		chan->voice->sc->sc_type & EMUXKI_AUDIGY ?
1063 			0xc0 : 0xff;	/* not max */
1064 
1065 	chan->fxsend.a.dest = 0x0;
1066 	chan->fxsend.b.dest = 0x1;
1067 	chan->fxsend.c.dest = 0x2;
1068 	chan->fxsend.d.dest = 0x3;
1069 	/* for audigy */
1070 	chan->fxsend.e.dest = 0x4;
1071 	chan->fxsend.f.dest = 0x5;
1072 	chan->fxsend.g.dest = 0x6;
1073 	chan->fxsend.h.dest = 0x7;
1074 
1075 	chan->pitch.initial = 0x0000;	/* shouldn't it be 0xE000 ? */
1076 	chan->pitch.current = 0x0000;	/* should it be 0x0400 */
1077 	chan->pitch.target = 0x0000;	/* the unity pitch shift ? */
1078 	chan->pitch.envelope_amount = 0x00;	/* none */
1079 
1080 	chan->initial_attenuation = 0x00;	/* no attenuation */
1081 	chan->volume.current = 0x0000;	/* no volume */
1082 	chan->volume.target = 0xffff;
1083 	chan->volume.envelope.current_state = 0x8000;	/* 0 msec delay */
1084 	chan->volume.envelope.hold_time = 0x7f;	/* 0 msec */
1085 	chan->volume.envelope.attack_time = 0x7F;	/* 5.5msec */
1086 	chan->volume.envelope.sustain_level = 0x7F;	/* full  */
1087 	chan->volume.envelope.decay_time = 0x7F;	/* 22msec  */
1088 
1089 	chan->filter.initial_cutoff_frequency = 0xff;	/* no filter */
1090 	chan->filter.current_cutoff_frequency = 0xffff;	/* no filtering */
1091 	chan->filter.target_cutoff_frequency = 0xffff;	/* no filtering */
1092 	chan->filter.lowpass_resonance_height = 0x0;
1093 	chan->filter.interpolation_ROM = 0x1;	/* full band */
1094 	chan->filter.envelope_amount = 0x7f;	/* none */
1095 	chan->filter.LFO_modulation_depth = 0x00;	/* none */
1096 
1097 	chan->loop.start = 0x000000;
1098 	chan->loop.end = 0x000010;	/* Why ? */
1099 
1100 	chan->modulation.envelope.current_state = 0x8000;
1101 	chan->modulation.envelope.hold_time = 0x00;	/* 127 better ? */
1102 	chan->modulation.envelope.attack_time = 0x00;	/* infinite */
1103 	chan->modulation.envelope.sustain_level = 0x00;	/* off */
1104 	chan->modulation.envelope.decay_time = 0x7f;	/* 22 msec */
1105 	chan->modulation.LFO_state = 0x8000;
1106 
1107 	chan->vibrato_LFO.state = 0x8000;
1108 	chan->vibrato_LFO.modulation_depth = 0x00;	/* none */
1109 	chan->vibrato_LFO.vibrato_depth = 0x00;
1110 	chan->vibrato_LFO.frequency = 0x00;	/* Why set to 24 when
1111 						 * initialized ? */
1112 
1113 	chan->tremolo_depth = 0x00;
1114 }
1115 
1116 /* only call it at splaudio */
1117 static struct emuxki_channel *
1118 emuxki_channel_new(struct emuxki_voice *voice, u_int8_t num)
1119 {
1120 	struct emuxki_channel *chan;
1121 
1122 	chan = malloc(sizeof(struct emuxki_channel), M_DEVBUF, M_WAITOK);
1123 	if (chan == NULL)
1124 		return NULL;
1125 
1126 	chan->voice = voice;
1127 	chan->num = num;
1128 	emuxki_chanparms_set_defaults(chan);
1129 	chan->voice->sc->channel[num] = chan;
1130 	return chan;
1131 }
1132 
1133 /* only call it at splaudio */
1134 static void
1135 emuxki_channel_delete(struct emuxki_channel *chan)
1136 {
1137 
1138 	chan->voice->sc->channel[chan->num] = NULL;
1139 	free(chan, M_DEVBUF);
1140 }
1141 
1142 static void
1143 emuxki_channel_set_fxsend(struct emuxki_channel *chan,
1144     struct emuxki_chanparms_fxsend *fxsend)
1145 {
1146 	/* Could do a memcpy ...*/
1147 	chan->fxsend.a.level = fxsend->a.level;
1148 	chan->fxsend.b.level = fxsend->b.level;
1149 	chan->fxsend.c.level = fxsend->c.level;
1150 	chan->fxsend.d.level = fxsend->d.level;
1151 	chan->fxsend.a.dest = fxsend->a.dest;
1152 	chan->fxsend.b.dest = fxsend->b.dest;
1153 	chan->fxsend.c.dest = fxsend->c.dest;
1154 	chan->fxsend.d.dest = fxsend->d.dest;
1155 
1156 	/* for audigy */
1157 	chan->fxsend.e.level = fxsend->e.level;
1158 	chan->fxsend.f.level = fxsend->f.level;
1159 	chan->fxsend.g.level = fxsend->g.level;
1160 	chan->fxsend.h.level = fxsend->h.level;
1161 	chan->fxsend.e.dest = fxsend->e.dest;
1162 	chan->fxsend.f.dest = fxsend->f.dest;
1163 	chan->fxsend.g.dest = fxsend->g.dest;
1164 	chan->fxsend.h.dest = fxsend->h.dest;
1165 }
1166 
1167 static void
1168 emuxki_channel_set_srate(struct emuxki_channel *chan, uint32_t srate)
1169 {
1170 
1171 	chan->pitch.target = (srate << 8) / 375;
1172 	chan->pitch.target = (chan->pitch.target >> 1) +
1173 		(chan->pitch.target & 1);
1174 	chan->pitch.target &= 0xffff;
1175 	chan->pitch.current = chan->pitch.target;
1176 	chan->pitch.initial =
1177 		(emuxki_rate_to_pitch(srate) >> 8) & EMU_CHAN_IP_MASK;
1178 }
1179 
1180 /* voice params must be set before calling this */
1181 static void
1182 emuxki_channel_set_bufparms(struct emuxki_channel *chan,
1183     uint32_t start, uint32_t end)
1184 {
1185 
1186 	chan->loop.start = start & EMU_CHAN_PSST_LOOPSTARTADDR_MASK;
1187 	chan->loop.end = end & EMU_CHAN_DSL_LOOPENDADDR_MASK;
1188 }
1189 
1190 static void
1191 emuxki_channel_commit_fx(struct emuxki_channel *chan)
1192 {
1193 	struct emuxki_softc *sc;
1194 	u_int8_t chano;
1195 
1196 	sc = chan->voice->sc;
1197 	chano = chan->num;
1198 	if(sc->sc_type & EMUXKI_AUDIGY) {
1199 		emuxki_write(sc, chano, EMU_A_CHAN_FXRT1,
1200 			      (chan->fxsend.d.dest << 24) |
1201 			      (chan->fxsend.c.dest << 16) |
1202 			      (chan->fxsend.b.dest << 8) |
1203 			      (chan->fxsend.a.dest));
1204 		emuxki_write(sc, chano, EMU_A_CHAN_FXRT2,
1205 			      (chan->fxsend.h.dest << 24) |
1206 			      (chan->fxsend.g.dest << 16) |
1207 			      (chan->fxsend.f.dest << 8) |
1208 			      (chan->fxsend.e.dest));
1209 		emuxki_write(sc, chano, EMU_A_CHAN_SENDAMOUNTS,
1210 			      (chan->fxsend.e.level << 24) |
1211 			      (chan->fxsend.f.level << 16) |
1212 			      (chan->fxsend.g.level << 8) |
1213 			      (chan->fxsend.h.level));
1214 	} else {
1215 		emuxki_write(sc, chano, EMU_CHAN_FXRT,
1216 			      (chan->fxsend.d.dest << 28) |
1217 			      (chan->fxsend.c.dest << 24) |
1218 			      (chan->fxsend.b.dest << 20) |
1219 			      (chan->fxsend.a.dest << 16));
1220 	}
1221 
1222 	emuxki_write(sc, chano, 0x10000000 | EMU_CHAN_PTRX,
1223 		      (chan->fxsend.a.level << 8) | chan->fxsend.b.level);
1224 	emuxki_write(sc, chano, EMU_CHAN_DSL,
1225 		      (chan->fxsend.d.level << 24) | chan->loop.end);
1226 	emuxki_write(sc, chano, EMU_CHAN_PSST,
1227 		      (chan->fxsend.c.level << 24) | chan->loop.start);
1228 }
1229 
1230 static void
1231 emuxki_channel_commit_parms(struct emuxki_channel *chan)
1232 {
1233 	struct emuxki_voice *voice;
1234 	struct emuxki_softc *sc;
1235 	uint32_t start, mapval;
1236 	uint8_t chano;
1237 
1238 	voice = chan->voice;
1239 	sc = voice->sc;
1240 	chano = chan->num;
1241 	start = chan->loop.start +
1242 		(voice->stereo ? 28 : 30) * (voice->b16 + 1);
1243 	mapval = DMAADDR(sc->silentpage) << 1 | EMU_CHAN_MAP_PTI_MASK;
1244 
1245 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1246 	emuxki_write(sc, chano, EMU_CHAN_CPF_STEREO, voice->stereo);
1247 
1248 	emuxki_channel_commit_fx(chan);
1249 
1250 	emuxki_write(sc, chano, EMU_CHAN_CCCA,
1251 		(chan->filter.lowpass_resonance_height << 28) |
1252 		(chan->filter.interpolation_ROM << 25) |
1253 		(voice->b16 ? 0 : EMU_CHAN_CCCA_8BITSELECT) | start);
1254 	emuxki_write(sc, chano, EMU_CHAN_Z1, 0);
1255 	emuxki_write(sc, chano, EMU_CHAN_Z2, 0);
1256 	emuxki_write(sc, chano, EMU_CHAN_MAPA, mapval);
1257 	emuxki_write(sc, chano, EMU_CHAN_MAPB, mapval);
1258 	emuxki_write(sc, chano, EMU_CHAN_CVCF_CURRFILTER,
1259 		chan->filter.current_cutoff_frequency);
1260 	emuxki_write(sc, chano, EMU_CHAN_VTFT_FILTERTARGET,
1261 		chan->filter.target_cutoff_frequency);
1262 	emuxki_write(sc, chano, EMU_CHAN_ATKHLDM,
1263 		(chan->modulation.envelope.hold_time << 8) |
1264 		chan->modulation.envelope.attack_time);
1265 	emuxki_write(sc, chano, EMU_CHAN_DCYSUSM,
1266 		(chan->modulation.envelope.sustain_level << 8) |
1267 		chan->modulation.envelope.decay_time);
1268 	emuxki_write(sc, chano, EMU_CHAN_LFOVAL1,
1269 		chan->modulation.LFO_state);
1270 	emuxki_write(sc, chano, EMU_CHAN_LFOVAL2,
1271 		chan->vibrato_LFO.state);
1272 	emuxki_write(sc, chano, EMU_CHAN_FMMOD,
1273 		(chan->vibrato_LFO.modulation_depth << 8) |
1274 		chan->filter.LFO_modulation_depth);
1275 	emuxki_write(sc, chano, EMU_CHAN_TREMFRQ,
1276 		(chan->tremolo_depth << 8));
1277 	emuxki_write(sc, chano, EMU_CHAN_FM2FRQ2,
1278 		(chan->vibrato_LFO.vibrato_depth << 8) |
1279 		chan->vibrato_LFO.frequency);
1280 	emuxki_write(sc, chano, EMU_CHAN_ENVVAL,
1281 		chan->modulation.envelope.current_state);
1282 	emuxki_write(sc, chano, EMU_CHAN_ATKHLDV,
1283 		(chan->volume.envelope.hold_time << 8) |
1284 		chan->volume.envelope.attack_time);
1285 	emuxki_write(sc, chano, EMU_CHAN_ENVVOL,
1286 		chan->volume.envelope.current_state);
1287 	emuxki_write(sc, chano, EMU_CHAN_PEFE,
1288 		(chan->pitch.envelope_amount << 8) |
1289 		chan->filter.envelope_amount);
1290 }
1291 
1292 static void
1293 emuxki_channel_start(struct emuxki_channel *chan)
1294 {
1295 	struct emuxki_voice *voice;
1296 	struct emuxki_softc *sc;
1297 	u_int8_t cache_sample, cache_invalid_size, chano;
1298 	u_int32_t sample;
1299 
1300 	voice = chan->voice;
1301 	sc = voice->sc;
1302 	chano = chan->num;
1303 	cache_sample = voice->stereo ? 4 : 2;
1304 	sample = voice->b16 ? 0x00000000 : 0x80808080;
1305 	cache_invalid_size = (voice->stereo ? 28 : 30) * (voice->b16 + 1);
1306 
1307 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1308 	while (cache_sample--) {
1309 		emuxki_write(sc, chano, EMU_CHAN_CD0 + cache_sample,
1310 			sample);
1311 	}
1312 	emuxki_write(sc, chano, EMU_CHAN_CCR_CACHEINVALIDSIZE, 0);
1313 	emuxki_write(sc, chano, EMU_CHAN_CCR_READADDRESS, 64);
1314 	emuxki_write(sc, chano, EMU_CHAN_CCR_CACHEINVALIDSIZE,
1315 		cache_invalid_size);
1316 	emuxki_write(sc, chano, EMU_CHAN_IFATN,
1317 		(chan->filter.target_cutoff_frequency << 8) |
1318 		chan->initial_attenuation);
1319 	emuxki_write(sc, chano, EMU_CHAN_VTFT_VOLUMETARGET,
1320 		chan->volume.target);
1321 	emuxki_write(sc, chano, EMU_CHAN_CVCF_CURRVOL,
1322 		chan->volume.current);
1323 	emuxki_write(sc, 0,
1324 		EMU_MKSUBREG(1, chano, EMU_SOLEL + (chano >> 5)),
1325 		0);	/* Clear stop on loop */
1326 	emuxki_write(sc, 0,
1327 		EMU_MKSUBREG(1, chano, EMU_CLIEL + (chano >> 5)),
1328 		0);	/* Clear loop interrupt */
1329 	emuxki_write(sc, chano, EMU_CHAN_DCYSUSV,
1330 		(chan->volume.envelope.sustain_level << 8) |
1331 		chan->volume.envelope.decay_time);
1332 	emuxki_write(sc, chano, EMU_CHAN_PTRX_PITCHTARGET,
1333 		chan->pitch.target);
1334 	emuxki_write(sc, chano, EMU_CHAN_CPF_PITCH,
1335 		chan->pitch.current);
1336 	emuxki_write(sc, chano, EMU_CHAN_IP, chan->pitch.initial);
1337 }
1338 
1339 static void
1340 emuxki_channel_stop(struct emuxki_channel *chan)
1341 {
1342 	struct emuxki_softc *sc;
1343 	u_int8_t chano;
1344 
1345 	sc = chan->voice->sc;
1346 	chano = chan->num;
1347 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1348 	emuxki_write(sc, chano, EMU_CHAN_PTRX_PITCHTARGET, 0);
1349 	emuxki_write(sc, chano, EMU_CHAN_CPF_PITCH, 0);
1350 	emuxki_write(sc, chano, EMU_CHAN_IFATN_ATTENUATION, 0xff);
1351 	emuxki_write(sc, chano, EMU_CHAN_VTFT_VOLUMETARGET, 0);
1352 	emuxki_write(sc, chano, EMU_CHAN_CVCF_CURRVOL, 0);
1353 	emuxki_write(sc, chano, EMU_CHAN_IP, 0);
1354 }
1355 
1356 /*
1357  * Voices management
1358  * emuxki_voice_dataloc : use(play or rec) independent dataloc union helpers
1359  * emuxki_voice_channel_* : play part of dataloc union helpers
1360  * emuxki_voice_recsrc_* : rec part of dataloc union helpers
1361  */
1362 
1363 /* Allocate channels for voice in case of play voice */
1364 static int
1365 emuxki_voice_channel_create(struct emuxki_voice *voice)
1366 {
1367 	struct emuxki_channel **channel;
1368 	uint8_t i, stereo;
1369 
1370 	channel = voice->sc->channel;
1371 	stereo = voice->stereo;
1372 	for (i = 0; i < EMU_NUMCHAN - stereo; i += stereo + 1) {
1373 		if ((stereo && (channel[i + 1] != NULL)) ||
1374 		    (channel[i] != NULL))	/* Looking for free channels */
1375 			continue;
1376 
1377 		if (stereo) {
1378 			voice->dataloc.chan[1] =
1379 				emuxki_channel_new(voice, i + 1);
1380 			if (voice->dataloc.chan[1] == NULL)
1381 				return ENOMEM;
1382 		}
1383 		voice->dataloc.chan[0] = emuxki_channel_new(voice, i);
1384 		if (voice->dataloc.chan[0] == NULL) {
1385 			if (stereo) {
1386 				emuxki_channel_delete(voice->dataloc.chan[1]);
1387 				voice->dataloc.chan[1] = NULL;
1388 			}
1389 			return ENOMEM;
1390 		}
1391 		return 0;
1392 	}
1393 	return EAGAIN;
1394 }
1395 
1396 /* When calling this function we assume no one can access the voice */
1397 static void
1398 emuxki_voice_channel_destroy(struct emuxki_voice *voice)
1399 {
1400 
1401 	emuxki_channel_delete(voice->dataloc.chan[0]);
1402 	voice->dataloc.chan[0] = NULL;
1403 	if (voice->stereo)
1404 		emuxki_channel_delete(voice->dataloc.chan[1]);
1405 	voice->dataloc.chan[1] = NULL;
1406 }
1407 
1408 /*
1409  * Will come back when used in voice_dataloc_create
1410  */
1411 static int
1412 emuxki_recsrc_reserve(struct emuxki_voice *voice, emuxki_recsrc_t source)
1413 {
1414 
1415 	if (source >= EMU_NUMRECSRCS) {
1416 #ifdef EMUXKI_DEBUG
1417 		printf("Tried to reserve invalid source: %d\n", source);
1418 #endif
1419 		return EINVAL;
1420 	}
1421 	if (voice->sc->recsrc[source] == voice)
1422 		return 0;			/* XXX */
1423 	if (voice->sc->recsrc[source] != NULL)
1424 		return EBUSY;
1425 	voice->sc->recsrc[source] = voice;
1426 	return 0;
1427 }
1428 
1429 /* When calling this function we assume the voice is stopped */
1430 static void
1431 emuxki_voice_recsrc_release(struct emuxki_softc *sc, emuxki_recsrc_t source)
1432 {
1433 
1434 	sc->recsrc[source] = NULL;
1435 }
1436 
1437 static int
1438 emuxki_voice_dataloc_create(struct emuxki_voice *voice)
1439 {
1440 	int error;
1441 
1442 	if (voice->use & EMU_VOICE_USE_PLAY) {
1443 		if ((error = emuxki_voice_channel_create(voice)))
1444 			return error;
1445 	} else {
1446 		if ((error =
1447 		    emuxki_recsrc_reserve(voice, voice->dataloc.source)))
1448 			return error;
1449 	}
1450 	return 0;
1451 }
1452 
1453 static void
1454 emuxki_voice_dataloc_destroy(struct emuxki_voice *voice)
1455 {
1456 
1457 	if (voice->use & EMU_VOICE_USE_PLAY) {
1458 		if (voice->dataloc.chan[0] != NULL)
1459 			emuxki_voice_channel_destroy(voice);
1460 	} else {
1461 		if (voice->dataloc.source != EMU_RECSRC_NOTSET) {
1462 			emuxki_voice_recsrc_release(voice->sc,
1463 						     voice->dataloc.source);
1464 			voice->dataloc.source = EMU_RECSRC_NOTSET;
1465 		}
1466 	}
1467 }
1468 
1469 static struct emuxki_voice *
1470 emuxki_voice_new(struct emuxki_softc *sc, uint8_t use)
1471 {
1472 	struct emuxki_voice *voice;
1473 
1474 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1475 
1476 	voice = sc->lvoice;
1477 	sc->lvoice = NULL;
1478 
1479 	if (!voice) {
1480 		mutex_exit(&sc->sc_intr_lock);
1481 		voice = kmem_alloc(sizeof(*voice), KM_SLEEP);
1482 		mutex_enter(&sc->sc_intr_lock);
1483 	} else if (voice->use != use) {
1484 		mutex_exit(&sc->sc_intr_lock);
1485 		emuxki_voice_dataloc_destroy(voice);
1486 		mutex_enter(&sc->sc_intr_lock);
1487 	} else
1488 		goto skip_initialize;
1489 
1490 	voice->sc = sc;
1491 	voice->state = !EMU_VOICE_STATE_STARTED;
1492 	voice->stereo = EMU_VOICE_STEREO_NOTSET;
1493 	voice->b16 = 0;
1494 	voice->sample_rate = 0;
1495 	if (use & EMU_VOICE_USE_PLAY)
1496 		voice->dataloc.chan[0] = voice->dataloc.chan[1] = NULL;
1497 	else
1498 		voice->dataloc.source = EMU_RECSRC_NOTSET;
1499 	voice->buffer = NULL;
1500 	voice->blksize = 0;
1501 	voice->trigblk = 0;
1502 	voice->blkmod = 0;
1503 	voice->inth = NULL;
1504 	voice->inthparam = NULL;
1505 	voice->use = use;
1506 
1507 skip_initialize:
1508 	LIST_INSERT_HEAD((&sc->voices), voice, next);
1509 
1510 	return voice;
1511 }
1512 
1513 static void
1514 emuxki_voice_delete(struct emuxki_voice *voice)
1515 {
1516 	struct emuxki_softc *sc;
1517 	struct emuxki_voice *lvoice;
1518 
1519 	sc = voice->sc;
1520 	if (voice->state & EMU_VOICE_STATE_STARTED)
1521 		emuxki_voice_halt(voice);
1522 
1523 	LIST_REMOVE(voice, next);
1524 	lvoice = sc->lvoice;
1525 	sc->lvoice = voice;
1526 
1527 	if (lvoice) {
1528 		mutex_exit(&sc->sc_lock);
1529 		emuxki_voice_dataloc_destroy(lvoice);
1530 		kmem_free(lvoice, sizeof(*lvoice));
1531 		mutex_enter(&sc->sc_lock);
1532 	}
1533 }
1534 
1535 static int
1536 emuxki_voice_set_stereo(struct emuxki_softc *sc,
1537     			struct emuxki_voice *voice, uint8_t stereo)
1538 {
1539 	int error;
1540 	emuxki_recsrc_t source;
1541 	struct emuxki_chanparms_fxsend fxsend;
1542 
1543 	source = 0;		/* XXX: gcc */
1544 	if (! (voice->use & EMU_VOICE_USE_PLAY))
1545 		source = voice->dataloc.source;
1546 	mutex_exit(&sc->sc_lock);
1547 	emuxki_voice_dataloc_destroy(voice);
1548 	if (! (voice->use & EMU_VOICE_USE_PLAY))
1549 		voice->dataloc.source = source;
1550 	voice->stereo = stereo;
1551 	error = emuxki_voice_dataloc_create(voice);
1552 	mutex_enter(&sc->sc_lock);
1553 	if (error)
1554 		return error;
1555 	if (voice->use & EMU_VOICE_USE_PLAY) {
1556 		fxsend.a.dest = 0x0;
1557 		fxsend.b.dest = 0x1;
1558 		fxsend.c.dest = 0x2;
1559 		fxsend.d.dest = 0x3;
1560 		/* for audigy */
1561 		fxsend.e.dest = 0x4;
1562 		fxsend.f.dest = 0x5;
1563 		fxsend.g.dest = 0x6;
1564 		fxsend.h.dest = 0x7;
1565 		if (voice->stereo) {
1566 			fxsend.a.level = fxsend.c.level = 0xc0;
1567 			fxsend.b.level = fxsend.d.level = 0x00;
1568 			fxsend.e.level = fxsend.g.level = 0xc0;
1569 			fxsend.f.level = fxsend.h.level = 0x00;
1570 			emuxki_channel_set_fxsend(voice->dataloc.chan[0],
1571 						   &fxsend);
1572 			fxsend.a.level = fxsend.c.level = 0x00;
1573 			fxsend.b.level = fxsend.d.level = 0xc0;
1574 			fxsend.e.level = fxsend.g.level = 0x00;
1575 			fxsend.f.level = fxsend.h.level = 0xc0;
1576 			emuxki_channel_set_fxsend(voice->dataloc.chan[1],
1577 						   &fxsend);
1578 		} /* No else : default is good for mono */
1579 	}
1580 	return 0;
1581 }
1582 
1583 static int
1584 emuxki_voice_set_srate(struct emuxki_voice *voice, uint32_t srate)
1585 {
1586 
1587 	if (voice->use & EMU_VOICE_USE_PLAY) {
1588 		if ((srate < 4000) || (srate > 48000))
1589 			return EINVAL;
1590 		voice->sample_rate = srate;
1591 		emuxki_channel_set_srate(voice->dataloc.chan[0], srate);
1592 		if (voice->stereo)
1593 			emuxki_channel_set_srate(voice->dataloc.chan[1],
1594 						  srate);
1595 	} else {
1596 		if ((srate < 8000) || (srate > 48000))
1597 			return EINVAL;
1598 		voice->sample_rate = srate;
1599 		if (emuxki_voice_adc_rate(voice) < 0) {
1600 			voice->sample_rate = 0;
1601 			return EINVAL;
1602 		}
1603 	}
1604 	return 0;
1605 }
1606 
1607 static int
1608 emuxki_voice_set_audioparms(struct emuxki_softc *sc,
1609     struct emuxki_voice *voice, uint8_t stereo, uint8_t b16, uint32_t srate)
1610 {
1611 	int error;
1612 
1613 	if (voice->stereo == stereo && voice->b16 == b16 &&
1614 	    voice->sample_rate == srate)
1615 		return 0;
1616 
1617 #ifdef EMUXKI_DEBUG
1618 	printf("Setting %s voice params : %s, %u bits, %u Hz\n",
1619 	       (voice->use & EMU_VOICE_USE_PLAY) ? "play" : "record",
1620 	       stereo ? "stereo" : "mono", (b16 + 1) * 8, srate);
1621 #endif
1622 	error = 0;
1623 	if (voice->stereo != stereo) {
1624 		if ((error = emuxki_voice_set_stereo(sc, voice, stereo)))
1625 			return error;
1626 	 }
1627 	voice->b16 = b16;
1628 	if (voice->sample_rate != srate)
1629 		error = emuxki_voice_set_srate(voice, srate);
1630 	return error;
1631 }
1632 
1633 /* voice audio parms (see just before) must be set prior to this */
1634 static int
1635 emuxki_voice_set_bufparms(struct emuxki_voice *voice, void *ptr,
1636     uint32_t bufsize, uint16_t blksize)
1637 {
1638 	struct emuxki_mem *mem;
1639 	struct emuxki_channel **chan;
1640 	uint32_t start, end;
1641 	uint8_t sample_size;
1642 	int idx;
1643 	int error;
1644 
1645 	error = EFAULT;
1646 	LIST_FOREACH(mem, &voice->sc->mem, next) {
1647 		if (KERNADDR(mem->dmamem) != ptr)
1648 			continue;
1649 
1650 		voice->buffer = mem;
1651 		sample_size = (voice->b16 + 1) * (voice->stereo + 1);
1652 		voice->trigblk = 0;	/* This shouldn't be needed */
1653 		voice->blkmod = bufsize / blksize;
1654 		if (bufsize % blksize)	  /* This should not happen */
1655 			voice->blkmod++;
1656 		error = 0;
1657 
1658 		if (voice->use & EMU_VOICE_USE_PLAY) {
1659 			voice->blksize = blksize / sample_size;
1660 			chan = voice->dataloc.chan;
1661 			start = mem->ptbidx << 12;
1662 			end = start + bufsize / sample_size;
1663 			emuxki_channel_set_bufparms(chan[0],
1664 						     start, end);
1665 			if (voice->stereo)
1666 				emuxki_channel_set_bufparms(chan[1],
1667 				     start, end);
1668 			voice->timerate = (uint32_t) 48000 *
1669 			    voice->blksize / voice->sample_rate;
1670 			if (voice->timerate < 5)
1671 				error = EINVAL;
1672 		} else {
1673 			voice->blksize = blksize;
1674 			for(idx = sizeof(emuxki_recbuf_sz) /
1675 			    sizeof(emuxki_recbuf_sz[0]); --idx >= 0;)
1676 				if (emuxki_recbuf_sz[idx] == bufsize)
1677 					break;
1678 			if (idx < 0) {
1679 #ifdef EMUXKI_DEBUG
1680 				printf("Invalid bufsize: %d\n", bufsize);
1681 #endif
1682 				return EINVAL;
1683 			}
1684 			emuxki_write(voice->sc, 0,
1685 			    emuxki_recsrc_szreg[voice->dataloc.source], idx);
1686 			emuxki_write(voice->sc, 0,
1687 			    emuxki_recsrc_bufaddrreg[voice->dataloc.source],
1688 			    DMAADDR(mem->dmamem));
1689 
1690 			/* Use timer to emulate DMA completion interrupt */
1691 			voice->timerate = (u_int32_t) 48000 * blksize /
1692 			    (voice->sample_rate * sample_size);
1693 			if (voice->timerate < 5) {
1694 #ifdef EMUXKI_DEBUG
1695 				printf("Invalid timerate: %d, blksize %d\n",
1696 				    voice->timerate, blksize);
1697 #endif
1698 				error = EINVAL;
1699 			}
1700 		}
1701 
1702 		break;
1703 	}
1704 
1705 	return error;
1706 }
1707 
1708 static void
1709 emuxki_voice_commit_parms(struct emuxki_voice *voice)
1710 {
1711 	if (voice->use & EMU_VOICE_USE_PLAY) {
1712 		emuxki_channel_commit_parms(voice->dataloc.chan[0]);
1713 		if (voice->stereo)
1714 			emuxki_channel_commit_parms(voice->dataloc.chan[1]);
1715 	}
1716 }
1717 
1718 static uint32_t
1719 emuxki_voice_curaddr(struct emuxki_voice *voice)
1720 {
1721 	int idxreg;
1722 	int rv;
1723 
1724 	/* XXX different semantics in these cases */
1725 	if (voice->use & EMU_VOICE_USE_PLAY) {
1726 		/* returns number of samples (an l/r pair counts 1) */
1727 		rv = emuxki_read(voice->sc,
1728 		    voice->dataloc.chan[0]->num, EMU_CHAN_CCCA_CURRADDR) -
1729 		    voice->dataloc.chan[0]->loop.start;
1730 	} else {
1731 		idxreg = 0;
1732 		/* returns number of bytes */
1733 		switch (voice->dataloc.source) {
1734 			case EMU_RECSRC_MIC:
1735 				idxreg = (voice->sc->sc_type & EMUXKI_AUDIGY) ?
1736 					EMU_A_MICIDX : EMU_MICIDX;
1737 				break;
1738 			case EMU_RECSRC_ADC:
1739 				idxreg = (voice->sc->sc_type & EMUXKI_AUDIGY) ?
1740 					EMU_A_ADCIDX : EMU_ADCIDX;
1741 				break;
1742 			case EMU_RECSRC_FX:
1743 				idxreg = EMU_FXIDX;
1744 				break;
1745 			default:
1746 #ifdef EMUXKI_DEBUG
1747 				printf("emu: bad recording source!\n");
1748 #endif
1749 				break;
1750 		}
1751 		rv = emuxki_read(voice->sc, 0, EMU_RECIDX(idxreg)
1752 				& EMU_RECIDX_MASK);
1753 	}
1754 	return rv;
1755 }
1756 
1757 static void
1758 emuxki_resched_timer(struct emuxki_softc *sc)
1759 {
1760 	struct emuxki_voice *voice;
1761 	uint16_t timerate;
1762 	uint8_t active;
1763 
1764 	timerate = 1024;
1765 	active = 0;
1766 	KASSERT(mutex_owned(&sc->sc_intr_lock));
1767 	LIST_FOREACH(voice, &sc->voices, next) {
1768 		if ((voice->state & EMU_VOICE_STATE_STARTED) == 0)
1769 			continue;
1770 		active = 1;
1771 		if (voice->timerate < timerate)
1772 			timerate = voice->timerate;
1773 	}
1774 
1775 	if (timerate & ~EMU_TIMER_RATE_MASK)
1776 		timerate = 0;
1777 	bus_space_write_2(sc->sc_iot, sc->sc_ioh, EMU_TIMER, timerate);
1778 	if (!active && (sc->timerstate & EMU_TIMER_STATE_ENABLED)) {
1779 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_INTE,
1780 			bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_INTE) &
1781 			~EMU_INTE_INTERTIMERENB);
1782 		sc->timerstate &= ~EMU_TIMER_STATE_ENABLED;
1783 	} else if (active && !(sc->timerstate & EMU_TIMER_STATE_ENABLED)) {
1784 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_INTE,
1785 			bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_INTE) |
1786 			EMU_INTE_INTERTIMERENB);
1787 		sc->timerstate |= EMU_TIMER_STATE_ENABLED;
1788 	}
1789 }
1790 
1791 static int
1792 emuxki_voice_adc_rate(struct emuxki_voice *voice)
1793 {
1794 
1795 	switch(voice->sample_rate) {
1796 		case 48000:
1797 			return EMU_ADCCR_SAMPLERATE_48;
1798 			break;
1799 		case 44100:
1800 			return EMU_ADCCR_SAMPLERATE_44;
1801 			break;
1802 		case 32000:
1803 			return EMU_ADCCR_SAMPLERATE_32;
1804 			break;
1805 		case 24000:
1806 			return EMU_ADCCR_SAMPLERATE_24;
1807 			break;
1808 		case 22050:
1809 			return EMU_ADCCR_SAMPLERATE_22;
1810 			break;
1811 		case 16000:
1812 			return EMU_ADCCR_SAMPLERATE_16;
1813 			break;
1814 		case 12000:
1815 			if(voice->sc->sc_type & EMUXKI_AUDIGY)
1816 				return EMU_A_ADCCR_SAMPLERATE_12;
1817 			else {
1818 #ifdef EMUXKI_DEBUG
1819 				printf("recording sample_rate not supported : %u\n", voice->sample_rate);
1820 #endif
1821 				return -1;
1822 			}
1823 			break;
1824 		case 11000:
1825 			if(voice->sc->sc_type & EMUXKI_AUDIGY)
1826 				return EMU_A_ADCCR_SAMPLERATE_11;
1827 			else
1828 				return EMU_ADCCR_SAMPLERATE_11;
1829 			break;
1830 		case 8000:
1831 			if(voice->sc->sc_type & EMUXKI_AUDIGY)
1832 				return EMU_A_ADCCR_SAMPLERATE_8;
1833 			else
1834 				return EMU_ADCCR_SAMPLERATE_8;
1835 			break;
1836 		default:
1837 #ifdef EMUXKI_DEBUG
1838 				printf("recording sample_rate not supported : %u\n", voice->sample_rate);
1839 #endif
1840 				return -1;
1841 	}
1842 	return -1;		/* shouldn't get here */
1843 }
1844 
1845 
1846 static void
1847 emuxki_voice_start(struct emuxki_voice *voice,
1848     void (*inth) (void *), void *inthparam)
1849 {
1850 	uint32_t val;
1851 
1852 	voice->inth = inth;
1853 	voice->inthparam = inthparam;
1854 	if (voice->use & EMU_VOICE_USE_PLAY) {
1855 		voice->trigblk = 1;
1856 		emuxki_channel_start(voice->dataloc.chan[0]);
1857 		if (voice->stereo)
1858 			emuxki_channel_start(voice->dataloc.chan[1]);
1859 	} else {
1860 		voice->trigblk = 1;
1861 		switch (voice->dataloc.source) {
1862 		case EMU_RECSRC_ADC:
1863 			/* XXX need to program DSP to output L+R
1864 			 * XXX in monaural case? */
1865 			if (voice->sc->sc_type & EMUXKI_AUDIGY) {
1866 				val = EMU_A_ADCCR_LCHANENABLE;
1867 				if (voice->stereo)
1868 					val |= EMU_A_ADCCR_RCHANENABLE;
1869 			} else {
1870 				val = EMU_ADCCR_LCHANENABLE;
1871 				if (voice->stereo)
1872 					val |= EMU_ADCCR_RCHANENABLE;
1873 			}
1874 			val |= emuxki_voice_adc_rate(voice);
1875 			emuxki_write(voice->sc, 0, EMU_ADCCR, 0);
1876 			emuxki_write(voice->sc, 0, EMU_ADCCR, val);
1877 			break;
1878 		case EMU_RECSRC_MIC:
1879 		case EMU_RECSRC_FX:
1880 			printf("unimplemented\n");
1881 			break;
1882 		case EMU_RECSRC_NOTSET:
1883 		default:
1884 			printf("Bad dataloc.source %d\n",
1885 			    voice->dataloc.source);
1886 			break;
1887 		}
1888 #if 0
1889 		switch (voice->dataloc.source) {
1890 		case EMU_RECSRC_ADC:
1891 		case EMU_RECSRC_FX:
1892 		case EMU_RECSRC_MIC:
1893 			/* DMA completion interrupt is useless; use timer */
1894 			KASSERT(mutex_owned(&sc->sc_intr_lock));
1895 			val = emu_rd(sc, INTE, 4);
1896 			val |= emuxki_recsrc_intrmasks[voice->dataloc.source];
1897 			emu_wr(sc, INTE, val, 4);
1898 			break;
1899 		default:
1900 			break;
1901 		}
1902 #endif
1903 	}
1904 	voice->state |= EMU_VOICE_STATE_STARTED;
1905 	emuxki_resched_timer(voice->sc);
1906 }
1907 
1908 static void
1909 emuxki_voice_halt(struct emuxki_voice *voice)
1910 {
1911 
1912 	if (voice->use & EMU_VOICE_USE_PLAY) {
1913 		emuxki_channel_stop(voice->dataloc.chan[0]);
1914 		if (voice->stereo)
1915 			emuxki_channel_stop(voice->dataloc.chan[1]);
1916 	} else {
1917 		switch (voice->dataloc.source) {
1918 		case EMU_RECSRC_ADC:
1919 			emuxki_write(voice->sc, 0, EMU_ADCCR, 0);
1920 			break;
1921 		case EMU_RECSRC_FX:
1922 		case EMU_RECSRC_MIC:
1923 			printf("unimplemented\n");
1924 			break;
1925 		default:
1926 		case EMU_RECSRC_NOTSET:
1927 			printf("Bad dataloc.source %d\n",
1928 			    voice->dataloc.source);
1929 			break;
1930 		}
1931 
1932 		switch (voice->dataloc.source) {
1933 		case EMU_RECSRC_ADC:
1934 		case EMU_RECSRC_FX:
1935 		case EMU_RECSRC_MIC:
1936 			/* This should reset buffer pointer */
1937 			emuxki_write(voice->sc, 0,
1938 			    emuxki_recsrc_szreg[voice->dataloc.source],
1939 			    EMU_RECBS_BUFSIZE_NONE);
1940 #if 0
1941 			KASSERT(mutex_owned(&sc->sc_intr_lock));
1942 			val = emu_rd(sc, INTE, 4);
1943 			val &= ~emuxki_recsrc_intrmasks[voice->dataloc.source];
1944 			emu_wr(sc, INTE, val, 4);
1945 #endif
1946 			break;
1947 		default:
1948 			break;
1949 		}
1950 	}
1951 	voice->state &= ~EMU_VOICE_STATE_STARTED;
1952 	emuxki_resched_timer(voice->sc);
1953 }
1954 
1955 /*
1956  * The interrupt handler
1957  */
1958 static int
1959 emuxki_intr(void *arg)
1960 {
1961 	struct emuxki_softc *sc;
1962 	struct emuxki_voice *voice;
1963 	uint32_t ipr, curblk;
1964 	int claim;
1965 
1966 	sc = arg;
1967 	claim = 0;
1968 
1969 	mutex_spin_enter(&sc->sc_intr_lock);
1970 
1971 	while ((ipr = bus_space_read_4(sc->sc_iot, sc->sc_ioh, EMU_IPR))) {
1972 		if (ipr & EMU_IPR_INTERVALTIMER) {
1973 			LIST_FOREACH(voice, &sc->voices, next) {
1974 				if ((voice->state &
1975 				      EMU_VOICE_STATE_STARTED) == 0)
1976 					continue;
1977 
1978 				curblk = emuxki_voice_curaddr(voice) /
1979 				       voice->blksize;
1980 #if 0
1981 				if (curblk == voice->trigblk) {
1982 					voice->inth(voice->inthparam);
1983 					voice->trigblk++;
1984 					voice->trigblk %= voice->blkmod;
1985 				}
1986 #else
1987 				while ((curblk >= voice->trigblk &&
1988 				    curblk < (voice->trigblk + voice->blkmod / 2)) ||
1989 				    ((int)voice->trigblk - (int)curblk) >
1990 				    (voice->blkmod / 2 + 1)) {
1991 					voice->inth(voice->inthparam);
1992 					voice->trigblk++;
1993 					voice->trigblk %= voice->blkmod;
1994 				}
1995 #endif
1996 			}
1997 		}
1998 
1999 		/* Got interrupt */
2000 		bus_space_write_4(sc->sc_iot, sc->sc_ioh, EMU_IPR, ipr);
2001 
2002 		claim = 1;
2003 	}
2004 
2005 	mutex_spin_exit(&sc->sc_intr_lock);
2006 
2007 	return claim;
2008 }
2009 
2010 
2011 /*
2012  * Audio Architecture callbacks
2013  */
2014 
2015 static int
2016 emuxki_open(void *addr, int flags)
2017 {
2018 	struct emuxki_softc *sc;
2019 
2020 	sc = addr;
2021 #ifdef EMUXKI_DEBUG
2022 	printf("%s: emuxki_open called\n", device_xname(sc->sc_dev));
2023 #endif
2024 
2025 	/*
2026 	 * Multiple voice support would be added as soon as I find a way to
2027 	 * trick the audio arch into supporting multiple voices.
2028 	 * Or I might integrate a modified audio arch supporting
2029 	 * multiple voices.
2030 	 */
2031 
2032 	/*
2033 	 * I did this because i have problems identifying the selected
2034 	 * recording source(s) which is necessary when setting recording
2035 	 * params This will be addressed very soon
2036 	 */
2037 	if (flags & AUOPEN_READ) {
2038 		sc->rvoice = emuxki_voice_new(sc, 0 /* EMU_VOICE_USE_RECORD */);
2039 		if (sc->rvoice == NULL)
2040 			return EBUSY;
2041 
2042 		/* XXX Hardcode RECSRC_ADC for now */
2043 		sc->rvoice->dataloc.source = EMU_RECSRC_ADC;
2044 	}
2045 
2046 	if (flags & AUOPEN_WRITE) {
2047 		sc->pvoice = emuxki_voice_new(sc, EMU_VOICE_USE_PLAY);
2048 		if (sc->pvoice == NULL) {
2049 			if (sc->rvoice) {
2050 				emuxki_voice_delete(sc->rvoice);
2051 				sc->rvoice = NULL;
2052 			}
2053 			return EBUSY;
2054 		}
2055 	}
2056 
2057 	return 0;
2058 }
2059 
2060 static void
2061 emuxki_close(void *addr)
2062 {
2063 	struct emuxki_softc *sc;
2064 
2065 	sc = addr;
2066 #ifdef EMUXKI_DEBUG
2067 	printf("%s: emu10K1_close called\n", device_xname(sc->sc_dev));
2068 #endif
2069 
2070 	/* No multiple voice support for now */
2071 	if (sc->rvoice != NULL) {
2072 		emuxki_voice_delete(sc->rvoice);
2073 		sc->rvoice = NULL;
2074 	}
2075 	if (sc->pvoice != NULL) {
2076 		emuxki_voice_delete(sc->pvoice);
2077 		sc->pvoice = NULL;
2078 	}
2079 }
2080 
2081 static int
2082 emuxki_query_encoding(void *addr, struct audio_encoding *fp)
2083 {
2084 #ifdef EMUXKI_DEBUG
2085 	struct emuxki_softc *sc;
2086 
2087 	sc = addr;
2088 	printf("%s: emuxki_query_encoding called\n", device_xname(sc->sc_dev));
2089 #endif
2090 
2091 	switch (fp->index) {
2092 	case 0:
2093 		strcpy(fp->name, AudioEulinear);
2094 		fp->encoding = AUDIO_ENCODING_ULINEAR;
2095 		fp->precision = 8;
2096 		fp->flags = 0;
2097 		break;
2098 	case 1:
2099 		strcpy(fp->name, AudioEmulaw);
2100 		fp->encoding = AUDIO_ENCODING_ULAW;
2101 		fp->precision = 8;
2102 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2103 		break;
2104 	case 2:
2105 		strcpy(fp->name, AudioEalaw);
2106 		fp->encoding = AUDIO_ENCODING_ALAW;
2107 		fp->precision = 8;
2108 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2109 		break;
2110 	case 3:
2111 		strcpy(fp->name, AudioEslinear);
2112 		fp->encoding = AUDIO_ENCODING_SLINEAR;
2113 		fp->precision = 8;
2114 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2115 		break;
2116 	case 4:
2117 		strcpy(fp->name, AudioEslinear_le);
2118 		fp->encoding = AUDIO_ENCODING_SLINEAR_LE;
2119 		fp->precision = 16;
2120 		fp->flags = 0;
2121 		break;
2122 	case 5:
2123 		strcpy(fp->name, AudioEulinear_le);
2124 		fp->encoding = AUDIO_ENCODING_ULINEAR_LE;
2125 		fp->precision = 16;
2126 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2127 		break;
2128 	case 6:
2129 		strcpy(fp->name, AudioEslinear_be);
2130 		fp->encoding = AUDIO_ENCODING_SLINEAR_BE;
2131 		fp->precision = 16;
2132 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2133 		break;
2134 	case 7:
2135 		strcpy(fp->name, AudioEulinear_be);
2136 		fp->encoding = AUDIO_ENCODING_ULINEAR_BE;
2137 		fp->precision = 16;
2138 		fp->flags = AUDIO_ENCODINGFLAG_EMULATED;
2139 		break;
2140 	default:
2141 		return EINVAL;
2142 	}
2143 	return 0;
2144 }
2145 
2146 static int
2147 emuxki_set_vparms(struct emuxki_softc *sc, struct emuxki_voice *voice,
2148     const audio_params_t *p, stream_filter_list_t *fil)
2149 {
2150 	int mode, i;
2151 
2152 	mode = (voice->use & EMU_VOICE_USE_PLAY) ?
2153 		AUMODE_PLAY : AUMODE_RECORD;
2154 	i = auconv_set_converter(emuxki_formats, EMUXKI_NFORMATS,
2155 				 mode, p, FALSE, fil);
2156 	if (i < 0)
2157 		return EINVAL;
2158 	if (fil->req_size > 0)
2159 		p = &fil->filters[0].param;
2160 	return emuxki_voice_set_audioparms(sc, voice, p->channels == 2,
2161 	    p->precision == 16, p->sample_rate);
2162 }
2163 
2164 static int
2165 emuxki_set_params(void *addr, int setmode, int usemode, audio_params_t *play,
2166     audio_params_t *rec, stream_filter_list_t *pfil, stream_filter_list_t *rfil)
2167 {
2168 	struct emuxki_softc *sc;
2169 	struct audio_params *p;
2170 	struct emuxki_voice *v;
2171 	stream_filter_list_t *fil;
2172 	int mode, error;
2173 
2174 	sc = addr;
2175 	for (mode = AUMODE_RECORD; mode != -1;
2176 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
2177 		if ((usemode & setmode & mode) == 0)
2178 			continue;
2179 
2180 		if (mode == AUMODE_PLAY) {
2181 			p = play;
2182 			fil = pfil;
2183 			v = sc->pvoice;
2184 		} else {
2185 			p = rec;
2186 			fil = rfil;
2187 			v = sc->rvoice;
2188 		}
2189 
2190 		if (v == NULL) {
2191 			continue;
2192 		}
2193 
2194 		/* No multiple voice support for now */
2195 		if ((error = emuxki_set_vparms(sc, v, p, fil)))
2196 			return error;
2197 	}
2198 
2199 	return 0;
2200 }
2201 
2202 static int
2203 emuxki_halt_output(void *addr)
2204 {
2205 	struct emuxki_softc *sc;
2206 
2207 	sc = addr;
2208 	/* No multiple voice support for now */
2209 	if (sc->pvoice == NULL)
2210 		return ENXIO;
2211 
2212 	emuxki_voice_halt(sc->pvoice);
2213 	return 0;
2214 }
2215 
2216 static int
2217 emuxki_halt_input(void *addr)
2218 {
2219 	struct emuxki_softc *sc;
2220 
2221 	sc = addr;
2222 #ifdef EMUXKI_DEBUG
2223 	printf("%s: emuxki_halt_input called\n", device_xname(sc->sc_dev));
2224 #endif
2225 
2226 	/* No multiple voice support for now */
2227 	if (sc->rvoice == NULL)
2228 		return ENXIO;
2229 	emuxki_voice_halt(sc->rvoice);
2230 	return 0;
2231 }
2232 
2233 static int
2234 emuxki_getdev(void *addr, struct audio_device *dev)
2235 {
2236 	struct emuxki_softc *sc;
2237 
2238 	sc = addr;
2239 	*dev = sc->sc_audv;
2240 	return 0;
2241 }
2242 
2243 static int
2244 emuxki_set_port(void *addr, mixer_ctrl_t *mctl)
2245 {
2246 	struct emuxki_softc *sc;
2247 
2248 	sc = addr;
2249 	return sc->codecif->vtbl->mixer_set_port(sc->codecif, mctl);
2250 }
2251 
2252 static int
2253 emuxki_get_port(void *addr, mixer_ctrl_t *mctl)
2254 {
2255 	struct emuxki_softc *sc;
2256 
2257 	sc = addr;
2258 	return sc->codecif->vtbl->mixer_get_port(sc->codecif, mctl);
2259 }
2260 
2261 static int
2262 emuxki_query_devinfo(void *addr, mixer_devinfo_t *minfo)
2263 {
2264 	struct emuxki_softc *sc;
2265 
2266 	sc = addr;
2267 	return sc->codecif->vtbl->query_devinfo(sc->codecif, minfo);
2268 }
2269 
2270 static void *
2271 emuxki_allocm(void *addr, int direction, size_t size)
2272 {
2273 	if (direction == AUMODE_PLAY)
2274 		return emuxki_pmem_alloc(addr, size);
2275 	else
2276 		return emuxki_rmem_alloc(addr, size);
2277 }
2278 
2279 static void
2280 emuxki_freem(void *addr, void *ptr, size_t size)
2281 {
2282 	struct emuxki_softc *sc;
2283 	struct emuxki_mem *mem;
2284 	uint32_t *ptb, silentpage;
2285 	size_t numblocks;
2286 	int i;
2287 
2288 	sc = addr;
2289 	ptb = KERNADDR(sc->ptb);
2290 	silentpage = DMAADDR(sc->silentpage) << 1;
2291 	LIST_FOREACH(mem, &sc->mem, next) {
2292 		if (KERNADDR(mem->dmamem) != ptr)
2293 			continue;
2294 
2295 		mutex_spin_enter(&sc->sc_intr_lock);
2296 		if (mem->ptbidx != EMU_RMEM) {
2297 			numblocks = DMASIZE(mem->dmamem) / EMU_PTESIZE;
2298 			if (DMASIZE(mem->dmamem) % EMU_PTESIZE)
2299 				numblocks++;
2300 			for (i = 0; i < numblocks; i++)
2301 				ptb[mem->ptbidx + i] =
2302 				    htole32(silentpage | (mem->ptbidx + i));
2303 		}
2304 		LIST_REMOVE(mem, next);
2305 		mutex_spin_exit(&sc->sc_intr_lock);
2306 
2307 		emuxki_mem_delete(mem, size);
2308 		break;
2309 	}
2310 }
2311 
2312 /* blocksize should be a divisor of allowable buffersize */
2313 /* XXX probably this could be done better */
2314 static int
2315 emuxki_round_blocksize(void *addr, int blksize,
2316     int mode, const audio_params_t* param)
2317 {
2318 #if 0
2319 	struct emuxki_softc *sc;
2320 	struct audio_softc *au;
2321 #endif
2322 	int bufsize;
2323 #if 0
2324 	sc = addr;
2325 	if (sc == NULL)
2326 		return blksize;
2327 
2328 	au = device_private(sc->sc_audev);
2329 	if (au == NULL)
2330 		return blksize;
2331 
2332 	bufsize = emuxki_round_buffersize(sc, AUMODE_RECORD,
2333 	    au->sc_rr.bufsize);
2334 #else
2335 	bufsize = 65536;
2336 #endif
2337 
2338 	while (bufsize > blksize)
2339 		bufsize /= 2;
2340 
2341 	return bufsize;
2342 }
2343 
2344 static size_t
2345 emuxki_round_buffersize(void *addr, int direction, size_t bsize)
2346 {
2347 
2348 	if (direction == AUMODE_PLAY) {
2349 		if (bsize < EMU_PTESIZE)
2350 			bsize = EMU_PTESIZE;
2351 		else if (bsize > (EMU_PTESIZE * EMU_MAXPTE))
2352 			bsize = EMU_PTESIZE * EMU_MAXPTE;
2353 		/* Would be better if set to max available */
2354 		else if (bsize % EMU_PTESIZE)
2355 			bsize = bsize -
2356 				(bsize % EMU_PTESIZE) +
2357 				EMU_PTESIZE;
2358 	} else {
2359 		int idx;
2360 
2361 		/* find nearest lower recbuf size */
2362 		for(idx = sizeof(emuxki_recbuf_sz) /
2363 		    sizeof(emuxki_recbuf_sz[0]); --idx >= 0; ) {
2364 			if (bsize >= emuxki_recbuf_sz[idx]) {
2365 				bsize = emuxki_recbuf_sz[idx];
2366 				break;
2367 			}
2368 		}
2369 
2370 		if (bsize == 0)
2371 			bsize = 384;
2372 	}
2373 
2374 	return bsize;
2375 }
2376 
2377 static paddr_t
2378 emuxki_mappage(void *addr, void *ptr, off_t off, int prot)
2379 {
2380 	struct emuxki_softc *sc;
2381 	struct emuxki_mem *mem;
2382 
2383 	sc = addr;
2384 
2385 	mutex_exit(&sc->sc_lock);
2386 	LIST_FOREACH(mem, &sc->mem, next) {
2387 		if (KERNADDR(mem->dmamem) == ptr) {
2388 			struct dmamem *dm = mem->dmamem;
2389 
2390 			return bus_dmamem_mmap(dm->dmat, dm->segs, dm->nsegs,
2391 			       off, prot, BUS_DMA_WAITOK);
2392 		}
2393 	}
2394 	mutex_enter(&sc->sc_lock);
2395 
2396 	return -1;
2397 }
2398 
2399 static int
2400 emuxki_get_props(void *addr)
2401 {
2402 	return AUDIO_PROP_MMAP | AUDIO_PROP_INDEPENDENT |
2403 	    AUDIO_PROP_FULLDUPLEX;
2404 }
2405 
2406 static int
2407 emuxki_trigger_output(void *addr, void *start, void *end, int blksize,
2408     void (*inth) (void *), void *inthparam, const audio_params_t *params)
2409 {
2410 	struct emuxki_softc *sc;
2411 	/* No multiple voice support for now */
2412 	struct emuxki_voice *voice;
2413 	int error;
2414 
2415 	sc = addr;
2416 	voice = sc->pvoice;
2417 	if (voice == NULL)
2418 		return ENXIO;
2419 	if ((error = emuxki_voice_set_audioparms(sc, voice, params->channels == 2,
2420 	    params->precision == 16, params->sample_rate)))
2421 		return error;
2422 	if ((error = emuxki_voice_set_bufparms(voice, start,
2423 	    (char *)end - (char *)start, blksize)))
2424 		return error;
2425 	emuxki_voice_commit_parms(voice);
2426 	emuxki_voice_start(voice, inth, inthparam);
2427 
2428 	return 0;
2429 }
2430 
2431 static int
2432 emuxki_trigger_input(void *addr, void *start, void *end, int blksize,
2433     void (*inth) (void *), void *inthparam, const audio_params_t *params)
2434 {
2435 	struct emuxki_softc *sc;
2436 	/* No multiple voice support for now */
2437 	struct emuxki_voice *voice;
2438 	int	error;
2439 
2440 	sc = addr;
2441 	voice = sc->rvoice;
2442 	if (voice == NULL)
2443 		return ENXIO;
2444 	if ((error = emuxki_voice_set_audioparms(sc, voice,
2445 	    params->channels == 2, params->precision == 16,
2446 	    params->sample_rate)))
2447 		return error;
2448 	if ((error = emuxki_voice_set_bufparms(voice, start,
2449 	    (char *)end - (char *)start, blksize)))
2450 		return error;
2451 	emuxki_voice_start(voice, inth, inthparam);
2452 
2453 	return 0;
2454 }
2455 
2456 /*
2457  * AC97 callbacks
2458  */
2459 
2460 static int
2461 emuxki_ac97_attach(void *arg, struct ac97_codec_if *codecif)
2462 {
2463 	struct emuxki_softc *sc;
2464 
2465 	sc = arg;
2466 	sc->codecif = codecif;
2467 	return 0;
2468 }
2469 
2470 static int
2471 emuxki_ac97_read(void *arg, uint8_t reg, uint16_t *val)
2472 {
2473 	struct emuxki_softc *sc;
2474 
2475 	sc = arg;
2476 	mutex_spin_enter(&sc->sc_ac97_index_lock);
2477 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, EMU_AC97ADDR, reg);
2478 	*val = bus_space_read_2(sc->sc_iot, sc->sc_ioh, EMU_AC97DATA);
2479 	mutex_spin_exit(&sc->sc_ac97_index_lock);
2480 
2481 	return 0;
2482 }
2483 
2484 static int
2485 emuxki_ac97_write(void *arg, uint8_t reg, uint16_t val)
2486 {
2487 	struct emuxki_softc *sc;
2488 
2489 	sc = arg;
2490 	mutex_spin_enter(&sc->sc_ac97_index_lock);
2491 	bus_space_write_1(sc->sc_iot, sc->sc_ioh, EMU_AC97ADDR, reg);
2492 	bus_space_write_2(sc->sc_iot, sc->sc_ioh, EMU_AC97DATA, val);
2493 	mutex_spin_exit(&sc->sc_ac97_index_lock);
2494 
2495 	return 0;
2496 }
2497 
2498 static int
2499 emuxki_ac97_reset(void *arg)
2500 {
2501 
2502 	return 0;
2503 }
2504 
2505 enum ac97_host_flags
2506 emuxki_ac97_flags(void *arg)
2507 {
2508 
2509 	return AC97_HOST_SWAPPED_CHANNELS;
2510 }
2511 
2512 static void
2513 emuxki_get_locks(void *arg, kmutex_t **intr, kmutex_t **proc)
2514 {
2515 	struct emuxki_softc *sc;
2516 
2517 	sc = arg;
2518 	*intr = &sc->sc_intr_lock;
2519 	*proc = &sc->sc_lock;
2520 }
2521