File: selector.c

package info (click to toggle)
gensio 2.2.4-1
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 2,776 kB
  • sloc: ansic: 45,195; python: 2,718; cpp: 1,129; sh: 586; makefile: 420
file content (1507 lines) | stat: -rw-r--r-- 35,866 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
/*
 *  gensio - A library for abstracting stream I/O
 *  Copyright (C) 2018  Corey Minyard <minyard@acm.org>
 *
 *  SPDX-License-Identifier: LGPL-2.1-only
 */

/* This file holds code to abstract the "select" call and make it
   easier to use.  The main thread lives here, the rest of the code
   uses a callback interface.  Basically, other parts of the program
   can register file descriptors with this code, when interesting
   things happen on those file descriptors this code will call
   routines registered with it. */

#include "config.h"
#include <gensio/selector.h>

#include <sys/time.h>
#include <time.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <stdio.h>
#include <syslog.h>
#include <string.h>
#include <assert.h>
#ifdef HAVE_EPOLL_PWAIT
#include <sys/epoll.h>
#else
#define EPOLL_CTL_ADD 0
#define EPOLL_CTL_DEL 0
#define EPOLL_CTL_MOD 0
#endif
#include "errtrig.h"

#ifndef EBADFD
/* At least MacOS doesn't have EBADFD. */
#define EBADFD EBADF
#endif

static void *
sel_alloc(unsigned int size)
{
    void *d;

    if (do_errtrig())
	return NULL;

    d = malloc(size);
    if (d)
	memset(d, 0, size);
    return d;
}

struct sel_runner_s
{
    struct selector_s *sel;
    sel_runner_func_t func;
    void *cb_data;
    int in_use;
    sel_runner_t *next;
};

typedef struct fd_state_s
{
    int               deleted;
    unsigned int      use_count;
    sel_fd_cleared_cb done;
    sel_runner_t      done_runner;
    int               tmp_fd;
    void              *done_cbdata;
} fd_state_t;

/* The control structure for each file descriptor. */
typedef struct fd_control_s
{
    /* This structure is allocated when an FD is set and it holds
       whether the FD has been deleted and information to handle the
       deletion. */
    fd_state_t       *state;

    /* Link in the hash list. */
    struct fd_control_s *next;

    /* Handlers for various events on an fd. */
    void             *data; /* Passed to the handlers */
    sel_fd_handler_t handle_read;
    sel_fd_handler_t handle_write;
    sel_fd_handler_t handle_except;

    int fd;

    /* Keep track of whether the event is enabled here. */
    char read_enabled;
    char write_enabled;
    char except_enabled;

#ifdef HAVE_EPOLL_PWAIT
    /* See the comment in process_fds_epoll() on the use of this. */
    uint32_t saved_events;
#endif
} fd_control_t;

typedef struct heap_val_s
{
    /* Set this to the function to call when the timeout occurs. */
    sel_timeout_handler_t handler;

    /* Set this to whatever you like.  You can use this to store your
       own data. */
    void *user_data;

    /* Set this to the time when the timer will go off. */
    struct timeval timeout;

    /* Who owns me? */
    struct selector_s *sel;

    /* Am I currently running? */
    int in_heap;

    /* Am I currently stopped? */
    int stopped;

    /* Have I been freed? */
    int freed;

    /* Am I currently in a handler? */
    int in_handler;

    sel_timeout_handler_t done_handler;
    void *done_cb_data;
} heap_val_t;

typedef struct theap_s theap_t;
#define heap_s theap_s
#define heap_node_s sel_timer_s
#define HEAP_EXPORT_NAME(s) theap_ ## s
#define HEAP_NAMES_LOCAL static
#define HEAP_OUTPUT_PRINTF "(%ld.%7.7ld)"
#define HEAP_OUTPUT_DATA pos->timeout.tv_sec, pos->timeout.tv_usec

static int
cmp_timeval(const struct timeval *tv1, const struct timeval *tv2)
{
    if (tv1->tv_sec < tv2->tv_sec)
	return -1;

    if (tv1->tv_sec > tv2->tv_sec)
	return 1;

    if (tv1->tv_usec < tv2->tv_usec)
	return -1;

    if (tv1->tv_usec > tv2->tv_usec)
	return 1;

    return 0;
}

static int
heap_cmp_key(heap_val_t *v1, heap_val_t *v2)
{
    return cmp_timeval(&v1->timeout, &v2->timeout);
}

#include "heap.h"

/* Used to build a list of threads that may need to be woken if a
   timer on the top of the heap changes, or an FD is added/removed.
   See i_wake_sel_thread() for more info. */
typedef struct sel_wait_list_s
{
    /* The thread to wake up. */
    long            thread_id;

    /* How to wake it. */
    sel_send_sig_cb send_sig;
    void            *send_sig_cb_data;

    /* The time when the thread is set to wake up. */
    struct timeval wake_time;

    struct sel_wait_list_s *next, *prev;
} sel_wait_list_t;

struct selector_s
{
    /* This is an hash table of file descriptors. */
    fd_control_t *fds[FD_SETSIZE];

    /* If something is deleted, we increment this count.  This way when
       a select/epoll returns a non-timeout, we know that we need to ignore
       it as it may be  from the just deleted fd. */
    unsigned long fd_del_count;

    void *fd_lock;

    /* The timer heap. */
    theap_t timer_heap;

    /* This is a list of items waiting to be woken up because they are
       sitting in a select.  See i_wake_sel_thread() for more info. */
    sel_wait_list_t wait_list;

    void *timer_lock;

    sel_runner_t *runner_head;
    sel_runner_t *runner_tail;

    int wake_sig;

#ifdef HAVE_EPOLL_PWAIT
    int epollfd;
#endif
    sel_lock_t *(*sel_lock_alloc)(void *cb_data);
    void (*sel_lock_free)(sel_lock_t *);
    void (*sel_lock)(sel_lock_t *);
    void (*sel_unlock)(sel_lock_t *);

    /* Everything below is only used for select() and ignore for epoll. */

    /* These are the offical fd_sets used to track what file descriptors
       need to be monitored. */
    volatile fd_set read_set;
    volatile fd_set write_set;
    volatile fd_set except_set;

    volatile int maxfd; /* The largest file descriptor registered with
			   this code. */
};

static void
sel_timer_lock(struct selector_s *sel)
{
    if (sel->sel_lock)
	sel->sel_lock(sel->timer_lock);
}

static void
sel_timer_unlock(struct selector_s *sel)
{
    if (sel->sel_lock)
	sel->sel_unlock(sel->timer_lock);
}

static void
sel_fd_lock(struct selector_s *sel)
{
    if (sel->sel_lock)
	sel->sel_lock(sel->fd_lock);
}

static void
sel_fd_unlock(struct selector_s *sel)
{
    if (sel->sel_lock)
	sel->sel_unlock(sel->fd_lock);
}

/* This function will wake the SEL thread.  It must be called with the
   timer lock held, because it messes with timeout.

   The operation is is subtle, but it does work.  The timeout in the
   selector is the data passed in (must be the actual data) as the
   timeout to select.  When we want to wake the select, we set the
   timeout to zero first.  That way, if the select has calculated the
   timeout but has not yet called select, then this will set it to
   zero (causing it to wait zero time).  If select has already been
   called, then the signal send should wake it up.  We only need to do
   this after we have calculated the timeout, but before we have
   called select, thus only things in the wait list matter. */
static void
i_wake_sel_thread(struct selector_s *sel, struct timeval *new_timeout)
{
    sel_wait_list_t *item;

    item = sel->wait_list.next;
    while (item != &sel->wait_list) {
	if (item->send_sig && (!new_timeout ||
			       cmp_timeval(new_timeout, &item->wake_time) < 0))
	    item->send_sig(item->thread_id, item->send_sig_cb_data);
	item = item->next;
    }
}

void
sel_wake_all(struct selector_s *sel)
{
    sel_timer_lock(sel);
    i_wake_sel_thread(sel, NULL);
    sel_timer_unlock(sel);
}

static void
wake_timer_sel_thread(struct selector_s *sel, volatile sel_timer_t *old_top,
		      struct timeval *new_timeout)
{
    if (old_top != theap_get_top(&sel->timer_heap))
	/* If the top value changed, restart the waiting threads if required. */
	i_wake_sel_thread(sel, new_timeout);
}

/* Wait list management.  These *must* be called with the timer list
   locked, and the values in the item *must not* change while in the
   list. */
static void
add_sel_wait_list(struct selector_s *sel, sel_wait_list_t *item,
		  sel_send_sig_cb send_sig,
		  void            *cb_data,
		  long thread_id,
		  struct timeval *wake_time)
{
    item->thread_id = thread_id;
    item->send_sig = send_sig;
    item->send_sig_cb_data = cb_data;
    item->wake_time = *wake_time;
    item->next = sel->wait_list.next;
    item->prev = &sel->wait_list;
    sel->wait_list.next->prev = item;
    sel->wait_list.next = item;
}
static void
remove_sel_wait_list(struct selector_s *sel, sel_wait_list_t *item)
{
    item->next->prev = item->prev;
    item->prev->next = item->next;
}

/* Initialize a single file descriptor. */
static void
init_fd(fd_control_t *fd)
{
    fd->state = NULL;
    fd->data = NULL;
    fd->handle_read = NULL;
    fd->handle_write = NULL;
    fd->handle_except = NULL;
    fd->read_enabled = 0;
    fd->write_enabled = 0;
    fd->except_enabled = 0;
}

#ifdef HAVE_EPOLL_PWAIT
static int
sel_update_fd(struct selector_s *sel, fd_control_t *fdc, int op)
{
    struct epoll_event event;
    int rv;

    if (sel->epollfd < 0)
	return 1;

    memset(&event, 0, sizeof(event));
    event.events = EPOLLONESHOT;
    event.data.fd = fdc->fd;
    if (fdc->saved_events) {
	if (op == EPOLL_CTL_DEL)
	    return 0;
	if (!fdc->read_enabled && !fdc->except_enabled)
	    return 0;
	fdc->saved_events = 0;
	op = EPOLL_CTL_ADD;
	if (fdc->read_enabled)
	    event.events |= EPOLLIN | EPOLLHUP;
	if (fdc->except_enabled)
	    event.events |= EPOLLERR | EPOLLPRI;
    } else if (op != EPOLL_CTL_DEL) {
	if (fdc->read_enabled)
	    event.events |= EPOLLIN | EPOLLHUP;
	if (fdc->write_enabled)
	    event.events |= EPOLLOUT;
	if (fdc->except_enabled)
	    event.events |= EPOLLERR | EPOLLPRI;
    }
    /* This should only fail due to system problems, and if that's the case,
       well, we should probably terminate. */
    rv = epoll_ctl(sel->epollfd, op, fdc->fd, &event);
    if (rv) {
	perror("epoll_ctl");
	assert(0);
    }
    return 0;
}
#else
static int
sel_update_fd(struct selector_s *sel, fd_control_t *fdc, int op)
{
    return 1;
}
#endif

static void
finish_oldstate(sel_runner_t *runner, void *cbdata)
{
    fd_state_t *oldstate = cbdata;

    if (oldstate->done)
	oldstate->done(oldstate->tmp_fd, oldstate->done_cbdata);
    free(oldstate);
}

/* Must be called with sel fd lock held. */
static fd_control_t *
get_fd(struct selector_s *sel, int fd)
{
    fd_control_t *fdc = sel->fds[fd % FD_SETSIZE];

    while (fdc && fdc->fd != fd)
	fdc = fdc->next;
    return fdc;
}

static void
valid_fd(struct selector_s *sel, int fd, fd_control_t **rfdc)
{
    fd_control_t *fdc;

    assert(fd >= 0);
    fdc = get_fd(sel, fd);
    assert(fdc != NULL);
    *rfdc = fdc;
}

/* Set the handlers for a file descriptor. */
int
sel_set_fd_handlers(struct selector_s *sel,
		    int               fd,
		    void              *data,
		    sel_fd_handler_t  read_handler,
		    sel_fd_handler_t  write_handler,
		    sel_fd_handler_t  except_handler,
		    sel_fd_cleared_cb done)
{
    fd_control_t *fdc;
    fd_state_t   *state, *oldstate = NULL;
    void         *olddata = NULL;
    int          added = 1;

#ifdef HAVE_EPOLL_PWAIT
    if (sel->epollfd < 0 && fd >= FD_SETSIZE)
	return EMFILE;
#endif

    state = sel_alloc(sizeof(*state));
    if (!state)
	return ENOMEM;
    memset(state, 0, sizeof(*state));
    state->done = done;
    memset(&state->done_runner, 0, sizeof(state->done_runner));
    state->done_runner.sel = sel;

    sel_fd_lock(sel);
    fdc = get_fd(sel, fd);
    if (!fdc) {
	fdc = sel_alloc(sizeof(*fdc));
	if (!fdc) {
	    sel_fd_unlock(sel);
	    free(state);
	    return ENOMEM;
	}
	fdc->fd = fd;
	/* Add it to the list. */
	fdc->next = sel->fds[fd % FD_SETSIZE];
	sel->fds[fd % FD_SETSIZE] = fdc;
    }

    if (fdc->state) {
	oldstate = fdc->state;
	olddata = fdc->data;
	added = 0;
#ifdef HAVE_EPOLL_PWAIT
	fdc->saved_events = 0;
#endif
	sel->fd_del_count++;
    }
    fdc->state = state;
    fdc->data = data;
    fdc->handle_read = read_handler;
    fdc->handle_write = write_handler;
    fdc->handle_except = except_handler;

    if (added) {
	/* Move maxfd up if necessary. */
	if (fd > sel->maxfd)
	    sel->maxfd = fd;

	if (sel_update_fd(sel, fdc, EPOLL_CTL_ADD))
	    sel_wake_all(sel);
    } else {
	if (sel_update_fd(sel, fdc, EPOLL_CTL_MOD))
	    sel_wake_all(sel);
    }
    sel_fd_unlock(sel);

    if (oldstate) {
	oldstate->deleted = 1;
	if (oldstate->use_count == 0) {
	    oldstate->tmp_fd = fd;
	    oldstate->done_cbdata = olddata;
	    sel_run(&oldstate->done_runner, finish_oldstate, oldstate);
	}
    }
    return 0;
}

static void
i_sel_clear_fd_handler(struct selector_s *sel, int fd, int rpt)
{
    fd_control_t *fdc;
    fd_state_t   *oldstate = NULL;
    void         *olddata = NULL;

    sel_fd_lock(sel);
    valid_fd(sel, fd, &fdc);

    if (fdc->state) {
	oldstate = fdc->state;
	olddata = fdc->data;
	fdc->state = NULL;

	sel_update_fd(sel, fdc, EPOLL_CTL_DEL);
#ifdef HAVE_EPOLL_PWAIT
	fdc->saved_events = 0;
#endif
	sel->fd_del_count++;
    }

    init_fd(fdc);
#ifdef HAVE_EPOLL_PWAIT
    if (sel->epollfd < 0)
#endif
    {
	FD_CLR(fd, &sel->read_set);
	FD_CLR(fd, &sel->write_set);
	FD_CLR(fd, &sel->except_set);
    }

    /* Move maxfd down if necessary. */
    if (fd == sel->maxfd) {
	while (sel->maxfd >= 0 && (!sel->fds[sel->maxfd] ||
				   !sel->fds[sel->maxfd]->state))
	    sel->maxfd--;
    }

    if (oldstate) {
	oldstate->deleted = 1;
	if (!rpt)
	    oldstate->done = NULL;
	if (oldstate->use_count == 0) {
	    oldstate->tmp_fd = fd;
	    oldstate->done_cbdata = olddata;
	    sel_run(&oldstate->done_runner, finish_oldstate, oldstate);
	}
    }

    sel_fd_unlock(sel);
}

/* Clear the handlers for a file descriptor and remove it from
   select's monitoring. */
void
sel_clear_fd_handlers(struct selector_s *sel, int fd)
{
    i_sel_clear_fd_handler(sel, fd, 1);
}

/* Clear the handlers for a file descriptor and remove it from
   select's monitoring, except that fd_cleared is not called. */
void
sel_clear_fd_handlers_norpt(struct selector_s *sel, int fd)
{
    i_sel_clear_fd_handler(sel, fd, 0);
}

/* Set whether the file descriptor will be monitored for data ready to
   read on the file descriptor. */
void
sel_set_fd_read_handler(struct selector_s *sel, int fd, int state)
{
    fd_control_t *fdc;

    sel_fd_lock(sel);
    valid_fd(sel, fd, &fdc);

    if (!fdc->state)
	goto out;

    if (state == SEL_FD_HANDLER_ENABLED) {
	if (fdc->read_enabled)
	    goto out;
	fdc->read_enabled = 1;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_SET(fd, &sel->read_set);
    } else if (state == SEL_FD_HANDLER_DISABLED) {
	if (!fdc->read_enabled)
	    goto out;
	fdc->read_enabled = 0;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_CLR(fd, &sel->read_set);
    }
    if (sel_update_fd(sel, fdc, EPOLL_CTL_MOD))
	sel_wake_all(sel);

 out:
    sel_fd_unlock(sel);
}

/* Set whether the file descriptor will be monitored for when the file
   descriptor can be written to. */
void
sel_set_fd_write_handler(struct selector_s *sel, int fd, int state)
{
    fd_control_t *fdc;

    sel_fd_lock(sel);
    valid_fd(sel, fd, &fdc);

    if (!fdc->state)
	goto out;

    if (state == SEL_FD_HANDLER_ENABLED) {
	if (fdc->write_enabled)
	    goto out;
	fdc->write_enabled = 1;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_SET(fd, &sel->write_set);
    } else if (state == SEL_FD_HANDLER_DISABLED) {
	if (!fdc->write_enabled)
	    goto out;
	fdc->write_enabled = 0;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_CLR(fd, &sel->write_set);
    }
    if (sel_update_fd(sel, fdc, EPOLL_CTL_MOD))
	sel_wake_all(sel);

 out:
    sel_fd_unlock(sel);
}

/* Set whether the file descriptor will be monitored for exceptions
   on the file descriptor. */
void
sel_set_fd_except_handler(struct selector_s *sel, int fd, int state)
{
    fd_control_t *fdc;

    sel_fd_lock(sel);
    valid_fd(sel, fd, &fdc);

    if (!fdc->state)
	goto out;

    if (state == SEL_FD_HANDLER_ENABLED) {
	if (fdc->except_enabled)
	    goto out;
	fdc->except_enabled = 1;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_SET(fd, &sel->except_set);
    } else if (state == SEL_FD_HANDLER_DISABLED) {
	if (!fdc->except_enabled)
	    goto out;
	fdc->except_enabled = 0;
#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd < 0)
#endif
	    FD_CLR(fd, &sel->except_set);
    }
    if (sel_update_fd(sel, fdc, EPOLL_CTL_MOD))
	sel_wake_all(sel);

 out:
    sel_fd_unlock(sel);
}

static void
diff_timeval(struct timeval *dest,
	     struct timeval *left,
	     struct timeval *right)
{
    if (   (left->tv_sec < right->tv_sec)
	|| (   (left->tv_sec == right->tv_sec)
	    && (left->tv_usec < right->tv_usec)))
    {
	/* If left < right, just force to zero, don't allow negative
           numbers. */
	dest->tv_sec = 0;
	dest->tv_usec = 0;
	return;
    }

    dest->tv_sec = left->tv_sec - right->tv_sec;
    dest->tv_usec = left->tv_usec - right->tv_usec;
    while (dest->tv_usec < 0) {
	dest->tv_usec += 1000000;
	dest->tv_sec--;
    }
}

static void
add_timeval(struct timeval *dest,
	    struct timeval *left,
	    struct timeval *right)
{
    dest->tv_sec = left->tv_sec + right->tv_sec;
    dest->tv_usec = left->tv_usec + right->tv_usec;
    while (dest->tv_usec > 1000000) {
	dest->tv_usec -= 1000000;
	dest->tv_sec++;
    }
}

int
sel_alloc_timer(struct selector_s     *sel,
		sel_timeout_handler_t handler,
		void                  *user_data,
		sel_timer_t           **new_timer)
{
    sel_timer_t *timer;

    timer = sel_alloc(sizeof(*timer));
    if (!timer)
	return ENOMEM;
    memset(timer, 0, sizeof(*timer));

    timer->val.handler = handler;
    timer->val.user_data = user_data;
    timer->val.sel = sel;
    timer->val.stopped = 1;
    *new_timer = timer;

    return 0;
}

static int
sel_stop_timer_i(struct selector_s *sel, sel_timer_t *timer)
{
    if (timer->val.stopped)
	return ETIMEDOUT;

    if (timer->val.in_heap) {
	theap_remove(&sel->timer_heap, timer);
	timer->val.in_heap = 0;
    }
    timer->val.stopped = 1;

    return 0;
}

int
sel_free_timer(sel_timer_t *timer)
{
    struct selector_s *sel = timer->val.sel;
    int in_handler;

    sel_timer_lock(sel);
    if (timer->val.in_heap)
	sel_stop_timer_i(sel, timer);
    timer->val.freed = 1;
    in_handler = timer->val.in_handler;
    sel_timer_unlock(sel);

    if (!in_handler)
	free(timer);

    return 0;
}

int
sel_start_timer(sel_timer_t    *timer,
		struct timeval *timeout)
{
    struct selector_s *sel = timer->val.sel;
    volatile sel_timer_t *old_top;

    sel_timer_lock(sel);
    if (timer->val.in_heap) {
	sel_timer_unlock(sel);
	return EBUSY;
    }

    old_top = theap_get_top(&sel->timer_heap);

    timer->val.timeout = *timeout;

    if (!timer->val.in_handler) {
	/* Wait until the handler returns to start the timer. */
	theap_add(&sel->timer_heap, timer);
	timer->val.in_heap = 1;
    }
    timer->val.stopped = 0;

    wake_timer_sel_thread(sel, old_top, timeout);

    sel_timer_unlock(sel);

    return 0;
}

int
sel_stop_timer(sel_timer_t *timer)
{
    struct selector_s *sel = timer->val.sel;
    int rv;

    sel_timer_lock(sel);
    rv = sel_stop_timer_i(sel, timer);
    sel_timer_unlock(sel);

    return rv;
}

int
sel_stop_timer_with_done(sel_timer_t *timer,
			 sel_timeout_handler_t done_handler,
			 void *cb_data)
{
    struct selector_s *sel = timer->val.sel;
    int rv = EBUSY;

    sel_timer_lock(sel);
    if (timer->val.done_handler)
	goto out_unlock;
    rv = ETIMEDOUT;
    if (timer->val.stopped || timer->val.in_handler)
	goto out_unlock;

    rv = 0;
    timer->val.stopped = 1;

    timer->val.done_handler = done_handler;
    timer->val.done_cb_data = cb_data;

    /*
     * We don't want to run the done handler here to avoid locking
     * issues.  So set it in_handler and stick it on the top of the
     * heap with an immediate timeout so it will be processed now.
     */
    timer->val.in_handler = 1;
    if (timer->val.in_heap) {
	theap_remove(&sel->timer_heap, timer);
	timer->val.in_heap = 0;
    }
    sel_get_monotonic_time(&timer->val.timeout);
    theap_add(&sel->timer_heap, timer);

 out_unlock:
    sel_timer_unlock(sel);
    return rv;
}

void
sel_get_monotonic_time(struct timeval *tv)
{
    struct timespec ts;

    clock_gettime(CLOCK_MONOTONIC, &ts);
    tv->tv_sec = ts.tv_sec;
    tv->tv_usec = (ts.tv_nsec + 500) / 1000;
}

/*
 * Process timers on selector.  The timeout is always set, to a very
 * long value if no timers are waiting.  Note that this *must* be
 * called with sel->timer_lock held.  Note that if this processes
 * any timers, the timeout will be set to { 0,0 }.
 */
static void
process_timers(struct selector_s       *sel,
	       unsigned int            *count,
	       volatile struct timeval *timeout,
	       struct timeval          *abstime)
{
    struct timeval now;
    sel_timer_t    *timer;

    timer = theap_get_top(&sel->timer_heap);
    sel_get_monotonic_time(&now);
    while (timer && cmp_timeval(&now, &timer->val.timeout) >= 0) {
	theap_remove(&(sel->timer_heap), timer);
	timer->val.in_heap = 0;
	timer->val.stopped = 1;

	/*
	 * A timer may be in a handler here if it has been stopped with
	 * a done_handler.  In that case the timer was stopped, so we
	 * don't call the main handler.
	 */
	if (!timer->val.in_handler) {
	    timer->val.in_handler = 1;
	    sel_timer_unlock(sel);
	    timer->val.handler(sel, timer, timer->val.user_data);
	    sel_timer_lock(sel);
	}
	(*count)++;
	if (timer->val.done_handler) {
	    sel_timeout_handler_t done_handler = timer->val.done_handler;
	    void *done_cb_data = timer->val.done_cb_data;

	    timer->val.done_handler = NULL;
	    timer->val.in_handler = 1;
	    sel_timer_unlock(sel);
	    done_handler(sel, timer, done_cb_data);
	    sel_timer_lock(sel);
	}
	timer->val.in_handler = 0;
	if (timer->val.freed)
	    free(timer);
	else if (!timer->val.stopped) {
	    /* We were restarted while in the handler. */
	    theap_add(&sel->timer_heap, timer);
	    timer->val.in_heap = 1;
	}

	timer = theap_get_top(&sel->timer_heap);
    }

    if (*count) {
	/* If called, set the timeout to zero. */
	timeout->tv_sec = 0;
	timeout->tv_usec = 0;
	*abstime = now;
    } else if (timer) {
	diff_timeval((struct timeval *) timeout,
		     (struct timeval *) &timer->val.timeout,
		     &now);
	*abstime = timer->val.timeout;
    } else {
	/* No timers, just set a long time. */
	timeout->tv_sec = 100000;
	timeout->tv_usec = 0;
	now.tv_sec +=timeout->tv_sec;
	*abstime = now;
    }
}

int
sel_alloc_runner(struct selector_s *sel, sel_runner_t **new_runner)
{
    sel_runner_t *runner;

    runner = sel_alloc(sizeof(*runner));
    if (!runner)
	return ENOMEM;
    memset(runner, 0, sizeof(*runner));
    runner->sel = sel;
    *new_runner = runner;
    return 0;
}

int
sel_free_runner(sel_runner_t *runner)
{
    struct selector_s *sel = runner->sel;

    sel_timer_lock(sel);
    if (runner->in_use) {
	sel_timer_unlock(sel);
	return EBUSY;
    }
    sel_timer_unlock(sel);
    free(runner);
    return 0;
}

int
sel_run(sel_runner_t *runner, sel_runner_func_t func, void *cb_data)
{
    struct selector_s *sel = runner->sel;

    sel_timer_lock(sel);
    if (runner->in_use) {
	sel_timer_unlock(sel);
	return EBUSY;
    }

    runner->func = func;
    runner->cb_data = cb_data;
    runner->next = NULL;
    runner->in_use = 1;

    if (sel->runner_tail) {
	sel->runner_tail->next = runner;
	sel->runner_tail = runner;
    } else {
	sel->runner_head = runner;
	sel->runner_tail = runner;
    }
    sel_timer_unlock(sel);
    return 0;
}

static unsigned int
process_runners(struct selector_s *sel)
{
    int count = 0;

    while (sel->runner_head) {
	sel_runner_t *runner = sel->runner_head;
	sel_runner_func_t func;
	void *cb_data;

	sel->runner_head = sel->runner_head->next;
	if (!sel->runner_head)
	    sel->runner_tail = NULL;
	runner->in_use = 0;
	func = runner->func;
	cb_data = runner->cb_data;
	sel_timer_unlock(sel);
	func(runner, cb_data);
	count++;
	sel_timer_lock(sel);
    }

    return count;
}

static void
handle_selector_call(struct selector_s *sel, fd_control_t *fdc,
		     volatile fd_set *fdset, int enabled,
		     sel_fd_handler_t handler)
{
    void             *data;
    fd_state_t       *state;

    if (handler == NULL) {
	/* Somehow we don't have a handler for this.
	   Just shut it down. */
	if (fdset)
	    FD_CLR(fdc->fd, fdset);
	return;
    }

    if (!enabled)
	/* The value was cleared, ignore it. */
	return;

    data = fdc->data;
    state = fdc->state;
    state->use_count++;
    sel_fd_unlock(sel);
    handler(fdc->fd, data);
    sel_fd_lock(sel);
    state->use_count--;
    if (state->deleted && state->use_count == 0) {
	if (state->done) {
	    sel_fd_unlock(sel);
	    state->done(fdc->fd, data);
	    sel_fd_lock(sel);
	}
	free(state);
    }
}

static void
setup_my_sigmask(sigset_t *sigmask, sigset_t *isigmask)
{
    if (isigmask) {
	*sigmask = *isigmask;
    } else {
#ifdef USE_PTHREADS
	pthread_sigmask(SIG_SETMASK, NULL, sigmask);
#else
	sigprocmask(SIG_SETMASK, NULL, sigmask);
#endif
    }
}

/*
 * return == 0  when timeout
 * 	  >  0  when successful
 * 	  <  0  when error
 */
static int
process_fds(struct selector_s	    *sel,
	    volatile struct timeval *timeout,
	    sigset_t *isigmask)
{
    fd_set      tmp_read_set;
    fd_set      tmp_write_set;
    fd_set      tmp_except_set;
    int i;
    int err;
    int num_fds;
    sigset_t sigmask;
    struct timespec ts = { .tv_sec = timeout->tv_sec,
			   .tv_nsec = timeout->tv_usec * 1000 };
    unsigned long entry_fd_del_count = sel->fd_del_count;
    fd_control_t *fdc;

    setup_my_sigmask(&sigmask, isigmask);
 retry:
    sel_fd_lock(sel);
    memcpy(&tmp_read_set, (void *) &sel->read_set, sizeof(tmp_read_set));
    memcpy(&tmp_write_set, (void *) &sel->write_set, sizeof(tmp_write_set));
    memcpy(&tmp_except_set, (void *) &sel->except_set, sizeof(tmp_except_set));
    num_fds = sel->maxfd + 1;
    sel_fd_unlock(sel);

    sigdelset(&sigmask, sel->wake_sig);
    err = pselect(num_fds,
		  &tmp_read_set,
		  &tmp_write_set,
		  &tmp_except_set,
		  &ts, &sigmask);
    if (err < 0) {
	if (errno == EBADF || errno == EBADFD)
	    /* We raced, just retry it. */
	    goto retry;
	goto out;
    }

    /* We got some I/O. */
    sel_fd_lock(sel);
    if (entry_fd_del_count != sel->fd_del_count)
	/* Something was deleted from the FD set, don't process this as it
	   may be from the old fd wakeup. */
	goto out_unlock;
    for (i = 0; i <= sel->maxfd; i++) {
	if (FD_ISSET(i, &tmp_read_set)) {
	    valid_fd(sel, i, &fdc);
	    handle_selector_call(sel, fdc, &sel->read_set, fdc->read_enabled,
				 fdc->handle_read);
	}
	if (FD_ISSET(i, &tmp_write_set)) {
	    valid_fd(sel, i, &fdc);
	    handle_selector_call(sel, fdc, &sel->write_set, fdc->write_enabled,
				 fdc->handle_write);
	}
	if (FD_ISSET(i, &tmp_except_set)) {
	    valid_fd(sel, i, &fdc);
	    handle_selector_call(sel, fdc, &sel->except_set,
				 fdc->except_enabled, fdc->handle_except);
	}
    }
 out_unlock:
    sel_fd_unlock(sel);
out:
    return err;
}

#ifdef HAVE_EPOLL_PWAIT
static int
process_fds_epoll(struct selector_s *sel, struct timeval *tvtimeout,
		  sigset_t *isigmask)
{
    int rv;
    struct epoll_event event;
    int timeout;
    sigset_t sigmask;
    fd_control_t *fdc;
    unsigned long entry_fd_del_count = sel->fd_del_count;

    setup_my_sigmask(&sigmask, isigmask);

    if (tvtimeout->tv_sec > 600)
	 /* Don't wait over 10 minutes, to work around an old epoll bug
	    and avoid issues with timeout overflowing on 64-bit systems,
	    which is much larger that 10 minutes, but who cares. */
	timeout = 600 * 1000;
    else
	timeout = ((tvtimeout->tv_sec * 1000) +
		   (tvtimeout->tv_usec + 999) / 1000);

    sigdelset(&sigmask, sel->wake_sig);
    rv = epoll_pwait(sel->epollfd, &event, 1, timeout, &sigmask);
    if (rv <= 0)
	return rv;

    sel_fd_lock(sel);
    valid_fd(sel, event.data.fd, &fdc);
    if (entry_fd_del_count != sel->fd_del_count)
	/* Something was deleted from the FD set, don't process this as it
	   may be from the old fd wakeup. */
	goto rearm;
    if (event.events & (EPOLLHUP | EPOLLERR)) {
	/*
	 * The crazy people that designed epoll made it so that EPOLLHUP
	 * and EPOLLERR always wake it up, even if they are not set.  That
	 * makes this fairly inconvenient, because we don't want to wake
	 * up in that case unless we explicitly ask for it.  Fortunately,
	 * in those cases we can pretty easily simulate it by just deleting
	 * it, since in those cases you will not get anything but an
	 * EPOLLHUP or EPOLLERR, anyway, and then doing the callback
	 * by hand.
	 */
	sel_update_fd(sel, fdc, EPOLL_CTL_DEL);
	fdc->saved_events = event.events & (EPOLLHUP | EPOLLERR);
	/*
	 * Have it handle read data, too, so if there is a pending
	 * error it will get handled.
	 */
	event.events |= EPOLLIN;
    }
    if (event.events & (EPOLLIN | EPOLLHUP))
	handle_selector_call(sel, fdc, NULL, fdc->read_enabled,
			     fdc->handle_read);
    if (event.events & EPOLLOUT)
	handle_selector_call(sel, fdc, NULL, fdc->write_enabled,
			     fdc->handle_write);
    if (event.events & (EPOLLPRI | EPOLLERR))
	handle_selector_call(sel, fdc, NULL, fdc->except_enabled,
			     fdc->handle_except);

 rearm:
    /* Rearm the event.  Remember it could have been deleted in the handler. */
    if (fdc->state)
	sel_update_fd(sel, fdc, EPOLL_CTL_MOD);
    sel_fd_unlock(sel);

    return rv;
}

int
sel_setup_forked_process(struct selector_s *sel)
{
    int i;

    /*
     * More epoll stupidity.  In a forked process we must create a new
     * epoll because the epoll state is shared between a parent and a
     * child.  If it worked like it should, each epoll instance would
     * be independent.  If you don't do this, disabling an fd in the
     * child disables the parent, too, and vice versa.
     */
    close(sel->epollfd);
    sel->epollfd = epoll_create(32768);
    if (sel->epollfd == -1) {
	return errno;
    }

    for (i = 0; i <= sel->maxfd; i++) {
	fd_control_t *fdc = sel->fds[i];
	if (fdc && fdc->state)
	    sel_update_fd(sel, fdc, EPOLL_CTL_ADD);
    }
    return 0;
}
#else
int
sel_setup_forked_process(struct selector_s *sel)
{
    /* Nothing to do. */
    return 0;
}
#endif

int
sel_select_intr_sigmask(struct selector_s *sel,
			sel_send_sig_cb send_sig,
			long            thread_id,
			void            *cb_data,
			struct timeval  *timeout,
			sigset_t        *sigmask)
{
    int             err = 0, old_errno;
    struct timeval  loc_timeout, wake_time;
    sel_wait_list_t wait_entry;
    unsigned int    count;
    struct timeval  end = { 0, 0 }, now;
    int user_timeout = 0;

    if (timeout) {
	sel_get_monotonic_time(&now);
	add_timeval(&end, &now, timeout);
    }

    sel_timer_lock(sel);
    count = process_runners(sel);
    process_timers(sel, &count, &loc_timeout, &wake_time);

    if (count == 0) {
	/* Didn't do anything, wait for something. */
	if (timeout) {
	    if (cmp_timeval(&loc_timeout, timeout) >= 0) {
		loc_timeout = *timeout;
		user_timeout = 1;
	    }
	}

	add_sel_wait_list(sel, &wait_entry, send_sig, cb_data, thread_id,
			  &wake_time);
	sel_timer_unlock(sel);

#ifdef HAVE_EPOLL_PWAIT
	if (sel->epollfd >= 0)
	    err = process_fds_epoll(sel, &loc_timeout, sigmask);
	else
#endif
	    err = process_fds(sel, &loc_timeout, sigmask);

	old_errno = errno;
	if (!user_timeout && !err) {
	    /*
	     * Only return a timeout if we waited on the user's timeout
	     * Otherwise there is a timer to process.
	     */
	    count++;
	}

	sel_timer_lock(sel);
	remove_sel_wait_list(sel, &wait_entry);

	/*
	 * Process runners before and after the wait.  This way any
	 * runners added while waiting will get processed.  Otherwise
	 * we would have to wake up other threads so the runners get
	 * handled immediately.  Do not add to the count, though, if
	 * we timed out we want to alert the user of that.
	 */
	process_runners(sel);
    }
    sel_timer_unlock(sel);
    if (timeout) {
	sel_get_monotonic_time(&now);
	diff_timeval(timeout, &end, &now);
    }

    if (err < 0) {
	errno = old_errno;
	return err;
    }

    return err + count;
}

int
sel_select_intr(struct selector_s *sel,
		sel_send_sig_cb send_sig,
		long            thread_id,
		void            *cb_data,
		struct timeval  *timeout)
{
    return sel_select_intr_sigmask(sel, send_sig, thread_id, cb_data, timeout,
				   NULL);
}

int
sel_select(struct selector_s *sel,
	   sel_send_sig_cb send_sig,
	   long            thread_id,
	   void            *cb_data,
	   struct timeval  *timeout)
{
    int err;

    err = sel_select_intr_sigmask(sel, send_sig, thread_id, cb_data, timeout,
				  NULL);
    if (err < 0 && errno == EINTR)
	/*
	 * If we get an EINTR, we don't want to report a timeout.  Just
	 * return that we did something.
	 */
	return 1;
    return err;
}

/* The main loop for the program.  This will select on the various
   sets, then scan for any available I/O to process.  It also monitors
   the time and call the timeout handlers periodically. */
int
sel_select_loop(struct selector_s *sel,
		sel_send_sig_cb send_sig,
		long            thread_id,
		void            *cb_data)
{
    for (;;) {
	int err = sel_select(sel, send_sig, thread_id, cb_data, NULL);

	if ((err < 0) && (errno != EINTR)) {
	    err = errno;
	    /* An error occurred. */
	    /* An error is bad, we need to abort. */
	    syslog(LOG_ERR, "select_loop() - select: %m");
	    return err;
	}
    }
}

/* Initialize the select code. */
int
sel_alloc_selector_thread(struct selector_s **new_selector, int wake_sig,
			  sel_lock_t *(*sel_lock_alloc)(void *cb_data),
			  void (*sel_lock_free)(sel_lock_t *),
			  void (*sel_lock)(sel_lock_t *),
			  void (*sel_unlock)(sel_lock_t *),
			  void *cb_data)
{
    struct selector_s *sel;
    int rv;
    sigset_t sigset;

    sel = sel_alloc(sizeof(*sel));
    if (!sel)
	return ENOMEM;
    memset(sel, 0, sizeof(*sel));

    sel->sel_lock_alloc = sel_lock_alloc;
    sel->sel_lock_free = sel_lock_free;
    sel->sel_lock = sel_lock;
    sel->sel_unlock = sel_unlock;

    /* The list is initially empty. */
    sel->wait_list.next = &sel->wait_list;
    sel->wait_list.prev = &sel->wait_list;

    sel->wake_sig = wake_sig;

    FD_ZERO((fd_set *) &sel->read_set);
    FD_ZERO((fd_set *) &sel->write_set);
    FD_ZERO((fd_set *) &sel->except_set);

    memset(sel->fds, 0, sizeof(sel->fds));

    theap_init(&sel->timer_heap);

    if (sel->sel_lock_alloc) {
	sel->timer_lock = sel->sel_lock_alloc(cb_data);
	if (!sel->timer_lock) {
	    free(sel);
	    return ENOMEM;
	}
	sel->fd_lock = sel->sel_lock_alloc(cb_data);
	if (!sel->fd_lock) {
	    sel->sel_lock_free(sel->fd_lock);
	    free(sel);
	    return ENOMEM;
	}
    }

    sigemptyset(&sigset);
    sigaddset(&sigset, wake_sig);
    rv = sigprocmask(SIG_BLOCK, &sigset, NULL);
    if (rv == -1) {
	rv = errno;
	if (sel->sel_lock_alloc) {
	    sel->sel_lock_free(sel->fd_lock);
		sel->sel_lock_free(sel->timer_lock);
	}
	free(sel);
	return rv;
    }

#ifdef HAVE_EPOLL_PWAIT
    sel->epollfd = epoll_create(32768);
    if (sel->epollfd == -1)
	syslog(LOG_ERR, "Unable to set up epoll, falling back to select: %m");
#endif

    *new_selector = sel;

    return 0;
}

int
sel_alloc_selector_nothread(struct selector_s **new_selector)
{
    return sel_alloc_selector_thread(new_selector, 0, NULL, NULL, NULL, NULL,
				     NULL);
}

int
sel_free_selector(struct selector_s *sel)
{
    sel_timer_t *elem;
    unsigned int i;

    elem = theap_get_top(&(sel->timer_heap));
    while (elem) {
	theap_remove(&(sel->timer_heap), elem);
	free(elem);
	elem = theap_get_top(&(sel->timer_heap));
    }
#ifdef HAVE_EPOLL_PWAIT
    if (sel->epollfd >= 0)
	close(sel->epollfd);
#endif
    for (i = 0; i < FD_SETSIZE; i++) {
	while (sel->fds[i]) {
	    fd_control_t *fdc = sel->fds[i];

	    sel->fds[i] = fdc->next;
	    if (fdc->state)
		free(fdc->state);
	    free(fdc);
	}
    }
    if (sel->fd_lock)
	sel->sel_lock_free(sel->fd_lock);
    if (sel->timer_lock)
	sel->sel_lock_free(sel->timer_lock);
    free(sel);

    return 0;
}