1 /*
2  * Copyright (c) 2022  The Chromium OS Authors
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 #include "usbc_timer.h"
8 
9 /** Timer flag to track if timer was started */
10 #define TIMER_STARTED 0
11 /** Timer flag to track if timer has expired */
12 #define TIMER_EXPIRED 1
13 
14 /**
15  * @brief The timer function that's executed when the timer expires
16  */
usbc_timer_handler(struct k_timer * timer)17 static void usbc_timer_handler(struct k_timer *timer)
18 {
19 	struct usbc_timer_t *usbc_timer = k_timer_user_data_get(timer);
20 
21 	atomic_set_bit(&usbc_timer->flags, TIMER_EXPIRED);
22 }
23 
usbc_timer_init(struct usbc_timer_t * usbc_timer,uint32_t timeout_ms)24 void usbc_timer_init(struct usbc_timer_t *usbc_timer, uint32_t timeout_ms)
25 {
26 	k_timer_init(&usbc_timer->timer, usbc_timer_handler, NULL);
27 	k_timer_user_data_set(&usbc_timer->timer, usbc_timer);
28 	usbc_timer->timeout_ms = timeout_ms;
29 }
30 
usbc_timer_start(struct usbc_timer_t * usbc_timer)31 void usbc_timer_start(struct usbc_timer_t *usbc_timer)
32 {
33 	atomic_clear_bit(&usbc_timer->flags, TIMER_EXPIRED);
34 	atomic_set_bit(&usbc_timer->flags, TIMER_STARTED);
35 	k_timer_start(&usbc_timer->timer, K_MSEC(usbc_timer->timeout_ms), K_NO_WAIT);
36 }
37 
usbc_timer_expired(struct usbc_timer_t * usbc_timer)38 bool usbc_timer_expired(struct usbc_timer_t *usbc_timer)
39 {
40 	bool started = atomic_test_bit(&usbc_timer->flags, TIMER_STARTED);
41 	bool expired = atomic_test_bit(&usbc_timer->flags, TIMER_EXPIRED);
42 
43 	if (started & expired) {
44 		atomic_clear_bit(&usbc_timer->flags, TIMER_STARTED);
45 		return true;
46 	}
47 
48 	return false;
49 }
50 
usbc_timer_running(struct usbc_timer_t * usbc_timer)51 bool usbc_timer_running(struct usbc_timer_t *usbc_timer)
52 {
53 	return atomic_test_bit(&usbc_timer->flags, TIMER_STARTED);
54 }
55 
usbc_timer_stop(struct usbc_timer_t * usbc_timer)56 void usbc_timer_stop(struct usbc_timer_t *usbc_timer)
57 {
58 	atomic_clear_bit(&usbc_timer->flags, TIMER_STARTED);
59 	k_timer_stop(&usbc_timer->timer);
60 }
61