blob: 11b7e6b499b7bcd50b431cd2c450b900c49de863 [file] [log] [blame]
Harald Welte59b04682009-06-10 05:40:52 +08001/* select filedescriptor handling, taken from:
2 * userspace logging daemon for the iptables ULOG target
3 * of the linux 2.4 netfilter subsystem.
4 *
5 * (C) 2000-2009 by Harald Welte <laforge@gnumonks.org>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License version 2
9 * as published by the Free Software Foundation
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, write to the Free Software
18 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
19 */
20
21#include <fcntl.h>
22#include <openbsc/select.h>
23#include <openbsc/linuxlist.h>
24#include <openbsc/timer.h>
25
26static int maxfd = 0;
27static LLIST_HEAD(bsc_fds);
28
29int bsc_register_fd(struct bsc_fd *fd)
30{
31 int flags;
32
33 /* make FD nonblocking */
34 flags = fcntl(fd->fd, F_GETFL);
35 if (flags < 0)
36 return flags;
37 flags |= O_NONBLOCK;
38 flags = fcntl(fd->fd, F_SETFL, flags);
39 if (flags < 0)
40 return flags;
41
42 /* Register FD */
43 if (fd->fd > maxfd)
44 maxfd = fd->fd;
45
46 llist_add_tail(&fd->list, &bsc_fds);
47
48 return 0;
49}
50
51void bsc_unregister_fd(struct bsc_fd *fd)
52{
53 llist_del(&fd->list);
54}
55
56int bsc_select_main(int polling)
57{
58 struct bsc_fd *ufd, *tmp;
59 fd_set readset, writeset, exceptset;
60 int work = 0, rc;
61 struct timeval no_time = {0, 0};
62
63 FD_ZERO(&readset);
64 FD_ZERO(&writeset);
65 FD_ZERO(&exceptset);
66
67 /* prepare read and write fdsets */
68 llist_for_each_entry(ufd, &bsc_fds, list) {
69 if (ufd->when & BSC_FD_READ)
70 FD_SET(ufd->fd, &readset);
71
72 if (ufd->when & BSC_FD_WRITE)
73 FD_SET(ufd->fd, &writeset);
74
75 if (ufd->when & BSC_FD_EXCEPT)
76 FD_SET(ufd->fd, &exceptset);
77 }
78
79 if (!polling)
80 bsc_prepare_timers();
81 rc = select(maxfd+1, &readset, &writeset, &exceptset, polling ? &no_time : bsc_nearest_timer());
82 if (rc < 0)
83 return 0;
84
85 /* fire timers */
86 bsc_update_timers();
87
88 /* call registered callback functions */
89 llist_for_each_entry_safe(ufd, tmp, &bsc_fds, list) {
90 int flags = 0;
91
92 if (FD_ISSET(ufd->fd, &readset))
93 flags |= BSC_FD_READ;
94
95 if (FD_ISSET(ufd->fd, &writeset))
96 flags |= BSC_FD_WRITE;
97
98 if (FD_ISSET(ufd->fd, &exceptset))
99 flags |= BSC_FD_EXCEPT;
100
101 if (flags) {
102 work = 1;
103 ufd->cb(ufd, flags);
104 }
105 }
106 return work;
107}