forked from koreader/koreader-base
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rtc.lua
413 lines (352 loc) · 13 KB
/
rtc.lua
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
--[[--
Module for interfacing with the RTC (real time clock).
This module provides the ability to schedule wakeups through RTC.
See <http://man7.org/linux/man-pages/man4/rtc.4.html> for technical details.
Things to keep in mind: the RTC tracks time in UTC.
So do we, as the API only passes around what amounts to time_t values,
i.e., a Posix epoch, which is intrinsically UTC.
@module ffi.rtc
]]
local ffi = require("ffi")
local bor = bit.bor
local C = ffi.C
-- Load header definitions for functions and constants to the ffi.C namespace.
require("ffi/posix_h")
require("ffi/rtc_h")
-----------------------------------------------------------------
local RTC = {
dev_rtc = "/dev/rtc0",
dodgy_rtc = false,
_wakeup_scheduled = false, -- Flipped in @{setWakeupAlarm} and @{unsetWakeupAlarm}.
_wakeup_scheduled_tm = nil, -- The tm struct of the last scheduled wakeup alarm.
}
--[[--
Adds seconds to epoch.
@int seconds_from_now Number of seconds.
@treturn int (cdata) Epoch (UTC).
--]]
function RTC:secondsFromNowToEpoch(seconds_from_now)
-- NOTE: Lua's os.time just calls time(), which returns an epoch (UTC).
return os.time() + seconds_from_now
end
--[[--
Enable/Disable the alarm interrupt.
The use of RTC_WKALM_SET allows us to bypass the need for RTC_AIE_* calls,
thanks to the enabled field in the rtc_wkalrm struct.
Busybox rtcwake still does an RTC_AIE_OFF when resuming from an alarm wakeup,
as does Nickel when powering off.
In this scenario, the modern util-linux rtcwake, which never uses legacy RTC_ALM_SET calls,
instead uses RTC_WKALM_SET filled from RTC_WKALM_RD but with enabled set to 0.
@enabled bool Whether the call enables or disables the alarm interrupt. Defaults to true.
@treturn bool Success.
@treturn re Error code (if any).
@treturn err Error string (if any).
--]]
function RTC:toggleAlarmInterrupt(enabled)
enabled = (enabled ~= nil) and enabled or true
local err
local fd = C.open(self.dev_rtc, bor(C.O_RDONLY, C.O_NONBLOCK, C.O_CLOEXEC))
if fd == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("toggleAlarmInterrupt open " .. self.dev_rtc, fd, err)
return nil, fd, err
end
local re = C.ioctl(fd, enabled and C.RTC_AIE_ON or C.RTC_AIE_OFF, 0)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
if enabled then
print("toggleAlarmInterrupt ioctl RTC_AIE_ON", re, err)
else
print("toggleAlarmInterrupt ioctl RTC_AIE_OFF", re, err)
end
return nil, re, err
end
re = C.close(fd)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("toggleAlarmInterrupt close " .. self.dev_rtc, re, err)
return nil, re, err
end
return true
end
--[[--
Set wakeup alarm.
If you want to set the alarm to a certain amount of time from now,
you can process your value with @{secondsFromNowToEpoch}.
@int Epoch (UTC).
@enabled bool Whether the call enables or disables the alarm. Defaults to true.
@treturn bool Success.
@treturn re Error code (if any).
@treturn err Error string (if any).
--]]
function RTC:setWakeupAlarm(epoch, enabled)
enabled = (enabled ~= nil) and enabled or true
self._wakeup_scheduled_tm = ffi.new("struct tm")
local ptm = C.gmtime_r(ffi.new("time_t[1]", epoch), self._wakeup_scheduled_tm)
local wake = ffi.new("struct rtc_wkalrm")
wake.time.tm_sec = ptm.tm_sec
wake.time.tm_min = ptm.tm_min
wake.time.tm_hour = ptm.tm_hour
wake.time.tm_mday = ptm.tm_mday
wake.time.tm_mon = ptm.tm_mon
wake.time.tm_year = ptm.tm_year
-- wday, yday, and isdst fields are unused by Linux
wake.time.tm_wday = -1
wake.time.tm_yday = -1
wake.time.tm_isdst = -1
wake.enabled = enabled and 1 or 0
local err
local fd = C.open(self.dev_rtc, bor(C.O_RDONLY, C.O_NONBLOCK, C.O_CLOEXEC))
if fd == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("setWakeupAlarm open " .. self.dev_rtc, fd, err)
return nil, fd, err
end
local re = C.ioctl(fd, C.RTC_WKALM_SET, wake)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("setWakeupAlarm ioctl RTC_WKALM_SET", re, err)
return nil, re, err
end
re = C.close(fd)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("setWakeupAlarm close " .. self.dev_rtc, re, err)
return nil, re, err
end
if enabled then
self._wakeup_scheduled = true
else
self._wakeup_scheduled = false
self._wakeup_scheduled_ptm = nil
end
return true
end
--[[--
Unset wakeup alarm.
--]]
function RTC:unsetWakeupAlarm()
-- NOTE: Both util-linux & busybox rtcwake leave the current alarm as-is, and just disable the alarm interrupt.
-- c.f., toggleAlarmInterrupt for details.
self:toggleAlarmInterrupt(false)
self._wakeup_scheduled = false
self._wakeup_scheduled_tm = nil
end
--[[--
Get a copy of the wakealarm we set (if any).
This value is compared with @{getWakeupAlarmSys} in @{validateWakeupAlarmByProximity}.
@treturn tm (time struct)
--]]
function RTC:getWakeupAlarm()
return self._wakeup_scheduled_tm
end
--[[--
Return the timestamp of the alarm we set (if any).
@treturn @int Epoch (UTC)
--]]
function RTC:getWakeupAlarmEpoch()
if self._wakeup_scheduled then
return tonumber(C.timegm(self._wakeup_scheduled_tm))
else
return nil
end
end
--[[--
Get RTC wakealarm from system.
@treturn tm (time struct)
--]]
function RTC:getWakeupAlarmSys()
local wake = ffi.new("struct rtc_wkalrm")
local err, re
local fd = C.open(self.dev_rtc, bor(C.O_RDONLY, C.O_NONBLOCK, C.O_CLOEXEC))
if fd == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("getWakeupAlarm open " .. self.dev_rtc, fd, err)
return nil, fd, err
end
re = C.ioctl(fd, C.RTC_WKALM_RD, wake)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("getWakeupAlarm ioctl RTC_WKALM_RD", re, err)
return nil, re, err
end
re = C.close(fd)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("getWakeupAlarm close " .. self.dev_rtc, re, err)
return nil, re, err
end
-- Seed a struct tm with the current time, because not every field will be set in wake
local t = ffi.new("time_t[1]")
t[0] = C.time(nil)
local tm = ffi.new("struct tm")
local ptm = C.gmtime_r(t, tm)
-- And now update it with the fields that *are* set by the ioctl
ptm.tm_sec = wake.time.tm_sec
ptm.tm_min = wake.time.tm_min
ptm.tm_hour = wake.time.tm_hour
ptm.tm_mday = wake.time.tm_mday
ptm.tm_mon = wake.time.tm_mon
ptm.tm_year = wake.time.tm_year
return tm
end
--[[--
Get RTC clock from system.
@treturn tm (time struct)
--]]
function RTC:readHardwareClock()
local rtc = ffi.new("struct rtc_time")
local err, re
local fd = C.open(self.dev_rtc, bor(C.O_RDONLY, C.O_NONBLOCK, C.O_CLOEXEC))
if fd == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("readHardwareClock open " .. self.dev_rtc, fd, err)
return nil, fd, err
end
re = C.ioctl(fd, C.RTC_RD_TIME, rtc)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("readHardwareClock ioctl RTC_RD_TIME", re, err)
return nil, re, err
end
re = C.close(fd)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("readHardwareClock close " .. self.dev_rtc, re, err)
return nil, re, err
end
-- Seed a struct tm with the current time, because not every field will be set in rtc
local t = ffi.new("time_t[1]")
t[0] = C.time(nil)
local tm = ffi.new("struct tm")
local ptm = C.gmtime_r(t, tm)
-- And now update it with the fields that *are* set by the ioctl
ptm.tm_sec = rtc.tm_sec
ptm.tm_min = rtc.tm_min
ptm.tm_hour = rtc.tm_hour
ptm.tm_mday = rtc.tm_mday
ptm.tm_mon = rtc.tm_mon
ptm.tm_year = rtc.tm_year
return tm
end
--[[--
Checks if the alarm we set matches the system alarm as well as the current time.
--]]
function RTC:validateWakeupAlarmByProximity(task_alarm, proximity)
-- In principle alarm time and current time should match within a second,
-- but let's be absurdly generous and assume anything within 30 is a match.
-- In practice, Kobo's suspend() schedules check_unexpected_wakeup 15s *after*
-- the actual wakeup, so we need to account for at least that much ;).
proximity = proximity or 30
-- Those are in UTC broken down time format (struct tm)
local alarm_tm = self:getWakeupAlarm()
local alarm_sys_tm = self:getWakeupAlarmSys()
if not (alarm_tm and alarm_sys_tm) then return end
-- We want everything in UTC time_t (i.e. a Posix epoch).
local now = os.time()
local rtc_now_tm = self:readHardwareClock()
-- time_t may be 64-bit, cast to a Lua number
local rtc_now = tonumber(C.timegm(rtc_now_tm))
local alarm = tonumber(C.timegm(alarm_tm))
local alarm_sys = tonumber(C.timegm(alarm_sys_tm))
-- Everything's in UTC, ask Lua to convert that to a human-readable format in the local timezone
-- NOTE: Ideally, the first three entries should be identical.
if task_alarm then
print("validateWakeupAlarmByProximity:",
"\ntask @ " .. task_alarm .. os.date(" (%F %T %z)", task_alarm), -- what we were asked to validate
"\nlast set alarm @ " .. alarm .. os.date(" (%F %T %z)", alarm), -- the last alarm *we* setup
"\ncurrent rtc alarm @ " .. alarm_sys .. os.date(" (%F %T %z)", alarm_sys), -- the current rtc alarm
"\ncurrent rtc time is " .. rtc_now .. os.date(" (%F %T %z)", rtc_now),
"\ncurrent time is " .. now .. os.date(" (%F %T %z)", now))
end
-- On dodgy RTCs, some aging batteries are (supposedly) causing reads to report a bogus value...
-- c.f., https://github.com/koreader/koreader/issues/7994 & https://github.com/koreader/koreader/issues/10996
if self.dodgy_rtc and alarm_sys <= 1 then
print("A dodgy RTC reported a bogus alarm value, assuming our previously set alarm fired as expected anyway")
alarm_sys = alarm
end
-- If our stored alarm and the system alarm don't match, we didn't set it.
if alarm ~= alarm_sys then return end
-- If our stored alarm and the provided task alarm don't match,
-- we're not talking about the same task. This should never happen.
if task_alarm and alarm ~= task_alarm then return end
local diff = now - alarm
if diff >= 0 and diff < proximity then return true end
end
--[[--
Checks if we scheduled a wakeup alarm.
@treturn bool
--]]
function RTC:isWakeupAlarmScheduled()
return self._wakeup_scheduled
end
-- Helpers for HCToSys
local function set_kernel_tz(tz)
local re = C.settimeofday(nil, tz)
if re == -1 then
local err = ffi.string(C.strerror(ffi.errno()))
print("set_kernel_tz settimeofday", re, err)
return nil, re, err
end
return true
end
--[[--
Sets the system clock based on the hardware clock.
(e.g., hwclock --hctosys).
Heavily inspired by busybox's hwclock applet.
--]]
function RTC:HCToSys()
local ok, err, re
local fd = C.open(self.dev_rtc, bor(C.O_RDONLY, C.O_NONBLOCK, C.O_CLOEXEC))
if fd == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("HCToSys open " .. self.dev_rtc, fd, err)
return nil, fd, err
end
-- Read the hardware clock
local tm = ffi.new("struct tm") -- tm is a superset of rtc_time, so we're good.
re = C.ioctl(fd, C.RTC_RD_TIME, tm)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("HCToSys ioctl RTC_RD_TIME", re, err)
return nil, re, err
end
re = C.close(fd)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("HCToSys close ".. self.dev_rtc, re, err)
return nil, re, err
end
-- Convert that UTC broken down representation to an UTC time_t...
local t = C.timegm(tm)
-- We want a timeval for settimeofday
local tv = ffi.new("struct timeval")
tv.tv_sec = t
-- Deal with some more kernel & TZ nonsense...
-- 1. Lock the kernel's warp_clock function
-- (iff that's the first settimeofday call after a cold boot! i.e., in our case, that's mostly going to be a NOP).
-- 2. Set the kernel timezone.
-- c.f., comments in hwclock in both busybox & util-linux, as well as gettimeofday(2) for more details.
local tz = ffi.new("struct timezone")
ok, re, err = set_kernel_tz(tz)
if not ok then
return nil, re, err
end
local cur = ffi.new("time_t[1]")
cur[0] = C.time(nil)
local broken = C.localtime(cur)
tz.tz_minuteswest = -broken.tm_gmtoff / 60
ok, re, err = set_kernel_tz(tz)
if not ok then
return nil, re, err
end
-- Finally set the system clock
re = C.settimeofday(tv, nil)
if re == -1 then
err = ffi.string(C.strerror(ffi.errno()))
print("HCToSys settimeofday", re, err)
return nil, re, err
end
return true
end
return RTC