Home | History | Annotate | Line # | Download | only in hdaudio
      1 /* $NetBSD: hdaudio.c,v 1.19 2026/07/23 22:07:44 riastradh Exp $ */
      2 
      3 /*
      4  * Copyright (c) 2009 Precedence Technologies Ltd <support (at) precedence.co.uk>
      5  * Copyright (c) 2009 Jared D. McNeill <jmcneill (at) invisible.ca>
      6  * All rights reserved.
      7  *
      8  * This code is derived from software contributed to The NetBSD Foundation
      9  * by Precedence Technologies Ltd
     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. The name of the author may not be used to endorse or promote products
     17  *    derived from this software without specific prior written permission.
     18  *
     19  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
     20  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
     21  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
     22  * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
     23  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
     24  * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
     25  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED
     26  * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
     27  * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
     28  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
     29  * SUCH DAMAGE.
     30  */
     31 
     32 #include <sys/cdefs.h>
     33 __KERNEL_RCSID(0, "$NetBSD: hdaudio.c,v 1.19 2026/07/23 22:07:44 riastradh Exp $");
     34 
     35 #include <sys/param.h>
     36 #include <sys/types.h>
     37 
     38 #include <sys/bus.h>
     39 #include <sys/conf.h>
     40 #include <sys/device.h>
     41 #include <sys/fcntl.h>
     42 #include <sys/kmem.h>
     43 #include <sys/module.h>
     44 #include <sys/systm.h>
     45 
     46 #include "hdaudiovar.h"
     47 #include "hdaudioreg.h"
     48 #include "hdaudioio.h"
     49 #include "hdaudio_verbose.h"
     50 #include "hdaudiodevs.h"
     51 
     52 /* #define	HDAUDIO_DEBUG */
     53 
     54 #define	HDAUDIO_RESET_TIMEOUT	5000
     55 #define HDAUDIO_CORB_TIMEOUT	1000
     56 #define	HDAUDIO_RIRB_TIMEOUT	5000
     57 
     58 #define	HDAUDIO_CODEC_DELAY	1000	/* spec calls for 250 */
     59 
     60 dev_type_open(hdaudioopen);
     61 dev_type_close(hdaudioclose);
     62 dev_type_ioctl(hdaudioioctl);
     63 
     64 const struct cdevsw hdaudio_cdevsw = {
     65 	.d_open = hdaudioopen,
     66 	.d_close = hdaudioclose,
     67 	.d_read = noread,
     68 	.d_write = nowrite,
     69 	.d_ioctl = hdaudioioctl,
     70 	.d_stop = nostop,
     71 	.d_tty = notty,
     72 	.d_poll = nopoll,
     73 	.d_mmap = nommap,
     74 	.d_kqfilter = nokqfilter,
     75 	.d_discard = nodiscard,
     76 	.d_flag = D_OTHER
     77 };
     78 
     79 extern struct cfdriver hdaudio_cd;
     80 
     81 #define	HDAUDIOUNIT(x)	minor((x))
     82 
     83 static void
     84 hdaudio_stream_init(struct hdaudio_softc *sc, int nis, int nos, int nbidir)
     85 {
     86 	int i, cnt = 0;
     87 
     88 	for (i = 0; i < nis && cnt < HDAUDIO_MAX_STREAMS; i++) {
     89 		sc->sc_stream[cnt].st_host = sc;
     90 		sc->sc_stream[cnt].st_enable = true;
     91 		sc->sc_stream[cnt].st_shift = cnt;
     92 		sc->sc_stream[cnt++].st_type = HDAUDIO_STREAM_ISS;
     93 	}
     94 	for (i = 0; i < nos && cnt < HDAUDIO_MAX_STREAMS; i++) {
     95 		sc->sc_stream[cnt].st_host = sc;
     96 		sc->sc_stream[cnt].st_enable = true;
     97 		sc->sc_stream[cnt].st_shift = cnt;
     98 		sc->sc_stream[cnt++].st_type = HDAUDIO_STREAM_OSS;
     99 	}
    100 	for (i = 0; i < nbidir && cnt < HDAUDIO_MAX_STREAMS; i++) {
    101 		sc->sc_stream[cnt].st_host = sc;
    102 		sc->sc_stream[cnt].st_enable = true;
    103 		sc->sc_stream[cnt].st_shift = cnt;
    104 		sc->sc_stream[cnt++].st_type = HDAUDIO_STREAM_BSS;
    105 	}
    106 
    107 	for (i = 0; i < cnt; i++)
    108 		hdaudio_stream_stop(&sc->sc_stream[i]);
    109 
    110 	sc->sc_stream_mask = 0;
    111 }
    112 
    113 static void
    114 hdaudio_codec_init(struct hdaudio_softc *sc)
    115 {
    116 	int i;
    117 
    118 	for (i = 0; i < HDAUDIO_MAX_CODECS; i++) {
    119 		sc->sc_codec[i].co_addr = i;
    120 		sc->sc_codec[i].co_host = sc;
    121 	}
    122 }
    123 
    124 static void
    125 hdaudio_init(struct hdaudio_softc *sc)
    126 {
    127 	const uint8_t vmaj = hda_read1(sc, HDAUDIO_MMIO_VMAJ);
    128 	const uint8_t vmin = hda_read1(sc, HDAUDIO_MMIO_VMIN);
    129 	const uint16_t gcap = hda_read2(sc, HDAUDIO_MMIO_GCAP);
    130 	const int nis = HDAUDIO_GCAP_ISS(gcap);
    131 	const int nos = HDAUDIO_GCAP_OSS(gcap);
    132 	const int nbidir = HDAUDIO_GCAP_BSS(gcap);
    133 	const int nsdo = HDAUDIO_GCAP_NSDO(gcap);
    134 	const int addr64 = HDAUDIO_GCAP_64OK(gcap);
    135 
    136 	hda_print(sc, "HDA ver. %d.%d, OSS %d, ISS %d, BSS %d, SDO %d%s\n",
    137 	    vmaj, vmin, nos, nis, nbidir, nsdo, addr64 ? ", 64-bit" : "");
    138 
    139 	/* Initialize codecs and streams */
    140 	hdaudio_codec_init(sc);
    141 	hdaudio_stream_init(sc, nis, nos, nbidir);
    142 }
    143 
    144 static int
    145 hdaudio_codec_probe(struct hdaudio_softc *sc)
    146 {
    147 	uint16_t statests;
    148 	int codecid;
    149 
    150 	statests = hda_read2(sc, HDAUDIO_MMIO_STATESTS);
    151 	for (codecid = 0; codecid < HDAUDIO_MAX_CODECS; codecid++)
    152 		if (statests & (1 << codecid))
    153 			sc->sc_codec[codecid].co_valid = true;
    154 	hda_write2(sc, HDAUDIO_MMIO_STATESTS, statests);
    155 
    156 	return statests;
    157 }
    158 
    159 int
    160 hdaudio_dma_alloc(struct hdaudio_softc *sc, struct hdaudio_dma *dma,
    161     int flags)
    162 {
    163 	int err;
    164 
    165 	KASSERT(dma->dma_size > 0);
    166 
    167 	err = bus_dmamem_alloc(sc->sc_dmat, dma->dma_size, 128, 0,
    168 	    dma->dma_segs, sizeof(dma->dma_segs) / sizeof(dma->dma_segs[0]),
    169 	    &dma->dma_nsegs, BUS_DMA_WAITOK);
    170 	if (err)
    171 		return err;
    172 	err = bus_dmamem_map(sc->sc_dmat, dma->dma_segs, dma->dma_nsegs,
    173 	    dma->dma_size, &dma->dma_addr, BUS_DMA_WAITOK | flags);
    174 	if (err)
    175 		goto free;
    176 	err = bus_dmamap_create(sc->sc_dmat, dma->dma_size, dma->dma_nsegs,
    177 	    dma->dma_size, 0, BUS_DMA_WAITOK, &dma->dma_map);
    178 	if (err)
    179 		goto unmap;
    180 	err = bus_dmamap_load(sc->sc_dmat, dma->dma_map, dma->dma_addr,
    181 	    dma->dma_size, NULL, BUS_DMA_WAITOK | flags);
    182 	if (err)
    183 		goto destroy;
    184 
    185 	memset(dma->dma_addr, 0, dma->dma_size);
    186 	bus_dmamap_sync(sc->sc_dmat, dma->dma_map, 0, dma->dma_size,
    187 	    BUS_DMASYNC_PREWRITE);
    188 
    189 	dma->dma_valid = true;
    190 	return 0;
    191 
    192 destroy:
    193 	bus_dmamap_destroy(sc->sc_dmat, dma->dma_map);
    194 unmap:
    195 	bus_dmamem_unmap(sc->sc_dmat, dma->dma_addr, dma->dma_size);
    196 free:
    197 	bus_dmamem_free(sc->sc_dmat, dma->dma_segs, dma->dma_nsegs);
    198 
    199 	dma->dma_valid = false;
    200 	return err;
    201 }
    202 
    203 void
    204 hdaudio_dma_free(struct hdaudio_softc *sc, struct hdaudio_dma *dma)
    205 {
    206 	if (dma->dma_valid == false)
    207 		return;
    208 	bus_dmamap_unload(sc->sc_dmat, dma->dma_map);
    209 	bus_dmamap_destroy(sc->sc_dmat, dma->dma_map);
    210 	bus_dmamem_unmap(sc->sc_dmat, dma->dma_addr, dma->dma_size);
    211 	bus_dmamem_free(sc->sc_dmat, dma->dma_segs, dma->dma_nsegs);
    212 	dma->dma_valid = false;
    213 }
    214 
    215 static void
    216 hdaudio_corb_enqueue(struct hdaudio_softc *sc, int addr, int nid,
    217     uint32_t control, uint32_t param)
    218 {
    219 	uint32_t *corb = DMA_KERNADDR(&sc->sc_corb);
    220 	uint32_t verb;
    221 	uint16_t corbrp;
    222 	int wp;
    223 
    224 	/* Build command */
    225 	verb = (addr << 28) | (nid << 20) | (control << 8) | param;
    226 
    227 	/* Fetch and update write pointer */
    228 	corbrp = hda_read2(sc, HDAUDIO_MMIO_CORBWP);
    229 	wp = (corbrp & 0xff) + 1;
    230 	if (wp >= (sc->sc_corb.dma_size / sizeof(*corb)))
    231 		wp = 0;
    232 
    233 	/* Enqueue command */
    234 	bus_dmamap_sync(sc->sc_dmat, sc->sc_corb.dma_map, 0,
    235 	    sc->sc_corb.dma_size, BUS_DMASYNC_POSTWRITE);
    236 	corb[wp] = verb;
    237 	bus_dmamap_sync(sc->sc_dmat, sc->sc_corb.dma_map, 0,
    238 	    sc->sc_corb.dma_size, BUS_DMASYNC_PREWRITE);
    239 
    240 	/* Commit updated write pointer */
    241 	hda_write2(sc, HDAUDIO_MMIO_CORBWP, wp);
    242 }
    243 
    244 static void
    245 hdaudio_rirb_unsol(struct hdaudio_softc *sc, struct rirb_entry *entry)
    246 {
    247 	struct hdaudio_codec *co;
    248 	struct hdaudio_function_group *fg;
    249 	uint8_t codecid = RIRB_CODEC_ID(entry);
    250 	unsigned int i;
    251 
    252 	if (codecid >= HDAUDIO_MAX_CODECS) {
    253 		hda_error(sc, "unsol: codec id 0x%02x out of range\n", codecid);
    254 		return;
    255 	}
    256 	co = &sc->sc_codec[codecid];
    257 	if (sc->sc_codec[codecid].co_valid == false) {
    258 		hda_error(sc, "unsol: codec id 0x%02x not valid\n", codecid);
    259 		return;
    260 	}
    261 
    262 	for (i = 0; i < co->co_nfg; i++) {
    263 		fg = &co->co_fg[i];
    264 		if (fg->fg_device && fg->fg_unsol)
    265 			fg->fg_unsol(fg->fg_device, entry->resp);
    266 	}
    267 }
    268 
    269 static uint32_t
    270 hdaudio_rirb_dequeue(struct hdaudio_softc *sc, bool unsol)
    271 {
    272 	uint16_t rirbwp;
    273 	uint64_t *rirb = DMA_KERNADDR(&sc->sc_rirb);
    274 	struct rirb_entry entry;
    275 	int retry;
    276 
    277 	for (;;) {
    278 		retry = HDAUDIO_RIRB_TIMEOUT;
    279 
    280 		rirbwp = hda_read2(sc, HDAUDIO_MMIO_RIRBWP);
    281 		while (--retry > 0 && (rirbwp & 0xff) == sc->sc_rirbrp) {
    282 			if (unsol) {
    283 				/* don't wait for more unsol events */
    284 				hda_trace(sc, "unsol: rirb empty\n");
    285 				return 0xffffffff;
    286 			}
    287 			hda_delay(10);
    288 			rirbwp = hda_read2(sc, HDAUDIO_MMIO_RIRBWP);
    289 		}
    290 		if (retry == 0) {
    291 			hda_error(sc, "RIRB timeout\n");
    292 			return 0xffffffff;
    293 		}
    294 
    295 		sc->sc_rirbrp++;
    296 		if (sc->sc_rirbrp >= (sc->sc_rirb.dma_size / sizeof(*rirb)))
    297 			sc->sc_rirbrp = 0;
    298 
    299 		bus_dmamap_sync(sc->sc_dmat, sc->sc_rirb.dma_map, 0,
    300 		    sc->sc_rirb.dma_size, BUS_DMASYNC_POSTREAD);
    301 		entry = *(struct rirb_entry *)&rirb[sc->sc_rirbrp];
    302 		bus_dmamap_sync(sc->sc_dmat, sc->sc_rirb.dma_map, 0,
    303 		    sc->sc_rirb.dma_size, BUS_DMASYNC_PREREAD);
    304 
    305 		hda_trace(sc, "%s: response %08X %08X\n",
    306 		    unsol ? "unsol" : "cmd  ",
    307 		    entry.resp, entry.resp_ex);
    308 
    309 		if (RIRB_UNSOL(&entry)) {
    310 			hdaudio_rirb_unsol(sc, &entry);
    311 			continue;
    312 		}
    313 
    314 		return entry.resp;
    315 	}
    316 }
    317 
    318 uint32_t
    319 hdaudio_command(struct hdaudio_codec *co, int nid, uint32_t control,
    320     uint32_t param)
    321 {
    322 	uint32_t result;
    323 	struct hdaudio_softc *sc = co->co_host;
    324 	mutex_enter(&sc->sc_corb_mtx);
    325 	result = hdaudio_command_unlocked(co, nid, control, param);
    326 	mutex_exit(&sc->sc_corb_mtx);
    327 	return result;
    328 }
    329 
    330 uint32_t
    331 hdaudio_command_unlocked(struct hdaudio_codec *co, int nid, uint32_t control,
    332     uint32_t param)
    333 {
    334 	struct hdaudio_softc *sc = co->co_host;
    335 	uint32_t result;
    336 
    337 	hda_trace(sc, "cmd  : request %08X %08X (%02X)\n",
    338 	    control, param, nid);
    339 	hdaudio_corb_enqueue(sc, co->co_addr, nid, control, param);
    340 	result = hdaudio_rirb_dequeue(sc, false);
    341 
    342 	/* Clear response interrupt status */
    343 	hda_write1(sc, HDAUDIO_MMIO_RIRBSTS, hda_read1(sc, HDAUDIO_MMIO_RIRBSTS));
    344 
    345 	return result;
    346 }
    347 
    348 static int
    349 hdaudio_corb_setsize(struct hdaudio_softc *sc)
    350 {
    351 	uint8_t corbsize;
    352 	bus_size_t bufsize = 0;
    353 
    354 	/*
    355 	 * The size of the CORB is programmable to 2, 16, or 256 entries
    356 	 * by using the CORBSIZE register. Choose a size based on the
    357 	 * controller capabilities, preferring a larger size when possible.
    358 	 */
    359 	corbsize = hda_read1(sc, HDAUDIO_MMIO_CORBSIZE);
    360 	corbsize &= ~0x3;
    361 	if ((corbsize >> 4) & 0x4) {
    362 		corbsize |= 0x2;
    363 		bufsize = 1024;
    364 	} else if ((corbsize >> 4) & 0x2) {
    365 		corbsize |= 0x1;
    366 		bufsize = 64;
    367 	} else if ((corbsize >> 4) & 0x1) {
    368 		corbsize |= 0x0;
    369 		bufsize = 8;
    370 	} else {
    371 		hda_error(sc, "couldn't configure CORB size\n");
    372 		return ENXIO;
    373 	}
    374 
    375 #if defined(HDAUDIO_DEBUG)
    376 	hda_print(sc, "using %d byte CORB (cap %X)\n",
    377 	    (int)bufsize, corbsize >> 4);
    378 #endif
    379 
    380 	sc->sc_corb.dma_size = bufsize;
    381 	sc->sc_corb.dma_sizereg = corbsize;
    382 
    383 	return 0;
    384 }
    385 
    386 static int
    387 hdaudio_corb_config(struct hdaudio_softc *sc)
    388 {
    389 	uint32_t corbubase, corblbase;
    390 	uint16_t corbrp;
    391 	int retry = HDAUDIO_CORB_TIMEOUT;
    392 
    393 	/* Program command buffer base address and size */
    394 	corblbase = (uint32_t)DMA_DMAADDR(&sc->sc_corb);
    395 	corbubase = (uint32_t)(((uint64_t)DMA_DMAADDR(&sc->sc_corb)) >> 32);
    396 	hda_write4(sc, HDAUDIO_MMIO_CORBLBASE, corblbase);
    397 	hda_write4(sc, HDAUDIO_MMIO_CORBUBASE, corbubase);
    398 	hda_write1(sc, HDAUDIO_MMIO_CORBSIZE, sc->sc_corb.dma_sizereg);
    399 
    400 	/* Clear the read and write pointers */
    401 	hda_write2(sc, HDAUDIO_MMIO_CORBRP, HDAUDIO_CORBRP_RP_RESET);
    402 	hda_write2(sc, HDAUDIO_MMIO_CORBRP, 0);
    403 	do {
    404 		hda_delay(10);
    405 		corbrp = hda_read2(sc, HDAUDIO_MMIO_CORBRP);
    406 	} while (--retry > 0 && (corbrp & HDAUDIO_CORBRP_RP_RESET) != 0);
    407 	if (retry == 0) {
    408 		hda_error(sc, "timeout resetting CORB\n");
    409 		return ETIME;
    410 	}
    411 	hda_write2(sc, HDAUDIO_MMIO_CORBWP, 0);
    412 
    413 	return 0;
    414 }
    415 
    416 static int
    417 hdaudio_corb_stop(struct hdaudio_softc *sc)
    418 {
    419 	uint8_t corbctl;
    420 	int retry = HDAUDIO_CORB_TIMEOUT;
    421 
    422 	/* Stop the CORB if necessary */
    423 	corbctl = hda_read1(sc, HDAUDIO_MMIO_CORBCTL);
    424 	if (corbctl & HDAUDIO_CORBCTL_RUN) {
    425 		corbctl &= ~HDAUDIO_CORBCTL_RUN;
    426 		hda_write1(sc, HDAUDIO_MMIO_CORBCTL, corbctl);
    427 		do {
    428 			hda_delay(10);
    429 			corbctl = hda_read1(sc, HDAUDIO_MMIO_CORBCTL);
    430 		} while (--retry > 0 && (corbctl & HDAUDIO_CORBCTL_RUN) != 0);
    431 		if (retry == 0) {
    432 			hda_error(sc, "timeout stopping CORB\n");
    433 			return ETIME;
    434 		}
    435 	}
    436 
    437 	return 0;
    438 }
    439 
    440 static int
    441 hdaudio_corb_start(struct hdaudio_softc *sc)
    442 {
    443 	uint8_t corbctl;
    444 	int retry = HDAUDIO_CORB_TIMEOUT;
    445 
    446 	/* Start the CORB if necessary */
    447 	corbctl = hda_read1(sc, HDAUDIO_MMIO_CORBCTL);
    448 	if ((corbctl & HDAUDIO_CORBCTL_RUN) == 0) {
    449 		corbctl |= HDAUDIO_CORBCTL_RUN;
    450 		hda_write1(sc, HDAUDIO_MMIO_CORBCTL, corbctl);
    451 		do {
    452 			hda_delay(10);
    453 			corbctl = hda_read1(sc, HDAUDIO_MMIO_CORBCTL);
    454 		} while (--retry > 0 && (corbctl & HDAUDIO_CORBCTL_RUN) == 0);
    455 		if (retry == 0) {
    456 			hda_error(sc, "timeout starting CORB\n");
    457 			return ETIME;
    458 		}
    459 	}
    460 
    461 	return 0;
    462 }
    463 
    464 static int
    465 hdaudio_rirb_stop(struct hdaudio_softc *sc)
    466 {
    467 	uint8_t rirbctl;
    468 	int retry = HDAUDIO_RIRB_TIMEOUT;
    469 
    470 	/* Stop the RIRB if necessary */
    471 	rirbctl = hda_read1(sc, HDAUDIO_MMIO_RIRBCTL);
    472 	if (rirbctl & (HDAUDIO_RIRBCTL_RUN|HDAUDIO_RIRBCTL_ROI_EN)) {
    473 		rirbctl &= ~HDAUDIO_RIRBCTL_RUN;
    474 		rirbctl &= ~HDAUDIO_RIRBCTL_ROI_EN;
    475 		hda_write1(sc, HDAUDIO_MMIO_RIRBCTL, rirbctl);
    476 		do {
    477 			hda_delay(10);
    478 			rirbctl = hda_read1(sc, HDAUDIO_MMIO_RIRBCTL);
    479 		} while (--retry > 0 && (rirbctl & HDAUDIO_RIRBCTL_RUN) != 0);
    480 		if (retry == 0) {
    481 			hda_error(sc, "timeout stopping RIRB\n");
    482 			return ETIME;
    483 		}
    484 	}
    485 
    486 	return 0;
    487 }
    488 
    489 static int
    490 hdaudio_rirb_start(struct hdaudio_softc *sc)
    491 {
    492 	uint8_t rirbctl;
    493 	int retry = HDAUDIO_RIRB_TIMEOUT;
    494 
    495 	/* Set the RIRB interrupt count */
    496 	hda_write2(sc, HDAUDIO_MMIO_RINTCNT, 1);
    497 
    498 	/* Start the RIRB */
    499 	rirbctl = hda_read1(sc, HDAUDIO_MMIO_RIRBCTL);
    500 	rirbctl |= HDAUDIO_RIRBCTL_RUN;
    501 	rirbctl |= HDAUDIO_RIRBCTL_INT_EN;
    502 	hda_write1(sc, HDAUDIO_MMIO_RIRBCTL, rirbctl);
    503 	do {
    504 		hda_delay(10);
    505 		rirbctl = hda_read1(sc, HDAUDIO_MMIO_RIRBCTL);
    506 	} while (--retry > 0 && (rirbctl & HDAUDIO_RIRBCTL_RUN) == 0);
    507 	if (retry == 0) {
    508 		hda_error(sc, "timeout starting RIRB\n");
    509 		return ETIME;
    510 	}
    511 
    512 	return 0;
    513 }
    514 
    515 static int
    516 hdaudio_rirb_setsize(struct hdaudio_softc *sc)
    517 {
    518 	uint8_t rirbsize;
    519 	bus_size_t bufsize = 0;
    520 
    521 	/*
    522 	 * The size of the RIRB is programmable to 2, 16, or 256 entries
    523 	 * by using the RIRBSIZE register. Choose a size based on the
    524 	 * controller capabilities, preferring a larger size when possible.
    525 	 */
    526 	rirbsize = hda_read1(sc, HDAUDIO_MMIO_RIRBSIZE);
    527 	rirbsize &= ~0x3;
    528 	if ((rirbsize >> 4) & 0x4) {
    529 		rirbsize |= 0x2;
    530 		bufsize = 2048;
    531 	} else if ((rirbsize >> 4) & 0x2) {
    532 		rirbsize |= 0x1;
    533 		bufsize = 128;
    534 	} else if ((rirbsize >> 4) & 0x1) {
    535 		rirbsize |= 0x0;
    536 		bufsize = 16;
    537 	} else {
    538 		hda_error(sc, "couldn't configure RIRB size\n");
    539 		return ENXIO;
    540 	}
    541 
    542 #if defined(HDAUDIO_DEBUG)
    543 	hda_print(sc, "using %d byte RIRB (cap %X)\n",
    544 	    (int)bufsize, rirbsize >> 4);
    545 #endif
    546 
    547 	sc->sc_rirb.dma_size = bufsize;
    548 	sc->sc_rirb.dma_sizereg = rirbsize;
    549 
    550 	return 0;
    551 }
    552 
    553 static int
    554 hdaudio_rirb_config(struct hdaudio_softc *sc)
    555 {
    556 	uint32_t rirbubase, rirblbase;
    557 
    558 	/* Program command buffer base address and size */
    559 	rirblbase = (uint32_t)DMA_DMAADDR(&sc->sc_rirb);
    560 	rirbubase = (uint32_t)(((uint64_t)DMA_DMAADDR(&sc->sc_rirb)) >> 32);
    561 	hda_write4(sc, HDAUDIO_MMIO_RIRBLBASE, rirblbase);
    562 	hda_write4(sc, HDAUDIO_MMIO_RIRBUBASE, rirbubase);
    563 	hda_write1(sc, HDAUDIO_MMIO_RIRBSIZE, sc->sc_rirb.dma_sizereg);
    564 
    565 	/* Clear the write pointer */
    566 	hda_write2(sc, HDAUDIO_MMIO_RIRBWP, HDAUDIO_RIRBWP_WP_RESET);
    567 	sc->sc_rirbrp = 0;
    568 
    569 	return 0;
    570 }
    571 
    572 static int
    573 hdaudio_reset(struct hdaudio_softc *sc)
    574 {
    575 	int retry = HDAUDIO_RESET_TIMEOUT;
    576 	uint32_t gctl;
    577 	int err;
    578 
    579 	if ((err = hdaudio_rirb_stop(sc)) != 0) {
    580 		hda_error(sc, "couldn't reset because RIRB is busy\n");
    581 		return err;
    582 	}
    583 	if ((err = hdaudio_corb_stop(sc)) != 0) {
    584 		hda_error(sc, "couldn't reset because CORB is busy\n");
    585 		return err;
    586 	}
    587 
    588 	/* Disable wake events */
    589 	hda_write2(sc, HDAUDIO_MMIO_WAKEEN, 0);
    590 
    591 	/* Disable interrupts */
    592 	hda_write4(sc, HDAUDIO_MMIO_INTCTL, 0);
    593 
    594 	/* Clear state change status register */
    595 	hda_write2(sc, HDAUDIO_MMIO_STATESTS,
    596 	    hda_read2(sc, HDAUDIO_MMIO_STATESTS));
    597 	hda_write1(sc, HDAUDIO_MMIO_RIRBSTS,
    598 	    hda_read1(sc, HDAUDIO_MMIO_RIRBSTS));
    599 
    600 	/* Put the controller into reset state */
    601 	gctl = hda_read4(sc, HDAUDIO_MMIO_GCTL);
    602 	gctl &= ~HDAUDIO_GCTL_CRST;
    603 	hda_write4(sc, HDAUDIO_MMIO_GCTL, gctl);
    604 	do {
    605 		hda_delay(10);
    606 		gctl = hda_read4(sc, HDAUDIO_MMIO_GCTL);
    607 	} while (--retry > 0 && (gctl & HDAUDIO_GCTL_CRST) != 0);
    608 	if (retry == 0) {
    609 		hda_error(sc, "timeout entering reset state\n");
    610 		return ETIME;
    611 	}
    612 
    613 	hda_delay(1000);
    614 
    615 	/* Now the controller is in reset state, so bring it out */
    616 	retry = HDAUDIO_RESET_TIMEOUT;
    617 	hda_write4(sc, HDAUDIO_MMIO_GCTL, gctl | HDAUDIO_GCTL_CRST);
    618 	do {
    619 		hda_delay(10);
    620 		gctl = hda_read4(sc, HDAUDIO_MMIO_GCTL);
    621 	} while (--retry > 0 && (gctl & HDAUDIO_GCTL_CRST) == 0);
    622 	if (retry == 0) {
    623 		hda_error(sc, "timeout leaving reset state\n");
    624 		return ETIME;
    625 	}
    626 
    627 	hda_delay(2000);
    628 
    629 	/* Accept unsolicited responses */
    630 	hda_write4(sc, HDAUDIO_MMIO_GCTL, gctl | HDAUDIO_GCTL_UNSOL_EN);
    631 
    632 	return 0;
    633 }
    634 
    635 static void
    636 hdaudio_intr_enable(struct hdaudio_softc *sc)
    637 {
    638 	hda_write4(sc, HDAUDIO_MMIO_INTSTS,
    639 	    hda_read4(sc, HDAUDIO_MMIO_INTSTS));
    640 	hda_write4(sc, HDAUDIO_MMIO_INTCTL,
    641 	    HDAUDIO_INTCTL_GIE | HDAUDIO_INTCTL_CIE);
    642 }
    643 
    644 static void
    645 hdaudio_intr_disable(struct hdaudio_softc *sc)
    646 {
    647 	hda_write4(sc, HDAUDIO_MMIO_INTCTL, 0);
    648 }
    649 
    650 static int
    651 hdaudio_config_print(void *opaque, const char *pnp)
    652 {
    653 	prop_dictionary_t dict = opaque;
    654 	uint8_t fgtype, nid;
    655 	uint16_t vendor, product;
    656 	const char *type = "unknown";
    657 
    658 	prop_dictionary_get_uint8(dict, "function-group-type", &fgtype);
    659 	prop_dictionary_get_uint8(dict, "node-id", &nid);
    660 	prop_dictionary_get_uint16(dict, "vendor-id", &vendor);
    661 	prop_dictionary_get_uint16(dict, "product-id", &product);
    662 	if (pnp) {
    663 		if (fgtype == HDAUDIO_GROUP_TYPE_AFG)
    664 			type = "hdafg";
    665 		else if (fgtype == HDAUDIO_GROUP_TYPE_VSM_FG)
    666 			type = "hdvsmfg";
    667 
    668 		aprint_normal("%s at %s", type, pnp);
    669 	}
    670 	aprint_debug(" vendor 0x%04X product 0x%04X nid 0x%02X",
    671 	    vendor, product, nid);
    672 
    673 	return UNCONF;
    674 }
    675 
    676 static void
    677 hdaudio_attach_fg(struct hdaudio_function_group *fg, prop_array_t config)
    678 {
    679 	struct hdaudio_codec *co = fg->fg_codec;
    680 	struct hdaudio_softc *sc = co->co_host;
    681 	prop_dictionary_t args = prop_dictionary_create();
    682 	uint64_t fgptr = (vaddr_t)fg;
    683 	int locs[1];
    684 
    685 	prop_dictionary_set_uint8(args, "function-group-type", fg->fg_type);
    686 	prop_dictionary_set_uint64(args, "function-group", fgptr);
    687 	prop_dictionary_set_uint8(args, "node-id", fg->fg_nid);
    688 	prop_dictionary_set_uint16(args, "vendor-id", fg->fg_vendor);
    689 	prop_dictionary_set_uint16(args, "product-id", fg->fg_product);
    690 	if (config)
    691 		prop_dictionary_set(args, "pin-config", config);
    692 
    693 	locs[0] = fg->fg_nid;
    694 
    695 	fg->fg_device = config_found(sc->sc_dev, args, hdaudio_config_print,
    696 	    CFARGS(.submatch = config_stdsubmatch,
    697 		   .locators = locs));
    698 
    699 	prop_object_release(args);
    700 }
    701 
    702 static void
    703 hdaudio_codec_attach(struct hdaudio_codec *co)
    704 {
    705 	struct hdaudio_softc *sc = co->co_host;
    706 	struct hdaudio_function_group *fg;
    707 	uint32_t vid, snc, fgrp;
    708 	int starting_node, num_nodes, nid;
    709 
    710 	if (co->co_valid == false)
    711 		return;
    712 
    713 	vid = hdaudio_command(co, 0, CORB_GET_PARAMETER, COP_VENDOR_ID);
    714 	snc = hdaudio_command(co, 0, CORB_GET_PARAMETER,
    715 	    COP_SUBORDINATE_NODE_COUNT);
    716 
    717 	/* make sure the vendor and product IDs are valid */
    718 	if (vid == 0xffffffff || vid == 0x00000000)
    719 		return;
    720 
    721 #ifdef HDAUDIO_DEBUG
    722 	uint32_t rid = hdaudio_command(co, 0, CORB_GET_PARAMETER,
    723 	    COP_REVISION_ID);
    724 	hda_print(sc, "Codec%02X: %04X:%04X HDA %d.%d rev %d stepping %d\n",
    725 	    co->co_addr, vid >> 16, vid & 0xffff,
    726 	    (rid >> 20) & 0xf, (rid >> 16) & 0xf,
    727 	    (rid >> 8) & 0xff, rid & 0xff);
    728 #endif
    729 	starting_node = (snc >> 16) & 0xff;
    730 	num_nodes = snc & 0xff;
    731 
    732 	/*
    733 	 * If the total number of nodes is 0, there's nothing we can do.
    734 	 * This shouldn't happen, so complain about it.
    735 	 */
    736 	if (num_nodes == 0) {
    737 		hda_error(sc, "Codec%02X: No subordinate nodes found (%08x)\n",
    738 		    co->co_addr, snc);
    739 		return;
    740 	}
    741 
    742 	co->co_nfg = num_nodes;
    743 	co->co_fg = kmem_zalloc(co->co_nfg * sizeof(*co->co_fg), KM_SLEEP);
    744 
    745 	for (nid = starting_node; nid < starting_node + num_nodes; nid++) {
    746 		fg = &co->co_fg[nid - starting_node];
    747 		fg->fg_codec = co;
    748 		fg->fg_nid = nid;
    749 		fg->fg_vendor = vid >> 16;
    750 		fg->fg_product = vid & 0xffff;
    751 
    752 		fgrp = hdaudio_command(co, nid, CORB_GET_PARAMETER,
    753 		    COP_FUNCTION_GROUP_TYPE);
    754 		switch (fgrp & 0xff) {
    755 		case 0x01:	/* Audio Function Group */
    756 			fg->fg_type = HDAUDIO_GROUP_TYPE_AFG;
    757 			break;
    758 		case 0x02:	/* Vendor Specific Modem Function Group */
    759 			fg->fg_type = HDAUDIO_GROUP_TYPE_VSM_FG;
    760 			break;
    761 		default:
    762 			/* Function group type not supported */
    763 			fg->fg_type = HDAUDIO_GROUP_TYPE_UNKNOWN;
    764 			break;
    765 		}
    766 		hdaudio_attach_fg(fg, NULL);
    767 	}
    768 }
    769 
    770 int
    771 hdaudio_stream_tag(struct hdaudio_stream *st)
    772 {
    773 	int ret = 0;
    774 
    775 	switch (st->st_type) {
    776 	case HDAUDIO_STREAM_ISS:
    777 		ret = 1;
    778 		break;
    779 	case HDAUDIO_STREAM_OSS:
    780 		ret = 2;
    781 		break;
    782 	case HDAUDIO_STREAM_BSS:
    783 		ret = 3;
    784 		break;
    785 	}
    786 
    787 	return ret;
    788 }
    789 
    790 int
    791 hdaudio_attach(device_t dev, struct hdaudio_softc *sc)
    792 {
    793 	int err, i;
    794 
    795 	KASSERT(sc->sc_memvalid == true);
    796 
    797 	sc->sc_dev = dev;
    798 	mutex_init(&sc->sc_corb_mtx, MUTEX_DEFAULT, IPL_AUDIO);
    799 	mutex_init(&sc->sc_stream_mtx, MUTEX_DEFAULT, IPL_AUDIO);
    800 
    801 	/*
    802 	 * Put the controller into a known state by entering and leaving
    803 	 * CRST as necessary.
    804 	 */
    805 	if ((err = hdaudio_reset(sc)) != 0)
    806 		goto fail;
    807 
    808 	/*
    809 	 * From the spec:
    810 	 *
    811 	 * Must wait 250us after reading CRST as a 1 before assuming that
    812 	 * codecs have all made status change requests and have been
    813 	 * registered by the controller.
    814 	 *
    815 	 * In reality, we need to wait longer than this.
    816 	 */
    817 	hda_delay(HDAUDIO_CODEC_DELAY);
    818 
    819 	/*
    820 	 * Read device capabilities
    821 	 */
    822 	hdaudio_init(sc);
    823 
    824 	/*
    825 	 * Detect codecs
    826 	 */
    827 	if (hdaudio_codec_probe(sc) == 0) {
    828 		hda_error(sc, "no codecs found\n");
    829 		err = ENODEV;
    830 		goto fail;
    831 	}
    832 
    833 	/*
    834 	 * Ensure that the device is in a known state
    835 	 */
    836 	hda_write2(sc, HDAUDIO_MMIO_STATESTS, HDAUDIO_STATESTS_SDIWAKE);
    837 	hda_write1(sc, HDAUDIO_MMIO_RIRBSTS,
    838 	    HDAUDIO_RIRBSTS_RIRBOIS | HDAUDIO_RIRBSTS_RINTFL);
    839 	hda_write4(sc, HDAUDIO_MMIO_INTSTS,
    840 	    hda_read4(sc, HDAUDIO_MMIO_INTSTS));
    841 	hda_write4(sc, HDAUDIO_MMIO_DPLBASE, 0);
    842 	hda_write4(sc, HDAUDIO_MMIO_DPUBASE, 0);
    843 
    844 	/*
    845 	 * Initialize the CORB. First negotiate a command buffer size,
    846 	 * then allocate and configure it.
    847 	 */
    848 	if ((err = hdaudio_corb_setsize(sc)) != 0)
    849 		goto fail;
    850 	if ((err = hdaudio_dma_alloc(sc, &sc->sc_corb, BUS_DMA_WRITE)) != 0)
    851 		goto fail;
    852 	if ((err = hdaudio_corb_config(sc)) != 0)
    853 		goto fail;
    854 
    855 	/*
    856 	 * Initialize the RIRB.
    857 	 */
    858 	if ((err = hdaudio_rirb_setsize(sc)) != 0)
    859 		goto fail;
    860 	if ((err = hdaudio_dma_alloc(sc, &sc->sc_rirb, BUS_DMA_READ)) != 0)
    861 		goto fail;
    862 	if ((err = hdaudio_rirb_config(sc)) != 0)
    863 		goto fail;
    864 
    865 	/*
    866 	 * Start the CORB and RIRB
    867 	 */
    868 	if ((err = hdaudio_corb_start(sc)) != 0)
    869 		goto fail;
    870 	if ((err = hdaudio_rirb_start(sc)) != 0)
    871 		goto fail;
    872 
    873 	/*
    874 	 * Identify and attach discovered codecs
    875 	 */
    876 	for (i = 0; i < HDAUDIO_MAX_CODECS; i++)
    877 		hdaudio_codec_attach(&sc->sc_codec[i]);
    878 
    879 	/*
    880 	 * Enable interrupts
    881 	 */
    882 	hdaudio_intr_enable(sc);
    883 
    884 fail:
    885 	if (err)
    886 		hda_error(sc, "device driver failed to attach\n");
    887 	return err;
    888 }
    889 
    890 int
    891 hdaudio_detach(struct hdaudio_softc *sc, int flags)
    892 {
    893 	int error;
    894 
    895 	/* Disable interrupts */
    896 	hdaudio_intr_disable(sc);
    897 
    898 	error = config_detach_children(sc->sc_dev, flags);
    899 	if (error != 0) {
    900 		hdaudio_intr_enable(sc);
    901 		return error;
    902 	}
    903 
    904 	mutex_destroy(&sc->sc_corb_mtx);
    905 	mutex_destroy(&sc->sc_stream_mtx);
    906 
    907 	hdaudio_dma_free(sc, &sc->sc_corb);
    908 	hdaudio_dma_free(sc, &sc->sc_rirb);
    909 
    910 	return 0;
    911 }
    912 
    913 bool
    914 hdaudio_resume(struct hdaudio_softc *sc)
    915 {
    916 	if (hdaudio_reset(sc) != 0)
    917 		return false;
    918 
    919 	hda_delay(HDAUDIO_CODEC_DELAY);
    920 
    921 	/*
    922 	 * Ensure that the device is in a known state
    923 	 */
    924 	hda_write2(sc, HDAUDIO_MMIO_STATESTS, HDAUDIO_STATESTS_SDIWAKE);
    925 	hda_write1(sc, HDAUDIO_MMIO_RIRBSTS,
    926 	    HDAUDIO_RIRBSTS_RIRBOIS | HDAUDIO_RIRBSTS_RINTFL);
    927 	hda_write4(sc, HDAUDIO_MMIO_INTSTS,
    928 	    hda_read4(sc, HDAUDIO_MMIO_INTSTS));
    929 	hda_write4(sc, HDAUDIO_MMIO_DPLBASE, 0);
    930 	hda_write4(sc, HDAUDIO_MMIO_DPUBASE, 0);
    931 
    932 	if (hdaudio_corb_config(sc) != 0)
    933 		return false;
    934 	if (hdaudio_rirb_config(sc) != 0)
    935 		return false;
    936 	if (hdaudio_corb_start(sc) != 0)
    937 		return false;
    938 	if (hdaudio_rirb_start(sc) != 0)
    939 		return false;
    940 
    941 	hdaudio_intr_enable(sc);
    942 
    943 	return true;
    944 }
    945 
    946 int
    947 hdaudio_rescan(struct hdaudio_softc *sc, const char *ifattr, const int *locs)
    948 {
    949 	struct hdaudio_codec *co;
    950 	struct hdaudio_function_group *fg;
    951 	unsigned int codec;
    952 
    953 	for (codec = 0; codec < HDAUDIO_MAX_CODECS; codec++) {
    954 		co = &sc->sc_codec[codec];
    955 		fg = co->co_fg;
    956 		if (!co->co_valid || fg == NULL)
    957 			continue;
    958 		if (fg->fg_device)
    959 			continue;
    960 		hdaudio_attach_fg(fg, NULL);
    961 	}
    962 
    963 	return 0;
    964 }
    965 
    966 void
    967 hdaudio_childdet(struct hdaudio_softc *sc, device_t child)
    968 {
    969 	struct hdaudio_codec *co;
    970 	struct hdaudio_function_group *fg;
    971 	unsigned int codec;
    972 
    973 	for (codec = 0; codec < HDAUDIO_MAX_CODECS; codec++) {
    974 		co = &sc->sc_codec[codec];
    975 		fg = co->co_fg;
    976 		if (!co->co_valid || fg == NULL)
    977 			continue;
    978 		if (fg->fg_device == child)
    979 			fg->fg_device = NULL;
    980 	}
    981 }
    982 
    983 int
    984 hdaudio_intr(struct hdaudio_softc *sc)
    985 {
    986 	struct hdaudio_stream *st;
    987 	uint32_t intsts, stream_mask;
    988 	int streamid = 0;
    989 	uint8_t rirbsts;
    990 
    991 	intsts = hda_read4(sc, HDAUDIO_MMIO_INTSTS);
    992 	if (!(intsts & HDAUDIO_INTSTS_GIS))
    993 		return 0;
    994 
    995 	if (intsts & HDAUDIO_INTSTS_CIS) {
    996 		rirbsts = hda_read1(sc, HDAUDIO_MMIO_RIRBSTS);
    997 		if (rirbsts & HDAUDIO_RIRBSTS_RINTFL) {
    998 			mutex_enter(&sc->sc_corb_mtx);
    999 			hdaudio_rirb_dequeue(sc, true);
   1000 			mutex_exit(&sc->sc_corb_mtx);
   1001 		}
   1002 		if (rirbsts & (HDAUDIO_RIRBSTS_RIRBOIS|HDAUDIO_RIRBSTS_RINTFL))
   1003 			hda_write1(sc, HDAUDIO_MMIO_RIRBSTS, rirbsts);
   1004 		hda_write4(sc, HDAUDIO_MMIO_INTSTS, HDAUDIO_INTSTS_CIS);
   1005 	}
   1006 	if (intsts & HDAUDIO_INTSTS_SIS_MASK) {
   1007 		mutex_enter(&sc->sc_stream_mtx);
   1008 		stream_mask = intsts & sc->sc_stream_mask;
   1009 		while (streamid < HDAUDIO_MAX_STREAMS && stream_mask != 0) {
   1010 			st = &sc->sc_stream[streamid++];
   1011 			if ((stream_mask & 1) != 0 && st->st_intr) {
   1012 				st->st_intr(st);
   1013 			}
   1014 			stream_mask >>= 1;
   1015 		}
   1016 		mutex_exit(&sc->sc_stream_mtx);
   1017 		hda_write4(sc, HDAUDIO_MMIO_INTSTS, HDAUDIO_INTSTS_SIS_MASK);
   1018 	}
   1019 
   1020 	return 1;
   1021 }
   1022 
   1023 struct hdaudio_stream *
   1024 hdaudio_stream_establish(struct hdaudio_softc *sc,
   1025     enum hdaudio_stream_type type, int (*intr)(struct hdaudio_stream *),
   1026     void *cookie)
   1027 {
   1028 	struct hdaudio_stream *st;
   1029 	struct hdaudio_dma dma;
   1030 	int i, err;
   1031 
   1032 	dma.dma_size = sizeof(struct hdaudio_bdl_entry) * HDAUDIO_BDL_MAX;
   1033 	dma.dma_sizereg = 0;
   1034 	err = hdaudio_dma_alloc(sc, &dma, BUS_DMA_COHERENT | BUS_DMA_NOCACHE);
   1035 	if (err)
   1036 		return NULL;
   1037 
   1038 	mutex_enter(&sc->sc_stream_mtx);
   1039 	for (i = 0; i < HDAUDIO_MAX_STREAMS; i++) {
   1040 		st = &sc->sc_stream[i];
   1041 		if (st->st_enable == false)
   1042 			break;
   1043 		if (st->st_type != type)
   1044 			continue;
   1045 		if (sc->sc_stream_mask & (1 << i))
   1046 			continue;
   1047 
   1048 		/* Allocate stream */
   1049 		st->st_bdl = dma;
   1050 		st->st_intr = intr;
   1051 		st->st_cookie = cookie;
   1052 		sc->sc_stream_mask |= (1 << i);
   1053 		mutex_exit(&sc->sc_stream_mtx);
   1054 		return st;
   1055 	}
   1056 	mutex_exit(&sc->sc_stream_mtx);
   1057 
   1058 	/* No streams of requested type available */
   1059 	hdaudio_dma_free(sc, &dma);
   1060 	return NULL;
   1061 }
   1062 
   1063 void
   1064 hdaudio_stream_disestablish(struct hdaudio_stream *st)
   1065 {
   1066 	struct hdaudio_softc *sc = st->st_host;
   1067 	struct hdaudio_dma dma;
   1068 
   1069 	KASSERT(sc->sc_stream_mask & (1 << st->st_shift));
   1070 
   1071 	mutex_enter(&sc->sc_stream_mtx);
   1072 	sc->sc_stream_mask &= ~(1 << st->st_shift);
   1073 	st->st_intr = NULL;
   1074 	st->st_cookie = NULL;
   1075 	dma = st->st_bdl;
   1076 	st->st_bdl.dma_valid = false;
   1077 	mutex_exit(&sc->sc_stream_mtx);
   1078 
   1079 	/* Can't bus_dmamem_unmap while holding a mutex.  */
   1080 	hdaudio_dma_free(sc, &dma);
   1081 }
   1082 
   1083 /*
   1084  * Convert most of audio_params_t to stream fmt descriptor; noticeably missing
   1085  * is the # channels bits, as this is encoded differently in codec and
   1086  * stream descriptors.
   1087  *
   1088  * TODO: validate that the stream and selected codecs can handle the fmt
   1089  */
   1090 uint16_t
   1091 hdaudio_stream_param(struct hdaudio_stream *st, const audio_params_t *param)
   1092 {
   1093 	uint16_t fmt = 0;
   1094 
   1095 	switch (param->encoding) {
   1096 	case AUDIO_ENCODING_AC3:
   1097 		fmt |= HDAUDIO_FMT_TYPE_NONPCM;
   1098 		break;
   1099 	default:
   1100 		fmt |= HDAUDIO_FMT_TYPE_PCM;
   1101 		break;
   1102 	}
   1103 
   1104 	switch (param->sample_rate) {
   1105 	case 8000:
   1106 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(1) |
   1107 		    HDAUDIO_FMT_DIV(6);
   1108 		break;
   1109 	case 11025:
   1110 		fmt |= HDAUDIO_FMT_BASE_44 | HDAUDIO_FMT_MULT(1) |
   1111 		    HDAUDIO_FMT_DIV(4);
   1112 		break;
   1113 	case 16000:
   1114 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(1) |
   1115 		    HDAUDIO_FMT_DIV(3);
   1116 		break;
   1117 	case 22050:
   1118 		fmt |= HDAUDIO_FMT_BASE_44 | HDAUDIO_FMT_MULT(1) |
   1119 		    HDAUDIO_FMT_DIV(2);
   1120 		break;
   1121 	case 32000:
   1122 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(2) |
   1123 		    HDAUDIO_FMT_DIV(3);
   1124 		break;
   1125 	case 44100:
   1126 		fmt |= HDAUDIO_FMT_BASE_44 | HDAUDIO_FMT_MULT(1);
   1127 		break;
   1128 	case 48000:
   1129 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(1);
   1130 		break;
   1131 	case 88200:
   1132 		fmt |= HDAUDIO_FMT_BASE_44 | HDAUDIO_FMT_MULT(2);
   1133 		break;
   1134 	case 96000:
   1135 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(2);
   1136 		break;
   1137 	case 176400:
   1138 		fmt |= HDAUDIO_FMT_BASE_44 | HDAUDIO_FMT_MULT(4);
   1139 		break;
   1140 	case 192000:
   1141 		fmt |= HDAUDIO_FMT_BASE_48 | HDAUDIO_FMT_MULT(4);
   1142 		break;
   1143 	default:
   1144 		return 0;
   1145 	}
   1146 
   1147 	if (param->precision == 16 && param->validbits == 8)
   1148 		fmt |= HDAUDIO_FMT_BITS_8_16;
   1149 	else if (param->precision == 16 && param->validbits == 16)
   1150 		fmt |= HDAUDIO_FMT_BITS_16_16;
   1151 	else if (param->precision == 32 && param->validbits == 20)
   1152 		fmt |= HDAUDIO_FMT_BITS_20_32;
   1153 	else if (param->precision == 32 && param->validbits == 24)
   1154 		fmt |= HDAUDIO_FMT_BITS_24_32;
   1155 	else if (param->precision == 32 && param->validbits == 32)
   1156 		fmt |= HDAUDIO_FMT_BITS_32_32;
   1157 	else
   1158 		return 0;
   1159 
   1160 	return fmt;
   1161 }
   1162 
   1163 void
   1164 hdaudio_stream_reset(struct hdaudio_stream *st)
   1165 {
   1166 	struct hdaudio_softc *sc = st->st_host;
   1167 	int snum = st->st_shift;
   1168 	int retry;
   1169 	uint8_t ctl0;
   1170 
   1171 	ctl0 = hda_read1(sc, HDAUDIO_SD_CTL0(snum));
   1172 	ctl0 |= HDAUDIO_CTL_SRST;
   1173 	hda_write1(sc, HDAUDIO_SD_CTL0(snum), ctl0);
   1174 
   1175 	retry = HDAUDIO_RESET_TIMEOUT;
   1176 	do {
   1177 		ctl0 = hda_read1(sc, HDAUDIO_SD_CTL0(snum));
   1178 		if (ctl0 & HDAUDIO_CTL_SRST)
   1179 			break;
   1180 		hda_delay(10);
   1181 	} while (--retry > 0);
   1182 
   1183 	ctl0 &= ~HDAUDIO_CTL_SRST;
   1184 	hda_write1(sc, HDAUDIO_SD_CTL0(snum), ctl0);
   1185 
   1186 	retry = HDAUDIO_RESET_TIMEOUT;
   1187 	do {
   1188 		ctl0 = hda_read1(sc, HDAUDIO_SD_CTL0(snum));
   1189 		if (!(ctl0 & HDAUDIO_CTL_SRST))
   1190 			break;
   1191 		hda_delay(10);
   1192 	} while (--retry > 0);
   1193 	if (retry == 0) {
   1194 		hda_error(sc, "timeout leaving stream reset state\n");
   1195 		return;
   1196 	}
   1197 }
   1198 
   1199 void
   1200 hdaudio_stream_start(struct hdaudio_stream *st, int blksize,
   1201     bus_size_t dmasize, const audio_params_t *params)
   1202 {
   1203 	struct hdaudio_softc *sc = st->st_host;
   1204 	struct hdaudio_bdl_entry *bdl;
   1205 	uint64_t dmaaddr;
   1206 	uint32_t intctl;
   1207 	uint16_t fmt;
   1208 	uint8_t ctl0, ctl2;
   1209 	int cnt, snum = st->st_shift;
   1210 
   1211 	KASSERT(sc->sc_stream_mask & (1 << st->st_shift));
   1212 	KASSERT(st->st_data.dma_valid == true);
   1213 	KASSERT(st->st_bdl.dma_valid == true);
   1214 
   1215 	hdaudio_stream_stop(st);
   1216 	hdaudio_stream_reset(st);
   1217 
   1218 	/*
   1219 	 * Configure buffer descriptor list
   1220 	 */
   1221 	dmaaddr = DMA_DMAADDR(&st->st_data);
   1222 	bdl = DMA_KERNADDR(&st->st_bdl);
   1223 	for (cnt = 0; cnt < HDAUDIO_BDL_MAX; cnt++) {
   1224 		bdl[cnt].address_lo = (uint32_t)dmaaddr;
   1225 		bdl[cnt].address_hi = dmaaddr >> 32;
   1226 		bdl[cnt].length = blksize;
   1227 		bdl[cnt].flags = HDAUDIO_BDL_ENTRY_IOC;
   1228 		dmaaddr += blksize;
   1229 		if (dmaaddr >= DMA_DMAADDR(&st->st_data) + dmasize) {
   1230 			cnt++;
   1231 			break;
   1232 		}
   1233 	}
   1234 
   1235 	/*
   1236 	 * Program buffer descriptor list
   1237 	 */
   1238 	dmaaddr = DMA_DMAADDR(&st->st_bdl);
   1239 	hda_write4(sc, HDAUDIO_SD_BDPL(snum), (uint32_t)dmaaddr);
   1240 	hda_write4(sc, HDAUDIO_SD_BDPU(snum), (uint32_t)(dmaaddr >> 32));
   1241 	hda_write2(sc, HDAUDIO_SD_LVI(snum), (cnt - 1) & 0xff);
   1242 
   1243 	/*
   1244 	 * Program cyclic buffer length
   1245 	 */
   1246 	hda_write4(sc, HDAUDIO_SD_CBL(snum), dmasize);
   1247 
   1248 	/*
   1249 	 * Program stream number (tag). Although controller hardware is
   1250 	 * capable of transmitting any stream number (0-15), by convention
   1251 	 * stream 0 is reserved as unused by software, so that converters
   1252 	 * whose stream numbers have been reset to 0 do not unintentionally
   1253 	 * decode data not intended for them.
   1254 	 */
   1255 	ctl2 = hda_read1(sc, HDAUDIO_SD_CTL2(snum));
   1256 	ctl2 &= ~0xf0;
   1257 	ctl2 |= hdaudio_stream_tag(st) << 4;
   1258 	hda_write1(sc, HDAUDIO_SD_CTL2(snum), ctl2);
   1259 
   1260 	/*
   1261 	 * Program stream format
   1262 	 */
   1263 	fmt = hdaudio_stream_param(st, params) |
   1264 	    HDAUDIO_FMT_CHAN(params->channels);
   1265 	hda_write2(sc, HDAUDIO_SD_FMT(snum), fmt);
   1266 
   1267 	/*
   1268 	 * Switch on interrupts for this stream
   1269 	 */
   1270 	intctl = hda_read4(sc, HDAUDIO_MMIO_INTCTL);
   1271 	intctl |= (1 << st->st_shift);
   1272 	hda_write4(sc, HDAUDIO_MMIO_INTCTL, intctl);
   1273 
   1274 	/*
   1275 	 * Start running the stream
   1276 	 */
   1277 	ctl0 = hda_read1(sc, HDAUDIO_SD_CTL0(snum));
   1278 	ctl0 |= HDAUDIO_CTL_DEIE | HDAUDIO_CTL_FEIE | HDAUDIO_CTL_IOCE |
   1279 	    HDAUDIO_CTL_RUN;
   1280 	hda_write1(sc, HDAUDIO_SD_CTL0(snum), ctl0);
   1281 }
   1282 
   1283 void
   1284 hdaudio_stream_stop(struct hdaudio_stream *st)
   1285 {
   1286 	struct hdaudio_softc *sc = st->st_host;
   1287 	uint32_t intctl;
   1288 	uint8_t ctl0;
   1289 	int snum = st->st_shift;
   1290 
   1291 	/*
   1292 	 * Stop running the stream
   1293 	 */
   1294 	ctl0 = hda_read1(sc, HDAUDIO_SD_CTL0(snum));
   1295 	ctl0 &= ~(HDAUDIO_CTL_DEIE | HDAUDIO_CTL_FEIE | HDAUDIO_CTL_IOCE |
   1296 	    HDAUDIO_CTL_RUN);
   1297 	hda_write1(sc, HDAUDIO_SD_CTL0(snum), ctl0);
   1298 
   1299 	/*
   1300 	 * Switch off interrupts for this stream
   1301 	 */
   1302 	intctl = hda_read4(sc, HDAUDIO_MMIO_INTCTL);
   1303 	intctl &= ~(1 << st->st_shift);
   1304 	hda_write4(sc, HDAUDIO_MMIO_INTCTL, intctl);
   1305 }
   1306 
   1307 /*
   1308  * /dev/hdaudioN interface
   1309  */
   1310 
   1311 static const char *
   1312 hdaudioioctl_fgrp_to_cstr(enum function_group_type type)
   1313 {
   1314 	switch (type) {
   1315 	case HDAUDIO_GROUP_TYPE_AFG:
   1316 		return "afg";
   1317 	case HDAUDIO_GROUP_TYPE_VSM_FG:
   1318 		return "vsmfg";
   1319 	default:
   1320 		return "unknown";
   1321 	}
   1322 }
   1323 
   1324 static struct hdaudio_function_group *
   1325 hdaudioioctl_fgrp_lookup(struct hdaudio_softc *sc, int codecid, int nid)
   1326 {
   1327 	struct hdaudio_codec *co;
   1328 	struct hdaudio_function_group *fg = NULL;
   1329 	int i;
   1330 
   1331 	if (codecid < 0 || codecid >= HDAUDIO_MAX_CODECS)
   1332 		return NULL;
   1333 	co = &sc->sc_codec[codecid];
   1334 	if (co->co_valid == false)
   1335 		return NULL;
   1336 
   1337 	for (i = 0; i < co->co_nfg; i++)
   1338 		if (co->co_fg[i].fg_nid == nid) {
   1339 			fg = &co->co_fg[i];
   1340 			break;
   1341 		}
   1342 
   1343 	return fg;
   1344 }
   1345 
   1346 static int
   1347 hdaudioioctl_fgrp_info(struct hdaudio_softc *sc, prop_dictionary_t request,
   1348     prop_dictionary_t response)
   1349 {
   1350 	struct hdaudio_codec *co;
   1351 	struct hdaudio_function_group *fg;
   1352 	prop_array_t array;
   1353 	prop_dictionary_t dict;
   1354 	int codecid, fgid;
   1355 
   1356 	array = prop_array_create();
   1357 	if (array == NULL)
   1358 		return ENOMEM;
   1359 
   1360 	for (codecid = 0; codecid < HDAUDIO_MAX_CODECS; codecid++) {
   1361 		co = &sc->sc_codec[codecid];
   1362 		if (co->co_valid == false)
   1363 			continue;
   1364 		for (fgid = 0; fgid < co->co_nfg; fgid++) {
   1365 			fg = &co->co_fg[fgid];
   1366 			dict = prop_dictionary_create();
   1367 			if (dict == NULL)
   1368 				return ENOMEM;
   1369 			prop_dictionary_set_string_nocopy(dict,
   1370 			    "type", hdaudioioctl_fgrp_to_cstr(fg->fg_type));
   1371 			prop_dictionary_set_int16(dict, "nid", fg->fg_nid);
   1372 			prop_dictionary_set_int16(dict, "codecid", codecid);
   1373 			prop_dictionary_set_uint16(dict, "vendor-id",
   1374 			    fg->fg_vendor);
   1375 			prop_dictionary_set_uint16(dict, "product-id",
   1376 			    fg->fg_product);
   1377 			prop_dictionary_set_uint32(dict, "subsystem-id",
   1378 			    sc->sc_subsystem);
   1379 			if (fg->fg_device)
   1380 				prop_dictionary_set_string(dict, "device",
   1381 				    device_xname(fg->fg_device));
   1382 			else
   1383 				prop_dictionary_set_string_nocopy(dict,
   1384 				    "device", "<none>");
   1385 			prop_array_add(array, dict);
   1386 		}
   1387 	}
   1388 
   1389 	prop_dictionary_set(response, "function-group-info", array);
   1390 	return 0;
   1391 }
   1392 
   1393 static int
   1394 hdaudioioctl_fgrp_getconfig(struct hdaudio_softc *sc,
   1395     prop_dictionary_t request, prop_dictionary_t response)
   1396 {
   1397 	struct hdaudio_function_group *fg;
   1398 	prop_dictionary_t dict;
   1399 	prop_array_t array;
   1400 	uint32_t nodecnt, wcap, config;
   1401 	int16_t codecid, nid, i;
   1402 	int startnode, endnode;
   1403 
   1404 	if (!prop_dictionary_get_int16(request, "codecid", &codecid) ||
   1405 	    !prop_dictionary_get_int16(request, "nid", &nid))
   1406 		return EINVAL;
   1407 
   1408 	fg = hdaudioioctl_fgrp_lookup(sc, codecid, nid);
   1409 	if (fg == NULL)
   1410 		return ENODEV;
   1411 
   1412 	array = prop_array_create();
   1413 	if (array == NULL)
   1414 		return ENOMEM;
   1415 
   1416 	nodecnt = hdaudio_command(fg->fg_codec, fg->fg_nid,
   1417 	    CORB_GET_PARAMETER, COP_SUBORDINATE_NODE_COUNT);
   1418 	startnode = COP_NODECNT_STARTNODE(nodecnt);
   1419 	endnode = startnode + COP_NODECNT_NUMNODES(nodecnt);
   1420 
   1421 	for (i = startnode; i < endnode; i++) {
   1422 		wcap = hdaudio_command(fg->fg_codec, i,
   1423 		    CORB_GET_PARAMETER, COP_AUDIO_WIDGET_CAPABILITIES);
   1424 		if (COP_AWCAP_TYPE(wcap) != COP_AWCAP_TYPE_PIN_COMPLEX)
   1425 			continue;
   1426 		config = hdaudio_command(fg->fg_codec, i,
   1427 		    CORB_GET_CONFIGURATION_DEFAULT, 0);
   1428 		dict = prop_dictionary_create();
   1429 		if (dict == NULL)
   1430 			return ENOMEM;
   1431 		prop_dictionary_set_int16(dict, "nid", i);
   1432 		prop_dictionary_set_uint32(dict, "config", config);
   1433 		prop_array_add(array, dict);
   1434 	}
   1435 
   1436 	prop_dictionary_set(response, "pin-config", array);
   1437 
   1438 	return 0;
   1439 }
   1440 
   1441 static int
   1442 hdaudioioctl_fgrp_setconfig(struct hdaudio_softc *sc,
   1443     prop_dictionary_t request, prop_dictionary_t response)
   1444 {
   1445 	struct hdaudio_function_group *fg;
   1446 	prop_array_t config;
   1447 	int16_t codecid, nid;
   1448 	int err;
   1449 
   1450 	if (!prop_dictionary_get_int16(request, "codecid", &codecid) ||
   1451 	    !prop_dictionary_get_int16(request, "nid", &nid))
   1452 		return EINVAL;
   1453 
   1454 	fg = hdaudioioctl_fgrp_lookup(sc, codecid, nid);
   1455 	if (fg == NULL)
   1456 		return ENODEV;
   1457 
   1458 	if (fg->fg_device) {
   1459 		err = config_detach(fg->fg_device, 0);
   1460 		if (err)
   1461 			return err;
   1462 		fg->fg_device = NULL;
   1463 	}
   1464 
   1465 	/* "pin-config" may be NULL, this means "use BIOS configuration" */
   1466 	config = prop_dictionary_get(request, "pin-config");
   1467 	if (config && prop_object_type(config) != PROP_TYPE_ARRAY) {
   1468 		prop_object_release(config);
   1469 		return EINVAL;
   1470 	}
   1471 	hdaudio_attach_fg(fg, config);
   1472 	if (config)
   1473 		prop_object_release(config);
   1474 
   1475 	return 0;
   1476 }
   1477 
   1478 static int
   1479 hdaudio_dispatch_fgrp_ioctl(struct hdaudio_softc *sc, u_long cmd,
   1480     prop_dictionary_t request, prop_dictionary_t response)
   1481 {
   1482 	struct hdaudio_function_group *fg;
   1483 	int (*infocb)(void *, prop_dictionary_t, prop_dictionary_t);
   1484 	prop_dictionary_t fgrp_dict;
   1485 	uint64_t info_fn;
   1486 	int16_t codecid, nid;
   1487 	void *fgrp_sc;
   1488 	bool rv;
   1489 	int err;
   1490 
   1491 	if (!prop_dictionary_get_int16(request, "codecid", &codecid) ||
   1492 	    !prop_dictionary_get_int16(request, "nid", &nid))
   1493 		return EINVAL;
   1494 
   1495 	fg = hdaudioioctl_fgrp_lookup(sc, codecid, nid);
   1496 	if (fg == NULL)
   1497 		return ENODEV;
   1498 	if (fg->fg_device == NULL)
   1499 		return ENXIO;
   1500 	fgrp_sc = device_private(fg->fg_device);
   1501 	fgrp_dict = device_properties(fg->fg_device);
   1502 
   1503 	switch (fg->fg_type) {
   1504 	case HDAUDIO_GROUP_TYPE_AFG:
   1505 		switch (cmd) {
   1506 		case HDAUDIO_FGRP_CODEC_INFO:
   1507 			rv = prop_dictionary_get_uint64(fgrp_dict,
   1508 			    "codecinfo-callback", &info_fn);
   1509 			if (!rv)
   1510 				return ENXIO;
   1511 			infocb = (void *)(uintptr_t)info_fn;
   1512 			err = infocb(fgrp_sc, request, response);
   1513 			break;
   1514 		case HDAUDIO_FGRP_WIDGET_INFO:
   1515 			rv = prop_dictionary_get_uint64(fgrp_dict,
   1516 			    "widgetinfo-callback", &info_fn);
   1517 			if (!rv)
   1518 				return ENXIO;
   1519 			infocb = (void *)(uintptr_t)info_fn;
   1520 			err = infocb(fgrp_sc, request, response);
   1521 			break;
   1522 		default:
   1523 			err = EINVAL;
   1524 			break;
   1525 		}
   1526 		break;
   1527 
   1528 	default:
   1529 		err = EINVAL;
   1530 		break;
   1531 	}
   1532 	return err;
   1533 }
   1534 
   1535 int
   1536 hdaudioopen(dev_t dev, int flag, int mode, struct lwp *l)
   1537 {
   1538 	device_t self;
   1539 
   1540 	self = device_lookup(&hdaudio_cd, HDAUDIOUNIT(dev));
   1541 	if (self == NULL)
   1542 		return ENXIO;
   1543 
   1544 	return 0;
   1545 }
   1546 
   1547 int
   1548 hdaudioclose(dev_t dev, int flag, int mode, struct lwp *l)
   1549 {
   1550 	return 0;
   1551 }
   1552 
   1553 int
   1554 hdaudioioctl(dev_t dev, u_long cmd, void *addr, int flag, struct lwp *l)
   1555 {
   1556 	struct hdaudio_softc *sc;
   1557 	struct plistref *pref = addr;
   1558 	prop_dictionary_t request, response;
   1559 	int err;
   1560 
   1561 	sc = device_lookup_private(&hdaudio_cd, HDAUDIOUNIT(dev));
   1562 	if (sc == NULL)
   1563 		return ENXIO;
   1564 
   1565 	response = prop_dictionary_create();
   1566 	if (response == NULL)
   1567 		return ENOMEM;
   1568 
   1569 	err = prop_dictionary_copyin_ioctl(pref, cmd, &request);
   1570 	if (err) {
   1571 		prop_object_release(response);
   1572 		return err;
   1573 	}
   1574 
   1575 	switch (cmd) {
   1576 	case HDAUDIO_FGRP_INFO:
   1577 		if (!(flag & FREAD)) {
   1578 			err = EACCES;
   1579 			break;
   1580 		}
   1581 		err = hdaudioioctl_fgrp_info(sc, request, response);
   1582 		break;
   1583 	case HDAUDIO_FGRP_GETCONFIG:
   1584 		if (!(flag & FREAD)) {
   1585 			err = EACCES;
   1586 			break;
   1587 		}
   1588 		err = hdaudioioctl_fgrp_getconfig(sc, request, response);
   1589 		break;
   1590 	case HDAUDIO_FGRP_SETCONFIG:
   1591 		if (!(flag & FWRITE)) {
   1592 			err = EACCES;
   1593 			break;
   1594 		}
   1595 		err = hdaudioioctl_fgrp_setconfig(sc, request, response);
   1596 		break;
   1597 	case HDAUDIO_FGRP_CODEC_INFO:
   1598 	case HDAUDIO_FGRP_WIDGET_INFO:
   1599 		if (!(flag & FREAD)) {
   1600 			err = EACCES;
   1601 			break;
   1602 		}
   1603 		err = hdaudio_dispatch_fgrp_ioctl(sc, cmd, request, response);
   1604 		break;
   1605 	default:
   1606 		err = EINVAL;
   1607 		break;
   1608 	}
   1609 
   1610 	if (!err)
   1611 		err = prop_dictionary_copyout_ioctl(pref, cmd, response);
   1612 
   1613 	if (response)
   1614 		prop_object_release(response);
   1615 	prop_object_release(request);
   1616 	return err;
   1617 }
   1618 
   1619 MODULE(MODULE_CLASS_DRIVER, hdaudio, "audio");
   1620 #ifdef _MODULE
   1621 static const struct cfiattrdata hdaudiobuscf_iattrdata = {
   1622         "hdaudiobus", 1, {
   1623                 { "nid", "-1", -1 },
   1624         }
   1625 };
   1626 static const struct cfiattrdata * const hdaudio_attrs[] = {
   1627 	&hdaudiobuscf_iattrdata, NULL
   1628 };
   1629 CFDRIVER_DECL(hdaudio, DV_AUDIODEV, hdaudio_attrs);
   1630 #endif
   1631 
   1632 static int
   1633 hdaudio_modcmd(modcmd_t cmd, void *opaque)
   1634 {
   1635 	int error = 0;
   1636 #ifdef _MODULE
   1637 	int bmaj = -1, cmaj = -1;
   1638 #endif
   1639 
   1640 	switch (cmd) {
   1641 	case MODULE_CMD_INIT:
   1642 #ifdef _MODULE
   1643 		error = devsw_attach("hdaudio", NULL, &bmaj,
   1644 		    &hdaudio_cdevsw, &cmaj);
   1645 		if (error)
   1646 			break;
   1647 		error = config_cfdriver_attach(&hdaudio_cd);
   1648 		if (error)
   1649 			devsw_detach(NULL, &hdaudio_cdevsw);
   1650 #endif
   1651 		break;
   1652 	case MODULE_CMD_FINI:
   1653 #ifdef _MODULE
   1654 		error = config_cfdriver_detach(&hdaudio_cd);
   1655 		if (error)
   1656 			break;
   1657 		devsw_detach(NULL, &hdaudio_cdevsw);
   1658 #endif
   1659 		break;
   1660 	default:
   1661 		error = ENOTTY;
   1662 		break;
   1663 	}
   1664 	return error;
   1665 }
   1666 
   1667 DEV_VERBOSE_DEFINE(hdaudio);
   1668