xref: /netbsd-src/sys/dev/pci/auich.c (revision 7330f729ccf0bd976a06f95fad452fe774fc7fd1)
1 /*	$NetBSD: auich.c,v 1.157 2019/06/08 08:02:38 isaki Exp $	*/
2 
3 /*-
4  * Copyright (c) 2000, 2004, 2005, 2008 The NetBSD Foundation, Inc.
5  * All rights reserved.
6  *
7  * This code is derived from software contributed to The NetBSD Foundation
8  * by Jason R. Thorpe and by Charles M. Hannum.
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  * Copyright (c) 2000 Michael Shalayeff
34  * All rights reserved.
35  *
36  * Redistribution and use in source and binary forms, with or without
37  * modification, are permitted provided that the following conditions
38  * are met:
39  * 1. Redistributions of source code must retain the above copyright
40  *    notice, this list of conditions and the following disclaimer.
41  * 2. Redistributions in binary form must reproduce the above copyright
42  *    notice, this list of conditions and the following disclaimer in the
43  *    documentation and/or other materials provided with the distribution.
44  * 3. The name of the author may not be used to endorse or promote products
45  *    derived from this software without specific prior written permission.
46  *
47  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
48  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
49  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
50  * IN NO EVENT SHALL THE AUTHOR OR HIS RELATIVES BE LIABLE FOR ANY DIRECT,
51  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
52  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
53  * SERVICES; LOSS OF MIND, USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
54  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
55  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
56  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
57  * THE POSSIBILITY OF SUCH DAMAGE.
58  *
59  *	from OpenBSD: ich.c,v 1.3 2000/08/11 06:17:18 mickey Exp
60  */
61 
62 /*
63  * Copyright (c) 2000 Katsurajima Naoto <raven@katsurajima.seya.yokohama.jp>
64  * Copyright (c) 2001 Cameron Grant <cg@freebsd.org>
65  * All rights reserved.
66  *
67  * Redistribution and use in source and binary forms, with or without
68  * modification, are permitted provided that the following conditions
69  * are met:
70  * 1. Redistributions of source code must retain the above copyright
71  *    notice, this list of conditions and the following disclaimer.
72  * 2. Redistributions in binary form must reproduce the above copyright
73  *    notice, this list of conditions and the following disclaimer in the
74  *    documentation and/or other materials provided with the distribution.
75  *
76  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
77  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
78  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
79  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
80  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
81  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
82  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
83  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHERIN CONTRACT, STRICT
84  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
85  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THEPOSSIBILITY OF
86  * SUCH DAMAGE.
87  *
88  * auich_calibrate() was from FreeBSD: ich.c,v 1.22 2002/06/27 22:36:01 scottl Exp
89  */
90 
91 
92 /* #define	AUICH_DEBUG */
93 /*
94  * AC'97 audio found on Intel 810/820/440MX chipsets.
95  *	http://developer.intel.com/design/chipsets/datashts/290655.htm
96  *	http://developer.intel.com/design/chipsets/manuals/298028.htm
97  * ICH3:http://www.intel.com/design/chipsets/datashts/290716.htm
98  * ICH4:http://www.intel.com/design/chipsets/datashts/290744.htm
99  * ICH5:http://www.intel.com/design/chipsets/datashts/252516.htm
100  * AMD8111:
101  *	http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/24674.pdf
102  *	http://www.amd.com/us-en/assets/content_type/white_papers_and_tech_docs/25720.pdf
103  *
104  * TODO:
105  *	- Add support for the dedicated microphone input.
106  *
107  * NOTE:
108  *      - The 440MX B-stepping at running 100MHz has a hardware erratum.
109  *        It causes PCI master abort and hangups until cold reboot.
110  *        http://www.intel.com/design/chipsets/specupdt/245051.htm
111  */
112 
113 #include <sys/cdefs.h>
114 __KERNEL_RCSID(0, "$NetBSD: auich.c,v 1.157 2019/06/08 08:02:38 isaki Exp $");
115 
116 #include <sys/param.h>
117 #include <sys/systm.h>
118 #include <sys/kernel.h>
119 #include <sys/kmem.h>
120 #include <sys/device.h>
121 #include <sys/fcntl.h>
122 #include <sys/proc.h>
123 #include <sys/sysctl.h>
124 #include <sys/audioio.h>
125 #include <sys/bus.h>
126 #include <sys/rndsource.h>
127 
128 #include <dev/pci/pcidevs.h>
129 #include <dev/pci/pcivar.h>
130 #include <dev/pci/auichreg.h>
131 
132 #include <dev/audio/audio_if.h>
133 
134 #include <dev/ic/ac97reg.h>
135 #include <dev/ic/ac97var.h>
136 
137 struct auich_dma {
138 	bus_dmamap_t map;
139 	void *addr;
140 	bus_dma_segment_t segs[1];
141 	int nsegs;
142 	size_t size;
143 	struct auich_dma *next;
144 };
145 
146 #define	DMAADDR(p)	((p)->map->dm_segs[0].ds_addr)
147 #define	KERNADDR(p)	((void *)((p)->addr))
148 
149 struct auich_cdata {
150 	struct auich_dmalist ic_dmalist_pcmo[ICH_DMALIST_MAX];
151 	struct auich_dmalist ic_dmalist_pcmi[ICH_DMALIST_MAX];
152 	struct auich_dmalist ic_dmalist_mici[ICH_DMALIST_MAX];
153 };
154 
155 #define	ICH_CDOFF(x)		offsetof(struct auich_cdata, x)
156 #define	ICH_PCMO_OFF(x)		ICH_CDOFF(ic_dmalist_pcmo[(x)])
157 #define	ICH_PCMI_OFF(x)		ICH_CDOFF(ic_dmalist_pcmi[(x)])
158 #define	ICH_MICI_OFF(x)		ICH_CDOFF(ic_dmalist_mici[(x)])
159 
160 struct auich_softc {
161 	device_t sc_dev;
162 	void *sc_ih;
163 	kmutex_t sc_lock;
164 	kmutex_t sc_intr_lock;
165 
166 	device_t sc_audiodev;
167 	audio_device_t sc_audev;
168 
169 	pci_chipset_tag_t sc_pc;
170 	pcitag_t sc_pt;
171 	bus_space_tag_t iot;
172 	bus_space_handle_t mix_ioh;
173 	bus_size_t mix_size;
174 	bus_space_handle_t aud_ioh;
175 	bus_size_t aud_size;
176 	bus_dma_tag_t dmat;
177 	pci_intr_handle_t intrh;
178 
179 	struct ac97_codec_if *codec_if;
180 	struct ac97_host_if host_if;
181 	int sc_codecnum;
182 	int sc_codectype;
183 	int sc_fixedrate;
184 	enum ac97_host_flags sc_codecflags;
185 	bool sc_spdif;
186 
187 	/* multi-channel control bits */
188 	int sc_pcm246_mask;
189 	int sc_pcm2;
190 	int sc_pcm4;
191 	int sc_pcm6;
192 
193 	/* DMA scatter-gather lists. */
194 	bus_dmamap_t sc_cddmamap;
195 #define	sc_cddma	sc_cddmamap->dm_segs[0].ds_addr
196 
197 	struct auich_cdata *sc_cdata;
198 
199 	struct auich_ring {
200 		int qptr;
201 		struct auich_dmalist *dmalist;
202 
203 		uint32_t start, p, end;
204 		int blksize;
205 
206 		void (*intr)(void *);
207 		void *arg;
208 	} pcmo, pcmi, mici;
209 
210 	struct auich_dma *sc_dmas;
211 
212 	/* SiS 7012 hack */
213 	int  sc_sample_shift;
214 	int  sc_sts_reg;
215 	/* 440MX workaround */
216 	int  sc_dmamap_flags;
217 	/* flags */
218 	int  sc_iose	:1,
219 		     	:31;
220 
221 	/* sysctl */
222 	struct sysctllog *sc_log;
223 	uint32_t sc_ac97_clock;
224 	int sc_ac97_clock_mib;
225 
226 	int	sc_modem_offset;
227 
228 #define AUICH_AUDIO_NFORMATS	3
229 #define AUICH_MODEM_NFORMATS	1
230 	struct audio_format sc_audio_formats[AUICH_AUDIO_NFORMATS];
231 	struct audio_format sc_modem_formats[AUICH_MODEM_NFORMATS];
232 
233 	int sc_cas_been_used;
234 };
235 
236 /* Debug */
237 #ifdef AUICH_DEBUG
238 #define	DPRINTF(l,x)	do { if (auich_debug & (l)) aprint_normal_dev x; } while(0)
239 int auich_debug = 0xfffe;
240 #define	ICH_DEBUG_CODECIO	0x0001
241 #define	ICH_DEBUG_DMA		0x0002
242 #define	ICH_DEBUG_INTR		0x0004
243 #else
244 #define	DPRINTF(x,y)	/* nothing */
245 #endif
246 
247 static int	auich_match(device_t, cfdata_t, void *);
248 static void	auich_attach(device_t, device_t, void *);
249 static int	auich_detach(device_t, int);
250 static void	auich_childdet(device_t, device_t);
251 static int	auich_intr(void *);
252 
253 CFATTACH_DECL2_NEW(auich, sizeof(struct auich_softc),
254     auich_match, auich_attach, auich_detach, NULL, NULL, auich_childdet);
255 
256 static int	auich_open(void *, int);
257 static void	auich_close(void *);
258 static int	auich_query_format(void *, struct audio_format_query *);
259 static int	auich_set_format(void *, int,
260 		    const audio_params_t *, const audio_params_t *,
261 		    audio_filter_reg_t *, audio_filter_reg_t *);
262 static int	auich_round_blocksize(void *, int, int, const audio_params_t *);
263 static void	auich_halt_pipe(struct auich_softc *, int);
264 static int	auich_halt_output(void *);
265 static int	auich_halt_input(void *);
266 static int	auich_getdev(void *, struct audio_device *);
267 static int	auich_set_port(void *, mixer_ctrl_t *);
268 static int	auich_get_port(void *, mixer_ctrl_t *);
269 static int	auich_query_devinfo(void *, mixer_devinfo_t *);
270 static void	*auich_allocm(void *, int, size_t);
271 static void	auich_freem(void *, void *, size_t);
272 static size_t	auich_round_buffersize(void *, int, size_t);
273 static int	auich_get_props(void *);
274 static void	auich_trigger_pipe(struct auich_softc *, int, struct auich_ring *);
275 static void	auich_intr_pipe(struct auich_softc *, int, struct auich_ring *);
276 static int	auich_trigger_output(void *, void *, void *, int,
277 		    void (*)(void *), void *, const audio_params_t *);
278 static int	auich_trigger_input(void *, void *, void *, int,
279 		    void (*)(void *), void *, const audio_params_t *);
280 static void	auich_get_locks(void *, kmutex_t **, kmutex_t **);
281 
282 static int	auich_alloc_cdata(struct auich_softc *);
283 
284 static int	auich_allocmem(struct auich_softc *, size_t, size_t,
285 		    struct auich_dma *);
286 static int	auich_freemem(struct auich_softc *, struct auich_dma *);
287 
288 static bool	auich_resume(device_t, const pmf_qual_t *);
289 static int	auich_set_rate(struct auich_softc *, int, u_long);
290 static int	auich_sysctl_verify(SYSCTLFN_ARGS);
291 static void	auich_finish_attach(device_t);
292 static void	auich_calibrate(struct auich_softc *);
293 static void	auich_clear_cas(struct auich_softc *);
294 
295 static int	auich_attach_codec(void *, struct ac97_codec_if *);
296 static int	auich_read_codec(void *, uint8_t, uint16_t *);
297 static int	auich_write_codec(void *, uint8_t, uint16_t);
298 static int	auich_reset_codec(void *);
299 static enum ac97_host_flags	auich_flags_codec(void *);
300 static void	auich_spdif_event(void *, bool);
301 
302 static const struct audio_hw_if auich_hw_if = {
303 	.open			= auich_open,
304 	.close			= auich_close,
305 	.query_format		= auich_query_format,
306 	.set_format		= auich_set_format,
307 	.round_blocksize	= auich_round_blocksize,
308 	.halt_output		= auich_halt_output,
309 	.halt_input		= auich_halt_input,
310 	.getdev			= auich_getdev,
311 	.set_port		= auich_set_port,
312 	.get_port		= auich_get_port,
313 	.query_devinfo		= auich_query_devinfo,
314 	.allocm			= auich_allocm,
315 	.freem			= auich_freem,
316 	.round_buffersize	= auich_round_buffersize,
317 	.get_props		= auich_get_props,
318 	.trigger_output		= auich_trigger_output,
319 	.trigger_input		= auich_trigger_input,
320 	.get_locks		= auich_get_locks,
321 };
322 
323 #define AUICH_FORMATS_1CH	0
324 #define AUICH_FORMATS_4CH	1
325 #define AUICH_FORMATS_6CH	2
326 #define AUICH_FORMAT(aumode, ch, chmask) \
327 	{ \
328 		.mode		= (aumode), \
329 		.encoding	= AUDIO_ENCODING_SLINEAR_LE, \
330 		.validbits	= 16, \
331 		.precision	= 16, \
332 		.channels	= (ch), \
333 		.channel_mask	= (chmask), \
334 		.frequency_type	= 0, \
335 		.frequency	= { 8000, 48000 }, \
336 	}
337 static const struct audio_format auich_audio_formats[AUICH_AUDIO_NFORMATS] = {
338 	AUICH_FORMAT(AUMODE_PLAY | AUMODE_RECORD, 2, AUFMT_STEREO),
339 	AUICH_FORMAT(AUMODE_PLAY                , 4, AUFMT_SURROUND4),
340 	AUICH_FORMAT(AUMODE_PLAY                , 6, AUFMT_DOLBY_5_1),
341 };
342 
343 #define AUICH_SPDIF_NFORMATS	1
344 static const struct audio_format auich_spdif_formats[AUICH_SPDIF_NFORMATS] = {
345 	{
346 		.mode		= AUMODE_PLAY | AUMODE_RECORD,
347 		.encoding	= AUDIO_ENCODING_SLINEAR_LE,
348 		.validbits	= 16,
349 		.precision	= 16,
350 		.channels	= 2,
351 		.channel_mask	= AUFMT_STEREO,
352 		.frequency_type	= 1,
353 		.frequency	= { 48000 },
354 	},
355 };
356 
357 static const struct audio_format auich_modem_formats[AUICH_MODEM_NFORMATS] = {
358 	{
359 		.mode		= AUMODE_PLAY | AUMODE_RECORD,
360 		.encoding	= AUDIO_ENCODING_SLINEAR_LE,
361 		.validbits	= 16,
362 		.precision	= 16,
363 		.channels	= 1,
364 		.channel_mask	= AUFMT_MONAURAL,
365 		.frequency_type	= 2,
366 		.frequency	= { 8000, 16000 },
367 	},
368 };
369 
370 #define PCI_ID_CODE0(v, p)	PCI_ID_CODE(PCI_VENDOR_##v, PCI_PRODUCT_##v##_##p)
371 #define PCIID_ICH		PCI_ID_CODE0(INTEL, 82801AA_ACA)
372 #define PCIID_ICH0		PCI_ID_CODE0(INTEL, 82801AB_ACA)
373 #define PCIID_ICH2		PCI_ID_CODE0(INTEL, 82801BA_ACA)
374 #define PCIID_440MX		PCI_ID_CODE0(INTEL, 82440MX_ACA)
375 #define PCIID_ICH3		PCI_ID_CODE0(INTEL, 82801CA_AC)
376 #define PCIID_ICH4		PCI_ID_CODE0(INTEL, 82801DB_AC)
377 #define PCIID_ICH5		PCI_ID_CODE0(INTEL, 82801EB_AC)
378 #define PCIID_ICH6		PCI_ID_CODE0(INTEL, 82801FB_AC)
379 #define PCIID_ICH7		PCI_ID_CODE0(INTEL, 82801G_ACA)
380 #define PCIID_I6300ESB		PCI_ID_CODE0(INTEL, 6300ESB_ACA)
381 #define PCIID_SIS7012		PCI_ID_CODE0(SIS, 7012_AC)
382 #define PCIID_NFORCE		PCI_ID_CODE0(NVIDIA, NFORCE_MCP_AC)
383 #define PCIID_NFORCE2		PCI_ID_CODE0(NVIDIA, NFORCE2_MCPT_AC)
384 #define PCIID_NFORCE2_400	PCI_ID_CODE0(NVIDIA, NFORCE2_400_MCPT_AC)
385 #define PCIID_NFORCE3		PCI_ID_CODE0(NVIDIA, NFORCE3_MCPT_AC)
386 #define PCIID_NFORCE3_250	PCI_ID_CODE0(NVIDIA, NFORCE3_250_MCPT_AC)
387 #define PCIID_NFORCE4		PCI_ID_CODE0(NVIDIA, NFORCE4_AC)
388 #define	PCIID_NFORCE430 	PCI_ID_CODE0(NVIDIA, NFORCE430_AC)
389 #define PCIID_AMD768		PCI_ID_CODE0(AMD, PBC768_AC)
390 #define PCIID_AMD8111		PCI_ID_CODE0(AMD, PBC8111_AC)
391 
392 #define	PCIID_ICH3MODEM		PCI_ID_CODE0(INTEL, 82801CA_MOD)
393 #define PCIID_ICH4MODEM		PCI_ID_CODE0(INTEL, 82801DB_MOD)
394 #define PCIID_ICH6MODEM 	PCI_ID_CODE0(INTEL, 82801FB_ACM)
395 
396 struct auich_devtype {
397 	pcireg_t	id;
398 	const char	*name;
399 	const char	*shortname;	/* must be less than 11 characters */
400 };
401 
402 static const struct auich_devtype auich_audio_devices[] = {
403 	{ PCIID_ICH,	"i82801AA (ICH) AC-97 Audio",	"ICH" },
404 	{ PCIID_ICH0,	"i82801AB (ICH0) AC-97 Audio",	"ICH0" },
405 	{ PCIID_ICH2,	"i82801BA (ICH2) AC-97 Audio",	"ICH2" },
406 	{ PCIID_440MX,	"i82440MX AC-97 Audio",		"440MX" },
407 	{ PCIID_ICH3,	"i82801CA (ICH3) AC-97 Audio",	"ICH3" },
408 	{ PCIID_ICH4,	"i82801DB/DBM (ICH4/ICH4M) AC-97 Audio", "ICH4" },
409 	{ PCIID_ICH5,	"i82801EB (ICH5) AC-97 Audio",	"ICH5" },
410 	{ PCIID_ICH6,	"i82801FB (ICH6) AC-97 Audio",	"ICH6" },
411 	{ PCIID_ICH7,	"i82801GB/GR (ICH7) AC-97 Audio",	"ICH7" },
412 	{ PCIID_I6300ESB,	"Intel 6300ESB AC-97 Audio",	"I6300ESB" },
413 	{ PCIID_SIS7012, "SiS 7012 AC-97 Audio",	"SiS7012" },
414 	{ PCIID_NFORCE,	"nForce MCP AC-97 Audio",	"nForce" },
415 	{ PCIID_NFORCE2, "nForce2 MCP-T AC-97 Audio",	"nForce2" },
416 	{ PCIID_NFORCE2_400, "nForce2 400 MCP-T AC-97 Audio",	"nForce2" },
417 	{ PCIID_NFORCE3, "nForce3 MCP-T AC-97 Audio",	"nForce3" },
418 	{ PCIID_NFORCE3_250, "nForce3 250 MCP-T AC-97 Audio", "nForce3" },
419 	{ PCIID_NFORCE4, "nForce4 AC-97 Audio",		"nForce4" },
420 	{ PCIID_NFORCE430, "nForce430 (MCP51) AC-97 Audio", "nForce430" },
421 	{ PCIID_AMD768,	"AMD768 AC-97 Audio",		"AMD768" },
422 	{ PCIID_AMD8111,"AMD8111 AC-97 Audio",		"AMD8111" },
423 	{ 0,		NULL,				NULL },
424 };
425 
426 static const struct auich_devtype auich_modem_devices[] = {
427 #ifdef AUICH_ATTACH_MODEM
428 	{ PCIID_ICH3MODEM, "i82801CA (ICH3) AC-97 Modem", "ICH3MODEM" },
429 	{ PCIID_ICH4MODEM, "i82801DB (ICH4) AC-97 Modem", "ICH4MODEM" },
430 	{ PCIID_ICH6MODEM, "i82801FB (ICH6) AC-97 Modem", "ICH6MODEM" },
431 #endif
432 	{ 0,		NULL,				NULL },
433 };
434 
435 static const struct auich_devtype *
436 auich_lookup(struct pci_attach_args *pa, const struct auich_devtype *auich_devices)
437 {
438 	const struct auich_devtype *d;
439 
440 	for (d = auich_devices; d->name != NULL; d++) {
441 		if (pa->pa_id == d->id)
442 			return d;
443 	}
444 
445 	return NULL;
446 }
447 
448 static int
449 auich_match(device_t parent, cfdata_t match, void *aux)
450 {
451 	struct pci_attach_args *pa;
452 
453 	pa = aux;
454 	if (auich_lookup(pa, auich_audio_devices) != NULL)
455 		return 1;
456 	if (auich_lookup(pa, auich_modem_devices) != NULL)
457 		return 1;
458 
459 	return 0;
460 }
461 
462 static void
463 auich_attach(device_t parent, device_t self, void *aux)
464 {
465 	struct auich_softc *sc = device_private(self);
466 	struct pci_attach_args *pa;
467 	pcireg_t v, subdev;
468 	const char *intrstr;
469 	const struct auich_devtype *d;
470 	const struct sysctlnode *node, *node_ac97clock;
471 	int err, node_mib, i;
472 	char intrbuf[PCI_INTRSTR_LEN];
473 
474 	sc->sc_dev = self;
475 	pa = aux;
476 
477 	if ((d = auich_lookup(pa, auich_modem_devices)) != NULL) {
478 		sc->sc_modem_offset = 0x10;
479 		sc->sc_codectype = AC97_CODEC_TYPE_MODEM;
480 	} else if ((d = auich_lookup(pa, auich_audio_devices)) != NULL) {
481 		sc->sc_modem_offset = 0;
482 		sc->sc_codectype = AC97_CODEC_TYPE_AUDIO;
483 	} else
484 		panic("auich_attach: impossible");
485 
486 	if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO)
487 		aprint_naive(": Audio controller\n");
488 	else
489 		aprint_naive(": Modem controller\n");
490 
491 	sc->sc_pc = pa->pa_pc;
492 	sc->sc_pt = pa->pa_tag;
493 
494 	aprint_normal(": %s\n", d->name);
495 
496 	if (d->id == PCIID_ICH4 || d->id == PCIID_ICH5 || d->id == PCIID_ICH6
497 	    || d->id == PCIID_ICH7 || d->id == PCIID_I6300ESB
498 	    || d->id == PCIID_ICH4MODEM) {
499 		/*
500 		 * Use native mode for Intel 6300ESB and ICH4/ICH5/ICH6/ICH7
501 		 */
502 
503 		if (pci_mapreg_map(pa, ICH_MMBAR, PCI_MAPREG_TYPE_MEM, 0,
504 		    &sc->iot, &sc->mix_ioh, NULL, &sc->mix_size)) {
505 			goto retry_map;
506 		}
507 		if (pci_mapreg_map(pa, ICH_MBBAR, PCI_MAPREG_TYPE_MEM, 0,
508 		    &sc->iot, &sc->aud_ioh, NULL, &sc->aud_size)) {
509 			goto retry_map;
510 		}
511 		goto map_done;
512 	} else
513 		goto non_native_map;
514 
515 retry_map:
516 	sc->sc_iose = 1;
517 	v = pci_conf_read(pa->pa_pc, pa->pa_tag, ICH_CFG);
518 	pci_conf_write(pa->pa_pc, pa->pa_tag, ICH_CFG,
519 		       v | ICH_CFG_IOSE);
520 
521 non_native_map:
522 	if (pci_mapreg_map(pa, ICH_NAMBAR, PCI_MAPREG_TYPE_IO, 0,
523 			   &sc->iot, &sc->mix_ioh, NULL, &sc->mix_size)) {
524 		aprint_error_dev(self, "can't map codec i/o space\n");
525 		return;
526 	}
527 	if (pci_mapreg_map(pa, ICH_NABMBAR, PCI_MAPREG_TYPE_IO, 0,
528 			   &sc->iot, &sc->aud_ioh, NULL, &sc->aud_size)) {
529 		aprint_error_dev(self, "can't map device i/o space\n");
530 		return;
531 	}
532 
533 map_done:
534 	sc->dmat = pa->pa_dmat;
535 
536 	/* enable bus mastering */
537 	v = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG);
538 	pci_conf_write(pa->pa_pc, pa->pa_tag, PCI_COMMAND_STATUS_REG,
539 	    v | PCI_COMMAND_MASTER_ENABLE | PCI_COMMAND_BACKTOBACK_ENABLE);
540 
541 	mutex_init(&sc->sc_lock, MUTEX_DEFAULT, IPL_NONE);
542 	mutex_init(&sc->sc_intr_lock, MUTEX_DEFAULT, IPL_AUDIO);
543 
544 	/* Map and establish the interrupt. */
545 	if (pci_intr_map(pa, &sc->intrh)) {
546 		aprint_error_dev(self, "can't map interrupt\n");
547 		return;
548 	}
549 	intrstr = pci_intr_string(pa->pa_pc, sc->intrh, intrbuf, sizeof(intrbuf));
550 	sc->sc_ih = pci_intr_establish_xname(pa->pa_pc, sc->intrh, IPL_AUDIO,
551 	    auich_intr, sc, device_xname(sc->sc_dev));
552 	if (sc->sc_ih == NULL) {
553 		aprint_error_dev(self, "can't establish interrupt");
554 		if (intrstr != NULL)
555 			aprint_error(" at %s", intrstr);
556 		aprint_error("\n");
557 		return;
558 	}
559 	aprint_normal_dev(self, "interrupting at %s\n", intrstr);
560 
561 	snprintf(sc->sc_audev.name, MAX_AUDIO_DEV_LEN, "%s AC97", d->shortname);
562 	snprintf(sc->sc_audev.version, MAX_AUDIO_DEV_LEN,
563 		 "0x%02x", PCI_REVISION(pa->pa_class));
564 	strlcpy(sc->sc_audev.config, device_xname(self), MAX_AUDIO_DEV_LEN);
565 
566 	/* SiS 7012 needs special handling */
567 	if (d->id == PCIID_SIS7012) {
568 		sc->sc_sts_reg = ICH_PICB;
569 		sc->sc_sample_shift = 0;
570 		sc->sc_pcm246_mask = ICH_SIS_PCM246_MASK;
571 		sc->sc_pcm2 = ICH_SIS_PCM2;
572 		sc->sc_pcm4 = ICH_SIS_PCM4;
573 		sc->sc_pcm6 = ICH_SIS_PCM6;
574 		/* Un-mute output. From Linux. */
575 		bus_space_write_4(sc->iot, sc->aud_ioh, ICH_SIS_NV_CTL,
576 		    bus_space_read_4(sc->iot, sc->aud_ioh, ICH_SIS_NV_CTL) |
577 		    ICH_SIS_CTL_UNMUTE);
578 	} else {
579 		sc->sc_sts_reg = ICH_STS;
580 		sc->sc_sample_shift = 1;
581 		sc->sc_pcm246_mask = ICH_PCM246_MASK;
582 		sc->sc_pcm2 = ICH_PCM2;
583 		sc->sc_pcm4 = ICH_PCM4;
584 		sc->sc_pcm6 = ICH_PCM6;
585 	}
586 
587 	/* Workaround for a 440MX B-stepping erratum */
588 	sc->sc_dmamap_flags = BUS_DMA_COHERENT;
589 	if (d->id == PCIID_440MX) {
590 		sc->sc_dmamap_flags |= BUS_DMA_NOCACHE;
591 		aprint_normal_dev(self, "DMA bug workaround enabled\n");
592 	}
593 
594 	/* Set up DMA lists. */
595 	sc->pcmo.qptr = sc->pcmi.qptr = sc->mici.qptr = 0;
596 	auich_alloc_cdata(sc);
597 
598 	DPRINTF(ICH_DEBUG_DMA, (sc->sc_dev, "%s: lists %p %p %p\n",
599 	    __func__, sc->pcmo.dmalist, sc->pcmi.dmalist, sc->mici.dmalist));
600 
601 	/* Modem codecs are always the secondary codec on ICH */
602 	sc->sc_codecnum = sc->sc_codectype == AC97_CODEC_TYPE_MODEM ? 1 : 0;
603 
604 	sc->host_if.arg = sc;
605 	sc->host_if.attach = auich_attach_codec;
606 	sc->host_if.read = auich_read_codec;
607 	sc->host_if.write = auich_write_codec;
608 	sc->host_if.reset = auich_reset_codec;
609 	sc->host_if.flags = auich_flags_codec;
610 	sc->host_if.spdif_event = auich_spdif_event;
611 
612 	subdev = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_SUBSYS_ID_REG);
613 	switch (subdev) {
614 	case 0x202f161f:	/* Gateway 7326GZ */
615 	case 0x203a161f:	/* Gateway 4028GZ */
616 	case 0x204c161f:	/* Kvazar-Micro Senator 3592XT */
617 	case 0x8144104d:	/* Sony VAIO PCG-TR* */
618 	case 0x8197104d:	/* Sony S1XP */
619 	case 0x81c0104d:	/* Sony VAIO type T */
620 	case 0x81c5104d:	/* Sony VAIO VGN-B1XP */
621 		sc->sc_codecflags = AC97_HOST_INVERTED_EAMP;
622 		break;
623 	default:
624 		sc->sc_codecflags = 0;
625 		break;
626 	}
627 
628 	if (ac97_attach_type(&sc->host_if, self, sc->sc_codectype,
629 	    &sc->sc_lock) != 0)
630 		return;
631 
632 	mutex_enter(&sc->sc_lock);
633 	sc->codec_if->vtbl->unlock(sc->codec_if);
634 	sc->sc_fixedrate = AC97_IS_FIXED_RATE(sc->codec_if);
635 
636 	/* setup audio_format */
637 	if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO) {
638 		memcpy(sc->sc_audio_formats, auich_audio_formats,
639 		    sizeof(auich_audio_formats));
640 		if (!AC97_IS_4CH(sc->codec_if))
641 			AUFMT_INVALIDATE(&sc->sc_audio_formats[AUICH_FORMATS_4CH]);
642 		if (!AC97_IS_6CH(sc->codec_if))
643 			AUFMT_INVALIDATE(&sc->sc_audio_formats[AUICH_FORMATS_6CH]);
644 		if (AC97_IS_FIXED_RATE(sc->codec_if)) {
645 			for (i = 0; i < AUICH_AUDIO_NFORMATS; i++) {
646 				sc->sc_audio_formats[i].frequency_type = 1;
647 				sc->sc_audio_formats[i].frequency[0] = 48000;
648 			}
649 		}
650 		mutex_exit(&sc->sc_lock);
651 	} else {
652 		mutex_exit(&sc->sc_lock);
653 		memcpy(sc->sc_modem_formats, auich_modem_formats,
654 		    sizeof(auich_modem_formats));
655 	}
656 
657 	/* Watch for power change */
658 	if (!pmf_device_register(self, NULL, auich_resume))
659 		aprint_error_dev(self, "couldn't establish power handler\n");
660 
661 	config_interrupts(self, auich_finish_attach);
662 
663 	/* sysctl setup */
664 	if (sc->sc_fixedrate && sc->sc_codectype == AC97_CODEC_TYPE_AUDIO)
665 		return;
666 
667 	err = sysctl_createv(&sc->sc_log, 0, NULL, &node, 0,
668 			     CTLTYPE_NODE, device_xname(self), NULL, NULL, 0,
669 			     NULL, 0, CTL_HW, CTL_CREATE, CTL_EOL);
670 	if (err != 0)
671 		goto sysctl_err;
672 	node_mib = node->sysctl_num;
673 
674 	if (!sc->sc_fixedrate) {
675 		/* passing the sc address instead of &sc->sc_ac97_clock */
676 		err = sysctl_createv(&sc->sc_log, 0, NULL, &node_ac97clock,
677 				     CTLFLAG_READWRITE,
678 				     CTLTYPE_INT, "ac97rate",
679 				     SYSCTL_DESCR("AC'97 codec link rate"),
680 				     auich_sysctl_verify, 0, (void *)sc, 0,
681 				     CTL_HW, node_mib, CTL_CREATE, CTL_EOL);
682 		if (err != 0)
683 			goto sysctl_err;
684 		sc->sc_ac97_clock_mib = node_ac97clock->sysctl_num;
685 	}
686 
687 	return;
688 
689  sysctl_err:
690 	aprint_error_dev(self, "failed to add sysctl nodes. (%d)\n", err);
691 	return;			/* failure of sysctl is not fatal. */
692 }
693 
694 static void
695 auich_childdet(device_t self, device_t child)
696 {
697 	struct auich_softc *sc = device_private(self);
698 
699 	KASSERT(sc->sc_audiodev == child);
700 	sc->sc_audiodev = NULL;
701 }
702 
703 static int
704 auich_detach(device_t self, int flags)
705 {
706 	struct auich_softc *sc = device_private(self);
707 
708 	/* audio */
709 	if (sc->sc_audiodev != NULL)
710 		config_detach(sc->sc_audiodev, flags);
711 
712 	/* sysctl */
713 	sysctl_teardown(&sc->sc_log);
714 
715 	mutex_enter(&sc->sc_lock);
716 
717 	/* ac97 */
718 	if (sc->codec_if != NULL)
719 		sc->codec_if->vtbl->detach(sc->codec_if);
720 
721 	mutex_exit(&sc->sc_lock);
722 	mutex_destroy(&sc->sc_lock);
723 	mutex_destroy(&sc->sc_intr_lock);
724 
725 	/* PCI */
726 	if (sc->sc_ih != NULL)
727 		pci_intr_disestablish(sc->sc_pc, sc->sc_ih);
728 	if (sc->mix_size != 0)
729 		bus_space_unmap(sc->iot, sc->mix_ioh, sc->mix_size);
730 	if (sc->aud_size != 0)
731 		bus_space_unmap(sc->iot, sc->aud_ioh, sc->aud_size);
732 	return 0;
733 }
734 
735 static int
736 auich_sysctl_verify(SYSCTLFN_ARGS)
737 {
738 	int error, tmp;
739 	struct sysctlnode node;
740 	struct auich_softc *sc;
741 
742 	node = *rnode;
743 	sc = rnode->sysctl_data;
744 	if (node.sysctl_num == sc->sc_ac97_clock_mib) {
745 		tmp = sc->sc_ac97_clock;
746 		node.sysctl_data = &tmp;
747 		error = sysctl_lookup(SYSCTLFN_CALL(&node));
748 		if (error || newp == NULL)
749 			return error;
750 
751 		if (tmp < 48000 || tmp > 96000)
752 			return EINVAL;
753 		mutex_enter(&sc->sc_lock);
754 		sc->sc_ac97_clock = tmp;
755 		mutex_exit(&sc->sc_lock);
756 	}
757 
758 	return 0;
759 }
760 
761 static void
762 auich_finish_attach(device_t self)
763 {
764 	struct auich_softc *sc = device_private(self);
765 
766 	mutex_enter(&sc->sc_lock);
767 	if (!AC97_IS_FIXED_RATE(sc->codec_if))
768 		auich_calibrate(sc);
769 	mutex_exit(&sc->sc_lock);
770 
771 	sc->sc_audiodev = audio_attach_mi(&auich_hw_if, sc, sc->sc_dev);
772 
773 	return;
774 }
775 
776 #define ICH_CODECIO_INTERVAL	10
777 static int
778 auich_read_codec(void *v, uint8_t reg, uint16_t *val)
779 {
780 	struct auich_softc *sc;
781 	int i;
782 	uint32_t status;
783 
784 	sc = v;
785 	/* wait for an access semaphore */
786 	for (i = ICH_SEMATIMO / ICH_CODECIO_INTERVAL; i-- &&
787 	    bus_space_read_1(sc->iot, sc->aud_ioh,
788 		ICH_CAS + sc->sc_modem_offset) & 1;
789 	    DELAY(ICH_CODECIO_INTERVAL));
790 
791 	/*
792 	 * Be permissive in first attempt. If previous instances of
793 	 * this routine were interrupted precisely at this point (after
794 	 * access is granted by CAS but before a command is sent),
795 	 * they could have left hardware in an inconsistent state where
796 	 * a command is expected and therefore semaphore wait would hit
797 	 * the timeout.
798 	 */
799 	if (!sc->sc_cas_been_used && i <= 0)
800 		i = 1;
801 	sc->sc_cas_been_used = 1;
802 
803 	if (i > 0) {
804 		*val = bus_space_read_2(sc->iot, sc->mix_ioh,
805 		    reg + (sc->sc_codecnum * ICH_CODEC_OFFSET));
806 		DPRINTF(ICH_DEBUG_CODECIO,
807 		    (sc->sc_dev, "%s(%x, %x)\n", __func__, reg, *val));
808 		status = bus_space_read_4(sc->iot, sc->aud_ioh,
809 		    ICH_GSTS + sc->sc_modem_offset);
810 		if (status & ICH_RCS) {
811 			bus_space_write_4(sc->iot, sc->aud_ioh,
812 					  ICH_GSTS + sc->sc_modem_offset,
813 					  status & ~(ICH_SRI|ICH_PRI|ICH_GSCI));
814 			*val = 0xffff;
815 			DPRINTF(ICH_DEBUG_CODECIO,
816 			    (sc->sc_dev, "%s: read_codec error\n", __func__));
817 			if (reg == AC97_REG_GPIO_STATUS)
818 				auich_clear_cas(sc);
819 			return -1;
820 		}
821 		if (reg == AC97_REG_GPIO_STATUS)
822 			auich_clear_cas(sc);
823 		return 0;
824 	} else {
825 		aprint_normal_dev(sc->sc_dev, "read_codec timeout\n");
826 		if (reg == AC97_REG_GPIO_STATUS)
827 			auich_clear_cas(sc);
828 		return -1;
829 	}
830 }
831 
832 static int
833 auich_write_codec(void *v, uint8_t reg, uint16_t val)
834 {
835 	struct auich_softc *sc;
836 	int i;
837 
838 	sc = v;
839 	DPRINTF(ICH_DEBUG_CODECIO, (sc->sc_dev, "%s(%x, %x)\n",
840 	    __func__, reg, val));
841 	/* wait for an access semaphore */
842 	for (i = ICH_SEMATIMO / ICH_CODECIO_INTERVAL; i-- &&
843 	    bus_space_read_1(sc->iot, sc->aud_ioh,
844 		ICH_CAS + sc->sc_modem_offset) & 1;
845 	    DELAY(ICH_CODECIO_INTERVAL));
846 
847 	/* Be permissive in first attempt (see comments in auich_read_codec) */
848 	if (!sc->sc_cas_been_used && i <= 0)
849 		i = 1;
850 	sc->sc_cas_been_used = 1;
851 
852 	if (i > 0) {
853 		bus_space_write_2(sc->iot, sc->mix_ioh,
854 		    reg + (sc->sc_codecnum * ICH_CODEC_OFFSET), val);
855 		return 0;
856 	} else {
857 		aprint_normal_dev(sc->sc_dev, "write_codec timeout\n");
858 		return -1;
859 	}
860 }
861 
862 static int
863 auich_attach_codec(void *v, struct ac97_codec_if *cif)
864 {
865 	struct auich_softc *sc;
866 
867 	sc = v;
868 	sc->codec_if = cif;
869 
870 	return 0;
871 }
872 
873 static int
874 auich_reset_codec(void *v)
875 {
876 	struct auich_softc *sc;
877 	int i;
878 	uint32_t control, status;
879 
880 	sc = v;
881 	control = bus_space_read_4(sc->iot, sc->aud_ioh,
882 	    ICH_GCTRL + sc->sc_modem_offset);
883 	if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO) {
884 		control &= ~(ICH_ACLSO | sc->sc_pcm246_mask);
885 	} else {
886 		control &= ~ICH_ACLSO;
887 		control |= ICH_GIE;
888 	}
889 	control |= (control & ICH_CRESET) ? ICH_WRESET : ICH_CRESET;
890 	bus_space_write_4(sc->iot, sc->aud_ioh,
891 	    ICH_GCTRL + sc->sc_modem_offset, control);
892 
893 	for (i = 500000; i >= 0; i--) {
894 		status = bus_space_read_4(sc->iot, sc->aud_ioh,
895 		    ICH_GSTS + sc->sc_modem_offset);
896 		if (status & (ICH_PCR | ICH_SCR | ICH_S2CR))
897 			break;
898 		DELAY(1);
899 	}
900 	if (i <= 0) {
901 		aprint_error_dev(sc->sc_dev, "auich_reset_codec: time out\n");
902 		return ETIMEDOUT;
903 	}
904 #ifdef AUICH_DEBUG
905 	if (status & ICH_SCR)
906 		aprint_normal_dev(sc->sc_dev, "The 2nd codec is ready.\n");
907 	if (status & ICH_S2CR)
908 		aprint_normal_dev(sc->sc_dev, "The 3rd codec is ready.\n");
909 #endif
910 	return 0;
911 }
912 
913 static enum ac97_host_flags
914 auich_flags_codec(void *v)
915 {
916 	struct auich_softc *sc = v;
917 	return sc->sc_codecflags;
918 }
919 
920 static void
921 auich_spdif_event(void *addr, bool flag)
922 {
923 	struct auich_softc *sc;
924 
925 	sc = addr;
926 	sc->sc_spdif = flag;
927 }
928 
929 static int
930 auich_open(void *addr, int flags)
931 {
932 	struct auich_softc *sc;
933 
934 	sc = (struct auich_softc *)addr;
935 	mutex_spin_exit(&sc->sc_intr_lock);
936 	sc->codec_if->vtbl->lock(sc->codec_if);
937 	mutex_spin_enter(&sc->sc_intr_lock);
938 	return 0;
939 }
940 
941 static void
942 auich_close(void *addr)
943 {
944 	struct auich_softc *sc;
945 
946 	sc = (struct auich_softc *)addr;
947 	mutex_spin_exit(&sc->sc_intr_lock);
948 	sc->codec_if->vtbl->unlock(sc->codec_if);
949 	mutex_spin_enter(&sc->sc_intr_lock);
950 }
951 
952 static int
953 auich_query_format(void *v, struct audio_format_query *afp)
954 {
955 	struct auich_softc *sc;
956 
957 	sc = (struct auich_softc *)v;
958 	if (sc->sc_spdif) {
959 		return audio_query_format(auich_spdif_formats,
960 		    AUICH_SPDIF_NFORMATS, afp);
961 	} else {
962 		return audio_query_format(sc->sc_audio_formats,
963 		    AUICH_AUDIO_NFORMATS, afp);
964 	}
965 }
966 
967 static int
968 auich_set_rate(struct auich_softc *sc, int mode, u_long srate)
969 {
970 	int ret;
971 	u_int ratetmp;
972 
973 	sc->codec_if->vtbl->set_clock(sc->codec_if, sc->sc_ac97_clock);
974 	ratetmp = srate;
975 	if (mode == AUMODE_RECORD)
976 		return sc->codec_if->vtbl->set_rate(sc->codec_if,
977 		    AC97_REG_PCM_LR_ADC_RATE, &ratetmp);
978 	ret = sc->codec_if->vtbl->set_rate(sc->codec_if,
979 	    AC97_REG_PCM_FRONT_DAC_RATE, &ratetmp);
980 	if (ret)
981 		return ret;
982 	ratetmp = srate;
983 	ret = sc->codec_if->vtbl->set_rate(sc->codec_if,
984 	    AC97_REG_PCM_SURR_DAC_RATE, &ratetmp);
985 	if (ret)
986 		return ret;
987 	ratetmp = srate;
988 	ret = sc->codec_if->vtbl->set_rate(sc->codec_if,
989 	    AC97_REG_PCM_LFE_DAC_RATE, &ratetmp);
990 	return ret;
991 }
992 
993 static int
994 auich_set_format(void *v, int setmode,
995     const audio_params_t *play, const audio_params_t *rec,
996     audio_filter_reg_t *pfil, audio_filter_reg_t *rfil)
997 {
998 	struct auich_softc *sc;
999 	const audio_params_t *p;
1000 	int mode, index;
1001 	uint32_t control;
1002 
1003 	sc = v;
1004 	for (mode = AUMODE_RECORD; mode != -1;
1005 	     mode = mode == AUMODE_RECORD ? AUMODE_PLAY : -1) {
1006 		if ((setmode & mode) == 0)
1007 			continue;
1008 
1009 		p = mode == AUMODE_PLAY ? play : rec;
1010 
1011 		if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO) {
1012 			if (!sc->sc_spdif)
1013 				index = audio_indexof_format(
1014 				    sc->sc_audio_formats, AUICH_AUDIO_NFORMATS,
1015 				    mode, p);
1016 			else
1017 				index = audio_indexof_format(
1018 				    auich_spdif_formats, AUICH_SPDIF_NFORMATS,
1019 				    mode, p);
1020 		} else {
1021 			index = audio_indexof_format(sc->sc_modem_formats,
1022 			    AUICH_MODEM_NFORMATS, mode, p);
1023 		}
1024 
1025 		/* p represents HW encoding */
1026 		if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO) {
1027 			if (sc->sc_audio_formats[index].frequency_type != 1
1028 			    && auich_set_rate(sc, mode, p->sample_rate))
1029 				return EINVAL;
1030 		} else {
1031 			if (sc->sc_modem_formats[index].frequency_type != 1
1032 			    && auich_set_rate(sc, mode, p->sample_rate))
1033 				return EINVAL;
1034 			auich_write_codec(sc, AC97_REG_LINE1_RATE,
1035 					  p->sample_rate);
1036 			auich_write_codec(sc, AC97_REG_LINE1_LEVEL, 0);
1037 		}
1038 		if (mode == AUMODE_PLAY &&
1039 		    sc->sc_codectype == AC97_CODEC_TYPE_AUDIO) {
1040 			control = bus_space_read_4(sc->iot, sc->aud_ioh,
1041 			    ICH_GCTRL + sc->sc_modem_offset);
1042 			control &= ~sc->sc_pcm246_mask;
1043 			if (p->channels == 4) {
1044 				control |= sc->sc_pcm4;
1045 			} else if (p->channels == 6) {
1046 				control |= sc->sc_pcm6;
1047 			}
1048 			bus_space_write_4(sc->iot, sc->aud_ioh,
1049 			    ICH_GCTRL + sc->sc_modem_offset, control);
1050 		}
1051 	}
1052 
1053 	return 0;
1054 }
1055 
1056 static int
1057 auich_round_blocksize(void *v, int blk, int mode,
1058     const audio_params_t *param)
1059 {
1060 
1061 	if (blk < 0x40)
1062 		return 0x40;		/* avoid 0 block size */
1063 
1064 	return blk & ~0x3f;		/* keep good alignment */
1065 }
1066 
1067 static void
1068 auich_halt_pipe(struct auich_softc *sc, int pipe)
1069 {
1070 	int i;
1071 	uint32_t status;
1072 
1073 	bus_space_write_1(sc->iot, sc->aud_ioh, pipe + ICH_CTRL, 0);
1074 	for (i = 0; i < 100; i++) {
1075 		status = bus_space_read_4(sc->iot, sc->aud_ioh, pipe + ICH_STS);
1076 		if (status & ICH_DCH)
1077 			break;
1078 		DELAY(1);
1079 	}
1080 	bus_space_write_1(sc->iot, sc->aud_ioh, pipe + ICH_CTRL, ICH_RR);
1081 
1082 #if AUICH_DEBUG
1083 	if (i > 0)
1084 		aprint_normal_dev(sc->sc_dev, "%s: halt took %d cycles\n",
1085 		    __func__, i);
1086 #endif
1087 }
1088 
1089 static int
1090 auich_halt_output(void *v)
1091 {
1092 	struct auich_softc *sc;
1093 
1094 	sc = v;
1095 	DPRINTF(ICH_DEBUG_DMA, (sc->sc_dev, "%s\n", __func__));
1096 
1097 	auich_halt_pipe(sc, ICH_PCMO);
1098 	sc->pcmo.intr = NULL;
1099 
1100 	return 0;
1101 }
1102 
1103 static int
1104 auich_halt_input(void *v)
1105 {
1106 	struct auich_softc *sc;
1107 
1108 	sc = v;
1109 	DPRINTF(ICH_DEBUG_DMA, (sc->sc_dev, "%s\n", __func__));
1110 
1111 	auich_halt_pipe(sc, ICH_PCMI);
1112 	sc->pcmi.intr = NULL;
1113 
1114 	return 0;
1115 }
1116 
1117 static int
1118 auich_getdev(void *v, struct audio_device *adp)
1119 {
1120 	struct auich_softc *sc;
1121 
1122 	sc = v;
1123 	*adp = sc->sc_audev;
1124 	return 0;
1125 }
1126 
1127 static int
1128 auich_set_port(void *v, mixer_ctrl_t *cp)
1129 {
1130 	struct auich_softc *sc;
1131 
1132 	sc = v;
1133 	return sc->codec_if->vtbl->mixer_set_port(sc->codec_if, cp);
1134 }
1135 
1136 static int
1137 auich_get_port(void *v, mixer_ctrl_t *cp)
1138 {
1139 	struct auich_softc *sc;
1140 
1141 	sc = v;
1142 	return sc->codec_if->vtbl->mixer_get_port(sc->codec_if, cp);
1143 }
1144 
1145 static int
1146 auich_query_devinfo(void *v, mixer_devinfo_t *dp)
1147 {
1148 	struct auich_softc *sc;
1149 
1150 	sc = v;
1151 	return sc->codec_if->vtbl->query_devinfo(sc->codec_if, dp);
1152 }
1153 
1154 static void *
1155 auich_allocm(void *v, int direction, size_t size)
1156 {
1157 	struct auich_softc *sc;
1158 	struct auich_dma *p;
1159 	int error;
1160 
1161 	if (size > (ICH_DMALIST_MAX * ICH_DMASEG_MAX))
1162 		return NULL;
1163 
1164 	p = kmem_alloc(sizeof(*p), KM_SLEEP);
1165 
1166 	sc = v;
1167 	error = auich_allocmem(sc, size, 0, p);
1168 	if (error) {
1169 		kmem_free(p, sizeof(*p));
1170 		return NULL;
1171 	}
1172 
1173 	p->next = sc->sc_dmas;
1174 	sc->sc_dmas = p;
1175 
1176 	return KERNADDR(p);
1177 }
1178 
1179 static void
1180 auich_freem(void *v, void *ptr, size_t size)
1181 {
1182 	struct auich_softc *sc;
1183 	struct auich_dma *p, **pp;
1184 
1185 	sc = v;
1186 	for (pp = &sc->sc_dmas; (p = *pp) != NULL; pp = &p->next) {
1187 		if (KERNADDR(p) == ptr) {
1188 			auich_freemem(sc, p);
1189 			*pp = p->next;
1190 			kmem_free(p, sizeof(*p));
1191 			return;
1192 		}
1193 	}
1194 }
1195 
1196 static size_t
1197 auich_round_buffersize(void *v, int direction, size_t size)
1198 {
1199 
1200 	if (size > (ICH_DMALIST_MAX * ICH_DMASEG_MAX))
1201 		size = ICH_DMALIST_MAX * ICH_DMASEG_MAX;
1202 
1203 	return size;
1204 }
1205 
1206 static int
1207 auich_get_props(void *v)
1208 {
1209 
1210 	return AUDIO_PROP_PLAYBACK | AUDIO_PROP_CAPTURE |
1211 	    AUDIO_PROP_INDEPENDENT | AUDIO_PROP_FULLDUPLEX;
1212 }
1213 
1214 static int
1215 auich_intr(void *v)
1216 {
1217 	struct auich_softc *sc;
1218 	int ret, gsts;
1219 #ifdef DIAGNOSTIC
1220 	int csts;
1221 #endif
1222 
1223 	sc = v;
1224 
1225 	if (!device_has_power(sc->sc_dev))
1226 		return (0);
1227 
1228 	mutex_spin_enter(&sc->sc_intr_lock);
1229 
1230 	ret = 0;
1231 #ifdef DIAGNOSTIC
1232 	csts = pci_conf_read(sc->sc_pc, sc->sc_pt, PCI_COMMAND_STATUS_REG);
1233 	if (csts & PCI_STATUS_MASTER_ABORT) {
1234 		aprint_error_dev(sc->sc_dev, "%s: PCI master abort\n",
1235 		    __func__);
1236 	}
1237 #endif
1238 
1239 	gsts = bus_space_read_4(sc->iot, sc->aud_ioh,
1240 	    ICH_GSTS + sc->sc_modem_offset);
1241 	DPRINTF(ICH_DEBUG_INTR, (sc->sc_dev, "%s: gsts=0x%x\n",
1242 	    __func__, gsts));
1243 
1244 	if ((sc->sc_codectype == AC97_CODEC_TYPE_AUDIO && gsts & ICH_POINT) ||
1245 	    (sc->sc_codectype == AC97_CODEC_TYPE_MODEM && gsts & ICH_MOINT)) {
1246 		int sts;
1247 
1248 		sts = bus_space_read_2(sc->iot, sc->aud_ioh,
1249 		    ICH_PCMO + sc->sc_sts_reg);
1250 		DPRINTF(ICH_DEBUG_INTR,
1251 		    (sc->sc_dev, "%s: osts=0x%x\n", __func__, sts));
1252 
1253 		if (sts & ICH_FIFOE)
1254 			aprint_error_dev(sc->sc_dev, "%s: fifo underrun\n",
1255 			    __func__);
1256 
1257 		if (sts & ICH_BCIS)
1258 			auich_intr_pipe(sc, ICH_PCMO, &sc->pcmo);
1259 
1260 		/* int ack */
1261 		bus_space_write_2(sc->iot, sc->aud_ioh, ICH_PCMO +
1262 		    sc->sc_sts_reg, sts & (ICH_BCIS | ICH_FIFOE));
1263 		if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO)
1264 			bus_space_write_4(sc->iot, sc->aud_ioh,
1265 			    ICH_GSTS + sc->sc_modem_offset, ICH_POINT);
1266 		else
1267 			bus_space_write_4(sc->iot, sc->aud_ioh,
1268 			    ICH_GSTS + sc->sc_modem_offset, ICH_MOINT);
1269 		ret++;
1270 	}
1271 
1272 	if ((sc->sc_codectype == AC97_CODEC_TYPE_AUDIO && gsts & ICH_PIINT) ||
1273 	    (sc->sc_codectype == AC97_CODEC_TYPE_MODEM && gsts & ICH_MIINT)) {
1274 		int sts;
1275 
1276 		sts = bus_space_read_2(sc->iot, sc->aud_ioh,
1277 		    ICH_PCMI + sc->sc_sts_reg);
1278 		DPRINTF(ICH_DEBUG_INTR,
1279 		    (sc->sc_dev, "%s: ists=0x%x\n", __func__, sts));
1280 
1281 		if (sts & ICH_FIFOE)
1282 			aprint_error_dev(sc->sc_dev, "%s: fifo overrun\n",
1283 			    __func__);
1284 
1285 		if (sts & ICH_BCIS)
1286 			auich_intr_pipe(sc, ICH_PCMI, &sc->pcmi);
1287 
1288 		/* int ack */
1289 		bus_space_write_2(sc->iot, sc->aud_ioh, ICH_PCMI +
1290 		    sc->sc_sts_reg, sts & (ICH_BCIS | ICH_FIFOE));
1291 		if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO)
1292 			bus_space_write_4(sc->iot, sc->aud_ioh,
1293 			    ICH_GSTS + sc->sc_modem_offset, ICH_PIINT);
1294 		else
1295 			bus_space_write_4(sc->iot, sc->aud_ioh,
1296 			    ICH_GSTS + sc->sc_modem_offset, ICH_MIINT);
1297 		ret++;
1298 	}
1299 
1300 	if (sc->sc_codectype == AC97_CODEC_TYPE_AUDIO && gsts & ICH_MINT) {
1301 		int sts;
1302 
1303 		sts = bus_space_read_2(sc->iot, sc->aud_ioh,
1304 		    ICH_MICI + sc->sc_sts_reg);
1305 		DPRINTF(ICH_DEBUG_INTR,
1306 		    (sc->sc_dev, "%s: ists=0x%x\n", __func__, sts));
1307 
1308 		if (sts & ICH_FIFOE)
1309 			aprint_error_dev(sc->sc_dev, "%s: fifo overrun\n",
1310 			    __func__);
1311 
1312 		if (sts & ICH_BCIS)
1313 			auich_intr_pipe(sc, ICH_MICI, &sc->mici);
1314 
1315 		/* int ack */
1316 		bus_space_write_2(sc->iot, sc->aud_ioh, ICH_MICI +
1317 		    sc->sc_sts_reg, sts & (ICH_BCIS | ICH_FIFOE));
1318 		bus_space_write_4(sc->iot, sc->aud_ioh,
1319 		    ICH_GSTS + sc->sc_modem_offset, ICH_MINT);
1320 		ret++;
1321 	}
1322 
1323 #ifdef AUICH_MODEM_DEBUG
1324 	if (sc->sc_codectype == AC97_CODEC_TYPE_MODEM && gsts & ICH_GSCI) {
1325 		aprint_normal_dev(sc->sc_dev, "gsts=0x%x\n", gsts);
1326 		/* int ack */
1327 		bus_space_write_4(sc->iot, sc->aud_ioh,
1328 		    ICH_GSTS + sc->sc_modem_offset, ICH_GSCI);
1329 		ret++;
1330 	}
1331 #endif
1332 
1333 	mutex_spin_exit(&sc->sc_intr_lock);
1334 
1335 	return ret;
1336 }
1337 
1338 static void
1339 auich_trigger_pipe(struct auich_softc *sc, int pipe, struct auich_ring *ring)
1340 {
1341 	int blksize, qptr;
1342 	struct auich_dmalist *q;
1343 
1344 	blksize = ring->blksize;
1345 
1346 	for (qptr = 0; qptr < ICH_DMALIST_MAX; qptr++) {
1347 		q = &ring->dmalist[qptr];
1348 		q->base = ring->p;
1349 		q->len = (blksize >> sc->sc_sample_shift) | ICH_DMAF_IOC;
1350 
1351 		ring->p += blksize;
1352 		if (ring->p >= ring->end)
1353 			ring->p = ring->start;
1354 	}
1355 	ring->qptr = 0;
1356 
1357 	bus_space_write_1(sc->iot, sc->aud_ioh, pipe + ICH_LVI,
1358 	    (qptr - 1) & ICH_LVI_MASK);
1359 	bus_space_write_1(sc->iot, sc->aud_ioh, pipe + ICH_CTRL,
1360 	    ICH_IOCE | ICH_FEIE | ICH_RPBM);
1361 }
1362 
1363 static void
1364 auich_intr_pipe(struct auich_softc *sc, int pipe, struct auich_ring *ring)
1365 {
1366 	int blksize, qptr, nqptr;
1367 	struct auich_dmalist *q;
1368 
1369 	blksize = ring->blksize;
1370 	qptr = ring->qptr;
1371 	nqptr = bus_space_read_1(sc->iot, sc->aud_ioh, pipe + ICH_CIV);
1372 
1373 	while (qptr != nqptr) {
1374 		q = &ring->dmalist[qptr];
1375 		q->base = ring->p;
1376 		q->len = (blksize >> sc->sc_sample_shift) | ICH_DMAF_IOC;
1377 
1378 		DPRINTF(ICH_DEBUG_INTR,
1379 		    (sc->sc_dev, "%s: %p, %p = %x @ 0x%x\n", __func__,
1380 		    &ring->dmalist[qptr], q, q->len, q->base));
1381 
1382 		ring->p += blksize;
1383 		if (ring->p >= ring->end)
1384 			ring->p = ring->start;
1385 
1386 		qptr = (qptr + 1) & ICH_LVI_MASK;
1387 		if (ring->intr)
1388 			ring->intr(ring->arg);
1389 	}
1390 	ring->qptr = qptr;
1391 
1392 	bus_space_write_1(sc->iot, sc->aud_ioh, pipe + ICH_LVI,
1393 	    (qptr - 1) & ICH_LVI_MASK);
1394 }
1395 
1396 static int
1397 auich_trigger_output(void *v, void *start, void *end, int blksize,
1398     void (*intr)(void *), void *arg, const audio_params_t *param)
1399 {
1400 	struct auich_softc *sc;
1401 	struct auich_dma *p;
1402 	size_t size;
1403 
1404 	sc = v;
1405 	DPRINTF(ICH_DEBUG_DMA,
1406 	    (sc->sc_dev, "%s(%p, %p, %d, %p, %p, %p)\n", __func__,
1407 	    start, end, blksize, intr, arg, param));
1408 
1409 	for (p = sc->sc_dmas; p && KERNADDR(p) != start; p = p->next)
1410 		continue;
1411 	if (!p) {
1412 		aprint_error_dev(sc->sc_dev, "%s: bad addr %p\n", __func__,
1413 		    start);
1414 		return EINVAL;
1415 	}
1416 
1417 	size = (size_t)((char *)end - (char *)start);
1418 
1419 	sc->pcmo.intr = intr;
1420 	sc->pcmo.arg = arg;
1421 	sc->pcmo.start = DMAADDR(p);
1422 	sc->pcmo.p = sc->pcmo.start;
1423 	sc->pcmo.end = sc->pcmo.start + size;
1424 	sc->pcmo.blksize = blksize;
1425 
1426 	bus_space_write_4(sc->iot, sc->aud_ioh, ICH_PCMO + ICH_BDBAR,
1427 	    sc->sc_cddma + ICH_PCMO_OFF(0));
1428 	auich_trigger_pipe(sc, ICH_PCMO, &sc->pcmo);
1429 
1430 	return 0;
1431 }
1432 
1433 static int
1434 auich_trigger_input(void *v, void *start, void *end, int blksize,
1435     void (*intr)(void *), void *arg, const audio_params_t *param)
1436 {
1437 	struct auich_softc *sc;
1438 	struct auich_dma *p;
1439 	size_t size;
1440 
1441 	sc = v;
1442 	DPRINTF(ICH_DEBUG_DMA,
1443 	    (sc->sc_dev, "%s(%p, %p, %d, %p, %p, %p)\n", __func__,
1444 	    start, end, blksize, intr, arg, param));
1445 
1446 	for (p = sc->sc_dmas; p && KERNADDR(p) != start; p = p->next)
1447 		continue;
1448 	if (!p) {
1449 		aprint_error_dev(sc->sc_dev, "%s: bad addr %p\n", __func__,
1450 		    start);
1451 		return EINVAL;
1452 	}
1453 
1454 	size = (size_t)((char *)end - (char *)start);
1455 
1456 	sc->pcmi.intr = intr;
1457 	sc->pcmi.arg = arg;
1458 	sc->pcmi.start = DMAADDR(p);
1459 	sc->pcmi.p = sc->pcmi.start;
1460 	sc->pcmi.end = sc->pcmi.start + size;
1461 	sc->pcmi.blksize = blksize;
1462 
1463 	bus_space_write_4(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_BDBAR,
1464 	    sc->sc_cddma + ICH_PCMI_OFF(0));
1465 	auich_trigger_pipe(sc, ICH_PCMI, &sc->pcmi);
1466 
1467 	return 0;
1468 }
1469 
1470 static int
1471 auich_allocmem(struct auich_softc *sc, size_t size, size_t align,
1472     struct auich_dma *p)
1473 {
1474 	int error;
1475 
1476 	p->size = size;
1477 	error = bus_dmamem_alloc(sc->dmat, p->size, align, 0,
1478 				 p->segs, sizeof(p->segs)/sizeof(p->segs[0]),
1479 				 &p->nsegs, BUS_DMA_WAITOK);
1480 	if (error)
1481 		return error;
1482 
1483 	error = bus_dmamem_map(sc->dmat, p->segs, p->nsegs, p->size,
1484 			       &p->addr, BUS_DMA_WAITOK|sc->sc_dmamap_flags);
1485 	if (error)
1486 		goto free;
1487 
1488 	error = bus_dmamap_create(sc->dmat, p->size, 1, p->size,
1489 				  0, BUS_DMA_WAITOK, &p->map);
1490 	if (error)
1491 		goto unmap;
1492 
1493 	error = bus_dmamap_load(sc->dmat, p->map, p->addr, p->size, NULL,
1494 				BUS_DMA_WAITOK);
1495 	if (error)
1496 		goto destroy;
1497 	return 0;
1498 
1499  destroy:
1500 	bus_dmamap_destroy(sc->dmat, p->map);
1501  unmap:
1502 	bus_dmamem_unmap(sc->dmat, p->addr, p->size);
1503  free:
1504 	bus_dmamem_free(sc->dmat, p->segs, p->nsegs);
1505 	return error;
1506 }
1507 
1508 static int
1509 auich_freemem(struct auich_softc *sc, struct auich_dma *p)
1510 {
1511 
1512 	bus_dmamap_unload(sc->dmat, p->map);
1513 	bus_dmamap_destroy(sc->dmat, p->map);
1514 	bus_dmamem_unmap(sc->dmat, p->addr, p->size);
1515 	bus_dmamem_free(sc->dmat, p->segs, p->nsegs);
1516 	return 0;
1517 }
1518 
1519 static int
1520 auich_alloc_cdata(struct auich_softc *sc)
1521 {
1522 	bus_dma_segment_t seg;
1523 	int error, rseg;
1524 
1525 	/*
1526 	 * Allocate the control data structure, and create and load the
1527 	 * DMA map for it.
1528 	 */
1529 	if ((error = bus_dmamem_alloc(sc->dmat,
1530 				      sizeof(struct auich_cdata),
1531 				      PAGE_SIZE, 0, &seg, 1, &rseg, 0)) != 0) {
1532 		aprint_error_dev(sc->sc_dev, "unable to allocate control data, error = %d\n", error);
1533 		goto fail_0;
1534 	}
1535 
1536 	if ((error = bus_dmamem_map(sc->dmat, &seg, rseg,
1537 				    sizeof(struct auich_cdata),
1538 				    (void **) &sc->sc_cdata,
1539 				    sc->sc_dmamap_flags)) != 0) {
1540 		aprint_error_dev(sc->sc_dev, "unable to map control data, error = %d\n", error);
1541 		goto fail_1;
1542 	}
1543 
1544 	if ((error = bus_dmamap_create(sc->dmat, sizeof(struct auich_cdata), 1,
1545 				       sizeof(struct auich_cdata), 0, 0,
1546 				       &sc->sc_cddmamap)) != 0) {
1547 		aprint_error_dev(sc->sc_dev, "unable to create control data DMA map, "
1548 		    "error = %d\n", error);
1549 		goto fail_2;
1550 	}
1551 
1552 	if ((error = bus_dmamap_load(sc->dmat, sc->sc_cddmamap,
1553 				     sc->sc_cdata, sizeof(struct auich_cdata),
1554 				     NULL, 0)) != 0) {
1555 		aprint_error_dev(sc->sc_dev, "unable tp load control data DMA map, "
1556 		    "error = %d\n", error);
1557 		goto fail_3;
1558 	}
1559 
1560 	sc->pcmo.dmalist = sc->sc_cdata->ic_dmalist_pcmo;
1561 	sc->pcmi.dmalist = sc->sc_cdata->ic_dmalist_pcmi;
1562 	sc->mici.dmalist = sc->sc_cdata->ic_dmalist_mici;
1563 
1564 	return 0;
1565 
1566  fail_3:
1567 	bus_dmamap_destroy(sc->dmat, sc->sc_cddmamap);
1568  fail_2:
1569 	bus_dmamem_unmap(sc->dmat, (void *) sc->sc_cdata,
1570 	    sizeof(struct auich_cdata));
1571  fail_1:
1572 	bus_dmamem_free(sc->dmat, &seg, rseg);
1573  fail_0:
1574 	return error;
1575 }
1576 
1577 static bool
1578 auich_resume(device_t dv, const pmf_qual_t *qual)
1579 {
1580 	struct auich_softc *sc = device_private(dv);
1581 	pcireg_t v;
1582 
1583 	mutex_enter(&sc->sc_lock);
1584 	mutex_spin_enter(&sc->sc_intr_lock);
1585 
1586 	if (sc->sc_iose) {
1587 		v = pci_conf_read(sc->sc_pc, sc->sc_pt, ICH_CFG);
1588 		pci_conf_write(sc->sc_pc, sc->sc_pt, ICH_CFG,
1589 			       v | ICH_CFG_IOSE);
1590 	}
1591 
1592 	auich_reset_codec(sc);
1593 	mutex_spin_exit(&sc->sc_intr_lock);
1594 	DELAY(1000);
1595 	(sc->codec_if->vtbl->restore_ports)(sc->codec_if);
1596 	mutex_exit(&sc->sc_lock);
1597 
1598 	return true;
1599 }
1600 
1601 /*
1602  * Calibrate card (some boards are overclocked and need scaling)
1603  */
1604 static void
1605 auich_calibrate(struct auich_softc *sc)
1606 {
1607 	struct timeval t1, t2;
1608 	uint8_t ociv, nciv;
1609 	uint64_t wait_us;
1610 	uint32_t actual_48k_rate, bytes, ac97rate;
1611 	void *temp_buffer;
1612 	struct auich_dma *p;
1613 	u_int rate;
1614 
1615 	/*
1616 	 * Grab audio from input for fixed interval and compare how
1617 	 * much we actually get with what we expect.  Interval needs
1618 	 * to be sufficiently short that no interrupts are
1619 	 * generated.
1620 	 */
1621 
1622 	/* Force the codec to a known state first. */
1623 	sc->codec_if->vtbl->set_clock(sc->codec_if, 48000);
1624 	rate = sc->sc_ac97_clock = 48000;
1625 	sc->codec_if->vtbl->set_rate(sc->codec_if, AC97_REG_PCM_LR_ADC_RATE,
1626 	    &rate);
1627 
1628 	/* Setup a buffer */
1629 	bytes = 64000;
1630 	temp_buffer = auich_allocm(sc, AUMODE_RECORD, bytes);
1631 
1632 	for (p = sc->sc_dmas; p && KERNADDR(p) != temp_buffer; p = p->next)
1633 		continue;
1634 	if (p == NULL) {
1635 		aprint_error_dev(sc->sc_dev, "%s: bad address %p\n",
1636 		    __func__, temp_buffer);
1637 		return;
1638 	}
1639 	sc->pcmi.dmalist[0].base = DMAADDR(p);
1640 	sc->pcmi.dmalist[0].len = (bytes >> sc->sc_sample_shift);
1641 
1642 	/*
1643 	 * our data format is stereo, 16 bit so each sample is 4 bytes.
1644 	 * assuming we get 48000 samples per second, we get 192000 bytes/sec.
1645 	 * we're going to start recording with interrupts disabled and measure
1646 	 * the time taken for one block to complete.  we know the block size,
1647 	 * we know the time in microseconds, we calculate the sample rate:
1648 	 *
1649 	 * actual_rate [bps] = bytes / (time [s] * 4)
1650 	 * actual_rate [bps] = (bytes * 1000000) / (time [us] * 4)
1651 	 * actual_rate [Hz] = (bytes * 250000) / time [us]
1652 	 */
1653 
1654 	/* prepare */
1655 	ociv = bus_space_read_1(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_CIV);
1656 	bus_space_write_4(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_BDBAR,
1657 			  sc->sc_cddma + ICH_PCMI_OFF(0));
1658 	bus_space_write_1(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_LVI,
1659 			  (0 - 1) & ICH_LVI_MASK);
1660 
1661 	/* start */
1662 	kpreempt_disable();
1663 	microtime(&t1);
1664 	bus_space_write_1(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_CTRL, ICH_RPBM);
1665 
1666 	/* wait */
1667 	nciv = ociv;
1668 	do {
1669 		microtime(&t2);
1670 		if (t2.tv_sec - t1.tv_sec > 1)
1671 			break;
1672 		nciv = bus_space_read_1(sc->iot, sc->aud_ioh,
1673 					ICH_PCMI + ICH_CIV);
1674 	} while (nciv == ociv);
1675 	microtime(&t2);
1676 
1677 	/* stop */
1678 	bus_space_write_1(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_CTRL, 0);
1679 	kpreempt_enable();
1680 
1681 	/* reset */
1682 	DELAY(100);
1683 	bus_space_write_1(sc->iot, sc->aud_ioh, ICH_PCMI + ICH_CTRL, ICH_RR);
1684 
1685 	/* turn time delta into us */
1686 	wait_us = ((t2.tv_sec - t1.tv_sec) * 1000000) + t2.tv_usec - t1.tv_usec;
1687 
1688 	auich_freem(sc, temp_buffer, bytes);
1689 
1690 	if (nciv == ociv) {
1691 		aprint_error_dev(sc->sc_dev, "ac97 link rate calibration "
1692 		    "timed out after %" PRIu64 " us\n", wait_us);
1693 		return;
1694 	}
1695 
1696 	if (wait_us == 0) {
1697 		/* Can happen with emulated hardware */
1698 		aprint_error_dev(sc->sc_dev, "abnormal zero delay during "
1699 		    "calibration\n");
1700 		return;
1701 	}
1702 
1703 	rnd_add_data(NULL, &wait_us, sizeof(wait_us), 1);
1704 
1705 	actual_48k_rate = (bytes * UINT64_C(250000)) / wait_us;
1706 
1707 	if (actual_48k_rate < 50000)
1708 		ac97rate = 48000;
1709 	else
1710 		ac97rate = ((actual_48k_rate + 500) / 1000) * 1000;
1711 
1712 	aprint_verbose_dev(sc->sc_dev, "measured ac97 link rate at %d Hz",
1713 	       actual_48k_rate);
1714 	if (ac97rate != actual_48k_rate)
1715 		aprint_verbose(", will use %d Hz", ac97rate);
1716 	aprint_verbose("\n");
1717 
1718 	sc->sc_ac97_clock = ac97rate;
1719 }
1720 
1721 static void
1722 auich_clear_cas(struct auich_softc *sc)
1723 {
1724 	/* Clear the codec access semaphore */
1725 	(void)bus_space_read_2(sc->iot, sc->mix_ioh,
1726 	    AC97_REG_RESET * (sc->sc_codecnum * ICH_CODEC_OFFSET));
1727 
1728 	return;
1729 }
1730 
1731 static void
1732 auich_get_locks(void *addr, kmutex_t **intr, kmutex_t **thread)
1733 {
1734 	struct auich_softc *sc;
1735 
1736 	sc = addr;
1737 	*intr = &sc->sc_intr_lock;
1738 	*thread = &sc->sc_lock;
1739 }
1740