/*
 *  ALSA sequencer device management
 *  Copyright (c) 1999 by Takashi Iwai <iwai@ww.uni-erlangen.de>
 *
 *   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_MAIN_OBJECT_FILE
#include "../../include/driver.h"
#include "../../include/seq_device.h"
#ifdef CONFIG_KMOD
#include <linux/kmod.h>
#endif

MODULE_AUTHOR("Takashi Iwai <iwai@ww.uni-erlangen.de>");
MODULE_DESCRIPTION("ALSA sequencer device management");
MODULE_SUPPORTED_DEVICE("sound");

/*
 * constants
 */

#define ID_LEN	32

/*
 * registered device information
 */
struct snd_seq_device {
	/* device info */
	snd_card_t *card;
	int device;
	char id[ID_LEN];
	char name[80];
	void *arg;
	int size;

	/* allocated device */
	snd_seq_dev_entry_t hw;

	/* link to next device */
	snd_seq_device_t *next;
};


/*
 * driver list
 */
typedef struct ops_list ops_list_t;

/* driver state */
#define DRIVER_EMPTY	0
#define DRIVER_LOADED	(1<<0)
#define DRIVER_REQUEST	(1<<1)
#define DRIVER_LOCKED	(1<<2)

struct ops_list {
	char id[ID_LEN];
	int driver;	/* driver state */
	int used;

	/* operators */
	snd_seq_dev_ops_t ops;

	/* registred devices */
	snd_seq_device_t *devhead, *devtail;
	int num_devices;
	int num_init_devices;
	struct semaphore reg_mutex;

	ops_list_t *next;
};


static ops_list_t *opslist = NULL;
static int num_ops = 0;
static DECLARE_MUTEX(ops_mutex);

/*
 * prototypes
 */
static int init_device(snd_seq_device_t *dev, ops_list_t *ops);
static int free_device(snd_seq_device_t *dev, ops_list_t *ops);
static ops_list_t *find_driver(char *id);
static ops_list_t *create_driver(char *id);
static void free_driver_use(ops_list_t *ops);
static void remove_drivers(void);

/*
 * load all registered drivers (called from the seq module)
 */

void snd_seq_device_load_drivers(void)
{
#ifdef CONFIG_KMOD
	ops_list_t *ops;
	char modname[64];

	down(&ops_mutex);
	for (ops = opslist; ops; ops = ops->next) {
		if (! (ops->driver & DRIVER_LOADED) &&
		    ! (ops->driver & DRIVER_REQUEST)) {
			sprintf(modname, "snd-%s", ops->id);
			ops->driver |= DRIVER_REQUEST;
			request_module(modname);
		}
	}
	up(&ops_mutex);
#endif
}

/*
 * register a sequencer device
 * card = card info (NULL allowed)
 * device = device number (if any)
 * name = name of this device (NULL allowed)
 * id = id of driver
 * arg = optional argument: if size > 0, duplicated. otherwise just copied.
 * size = size of argument data.
 * result = return pointer (NULL allowed if unnecessary)
 */
int
snd_seq_device_register(snd_card_t *card, int device, char *name, char *id,
			void *arg, int size, snd_seq_device_t **result)
{
	snd_seq_device_t *dev;
	ops_list_t *ops;

	if (result)
		*result = NULL;

	if (id == NULL)
		return -EINVAL;

	dev = snd_kcalloc(sizeof(*dev), GFP_KERNEL);
	if (dev == NULL)
		return -ENOMEM;

	/* set up device info */
	dev->card = card;
	dev->device = device;
	if (name) {
		strncpy(dev->name, name, sizeof(dev->name) - 1);
		dev->name[sizeof(dev->name)-1] = 0;
	} else {
		if (card)
			sprintf(dev->name, "card %d: %s: %d", card->number, id, device);
		else
			sprintf(dev->name, "%s: %d", id, device);
	}

	strncpy(dev->id, id, sizeof(dev->id) - 1);
	dev->id[sizeof(dev->id) - 1] = 0;

	if (size > 0 && arg) {
		dev->arg = snd_kmalloc(size, GFP_KERNEL);
		if (dev->arg == NULL) {
			snd_kfree(dev);
			return -ENOMEM;
		}
		memcpy(dev->arg, arg, size);
	} else
		dev->arg = arg;
	dev->size = size;
	dev->next = NULL;

	ops = find_driver(id);
	if (ops == NULL) {
		ops = create_driver(id);
		if (ops == NULL) {
			if (dev->size > 0 && dev->arg)
				snd_kfree(dev->arg);
			snd_kfree(dev);
			return -ENOMEM;
		}
	}
	/* add this device to the list */
	down(&ops->reg_mutex);
	if (ops->devtail)
		ops->devtail->next = dev;
	else
		ops->devhead = dev;
	ops->devtail = dev;
	ops->num_devices++;
	up(&ops->reg_mutex);

	if (ops->driver & DRIVER_LOADED)
		/* initialize this device if possible */
		init_device(dev, ops);

	free_driver_use(ops);
	if (result)
		*result = dev;

	MOD_INC_USE_COUNT;
	return 0;
}


/*
 * find the matching device
 */
snd_seq_device_t *
snd_seq_device_find(snd_card_t *card, int device, char *id)
{
	ops_list_t *ops;
	snd_seq_device_t *dev;

	ops = find_driver(id);
	if (ops == NULL)
		return NULL;
	down(&ops->reg_mutex);
	for (dev = ops->devhead; dev; dev = dev->next) {
		if (dev->card == card && dev->device == device)
			break;
	}
	up(&ops->reg_mutex);
	free_driver_use(ops);

	return dev;
}


/*
 * unregister the existing device
 */
int
snd_seq_device_unregister(snd_seq_device_t *dev)
{
	ops_list_t *ops;
	snd_seq_device_t *prev, *p;

	if (dev == NULL)
		return -EINVAL;

	ops = find_driver(dev->id);
	if (ops == NULL)
		return -ENXIO;

	/* remove the device from the list */
	down(&ops->reg_mutex);
	prev = NULL;
	for (p = ops->devhead; p; prev = p, p = p->next) {
		if (p == dev) {
			if (prev)
				prev->next = p->next;
			else
				ops->devhead = p->next;
			if (ops->devtail == p)
				ops->devtail = prev;
			ops->num_devices--;
			break;
		}
	}
	if (p == NULL)
		snd_printk("seq_device: FATAL ERROR: can't find entry\n");
	up(&ops->reg_mutex);

	/* release device if already used */
	if (dev->hw)
		free_device(dev, ops);

	if (dev->size > 0 && dev->arg)
		snd_kfree(dev->arg);
	snd_kfree(dev);

	free_driver_use(ops);

	MOD_DEC_USE_COUNT;
	return 0;
}


/*
 * register device driver
 * id = driver id
 * entry = driver operators - duplicated to each instance
 */
int
snd_seq_device_register_driver(char *id, snd_seq_dev_ops_t *entry)
{
	snd_seq_device_t *dev;
	ops_list_t *ops;

	if (id == NULL || entry == NULL ||
	    entry->init_device == NULL || entry->free_device == NULL)
		return -EINVAL;

	ops = find_driver(id);
	if (ops == NULL) {
		ops = create_driver(id);
		if (ops == NULL)
			return -ENOMEM;
	}
	if (ops->driver & DRIVER_LOADED) {
		snd_printk("driver_register: driver '%s' already exists\n", id);
		free_driver_use(ops);
		return -EBUSY;
	}

	down(&ops->reg_mutex);
	/* copy driver operators */
	memcpy(&ops->ops, entry, sizeof(*entry));
	ops->driver |= DRIVER_LOADED;

	/* initialize existing devices if necessary */
	for (dev = ops->devhead; dev; dev = dev->next) {
		if (dev->hw == NULL)
			init_device(dev, ops);
	}
	up(&ops->reg_mutex);

	free_driver_use(ops);

	MOD_INC_USE_COUNT;
	return 0;
}


/*
 * create driver record
 */
static ops_list_t *
create_driver(char *id)
{
	ops_list_t *ops;

	ops = snd_kcalloc(sizeof(*ops), GFP_KERNEL);
	if (ops == NULL)
		return ops;

	/* set up driver entry */
	strncpy(ops->id, id, sizeof(ops->id) - 1);
	ops->id[sizeof(ops->id) - 1] = 0;
	init_MUTEX(&ops->reg_mutex);
	ops->driver = DRIVER_EMPTY;
	/* lock this instance */
	ops->used = 1;

	/* register driver entry */
	down(&ops_mutex);
	ops->next = opslist;
	opslist = ops;
	num_ops++;
	up(&ops_mutex);

	return ops;
}


/*
 * unregister the specified driver
 */
int
snd_seq_device_unregister_driver(char *id)
{
	ops_list_t *ops;
	snd_seq_device_t *dev;

	ops = find_driver(id);
	if (ops == NULL)
		return -ENXIO;
	if (! (ops->driver & DRIVER_LOADED) ||
	    (ops->driver & DRIVER_LOCKED)) {
		snd_printk("driver_unregister: cannot unload driver '%s'\n", id);
		free_driver_use(ops);
		return -EBUSY;
	}

	/* close and release all devices associated with this driver */
	down(&ops->reg_mutex);
	ops->driver |= DRIVER_LOCKED; /* do not remove this driver recursively */
	for (dev = ops->devhead; dev; dev = dev->next) {
		if (dev->hw)
			free_device(dev, ops);
	}
	ops->driver &= ~(DRIVER_LOADED|DRIVER_LOCKED);
	if (ops->num_init_devices > 0)
		snd_printk("free_driver: init_devices > 0!! (%d)\n", ops->num_init_devices);
	up(&ops->reg_mutex);

	free_driver_use(ops);

	/* remove empty driver entries */
	remove_drivers();

	MOD_DEC_USE_COUNT;
	return 0;
}


/*
 * remove empty driver entries
 */
static void
remove_drivers(void)
{
	ops_list_t *ops, *prev, *next;

	down(&ops_mutex);
	prev = NULL;
	ops = opslist;
	while (ops) {
		next = ops->next;
		if (! (ops->driver & DRIVER_LOADED) &&
		    ops->used == 0 && ops->num_devices == 0) {
			if (prev)
				prev->next = ops->next;
			else
				opslist = ops->next;
			snd_kfree(ops);
			num_ops--;
		} else {
			prev = ops;
		}
		ops = next;
	}
	up(&ops_mutex);
}

/*
 * initialize the device - call init_device operator
 */
static int
init_device(snd_seq_device_t *dev, ops_list_t *ops)
{
	if (ops->ops.init_device(dev->card, dev->device, dev->name, dev->id,
				 dev->arg, dev->size, &dev->hw) >= 0) {
		ops->num_init_devices++;
	} else {
		snd_printk("init_device failed: %s: %s\n", dev->name, dev->id);
	}

	return 0;
}

/*
 * release the device - call free_device operator
 */
static int
free_device(snd_seq_device_t *dev, ops_list_t *ops)
{
	if (ops->ops.free_device(dev->card, dev->device, dev->arg,
				 dev->size, dev->hw) >= 0) {
		ops->num_init_devices--;
		dev->hw = NULL;
	} else {
		snd_printk("free_device failed: %s: %s\n", dev->name, dev->id);
	}

	return 0;
}

/*
 * find the matching driver with given id
 */
static ops_list_t *
find_driver(char *id)
{
	ops_list_t *ops;

	down(&ops_mutex);
	for (ops = opslist; ops; ops = ops->next) {
		if (strcmp(ops->id, id) == 0) {
			ops->used++;
			break;
		}
	}
	up(&ops_mutex);
	return ops;
}

static void
free_driver_use(ops_list_t *ops)
{
	down(&ops_mutex);
	ops->used--;
	up(&ops_mutex);
}


/*
 * module part
 */

int init_module(void)
{
	return 0;
}

void cleanup_module(void)
{
	remove_drivers();
	if (num_ops)
		snd_printk("seq_device: drivers not released (%d)\n", num_ops);
}

EXPORT_SYMBOL(snd_seq_device_load_drivers);
EXPORT_SYMBOL(snd_seq_device_register);
EXPORT_SYMBOL(snd_seq_device_find);
EXPORT_SYMBOL(snd_seq_device_unregister);
EXPORT_SYMBOL(snd_seq_device_register_driver);
EXPORT_SYMBOL(snd_seq_device_unregister_driver);
