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