xref: /illumos-gate/usr/src/uts/common/io/audio/drv/audiots/audiots.c (revision 89b2a9fbeabf42fa54594df0e5927bcc50a07cc9)
1 /*
2  * CDDL HEADER START
3  *
4  * The contents of this file are subject to the terms of the
5  * Common Development and Distribution License (the "License").
6  * You may not use this file except in compliance with the License.
7  *
8  * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
9  * or http://www.opensolaris.org/os/licensing.
10  * See the License for the specific language governing permissions
11  * and limitations under the License.
12  *
13  * When distributing Covered Code, include this CDDL HEADER in each
14  * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
15  * If applicable, add the following below this CDDL HEADER, with the
16  * fields enclosed by brackets "[]" replaced with your own identifying
17  * information: Portions Copyright [yyyy] [name of copyright owner]
18  *
19  * CDDL HEADER END
20  */
21 /*
22  * Copyright 2009 Sun Microsystems, Inc.  All rights reserved.
23  * Use is subject to license terms.
24  */
25 
26 
27 /*
28  * audiots Audio Driver
29  *
30  * This Audio Driver controls the T2 audio core in the ALI M1553
31  * southbridge chip. This chip supports multiple play streams, but just
32  * a single record stream. It also supports wave table synthesis and
33  * hardware MIDI and joystick ports. Unfortunately the MIDI ports are
34  * not available because their pins have been re-assigned to expose
35  * interrupts. We also aren't going to do anything with the joystick
36  * ports. The audio core controls an AC-97 V2.1 Codec.
37  *
38  * The DMA engine uses a single buffer which is large enough to hold
39  * two interrupts worth of data. When it gets to the mid point an
40  * interrupt is generated and data is either sent (for record) or
41  * requested and put in that half of the buffer (for play). When the
42  * second half is played we do the same, but the audio core loops the
43  * pointer back to the beginning.
44  *
45  * The audio core has a bug in silicon that doesn't let it read the AC-97
46  * Codec's register. T2 has provided an algorithm that attempts to read the
47  * the Codec several times. This is probably heuristic and thus isn't
48  * absolutely guaranteed to work. However we do have to place a limit on
49  * the looping, otherwise when we read a valid 0x00 we would never exit
50  * the loop. Unfortunately there is also a problem with writing the AC-97
51  * Codec's registers as well. Thus we read it back to verify the write.
52  *
53  * The AC'97 common code provides shadow state for AC'97 registers for us,
54  * so we only need to read those registers during early startup (primarily
55  * to determine codec id and capabilities.)
56  *
57  * We don't save any of the audio controller registers during normal
58  * operation. When we need to save register state we only have to save
59  * the aram and eram. The rest of the controller state is never modified
60  * from the initial programming. Thus restoring the controller state
61  * can be done from audiots_chip_init() as well.
62  *
63  *
64  * WARNING: The SME birdsnest platform uses a PCI bridge chip between the
65  *	CPU and the southbridge containing the audio core. There is
66  *	a bug in silicon that causes a bogus parity error. With the mixer
67  *	reimplementation project, Bug 4374774, the audio driver is always
68  *	set to the best precision and number of channels. Thus when turning
69  *	the mixer on and off the only thing that changes is the sample rate.
70  *	This change in programming doesn't trigger the silicon error.
71  *	Thus the supported channels must always be 2 and the precision
72  *	must always be 16-bits. This will keep any future change in the
73  *	mixer from exposing this bug.
74  *
75  * Due to a hardware bug, system power management is not supported by this
76  * driver.
77  *
78  *	CAUTION: If audio controller state is changed outside of aram
79  *		and eram then that information must be saved and restored
80  *		during power management shutdown and bringup.
81  *
82  *	NOTE: The AC-97 Codec's reset pin is set to PCI reset, so we
83  *		can't power down the Codec all the way.
84  *
85  *	NOTE: This driver depends on the drv/audio and misc/ac97
86  *		modules being loaded first.
87  *
88  *	NOTE: Don't OR the ap_stop register to stop a play or record. This
89  *		will just stop all active channels because a read of ap_stop
90  *		returns ap_start. Just set the ap_stop register with the
91  *		channels you want to stop. The same goes for ap_start.
92  *
93  *	NOTE: There is a hardware problem with P2 rev motherboards. After
94  *		prolonged use, reading the AC97 register will always return
95  *		busy. The AC97 register is now useless. Consequently, we are no
96  *		longer able to program the Codec. This work around disables
97  *		audio when this state is detected. It's not great, but its
98  *		better than having audio blasting out at 100% all the time.
99  *
100  *	NOTE: Power Management testing has also exposed this AC97 timeout
101  *		problem. Management has decided this is too risky for customers
102  *		and hence they want power management support removed from the
103  *		audio subsystem. All PM support is now removed.
104  */
105 
106 #include <sys/modctl.h>
107 #include <sys/kmem.h>
108 #include <sys/pci.h>
109 #include <sys/ddi.h>
110 #include <sys/sunddi.h>
111 #include <sys/debug.h>
112 #include <sys/note.h>
113 #include <sys/audio/audio_driver.h>
114 #include <sys/audio/ac97.h>
115 #include "audiots.h"
116 
117 /*
118  * Module linkage routines for the kernel
119  */
120 static int audiots_attach(dev_info_t *, ddi_attach_cmd_t);
121 static int audiots_detach(dev_info_t *, ddi_detach_cmd_t);
122 static int audiots_quiesce(dev_info_t *);
123 
124 /*
125  * Entry point routine prototypes
126  */
127 static int audiots_open(void *, int, unsigned *, unsigned *, caddr_t *);
128 static void audiots_close(void *);
129 static int audiots_start(void *);
130 static void audiots_stop(void *);
131 static int audiots_format(void *);
132 static int audiots_channels(void *);
133 static int audiots_rate(void *);
134 static void audiots_chinfo(void *, int, unsigned *, unsigned *);
135 static uint64_t audiots_count(void *);
136 static void audiots_sync(void *, unsigned);
137 static size_t audiots_qlen(void *);
138 
139 static audio_engine_ops_t	audiots_engine_ops = {
140 	AUDIO_ENGINE_VERSION,
141 	audiots_open,
142 	audiots_close,
143 	audiots_start,
144 	audiots_stop,
145 	audiots_count,
146 	audiots_format,
147 	audiots_channels,
148 	audiots_rate,
149 	audiots_sync,
150 	audiots_qlen,
151 	audiots_chinfo
152 };
153 
154 /*
155  * Local Routine Prototypes
156  */
157 static void audiots_power_up(audiots_state_t *);
158 static void audiots_chip_init(audiots_state_t *);
159 static uint16_t audiots_get_ac97(void *, uint8_t);
160 static void audiots_set_ac97(void *, uint8_t, uint16_t);
161 static int audiots_init_state(audiots_state_t *, dev_info_t *);
162 static uint_t audiots_intr(caddr_t);
163 static int audiots_map_regs(dev_info_t *, audiots_state_t *);
164 static void audiots_update_port(audiots_port_t *);
165 static void audiots_start_port(audiots_port_t *);
166 static void audiots_stop_port(audiots_port_t *);
167 static uint16_t audiots_read_ac97(audiots_state_t *, int);
168 static void audiots_stop_everything(audiots_state_t *);
169 static void audiots_destroy(audiots_state_t *);
170 static int audiots_alloc_port(audiots_state_t *, int);
171 static void audiots_reset_port(audiots_port_t *);
172 
173 /*
174  * Global variables, but viewable only by this file.
175  */
176 
177 /* anchor for soft state structures */
178 static void *audiots_statep;
179 
180 /* driver name, so we don't have to call ddi_driver_name() or hard code strs */
181 static char *audiots_name = TS_NAME;
182 
183 /*
184  * DDI Structures
185  */
186 
187 /* Device operations structure */
188 static struct dev_ops audiots_dev_ops = {
189 	DEVO_REV,		/* devo_rev */
190 	0,			/* devo_refcnt */
191 	NULL,			/* devo_getinfo */
192 	nulldev,		/* devo_identify - obsolete */
193 	nulldev,		/* devo_probe */
194 	audiots_attach,		/* devo_attach */
195 	audiots_detach,		/* devo_detach */
196 	nodev,			/* devo_reset */
197 	NULL,			/* devo_cb_ops */
198 	NULL,			/* devo_bus_ops */
199 	NULL,			/* devo_power */
200 	audiots_quiesce,	/* devo_quiesce */
201 };
202 
203 /* Linkage structure for loadable drivers */
204 static struct modldrv audiots_modldrv = {
205 	&mod_driverops,		/* drv_modops */
206 	TS_MOD_NAME,		/* drv_linkinfo */
207 	&audiots_dev_ops	/* drv_dev_ops */
208 };
209 
210 /* Module linkage structure */
211 static struct modlinkage audiots_modlinkage = {
212 	MODREV_1,			/* ml_rev */
213 	(void *)&audiots_modldrv,	/* ml_linkage */
214 	NULL				/* NULL terminates the list */
215 };
216 
217 
218 /*
219  * NOTE: Grover OBP v4.0.166 and rev G of the ALI Southbridge chip force the
220  * audiots driver to use the upper 2 GB DMA address range. However to maintain
221  * backwards compatibility with older systems/OBP, we're going to try the full
222  * 4 GB DMA range.
223  *
224  * Eventually, this will be set back to using the proper high 2 GB DMA range.
225  */
226 
227 /* Device attribute structure - full 4 gig address range */
228 static ddi_dma_attr_t audiots_attr = {
229 	DMA_ATTR_VERSION,		/* version */
230 	0x0000000000000000LL,		/* dlim_addr_lo */
231 	0x00000000ffffffffLL,		/* dlim_addr_hi */
232 	0x0000000000003fffLL,		/* DMA counter register - 16 bits */
233 	0x0000000000000008LL,		/* DMA address alignment, 64-bit */
234 	0x0000007f,			/* 1 through 64 byte burst sizes */
235 	0x00000001,			/* min effective DMA size */
236 	0x0000000000003fffLL,		/* maximum transfer size, 16k */
237 	0x000000000000ffffLL,		/* segment boundary, 64k */
238 	0x00000001,			/* s/g list length, no s/g */
239 	0x00000001,			/* granularity of device, don't care */
240 	0				/* DMA flags */
241 };
242 
243 static ddi_device_acc_attr_t ts_acc_attr = {
244 	DDI_DEVICE_ATTR_V0,
245 	DDI_NEVERSWAP_ACC,
246 	DDI_STRICTORDER_ACC
247 };
248 
249 static ddi_device_acc_attr_t ts_regs_attr = {
250 	DDI_DEVICE_ATTR_V0,
251 	DDI_STRUCTURE_LE_ACC,
252 	DDI_STRICTORDER_ACC
253 };
254 
255 /*
256  * _init()
257  *
258  * Description:
259  *	Driver initialization, called when driver is first loaded.
260  *	This is how access is initially given to all the static structures.
261  *
262  * Arguments:
263  *	None
264  *
265  * Returns:
266  *	ddi_soft_state_init() status, see ddi_soft_state_init(9f), or
267  *	mod_install() status, see mod_install(9f)
268  */
269 int
270 _init(void)
271 {
272 	int		error;
273 
274 	audio_init_ops(&audiots_dev_ops, TS_NAME);
275 
276 	/* initialize the soft state */
277 	if ((error = ddi_soft_state_init(&audiots_statep,
278 	    sizeof (audiots_state_t), 1)) != 0) {
279 		audio_fini_ops(&audiots_dev_ops);
280 		return (error);
281 	}
282 
283 	if ((error = mod_install(&audiots_modlinkage)) != 0) {
284 		audio_fini_ops(&audiots_dev_ops);
285 		ddi_soft_state_fini(&audiots_statep);
286 	}
287 
288 	return (error);
289 }
290 
291 /*
292  * _fini()
293  *
294  * Description:
295  *	Module de-initialization, called when the driver is to be unloaded.
296  *
297  * Arguments:
298  *	None
299  *
300  * Returns:
301  *	mod_remove() status, see mod_remove(9f)
302  */
303 int
304 _fini(void)
305 {
306 	int		error;
307 
308 	if ((error = mod_remove(&audiots_modlinkage)) != 0) {
309 		return (error);
310 	}
311 
312 	/* free the soft state internal structures */
313 	ddi_soft_state_fini(&audiots_statep);
314 
315 	/* clean up ops */
316 	audio_fini_ops(&audiots_dev_ops);
317 
318 	return (0);
319 }
320 
321 /*
322  * _info()
323  *
324  * Description:
325  *	Module information, returns infomation about the driver.
326  *
327  * Arguments:
328  *	modinfo *modinfop	Pointer to the opaque modinfo structure
329  *
330  * Returns:
331  *	mod_info() status, see mod_info(9f)
332  */
333 int
334 _info(struct modinfo *modinfop)
335 {
336 	int		error;
337 
338 	error = mod_info(&audiots_modlinkage, modinfop);
339 
340 	return (error);
341 }
342 
343 
344 /*
345  * audiots_attach()
346  *
347  * Description:
348  *	Attach an instance of the audiots driver. This routine does the
349  *	device dependent attach tasks.
350  *
351  * Arguments:
352  *	dev_info_t	*dip	Pointer to the device's dev_info struct
353  *	ddi_attach_cmd_t cmd	Attach command
354  *
355  * Returns:
356  *	DDI_SUCCESS		The driver was initialized properly
357  *	DDI_FAILURE		The driver couldn't be initialized properly
358  */
359 static int
360 audiots_attach(dev_info_t *dip, ddi_attach_cmd_t cmd)
361 {
362 	audiots_state_t		*state;
363 	int			instance;
364 
365 	instance = ddi_get_instance(dip);
366 
367 	switch (cmd) {
368 	case DDI_ATTACH:
369 		break;
370 	case DDI_RESUME:
371 
372 		/* we've already allocated the state structure so get ptr */
373 		if ((state = ddi_get_soft_state(audiots_statep, instance)) ==
374 		    NULL) {
375 			/* this will probably panic */
376 			cmn_err(CE_WARN,
377 			    "!%s%d: RESUME get soft state failed",
378 			    audiots_name, instance);
379 			return (DDI_FAILURE);
380 		}
381 
382 		ASSERT(dip == state->ts_dip);
383 
384 		/* suspend/resume resets the chip, so we have no more faults */
385 		if (state->ts_flags & TS_AUDIO_READ_FAILED) {
386 			ddi_dev_report_fault(state->ts_dip,
387 			    DDI_SERVICE_RESTORED,
388 			    DDI_DEVICE_FAULT,
389 			    "check port, gain, balance, and mute settings");
390 			/* and clear the fault state flags */
391 			state->ts_flags &=
392 			    ~(TS_AUDIO_READ_FAILED|TS_READ_FAILURE_PRINTED);
393 		}
394 
395 		audiots_power_up(state);
396 		audiots_chip_init(state);
397 		ac97_resume(state->ts_ac97);
398 
399 		mutex_enter(&state->ts_lock);
400 		/*
401 		 * Initialize/reset ports.  Done under the lock, to
402 		 * avoid race with interrupt service routine.
403 		 */
404 		state->ts_suspended = B_FALSE;
405 		for (int i = 0; i < TS_NUM_PORTS; i++) {
406 			audiots_port_t	*port = state->ts_ports[i];
407 			if (port != NULL) {
408 				/* relocate any streams properly */
409 				if (port->tp_engine)
410 					audio_engine_reset(port->tp_engine);
411 
412 				/* do a hardware reset on the port */
413 				audiots_reset_port(port);
414 				if (port->tp_started) {
415 					audiots_start_port(port);
416 				} else {
417 					audiots_stop_port(port);
418 				}
419 			}
420 		}
421 		mutex_exit(&state->ts_lock);
422 
423 		return (DDI_SUCCESS);
424 
425 	default:
426 		cmn_err(CE_WARN, "!%s%d: attach() unknown command: 0x%x",
427 		    audiots_name, instance, cmd);
428 		return (DDI_FAILURE);
429 	}
430 
431 	/* before we do anything make sure that we haven't had a h/w failure */
432 	if (ddi_get_devstate(dip) == DDI_DEVSTATE_DOWN) {
433 		cmn_err(CE_WARN, "%s%d: The audio hardware has "
434 		    "been disabled.", audiots_name, instance);
435 		cmn_err(CE_CONT, "Please reboot to restore audio.");
436 		return (DDI_FAILURE);
437 	}
438 
439 	/* we don't support high level interrupts in this driver */
440 	if (ddi_intr_hilevel(dip, 0) != 0) {
441 		cmn_err(CE_WARN, "!%s%d: unsupported high level interrupt",
442 		    audiots_name, instance);
443 		return (DDI_FAILURE);
444 	}
445 
446 	/* allocate the state structure */
447 	if (ddi_soft_state_zalloc(audiots_statep, instance) == DDI_FAILURE) {
448 		cmn_err(CE_WARN, "!%s%d: soft state allocate failed",
449 		    audiots_name, instance);
450 		return (DDI_FAILURE);
451 	}
452 
453 	/*
454 	 * WARNING: From here on all errors require that we free memory,
455 	 *	including the state structure.
456 	 */
457 
458 	/* get the state structure - cannot fail */
459 	state = ddi_get_soft_state(audiots_statep, instance);
460 	ASSERT(state != NULL);
461 
462 	if ((state->ts_adev = audio_dev_alloc(dip, 0)) == NULL) {
463 		cmn_err(CE_WARN, "unable to allocate audio dev");
464 		goto error;
465 	}
466 
467 	/* map in the registers, allocate DMA buffers, etc. */
468 	if (audiots_map_regs(dip, state) == DDI_FAILURE) {
469 		audio_dev_warn(state->ts_adev, "unable to map registers");
470 		goto error;
471 	}
472 
473 	/* initialize the audio state structures */
474 	if (audiots_init_state(state, dip) == DDI_FAILURE) {
475 		audio_dev_warn(state->ts_adev, "init state structure failed");
476 		goto error;
477 	}
478 
479 	/* power up */
480 	audiots_power_up(state);
481 
482 	/* initialize the audio controller */
483 	audiots_chip_init(state);
484 
485 	/* initialize the AC-97 Codec */
486 	if (ac97_init(state->ts_ac97, state->ts_adev) != 0) {
487 		goto error;
488 	}
489 
490 	/* put the engine interrupts into a known state -- all off */
491 	ddi_put32(state->ts_acch, &state->ts_regs->aud_regs.ap_ainten,
492 	    TS_ALL_DMA_OFF);
493 
494 	/* call the framework attach routine */
495 	if (audio_dev_register(state->ts_adev) != DDI_SUCCESS) {
496 		audio_dev_warn(state->ts_adev, "unable to register audio");
497 		goto error;
498 	}
499 
500 	/* set up kernel statistics */
501 	state->ts_ksp = kstat_create(TS_NAME, instance, TS_NAME,
502 	    "controller", KSTAT_TYPE_INTR, 1, KSTAT_FLAG_PERSISTENT);
503 	if (state->ts_ksp != NULL) {
504 		kstat_install(state->ts_ksp);
505 	}
506 
507 	/* set up the interrupt handler */
508 	if (ddi_add_intr(dip, 0, NULL, NULL, audiots_intr,
509 	    (caddr_t)state) != DDI_SUCCESS) {
510 		audio_dev_warn(state->ts_adev,
511 		    "failed to register interrupt handler");
512 		goto error;
513 	}
514 	state->ts_flags |= TS_INTR_INSTALLED;
515 
516 	/* everything worked out, so report the device */
517 	ddi_report_dev(dip);
518 
519 	return (DDI_SUCCESS);
520 
521 error:
522 	audiots_destroy(state);
523 	return (DDI_FAILURE);
524 }
525 
526 /*
527  * audiots_detach()
528  *
529  * Description:
530  *	Detach an instance of the audiots driver.
531  *
532  * Arguments:
533  *	dev_info_t	*dip	Pointer to the device's dev_info struct
534  *	ddi_detach_cmd_t cmd	Detach command
535  *
536  * Returns:
537  *	DDI_SUCCESS		The driver was detached
538  *	DDI_FAILURE		The driver couldn't be detached
539  */
540 static int
541 audiots_detach(dev_info_t *dip, ddi_detach_cmd_t cmd)
542 {
543 	audiots_state_t		*state;
544 	int			instance;
545 
546 	instance = ddi_get_instance(dip);
547 
548 	/* get the state structure */
549 	if ((state = ddi_get_soft_state(audiots_statep, instance)) == NULL) {
550 		cmn_err(CE_WARN, "!%s%d: detach get soft state failed",
551 		    audiots_name, instance);
552 		return (DDI_FAILURE);
553 	}
554 
555 	switch (cmd) {
556 	case DDI_DETACH:
557 		break;
558 	case DDI_SUSPEND:
559 
560 		ac97_suspend(state->ts_ac97);
561 
562 		mutex_enter(&state->ts_lock);
563 
564 		state->ts_suspended = B_TRUE;	/* stop new ops */
565 
566 		/* we may already be powered down, so only save state if up */
567 
568 		/* stop playing and recording */
569 		(void) audiots_stop_everything(state);
570 
571 		mutex_exit(&state->ts_lock);
572 
573 		return (DDI_SUCCESS);
574 
575 	default:
576 		return (DDI_FAILURE);
577 	}
578 
579 	/* attempt to unregister from the framework first */
580 	if (audio_dev_unregister(state->ts_adev) != DDI_SUCCESS) {
581 		return (DDI_FAILURE);
582 	}
583 
584 	audiots_destroy(state);
585 
586 	return (DDI_SUCCESS);
587 
588 }
589 
590 /*
591  * audiots_quiesce()
592  *
593  * Description:
594  *	Quiesce an instance of the audiots driver. Stops all DMA and
595  *	interrupts.
596  *
597  * Arguments:
598  *	dev_info_t	*dip	Pointer to the device's dev_info struct
599  *
600  * Returns:
601  *	DDI_SUCCESS		The driver was quiesced
602  *	DDI_SUCCESS		The driver was NOT quiesced
603  */
604 static int
605 audiots_quiesce(dev_info_t *dip)
606 {
607 	audiots_state_t		*state;
608 	int			instance;
609 
610 	instance = ddi_get_instance(dip);
611 
612 	/* get the state structure */
613 	if ((state = ddi_get_soft_state(audiots_statep, instance)) == NULL) {
614 		return (DDI_FAILURE);
615 	}
616 
617 	audiots_stop_everything(state);
618 
619 	return (DDI_SUCCESS);
620 }
621 
622 /*
623  * audiots_power_up()
624  *
625  * Description
626  *	Ensure that the device is running in PCI power state D0.
627  */
628 static void
629 audiots_power_up(audiots_state_t *state)
630 {
631 	ddi_acc_handle_t	pcih = state->ts_pcih;
632 	uint8_t			ptr;
633 	uint16_t		pmcsr;
634 
635 	if ((pci_config_get16(pcih, PCI_CONF_STAT) & PCI_STAT_CAP) == 0) {
636 		/* does not implement PCI capabilities -- no PM */
637 		return;
638 	}
639 
640 	ptr = pci_config_get8(pcih, PCI_CONF_CAP_PTR);
641 	for (;;) {
642 		if (ptr == PCI_CAP_NEXT_PTR_NULL) {
643 			/* PM capability not found */
644 			return;
645 		}
646 		if (pci_config_get8(pcih, ptr + PCI_CAP_ID) == PCI_CAP_ID_PM) {
647 			/* found it */
648 			break;
649 		}
650 		ptr = pci_config_get8(pcih, ptr + PCI_CAP_NEXT_PTR);
651 	}
652 
653 	/* if we got here, then got valid PMCSR pointer */
654 	ptr += PCI_PMCSR;
655 
656 	/* check to see if we are already in state D0 */
657 	pmcsr = pci_config_get16(pcih, ptr);
658 	if ((pmcsr & PCI_PMCSR_STATE_MASK) != PCI_PMCSR_D0) {
659 
660 		/* D3hot (or any other state) -> D0 */
661 		pmcsr &= ~PCI_PMCSR_STATE_MASK;
662 		pmcsr |= PCI_PMCSR_D0;
663 		pci_config_put16(pcih, ptr, pmcsr);
664 	}
665 
666 	/*
667 	 * Wait for it to power up - PCI spec says 10 ms is enough.
668 	 * We double it.  Note that no locks are held when this routine
669 	 * is called, so we can sleep (we are in attach context only).
670 	 *
671 	 * We do this delay even if already powerd up, just to make
672 	 * sure we aren't seeing something that *just* transitioned
673 	 * into D0 state.
674 	 */
675 	delay(drv_usectohz(TS_20MS));
676 
677 	/* clear PME# flag */
678 	pmcsr = pci_config_get16(pcih, ptr);
679 	pci_config_put16(pcih, ptr, pmcsr | PCI_PMCSR_PME_STAT);
680 }
681 
682 /*
683  * audiots_chip_init()
684  *
685  * Description:
686  *	Initialize the audio core.
687  *
688  * Arguments:
689  *	audiots_state_t	*state		The device's state structure
690  *
691  * Returns:
692  *	void
693  */
694 static void
695 audiots_chip_init(audiots_state_t *state)
696 {
697 	ddi_acc_handle_t	handle = state->ts_acch;
698 	audiots_regs_t		*regs = state->ts_regs;
699 	int			str;
700 
701 	/* start with all interrupts & dma channels disabled */
702 	ddi_put32(handle, &regs->aud_regs.ap_stop, TS_ALL_DMA_ENGINES);
703 	ddi_put32(handle, &regs->aud_regs.ap_ainten, TS_ALL_DMA_OFF);
704 
705 	/* set global music and wave volume to 0dB */
706 	ddi_put32(handle, &regs->aud_regs.ap_volume, 0x0);
707 
708 	/* enable end interrupts for all channels. */
709 	ddi_put32(handle, &regs->aud_regs.ap_cir_gc, AP_CIR_GC_ENDLP_IE);
710 
711 	/* for each stream, set gain and vol settings */
712 	for (str = 0; str < TS_MAX_HW_CHANNELS; str++) {
713 		/*
714 		 * Set volume to all off, 1st left and then right.
715 		 * These are never changed, so we don't have to save them.
716 		 */
717 		ddi_put16(handle,
718 		    &regs->aud_ram[str].eram.eram_gvsel_pan_vol,
719 		    (ERAM_WAVE_VOL|ERAM_PAN_LEFT|ERAM_PAN_0dB|
720 		    ERAM_VOL_MAX_ATTEN));
721 		ddi_put16(handle,
722 		    &regs->aud_ram[str].eram.eram_gvsel_pan_vol,
723 		    (ERAM_WAVE_VOL|ERAM_PAN_RIGHT|ERAM_PAN_0dB|
724 		    ERAM_VOL_MAX_ATTEN));
725 
726 		/*
727 		 * The envelope engine *MUST* remain in still mode (off).
728 		 * Otherwise bad things like gain randomly disappearing might
729 		 * happen. See bug #4332773.
730 		 */
731 
732 		ddi_put32(handle, &regs->aud_ram[str].eram.eram_ebuf1,
733 		    ERAM_EBUF_STILL);
734 		ddi_put32(handle, &regs->aud_ram[str].eram.eram_ebuf2,
735 		    ERAM_EBUF_STILL);
736 
737 		/* program the initial eram and aram rate */
738 		ddi_put16(handle, &regs->aud_ram[str].aram.aram_delta,
739 		    1 << TS_SRC_SHIFT);
740 		ddi_put16(handle, &regs->aud_ram[str].eram.eram_ctrl_ec,
741 		    ERAM_16_BITS | ERAM_STEREO | ERAM_LOOP_MODE |
742 		    ERAM_SIGNED_PCM);
743 	}
744 
745 	/* program channel 31 for record */
746 	OR_SET_WORD(handle, &state->ts_regs->aud_regs.ap_global_control,
747 	    (AP_CLOGAL_CTRL_E_PCMIN_CH31|AP_CLOGAL_CTRL_PCM_OUT_AC97|
748 	    AP_CLOGAL_CTRL_MMC_FROM_MIXER|AP_CLOGAL_CTRL_PCM_OUT_TO_AC97));
749 
750 	/* do a warm reset, which powers up the Codec */
751 	OR_SET_WORD(handle, &state->ts_regs->aud_regs.ap_sctrl,
752 	    AP_SCTRL_WRST_CODEC);
753 	drv_usecwait(2);
754 	AND_SET_WORD(handle, &state->ts_regs->aud_regs.ap_sctrl,
755 	    ~AP_SCTRL_WRST_CODEC);
756 
757 	/* do a warm reset via the Codec, yes, I'm being paranoid! */
758 	audiots_set_ac97(state, AC97_RESET_REGISTER, 0);
759 
760 	/* Make sure the Codec is powered up. */
761 	int i = TS_WAIT_CNT;
762 	while ((audiots_get_ac97(state, AC97_POWERDOWN_CTRL_STAT_REGISTER) &
763 	    PCSR_POWERD_UP) != PCSR_POWERD_UP && i--) {
764 		drv_usecwait(1);
765 	}
766 
767 }
768 
769 /*
770  * audiots_get_ac97()
771  *
772  * Description:
773  *	Get the value in the specified AC-97 Codec register. There is a
774  *	bug in silicon which forces us to do multiple reads of the Codec's
775  *	register. This algorithm was provided by T2 and is heuristic in
776  *	nature. Unfortunately we have no guarantees that the real answer
777  *	isn't 0x0000, which is what we get when a read fails. So we loop
778  *	TS_LOOP_CNT times before we give up. We just have to hope this is
779  *	sufficient to give us the correct value.
780  *
781  * Arguments:
782  *	audiots_state_t	*state		The device's state structure
783  *	int		reg		AC-97 register number
784  *
785  * Returns:
786  *	unsigned short		The value in the specified register
787  */
788 static uint16_t
789 audiots_get_ac97(void *arg, uint8_t reg)
790 {
791 	audiots_state_t		*state = arg;
792 	ddi_acc_handle_t	handle = state->ts_acch;
793 	uint16_t		*data;
794 	int			count;
795 	int			delay;
796 	uint16_t		first;
797 	uint16_t		next;
798 
799 	if (state->ts_revid == AC_REV_ID1) {
800 		data = &state->ts_regs->aud_regs.ap_acrd_35D_data;
801 	} else {
802 		data = &state->ts_regs->aud_regs.ap_acrdwr_data;
803 	}
804 
805 	/* make sure the register is good */
806 	reg &= AP_ACRD_INDEX_MASK;
807 	for (count = TS_LOOP_CNT; count--; ) {
808 		if ((first = audiots_read_ac97(state, reg)) != 0) {
809 			next = first;
810 			break;
811 		}
812 
813 		delay = TS_DELAY_CNT;
814 		while (delay--) {
815 			(void) ddi_get16(handle, data);
816 		}
817 
818 		if ((next = audiots_read_ac97(state, reg)) != 0) {
819 			break;
820 		}
821 	}
822 
823 	/*
824 	 * Arggg, if you let the next read happen too soon then it fails.
825 	 * 12 usec fails, 13 usec succeeds. So set it to 20 for safety.
826 	 */
827 	drv_usecwait(TS_20US);
828 
829 	return (next);
830 
831 }
832 
833 /*
834  * audiots_init_state()
835  *
836  * Description:
837  *	This routine initializes the audio driver's state structure.
838  *	This includes reading the properties.
839  *
840  *	CAUTION: This routine cannot allocate resources, unless it frees
841  *		them before returning for an error. Also, error_destroy:
842  *		in audiots_attach() would need to be fixed as well.
843  *
844  *	NOTE: birdsnest supports CD ROM input. We check for the cdrom
845  *		property. If there we turn it on.
846  *
847  * Arguments:
848  *	audiots_state_t	*state		The device's state structure
849  *	dev_info_t	*dip		Pointer to the device's dev_info struct
850  *
851  * Returns:
852  *	DDI_SUCCESS			State structure initialized
853  *	DDI_FAILURE			State structure not initialized
854  */
855 static int
856 audiots_init_state(audiots_state_t *state, dev_info_t *dip)
857 {
858 	state->ts_ac97 = ac97_alloc(dip, audiots_get_ac97,
859 	    audiots_set_ac97, state);
860 
861 	if (state->ts_ac97 == NULL) {
862 		return (DDI_FAILURE);
863 	}
864 
865 	/* save the device info pointer */
866 	state->ts_dip = dip;
867 
868 	/* get the iblock cookie needed for interrupt context */
869 	if (ddi_get_iblock_cookie(dip, 0, &state->ts_iblock) != DDI_SUCCESS) {
870 		audio_dev_warn(state->ts_adev,
871 		    "cannot get iblock cookie");
872 		return (DDI_FAILURE);
873 	}
874 
875 	/* initialize the state mutexes and condition variables */
876 	mutex_init(&state->ts_lock, NULL, MUTEX_DRIVER, state->ts_iblock);
877 	state->ts_flags |= TS_MUTEX_INIT;
878 
879 	for (int i = 0; i < TS_NUM_PORTS; i++) {
880 		if (audiots_alloc_port(state, i) != DDI_SUCCESS) {
881 			return (DDI_FAILURE);
882 		}
883 	}
884 	/* init power management state */
885 	state->ts_suspended = B_FALSE;
886 
887 	return (DDI_SUCCESS);
888 
889 }
890 
891 /*
892  * audiots_intr()
893  *
894  * Description:
895  *	Interrupt service routine for both play and record. For play we
896  *	get the next buffers worth of audio. For record we send it on to
897  *	the mixer.
898  *
899  *	NOTE: This device needs to make sure any PIO access required to clear
900  *	its interrupt has made it out on the PCI bus before returning from its
901  *	interrupt handler so that the interrupt has been deasserted. This is
902  *	done by rereading the address engine interrupt register.
903  *
904  * Arguments:
905  *	caddr_t		T	Pointer to the interrupting device's state
906  *				structure
907  *
908  * Returns:
909  *	DDI_INTR_CLAIMED	Interrupt claimed and processed
910  *	DDI_INTR_UNCLAIMED	Interrupt not claimed, and thus ignored
911  */
912 static uint_t
913 audiots_intr(caddr_t T)
914 {
915 	audiots_state_t		*state = (void *)T;
916 	audiots_regs_t		*regs = state->ts_regs;
917 	ddi_acc_handle_t	handle = state->ts_acch;
918 	uint32_t		interrupts;
919 
920 	mutex_enter(&state->ts_lock);
921 
922 	if (state->ts_suspended) {
923 		mutex_exit(&state->ts_lock);
924 		return (DDI_INTR_UNCLAIMED);
925 	}
926 
927 	interrupts = ddi_get32(handle, &regs->aud_regs.ap_aint);
928 	if (interrupts == 0) {
929 		mutex_exit(&state->ts_lock);
930 		/* no interrupts to process, so it's not us */
931 		return (DDI_INTR_UNCLAIMED);
932 	}
933 
934 	/*
935 	 * Clear the interrupts to acknowledge.  Also, reread the
936 	 * interrupt reg to ensure that PIO write has completed.
937 	 */
938 	ddi_put32(handle, &regs->aud_regs.ap_aint, interrupts);
939 	(void) ddi_get32(handle, &regs->aud_regs.ap_aint);
940 
941 	/* update the kernel interrupt statistics */
942 	if (state->ts_ksp) {
943 		TS_KIOP(state)->intrs[KSTAT_INTR_HARD]++;
944 	}
945 
946 	mutex_exit(&state->ts_lock);
947 
948 	for (int i = 0; i < TS_NUM_PORTS; i++) {
949 		audiots_port_t	*port = state->ts_ports[i];
950 
951 		if (((interrupts & port->tp_int_mask) == 0) ||
952 		    (!port->tp_started))
953 			continue;
954 
955 		if (i == TS_INPUT_PORT) {
956 			audio_engine_produce(port->tp_engine);
957 		} else {
958 			audio_engine_consume(port->tp_engine);
959 		}
960 	}
961 
962 	return (DDI_INTR_CLAIMED);
963 
964 }
965 
966 /*
967  * audiots_map_regs()
968  *
969  * Description:
970  *	This routine maps the registers in.
971  *
972  *	Once the config space registers are mapped in we determine if the
973  *	audio core may be power managed. It should, but if it doesn't,
974  *	then trying to may cause the core to hang.
975  *
976  *	CAUTION: Make sure all errors call audio_dev_warn().
977  *
978  * Arguments:
979  *	dev_info_t	*dip            Pointer to the device's devinfo
980  *	audiots_state_t	*state          The device's state structure
981  * Returns:
982  *	DDI_SUCCESS		Registers successfully mapped
983  *	DDI_FAILURE		Registers not successfully mapped
984  */
985 static int
986 audiots_map_regs(dev_info_t *dip, audiots_state_t *state)
987 {
988 	char	rev[16];
989 	char	*name;
990 
991 	/* map in the registers, the config and memory mapped registers */
992 	if (pci_config_setup(dip, &state->ts_pcih) != DDI_SUCCESS) {
993 		audio_dev_warn(state->ts_adev,
994 		    "unable to map PCI configuration space");
995 		return (DDI_FAILURE);
996 	}
997 
998 	/* Read the Audio Controller's vendor, device, and revision IDs */
999 	state->ts_devid =
1000 	    (pci_config_get16(state->ts_pcih, PCI_CONF_VENID) << 16) |
1001 	    pci_config_get16(state->ts_pcih, PCI_CONF_DEVID);
1002 	state->ts_revid = pci_config_get8(state->ts_pcih, PCI_CONF_REVID);
1003 
1004 	if (ddi_regs_map_setup(dip, TS_MEM_MAPPED_REGS,
1005 	    (caddr_t *)&state->ts_regs, 0, 0, &ts_regs_attr, &state->ts_acch) !=
1006 	    DDI_SUCCESS) {
1007 		audio_dev_warn(state->ts_adev,
1008 		    "unable to map PCI device registers");
1009 		return (DDI_FAILURE);
1010 	}
1011 
1012 	switch (state->ts_devid) {
1013 	case 0x10b95451:
1014 		name = "ALI M5451";
1015 		break;
1016 	default:
1017 		name = "audiots";
1018 		break;
1019 	}
1020 	(void) snprintf(rev, sizeof (rev), "Rev %x", state->ts_revid);
1021 	audio_dev_set_description(state->ts_adev, name);
1022 	audio_dev_set_version(state->ts_adev, rev);
1023 
1024 	return (DDI_SUCCESS);
1025 }
1026 
1027 /*
1028  * audiots_alloc_port()
1029  *
1030  * Description:
1031  *	This routine allocates the DMA handles and the memory for the
1032  *	DMA engines to use. It then binds each of the buffers to its
1033  *	respective handle, getting a DMA cookie.
1034  *
1035  *	NOTE: All of the ddi_dma_... routines sleep if they cannot get
1036  *		memory. This means these calls should always succeed.
1037  *
1038  *	NOTE: ddi_dma_alloc_handle() attempts to use the full 4 GB DMA address
1039  *		range. This is to work around Southbridge rev E/G OBP issues.
1040  *		(See Grover OBP note above)
1041  *
1042  *	CAUTION: Make sure all errors call audio_dev_warn().
1043  *
1044  * Arguments:
1045  *	audiots_port_t	*state          The port structure for a device stream
1046  *	int		num		The port number
1047  *
1048  * Returns:
1049  *	DDI_SUCCESS		DMA resources mapped
1050  *	DDI_FAILURE		DMA resources not successfully mapped
1051  */
1052 int
1053 audiots_alloc_port(audiots_state_t *state, int num)
1054 {
1055 	audiots_port_t		*port;
1056 	dev_info_t		*dip = state->ts_dip;
1057 	audio_dev_t		*adev = state->ts_adev;
1058 	char			*prop;
1059 	int			dir;
1060 	unsigned		caps;
1061 	ddi_dma_cookie_t	cookie;
1062 	unsigned		count;
1063 	int			rc;
1064 	ddi_acc_handle_t	regsh = state->ts_acch;
1065 	uint32_t		*gcptr = &state->ts_regs->aud_regs.ap_cir_gc;
1066 
1067 	port = kmem_zalloc(sizeof (*port), KM_SLEEP);
1068 	state->ts_ports[num] = port;
1069 	port->tp_num = num;
1070 	port->tp_state = state;
1071 	port->tp_started = B_FALSE;
1072 	port->tp_rate = 48000;
1073 
1074 	if (num == TS_INPUT_PORT) {
1075 		prop = "record-interrupts";
1076 		dir = DDI_DMA_READ;
1077 		caps = ENGINE_INPUT_CAP;
1078 		port->tp_dma_stream = 31;
1079 		port->tp_int_stream = 2;
1080 		port->tp_sync_dir = DDI_DMA_SYNC_FORKERNEL;
1081 	} else {
1082 		prop = "play-interrupts";
1083 		dir = DDI_DMA_WRITE;
1084 		caps = ENGINE_OUTPUT_CAP;
1085 		port->tp_dma_stream = 0;
1086 		port->tp_int_stream = 1;
1087 		port->tp_sync_dir = DDI_DMA_SYNC_FORDEV;
1088 	}
1089 	port->tp_int_mask = (1U << port->tp_int_stream);
1090 	port->tp_dma_mask = (1U << port->tp_dma_stream);
1091 
1092 	/* get the number of interrupts per second */
1093 	port->tp_intrs = ddi_prop_get_int(DDI_DEV_T_ANY, dip,
1094 	    DDI_PROP_DONTPASS, prop, TS_INTS);
1095 
1096 	/* make sure the values are good */
1097 	if (port->tp_intrs < TS_MIN_INTS) {
1098 		audio_dev_warn(adev, "%s too low, %d, resetting to %d",
1099 		    prop, port->tp_intrs, TS_INTS);
1100 		port->tp_intrs = TS_INTS;
1101 	} else if (port->tp_intrs > TS_MAX_INTS) {
1102 		audio_dev_warn(adev, "%s too high, %d, resetting to %d",
1103 		    prop, port->tp_intrs, TS_INTS);
1104 		port->tp_intrs = TS_INTS;
1105 	}
1106 
1107 	/*
1108 	 * Now allocate space.  We configure for the worst case.  The
1109 	 * worst (biggest) case is 48000 kHz, at 4 bytes per frame
1110 	 * (16-bit stereo), with the lowest interrupt frequency.  We
1111 	 * need two fragments though, and each half has to be rounded
1112 	 * up to allow for alignment considerations.
1113 	 */
1114 
1115 	/* allocate dma handle */
1116 	rc = ddi_dma_alloc_handle(dip, &audiots_attr, DDI_DMA_SLEEP,
1117 	    NULL, &port->tp_dmah);
1118 	if (rc != DDI_SUCCESS) {
1119 		audio_dev_warn(adev, "ddi_dma_alloc_handle failed: %d", rc);
1120 		return (DDI_FAILURE);
1121 	}
1122 	/* allocate DMA buffer */
1123 	rc = ddi_dma_mem_alloc(port->tp_dmah, TS_BUFSZ, &ts_acc_attr,
1124 	    DDI_DMA_CONSISTENT, DDI_DMA_SLEEP, NULL, &port->tp_kaddr,
1125 	    &port->tp_size, &port->tp_acch);
1126 	if (rc == DDI_FAILURE) {
1127 		audio_dev_warn(adev, "dma_mem_alloc failed");
1128 		return (DDI_FAILURE);
1129 	}
1130 
1131 	/* bind DMA buffer */
1132 	rc = ddi_dma_addr_bind_handle(port->tp_dmah, NULL,
1133 	    port->tp_kaddr, port->tp_size, dir|DDI_DMA_CONSISTENT,
1134 	    DDI_DMA_SLEEP, NULL, &cookie, &count);
1135 	if (rc != DDI_DMA_MAPPED) {
1136 		audio_dev_warn(adev,
1137 		    "ddi_dma_addr_bind_handle failed: %d", rc);
1138 		return (DDI_FAILURE);
1139 	}
1140 	ASSERT(count == 1);
1141 
1142 	port->tp_paddr = cookie.dmac_address;
1143 	if ((unsigned)port->tp_paddr & 0x80000000U) {
1144 		ddi_put32(regsh, gcptr,
1145 		    ddi_get32(regsh, gcptr) | AP_CIR_GC_SYS_MEM_4G_ENABLE);
1146 	} else {
1147 		ddi_put32(regsh, gcptr,
1148 		    ddi_get32(regsh, gcptr) & ~(AP_CIR_GC_SYS_MEM_4G_ENABLE));
1149 	}
1150 	port->tp_engine = audio_engine_alloc(&audiots_engine_ops, caps);
1151 	if (port->tp_engine == NULL) {
1152 		audio_dev_warn(adev, "audio_engine_alloc failed");
1153 		return (DDI_FAILURE);
1154 	}
1155 
1156 	audio_engine_set_private(port->tp_engine, port);
1157 	audio_dev_add_engine(adev, port->tp_engine);
1158 
1159 	return (DDI_SUCCESS);
1160 }
1161 
1162 /*
1163  * audiots_read_ac97()
1164  *
1165  * Description:
1166  *	This routine actually reads the AC-97 Codec's register. It may
1167  *	be called several times to succeed.
1168  *
1169  * NOTE:
1170  * 	Revision M1535D B1-C of the ALI SouthBridge includes a workaround for
1171  *	the broken busy flag. Resetting the busy flag requires a software tweak
1172  *	to go with the worked around hardware. When we detect failure, we make
1173  *	10 attempts to reset the chip before we fail. This should reset the new
1174  *	SB systems. On all SB systems, this will increse the read delay
1175  *	slightly, but shouldn't bother it otherwise.
1176  *
1177  * Arguments:
1178  *	audiots_state_t	*state		The device's state structure
1179  *	int		reg		AC-97 register number
1180  *
1181  * Returns:
1182  *	unsigned short		The value in the specified register
1183  */
1184 static uint16_t
1185 audiots_read_ac97(audiots_state_t *state, int reg)
1186 {
1187 	ddi_acc_handle_t	acch = state->ts_acch;
1188 	uint16_t		*addr;
1189 	uint16_t		*data;
1190 	uint32_t		*stimer = &state->ts_regs->aud_regs.ap_stimer;
1191 	uint32_t		chk1;
1192 	uint32_t		chk2;
1193 	int			resets = 0;
1194 	int			i;
1195 
1196 	if (state->ts_revid == AC_REV_ID1) {
1197 		addr = &state->ts_regs->aud_regs.ap_acrd_35D_reg;
1198 		data = &state->ts_regs->aud_regs.ap_acrd_35D_data;
1199 	} else {
1200 		addr = &state->ts_regs->aud_regs.ap_acrdwr_reg;
1201 		data = &state->ts_regs->aud_regs.ap_acrdwr_data;
1202 	}
1203 
1204 first_read:
1205 	/* wait for ready to send read request */
1206 	for (i = 0; i < TS_READ_TRIES; i++) {
1207 		if (!(ddi_get16(acch, addr) & AP_ACRD_R_READ_BUSY)) {
1208 			break;
1209 		}
1210 		/* don't beat on the bus */
1211 		drv_usecwait(1);
1212 	}
1213 	if (i >= TS_READ_TRIES) {
1214 		if (resets < TS_RESET_TRIES) {
1215 			/* Attempt to reset */
1216 			drv_usecwait(TS_20US);
1217 			ddi_put16(acch, addr, TS_SB_RESET);
1218 			resets++;
1219 			goto first_read;
1220 		} else {
1221 			state->ts_flags |= TS_AUDIO_READ_FAILED;
1222 			if (!(state->ts_flags & TS_READ_FAILURE_PRINTED)) {
1223 				ddi_dev_report_fault(state->ts_dip,
1224 				    DDI_SERVICE_LOST, DDI_DEVICE_FAULT,
1225 				    "Unable to communicate with AC97 CODEC");
1226 				audio_dev_warn(state->ts_adev,
1227 				    "The audio AC97 register has timed out.");
1228 				audio_dev_warn(state->ts_adev,
1229 				    "Audio is now disabled.");
1230 				audio_dev_warn(state->ts_adev,
1231 				    "Please reboot to restore audio.");
1232 
1233 				/* Don't flood the console */
1234 				state->ts_flags |= TS_READ_FAILURE_PRINTED;
1235 			}
1236 		}
1237 		return (0);
1238 	}
1239 
1240 	/* program the register to read */
1241 	ddi_put16(acch, addr, (reg|AP_ACRD_W_PRIMARY_CODEC|
1242 	    AP_ACRD_W_READ_MIXER_REG|AP_ACRD_W_AUDIO_READ_REQ&
1243 	    (~AP_ACWR_W_SELECT_WRITE)));
1244 
1245 	/* hardware bug work around */
1246 	chk1 = ddi_get32(acch, stimer);
1247 	chk2 = ddi_get32(acch, stimer);
1248 	i = TS_WAIT_CNT;
1249 	while (chk1 == chk2 && i) {
1250 		chk2 = ddi_get32(acch, stimer);
1251 		i--;
1252 	}
1253 	OR_SET_SHORT(acch, addr, AP_ACRD_W_READ_MIXER_REG);
1254 	resets = 0;
1255 
1256 second_read:
1257 	/* wait again for read to send read request */
1258 	for (i = 0; i < TS_READ_TRIES; i++) {
1259 		if (!(ddi_get16(acch, addr) & AP_ACRD_R_READ_BUSY)) {
1260 			break;
1261 		}
1262 		/* don't beat on the bus */
1263 		drv_usecwait(1);
1264 	}
1265 	if (i >= TS_READ_TRIES) {
1266 		if (resets < TS_RESET_TRIES) {
1267 			/* Attempt to reset */
1268 			drv_usecwait(TS_20US);
1269 			ddi_put16(acch, addr, TS_SB_RESET);
1270 			resets++;
1271 			goto second_read;
1272 		} else {
1273 			state->ts_flags |= TS_AUDIO_READ_FAILED;
1274 			if (!(state->ts_flags & TS_READ_FAILURE_PRINTED)) {
1275 				ddi_dev_report_fault(state->ts_dip,
1276 				    DDI_SERVICE_LOST, DDI_DEVICE_FAULT,
1277 				    "Unable to communicate with AC97 CODEC");
1278 				audio_dev_warn(state->ts_adev,
1279 				    "The audio AC97 register has timed out.");
1280 				audio_dev_warn(state->ts_adev,
1281 				    "Audio is now disabled.");
1282 				audio_dev_warn(state->ts_adev,
1283 				    "Please reboot to restore audio.");
1284 
1285 				/* Don't flood the console */
1286 				state->ts_flags |= TS_READ_FAILURE_PRINTED;
1287 			}
1288 		}
1289 		return (0);
1290 	}
1291 
1292 	return (ddi_get16(acch, data));
1293 
1294 }	/* audiots_read_ac97() */
1295 
1296 /*
1297  * audiots_set_ac97()
1298  *
1299  * Description:
1300  *	Set the value in the specified AC-97 Codec register. Just like
1301  *	reading the AC-97 Codec, it is possible there is a problem writing
1302  *	it as well. So we loop.
1303  *
1304  * Arguments:
1305  *	audiots_state_t	*state		The device's state structure
1306  *	int		reg		AC-97 register number
1307  *	uint16_t	value		The value to write
1308  *
1309  * Returns:
1310  *	void
1311  */
1312 static void
1313 audiots_set_ac97(void *arg, uint8_t reg8, uint16_t data)
1314 {
1315 	audiots_state_t	*state = arg;
1316 	ddi_acc_handle_t handle = state->ts_acch;
1317 	uint16_t	*data_addr = &state->ts_regs->aud_regs.ap_acrdwr_data;
1318 	uint16_t	*reg_addr = &state->ts_regs->aud_regs.ap_acrdwr_reg;
1319 	int		count;
1320 	int		i;
1321 	uint16_t	tmp_short;
1322 	uint16_t	reg = reg8;
1323 
1324 	reg &= AP_ACWR_INDEX_MASK;
1325 
1326 	/* Don't touch the reserved bits on the pre 35D+ SouthBridge */
1327 	if (state->ts_revid == AC_REV_ID1) {
1328 		reg |= AP_ACWR_W_PRIMARY_CODEC|AP_ACWR_W_WRITE_MIXER_REG;
1329 	} else {
1330 		reg |= AP_ACWR_W_PRIMARY_CODEC|AP_ACWR_W_WRITE_MIXER_REG|
1331 		    AP_ACWR_W_SELECT_WRITE;
1332 	}
1333 
1334 	for (count = TS_LOOP_CNT; count--; ) {
1335 		/* wait for ready to write */
1336 		for (i = 0; i < TS_WAIT_CNT; i++) {
1337 			if (!(ddi_get16(handle, reg_addr) &
1338 			    AP_ACWR_R_WRITE_BUSY)) {
1339 				/* ready to write */
1340 				ddi_put16(handle, reg_addr, reg);
1341 
1342 				/* Write the data */
1343 				ddi_put16(handle, data_addr, data);
1344 				break;
1345 			}
1346 		}
1347 		if (i >= TS_WAIT_CNT) {
1348 			/* try again */
1349 			continue;
1350 		}
1351 
1352 		/* wait for write to complete */
1353 		for (i = 0; i < TS_WAIT_CNT; i++) {
1354 			if (!(ddi_get16(handle, reg_addr) &
1355 			    AP_ACWR_R_WRITE_BUSY)) {
1356 				/* done writing */
1357 				break;
1358 			}
1359 		}
1360 
1361 		/* verify the value written */
1362 		tmp_short = audiots_get_ac97(state, reg8);
1363 		if (data == tmp_short) {
1364 			/* successfully loaded, so we can return */
1365 			return;
1366 		}
1367 	}
1368 
1369 }	/* audiots_set_ac97() */
1370 
1371 /*
1372  * audiots_reset_port()
1373  *
1374  * Description:
1375  *	Initializes the hardware for a DMA engine.
1376  *	We only support stereo 16-bit linear PCM (signed native endian).
1377  *
1378  *	The audio core uses a single DMA buffer which is divided into two
1379  *	halves. An interrupt is generated when the middle of the buffer has
1380  *	been reached and at the end. The audio core resets the pointer back
1381  *	to the beginning automatically. After the interrupt the driver clears
1382  *	the buffer and asks the mixer for more audio samples. If there aren't
1383  *	enough then silence is played out.
1384  *
1385  * Arguments:
1386  *	audiots_port_t	*port		The DMA engine to reset
1387  *
1388  * Returns:
1389  *	void
1390  */
1391 static void
1392 audiots_reset_port(audiots_port_t *port)
1393 {
1394 	audiots_state_t		*state = port->tp_state;
1395 	ddi_acc_handle_t	handle = state->ts_acch;
1396 	audiots_regs_t		*regs = state->ts_regs;
1397 	audiots_aram_t		*aram;
1398 	audiots_eram_t		*eram;
1399 	unsigned		delta;
1400 	uint16_t		ctrl;
1401 	uint16_t		gvsel;
1402 	uint16_t		eso;
1403 
1404 	if (state->ts_suspended)
1405 		return;
1406 
1407 	port->tp_cso = 0;
1408 
1409 	gvsel = ERAM_WAVE_VOL | ERAM_PAN_0dB | ERAM_VOL_DEFAULT;
1410 	ctrl = ERAM_16_BITS | ERAM_STEREO | ERAM_LOOP_MODE | ERAM_SIGNED_PCM;
1411 	for (int i = 0; i < 2; i++) {
1412 
1413 		delta = (port->tp_rate << TS_SRC_SHIFT) / TS_RATE;
1414 
1415 		if (i == 0) {
1416 			/* first do the DMA stream */
1417 			aram = &regs->aud_ram[port->tp_dma_stream].aram;
1418 			eram = &regs->aud_ram[port->tp_dma_stream].eram;
1419 			if (port->tp_num == TS_INPUT_PORT) {
1420 				delta = (TS_RATE << TS_SRC_SHIFT) /
1421 				    port->tp_rate;
1422 			}
1423 			eso = port->tp_nframes - 1;
1424 		} else {
1425 			/* else do the interrupt stream */
1426 			aram = &regs->aud_ram[port->tp_int_stream].aram;
1427 			eram = &regs->aud_ram[port->tp_int_stream].eram;
1428 			/* interrupt stream is silent */
1429 			gvsel |= ERAM_VOL_MAX_ATTEN;
1430 			eso = port->tp_fragfr - 1;
1431 		}
1432 
1433 		/* program the sample rate */
1434 		ddi_put16(handle, &aram->aram_delta, (uint16_t)delta);
1435 
1436 		/* program the precision, number of channels and loop mode */
1437 		ddi_put16(handle, &eram->eram_ctrl_ec, ctrl);
1438 
1439 		/* program the volume settings */
1440 		ddi_put16(handle, &eram->eram_gvsel_pan_vol, gvsel);
1441 
1442 		/* set ALPHA and FMS to 0 */
1443 		ddi_put16(handle, &aram->aram_alpha_fms, 0x0);
1444 
1445 		/* set CSO to 0 */
1446 		ddi_put16(handle, &aram->aram_cso, 0x0);
1447 
1448 		/* set LBA */
1449 		ddi_put32(handle, &aram->aram_cptr_lba,
1450 		    port->tp_paddr & ARAM_LBA_MASK);
1451 
1452 		/* set ESO */
1453 		ddi_put16(handle, &aram->aram_eso, eso);
1454 	}
1455 
1456 	/* stop the DMA & interrupt engines */
1457 	ddi_put32(handle, &regs->aud_regs.ap_stop,
1458 	    port->tp_int_mask | port->tp_dma_mask);
1459 
1460 	/* enable interrupts */
1461 	OR_SET_WORD(handle, &regs->aud_regs.ap_ainten, port->tp_int_mask);
1462 }
1463 
1464 /*
1465  * audiots_open()
1466  *
1467  * Description:
1468  *	Opens a DMA engine for use.  Will also ensure the device is powered
1469  *	up if not already done so.
1470  *
1471  * Arguments:
1472  *	void		*arg		The DMA engine to set up
1473  *	int		flag		Open flags
1474  *	unsigned	*fragfrp	Receives number of frames per fragment
1475  *	unsigned	*nfragsp	Receives number of fragments
1476  *	caddr_t		*bufp		Receives kernel data buffer
1477  *
1478  * Returns:
1479  *	0	on success
1480  *	errno	on failure
1481  */
1482 static int
1483 audiots_open(void *arg, int flag,
1484     unsigned *fragfrp, unsigned *nfragsp, caddr_t *bufp)
1485 {
1486 	audiots_port_t	*port = arg;
1487 	unsigned	nfrag;
1488 
1489 	_NOTE(ARGUNUSED(flag));
1490 
1491 	/*
1492 	 * Round up - we have to have a sample that is a whole number
1493 	 * of 64-bit words.  Since our frames are 4 bytes wide, we
1494 	 * just need an even number of frames.
1495 	 */
1496 	port->tp_fragfr = port->tp_rate / port->tp_intrs;
1497 	port->tp_fragfr = (port->tp_fragfr + 1) & ~1;
1498 	nfrag = port->tp_size / (port->tp_fragfr * TS_FRAMESZ);
1499 	port->tp_nframes = nfrag * port->tp_fragfr;
1500 	port->tp_started = B_FALSE;
1501 	port->tp_count = 0;
1502 	port->tp_cso = 0;
1503 	*fragfrp = port->tp_fragfr;
1504 	*nfragsp = nfrag;
1505 	*bufp = port->tp_kaddr;
1506 
1507 	/*
1508 	 * This should always be true because we used a worst case
1509 	 * assumption when calculating the port->tp_size.
1510 	 */
1511 	ASSERT((port->tp_fragfr * nfrag) <= port->tp_size);
1512 
1513 	mutex_enter(&port->tp_state->ts_lock);
1514 	audiots_reset_port(port);
1515 	mutex_exit(&port->tp_state->ts_lock);
1516 
1517 	return (0);
1518 }
1519 
1520 /*
1521  * audiots_close()
1522  *
1523  * Description:
1524  *	Closes an audio DMA engine that was previously opened.  Since
1525  *	nobody is using it, we take this opportunity to possibly power
1526  *	down the entire device.
1527  *
1528  * Arguments:
1529  *	void	*arg		The DMA engine to shut down
1530  *
1531  * Returns:
1532  *	void
1533  */
1534 static void
1535 audiots_close(void *arg)
1536 {
1537 	audiots_port_t	*port = arg;
1538 	audiots_state_t	*state = port->tp_state;
1539 
1540 	mutex_enter(&state->ts_lock);
1541 	audiots_stop_port(port);
1542 	port->tp_started = B_FALSE;
1543 	mutex_exit(&state->ts_lock);
1544 }
1545 
1546 /*
1547  * audiots_stop()
1548  *
1549  * Description:
1550  *	This is called by the framework to stop a port that is
1551  *	transferring data.
1552  *
1553  * Arguments:
1554  *	void	*arg		The DMA engine to stop
1555  *
1556  * Returns:
1557  *	void
1558  */
1559 static void
1560 audiots_stop(void *arg)
1561 {
1562 	audiots_port_t	*port = arg;
1563 	audiots_state_t	*state = port->tp_state;
1564 
1565 	mutex_enter(&state->ts_lock);
1566 	if (port->tp_started) {
1567 		audiots_stop_port(port);
1568 	}
1569 	port->tp_started = B_FALSE;
1570 	mutex_exit(&state->ts_lock);
1571 }
1572 
1573 /*
1574  * audiots_start()
1575  *
1576  * Description:
1577  *	This is called by the framework to start a port transferring data.
1578  *
1579  * Arguments:
1580  *	void	*arg		The DMA engine to start
1581  *
1582  * Returns:
1583  *	0 	on success (never fails, errno if it did)
1584  */
1585 static int
1586 audiots_start(void *arg)
1587 {
1588 	audiots_port_t	*port = arg;
1589 	audiots_state_t	*state = port->tp_state;
1590 
1591 	mutex_enter(&state->ts_lock);
1592 	if (!port->tp_started) {
1593 		audiots_start_port(port);
1594 		port->tp_started = B_TRUE;
1595 	}
1596 	mutex_exit(&state->ts_lock);
1597 	return (0);
1598 }
1599 
1600 /*
1601  * audiots_chinfo()
1602  *
1603  * Description:
1604  *	This is called by the framework to query the channel offsets
1605  *	and ordering.
1606  *
1607  * Arguments:
1608  *	void	*arg		The DMA engine to query
1609  *	int	chan		Channel number.
1610  *	unsigned *offset	Starting offset of channel.
1611  *	unsigned *incr		Increment (in samples) between frames.
1612  *
1613  * Returns:
1614  *	0 indicating rate array is range instead of enumeration
1615  */
1616 
1617 static void
1618 audiots_chinfo(void *arg, int chan, unsigned *offset, unsigned *incr)
1619 {
1620 	_NOTE(ARGUNUSED(arg));
1621 	*offset = chan;
1622 	*incr = 2;
1623 }
1624 
1625 /*
1626  * audiots_format()
1627  *
1628  * Description:
1629  *	Called by the framework to query the format for the device.
1630  *
1631  * Arguments:
1632  *	void	*arg		The DMA engine to query
1633  *
1634  * Returns:
1635  *	AUDIO_FORMAT_S16_LE.
1636  */
1637 static int
1638 audiots_format(void *arg)
1639 {
1640 	_NOTE(ARGUNUSED(arg));
1641 
1642 	return (AUDIO_FORMAT_S16_LE);
1643 }
1644 
1645 
1646 /*
1647  * audiots_channels()
1648  *
1649  * Description:
1650  *	Called by the framework to query the channnels for the device.
1651  *
1652  * Arguments:
1653  *	void	*arg		The DMA engine to query
1654  *
1655  * Returns:
1656  *	2 (Stereo).
1657  */
1658 static int
1659 audiots_channels(void *arg)
1660 {
1661 	_NOTE(ARGUNUSED(arg));
1662 
1663 	return (2);
1664 }
1665 
1666 /*
1667  * audiots_rate()
1668  *
1669  * Description:
1670  *	Called by the framework to query the sample rates for the device.
1671  *
1672  * Arguments:
1673  *	void	*arg		The DMA engine to query
1674  *
1675  * Returns:
1676  *	Sample rate in HZ (always 48000).
1677  */
1678 static int
1679 audiots_rate(void *arg)
1680 {
1681 	audiots_port_t *port = arg;
1682 
1683 	return (port->tp_rate);
1684 }
1685 
1686 /*
1687  * audiots_count()
1688  *
1689  * Description:
1690  *	This is called by the framework to get the engine's frame counter
1691  *
1692  * Arguments:
1693  *	void	*arg		The DMA engine to query
1694  *
1695  * Returns:
1696  *	frame count for current engine
1697  */
1698 static uint64_t
1699 audiots_count(void *arg)
1700 {
1701 	audiots_port_t	*port = arg;
1702 	audiots_state_t	*state = port->tp_state;
1703 	uint64_t	val;
1704 
1705 	mutex_enter(&state->ts_lock);
1706 	audiots_update_port(port);
1707 
1708 	val = port->tp_count;
1709 	mutex_exit(&state->ts_lock);
1710 	return (val);
1711 }
1712 
1713 /*
1714  * audiots_sync()
1715  *
1716  * Description:
1717  *	This is called by the framework to synchronize DMA caches.
1718  *	We also leverage this do some endian swapping, because on SPARC
1719  *	the chip accesses the DMA region using 32-bit little-endian
1720  *	accesses.  Its not enough to just use the framework's sample
1721  *	conversion logic, because the channels will also be backwards.
1722  *
1723  * Arguments:
1724  *	void	*arg		The DMA engine to sync
1725  *
1726  * Returns:
1727  *	void
1728  */
1729 static void
1730 audiots_sync(void *arg, unsigned nframes)
1731 {
1732 	audiots_port_t *port = arg;
1733 	_NOTE(ARGUNUSED(nframes));
1734 
1735 	(void) ddi_dma_sync(port->tp_dmah, 0, 0, port->tp_sync_dir);
1736 }
1737 
1738 /*
1739  * audiots_qlen()
1740  *
1741  * Description:
1742  *	This is called by the framework to determine on-device queue length.
1743  *
1744  * Arguments:
1745  *	void	*arg		The DMA engine to query
1746  *
1747  * Returns:
1748  *	hardware queue length not reported by count (0 for this device)
1749  */
1750 static size_t
1751 audiots_qlen(void *arg)
1752 {
1753 	_NOTE(ARGUNUSED(arg));
1754 	return (0);
1755 }
1756 
1757 /*
1758  * audiots_start_port()
1759  *
1760  * Description:
1761  *	The audio core uses a single DMA buffer which is divided into two
1762  *	halves. An interrupt is generated when the middle of the buffer has
1763  *	been reached and at the end. The audio core resets the pointer back
1764  *	to the beginning automatically. After the interrupt the driver clears
1765  *	the buffer and asks the mixer for more audio samples. If there aren't
1766  *	enough then silence is played out.
1767  *
1768  * Arguments:
1769  *	audiots_port_t	*port		The DMA engine to start up
1770  *
1771  * Returns:
1772  *	void
1773  */
1774 static void
1775 audiots_start_port(audiots_port_t *port)
1776 {
1777 	audiots_state_t		*state = port->tp_state;
1778 	audiots_regs_t		*regs = state->ts_regs;
1779 	ddi_acc_handle_t	handle = state->ts_acch;
1780 
1781 	ASSERT(mutex_owned(&state->ts_lock));
1782 
1783 	/* if suspended then do nothing else */
1784 	if (state->ts_suspended)  {
1785 		return;
1786 	}
1787 
1788 	/* make sure it starts playing */
1789 	ddi_put32(handle, &regs->aud_regs.ap_start,
1790 	    port->tp_dma_mask | port->tp_int_mask);
1791 
1792 	ASSERT(mutex_owned(&state->ts_lock));
1793 }
1794 
1795 /*
1796  * audiots_stop_port()
1797  *
1798  * Description:
1799  *	This routine stops a DMA engine.
1800  *
1801  * Arguments:
1802  *	audiots_port_t	*port		The port to stop
1803  *
1804  * Returns:
1805  *	void
1806  */
1807 static void
1808 audiots_stop_port(audiots_port_t *port)
1809 {
1810 	audiots_state_t *state = port->tp_state;
1811 
1812 	ASSERT(mutex_owned(&state->ts_lock));
1813 
1814 	if (state->ts_suspended)
1815 		return;
1816 
1817 	ddi_put32(state->ts_acch, &state->ts_regs->aud_regs.ap_stop,
1818 	    port->tp_int_mask | port->tp_dma_mask);
1819 
1820 	ASSERT(mutex_owned(&state->ts_lock));
1821 }
1822 
1823 /*
1824  * audiots_update_port()
1825  *
1826  * Description:
1827  *	This routine updates the ports frame counter from hardware, and
1828  *	gracefully handles wraps.
1829  *
1830  * Arguments:
1831  *	audiots_port_t	*port		The port to stop
1832  *
1833  * Returns:
1834  *	void
1835  */
1836 static void
1837 audiots_update_port(audiots_port_t *port)
1838 {
1839 	audiots_state_t		*state = port->tp_state;
1840 
1841 	uint16_t		cso;
1842 	unsigned		n;
1843 
1844 	ASSERT(mutex_owned(&state->ts_lock));
1845 
1846 	if (state->ts_suspended)
1847 		return;
1848 
1849 	cso = ddi_get16(state->ts_acch,
1850 	    &state->ts_regs->aud_ram[port->tp_dma_stream].aram.aram_cso);
1851 
1852 	n = (cso >= port->tp_cso) ?
1853 	    cso - port->tp_cso :
1854 	    cso + port->tp_nframes - port->tp_cso;
1855 
1856 	port->tp_cso = cso;
1857 	port->tp_count += n;
1858 }
1859 
1860 /*
1861  * audiots_stop_everything()
1862  *
1863  * Description:
1864  *	This routine disables the address engine interrupt for all 32 DMA
1865  *	engines. Just to be sure, it then explicitly issues a stop command to
1866  *	the address engine and envelope engines for all 32 channels.
1867  *
1868  * NOTE:
1869  *
1870  * 	There is a hardware bug that generates a spurious interrupt
1871  *	when the DMA engines are stopped. It's not consistent - it
1872  *	happens every 1 out of 6 stops or so. It will show up as a
1873  *	record interrupt. The problem is that once the driver is
1874  *	detached or if the system goes into low power mode, nobody
1875  *	will service that interrupt. The system will eventually become
1876  *	unusable.
1877  *
1878  * Arguments:
1879  *	audiots_state_t	*state		The device's state structure
1880  *
1881  * Returns:
1882  *	void
1883  */
1884 static void
1885 audiots_stop_everything(audiots_state_t *state)
1886 {
1887 	if (state->ts_acch == NULL)
1888 		return;
1889 
1890 	ddi_put32(state->ts_acch, &state->ts_regs->aud_regs.ap_ainten,
1891 	    TS_ALL_DMA_OFF);
1892 
1893 	ddi_put32(state->ts_acch, &state->ts_regs->aud_regs.ap_stop,
1894 	    TS_ALL_DMA_ENGINES);
1895 
1896 	ddi_put32(state->ts_acch, &state->ts_regs->aud_regs.ap_aint,
1897 	    TS_ALL_DMA_ENGINES);
1898 }
1899 
1900 /*
1901  * audiots_free_port()
1902  *
1903  * Description:
1904  *	This routine unbinds the DMA cookies, frees the DMA buffers,
1905  *	deallocates the DMA handles.
1906  *
1907  * Arguments:
1908  *	audiots_port_t	*port	The port structure for a device stream.
1909  *
1910  * Returns:
1911  *	None
1912  */
1913 void
1914 audiots_free_port(audiots_port_t *port)
1915 {
1916 	if (port == NULL)
1917 		return;
1918 
1919 	if (port->tp_engine) {
1920 		audio_dev_remove_engine(port->tp_state->ts_adev,
1921 		    port->tp_engine);
1922 		audio_engine_free(port->tp_engine);
1923 	}
1924 	if (port->tp_paddr) {
1925 		(void) ddi_dma_unbind_handle(port->tp_dmah);
1926 	}
1927 	if (port->tp_acch) {
1928 		ddi_dma_mem_free(&port->tp_acch);
1929 	}
1930 	if (port->tp_dmah) {
1931 		ddi_dma_free_handle(&port->tp_dmah);
1932 	}
1933 	kmem_free(port, sizeof (*port));
1934 }
1935 
1936 /*
1937  * audiots_destroy()
1938  *
1939  * Description:
1940  *	This routine releases all resources held by the device instance,
1941  *	as part of either detach or a failure in attach.
1942  *
1943  * Arguments:
1944  *	audiots_state_t	*state	The device soft state.
1945  *
1946  * Returns:
1947  *	None
1948  */
1949 void
1950 audiots_destroy(audiots_state_t *state)
1951 {
1952 	audiots_stop_everything(state);
1953 
1954 	if (state->ts_flags & TS_INTR_INSTALLED)
1955 		ddi_remove_intr(state->ts_dip, 0, NULL);
1956 
1957 	if (state->ts_ksp)
1958 		kstat_delete(state->ts_ksp);
1959 
1960 	for (int i = 0; i < TS_NUM_PORTS; i++)
1961 		audiots_free_port(state->ts_ports[i]);
1962 
1963 	if (state->ts_acch)
1964 		ddi_regs_map_free(&state->ts_acch);
1965 
1966 	if (state->ts_pcih)
1967 		pci_config_teardown(&state->ts_pcih);
1968 
1969 	if (state->ts_ac97)
1970 		ac97_free(state->ts_ac97);
1971 
1972 	if (state->ts_adev)
1973 		audio_dev_free(state->ts_adev);
1974 
1975 	if (state->ts_flags & TS_MUTEX_INIT) {
1976 		mutex_destroy(&state->ts_lock);
1977 	}
1978 
1979 	ddi_soft_state_free(audiots_statep, ddi_get_instance(state->ts_dip));
1980 }
1981