#ifndef __QNXNTO__

#include "driver.h"

pid_t intr_thread_pids[SND_CARDS];

void 
snd_enable_irq(snd_irq_t *irq)
{
	if ( irq->id == 0 ) {
		if ( x_attach_interrupts(irq) == 0 ) {
			snd_printd("IRQ %d Enabled - %d\n",irq->irq, irq->id);
		}
	}
}


void 
snd_disable_irq(snd_irq_t *irq)
{
        qnx_hint_mask(irq->irq, 2);
	snd_printd("IRQ %d Disabled - %d\n", irq->irq, irq->id);
}


static void
signal_handler(int sig)
{
        /* should we blow away the parent? */
        
        if (parent)
                kill(parent, SIGTERM);
        _endthread();

}


static void 
x_interrupt_thread(void *param)
{
        struct sched_param 	sp;
        pid_t			pid;
        struct snd_stru_irq	*irqp;

	irqp = (struct snd_stru_irq *) param;
        
        sched_getparam(0, &sp);
        sp.sched_priority += 5;

        if (sched_setscheduler(0, SCHED_FIFO, &sp) < 0) {
                perror("sched_setscheduler");
                _endthread();
        }

	setup_signal_handling(signal_handler);
        
        while (1) {

                pid = Receive(0, NULL, 0);

                if (pid < 0) {
                        perror("Irq thread: Receive");
                        continue;
                }

		irqp->handler(irqp->dev_id);

		/* renable the PIC */

		if (irqp->irq < 8)
			outp(IMR1, inp(IMR1) & ~(1 << irqp->irq));
		else
			outp(IMR2, inp(IMR2) & ~(1 << (irqp->irq - 8)));

        }	                
}


static int 
x_attach_interrupts(snd_irq_t *irq)
{
        int i;

        if((irq->tid = _beginthread(x_interrupt_thread, 
                                    NULL, 4096, irq)) < 0) {
                perror("_beginthread");
                return (errno);
        }
        
        /* save away the thread pid so we can blow it
         * away if the main thread is sigkilled
         */
        
        for (i = 0; i < SND_CARDS; i++) {
                if (intr_thread_pids[i] == 0)
                        break;
        }
        intr_thread_pids[i] = irq->tid;
        
        if (hint_connect(irq->irq, irq) < 0) {
                snd_printk("Unable to attach irq %i\n", irq->irq);
                return (errno);
        }
        
        return (0);
}


void
destroy_intr_thread(pid_t pid)
{
        int i;

        kill(pid, SIGTERM);
        for (i = 0; i < SND_CARDS; i++) {
                if (intr_thread_pids[i] == pid)
                        break;
        }
        if (i < SND_CARDS) 
                intr_thread_pids[i] = 0;
}


#endif
