timer.c revision 1.8
1/*	$OpenBSD: timer.c,v 1.8 2012/06/22 16:06:31 mikeb Exp $	*/
2
3/*
4 * Copyright (c) 2010 Reyk Floeter <reyk@vantronix.net>
5 *
6 * Permission to use, copy, modify, and distribute this software for any
7 * purpose with or without fee is hereby granted, provided that the above
8 * copyright notice and this permission notice appear in all copies.
9 *
10 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
11 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
12 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
13 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
14 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
15 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
16 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
17 */
18
19#include <sys/param.h>
20#include <sys/queue.h>
21#include <sys/socket.h>
22#include <sys/uio.h>
23
24#include <stdio.h>
25#include <stdlib.h>
26#include <unistd.h>
27#include <string.h>
28#include <errno.h>
29#include <fcntl.h>
30#include <ctype.h>
31#include <event.h>
32
33#include "iked.h"
34
35void	 timer_callback(int, short, void *);
36
37void
38timer_initialize(struct iked *env, struct iked_timer *tmr,
39    void (*cb)(struct iked *, void *), void *arg)
40{
41	tmr->tmr_env = env;
42	tmr->tmr_cb = cb;
43	tmr->tmr_cbarg = arg;
44	evtimer_set(&tmr->tmr_ev, timer_callback, tmr);
45}
46
47int
48timer_initialized(struct iked *env, struct iked_timer *tmr)
49{
50	if (tmr && tmr->tmr_env == env && tmr->tmr_cb &&
51	    evtimer_initialized(&tmr->tmr_ev))
52		return (1);
53	return (0);
54}
55
56void
57timer_register(struct iked *env, struct iked_timer *tmr, int timeout)
58{
59	struct timeval		 tv = { timeout };
60
61	if (evtimer_initialized(&tmr->tmr_ev) &&
62	    evtimer_pending(&tmr->tmr_ev, NULL))
63		evtimer_del(&tmr->tmr_ev);
64
65	evtimer_add(&tmr->tmr_ev, &tv);
66}
67
68void
69timer_deregister(struct iked *env, struct iked_timer *tmr)
70{
71	evtimer_del(&tmr->tmr_ev);
72}
73
74void
75timer_callback(int fd, short event, void *arg)
76{
77	struct iked_timer	*tmr = arg;
78
79	if (tmr->tmr_cb)
80		tmr->tmr_cb(tmr->tmr_env, tmr->tmr_cbarg);
81}
82