Introduce a simple timer API....

One can use add_timer or schedule_timer to add a timer. After
the timeout time has been reached the callback will be called.
One can call add_time/schedule_timer and del_timer from within
the callback.
diff --git a/Makefile.am b/Makefile.am
index b3a37ee..1ba0604 100644
--- a/Makefile.am
+++ b/Makefile.am
@@ -1,7 +1,7 @@
 AUTOMAKE_OPTIONS = foreign dist-bzip2 1.6
 
 INCLUDES = $(all_includes) -I$(top_srcdir)/include
-SUBDIRS = include src
+SUBDIRS = include src tests
 
 #dist-hook:
 #	rm -rf `find $(distdir) -name .svn`
diff --git a/configure.in b/configure.in
index 1c4070c..034972a 100644
--- a/configure.in
+++ b/configure.in
@@ -16,4 +16,10 @@
 
 dnl Checks for typedefs, structures and compiler characteristics
 
-AC_OUTPUT(include/openbsc/Makefile include/Makefile src/Makefile Makefile)
+AC_OUTPUT(
+    include/openbsc/Makefile
+    include/Makefile
+    src/Makefile
+    tests/Makefile
+    tests/timer/Makefile
+    Makefile)
diff --git a/include/openbsc/timer.h b/include/openbsc/timer.h
new file mode 100644
index 0000000..e8dc91a
--- /dev/null
+++ b/include/openbsc/timer.h
@@ -0,0 +1,70 @@
+/*
+ * (C) 2008 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * All Rights Reserved
+ *
+ * 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ */
+
+#ifndef TIMER_H
+#define TIMER_H
+
+#include <sys/time.h>
+
+#include "linuxlist.h"
+
+/**
+ * Timer management:
+ *      - Create a struct timer_list
+ *      - Fill out timeout and use add_timer or
+ *        use schedule_timer to schedule a timer in
+ *        x seconds and microseconds from now...
+ *      - Use del_timer to remove the timer
+ *
+ *  Internally:
+ *      - We hook into select.c to give a timeval of the
+ *        nearest timer. On already passed timers we give
+ *        it a 0 to immediately fire after the select
+ *      - update_timers will call the callbacks and remove
+ *        the timers.
+ *
+ */
+struct timer_list {
+	struct llist_head entry;
+	struct timeval timeout;
+	int active  : 1;
+	int handled : 1;
+
+	void (*cb)(void*);
+	void *data;
+};
+
+/**
+ * timer management
+ */
+void add_timer(struct timer_list *timer);
+void schedule_timer(struct timer_list *timer, int seconds, int microseconds);
+void del_timer(struct timer_list *timer);
+int timer_pending(struct timer_list *timer);
+
+
+/**
+ * internal timer list management
+ */
+struct timeval *nearest_timer();
+void prepare_timers();
+void update_timers();
+
+#endif
diff --git a/src/Makefile.am b/src/Makefile.am
index bf55f26..6209906 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -4,7 +4,7 @@
 sbin_PROGRAMS = bsc_hack db_test
 
 bsc_hack_SOURCES = bsc_hack.c misdn.c abis_rsl.c abis_nm.c gsm_04_08.c gsm_data.c \
-		gsm_subscriber.c msgb.c select.c chan_alloc.c
+		gsm_subscriber.c msgb.c select.c chan_alloc.c timer.c
 
 db_test_SOURCES = db_test.c db.c
 db_test_LDADD = -ldl -ldbi
diff --git a/src/select.c b/src/select.c
index 4af1670..b5d22c5 100644
--- a/src/select.c
+++ b/src/select.c
@@ -21,6 +21,7 @@
 #include <fcntl.h>
 #include <openbsc/select.h>
 #include <openbsc/linuxlist.h>
+#include <openbsc/timer.h>
 
 static int maxfd = 0;
 static LLIST_HEAD(bsc_fds);
@@ -74,24 +75,29 @@
 			FD_SET(ufd->fd, &exceptset);
 	}
 
-	i = select(maxfd+1, &readset, &writeset, &exceptset, NULL);
-	if (i > 0) {
-		/* call registered callback functions */
-		llist_for_each_entry(ufd, &bsc_fds, list) {
-			int flags = 0;
+	prepare_timers();
+	i = select(maxfd+1, &readset, &writeset, &exceptset, nearest_timer());
+	if (i < 0)
+		return i;
 
-			if (FD_ISSET(ufd->fd, &readset))
-				flags |= BSC_FD_READ;
+	/* fire timers */
+	update_timers();
 
-			if (FD_ISSET(ufd->fd, &writeset))
-				flags |= BSC_FD_WRITE;
+	/* call registered callback functions */
+	llist_for_each_entry(ufd, &bsc_fds, list) {
+	    int flags = 0;
 
-			if (FD_ISSET(ufd->fd, &exceptset))
-				flags |= BSC_FD_EXCEPT;
+	    if (FD_ISSET(ufd->fd, &readset))
+		flags |= BSC_FD_READ;
 
-			if (flags)
-				ufd->cb(ufd, flags);
-		}
+	    if (FD_ISSET(ufd->fd, &writeset))
+		flags |= BSC_FD_WRITE;
+
+	    if (FD_ISSET(ufd->fd, &exceptset))
+		flags |= BSC_FD_EXCEPT;
+
+	    if (flags)
+		ufd->cb(ufd, flags);
 	}
 	return i;
 }
diff --git a/src/timer.c b/src/timer.c
new file mode 100644
index 0000000..158ee76
--- /dev/null
+++ b/src/timer.c
@@ -0,0 +1,168 @@
+/*
+ * (C) 2008 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * All Rights Reserved
+ *
+ * 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ */
+
+#include <assert.h>
+#include <string.h>
+#include <openbsc/timer.h>
+
+static LLIST_HEAD(timer_list);
+static struct timeval s_nearest_time;
+static struct timeval s_select_time;
+
+#define MICRO_SECONDS  1000000LL
+
+#define TIME_SMALLER(left, right) \
+        (left.tv_sec*MICRO_SECONDS+left.tv_usec) <= (right.tv_sec*MICRO_SECONDS+right.tv_usec)
+
+void add_timer(struct timer_list *timer)
+{
+	struct timer_list *list_timer;
+
+	/* TODO: Optimize and remember the closest item... */
+	timer->active = 1;
+
+	/* this might be called from within update_timers */
+	llist_for_each_entry(list_timer, &timer_list, entry)
+		if (timer == list_timer)
+			return;
+
+	llist_add(&timer->entry, &timer_list);
+}
+
+void schedule_timer(struct timer_list *timer, int seconds, int microseconds)
+{
+	struct timeval current_time;
+
+	gettimeofday(&current_time, NULL);
+	unsigned long long currentTime = current_time.tv_sec * MICRO_SECONDS + current_time.tv_usec;
+	currentTime += seconds * MICRO_SECONDS + microseconds;
+	timer->timeout.tv_sec = currentTime / MICRO_SECONDS;
+	timer->timeout.tv_usec = currentTime % MICRO_SECONDS;
+	add_timer(timer);
+}
+
+void del_timer(struct timer_list *timer)
+{
+	if (timer_pending(timer)) {
+		timer->active = 0;
+		llist_del(&timer->entry);
+	}
+}
+
+int timer_pending(struct timer_list *timer)
+{
+	return timer->active;
+}
+
+/*
+ * if we have a nearest time return the delta between the current
+ * time and the time of the nearest timer.
+ * If the nearest timer timed out return NULL and then we will
+ * dispatch everything after the select
+ */
+struct timeval *nearest_timer()
+{
+	struct timeval current_time;
+
+	if (s_nearest_time.tv_sec == 0 && s_nearest_time.tv_usec == 0)
+		return NULL;
+
+	if (gettimeofday(&current_time, NULL) == -1)
+		return NULL;
+
+	unsigned long long nearestTime = s_nearest_time.tv_sec * MICRO_SECONDS + s_nearest_time.tv_usec;
+	unsigned long long currentTime = current_time.tv_sec * MICRO_SECONDS + current_time.tv_usec;
+
+	if (nearestTime < currentTime) {
+		s_select_time.tv_sec = 0;
+		s_select_time.tv_usec = 0;
+	} else {
+		s_select_time.tv_sec = (nearestTime - currentTime) / MICRO_SECONDS;
+		s_select_time.tv_usec = (nearestTime - currentTime) % MICRO_SECONDS;
+	}
+
+	return &s_select_time;
+}
+
+/*
+ * Find the nearest time and update s_nearest_time
+ */
+void prepare_timers()
+{
+	struct timer_list *timer, *nearest_timer = NULL;
+	llist_for_each_entry(timer, &timer_list, entry) {
+		if (!nearest_timer || TIME_SMALLER(timer->timeout, nearest_timer->timeout)) {
+			nearest_timer = timer;
+		}
+	}
+
+	if (nearest_timer) {
+		s_nearest_time = nearest_timer->timeout;
+	} else {
+		memset(&s_nearest_time, 0, sizeof(struct timeval));
+	}
+}
+
+/*
+ * fire all timers... and remove them
+ */
+void update_timers()
+{
+	struct timeval current_time;
+	struct timer_list *timer, *tmp;
+
+	gettimeofday(&current_time, NULL);
+
+	/*
+	 * The callbacks might mess with our list and in this case
+	 * even llist_for_each_entry_safe is not safe to use. To allow
+	 * del_timer, add_timer, schedule_timer to be called from within
+	 * the callback we jump through some loops.
+	 *
+	 * First we set the handled flag of each active timer to zero,
+	 * then we iterate over the list and execute the callbacks. As the
+	 * list might have been changed (specially the next) from within
+	 * the callback we have to start over again. Once every callback
+	 * is dispatched we will remove the non-active from the list.
+	 *
+	 * TODO: If this is a performance issue we can poison a global
+	 * variable in add_timer and del_timer and only then restart.
+	 */
+	llist_for_each_entry(timer, &timer_list, entry) {
+		timer->handled = 0;
+	}
+
+restart:
+	llist_for_each_entry(timer, &timer_list, entry) {
+		if (!timer->handled && TIME_SMALLER(timer->timeout, current_time)) {
+			timer->handled = 1;
+			timer->active = 0;
+			(*timer->cb)(timer->data);
+			goto restart;
+		}
+	}
+
+	llist_for_each_entry_safe(timer, tmp, &timer_list, entry) {
+		timer->handled = 0;
+		if (!timer->active) {
+			llist_del(&timer->entry);
+		}
+	}
+}
diff --git a/tests/Makefile.am b/tests/Makefile.am
new file mode 100644
index 0000000..f7cfd54
--- /dev/null
+++ b/tests/Makefile.am
@@ -0,0 +1 @@
+SUBDIRS = timer
diff --git a/tests/timer/Makefile.am b/tests/timer/Makefile.am
new file mode 100644
index 0000000..726fb7f
--- /dev/null
+++ b/tests/timer/Makefile.am
@@ -0,0 +1,5 @@
+INCLUDES = $(all_includes) -I$(top_srcdir)/include
+bin_PROGRAMS = timer_test
+
+timer_test_SOURCES = timer_test.c $(top_srcdir)/src/timer.c $(top_srcdir)/src/select.c
+
diff --git a/tests/timer/timer_test.c b/tests/timer/timer_test.c
new file mode 100644
index 0000000..4d98aef
--- /dev/null
+++ b/tests/timer/timer_test.c
@@ -0,0 +1,62 @@
+/*
+ * (C) 2008 by Holger Hans Peter Freyther <zecke@selfish.org>
+ * All Rights Reserved
+ *
+ * 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.,
+ * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ */
+
+#include <stdio.h>
+
+#include <openbsc/timer.h>
+#include <openbsc/select.h>
+
+static void timer_fired(unsigned long data);
+
+static struct timer_list timer_one = {
+    .cb = timer_fired,
+    .data = (void*)1,
+};
+
+static struct timer_list timer_two = {
+    .cb = timer_fired,
+    .data = (void*)2,
+};
+
+static void timer_fired(unsigned long data)
+{
+    printf("Fired timer: %lu\n", data);
+
+    if (data == 1) {
+        schedule_timer(&timer_one, 3, 0);
+        del_timer(&timer_two);
+    } else if (data == 2) {
+        printf("Should not be fired... bug in del_timer\n");
+    } else  {
+        printf("wtf... wrong data\n");
+    }
+}
+
+int main(int argc, char** argv)
+{
+    printf("Starting... timer\n");
+
+    schedule_timer(&timer_one, 3, 0);
+    schedule_timer(&timer_two, 5, 0);
+
+    while (1) {
+        bsc_select_main();
+    }
+}