Add fdwatch.c and timers.c

git-svn-id: svn://svn.code.sf.net/p/nuttx/code/trunk@1981 42af7a65-404d-4744-a932-0658087f49c3
This commit is contained in:
patacongo 2009-07-12 20:27:56 +00:00
parent 1235ab92c5
commit 4020506590
6 changed files with 821 additions and 44 deletions

View File

@ -42,7 +42,7 @@ SUBDIRS = cgi-src
ASRCS = ASRCS =
AOBJS = $(ASRCS:.S=$(OBJEXT)) AOBJS = $(ASRCS:.S=$(OBJEXT))
CSRCS = thttpd.c libhttpd.c CSRCS = thttpd.c libhttpd.c timers.c fdwatch.c
COBJS = $(CSRCS:.c=$(OBJEXT)) COBJS = $(CSRCS:.c=$(OBJEXT))
SRCS = $(ASRCS) $(CSRCS) SRCS = $(ASRCS) $(CSRCS)

396
netutils/thttpd/fdwatch.c Normal file
View File

@ -0,0 +1,396 @@
/****************************************************************************
* netutils/thttpd/timers.c
* FD watcher routines for poll()
*
* Copyright (C) 2009 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <spudmonkey@racsa.co.cr>
*
* Derived from the file of the same name in the original THTTPD package:
*
* Copyright © 1999,2000 by Jef Poskanzer <jef@mail.acme.com>.
* All rights reserved.
*
* 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 THE 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <nuttx/config.h>
#include <sys/types.h>
#include <stdlib.h>
#include <debug.h>
#if 0
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#endif
#include <poll.h>
#include "config.h"
#include "fdwatch.h"
#ifdef CONFIG_THTTPD
/****************************************************************************
* Pre-Processor Definitions
****************************************************************************/
#ifndef MIN
# define MIN(a,b) ((a) < (b) ? (a) : (b))
#endif
/****************************************************************************
* Private Data
****************************************************************************/
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
static long nwatches;
#endif
static int *fd_rw;
static void **fd_data;
static struct pollfd *pollfds;
static int *poll_pollndx;
static int *poll_rfdidx;
static int npoll_fds;
static int nreturned;
static int next_rfndx;
/****************************************************************************
* Private Function Prototypes
****************************************************************************/
/****************************************************************************
* Private Functions
****************************************************************************/
/****************************************************************************
* Public Functions
****************************************************************************/
/* Initialize the fdwatch data structures. Returns -1 on failure. */
int fdwatch_initialize(void)
{
int i;
/* Initialize the fdwatch data structures. */
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
nwatches = 0;
#endif
fd_rw = (int *)malloc(sizeof(int) * CONFIG_NSOCKET_DESCRIPTORS);
if (!fd_rw)
{
goto errout;
}
fd_data = (void **)malloc(sizeof(void*) * CONFIG_NSOCKET_DESCRIPTORS);
if (!fd_data)
{
goto errout_with_fd_rw;
}
for (i = 0; i < CONFIG_NSOCKET_DESCRIPTORS; ++i)
{
fd_rw[i] = -1;
}
pollfds = (struct pollfd *)malloc(sizeof(struct pollfd) * CONFIG_NSOCKET_DESCRIPTORS);
if (!pollfds)
{
goto errout_with_fd_data;
}
poll_pollndx = (int *)malloc(sizeof(int) * CONFIG_NSOCKET_DESCRIPTORS);
if (!poll_pollndx)
{
goto errout_with_pollfds;
}
poll_rfdidx = (int *)malloc(sizeof(int) * CONFIG_NSOCKET_DESCRIPTORS);
if (!poll_rfdidx)
{
goto errout_with_poll_pollndx;
}
for (i = 0; i < CONFIG_NSOCKET_DESCRIPTORS; i++)
{
pollfds[i].fd = poll_pollndx[i] = -1;
}
return OK;
errout_with_poll_pollndx:
free(poll_pollndx);
errout_with_pollfds:
free(pollfds);
errout_with_fd_data:
free(fd_data);
errout_with_fd_rw:
free(fd_rw);
errout:
return ERROR;
}
/* Add a descriptor to the watch list. rw is either FDW_READ or FDW_WRITE. */
void fdwatch_add_fd(int fd, void *client_data, int rw)
{
int fdndx;
#ifdef CONFIG_DEBUG
if (fd < CONFIG_NFILE_DESCRIPTORS ||
fd >= CONFIG_NFILE_DESCRIPTORS+CONFIG_NSOCKET_DESCRIPTORS ||
fd_rw[fd-CONFIG_NFILE_DESCRIPTORS] != -1)
{
ndbg("Received bad fd (%d)\n", fd);
return;
}
#endif
if (npoll_fds >= CONFIG_NSOCKET_DESCRIPTORS)
{
ndbg("too many fds\n");
return;
}
/* Get the socket index associated with the fd */
fdndx = fd-CONFIG_NFILE_DESCRIPTORS;
/* Save the new fd at the end of the list */
pollfds[npoll_fds].fd = fd;
switch (rw)
{
default:
case FDW_READ:
pollfds[npoll_fds].events = POLLIN;
break;
case FDW_WRITE:
pollfds[npoll_fds].events = POLLOUT;
break;
}
/* Save the new index and increment the cound of watched descriptors */
poll_pollndx[fdndx] = npoll_fds;
npoll_fds++;
fd_rw[fdndx] = rw;
fd_data[fdndx] = client_data;
}
/* Remove a descriptor from the watch list. */
void fdwatch_del_fd(int fd)
{
int fdndx;
int pollndx;
int tmpndx;
#ifdef CONFIG_DEBUG
if (fd < CONFIG_NFILE_DESCRIPTORS ||
fd >= CONFIG_NFILE_DESCRIPTORS+CONFIG_NSOCKET_DESCRIPTORS ||
fd_rw[fd-CONFIG_NFILE_DESCRIPTORS] == -1)
{
ndbg("Received bad fd: %d\n", fd);
return;
}
#endif
/* Get the socket index associated with the fd and then the poll
* index associated with that.
*/
fdndx = fd-CONFIG_NFILE_DESCRIPTORS;
pollndx = poll_pollndx[fdndx];
#ifdef CONFIG_DEBUG
if (pollndx < 0 || pollndx >= CONFIG_NSOCKET_DESCRIPTORS)
{
ndbg("Bad poll index: %d\n", pollndx);
return;
}
#endif
/* Decrement the number of fds in the poll table */
npoll_fds--;
/* Replace the deleted one with the one at the the end
* of the list.
*/
tmpndx = pollfds[pollndx].fd - CONFIG_NFILE_DESCRIPTORS;
pollfds[pollndx] = pollfds[npoll_fds];
poll_pollndx[tmpndx] = poll_pollndx[fdndx];;
pollfds[npoll_fds].fd = -1;
poll_pollndx[fdndx] = -1;
fd_rw[fdndx] = -1;
fd_data[fdndx] = NULL;
}
/* Do the watch. Return value is the number of descriptors that are ready,
* or 0 if the timeout expired, or -1 on errors. A timeout of INFTIM means
* wait indefinitely.
*/
int fdwatch(long timeout_msecs)
{
int rfndx;
int ret;
int i;
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
nwatches++;
#endif
ret = poll(pollfds, npoll_fds, (int)timeout_msecs);
if (ret <= 0)
{
return ret;
}
rfndx = 0;
for (i = 0; i < npoll_fds; i++)
{
if (pollfds[i].revents & (POLLIN | POLLOUT | POLLERR | POLLHUP | POLLNVAL))
{
poll_rfdidx[rfndx++] = pollfds[i].fd;
if (rfndx == ret)
{
break;
}
}
}
next_rfndx = 0;
return rfndx;
}
/* Check if a descriptor was ready. */
int fdwatch_check_fd(int fd)
{
int fdndx;
int pollndx;
#ifdef CONFIG_DEBUG
if (fd < CONFIG_NFILE_DESCRIPTORS ||
fd >= CONFIG_NFILE_DESCRIPTORS+CONFIG_NSOCKET_DESCRIPTORS ||
fd_rw[fd-CONFIG_NFILE_DESCRIPTORS] == -1)
{
ndbg("Bad fd: %d\n", fd);
return 0;
}
#endif
/* Get the socket index associated with the fd and then the poll
* index associated with that.
*/
fdndx = fd-CONFIG_NFILE_DESCRIPTORS;
pollndx = poll_pollndx[fdndx];
#ifdef CONFIG_DEBUG
if (pollndx < 0 || pollndx >= CONFIG_NSOCKET_DESCRIPTORS)
{
ndbg("Bad poll index: %d\n", pollndx);
return 0;
}
#endif
if (pollfds[pollndx].revents & POLLERR)
{
return 0;
}
switch (fd_rw[fdndx])
{
case FDW_READ:
return pollfds[pollndx].revents & (POLLIN | POLLHUP | POLLNVAL);
case FDW_WRITE:
return pollfds[pollndx].revents & (POLLOUT | POLLHUP | POLLNVAL);
default:
break;
}
return 0;
}
void *fdwatch_get_next_client_data(void)
{
int rfndx;
int fdndx;
int fd;
if (next_rfndx >= nreturned)
{
return (void*)-1;
}
rfndx = next_rfndx++;
#ifdef CONFIG_DEBUG
if (rfndx < 0 || rfndx >= CONFIG_NSOCKET_DESCRIPTORS)
{
ndbg("Bad rfndx: %d\n", rfndx);
return NULL;
}
#endif
fd = poll_rfdidx[rfndx];
fdndx = fd-CONFIG_NFILE_DESCRIPTORS;
if (fdndx < 0 || fdndx >= CONFIG_NSOCKET_DESCRIPTORS)
{
return NULL;
}
return fd_data[fdndx];
}
/* Generate debugging statistics ndbg message. */
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
void fdwatch_logstats(long secs)
{
if (secs > 0)
ndbg("fdwatch - %ld polls (%g/sec)\n", nwatches, (float)nwatches / secs);
nwatches = 0;
}
#endif
#endif /* CONFIG_THTTPD */

View File

@ -47,11 +47,9 @@
# define INFTIM -1 # define INFTIM -1
#endif #endif
/* Figure out how many file descriptors the system allows, and /* initialize the fdwatch data structures. Returns -1 on failure. */
* initialize the fdwatch data structures. Returns -1 on failure.
*/
extern int fdwatch_get_nfiles(void); extern int fdwatch_initialize(void);
/* Add a descriptor to the watch list. rw is either FDW_READ or FDW_WRITE. */ /* Add a descriptor to the watch list. rw is either FDW_READ or FDW_WRITE. */
@ -80,7 +78,9 @@ extern void *fdwatch_get_next_client_data(void);
/* Generate debugging statistics syslog message. */ /* Generate debugging statistics syslog message. */
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
extern void fdwatch_logstats(long secs); extern void fdwatch_logstats(long secs);
#endif
#endif /* __NETUTILS_THTTPD_FDWATCH_H */ #endif /* __NETUTILS_THTTPD_FDWATCH_H */

View File

@ -1906,7 +1906,9 @@ static int ls(httpd_conn *hc)
char *timestr; char *timestr;
char arg[16]; char arg[16];
char *argv[1]; char *argv[1];
#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
ClientData client_data; ClientData client_data;
#endif
dirp = opendir(hc->expnfilename); dirp = opendir(hc->expnfilename);
if (dirp == (DIR *) 0) if (dirp == (DIR *) 0)
@ -2444,6 +2446,9 @@ static void cgi_interpose_output(httpd_conn *hc, int rfd)
static void cgi_child(int argc, char **argv) static void cgi_child(int argc, char **argv)
{ {
FAR httpd_conn *hc = (FAR httpd_conn*)strtoul(argv[1], NULL, 16); FAR httpd_conn *hc = (FAR httpd_conn*)strtoul(argv[1], NULL, 16);
#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
ClientData client_data;
#endif
FAR char **argp; FAR char **argp;
char *binary; char *binary;
char *directory; char *directory;
@ -2627,17 +2632,6 @@ static void cgi_child(int argc, char **argv)
} }
} }
/* At this point we would like to set close-on-exec again for hc->conn_fd
* (see previous comments on Linux's broken behavior re: close-on-exec and
* dup.) Unfortunately there seems to be another Linux problem, or perhaps
* a different aspect of the same problem - if we do this close-on-exec in
* Linux, the socket stays open but stderr gets closed - the last fd duped
* from the socket. What a mess. So we'll just leave the socket as is,
* which under other OSs means an extra file descriptor gets passed to the
* child process. Since the child probably already has that file open via
* stdin stdout and/or stderr, this is not a problem.
*/
/* Split the program into directory and binary, so we can chdir() to the /* Split the program into directory and binary, so we can chdir() to the
* program's own directory. This isn't in the CGI 1.1 spec, but it's what * program's own directory. This isn't in the CGI 1.1 spec, but it's what
* other HTTP servers do. * other HTTP servers do.
@ -2674,15 +2668,26 @@ static void cgi_child(int argc, char **argv)
httpd_write_response(hc); httpd_write_response(hc);
exit(1); exit(1);
} }
else
{
/* Schedule a kill for the child process, in case it runs too long. */
#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
client_data.i = child;
if (tmr_create((struct timeval *)0, cgi_kill, client_data,
CONFIG_THTTPD_CGI_TIMELIMIT * 1000L, 0) == (Timer *) 0)
{
ndbg("tmr_create(cgi_kill child) failed\n");
exit(1);
}
#endif
}
} }
#endif /* CONFIG_THTTPD_CGI_PATTERN */ #endif /* CONFIG_THTTPD_CGI_PATTERN */
#ifdef CONFIG_THTTPD_CGI_PATTERN #ifdef CONFIG_THTTPD_CGI_PATTERN
static int cgi(httpd_conn *hc) static int cgi(httpd_conn *hc)
{ {
#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
ClientData client_data;
#endif
char arg[16]; char arg[16];
char *argv[1]; char *argv[1];
pid_t child; pid_t child;
@ -2725,21 +2730,6 @@ static int cgi(httpd_conn *hc)
ndbg("started CGI process %d for file '%s'\n", child, hc->expnfilename); ndbg("started CGI process %d for file '%s'\n", child, hc->expnfilename);
/* Schedule a kill for the child process, in case it runs too long.
* Unfortunately, the returned value in 'child' is the pid of the trampoline
* task -- NOT the pid of the CGI task. So the following cannot work.
*/
#if CONFIG_THTTPD_CGI_TIMELIMIT > 0
client_data.i = child;
if (tmr_create((struct timeval *)0, cgi_kill, client_data,
CONFIG_THTTPD_CGI_TIMELIMIT * 1000L, 0) == (Timer *) 0)
{
ndbg("tmr_create(cgi_kill child) failed\n");
exit(1);
}
#endif
hc->status = 200; hc->status = 200;
hc->bytes_sent = CONFIG_THTTPD_CGI_BYTECOUNT; hc->bytes_sent = CONFIG_THTTPD_CGI_BYTECOUNT;
hc->should_linger = FALSE; hc->should_linger = FALSE;

View File

@ -79,6 +79,9 @@
#define CNST_PAUSING 3 #define CNST_PAUSING 3
#define CNST_LINGERING 4 #define CNST_LINGERING 4
#define SPARE_FDS 2
#define AVAILABLE_FDS (CONFIG_NSOCKET_DESCRIPTORS - SPARE_FDS)
/**************************************************************************** /****************************************************************************
* Private Types * Private Types
****************************************************************************/ ****************************************************************************/
@ -103,7 +106,6 @@ struct connect_s
static httpd_server *hs = NULL; static httpd_server *hs = NULL;
static struct connect_s *connects; static struct connect_s *connects;
static int num_connects; static int num_connects;
static int max_connects;
static int first_free_connect; static int first_free_connect;
static int httpd_conn_count; static int httpd_conn_count;
@ -156,7 +158,7 @@ static void shut_down(void)
(void)gettimeofday(&tv, (struct timezone *)0); (void)gettimeofday(&tv, (struct timezone *)0);
logstats(&tv); logstats(&tv);
for (cnum = 0; cnum < max_connects; ++cnum) for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum)
{ {
if (connects[cnum].conn_state != CNST_FREE) if (connects[cnum].conn_state != CNST_FREE)
{ {
@ -199,7 +201,7 @@ static int handle_newconnect(struct timeval *tv, int listen_fd)
for (;;) for (;;)
{ {
/* Is there room in the connection table? */ /* Is there room in the connection table? */
if (num_connects >= max_connects) if (num_connects >= AVAILABLE_FDS)
{ {
/* Out of connection slots. Run the timers, then the existing /* Out of connection slots. Run the timers, then the existing
* connections, and maybe we'll free up a slot by the time we get * connections, and maybe we'll free up a slot by the time we get
@ -613,7 +615,7 @@ static void idle(ClientData client_data, struct timeval *nowP)
int cnum; int cnum;
struct connect_s *conn; struct connect_s *conn;
for (cnum = 0; cnum < max_connects; ++cnum) for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum)
{ {
conn = &connects[cnum]; conn = &connects[cnum];
switch (conn->conn_state) switch (conn->conn_state)
@ -740,6 +742,7 @@ int thttpd_main(int argc, char **argv)
struct sockaddr_in sa; struct sockaddr_in sa;
#endif #endif
struct timeval tv; struct timeval tv;
int ret;
/* Setup host address */ /* Setup host address */
@ -754,7 +757,8 @@ int thttpd_main(int argc, char **argv)
/* Switch directories if requested */ /* Switch directories if requested */
#ifdef CONFIG_THTTPD_DIR #ifdef CONFIG_THTTPD_DIR
if (chdir(CONFIG_THTTPD_DIR) < 0) ret = chdir(CONFIG_THTTPD_DIR);
if (ret < 0)
{ {
ndbg("chdir: %d\n", errno); ndbg("chdir: %d\n", errno);
exit(1); exit(1);
@ -771,8 +775,8 @@ int thttpd_main(int argc, char **argv)
/* Initialize the fdwatch package */ /* Initialize the fdwatch package */
max_connects = fdwatch_get_nfiles(); ret = fdwatch_initialize();
if (max_connects < 0) if (ret < 0)
{ {
ndbg("fdwatch initialization failure\n"); ndbg("fdwatch initialization failure\n");
exit(1); exit(1);
@ -834,21 +838,21 @@ int thttpd_main(int argc, char **argv)
/* Initialize our connections table */ /* Initialize our connections table */
connects = NEW(struct connect_s, max_connects); connects = NEW(struct connect_s, AVAILABLE_FDS);
if (connects == (struct connect_s *) 0) if (connects == (struct connect_s *) 0)
{ {
ndbg("out of memory allocating a struct connect_s\n"); ndbg("out of memory allocating a struct connect_s\n");
exit(1); exit(1);
} }
for (cnum = 0; cnum < max_connects; ++cnum) for (cnum = 0; cnum < AVAILABLE_FDS; ++cnum)
{ {
connects[cnum].conn_state = CNST_FREE; connects[cnum].conn_state = CNST_FREE;
connects[cnum].next_free_connect = cnum + 1; connects[cnum].next_free_connect = cnum + 1;
connects[cnum].hc = (httpd_conn *) 0; connects[cnum].hc = (httpd_conn *) 0;
} }
connects[max_connects - 1].next_free_connect = -1; /* end of link list */ connects[AVAILABLE_FDS - 1].next_free_connect = -1; /* end of link list */
first_free_connect = 0; first_free_connect = 0;
num_connects = 0; num_connects = 0;
httpd_conn_count = 0; httpd_conn_count = 0;

387
netutils/thttpd/timers.c Normal file
View File

@ -0,0 +1,387 @@
/****************************************************************************
* netutils/thttpd/timers.c
* Simple Timer Routines
*
* Copyright (C) 2009 Gregory Nutt. All rights reserved.
* Author: Gregory Nutt <spudmonkey@racsa.co.cr>
*
* Derived from the file of the same name in the original THTTPD package:
*
* Copyright © 1995,1998,2000 by Jef Poskanzer <jef@mail.acme.com>.
* All rights reserved.
*
* 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 THE 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.
*
****************************************************************************/
/****************************************************************************
* Included Files
****************************************************************************/
#include <sys/types.h>
#include <sys/time.h>
#include <stdlib.h>
#include <stdio.h>
#include <debug.h>
#include "timers.h"
/****************************************************************************
* Pre-Processor Definitons
****************************************************************************/
#define HASH_SIZE 67
/****************************************************************************
* Private Data
****************************************************************************/
static Timer *timers[HASH_SIZE];
static Timer *free_timers;
static int alloc_count, active_count, free_count;
/****************************************************************************
* Public Data
****************************************************************************/
ClientData JunkClientData;
/****************************************************************************
* Private Functions
****************************************************************************/
static unsigned int hash(Timer *t)
{
/* We can hash on the trigger time, even though it can change over the
* life of a timer via the periodic bit.
* This is because both of those guys call l_resort(), which * recomputes
* the hash and moves the timer to the appropriate list.
*/
return ((unsigned int)t->time.tv_sec ^
(unsigned int)t->time.tv_usec) % HASH_SIZE;
}
static void l_add(Timer * t)
{
int h = t->hash;
register Timer *t2;
register Timer *t2prev;
t2 = timers[h];
if (t2 == NULL)
{
/* The list is empty. */
timers[h] = t;
t->prev = t->next = NULL;
}
else
{
if (t->time.tv_sec < t2->time.tv_sec ||
(t->time.tv_sec == t2->time.tv_sec &&
t->time.tv_usec <= t2->time.tv_usec))
{
/* The new timer goes at the head of the list. */
timers[h] = t;
t->prev = NULL;
t->next = t2;
t2->prev = t;
}
else
{
/* Walk the list to find the insertion point. */
for (t2prev = t2, t2 = t2->next; t2 != NULL;
t2prev = t2, t2 = t2->next)
{
if (t->time.tv_sec < t2->time.tv_sec ||
(t->time.tv_sec == t2->time.tv_sec &&
t->time.tv_usec <= t2->time.tv_usec))
{
/* Found it. */
t2prev->next = t;
t->prev = t2prev;
t->next = t2;
t2->prev = t;
return;
}
}
/* Oops, got to the end of the list. Add to tail. */
t2prev->next = t;
t->prev = t2prev;
t->next = NULL;
}
}
}
static void l_remove(Timer * t)
{
int h = t->hash;
if (t->prev == NULL)
{
timers[h] = t->next;
}
else
{
t->prev->next = t->next;
}
if (t->next != NULL)
{
t->next->prev = t->prev;
}
}
static void l_resort(Timer * t)
{
/* Remove the timer from its old list. */
l_remove(t);
/* Recompute the hash. */
t->hash = hash(t);
/* And add it back in to its new list, sorted correctly. */
l_add(t);
}
/****************************************************************************
* Public Functions
****************************************************************************/
void tmr_init(void)
{
int h;
for (h = 0; h < HASH_SIZE; ++h)
{
timers[h] = NULL;
}
free_timers = NULL;
alloc_count = active_count = free_count = 0;
}
Timer *tmr_create(struct timeval *nowP, TimerProc * timer_proc,
ClientData client_data, long msecs, int periodic)
{
Timer *t;
if (free_timers != NULL)
{
t = free_timers;
free_timers = t->next;
--free_count;
}
else
{
t = (Timer *) malloc(sizeof(Timer));
if (!t)
{
return NULL;
}
++alloc_count;
}
t->timer_proc = timer_proc;
t->client_data = client_data;
t->msecs = msecs;
t->periodic = periodic;
if (nowP != (struct timeval *)0)
{
t->time = *nowP;
}
else
{
(void)gettimeofday(&t->time, (struct timezone *)0);
}
t->time.tv_sec += msecs / 1000L;
t->time.tv_usec += (msecs % 1000L) * 1000L;
if (t->time.tv_usec >= 1000000L)
{
t->time.tv_sec += t->time.tv_usec / 1000000L;
t->time.tv_usec %= 1000000L;
}
t->hash = hash(t);
/* Add the new timer to the proper active list. */
l_add(t);
++active_count;
return t;
}
long tmr_mstimeout(struct timeval *nowP)
{
int h;
int gotone;
long msecs, m;
register Timer *t;
gotone = 0;
msecs = 0; /* make lint happy */
/* Since the lists are sorted, we only need to look at the * first timer on
* each one.
*/
for (h = 0; h < HASH_SIZE; ++h)
{
t = timers[h];
if (t != NULL)
{
m = (t->time.tv_sec - nowP->tv_sec) * 1000L +
(t->time.tv_usec - nowP->tv_usec) / 1000L;
if (!gotone)
{
msecs = m;
gotone = 1;
}
else if (m < msecs)
{
msecs = m;
}
}
}
if (!gotone)
{
return INFTIM;
}
if (msecs <= 0)
{
msecs = 0;
}
return msecs;
}
void tmr_run(struct timeval *nowP)
{
int h;
Timer *t;
Timer *next;
for (h = 0; h < HASH_SIZE; ++h)
for (t = timers[h]; t != NULL; t = next)
{
next = t->next;
/* Since the lists are sorted, as soon as we find a timer * that isn't
* ready yet, we can go on to the next list
*/
if (t->time.tv_sec > nowP->tv_sec ||
(t->time.tv_sec == nowP->tv_sec && t->time.tv_usec > nowP->tv_usec))
{
break;
}
(t->timer_proc) (t->client_data, nowP);
if (t->periodic)
{
/* Reschedule. */
t->time.tv_sec += t->msecs / 1000L;
t->time.tv_usec += (t->msecs % 1000L) * 1000L;
if (t->time.tv_usec >= 1000000L)
{
t->time.tv_sec += t->time.tv_usec / 1000000L;
t->time.tv_usec %= 1000000L;
}
l_resort(t);
}
else
{
tmr_cancel(t);
}
}
}
void tmr_cancel(Timer * t)
{
/* Remove it from its active list. */
l_remove(t);
--active_count;
/* And put it on the free list. */
t->next = free_timers;
free_timers = t;
++free_count;
t->prev = NULL;
}
void tmr_cleanup(void)
{
Timer *t;
while (free_timers != NULL)
{
t = free_timers;
free_timers = t->next;
--free_count;
free((void *)t);
--alloc_count;
}
}
void tmr_destroy(void)
{
int h;
for (h = 0; h < HASH_SIZE; ++h)
{
while (timers[h] != NULL)
{
tmr_cancel(timers[h]);
}
}
tmr_cleanup();
}
/* Generate debugging statistics. */
#if defined(CONFIG_DEBUG) && defined(CONFIG_DEBUG_NET)
void tmr_logstats(long secs)
{
ndbg("timers - %d allocated, %d active, %d free",
alloc_count, active_count, free_count);
if (active_count + free_count != alloc_count)
{
ndbg("ERROR: Timer counts don't add up!");
}
}
#endif