summaryrefslogtreecommitdiffstats
path: root/sdbusplus/timer.hpp
blob: 20ac203585af6fe8739ff2b6aaeb8086003f8333 (plain)
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
#pragma once

#include <systemd/sd-event.h>

#include <chrono>
#include <functional>

namespace phosphor
{

/** @class Timer
 *  @brief Manages starting watchdog timers and handling timeouts
 */
class Timer
{
  public:
    /** @brief Only need the default Timer */
    Timer() = delete;
    Timer(const Timer&) = delete;
    Timer& operator=(const Timer&) = delete;
    Timer(Timer&&) = delete;
    Timer& operator=(Timer&&) = delete;

    /** @brief Constructs timer object
     *         Uses the default sd_event object
     *
     *  @param[in] funcCallBack - optional function callback for timer
     *                            expirations
     */
    Timer(std::function<void()> userCallBack = nullptr) :
        event(nullptr), eventSource(nullptr), expired(false),
        userCallBack(userCallBack)
    {
        // take a reference to the default event object
        sd_event_default(&event);
        // Initialize the timer
        initialize();
    }

    /** @brief Constructs timer object
     *
     *  @param[in] events - sd_event pointer
     *  @param[in] funcCallBack - optional function callback for timer
     *                            expirations
     */
    Timer(sd_event* event, std::function<void()> userCallBack = nullptr) :
        event(event), eventSource(nullptr), expired(false),
        userCallBack(userCallBack)
    {
        if (!event)
        {
            // take a reference to the default event object
            sd_event_default(&event);
        }
        else
        {
            // take a reference to the event; the caller can
            // keep their ref or drop it without harm
            sd_event_ref(event);
        }
        // Initialize the timer
        initialize();
    }

    ~Timer()
    {
        // the *_unref functions do nothing if passed nullptr
        // so no need to check first
        eventSource = sd_event_source_unref(eventSource);
        event = sd_event_unref(event);
    }

    inline bool isExpired() const
    {
        return expired;
    }

    inline bool isRunning() const
    {
        int running = 0;
        if (sd_event_source_get_enabled(eventSource, &running) < 0)
        {
            return false;
        }
        return running != SD_EVENT_OFF;
    }

    /** @brief Starts the timer with specified expiration value.
     *  input is an offset from the current steady_clock
     */
    int start(std::chrono::microseconds usec, bool periodic = false)
    {
        // Disable the timer
        stop();
        expired = false;
        duration = usec;
        if (periodic)
        {
            // A periodic timer means that when the timer goes off,
            // it automatically rearms and starts running again
            runType = SD_EVENT_ON;
        }
        else
        {
            // A ONESHOT timer means that when the timer goes off,
            // it moves to disabled state.
            runType = SD_EVENT_ONESHOT;
        }

        // Get the current MONOTONIC time and add the delta
        auto expireTime = getTime() + usec;

        // Set the time
        int r = sd_event_source_set_time(eventSource, expireTime.count());
        if (r < 0)
        {
            throw std::runtime_error("Failure to set timer");
        }

        r = setEnabled(runType);
        if (r < 0)
        {
            throw std::runtime_error("Failure to start timer");
        }
        return r;
    }

    int stop()
    {
        return setEnabled(SD_EVENT_OFF);
    }

  private:
    /** @brief the sd_event structure */
    sd_event* event;

    /** @brief Source of events */
    sd_event_source* eventSource;

    /** @brief Returns if the associated timer is expired
     *
     *  This is set to true when the timeoutHandler is called into
     */
    bool expired;

    /** @brief Optional function to call on timer expiration */
    std::function<void()> userCallBack;

    /** @brief timer duration */
    std::chrono::microseconds duration;

    /** @brief timer run type (oneshot or periodic) */
    int runType;

    /** @brief Initializes the timer object with infinite
     *         expiration time and sets up the callback handler
     *
     *  @return None.
     *
     *  @error std::runtime exception thrown
     */
    void initialize()
    {
        if (!event)
        {
            throw std::runtime_error("Timer has no event loop");
        }
        // This can not be called more than once.
        if (eventSource)
        {
            throw std::runtime_error("Timer already initialized");
        }

        // Add infinite expiration time
        auto r = sd_event_add_time(
            event, &eventSource,
            CLOCK_MONOTONIC, // Time base
            UINT64_MAX,      // Expire time - way long time
            0,               // Use default event accuracy
            [](sd_event_source* eventSource, uint64_t usec, void* userData) {
                auto timer = static_cast<Timer*>(userData);
                return timer->timeoutHandler();
            },     // Callback handler on timeout
            this); // User data
        if (r < 0)
        {
            throw std::runtime_error("Timer initialization failed");
        }

        // Disable the timer for now
        r = stop();
        if (r < 0)
        {
            throw std::runtime_error("Disabling the timer failed");
        }
    }

    /** @brief Enables / disables the timer */
    int setEnabled(int action)
    {
        return sd_event_source_set_enabled(eventSource, action);
    }

    /** @brief Callback function when timer goes off
     *
     *  On getting the signal, initiate the hard power off request
     *
     *  @param[in] eventSource - Source of the event
     *  @param[in] usec        - time in micro seconds
     *  @param[in] userData    - User data pointer
     *
     */
    int timeoutHandler()
    {
        if (runType == SD_EVENT_ON)
        {
            // set the event to the future
            auto expireTime = getTime() + duration;

            // Set the time
            int r = sd_event_source_set_time(eventSource, expireTime.count());
            if (r < 0)
            {
                throw std::runtime_error("Failure to set timer");
            }
        }
        expired = true;

        // Call optional user call back function if available
        if (userCallBack)
        {
            userCallBack();
        }

        int running;
        if (sd_event_source_get_enabled(eventSource, &running) < 0 ||
            running == SD_EVENT_ONESHOT)
        {
            stop();
        }
        return 0;
    }

    /** @brief Gets the current time from steady clock */
    static std::chrono::microseconds getTime()
    {
        using namespace std::chrono;
        auto usec = steady_clock::now().time_since_epoch();
        return duration_cast<microseconds>(usec);
    }
};

} // namespace phosphor
OpenPOWER on IntegriCloud