-
Notifications
You must be signed in to change notification settings - Fork 44
/
airscan-eloop.c
605 lines (501 loc) · 14.8 KB
/
airscan-eloop.c
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
/* AirScan (a.k.a. eSCL) backend for SANE
*
* Copyright (C) 2019 and up by Alexander Pevzner ([email protected])
* See LICENSE for license terms and conditions
*
* Event loop (runs in separate thread)
*/
#include "airscan.h"
#include <avahi-common/simple-watch.h>
#include <avahi-common/timeval.h>
#include <errno.h>
#include <unistd.h>
/******************** Constants *********************/
#define ELOOP_START_STOP_CALLBACKS_MAX 8
/******************** Static variables *********************/
static AvahiSimplePoll *eloop_poll;
static pthread_t eloop_thread;
static pthread_mutex_t eloop_mutex;
static bool eloop_thread_running;
static ll_head eloop_call_pending_list;
static bool eloop_poll_restart;
static __thread char eloop_estring[256];
static void (*eloop_start_stop_callbacks[ELOOP_START_STOP_CALLBACKS_MAX]) (bool);
static int eloop_start_stop_callbacks_count;
/******************** Standard errors *********************/
error ERROR_ENOMEM = (error) "Out of memory";
/******************** Forward declarations *********************/
static int
eloop_poll_func (struct pollfd *ufds, unsigned int nfds, int timeout, void *p);
static void
eloop_call_execute (void);
/* Initialize event loop
*/
SANE_Status
eloop_init (void)
{
pthread_mutexattr_t attr;
bool attr_initialized = false;
bool mutex_initialized = false;
SANE_Status status = SANE_STATUS_NO_MEM;
ll_init(&eloop_call_pending_list);
eloop_start_stop_callbacks_count = 0;
/* Initialize eloop_mutex */
if (pthread_mutexattr_init(&attr)) {
goto DONE;
}
attr_initialized = true;
if (pthread_mutexattr_settype(&attr, PTHREAD_MUTEX_RECURSIVE)) {
goto DONE;
}
if (pthread_mutex_init(&eloop_mutex, &attr)) {
goto DONE;
}
mutex_initialized = true;
/* Create AvahiSimplePoll */
eloop_poll = avahi_simple_poll_new();
if (eloop_poll == NULL) {
goto DONE;
}
avahi_simple_poll_set_func(eloop_poll, eloop_poll_func, NULL);
/* Update status */
status = SANE_STATUS_GOOD;
/* Cleanup and exit */
DONE:
if (attr_initialized) {
pthread_mutexattr_destroy(&attr);
}
if (status != SANE_STATUS_GOOD && mutex_initialized) {
pthread_mutex_destroy(&eloop_mutex);
}
return status;
}
/* Cleanup event loop
*/
void
eloop_cleanup (void)
{
if (eloop_poll != NULL) {
avahi_simple_poll_free(eloop_poll);
pthread_mutex_destroy(&eloop_mutex);
eloop_poll = NULL;
}
}
/* Add start/stop callback. This callback is called
* on a event loop thread context, once when event
* loop is started, and second time when it is stopped
*
* Start callbacks are called in the same order as
* they were added. Stop callbacks are called in a
* reverse order
*/
void
eloop_add_start_stop_callback (void (*callback) (bool start))
{
log_assert(NULL,
eloop_start_stop_callbacks_count < ELOOP_START_STOP_CALLBACKS_MAX);
eloop_start_stop_callbacks[eloop_start_stop_callbacks_count] = callback;
eloop_start_stop_callbacks_count ++;
}
/* Poll function hook
*/
static int
eloop_poll_func (struct pollfd *ufds, unsigned int nfds, int timeout,
void *userdata)
{
int rc;
(void) userdata;
eloop_poll_restart = false;
pthread_mutex_unlock(&eloop_mutex);
rc = poll(ufds, nfds, timeout);
pthread_mutex_lock(&eloop_mutex);
/* Avahi multithreading support is semi-broken. Though new
* AvahiWatch could be added from a context of any thread
* (Avahi internal structures are properly interlocked, and
* event loop thread is properly woken by poll->watch_new()),
* Avahi internal indices are only rebuild in the beginning
* of the avahi_simple_poll_iterate(), when avahi_simple_poll_prepare()
* is called. So when Avahi returns from the poll() syscall
* and calls avahi_simple_poll_dispatch(), it asserts, if new
* AvahiWatch, which causes process to crash.
*
* To work around this crash, we force avahi_simple_poll_iterate()
* to exit before calling of avahi_simple_poll_dispatch() by
* returning error code from here. The subsequent call of
* avahi_simple_poll_iterate() fixes the situation by calling
* avahi_simple_poll_prepare() first.
*
* The returned error code cannot be EINTR, because interrupted
* system call errors are ignored by Avahi (it simply restarts
* the operation) and needs to be distinguished by a "normal"
* errors, so event loop in the eloop_thread_func() will handle
* it in appropriate manner.
*
* For now we use EBUSY error code for this purpose
*/
if (eloop_poll_restart) {
/* We have to return an error other than EINTR to restart the
avahi loop. */
errno = EBUSY;
return -1;
}
return rc;
}
/* Event loop thread main function
*/
static void*
eloop_thread_func (void *data)
{
int i;
(void) data;
pthread_mutex_lock(&eloop_mutex);
for (i = 0; i < eloop_start_stop_callbacks_count; i ++) {
eloop_start_stop_callbacks[i](true);
}
__atomic_store_n(&eloop_thread_running, true, __ATOMIC_SEQ_CST);
do {
eloop_call_execute();
i = avahi_simple_poll_iterate(eloop_poll, -1);
} while (i == 0 || (i < 0 && (errno == EINTR || errno == EBUSY)));
for (i = eloop_start_stop_callbacks_count - 1; i >= 0; i --) {
eloop_start_stop_callbacks[i](false);
}
pthread_mutex_unlock(&eloop_mutex);
return NULL;
}
/* Start event loop thread.
*/
void
eloop_thread_start (void)
{
int rc;
useconds_t usec = 100;
rc = pthread_create(&eloop_thread, NULL, eloop_thread_func, NULL);
if (rc != 0) {
log_panic(NULL, "pthread_create: %s", strerror(rc));
}
/* Wait until thread is started and all start callbacks are executed */
while (!__atomic_load_n(&eloop_thread_running, __ATOMIC_SEQ_CST)) {
usleep(usec);
usec += usec;
}
}
/* Stop event loop thread and wait until its termination
*/
void
eloop_thread_stop (void)
{
if (__atomic_load_n(&eloop_thread_running, __ATOMIC_SEQ_CST)) {
avahi_simple_poll_quit(eloop_poll);
pthread_join(eloop_thread, NULL);
__atomic_store_n(&eloop_thread_running, false, __ATOMIC_SEQ_CST);
}
}
/* Acquire event loop mutex
*/
void
eloop_mutex_lock (void)
{
pthread_mutex_lock(&eloop_mutex);
}
/* Release event loop mutex
*/
void
eloop_mutex_unlock (void)
{
pthread_mutex_unlock(&eloop_mutex);
}
/* Wait on conditional variable under the event loop mutex
*/
void
eloop_cond_wait (pthread_cond_t *cond)
{
pthread_cond_wait(cond, &eloop_mutex);
}
/* Get AvahiPoll that runs in event loop thread
*/
const AvahiPoll*
eloop_poll_get (void)
{
return avahi_simple_poll_get(eloop_poll);
}
/* eloop_call_pending represents a pending eloop_call
*/
typedef struct {
void (*func)(void*); /* Function to be called */
void *data; /* It's argument */
uint64_t callid; /* For eloop_call_cancel() */
ll_node node; /* In eloop_call_pending_list */
} eloop_call_pending;
/* Execute function calls deferred by eloop_call()
*/
static void
eloop_call_execute (void)
{
ll_node *node;
while ((node = ll_pop_beg(&eloop_call_pending_list)) != NULL) {
eloop_call_pending *pending;
pending = OUTER_STRUCT(node, eloop_call_pending, node);
pending->func(pending->data);
mem_free(pending);
}
}
/* Call function on a context of event loop thread
* The returned value can be supplied as a `callid'
* parameter for the eloop_call_cancel() function
*/
uint64_t
eloop_call (void (*func)(void*), void *data)
{
eloop_call_pending *p = mem_new(eloop_call_pending, 1);
static uint64_t callid;
uint64_t ret;
p->func = func;
p->data = data;
pthread_mutex_lock(&eloop_mutex);
ret = ++ callid;
p->callid = ret;
ll_push_end(&eloop_call_pending_list, &p->node);
pthread_mutex_unlock(&eloop_mutex);
avahi_simple_poll_wakeup(eloop_poll);
return ret;
}
/* Cancel pending eloop_call
*
* This is safe to cancel already finished call (at this
* case nothing will happen)
*/
void
eloop_call_cancel (uint64_t callid)
{
ll_node *node;
for (LL_FOR_EACH(node, &eloop_call_pending_list)) {
eloop_call_pending *p = OUTER_STRUCT(node, eloop_call_pending, node);
if (p->callid == callid) {
ll_del(&p->node);
mem_free(p);
return;
}
}
}
/* Event notifier. Calls user-defined function on a context
* of event loop thread, when event is triggered. This is
* safe to trigger the event from a context of any thread
* or even from a signal handler
*/
struct eloop_event {
pollable *p; /* Underlying pollable event */
eloop_fdpoll *fdpoll; /* Underlying fdpoll */
void (*callback)(void*); /* user-defined callback */
void *data; /* callback's argument */
};
/* eloop_event eloop_fdpoll callback
*/
static void
eloop_event_callback (int fd, void *data, ELOOP_FDPOLL_MASK mask)
{
eloop_event *event = data;
(void) fd;
(void) mask;
pollable_reset(event->p);
event->callback(event->data);
}
/* Create new event notifier. May return NULL
*/
eloop_event*
eloop_event_new (void (*callback)(void *), void *data)
{
eloop_event *event;
pollable *p;
p = pollable_new();
if (p == NULL) {
return NULL;
}
event = mem_new(eloop_event, 1);
event->p = p;
event->callback = callback;
event->data = data;
event->fdpoll = eloop_fdpoll_new(pollable_get_fd(p),
eloop_event_callback, event);
eloop_fdpoll_set_mask(event->fdpoll, ELOOP_FDPOLL_READ);
return event;
}
/* Destroy event notifier
*/
void
eloop_event_free (eloop_event *event)
{
eloop_fdpoll_free(event->fdpoll);
pollable_free(event->p);
mem_free(event);
}
/* Trigger an event
*/
void
eloop_event_trigger (eloop_event *event)
{
pollable_signal(event->p);
}
/* Timer. Calls user-defined function after a specified
* interval
*/
struct eloop_timer {
AvahiTimeout *timeout; /* Underlying AvahiTimeout */
void (*callback)(void *); /* User callback */
void *data; /* User data */
};
/* eloop_timer callback for AvahiTimeout
*/
static void
eloop_timer_callback (AvahiTimeout *t, void *data)
{
eloop_timer *timer = data;
(void) t;
timer->callback(timer->data);
eloop_timer_cancel(timer);
}
/* Create new timer. Timeout is in milliseconds
*/
eloop_timer*
eloop_timer_new (int timeout, void (*callback)(void *), void *data)
{
const AvahiPoll *poll = eloop_poll_get();
eloop_timer *timer = mem_new(eloop_timer, 1);
struct timeval end;
avahi_elapse_time(&end, timeout, 0);
timer->timeout = poll->timeout_new(poll, &end, eloop_timer_callback, timer);
timer->callback = callback;
timer->data = data;
return timer;
}
/* Cancel a timer
*
* Caller SHOULD NOT cancel expired timer (timer with called
* callback) -- this is done automatically
*/
void
eloop_timer_cancel (eloop_timer *timer)
{
const AvahiPoll *poll = eloop_poll_get();
poll->timeout_free(timer->timeout);
mem_free(timer);
}
/* Convert ELOOP_FDPOLL_MASK to string. Used for logging.
*/
const char*
eloop_fdpoll_mask_str (ELOOP_FDPOLL_MASK mask)
{
switch (mask & ELOOP_FDPOLL_BOTH) {
case 0: return "{--}";
case ELOOP_FDPOLL_READ: return "{r-}";
case ELOOP_FDPOLL_WRITE: return "{-w}";
case ELOOP_FDPOLL_BOTH: return "{rw}";
}
return "{??}"; /* Should never happen indeed */
}
/* eloop_fdpoll notifies user when file becomes
* readable, writable or both, depending on its
* event mask
*/
struct eloop_fdpoll {
AvahiWatch *watch; /* Underlying AvahiWatch */
int fd; /* Underlying file descriptor */
ELOOP_FDPOLL_MASK mask; /* Mask of active events */
void (*callback)( /* User-defined callback */
int, void*, ELOOP_FDPOLL_MASK);
void *data; /* Callback's data */
};
/* eloop_fdpoll callback for AvahiWatch
*/
static void
eloop_fdpoll_callback (AvahiWatch *w, int fd, AvahiWatchEvent event,
void *data)
{
eloop_fdpoll *fdpoll = data;
ELOOP_FDPOLL_MASK mask = 0;
(void) w;
if ((event & AVAHI_WATCH_IN) != 0) {
mask |= ELOOP_FDPOLL_READ;
}
if ((event & AVAHI_WATCH_OUT) != 0) {
mask |= ELOOP_FDPOLL_WRITE;
}
fdpoll->callback(fd, fdpoll->data, mask);
}
/* Create eloop_fdpoll
*
* Callback will be called, when file will be ready for read/write/both,
* depending on mask
*
* Initial mask value is 0, and it can be changed, using
* eloop_fdpoll_set_mask() function
*/
eloop_fdpoll*
eloop_fdpoll_new (int fd,
void (*callback) (int, void*, ELOOP_FDPOLL_MASK), void *data)
{
const AvahiPoll *poll = eloop_poll_get();
eloop_fdpoll *fdpoll = mem_new(eloop_fdpoll, 1);
fdpoll->fd = fd;
fdpoll->callback = callback;
fdpoll->data = data;
eloop_poll_restart = true;
fdpoll->watch = poll->watch_new(poll, fd, 0, eloop_fdpoll_callback, fdpoll);
return fdpoll;
}
/* Destroy eloop_fdpoll
*/
void
eloop_fdpoll_free (eloop_fdpoll *fdpoll)
{
const AvahiPoll *poll = eloop_poll_get();
poll->watch_free(fdpoll->watch);
mem_free(fdpoll);
}
/* Set eloop_fdpoll event mask. It returns a previous value of event mask
*/
ELOOP_FDPOLL_MASK
eloop_fdpoll_set_mask (eloop_fdpoll *fdpoll, ELOOP_FDPOLL_MASK mask)
{
ELOOP_FDPOLL_MASK old_mask = fdpoll->mask;
if (old_mask != mask) {
const AvahiPoll *poll = eloop_poll_get();
AvahiWatchEvent events = 0;
if ((mask & ELOOP_FDPOLL_READ) != 0) {
events |= AVAHI_WATCH_IN;
}
if ((mask & ELOOP_FDPOLL_WRITE) != 0) {
events |= AVAHI_WATCH_OUT;
}
fdpoll->mask = mask;
poll->watch_update(fdpoll->watch, events);
}
return old_mask;
}
/* Format error string, as printf() does and save result
* in the memory, owned by the event loop
*
* Caller should not free returned string. This is safe
* to use the returned string as an argument to the
* subsequent eloop_eprintf() call.
*
* The returned string remains valid until next call
* to eloop_eprintf(), which makes it usable to
* report errors up by the stack. However, it should
* not be assumed, that the string will remain valid
* on a next eloop roll, so don't save this string
* anywhere, if you need to do so, create a copy!
*/
error
eloop_eprintf(const char *fmt, ...)
{
va_list ap;
char buf[sizeof(eloop_estring)];
va_start(ap, fmt);
vsnprintf(buf, sizeof(buf), fmt, ap);
strcpy(eloop_estring, buf);
va_end(ap);
return ERROR(eloop_estring);
}
/* vim:ts=8:sw=4:et
*/