/*
 *   ALSA sequencer Timing queue handling
 *   Copyright (c) 1998 by Frank van de Pol <frank@vande-pol.demon.nl>
 *
 *   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.
 *
 */

#include "../../include/driver.h"

#include "seq_memory.h"
#include "seq_queue.h"
#include "seq_clientmgr.h"
#include "seq_fifo.h"
#include "seq_timer.h"
#include "seq_info.h"


/* root for the queues */
static queue_t *queuetab[SND_SEQ_MAX_QUEUES];

/* number of queues allocated */
static int num_queues = 0;


/* FIXME: should add list of active queues (for optimisation of timer), sort of 'run queue' */



/* setup queues */
void snd_seq_queues_init(int num)
{
	int c;
	queue_t *q;

	if (num > SND_SEQ_MAX_QUEUES) {
		snd_printd("Limiting number of timing queues to %d (SND_SEQ_MAX_QUEUES)\n", SND_SEQ_MAX_QUEUES);
		num = SND_SEQ_MAX_QUEUES;
	}
	num_queues = num;

	for (c = 0; c < num; c++) {
		q = snd_seq_queue_new();
		queuetab[q->queue = c] = q;
	}
}

/* delete queues */
void snd_seq_queues_delete(void)
{
	int c;

	for (c = 0; c < num_queues; c++)
		snd_seq_queue_delete(&queuetab[c]);

	num_queues = 0;
}


/* create new queue (constructor) */
queue_t *snd_seq_queue_new(void)
{
	queue_t *q;

	q = snd_kcalloc(sizeof(queue_t), GFP_KERNEL);
	if (q == NULL) {
		snd_printd("malloc failed for snd_seq_queue_new()\n");
		return NULL;
	}

	q->owner_lock = SPIN_LOCK_UNLOCKED;
	q->clients_lock = SPIN_LOCK_UNLOCKED;
	q->check_lock = SPIN_LOCK_UNLOCKED;
	init_MUTEX(&q->use_mutex);

	q->tickq = snd_seq_prioq_new();
	q->timeq = snd_seq_prioq_new();
	q->timer = snd_seq_timer_new();

	q->owner = SEQ_QUEUE_NO_OWNER;
	q->locked = q->klocked = 0;
	
	return q;
}

/* delete queue (destructor) */
void snd_seq_queue_delete(queue_t ** queue)
{
	queue_t *q = *queue;

	*queue = NULL;

	if (q == NULL) {
		snd_printd("oops: snd_seq_queue_delete() called with NULL queue\n");
		return;
	}
	if (q->owner != SEQ_QUEUE_NO_OWNER) {
		snd_printd("warning: snd_seq_queue_delete(), timer is still owned by client #%d\n", q->owner);
	}
	q->locked = 0;

	/* release resources... */
	snd_seq_prioq_delete(&q->tickq);
	snd_seq_prioq_delete(&q->timeq);
	snd_seq_timer_delete(&q->timer);

	snd_kfree(q);
}



/* return pointer to queue structure for specified id */
queue_t *queueptr(int queueid)
{
	if (queueid < 0 || queueid >= num_queues) {
		snd_printd("Seq: oops. Trying to get pointer to queue %d\n", queueid);
		return NULL;
	}
	return queuetab[queueid];
}




/* -------------------------------------------------------- */

void snd_seq_check_queue(queue_t *q, int atomic, int hop)
{
	unsigned long flags;
	int dequeue = SND_SEQ_MAX_DEQUEUE;
	int rc;
	snd_seq_event_cell_t *cell;

	if (q == NULL)
		return;

	/* make this function non-reentrant */
	spin_lock_irqsave(&q->check_lock, flags);
	if (q->check_blocked) {
		q->check_again = 1;
		spin_unlock_irqrestore(&q->check_lock, flags);
		return;		/* other thread is already checking queues */
	}
	q->check_blocked = 1;
	spin_unlock_irqrestore(&q->check_lock, flags);

      __again:

	/* Process tick queue... */

	/* limit the number of elements dequeued per pass to save the machine from lockups */
	while (dequeue > 0) {

		cell = snd_seq_prioq_cell_peek(q->tickq);
		if (cell == NULL)
			break;
		if (snd_seq_compare_tick_time(&q->timer->cur_tick, &cell->event.time.tick)) {
			cell = snd_seq_prioq_cell_out(q->tickq);
			if (cell != NULL) {
				rc = snd_seq_dispatch_event(cell, atomic, hop);
				if (rc > 0)
					dequeue -= rc;
			}
		} else {
			/* event remains in the queue */
			break;
		}
	}


	/* Process time queue... */

	/* limit the number of elements dequeued per pass to save the machine from lockups */
	while (dequeue > 0) {
		cell = snd_seq_prioq_cell_peek(q->timeq);
		if (cell == NULL)
			break;
		if (snd_seq_compare_real_time(&q->timer->cur_time, &cell->event.time.real)) {
			cell = snd_seq_prioq_cell_out(q->timeq);
			if (cell != NULL) {
				rc = snd_seq_dispatch_event(cell, atomic, hop);
				if (rc > 0)
					dequeue -= rc;
			}

		} else {
			/* event remains in the queue */
			break;
		}
	}

	/* free lock */
	spin_lock_irqsave(&q->check_lock, flags);
	if (q->check_again) {
		q->check_again = 0;
		spin_unlock_irqrestore(&q->check_lock, flags);
		goto __again;
	}
	q->check_blocked = 0;
	spin_unlock_irqrestore(&q->check_lock, flags);
}

/* check queues and dispatch events */
void snd_seq_check_queues(int atomic, int hop)
{
	int c;

	/* NOTE: this is not efficient for large number of queues! */
	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		queue_t *q = queueptr(c);

		if (q == NULL)
			continue;
		snd_seq_check_queue(q, atomic, hop);
	}
}


/* enqueue a event to singe queue */
int snd_seq_enqueue_event(snd_seq_event_cell_t *cell, int atomic, int hop)
{
	int dest;
	queue_t *q;

	if (cell == NULL) {
		snd_printd("oops: snd_seq_enqueue_event() called with NULL cell\n");
		return -EINVAL;
	}
	dest = cell->event.dest.queue;		/* dest queue */
	q = queueptr(dest);
	if (q == NULL)
		return -EINVAL;
	/* handle relative time stamps, convert them into absolute */
	if ((cell->event.flags & SND_SEQ_TIME_MODE_MASK) == SND_SEQ_TIME_MODE_REL) {
		switch (cell->event.flags & SND_SEQ_TIME_STAMP_MASK) {
			case SND_SEQ_TIME_STAMP_TICK:
				cell->event.time.tick += q->timer->cur_tick;
				cell->event.flags &= ~SND_SEQ_TIME_STAMP_MASK;
				cell->event.flags |= SND_SEQ_TIME_STAMP_TICK;
				break;

			case SND_SEQ_TIME_STAMP_REAL:
				snd_seq_inc_real_time(&cell->event.time.real, &q->timer->cur_time);
				cell->event.flags &= ~SND_SEQ_TIME_STAMP_MASK;
				cell->event.flags |= SND_SEQ_TIME_STAMP_REAL;
				break;
		}
	}
	/* enqueue event in the real-time or midi queue */
	switch (cell->event.flags & SND_SEQ_TIME_STAMP_MASK) {
		case SND_SEQ_TIME_STAMP_TICK:
			snd_seq_prioq_cell_in(q->tickq, cell);
			break;

		case SND_SEQ_TIME_STAMP_REAL:
			snd_seq_prioq_cell_in(q->timeq, cell);
			break;
	}

	/* trigger dispatching */
	snd_seq_check_queues(atomic, hop);

	return 0;
}



/* check if client has access to queue's parameters, return 1 if client is
   allowed to make changes to the queue */

static inline int check_access(queue_t * q, int client)
{
	return ((!q->locked && !q->klocked) || (q->owner == client));
}

int snd_seq_queue_check_access(int queueid, int client)
{
	queue_t *q = queueptr(queueid);

	if (q) {
		return check_access(q, client);
	} else {
		return 0;
	}
}


/* access to queue's timer */
int snd_seq_queue_timer_stop(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 0;
		spin_unlock_irqrestore(&q->owner_lock, flags);
		snd_seq_timer_stop(q->timer);
	} else {
		spin_unlock_irqrestore(&q->owner_lock, flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_start(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 1;
		spin_unlock_irqrestore(&q->owner_lock, flags);
		snd_seq_prioq_leave(q->tickq, client, 1);
		snd_seq_prioq_leave(q->timeq, client, 1);
		snd_seq_timer_start(q->timer);
	} else {
		spin_unlock_irqrestore(&q->owner_lock, flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_continue(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		q->owner = client;
		q->klocked = 1;
		spin_unlock_irqrestore(&q->owner_lock, flags);
		snd_seq_timer_continue(q->timer);
	} else {
		spin_unlock_irqrestore(&q->owner_lock, flags);
		return -EPERM;
	}
	return 0;
}


int snd_seq_queue_timer_set_tempo(int queueid, int client, int tempo)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		result = snd_seq_timer_set_tempo(q->timer, tempo);
		if (result >= 0)
			q->owner = client;
	} else {
		result = -EPERM;
	}
	spin_unlock_irqrestore(&q->owner_lock, flags);
	return result;
}

int snd_seq_queue_timer_set_ppq(int queueid, int client, int ppq)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		result = snd_seq_timer_set_ppq(q->timer, ppq);
		if (result >= 0)
			q->owner = client;
	} else {
		result = -EPERM;
	}
	spin_unlock_irqrestore(&q->owner_lock, flags);
	return result;
}


int snd_seq_queue_set_owner(int queueid, int client)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		q->owner = client;
	} else {
		result = -EPERM;
	}
	spin_unlock_irqrestore(&q->owner_lock, flags);
	return result;
}



int snd_seq_queue_set_locked(int queueid, int client, int locked)
{
	unsigned long flags;
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (!q)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (check_access(q, client)) {
		q->locked = locked ? 1 : 0;
		q->owner = client;
	} else {
		result = -EPERM;
	}
	spin_unlock_irqrestore(&q->owner_lock, flags);
	return result;
}

int snd_seq_queue_timer_open(int queueid)
{
	int result = 0;
	queue_t *queue;
	timer_t *tmr;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	tmr = queue->timer;
	switch (tmr->type) {
	case SND_SEQ_TIMER_MASTER:
	case SND_SEQ_TIMER_SLAVE:
		if ((result = snd_seq_timer_open(queue)) < 0) {
			snd_seq_timer_defaults(tmr);
			return snd_seq_timer_open(queue);
		}
		break;
	case SND_SEQ_TIMER_MIDI_CLOCK:
	case SND_SEQ_TIMER_MIDI_TICK:
		if ((result = snd_seq_timer_midi_open(queue)) < 0) {
			snd_seq_timer_defaults(tmr);
			return snd_seq_timer_open(queue);
		}
		break;
	default:
		return -EINVAL;
	}
	return result;
}

int snd_seq_queue_timer_close(int queueid)
{
	queue_t *queue;
	timer_t *tmr;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	tmr = queue->timer;
	switch (tmr->type) {
	case SND_SEQ_TIMER_MASTER:
	case SND_SEQ_TIMER_SLAVE:
		snd_seq_timer_close(queue);
		break;
	case SND_SEQ_TIMER_MIDI_CLOCK:
	case SND_SEQ_TIMER_MIDI_TICK:
		snd_seq_timer_midi_close(queue);
		break;
	default:
		return -EINVAL;
	}
	return 0;
}

int snd_seq_queue_use(int queueid, int client, int use)
{
	queue_t *queue;
	unsigned long flags;

	queue = queueptr(queueid);
	if (queue == NULL)
		return -EINVAL;
	down(&queue->use_mutex);
	spin_lock_irqsave(&queue->clients_lock, flags);
	if (use) {
		if (!test_and_set_bit(client, &queue->clients_bitmap))
			queue->clients++;
	} else {
		if (test_and_clear_bit(client, &queue->clients_bitmap))
			queue->clients--;
	}
	spin_unlock_irqrestore(&queue->clients_lock, flags);
	if (queue->clients) {
		if (use && queue->clients == 1)
			snd_seq_timer_defaults(queue->timer);
		snd_seq_timer_open(queue);
	} else {
		snd_seq_timer_close(queue);
	}
	up(&queue->use_mutex);
	return 0;
}


/* notification that client has left the system */
void snd_seq_queue_client_termination(int client)
{
	unsigned long flags;
	queue_t *q;
	int c;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		spin_lock_irqsave(&q->owner_lock, flags);
		if (q->owner == client) {
			q->klocked = 1;
		}
		spin_unlock_irqrestore(&q->owner_lock, flags);
		if (q->owner == client) {
			if (q->timer->running)
				snd_seq_timer_stop(q->timer);
			snd_seq_timer_reset(q->timer);
		}
	}
}

/* final stage notification - remove cells for no longer exist client */
void snd_seq_queue_client_leave(int client)
{
	unsigned long flags;
	int c;
	queue_t *q;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		snd_seq_prioq_leave(q->tickq, client, q->owner == client);
		snd_seq_prioq_leave(q->timeq, client, q->owner == client);
		spin_lock_irqsave(&q->owner_lock, flags);
		if (q->owner == client) {
			q->owner = SEQ_QUEUE_NO_OWNER;
			q->locked = 0;
			q->klocked = 0;
		}
		spin_unlock_irqrestore(&q->owner_lock, flags);
		snd_seq_queue_use(c, client, 0);
	}
}

/* remove cells only */
void snd_seq_queue_client_leave_cells(int client)
{
	int c;
	queue_t *q;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		snd_seq_prioq_leave(q->tickq, client, 0);
		snd_seq_prioq_leave(q->timeq, client, 0);
	}
}

/* remove cells based on flush criteria */
void snd_seq_queue_remove_cells(int client, snd_seq_remove_events_t *info)
{
	int c;
	queue_t *q;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (!q)
			continue;
		if (! test_bit(client, q->clients_bitmap))
			continue;

		if ((info->remove_mode & SND_SEQ_REMOVE_DEST)
				&& q->queue != info->dest.queue) {
			continue;
		}

		snd_seq_prioq_remove_events(q->tickq, client, info);
		snd_seq_prioq_remove_events(q->timeq, client, info);
	}
}

/* exported to seq_info.c */
void snd_seq_info_queues_read(snd_info_buffer_t * buffer, void *private_data)
{
	int c;
	int bpm;
	queue_t *q;
	timer_t *tmr;
	snd_seq_event_cell_t *cell;

	for (c = 0; c < SND_SEQ_MAX_QUEUES; c++) {
		q = queueptr(c);
		if (q == NULL)
			continue;
		tmr = q->timer;

		if (tmr->tempo)
			bpm = 60000000 / tmr->tempo;
		else
			bpm = 0;

		snd_iprintf(buffer, "queue %d:\n", c);
		snd_iprintf(buffer, "owned by client    : %d\n", q->owner);
		snd_iprintf(buffer, "lock status        : %s\n", q->locked ? "Locked" : "Free");
		snd_iprintf(buffer, "queued time events : %d\n", snd_seq_prioq_avail(q->timeq));
		snd_iprintf(buffer, "queued tick events : %d\n", snd_seq_prioq_avail(q->tickq));
		snd_iprintf(buffer, "timer state        : %s\n", tmr->running ? "Running" : "Stopped");
		snd_iprintf(buffer, "timer PPQ          : %d\n", tmr->ppq);
		snd_iprintf(buffer, "current tempo      : %d\n", tmr->tempo);
		snd_iprintf(buffer, "current BPM        : %d\n", bpm);
		snd_iprintf(buffer, "current time       : %d.%09d s\n", tmr->cur_time.tv_sec, tmr->cur_time.tv_nsec);
		snd_iprintf(buffer, "current tick       : %d\n", tmr->cur_tick);
		cell = snd_seq_prioq_cell_peek(q->timeq);
		snd_iprintf(buffer, "queue top (time)   : %d.%09d s\n",
			    (cell ? cell->event.time.real.tv_sec : 0),
			    (cell ? cell->event.time.real.tv_nsec : 0));
		cell = snd_seq_prioq_cell_peek(q->tickq);
		snd_iprintf(buffer, "queue top (tick)   : %d\n",
			    (cell ? cell->event.time.tick : 0));
		snd_iprintf(buffer, "\n");
	}
}
