/*
 *   ALSA sequencer Timing queue handling
 *   Copyright (c) 1998-1999 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.
 *
 * MAJOR CHANGES
 *   Nov. 13, 1999	Takashi Iwai <iwai@ww.uni-erlangen.de>
 *     - Queues are allocated dynamically via ioctl.
 *     - When owner client is deleted, all owned queues are deleted, too.
 *     - Owner of unlocked queue is kept unmodified even if it is
 *	 manipulated by other clients.
 *     - Owner field in SET_QUEUE_OWNER ioctl must be identical with the
 *       caller client.  i.e. Changing owner to a third client is not
 *       allowed.
 */

#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"


/* list of allocated queues */
static queue_t *queue_list = NULL;
static rwlock_t queue_list_lock = RW_LOCK_UNLOCKED;
/* number of queues allocated */
static int num_queues = 0;

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

/* assign queue id and insert to list */
/* NOTE: this function cannot be called from interrupt */
static void queue_list_add(queue_t *q)
{
	queue_t *nextq, *prevq;
	int id;
	unsigned long flags;

	write_lock_irqsave(&queue_list_lock, flags);
	id = 0;
	prevq = NULL;
	for (nextq = queue_list; nextq; prevq = nextq, nextq = nextq->next) {
		if (id < nextq->queue)
			break;
		id = nextq->queue + 1;
	}
	q->queue = id;
	q->next = nextq;
	if (prevq)
		prevq->next = q;
	else
		queue_list = q;
	num_queues++;
	write_unlock_irqrestore(&queue_list_lock, flags);
}

/* remove the given queue from list */
/* NOTE: this function cannot be called from interrupt */
static void queue_list_remove(queue_t *q)
{
	queue_t *prevq;
	unsigned long flags;

	write_lock_irqsave(&queue_list_lock, flags);
	if (queue_list == q) {
		queue_list = q->next;
		num_queues--;
	} else {
		for (prevq = queue_list; prevq; prevq = prevq->next) {
			if (prevq->next == q) {
				prevq->next = q->next;
				num_queues--;
				break;
			}
		}
	}
	write_unlock_irqrestore(&queue_list_lock, flags);
}

/* Remove all queues owned by client from the linked list
 * This returns the linked-list of deleted queues
 */
/* NOTE: this function cannot be called from interrupt */
static queue_t *queue_list_remove_client(int client)
{
	queue_t *q, *prevq, *nextq, *deleteq;
	unsigned long flags;

	write_lock_irqsave(&queue_list_lock, flags);
	deleteq = NULL;
	prevq = NULL;
	for (q = queue_list; q; prevq = q, q = nextq) {
		nextq = q->next;
		spin_lock(&q->owner_lock);
		if (q->owner == client) {
			if (prevq)
				prevq->next = nextq;
			else
				queue_list = nextq;
			num_queues--;
			q->next = deleteq;
			deleteq = q;
		}
		spin_unlock(&q->owner_lock);
	}
	write_unlock_irqrestore(&queue_list_lock, flags);

	return deleteq;
}

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

/* create new queue (constructor) */
static queue_t *queue_new(int owner, int locked)
{
	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;
	}

	spin_lock_init(&q->owner_lock);
	spin_lock_init(&q->clients_lock);
	spin_lock_init(&q->check_lock);
	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 = owner;
	q->locked = locked;
	q->klocked = 0;

	q->queue = -1;
	q->next = NULL;

	return q;
}

/* delete queue (destructor) */
static void queue_delete(queue_t *q)
{
	/* stop and release the timer */
	snd_seq_timer_stop(q->timer);
	snd_seq_timer_close(q);

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

	snd_kfree(q);
}


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

/* setup queues */
void __init snd_seq_queues_init(void)
{
	/* NOTHING */
}

/* delete all existing queues */
void __exit snd_seq_queues_delete(void)
{
	queue_t *q, *nextq;
	unsigned long flags;

	/* clear list */
	write_lock_irqsave(&queue_list_lock, flags);
	q = queue_list;
	queue_list = NULL;
	num_queues = 0;
	write_unlock_irqrestore(&queue_list_lock, flags);

	for (; q; q = nextq) {
		nextq = q->next;
		queue_delete(q);
	}
}

/* allocate a new queue -
 * return queue index value or negative value for error
 */
int snd_seq_queue_alloc(int client, int locked)
{
	queue_t *q;

	q = queue_new(client, locked);
	if (q == NULL)
		return -ENOMEM;
	queue_list_add(q); /* add to list */
	snd_seq_queue_use(q->queue, client, 1); /* use this queue */

	return q->queue;
}


/* delete a queue - queue must be owned by the client */
int snd_seq_queue_delete(int client, int queueid)
{
	queue_t *q;
	unsigned long flags;

	q = queueptr(queueid);
	if (q == NULL)
		return -EINVAL;

	spin_lock_irqsave(&q->owner_lock, flags);
	if (q->owner != client) {
		spin_unlock_irqrestore(&q->owner_lock, flags);
		return -EPERM;
	}
	q->klocked = 1;
	spin_unlock_irqrestore(&q->owner_lock, flags);

	queue_list_remove(q);

	queue_delete(q);

	return 0;
}


/* return pointer to queue structure for specified id */
queue_t *queueptr(int queueid)
{
	queue_t *q;

	/* just a linear search - well, hash table would be far better.. */
	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		if (q->queue == queueid)
			break;
	}
	read_unlock(&queue_list_lock);
	return q;
}


/* return the (first) queue matching with the specified name */
queue_t *snd_seq_queue_find_name(char *name)
{
	queue_t *q;

	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		if (strncpy(q->name, name, sizeof(q->name)) == 0)
			break;
	}
	read_unlock(&queue_list_lock);
	return q;
}


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

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.time)) {
			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);
}


/* 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.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.time, &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_queue(q, atomic, hop);

	return 0;
}


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

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

/* check if the client has permission to modify queue parameters.
 * if it does, lock the queue
 */
static int queue_access_lock(queue_t *q, int client)
{
	unsigned long flags;
	int access_ok;
	
	spin_lock_irqsave(&q->owner_lock, flags);
	access_ok = check_access(q, client);
	if (access_ok)
		q->klocked = 1;
	spin_unlock_irqrestore(&q->owner_lock, flags);
	return access_ok;
}

/* unlock the queue */
static inline void queue_access_unlock(queue_t *q)
{
	unsigned long flags;

	spin_lock_irqsave(&q->owner_lock, flags);
	q->klocked = 0;
	spin_unlock_irqrestore(&q->owner_lock, flags);
}

/* exported - only checking permission */
int snd_seq_queue_check_access(int queueid, int client)
{
	queue_t *q = queueptr(queueid);
	int access_ok;
	unsigned long flags;

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

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

/*
 * access to queue's timer
 */

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

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	snd_seq_timer_stop(q->timer);
	queue_access_unlock(q);

	return 0;
}


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

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	snd_seq_prioq_leave(q->tickq, client, 1);
	snd_seq_prioq_leave(q->timeq, client, 1);
	snd_seq_timer_start(q->timer);
	queue_access_unlock(q);
	
	return 0;
}


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

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	snd_seq_timer_continue(q->timer);
	queue_access_unlock(q);

	return 0;
}


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

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	result = snd_seq_timer_set_tempo(q->timer, tempo);
	queue_access_unlock(q);

	return result;
}


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

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	result = snd_seq_timer_set_ppq(q->timer, ppq);
	queue_access_unlock(q);

	return result;
}


int snd_seq_queue_timer_set_position_tick(int queueid, int client, snd_seq_tick_time_t position)
{
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	result = snd_seq_timer_set_position_tick(q->timer, position);
	queue_access_unlock(q);

	return result;
}


int snd_seq_queue_timer_set_position_time(int queueid, int client, snd_seq_real_time_t position)
{
	queue_t *q = queueptr(queueid);
	int result = 0;

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	result = snd_seq_timer_set_position_time(q->timer, position);
	queue_access_unlock(q);

	return result;
}



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

/*
 * change queue's owner and permission
 */
int snd_seq_queue_set_owner(int queueid, int client, int locked)
{
	queue_t *q = queueptr(queueid);

	if (q == NULL)
		return -EINVAL;

	if (! queue_access_lock(q, client))
		return -EPERM;

	q->locked = locked ? 1 : 0;
	q->owner = client;
	queue_access_unlock(q);

	return 0;
}


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

/* open timer -
 * q->use mutex should be down before calling this function to avoid
 * confliction with snd_seq_queue_use()
 */
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;
}

/* close timer -
 * q->use mutex should be down before calling this function
 */
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;
}

/* use or unuse this queue -
 * if it is the first client, starts the timer.
 * if it is not longer used by any clients, stop the timer.
 */
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;
}

/*
 * check if queue is used by the client
 * return negative value if the queue is invalid.
 * return 0 if not used, 1 if used.
 */
int snd_seq_queue_is_used(int queueid, int client)
{
	queue_t *q;

	q = queueptr(queueid);
	if (q == NULL)
		return -EINVAL; /* invalid queue */
	return test_bit(client, &q->clients_bitmap) ? 1 : 0;
}


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

/* notification that client has left the system -
 * stop the timer on all queues owned by this client
 */
void snd_seq_queue_client_termination(int client)
{
	unsigned long flags;
	queue_t *q;

	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		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);
		}
	}
	read_unlock(&queue_list_lock);
}

/* final stage notification -
 * remove cells for no longer exist client (for non-owned queue)
 * or delete this queue (for owned queue)
 */
void snd_seq_queue_client_leave(int client)
{
	queue_t *q, *nextq;

	/* extract own queues from queue list */
	q = queue_list_remove_client(client);

	/* delete own queues */
	for (; q; q = nextq) {
		nextq = q->next;
		queue_delete(q);
	}

	/* remove cells from existing queues -
	 * they are not owned by this client
	 */
	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		if (! test_bit(client, q->clients_bitmap))
			continue;
		snd_seq_prioq_leave(q->tickq, client, 0);
		snd_seq_prioq_leave(q->timeq, client, 0);
		snd_seq_queue_use(q->queue, client, 0);
	}
	read_unlock(&queue_list_lock);
}


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

/* remove cells from all queues */
void snd_seq_queue_client_leave_cells(int client)
{
	queue_t *q;

	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		snd_seq_prioq_leave(q->tickq, client, 0);
		snd_seq_prioq_leave(q->timeq, client, 0);
	}
	read_unlock(&queue_list_lock);
}

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

	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		if (! test_bit(client, q->clients_bitmap))
			continue;

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

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


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

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

	read_lock(&queue_list_lock);
	for (q = queue_list; q; q = q->next) {
		tmr = q->timer;

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

		snd_iprintf(buffer, "queue %d: [%s]\n", q->queue, q->name);
		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);
#if 0
		{
			snd_seq_event_cell_t *cell;
			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));
		}
#endif
		snd_iprintf(buffer, "\n");
	}
	read_unlock(&queue_list_lock);
}
