/*
 *  Copyright (c) by Jaroslav Kysela <perex@suse.cz>
 *  Routines for control of GF1 chip (PCM things)
 *
 *  InterWave chips supports interleaved DMA, but this feature isn't used in
 *  this code.
 *  
 *  This code emulates autoinit DMA transfer for playback, recording by GF1
 *  chip doesn't support autoinit DMA.
 *
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 *
 */

#define __SND_OSS_COMPAT__
#include "../../include/driver.h"
#include "../../include/ulaw.h"
#include "../../include/gus.h"
#include "gus_tables.h"

/* maximum rate */

#define SND_GF1_PCM_RATE	48000

#define SND_GF1_PCM_PFLG_NONE		0
#define SND_GF1_PCM_PFLG_ACTIVE		(1<<0)
#define SND_GF1_PCM_PFLG_NEUTRAL	(2<<0)

typedef struct {
	snd_gus_card_t * gus;
	snd_pcm_subchn_t * subchn;
	spinlock_t lock;
	int voices;
	snd_gus_voice_t *pvoices[2];
	unsigned int memory;
	unsigned short flags;
	unsigned char voice_ctrl, ramp_ctrl;
	unsigned int bpos;
	unsigned int blocks;
	unsigned int block_size;
	unsigned int dma_size;
	wait_queue_head_t sleep;
	atomic_t dma_count;
	int final_volume;
} gus_pcm_private_t;

static void snd_gf1_pcm_block_change_ack(snd_gus_card_t * gus, void *private_data)
{
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, private_data, );

	if (pcmp) {
		atomic_dec(&pcmp->dma_count);
		wake_up(&pcmp->sleep);
	}
}

static void snd_gf1_pcm_block_change(snd_pcm_subchn_t * subchn,
				     unsigned int offset,
				     unsigned int addr,
				     unsigned int count)
{
	snd_gf1_dma_block_t block;
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, );

	// snd_printk("block change - offset = 0x%x, count = 0x%x\n", offset, count);
	if (offset & 31)
		snd_printd("gf1 pcm block change - unaligned access\n");
	if (count < 32)
		snd_printd("gf1 pcm block change - wrong count\n");
	memset(&block, 0, sizeof(block));
	block.cmd = SND_GF1_DMA_IRQ;
	if (snd_pcm_format_unsigned(runtime->format.format))
		block.cmd |= SND_GF1_DMA_UNSIGNED;
	if (snd_pcm_format_width(runtime->format.format) == 16)
		block.cmd |= SND_GF1_DMA_16BIT;
	block.addr = addr;
	block.buffer = runtime->dma_area->buf + offset;
	block.count = count;
	block.private_data = pcmp;
	block.ack = snd_gf1_pcm_block_change_ack;
	if (!snd_gf1_dma_transfer_block(pcmp->gus, &block, 0, 0))
		atomic_inc(&pcmp->dma_count);
}

static void snd_gf1_pcm_trigger_up(snd_pcm_subchn_t * subchn)
{
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, );
	snd_gus_card_t * gus = pcmp->gus;
	unsigned long flags;
	unsigned char voice_ctrl, ramp_ctrl;
	unsigned short rate;
	unsigned int curr, begin, end;
	unsigned short vol;
	unsigned char pan;
	unsigned int voice;

	if (subchn == NULL)
		return;
	spin_lock_irqsave(&pcmp->lock, flags);
	if (pcmp->flags & SND_GF1_PCM_PFLG_ACTIVE) {
		spin_unlock_irqrestore(&pcmp->lock, flags);
		return;
	}
	pcmp->flags |= SND_GF1_PCM_PFLG_ACTIVE;
	pcmp->final_volume = 0;
	spin_unlock_irqrestore(&pcmp->lock, flags);
	rate = snd_gf1_translate_freq(gus, runtime->format.rate << 4);
	/* enable WAVE IRQ */
	voice_ctrl = snd_pcm_format_width(runtime->format.format) == 16 ? 0x24 : 0x20;
	/* enable RAMP IRQ + rollover */
	ramp_ctrl = 0x24;
	if (pcmp->blocks == 1) {
		voice_ctrl |= 0x08;	/* loop enable */
		ramp_ctrl &= ~0x04;	/* disable rollover */
	}
	for (voice = 0; voice < pcmp->voices; voice++) {
		begin = pcmp->memory + voice * (pcmp->dma_size / runtime->format.voices);
		curr = begin + (pcmp->bpos * pcmp->block_size) / runtime->format.voices;
		end = curr + (pcmp->block_size / runtime->format.voices);
		end -= snd_pcm_format_width(runtime->format.format) == 16 ? 2 : 1;
		// snd_printk("init: curr=0x%x, begin=0x%x, end=0x%x, ctrl=0x%x, ramp=0x%x, rate=0x%x\n", curr, begin, end, voice_ctrl, ramp_ctrl, rate);
		pan = runtime->format.voices == 2 ? (!voice ? 1 : 14) : 8;
		vol = !voice ? gus->gf1.pcm_volume_level_left : gus->gf1.pcm_volume_level_right;
		spin_lock_irqsave(&gus->reg_lock, flags);
		snd_gf1_select_voice(gus, pcmp->pvoices[voice]->number);
		snd_gf1_write8(gus, SND_GF1_VB_PAN, pan);
		snd_gf1_write16(gus, SND_GF1_VW_FREQUENCY, rate);
		snd_gf1_write_addr(gus, SND_GF1_VA_START, begin << 4, voice_ctrl & 4);
		snd_gf1_write_addr(gus, SND_GF1_VA_END, end << 4, voice_ctrl & 4);
		snd_gf1_write_addr(gus, SND_GF1_VA_CURRENT, curr << 4, voice_ctrl & 4);
		snd_gf1_write16(gus, SND_GF1_VW_VOLUME, SND_GF1_MIN_VOLUME << 4);
		snd_gf1_write8(gus, SND_GF1_VB_VOLUME_RATE, 0x2f);
		snd_gf1_write8(gus, SND_GF1_VB_VOLUME_START, SND_GF1_MIN_OFFSET);
		snd_gf1_write8(gus, SND_GF1_VB_VOLUME_END, vol >> 8);
		snd_gf1_write8(gus, SND_GF1_VB_VOLUME_CONTROL, ramp_ctrl);
		if (!gus->gf1.enh_mode) {
			snd_gf1_delay(gus);
			snd_gf1_write8(gus, SND_GF1_VB_VOLUME_CONTROL, ramp_ctrl);
		}
		spin_unlock_irqrestore(&gus->reg_lock, flags);
	}
	spin_lock_irqsave(&gus->reg_lock, flags);
	for (voice = 0; voice < pcmp->voices; voice++) {
		snd_gf1_select_voice(gus, pcmp->pvoices[voice]->number);
		if (gus->gf1.enh_mode)
			snd_gf1_write8(gus, SND_GF1_VB_MODE, 0x00);	/* deactivate voice */
		snd_gf1_write8(gus, SND_GF1_VB_ADDRESS_CONTROL, voice_ctrl);
		voice_ctrl &= ~0x20;
	}
	voice_ctrl |= 0x20;
	if (!gus->gf1.enh_mode) {
		snd_gf1_delay(gus);
		for (voice = 0; voice < pcmp->voices; voice++) {
			snd_gf1_select_voice(gus, pcmp->pvoices[voice]->number);
			snd_gf1_write8(gus, SND_GF1_VB_ADDRESS_CONTROL, voice_ctrl);
			voice_ctrl &= ~0x20;	/* disable IRQ for next voice */
		}
	}
	spin_unlock_irqrestore(&gus->reg_lock, flags);
}

static void snd_gf1_pcm_interrupt_wave(snd_gus_card_t * gus, snd_gus_voice_t *pvoice)
{
	gus_pcm_private_t * pcmp;
	snd_pcm_runtime_t * runtime;
	unsigned char voice_ctrl, ramp_ctrl;
	int idx;
	unsigned int end, step;

	if (!pvoice->private_data) {
		snd_printd("snd_gf1_pcm: unknown wave irq?\n");
		snd_gf1_smart_stop_voice(gus, pvoice->number);
		return;
	}
	pcmp = snd_magic_cast(gus_pcm_private_t, pvoice->private_data, );
	if (pcmp == NULL) {
		snd_printd("snd_gf1_pcm: unknown wave irq?\n");
		snd_gf1_smart_stop_voice(gus, pvoice->number);
		return;
	}		
	gus = pcmp->gus;
	runtime = pcmp->subchn->runtime;

	spin_lock(&gus->reg_lock);
	snd_gf1_select_voice(gus, pvoice->number);
	voice_ctrl = snd_gf1_read8(gus, SND_GF1_VB_ADDRESS_CONTROL) & ~0x8b;
	ramp_ctrl = (snd_gf1_read8(gus, SND_GF1_VB_VOLUME_CONTROL) & ~0xa4) | 0x03;
#if 0
	snd_gf1_select_voice(gus, pvoice->number);
	printk("position = 0x%x\n", (snd_gf1_read_addr(gus, SND_GF1_VA_CURRENT, voice_ctrl & 4) >> 4));
	snd_gf1_select_voice(gus, pcmp->pvoices[1]->number);
	printk("position = 0x%x\n", (snd_gf1_read_addr(gus, SND_GF1_VA_CURRENT, voice_ctrl & 4) >> 4));
	snd_gf1_select_voice(gus, pvoice->number);
#endif
	pcmp->bpos++;
	pcmp->bpos %= pcmp->blocks;
	if (pcmp->bpos + 1 >= pcmp->blocks) {	/* last block? */
		voice_ctrl |= 0x08;	/* enable loop */
	} else {
		ramp_ctrl |= 0x04;	/* enable rollover */
	}
	end = pcmp->memory + (((pcmp->bpos + 1) * pcmp->block_size) / runtime->format.voices);
	end -= voice_ctrl & 4 ? 2 : 1;
	step = pcmp->dma_size / runtime->format.voices;
	voice_ctrl |= 0x20;
	if (!pcmp->final_volume) {
		ramp_ctrl |= 0x20;
		ramp_ctrl &= ~0x03;
	}
	for (idx = 0; idx < pcmp->voices; idx++, end += step) {
		snd_gf1_select_voice(gus, pcmp->pvoices[idx]->number);
		snd_gf1_write_addr(gus, SND_GF1_VA_END, end << 4, voice_ctrl & 4);
		snd_gf1_write8(gus, SND_GF1_VB_ADDRESS_CONTROL, voice_ctrl);
		snd_gf1_write8(gus, SND_GF1_VB_VOLUME_CONTROL, ramp_ctrl);
		voice_ctrl &= ~0x20;
	}
	if (!gus->gf1.enh_mode) {
		snd_gf1_delay(gus);
		voice_ctrl |= 0x20;
		for (idx = 0; idx < pcmp->voices; idx++) {
			snd_gf1_select_voice(gus, pcmp->pvoices[idx]->number);
			snd_gf1_write8(gus, SND_GF1_VB_ADDRESS_CONTROL, voice_ctrl);
			snd_gf1_write8(gus, SND_GF1_VB_VOLUME_CONTROL, ramp_ctrl);
			voice_ctrl &= ~0x20;
		}
	}
	spin_unlock(&gus->reg_lock);

	snd_pcm_transfer_done(pcmp->subchn);
#if 0
	if ((runtime->flags & SND_PCM_FLG_MMAP) &&
	    *runtime->status == SND_PCM_STATUS_RUNNING) {
		end = pcmp->bpos * pcmp->block_size;
		if (runtime->format.voices > 1) {
			snd_gf1_pcm_block_change(pcmp->subchn, end, pcmp->memory + (end / 2), pcmp->block_size / 2);
			snd_gf1_pcm_block_change(pcmp->subchn, end + (pcmp->block_size / 2), pcmp->memory + (pcmp->dma_size / 2) + (end / 2), pcmp->block_size / 2);
		} else {
			snd_gf1_pcm_block_change(pcmp->subchn, end, pcmp->memory + end, pcmp->block_size);
		}
	}
#endif
}

static void snd_gf1_pcm_interrupt_volume(snd_gus_card_t * gus, snd_gus_voice_t * pvoice)
{
	unsigned short vol;
	int cvoice;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, pvoice->private_data, );

	/* stop ramp, but leave rollover bit untouched */
	spin_lock(&gus->reg_lock);
	snd_gf1_select_voice(gus, pvoice->number);
	snd_gf1_ctrl_stop(gus, SND_GF1_VB_VOLUME_CONTROL);
	spin_unlock(&gus->reg_lock);
	if (pcmp == NULL)
		return;
	/* are we active? */
	if (!(pcmp->flags & SND_GF1_PCM_PFLG_ACTIVE))
		return;
	/* load real volume - better precision */
	cvoice = pcmp->pvoices[0] == pvoice ? 0 : 1;
	if (pcmp->subchn == NULL)
		return;
	vol = !cvoice ? gus->gf1.pcm_volume_level_left : gus->gf1.pcm_volume_level_right;
	spin_lock(&gus->reg_lock);
	snd_gf1_select_voice(gus, pvoice->number);
	snd_gf1_write16(gus, SND_GF1_VW_VOLUME, vol);
	pcmp->final_volume = 1;
	spin_unlock(&gus->reg_lock);
}

static void snd_gf1_pcm_volume_change(snd_gus_card_t * gus)
{
}

static int snd_gf1_pcm_poke_block(snd_gus_card_t *gus, char *buf, int pos,
				  int count, int w16, int invert)
{
	int len;
	unsigned long flags;

	// printk("poke block; buf = 0x%x, pos = %i, count = %i, port = 0x%x\n", (int)buf, pos, count, gus->gf1.port);
	while (count > 0) {
		len = count;
		if (len > 512)		/* limit, to allow IRQ */
			len = 512;
		count -= len;
		if (gus->interwave) {
			spin_lock_irqsave(&gus->reg_lock, flags);
			snd_gf1_write8(gus, SND_GF1_GB_MEMORY_CONTROL, 0x01 | (invert ? 0x08 : 0x00));
			snd_gf1_dram_addr(gus, pos);
			if (w16) {
				outb(SND_GF1_GW_DRAM_IO16, GUSP(gus, GF1REGSEL));
				outsw(GUSP(gus, GF1DATALOW), buf, len >> 1);
			} else {
				outsb(GUSP(gus, DRAM), buf, len);
			}
			spin_unlock_irqrestore(&gus->reg_lock, flags);
			buf += 512;
			pos += 512;
		} else {
			invert = invert ? 0x80 : 0x00;
			if (w16) {
				len >>= 1;
				while (len--) {
					snd_gf1_poke(gus, pos++, *buf++);
					snd_gf1_poke(gus, pos++, *buf++ ^ invert);
				}
			} else {
				while (len--)
					snd_gf1_poke(gus, pos++, *buf++ ^ invert);
			}
		}
		schedule_timeout(1);
		if (signal_pending(current))
			return -EAGAIN;
	}
	return 0;
}

static void snd_gf1_pcm_separate_16bit(unsigned short *buf, int dma_size, int count)
{
	unsigned short *dst1, *dst2;
	
	dst1 = buf + dma_size / 4;
	dst2 = dst1 + dma_size / 8;
	while (count--) {
		*dst1++ = *buf++;
		*dst2++ = *buf++;
	}
}
				       
static void snd_gf1_pcm_separate_8bit(unsigned char *buf, int dma_size, int count)
{
	unsigned char *dst1, *dst2;
	
	dst1 = buf + dma_size / 2;
	dst2 = dst1 + dma_size / 4;
	// printk("buf = 0x%x, dst1 = 0x%x, dst2 = 0x%x\n", (int)buf, (int)dst1, (int)dst2);
	while (count--) {
		*dst1++ = *buf++;
		*dst2++ = *buf++;
	}
}
				       
static int snd_gf1_pcm_playback_memcpy(snd_pcm_subchn_t *subchn,
				       int voice,
				       int pos,
				       void *src,
				       int count)
{
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);
	
	if (runtime->mode == SND_PCM_MODE_BLOCK) {
		if (copy_from_user(runtime->dma_area->buf + pos, src, count))
			return -EFAULT;
		if (runtime->format.voices > 1) {
			snd_gf1_pcm_block_change(subchn, pos, (pos / 2) + pcmp->memory, count / 2);
			snd_gf1_pcm_block_change(subchn, pos + (pcmp->block_size / 2), (pcmp->dma_size / 2) + (pos / 2) + pcmp->memory, count / 2);
		} else {
			snd_gf1_pcm_block_change(subchn, pos, pcmp->memory + pos, count);
		}
	} else {
		snd_gus_card_t *gus = pcmp->gus;
		char *buf;
		int len, err, w16, invert;

		w16 = (snd_pcm_format_width(runtime->format.format) == 16);
		invert = snd_pcm_format_unsigned(runtime->format.format);
		if (runtime->format.voices == 1) {
			if (copy_from_user(buf = (runtime->dma_area->buf + pos), src, count))
				return -EFAULT;
			if ((err = snd_gf1_pcm_poke_block(gus, buf, pos + pcmp->memory, count, w16, invert)) < 0)
				return err;
		} else {
			buf = runtime->dma_area->buf;
			while (count > 0) {
				len = count;
				if (len > pcmp->dma_size / 2)
					len = pcmp->dma_size / 2;
				if (copy_from_user(buf, src, len))
					return -EFAULT;
				if (w16) {
					snd_gf1_pcm_separate_16bit((short *)buf, pcmp->dma_size, len / 4);
				} else {
					snd_gf1_pcm_separate_8bit(buf, pcmp->dma_size, len / 2);
				}
				if ((err = snd_gf1_pcm_poke_block(gus, buf + (pcmp->dma_size / 2), (pos / 2) + pcmp->memory, len / 2, w16, invert)) < 0)
					return err;
				if ((err = snd_gf1_pcm_poke_block(gus, buf + (pcmp->dma_size / 2) + (pcmp->dma_size / 4), (pcmp->dma_size / 2) + (pos / 2) + pcmp->memory, len / 2, w16, invert)) < 0)
					return err;
				src += len;
				count -= len;
				pos += len;
			}
		}
	}
	return 0;
}

static int snd_gf1_pcm_playback_ioctl(void *private_data,
				      snd_pcm_subchn_t * subchn,
				      unsigned int cmd,
				      unsigned long *arg)
{
	int result;
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);

	result = snd_pcm_lib_ioctl(private_data, subchn, cmd, arg);
	if (result < 0)
		return result;
	if (cmd == SND_PCM_IOCTL1_PARAMS) {
		pcmp->voices = runtime->format.voices;
		if (runtime->mode == SND_PCM_MODE_BLOCK) {
			int val = 31, err;

			if (pcmp->voices > 1)
				val = 63;
			runtime->buf.block.frag_size += val;
			runtime->buf.block.frag_size /= (val + 1);
			runtime->buf.block.frag_size *= (val + 1);
			if ((err = snd_pcm_lib_set_buffer_size(subchn, runtime->dma_area->size)) < 0)
				return err;
		}
	}
	return 0;
}

static int snd_gf1_pcm_playback_prepare(void *private_data,
					snd_pcm_subchn_t * subchn)
{
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);

	pcmp->bpos = 0;
	pcmp->dma_size = snd_pcm_lib_transfer_size(subchn);
	pcmp->block_size = snd_pcm_lib_transfer_fragment(subchn);
	pcmp->blocks = pcmp->dma_size / pcmp->block_size;
	return 0;
}

static int snd_gf1_pcm_playback_trigger(void *private_data,
					snd_pcm_subchn_t * subchn,
					int cmd)
{
	unsigned long flags;
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);
	int voice;

	if (cmd == SND_PCM_TRIGGER_GO) {
		snd_gf1_pcm_trigger_up(subchn);
	} else if (cmd == SND_PCM_TRIGGER_STOP) {
		spin_lock_irqsave(&pcmp->lock, flags);
		pcmp->flags &= ~SND_GF1_PCM_PFLG_ACTIVE;
		spin_unlock_irqrestore(&pcmp->lock, flags);
		voice = pcmp->pvoices[0]->number;
		snd_gf1_stop_voices(gus, voice, voice);
		voice = pcmp->pvoices[1]->number;
		snd_gf1_stop_voices(gus, voice, voice);
	} else {
		return -EINVAL;
	}
	return 0;
}

static unsigned int snd_gf1_pcm_playback_pointer(void *private_data,
						 snd_pcm_subchn_t * subchn)
{
	unsigned long flags;
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);
	unsigned int pos;
	unsigned char voice_ctrl;

	pos = 0;
	spin_lock_irqsave(&gus->reg_lock, flags);
	if (pcmp->flags & SND_GF1_PCM_PFLG_ACTIVE) {
		snd_gf1_select_voice(gus, pcmp->pvoices[0]->number);
		voice_ctrl = snd_gf1_read8(gus, SND_GF1_VB_ADDRESS_CONTROL);
		pos = (snd_gf1_read_addr(gus, SND_GF1_VA_CURRENT, voice_ctrl & 4) >> 4) - pcmp->memory;
		if (subchn->runtime->format.voices > 1)
			pos <<= 1;
	}
	spin_unlock_irqrestore(&gus->reg_lock, flags);
	return pos;
}

static int snd_gf1_pcm_capture_ioctl(void *private_data,
				     snd_pcm_subchn_t * subchn,
				     unsigned int cmd,
				     unsigned long *arg)
{
	int result;
	snd_pcm_runtime_t *runtime = subchn->runtime;
	
	result = snd_pcm_lib_ioctl(private_data, subchn, cmd, arg);
	if (result < 0)
		return result;
	if (cmd == SND_PCM_IOCTL1_PARAMS) {
		unsigned int tmp;
	
		tmp = ((9878400L + (runtime->format.rate << 3)) / (runtime->format.rate << 4)) - 2;
		runtime->format.rate = 9878400L / ((tmp + 2) << 4);
	}
	return 0;
}

static int snd_gf1_pcm_capture_prepare(void *private_data,
				       snd_pcm_subchn_t * subchn)
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	snd_pcm_runtime_t *runtime = subchn->runtime;
	unsigned short tmp;

	gus->c_dma_size = snd_pcm_lib_transfer_size(subchn);
	gus->c_frag_size = snd_pcm_lib_transfer_fragment(subchn);
	tmp = ((9878400L + (runtime->format.rate << 3)) / (runtime->format.rate << 4)) - 2;
	snd_gf1_i_write8(gus, SND_GF1_GB_RECORD_RATE, tmp);
	gus->gf1.pcm_rcntrl_reg = 0x21;		/* IRQ at end, enable & start */
	if (runtime->format.voices > 1)
		gus->gf1.pcm_rcntrl_reg |= 2;
	if (gus->gf1.dma2ptr->dma > 3)
		gus->gf1.pcm_rcntrl_reg |= 4;
	if (snd_pcm_format_unsigned(runtime->format.format))
		gus->gf1.pcm_rcntrl_reg |= 0x80;
	snd_gf1_i_write8(gus, SND_GF1_GB_REC_DMA_CONTROL, 0);	/* disable sampling */
	snd_gf1_i_look8(gus, SND_GF1_GB_REC_DMA_CONTROL);	/* Sampling Control Register */
	snd_dma_program(gus->gf1.dma2ptr->dma, &runtime->dma_area->buf[runtime->buf_position % gus->c_dma_size], gus->c_frag_size, DMA_MODE_READ);
	return 0;
}

static int snd_gf1_pcm_capture_trigger(void *private_data,
				       snd_pcm_subchn_t * subchn,
				       int cmd)
{
	unsigned long flags;
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	int val;
	
	if (cmd == SND_PCM_TRIGGER_GO) {
		val = gus->gf1.pcm_rcntrl_reg;
	} else if (cmd == SND_PCM_TRIGGER_STOP) {
		val = 0;
	} else {
		return -EINVAL;
	}

	spin_lock_irqsave(&gus->reg_lock, flags);
	snd_gf1_write8(gus, SND_GF1_GB_REC_DMA_CONTROL, val);
	snd_gf1_look8(gus, SND_GF1_GB_REC_DMA_CONTROL);
	spin_unlock_irqrestore(&gus->reg_lock, flags);
	return 0;
}

static unsigned int snd_gf1_pcm_capture_pointer(void *private_data,
					        snd_pcm_subchn_t * subchn)
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);

	return (subchn->runtime->buf_position + (gus->c_frag_size - snd_dma_residue(gus->gf1.dma2ptr->dma))) % gus->c_dma_size;
}

static void snd_gf1_pcm_interrupt_dma_read(snd_gus_card_t * gus)
{
	snd_gf1_i_write8(gus, SND_GF1_GB_REC_DMA_CONTROL, 0);	/* disable sampling */
	snd_gf1_i_look8(gus, SND_GF1_GB_REC_DMA_CONTROL);	/* Sampling Control Register */
	snd_gf1_pcm_capture_prepare(gus, gus->pcm_cap_subchn); 
	snd_gf1_pcm_capture_trigger(gus, gus->pcm_cap_subchn, SND_PCM_TRIGGER_GO);
}

static snd_pcm_hardware_t snd_gf1_pcm_playback =
{
	SND_PCM_CHNINFO_STREAM |
	SND_PCM_CHNINFO_NONINTERLEAVE |
	SND_PCM_CHNINFO_BLOCK,
	SND_PCM_FMT_S8 | SND_PCM_FMT_U8 |
	SND_PCM_FMT_S16_LE | SND_PCM_FMT_U16_LE,	/* hardware formats */
	SND_PCM_RATE_CONTINUOUS | SND_PCM_RATE_8000_44100,
	5510,			/* min. rate */
	48000,			/* max. rate */
	1,			/* min. voices */
	2,			/* max. voices */
	64,			/* min. fragment size */
	(128*1024),		/* max. fragment size */
	31,			/* fragment align */
	0,			/* FIFO size (unknown) */
	4,			/* transfer block size */
	snd_gf1_pcm_playback_ioctl,
	snd_gf1_pcm_playback_prepare,
	snd_gf1_pcm_playback_trigger,
	snd_gf1_pcm_playback_pointer
};

static snd_pcm_hardware_t snd_gf1_pcm_capture =
{
	SND_PCM_CHNINFO_MMAP | SND_PCM_CHNINFO_STREAM |
	SND_PCM_CHNINFO_BLOCK | SND_PCM_CHNINFO_INTERLEAVE |
	SND_PCM_CHNINFO_MMAP_VALID,
	SND_PCM_FMT_S8 | SND_PCM_FMT_U8,	/* hardware formats */
	SND_PCM_RATE_CONTINUOUS | SND_PCM_RATE_8000_44100,
	5510,			/* min. rate */
	44100,			/* max. rate */
	1,			/* min. voices */
	2,			/* max. voices */
	64,			/* min. fragment size */
	(128*1024),		/* max. fragment size */
	3,			/* fragment align */
	0,			/* FIFO size (unknown) */
	2,			/* transfer block size */
	snd_gf1_pcm_capture_ioctl,
	snd_gf1_pcm_capture_prepare,
	snd_gf1_pcm_capture_trigger,
	snd_gf1_pcm_capture_pointer
};

static void snd_gf1_pcm_playback_free(void *private_data)
{
	gus_pcm_private_t * pcmp = snd_magic_cast(gus_pcm_private_t, private_data, );
	snd_gus_card_t * gus = pcmp->gus;
	
	snd_gf1_free_voice(pcmp->gus, pcmp->pvoices[0]);
	snd_gf1_free_voice(pcmp->gus, pcmp->pvoices[1]);
	if (pcmp->memory > 0)
		snd_gf1_mem_free(&gus->gf1.mem_alloc, pcmp->memory);
	snd_magic_kfree(pcmp);
}

static int snd_gf1_pcm_playback_open(void *private_data,
				     snd_pcm_subchn_t *subchn)
{
	int err;
	gus_pcm_private_t *pcmp;
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	snd_pcm_runtime_t *runtime = subchn->runtime;
	snd_gf1_mem_block_t *block;

	pcmp = snd_magic_kcalloc(gus_pcm_private_t, 0, GFP_KERNEL);
	if (pcmp == NULL)
		return -ENOMEM;
	pcmp->gus = gus;
	spin_lock_init(&pcmp->lock);
	init_waitqueue_head(&pcmp->sleep);
	atomic_set(&pcmp->dma_count, 0);

	runtime->private_data = pcmp;
	runtime->private_free = snd_gf1_pcm_playback_free;

	if ((pcmp->pvoices[0] = snd_gf1_alloc_voice(gus, SND_GF1_VOICE_TYPE_PCM, 0, 0)) == NULL)
		return -EAGAIN;
	if ((pcmp->pvoices[1] = snd_gf1_alloc_voice(gus, SND_GF1_VOICE_TYPE_PCM, 0, 0)) == NULL)
		return -EAGAIN;
	if ((err = snd_pcm_dma_alloc(subchn, gus->gf1.dma1ptr,
				     "GF1 PCM - playback")) < 0)
		return err;
	if ((block = snd_gf1_mem_alloc(&gus->gf1.mem_alloc,
	                               SND_GF1_MEM_OWNER_DRIVER,
				       "GF1 PCM",
	                               subchn->runtime->dma_area->size, 1, 32,
	                               NULL)) == NULL) {
		snd_pcm_dma_free(subchn);
		return -ENOMEM;
	}
	pcmp->memory = block->ptr;
#if 0
	printk("playback.buffer = 0x%lx, gf1.pcm_buffer = 0x%lx\n", (long) pcm->playback.buffer, (long) gus->gf1.pcm_buffer);
#endif
	if (snd_gf1_dma_init(gus) < 0) {
		snd_pcm_dma_free(subchn);
		return -ENOMEM;
	}
	pcmp->pvoices[0]->handler_wave =
	pcmp->pvoices[1]->handler_wave = snd_gf1_pcm_interrupt_wave;
	pcmp->pvoices[0]->handler_volume =
	pcmp->pvoices[1]->handler_volume = snd_gf1_pcm_interrupt_volume;
	pcmp->pvoices[0]->volume_change =
	pcmp->pvoices[1]->volume_change = snd_gf1_pcm_volume_change;
	pcmp->pvoices[0]->private_data =
	pcmp->pvoices[1]->private_data = pcmp;
	pcmp->flags = SND_GF1_PCM_PFLG_NONE;
	pcmp->subchn = subchn;
	runtime->hw = &snd_gf1_pcm_playback;
	runtime->hw_memcpy = snd_gf1_pcm_playback_memcpy;
	return 0;
}

static int snd_gf1_pcm_playback_close(void *private_data,
				      snd_pcm_subchn_t * subchn)
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);
	snd_pcm_runtime_t *runtime = subchn->runtime;
	gus_pcm_private_t *pcmp = snd_magic_cast(gus_pcm_private_t, runtime->private_data, -ENXIO);
	unsigned long jiffies_old;

	jiffies_old = jiffies;
	while (atomic_read(&pcmp->dma_count) > 0) {
		interruptible_sleep_on_timeout(&pcmp->sleep, 1);
		if ((signed long)(jiffies - jiffies_old) > 2*HZ) {
			snd_printk("gf1 pcm - serious DMA problem\n");
			break;
		}
	}
	snd_gf1_dma_done(gus);	
	snd_pcm_dma_free(subchn);
	return 0;
}

static int snd_gf1_pcm_capture_open(void *private_data,
				    snd_pcm_subchn_t * subchn)
{
	int err;
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);

	if ((err = snd_pcm_dma_alloc(subchn, gus->gf1.dma2ptr, "GF1 PCM - record")) < 0)
		return err;
	gus->gf1.interrupt_handler_dma_read = snd_gf1_pcm_interrupt_dma_read;
	gus->pcm_cap_subchn = subchn;
	subchn->runtime->hw = &snd_gf1_pcm_capture;
	return 0;
}

static int snd_gf1_pcm_capture_close(void *private_data,
				      snd_pcm_subchn_t * subchn)
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, -ENXIO);

	gus->pcm_cap_subchn = NULL;
	snd_gf1_set_default_handlers(gus, SND_GF1_HANDLER_DMA_READ);
	snd_pcm_dma_free(subchn);
	return 0;
}

static void snd_gf1_pcm_free(void *private_data)
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, private_data, );
	gus->pcm = NULL;
}

static int snd_gf1_pcm_volume_level(snd_kmixer_element_t *element, int w_flag, int *voices) 
{
	snd_gus_card_t *gus = snd_magic_cast(snd_gus_card_t, element->private_data, -ENXIO);
	unsigned long flags;
	unsigned short vol;
	int change = 0, idx;
	gus_pcm_private_t *pcmp;
	snd_gus_voice_t *pvoice;

	spin_lock_irqsave(&gus->pcm_volume_level_lock, flags);
	if (!w_flag) {
		voices[0] = gus->gf1.pcm_volume_level_left1;
		voices[1] = gus->gf1.pcm_volume_level_right1;
	} else {
		change = voices[0] != gus->gf1.pcm_volume_level_left1 ||
		         voices[1] != gus->gf1.pcm_volume_level_right1;
		gus->gf1.pcm_volume_level_left1 = voices[0];
		gus->gf1.pcm_volume_level_right1 = voices[1];
		gus->gf1.pcm_volume_level_left = snd_gf1_lvol_to_gvol_raw(voices[0] << 9) << 4;
		gus->gf1.pcm_volume_level_right = snd_gf1_lvol_to_gvol_raw(voices[1] << 9) << 4;
	}
	spin_unlock_irqrestore(&gus->pcm_volume_level_lock, flags);
	if (!change)
		return 0;
	/* are we active? */
	spin_lock_irqsave(&gus->voice_alloc, flags);
	for (idx = 0; idx < 32; idx++) {
		pvoice = &gus->gf1.voices[idx];
		if (!pvoice->pcm)
			continue;
		pcmp = snd_magic_cast(gus_pcm_private_t, pvoice->private_data, -ENXIO);
		if (!(pcmp->flags & SND_GF1_PCM_PFLG_ACTIVE))
			continue;
		/* load real volume - better precision */
		spin_lock_irqsave(&gus->reg_lock, flags);
		snd_gf1_select_voice(gus, pvoice->number);
		snd_gf1_ctrl_stop(gus, SND_GF1_VB_VOLUME_CONTROL);
		vol = pvoice == pcmp->pvoices[0] ? gus->gf1.pcm_volume_level_left : gus->gf1.pcm_volume_level_right;
		snd_gf1_write16(gus, SND_GF1_VW_VOLUME, vol);
		pcmp->final_volume = 1;
		spin_unlock_irqrestore(&gus->reg_lock, flags);
	}
	spin_unlock_irqrestore(&gus->voice_alloc, flags);
	return change;
}

static int snd_gus_mixer_group_pcm(snd_kmixer_group_t * group,
				   snd_kmixer_file_t * file,
				   int w_flag,
				   snd_mixer_group_t * ugroup)
{
	snd_gus_card_t *codec = snd_magic_cast(snd_gus_card_t, group->private_data, -ENXIO);
	int voices[2];
	int change = 0;

	if (!w_flag) {
		ugroup->caps = SND_MIXER_GRPCAP_VOLUME;
		ugroup->channels = SND_MIXER_CHN_MASK_STEREO;
		snd_gf1_pcm_volume_level(codec->me_vol_pcm, 0, voices);
		ugroup->volume.names.front_left = voices[0];
		ugroup->volume.names.front_right = voices[1];
		ugroup->min = 0;
		ugroup->max = 127;
	} else {
		voices[0] = ugroup->volume.names.front_left & 127;
		voices[1] = ugroup->volume.names.front_right & 127;
		if (snd_gf1_pcm_volume_level(codec->me_vol_pcm, 1, voices) > 0) {
			snd_mixer_element_value_change(file, codec->me_vol_pcm, 0);
			change = 1;
		}
	}
	return change;
}

int snd_gf1_pcm_new(snd_gus_card_t * gus, snd_kmixer_t * mixer,
		    snd_kmixer_element_t * parent, int pcm_dev,
		    snd_pcm_t ** rpcm)
{
        static struct snd_mixer_element_volume1_range pcm_range[2] = {
		{0, 127, -9600, 0},
		{0, 127, -9600, 0}
	};
	snd_card_t *card;
	snd_pcm_t *pcm;
	snd_kmixer_group_t *group;
	int err;

	*rpcm = NULL;
	card = gus->card;
	err = snd_pcm_new(card,
			  gus->interwave ? "AMD InterWave" : "GF1",
			  pcm_dev,
			  gus->gf1.pcm_voices / 2,
			  !gus->interwave && !gus->ess_flag ? 1 : 0,
			  &pcm);
	if (err < 0)
		return err;
	pcm->private_data = gus;
	pcm->private_free = snd_gf1_pcm_free;
	/* playback setup */
	pcm->chn[SND_PCM_CHANNEL_PLAYBACK].private_data = gus;
	pcm->chn[SND_PCM_CHANNEL_PLAYBACK].open = snd_gf1_pcm_playback_open;
	pcm->chn[SND_PCM_CHANNEL_PLAYBACK].close = snd_gf1_pcm_playback_close;
	
	pcm->info_flags = SND_PCM_INFO_PLAYBACK;
	if (!gus->interwave && !gus->ess_flag) {
		/* capture setup */
		pcm->chn[SND_PCM_CHANNEL_CAPTURE].private_data = gus;
		pcm->chn[SND_PCM_CHANNEL_CAPTURE].open = snd_gf1_pcm_capture_open;
		pcm->chn[SND_PCM_CHANNEL_CAPTURE].close = snd_gf1_pcm_capture_close;
		pcm->info_flags |= SND_PCM_INFO_CAPTURE;
		if (gus->gf1.dma1ptr != gus->gf1.dma2ptr)
			pcm->info_flags |= SND_PCM_INFO_DUPLEX;
	}
	strcpy(pcm->name, pcm->id);
	if (gus->interwave) {
		sprintf(pcm->name + strlen(pcm->name), " rev %c", gus->revision + 'A');
	}
	strcat(pcm->name, " (synth)");
	gus->pcm = pcm;
	if ((group = snd_mixer_lib_group_ctrl(mixer, SND_MIXER_IN_PCM, pcm_dev, gus->ics_flag || gus->card->type == SND_CARD_TYPE_GUS_ACE ? SND_MIXER_OSS_PCM : SND_MIXER_OSS_ALTPCM, snd_gus_mixer_group_pcm, gus)) == NULL)
		printk("Oops. Can't register the PCM group for GF1 PCM.");
	if ((gus->me_playback = snd_mixer_lib_pcm1(mixer, SND_MIXER_ELEMENT_PLAYBACK, pcm_dev, SND_MIXER_ETYPE_PLAYBACK1, 1, &pcm_dev)) == NULL)
		printk("Oops. Can't register the playback mixer element for GF1 PCM.");
	if ((gus->me_vol_pcm = snd_mixer_lib_volume1(mixer, "PCM Volume", pcm_dev, 2, pcm_range, snd_gf1_pcm_volume_level, gus)) == NULL)
		printk("Oops. Can't register the PCM Volume mixer element for GF1 PCM.");
	if (group && gus->me_vol_pcm)
		snd_mixer_group_element_add(mixer, group, gus->me_vol_pcm);
	if (gus->me_playback && gus->me_vol_pcm) {
		snd_mixer_element_route_add(mixer, gus->me_playback, gus->me_vol_pcm);
		snd_mixer_element_route_add(mixer, gus->me_vol_pcm, parent);
	}
	*rpcm = pcm;
	return 0;
}

