]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/core/timer.c
core: use ASSERT_PTR(CAST(u)) everywhere
[thirdparty/systemd.git] / src / core / timer.c
CommitLineData
db9ecf05 1/* SPDX-License-Identifier: LGPL-2.1-or-later */
a7334b09 2
ca78ad1d
ZJS
3#include <sys/stat.h>
4#include <sys/types.h>
5#include <unistd.h>
6
d46de8a1
LP
7#include <errno.h>
8
b5efdb8a 9#include "alloc-util.h"
07630cea
LP
10#include "bus-error.h"
11#include "bus-util.h"
871d7de4 12#include "dbus-timer.h"
6fcbec6f 13#include "dbus-unit.h"
f4f15635 14#include "fs-util.h"
6bedfcbb 15#include "parse-util.h"
744c7693 16#include "random-util.h"
d68c645b 17#include "serialize.h"
a40eb732 18#include "special.h"
8b43440b 19#include "string-table.h"
07630cea 20#include "string-util.h"
b1d4f8e1 21#include "timer.h"
07630cea
LP
22#include "unit-name.h"
23#include "unit.h"
b1d4f8e1 24#include "user-util.h"
c1d9ba99 25#include "virt.h"
871d7de4
LP
26
27static const UnitActiveState state_translation_table[_TIMER_STATE_MAX] = {
28 [TIMER_DEAD] = UNIT_INACTIVE,
29 [TIMER_WAITING] = UNIT_ACTIVE,
30 [TIMER_RUNNING] = UNIT_ACTIVE,
31 [TIMER_ELAPSED] = UNIT_ACTIVE,
fdf20a31 32 [TIMER_FAILED] = UNIT_FAILED
871d7de4
LP
33};
34
718db961
LP
35static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata);
36
871d7de4 37static void timer_init(Unit *u) {
e9fa1bf7 38 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 39
ac155bb8 40 assert(u->load_state == UNIT_STUB);
871d7de4 41
3a43da28
KS
42 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
43 t->next_elapse_realtime = USEC_INFINITY;
c9e120e0 44 t->accuracy_usec = u->manager->defaults.timer_accuracy_usec;
3e0c30ac 45 t->remain_after_elapse = true;
871d7de4 46}
5cb5a6ff 47
74051b9b 48void timer_free_values(Timer *t) {
871d7de4
LP
49 TimerValue *v;
50
51 assert(t);
52
52e3671b 53 while ((v = LIST_POP(value, t->values))) {
3e044c49 54 calendar_spec_free(v->calendar_spec);
871d7de4
LP
55 free(v);
56 }
74051b9b
LP
57}
58
59static void timer_done(Unit *u) {
e9fa1bf7 60 Timer *t = ASSERT_PTR(TIMER(u));
74051b9b
LP
61
62 timer_free_values(t);
871d7de4 63
5dcadb4c
ZJS
64 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
65 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
06642d17 66
756491af 67 t->stamp_path = mfree(t->stamp_path);
871d7de4
LP
68}
69
70static int timer_verify(Timer *t) {
71 assert(t);
75193d41 72 assert(UNIT(t)->load_state == UNIT_LOADED);
871d7de4 73
d85ff944
YW
74 if (!t->values && !t->on_clock_change && !t->on_timezone_change)
75 return log_unit_error_errno(UNIT(t), SYNTHETIC_ERRNO(ENOEXEC), "Timer unit lacks value setting. Refusing.");
871d7de4
LP
76
77 return 0;
78}
79
6c155fe3
LP
80static int timer_add_default_dependencies(Timer *t) {
81 int r;
82
83 assert(t);
84
4c9ea260
LP
85 if (!UNIT(t)->default_dependencies)
86 return 0;
87
35d8c19a 88 r = unit_add_dependency_by_name(UNIT(t), UNIT_BEFORE, SPECIAL_TIMERS_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
e3d84721
LP
89 if (r < 0)
90 return r;
2a77d31d 91
463d0d15 92 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
3835b9aa 93 r = unit_add_two_dependencies_by_name(UNIT(t), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
36697dc0 94 if (r < 0)
6c155fe3 95 return r;
19f8d037 96
fe934b42 97 LIST_FOREACH(value, v, t->values) {
fe934b42
LP
98 if (v->base != TIMER_CALENDAR)
99 continue;
100
101 FOREACH_STRING(target, SPECIAL_TIME_SYNC_TARGET, SPECIAL_TIME_SET_TARGET) {
102 r = unit_add_dependency_by_name(UNIT(t), UNIT_AFTER, target, true, UNIT_DEPENDENCY_DEFAULT);
19f8d037
TGR
103 if (r < 0)
104 return r;
19f8d037 105 }
fe934b42
LP
106
107 break;
108 }
2a77d31d 109 }
6c155fe3 110
3835b9aa 111 return unit_add_two_dependencies_by_name(UNIT(t), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
eef85c4a
LP
112}
113
114static int timer_add_trigger_dependencies(Timer *t) {
115 Unit *x;
116 int r;
117
118 assert(t);
119
bc32241e 120 if (UNIT_TRIGGER(UNIT(t)))
eef85c4a
LP
121 return 0;
122
123 r = unit_load_related_unit(UNIT(t), ".service", &x);
124 if (r < 0)
125 return r;
126
127 return unit_add_two_dependencies(UNIT(t), UNIT_BEFORE, UNIT_TRIGGERS, x, true, UNIT_DEPENDENCY_IMPLICIT);
6c155fe3
LP
128}
129
06642d17 130static int timer_setup_persistent(Timer *t) {
d3ab7b80 131 _cleanup_free_ char *stamp_path = NULL;
06642d17
LP
132 int r;
133
134 assert(t);
135
136 if (!t->persistent)
137 return 0;
138
463d0d15 139 if (MANAGER_IS_SYSTEM(UNIT(t)->manager)) {
06642d17 140
9e615fa3 141 r = unit_add_mounts_for(UNIT(t), "/var/lib/systemd/timers", UNIT_DEPENDENCY_FILE, UNIT_MOUNT_REQUIRES);
06642d17
LP
142 if (r < 0)
143 return r;
144
d3ab7b80 145 stamp_path = strjoin("/var/lib/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
146 } else {
147 const char *e;
148
149 e = getenv("XDG_DATA_HOME");
150 if (e)
d3ab7b80 151 stamp_path = strjoin(e, "/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
152 else {
153
154 _cleanup_free_ char *h = NULL;
155
156 r = get_home_dir(&h);
23bbb0de 157 if (r < 0)
f2341e0a 158 return log_unit_error_errno(UNIT(t), r, "Failed to determine home directory: %m");
06642d17 159
d3ab7b80 160 stamp_path = strjoin(h, "/.local/share/systemd/timers/stamp-", UNIT(t)->id);
06642d17
LP
161 }
162 }
163
d3ab7b80 164 if (!stamp_path)
06642d17
LP
165 return log_oom();
166
d3ab7b80 167 return free_and_replace(t->stamp_path, stamp_path);
06642d17
LP
168}
169
acf24a1a
KG
170static uint64_t timer_get_fixed_delay_hash(Timer *t) {
171 static const uint8_t hash_key[] = {
172 0x51, 0x0a, 0xdb, 0x76, 0x29, 0x51, 0x42, 0xc2,
173 0x80, 0x35, 0xea, 0xe6, 0x8e, 0x3a, 0x37, 0xbd
174 };
175
176 struct siphash state;
177 sd_id128_t machine_id;
178 uid_t uid;
179 int r;
180
181 assert(t);
182
183 uid = getuid();
184 r = sd_id128_get_machine(&machine_id);
185 if (r < 0) {
186 log_unit_debug_errno(UNIT(t), r,
187 "Failed to get machine ID for the fixed delay calculation, proceeding with 0: %m");
188 machine_id = SD_ID128_NULL;
189 }
190
191 siphash24_init(&state, hash_key);
c01a5c05 192 siphash24_compress_typesafe(machine_id, &state);
acf24a1a 193 siphash24_compress_boolean(MANAGER_IS_SYSTEM(UNIT(t)->manager), &state);
c01a5c05 194 siphash24_compress_typesafe(uid, &state);
acf24a1a
KG
195 siphash24_compress_string(UNIT(t)->id, &state);
196
197 return siphash24_finalize(&state);
198}
199
871d7de4 200static int timer_load(Unit *u) {
e9fa1bf7 201 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4
LP
202 int r;
203
ac155bb8 204 assert(u->load_state == UNIT_STUB);
871d7de4 205
c3620770 206 r = unit_load_fragment_and_dropin(u, true);
36697dc0 207 if (r < 0)
871d7de4
LP
208 return r;
209
75193d41
ZJS
210 if (u->load_state != UNIT_LOADED)
211 return 0;
871d7de4 212
75193d41
ZJS
213 /* This is a new unit? Then let's add in some extras */
214 r = timer_add_trigger_dependencies(t);
215 if (r < 0)
216 return r;
57020a3a 217
75193d41
ZJS
218 r = timer_setup_persistent(t);
219 if (r < 0)
220 return r;
06642d17 221
75193d41
ZJS
222 r = timer_add_default_dependencies(t);
223 if (r < 0)
224 return r;
871d7de4
LP
225
226 return timer_verify(t);
227}
228
229static void timer_dump(Unit *u, FILE *f, const char *prefix) {
e9fa1bf7 230 Timer *t = ASSERT_PTR(TIMER(u));
3ecaa09b 231 Unit *trigger;
034c6ed7 232
e9fa1bf7
MY
233 assert(f);
234 assert(prefix);
235
3ecaa09b
LP
236 trigger = UNIT_TRIGGER(u);
237
871d7de4
LP
238 fprintf(f,
239 "%sTimer State: %s\n"
067d72c9 240 "%sResult: %s\n"
9f5eb56a 241 "%sUnit: %s\n"
dedabea4
LP
242 "%sPersistent: %s\n"
243 "%sWakeSystem: %s\n"
3e0c30ac 244 "%sAccuracy: %s\n"
efebb613 245 "%sRemainAfterElapse: %s\n"
acf24a1a 246 "%sFixedRandomDelay: %s\n"
efebb613 247 "%sOnClockChange: %s\n"
0810e396 248 "%sOnTimeZoneChange: %s\n",
871d7de4 249 prefix, timer_state_to_string(t->state),
067d72c9 250 prefix, timer_result_to_string(t->result),
9f5eb56a 251 prefix, trigger ? trigger->id : "n/a",
dedabea4
LP
252 prefix, yes_no(t->persistent),
253 prefix, yes_no(t->wake_system),
5291f26d 254 prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
efebb613 255 prefix, yes_no(t->remain_after_elapse),
acf24a1a 256 prefix, yes_no(t->fixed_random_delay),
efebb613
LP
257 prefix, yes_no(t->on_clock_change),
258 prefix, yes_no(t->on_timezone_change));
871d7de4 259
2762ce2d 260 LIST_FOREACH(value, v, t->values)
36697dc0
LP
261 if (v->base == TIMER_CALENDAR) {
262 _cleanup_free_ char *p = NULL;
263
25cb94d4 264 (void) calendar_spec_to_string(v->calendar_spec, &p);
36697dc0
LP
265
266 fprintf(f,
267 "%s%s: %s\n",
268 prefix,
269 timer_base_to_string(v->base),
270 strna(p));
5291f26d 271 } else
36697dc0
LP
272 fprintf(f,
273 "%s%s: %s\n",
274 prefix,
275 timer_base_to_string(v->base),
5291f26d 276 FORMAT_TIMESPAN(v->value, 0));
871d7de4
LP
277}
278
279static void timer_set_state(Timer *t, TimerState state) {
280 TimerState old_state;
e9fa1bf7 281
034c6ed7 282 assert(t);
871d7de4 283
6fcbec6f
LP
284 if (t->state != state)
285 bus_unit_send_pending_change_signal(UNIT(t), false);
286
871d7de4
LP
287 old_state = t->state;
288 t->state = state;
289
36697dc0 290 if (state != TIMER_WAITING) {
5dcadb4c
ZJS
291 t->monotonic_event_source = sd_event_source_disable_unref(t->monotonic_event_source);
292 t->realtime_event_source = sd_event_source_disable_unref(t->realtime_event_source);
6e2c9ce1
ZJS
293 t->next_elapse_monotonic_or_boottime = USEC_INFINITY;
294 t->next_elapse_realtime = USEC_INFINITY;
36697dc0 295 }
871d7de4
LP
296
297 if (state != old_state)
f2341e0a 298 log_unit_debug(UNIT(t), "Changed %s -> %s", timer_state_to_string(old_state), timer_state_to_string(state));
871d7de4 299
96b09de5 300 unit_notify(UNIT(t), state_translation_table[old_state], state_translation_table[state], /* reload_success = */ true);
871d7de4
LP
301}
302
aa1f95d2 303static void timer_enter_waiting(Timer *t, bool time_change);
871d7de4 304
be847e82 305static int timer_coldplug(Unit *u) {
e9fa1bf7 306 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 307
871d7de4
LP
308 assert(t->state == TIMER_DEAD);
309
3e0c30ac
LP
310 if (t->deserialized_state == t->state)
311 return 0;
871d7de4 312
3e0c30ac 313 if (t->deserialized_state == TIMER_WAITING)
aa1f95d2 314 timer_enter_waiting(t, false);
3e0c30ac
LP
315 else
316 timer_set_state(t, t->deserialized_state);
871d7de4
LP
317
318 return 0;
319}
320
067d72c9 321static void timer_enter_dead(Timer *t, TimerResult f) {
871d7de4
LP
322 assert(t);
323
a0fef983 324 if (t->result == TIMER_SUCCESS)
067d72c9 325 t->result = f;
871d7de4 326
aac99f30 327 unit_log_result(UNIT(t), t->result == TIMER_SUCCESS, timer_result_to_string(t->result));
067d72c9 328 timer_set_state(t, t->result != TIMER_SUCCESS ? TIMER_FAILED : TIMER_DEAD);
871d7de4
LP
329}
330
3e0c30ac
LP
331static void timer_enter_elapsed(Timer *t, bool leave_around) {
332 assert(t);
333
334 /* If a unit is marked with RemainAfterElapse=yes we leave it
335 * around even after it elapsed once, so that starting it
336 * later again does not necessarily mean immediate
337 * retriggering. We unconditionally leave units with
338 * TIMER_UNIT_ACTIVE or TIMER_UNIT_INACTIVE triggers around,
339 * since they might be restarted automatically at any time
340 * later on. */
341
342 if (t->remain_after_elapse || leave_around)
343 timer_set_state(t, TIMER_ELAPSED);
344 else
345 timer_enter_dead(t, TIMER_SUCCESS);
346}
347
744c7693 348static void add_random(Timer *t, usec_t *v) {
744c7693
LP
349 usec_t add;
350
351 assert(t);
3f51aec8 352 assert(v);
744c7693
LP
353
354 if (t->random_usec == 0)
355 return;
356 if (*v == USEC_INFINITY)
357 return;
358
acf24a1a 359 add = (t->fixed_random_delay ? timer_get_fixed_delay_hash(t) : random_u64()) % t->random_usec;
744c7693
LP
360
361 if (*v + add < *v) /* overflow */
362 *v = (usec_t) -2; /* Highest possible value, that is not USEC_INFINITY */
363 else
364 *v += add;
365
5291f26d 366 log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
744c7693
LP
367}
368
aa1f95d2 369static void timer_enter_waiting(Timer *t, bool time_change) {
36697dc0 370 bool found_monotonic = false, found_realtime = false;
3e0c30ac 371 bool leave_around = false;
c54be90b 372 triple_timestamp ts;
e903182e 373 Unit *trigger;
871d7de4
LP
374 int r;
375
e903182e
LP
376 assert(t);
377
378 trigger = UNIT_TRIGGER(UNIT(t));
379 if (!trigger) {
380 log_unit_error(UNIT(t), "Unit to trigger vanished.");
e7912a08 381 goto fail;
e903182e
LP
382 }
383
fa5a0251 384 triple_timestamp_now(&ts);
dedabea4 385 t->next_elapse_monotonic_or_boottime = t->next_elapse_realtime = 0;
871d7de4
LP
386
387 LIST_FOREACH(value, v, t->values) {
871d7de4
LP
388 if (v->disabled)
389 continue;
390
36697dc0 391 if (v->base == TIMER_CALENDAR) {
58afc4f8 392 usec_t b, rebased;
06642d17 393
0bf1d0ff
LB
394 /* If we know the last time this was
395 * triggered, schedule the job based relative
396 * to that. If we don't, just start from
397 * the activation time. */
398
e21f75af 399 if (dual_timestamp_is_set(&t->last_trigger))
9ea9faff 400 b = t->last_trigger.realtime;
6546045f
DDM
401 else if (dual_timestamp_is_set(&UNIT(t)->inactive_exit_timestamp))
402 b = UNIT(t)->inactive_exit_timestamp.realtime;
403 else
404 b = ts.realtime;
06642d17
LP
405
406 r = calendar_spec_next_usec(v->calendar_spec, b, &v->next_elapse);
36697dc0
LP
407 if (r < 0)
408 continue;
409
58afc4f8
LP
410 /* To make the delay due to RandomizedDelaySec= work even at boot, if the scheduled
411 * time has already passed, set the time when systemd first started as the scheduled
412 * time. Note that we base this on the monotonic timestamp of the boot, not the
413 * realtime one, since the wallclock might have been off during boot. */
414 rebased = map_clock_usec(UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic,
415 CLOCK_MONOTONIC, CLOCK_REALTIME);
416 if (v->next_elapse < rebased)
417 v->next_elapse = rebased;
a87c1d3a 418
36697dc0
LP
419 if (!found_realtime)
420 t->next_elapse_realtime = v->next_elapse;
10717a1a 421 else
36697dc0 422 t->next_elapse_realtime = MIN(t->next_elapse_realtime, v->next_elapse);
871d7de4 423
36697dc0 424 found_realtime = true;
871d7de4 425
60933bb8
AJ
426 } else {
427 usec_t base;
c54be90b 428
36697dc0 429 switch (v->base) {
871d7de4 430
36697dc0
LP
431 case TIMER_ACTIVE:
432 if (state_translation_table[t->state] == UNIT_ACTIVE)
433 base = UNIT(t)->inactive_exit_timestamp.monotonic;
434 else
c54be90b 435 base = ts.monotonic;
36697dc0 436 break;
871d7de4 437
36697dc0 438 case TIMER_BOOT:
c1d9ba99
MS
439 if (detect_container() <= 0) {
440 /* CLOCK_MONOTONIC equals the uptime on Linux */
441 base = 0;
442 break;
443 }
444 /* In a container we don't want to include the time the host
445 * was already up when the container started, so count from
ec251fe7 446 * our own startup. */
4831981d 447 _fallthrough_;
36697dc0 448 case TIMER_STARTUP:
9f9f0342 449 base = UNIT(t)->manager->timestamps[MANAGER_TIMESTAMP_USERSPACE].monotonic;
36697dc0 450 break;
871d7de4 451
36697dc0 452 case TIMER_UNIT_ACTIVE:
3e0c30ac 453 leave_around = true;
525b95f1 454 base = MAX(trigger->inactive_exit_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 455 if (base <= 0)
36697dc0 456 continue;
36697dc0 457 break;
871d7de4 458
36697dc0 459 case TIMER_UNIT_INACTIVE:
3e0c30ac 460 leave_around = true;
525b95f1 461 base = MAX(trigger->inactive_enter_timestamp.monotonic, t->last_trigger.monotonic);
e41e1943 462 if (base <= 0)
36697dc0 463 continue;
36697dc0 464 break;
871d7de4 465
36697dc0 466 default:
04499a70 467 assert_not_reached();
36697dc0 468 }
871d7de4 469
c54be90b 470 v->next_elapse = usec_add(usec_shift_clock(base, CLOCK_MONOTONIC, TIMER_MONOTONIC_CLOCK(t)), v->value);
36697dc0 471
aa1f95d2
MK
472 if (dual_timestamp_is_set(&t->last_trigger) &&
473 !time_change &&
c54be90b
LP
474 v->next_elapse < triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)) &&
475 IN_SET(v->base, TIMER_ACTIVE, TIMER_BOOT, TIMER_STARTUP)) {
e41e1943 476 /* This is a one time trigger, disable it now */
36697dc0
LP
477 v->disabled = true;
478 continue;
479 }
480
481 if (!found_monotonic)
dedabea4 482 t->next_elapse_monotonic_or_boottime = v->next_elapse;
36697dc0 483 else
dedabea4 484 t->next_elapse_monotonic_or_boottime = MIN(t->next_elapse_monotonic_or_boottime, v->next_elapse);
36697dc0
LP
485
486 found_monotonic = true;
487 }
871d7de4
LP
488 }
489
efebb613 490 if (!found_monotonic && !found_realtime && !t->on_timezone_change && !t->on_clock_change) {
f2341e0a 491 log_unit_debug(UNIT(t), "Timer is elapsed.");
3e0c30ac 492 timer_enter_elapsed(t, leave_around);
871d7de4
LP
493 return;
494 }
495
36697dc0 496 if (found_monotonic) {
3e0c30ac 497 usec_t left;
dedabea4 498
744c7693
LP
499 add_random(t, &t->next_elapse_monotonic_or_boottime);
500
c54be90b 501 left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
5291f26d 502 log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
871d7de4 503
718db961 504 if (t->monotonic_event_source) {
dedabea4 505 r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
e7912a08
LP
506 if (r < 0) {
507 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule monotonic event source: %m");
718db961 508 goto fail;
e7912a08 509 }
718db961
LP
510
511 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_ONESHOT);
e7912a08
LP
512 if (r < 0) {
513 log_unit_warning_errno(UNIT(t), r, "Failed to enable monotonic event source: %m");
cbf60d0a 514 goto fail;
e7912a08 515 }
cbf60d0a
LP
516 } else {
517
6a0f1f6d
LP
518 r = sd_event_add_time(
519 UNIT(t)->manager->event,
520 &t->monotonic_event_source,
dedabea4
LP
521 t->wake_system ? CLOCK_BOOTTIME_ALARM : CLOCK_MONOTONIC,
522 t->next_elapse_monotonic_or_boottime, t->accuracy_usec,
6a0f1f6d 523 timer_dispatch, t);
e7912a08
LP
524 if (r < 0) {
525 log_unit_warning_errno(UNIT(t), r, "Failed to add monotonic event source: %m");
cbf60d0a 526 goto fail;
e7912a08 527 }
718db961 528
cbf60d0a
LP
529 (void) sd_event_source_set_description(t->monotonic_event_source, "timer-monotonic");
530 }
7dfbe2e3 531
718db961 532 } else if (t->monotonic_event_source) {
718db961 533
06642d17 534 r = sd_event_source_set_enabled(t->monotonic_event_source, SD_EVENT_OFF);
e7912a08
LP
535 if (r < 0) {
536 log_unit_warning_errno(UNIT(t), r, "Failed to disable monotonic event source: %m");
718db961 537 goto fail;
e7912a08 538 }
718db961 539 }
36697dc0
LP
540
541 if (found_realtime) {
744c7693
LP
542 add_random(t, &t->next_elapse_realtime);
543
04f5c018 544 log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
36697dc0 545
718db961
LP
546 if (t->realtime_event_source) {
547 r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
e7912a08
LP
548 if (r < 0) {
549 log_unit_warning_errno(UNIT(t), r, "Failed to reschedule realtime event source: %m");
718db961 550 goto fail;
e7912a08 551 }
718db961
LP
552
553 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_ONESHOT);
e7912a08
LP
554 if (r < 0) {
555 log_unit_warning_errno(UNIT(t), r, "Failed to enable realtime event source: %m");
cbf60d0a 556 goto fail;
e7912a08 557 }
cbf60d0a 558 } else {
6a0f1f6d
LP
559 r = sd_event_add_time(
560 UNIT(t)->manager->event,
561 &t->realtime_event_source,
dedabea4 562 t->wake_system ? CLOCK_REALTIME_ALARM : CLOCK_REALTIME,
6a0f1f6d
LP
563 t->next_elapse_realtime, t->accuracy_usec,
564 timer_dispatch, t);
e7912a08
LP
565 if (r < 0) {
566 log_unit_warning_errno(UNIT(t), r, "Failed to add realtime event source: %m");
cbf60d0a 567 goto fail;
e7912a08 568 }
718db961 569
cbf60d0a
LP
570 (void) sd_event_source_set_description(t->realtime_event_source, "timer-realtime");
571 }
7dfbe2e3 572
718db961 573 } else if (t->realtime_event_source) {
718db961 574
06642d17 575 r = sd_event_source_set_enabled(t->realtime_event_source, SD_EVENT_OFF);
e7912a08
LP
576 if (r < 0) {
577 log_unit_warning_errno(UNIT(t), r, "Failed to disable realtime event source: %m");
718db961 578 goto fail;
e7912a08 579 }
718db961 580 }
871d7de4
LP
581
582 timer_set_state(t, TIMER_WAITING);
583 return;
584
585fail:
067d72c9 586 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
587}
588
589static void timer_enter_running(Timer *t) {
c8bc7519 590 _cleanup_(activation_details_unrefp) ActivationDetails *details = NULL;
4afd3348 591 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
e903182e 592 Unit *trigger;
c8bc7519 593 Job *job;
871d7de4 594 int r;
398ef8ba 595
871d7de4
LP
596 assert(t);
597
ba3e67a7 598 /* Don't start job if we are supposed to go down */
31afa0a4 599 if (unit_stop_pending(UNIT(t)))
ba3e67a7
LP
600 return;
601
e903182e
LP
602 trigger = UNIT_TRIGGER(UNIT(t));
603 if (!trigger) {
604 log_unit_error(UNIT(t), "Unit to trigger vanished.");
e7912a08 605 goto fail;
e903182e
LP
606 }
607
c8bc7519
LB
608 details = activation_details_new(UNIT(t));
609 if (!details) {
e7912a08 610 log_oom();
c8bc7519
LB
611 goto fail;
612 }
613
614 r = manager_add_job(UNIT(t)->manager, JOB_START, trigger, JOB_REPLACE, NULL, &error, &job);
e7912a08
LP
615 if (r < 0) {
616 log_unit_warning(UNIT(t), "Failed to queue unit startup job: %s", bus_error_message(&error, r));
871d7de4 617 goto fail;
e7912a08 618 }
871d7de4 619
fa5a0251 620 dual_timestamp_now(&t->last_trigger);
c8bc7519
LB
621 ACTIVATION_DETAILS_TIMER(details)->last_trigger = t->last_trigger;
622
623 job_set_activation_details(job, details);
06642d17 624
472fc28f 625 if (t->stamp_path)
ee735086 626 touch_file(t->stamp_path, true, t->last_trigger.realtime, UID_INVALID, GID_INVALID, MODE_INVALID);
e41e1943 627
871d7de4
LP
628 timer_set_state(t, TIMER_RUNNING);
629 return;
630
631fail:
067d72c9 632 timer_enter_dead(t, TIMER_FAILURE_RESOURCES);
871d7de4
LP
633}
634
635static int timer_start(Unit *u) {
e9fa1bf7 636 Timer *t = ASSERT_PTR(TIMER(u));
07299350 637 int r;
871d7de4 638
3742095b 639 assert(IN_SET(t->state, TIMER_DEAD, TIMER_FAILED));
01f78473 640
a4191c9f
LP
641 r = unit_test_trigger_loaded(u);
642 if (r < 0)
643 return r;
871d7de4 644
4b58153d
LP
645 r = unit_acquire_invocation_id(u);
646 if (r < 0)
647 return r;
648
06642d17
LP
649 t->last_trigger = DUAL_TIMESTAMP_NULL;
650
779042e7
MC
651 /* Reenable all timers that depend on unit activation time */
652 LIST_FOREACH(value, v, t->values)
653 if (v->base == TIMER_ACTIVE)
654 v->disabled = false;
655
06642d17
LP
656 if (t->stamp_path) {
657 struct stat st;
658
77542a79
LP
659 if (stat(t->stamp_path, &st) >= 0) {
660 usec_t ft;
661
662 /* Load the file timestamp, but only if it is actually in the past. If it is in the future,
663 * something is wrong with the system clock. */
664
665 ft = timespec_load(&st.st_mtim);
666 if (ft < now(CLOCK_REALTIME))
667 t->last_trigger.realtime = ft;
04f5c018 668 else
77542a79 669 log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
04f5c018 670 FORMAT_TIMESTAMP(ft));
77542a79
LP
671
672 } else if (errno == ENOENT)
2762ce2d 673 /* The timer has never run before, make sure a stamp file exists. */
4b58153d 674 (void) touch_file(t->stamp_path, true, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
06642d17
LP
675 }
676
067d72c9 677 t->result = TIMER_SUCCESS;
aa1f95d2 678 timer_enter_waiting(t, false);
82a2b6bb 679 return 1;
871d7de4
LP
680}
681
682static int timer_stop(Unit *u) {
e9fa1bf7 683 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 684
3742095b 685 assert(IN_SET(t->state, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED));
871d7de4 686
067d72c9 687 timer_enter_dead(t, TIMER_SUCCESS);
82a2b6bb 688 return 1;
871d7de4
LP
689}
690
691static int timer_serialize(Unit *u, FILE *f, FDSet *fds) {
e9fa1bf7 692 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 693
871d7de4
LP
694 assert(f);
695 assert(fds);
696
d68c645b
LP
697 (void) serialize_item(f, "state", timer_state_to_string(t->state));
698 (void) serialize_item(f, "result", timer_result_to_string(t->result));
871d7de4 699
eba1cf56 700 if (dual_timestamp_is_set(&t->last_trigger))
d68c645b 701 (void) serialize_usec(f, "last-trigger-realtime", t->last_trigger.realtime);
06642d17
LP
702
703 if (t->last_trigger.monotonic > 0)
d68c645b 704 (void) serialize_usec(f, "last-trigger-monotonic", t->last_trigger.monotonic);
06642d17 705
871d7de4
LP
706 return 0;
707}
708
709static int timer_deserialize_item(Unit *u, const char *key, const char *value, FDSet *fds) {
e9fa1bf7 710 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 711
871d7de4
LP
712 assert(key);
713 assert(value);
714 assert(fds);
715
716 if (streq(key, "state")) {
717 TimerState state;
718
36697dc0
LP
719 state = timer_state_from_string(value);
720 if (state < 0)
f2341e0a 721 log_unit_debug(u, "Failed to parse state value: %s", value);
871d7de4
LP
722 else
723 t->deserialized_state = state;
d68c645b 724
067d72c9
LP
725 } else if (streq(key, "result")) {
726 TimerResult f;
727
728 f = timer_result_from_string(value);
729 if (f < 0)
f2341e0a 730 log_unit_debug(u, "Failed to parse result value: %s", value);
067d72c9
LP
731 else if (f != TIMER_SUCCESS)
732 t->result = f;
06642d17 733
d68c645b
LP
734 } else if (streq(key, "last-trigger-realtime"))
735 (void) deserialize_usec(value, &t->last_trigger.realtime);
736 else if (streq(key, "last-trigger-monotonic"))
737 (void) deserialize_usec(value, &t->last_trigger.monotonic);
738 else
f2341e0a 739 log_unit_debug(u, "Unknown serialization key: %s", key);
871d7de4
LP
740
741 return 0;
034c6ed7
LP
742}
743
d1e8e8b5 744static UnitActiveState timer_active_state(Unit *u) {
e9fa1bf7 745 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 746
e9fa1bf7 747 return state_translation_table[t->state];
871d7de4
LP
748}
749
d1e8e8b5 750static const char *timer_sub_state_to_string(Unit *u) {
e9fa1bf7 751 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 752
e9fa1bf7 753 return timer_state_to_string(t->state);
871d7de4
LP
754}
755
718db961 756static int timer_dispatch(sd_event_source *s, uint64_t usec, void *userdata) {
e9fa1bf7 757 Timer *t = ASSERT_PTR(TIMER(userdata));
5cb5a6ff 758
871d7de4 759 if (t->state != TIMER_WAITING)
718db961 760 return 0;
5cb5a6ff 761
f2341e0a 762 log_unit_debug(UNIT(t), "Timer elapsed.");
871d7de4 763 timer_enter_running(t);
718db961 764 return 0;
5cb5a6ff
LP
765}
766
3ecaa09b 767static void timer_trigger_notify(Unit *u, Unit *other) {
e9fa1bf7 768 Timer *t = ASSERT_PTR(TIMER(u));
871d7de4 769
3ecaa09b 770 assert(other);
871d7de4 771
0377cd29
LP
772 /* Filter out invocations with bogus state */
773 assert(UNIT_IS_LOAD_COMPLETE(other->load_state));
871d7de4 774
3ecaa09b
LP
775 /* Reenable all timers that depend on unit state */
776 LIST_FOREACH(value, v, t->values)
3742095b 777 if (IN_SET(v->base, TIMER_UNIT_ACTIVE, TIMER_UNIT_INACTIVE))
3ecaa09b 778 v->disabled = false;
01f78473 779
3ecaa09b 780 switch (t->state) {
871d7de4 781
3ecaa09b
LP
782 case TIMER_WAITING:
783 case TIMER_ELAPSED:
871d7de4 784
3ecaa09b 785 /* Recalculate sleep time */
aa1f95d2 786 timer_enter_waiting(t, false);
3ecaa09b 787 break;
871d7de4 788
3ecaa09b 789 case TIMER_RUNNING:
871d7de4 790
3ecaa09b 791 if (UNIT_IS_INACTIVE_OR_FAILED(unit_active_state(other))) {
f2341e0a 792 log_unit_debug(UNIT(t), "Got notified about unit deactivation.");
aa1f95d2 793 timer_enter_waiting(t, false);
3ecaa09b
LP
794 }
795 break;
871d7de4 796
3ecaa09b
LP
797 case TIMER_DEAD:
798 case TIMER_FAILED:
799 break;
871d7de4 800
3ecaa09b 801 default:
04499a70 802 assert_not_reached();
871d7de4 803 }
871d7de4
LP
804}
805
fdf20a31 806static void timer_reset_failed(Unit *u) {
e9fa1bf7 807 Timer *t = ASSERT_PTR(TIMER(u));
5632e374 808
fdf20a31 809 if (t->state == TIMER_FAILED)
5632e374
LP
810 timer_set_state(t, TIMER_DEAD);
811
067d72c9 812 t->result = TIMER_SUCCESS;
5632e374
LP
813}
814
8742514c 815static void timer_time_change(Unit *u) {
e9fa1bf7 816 Timer *t = ASSERT_PTR(TIMER(u));
13f512d3 817 usec_t ts;
8742514c 818
8742514c
LP
819 if (t->state != TIMER_WAITING)
820 return;
821
13f512d3
AJ
822 /* If we appear to have triggered in the future, the system clock must
823 * have been set backwards. So let's rewind our own clock and allow
0923b425 824 * the future triggers to happen again :). Exactly the same as when
13f512d3
AJ
825 * you start a timer unit with Persistent=yes. */
826 ts = now(CLOCK_REALTIME);
827 if (t->last_trigger.realtime > ts)
828 t->last_trigger.realtime = ts;
829
efebb613
LP
830 if (t->on_clock_change) {
831 log_unit_debug(u, "Time change, triggering activation.");
832 timer_enter_running(t);
833 } else {
834 log_unit_debug(u, "Time change, recalculating next elapse.");
835 timer_enter_waiting(t, true);
836 }
8742514c
LP
837}
838
bbf5fd8e 839static void timer_timezone_change(Unit *u) {
e9fa1bf7 840 Timer *t = ASSERT_PTR(TIMER(u));
bbf5fd8e
LP
841
842 if (t->state != TIMER_WAITING)
843 return;
844
efebb613
LP
845 if (t->on_timezone_change) {
846 log_unit_debug(u, "Timezone change, triggering activation.");
847 timer_enter_running(t);
848 } else {
849 log_unit_debug(u, "Timezone change, recalculating next elapse.");
850 timer_enter_waiting(t, false);
851 }
bbf5fd8e
LP
852}
853
89f6fe7b 854static int timer_clean(Unit *u, ExecCleanMask mask) {
e9fa1bf7 855 Timer *t = ASSERT_PTR(TIMER(u));
89f6fe7b
LP
856 int r;
857
89f6fe7b
LP
858 assert(mask != 0);
859
860 if (t->state != TIMER_DEAD)
861 return -EBUSY;
862
4f06325c 863 if (mask != EXEC_CLEAN_STATE)
89f6fe7b
LP
864 return -EUNATCH;
865
866 r = timer_setup_persistent(t);
867 if (r < 0)
868 return r;
869
870 if (!t->stamp_path)
871 return -EUNATCH;
872
873 if (unlink(t->stamp_path) && errno != ENOENT)
874 return log_unit_error_errno(u, errno, "Failed to clean stamp file of timer: %m");
875
876 return 0;
877}
878
879static int timer_can_clean(Unit *u, ExecCleanMask *ret) {
e9fa1bf7 880 Timer *t = ASSERT_PTR(TIMER(u));
89f6fe7b 881
4fb8f1e8 882 assert(ret);
89f6fe7b
LP
883
884 *ret = t->persistent ? EXEC_CLEAN_STATE : 0;
885 return 0;
886}
887
705578c3 888static int timer_can_start(Unit *u) {
e9fa1bf7 889 Timer *t = ASSERT_PTR(TIMER(u));
9727f242
DDM
890 int r;
891
9727f242
DDM
892 r = unit_test_start_limit(u);
893 if (r < 0) {
894 timer_enter_dead(t, TIMER_FAILURE_START_LIMIT_HIT);
895 return r;
896 }
897
705578c3 898 return 1;
9727f242
DDM
899}
900
c8bc7519 901static void activation_details_timer_serialize(ActivationDetails *details, FILE *f) {
e9fa1bf7 902 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519 903
c8bc7519
LB
904 assert(f);
905 assert(t);
906
907 (void) serialize_dual_timestamp(f, "activation-details-timer-last-trigger", &t->last_trigger);
908}
909
910static int activation_details_timer_deserialize(const char *key, const char *value, ActivationDetails **details) {
911 int r;
912
913 assert(key);
914 assert(value);
915
916 if (!details || !*details)
917 return -EINVAL;
918
919 ActivationDetailsTimer *t = ACTIVATION_DETAILS_TIMER(*details);
920 if (!t)
921 return -EINVAL;
922
923 if (!streq(key, "activation-details-timer-last-trigger"))
924 return -EINVAL;
925
926 r = deserialize_dual_timestamp(value, &t->last_trigger);
927 if (r < 0)
928 return r;
929
930 return 0;
931}
932
933static int activation_details_timer_append_env(ActivationDetails *details, char ***strv) {
e9fa1bf7 934 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519
LB
935 int r;
936
c8bc7519
LB
937 assert(strv);
938 assert(t);
939
940 if (!dual_timestamp_is_set(&t->last_trigger))
941 return 0;
942
6457ce15 943 r = strv_extendf(strv, "TRIGGER_TIMER_REALTIME_USEC=" USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
944 if (r < 0)
945 return r;
946
6457ce15 947 r = strv_extendf(strv, "TRIGGER_TIMER_MONOTONIC_USEC=" USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
948 if (r < 0)
949 return r;
950
951 return 2; /* Return the number of variables added to the env block */
952}
953
954static int activation_details_timer_append_pair(ActivationDetails *details, char ***strv) {
e9fa1bf7 955 ActivationDetailsTimer *t = ASSERT_PTR(ACTIVATION_DETAILS_TIMER(details));
c8bc7519
LB
956 int r;
957
c8bc7519
LB
958 assert(strv);
959 assert(t);
960
961 if (!dual_timestamp_is_set(&t->last_trigger))
962 return 0;
963
964 r = strv_extend(strv, "trigger_timer_realtime_usec");
965 if (r < 0)
966 return r;
967
6457ce15 968 r = strv_extendf(strv, USEC_FMT, t->last_trigger.realtime);
c8bc7519
LB
969 if (r < 0)
970 return r;
971
972 r = strv_extend(strv, "trigger_timer_monotonic_usec");
973 if (r < 0)
974 return r;
975
6457ce15 976 r = strv_extendf(strv, USEC_FMT, t->last_trigger.monotonic);
c8bc7519
LB
977 if (r < 0)
978 return r;
979
980 return 2; /* Return the number of pairs added to the env block */
981}
982
f8a990a0
DDM
983uint64_t timer_next_elapse_monotonic(const Timer *t) {
984 assert(t);
985
986 return (uint64_t) usec_shift_clock(t->next_elapse_monotonic_or_boottime,
987 TIMER_MONOTONIC_CLOCK(t), CLOCK_MONOTONIC);
988}
989
871d7de4 990static const char* const timer_base_table[_TIMER_BASE_MAX] = {
48d83e33
ZJS
991 [TIMER_ACTIVE] = "OnActiveSec",
992 [TIMER_BOOT] = "OnBootSec",
993 [TIMER_STARTUP] = "OnStartupSec",
994 [TIMER_UNIT_ACTIVE] = "OnUnitActiveSec",
36697dc0 995 [TIMER_UNIT_INACTIVE] = "OnUnitInactiveSec",
48d83e33 996 [TIMER_CALENDAR] = "OnCalendar"
871d7de4
LP
997};
998
999DEFINE_STRING_TABLE_LOOKUP(timer_base, TimerBase);
1000
f8a990a0
DDM
1001char* timer_base_to_usec_string(TimerBase i) {
1002 _cleanup_free_ char *buf = NULL;
1003 const char *s;
1004 size_t l;
1005
1006 s = timer_base_to_string(i);
1007
1008 if (endswith(s, "Sec")) {
1009 /* s/Sec/USec/ */
1010 l = strlen(s);
1011 buf = new(char, l+2);
1012 if (!buf)
1013 return NULL;
1014
1015 memcpy(buf, s, l-3);
1016 memcpy(buf+l-3, "USec", 5);
1017 } else {
1018 buf = strdup(s);
1019 if (!buf)
1020 return NULL;
1021 }
1022
1023 return TAKE_PTR(buf);
1024}
1025
067d72c9 1026static const char* const timer_result_table[_TIMER_RESULT_MAX] = {
40f41f34
DDM
1027 [TIMER_SUCCESS] = "success",
1028 [TIMER_FAILURE_RESOURCES] = "resources",
1029 [TIMER_FAILURE_START_LIMIT_HIT] = "start-limit-hit",
067d72c9
LP
1030};
1031
1032DEFINE_STRING_TABLE_LOOKUP(timer_result, TimerResult);
1033
87f0e418 1034const UnitVTable timer_vtable = {
7d17cfbc 1035 .object_size = sizeof(Timer),
718db961 1036
f975e971
LP
1037 .sections =
1038 "Unit\0"
1039 "Timer\0"
1040 "Install\0",
d8a812d1 1041 .private_section = "Timer",
5cb5a6ff 1042
c80a9a33
LP
1043 .can_transient = true,
1044 .can_fail = true,
1045 .can_trigger = true,
1046
871d7de4 1047 .init = timer_init,
034c6ed7 1048 .done = timer_done,
871d7de4
LP
1049 .load = timer_load,
1050
1051 .coldplug = timer_coldplug,
1052
1053 .dump = timer_dump,
1054
1055 .start = timer_start,
1056 .stop = timer_stop,
1057
89f6fe7b
LP
1058 .clean = timer_clean,
1059 .can_clean = timer_can_clean,
1060
871d7de4
LP
1061 .serialize = timer_serialize,
1062 .deserialize_item = timer_deserialize_item,
1063
1064 .active_state = timer_active_state,
1065 .sub_state_to_string = timer_sub_state_to_string,
1066
3ecaa09b
LP
1067 .trigger_notify = timer_trigger_notify,
1068
fdf20a31 1069 .reset_failed = timer_reset_failed,
8742514c 1070 .time_change = timer_time_change,
bbf5fd8e 1071 .timezone_change = timer_timezone_change,
5632e374 1072
d8a812d1 1073 .bus_set_property = bus_timer_set_property,
9727f242 1074
705578c3 1075 .can_start = timer_can_start,
5cb5a6ff 1076};
c8bc7519
LB
1077
1078const ActivationDetailsVTable activation_details_timer_vtable = {
1079 .object_size = sizeof(ActivationDetailsTimer),
1080
1081 .serialize = activation_details_timer_serialize,
1082 .deserialize = activation_details_timer_deserialize,
1083 .append_env = activation_details_timer_append_env,
1084 .append_pair = activation_details_timer_append_pair,
1085};