/*
 * IPVS         An implementation of the IP virtual server support for the
 *              LINUX operating system.  IPVS is now implemented as a module
 *              over the Netfilter framework. IPVS can be used to build a
 *              high-performance and highly available server based on a
 *              cluster of servers.
 *
 * Version:     $Id: ip_vs_timer.c,v 1.3 2000/07/06 14:57:09 wensong Exp $
 *
 * Authors:     Wensong Zhang <wensong@iinchina.net>
 *              Julian Anastasov <uli@linux.tu-varna.acad.bg>
 *
 *              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.
 *
 * Changes:
 *
 */
#include <linux/kernel.h>
#include <linux/types.h>
#include <linux/timer.h>

#include "ip_vs.h"
//#include <net/ip_vs.h>

/*
 * The following block implements slow timers for IPVS, most code is stolen
 * from linux/kernel/timer.c.
 * Slow timer is used to avoid the overhead of cascading timers, when lots
 * of connection entries (>50,000) are cluttered in the system.
 */
#define SHIFT_BITS 6
#define TVN_BITS 8
#define TVR_BITS 10
#define TVN_SIZE (1 << TVN_BITS)
#define TVR_SIZE (1 << TVR_BITS)
#define TVN_MASK (TVN_SIZE - 1)
#define TVR_MASK (TVR_SIZE - 1)

struct sltimer_vec {
        int index;
        struct list_head vec[TVN_SIZE];
};

struct sltimer_vec_root {
        int index;
        struct list_head vec[TVR_SIZE];
};

static struct sltimer_vec sltv3 = { 0 };
static struct sltimer_vec sltv2 = { 0 };
static struct sltimer_vec_root sltv1 = { 0 };

static struct sltimer_vec * const sltvecs[] = {
	(struct sltimer_vec *)&sltv1, &sltv2, &sltv3
};

#define NOOF_SLTVECS (sizeof(sltvecs) / sizeof(sltvecs[0]))

static void init_sltimervecs (void)
{
	int i;

	for (i = 0; i < TVN_SIZE; i++) {
		INIT_LIST_HEAD(sltv3.vec + i);
		INIT_LIST_HEAD(sltv2.vec + i);
	}
	for (i = 0; i < TVR_SIZE; i++)
		INIT_LIST_HEAD(sltv1.vec + i);
}

static unsigned long sltimer_jiffies = 0;

static inline void internal_add_sltimer(struct timer_list *timer)
{
	/*
	 * must be cli-ed when calling this
	 */
	unsigned long expires = timer->expires;
	unsigned long idx = (expires - sltimer_jiffies) >> SHIFT_BITS;
	struct list_head * vec;

	if (idx < TVR_SIZE) {
		int i = (expires >> SHIFT_BITS) & TVR_MASK;
		vec = sltv1.vec + i;
	} else if (idx < 1 << (TVR_BITS + TVN_BITS)) {
		int i = (expires >> (SHIFT_BITS+TVR_BITS)) & TVN_MASK;
		vec = sltv2.vec + i;
	} else if ((signed long) idx < 0) {
		/*
                 * can happen if you add a timer with expires == jiffies,
		 * or you set a timer to go off in the past
		 */
		vec = sltv1.vec + sltv1.index;
	} else if (idx <= 0xffffffffUL) {
		int i = (expires >> (SHIFT_BITS+TVR_BITS+TVN_BITS)) & TVN_MASK;
		vec = sltv3.vec + i;
	} else {
		/* Can only get here on architectures with 64-bit jiffies */
		INIT_LIST_HEAD(&timer->list);
	}
	/*
	 * Timers are FIFO!
	 */
	list_add(&timer->list, vec->prev);
}

rwlock_t __ip_vs_sltimerlist_lock = RW_LOCK_UNLOCKED;

void add_sltimer(struct timer_list *timer)
{
	write_lock(&__ip_vs_sltimerlist_lock);
	if (timer->list.next)
		goto bug;
	internal_add_sltimer(timer);
  out:
	write_unlock(&__ip_vs_sltimerlist_lock);
	return;

  bug:
	printk("bug: kernel sltimer added twice at %p.\n",
               __builtin_return_address(0));
	goto out;
}

static inline int detach_sltimer(struct timer_list *timer)
{
	if (!timer_pending(timer))
		return 0;
	list_del(&timer->list);
	return 1;
}

void mod_sltimer(struct timer_list *timer, unsigned long expires)
{
        int ret;

	write_lock(&__ip_vs_sltimerlist_lock);
	timer->expires = expires;
	ret = detach_sltimer(timer);
	internal_add_sltimer(timer);
	write_unlock(&__ip_vs_sltimerlist_lock);
}

int del_sltimer(struct timer_list * timer)
{
	int ret;

	write_lock(&__ip_vs_sltimerlist_lock);
	ret = detach_sltimer(timer);
	timer->list.next = timer->list.prev = 0;
	write_unlock(&__ip_vs_sltimerlist_lock);
	return ret;
}


static inline void cascade_sltimers(struct sltimer_vec *tv)
{
	/*
	 * cascade all the timers from tv up one level
	 */
	struct list_head *head, *curr, *next;
	
	head = tv->vec + tv->index;
	curr = head->next;

	/*
	 * We are removing _all_ timers from the list, so we don't  have to
	 * detach them individually, just clear the list afterwards.
	 */
	while (curr != head) {
		struct timer_list *tmp;
		
		tmp = list_entry(curr, struct timer_list, list);
		next = curr->next;
		list_del(curr); // not needed
		internal_add_sltimer(tmp);
		curr = next;
	}
	INIT_LIST_HEAD(head);
	tv->index = (tv->index + 1) & TVN_MASK;
}

static inline void run_sltimer_list(void)
{
	write_lock(&__ip_vs_sltimerlist_lock);
	while ((long)(jiffies - sltimer_jiffies) >= 0) {
		struct list_head *head, *curr;
		if (!sltv1.index) {
			int n = 1;
			do {
				cascade_sltimers(sltvecs[n]);
			} while (sltvecs[n]->index == 1 && ++n < NOOF_SLTVECS);
		}
          repeat:
		head = sltv1.vec + sltv1.index;
		curr = head->next;
		if (curr != head) {
			struct timer_list *timer;
			void (*fn)(unsigned long);
			unsigned long data;

			timer = list_entry(curr, struct timer_list, list);
			fn = timer->function;
			data= timer->data;

			detach_sltimer(timer);
			timer->list.next = timer->list.prev = NULL;
			timer_set_running(timer);
			write_unlock(&__ip_vs_sltimerlist_lock);
			fn(data);
			write_lock(&__ip_vs_sltimerlist_lock);
			goto repeat;
		}
		sltimer_jiffies += 1<<SHIFT_BITS;
		sltv1.index = (sltv1.index + 1) & TVR_MASK;
	}
	write_unlock(&__ip_vs_sltimerlist_lock);
}

static void sltimer_handler(unsigned long data);

struct timer_list slow_timer = { function: sltimer_handler };

/*
 *  Slow timer handler is activated every second
 */
#define SLTIMER_PERIOD	     1*HZ

void sltimer_handler(unsigned long data)
{
	run_sltimer_list();

	update_defense_level();
	if (atomic_read(&ip_vs_dropentry))
		ip_vs_random_dropentry();

	mod_timer(&slow_timer, (jiffies + SLTIMER_PERIOD));
}


void ip_vs_sltimer_init(void)
{
	/*
	 * Hook the slow_timer handler in the system timer.
	 */
	init_sltimervecs();
	slow_timer.expires = jiffies+SLTIMER_PERIOD;
	add_timer(&slow_timer);
}


void ip_vs_sltimer_cleanup(void)
{
	del_timer(&slow_timer);
}
