1 /*
2  * Copyright (C) 2018-2022 Intel Corporation.
3  * SPDX-License-Identifier: BSD-3-Clause
4  */
5 
6 #include <stdio.h>
7 #include <sys/queue.h>
8 #include <pthread.h>
9 #include "event_queue.h"
10 #include "log_sys.h"
11 
12 const char *etype_str[] = {"CRASH", "INFO", "UPTIME", "HEART_BEAT",
13 					"REBOOT", "VM", "UNKNOWN"};
14 
15 static pthread_mutex_t eq_mtx = PTHREAD_MUTEX_INITIALIZER;
16 static pthread_cond_t pcond = PTHREAD_COND_INITIALIZER;
17 TAILQ_HEAD(, event_t) event_q;
18 
19 /**
20  * Enqueue an event to event_queue.
21  *
22  * @param event Event to process.
23  */
event_enqueue(struct event_t * event)24 void event_enqueue(struct event_t *event)
25 {
26 	pthread_mutex_lock(&eq_mtx);
27 	TAILQ_INSERT_TAIL(&event_q, event, entries);
28 	pthread_cond_signal(&pcond);
29 	LOGD("enqueue %d, (%d)%s\n", event->event_type, event->len,
30 	     event->path);
31 	pthread_mutex_unlock(&eq_mtx);
32 }
33 
34 /**
35  * Count the number of events in event_queue.
36  *
37  * @return count.
38  */
events_count(void)39 int events_count(void)
40 {
41 	struct event_t *e;
42 	int count = 0;
43 
44 	pthread_mutex_lock(&eq_mtx);
45 	TAILQ_FOREACH(e, &event_q, entries)
46 		count++;
47 	pthread_mutex_unlock(&eq_mtx);
48 
49 	return count;
50 }
51 
52 /**
53  * Dequeue an event from event_queue.
54  *
55  * @return the dequeued event.
56  */
event_dequeue(void)57 struct event_t *event_dequeue(void)
58 {
59 	struct event_t *e;
60 
61 	pthread_mutex_lock(&eq_mtx);
62 	while (TAILQ_EMPTY(&event_q))
63 		pthread_cond_wait(&pcond, &eq_mtx);
64 	e = TAILQ_FIRST(&event_q);
65 	TAILQ_REMOVE(&event_q, e, entries);
66 	LOGD("dequeue %d, (%d)%s\n", e->event_type, e->len, e->path);
67 	pthread_mutex_unlock(&eq_mtx);
68 
69 	return e;
70 }
71 
72 /**
73  * Initailize event_queue.
74  */
init_event_queue(void)75 void init_event_queue(void)
76 {
77 	TAILQ_INIT(&event_q);
78 }
79