/*-
 * Copyright 2018 UPLEX Nils Goroll Systemoptimierung
 * All rights reserved.
 *
 * Author: Nils Goroll <nils.goroll@uplex.de>
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL AUTHOR OR CONTRIBUTORS BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include "config.h"

#include <string.h>
#include <stdlib.h>
#include <pthread.h>

#include <cache/cache.h>
#include <vcl.h>

#include <sys/socket.h>
#include <vsa.h>

#include "vmb.h"
#include "vcc_globalvar_if.h"
#include "type_magics.h"
#include "type_cp.h"
#include "compat.h"

typedef void var_free_f(const void *);

struct vmod_globalvar_var {
	unsigned	magic;	// same magic as vmod obj | below
#define VMOD_GLOBALVAR_VAR_MAGIC_BITS	0x07a80000
	unsigned	refcnt;
	pthread_mutex_t mtx;
	var_free_f	*free_f;
	const void	*val;
};

/* reference per value where the value is not immediate:
 *
 * the vmod obj keeps a reference as long as the value is live
 *
 * for read access, we grab a reference once per task: when the priv_task is new
 * (priv is NULL) we refcnt, then set the priv to the value struct
 *
 * return void pointer to value
 */

static void
unref_var(struct vmod_globalvar_var *v)
{
	unsigned r;

	AZ(pthread_mutex_lock(&v->mtx));
	r = --v->refcnt;
	AZ(pthread_mutex_unlock(&v->mtx));

	if (r)
		return;

	AZ(v->refcnt);
	AN(v->free_f);
	v->free_f(v->val);
	AZ(pthread_mutex_destroy(&v->mtx));
	free(v);
}

static void
ref_var(struct vmod_globalvar_var *v)
{
	AN(v->refcnt);	// must be alive

	AZ(pthread_mutex_lock(&v->mtx));
	v->refcnt++;
	AZ(pthread_mutex_unlock(&v->mtx));
}

static void
task_unref_var(VRT_CTX, void *ptr) {

	(void) ctx;
	unref_var((struct vmod_globalvar_var *) ptr);
}

static const struct vmod_priv_methods priv_task_methods[1] = {{
		.magic = VMOD_PRIV_METHODS_MAGIC,
		.type = "vmod_globalvar_priv_task",
		.fini = task_unref_var
}};

static const void *
task_ref_var(VRT_CTX, struct vmod_globalvar_var *v, unsigned magic) {
	struct vmod_priv *t;

	CHECK_OBJ_NOTNULL(v, magic);

	if (ctx->method & VCL_MET_TASK_H)
		return (v);

	t = VRT_priv_task(ctx, v);

	if (t == NULL) {
		VRT_fail(ctx, "no priv_task");
		return (NULL);
	}

	if (t->priv == NULL) {
		ref_var(v);
		t->priv = v;
		t->methods = priv_task_methods;
	}

	assert(t->priv == v);
	AN(v->refcnt);
	return (v->val);
}

#define tv_magic	0x3000

#define VMOD_GLOBALVAR_ACL_MAGIC		(tv_magic | OBJVAR_ACL_MAGIC)
#define VMOD_GLOBALVAR_BACKEND_MAGIC	(tv_magic | OBJVAR_BACKEND_MAGIC)
#define VMOD_GLOBALVAR_BLOB_MAGIC	(tv_magic | OBJVAR_BLOB_MAGIC)
#define VMOD_GLOBALVAR_BODY_MAGIC	(tv_magic | OBJVAR_BODY_MAGIC)
#define VMOD_GLOBALVAR_BOOL_MAGIC	(tv_magic | OBJVAR_BOOL_MAGIC)
#define VMOD_GLOBALVAR_BYTES_MAGIC	(tv_magic | OBJVAR_BYTES_MAGIC)
#define VMOD_GLOBALVAR_DURATION_MAGIC	(tv_magic | OBJVAR_DURATION_MAGIC)
#define VMOD_GLOBALVAR_HEADER_MAGIC	(tv_magic | OBJVAR_HEADER_MAGIC)
#define VMOD_GLOBALVAR_INT_MAGIC		(tv_magic | OBJVAR_INT_MAGIC)
#define VMOD_GLOBALVAR_IP_MAGIC		(tv_magic | OBJVAR_IP_MAGIC)
#define VMOD_GLOBALVAR_PROBE_MAGIC	(tv_magic | OBJVAR_PROBE_MAGIC)
#define VMOD_GLOBALVAR_REAL_MAGIC	(tv_magic | OBJVAR_REAL_MAGIC)
#define VMOD_GLOBALVAR_STEVEDORE_MAGIC	(tv_magic | OBJVAR_STEVEDORE_MAGIC)
#define VMOD_GLOBALVAR_STRING_MAGIC	(tv_magic | OBJVAR_STRING_MAGIC)
#define VMOD_GLOBALVAR_TIME_MAGIC	(tv_magic | OBJVAR_TIME_MAGIC)

#define immediate(vmod_, VMODPFX_, vmodpfx_, TYPE, type)		\
	struct vmodpfx_ ## type {					\
		uint16_t		magic;				\
		unsigned		defined:1;			\
		VCL_ ## TYPE		var;				\
	};								\
									\
	static inline void						\
	init_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
									\
		(void) v;						\
	}								\
									\
	static inline void						\
	fini_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
		FREE_ ## TYPE (v->var);					\
	}								\
									\
	static inline void						\
	set_var_ ## type(struct vmodpfx_ ## type *v, VCL_ ## TYPE val)	\
	{								\
		CP_ ## TYPE (v->var, val);				\
		VWMB();							\
		v->defined = 1;					\
	}								\
									\
	static inline void						\
	undef_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
		v->defined = 0;						\
	}								\
									\
	VCL_ ## TYPE							\
	vmod_ ## type ## _get(VRT_CTX, struct vmodpfx_ ## type *v,	\
	    struct VARGS(type ## _get) *a)				\
	{								\
		if (! v->defined) {					\
			if (a->valid_fallback)				\
				return (a->fallback);			\
			return (DEF_ ## TYPE(ctx));			\
		}							\
		VRMB();							\
		return (v->var);					\
	}

#define pointer(vmod_, VMODPFX_, vmodpfx_, TYPE, type)			\
	struct vmodpfx_ ## type {					\
		uint16_t			magic;			\
		unsigned			defined:1;		\
		pthread_mutex_t		mtx;			\
		struct vmod_globalvar_var	*var;			\
	};								\
									\
	static inline void						\
	init_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
		AZ(pthread_mutex_init(&v->mtx, NULL));			\
	}								\
									\
	static inline void						\
	fini_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
		unref_var(v->var);					\
		AZ(pthread_mutex_destroy(&v->mtx));			\
	}								\
									\
	static void							\
	free_var_ ## type(const void *v)				\
	{								\
		VCL_ ## TYPE vv = v;					\
		FREE_ ## TYPE(vv);					\
		AZ(vv);							\
	}								\
									\
	static inline void						\
	set_var_ ## type(struct vmodpfx_ ## type *v, VCL_ ## TYPE val)	\
	{								\
		struct vmod_globalvar_var *o, *n;			\
		const unsigned magic = VMOD_GLOBALVAR_VAR_MAGIC_BITS |	\
		    VMODPFX_ ## TYPE ## _MAGIC;				\
									\
		ALLOC_OBJ(n, magic);					\
		AN(n);							\
		n->refcnt = 1;						\
		AZ(pthread_mutex_init(&n->mtx, NULL));			\
		n->free_f = free_var_ ## type;				\
		CP_ ## TYPE (n->val, val);				\
									\
		AZ(pthread_mutex_lock(&v->mtx));			\
		o = v->var;						\
		v->var = n;						\
		v->defined = 1;					\
		AZ(pthread_mutex_unlock(&v->mtx));			\
		if (o)							\
			unref_var(o);					\
	}								\
									\
	static inline void						\
	undef_var_ ## type(struct vmodpfx_ ## type *v)			\
	{								\
		struct vmod_globalvar_var *o;				\
									\
		pthread_mutex_lock(&v->mtx);				\
		o = v->var;						\
		v->var = NULL;						\
		v->defined = 0;					\
		pthread_mutex_unlock(&v->mtx);				\
		if (o)							\
			unref_var(o);					\
	}								\
									\
	VCL_ ## TYPE							\
	vmod_ ## type ## _get(VRT_CTX, struct vmodpfx_ ## type *v,	\
	    struct VARGS(type ## _get) *a)				\
	{								\
		VCL_ ## TYPE	r;					\
		const unsigned magic = VMOD_GLOBALVAR_VAR_MAGIC_BITS |	\
		    VMODPFX_ ## TYPE ## _MAGIC;				\
		int fallback = 0;					\
									\
		CHECK_OBJ_NOTNULL(v, VMODPFX_ ## TYPE ## _MAGIC);	\
									\
		if (! v->defined)					\
			goto def;					\
									\
		pthread_mutex_lock(&v->mtx);				\
		if (! v->defined)					\
			fallback = 1;					\
		else							\
			r = task_ref_var(ctx, v->var, magic);		\
		pthread_mutex_unlock(&v->mtx);				\
		if (fallback)						\
			goto def;					\
		return (r);						\
	  def:								\
		if (a->valid_fallback)					\
			return (a->fallback);				\
		return (DEF_ ## TYPE(ctx));				\
	}

#define var_code(vmod_, VMODPFX_, vmodpfx_, TYPE, type)			\
	KIND_ ## TYPE (vmod_, VMODPFX_, vmodpfx_, TYPE, type)		\
									\
	VCL_VOID							\
	vmod_ ## type ## __init(VRT_CTX,				\
	    struct vmodpfx_ ## type **vp,				\
	    const char *vcl_name,					\
	    struct VARGS(type ##__init) *args)				\
	{								\
		struct vmodpfx_ ## type *v;				\
									\
		AN(vp);							\
		AZ(*vp);						\
									\
		ALLOC_OBJ(v, VMODPFX_ ## TYPE ## _MAGIC);		\
		if (v == NULL) {					\
			VRT_fail(ctx, "%s: alloc failed", vcl_name);	\
			return;						\
		}							\
									\
		init_var_ ## type(v);					\
									\
		if (args->valid_init)					\
			set_var_ ## type(v, args->init);		\
									\
		*vp = v;						\
	}								\
									\
	VCL_VOID							\
	vmod_ ## type ## __fini(struct vmodpfx_ ## type **vp)		\
	{								\
		struct vmodpfx_ ## type *v = *vp;			\
									\
		*vp = NULL;						\
		if (v == NULL)						\
			return;						\
									\
		CHECK_OBJ(v, VMODPFX_ ## TYPE ## _MAGIC);		\
		fini_var_ ## type(v);					\
		FREE_OBJ(v);						\
	}								\
									\
	VCL_VOID							\
	vmod_ ## type ## _set(VRT_CTX, struct vmodpfx_ ## type *v,	\
	    VCL_ ## TYPE val)						\
	{								\
									\
		(void) ctx;						\
		CHECK_OBJ_NOTNULL(v, VMODPFX_ ## TYPE ## _MAGIC);	\
									\
		set_var_ ## type(v, val);				\
	}								\
									\
	VCL_VOID							\
	vmod_ ## type ## _undefine(VRT_CTX, struct vmodpfx_ ## type *v) \
	{								\
		(void) ctx;						\
		CHECK_OBJ_NOTNULL(v, VMODPFX_ ## TYPE ## _MAGIC);	\
									\
		if (! v->defined)					\
			return;						\
									\
		undef_var_ ## type(v);					\
	}								\
									\
	VCL_BOOL							\
	vmod_ ## type ## _defined(VRT_CTX, struct vmodpfx_ ## type *v)	\
	{								\
									\
		(void) ctx;						\
		CHECK_OBJ_NOTNULL(v, VMODPFX_ ## TYPE ## _MAGIC);	\
									\
		return (!!v->defined);					\
	}


#define VCC_TYPE(TYPE, type) var_code(vmod_, VMOD_GLOBALVAR_, vmod_globalvar_, TYPE, type)
#include "tbl_types.h"
