forked from joan2937/lg
-
Notifications
You must be signed in to change notification settings - Fork 2
/
lgPthAlerts.c
700 lines (577 loc) · 19 KB
/
lgPthAlerts.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
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
/*
This is free and unencumbered software released into the public domain.
Anyone is free to copy, modify, publish, use, compile, sell, or
distribute this software, either in source code form or as a compiled
binary, for any purpose, commercial or non-commercial, and by any
means.
In jurisdictions that recognize copyright laws, the author or authors
of this software dedicate any and all copyright interest in the
software to the public domain. We make this dedication for the benefit
of the public at large and to the detriment of our heirs and
successors. We intend this dedication to be an overt act of
relinquishment in perpetuity of all present and future rights to this
software under copyright law.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
OTHER DEALINGS IN THE SOFTWARE.
For more information, please refer to <http://unlicense.org/>
*/
#define _GNU_SOURCE /* needed for ppoll */
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
#include <poll.h>
#include "lgDbg.h"
#include "lgHdl.h"
#include "lgGpio.h"
#include "lgPthAlerts.h"
#define LG_MAX_ALERTS 2000
#define LG_GPIO_MAX_ALERTS_PER_READ 128
pthread_t pthAlert;
pthread_mutex_t lgAlertMutex = PTHREAD_MUTEX_INITIALIZER;
volatile lgAlertRec_p alertRec = NULL;
pthread_mutex_t lgAlertCondMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t lgAlertCond = PTHREAD_COND_INITIALIZER;
int pthAlertRunning = LG_THREAD_NONE;
lgGpioAlert_t aBuf[LG_MAX_ALERTS];
static void xWaitForSignal(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
pthread_mutex_lock(mutex);
pthread_cond_wait(cond, mutex);
pthread_mutex_unlock(mutex);
}
void xSendUnwaitSignal(pthread_cond_t *cond, pthread_mutex_t *mutex)
{
pthread_mutex_lock(mutex);
pthread_cond_signal(cond);
pthread_mutex_unlock(mutex);
}
int tscomp(const void *p1, const void *p2)
{
const lgGpioAlert_t *e1 = p1;
const lgGpioAlert_t *e2 = p2;
return e1->report.timestamp - e2->report.timestamp;
}
uint64_t xMonotonicTimestamp(void)
{
struct timespec xts;
clock_gettime(CLOCK_MONOTONIC, &xts); // get current time
return ((uint64_t)1E9 * xts.tv_sec) + xts.tv_nsec;
}
void emitNotifications(int count)
{
static int maxHandles = 20;
static int *handles = NULL;
lgGpioReport_t report[LG_MAX_ALERTS];
int numHandles;
int i;
int status;
lgNotify_t *h;
int emit;
int d;
int sent;
int max_emits;
int err;
if (handles == NULL) handles = malloc(sizeof(int) * maxHandles);
numHandles = lgHdlGetHandlesForType(
LG_HDL_TYPE_NOTIFY, handles, maxHandles);
if (numHandles > maxHandles)
{
LG_DBG(LG_DEBUG_ALWAYS, "too many notifications");
numHandles = maxHandles;
}
for (i=0; i<numHandles; i++)
{
status = lgHdlGetLockedObjTrusted(
handles[i], LG_HDL_TYPE_NOTIFY, (void **)&h);
if (status < 0) continue;
if (h->state == LG_NOTIFY_CLOSING)
{
lgHdlFree(handles[i], LG_HDL_TYPE_NOTIFY);
}
else if (h->state >= LG_NOTIFY_RUNNING)
{
emit = 0;
if (h->state == LG_NOTIFY_RUNNING)
{
for (d=0; d<count; d++)
{
/* is this for this notify handle? */
if (handles[i] == aBuf[d].nfyHandle)
{
report[emit] = aBuf[d].report;
emit++;
}
}
}
if (emit)
{
max_emits = h->max_emits;
sent = 0;
while (emit > 0)
{
if (emit > max_emits)
{
err = write(h->fd,
report+sent,
max_emits*sizeof(lgGpioReport_t));
if (err != (max_emits*sizeof(lgGpioReport_t)))
{
if (err < 0)
{
if ((errno != EAGAIN) && (errno != EWOULDBLOCK))
{
/* serious error, no point continuing */
LG_DBG(LG_DEBUG_ALWAYS, "fd=%d err=%d errno=%d",
h->fd, err, errno);
LG_DBG(LG_DEBUG_ALWAYS, "%s", strerror(errno));
h->state = LG_NOTIFY_CLOSING;
break;
}
//else gpioStats.wouldBlockPipeWrite++;
}
else
{
//gpioStats.shortPipeWrite++;
LG_DBG(LG_DEBUG_ALWAYS, "sent %zd, asked for %d",
err/sizeof(lgGpioReport_t), max_emits);
}
}
else
{
//gpioStats.goodPipeWrite++;
}
sent += max_emits;
emit -= max_emits;
}
else
{
err = write(h->fd,
report+sent,
emit*sizeof(lgGpioReport_t));
if (err != (emit*sizeof(lgGpioReport_t)))
{
if (err < 0)
{
if ((errno != EAGAIN) && (errno != EWOULDBLOCK))
{
LG_DBG(LG_DEBUG_ALWAYS, "fd=%d err=%d errno=%d",
h->fd, err, errno);
LG_DBG(LG_DEBUG_ALWAYS, "%s", strerror(errno));
/* serious error, no point continuing */
h->state = LG_NOTIFY_CLOSING;
break;
}
//else gpioStats.wouldBlockPipeWrite++;
}
else
{
//gpioStats.shortPipeWrite++;
LG_DBG(LG_DEBUG_ALWAYS, "sent %zd, asked for %d",
err/sizeof(lgGpioReport_t), emit);
}
}
else
{
//gpioStats.goodPipeWrite++;
}
sent += emit;
emit = 0;
}
}
}
}
lgHdlUnlock(handles[i]);
}
}
int emit(int count, uint64_t tmax)
{
int i;
for (i=0; i<count; i++)
{
if (aBuf[i].report.timestamp > tmax) break;
}
if (lgGpioSamplesFunc)
(lgGpioSamplesFunc)(i, aBuf, lgGpioSamplesUserdata);
emitNotifications(i);
return i;
}
void printbuf(int count, char *str)
{
int i;
fprintf(stderr, "%s\n", str);
for (i=0; i<count; i++)
{
fprintf(stderr, "%"PRIu64" %d %d %d (%d of %d)\n",
aBuf[i].report.timestamp, aBuf[i].report.level,
aBuf[i].report.chip, aBuf[i].report.gpio, i+1, count);
}
}
void lgcheck(int count, char *str)
{
int i;
int64_t diff;
for (i=1; i<count; i++)
{
diff = aBuf[i-1].report.timestamp - aBuf[i].report.timestamp;
if (diff > 0)
{
fprintf(stderr, "%s\n%"PRIu64" %d %d %d\n",
str, aBuf[i-1].report.timestamp, aBuf[i-1].report.level,
aBuf[i-1].report.chip, aBuf[i-1].report.gpio);
fprintf(stderr, "%"PRIu64" %d %d %d\n\n",
aBuf[i].report.timestamp, aBuf[i].report.level,
aBuf[i].report.chip, aBuf[i].report.gpio);
}
}
}
void xDebWatEvt(
lgAlertRec_p p, uint64_t ts, int *cp, struct gpio_v2_line_event *ep)
{
int64_t nano_diff;
if (p->debounce_nanos && !p->debounced)
{
/*
Only report stable edges. A stable edge is defined as one
which has not changed for debounce nanoseconds.
The following rules are applied.
1. If only rising edges are being monitored a rising edge
is reported if and only no other edge is detected for at
least debounce nanoseconds after it occurred.
2. If only falling edges are being monitored a falling edge
is reported if and only no other edge is detected for at
least debounce nanoseconds after it occurred.
3. If both edges are being monitored an edge is reported
if and only no other edge is detected for at least debounce
nanoseconds after it occurred and the edge is different to
the previously reported edge.
*/
nano_diff = ts - p->last_evt_ts;
if (nano_diff > p->debounce_nanos)
{
/* GPIO stable for debounce period */
if ((p->eFlags != LG_BOTH_EDGES) ||
(p->last_rpt_lv != p->last_evt_lv))
{
/*
LG_DBG(LG_DEBUG_ALWAYS, "g=%d(%d) diff=%"PRId64" deb=%"PRIu64" ts=%"PRIu64" lts=%"PRIu64"",
p->gpio, p->last_evt_lv, nano_diff, p->debounce_nanos, ts/100000, p->last_evt_ts/100000);
*/
aBuf[*cp].report.timestamp = p->last_evt_ts + p->debounce_nanos;
aBuf[*cp].report.level = p->last_evt_lv;
aBuf[*cp].report.chip = p->chip->gpiochip;
aBuf[*cp].report.gpio = p->gpio;
aBuf[*cp].report.flags = 0;
aBuf[*cp].nfyHandle = p->nfyHandle;
if (++(*cp) < LG_MAX_ALERTS)
{
p->last_rpt_ts = p->last_evt_ts + p->debounce_nanos;
p->last_rpt_lv = p->last_evt_lv;
p->debounced = 1;
p->watchdogd = 0;
}
else
{
--(*cp);
LG_DBG(LG_DEBUG_ALWAYS, "more than %d alerts", LG_MAX_ALERTS);
}
}
}
}
if (p->watchdog_nanos && !p->watchdogd)
{
/*
Ensure that a watchdog report is sent for a GPIO in the
absence of edge reports.
The following rule is applied.
If no edge report has been issued for the GPIO in
the last watchdog nanoseconds then one watchdog report
is generated.
Note that only one watchdog report is sent until the
watchdog is reset by the sending of an edge report.
*/
nano_diff = ts - p->last_rpt_ts;
if (nano_diff > p->watchdog_nanos)
{
/*
LG_DBG(LG_DEBUG_ALWAYS, "g=%d(2) diff=%"PRId64" wdg=%"PRIu64" ts=%"PRIu64" lts=%"PRIu64"",
p->gpio, nano_diff, p->watchdog_nanos, ts/100000, p->last_rpt_ts/100000);
*/
aBuf[*cp].report.timestamp = p->last_rpt_ts + p->watchdog_nanos;
aBuf[*cp].report.level = LG_TIMEOUT;
aBuf[*cp].report.chip = p->chip->gpiochip;
aBuf[*cp].report.gpio = p->gpio;
aBuf[*cp].report.flags = 0;
aBuf[*cp].nfyHandle = p->nfyHandle;
if (++(*cp) < LG_MAX_ALERTS)
{
p->watchdogd = 1;
p->last_rpt_ts = p->last_rpt_ts + p->watchdog_nanos;
p->last_rpt_lv = LG_TIMEOUT;
}
else
{
--(*cp);
LG_DBG(LG_DEBUG_ALWAYS, "more than %d alerts", LG_MAX_ALERTS);
}
}
}
if (ep != NULL)
{
p->last_evt_ts = ts;
p->last_evt_lv = 2 - ep->id; /* (falling) 2 (rising) 1 -> 0 1 */
p->debounced = 0;
if (!p->debounce_nanos) // report straightaway if no debounce
{
aBuf[*cp].report.timestamp = p->last_evt_ts;
aBuf[*cp].report.level = p->last_evt_lv;
aBuf[*cp].report.chip = p->chip->gpiochip;
aBuf[*cp].report.gpio = p->gpio;
aBuf[*cp].report.flags = 0;
aBuf[*cp].nfyHandle = p->nfyHandle;
if (++(*cp) < LG_MAX_ALERTS)
{
p->watchdogd = 0;
p->last_rpt_ts = p->last_evt_ts;
p->last_rpt_lv = p->last_evt_lv;
}
else
{
--(*cp);
LG_DBG(LG_DEBUG_ALWAYS, "more than %d alerts", LG_MAX_ALERTS);
}
}
}
}
void *lgPthAlert(void)
{
lgAlertRec_p p, t;
int i, e;
int num_gpio;
int gpiobasecount;
int retval;
int count=0;
int sent;
int bytes;
uint64_t lastGT=0;
uint64_t lastLT=0;
uint64_t nowLT;
uint64_t nowGT;
struct pollfd pfd[64];
lgAlertRec_p pAlertRec[64];
struct gpio_v2_line_event eIn[LG_GPIO_MAX_ALERTS_PER_READ];
struct timespec tspec = {0, 5e5}; /* 0.5 ms timeout */
while (1)
{
pthread_mutex_lock(&lgAlertMutex);
if (alertRec != NULL)
{
p = alertRec;
i = 0;
/* poll active alerts */
while (p != NULL)
{
if (p->active)
{
pfd[i].fd= p->state->fd;
pfd[i].events = POLLIN|POLLPRI;
pAlertRec[i] = p;
i++;
}
else
{
/* delete inactive record */
if (p->prev) p->prev->next = p->next;
else alertRec = p->next;
if (p->next) p->next->prev = p->prev;
t = p; p = p->prev; free(t);
}
if (p) p = p->next;
}
num_gpio = i;
pthread_mutex_unlock(&lgAlertMutex);
if (num_gpio > 0)
{
retval = ppoll(pfd, num_gpio, &tspec, NULL);
nowLT = xMonotonicTimestamp();
for (i=0; i<num_gpio; i++)
{
gpiobasecount = count;
p = pAlertRec[i];
if ((retval > 0) && (pfd[i].revents))
{
/* GPIO changed during ppoll */
bytes = read(pfd[i].fd, &eIn, sizeof(eIn));
if (bytes > 0)
{
e = 0;
while (bytes >= sizeof(eIn[0]))
{
/* debounce and watchdog */
xDebWatEvt(p, eIn[e].timestamp_ns, &count, &eIn[e]);
bytes -= sizeof(eIn[0]);
e++;
}
if (e)
{
p->last_rpt_ts = eIn[e-1].timestamp_ns;
if (eIn[e-1].timestamp_ns > lastGT)
{
lastGT = eIn[e-1].timestamp_ns;
lastLT = nowLT;
}
}
if (bytes)
{
if (p->active)
LG_DBG(LG_DEBUG_ALWAYS, "bytes left=%d (%s)",
bytes, strerror(errno));
}
}
else
{
if (p->active)
LG_DBG(LG_DEBUG_ALWAYS, "read error %d (%s)",
errno, strerror(errno));
}
}
if (gpiobasecount < count)
{
if (p->state->alertFunc)
{
(p->state->alertFunc)(count-gpiobasecount,
&aBuf[gpiobasecount], p->state->userdata);
}
}
}
nowGT = lastGT + (nowLT - lastLT);
// LG_DBG(LG_DEBUG_ALWAYS, "ts=%"PRIu64"", nowGT/100000);
if (lastGT)
{
for (i=0; i<num_gpio; i++)
{
gpiobasecount = count;
p = pAlertRec[i];
// The 50 microsecond leeway is to make sure the
// kernel has supplied current data for all GPIO
// before timing out debounce and watchdogs.
xDebWatEvt(p, nowGT-50000, &count, NULL);
if (gpiobasecount < count)
{
if (p->state->alertFunc)
{
(p->state->alertFunc)(count-gpiobasecount,
&aBuf[gpiobasecount], p->state->userdata);
}
}
}
}
if (count > 1)
{
/*
LG_DBG(LG_DEBUG_ALWAYS, "nowGT=%"PRIu64" count=%d",
nowGT/100000, count);
*/
// printbuf(count, "pre qsort");
qsort(aBuf, count, sizeof(aBuf[0]), tscomp);
//lgcheck(count, "check post qsort");
// printbuf(count, "post qsort");
}
/* emit any due alerts */
// printbuf(count, "pre emit");
// delay 500 microseconds before reporting a GPIO
// to make sure the events are sorted in time order.
sent = emit(count, nowGT-500000);
if (sent)
{
if (sent != count)
{
/* shuffle entries down */
memmove(aBuf, aBuf+sent, sizeof(aBuf[0])*(count-sent));
}
count -= sent;
}
//printbuf(count, "post emit");
}
else /* no active alerts */
{
emit(count, -1); /* empty the buffer */
count = 0;
lastGT = 0;
xWaitForSignal(&lgAlertCond, &lgAlertCondMutex);
}
}
else /* no alerts */
{
pthread_mutex_unlock(&lgAlertMutex);
emit(count, -1); /* empty the buffer */
count = 0;
lastGT = 0;
xWaitForSignal(&lgAlertCond, &lgAlertCondMutex);
}
}
pthAlertRunning = LG_THREAD_NONE;
pthread_exit(NULL);
}
void lgPthAlertStart(void)
{
if (!pthAlertRunning)
{
if (pthread_create(&pthAlert, NULL, (void*)lgPthAlert, NULL) == 0)
{
pthread_detach(pthAlert);
pthAlertRunning = LG_THREAD_STARTED;
}
}
}
void lgPthAlertStop(lgChipObj_p chip)
{
lgAlertRec_p evt;
/* stop any alert reads on chip */
for (evt=alertRec; evt!=NULL; evt=evt->next)
{
if (chip->handle == evt->chip->handle) evt->active =0;
}
xSendUnwaitSignal(&lgAlertCond, &lgAlertCondMutex);
}
lgAlertRec_p lgGpioGetAlertRec(lgChipObj_p chip, int gpio)
{
lgAlertRec_p p = alertRec;
while ((p != NULL) && ((p->chip != chip) || (p->gpio != gpio)))
p = p->next;
return p;
}
lgAlertRec_p lgGpioCreateAlertRec(
lgChipObj_p chip, int gpio, lgLineInf_p state, int nfyHandle)
{
lgAlertRec_p p;
p = malloc(sizeof(lgAlertRec_t));
if (p)
{
p->chip = chip;
p->gpio = gpio;
p->state = state;
p->nfyHandle = nfyHandle;
p->active = 1;
p->debounced = 1;
p->watchdogd = 1;
p->last_rpt_lv = -1; /* impossible level */
p->debounce_nanos = state->debounce_us * 1e3;
p->watchdog_nanos = state->watchdog_us * 1e3;
p->eFlags = state->eFlags;
pthread_mutex_lock(&lgAlertMutex);
p->prev = NULL;
p->next = alertRec;
if (alertRec) alertRec->prev = p;
alertRec = p;
pthread_mutex_unlock(&lgAlertMutex);
xSendUnwaitSignal(&lgAlertCond, &lgAlertCondMutex);
}
return p;
}