xref: /openbsd-src/sys/dev/pci/azalia.c (revision f2da64fbbbf1b03f09f390ab01267c93dfd77c4c)
1 /*	$OpenBSD: azalia.c,v 1.229 2016/09/19 06:46:44 ratchov Exp $	*/
2 /*	$NetBSD: azalia.c,v 1.20 2006/05/07 08:31:44 kent Exp $	*/
3 
4 /*-
5  * Copyright (c) 2005 The NetBSD Foundation, Inc.
6  * All rights reserved.
7  *
8  * This code is derived from software contributed to The NetBSD Foundation
9  * by TAMURA Kent
10  *
11  * Redistribution and use in source and binary forms, with or without
12  * modification, are permitted provided that the following conditions
13  * are met:
14  * 1. Redistributions of source code must retain the above copyright
15  *    notice, this list of conditions and the following disclaimer.
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in the
18  *    documentation and/or other materials provided with the distribution.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE NETBSD FOUNDATION, INC. AND CONTRIBUTORS
21  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
22  * TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
23  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR CONTRIBUTORS
24  * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
25  * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
26  * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
27  * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
28  * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
29  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
30  * POSSIBILITY OF SUCH DAMAGE.
31  */
32 
33 /*
34  * High Definition Audio Specification
35  *	ftp://download.intel.com/standards/hdaudio/pdf/HDAudio_03.pdf
36  *
37  *
38  * TO DO:
39  *  - multiple codecs (needed?)
40  *  - multiple streams (needed?)
41  */
42 
43 #include <sys/param.h>
44 #include <sys/device.h>
45 #include <sys/malloc.h>
46 #include <sys/systm.h>
47 #include <sys/types.h>
48 #include <sys/timeout.h>
49 #include <dev/audio_if.h>
50 #include <dev/pci/pcidevs.h>
51 #include <dev/pci/pcivar.h>
52 
53 #include <dev/pci/azalia.h>
54 
55 typedef struct audio_params audio_params_t;
56 
57 struct audio_format {
58 	void *driver_data;
59 	int32_t mode;
60 	u_int encoding;
61 	u_int precision;
62 	u_int channels;
63 
64 	/**
65 	 * 0: frequency[0] is lower limit, and frequency[1] is higher limit.
66 	 * 1-16: frequency[0] to frequency[frequency_type-1] are valid.
67 	 */
68 	u_int frequency_type;
69 
70 #define	AUFMT_MAX_FREQUENCIES	16
71 	/**
72 	 * sampling rates
73 	 */
74 	u_int frequency[AUFMT_MAX_FREQUENCIES];
75 };
76 
77 
78 #ifdef AZALIA_DEBUG
79 # define DPRINTFN(n,x)	do { if (az_debug > (n)) printf x; } while (0/*CONSTCOND*/)
80 int az_debug = 0;
81 #else
82 # define DPRINTFN(n,x)	do {} while (0/*CONSTCOND*/)
83 #endif
84 
85 
86 /* ----------------------------------------------------------------
87  * ICH6/ICH7 constant values
88  * ---------------------------------------------------------------- */
89 
90 /* PCI registers */
91 #define ICH_PCI_HDBARL	0x10
92 #define ICH_PCI_HDBARU	0x14
93 #define ICH_PCI_HDCTL	0x40
94 #define		ICH_PCI_HDCTL_CLKDETCLR		0x08
95 #define		ICH_PCI_HDCTL_CLKDETEN		0x04
96 #define		ICH_PCI_HDCTL_CLKDETINV		0x02
97 #define		ICH_PCI_HDCTL_SIGNALMODE	0x01
98 #define ICH_PCI_HDTCSEL	0x44
99 #define		ICH_PCI_HDTCSEL_MASK	0x7
100 #define ICH_PCI_MMC	0x62
101 #define		ICH_PCI_MMC_ME		0x1
102 
103 /* internal types */
104 
105 typedef struct {
106 	bus_dmamap_t map;
107 	caddr_t addr;		/* kernel virtual address */
108 	bus_dma_segment_t segments[1];
109 	size_t size;
110 } azalia_dma_t;
111 #define AZALIA_DMA_DMAADDR(p)	((p)->map->dm_segs[0].ds_addr)
112 
113 typedef struct {
114 	struct azalia_t *az;
115 	int regbase;
116 	int number;
117 	int dir;		/* AUMODE_PLAY or AUMODE_RECORD */
118 	uint32_t intr_bit;
119 	azalia_dma_t bdlist;
120 	azalia_dma_t buffer;
121 	void (*intr)(void*);
122 	void *intr_arg;
123 	int bufsize;
124 	uint16_t fmt;
125 	int blk;
126 	unsigned int swpos;		/* position in the audio(4) layer */
127 } stream_t;
128 #define STR_READ_1(s, r)	\
129 	bus_space_read_1((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r)
130 #define STR_READ_2(s, r)	\
131 	bus_space_read_2((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r)
132 #define STR_READ_4(s, r)	\
133 	bus_space_read_4((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r)
134 #define STR_WRITE_1(s, r, v)	\
135 	bus_space_write_1((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r, v)
136 #define STR_WRITE_2(s, r, v)	\
137 	bus_space_write_2((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r, v)
138 #define STR_WRITE_4(s, r, v)	\
139 	bus_space_write_4((s)->az->iot, (s)->az->ioh, (s)->regbase + HDA_SD_##r, v)
140 
141 typedef struct azalia_t {
142 	struct device dev;
143 
144 	pci_chipset_tag_t pc;
145 	pcitag_t tag;
146 	void *ih;
147 	bus_space_tag_t iot;
148 	bus_space_handle_t ioh;
149 	bus_size_t map_size;
150 	bus_dma_tag_t dmat;
151 	pcireg_t pciid;
152 	uint32_t subid;
153 
154 	codec_t *codecs;
155 	int ncodecs;		/* number of codecs */
156 	int codecno;		/* index of the using codec */
157 	int detached;		/* 1 if failed to initialize, 2 if
158 				 * azalia_pci_detach has run
159 				 */
160 	azalia_dma_t corb_dma;
161 	int corb_entries;
162 	uint8_t corbsize;
163 	azalia_dma_t rirb_dma;
164 	int rirb_entries;
165 	uint8_t rirbsize;
166 	int rirb_rp;
167 #define UNSOLQ_SIZE	256
168 	rirb_entry_t *unsolq;
169 	int unsolq_wp;
170 	int unsolq_rp;
171 	int unsolq_kick;
172 	struct timeout unsol_to;
173 
174 	int ok64;
175 	int nistreams, nostreams, nbstreams;
176 	stream_t pstream;
177 	stream_t rstream;
178 } azalia_t;
179 #define XNAME(sc)		((sc)->dev.dv_xname)
180 #define AZ_READ_1(z, r)		bus_space_read_1((z)->iot, (z)->ioh, HDA_##r)
181 #define AZ_READ_2(z, r)		bus_space_read_2((z)->iot, (z)->ioh, HDA_##r)
182 #define AZ_READ_4(z, r)		bus_space_read_4((z)->iot, (z)->ioh, HDA_##r)
183 #define AZ_WRITE_1(z, r, v)	bus_space_write_1((z)->iot, (z)->ioh, HDA_##r, v)
184 #define AZ_WRITE_2(z, r, v)	bus_space_write_2((z)->iot, (z)->ioh, HDA_##r, v)
185 #define AZ_WRITE_4(z, r, v)	bus_space_write_4((z)->iot, (z)->ioh, HDA_##r, v)
186 
187 
188 /* prototypes */
189 uint8_t azalia_pci_read(pci_chipset_tag_t, pcitag_t, int);
190 void	azalia_pci_write(pci_chipset_tag_t, pcitag_t, int, uint8_t);
191 int	azalia_pci_match(struct device *, void *, void *);
192 void	azalia_pci_attach(struct device *, struct device *, void *);
193 int	azalia_pci_activate(struct device *, int);
194 int	azalia_pci_detach(struct device *, int);
195 void	azalia_configure_pci(azalia_t *);
196 int	azalia_intr(void *);
197 void	azalia_print_codec(codec_t *);
198 int	azalia_reset(azalia_t *);
199 int	azalia_get_ctrlr_caps(azalia_t *);
200 int	azalia_init(azalia_t *, int);
201 int	azalia_init_codecs(azalia_t *);
202 int	azalia_init_streams(azalia_t *);
203 void	azalia_shutdown(void *);
204 int	azalia_halt_corb(azalia_t *);
205 int	azalia_init_corb(azalia_t *, int);
206 int	azalia_halt_rirb(azalia_t *);
207 int	azalia_init_rirb(azalia_t *, int);
208 int	azalia_set_command(azalia_t *, nid_t, int, uint32_t, uint32_t);
209 int	azalia_get_response(azalia_t *, uint32_t *);
210 void	azalia_rirb_kick_unsol_events(void *);
211 void	azalia_rirb_intr(azalia_t *);
212 int	azalia_alloc_dmamem(azalia_t *, size_t, size_t, azalia_dma_t *);
213 int	azalia_free_dmamem(const azalia_t *, azalia_dma_t*);
214 
215 int	azalia_codec_init(codec_t *);
216 int	azalia_codec_delete(codec_t *);
217 void	azalia_codec_add_bits(codec_t *, int, uint32_t, int);
218 void	azalia_codec_add_format(codec_t *, int, int, uint32_t, int32_t);
219 int	azalia_codec_connect_stream(stream_t *);
220 int	azalia_codec_disconnect_stream(stream_t *);
221 void	azalia_codec_print_audiofunc(const codec_t *);
222 void	azalia_codec_print_groups(const codec_t *);
223 int	azalia_codec_find_defdac(codec_t *, int, int);
224 int	azalia_codec_find_defadc(codec_t *, int, int);
225 int	azalia_codec_find_defadc_sub(codec_t *, nid_t, int, int);
226 int	azalia_codec_init_volgroups(codec_t *);
227 int	azalia_codec_sort_pins(codec_t *);
228 int	azalia_codec_select_micadc(codec_t *);
229 int	azalia_codec_select_dacs(codec_t *);
230 int	azalia_codec_select_spkrdac(codec_t *);
231 int	azalia_codec_find_inputmixer(codec_t *);
232 
233 int	azalia_widget_init(widget_t *, const codec_t *, int);
234 int	azalia_widget_label_widgets(codec_t *);
235 int	azalia_widget_init_audio(widget_t *, const codec_t *);
236 int	azalia_widget_init_pin(widget_t *, const codec_t *);
237 int	azalia_widget_init_connection(widget_t *, const codec_t *);
238 int	azalia_widget_check_conn(codec_t *, int, int);
239 int	azalia_widget_sole_conn(codec_t *, nid_t);
240 void	azalia_widget_print_widget(const widget_t *, const codec_t *);
241 void	azalia_widget_print_audio(const widget_t *, const char *);
242 void	azalia_widget_print_pin(const widget_t *);
243 
244 int	azalia_stream_init(stream_t *, azalia_t *, int, int, int);
245 int	azalia_stream_reset(stream_t *);
246 int	azalia_stream_start(stream_t *);
247 int	azalia_stream_halt(stream_t *);
248 int	azalia_stream_intr(stream_t *);
249 
250 int	azalia_open(void *, int);
251 void	azalia_close(void *);
252 int	azalia_set_params(void *, int, int, audio_params_t *,
253 	audio_params_t *);
254 int	azalia_round_blocksize(void *, int);
255 int	azalia_halt_output(void *);
256 int	azalia_halt_input(void *);
257 int	azalia_set_port(void *, mixer_ctrl_t *);
258 int	azalia_get_port(void *, mixer_ctrl_t *);
259 int	azalia_query_devinfo(void *, mixer_devinfo_t *);
260 void	*azalia_allocm(void *, int, size_t, int, int);
261 void	azalia_freem(void *, void *, int);
262 size_t	azalia_round_buffersize(void *, int, size_t);
263 int	azalia_get_props(void *);
264 int	azalia_trigger_output(void *, void *, void *, int,
265 	void (*)(void *), void *, audio_params_t *);
266 int	azalia_trigger_input(void *, void *, void *, int,
267 	void (*)(void *), void *, audio_params_t *);
268 
269 int	azalia_params2fmt(const audio_params_t *, uint16_t *);
270 
271 int	azalia_match_format(codec_t *, int, audio_params_t *);
272 int	azalia_set_params_sub(codec_t *, int, audio_params_t *);
273 
274 void	azalia_save_mixer(codec_t *);
275 void	azalia_restore_mixer(codec_t *);
276 
277 int	azalia_suspend(azalia_t *);
278 int	azalia_resume(azalia_t *);
279 int	azalia_resume_codec(codec_t *);
280 
281 /* variables */
282 struct cfattach azalia_ca = {
283 	sizeof(azalia_t), azalia_pci_match, azalia_pci_attach,
284 	azalia_pci_detach, azalia_pci_activate
285 };
286 
287 struct cfdriver azalia_cd = {
288 	NULL, "azalia", DV_DULL
289 };
290 
291 struct audio_hw_if azalia_hw_if = {
292 	azalia_open,
293 	azalia_close,
294 	azalia_set_params,
295 	azalia_round_blocksize,
296 	NULL,			/* commit_settings */
297 	NULL,			/* init_output */
298 	NULL,			/* init_input */
299 	NULL,			/* start_output */
300 	NULL,			/* start_input */
301 	azalia_halt_output,
302 	azalia_halt_input,
303 	NULL,			/* speaker_ctl */
304 	NULL,			/* setfd */
305 	azalia_set_port,
306 	azalia_get_port,
307 	azalia_query_devinfo,
308 	azalia_allocm,
309 	azalia_freem,
310 	azalia_round_buffersize,
311 	azalia_get_props,
312 	azalia_trigger_output,
313 	azalia_trigger_input
314 };
315 
316 static const char *pin_devices[16] = {
317 	AudioNline, AudioNspeaker, AudioNheadphone, AudioNcd,
318 	"SPDIF", "digital-out", "modem-line", "modem-handset",
319 	"line-in", AudioNaux, AudioNmicrophone, "telephony",
320 	"SPDIF-in", "digital-in", "beep", "other"};
321 static const char *wtypes[16] = {
322 	"dac", "adc", "mix", "sel", "pin", "pow", "volume",
323 	"beep", "wid08", "wid09", "wid0a", "wid0b", "wid0c",
324 	"wid0d", "wid0e", "vendor"};
325 static const char *line_colors[16] = {
326 	"unk", "blk", "gry", "blu", "grn", "red", "org", "yel",
327 	"pur", "pnk", "0xa", "0xb", "0xc", "0xd", "wht", "oth"};
328 
329 /* ================================================================
330  * PCI functions
331  * ================================================================ */
332 
333 #define ATI_PCIE_SNOOP_REG		0x42
334 #define ATI_PCIE_SNOOP_MASK		0xf8
335 #define ATI_PCIE_SNOOP_ENABLE		0x02
336 #define NVIDIA_PCIE_SNOOP_REG		0x4e
337 #define NVIDIA_PCIE_SNOOP_MASK		0xf0
338 #define NVIDIA_PCIE_SNOOP_ENABLE	0x0f
339 #define NVIDIA_HDA_ISTR_COH_REG		0x4d
340 #define NVIDIA_HDA_OSTR_COH_REG		0x4c
341 #define NVIDIA_HDA_STR_COH_ENABLE	0x01
342 #define INTEL_PCIE_NOSNOOP_REG		0x79
343 #define INTEL_PCIE_NOSNOOP_MASK		0xf7
344 #define INTEL_PCIE_NOSNOOP_ENABLE	0x08
345 
346 uint8_t
347 azalia_pci_read(pci_chipset_tag_t pc, pcitag_t pa, int reg)
348 {
349 	return (pci_conf_read(pc, pa, (reg & ~0x03)) >>
350 	    ((reg & 0x03) * 8) & 0xff);
351 }
352 
353 void
354 azalia_pci_write(pci_chipset_tag_t pc, pcitag_t pa, int reg, uint8_t val)
355 {
356 	pcireg_t pcival;
357 
358 	pcival = pci_conf_read(pc, pa, (reg & ~0x03));
359 	pcival &= ~(0xff << ((reg & 0x03) * 8));
360 	pcival |= (val << ((reg & 0x03) * 8));
361 	pci_conf_write(pc, pa, (reg & ~0x03), pcival);
362 }
363 
364 void
365 azalia_configure_pci(azalia_t *az)
366 {
367 	pcireg_t v;
368 	uint8_t reg;
369 
370 	/* enable back-to-back */
371 	v = pci_conf_read(az->pc, az->tag, PCI_COMMAND_STATUS_REG);
372 	pci_conf_write(az->pc, az->tag, PCI_COMMAND_STATUS_REG,
373 	    v | PCI_COMMAND_BACKTOBACK_ENABLE);
374 
375 	/* traffic class select */
376 	v = pci_conf_read(az->pc, az->tag, ICH_PCI_HDTCSEL);
377 	pci_conf_write(az->pc, az->tag, ICH_PCI_HDTCSEL,
378 	    v & ~(ICH_PCI_HDTCSEL_MASK));
379 
380 	/* enable PCIe snoop */
381 	switch (PCI_PRODUCT(az->pciid)) {
382 	case PCI_PRODUCT_ATI_SB450_HDA:
383 	case PCI_PRODUCT_ATI_SBX00_HDA:
384 	case PCI_PRODUCT_AMD_HUDSON2_HDA:
385 		reg = azalia_pci_read(az->pc, az->tag, ATI_PCIE_SNOOP_REG);
386 		reg &= ATI_PCIE_SNOOP_MASK;
387 		reg |= ATI_PCIE_SNOOP_ENABLE;
388 		azalia_pci_write(az->pc, az->tag, ATI_PCIE_SNOOP_REG, reg);
389 		break;
390 	case PCI_PRODUCT_NVIDIA_MCP51_HDA:
391 	case PCI_PRODUCT_NVIDIA_MCP55_HDA:
392 	case PCI_PRODUCT_NVIDIA_MCP61_HDA_1:
393 	case PCI_PRODUCT_NVIDIA_MCP61_HDA_2:
394 	case PCI_PRODUCT_NVIDIA_MCP65_HDA_1:
395 	case PCI_PRODUCT_NVIDIA_MCP65_HDA_2:
396 	case PCI_PRODUCT_NVIDIA_MCP67_HDA_1:
397 	case PCI_PRODUCT_NVIDIA_MCP67_HDA_2:
398 	case PCI_PRODUCT_NVIDIA_MCP73_HDA_1:
399 	case PCI_PRODUCT_NVIDIA_MCP73_HDA_2:
400 	case PCI_PRODUCT_NVIDIA_MCP77_HDA_1:
401 	case PCI_PRODUCT_NVIDIA_MCP77_HDA_2:
402 	case PCI_PRODUCT_NVIDIA_MCP77_HDA_3:
403 	case PCI_PRODUCT_NVIDIA_MCP77_HDA_4:
404 	case PCI_PRODUCT_NVIDIA_MCP79_HDA_1:
405 	case PCI_PRODUCT_NVIDIA_MCP79_HDA_2:
406 	case PCI_PRODUCT_NVIDIA_MCP79_HDA_3:
407 	case PCI_PRODUCT_NVIDIA_MCP79_HDA_4:
408 	case PCI_PRODUCT_NVIDIA_MCP89_HDA_1:
409 	case PCI_PRODUCT_NVIDIA_MCP89_HDA_2:
410 	case PCI_PRODUCT_NVIDIA_MCP89_HDA_3:
411 	case PCI_PRODUCT_NVIDIA_MCP89_HDA_4:
412 		reg = azalia_pci_read(az->pc, az->tag,
413 		    NVIDIA_HDA_OSTR_COH_REG);
414 		reg |= NVIDIA_HDA_STR_COH_ENABLE;
415 		azalia_pci_write(az->pc, az->tag,
416 		    NVIDIA_HDA_OSTR_COH_REG, reg);
417 
418 		reg = azalia_pci_read(az->pc, az->tag,
419 		    NVIDIA_HDA_ISTR_COH_REG);
420 		reg |= NVIDIA_HDA_STR_COH_ENABLE;
421 		azalia_pci_write(az->pc, az->tag,
422 		    NVIDIA_HDA_ISTR_COH_REG, reg);
423 
424 		reg = azalia_pci_read(az->pc, az->tag,
425 		    NVIDIA_PCIE_SNOOP_REG);
426 		reg &= NVIDIA_PCIE_SNOOP_MASK;
427 		reg |= NVIDIA_PCIE_SNOOP_ENABLE;
428 		azalia_pci_write(az->pc, az->tag,
429 		    NVIDIA_PCIE_SNOOP_REG, reg);
430 
431 		reg = azalia_pci_read(az->pc, az->tag,
432 		    NVIDIA_PCIE_SNOOP_REG);
433 		if ((reg & NVIDIA_PCIE_SNOOP_ENABLE) !=
434 		    NVIDIA_PCIE_SNOOP_ENABLE) {
435 			printf(": could not enable PCIe cache snooping!\n");
436 		}
437 		break;
438 	case PCI_PRODUCT_INTEL_82801FB_HDA:
439 	case PCI_PRODUCT_INTEL_82801GB_HDA:
440 	case PCI_PRODUCT_INTEL_82801H_HDA:
441 	case PCI_PRODUCT_INTEL_82801I_HDA:
442 	case PCI_PRODUCT_INTEL_82801JI_HDA:
443 	case PCI_PRODUCT_INTEL_82801JD_HDA:
444 	case PCI_PRODUCT_INTEL_6321ESB_HDA:
445 	case PCI_PRODUCT_INTEL_3400_HDA:
446 	case PCI_PRODUCT_INTEL_QS57_HDA:
447 	case PCI_PRODUCT_INTEL_6SERIES_HDA:
448 	case PCI_PRODUCT_INTEL_7SERIES_HDA:
449 	case PCI_PRODUCT_INTEL_8SERIES_HDA:
450 	case PCI_PRODUCT_INTEL_8SERIES_LP_HDA:
451 	case PCI_PRODUCT_INTEL_9SERIES_HDA:
452 	case PCI_PRODUCT_INTEL_9SERIES_LP_HDA:
453 	case PCI_PRODUCT_INTEL_BAYTRAIL_HDA:
454 	case PCI_PRODUCT_INTEL_100SERIES_HDA:
455 	case PCI_PRODUCT_INTEL_100SERIES_LP_HDA:
456 	case PCI_PRODUCT_INTEL_C600_HDA:
457 	case PCI_PRODUCT_INTEL_C610_HDA:
458 		reg = azalia_pci_read(az->pc, az->tag,
459 		    INTEL_PCIE_NOSNOOP_REG);
460 		reg &= INTEL_PCIE_NOSNOOP_MASK;
461 		azalia_pci_write(az->pc, az->tag,
462 		    INTEL_PCIE_NOSNOOP_REG, reg);
463 		break;
464 	}
465 }
466 
467 int
468 azalia_pci_match(struct device *parent, void *match, void *aux)
469 {
470 	struct pci_attach_args *pa;
471 
472 	pa = aux;
473 	if (PCI_CLASS(pa->pa_class) == PCI_CLASS_MULTIMEDIA
474 	    && PCI_SUBCLASS(pa->pa_class) == PCI_SUBCLASS_MULTIMEDIA_HDAUDIO)
475 		return 1;
476 	return 0;
477 }
478 
479 void
480 azalia_pci_attach(struct device *parent, struct device *self, void *aux)
481 {
482 	azalia_t *sc;
483 	struct pci_attach_args *pa;
484 	pcireg_t v;
485 	uint8_t reg;
486 	pci_intr_handle_t ih;
487 	const char *interrupt_str;
488 
489 	sc = (azalia_t*)self;
490 	pa = aux;
491 
492 	sc->dmat = pa->pa_dmat;
493 
494 	pci_set_powerstate(pa->pa_pc, pa->pa_tag, PCI_PMCSR_STATE_D0);
495 
496 	v = pci_conf_read(pa->pa_pc, pa->pa_tag, ICH_PCI_HDBARL);
497 	v &= PCI_MAPREG_TYPE_MASK | PCI_MAPREG_MEM_TYPE_MASK;
498 	if (pci_mapreg_map(pa, ICH_PCI_HDBARL, v, 0,
499 			   &sc->iot, &sc->ioh, NULL, &sc->map_size, 0)) {
500 		printf(": can't map device i/o space\n");
501 		return;
502 	}
503 
504 	sc->pc = pa->pa_pc;
505 	sc->tag = pa->pa_tag;
506 	sc->pciid = pa->pa_id;
507 	sc->subid = pci_conf_read(pa->pa_pc, pa->pa_tag, PCI_SUBSYS_ID_REG);
508 
509 	azalia_configure_pci(sc);
510 
511 	/* disable MSI, use INTx instead */
512 	if (PCI_VENDOR(sc->pciid) == PCI_VENDOR_INTEL) {
513 		reg = azalia_pci_read(sc->pc, sc->tag, ICH_PCI_MMC);
514 		reg &= ~(ICH_PCI_MMC_ME);
515 		azalia_pci_write(sc->pc, sc->tag, ICH_PCI_MMC, reg);
516 	}
517 
518 	/* interrupt */
519 	if (pci_intr_map_msi(pa, &ih) && pci_intr_map(pa, &ih)) {
520 		printf(": can't map interrupt\n");
521 		return;
522 	}
523 	interrupt_str = pci_intr_string(pa->pa_pc, ih);
524 	sc->ih = pci_intr_establish(pa->pa_pc, ih, IPL_AUDIO | IPL_MPSAFE,
525 	    azalia_intr, sc, sc->dev.dv_xname);
526 	if (sc->ih == NULL) {
527 		printf(": can't establish interrupt");
528 		if (interrupt_str != NULL)
529 			printf(" at %s", interrupt_str);
530 		printf("\n");
531 		return;
532 	}
533 	printf(": %s\n", interrupt_str);
534 
535 	if (azalia_init(sc, 0))
536 		goto err_exit;
537 
538 	if (azalia_init_codecs(sc))
539 		goto err_exit;
540 
541 	if (azalia_init_streams(sc))
542 		goto err_exit;
543 
544 	audio_attach_mi(&azalia_hw_if, sc, &sc->dev);
545 
546 	return;
547 
548 err_exit:
549 	sc->detached = 1;
550 	azalia_pci_detach(self, 0);
551 }
552 
553 int
554 azalia_pci_activate(struct device *self, int act)
555 {
556 	azalia_t *sc = (azalia_t*)self;
557 	int rv = 0;
558 
559 	switch (act) {
560 	case DVACT_SUSPEND:
561 		azalia_suspend(sc);
562 		break;
563 	case DVACT_POWERDOWN:
564 		azalia_shutdown(sc);
565 		break;
566 	case DVACT_RESUME:
567 		azalia_resume(sc);
568 		rv = config_activate_children(self, act);
569 		break;
570 	default:
571 		rv = config_activate_children(self, act);
572 		break;
573 	}
574 	return (rv);
575 }
576 
577 int
578 azalia_pci_detach(struct device *self, int flags)
579 {
580 	azalia_t *az = (azalia_t*)self;
581 	uint32_t gctl;
582 	int i;
583 
584 	DPRINTF(("%s\n", __func__));
585 
586 	/*
587 	 * this function is called if the device could not be supported,
588 	 * in which case az->detached == 1.  check if this function has
589 	 * already cleaned up.
590 	 */
591 	if (az->detached > 1)
592 		return 0;
593 
594 	config_detach_children(self, flags);
595 
596 	/* disable unsolicited responses if soft detaching */
597 	if (az->detached == 1) {
598 		gctl = AZ_READ_4(az, GCTL);
599 		AZ_WRITE_4(az, GCTL, gctl &~(HDA_GCTL_UNSOL));
600 	}
601 
602 	timeout_del(&az->unsol_to);
603 
604 	DPRINTF(("%s: delete streams\n", __func__));
605 	if (az->rstream.bdlist.addr != NULL)
606 		azalia_free_dmamem(az, &az->rstream.bdlist);
607 	if (az->pstream.bdlist.addr != NULL)
608 		azalia_free_dmamem(az, &az->pstream.bdlist);
609 
610 	DPRINTF(("%s: delete codecs\n", __func__));
611 	for (i = 0; i < az->ncodecs; i++) {
612 		azalia_codec_delete(&az->codecs[i]);
613 	}
614 	az->ncodecs = 0;
615 	if (az->codecs != NULL) {
616 		free(az->codecs, M_DEVBUF, 0);
617 		az->codecs = NULL;
618 	}
619 
620 	DPRINTF(("%s: delete CORB and RIRB\n", __func__));
621 	if (az->corb_dma.addr != NULL)
622 		azalia_free_dmamem(az, &az->corb_dma);
623 	if (az->rirb_dma.addr != NULL)
624 		azalia_free_dmamem(az, &az->rirb_dma);
625 	if (az->unsolq != NULL) {
626 		free(az->unsolq, M_DEVBUF, 0);
627 		az->unsolq = NULL;
628 	}
629 
630 	/* disable interrupts if soft detaching */
631 	if (az->detached == 1) {
632 		DPRINTF(("%s: disable interrupts\n", __func__));
633 		AZ_WRITE_4(az, INTCTL, 0);
634 
635 		DPRINTF(("%s: clear interrupts\n", __func__));
636 		AZ_WRITE_4(az, INTSTS, HDA_INTSTS_CIS | HDA_INTSTS_GIS);
637 		AZ_WRITE_2(az, STATESTS, HDA_STATESTS_SDIWAKE);
638 		AZ_WRITE_1(az, RIRBSTS, HDA_RIRBSTS_RINTFL | HDA_RIRBSTS_RIRBOIS);
639 	}
640 
641 	DPRINTF(("%s: delete PCI resources\n", __func__));
642 	if (az->ih != NULL) {
643 		pci_intr_disestablish(az->pc, az->ih);
644 		az->ih = NULL;
645 	}
646 	if (az->map_size != 0) {
647 		bus_space_unmap(az->iot, az->ioh, az->map_size);
648 		az->map_size = 0;
649 	}
650 
651 	az->detached = 2;
652 	return 0;
653 }
654 
655 int
656 azalia_intr(void *v)
657 {
658 	azalia_t *az = v;
659 	uint32_t intsts;
660 	int ret = 0;
661 
662 	mtx_enter(&audio_lock);
663 	intsts = AZ_READ_4(az, INTSTS);
664 	if (intsts == 0 || intsts == 0xffffffff) {
665 		mtx_leave(&audio_lock);
666 		return (ret);
667 	}
668 
669 	AZ_WRITE_4(az, INTSTS, intsts);
670 
671 	if (intsts & az->pstream.intr_bit) {
672 		azalia_stream_intr(&az->pstream);
673 		ret = 1;
674 	}
675 
676 	if (intsts & az->rstream.intr_bit) {
677 		azalia_stream_intr(&az->rstream);
678 		ret = 1;
679 	}
680 
681 	if ((intsts & HDA_INTSTS_CIS) &&
682 	    (AZ_READ_1(az, RIRBCTL) & HDA_RIRBCTL_RINTCTL) &&
683 	    (AZ_READ_1(az, RIRBSTS) & HDA_RIRBSTS_RINTFL)) {
684 		azalia_rirb_intr(az);
685 		ret = 1;
686 	}
687 	mtx_leave(&audio_lock);
688 	return (ret);
689 }
690 
691 void
692 azalia_shutdown(void *v)
693 {
694 	azalia_t *az = (azalia_t *)v;
695 	uint32_t gctl;
696 
697 	/* disable unsolicited response */
698 	gctl = AZ_READ_4(az, GCTL);
699 	AZ_WRITE_4(az, GCTL, gctl & ~(HDA_GCTL_UNSOL));
700 
701 	timeout_del(&az->unsol_to);
702 
703 	/* halt CORB/RIRB */
704 	azalia_halt_corb(az);
705 	azalia_halt_rirb(az);
706 }
707 
708 /* ================================================================
709  * HDA controller functions
710  * ================================================================ */
711 
712 void
713 azalia_print_codec(codec_t *codec)
714 {
715 	const char *vendor;
716 
717 	if (codec->name == NULL) {
718 		vendor = pci_findvendor(codec->vid >> 16);
719 		if (vendor == NULL)
720 			printf("0x%04x/0x%04x",
721 			    codec->vid >> 16, codec->vid & 0xffff);
722 		else
723 			printf("%s/0x%04x", vendor, codec->vid & 0xffff);
724 	} else
725 		printf("%s", codec->name);
726 }
727 
728 int
729 azalia_reset(azalia_t *az)
730 {
731 	uint32_t gctl;
732 	int i;
733 
734 	/* 4.2.2 Starting the High Definition Audio Controller */
735 	DPRINTF(("%s: resetting\n", __func__));
736 	gctl = AZ_READ_4(az, GCTL);
737 	AZ_WRITE_4(az, GCTL, gctl & ~HDA_GCTL_CRST);
738 	for (i = 5000; i > 0; i--) {
739 		DELAY(10);
740 		if ((AZ_READ_4(az, GCTL) & HDA_GCTL_CRST) == 0)
741 			break;
742 	}
743 	DPRINTF(("%s: reset counter = %d\n", __func__, i));
744 	if (i == 0) {
745 		DPRINTF(("%s: reset failure\n", XNAME(az)));
746 		return(ETIMEDOUT);
747 	}
748 	DELAY(1000);
749 	gctl = AZ_READ_4(az, GCTL);
750 	AZ_WRITE_4(az, GCTL, gctl | HDA_GCTL_CRST);
751 	for (i = 5000; i > 0; i--) {
752 		DELAY(10);
753 		if (AZ_READ_4(az, GCTL) & HDA_GCTL_CRST)
754 			break;
755 	}
756 	DPRINTF(("%s: reset counter = %d\n", __func__, i));
757 	if (i == 0) {
758 		DPRINTF(("%s: reset-exit failure\n", XNAME(az)));
759 		return(ETIMEDOUT);
760 	}
761 	DELAY(1000);
762 
763 	return(0);
764 }
765 
766 int
767 azalia_get_ctrlr_caps(azalia_t *az)
768 {
769 	int i, n;
770 	uint16_t gcap;
771 	uint16_t statests;
772 	uint8_t cap;
773 
774 	DPRINTF(("%s: host: High Definition Audio rev. %d.%d\n",
775 	    XNAME(az), AZ_READ_1(az, VMAJ), AZ_READ_1(az, VMIN)));
776 	gcap = AZ_READ_2(az, GCAP);
777 	az->nistreams = HDA_GCAP_ISS(gcap);
778 	az->nostreams = HDA_GCAP_OSS(gcap);
779 	az->nbstreams = HDA_GCAP_BSS(gcap);
780 	az->ok64 = (gcap & HDA_GCAP_64OK) != 0;
781 	DPRINTF(("%s: host: %d output, %d input, and %d bidi streams\n",
782 	    XNAME(az), az->nostreams, az->nistreams, az->nbstreams));
783 
784 	/* 4.3 Codec discovery */
785 	statests = AZ_READ_2(az, STATESTS);
786 	for (i = 0, n = 0; i < HDA_MAX_CODECS; i++) {
787 		if ((statests >> i) & 1) {
788 			DPRINTF(("%s: found a codec at #%d\n", XNAME(az), i));
789 			n++;
790 		}
791 	}
792 	az->ncodecs = n;
793 	if (az->ncodecs < 1) {
794 		printf("%s: no HD-Audio codecs\n", XNAME(az));
795 		return -1;
796 	}
797 	az->codecs = mallocarray(az->ncodecs, sizeof(codec_t), M_DEVBUF,
798 	    M_NOWAIT | M_ZERO);
799 	if (az->codecs == NULL) {
800 		printf("%s: can't allocate memory for codecs\n", XNAME(az));
801 		return ENOMEM;
802 	}
803 	for (i = 0, n = 0; n < az->ncodecs; i++) {
804 		if ((statests >> i) & 1) {
805 			az->codecs[n].address = i;
806 			az->codecs[n++].az = az;
807 		}
808 	}
809 
810 	/* determine CORB size */
811 	az->corbsize = AZ_READ_1(az, CORBSIZE);
812 	cap = az->corbsize & HDA_CORBSIZE_CORBSZCAP_MASK;
813 	az->corbsize  &= ~HDA_CORBSIZE_CORBSIZE_MASK;
814 	if (cap & HDA_CORBSIZE_CORBSZCAP_256) {
815 		az->corb_entries = 256;
816 		az->corbsize |= HDA_CORBSIZE_CORBSIZE_256;
817 	} else if (cap & HDA_CORBSIZE_CORBSZCAP_16) {
818 		az->corb_entries = 16;
819 		az->corbsize |= HDA_CORBSIZE_CORBSIZE_16;
820 	} else if (cap & HDA_CORBSIZE_CORBSZCAP_2) {
821 		az->corb_entries = 2;
822 		az->corbsize |= HDA_CORBSIZE_CORBSIZE_2;
823 	} else {
824 		printf("%s: invalid CORBSZCAP: 0x%2x\n", XNAME(az), cap);
825 		return(-1);
826 	}
827 
828 	/* determine RIRB size */
829 	az->rirbsize = AZ_READ_1(az, RIRBSIZE);
830 	cap = az->rirbsize & HDA_RIRBSIZE_RIRBSZCAP_MASK;
831 	az->rirbsize &= ~HDA_RIRBSIZE_RIRBSIZE_MASK;
832 	if (cap & HDA_RIRBSIZE_RIRBSZCAP_256) {
833 		az->rirb_entries = 256;
834 		az->rirbsize |= HDA_RIRBSIZE_RIRBSIZE_256;
835 	} else if (cap & HDA_RIRBSIZE_RIRBSZCAP_16) {
836 		az->rirb_entries = 16;
837 		az->rirbsize |= HDA_RIRBSIZE_RIRBSIZE_16;
838 	} else if (cap & HDA_RIRBSIZE_RIRBSZCAP_2) {
839 		az->rirb_entries = 2;
840 		az->rirbsize |= HDA_RIRBSIZE_RIRBSIZE_2;
841 	} else {
842 		printf("%s: invalid RIRBSZCAP: 0x%2x\n", XNAME(az), cap);
843 		return(-1);
844 	}
845 
846 	return(0);
847 }
848 
849 int
850 azalia_init(azalia_t *az, int resuming)
851 {
852 	int err;
853 
854 	err = azalia_reset(az);
855 	if (err)
856 		return(err);
857 
858 	if (!resuming) {
859 		err = azalia_get_ctrlr_caps(az);
860 		if (err)
861 			return(err);
862 	}
863 
864 	/* clear interrupt status */
865 	AZ_WRITE_2(az, STATESTS, HDA_STATESTS_SDIWAKE);
866 	AZ_WRITE_1(az, RIRBSTS, HDA_RIRBSTS_RINTFL | HDA_RIRBSTS_RIRBOIS);
867 	AZ_WRITE_4(az, INTSTS, HDA_INTSTS_CIS | HDA_INTSTS_GIS);
868 	AZ_WRITE_4(az, DPLBASE, 0);
869 	AZ_WRITE_4(az, DPUBASE, 0);
870 
871 	/* 4.4.1 Command Outbound Ring Buffer */
872 	err = azalia_init_corb(az, resuming);
873 	if (err)
874 		return(err);
875 
876 	/* 4.4.2 Response Inbound Ring Buffer */
877 	err = azalia_init_rirb(az, resuming);
878 	if (err)
879 		return(err);
880 
881 	AZ_WRITE_4(az, INTCTL,
882 	    AZ_READ_4(az, INTCTL) | HDA_INTCTL_CIE | HDA_INTCTL_GIE);
883 
884 	return(0);
885 }
886 
887 int
888 azalia_init_codecs(azalia_t *az)
889 {
890 	codec_t *codec;
891 	int c, i;
892 
893 	c = 0;
894 	for (i = 0; i < az->ncodecs; i++) {
895 		if (!azalia_codec_init(&az->codecs[i]))
896 			c++;
897 	}
898 	if (c == 0) {
899 		printf("%s: No codecs found\n", XNAME(az));
900 		return(1);
901 	}
902 
903 	/* Use the first codec capable of analog I/O.  If there are none,
904 	 * use the first codec capable of digital I/O.  Skip HDMI codecs.
905 	 */
906 	c = -1;
907 	for (i = 0; i < az->ncodecs; i++) {
908 		codec = &az->codecs[i];
909 		if ((codec->audiofunc < 0) ||
910 		    (codec->codec_type == AZ_CODEC_TYPE_HDMI))
911 			continue;
912 		if (codec->codec_type == AZ_CODEC_TYPE_DIGITAL) {
913 			if (c < 0)
914 				c = i;
915 		} else {
916 			c = i;
917 			break;
918 		}
919 	}
920 	az->codecno = c;
921 	if (az->codecno < 0) {
922 		printf("%s: no supported codecs\n", XNAME(az));
923 		return(1);
924 	}
925 
926 	printf("%s: codecs: ", XNAME(az));
927 	for (i = 0; i < az->ncodecs; i++) {
928 		azalia_print_codec(&az->codecs[i]);
929 		if (i < az->ncodecs - 1)
930 			printf(", ");
931 	}
932 	if (az->ncodecs > 1) {
933 		printf(", using ");
934 		azalia_print_codec(&az->codecs[az->codecno]);
935 	}
936 	printf("\n");
937 
938 	/* All codecs with audio are enabled, but only one will be used. */
939 	for (i = 0; i < az->ncodecs; i++) {
940 		codec = &az->codecs[i];
941 		if (i != az->codecno) {
942 			if (codec->audiofunc < 0)
943 				continue;
944 			azalia_comresp(codec, codec->audiofunc,
945 			    CORB_SET_POWER_STATE, CORB_PS_D3, NULL);
946 			DELAY(100);
947 			azalia_codec_delete(codec);
948 		}
949 	}
950 
951 	/* Enable unsolicited responses now that az->codecno is set. */
952 	AZ_WRITE_4(az, GCTL, AZ_READ_4(az, GCTL) | HDA_GCTL_UNSOL);
953 
954 	return(0);
955 }
956 
957 int
958 azalia_init_streams(azalia_t *az)
959 {
960 	int err;
961 
962 	/* Use stream#1 and #2.  Don't use stream#0. */
963 	err = azalia_stream_init(&az->pstream, az, az->nistreams + 0,
964 	    1, AUMODE_PLAY);
965 	if (err)
966 		return(err);
967 	err = azalia_stream_init(&az->rstream, az, 0, 2, AUMODE_RECORD);
968 	if (err)
969 		return(err);
970 
971 	return(0);
972 }
973 
974 int
975 azalia_halt_corb(azalia_t *az)
976 {
977 	uint8_t corbctl;
978 	int i;
979 
980 	corbctl = AZ_READ_1(az, CORBCTL);
981 	if (corbctl & HDA_CORBCTL_CORBRUN) { /* running? */
982 		AZ_WRITE_1(az, CORBCTL, corbctl & ~HDA_CORBCTL_CORBRUN);
983 		for (i = 5000; i > 0; i--) {
984 			DELAY(10);
985 			corbctl = AZ_READ_1(az, CORBCTL);
986 			if ((corbctl & HDA_CORBCTL_CORBRUN) == 0)
987 				break;
988 		}
989 		if (i == 0) {
990 			DPRINTF(("%s: CORB is running\n", XNAME(az)));
991 			return EBUSY;
992 		}
993 	}
994 	return(0);
995 }
996 
997 int
998 azalia_init_corb(azalia_t *az, int resuming)
999 {
1000 	int err, i;
1001 	uint16_t corbrp, corbwp;
1002 	uint8_t corbctl;
1003 
1004 	err = azalia_halt_corb(az);
1005 	if (err)
1006 		return(err);
1007 
1008 	if (!resuming) {
1009 		err = azalia_alloc_dmamem(az,
1010 		    az->corb_entries * sizeof(corb_entry_t), 128,
1011 		    &az->corb_dma);
1012 		if (err) {
1013 			printf("%s: can't allocate CORB buffer\n", XNAME(az));
1014 			return(err);
1015 		}
1016 		DPRINTF(("%s: CORB allocation succeeded.\n", __func__));
1017 	}
1018 	timeout_set(&az->unsol_to, azalia_rirb_kick_unsol_events, az);
1019 
1020 	AZ_WRITE_4(az, CORBLBASE, (uint32_t)AZALIA_DMA_DMAADDR(&az->corb_dma));
1021 	AZ_WRITE_4(az, CORBUBASE, PTR_UPPER32(AZALIA_DMA_DMAADDR(&az->corb_dma)));
1022 	AZ_WRITE_1(az, CORBSIZE, az->corbsize);
1023 
1024 	/* reset CORBRP */
1025 	corbrp = AZ_READ_2(az, CORBRP);
1026 	AZ_WRITE_2(az, CORBRP, corbrp | HDA_CORBRP_CORBRPRST);
1027 	AZ_WRITE_2(az, CORBRP, corbrp & ~HDA_CORBRP_CORBRPRST);
1028 	for (i = 5000; i > 0; i--) {
1029 		DELAY(10);
1030 		corbrp = AZ_READ_2(az, CORBRP);
1031 		if ((corbrp & HDA_CORBRP_CORBRPRST) == 0)
1032 			break;
1033 	}
1034 	if (i == 0) {
1035 		DPRINTF(("%s: CORBRP reset failure\n", XNAME(az)));
1036 		return -1;
1037 	}
1038 	DPRINTF(("%s: CORBWP=%d; size=%d\n", __func__,
1039 		 AZ_READ_2(az, CORBRP) & HDA_CORBRP_CORBRP, az->corb_entries));
1040 
1041 	/* clear CORBWP */
1042 	corbwp = AZ_READ_2(az, CORBWP);
1043 	AZ_WRITE_2(az, CORBWP, corbwp & ~HDA_CORBWP_CORBWP);
1044 
1045 	/* Run! */
1046 	corbctl = AZ_READ_1(az, CORBCTL);
1047 	AZ_WRITE_1(az, CORBCTL, corbctl | HDA_CORBCTL_CORBRUN);
1048 	return 0;
1049 }
1050 
1051 int
1052 azalia_halt_rirb(azalia_t *az)
1053 {
1054 	int i;
1055 	uint8_t rirbctl;
1056 
1057 	rirbctl = AZ_READ_1(az, RIRBCTL);
1058 	if (rirbctl & HDA_RIRBCTL_RIRBDMAEN) { /* running? */
1059 		AZ_WRITE_1(az, RIRBCTL, rirbctl & ~HDA_RIRBCTL_RIRBDMAEN);
1060 		for (i = 5000; i > 0; i--) {
1061 			DELAY(10);
1062 			rirbctl = AZ_READ_1(az, RIRBCTL);
1063 			if ((rirbctl & HDA_RIRBCTL_RIRBDMAEN) == 0)
1064 				break;
1065 		}
1066 		if (i == 0) {
1067 			DPRINTF(("%s: RIRB is running\n", XNAME(az)));
1068 			return(EBUSY);
1069 		}
1070 	}
1071 	return(0);
1072 }
1073 
1074 int
1075 azalia_init_rirb(azalia_t *az, int resuming)
1076 {
1077 	int err, i;
1078 	uint16_t rirbwp;
1079 	uint8_t rirbctl;
1080 
1081 	err = azalia_halt_rirb(az);
1082 	if (err)
1083 		return(err);
1084 
1085 	if (!resuming) {
1086 		err = azalia_alloc_dmamem(az,
1087 		    az->rirb_entries * sizeof(rirb_entry_t), 128,
1088 		    &az->rirb_dma);
1089 		if (err) {
1090 			printf("%s: can't allocate RIRB buffer\n", XNAME(az));
1091 			return err;
1092 		}
1093 		DPRINTF(("%s: RIRB allocation succeeded.\n", __func__));
1094 
1095 		/* setup the unsolicited response queue */
1096 		az->unsolq = malloc(sizeof(rirb_entry_t) * UNSOLQ_SIZE,
1097 		    M_DEVBUF, M_NOWAIT | M_ZERO);
1098 		if (az->unsolq == NULL) {
1099 			DPRINTF(("%s: can't allocate unsolicited response queue.\n",
1100 			    XNAME(az)));
1101 			azalia_free_dmamem(az, &az->rirb_dma);
1102 			return ENOMEM;
1103 		}
1104 	}
1105 	AZ_WRITE_4(az, RIRBLBASE, (uint32_t)AZALIA_DMA_DMAADDR(&az->rirb_dma));
1106 	AZ_WRITE_4(az, RIRBUBASE, PTR_UPPER32(AZALIA_DMA_DMAADDR(&az->rirb_dma)));
1107 	AZ_WRITE_1(az, RIRBSIZE, az->rirbsize);
1108 
1109 	/* reset the write pointer */
1110 	rirbwp = AZ_READ_2(az, RIRBWP);
1111 	AZ_WRITE_2(az, RIRBWP, rirbwp | HDA_RIRBWP_RIRBWPRST);
1112 
1113 	/* clear the read pointer */
1114 	az->rirb_rp = AZ_READ_2(az, RIRBWP) & HDA_RIRBWP_RIRBWP;
1115 	DPRINTF(("%s: RIRBRP=%d, size=%d\n", __func__, az->rirb_rp,
1116 	    az->rirb_entries));
1117 
1118 	az->unsolq_rp = 0;
1119 	az->unsolq_wp = 0;
1120 	az->unsolq_kick = 0;
1121 
1122 	AZ_WRITE_2(az, RINTCNT, 1);
1123 
1124 	/* Run! */
1125 	rirbctl = AZ_READ_1(az, RIRBCTL);
1126 	AZ_WRITE_1(az, RIRBCTL, rirbctl |
1127 	    HDA_RIRBCTL_RIRBDMAEN | HDA_RIRBCTL_RINTCTL);
1128 	for (i = 5000; i > 0; i--) {
1129 		DELAY(10);
1130 		rirbctl = AZ_READ_1(az, RIRBCTL);
1131 		if (rirbctl & HDA_RIRBCTL_RIRBDMAEN)
1132 			break;
1133 	}
1134 	if (i == 0) {
1135 		DPRINTF(("%s: RIRB is not running\n", XNAME(az)));
1136 		return(EBUSY);
1137 	}
1138 
1139 	return (0);
1140 }
1141 
1142 int
1143 azalia_comresp(const codec_t *codec, nid_t nid, uint32_t control,
1144     uint32_t param, uint32_t* result)
1145 {
1146 	int err;
1147 
1148 	mtx_enter(&audio_lock);
1149 	err = azalia_set_command(codec->az, codec->address, nid, control,
1150 	    param);
1151 	if (err)
1152 		goto exit;
1153 	err = azalia_get_response(codec->az, result);
1154 exit:
1155 	mtx_leave(&audio_lock);
1156 	return(err);
1157 }
1158 
1159 int
1160 azalia_set_command(azalia_t *az, int caddr, nid_t nid, uint32_t control,
1161     uint32_t param)
1162 {
1163 	corb_entry_t *corb;
1164 	int  wp;
1165 	uint32_t verb;
1166 	uint16_t corbwp;
1167 
1168 	if ((AZ_READ_1(az, CORBCTL) & HDA_CORBCTL_CORBRUN) == 0) {
1169 		printf("%s: CORB is not running.\n", XNAME(az));
1170 		return(-1);
1171 	}
1172 	verb = (caddr << 28) | (nid << 20) | (control << 8) | param;
1173 	corbwp = AZ_READ_2(az, CORBWP);
1174 	wp = corbwp & HDA_CORBWP_CORBWP;
1175 	corb = (corb_entry_t*)az->corb_dma.addr;
1176 	if (++wp >= az->corb_entries)
1177 		wp = 0;
1178 	corb[wp] = verb;
1179 
1180 	AZ_WRITE_2(az, CORBWP, (corbwp & ~HDA_CORBWP_CORBWP) | wp);
1181 
1182 	return(0);
1183 }
1184 
1185 int
1186 azalia_get_response(azalia_t *az, uint32_t *result)
1187 {
1188 	const rirb_entry_t *rirb;
1189 	int i;
1190 	uint16_t wp;
1191 
1192 	if ((AZ_READ_1(az, RIRBCTL) & HDA_RIRBCTL_RIRBDMAEN) == 0) {
1193 		printf("%s: RIRB is not running.\n", XNAME(az));
1194 		return(-1);
1195 	}
1196 
1197 	rirb = (rirb_entry_t*)az->rirb_dma.addr;
1198 	i = 5000;
1199 	for (;;) {
1200 		while (i > 0) {
1201 			wp = AZ_READ_2(az, RIRBWP) & HDA_RIRBWP_RIRBWP;
1202 			if (az->rirb_rp != wp)
1203 				break;
1204 			DELAY(10);
1205 			i--;
1206 		}
1207 		if (i == 0) {
1208 			DPRINTF(("%s: RIRB time out\n", XNAME(az)));
1209 			return(ETIMEDOUT);
1210 		}
1211 		if (++az->rirb_rp >= az->rirb_entries)
1212 			az->rirb_rp = 0;
1213 		if (rirb[az->rirb_rp].resp_ex & RIRB_RESP_UNSOL) {
1214 			az->unsolq[az->unsolq_wp].resp = rirb[az->rirb_rp].resp;
1215 			az->unsolq[az->unsolq_wp++].resp_ex = rirb[az->rirb_rp].resp_ex;
1216 			az->unsolq_wp %= UNSOLQ_SIZE;
1217 		} else
1218 			break;
1219 	}
1220 	if (result != NULL)
1221 		*result = rirb[az->rirb_rp].resp;
1222 
1223 	return(0);
1224 }
1225 
1226 void
1227 azalia_rirb_kick_unsol_events(void *v)
1228 {
1229 	azalia_t *az = v;
1230 	int addr, tag;
1231 
1232 	if (az->unsolq_kick)
1233 		return;
1234 	az->unsolq_kick = 1;
1235 	while (az->unsolq_rp != az->unsolq_wp) {
1236 		addr = RIRB_RESP_CODEC(az->unsolq[az->unsolq_rp].resp_ex);
1237 		tag = RIRB_UNSOL_TAG(az->unsolq[az->unsolq_rp].resp);
1238 		DPRINTF(("%s: codec address=%d tag=%d\n", __func__, addr, tag));
1239 
1240 		az->unsolq_rp++;
1241 		az->unsolq_rp %= UNSOLQ_SIZE;
1242 
1243 		/* We only care about events on the using codec. */
1244 		if (az->codecs[az->codecno].address == addr)
1245 			azalia_unsol_event(&az->codecs[az->codecno], tag);
1246 	}
1247 	az->unsolq_kick = 0;
1248 }
1249 
1250 void
1251 azalia_rirb_intr(azalia_t *az)
1252 {
1253 	const rirb_entry_t *rirb;
1254 	uint16_t wp;
1255 	uint8_t rirbsts;
1256 
1257 	rirbsts = AZ_READ_1(az, RIRBSTS);
1258 
1259 	wp = AZ_READ_2(az, RIRBWP) & HDA_RIRBWP_RIRBWP;
1260 	rirb = (rirb_entry_t*)az->rirb_dma.addr;
1261 	while (az->rirb_rp != wp) {
1262 		if (++az->rirb_rp >= az->rirb_entries)
1263 			az->rirb_rp = 0;
1264 		if (rirb[az->rirb_rp].resp_ex & RIRB_RESP_UNSOL) {
1265 			az->unsolq[az->unsolq_wp].resp = rirb[az->rirb_rp].resp;
1266 			az->unsolq[az->unsolq_wp++].resp_ex = rirb[az->rirb_rp].resp_ex;
1267 			az->unsolq_wp %= UNSOLQ_SIZE;
1268 		} else {
1269 			DPRINTF(("%s: dropped solicited response\n", __func__));
1270 		}
1271 	}
1272 	timeout_add_msec(&az->unsol_to, 1);
1273 
1274 	AZ_WRITE_1(az, RIRBSTS,
1275 	    rirbsts | HDA_RIRBSTS_RIRBOIS | HDA_RIRBSTS_RINTFL);
1276 }
1277 
1278 int
1279 azalia_alloc_dmamem(azalia_t *az, size_t size, size_t align, azalia_dma_t *d)
1280 {
1281 	int err;
1282 	int nsegs;
1283 
1284 	d->size = size;
1285 	err = bus_dmamem_alloc(az->dmat, size, align, 0, d->segments, 1,
1286 	    &nsegs, BUS_DMA_NOWAIT);
1287 	if (err)
1288 		return err;
1289 	if (nsegs != 1)
1290 		goto free;
1291 	err = bus_dmamem_map(az->dmat, d->segments, 1, size,
1292 	    &d->addr, BUS_DMA_NOWAIT | BUS_DMA_COHERENT);
1293 	if (err)
1294 		goto free;
1295 	err = bus_dmamap_create(az->dmat, size, 1, size, 0,
1296 	    BUS_DMA_NOWAIT, &d->map);
1297 	if (err)
1298 		goto unmap;
1299 	err = bus_dmamap_load(az->dmat, d->map, d->addr, size,
1300 	    NULL, BUS_DMA_NOWAIT);
1301 	if (err)
1302 		goto destroy;
1303 
1304 	if (!az->ok64 && PTR_UPPER32(AZALIA_DMA_DMAADDR(d)) != 0) {
1305 		azalia_free_dmamem(az, d);
1306 		return -1;
1307 	}
1308 	return 0;
1309 
1310 destroy:
1311 	bus_dmamap_destroy(az->dmat, d->map);
1312 unmap:
1313 	bus_dmamem_unmap(az->dmat, d->addr, size);
1314 free:
1315 	bus_dmamem_free(az->dmat, d->segments, 1);
1316 	d->addr = NULL;
1317 	return err;
1318 }
1319 
1320 int
1321 azalia_free_dmamem(const azalia_t *az, azalia_dma_t* d)
1322 {
1323 	if (d->addr == NULL)
1324 		return 0;
1325 	bus_dmamap_unload(az->dmat, d->map);
1326 	bus_dmamap_destroy(az->dmat, d->map);
1327 	bus_dmamem_unmap(az->dmat, d->addr, d->size);
1328 	bus_dmamem_free(az->dmat, d->segments, 1);
1329 	d->addr = NULL;
1330 	return 0;
1331 }
1332 
1333 int
1334 azalia_suspend(azalia_t *az)
1335 {
1336 	int err;
1337 
1338 	if (az->detached)
1339 		return 0;
1340 
1341 	/* disable unsolicited responses */
1342 	AZ_WRITE_4(az, GCTL, AZ_READ_4(az, GCTL) & ~HDA_GCTL_UNSOL);
1343 
1344 	timeout_del(&az->unsol_to);
1345 
1346 	azalia_save_mixer(&az->codecs[az->codecno]);
1347 	/* azalia_halt_{corb,rirb}() only fail if the {CORB,RIRB} can't
1348 	 * be stopped and azalia_init_{corb,rirb}(), which starts the
1349 	 * {CORB,RIRB}, first calls azalia_halt_{corb,rirb}().  If halt
1350 	 * fails, don't try to restart.
1351 	 */
1352 	err = azalia_halt_corb(az);
1353 	if (err)
1354 		goto corb_fail;
1355 
1356 	err = azalia_halt_rirb(az);
1357 	if (err)
1358 		goto rirb_fail;
1359 
1360 	/* stop interrupts and clear status registers */
1361 	AZ_WRITE_4(az, INTCTL, 0);
1362 	AZ_WRITE_4(az, INTSTS, HDA_INTSTS_CIS | HDA_INTSTS_GIS);
1363 	AZ_WRITE_2(az, STATESTS, HDA_STATESTS_SDIWAKE);
1364 	AZ_WRITE_1(az, RIRBSTS, HDA_RIRBSTS_RINTFL | HDA_RIRBSTS_RIRBOIS);
1365 
1366 	return 0;
1367 
1368 rirb_fail:
1369 	azalia_init_corb(az, 1);
1370 corb_fail:
1371 	AZ_WRITE_4(az, GCTL, AZ_READ_4(az, GCTL) | HDA_GCTL_UNSOL);
1372 
1373 	return err;
1374 }
1375 
1376 int
1377 azalia_resume_codec(codec_t *this)
1378 {
1379 	widget_t *w;
1380 	uint32_t result;
1381 	int i, err;
1382 
1383 	err = azalia_comresp(this, this->audiofunc, CORB_SET_POWER_STATE,
1384  	    CORB_PS_D0, &result);
1385 	if (err) {
1386 		DPRINTF(("%s: power audio func error: result=0x%8.8x\n",
1387 		    __func__, result));
1388 	}
1389 	DELAY(100);
1390 
1391 	FOR_EACH_WIDGET(this, i) {
1392 		w = &this->w[i];
1393 		if (w->widgetcap & COP_AWCAP_POWER) {
1394 			azalia_comresp(this, w->nid, CORB_SET_POWER_STATE,
1395 			    CORB_PS_D0, &result);
1396 			DELAY(100);
1397 		}
1398 		if (w->type == COP_AWTYPE_PIN_COMPLEX)
1399 			azalia_widget_init_pin(w, this);
1400 		if (this->qrks & AZ_QRK_WID_MASK)
1401 			azalia_codec_widget_quirks(this, w->nid);
1402 	}
1403 
1404 	if (this->qrks & AZ_QRK_GPIO_MASK) {
1405 		err = azalia_codec_gpio_quirks(this);
1406 		if (err)
1407 			return err;
1408 	}
1409 
1410 	azalia_restore_mixer(this);
1411 
1412 	return(0);
1413 }
1414 
1415 int
1416 azalia_resume(azalia_t *az)
1417 {
1418 	int err;
1419 
1420 	if (az->detached)
1421 		return 0;
1422 
1423 	azalia_configure_pci(az);
1424 
1425 	/* is this necessary? */
1426 	pci_conf_write(az->pc, az->tag, PCI_SUBSYS_ID_REG, az->subid);
1427 
1428 	err = azalia_init(az, 1);
1429 	if (err)
1430 		return err;
1431 
1432 	/* enable unsolicited responses on the controller */
1433 	AZ_WRITE_4(az, GCTL, AZ_READ_4(az, GCTL) | HDA_GCTL_UNSOL);
1434 
1435 	err = azalia_resume_codec(&az->codecs[az->codecno]);
1436 	if (err)
1437 		return err;
1438 
1439 	err = azalia_codec_enable_unsol(&az->codecs[az->codecno]);
1440 	if (err)
1441 		return err;
1442 
1443 	return 0;
1444 }
1445 
1446 void
1447 azalia_save_mixer(codec_t *this)
1448 {
1449 	mixer_item_t *m;
1450 	mixer_ctrl_t mc;
1451 	int i;
1452 
1453 	for (i = 0; i < this->nmixers; i++) {
1454 		m = &this->mixers[i];
1455 		if (m->nid == this->playvols.master)
1456 			continue;
1457 		mc.dev = i;
1458 		mc.type = m->devinfo.type;
1459 		azalia_mixer_get(this, m->nid, m->target, &mc);
1460 		switch (mc.type) {
1461 		case AUDIO_MIXER_ENUM:
1462 			m->saved.ord = mc.un.ord;
1463 			break;
1464 		case AUDIO_MIXER_SET:
1465 			m->saved.mask = mc.un.mask;
1466 			break;
1467 		case AUDIO_MIXER_VALUE:
1468 			m->saved.value = mc.un.value;
1469 			break;
1470 		case AUDIO_MIXER_CLASS:
1471 			break;
1472 		default:
1473 			DPRINTF(("%s: invalid mixer type in mixer %d\n",
1474 			    __func__, mc.dev));
1475 			break;
1476 		}
1477 	}
1478 }
1479 
1480 void
1481 azalia_restore_mixer(codec_t *this)
1482 {
1483 	mixer_item_t *m;
1484 	mixer_ctrl_t mc;
1485 	int i;
1486 
1487 	for (i = 0; i < this->nmixers; i++) {
1488 		m = &this->mixers[i];
1489 		if (m->nid == this->playvols.master)
1490 			continue;
1491 		mc.dev = i;
1492 		mc.type = m->devinfo.type;
1493 		switch (mc.type) {
1494 		case AUDIO_MIXER_ENUM:
1495 			mc.un.ord = m->saved.ord;
1496 			break;
1497 		case AUDIO_MIXER_SET:
1498 			mc.un.mask = m->saved.mask;
1499 			break;
1500 		case AUDIO_MIXER_VALUE:
1501 			mc.un.value = m->saved.value;
1502 			break;
1503 		case AUDIO_MIXER_CLASS:
1504 			break;
1505 		default:
1506 			DPRINTF(("%s: invalid mixer type in mixer %d\n",
1507 			    __func__, mc.dev));
1508 			continue;
1509 		}
1510 		azalia_mixer_set(this, m->nid, m->target, &mc);
1511 	}
1512 }
1513 
1514 /* ================================================================
1515  * HDA codec functions
1516  * ================================================================ */
1517 
1518 int
1519 azalia_codec_init(codec_t *this)
1520 {
1521 	widget_t *w;
1522 	uint32_t rev, id, result;
1523 	int err, addr, n, i, nspdif, nhdmi;
1524 
1525 	addr = this->address;
1526 	/* codec vendor/device/revision */
1527 	err = azalia_comresp(this, CORB_NID_ROOT, CORB_GET_PARAMETER,
1528 	    COP_REVISION_ID, &rev);
1529 	if (err)
1530 		return err;
1531 	err = azalia_comresp(this, CORB_NID_ROOT, CORB_GET_PARAMETER,
1532 	    COP_VENDOR_ID, &id);
1533 	if (err)
1534 		return err;
1535 	this->vid = id;
1536 	this->subid = this->az->subid;
1537 	azalia_codec_init_vtbl(this);
1538 	DPRINTF(("%s: codec[%d] vid 0x%8.8x, subid 0x%8.8x, rev. %u.%u,",
1539 	    XNAME(this->az), addr, this->vid, this->subid,
1540 	    COP_RID_REVISION(rev), COP_RID_STEPPING(rev)));
1541 	DPRINTF((" HDA version %u.%u\n",
1542 	    COP_RID_MAJ(rev), COP_RID_MIN(rev)));
1543 
1544 	/* identify function nodes */
1545 	err = azalia_comresp(this, CORB_NID_ROOT, CORB_GET_PARAMETER,
1546 	    COP_SUBORDINATE_NODE_COUNT, &result);
1547 	if (err)
1548 		return err;
1549 	this->nfunctions = COP_NSUBNODES(result);
1550 	if (COP_NSUBNODES(result) <= 0) {
1551 		DPRINTF(("%s: codec[%d]: No function groups\n",
1552 		    XNAME(this->az), addr));
1553 		return -1;
1554 	}
1555 	/* iterate function nodes and find an audio function */
1556 	n = COP_START_NID(result);
1557 	DPRINTF(("%s: nidstart=%d #functions=%d\n",
1558 	    XNAME(this->az), n, this->nfunctions));
1559 	this->audiofunc = -1;
1560 	for (i = 0; i < this->nfunctions; i++) {
1561 		err = azalia_comresp(this, n + i, CORB_GET_PARAMETER,
1562 		    COP_FUNCTION_GROUP_TYPE, &result);
1563 		if (err)
1564 			continue;
1565 		DPRINTF(("%s: FTYPE result = 0x%8.8x\n", __func__, result));
1566 		if (COP_FTYPE(result) == COP_FTYPE_AUDIO) {
1567 			this->audiofunc = n + i;
1568 			break;	/* XXX multiple audio functions? */
1569 		}
1570 	}
1571 	if (this->audiofunc < 0) {
1572 		DPRINTF(("%s: codec[%d]: No audio function groups\n",
1573 		    XNAME(this->az), addr));
1574 		return -1;
1575 	}
1576 
1577 	/* power the audio function */
1578 	azalia_comresp(this, this->audiofunc, CORB_SET_POWER_STATE,
1579 	    CORB_PS_D0, &result);
1580 	DELAY(100);
1581 
1582 	/* check widgets in the audio function */
1583 	err = azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
1584 	    COP_SUBORDINATE_NODE_COUNT, &result);
1585 	if (err)
1586 		return err;
1587 	DPRINTF(("%s: There are %d widgets in the audio function.\n",
1588 	   __func__, COP_NSUBNODES(result)));
1589 	this->wstart = COP_START_NID(result);
1590 	if (this->wstart < 2) {
1591 		printf("%s: invalid node structure\n", XNAME(this->az));
1592 		return -1;
1593 	}
1594 	this->wend = this->wstart + COP_NSUBNODES(result);
1595 	this->w = mallocarray(this->wend, sizeof(widget_t), M_DEVBUF,
1596 	    M_NOWAIT | M_ZERO);
1597 	if (this->w == NULL) {
1598 		printf("%s: out of memory\n", XNAME(this->az));
1599 		return ENOMEM;
1600 	}
1601 
1602 	/* query the base parameters */
1603 	azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
1604 	    COP_STREAM_FORMATS, &result);
1605 	this->w[this->audiofunc].d.audio.encodings = result;
1606 	azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
1607 	    COP_PCM, &result);
1608 	this->w[this->audiofunc].d.audio.bits_rates = result;
1609 	azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
1610 	    COP_INPUT_AMPCAP, &result);
1611 	this->w[this->audiofunc].inamp_cap = result;
1612 	azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
1613 	    COP_OUTPUT_AMPCAP, &result);
1614 	this->w[this->audiofunc].outamp_cap = result;
1615 
1616 	azalia_codec_print_audiofunc(this);
1617 
1618 	strlcpy(this->w[CORB_NID_ROOT].name, "root",
1619 	    sizeof(this->w[CORB_NID_ROOT].name));
1620 	strlcpy(this->w[this->audiofunc].name, "hdaudio",
1621 	    sizeof(this->w[this->audiofunc].name));
1622 	this->w[this->audiofunc].enable = 1;
1623 
1624 	FOR_EACH_WIDGET(this, i) {
1625 		w = &this->w[i];
1626 		err = azalia_widget_init(w, this, i);
1627 		if (err)
1628 			return err;
1629 		err = azalia_widget_init_connection(w, this);
1630 		if (err)
1631 			return err;
1632 
1633 		azalia_widget_print_widget(w, this);
1634 
1635 		if (this->qrks & AZ_QRK_WID_MASK) {
1636 			azalia_codec_widget_quirks(this, i);
1637 		}
1638 	}
1639 
1640 	this->na_dacs = this->na_dacs_d = 0;
1641 	this->na_adcs = this->na_adcs_d = 0;
1642 	this->speaker = this->speaker2 = this->spkr_dac =
1643 	    this->fhp = this->fhp_dac =
1644 	    this->mic = this->mic_adc = -1;
1645 	this->nsense_pins = 0;
1646 	this->nout_jacks = 0;
1647 	nspdif = nhdmi = 0;
1648 	FOR_EACH_WIDGET(this, i) {
1649 		w = &this->w[i];
1650 
1651 		if (!w->enable)
1652 			continue;
1653 
1654 		switch (w->type) {
1655 
1656 		case COP_AWTYPE_AUDIO_MIXER:
1657 		case COP_AWTYPE_AUDIO_SELECTOR:
1658 			if (!azalia_widget_check_conn(this, i, 0))
1659 				w->enable = 0;
1660 			break;
1661 
1662 		case COP_AWTYPE_AUDIO_OUTPUT:
1663 			if ((w->widgetcap & COP_AWCAP_DIGITAL) == 0) {
1664 				if (this->na_dacs < HDA_MAX_CHANNELS)
1665 					this->a_dacs[this->na_dacs++] = i;
1666 			} else {
1667 				if (this->na_dacs_d < HDA_MAX_CHANNELS)
1668 					this->a_dacs_d[this->na_dacs_d++] = i;
1669 			}
1670 			break;
1671 
1672 		case COP_AWTYPE_AUDIO_INPUT:
1673 			if ((w->widgetcap & COP_AWCAP_DIGITAL) == 0) {
1674 				if (this->na_adcs < HDA_MAX_CHANNELS)
1675 					this->a_adcs[this->na_adcs++] = i;
1676 			} else {
1677 				if (this->na_adcs_d < HDA_MAX_CHANNELS)
1678 					this->a_adcs_d[this->na_adcs_d++] = i;
1679 			}
1680 			break;
1681 
1682 		case COP_AWTYPE_PIN_COMPLEX:
1683 			switch (CORB_CD_PORT(w->d.pin.config)) {
1684 			case CORB_CD_FIXED:
1685 				switch (w->d.pin.device) {
1686 				case CORB_CD_SPEAKER:
1687 					if (this->speaker == -1) {
1688 						this->speaker = i;
1689 					} else if (w->d.pin.association <
1690 					    this->w[this->speaker].d.pin.association ||
1691 					    (w->d.pin.association ==
1692 					    this->w[this->speaker].d.pin.association &&
1693 					    w->d.pin.sequence <
1694 					    this->w[this->speaker].d.pin.sequence)) {
1695 						this->speaker2 = this->speaker;
1696 						this->speaker = i;
1697 					} else {
1698 						this->speaker2 = i;
1699 					}
1700 					if (this->speaker == i)
1701 						this->spkr_dac =
1702 						    azalia_codec_find_defdac(this, i, 0);
1703 					break;
1704 				case CORB_CD_MICIN:
1705 					this->mic = i;
1706 					this->mic_adc =
1707 					    azalia_codec_find_defadc(this, i, 0);
1708 					break;
1709 				}
1710 				break;
1711 			case CORB_CD_JACK:
1712 				if (w->d.pin.device == CORB_CD_LINEOUT)
1713 					this->nout_jacks++;
1714 				else if (w->d.pin.device == CORB_CD_HEADPHONE &&
1715 				    CORB_CD_LOC_GEO(w->d.pin.config) ==
1716 				    CORB_CD_FRONT) {
1717 					this->fhp = i;
1718 					this->fhp_dac =
1719 					    azalia_codec_find_defdac(this, i, 0);
1720 				}
1721 				if (this->nsense_pins >= HDA_MAX_SENSE_PINS ||
1722 				    !(w->d.pin.cap & COP_PINCAP_PRESENCE))
1723 					break;
1724 				/* check override bit */
1725 				err = azalia_comresp(this, i,
1726 				    CORB_GET_CONFIGURATION_DEFAULT, 0, &result);
1727 				if (err)
1728 					break;
1729 				if (!(CORB_CD_MISC(result) & CORB_CD_PRESENCEOV)) {
1730 					this->sense_pins[this->nsense_pins++] = i;
1731 				}
1732 				break;
1733 			}
1734 			if ((w->d.pin.device == CORB_CD_DIGITALOUT) &&
1735 			    (w->d.pin.cap & COP_PINCAP_HDMI))
1736 				nhdmi++;
1737 			else if (w->d.pin.device == CORB_CD_SPDIFOUT ||
1738 			    w->d.pin.device == CORB_CD_SPDIFIN)
1739 				nspdif++;
1740 			break;
1741 		}
1742 	}
1743 	this->codec_type = AZ_CODEC_TYPE_ANALOG;
1744 	if ((this->na_dacs == 0) && (this->na_adcs == 0)) {
1745 		this->codec_type = AZ_CODEC_TYPE_DIGITAL;
1746 		if (nspdif == 0 && nhdmi > 0)
1747 			this->codec_type = AZ_CODEC_TYPE_HDMI;
1748 	}
1749 
1750 	/* make sure built-in mic is connected to an adc */
1751 	if (this->mic != -1 && this->mic_adc == -1) {
1752 		if (azalia_codec_select_micadc(this)) {
1753 			DPRINTF(("%s: cound not select mic adc\n", __func__));
1754 		}
1755 	}
1756 
1757 	err = azalia_codec_sort_pins(this);
1758 	if (err)
1759 		return err;
1760 
1761 	err = azalia_codec_find_inputmixer(this);
1762 	if (err)
1763 		return err;
1764 
1765 	/* If the codec can do multichannel, select different DACs for
1766 	 * the multichannel jack group.  Also be sure to keep track of
1767 	 * which DAC the front headphone is connected to.
1768 	 */
1769 	if (this->na_dacs >= 3 && this->nopins >= 3) {
1770 		err = azalia_codec_select_dacs(this);
1771 		if (err)
1772 			return err;
1773 	}
1774 
1775 	err = azalia_codec_select_spkrdac(this);
1776 	if (err)
1777 		return err;
1778 
1779 	err = azalia_init_dacgroup(this);
1780 	if (err)
1781 		return err;
1782 
1783 	azalia_codec_print_groups(this);
1784 
1785 	err = azalia_widget_label_widgets(this);
1786 	if (err)
1787 		return err;
1788 
1789 	err = azalia_codec_construct_format(this, 0, 0);
1790 	if (err)
1791 		return err;
1792 
1793 	err = azalia_codec_init_volgroups(this);
1794 	if (err)
1795 		return err;
1796 
1797 	if (this->qrks & AZ_QRK_GPIO_MASK) {
1798 		err = azalia_codec_gpio_quirks(this);
1799 		if (err)
1800 			return err;
1801 	}
1802 
1803 	err = azalia_mixer_init(this);
1804 	if (err)
1805 		return err;
1806 
1807 	return 0;
1808 }
1809 
1810 int
1811 azalia_codec_find_inputmixer(codec_t *this)
1812 {
1813 	widget_t *w;
1814 	int i, j;
1815 
1816 	this->input_mixer = -1;
1817 
1818 	FOR_EACH_WIDGET(this, i) {
1819 		w = &this->w[i];
1820 		if (w->type != COP_AWTYPE_AUDIO_MIXER)
1821 			continue;
1822 
1823 		/* can input from a pin */
1824 		for (j = 0; j < this->nipins; j++) {
1825 			if (azalia_codec_fnode(this, this->ipins[j].nid,
1826 			    w->nid, 0) != -1)
1827 				break;
1828 		}
1829 		if (j == this->nipins)
1830 			continue;
1831 
1832 		/* can output to a pin */
1833 		for (j = 0; j < this->nopins; j++) {
1834 			if (azalia_codec_fnode(this, w->nid,
1835 			    this->opins[j].nid, 0) != -1)
1836 				break;
1837 		}
1838 		if (j == this->nopins)
1839 			continue;
1840 
1841 		/* can output to an ADC */
1842 		for (j = 0; j < this->na_adcs; j++) {
1843 			if (azalia_codec_fnode(this, w->nid,
1844 			    this->a_adcs[j], 0) != -1)
1845 				break;
1846 		}
1847 		if (j == this->na_adcs)
1848 			continue;
1849 
1850 		this->input_mixer = i;
1851 		break;
1852 	}
1853 	return(0);
1854 }
1855 
1856 int
1857 azalia_codec_select_micadc(codec_t *this)
1858 {
1859 	widget_t *w;
1860 	int i, j, conv, err;
1861 
1862 	for (i = 0; i < this->na_adcs; i++) {
1863 		if (azalia_codec_fnode(this, this->mic,
1864 		    this->a_adcs[i], 0) >= 0)
1865 			break;
1866 	}
1867 	if (i >= this->na_adcs)
1868 		return(-1);
1869 	conv = this->a_adcs[i];
1870 
1871 	w = &this->w[conv];
1872 	for (j = 0; j < 10; j++) {
1873 		for (i = 0; i < w->nconnections; i++) {
1874 			if (!azalia_widget_enabled(this, w->connections[i]))
1875 				continue;
1876 			if (azalia_codec_fnode(this, this->mic,
1877 			    w->connections[i], j + 1) >= 0) {
1878 				break;
1879 			}
1880 		}
1881 		if (i >= w->nconnections)
1882 			return(-1);
1883 		err = azalia_comresp(this, w->nid,
1884 		    CORB_SET_CONNECTION_SELECT_CONTROL, i, 0);
1885 		if (err)
1886 			return(err);
1887 		w->selected = i;
1888 		if (w->connections[i] == this->mic) {
1889 			this->mic_adc = conv;
1890 			return(0);
1891 		}
1892 		w = &this->w[w->connections[i]];
1893 	}
1894 	return(-1);
1895 }
1896 
1897 int
1898 azalia_codec_sort_pins(codec_t *this)
1899 {
1900 #define MAX_PINS	16
1901 	const widget_t *w;
1902 	struct io_pin opins[MAX_PINS], opins_d[MAX_PINS];
1903 	struct io_pin ipins[MAX_PINS], ipins_d[MAX_PINS];
1904 	int nopins, nopins_d, nipins, nipins_d;
1905 	int prio, loc, add, nd, conv;
1906 	int i, j, k;
1907 
1908 	nopins = nopins_d = nipins = nipins_d = 0;
1909 
1910 	FOR_EACH_WIDGET(this, i) {
1911 		w = &this->w[i];
1912 		if (!w->enable || w->type != COP_AWTYPE_PIN_COMPLEX)
1913 			continue;
1914 
1915 		loc = 0;
1916 		if (this->na_dacs >= 3 && this->nout_jacks < 3)
1917 			loc = CORB_CD_LOC_GEO(w->d.pin.config);
1918 
1919 		prio = w->d.pin.association << 4 | w->d.pin.sequence;
1920 		conv = -1;
1921 
1922 		/* analog out */
1923 		if ((w->d.pin.cap & COP_PINCAP_OUTPUT) &&
1924 		    !(w->widgetcap & COP_AWCAP_DIGITAL)) {
1925 			add = nd = 0;
1926 			conv = azalia_codec_find_defdac(this, w->nid, 0);
1927 			switch(w->d.pin.device) {
1928 			/* primary - output by default */
1929 			case CORB_CD_SPEAKER:
1930 				if (w->nid == this->speaker ||
1931 				    w->nid == this->speaker2)
1932 					break;
1933 				/* FALLTHROUGH */
1934 			case CORB_CD_HEADPHONE:
1935 			case CORB_CD_LINEOUT:
1936 				add = 1;
1937 				break;
1938 			/* secondary - input by default */
1939 			case CORB_CD_MICIN:
1940 				if (w->nid == this->mic)
1941 					break;
1942 				/* FALLTHROUGH */
1943 			case CORB_CD_LINEIN:
1944 				add = nd = 1;
1945 				break;
1946 			}
1947 			if (add && nopins < MAX_PINS) {
1948 				opins[nopins].nid = w->nid;
1949 				opins[nopins].conv = conv;
1950 				prio |= (nd << 8) | (loc << 9);
1951 				opins[nopins].prio = prio;
1952 				nopins++;
1953 			}
1954 		}
1955 		/* digital out */
1956 		if ((w->d.pin.cap & COP_PINCAP_OUTPUT) &&
1957 		    (w->widgetcap & COP_AWCAP_DIGITAL)) {
1958 			conv = azalia_codec_find_defdac(this, w->nid, 0);
1959 			switch(w->d.pin.device) {
1960 			case CORB_CD_SPDIFOUT:
1961 			case CORB_CD_DIGITALOUT:
1962 				if (nopins_d < MAX_PINS) {
1963 					opins_d[nopins_d].nid = w->nid;
1964 					opins_d[nopins_d].conv = conv;
1965 					opins_d[nopins_d].prio = prio;
1966 					nopins_d++;
1967 				}
1968 				break;
1969 			}
1970 		}
1971 		/* analog in */
1972 		if ((w->d.pin.cap & COP_PINCAP_INPUT) &&
1973 		    !(w->widgetcap & COP_AWCAP_DIGITAL)) {
1974 			add = nd = 0;
1975 			conv = azalia_codec_find_defadc(this, w->nid, 0);
1976 			switch(w->d.pin.device) {
1977 			/* primary - input by default */
1978 			case CORB_CD_MICIN:
1979 			case CORB_CD_LINEIN:
1980 				add = 1;
1981 				break;
1982 			/* secondary - output by default */
1983 			case CORB_CD_SPEAKER:
1984 				if (w->nid == this->speaker ||
1985 				    w->nid == this->speaker2)
1986 					break;
1987 				/* FALLTHROUGH */
1988 			case CORB_CD_HEADPHONE:
1989 			case CORB_CD_LINEOUT:
1990 				add = nd = 1;
1991 				break;
1992 			}
1993 			if (add && nipins < MAX_PINS) {
1994 				ipins[nipins].nid = w->nid;
1995 				ipins[nipins].prio = prio | (nd << 8);
1996 				ipins[nipins].conv = conv;
1997 				nipins++;
1998 			}
1999 		}
2000 		/* digital in */
2001 		if ((w->d.pin.cap & COP_PINCAP_INPUT) &&
2002 		    (w->widgetcap & COP_AWCAP_DIGITAL)) {
2003 			conv = azalia_codec_find_defadc(this, w->nid, 0);
2004 			switch(w->d.pin.device) {
2005 			case CORB_CD_SPDIFIN:
2006 			case CORB_CD_DIGITALIN:
2007 			case CORB_CD_MICIN:
2008 				if (nipins_d < MAX_PINS) {
2009 					ipins_d[nipins_d].nid = w->nid;
2010 					ipins_d[nipins_d].prio = prio;
2011 					ipins_d[nipins_d].conv = conv;
2012 					nipins_d++;
2013 				}
2014 				break;
2015 			}
2016 		}
2017 	}
2018 
2019 	this->opins = mallocarray(nopins, sizeof(struct io_pin), M_DEVBUF,
2020 	    M_NOWAIT | M_ZERO);
2021 	if (this->opins == NULL)
2022 		return(ENOMEM);
2023 	this->nopins = 0;
2024 	for (i = 0; i < nopins; i++) {
2025 		for (j = 0; j < this->nopins; j++)
2026 			if (this->opins[j].prio > opins[i].prio)
2027 				break;
2028 		for (k = this->nopins; k > j; k--)
2029 			this->opins[k] = this->opins[k - 1];
2030 		if (j < nopins)
2031 			this->opins[j] = opins[i];
2032 		this->nopins++;
2033 		if (this->nopins == nopins)
2034 			break;
2035 	}
2036 
2037 	this->opins_d = mallocarray(nopins_d, sizeof(struct io_pin), M_DEVBUF,
2038 	    M_NOWAIT | M_ZERO);
2039 	if (this->opins_d == NULL)
2040 		return(ENOMEM);
2041 	this->nopins_d = 0;
2042 	for (i = 0; i < nopins_d; i++) {
2043 		for (j = 0; j < this->nopins_d; j++)
2044 			if (this->opins_d[j].prio > opins_d[i].prio)
2045 				break;
2046 		for (k = this->nopins_d; k > j; k--)
2047 			this->opins_d[k] = this->opins_d[k - 1];
2048 		if (j < nopins_d)
2049 			this->opins_d[j] = opins_d[i];
2050 		this->nopins_d++;
2051 		if (this->nopins_d == nopins_d)
2052 			break;
2053 	}
2054 
2055 	this->ipins = mallocarray(nipins, sizeof(struct io_pin), M_DEVBUF,
2056 	    M_NOWAIT | M_ZERO);
2057 	if (this->ipins == NULL)
2058 		return(ENOMEM);
2059 	this->nipins = 0;
2060 	for (i = 0; i < nipins; i++) {
2061 		for (j = 0; j < this->nipins; j++)
2062 			if (this->ipins[j].prio > ipins[i].prio)
2063 				break;
2064 		for (k = this->nipins; k > j; k--)
2065 			this->ipins[k] = this->ipins[k - 1];
2066 		if (j < nipins)
2067 			this->ipins[j] = ipins[i];
2068 		this->nipins++;
2069 		if (this->nipins == nipins)
2070 			break;
2071 	}
2072 
2073 	this->ipins_d = mallocarray(nipins_d, sizeof(struct io_pin), M_DEVBUF,
2074 	    M_NOWAIT | M_ZERO);
2075 	if (this->ipins_d == NULL)
2076 		return(ENOMEM);
2077 	this->nipins_d = 0;
2078 	for (i = 0; i < nipins_d; i++) {
2079 		for (j = 0; j < this->nipins_d; j++)
2080 			if (this->ipins_d[j].prio > ipins_d[i].prio)
2081 				break;
2082 		for (k = this->nipins_d; k > j; k--)
2083 			this->ipins_d[k] = this->ipins_d[k - 1];
2084 		if (j < nipins_d)
2085 			this->ipins_d[j] = ipins_d[i];
2086 		this->nipins_d++;
2087 		if (this->nipins_d == nipins_d)
2088 			break;
2089 	}
2090 
2091 #ifdef AZALIA_DEBUG
2092 	printf("%s: analog out pins:", __func__);
2093 	for (i = 0; i < this->nopins; i++)
2094 		printf(" 0x%2.2x->0x%2.2x", this->opins[i].nid,
2095 		    this->opins[i].conv);
2096 	printf("\n");
2097 	printf("%s: digital out pins:", __func__);
2098 	for (i = 0; i < this->nopins_d; i++)
2099 		printf(" 0x%2.2x->0x%2.2x", this->opins_d[i].nid,
2100 		    this->opins_d[i].conv);
2101 	printf("\n");
2102 	printf("%s: analog in pins:", __func__);
2103 	for (i = 0; i < this->nipins; i++)
2104 		printf(" 0x%2.2x->0x%2.2x", this->ipins[i].nid,
2105 		    this->ipins[i].conv);
2106 	printf("\n");
2107 	printf("%s: digital in pins:", __func__);
2108 	for (i = 0; i < this->nipins_d; i++)
2109 		printf(" 0x%2.2x->0x%2.2x", this->ipins_d[i].nid,
2110 		    this->ipins_d[i].conv);
2111 	printf("\n");
2112 #endif
2113 
2114 	return 0;
2115 #undef MAX_PINS
2116 }
2117 
2118 int
2119 azalia_codec_select_dacs(codec_t *this)
2120 {
2121 	widget_t *w;
2122 	nid_t *convs;
2123 	int nconv, conv;
2124 	int i, j, k, err;
2125 
2126 	convs = mallocarray(this->na_dacs, sizeof(nid_t), M_DEVBUF,
2127 	    M_NOWAIT | M_ZERO);
2128 	if (convs == NULL)
2129 		return(ENOMEM);
2130 
2131 	err = 0;
2132 	nconv = 0;
2133 	for (i = 0; i < this->nopins; i++) {
2134 		w = &this->w[this->opins[i].nid];
2135 
2136 		conv = this->opins[i].conv;
2137 		for (j = 0; j < nconv; j++) {
2138 			if (conv == convs[j])
2139 				break;
2140 		}
2141 		if (j == nconv) {
2142 			convs[nconv++] = conv;
2143 			if (w->nid == this->fhp)
2144 				this->fhp_dac = conv;
2145 			if (nconv >= this->na_dacs) {
2146 				break;
2147 			}
2148 		} else {
2149 			/* find a different dac */
2150 			conv = -1;
2151 			for (j = 0; j < w->nconnections; j++) {
2152 				if (!azalia_widget_enabled(this,
2153 				    w->connections[j]))
2154 					continue;
2155 				conv = azalia_codec_find_defdac(this,
2156 				    w->connections[j], 1);
2157 				if (conv == -1)
2158 					continue;
2159 				for (k = 0; k < nconv; k++) {
2160 					if (conv == convs[k])
2161 						break;
2162 				}
2163 				if (k == nconv)
2164 					break;
2165 			}
2166 			if (j < w->nconnections && conv != -1) {
2167 				err = azalia_comresp(this, w->nid,
2168 				    CORB_SET_CONNECTION_SELECT_CONTROL, j, 0);
2169 				if (err)
2170 					break;
2171 				w->selected = j;
2172 				this->opins[i].conv = conv;
2173 				if (w->nid == this->fhp)
2174 					this->fhp_dac = conv;
2175 				convs[nconv++] = conv;
2176 				if (nconv >= this->na_dacs)
2177 					break;
2178 			}
2179 		}
2180 	}
2181 
2182 	free(convs, M_DEVBUF, 0);
2183 	return(err);
2184 }
2185 
2186 /* Connect the speaker to a DAC that no other output pin is connected
2187  * to by default.  If that is not possible, connect to a DAC other
2188  * than the one the first output pin is connected to.
2189  */
2190 int
2191 azalia_codec_select_spkrdac(codec_t *this)
2192 {
2193 	widget_t *w;
2194 	nid_t convs[HDA_MAX_CHANNELS];
2195 	int nconv, conv;
2196 	int i, j, err, fspkr, conn;
2197 
2198 	nconv = fspkr = 0;
2199 	for (i = 0; i < this->nopins; i++) {
2200 		conv = this->opins[i].conv;
2201 		for (j = 0; j < nconv; j++) {
2202 			if (conv == convs[j])
2203 				break;
2204 		}
2205 		if (j == nconv) {
2206 			if (conv == this->spkr_dac)
2207 				fspkr = 1;
2208 			convs[nconv++] = conv;
2209 			if (nconv == this->na_dacs)
2210 				break;
2211 		}
2212 	}
2213 
2214 	if (fspkr) {
2215 		conn = conv = -1;
2216 		w = &this->w[this->speaker];
2217 		for (i = 0; i < w->nconnections; i++) {
2218 			conv = azalia_codec_find_defdac(this,
2219 			    w->connections[i], 1);
2220 			for (j = 0; j < nconv; j++)
2221 				if (conv == convs[j])
2222 					break;
2223 			if (j == nconv)
2224 				break;
2225 		}
2226 		if (i < w->nconnections) {
2227 			conn = i;
2228 		} else {
2229 			/* Couldn't get a unique DAC.  Try to get a diferent
2230 			 * DAC than the first pin's DAC.
2231 			 */
2232 			if (this->spkr_dac == this->opins[0].conv) {
2233 				/* If the speaker connection can't be changed,
2234 				 * change the first pin's connection.
2235 				 */
2236 				if (w->nconnections == 1)
2237 					w = &this->w[this->opins[0].nid];
2238 				for (j = 0; j < w->nconnections; j++) {
2239 					conv = azalia_codec_find_defdac(this,
2240 					    w->connections[j], 1);
2241 					if (conv != this->opins[0].conv) {
2242 						conn = j;
2243 						break;
2244 					}
2245 				}
2246 			}
2247 		}
2248 		if (conn != -1 && conv != -1) {
2249 			err = azalia_comresp(this, w->nid,
2250 			    CORB_SET_CONNECTION_SELECT_CONTROL, conn, 0);
2251 			if (err)
2252 				return(err);
2253 			w->selected = conn;
2254 			if (w->nid == this->speaker)
2255 				this->spkr_dac = conv;
2256 			else
2257 				this->opins[0].conv = conv;
2258 		}
2259 	}
2260 
2261 	/* If there is a speaker2, try to connect it to spkr_dac. */
2262 	if (this->speaker2 != -1) {
2263 		conn = conv = -1;
2264 		w = &this->w[this->speaker2];
2265 		for (i = 0; i < w->nconnections; i++) {
2266 			conv = azalia_codec_find_defdac(this,
2267 			    w->connections[i], 1);
2268 			if (conv == this->spkr_dac) {
2269 				conn = i;
2270 				break;
2271 			}
2272 		}
2273 		if (conn != -1) {
2274 			err = azalia_comresp(this, w->nid,
2275 			    CORB_SET_CONNECTION_SELECT_CONTROL, conn, 0);
2276 			if (err)
2277 				return(err);
2278 			w->selected = conn;
2279 		}
2280 	}
2281 
2282 	return(0);
2283 }
2284 
2285 int
2286 azalia_codec_find_defdac(codec_t *this, int index, int depth)
2287 {
2288 	const widget_t *w;
2289 	int i, ret;
2290 
2291 	w = &this->w[index];
2292 	if (w->enable == 0)
2293 		return -1;
2294 
2295 	if (w->type == COP_AWTYPE_AUDIO_OUTPUT)
2296 		return index;
2297 
2298 	if (depth > 0 &&
2299 	    (w->type == COP_AWTYPE_PIN_COMPLEX ||
2300 	    w->type == COP_AWTYPE_BEEP_GENERATOR ||
2301 	    w->type == COP_AWTYPE_AUDIO_INPUT))
2302 		return -1;
2303 	if (++depth >= 10)
2304 		return -1;
2305 
2306 	if (w->nconnections > 0) {
2307 		/* by default, all mixer connections are active */
2308 		if (w->type == COP_AWTYPE_AUDIO_MIXER) {
2309 			for (i = 0; i < w->nconnections; i++) {
2310 				index = w->connections[i];
2311 				if (!azalia_widget_enabled(this, index))
2312 					continue;
2313 				ret = azalia_codec_find_defdac(this, index,
2314 				    depth);
2315 				if (ret >= 0)
2316 					return ret;
2317 			}
2318 		/* 7.3.3.2 Connection Select Control
2319 		 * If an attempt is made to Set an index value greater than
2320 		 * the number of list entries (index is equal to or greater
2321 		 * than the Connection List Length property for the widget)
2322 		 * the behavior is not predictable.
2323 		 */
2324 
2325 		/* negative index values are wrong too */
2326 		} else if (w->selected >= 0 &&
2327 			w->selected < sizeof(w->connections)) {
2328 				index = w->connections[w->selected];
2329 				if (VALID_WIDGET_NID(index, this)) {
2330 					ret = azalia_codec_find_defdac(this,
2331 						index, depth);
2332 					if (ret >= 0)
2333 						return ret;
2334 				}
2335 		}
2336 	}
2337 
2338 	return -1;
2339 }
2340 
2341 int
2342 azalia_codec_find_defadc_sub(codec_t *this, nid_t node, int index, int depth)
2343 {
2344 	const widget_t *w;
2345 	int i, ret;
2346 
2347 	w = &this->w[index];
2348 	if (w->nid == node) {
2349 		return index;
2350 	}
2351 	/* back at the beginning or a bad end */
2352 	if (depth > 0 &&
2353 	    (w->type == COP_AWTYPE_PIN_COMPLEX ||
2354 	    w->type == COP_AWTYPE_BEEP_GENERATOR ||
2355 	    w->type == COP_AWTYPE_AUDIO_OUTPUT ||
2356 	    w->type == COP_AWTYPE_AUDIO_INPUT))
2357 		return -1;
2358 	if (++depth >= 10)
2359 		return -1;
2360 
2361 	if (w->nconnections > 0) {
2362 		/* by default, all mixer connections are active */
2363 		if (w->type == COP_AWTYPE_AUDIO_MIXER) {
2364 			for (i = 0; i < w->nconnections; i++) {
2365 				if (!azalia_widget_enabled(this, w->connections[i]))
2366 					continue;
2367 				ret = azalia_codec_find_defadc_sub(this, node,
2368 				    w->connections[i], depth);
2369 				if (ret >= 0)
2370 					return ret;
2371 			}
2372 		/* 7.3.3.2 Connection Select Control
2373 		 * If an attempt is made to Set an index value greater than
2374 		 * the number of list entries (index is equal to or greater
2375 		 * than the Connection List Length property for the widget)
2376 		 * the behavior is not predictable.
2377 		 */
2378 
2379 		/* negative index values are wrong too */
2380 		} else if (w->selected >= 0 &&
2381 			w->selected < sizeof(w->connections)) {
2382 				index = w->connections[w->selected];
2383 				if (VALID_WIDGET_NID(index, this)) {
2384 					ret = azalia_codec_find_defadc_sub(this,
2385 						node, index, depth);
2386 					if (ret >= 0)
2387 						return ret;
2388 				}
2389 		}
2390 	}
2391 	return -1;
2392 }
2393 
2394 int
2395 azalia_codec_find_defadc(codec_t *this, int index, int depth)
2396 {
2397 	int i, j, conv;
2398 
2399 	conv = -1;
2400 	for (i = 0; i < this->na_adcs; i++) {
2401 		j = azalia_codec_find_defadc_sub(this, index,
2402 		    this->a_adcs[i], 0);
2403 		if (j >= 0) {
2404 			conv = this->a_adcs[i];
2405 			break;
2406 		}
2407 	}
2408 	return(conv);
2409 }
2410 
2411 int
2412 azalia_codec_init_volgroups(codec_t *this)
2413 {
2414 	const widget_t *w;
2415 	uint32_t cap, result;
2416 	int i, j, dac, err;
2417 
2418 	j = 0;
2419 	this->playvols.mask = 0;
2420 	FOR_EACH_WIDGET(this, i) {
2421 		w = &this->w[i];
2422 		if (w->enable == 0)
2423 			continue;
2424 		if (w->mixer_class == AZ_CLASS_RECORD)
2425 			continue;
2426 		if (!(w->widgetcap & COP_AWCAP_OUTAMP))
2427 			continue;
2428 		if ((COP_AMPCAP_NUMSTEPS(w->outamp_cap) == 0) &&
2429 		    !(w->outamp_cap & COP_AMPCAP_MUTE))
2430 			continue;
2431 		this->playvols.mask |= (1 << j);
2432 		this->playvols.slaves[j++] = w->nid;
2433 		if (j >= AZ_MAX_VOL_SLAVES)
2434 			break;
2435 	}
2436 	this->playvols.nslaves = j;
2437 
2438 	this->playvols.cur = 0;
2439 	for (i = 0; i < this->playvols.nslaves; i++) {
2440 		w = &this->w[this->playvols.slaves[i]];
2441 		if (w->nid == this->input_mixer ||
2442 		    w->parent == this->input_mixer ||
2443 		    WIDGET_CHANNELS(w) < 2)
2444 			continue;
2445 		j = 0;
2446 		/* azalia_codec_find_defdac only goes 10 connections deep.
2447 		 * Start the connection depth at 7 so it doesn't go more
2448 		 * than 3 connections deep.
2449 		 */
2450 		if (w->type == COP_AWTYPE_AUDIO_MIXER ||
2451 		    w->type == COP_AWTYPE_AUDIO_SELECTOR)
2452 			j = 7;
2453 		dac = azalia_codec_find_defdac(this, w->nid, j);
2454 		if (dac == -1)
2455 			continue;
2456 		if (dac != this->dacs.groups[this->dacs.cur].conv[0] &&
2457 		    dac != this->spkr_dac && dac != this->fhp_dac)
2458 			continue;
2459 		cap = w->outamp_cap;
2460 		if ((cap & COP_AMPCAP_MUTE) && COP_AMPCAP_NUMSTEPS(cap)) {
2461 			if (w->type == COP_AWTYPE_BEEP_GENERATOR) {
2462 				continue;
2463 			} else if (w->type == COP_AWTYPE_PIN_COMPLEX) {
2464 				err = azalia_comresp(this, w->nid,
2465 				    CORB_GET_PIN_WIDGET_CONTROL, 0, &result);
2466 				if (!err && (result & CORB_PWC_OUTPUT))
2467 					this->playvols.cur |= (1 << i);
2468 			} else
2469 				this->playvols.cur |= (1 << i);
2470 		}
2471 	}
2472 	if (this->playvols.cur == 0) {
2473 		for (i = 0; i < this->playvols.nslaves; i++) {
2474 			w = &this->w[this->playvols.slaves[i]];
2475 			j = 0;
2476 			if (w->type == COP_AWTYPE_AUDIO_MIXER ||
2477 			    w->type == COP_AWTYPE_AUDIO_SELECTOR)
2478 				j = 7;
2479 			dac = azalia_codec_find_defdac(this, w->nid, j);
2480 			if (dac == -1)
2481 				continue;
2482 			if (dac != this->dacs.groups[this->dacs.cur].conv[0] &&
2483 			    dac != this->spkr_dac && dac != this->fhp_dac)
2484 				continue;
2485 			if (w->type == COP_AWTYPE_BEEP_GENERATOR)
2486 				continue;
2487 			if (w->type == COP_AWTYPE_PIN_COMPLEX) {
2488 				err = azalia_comresp(this, w->nid,
2489 				    CORB_GET_PIN_WIDGET_CONTROL, 0, &result);
2490 				if (!err && (result & CORB_PWC_OUTPUT))
2491 					this->playvols.cur |= (1 << i);
2492 			} else {
2493 				this->playvols.cur |= (1 << i);
2494 			}
2495 		}
2496 	}
2497 
2498 	this->playvols.master = this->audiofunc;
2499 	if (this->playvols.nslaves > 0) {
2500 		FOR_EACH_WIDGET(this, i) {
2501 			w = &this->w[i];
2502 			if (w->type != COP_AWTYPE_VOLUME_KNOB)
2503 				continue;
2504 			if (!COP_VKCAP_NUMSTEPS(w->d.volume.cap))
2505 				continue;
2506 			this->playvols.master = w->nid;
2507 			break;
2508 		}
2509 	}
2510 
2511 	j = 0;
2512 	this->recvols.mask = 0;
2513 	FOR_EACH_WIDGET(this, i) {
2514 		w = &this->w[i];
2515 		if (w->enable == 0)
2516 			continue;
2517 		if (w->type == COP_AWTYPE_AUDIO_INPUT ||
2518 		    w->type == COP_AWTYPE_PIN_COMPLEX) {
2519 			if (!(w->widgetcap & COP_AWCAP_INAMP))
2520 				continue;
2521 			if ((COP_AMPCAP_NUMSTEPS(w->inamp_cap) == 0) &&
2522 			    !(w->inamp_cap & COP_AMPCAP_MUTE))
2523 				continue;
2524 		} else if (w->type == COP_AWTYPE_AUDIO_MIXER ||
2525 		    w->type == COP_AWTYPE_AUDIO_SELECTOR) {
2526 			if (w->mixer_class != AZ_CLASS_RECORD)
2527 				continue;
2528 			if (!(w->widgetcap & COP_AWCAP_OUTAMP))
2529 				continue;
2530 			if ((COP_AMPCAP_NUMSTEPS(w->outamp_cap) == 0) &&
2531 			    !(w->outamp_cap & COP_AMPCAP_MUTE))
2532 				continue;
2533 		} else {
2534 			continue;
2535 		}
2536 		this->recvols.mask |= (1 << j);
2537 		this->recvols.slaves[j++] = w->nid;
2538 		if (j >= AZ_MAX_VOL_SLAVES)
2539 			break;
2540 	}
2541 	this->recvols.nslaves = j;
2542 
2543 	this->recvols.cur = 0;
2544 	for (i = 0; i < this->recvols.nslaves; i++) {
2545 		w = &this->w[this->recvols.slaves[i]];
2546 		cap = w->outamp_cap;
2547 		if (w->type == COP_AWTYPE_AUDIO_INPUT ||
2548 		    w->type != COP_AWTYPE_PIN_COMPLEX)
2549 			cap = w->inamp_cap;
2550 		 else
2551 			if (w->mixer_class != AZ_CLASS_RECORD)
2552 				continue;
2553 		if ((cap & COP_AMPCAP_MUTE) && COP_AMPCAP_NUMSTEPS(cap)) {
2554 			if (w->type == COP_AWTYPE_PIN_COMPLEX) {
2555 				err = azalia_comresp(this, w->nid,
2556 				    CORB_GET_PIN_WIDGET_CONTROL, 0, &result);
2557 				if (!err && !(result & CORB_PWC_OUTPUT))
2558 					this->recvols.cur |= (1 << i);
2559 			} else
2560 				this->recvols.cur |= (1 << i);
2561 		}
2562 	}
2563 	if (this->recvols.cur == 0) {
2564 		for (i = 0; i < this->recvols.nslaves; i++) {
2565 			w = &this->w[this->recvols.slaves[i]];
2566 			cap = w->outamp_cap;
2567 			if (w->type == COP_AWTYPE_AUDIO_INPUT ||
2568 			    w->type != COP_AWTYPE_PIN_COMPLEX)
2569 				cap = w->inamp_cap;
2570 			 else
2571 				if (w->mixer_class != AZ_CLASS_RECORD)
2572 					continue;
2573 			if (w->type == COP_AWTYPE_PIN_COMPLEX) {
2574 				err = azalia_comresp(this, w->nid,
2575 				    CORB_GET_PIN_WIDGET_CONTROL, 0, &result);
2576 				if (!err && !(result & CORB_PWC_OUTPUT))
2577 					this->recvols.cur |= (1 << i);
2578 			} else {
2579 				this->recvols.cur |= (1 << i);
2580 			}
2581 		}
2582 	}
2583 
2584 	this->recvols.master = this->audiofunc;
2585 
2586 	return 0;
2587 }
2588 
2589 int
2590 azalia_codec_delete(codec_t *this)
2591 {
2592 	azalia_mixer_delete(this);
2593 
2594 	if (this->formats != NULL) {
2595 		free(this->formats, M_DEVBUF, 0);
2596 		this->formats = NULL;
2597 	}
2598 	this->nformats = 0;
2599 
2600 	if (this->opins != NULL) {
2601 		free(this->opins, M_DEVBUF, 0);
2602 		this->opins = NULL;
2603 	}
2604 	this->nopins = 0;
2605 
2606 	if (this->opins_d != NULL) {
2607 		free(this->opins_d, M_DEVBUF, 0);
2608 		this->opins_d = NULL;
2609 	}
2610 	this->nopins_d = 0;
2611 
2612 	if (this->ipins != NULL) {
2613 		free(this->ipins, M_DEVBUF, 0);
2614 		this->ipins = NULL;
2615 	}
2616 	this->nipins = 0;
2617 
2618 	if (this->ipins_d != NULL) {
2619 		free(this->ipins_d, M_DEVBUF, 0);
2620 		this->ipins_d = NULL;
2621 	}
2622 	this->nipins_d = 0;
2623 
2624 	if (this->w != NULL) {
2625 		free(this->w, M_DEVBUF, 0);
2626 		this->w = NULL;
2627 	}
2628 
2629 	return 0;
2630 }
2631 
2632 int
2633 azalia_codec_construct_format(codec_t *this, int newdac, int newadc)
2634 {
2635 	const convgroup_t *group;
2636 	uint32_t bits_rates;
2637 	int variation;
2638 	int nbits, c, chan, i;
2639 	nid_t nid;
2640 
2641 	variation = 0;
2642 
2643 	if (this->dacs.ngroups > 0 && newdac < this->dacs.ngroups &&
2644 	    newdac >= 0) {
2645 		this->dacs.cur = newdac;
2646 		group = &this->dacs.groups[this->dacs.cur];
2647 		bits_rates = this->w[group->conv[0]].d.audio.bits_rates;
2648 		nbits = 0;
2649 		if (bits_rates & COP_PCM_B8)
2650 			nbits++;
2651 		if (bits_rates & COP_PCM_B16)
2652 			nbits++;
2653 		if (bits_rates & COP_PCM_B20)
2654 			nbits++;
2655 		if (bits_rates & COP_PCM_B24)
2656 			nbits++;
2657 		if ((bits_rates & COP_PCM_B32) &&
2658 		    !(this->w[group->conv[0]].widgetcap & COP_AWCAP_DIGITAL))
2659 			nbits++;
2660 		if (nbits == 0) {
2661 			printf("%s: invalid DAC PCM format: 0x%8.8x\n",
2662 			    XNAME(this->az), bits_rates);
2663 			return -1;
2664 		}
2665 		variation += group->nconv * nbits;
2666 	}
2667 
2668 	if (this->adcs.ngroups > 0 && newadc < this->adcs.ngroups &&
2669 	    newadc >= 0) {
2670 		this->adcs.cur = newadc;
2671 		group = &this->adcs.groups[this->adcs.cur];
2672 		bits_rates = this->w[group->conv[0]].d.audio.bits_rates;
2673 		nbits = 0;
2674 		if (bits_rates & COP_PCM_B8)
2675 			nbits++;
2676 		if (bits_rates & COP_PCM_B16)
2677 			nbits++;
2678 		if (bits_rates & COP_PCM_B20)
2679 			nbits++;
2680 		if (bits_rates & COP_PCM_B24)
2681 			nbits++;
2682 		if ((bits_rates & COP_PCM_B32) &&
2683 		    !(this->w[group->conv[0]].widgetcap & COP_AWCAP_DIGITAL))
2684 			nbits++;
2685 		if (nbits == 0) {
2686 			printf("%s: invalid ADC PCM format: 0x%8.8x\n",
2687 			    XNAME(this->az), bits_rates);
2688 			return -1;
2689 		}
2690 		variation += group->nconv * nbits;
2691 	}
2692 
2693 	if (variation == 0) {
2694 		DPRINTF(("%s: no converter groups\n", XNAME(this->az)));
2695 		return -1;
2696 	}
2697 
2698 	if (this->formats != NULL)
2699 		free(this->formats, M_DEVBUF, 0);
2700 	this->nformats = 0;
2701 	this->formats = mallocarray(variation, sizeof(struct audio_format),
2702 	    M_DEVBUF, M_NOWAIT | M_ZERO);
2703 	if (this->formats == NULL) {
2704 		printf("%s: out of memory in %s\n",
2705 		    XNAME(this->az), __func__);
2706 		return ENOMEM;
2707 	}
2708 
2709 	/* register formats for playback */
2710 	if (this->dacs.ngroups > 0) {
2711 		group = &this->dacs.groups[this->dacs.cur];
2712 		for (c = 0; c < group->nconv; c++) {
2713 			chan = 0;
2714 			bits_rates = ~0;
2715 			if (this->w[group->conv[0]].widgetcap &
2716 			    COP_AWCAP_DIGITAL)
2717 				bits_rates &= ~(COP_PCM_B32);
2718 			for (i = 0; i <= c; i++) {
2719 				nid = group->conv[i];
2720 				chan += WIDGET_CHANNELS(&this->w[nid]);
2721 				bits_rates &= this->w[nid].d.audio.bits_rates;
2722 			}
2723 			azalia_codec_add_bits(this, chan, bits_rates,
2724 			    AUMODE_PLAY);
2725 		}
2726 	}
2727 
2728 	/* register formats for recording */
2729 	if (this->adcs.ngroups > 0) {
2730 		group = &this->adcs.groups[this->adcs.cur];
2731 		for (c = 0; c < group->nconv; c++) {
2732 			chan = 0;
2733 			bits_rates = ~0;
2734 			if (this->w[group->conv[0]].widgetcap &
2735 			    COP_AWCAP_DIGITAL)
2736 				bits_rates &= ~(COP_PCM_B32);
2737 			for (i = 0; i <= c; i++) {
2738 				nid = group->conv[i];
2739 				chan += WIDGET_CHANNELS(&this->w[nid]);
2740 				bits_rates &= this->w[nid].d.audio.bits_rates;
2741 			}
2742 			azalia_codec_add_bits(this, chan, bits_rates,
2743 			    AUMODE_RECORD);
2744 		}
2745 	}
2746 
2747 	return 0;
2748 }
2749 
2750 void
2751 azalia_codec_add_bits(codec_t *this, int chan, uint32_t bits_rates, int mode)
2752 {
2753 	if (bits_rates & COP_PCM_B8)
2754 		azalia_codec_add_format(this, chan, 8, bits_rates, mode);
2755 	if (bits_rates & COP_PCM_B16)
2756 		azalia_codec_add_format(this, chan, 16, bits_rates, mode);
2757 	if (bits_rates & COP_PCM_B20)
2758 		azalia_codec_add_format(this, chan, 20, bits_rates, mode);
2759 	if (bits_rates & COP_PCM_B24)
2760 		azalia_codec_add_format(this, chan, 24, bits_rates, mode);
2761 	if (bits_rates & COP_PCM_B32)
2762 		azalia_codec_add_format(this, chan, 32, bits_rates, mode);
2763 }
2764 
2765 void
2766 azalia_codec_add_format(codec_t *this, int chan, int prec, uint32_t rates,
2767     int32_t mode)
2768 {
2769 	struct audio_format *f;
2770 
2771 	f = &this->formats[this->nformats++];
2772 	f->mode = mode;
2773 	f->encoding = AUDIO_ENCODING_SLINEAR_LE;
2774 	if (prec == 8)
2775 		f->encoding = AUDIO_ENCODING_ULINEAR_LE;
2776 	f->precision = prec;
2777 	f->channels = chan;
2778 	f->frequency_type = 0;
2779 	if (rates & COP_PCM_R80)
2780 		f->frequency[f->frequency_type++] = 8000;
2781 	if (rates & COP_PCM_R110)
2782 		f->frequency[f->frequency_type++] = 11025;
2783 	if (rates & COP_PCM_R160)
2784 		f->frequency[f->frequency_type++] = 16000;
2785 	if (rates & COP_PCM_R220)
2786 		f->frequency[f->frequency_type++] = 22050;
2787 	if (rates & COP_PCM_R320)
2788 		f->frequency[f->frequency_type++] = 32000;
2789 	if (rates & COP_PCM_R441)
2790 		f->frequency[f->frequency_type++] = 44100;
2791 	if (rates & COP_PCM_R480)
2792 		f->frequency[f->frequency_type++] = 48000;
2793 	if (rates & COP_PCM_R882)
2794 		f->frequency[f->frequency_type++] = 88200;
2795 	if (rates & COP_PCM_R960)
2796 		f->frequency[f->frequency_type++] = 96000;
2797 	if (rates & COP_PCM_R1764)
2798 		f->frequency[f->frequency_type++] = 176400;
2799 	if (rates & COP_PCM_R1920)
2800 		f->frequency[f->frequency_type++] = 192000;
2801 	if (rates & COP_PCM_R3840)
2802 		f->frequency[f->frequency_type++] = 384000;
2803 }
2804 
2805 int
2806 azalia_codec_connect_stream(stream_t *this)
2807 {
2808 	const codec_t *codec = &this->az->codecs[this->az->codecno];
2809 	const convgroup_t *group;
2810 	widget_t *w;
2811 	uint32_t digital, stream_chan;
2812 	int i, err, curchan, nchan, widchan;
2813 
2814 	err = 0;
2815 	nchan = (this->fmt & HDA_SD_FMT_CHAN) + 1;
2816 
2817 	if (this->dir == AUMODE_RECORD)
2818 		group = &codec->adcs.groups[codec->adcs.cur];
2819 	else
2820 		group = &codec->dacs.groups[codec->dacs.cur];
2821 
2822 	curchan = 0;
2823 	for (i = 0; i < group->nconv; i++) {
2824 		w = &codec->w[group->conv[i]];
2825 		widchan = WIDGET_CHANNELS(w);
2826 
2827 		stream_chan = (this->number << 4);
2828 		if (curchan < nchan) {
2829 			stream_chan |= curchan;
2830 		} else if (w->nid == codec->spkr_dac ||
2831 		    w->nid == codec->fhp_dac) {
2832 			stream_chan |= 0;	/* first channel(s) */
2833 		} else
2834 			stream_chan = 0;	/* idle stream */
2835 
2836 		if (stream_chan == 0) {
2837 			DPRINTFN(0, ("%s: %2.2x is idle\n", __func__, w->nid));
2838 		} else {
2839 			DPRINTFN(0, ("%s: %2.2x on stream chan %d\n", __func__,
2840 			    w->nid, stream_chan & ~(this->number << 4)));
2841 		}
2842 
2843 		err = azalia_comresp(codec, w->nid, CORB_SET_CONVERTER_FORMAT,
2844 		    this->fmt, NULL);
2845 		if (err) {
2846 			DPRINTF(("%s: nid %2.2x fmt %2.2x: %d\n",
2847 			    __func__, w->nid, this->fmt, err));
2848 			break;
2849 		}
2850 		err = azalia_comresp(codec, w->nid,
2851 		    CORB_SET_CONVERTER_STREAM_CHANNEL, stream_chan, NULL);
2852 		if (err) {
2853 			DPRINTF(("%s: nid %2.2x chan %d: %d\n",
2854 			    __func__, w->nid, stream_chan, err));
2855 			break;
2856 		}
2857 
2858 		if (w->widgetcap & COP_AWCAP_DIGITAL) {
2859 			err = azalia_comresp(codec, w->nid,
2860 			    CORB_GET_DIGITAL_CONTROL, 0, &digital);
2861 			if (err) {
2862 				DPRINTF(("%s: nid %2.2x get digital: %d\n",
2863 				    __func__, w->nid, err));
2864 				break;
2865 			}
2866 			digital = (digital & 0xff) | CORB_DCC_DIGEN;
2867 			err = azalia_comresp(codec, w->nid,
2868 			    CORB_SET_DIGITAL_CONTROL_L, digital, NULL);
2869 			if (err) {
2870 				DPRINTF(("%s: nid %2.2x set digital: %d\n",
2871 				    __func__, w->nid, err));
2872 				break;
2873 			}
2874 		}
2875 		curchan += widchan;
2876 	}
2877 
2878 	return err;
2879 }
2880 
2881 int
2882 azalia_codec_disconnect_stream(stream_t *this)
2883 {
2884 	const codec_t *codec = &this->az->codecs[this->az->codecno];
2885 	const convgroup_t *group;
2886 	uint32_t v;
2887 	int i;
2888 	nid_t nid;
2889 
2890 	if (this->dir == AUMODE_RECORD)
2891 		group = &codec->adcs.groups[codec->adcs.cur];
2892 	else
2893 		group = &codec->dacs.groups[codec->dacs.cur];
2894 	for (i = 0; i < group->nconv; i++) {
2895 		nid = group->conv[i];
2896 		azalia_comresp(codec, nid, CORB_SET_CONVERTER_STREAM_CHANNEL,
2897 		    0, NULL);	/* stream#0 */
2898 		if (codec->w[nid].widgetcap & COP_AWCAP_DIGITAL) {
2899 			/* disable S/PDIF */
2900 			azalia_comresp(codec, nid, CORB_GET_DIGITAL_CONTROL,
2901 			    0, &v);
2902 			v = (v & ~CORB_DCC_DIGEN) & 0xff;
2903 			azalia_comresp(codec, nid, CORB_SET_DIGITAL_CONTROL_L,
2904 			    v, NULL);
2905 		}
2906 	}
2907 	return 0;
2908 }
2909 
2910 /* ================================================================
2911  * HDA widget functions
2912  * ================================================================ */
2913 
2914 int
2915 azalia_widget_init(widget_t *this, const codec_t *codec, nid_t nid)
2916 {
2917 	uint32_t result;
2918 	int err;
2919 
2920 	err = azalia_comresp(codec, nid, CORB_GET_PARAMETER,
2921 	    COP_AUDIO_WIDGET_CAP, &result);
2922 	if (err)
2923 		return err;
2924 	this->nid = nid;
2925 	this->widgetcap = result;
2926 	this->type = COP_AWCAP_TYPE(result);
2927 	if (this->widgetcap & COP_AWCAP_POWER) {
2928 		azalia_comresp(codec, nid, CORB_SET_POWER_STATE, CORB_PS_D0,
2929 		    &result);
2930 		DELAY(100);
2931 	}
2932 
2933 	this->enable = 1;
2934 	this->mixer_class = -1;
2935 	this->parent = codec->audiofunc;
2936 
2937 	switch (this->type) {
2938 	case COP_AWTYPE_AUDIO_OUTPUT:
2939 		/* FALLTHROUGH */
2940 	case COP_AWTYPE_AUDIO_INPUT:
2941 		azalia_widget_init_audio(this, codec);
2942 		break;
2943 	case COP_AWTYPE_PIN_COMPLEX:
2944 		azalia_widget_init_pin(this, codec);
2945 		break;
2946 	case COP_AWTYPE_VOLUME_KNOB:
2947 		err = azalia_comresp(codec, this->nid, CORB_GET_PARAMETER,
2948 		    COP_VOLUME_KNOB_CAPABILITIES, &result);
2949 		if (err)
2950 			return err;
2951 		this->d.volume.cap = result;
2952 		break;
2953 	case COP_AWTYPE_POWER:
2954 		/* FALLTHROUGH */
2955 	case COP_AWTYPE_VENDOR_DEFINED:
2956 		this->enable = 0;
2957 		break;
2958 	}
2959 
2960 	/* amplifier information */
2961 	/* XXX (ab)use bits 24-30 to store the "control offset", which is
2962 	 * the number of steps, starting at 0, that have no effect.  these
2963 	 * bits are reserved in HDA 1.0.
2964 	 */
2965 	if (this->widgetcap & COP_AWCAP_INAMP) {
2966 		if (this->widgetcap & COP_AWCAP_AMPOV)
2967 			azalia_comresp(codec, nid, CORB_GET_PARAMETER,
2968 			    COP_INPUT_AMPCAP, &this->inamp_cap);
2969 		else
2970 			this->inamp_cap = codec->w[codec->audiofunc].inamp_cap;
2971 		this->inamp_cap &= ~(0x7f << 24);
2972 	}
2973 	if (this->widgetcap & COP_AWCAP_OUTAMP) {
2974 		if (this->widgetcap & COP_AWCAP_AMPOV)
2975 			azalia_comresp(codec, nid, CORB_GET_PARAMETER,
2976 			    COP_OUTPUT_AMPCAP, &this->outamp_cap);
2977 		else
2978 			this->outamp_cap = codec->w[codec->audiofunc].outamp_cap;
2979 		this->outamp_cap &= ~(0x7f << 24);
2980 	}
2981 	return 0;
2982 }
2983 
2984 int
2985 azalia_widget_sole_conn(codec_t *this, nid_t nid)
2986 {
2987 	int i, j, target, nconn, has_target;
2988 
2989 	/* connected to ADC */
2990 	for (i = 0; i < this->adcs.ngroups; i++) {
2991 		for (j = 0; j < this->adcs.groups[i].nconv; j++) {
2992 			target = this->adcs.groups[i].conv[j];
2993 			if (this->w[target].nconnections == 1 &&
2994 			    this->w[target].connections[0] == nid) {
2995 				return target;
2996 			}
2997 		}
2998 	}
2999 	/* connected to DAC */
3000 	for (i = 0; i < this->dacs.ngroups; i++) {
3001 		for (j = 0; j < this->dacs.groups[i].nconv; j++) {
3002 			target = this->dacs.groups[i].conv[j];
3003 			if (this->w[target].nconnections == 1 &&
3004 			    this->w[target].connections[0] == nid) {
3005 				return target;
3006 			}
3007 		}
3008 	}
3009 	/* connected to pin complex */
3010 	target = -1;
3011 	FOR_EACH_WIDGET(this, i) {
3012 		if (this->w[i].type != COP_AWTYPE_PIN_COMPLEX)
3013 			continue;
3014 		if (this->w[i].nconnections == 1 &&
3015 		    this->w[i].connections[0] == nid) {
3016 			if (target != -1)
3017 				return -1;
3018 			target = i;
3019 		} else {
3020 			nconn = 0;
3021 			has_target = 0;
3022 			for (j = 0; j < this->w[i].nconnections; j++) {
3023 				if (!this->w[this->w[i].connections[j]].enable)
3024 					continue;
3025 				nconn++;
3026 				if (this->w[i].connections[j] == nid)
3027 					has_target = 1;
3028 			}
3029 			if (has_target == 1) {
3030 				if (nconn == 1) {
3031 					if (target != -1)
3032 						return -1;
3033 					target = i;
3034 				} else {
3035 					/* not sole connection at least once */
3036 					return -1;
3037 				}
3038 			}
3039 		}
3040 	}
3041 	if (target != -1)
3042 		return target;
3043 
3044 	return -1;
3045 }
3046 
3047 int
3048 azalia_widget_label_widgets(codec_t *codec)
3049 {
3050 	widget_t *w;
3051 	convgroup_t *group;
3052 	int types[16];
3053 	int pins[16];
3054 	int colors_used, use_colors, schan;
3055 	int i, j;
3056 
3057 	bzero(&pins, sizeof(pins));
3058 	bzero(&types, sizeof(types));
3059 
3060 	/* If codec has more than one line-out jack, check if the jacks
3061 	 * have unique colors.  If so, use the colors in the mixer names.
3062 	 */
3063 	use_colors = 1;
3064 	colors_used = 0;
3065 	if (codec->nout_jacks < 2)
3066 		use_colors = 0;
3067 	for (i = 0; use_colors && i < codec->nopins; i++) {
3068 		w = &codec->w[codec->opins[i].nid];
3069 		if (w->d.pin.device != CORB_CD_LINEOUT)
3070 			continue;
3071 		if (colors_used & (1 << w->d.pin.color))
3072 			use_colors = 0;
3073 		else
3074 			colors_used |= (1 << w->d.pin.color);
3075 	}
3076 
3077 	FOR_EACH_WIDGET(codec, i) {
3078 		w = &codec->w[i];
3079 		/* default for disabled/unused widgets */
3080 		snprintf(w->name, sizeof(w->name), "u-wid%2.2x", w->nid);
3081 		if (w->enable == 0)
3082 			continue;
3083 		switch (w->type) {
3084 		case COP_AWTYPE_PIN_COMPLEX:
3085 			pins[w->d.pin.device]++;
3086 			if (use_colors && w->d.pin.device == CORB_CD_LINEOUT) {
3087 				snprintf(w->name, sizeof(w->name), "%s-%s",
3088 				    pin_devices[w->d.pin.device],
3089 				    line_colors[w->d.pin.color]);
3090 			} else if (pins[w->d.pin.device] > 1) {
3091 				snprintf(w->name, sizeof(w->name), "%s%d",
3092 				    pin_devices[w->d.pin.device],
3093 				    pins[w->d.pin.device]);
3094 			} else {
3095 				snprintf(w->name, sizeof(w->name), "%s",
3096 				    pin_devices[w->d.pin.device]);
3097 			}
3098 			break;
3099 		case COP_AWTYPE_AUDIO_OUTPUT:
3100 			if (codec->dacs.ngroups < 1)
3101 				break;
3102 			group = &codec->dacs.groups[0];
3103 			schan = 0;
3104 			for (j = 0; j < group->nconv; j++) {
3105 				if (w->nid == group->conv[j]) {
3106 					snprintf(w->name, sizeof(w->name),
3107 					    "%s-%d:%d", wtypes[w->type], schan,
3108 					    schan + WIDGET_CHANNELS(w) - 1);
3109 				}
3110 				schan += WIDGET_CHANNELS(w);
3111 			}
3112 			if (codec->dacs.ngroups < 2)
3113 				break;
3114 			group = &codec->dacs.groups[1];
3115 			schan = 0;
3116 			for (j = 0; j < group->nconv; j++) {
3117 				if (w->nid == group->conv[j]) {
3118 					snprintf(w->name, sizeof(w->name),
3119 					    "dig-%s-%d:%d", wtypes[w->type],
3120 					    schan,
3121 					    schan + WIDGET_CHANNELS(w) - 1);
3122 				}
3123 				schan += WIDGET_CHANNELS(w);
3124 			}
3125 			break;
3126 		case COP_AWTYPE_AUDIO_INPUT:
3127 			w->mixer_class = AZ_CLASS_RECORD;
3128 			if (codec->adcs.ngroups < 1)
3129 				break;
3130 			group = &codec->adcs.groups[0];
3131 			schan = 0;
3132 			for (j = 0; j < group->nconv; j++) {
3133 				if (w->nid == group->conv[j]) {
3134 					snprintf(w->name, sizeof(w->name),
3135 					    "%s-%d:%d", wtypes[w->type], schan,
3136 					    schan + WIDGET_CHANNELS(w) - 1);
3137 				}
3138 				schan += WIDGET_CHANNELS(w);
3139 			}
3140 			if (codec->adcs.ngroups < 2)
3141 				break;
3142 			group = &codec->adcs.groups[1];
3143 			schan = 0;
3144 			for (j = 0; j < group->nconv; j++) {
3145 				if (w->nid == group->conv[j]) {
3146 					snprintf(w->name, sizeof(w->name),
3147 					    "dig-%s-%d:%d", wtypes[w->type],
3148 					    schan,
3149 					    schan + WIDGET_CHANNELS(w) - 1);
3150 				}
3151 				schan += WIDGET_CHANNELS(w);
3152 			}
3153 			break;
3154 		default:
3155 			types[w->type]++;
3156 			if (types[w->type] > 1)
3157 				snprintf(w->name, sizeof(w->name), "%s%d",
3158 				    wtypes[w->type], types[w->type]);
3159 			else
3160 				snprintf(w->name, sizeof(w->name), "%s",
3161 				    wtypes[w->type]);
3162 			break;
3163 		}
3164 	}
3165 
3166 	/* Mixers and selectors that connect to only one other widget are
3167 	 * functionally part of the widget they are connected to.  Show that
3168 	 * relationship in the name.
3169 	 */
3170 	FOR_EACH_WIDGET(codec, i) {
3171 		if (codec->w[i].type != COP_AWTYPE_AUDIO_MIXER &&
3172 		    codec->w[i].type != COP_AWTYPE_AUDIO_SELECTOR)
3173 			continue;
3174 		if (codec->w[i].enable == 0)
3175 			continue;
3176 		j = azalia_widget_sole_conn(codec, i);
3177 		if (j == -1) {
3178 			/* Special case.  A selector with outamp capabilities
3179 			 * and is connected to a single widget that has either
3180 			 * no input or no output capabilities.  This widget
3181 			 * serves as the input or output amp for the widget
3182 			 * it is connected to.
3183 			 */
3184 			if (codec->w[i].type == COP_AWTYPE_AUDIO_SELECTOR &&
3185 			    (codec->w[i].widgetcap & COP_AWCAP_OUTAMP) &&
3186 			    codec->w[i].nconnections == 1) {
3187 				j = codec->w[i].connections[0];
3188 				if (!azalia_widget_enabled(codec, j))
3189 					continue;
3190 				if (!(codec->w[j].widgetcap & COP_AWCAP_INAMP))
3191 					codec->w[i].mixer_class =
3192 					    AZ_CLASS_INPUT;
3193 				else if (!(codec->w[j].widgetcap & COP_AWCAP_OUTAMP))
3194 					codec->w[i].mixer_class =
3195 					    AZ_CLASS_OUTPUT;
3196 				else
3197 					continue;
3198 			}
3199 		}
3200 		if (j >= 0) {
3201 			/* As part of a disabled widget, this widget
3202 			 * should be disabled as well.
3203 			 */
3204 			if (codec->w[j].enable == 0) {
3205 				codec->w[i].enable = 0;
3206 				snprintf(codec->w[i].name,
3207 				    sizeof(codec->w[i].name),
3208 				    "u-wid%2.2x", i);
3209 				continue;
3210 			}
3211 			snprintf(codec->w[i].name, sizeof(codec->w[i].name),
3212 			    "%s", codec->w[j].name);
3213 			if (codec->w[j].mixer_class == AZ_CLASS_RECORD)
3214 				codec->w[i].mixer_class = AZ_CLASS_RECORD;
3215 			codec->w[i].parent = j;
3216 		}
3217 	}
3218 
3219 	return 0;
3220 }
3221 
3222 int
3223 azalia_widget_init_audio(widget_t *this, const codec_t *codec)
3224 {
3225 	uint32_t result;
3226 	int err;
3227 
3228 	/* check audio format */
3229 	if (this->widgetcap & COP_AWCAP_FORMATOV) {
3230 		err = azalia_comresp(codec, this->nid, CORB_GET_PARAMETER,
3231 		    COP_STREAM_FORMATS, &result);
3232 		if (err)
3233 			return err;
3234 		this->d.audio.encodings = result;
3235 		if (result == 0) { /* quirk for CMI9880.
3236 				    * This must not occur usually... */
3237 			this->d.audio.encodings =
3238 			    codec->w[codec->audiofunc].d.audio.encodings;
3239 			this->d.audio.bits_rates =
3240 			    codec->w[codec->audiofunc].d.audio.bits_rates;
3241 		} else {
3242 			if ((result & COP_STREAM_FORMAT_PCM) == 0) {
3243 				printf("%s: %s: No PCM support: %x\n",
3244 				    XNAME(codec->az), this->name, result);
3245 				return -1;
3246 			}
3247 			err = azalia_comresp(codec, this->nid,
3248 			    CORB_GET_PARAMETER, COP_PCM, &result);
3249 			if (err)
3250 				return err;
3251 			this->d.audio.bits_rates = result;
3252 		}
3253 	} else {
3254 		this->d.audio.encodings =
3255 		    codec->w[codec->audiofunc].d.audio.encodings;
3256 		this->d.audio.bits_rates =
3257 		    codec->w[codec->audiofunc].d.audio.bits_rates;
3258 	}
3259 	return 0;
3260 }
3261 
3262 int
3263 azalia_widget_init_pin(widget_t *this, const codec_t *codec)
3264 {
3265 	uint32_t result, dir;
3266 	int err;
3267 
3268 	err = azalia_comresp(codec, this->nid, CORB_GET_CONFIGURATION_DEFAULT,
3269 	    0, &result);
3270 	if (err)
3271 		return err;
3272 	this->d.pin.config = result;
3273 	this->d.pin.sequence = CORB_CD_SEQUENCE(result);
3274 	this->d.pin.association = CORB_CD_ASSOCIATION(result);
3275 	this->d.pin.color = CORB_CD_COLOR(result);
3276 	this->d.pin.device = CORB_CD_DEVICE(result);
3277 
3278 	err = azalia_comresp(codec, this->nid, CORB_GET_PARAMETER,
3279 	    COP_PINCAP, &result);
3280 	if (err)
3281 		return err;
3282 	this->d.pin.cap = result;
3283 
3284 	dir = CORB_PWC_INPUT;
3285 	switch (this->d.pin.device) {
3286 	case CORB_CD_LINEOUT:
3287 	case CORB_CD_SPEAKER:
3288 	case CORB_CD_HEADPHONE:
3289 	case CORB_CD_SPDIFOUT:
3290 	case CORB_CD_DIGITALOUT:
3291 		dir = CORB_PWC_OUTPUT;
3292 		break;
3293 	}
3294 
3295 	if (dir == CORB_PWC_INPUT && !(this->d.pin.cap & COP_PINCAP_INPUT))
3296 		dir = CORB_PWC_OUTPUT;
3297 	if (dir == CORB_PWC_OUTPUT && !(this->d.pin.cap & COP_PINCAP_OUTPUT))
3298 		dir = CORB_PWC_INPUT;
3299 
3300 	if (dir == CORB_PWC_INPUT && this->d.pin.device == CORB_CD_MICIN) {
3301 		if (COP_PINCAP_VREF(this->d.pin.cap) & (1 << CORB_PWC_VREF_80))
3302 			dir |= CORB_PWC_VREF_80;
3303 		else if (COP_PINCAP_VREF(this->d.pin.cap) &
3304 		    (1 << CORB_PWC_VREF_50))
3305 			dir |= CORB_PWC_VREF_50;
3306 	}
3307 
3308 	if ((codec->qrks & AZ_QRK_WID_OVREF50) && (dir == CORB_PWC_OUTPUT))
3309 		dir |= CORB_PWC_VREF_50;
3310 
3311 	azalia_comresp(codec, this->nid, CORB_SET_PIN_WIDGET_CONTROL,
3312 	    dir, NULL);
3313 
3314 	if (this->d.pin.cap & COP_PINCAP_EAPD) {
3315 		err = azalia_comresp(codec, this->nid,
3316 		    CORB_GET_EAPD_BTL_ENABLE, 0, &result);
3317 		if (err)
3318 			return err;
3319 		result &= 0xff;
3320 		result |= CORB_EAPD_EAPD;
3321 		err = azalia_comresp(codec, this->nid,
3322 		    CORB_SET_EAPD_BTL_ENABLE, result, &result);
3323 		if (err)
3324 			return err;
3325 	}
3326 
3327 	/* Disable unconnected pins */
3328 	if (CORB_CD_PORT(this->d.pin.config) == CORB_CD_NONE)
3329 		this->enable = 0;
3330 
3331 	return 0;
3332 }
3333 
3334 int
3335 azalia_widget_init_connection(widget_t *this, const codec_t *codec)
3336 {
3337 	uint32_t result;
3338 	int err;
3339 	int i, j, k;
3340 	int length, nconn, bits, conn, last;
3341 
3342 	this->selected = -1;
3343 	if ((this->widgetcap & COP_AWCAP_CONNLIST) == 0)
3344 		return 0;
3345 
3346 	err = azalia_comresp(codec, this->nid, CORB_GET_PARAMETER,
3347 	    COP_CONNECTION_LIST_LENGTH, &result);
3348 	if (err)
3349 		return err;
3350 
3351 	bits = 8;
3352 	if (result & COP_CLL_LONG)
3353 		bits = 16;
3354 
3355 	length = COP_CLL_LENGTH(result);
3356 	if (length == 0)
3357 		return 0;
3358 
3359 	/*
3360 	 * 'length' is the number of entries, not the number of
3361 	 * connections.  Find the number of connections, 'nconn', so
3362 	 * enough space can be allocated for the list of connected
3363 	 * nids.
3364 	 */
3365 	nconn = last = 0;
3366 	for (i = 0; i < length;) {
3367 		err = azalia_comresp(codec, this->nid,
3368 		    CORB_GET_CONNECTION_LIST_ENTRY, i, &result);
3369 		if (err)
3370 			return err;
3371 		for (k = 0; i < length && (k < 32 / bits); k++) {
3372 			conn = (result >> (k * bits)) & ((1 << bits) - 1);
3373 			/* If high bit is set, this is the end of a continuous
3374 			 * list that started with the last connection.
3375 			 */
3376 			if ((nconn > 0) && (conn & (1 << (bits - 1))))
3377 				nconn += (conn & ~(1 << (bits - 1))) - last;
3378 			else
3379 				nconn++;
3380 			last = conn;
3381 			i++;
3382 		}
3383 	}
3384 
3385 	this->connections = mallocarray(nconn, sizeof(nid_t), M_DEVBUF, M_NOWAIT);
3386 	if (this->connections == NULL) {
3387 		printf("%s: out of memory\n", XNAME(codec->az));
3388 		return ENOMEM;
3389 	}
3390 	for (i = 0; i < nconn;) {
3391 		err = azalia_comresp(codec, this->nid,
3392 		    CORB_GET_CONNECTION_LIST_ENTRY, i, &result);
3393 		if (err)
3394 			return err;
3395 		for (k = 0; i < nconn && (k < 32 / bits); k++) {
3396 			conn = (result >> (k * bits)) & ((1 << bits) - 1);
3397 			/* If high bit is set, this is the end of a continuous
3398 			 * list that started with the last connection.
3399 			 */
3400 			if ((i > 0) && (conn & (1 << (bits - 1)))) {
3401 				for (j = 1; i < nconn && j <= conn - last; j++)
3402 					this->connections[i++] = last + j;
3403 			} else {
3404 				this->connections[i++] = conn;
3405 			}
3406 			last = conn;
3407 		}
3408 	}
3409 	this->nconnections = nconn;
3410 
3411 	if (nconn > 0) {
3412 		err = azalia_comresp(codec, this->nid,
3413 		    CORB_GET_CONNECTION_SELECT_CONTROL, 0, &result);
3414 		if (err)
3415 			return err;
3416 		this->selected = CORB_CSC_INDEX(result);
3417 	}
3418 	return 0;
3419 }
3420 
3421 int
3422 azalia_widget_check_conn(codec_t *codec, int index, int depth)
3423 {
3424 	const widget_t *w;
3425 	int i;
3426 
3427 	w = &codec->w[index];
3428 
3429 	if (w->type == COP_AWTYPE_BEEP_GENERATOR)
3430 		return 0;
3431 
3432 	if (depth > 0 &&
3433 	    (w->type == COP_AWTYPE_PIN_COMPLEX ||
3434 	    w->type == COP_AWTYPE_AUDIO_OUTPUT ||
3435 	    w->type == COP_AWTYPE_AUDIO_INPUT)) {
3436 		if (w->enable)
3437 			return 1;
3438 		else
3439 			return 0;
3440 	}
3441 	if (++depth >= 10)
3442 		return 0;
3443 	for (i = 0; i < w->nconnections; i++) {
3444 		if (!azalia_widget_enabled(codec, w->connections[i]))
3445 			continue;
3446 		if (azalia_widget_check_conn(codec, w->connections[i], depth))
3447 			return 1;
3448 	}
3449 	return 0;
3450 }
3451 
3452 #ifdef AZALIA_DEBUG
3453 
3454 #define	WIDGETCAP_BITS							\
3455     "\20\014LRSWAP\013POWER\012DIGITAL"					\
3456     "\011CONNLIST\010UNSOL\07PROC\06STRIPE\05FORMATOV\04AMPOV\03OUTAMP"	\
3457     "\02INAMP\01STEREO"
3458 
3459 #define	PINCAP_BITS	"\20\021EAPD\16VREF100\15VREF80" \
3460     "\13VREFGND\12VREF50\11VREFHIZ\07BALANCE\06INPUT" \
3461     "\05OUTPUT\04HEADPHONE\03PRESENCE\02TRIGGER\01IMPEDANCE"
3462 
3463 #define	ENCODING_BITS	"\20\3AC3\2FLOAT32\1PCM"
3464 
3465 #define	BITSRATES_BITS	"\20\x15""32bit\x14""24bit\x13""20bit"		\
3466     "\x12""16bit\x11""8bit""\x0c""384kHz\x0b""192kHz\x0a""176.4kHz"	\
3467     "\x09""96kHz\x08""88.2kHz\x07""48kHz\x06""44.1kHz\x05""32kHz\x04"	\
3468     "22.05kHz\x03""16kHz\x02""11.025kHz\x01""8kHz"
3469 
3470 static const char *pin_colors[16] = {
3471 	"unknown", "black", "gray", "blue",
3472 	"green", "red", "orange", "yellow",
3473 	"purple", "pink", "col0a", "col0b",
3474 	"col0c", "col0d", "white", "other"};
3475 static const char *pin_conn[4] = {
3476 	"jack", "none", "fixed", "combined"};
3477 static const char *pin_conntype[16] = {
3478 	"unknown", "1/8", "1/4", "atapi", "rca", "optical",
3479 	"digital", "analog", "din", "xlr", "rj-11", "combination",
3480 	"con0c", "con0d", "con0e", "other"};
3481 static const char *pin_geo[15] = {
3482 	"n/a", "rear", "front", "left",
3483 	"right", "top", "bottom", "spec0", "spec1", "spec2",
3484 	"loc0a", "loc0b", "loc0c", "loc0d", "loc0f"};
3485 static const char *pin_chass[4] = {
3486 	"external", "internal", "separate", "other"};
3487 
3488 void
3489 azalia_codec_print_audiofunc(const codec_t *this)
3490 {
3491 	uint32_t result;
3492 
3493 	azalia_widget_print_audio(&this->w[this->audiofunc], "\t");
3494 
3495 	result = this->w[this->audiofunc].inamp_cap;
3496 	DPRINTF(("\tinamp: mute=%u size=%u steps=%u offset=%u\n",
3497 	    (result & COP_AMPCAP_MUTE) != 0, COP_AMPCAP_STEPSIZE(result),
3498 	    COP_AMPCAP_NUMSTEPS(result), COP_AMPCAP_OFFSET(result)));
3499 	result = this->w[this->audiofunc].outamp_cap;
3500 	DPRINTF(("\toutamp: mute=%u size=%u steps=%u offset=%u\n",
3501 	    (result & COP_AMPCAP_MUTE) != 0, COP_AMPCAP_STEPSIZE(result),
3502 	    COP_AMPCAP_NUMSTEPS(result), COP_AMPCAP_OFFSET(result)));
3503 	azalia_comresp(this, this->audiofunc, CORB_GET_PARAMETER,
3504 	    COP_GPIO_COUNT, &result);
3505 	DPRINTF(("\tgpio: wake=%u unsol=%u gpis=%u gpos=%u gpios=%u\n",
3506 	    (result & COP_GPIO_WAKE) != 0, (result & COP_GPIO_UNSOL) != 0,
3507 	    COP_GPIO_GPIS(result), COP_GPIO_GPOS(result),
3508 	    COP_GPIO_GPIOS(result)));
3509 }
3510 
3511 void
3512 azalia_codec_print_groups(const codec_t *this)
3513 {
3514 	int i, n;
3515 
3516 	for (i = 0; i < this->dacs.ngroups; i++) {
3517 		printf("%s: dacgroup[%d]:", XNAME(this->az), i);
3518 		for (n = 0; n < this->dacs.groups[i].nconv; n++) {
3519 			printf(" %2.2x", this->dacs.groups[i].conv[n]);
3520 		}
3521 		printf("\n");
3522 	}
3523 	for (i = 0; i < this->adcs.ngroups; i++) {
3524 		printf("%s: adcgroup[%d]:", XNAME(this->az), i);
3525 		for (n = 0; n < this->adcs.groups[i].nconv; n++) {
3526 			printf(" %2.2x", this->adcs.groups[i].conv[n]);
3527 		}
3528 		printf("\n");
3529 	}
3530 }
3531 
3532 void
3533 azalia_widget_print_audio(const widget_t *this, const char *lead)
3534 {
3535 	printf("%sencodings=%b\n", lead, this->d.audio.encodings,
3536 	    ENCODING_BITS);
3537 	printf("%sPCM formats=%b\n", lead, this->d.audio.bits_rates,
3538 	    BITSRATES_BITS);
3539 }
3540 
3541 void
3542 azalia_widget_print_widget(const widget_t *w, const codec_t *codec)
3543 {
3544 	int i;
3545 
3546 	printf("%s: ", XNAME(codec->az));
3547 	printf("%s%2.2x wcap=%b\n", w->type == COP_AWTYPE_PIN_COMPLEX ?
3548 	    pin_colors[w->d.pin.color] : wtypes[w->type],
3549 	    w->nid, w->widgetcap, WIDGETCAP_BITS);
3550 	if (w->widgetcap & COP_AWCAP_FORMATOV)
3551 		azalia_widget_print_audio(w, "\t");
3552 	if (w->type == COP_AWTYPE_PIN_COMPLEX)
3553 		azalia_widget_print_pin(w);
3554 
3555 	if (w->type == COP_AWTYPE_VOLUME_KNOB)
3556 		printf("\tdelta=%d steps=%d\n",
3557 		    !!(w->d.volume.cap & COP_VKCAP_DELTA),
3558 		    COP_VKCAP_NUMSTEPS(w->d.volume.cap));
3559 
3560 	if ((w->widgetcap & COP_AWCAP_INAMP) &&
3561 	    (w->widgetcap & COP_AWCAP_AMPOV))
3562 		printf("\tinamp: mute=%u size=%u steps=%u offset=%u\n",
3563 		    (w->inamp_cap & COP_AMPCAP_MUTE) != 0,
3564 		    COP_AMPCAP_STEPSIZE(w->inamp_cap),
3565 		    COP_AMPCAP_NUMSTEPS(w->inamp_cap),
3566 		    COP_AMPCAP_OFFSET(w->inamp_cap));
3567 
3568 	if ((w->widgetcap & COP_AWCAP_OUTAMP) &&
3569 	    (w->widgetcap & COP_AWCAP_AMPOV))
3570 		printf("\toutamp: mute=%u size=%u steps=%u offset=%u\n",
3571 		    (w->outamp_cap & COP_AMPCAP_MUTE) != 0,
3572 		    COP_AMPCAP_STEPSIZE(w->outamp_cap),
3573 		    COP_AMPCAP_NUMSTEPS(w->outamp_cap),
3574 		    COP_AMPCAP_OFFSET(w->outamp_cap));
3575 
3576 	if (w->nconnections > 0) {
3577 		printf("\tconnections=0x%x", w->connections[0]);
3578 		for (i = 1; i < w->nconnections; i++)
3579 			printf(",0x%x", w->connections[i]);
3580 		printf("; selected=0x%x\n", w->connections[w->selected]);
3581 	}
3582 }
3583 
3584 void
3585 azalia_widget_print_pin(const widget_t *this)
3586 {
3587 	printf("\tcap=%b\n", this->d.pin.cap, PINCAP_BITS);
3588 	printf("\t[%2.2d/%2.2d] ", CORB_CD_ASSOCIATION(this->d.pin.config),
3589 	    CORB_CD_SEQUENCE(this->d.pin.config));
3590 	printf("color=%s ", pin_colors[CORB_CD_COLOR(this->d.pin.config)]);
3591 	printf("device=%s ", pin_devices[CORB_CD_DEVICE(this->d.pin.config)]);
3592 	printf("conn=%s ", pin_conn[CORB_CD_PORT(this->d.pin.config)]);
3593 	printf("conntype=%s\n", pin_conntype[CORB_CD_CONNECTION(this->d.pin.config)]);
3594 	printf("\tlocation=%s ", pin_geo[CORB_CD_LOC_GEO(this->d.pin.config)]);
3595 	printf("chassis=%s ", pin_chass[CORB_CD_LOC_CHASS(this->d.pin.config)]);
3596 	printf("special=");
3597 	if (CORB_CD_LOC_GEO(this->d.pin.config) == CORB_CD_LOC_SPEC0) {
3598 		if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_EXTERNAL)
3599 			printf("rear-panel");
3600 		else if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_INTERNAL)
3601 			printf("riser");
3602 		else if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_LOC_OTHER)
3603 			printf("mobile-lid-internal");
3604 	} else if (CORB_CD_LOC_GEO(this->d.pin.config) == CORB_CD_LOC_SPEC1) {
3605 		if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_EXTERNAL)
3606 			printf("drive-bay");
3607 		else if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_INTERNAL)
3608 			printf("hdmi");
3609 		else if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_LOC_OTHER)
3610 			printf("mobile-lid-external");
3611 	} else if (CORB_CD_LOC_GEO(this->d.pin.config) == CORB_CD_LOC_SPEC2) {
3612 		if (CORB_CD_LOC_CHASS(this->d.pin.config) == CORB_CD_INTERNAL)
3613 			printf("atapi");
3614 	} else
3615 		printf("none");
3616 	printf("\n");
3617 }
3618 
3619 #else	/* AZALIA_DEBUG */
3620 
3621 void
3622 azalia_codec_print_audiofunc(const codec_t *this) {}
3623 
3624 void
3625 azalia_codec_print_groups(const codec_t *this) {}
3626 
3627 void
3628 azalia_widget_print_audio(const widget_t *this, const char *lead) {}
3629 
3630 void
3631 azalia_widget_print_widget(const widget_t *w, const codec_t *codec) {}
3632 
3633 void
3634 azalia_widget_print_pin(const widget_t *this) {}
3635 
3636 #endif	/* AZALIA_DEBUG */
3637 
3638 /* ================================================================
3639  * Stream functions
3640  * ================================================================ */
3641 
3642 int
3643 azalia_stream_init(stream_t *this, azalia_t *az, int regindex, int strnum,
3644     int dir)
3645 {
3646 	int err;
3647 
3648 	this->az = az;
3649 	this->regbase = HDA_SD_BASE + regindex * HDA_SD_SIZE;
3650 	this->intr_bit = 1 << regindex;
3651 	this->number = strnum;
3652 	this->dir = dir;
3653 
3654 	/* setup BDL buffers */
3655 	err = azalia_alloc_dmamem(az, sizeof(bdlist_entry_t) * HDA_BDL_MAX,
3656 				  128, &this->bdlist);
3657 	if (err) {
3658 		printf("%s: can't allocate a BDL buffer\n", XNAME(az));
3659 		return err;
3660 	}
3661 	return 0;
3662 }
3663 
3664 int
3665 azalia_stream_reset(stream_t *this)
3666 {
3667 	int i;
3668 	uint16_t ctl;
3669 	uint8_t sts;
3670 
3671 	/* Make sure RUN bit is zero before resetting */
3672 	ctl = STR_READ_2(this, CTL);
3673 	ctl &= ~HDA_SD_CTL_RUN;
3674 	STR_WRITE_2(this, CTL, ctl);
3675 	DELAY(40);
3676 
3677 	/* Start reset and wait for chip to enter. */
3678 	ctl = STR_READ_2(this, CTL);
3679 	STR_WRITE_2(this, CTL, ctl | HDA_SD_CTL_SRST);
3680 	for (i = 5000; i > 0; i--) {
3681 		DELAY(10);
3682 		ctl = STR_READ_2(this, CTL);
3683 		if (ctl & HDA_SD_CTL_SRST)
3684 			break;
3685 	}
3686 	if (i == 0) {
3687 		DPRINTF(("%s: stream reset failure 1\n", XNAME(this->az)));
3688 		return -1;
3689 	}
3690 
3691 	/* Clear reset and wait for chip to finish */
3692 	STR_WRITE_2(this, CTL, ctl & ~HDA_SD_CTL_SRST);
3693 	for (i = 5000; i > 0; i--) {
3694 		DELAY(10);
3695 		ctl = STR_READ_2(this, CTL);
3696 		if ((ctl & HDA_SD_CTL_SRST) == 0)
3697 			break;
3698 	}
3699 	if (i == 0) {
3700 		DPRINTF(("%s: stream reset failure 2\n", XNAME(this->az)));
3701 		return -1;
3702 	}
3703 
3704 	sts = STR_READ_1(this, STS);
3705 	sts |= HDA_SD_STS_DESE | HDA_SD_STS_FIFOE | HDA_SD_STS_BCIS;
3706 	STR_WRITE_1(this, STS, sts);
3707 
3708 	return (0);
3709 }
3710 
3711 int
3712 azalia_stream_start(stream_t *this)
3713 {
3714 	bdlist_entry_t *bdlist;
3715 	bus_addr_t dmaaddr, dmaend;
3716 	int err, index;
3717 	uint32_t intctl;
3718 	uint8_t ctl2;
3719 
3720 	err = azalia_stream_reset(this);
3721 	if (err) {
3722 		DPRINTF(("%s: stream reset failed\n", "azalia"));
3723 		return err;
3724 	}
3725 
3726 	STR_WRITE_4(this, BDPL, 0);
3727 	STR_WRITE_4(this, BDPU, 0);
3728 
3729 	/* setup BDL */
3730 	dmaaddr = AZALIA_DMA_DMAADDR(&this->buffer);
3731 	dmaend = dmaaddr + this->bufsize;
3732 	bdlist = (bdlist_entry_t*)this->bdlist.addr;
3733 	for (index = 0; index < HDA_BDL_MAX; index++) {
3734 		bdlist[index].low = htole32(dmaaddr);
3735 		bdlist[index].high = htole32(PTR_UPPER32(dmaaddr));
3736 		bdlist[index].length = htole32(this->blk);
3737 		bdlist[index].flags = htole32(BDLIST_ENTRY_IOC);
3738 		dmaaddr += this->blk;
3739 		if (dmaaddr >= dmaend) {
3740 			index++;
3741 			break;
3742 		}
3743 	}
3744 
3745 	DPRINTFN(1, ("%s: size=%d fmt=0x%4.4x index=%d\n",
3746 	    __func__, this->bufsize, this->fmt, index));
3747 
3748 	dmaaddr = AZALIA_DMA_DMAADDR(&this->bdlist);
3749 	STR_WRITE_4(this, BDPL, dmaaddr);
3750 	STR_WRITE_4(this, BDPU, PTR_UPPER32(dmaaddr));
3751 	STR_WRITE_2(this, LVI, (index - 1) & HDA_SD_LVI_LVI);
3752 	ctl2 = STR_READ_1(this, CTL2);
3753 	STR_WRITE_1(this, CTL2,
3754 	    (ctl2 & ~HDA_SD_CTL2_STRM) | (this->number << HDA_SD_CTL2_STRM_SHIFT));
3755 	STR_WRITE_4(this, CBL, this->bufsize);
3756 	STR_WRITE_2(this, FMT, this->fmt);
3757 
3758 	err = azalia_codec_connect_stream(this);
3759 	if (err)
3760 		return EINVAL;
3761 
3762 	intctl = AZ_READ_4(this->az, INTCTL);
3763 	intctl |= this->intr_bit;
3764 	AZ_WRITE_4(this->az, INTCTL, intctl);
3765 
3766 	STR_WRITE_1(this, CTL, STR_READ_1(this, CTL) |
3767 	    HDA_SD_CTL_DEIE | HDA_SD_CTL_FEIE | HDA_SD_CTL_IOCE |
3768 	    HDA_SD_CTL_RUN);
3769 	return (0);
3770 }
3771 
3772 int
3773 azalia_stream_halt(stream_t *this)
3774 {
3775 	uint16_t ctl;
3776 
3777 	ctl = STR_READ_2(this, CTL);
3778 	ctl &= ~(HDA_SD_CTL_DEIE | HDA_SD_CTL_FEIE | HDA_SD_CTL_IOCE | HDA_SD_CTL_RUN);
3779 	STR_WRITE_2(this, CTL, ctl);
3780 	AZ_WRITE_4(this->az, INTCTL,
3781 	    AZ_READ_4(this->az, INTCTL) & ~this->intr_bit);
3782 	azalia_codec_disconnect_stream(this);
3783 
3784 	return (0);
3785 }
3786 
3787 #define	HDA_SD_STS_BITS	"\20\3BCIS\4FIFOE\5DESE\6FIFORDY"
3788 
3789 int
3790 azalia_stream_intr(stream_t *this)
3791 {
3792 	unsigned int lpib, fifos, hwpos, cnt;
3793 	u_int8_t sts;
3794 
3795 	sts = STR_READ_1(this, STS);
3796 	STR_WRITE_1(this, STS, sts |
3797 	    HDA_SD_STS_DESE | HDA_SD_STS_FIFOE | HDA_SD_STS_BCIS);
3798 
3799 	if (sts & (HDA_SD_STS_DESE | HDA_SD_STS_FIFOE))
3800 		DPRINTF(("%s: stream %d: sts=%b\n", XNAME(this->az),
3801 		    this->number, sts, HDA_SD_STS_BITS));
3802 
3803 	if (sts & HDA_SD_STS_BCIS) {
3804 		lpib = STR_READ_4(this, LPIB);
3805 		fifos = STR_READ_2(this, FIFOS);
3806 		if (fifos & 1)
3807 			fifos++;
3808 		hwpos = lpib;
3809 		if (this->dir == AUMODE_PLAY)
3810 			hwpos += fifos + 1;
3811 		if (hwpos >= this->bufsize)
3812 			hwpos -= this->bufsize;
3813 		DPRINTFN(2, ("%s: stream %d, pos = %d -> %d, "
3814 		    "lpib = %u, fifos = %u\n", __func__,
3815 		    this->number, this->swpos, hwpos, lpib, fifos));
3816 		cnt = 0;
3817 		while (hwpos - this->swpos >= this->blk) {
3818 			this->intr(this->intr_arg);
3819 			this->swpos += this->blk;
3820 			if (this->swpos == this->bufsize)
3821 				this->swpos = 0;
3822 			cnt++;
3823 		}
3824 		if (cnt != 1) {
3825 			DPRINTF(("%s: stream %d: hwpos %u, %u intrs\n",
3826 			    __func__, this->number, this->swpos, cnt));
3827 		}
3828 	}
3829 	return (1);
3830 }
3831 
3832 /* ================================================================
3833  * MI audio entries
3834  * ================================================================ */
3835 
3836 int
3837 azalia_open(void *v, int flags)
3838 {
3839 	azalia_t *az;
3840 	codec_t *codec;
3841 
3842 	DPRINTFN(1, ("%s: flags=0x%x\n", __func__, flags));
3843 	az = v;
3844 	codec = &az->codecs[az->codecno];
3845 	codec->running++;
3846 	return 0;
3847 }
3848 
3849 void
3850 azalia_close(void *v)
3851 {
3852 	azalia_t *az;
3853 	codec_t *codec;
3854 
3855 	DPRINTFN(1, ("%s\n", __func__));
3856 	az = v;
3857 	codec = &az->codecs[az->codecno];
3858 	codec->running--;
3859 }
3860 
3861 int
3862 azalia_match_format(codec_t *codec, int mode, audio_params_t *par)
3863 {
3864 	int i;
3865 
3866 	DPRINTFN(1, ("%s: mode=%d, want: enc=%d, prec=%d, chans=%d\n", __func__,
3867 	    mode, par->encoding, par->precision, par->channels));
3868 
3869 	for (i = 0; i < codec->nformats; i++) {
3870 		if (mode != codec->formats[i].mode)
3871 			continue;
3872 		if (par->encoding != codec->formats[i].encoding)
3873 			continue;
3874 		if (par->precision != codec->formats[i].precision)
3875 			continue;
3876 		if (par->channels != codec->formats[i].channels)
3877 			continue;
3878 		break;
3879 	}
3880 
3881 	DPRINTFN(1, ("%s: return: enc=%d, prec=%d, chans=%d\n", __func__,
3882 	    codec->formats[i].encoding, codec->formats[i].precision,
3883 	    codec->formats[i].channels));
3884 
3885 	return (i);
3886 }
3887 
3888 int
3889 azalia_set_params_sub(codec_t *codec, int mode, audio_params_t *par)
3890 {
3891 	char *cmode;
3892 	int i, j;
3893 	uint ochan, oenc, opre;
3894 
3895 	if (mode == AUMODE_PLAY)
3896 		cmode = "play";
3897 	else
3898 		cmode = "record";
3899 
3900 	ochan = par->channels;
3901 	oenc = par->encoding;
3902 	opre = par->precision;
3903 
3904 	if ((mode == AUMODE_PLAY && codec->dacs.ngroups == 0) ||
3905 	    (mode == AUMODE_RECORD && codec->adcs.ngroups == 0))
3906 		return 0;
3907 
3908 	i = azalia_match_format(codec, mode, par);
3909 	if (i == codec->nformats && (par->precision != 16 || par->encoding !=
3910 	    AUDIO_ENCODING_SLINEAR_LE)) {
3911 		/* try with default encoding/precision */
3912 		par->encoding = AUDIO_ENCODING_SLINEAR_LE;
3913 		par->precision = 16;
3914 		i = azalia_match_format(codec, mode, par);
3915 	}
3916 	if (i == codec->nformats && par->channels != 2) {
3917 		/* try with default channels */
3918 		par->encoding = oenc;
3919 		par->precision = opre;
3920 		par->channels = 2;
3921 		i = azalia_match_format(codec, mode, par);
3922 	}
3923 	/* try with default everything */
3924 	if (i == codec->nformats) {
3925 		par->encoding = AUDIO_ENCODING_SLINEAR_LE;
3926 		par->precision = 16;
3927 		par->channels = 2;
3928 		i = azalia_match_format(codec, mode, par);
3929 		if (i == codec->nformats) {
3930 			DPRINTF(("%s: can't find %s format %u/%u/%u\n",
3931 			    __func__, cmode, par->encoding,
3932 			    par->precision, par->channels));
3933 			return EINVAL;
3934 		}
3935 	}
3936 	if (codec->formats[i].frequency_type == 0) {
3937 		DPRINTF(("%s: matched %s format %d has 0 frequencies\n",
3938 		    __func__, cmode, i));
3939 		return EINVAL;
3940 	}
3941 
3942 	for (j = 0; j < codec->formats[i].frequency_type; j++) {
3943 		if (par->sample_rate != codec->formats[i].frequency[j])
3944 			continue;
3945 		break;
3946 	}
3947 	if (j == codec->formats[i].frequency_type) {
3948 		/* try again with default */
3949 		par->sample_rate = 48000;
3950 		for (j = 0; j < codec->formats[i].frequency_type; j++) {
3951 			if (par->sample_rate != codec->formats[i].frequency[j])
3952 				continue;
3953 			break;
3954 		}
3955 		if (j == codec->formats[i].frequency_type) {
3956 			DPRINTF(("%s: can't find %s rate %lu\n",
3957 			    __func__, cmode, par->sample_rate));
3958 			return EINVAL;
3959 		}
3960 	}
3961 	par->bps = AUDIO_BPS(par->precision);
3962 	par->msb = 1;
3963 
3964 	return (0);
3965 }
3966 
3967 int
3968 azalia_set_params(void *v, int smode, int umode, audio_params_t *p,
3969     audio_params_t *r)
3970 {
3971 	azalia_t *az;
3972 	codec_t *codec;
3973 	int ret;
3974 
3975 	az = v;
3976 	codec = &az->codecs[az->codecno];
3977 	if (codec->nformats == 0) {
3978 		DPRINTF(("%s: codec has no formats\n", __func__));
3979 		return EINVAL;
3980 	}
3981 
3982 	if (smode & AUMODE_RECORD && r != NULL) {
3983 		ret = azalia_set_params_sub(codec, AUMODE_RECORD, r);
3984 		if (ret)
3985 			return (ret);
3986 	}
3987 
3988 	if (smode & AUMODE_PLAY && p != NULL) {
3989 		ret = azalia_set_params_sub(codec, AUMODE_PLAY, p);
3990 		if (ret)
3991 			return (ret);
3992 	}
3993 
3994 	return (0);
3995 }
3996 
3997 int
3998 azalia_round_blocksize(void *v, int blk)
3999 {
4000 	azalia_t *az;
4001 	size_t size;
4002 
4003 	blk &= ~0x7f;		/* must be multiple of 128 */
4004 	if (blk <= 0)
4005 		blk = 128;
4006 	/* number of blocks must be <= HDA_BDL_MAX */
4007 	az = v;
4008 	size = az->pstream.buffer.size;
4009 	if (size > HDA_BDL_MAX * blk) {
4010 		blk = size / HDA_BDL_MAX;
4011 		if (blk & 0x7f)
4012 			blk = (blk + 0x7f) & ~0x7f;
4013 	}
4014 	DPRINTFN(1,("%s: resultant block size = %d\n", __func__, blk));
4015 	return blk;
4016 }
4017 
4018 int
4019 azalia_halt_output(void *v)
4020 {
4021 	azalia_t *az;
4022 
4023 	DPRINTFN(1, ("%s\n", __func__));
4024 	az = v;
4025 	return azalia_stream_halt(&az->pstream);
4026 }
4027 
4028 int
4029 azalia_halt_input(void *v)
4030 {
4031 	azalia_t *az;
4032 
4033 	DPRINTFN(1, ("%s\n", __func__));
4034 	az = v;
4035 	return azalia_stream_halt(&az->rstream);
4036 }
4037 
4038 int
4039 azalia_set_port(void *v, mixer_ctrl_t *mc)
4040 {
4041 	azalia_t *az;
4042 	codec_t *co;
4043 	const mixer_item_t *m;
4044 
4045 	az = v;
4046 	co = &az->codecs[az->codecno];
4047 	if (mc->dev < 0 || mc->dev >= co->nmixers)
4048 		return EINVAL;
4049 
4050 	m = &co->mixers[mc->dev];
4051 	if (mc->type != m->devinfo.type)
4052 		return EINVAL;
4053 
4054 	return azalia_mixer_set(co, m->nid, m->target, mc);
4055 }
4056 
4057 int
4058 azalia_get_port(void *v, mixer_ctrl_t *mc)
4059 {
4060 	azalia_t *az;
4061 	codec_t *co;
4062 	const mixer_item_t *m;
4063 
4064 	az = v;
4065 	co = &az->codecs[az->codecno];
4066 	if (mc->dev < 0 || mc->dev >= co->nmixers)
4067 		return EINVAL;
4068 
4069 	m = &co->mixers[mc->dev];
4070 	mc->type = m->devinfo.type;
4071 
4072 	return azalia_mixer_get(co, m->nid, m->target, mc);
4073 }
4074 
4075 int
4076 azalia_query_devinfo(void *v, mixer_devinfo_t *mdev)
4077 {
4078 	azalia_t *az;
4079 	const codec_t *co;
4080 
4081 	az = v;
4082 	co = &az->codecs[az->codecno];
4083 	if (mdev->index < 0 || mdev->index >= co->nmixers)
4084 		return ENXIO;
4085 	*mdev = co->mixers[mdev->index].devinfo;
4086 	return 0;
4087 }
4088 
4089 void *
4090 azalia_allocm(void *v, int dir, size_t size, int pool, int flags)
4091 {
4092 	azalia_t *az;
4093 	stream_t *stream;
4094 	int err;
4095 
4096 	az = v;
4097 	stream = dir == AUMODE_PLAY ? &az->pstream : &az->rstream;
4098 	err = azalia_alloc_dmamem(az, size, 128, &stream->buffer);
4099 	if (err) {
4100 		printf("%s: allocm failed\n", az->dev.dv_xname);
4101 		return NULL;
4102 	}
4103 	return stream->buffer.addr;
4104 }
4105 
4106 void
4107 azalia_freem(void *v, void *addr, int pool)
4108 {
4109 	azalia_t *az;
4110 	stream_t *stream;
4111 
4112 	az = v;
4113 	if (addr == az->pstream.buffer.addr) {
4114 		stream = &az->pstream;
4115 	} else if (addr == az->rstream.buffer.addr) {
4116 		stream = &az->rstream;
4117 	} else {
4118 		return;
4119 	}
4120 	azalia_free_dmamem(az, &stream->buffer);
4121 }
4122 
4123 size_t
4124 azalia_round_buffersize(void *v, int dir, size_t size)
4125 {
4126 	size &= ~0x7f;		/* must be multiple of 128 */
4127 	if (size <= 0)
4128 		size = 128;
4129 	return size;
4130 }
4131 
4132 int
4133 azalia_get_props(void *v)
4134 {
4135 	return AUDIO_PROP_INDEPENDENT | AUDIO_PROP_FULLDUPLEX;
4136 }
4137 
4138 int
4139 azalia_trigger_output(void *v, void *start, void *end, int blk,
4140     void (*intr)(void *), void *arg, audio_params_t *param)
4141 {
4142 	azalia_t *az;
4143 	int err;
4144 	uint16_t fmt;
4145 
4146 	az = v;
4147 
4148 	if (az->codecs[az->codecno].dacs.ngroups == 0) {
4149 		DPRINTF(("%s: can't play without a DAC\n", __func__));
4150 		return ENXIO;
4151 	}
4152 
4153 	err = azalia_params2fmt(param, &fmt);
4154 	if (err)
4155 		return(EINVAL);
4156 
4157 	az->pstream.bufsize = (caddr_t)end - (caddr_t)start;
4158 	az->pstream.blk = blk;
4159 	az->pstream.fmt = fmt;
4160 	az->pstream.intr = intr;
4161 	az->pstream.intr_arg = arg;
4162 	az->pstream.swpos = 0;
4163 
4164 	return azalia_stream_start(&az->pstream);
4165 }
4166 
4167 int
4168 azalia_trigger_input(void *v, void *start, void *end, int blk,
4169     void (*intr)(void *), void *arg, audio_params_t *param)
4170 {
4171 	azalia_t *az;
4172 	int err;
4173 	uint16_t fmt;
4174 
4175 	DPRINTFN(1, ("%s: this=%p start=%p end=%p blk=%d {enc=%u %uch %ubit %luHz}\n",
4176 	    __func__, v, start, end, blk, param->encoding, param->channels,
4177 	    param->precision, param->sample_rate));
4178 
4179 	az = v;
4180 
4181 	if (az->codecs[az->codecno].adcs.ngroups == 0) {
4182 		DPRINTF(("%s: can't record without an ADC\n", __func__));
4183 		return ENXIO;
4184 	}
4185 
4186 	err = azalia_params2fmt(param, &fmt);
4187 	if (err)
4188 		return(EINVAL);
4189 
4190 	az->rstream.bufsize = (caddr_t)end - (caddr_t)start;
4191 	az->rstream.blk = blk;
4192 	az->rstream.fmt = fmt;
4193 	az->rstream.intr = intr;
4194 	az->rstream.intr_arg = arg;
4195 	az->rstream.swpos = 0;
4196 
4197 	return azalia_stream_start(&az->rstream);
4198 }
4199 
4200 /* --------------------------------
4201  * helpers for MI audio functions
4202  * -------------------------------- */
4203 int
4204 azalia_params2fmt(const audio_params_t *param, uint16_t *fmt)
4205 {
4206 	uint16_t ret;
4207 
4208 	ret = 0;
4209 	if (param->channels > HDA_MAX_CHANNELS) {
4210 		printf("%s: too many channels: %u\n", __func__,
4211 		    param->channels);
4212 		return EINVAL;
4213 	}
4214 
4215 	DPRINTFN(1, ("%s: prec=%d, chan=%d, rate=%ld\n", __func__,
4216 	    param->precision, param->channels, param->sample_rate));
4217 
4218 	/* XXX: can channels be >2 ? */
4219 	ret |= param->channels - 1;
4220 
4221 	switch (param->precision) {
4222 	case 8:
4223 		ret |= HDA_SD_FMT_BITS_8_16;
4224 		break;
4225 	case 16:
4226 		ret |= HDA_SD_FMT_BITS_16_16;
4227 		break;
4228 	case 20:
4229 		ret |= HDA_SD_FMT_BITS_20_32;
4230 		break;
4231 	case 24:
4232 		ret |= HDA_SD_FMT_BITS_24_32;
4233 		break;
4234 	case 32:
4235 		ret |= HDA_SD_FMT_BITS_32_32;
4236 		break;
4237 	}
4238 
4239 	switch (param->sample_rate) {
4240 	default:
4241 	case 384000:
4242 		printf("%s: invalid sample_rate: %lu\n", __func__,
4243 		    param->sample_rate);
4244 		return EINVAL;
4245 	case 192000:
4246 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X4 | HDA_SD_FMT_DIV_BY1;
4247 		break;
4248 	case 176400:
4249 		ret |= HDA_SD_FMT_BASE_44 | HDA_SD_FMT_MULT_X4 | HDA_SD_FMT_DIV_BY1;
4250 		break;
4251 	case 96000:
4252 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X2 | HDA_SD_FMT_DIV_BY1;
4253 		break;
4254 	case 88200:
4255 		ret |= HDA_SD_FMT_BASE_44 | HDA_SD_FMT_MULT_X2 | HDA_SD_FMT_DIV_BY1;
4256 		break;
4257 	case 48000:
4258 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY1;
4259 		break;
4260 	case 44100:
4261 		ret |= HDA_SD_FMT_BASE_44 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY1;
4262 		break;
4263 	case 32000:
4264 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X2 | HDA_SD_FMT_DIV_BY3;
4265 		break;
4266 	case 22050:
4267 		ret |= HDA_SD_FMT_BASE_44 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY2;
4268 		break;
4269 	case 16000:
4270 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY3;
4271 		break;
4272 	case 11025:
4273 		ret |= HDA_SD_FMT_BASE_44 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY4;
4274 		break;
4275 	case 8000:
4276 		ret |= HDA_SD_FMT_BASE_48 | HDA_SD_FMT_MULT_X1 | HDA_SD_FMT_DIV_BY6;
4277 		break;
4278 	}
4279 	*fmt = ret;
4280 	return 0;
4281 }
4282