/*
 *               Copyright (C) 2006, BroadOn Communications Corp.
 *
 *  These coded instructions, statements, and computer programs contain
 *  unpublished  proprietary information of BroadOn Communications Corp.,
 *  and  are protected by Federal copyright law. They may not be disclosed
 *  to  third  parties or copied or duplicated in any form, in whole or in
 *  part, without the prior written consent of BroadOn Communications Corp.
 *
 */

/* TO DO --
 * xxx 1. use timer to determine when PLL has locked. done
 * xxx 2. what control to give over mic mute/unmute/boost? none.
 * 3. allow under/overflow to be cleared/ingored? how?
 * xxx 4. support for headphone detect gpio
 * 5. remove AUD_SET_EXT_CODEC ioctl
 */

#include <sc/sc.h>
#include <sc/ios.h>
#include <sc/priority.h>
#include <ioslibc.h>
#include <sc/aud.h>
#include <sc/wa.h>

#define STACK_SIZE 2048
const u8 _initStack[STACK_SIZE];
const u32 _initStackSize = sizeof(_initStack);
const u32 _initPriority = IOS_PRIORITY_AUDIO;

/* device state */
#define AUD_STATE_CLOSED 1  /* device is closed */
#define AUD_STATE_OPEN   2  /* device has been opened, but not configured */
#define AUD_STATE_CONFIG 3  /* device has been configured, ready for reads/writes */

/* internal device info */
typedef struct {
    u8 state;       /* device state, see AUD_STATE_* */
    u32 volume;     /* current volume */
    u8 dacMuted;    /* 1 if DAC is currently muted, else 0 */
    u8 sidetone;    /* 1 if microphone->headphone sidetone is enabled, else 0 */
    u8 flags;       /* flags passed with open command */
    u8 userConfig;  /* audio configuration, see AUD_CONFIG_* */
    u8 config;      /* simplified config, uses lowest allowable MCLK freq */
    u8 firstRead;   /* no reads have been performed since open */
    u8 firstWrite;  /* no writes have been performed since open */
} AudContext;

#define AUD_NUM_DEV 1
AudContext audContext[AUD_NUM_DEV];

/* read/write queues */
#define AUD_MAX_READS 2
#define AUD_MAX_WRITES 2

static u32 __nAudReads = 0;
static struct { IOSResourceRequest *req; u32 size, sizeIdx; } __audReadQ[AUD_MAX_READS];
static u32 __audReadQHead = 0;

static u32 __nAudWrites = 0;
static struct { IOSResourceRequest *req; u32 size, sizeIdx; } __audWriteQ[AUD_MAX_WRITES];
static u32 __audWriteQHead = 0;

/* XXX following def's should be in stdio.h, fcntl.h, or similar */
#define O_ACCMODE 0x3
#define O_RDONLY  0x0
#define O_WRONLY  0x1
#define O_RDWR    0x2

#define OPEN_FOR_READ(f)   (((f)&O_ACCMODE) == O_RDONLY || ((f)&O_ACCMODE) == O_RDWR)
#define OPEN_FOR_WRITE(f)  (((f)&O_ACCMODE) == O_WRONLY || ((f)&O_ACCMODE) == O_RDWR)

/*
 * NC audio hardware definitions
 */

#define ADC_CLEAR  (AUD_ADC_CTRL_WE | AUD_ADC_CTRL_OVER | \
		    AUD_ADC_CTRL_MVIOL | AUD_ADC_CTRL_INTR)
#define ADC_START  (AUD_ADC_CTRL_ENA | AUD_ADC_CTRL_MASK | \
		    AUD_ADC_CTRL_WE)

#define DAC_CLEAR  (AUD_DAC_CTRL_WE | AUD_DAC_CTRL_UNDER | \
		    AUD_DAC_CTRL_MVIOL | AUD_DAC_CTRL_INTR)
#define DAC_START  (AUD_DAC_CTRL_ENA | AUD_DAC_CTRL_MASK | \
		    AUD_DAC_CTRL_WE)

#define PLL172    (43<<AUD_PLL_CTL_F_SHIFT) | (3<<AUD_PLL_CTL_R_SHIFT) | \
                   (2<<AUD_PLL_CTL_OD_SHIFT)
#define PLL158    (79<<AUD_PLL_CTL_F_SHIFT) | (6<<AUD_PLL_CTL_R_SHIFT) | \
                   (2<<AUD_PLL_CTL_OD_SHIFT)

/* run the DAC MCLK as slow as possible since it's not used in common clock mode */
#define MCLK_DIV_DACMAX (63<<AUD_MCLK_DIV_DAC_DIVLO_SHIFT) |    \
                        (63<<AUD_MCLK_DIV_DAC_DIVHI_SHIFT)
#define MCLK_DIV_ADC14  (6<<AUD_MCLK_DIV_ADC_DIVLO_SHIFT) | \
                        (6<<AUD_MCLK_DIV_ADC_DIVHI_SHIFT)
#define MCLK_DIV_DAC14  (6<<AUD_MCLK_DIV_DAC_DIVLO_SHIFT) | \
                        (6<<AUD_MCLK_DIV_DAC_DIVHI_SHIFT)

#define MCLK_DIV14   MCLK_DIV_ADC14 | MCLK_DIV_DAC14  /* XXX MAX */

#define BCLK_DIV8  (3<<AUD_DAC_CFG_BCLK_DIV_SHIFT)
#define BCLK_DIV12 (5<<AUD_DAC_CFG_BCLK_DIV_SHIFT)
#define BCLK_DIV44 (21<<AUD_DAC_CFG_BCLK_DIV_SHIFT)
#define BCLK_DIV48 (23<<AUD_DAC_CFG_BCLK_DIV_SHIFT)

#define LR_DIV32   (15<<AUD_DAC_CFG_LR_DIV_SHIFT)
#define LR_DIV192  (95<<AUD_DAC_CFG_LR_DIV_SHIFT)
#define LR_DIV176  (87<<AUD_DAC_CFG_LR_DIV_SHIFT)

/*
 * Wolfson WM8731L definitions
 */

#define DEEMP48   (3<<WM_DPATH_DEEMP_SHIFT)
#define DEEMP44   (2<<WM_DPATH_DEEMP_SHIFT)
#define DEEMP32   (1<<WM_DPATH_DEEMP_SHIFT)
#define DEEMPNONE (0<<WM_DPATH_DEEMP_SHIFT)

#define CODEC_POWER_OFF  (WM_PWRDOWN_PWROFF | WM_PWRDOWN_CLKOUT |       \
                          WM_PWRDOWN_OSC | WM_PWRDOWN_OUT |             \
                          WM_PWRDOWN_DAC | WM_PWRDOWN_ADC |             \
                          WM_PWRDOWN_MIC | WM_PWRDOWN_LINEIN)

/*
 * NC audio hardware configurations
 */

struct 
{
    u32 pll_ctl;
    u32 mclk_div;
    u32 adc_cfg;
    u32 dac_cfg;
}
    __audConfig[] = {
        {PLL172, MCLK_DIV14, BCLK_DIV8  | LR_DIV32 , BCLK_DIV8  | LR_DIV32 }, /* AUD_CONFIG_ADC_48_DAC_48 */
        {PLL172, MCLK_DIV14, BCLK_DIV8  | LR_DIV32 , BCLK_DIV8  | LR_DIV192}, /* AUD_CONFIG_ADC_48_DAC_8 */
        {PLL172, MCLK_DIV14, BCLK_DIV8  | LR_DIV192, BCLK_DIV8  | LR_DIV32 }, /* AUD_CONFIG_ADC_8_DAC_48 */
        {PLL172, MCLK_DIV14, BCLK_DIV48 | LR_DIV32 , BCLK_DIV48 | LR_DIV32 }, /* AUD_CONFIG_ADC_8_DAC_8 */
        {PLL172, MCLK_DIV14, BCLK_DIV12 | LR_DIV32 , BCLK_DIV12 | LR_DIV32 }, /* AUD_CONFIG_ADC_32_DAC_32 */
        {PLL158, MCLK_DIV14, BCLK_DIV8  | LR_DIV32 , BCLK_DIV8  | LR_DIV32 }, /* AUD_CONFIG_ADC_44P1_DAC_44P1 */
        {PLL158, MCLK_DIV14, BCLK_DIV8  | LR_DIV32 , BCLK_DIV8  | LR_DIV176}, /* AUD_CONFIG_ADC_44P1_DAC_8P018 */
        {PLL158, MCLK_DIV14, BCLK_DIV8  | LR_DIV176, BCLK_DIV8  | LR_DIV32 }, /* AUD_CONFIG_ADC_8P018_DAC_44P1 */
        {PLL158, MCLK_DIV14, BCLK_DIV44 | LR_DIV32 , BCLK_DIV44 | LR_DIV32 }  /* AUD_CONFIG_ADC_8P018_DAC_8P018 */
    };

#define AUD_CONFIG_MAX sizeof(__audConfig)/sizeof(__audConfig[0])

/*
 * Wolfson WM8731L configurations
 */

struct 
{
    u8 deemp;
    u8 sr;
}
    __codecConfig[] = {
        {DEEMP48, 0<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_48_DAC_48 */
        {DEEMP48, 1<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_48_DAC_8 */
        {DEEMP48, 2<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_8_DAC_48 */
        {DEEMP48, 3<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_8_DAC_8 */
        {DEEMP32, 6<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_32_DAC_32 */
        {DEEMP44, 8<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_44P1_DAC_44P1 */
        {DEEMP44, 9<<WM_SCTL_SR_SHIFT},  /* AUD_CONFIG_ADC_44P1_DAC_8P018 */
        {DEEMP44, 10<<WM_SCTL_SR_SHIFT}, /* AUD_CONFIG_ADC_8P018_DAC_44P1 */
        {DEEMP44, 11<<WM_SCTL_SR_SHIFT}  /* AUD_CONFIG_ADC_8P018_DAC_8P018 */
    };

/*
 * debugging macros
 */

/* #define AUD_DEBUG */

#ifdef AUD_DEBUG
#define AUD_LOG(...) printf("AUD: " __VA_ARGS__)
#define AUD_ERROR(msg) printf("AUD: Error: %s failed\n", msg)
#define WAWrite(a,d)  printf("WAWrite: a=0x%02x, d=0x%03x\n",a,d);    \
    WAWrite(a,d) 
#else
#define AUD_LOG(...)
#define AUD_ERROR(msg) /* printf("AUD: Error: %s failed\n", msg) */
#endif

/*
 * audSetDACMute -- mute the DAC output of Wolfson WM8731L chip
 */
static void
audSetDACMute(AudContext *ac, u32 mute)
{
    if ( OPEN_FOR_WRITE(ac->flags) ) {
        u32 dpath = __codecConfig[ac->config].deemp;
        if ( mute )
            dpath |= WM_DPATH_DACMUTE;
        
        WAWrite(WM_DPATH_REG, dpath);
        
        ac->dacMuted = mute;
    }
}


/*
 * audSetHPVolume -- set headphone volume of Wolfson WM8731L chip
 *
 * volume adjustments generate an audible pop if the change is
 * very large; to keep the change small, linearly ramp between
 * the old and new volume settings with small step size; a step
 * size of 3 (=3dB) seems to work ok
 */
#define AUD_VOLUME_STEP_SIZE 3
static void
audSetHPVolume(AudContext *ac, u32 v)
{
    int vStart;  /* start volume */
    int vEnd;    /* target volume */
    u32 lphone;  /* Wolfson Left Headphone Out register */
    int i;

    /* shortcut if no volume change */
    if ( ac->volume != v ) {
    
        /* if volume is mute, then ramp down to/up from AUD_VOLUME_MIN 
         * before actually muting
         */
        vStart = ac->volume == AUD_VOLUME_MUTE ? AUD_VOLUME_MIN : ac->volume;
        vEnd = v == AUD_VOLUME_MUTE ? AUD_VOLUME_MIN : v;
        
        /* ramp from start volume to target volume */
        if ( vStart <= vEnd ) {
            /* ramp volume up */
            for (i=vStart+AUD_VOLUME_STEP_SIZE; i<vEnd; i+=AUD_VOLUME_STEP_SIZE) {
                lphone = ((i << WM_LPHONE_VOL_SHIFT) & WM_LPHONE_VOL_MASK) |
                    WM_LPHONE_BOTH | WM_LPHONE_LZCEN;
                WAWrite(WM_LPHONE_REG, lphone);
            }
        } else {
            /* ramp volume down */
            for (i=vStart-AUD_VOLUME_STEP_SIZE; i>vEnd; i-=AUD_VOLUME_STEP_SIZE) {
                lphone = ((i << WM_LPHONE_VOL_SHIFT) & WM_LPHONE_VOL_MASK) |
                    WM_LPHONE_BOTH | WM_LPHONE_LZCEN;
                WAWrite(WM_LPHONE_REG, lphone);
            }
        }
        
        /* finally, set the target volume */
        lphone = ((v << WM_LPHONE_VOL_SHIFT) & WM_LPHONE_VOL_MASK) |
            WM_LPHONE_BOTH | WM_LPHONE_LZCEN;
        WAWrite(WM_LPHONE_REG, lphone);
        
        /* keep track of current volume */
        ac->volume = v;
    }
}

/*
 * audVolume -- set the DAC mute and/or headphone volume
 *              of Wolfson WM8731L chip to achieve the
 *              requested volume
 *
 * if audio device is only open for playback (DAC), then
 * handle muting by simply soft-muting the DAC; if, however,
 * audio is open for input and the mic sidetone is enabled
 * then muting requires actually ramping down the headphone
 * volume.  This complication just speeds up muting and
 * unmuting for the playback-only mode.
 */
static void
audVolume(AudContext *ac, u32 v)
{
    int rs = OPEN_FOR_READ(ac->flags) && ac->sidetone;
    int w = OPEN_FOR_WRITE(ac->flags);
    
    if ( v == AUD_VOLUME_MUTE ) {
        if ( rs )
            audSetHPVolume(ac, v);
        if ( w )
            audSetDACMute(ac, 1);
    } else {
        if ( w || rs )
            audSetHPVolume(ac, v);
        if ( w && ac->dacMuted )
            audSetDACMute(ac, 0);
    }
}

/*
 * audInit -- initialized NC audio hardware and Wolfson WM8731L hardware
 */
static IOSError
audInit(AudContext *ac)
{
    u32 apath, pwrdown;
    int r = OPEN_FOR_READ(ac->flags);
    int w = OPEN_FOR_WRITE(ac->flags);

    IOSError rv = IOS_ERROR_FAIL_INTERNAL, lrv;
    
    IOS_SetPower(IOS_DEVICE_AUDIO, 1);

    /* create message queue & timer, used to ensure PLL has time to lock */
    IOSMessageQueueId mq;
    IOSMessage msgArray[1];
    IOSMessage msg;
    IOSTimerId t1;
    
    if ((mq = IOS_CreateMessageQueue(msgArray, sizeof(msgArray)/sizeof(msgArray[0]))) < 0) {
        AUD_ERROR("IOS_CreateMessageQueue for timer");
        AUD_LOG("Error = %d", mq);
        goto out;
    }

    /* PLL initialization */
    IO_WRITE(AUD_PLL_CTL_REG, __audConfig[ac->config].pll_ctl | AUD_PLL_CTL_MRST);

    /* PLL takes 500usec to lock;
     * timer resolution is 200 system clock ticks;
     * max system clock frequency is 103.2MHz;
     * num ticks = 500e-6/(200/103.2e6) = 258;
     */
#define AUD_PLL_LOCK_TICKS 258  /* =500usec in hw timer ticks */
#define AUD_PLL_LOCK_MSG   0xbabecafe  /* dummy argument */
    if ( (t1 = IOS_CreateTimer(AUD_PLL_LOCK_TICKS, 0, mq, AUD_PLL_LOCK_MSG)) < 0 ) {
        AUD_ERROR("IOS_CreateTimer");
        AUD_LOG("Error = %d", t1);
        IOS_DestroyMessageQueue(mq);
        goto out;
    }
    
    if ( (lrv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK ) {
        AUD_ERROR("IOS_ReceiveMessage for timer");
        AUD_LOG("Error = %d", lrv);
        IOS_DestroyMessageQueue(mq);
        IOS_DestroyTimer(t1);
        goto out;
    }
    
    if ( (lrv = IOS_DestroyMessageQueue(mq)) != IOS_ERROR_OK ) {
        AUD_ERROR("IOS_DestroyMessageQueue for timer");
        AUD_LOG("Error = %d", lrv);
        IOS_DestroyTimer(t1);
        goto out;
    }
        
    if ( (lrv = IOS_DestroyTimer(t1)) != IOS_ERROR_OK ) {
        AUD_ERROR("IOS_ReceiveMessage for timer");
        AUD_LOG("Error = %d", lrv);
        goto out;
    }

    /* XXX better way? */

    IO_WRITE(AUD_MCLK_DIV_REG, __audConfig[ac->config].mclk_div);
    IO_WRITE(AUD_PLL_CTL_REG, __audConfig[ac->config].pll_ctl);

    
    /* ADC/DAC initialization */

    /* reset ADC/DAC -- both required since we're in common clock mode */
    IO_WRITE(AUD_ADC_CTRL_REG, ADC_CLEAR);
    IO_WRITE(AUD_ADC_CTRL_REG, ADC_CLEAR);
    IO_WRITE(AUD_DAC_CTRL_REG, DAC_CLEAR); /* need 2 since sometimes underflow will be set if DAC is still running. */
    IO_WRITE(AUD_DAC_CTRL_REG, DAC_CLEAR);

    IO_WRITE(AUD_ADC_CFG_REG, __audConfig[ac->config].adc_cfg);
    IO_WRITE(AUD_DAC_CFG_REG, __audConfig[ac->config].dac_cfg | AUD_DAC_CFG_MCLK_COM);

    /* codec initialization */
    WAInit();
    WAWrite(WM_RESET_REG, WM_RESET_RESET);
    
    /* Power up -- leave WM_PWRDOWN_OUT asserted until the very end to avoid pops */
    pwrdown = WM_PWRDOWN_CLKOUT | WM_PWRDOWN_OSC | WM_PWRDOWN_OUT | WM_PWRDOWN_LINEIN;
    if ( !r )
        pwrdown |= WM_PWRDOWN_ADC | WM_PWRDOWN_MIC;
    WAWrite(WM_PWRDOWN_REG, pwrdown);

    /* Enable microphone side-tone, microphone input to ADC */
    apath = 0;
    if ( r )
        apath |= WM_APATH_MICBOOST | WM_APATH_MICMUTE | WM_APATH_INSEL;
    if ( r && ac->sidetone )
        apath |= WM_APATH_SIDETONE | (0<<WM_APATH_SIDEATT_SHIFT);
    if ( w ) 
        apath |= WM_APATH_DACSEL;
    WAWrite(WM_APATH_REG, apath);
       
    /* set DAC soft mute, deemphasis */
    audSetDACMute(ac, 1);
    
    /* configure Digital Audio Interface Format */
    WAWrite(WM_DAFMT_REG, WM_DAFMT_LEFTMSB | WM_DAFMT_IWL_16 /* | WM_DAFMT_LRSWAP */);

    /* configure Sampling Control */
    WAWrite(WM_SCTL_REG, __codecConfig[ac->config].sr);

    /* activate ADC/DAC */
    WAWrite(WM_ACTL_REG, WM_ACTL_ACTIVE);

    /* turn on output drivers, if needed */
    if ( w || ( r && ac->sidetone ) ) {
        pwrdown &= ~WM_PWRDOWN_OUT;
        WAWrite(WM_PWRDOWN_REG, pwrdown);
    }

    /* unmute mic */
    if ( r ) {
        apath &= ~WM_APATH_MICMUTE;
        WAWrite(WM_APATH_REG, apath);
    }

    /* set volume, muting/unmuting DAC as required */
    int v = ac->volume;
    ac->volume = AUD_VOLUME_DEFAULT; /* ramp volume from default to target */
    audVolume(ac, v);
    
    rv = IOS_ERROR_OK;
out:
    return rv;
}

/*
 * audShutdown -- shut down NC audio hardware and Wolfson WM8731 hardware
 */
static void
audShutdown()
{
    /* simply reset the codec as a shortcut to muting all inputs/outputs */
    WAWrite(WM_RESET_REG, WM_RESET_RESET);
    /* then powerdown all subunits within the codec to save power */
    WAWrite(WM_PWRDOWN_REG, CODEC_POWER_OFF);

    /* reset the ADC/DAC */
    IO_WRITE(AUD_ADC_CTRL_REG, ADC_CLEAR);
    IO_WRITE(AUD_DAC_CTRL_REG, DAC_CLEAR);

    /* put the MCLK dividers into reset and powerdown the PLL */
    u32 v = IO_READ(AUD_PLL_CTL_REG);
    IO_WRITE(AUD_PLL_CTL_REG, v | AUD_PLL_CTL_MRST);
    IO_WRITE(AUD_PLL_CTL_REG, v | AUD_PLL_CTL_MRST | AUD_PLL_CTL_PD);
    
    /* powerdown the audio module */
    IOS_SetPower(IOS_DEVICE_AUDIO, 0);

}

/* audConvertSize -- convert buffer size in bytes to the corresponding
 * sizeIdx value used in the SIZE field of the AUD_DAC_PTR/AUD_ADC_PTR
 * registers.  size must be 32 or greater.
 *
 * size, bytes      sizeIdx
 * -----------      -------
 * 32 - 63          0
 * 64 - 127         1
 * 128 - 255        2
 * 256 - 511        4
 * 512 - 1023       4
 * 1024 - 2047      5
 * 2048 - 4095      6
 * >= 4096          7
 */
static int
audConvertSize(int size) 
{
    int ret = 0;

    size = size >> 6;
  
    while (size > 0) {
	ret++;
	size = size >> 1;
    }

    if (ret>7)
        ret = 7;
    
    return ret;
}

/*
 * audConvertSizeIdx -- convert sizeIdx used in the SIZE field of
 * AUD_DAC_PTR/AUD_ADC_PTR registers to the corresponding byte size
 * value.
 *
 * sizeIdx        size, bytes
 * -------        -----------
 * 0              32
 * 1              64
 * 2              128
 * 3              256
 * 4              512
 * 5              1024
 * 6              2048
 * 7              4096
 */
static int audConvertSizeIdx(int sizeIdx) 
{
    return 1<<(5+sizeIdx);
}

/*
 * audWriteFifo -- wite pointer and size into NC hardware fifo register
 */
static void
audWriteFifo(u32 reg, u32 sizeIdx, u32 buffer)
{
    u32 r = (sizeIdx << AUD_ADC_PTR_SIZE_SHIFT) | CPU_TO_BUS_ADDR(buffer); 
    AUD_LOG("audWriteFifo: reg 0x%08x, r 0x%08x\n", reg, r);
    IO_WRITE(reg, r);
}

/*
 * audEventADC handler
 */
static void
audEventADC()
{
    AUD_LOG("in audEventADC:\n");

    /* read status register */
    u32 status = IO_READ(AUD_ADC_CTRL_REG);

    if ( __nAudReads <= 0 ) {
        AUD_ERROR("ADC: dropping unexpected event");
    } else {
        /* dequeue completed read */
        IOSError rv = (IOSError) __audReadQ[__audReadQHead].size;
        IOSResourceRequest *req = __audReadQ[__audReadQHead].req;
        __audReadQHead = (__audReadQHead + 1) % AUD_MAX_READS;
        __nAudReads--;
        /* push next read buffer pointer onto hardware fifo */
        if ( __nAudReads >= 2 ) {  /* hw read fifo depth is 2 */
            int next = (__audReadQHead + 1) % AUD_MAX_READS;
            audWriteFifo(AUD_ADC_PTR_REG,
                         __audReadQ[next].sizeIdx,
                         (u32)__audReadQ[next].req->args.read.outPtr);
        }
        /* check for overflow */
        if ( status & AUD_ADC_CTRL_OVER ) {
/*            AUD_ERROR("ADC: OVER"); */
            rv = IOS_ERROR_NOTREADY;
            IO_WRITE(AUD_ADC_CTRL_REG, AUD_ADC_CTRL_OVER);
        }
        /* check for memory access violation */
        if ( status & AUD_ADC_CTRL_MVIOL ) {
            rv = IOS_ERROR_ACCESS;
            IO_WRITE(AUD_ADC_CTRL_REG, AUD_ADC_CTRL_MVIOL);
        }
        /* return status of completed read */
        AUD_LOG("  IOS_READ %08x Returning = %d\n", (IOSMessage)req, rv);
        IOS_ResourceReply(req, rv);
    }
        
}

/*
 * audEventDAC handler
 */
static void
audEventDAC()
{
    AUD_LOG("in audEventDAC:\n");
    
    /* read status register */
    u32 status = IO_READ(AUD_DAC_CTRL_REG);

    if ( __nAudWrites <= 0 ) {
        AUD_ERROR("DAC: dropping unexpected event");
    } else {
        /* dequeue completed write */
        IOSError rv = (IOSError) __audWriteQ[__audWriteQHead].size;
        IOSResourceRequest *req = __audWriteQ[__audWriteQHead].req;
        __audWriteQHead = (__audWriteQHead + 1) % AUD_MAX_WRITES;
        __nAudWrites--;
        /* push next write buffer pointer onto hardware fifo */
        if ( __nAudWrites >= 2 ) {  /* hw write fifo depth is 2 */
            int next = (__audWriteQHead + 1) % AUD_MAX_WRITES;
            audWriteFifo(AUD_DAC_PTR_REG,
                         __audWriteQ[next].sizeIdx,
                         (u32)__audWriteQ[next].req->args.write.inPtr);
        }
        /* check for underflow */
        if ( status & AUD_DAC_CTRL_UNDER ) {
/*            AUD_ERROR("DAC: UNDER"); */
            rv = IOS_ERROR_NOTREADY;
            IO_WRITE(AUD_DAC_CTRL_REG, AUD_DAC_CTRL_UNDER);
        }
        /* check for memory access violation */
        if ( status & AUD_ADC_CTRL_MVIOL ) {
            rv = IOS_ERROR_ACCESS;
            IO_WRITE(AUD_ADC_CTRL_REG, AUD_ADC_CTRL_MVIOL);
        }
        /* return status of completed write */
        AUD_LOG("  IOS_WRITE %08x Returning = %d\n", (IOSMessage)req, rv);
        IOS_ResourceReply(req, rv);
    }

}

/*
 * audOpen
 */
static IOSError
audOpen(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_OK;
    u32 dev = 0;
    IOSResourceOpen *args = &req->args.open;
    int i;

    AUD_LOG("in audOpen: '%s', f=%d, u=%d, g=%d\n", args->path, args->flags, args->uid, args->gid);

    if (!strncmp(args->path, AUD_DEV "0", sizeof(AUD_DEV))) {
        AUD_LOG("audOpen: strncmp(%s,%s,%d)\n",args->path, AUD_DEV "0", sizeof(AUD_DEV));
        dev = 0;
    } else {
        rv = IOS_ERROR_NOEXISTS;
        goto out;
    }
        
    for (i = 0; i < AUD_NUM_DEV; ++i) {
        if (audContext[i].state == AUD_STATE_CLOSED) {
            break;
        }
    }

    if (i == AUD_NUM_DEV) {
        rv = IOS_ERROR_MAX;
        goto out;
    }

    switch ( args->flags & O_ACCMODE ) {
    case O_RDONLY:
    case O_WRONLY:
    case O_RDWR:
        audContext[i].flags = args->flags;
        break;
    default:
        rv = IOS_ERROR_INVALID_FLAG;
        goto out;
        break;
    }

    audContext[i].state = AUD_STATE_OPEN;
    audContext[i].volume = AUD_VOLUME_DEFAULT;
    audContext[i].dacMuted = 0;
    audContext[i].sidetone = 0;
    audContext[i].userConfig = AUD_CONFIG_UNDEF;
    audContext[i].config = AUD_CONFIG_UNDEF;
    audContext[i].firstRead = 1;
    audContext[i].firstWrite = 1;

    rv = (IOSError) &audContext[i];
    
out:
    return rv;
}

/*
 * audClose
 */
static IOSError
audClose(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID;
    AudContext *ac = (AudContext *) req->handle;

    AUD_LOG("in audClose\n");
    
    if ( ac->state == AUD_STATE_OPEN ) {
        ac->state = AUD_STATE_CLOSED;
        rv = IOS_ERROR_OK;
    } else if ( ac->state == AUD_STATE_CONFIG ) {
        /* can't close if there are pending reads/writes */
        if ( __nAudReads || __nAudWrites ) {
            rv = IOS_ERROR_NOTREADY;
        } else {
            ac->state = AUD_STATE_CLOSED;
            audShutdown();
            rv = IOS_ERROR_OK;
        }
    }
    
    return rv;
}

/*
 * audRead
 */
static IOSError
audRead(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID;
    AudContext *ac = (AudContext *) req->handle;
    IOSResourceRead *args = &req->args.read;
    
    AUD_LOG("in audRead: in=(0x%08x,%d)\n", args->outPtr, args->outLen);

    if ( ac->state != AUD_STATE_CONFIG ) {
        rv = IOS_ERROR_NOTREADY;
    } else if ( ! OPEN_FOR_READ(ac->flags) ) {
        rv = IOS_ERROR_ACCESS;
    } else if ( (u32)args->outPtr & 0xf ) {
        rv = IOS_ERROR_INVALID;
    } else if ( !args->outLen || (args->outLen & 0xf) ) {
        rv = IOS_ERROR_INVALID_SIZE;
    } else if ( __nAudReads >= AUD_MAX_READS ) {
        rv = IOS_ERROR_QFULL;
    } else {
        /* enqueue new read */
        int tail = (__audReadQHead + __nAudReads) % AUD_MAX_READS;
        __audReadQ[tail].req = req;
        __audReadQ[tail].sizeIdx = audConvertSize((u32)args->outLen);
        __audReadQ[tail].size = audConvertSizeIdx(__audReadQ[tail].sizeIdx);
        __nAudReads++;
        /* push new read buffer onto fifo, if not full */
        if ( __nAudReads <= 2 ) {  /* hw read fifo depth is 2 */
            audWriteFifo(AUD_ADC_PTR_REG, __audReadQ[tail].sizeIdx, (u32)args->outPtr);
            if ( ac->firstRead ) {
                IO_WRITE(AUD_ADC_CTRL_REG,ADC_START);
                ac->firstRead = 0;
            }
        }
        rv = IOS_ERROR_OK;
    }
    
    return rv;
}

/*
 * audWrite
 */
static IOSError
audWrite(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID;
    AudContext *ac = (AudContext *) req->handle;
    IOSResourceWrite *args = &req->args.write;
    
    AUD_LOG("in audWrite: in=(0x%08x,%d)\n", args->inPtr, args->inLen);

    if ( ac->state != AUD_STATE_CONFIG ) {
        rv = IOS_ERROR_NOTREADY;
    } else if ( ! OPEN_FOR_WRITE(ac->flags) ) {
        rv = IOS_ERROR_ACCESS;
    } else if ( (u32)args->inPtr & 0xf ) {
        rv = IOS_ERROR_INVALID;
    } else if ( !args->inLen || (args->inLen & 0xf) ) {
        rv = IOS_ERROR_INVALID_SIZE;
    } else if ( __nAudWrites >= AUD_MAX_WRITES ) {
        rv = IOS_ERROR_QFULL;
    } else {
        /* enqueue new write */
        int tail = (__audWriteQHead + __nAudWrites) % AUD_MAX_WRITES;
        __audWriteQ[tail].req = req;
        __audWriteQ[tail].sizeIdx = audConvertSize((u32)args->inLen);
        __audWriteQ[tail].size = audConvertSizeIdx(__audWriteQ[tail].sizeIdx);
        __nAudWrites++;
        /* push new write buffer onto fifo, if not full */
        if ( __nAudWrites <= 2 ) {  /* hw write fifo depth is 2 */
            audWriteFifo(AUD_DAC_PTR_REG, __audWriteQ[tail].sizeIdx, (u32)args->inPtr);
            if ( ac->firstWrite ) {
                IO_WRITE(AUD_DAC_CTRL_REG,DAC_START);
                ac->firstWrite = 0;
            }
        }
        rv = IOS_ERROR_OK;
    }
    
    return rv;
}

/*
 * audIoctl
 */
static IOSError
audIoctl(IOSResourceRequest *req)
{
    IOSError rv = IOS_ERROR_INVALID;
    AudContext *ac = (AudContext *) req->handle;
    
    AUD_LOG("in audIoctl: cmd=%d, in=(%d,%d), out=(%d,%d)\n",
            req->args.ioctl.cmd,
            req->args.ioctl.inPtr, req->args.ioctl.inLen,
            req->args.ioctl.outPtr, req->args.ioctl.outLen);

    if ( ac->state != AUD_STATE_OPEN && ac->state != AUD_STATE_CONFIG ) {
        rv = IOS_ERROR_NOTREADY;
        goto out;
    }

    switch ( req->args.ioctl.cmd ) {
    case AUD_SET_VOLUME:
        if (req->args.ioctl.inPtr && req->args.ioctl.inLen == sizeof(u32) ) {
            u32 v = *((u32 *)req->args.ioctl.inPtr);
            /* check for legal bounds */
            if ( (v < AUD_VOLUME_MIN || v > AUD_VOLUME_MAX) && (v != AUD_VOLUME_MUTE) ) {
                rv = IOS_ERROR_INVALID_FLAG;
                break;
            }
            if ( req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
                /* return the old value if outPtr & outLen are valid */
                *((u32*)req->args.ioctl.outPtr) = ac->dacMuted ? AUD_VOLUME_MUTE : ac->volume;
            }
            /* set volume */
            AUD_LOG("setting volume to %d\n",v);
            if ( ac->state == AUD_STATE_CONFIG ) {
                audVolume(ac, v);
            } else if ( ac->state == AUD_STATE_OPEN ) {
                ac->volume = v;
            }
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_GET_VOLUME:
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            /* get volume */
            u32 v = ac->dacMuted ? AUD_VOLUME_MUTE : ac->volume;
            AUD_LOG("getting volume of %d\n",v);
            *((u32 *)req->args.ioctl.outPtr) = v;
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_SET_SIDETONE:
        if (req->args.ioctl.inPtr && req->args.ioctl.inLen == sizeof(u32) ) {
            if ( ac->state != AUD_STATE_OPEN ) {
                rv = IOS_ERROR_NOTREADY;
                break;
            }
            /* check for legal bounds */
            u32 v = *(u32 *)req->args.ioctl.inPtr;
            if ( v != 0 && v != 1 ) {
                rv = IOS_ERROR_INVALID_FLAG;
                break;
            }
            if ( req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
                /* return the old value if outPtr & outLen are valid */
                *((u32*)req->args.ioctl.outPtr) = ac->sidetone;
            }
            /* set sidetone */
            AUD_LOG("setting sidetone to %d\n",v);
            ac->sidetone = v;
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_GET_SIDETONE:
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            /* get sidetone */
            AUD_LOG("getting sidetone of %d\n",ac->sidetone);
            *((u32 *)req->args.ioctl.outPtr) = ac->sidetone;
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_SET_CONFIG:
        if (req->args.ioctl.inPtr && req->args.ioctl.inLen == sizeof(u32) ) {
            u32 config = *((u32 *)req->args.ioctl.inPtr);
            if ( ac->state != AUD_STATE_OPEN ) {
                rv = IOS_ERROR_NOTREADY;
                break;
            }
            if ( config < 0 || config >= AUD_CONFIG_MAX ) {
                rv = IOS_ERROR_INVALID_FLAG;
                break;
            }
            ac->userConfig = ac->config = config;
            /* use lower-power (i.e., lower freq) configuration if it's transparent
             * to the user.  for example, if the user selects 48KHz ADC and 8KHz DAC
             * but then opens the audio device as write-only, the 48KHz ADC isn't
             * really used; in this case configure the system for 8KHz ADC and 8KHz
             * DAC since it has slower clocks and therefore will use less power
             */
            int r = OPEN_FOR_READ(ac->flags);
            int w = OPEN_FOR_WRITE(ac->flags);
            if ( (config == AUD_CONFIG_ADC_48_DAC_8 && !r) ||
                 (config == AUD_CONFIG_ADC_8_DAC_48 && !w) )
                ac->config = AUD_CONFIG_ADC_8_DAC_8;
            if ( (config == AUD_CONFIG_ADC_44P1_DAC_8P018 && !r) ||
                 (config == AUD_CONFIG_ADC_8P018_DAC_44P1 && !w) )
                ac->config = AUD_CONFIG_ADC_8P018_DAC_8P018;
            
            AUD_LOG("setting config to ext = %d, int = %d\n", ac->userConfig, ac->config);

            if ( (rv = audInit(ac)) != IOS_ERROR_OK ) {
                ac->userConfig = ac->config = AUD_CONFIG_UNDEF;
                rv = IOS_ERROR_FAIL_INTERNAL;
                break;
            }
            ac->state = AUD_STATE_CONFIG;
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_GET_CONFIG:
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            *((u32 *)req->args.ioctl.outPtr) = ac->userConfig;
            AUD_LOG("getting config of %d (ext)\n", ac->userConfig);
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_GET_HEADSET:
        if (req->args.ioctl.outPtr && req->args.ioctl.outLen == sizeof(u32) ) {
            if ( ac->state == AUD_STATE_OPEN ) {
                /* hardware not enabled yet, so temporarily enable it */
                IOS_SetPower(IOS_DEVICE_AUDIO, 1);
                WAInit();  /* configure audio GPIO's */
            }
            int v = IO_READ(AUD_GPIO_DATA_REG) & 0x80 ? 1 : 0;
            AUD_LOG("getting headset of %d\n", v);
            *((u32 *)req->args.ioctl.outPtr) = v;
            if ( ac->state == AUD_STATE_OPEN ) {
                /* return hardware to its initial disabled state */
                IOS_SetPower(IOS_DEVICE_AUDIO, 0);
            }
            rv = IOS_ERROR_OK;
        } 
        break;
    case AUD_SET_EXT_CODEC:
        if (req->args.ioctl.inPtr && req->args.ioctl.inLen == 2*sizeof(u32) ) {
            u32 addr = *((u32 *)req->args.ioctl.inPtr);
            u32 val = *((u32 *)req->args.ioctl.inPtr+1);
            AUD_LOG("manually writing codec register: a=%d (0x%08x), d=%d (0x%08x)\n",addr,val);
            WAWrite(addr,val);
            rv = IOS_ERROR_OK;
        }
    default:
        rv = IOS_ERROR_INVALID;
        break;
    }
    
out:
    return rv;
}

/*
 * audIoctlv
 */
static IOSError
audIoctlv(IOSResourceRequest *req)
{
    /* not supported */
    return IOS_ERROR_INVALID;
}

/*
 * main
 */
int main(void)
{
    IOSError rv;
    IOSMessageQueueId mq;
    IOSMessage msgArray[8];
    IOSMessage msg;
    u32 i;
    
#ifdef USB_PRINTF
    /* Initialize the printf buffer */
    extern void  *__usbPrintfBuf;
    if ((__usbPrintfBuf = IOS_Alloc(0, PRINTF_BUF_SIZE)) == NULL) {
        rv = IOS_ERROR_MAX;
        goto out;
    }
#endif

    AUD_LOG("Starting\n");
    
    /* initialize private data structures */
    for (i=0; i<AUD_NUM_DEV; i++) {
        audContext[i].state = AUD_STATE_CLOSED;
        audContext[i].dacMuted = 0;
        audContext[i].volume = 0;
        audContext[i].sidetone = 0;
        audContext[i].flags = 0;
        audContext[i].userConfig = AUD_CONFIG_UNDEF;
        audContext[i].config = AUD_CONFIG_UNDEF;
        audContext[i].firstRead = 0;
        audContext[i].firstWrite = 0;
    }
    
    __nAudReads = 0;
    __nAudWrites = 0;
    __audReadQHead = 0;
    __audWriteQHead = 0;
    
    /* Create a message queue */
    AUD_LOG("Create message queue [%08x]\n", msgArray);
    if ((rv = mq = IOS_CreateMessageQueue(msgArray, sizeof(msgArray)/sizeof(msgArray[0]))) < 0) {
        AUD_ERROR("IOS_CreateMessageQueue");
        AUD_LOG("Error = %d", rv);
        goto out;
    }

    /* Register the message queue with the kernel */
    AUD_LOG("Register as Resource Manager\n");
    if ((rv = IOS_RegisterResourceManager(AUD_DEV, mq)) != IOS_ERROR_OK) {
        AUD_ERROR("IOS_RegisterResourceManager");
        AUD_LOG("Error = %d", rv);
        goto out;
    }

    /* Register the message queue to handle ADC events */
    AUD_LOG("Register with Event Handler for ADC events\n");
    if ((rv = IOS_HandleEvent(IOS_EVENT_ADC, mq, (int)audEventADC)) != IOS_ERROR_OK) {
        AUD_ERROR("IOS_HandleEvent for IOS_EVENT_ADC");
        AUD_LOG("Error = %d", rv);
        goto out;
    }
  
    /* Register the message queue to handle DAC events */
    AUD_LOG("Register with Event Handler for DAC events\n");
    if ((rv = IOS_HandleEvent(IOS_EVENT_DAC, mq, (int)audEventDAC)) != IOS_ERROR_OK) {
        AUD_ERROR("IOS_HandleEvent for IOS_EVENT_DAC");
        AUD_LOG("Error = %d", rv);
        goto out;
    }
  
    /* Main dispatch loop */
    while (1) {
        AUD_LOG("waiting for msg\n");
        
        /* Receive a command */
        if ((rv = IOS_ReceiveMessage(mq, &msg, IOS_MESSAGE_BLOCK)) != IOS_ERROR_OK) {
            AUD_ERROR("IOS_ReceiveMessage");
            goto out;
        }
        AUD_LOG("Received resource request: %08x\n", msg);

        /* Dispatch command */
        if ( msg == (int)audEventADC ) {  /* recvd ADC event from interrupt handler */
            AUD_LOG("  ADC Event\n", msg);
            audEventADC();
        } else if ( msg == (int)audEventDAC ) {  /* recvd DAC event from interrupt handler */
            AUD_LOG("  DAC Event\n", msg);
            audEventDAC();
        } else {  /* Resource Manager request */
            IOSResourceRequest *req = (IOSResourceRequest *) msg;
            switch (req->cmd) {
            case IOS_OPEN:
                AUD_LOG("  IOS_OPEN %08x\n", msg);
                rv = audOpen(req);
                AUD_LOG("  IOS_OPEN %08x Returning = %d (%s)\n", msg, rv, rv < 0 ? "fail" : "pass");
                IOS_ResourceReply(req, rv);
                break;
            case IOS_CLOSE:
                AUD_LOG("  IOS_CLOSE %08x\n", msg);
                rv = audClose(req);
                AUD_LOG("  IOS_CLOSE %08x Returning = %d\n", msg, rv);
                IOS_ResourceReply(req, rv);
                break;
            case IOS_READ:
                AUD_LOG("  IOS_READ %08x\n", msg);
                rv = audRead(req);
                if (rv != IOS_ERROR_OK) {
                    AUD_LOG("  IOS_READ %08x Returning = %d\n", msg, rv);
                    IOS_ResourceReply(req, rv);
                }
                break;
            case IOS_WRITE:
                AUD_LOG("  IOS_WRITE %08x\n", msg);
                rv = audWrite(req);
                if (rv != IOS_ERROR_OK) {
                    AUD_LOG("  IOS_WRITE %08x Returning = %d\n", msg, rv);
                    IOS_ResourceReply(req, rv);
                }
                break;
            case IOS_IOCTL:
                AUD_LOG("  IOS_IOCTL %08x\n", msg);
                rv = audIoctl(req);
                AUD_LOG("  IOS_IOCTL %08x Returning = %d\n", msg, rv);
                IOS_ResourceReply(req, rv);
                break;
            case IOS_IOCTLV:
                AUD_LOG("  IOS_IOCTLV %08x\n", msg);
                rv = audIoctlv(req);
                AUD_LOG("  IOS_IOCTLV %08x Returning = %d\n", msg, rv);
                IOS_ResourceReply(req, rv);
                break;
            default:
                AUD_LOG("  Unsupported %08x\n", msg);
                rv = IOS_ERROR_INVALID;
                AUD_LOG("  Unsupported %08x Returning = %d\n", msg, rv);
                IOS_ResourceReply(req, rv);
                break;
            } /* switch */
        } /* if */
        
    } /* while */

    /* this code executes only if the ADC or DAC event
     * handler reports a catastropic error
     */

    /* Unregister the ADC event handler */
    AUD_LOG("Unregister Event Handler for DAC events\n");
    if ((rv = IOS_UnhandleEvent(IOS_EVENT_DAC)) != IOS_ERROR_OK) {
        AUD_ERROR("IOS_UnhandleEvent for IOS_EVENT_DAC");
        AUD_LOG("Error = %d", rv);
    }

    /* Unregister the DAC event handler */
    AUD_LOG("Unregister Event Handler for ADC events\n");
    if ((rv = IOS_UnhandleEvent(IOS_EVENT_ADC)) != IOS_ERROR_OK) {
        AUD_ERROR("IOS_UnhandleEvent for IOS_EVENT_ADC");
        AUD_LOG("Error = %d", rv);
    }

out:
    AUD_LOG("Exiting\n");
    return 0;
}
