// SPDX-License-Identifier: GPL-2.0
/*
 * AVIRT - ALSA Virtual Soundcard
 *
 * Copyright (c) 2010-2018 Fiberdyne Systems Pty Ltd
 *
 * core.c - AVIRT core internals
 */

#include <linux/module.h>
#include <linux/string.h>
#include <linux/slab.h>
#include <sound/initval.h>
#include <linux/platform_device.h>

#include "core.h"

MODULE_AUTHOR("James O'Shannessy <james.oshannessy@fiberdyne.com.au>");
MODULE_AUTHOR("Mark Farrugia <mark.farrugia@fiberdyne.com.au>");
MODULE_DESCRIPTION("ALSA virtual, dynamic soundcard");
MODULE_LICENSE("GPL v2");

#define D_LOGNAME "core"

#define D_INFOK(fmt, args...) DINFO(D_LOGNAME, fmt, ##args)
#define D_PRINTK(fmt, args...) DDEBUG(D_LOGNAME, fmt, ##args)
#define D_ERRORK(fmt, args...) DERROR(D_LOGNAME, fmt, ##args)

#define PCM_OPS_SET(pcm_ops_ap, pcm_ops, cb)                                   \
	((pcm_ops_ap->cb) ? ((*pcm_ops)->cb = pcm_ops_ap->cb) :                \
			    ((*pcm_ops)->cb = NULL));

#define SND_AVIRT_DRIVER "snd_avirt"

static struct snd_avirt_core core = {
	.version = { 0, 0, 1 },
	.stream_count = 0,
	.streams_sealed = false,
};

static LIST_HEAD(audiopath_list);

/**
 * pcm_private_free - callback function to free private data allocated to pcm
 * @pcm: the PCM object
 */
static void pcm_private_free(struct snd_pcm *pcm)
{
	struct snd_avirt_private_data *avirt_private_data;

	/* Free Audio Path private data */
	avirt_private_data = (struct snd_avirt_private_data *)pcm->private_data;
	if (avirt_private_data) {
		if (avirt_private_data->ap_private_data &&
		    avirt_private_data->ap_private_free)
			avirt_private_data->ap_private_free(pcm);
	}

	kfree(pcm->private_data);
}

static struct snd_pcm *snd_avirt_pcm_create(struct snd_avirt_stream *stream)
{
	struct snd_avirt_private_data *avirt_private_data;
	struct snd_pcm *pcm;
	bool playback = false, capture = false;
	int err;

	if (!stream->direction)
		playback = true;
	else
		capture = true;

	/** Special case: loopback */
	if (!strcmp(stream->map, "ap_loopback")) {
		playback = true;
		capture = true;
	}

	err = snd_pcm_new(core.card, stream->name, stream->device, playback,
			  capture, &pcm);

	if (err < 0) {
		D_ERRORK("Failed to create PCM device for stream: '%s'",
			 stream->name);
		return ERR_PTR(err);
	}

	/** Register driver callbacks */
	if (playback)
		snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
				stream->pcm_ops);
	if (capture)
		snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE, stream->pcm_ops);

	pcm->info_flags = 0;
	strcpy(pcm->name, stream->name);

	avirt_private_data = kzalloc(sizeof(*avirt_private_data), GFP_KERNEL);
	pcm->private_data = avirt_private_data;
	// Set the private free function for the private user data
	pcm->private_free = pcm_private_free;

	snd_device_register(core.card, pcm);

	return pcm;
}

int snd_avirt_stream_set_map(struct snd_avirt_stream *stream, const char *map)
{
	struct snd_avirt_audiopath *audiopath;
	struct snd_pcm_ops *pcm_ops_ap;

	/* If already sealed, we cannot create the stream */
	if (snd_avirt_streams_sealed()) {
		D_ERRORK("Streams already sealed. Cannot set map: '%s'", map);
		return -EPERM;
	}

	if (!strcmp(stream->map, map))
		return -1;

	memcpy(stream->map, (char *)map, strlen(map));
	audiopath = snd_avirt_audiopath_get(map);
	if (!audiopath) {
		D_ERRORK("Cannot find Audio Path uid: '%s'!", stream->map);
		return -EFAULT;
	}

	if (!stream->direction)
		pcm_ops_ap = (struct snd_pcm_ops *)audiopath->pcm_playback_ops;
	else
		pcm_ops_ap = (struct snd_pcm_ops *)audiopath->pcm_capture_ops;

	if (!pcm_ops_ap) {
		D_ERRORK("No PCM ops for direction '%s' for Audio Path: %s",
			 (stream->direction) ? "capture" : "playback",
			 stream->map);
		return -EFAULT;
	}

	/* Set PCM ops for the Audio Path*/
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, prepare);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, trigger);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, pointer);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, get_time_info);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, fill_silence);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, copy_user);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, copy_kernel);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, mmap);
	PCM_OPS_SET(pcm_ops_ap, &stream->pcm_ops, ack);

	/* If not created, create the PCM device now */
	if (!stream->pcm) {
		stream->pcm = snd_avirt_pcm_create(stream);
		if (IS_ERR_OR_NULL(stream->pcm))
			return -EFAULT;
	}

	return 0;
}

static int snd_avirt_streams_get(const char *map,
				 struct snd_avirt_stream_array *stream_array)
{
	struct list_head *entry;
	struct config_item *item;
	struct snd_avirt_stream *stream;

	list_for_each (entry, &core.stream_group->cg_children) {
		item = container_of(entry, struct config_item, ci_entry);
		stream = snd_avirt_stream_from_config_item(item);
		if (!strcmp(map, stream->map)) {
			stream_array->streams[stream_array->count++] = stream;
		}
	}

	return stream_array->count;
}

/**
 * snd_avirt_audiopath_get - retrieves the Audio Path by its UID
 * @uid: Unique ID for the Audio Path
 * @return: Corresponding Audio Path
 */
struct snd_avirt_audiopath *snd_avirt_audiopath_get(const char *uid)
{
	struct snd_avirt_audiopath_obj *ap_obj;

	list_for_each_entry (ap_obj, &audiopath_list, list) {
		if (!strcmp(ap_obj->path->uid, uid))
			return ap_obj->path;
	}

	return NULL;
}
EXPORT_SYMBOL_GPL(snd_avirt_audiopath_get);

/**
 * snd_avirt_audiopath_register - register Audio Path with AVIRT
 * @audiopath: Audio Path to be registered
 * @return: 0 on success or error code otherwise
 */
int snd_avirt_audiopath_register(struct snd_avirt_audiopath *audiopath)
{
	struct snd_avirt_audiopath_obj *audiopath_obj;
	struct snd_avirt_stream_array stream_array;

	if (!audiopath) {
		D_ERRORK("Audio Path is NULL!");
		return -EINVAL;
	}

	audiopath_obj = snd_avirt_audiopath_create_obj(audiopath->uid);
	if (!audiopath_obj) {
		D_INFOK("Failed to alloc driver object");
		return -ENOMEM;
	}
	audiopath_obj->path = audiopath;

	audiopath->context = audiopath_obj;
	D_INFOK("Registered new Audio Path: %s", audiopath->name);

	list_add_tail(&audiopath_obj->list, &audiopath_list);

	// If we have already sealed the streams, configure this AP
	if (core.streams_sealed) {
		stream_array.count = 0;
		if (snd_avirt_streams_get(audiopath->uid, &stream_array) > 0)
			audiopath->configure(core.card, &stream_array);
	}

	return 0;
}
EXPORT_SYMBOL_GPL(snd_avirt_audiopath_register);

/**
 * snd_avirt_audiopath_deregister - deregister Audio Path with AVIRT
 * @audiopath: Audio Path to be deregistered
 * @return: 0 on success or error code otherwise
 */
int snd_avirt_audiopath_deregister(struct snd_avirt_audiopath *audiopath)
{
	struct snd_avirt_audiopath_obj *audiopath_obj;

	// Check if audio path is registered
	if (!audiopath) {
		D_ERRORK("Bad Audio Path Driver");
		return -EINVAL;
	}

	audiopath_obj = audiopath->context;
	if (!audiopath_obj) {
		D_INFOK("driver not registered");
		return -EINVAL;
	}

	list_del(&audiopath_obj->list);
	snd_avirt_audiopath_destroy_obj(audiopath_obj);
	D_INFOK("Deregistered Audio Path %s", audiopath->uid);

	return 0;
}
EXPORT_SYMBOL_GPL(snd_avirt_audiopath_deregister);

/**
 * snd_avirt_route_create - Create audio route
 * @name: The name designated to the audio route
 * @direction: The PCM direction (SNDRV_PCM_STREAM_PLAYBACK or
 *             SNDRV_PCM_STREAM_CAPTURE)
 * @return: The newly created audio route if successful, or an error pointer
 */
struct snd_avirt_route *snd_avirt_route_create(const char *name, int direction)
{
	struct snd_avirt_route *route;

	route = kzalloc(sizeof(*route), GFP_KERNEL);
	if (!route)
		return ERR_PTR(-ENOMEM);

	strcpy(route->name, name);
	route->channels = 0;
	route->direction = direction;

	return route;
}

/**
 * snd_avirt_stream_create - Create audio stream, including it's ALSA PCM device
 * @name: The name designated to the audio stream
 * @direction: The PCM direction (SNDRV_PCM_STREAM_PLAYBACK or
 *             SNDRV_PCM_STREAM_CAPTURE)
 * @return: The newly created audio stream if successful, or an error pointer
 */
struct snd_avirt_stream *snd_avirt_stream_create(const char *name,
						 int direction)
{
	struct snd_avirt_stream *stream;

	if ((core.stream_count + 1) > MAX_STREAMS) {
		D_ERRORK("Cannot add stream %s, PCMs are maxxed out!", name);
		return ERR_PTR(-EPERM);
	}

	stream = kzalloc(sizeof(*stream), GFP_KERNEL);
	if (!stream)
		return ERR_PTR(-ENOMEM);

	strcpy(stream->name, name);
	strcpy(stream->map, "none");
	stream->channels = 0;
	stream->direction = direction;
	stream->device = core.stream_count++;

	/* Initialize PCM ops table for this stream.
	 * Will be populated once map is known */
	stream->pcm_ops = kzalloc(sizeof(struct snd_pcm_ops), GFP_KERNEL);
	if (!stream->pcm_ops) {
		D_ERRORK("Failed to allocate PCM ops table");
		return ERR_PTR(-EFAULT);
	}
	memcpy(stream->pcm_ops, &pcm_ops_avirt, sizeof(struct snd_pcm_ops));

	D_INFOK("name:%s device:%d", name, stream->device);

	return stream;
}

int snd_avirt_streams_seal(void)
{
	int err = 0, i = 0;
	struct snd_avirt_audiopath_obj *ap_obj;
	struct snd_avirt_stream_array stream_array;

	if (core.streams_sealed) {
		D_ERRORK("streams are already sealed!");
		return -1;
	}

	list_for_each_entry (ap_obj, &audiopath_list, list) {
		for (i = 0; i < MAX_STREAMS; i++)
			stream_array.streams[i] = NULL;
		stream_array.count = 0;
		if (snd_avirt_streams_get(ap_obj->path->uid, &stream_array) <=
		    0)
			continue;

		D_INFOK("Do configure for AP: %s streams:%d cb:%p",
			ap_obj->path->uid, stream_array.count,
			ap_obj->path->configure);
		ap_obj->path->configure(core.card, &stream_array);
	}

	core.streams_sealed = true;

	return err;
}

bool snd_avirt_streams_sealed(void)
{
	return core.streams_sealed;
}

struct snd_avirt_stream *snd_avirt_stream_find_by_device(unsigned int device)
{
	struct snd_avirt_stream *stream;
	struct config_item *item;
	struct list_head *entry;

	if (device >= core.stream_count) {
		D_ERRORK("Stream device number is larger than stream count");
		return ERR_PTR(-EINVAL);
	}

	list_for_each (entry, &core.stream_group->cg_children) {
		item = container_of(entry, struct config_item, ci_entry);
		stream = snd_avirt_stream_from_config_item(item);
		if (!stream)
			return ERR_PTR(-EFAULT);
		if (stream->device == device)
			return stream;
	}

	return NULL;
}

static int snd_avirt_core_probe(struct platform_device *devptr)
{
	int err;

	// Create the card instance
	err = snd_card_new(&devptr->dev, SNDRV_DEFAULT_IDX1, "avirt",
			   THIS_MODULE, 0, &core.card);
	if (err < 0) {
		D_ERRORK("Failed to create sound card");
		return err;
	}

	strncpy(core.card->driver, "avirt-alsa-dev", 16);
	strncpy(core.card->shortname, "avirt", 32);
	strncpy(core.card->longname, "A virtual sound card driver for ALSA",
		80);

	return 0;
}

static int snd_avirt_core_remove(struct platform_device *devptr)
{
	snd_card_free(core.card);

	return 0;
}

static struct platform_driver snd_avirt_driver = {
	.probe = snd_avirt_core_probe,
	.remove = snd_avirt_core_remove,
	.driver =
		{
			.name = SND_AVIRT_DRIVER,
		},
};

/**
 * snd_avirt_core_init - Initialize the kernel module
 */
static int __init snd_avirt_core_init(void)
{
	int err;

	D_INFOK("Alsa Virtual Sound Driver avirt-%d.%d.%d", core.version[0],
		core.version[1], core.version[2]);

	err = platform_driver_register(&snd_avirt_driver);
	if (err < 0)
		return err;

	core.plat_dev =
		platform_device_register_simple(SND_AVIRT_DRIVER, 0, NULL, 0);
	if (IS_ERR(core.plat_dev)) {
		err = PTR_ERR(core.plat_dev);
		goto exit_platform_device;
	}

	core.class = class_create(THIS_MODULE, SND_AVIRT_DRIVER);
	if (IS_ERR(core.class)) {
		D_ERRORK("No udev support");
		return PTR_ERR(core.class);
	}

	core.dev = device_create(core.class, NULL, 0, NULL, "core");
	if (IS_ERR(core.dev)) {
		err = PTR_ERR(core.dev);
		goto exit_class;
	}

	err = snd_avirt_sysfs_init(&core);
	if (err < 0)
		goto exit_class_container;

	err = snd_card_register(core.card);
	if (err < 0) {
		D_ERRORK("Sound card registration failed!");
		snd_card_free(core.card);
	}

	err = snd_avirt_configfs_init(&core);
	if (err < 0)
		goto exit_sysfs;

	return 0;

exit_sysfs:
	snd_avirt_sysfs_exit(&core);
exit_class_container:
	device_destroy(core.class, 0);
exit_class:
	class_destroy(core.class);
exit_platform_device:
	platform_device_unregister(core.plat_dev);
	platform_driver_unregister(&snd_avirt_driver);

	return err;
}

/**
 * snd_avirt_core_exit - Destroy the kernel module
 */
static void __exit snd_avirt_core_exit(void)
{
	snd_avirt_configfs_exit(&core);
	snd_avirt_sysfs_exit(&core);
	device_destroy(core.class, 0);
	class_destroy(core.class);
	platform_device_unregister(core.plat_dev);
	platform_driver_unregister(&snd_avirt_driver);
}

module_init(snd_avirt_core_init);
module_exit(snd_avirt_core_exit);