1
0
mirror of https://github.com/systemd/systemd synced 2026-03-22 14:54:52 +01:00

Compare commits

...

23 Commits

Author SHA1 Message Date
Yu Watanabe
e18f21e349
Merge pull request #20109 from keszybz/timestamp-macros
Add macros that define scratch buffer internally for timestamp/timespan formatting
2021-07-14 16:14:08 +09:00
Zbigniew Jędrzejewski-Szmek
ae732f6e2d networkd: minor refactoring 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
7dc7ab311b networkd: replace one trivial asprintf with xsprintf 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
fbc39784b0 shared/killall: replace one trivial asprintf with xsprintf 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
12619d0a80 tree-wide: do not use (void) asprintf
asprintf(3) says that the pointer is "undefined" after a failed call.
In the current glibc implementation it is just NULL. In principle the
call could return a valid pointer with bad contents or something.

We have two styles of error handling: in a majority of cases we would
check the return value, but sometimes we used (void) and relied on the
pointer not being set. In practice both styles should be equivalent,
but gcc doesn't like the second one with -Wunused-result. (Though only
sometimes. E.g. on my F34 box I don't get the same warnings as in CI,
even though the compiler version is very similar and the compilation
options are the same…). It's also nice to be consistent in our code base.
So let's always use the first style of error checking.
2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
cb3e854fed basic/time-util: indentation 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
6c6368e938 basic/{time,format}-util: warn when format result is unused
Now that anonymous buffers are used in almost all cases, code which
does not use the return value is usually broken.
2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
bc2a4af25f meson: re-enable -Wunused-result with clang
We disabled it in f73fb7b742f294b6d2126afa16001bd2ff6ab461 in response to an
apparent gcc bug. It seems that depending on the combination of optimization
options, gcc still ignores (void). But this seems to work fine with clang, so
let's re-enable the warning conditionally.
2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
9ca7e3d00d Replace format_bytes_cgroup_protection with FORMAT_BYTES_CGROUP_PROTECTION 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
46e23f9a8d tree-wide: add FORMAT_BYTES_FULL() 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
3c90437083 cgtop: use anonymous buffers for formatting of bytes and timespans 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
d3e4029457 basic/macro: make CONST_MAX(DECIMAL_STR_MAX(…), STRLEN(…)) possible
When those two macros were used together in CONST_MAX(), gcc would complain
about a type mismatch. So either DECIMAL_STR_MAX() should be made size_t like
STRLEN(), or STRLEN() be made unsigned.

Since those macros are only usable on arguments of (small) fixed size, any type
should be fine (even char would work…). For buffer size specifications, both
size_t and unsigned are OK. But unsigned was used for DECIMAL_STR_MAX macros
and FORMAT_foo_MAX macros, making STRLEN the only exception, so let's adjust
STRLEN() to be unsigned too.

Also: I don't think this is currently used anywhere, but if any of those macros
were used as an argument to sprintf, size_t would require a cast. ("%*s"
requires an int/unsigned argument.)
2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
22fd4a8f85 import: use SYNTHETIC_ERRNO in one more place 2021-07-09 11:11:25 +02:00
Zbigniew Jędrzejewski-Szmek
2b59bf51a0 tree-wide: add FORMAT_BYTES() 2021-07-09 11:11:21 +02:00
Zbigniew Jędrzejewski-Szmek
6c1abe8807 Inline some iterator variables 2021-07-09 11:03:36 +02:00
Zbigniew Jędrzejewski-Szmek
0086ef19cb tree-wide: add FORMAT_TIMESTAMP_STYLE() 2021-07-09 11:03:36 +02:00
Zbigniew Jędrzejewski-Szmek
6dc57047ff shared/format-table: allocate buffer of sufficient size 2021-07-09 11:03:36 +02:00
Zbigniew Jędrzejewski-Szmek
32fc5c4763 tree-wide: add FORMAT_TIMESTAMP_RELATIVE() 2021-07-09 11:03:36 +02:00
Zbigniew Jędrzejewski-Szmek
5291f26d4a tree-wide: add FORMAT_TIMESPAN() 2021-07-09 11:03:36 +02:00
Zbigniew Jędrzejewski-Szmek
5e62ac8b51 sd-journal: add FORMAT_TIMESTAMP_SAFE() 2021-07-09 11:03:35 +02:00
Zbigniew Jędrzejewski-Szmek
04f5c018ce tree-wide: use FORMAT_TIMESTAMP() 2021-07-09 11:03:35 +02:00
Zbigniew Jędrzejewski-Szmek
ae7c644c22 basic/time-util: add FORMAT_TIMESTAMP
This uses the same idea of an anonyous buffer as ETHER_ADDR_TO_STR().
2021-07-09 11:03:35 +02:00
Zbigniew Jędrzejewski-Szmek
e265fa8198 test-ether-addr-util: add a simple test that HW_ADDR_TO_STR works with nesting
It seems to, but I was a bit incredulous… The comment is adjusted to match
the standard.

The trick with a temporary buffer is neat. I wasn't sure if it is valid, but
the standard says so. The test really tests that we are reading the rules right
and that the compiler doesn't do anythign strange or emit an unexpected
warning.
2021-07-09 11:03:35 +02:00
99 changed files with 687 additions and 955 deletions

View File

@ -322,7 +322,6 @@ basic_disabled_warnings = [
'-Wno-format-signedness', '-Wno-format-signedness',
'-Wno-missing-field-initializers', '-Wno-missing-field-initializers',
'-Wno-unused-parameter', '-Wno-unused-parameter',
'-Wno-unused-result',
] ]
possible_common_cc_flags = [ possible_common_cc_flags = [
@ -366,6 +365,12 @@ if cc.get_id() == 'gcc' and (not '02'.contains(get_option('optimization')) or
possible_common_cc_flags += '-Wno-maybe-uninitialized' possible_common_cc_flags += '-Wno-maybe-uninitialized'
endif endif
# Disable -Wno-unused-result with gcc, see
# https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425.
if cc.get_id() == 'gcc'
possible_common_cc_flags += '-Wno-unused-result'
endif
# --as-needed and --no-undefined are provided by meson by default, # --as-needed and --no-undefined are provided by meson by default,
# run mesonconf to see what is enabled # run mesonconf to see what is enabled
possible_link_flags = [ possible_link_flags = [

View File

@ -583,11 +583,12 @@ static int assess_system_call_filter(
assert(a->parameter < _SYSCALL_FILTER_SET_MAX); assert(a->parameter < _SYSCALL_FILTER_SET_MAX);
const SyscallFilterSet *f = syscall_filter_sets + a->parameter; const SyscallFilterSet *f = syscall_filter_sets + a->parameter;
char *d = NULL; _cleanup_free_ char *d = NULL;
uint64_t b; uint64_t b;
int r;
if (!info->system_call_filter_allow_list && set_isempty(info->system_call_filter)) { if (!info->system_call_filter_allow_list && set_isempty(info->system_call_filter)) {
d = strdup("Service does not filter system calls"); r = free_and_strdup(&d, "Service does not filter system calls");
b = 10; b = 10;
} else { } else {
bool bad; bool bad;
@ -599,34 +600,33 @@ static int assess_system_call_filter(
if (info->system_call_filter_allow_list) { if (info->system_call_filter_allow_list) {
if (bad) { if (bad) {
(void) asprintf(&d, "System call allow list defined for service, and %s is included " r = asprintf(&d, "System call allow list defined for service, and %s is included "
"(e.g. %s is allowed)", "(e.g. %s is allowed)",
f->name, offender); f->name, offender);
b = 9; b = 9;
} else { } else {
(void) asprintf(&d, "System call allow list defined for service, and %s is not included", r = asprintf(&d, "System call allow list defined for service, and %s is not included",
f->name); f->name);
b = 0; b = 0;
} }
} else { } else {
if (bad) { if (bad) {
(void) asprintf(&d, "System call deny list defined for service, and %s is not included " r = asprintf(&d, "System call deny list defined for service, and %s is not included "
"(e.g. %s is allowed)", "(e.g. %s is allowed)",
f->name, offender); f->name, offender);
b = 10; b = 10;
} else { } else {
(void) asprintf(&d, "System call deny list defined for service, and %s is included", r = asprintf(&d, "System call deny list defined for service, and %s is included",
f->name); f->name);
b = 0; b = 0;
} }
} }
} }
if (r < 0)
if (!d)
return log_oom(); return log_oom();
*ret_badness = b; *ret_badness = b;
*ret_description = d; *ret_description = TAKE_PTR(d);
return 0; return 0;
} }

View File

@ -479,7 +479,6 @@ manager:
} }
static int pretty_boot_time(sd_bus *bus, char **_buf) { static int pretty_boot_time(sd_bus *bus, char **_buf) {
char ts[FORMAT_TIMESPAN_MAX];
BootTimes *t; BootTimes *t;
static char buf[4096]; static char buf[4096];
size_t size; size_t size;
@ -524,23 +523,23 @@ static int pretty_boot_time(sd_bus *bus, char **_buf) {
size = strpcpyf(&ptr, size, "Startup finished in "); size = strpcpyf(&ptr, size, "Startup finished in ");
if (t->firmware_time > 0) if (t->firmware_time > 0)
size = strpcpyf(&ptr, size, "%s (firmware) + ", format_timespan(ts, sizeof(ts), t->firmware_time - t->loader_time, USEC_PER_MSEC)); size = strpcpyf(&ptr, size, "%s (firmware) + ", FORMAT_TIMESPAN(t->firmware_time - t->loader_time, USEC_PER_MSEC));
if (t->loader_time > 0) if (t->loader_time > 0)
size = strpcpyf(&ptr, size, "%s (loader) + ", format_timespan(ts, sizeof(ts), t->loader_time, USEC_PER_MSEC)); size = strpcpyf(&ptr, size, "%s (loader) + ", FORMAT_TIMESPAN(t->loader_time, USEC_PER_MSEC));
if (t->kernel_done_time > 0) if (t->kernel_done_time > 0)
size = strpcpyf(&ptr, size, "%s (kernel) + ", format_timespan(ts, sizeof(ts), t->kernel_done_time, USEC_PER_MSEC)); size = strpcpyf(&ptr, size, "%s (kernel) + ", FORMAT_TIMESPAN(t->kernel_done_time, USEC_PER_MSEC));
if (t->initrd_time > 0) if (t->initrd_time > 0)
size = strpcpyf(&ptr, size, "%s (initrd) + ", format_timespan(ts, sizeof(ts), t->userspace_time - t->initrd_time, USEC_PER_MSEC)); size = strpcpyf(&ptr, size, "%s (initrd) + ", FORMAT_TIMESPAN(t->userspace_time - t->initrd_time, USEC_PER_MSEC));
size = strpcpyf(&ptr, size, "%s (userspace) ", format_timespan(ts, sizeof(ts), t->finish_time - t->userspace_time, USEC_PER_MSEC)); size = strpcpyf(&ptr, size, "%s (userspace) ", FORMAT_TIMESPAN(t->finish_time - t->userspace_time, USEC_PER_MSEC));
if (t->kernel_done_time > 0) if (t->kernel_done_time > 0)
strpcpyf(&ptr, size, "= %s ", format_timespan(ts, sizeof(ts), t->firmware_time + t->finish_time, USEC_PER_MSEC)); strpcpyf(&ptr, size, "= %s ", FORMAT_TIMESPAN(t->firmware_time + t->finish_time, USEC_PER_MSEC));
if (unit_id && timestamp_is_set(activated_time)) { if (unit_id && timestamp_is_set(activated_time)) {
usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset; usec_t base = t->userspace_time > 0 ? t->userspace_time : t->reverse_offset;
size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id, size = strpcpyf(&ptr, size, "\n%s reached after %s in userspace", unit_id,
format_timespan(ts, sizeof(ts), activated_time - base, USEC_PER_MSEC)); FORMAT_TIMESPAN(activated_time - base, USEC_PER_MSEC));
} else if (unit_id && activated_time == 0) } else if (unit_id && activated_time == 0)
size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id); size = strpcpyf(&ptr, size, "\n%s was never reached", unit_id);
else if (unit_id && activated_time == USEC_INFINITY) else if (unit_id && activated_time == USEC_INFINITY)
@ -591,7 +590,6 @@ static void svg_graph_box(double height, double begin, double end) {
} }
static int plot_unit_times(UnitTimes *u, double width, int y) { static int plot_unit_times(UnitTimes *u, double width, int y) {
char ts[FORMAT_TIMESPAN_MAX];
bool b; bool b;
if (!u->name) if (!u->name)
@ -605,7 +603,7 @@ static int plot_unit_times(UnitTimes *u, double width, int y) {
b = u->activating * SCALE_X < width / 2; b = u->activating * SCALE_X < width / 2;
if (u->time) if (u->time)
svg_text(b, u->activating, y, "%s (%s)", svg_text(b, u->activating, y, "%s (%s)",
u->name, format_timespan(ts, sizeof(ts), u->time, USEC_PER_MSEC)); u->name, FORMAT_TIMESPAN(u->time, USEC_PER_MSEC));
else else
svg_text(b, u->activating, y, "%s", u->name); svg_text(b, u->activating, y, "%s", u->name);
@ -836,8 +834,6 @@ static int list_dependencies_print(
UnitTimes *times, UnitTimes *times,
BootTimes *boot) { BootTimes *boot) {
char ts[FORMAT_TIMESPAN_MAX], ts2[FORMAT_TIMESPAN_MAX];
for (unsigned i = level; i != 0; i--) for (unsigned i = level; i != 0; i--)
printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE)); printf("%s", special_glyph(branches & (1 << (i-1)) ? SPECIAL_GLYPH_TREE_VERTICAL : SPECIAL_GLYPH_TREE_SPACE));
@ -846,10 +842,10 @@ static int list_dependencies_print(
if (times) { if (times) {
if (times->time > 0) if (times->time > 0)
printf("%s%s @%s +%s%s", ansi_highlight_red(), name, printf("%s%s @%s +%s%s", ansi_highlight_red(), name,
format_timespan(ts, sizeof(ts), times->activating - boot->userspace_time, USEC_PER_MSEC), FORMAT_TIMESPAN(times->activating - boot->userspace_time, USEC_PER_MSEC),
format_timespan(ts2, sizeof(ts2), times->time, USEC_PER_MSEC), ansi_normal()); FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
else if (times->activated > boot->userspace_time) else if (times->activated > boot->userspace_time)
printf("%s @%s", name, format_timespan(ts, sizeof(ts), times->activated - boot->userspace_time, USEC_PER_MSEC)); printf("%s @%s", name, FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
else else
printf("%s", name); printf("%s", name);
} else } else
@ -964,7 +960,6 @@ static int list_dependencies_one(sd_bus *bus, const char *name, unsigned level,
static int list_dependencies(sd_bus *bus, const char *name) { static int list_dependencies(sd_bus *bus, const char *name) {
_cleanup_strv_free_ char **units = NULL; _cleanup_strv_free_ char **units = NULL;
char ts[FORMAT_TIMESPAN_MAX];
UnitTimes *times; UnitTimes *times;
int r; int r;
const char *id; const char *id;
@ -1004,9 +999,10 @@ static int list_dependencies(sd_bus *bus, const char *name) {
if (times) { if (times) {
if (times->time) if (times->time)
printf("%s%s +%s%s\n", ansi_highlight_red(), id, printf("%s%s +%s%s\n", ansi_highlight_red(), id,
format_timespan(ts, sizeof(ts), times->time, USEC_PER_MSEC), ansi_normal()); FORMAT_TIMESPAN(times->time, USEC_PER_MSEC), ansi_normal());
else if (times->activated > boot->userspace_time) else if (times->activated > boot->userspace_time)
printf("%s @%s\n", id, format_timespan(ts, sizeof(ts), times->activated - boot->userspace_time, USEC_PER_MSEC)); printf("%s @%s\n", id,
FORMAT_TIMESPAN(times->activated - boot->userspace_time, USEC_PER_MSEC));
else else
printf("%s\n", id); printf("%s\n", id);
} }

View File

@ -120,13 +120,10 @@ int efi_get_variable(
n = st.st_size - 4; n = st.st_size - 4;
if (DEBUG_LOGGING) { if (DEBUG_LOGGING) {
char ts[FORMAT_TIMESPAN_MAX]; usec_t end = now(CLOCK_MONOTONIC);
usec_t end;
end = now(CLOCK_MONOTONIC);
if (end > begin + EFI_RETRY_DELAY) if (end > begin + EFI_RETRY_DELAY)
log_debug("Detected slow EFI variable read access on %s: %s", log_debug("Detected slow EFI variable read access on %s: %s",
variable, format_timespan(ts, sizeof(ts), end - begin, 1)); variable, FORMAT_TIMESPAN(end - begin, 1));
} }
/* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable /* Note that efivarfs interestingly doesn't require ftruncate() to update an existing EFI variable

View File

@ -23,7 +23,9 @@ struct hw_addr_data {
#define HW_ADDR_TO_STRING_MAX (3*HW_ADDR_MAX_SIZE) #define HW_ADDR_TO_STRING_MAX (3*HW_ADDR_MAX_SIZE)
char* hw_addr_to_string(const struct hw_addr_data *addr, char buffer[HW_ADDR_TO_STRING_MAX]); char* hw_addr_to_string(const struct hw_addr_data *addr, char buffer[HW_ADDR_TO_STRING_MAX]);
/* Use only as function argument, never stand-alone! */ /* Note: the lifetime of the compound literal is the immediately surrounding block,
* see C11 §6.5.2.5, and
* https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
#define HW_ADDR_TO_STR(hw_addr) hw_addr_to_string((hw_addr), (char[HW_ADDR_TO_STRING_MAX]){}) #define HW_ADDR_TO_STR(hw_addr) hw_addr_to_string((hw_addr), (char[HW_ADDR_TO_STRING_MAX]){})
#define HW_ADDR_NULL ((const struct hw_addr_data){}) #define HW_ADDR_NULL ((const struct hw_addr_data){})

View File

@ -74,16 +74,17 @@ typedef enum {
#define FORMAT_BYTES_MAX 16U #define FORMAT_BYTES_MAX 16U
char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag); char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) _warn_unused_result_;
_warn_unused_result_
static inline char *format_bytes(char *buf, size_t l, uint64_t t) { static inline char *format_bytes(char *buf, size_t l, uint64_t t) {
return format_bytes_full(buf, l, t, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | FORMAT_BYTES_TRAILING_B); return format_bytes_full(buf, l, t, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | FORMAT_BYTES_TRAILING_B);
} }
static inline char *format_bytes_cgroup_protection(char *buf, size_t l, uint64_t t) { /* Note: the lifetime of the compound literal is the immediately surrounding block,
if (t == CGROUP_LIMIT_MAX) { * see C11 §6.5.2.5, and
(void) snprintf(buf, l, "%s", "infinity"); * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
return buf; #define FORMAT_BYTES(t) format_bytes((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t)
} #define FORMAT_BYTES_FULL(t, flag) format_bytes_full((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t, flag)
return format_bytes(buf, l, t);
} #define FORMAT_BYTES_CGROUP_PROTECTION(t) (t == CGROUP_LIMIT_MAX ? "infinity" : FORMAT_BYTES(t))

View File

@ -30,6 +30,7 @@
#define _weakref_(x) __attribute__((__weakref__(#x))) #define _weakref_(x) __attribute__((__weakref__(#x)))
#define _alignas_(x) __attribute__((__aligned__(__alignof(x)))) #define _alignas_(x) __attribute__((__aligned__(__alignof(x))))
#define _alignptr_ __attribute__((__aligned__(sizeof(void*)))) #define _alignptr_ __attribute__((__aligned__(sizeof(void*))))
#define _warn_unused_result_ __attribute__((__warn_unused_result__))
#if __GNUC__ >= 7 #if __GNUC__ >= 7
#define _fallthrough_ __attribute__((__fallthrough__)) #define _fallthrough_ __attribute__((__fallthrough__))
#else #else
@ -213,7 +214,7 @@ static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) {
* Contrary to strlen(), this is a constant expression. * Contrary to strlen(), this is a constant expression.
* @x: a string literal. * @x: a string literal.
*/ */
#define STRLEN(x) (sizeof(""x"") - 1) #define STRLEN(x) ((unsigned) sizeof(""x"") - 1)
/* /*
* container_of - cast a member of a structure out to the containing structure * container_of - cast a member of a structure out to the containing structure
@ -341,10 +342,10 @@ static inline int __coverity_check_and_return__(int condition) {
* negative '-' prefix (hence works correctly on signed * negative '-' prefix (hence works correctly on signed
* types). Includes space for the trailing NUL. */ * types). Includes space for the trailing NUL. */
#define DECIMAL_STR_MAX(type) \ #define DECIMAL_STR_MAX(type) \
(2+(sizeof(type) <= 1 ? 3 : \ (2U+(sizeof(type) <= 1 ? 3U : \
sizeof(type) <= 2 ? 5 : \ sizeof(type) <= 2 ? 5U : \
sizeof(type) <= 4 ? 10 : \ sizeof(type) <= 4 ? 10U : \
sizeof(type) <= 8 ? 20 : sizeof(int[-2*(sizeof(type) > 8)]))) sizeof(type) <= 8 ? 20U : (unsigned) sizeof(int[-2*(sizeof(type) > 8)])))
#define DECIMAL_STR_WIDTH(x) \ #define DECIMAL_STR_WIDTH(x) \
({ \ ({ \

View File

@ -300,26 +300,26 @@ int rlimit_parse(int resource, const char *val, struct rlimit *ret) {
} }
int rlimit_format(const struct rlimit *rl, char **ret) { int rlimit_format(const struct rlimit *rl, char **ret) {
char *s = NULL; _cleanup_free_ char *s = NULL;
int r;
assert(rl); assert(rl);
assert(ret); assert(ret);
if (rl->rlim_cur >= RLIM_INFINITY && rl->rlim_max >= RLIM_INFINITY) if (rl->rlim_cur >= RLIM_INFINITY && rl->rlim_max >= RLIM_INFINITY)
s = strdup("infinity"); r = free_and_strdup(&s, "infinity");
else if (rl->rlim_cur >= RLIM_INFINITY) else if (rl->rlim_cur >= RLIM_INFINITY)
(void) asprintf(&s, "infinity:" RLIM_FMT, rl->rlim_max); r = asprintf(&s, "infinity:" RLIM_FMT, rl->rlim_max);
else if (rl->rlim_max >= RLIM_INFINITY) else if (rl->rlim_max >= RLIM_INFINITY)
(void) asprintf(&s, RLIM_FMT ":infinity", rl->rlim_cur); r = asprintf(&s, RLIM_FMT ":infinity", rl->rlim_cur);
else if (rl->rlim_cur == rl->rlim_max) else if (rl->rlim_cur == rl->rlim_max)
(void) asprintf(&s, RLIM_FMT, rl->rlim_cur); r = asprintf(&s, RLIM_FMT, rl->rlim_cur);
else else
(void) asprintf(&s, RLIM_FMT ":" RLIM_FMT, rl->rlim_cur, rl->rlim_max); r = asprintf(&s, RLIM_FMT ":" RLIM_FMT, rl->rlim_cur, rl->rlim_max);
if (r < 0)
if (!s)
return -ENOMEM; return -ENOMEM;
*ret = s; *ret = TAKE_PTR(s);
return 0; return 0;
} }

View File

@ -111,20 +111,31 @@ usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock);
usec_t timespec_load(const struct timespec *ts) _pure_; usec_t timespec_load(const struct timespec *ts) _pure_;
nsec_t timespec_load_nsec(const struct timespec *ts) _pure_; nsec_t timespec_load_nsec(const struct timespec *ts) _pure_;
struct timespec *timespec_store(struct timespec *ts, usec_t u); struct timespec* timespec_store(struct timespec *ts, usec_t u);
struct timespec *timespec_store_nsec(struct timespec *ts, nsec_t n); struct timespec* timespec_store_nsec(struct timespec *ts, nsec_t n);
usec_t timeval_load(const struct timeval *tv) _pure_; usec_t timeval_load(const struct timeval *tv) _pure_;
struct timeval *timeval_store(struct timeval *tv, usec_t u); struct timeval* timeval_store(struct timeval *tv, usec_t u);
char *format_timestamp_style(char *buf, size_t l, usec_t t, TimestampStyle style); char* format_timestamp_style(char *buf, size_t l, usec_t t, TimestampStyle style) _warn_unused_result_;
char *format_timestamp_relative(char *buf, size_t l, usec_t t); char* format_timestamp_relative(char *buf, size_t l, usec_t t) _warn_unused_result_;
char *format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy); char* format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) _warn_unused_result_;
static inline char *format_timestamp(char *buf, size_t l, usec_t t) { _warn_unused_result_
static inline char* format_timestamp(char *buf, size_t l, usec_t t) {
return format_timestamp_style(buf, l, t, TIMESTAMP_PRETTY); return format_timestamp_style(buf, l, t, TIMESTAMP_PRETTY);
} }
/* Note: the lifetime of the compound literal is the immediately surrounding block,
* see C11 §6.5.2.5, and
* https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
#define FORMAT_TIMESTAMP(t) format_timestamp((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t)
#define FORMAT_TIMESTAMP_RELATIVE(t) \
format_timestamp_relative((char[FORMAT_TIMESTAMP_RELATIVE_MAX]){}, FORMAT_TIMESTAMP_RELATIVE_MAX, t)
#define FORMAT_TIMESPAN(t, accuracy) format_timespan((char[FORMAT_TIMESPAN_MAX]){}, FORMAT_TIMESPAN_MAX, t, accuracy)
#define FORMAT_TIMESTAMP_STYLE(t, style) \
format_timestamp_style((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t, style)
int parse_timestamp(const char *t, usec_t *usec); int parse_timestamp(const char *t, usec_t *usec);
int parse_sec(const char *t, usec_t *usec); int parse_sec(const char *t, usec_t *usec);
@ -156,9 +167,8 @@ usec_t jiffies_to_usec(uint32_t jiffies);
bool in_utc_timezone(void); bool in_utc_timezone(void);
static inline usec_t usec_add(usec_t a, usec_t b) { static inline usec_t usec_add(usec_t a, usec_t b) {
/* Adds two time values, and makes sure USEC_INFINITY as input results as USEC_INFINITY in output,
/* Adds two time values, and makes sure USEC_INFINITY as input results as USEC_INFINITY in output, and doesn't * and doesn't overflow. */
* overflow. */
if (a > USEC_INFINITY - b) /* overflow check */ if (a > USEC_INFINITY - b) /* overflow check */
return USEC_INFINITY; return USEC_INFINITY;
@ -167,7 +177,6 @@ static inline usec_t usec_add(usec_t a, usec_t b) {
} }
static inline usec_t usec_sub_unsigned(usec_t timestamp, usec_t delta) { static inline usec_t usec_sub_unsigned(usec_t timestamp, usec_t delta) {
if (timestamp == USEC_INFINITY) /* Make sure infinity doesn't degrade */ if (timestamp == USEC_INFINITY) /* Make sure infinity doesn't degrade */
return USEC_INFINITY; return USEC_INFINITY;
if (timestamp < delta) if (timestamp < delta)
@ -184,14 +193,14 @@ static inline usec_t usec_sub_signed(usec_t timestamp, int64_t delta) {
} }
#if SIZEOF_TIME_T == 8 #if SIZEOF_TIME_T == 8
/* The last second we can format is 31. Dec 9999, 1s before midnight, because otherwise we'd enter 5 digit year /* The last second we can format is 31. Dec 9999, 1s before midnight, because otherwise we'd enter 5 digit
* territory. However, since we want to stay away from this in all timezones we take one day off. */ * year territory. However, since we want to stay away from this in all timezones we take one day off. */
#define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 253402214399000000) # define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 253402214399000000)
#elif SIZEOF_TIME_T == 4 #elif SIZEOF_TIME_T == 4
/* With a 32bit time_t we can't go beyond 2038... */ /* With a 32bit time_t we can't go beyond 2038... */
#define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 2147483647000000) # define USEC_TIMESTAMP_FORMATTABLE_MAX ((usec_t) 2147483647000000)
#else #else
#error "Yuck, time_t is neither 4 nor 8 bytes wide?" # error "Yuck, time_t is neither 4 nor 8 bytes wide?"
#endif #endif
int time_change_fd(void); int time_change_fd(void);

View File

@ -101,6 +101,10 @@ static const char *maybe_format_timespan(char *buf, size_t l, usec_t t, usec_t a
return format_timespan(buf, l, t, accuracy); return format_timespan(buf, l, t, accuracy);
} }
#define BUFSIZE1 CONST_MAX(FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t))
#define MAYBE_FORMAT_TIMESPAN(t, accuracy) \
maybe_format_timespan((char[BUFSIZE1]){}, BUFSIZE1, t, accuracy)
static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64_t t) { static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64_t t) {
if (!is_valid) if (!is_valid)
return "-"; return "-";
@ -111,6 +115,10 @@ static const char *maybe_format_bytes(char *buf, size_t l, bool is_valid, uint64
return format_bytes(buf, l, t); return format_bytes(buf, l, t);
} }
#define BUFSIZE2 CONST_MAX(FORMAT_BYTES_MAX, DECIMAL_STR_MAX(uint64_t))
#define MAYBE_FORMAT_BYTES(is_valid, t) \
maybe_format_bytes((char[BUFSIZE2]){}, BUFSIZE2, is_valid, t)
static bool is_root_cgroup(const char *path) { static bool is_root_cgroup(const char *path) {
/* Returns true if the specified path belongs to the root cgroup. The root cgroup is special on cgroup v2 as it /* Returns true if the specified path belongs to the root cgroup. The root cgroup is special on cgroup v2 as it
@ -595,8 +603,7 @@ static void display(Hashmap *a) {
Group *g; Group *g;
Group **array; Group **array;
signed path_columns; signed path_columns;
unsigned rows, n = 0, j, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */ unsigned rows, n = 0, maxtcpu = 0, maxtpath = 3; /* 3 for ellipsize() to work properly */
char buffer[MAX4(21U, FORMAT_BYTES_MAX, FORMAT_TIMESPAN_MAX, DECIMAL_STR_MAX(usec_t))];
assert(a); assert(a);
@ -612,43 +619,38 @@ static void display(Hashmap *a) {
typesafe_qsort(array, n, group_compare); typesafe_qsort(array, n, group_compare);
/* Find the longest names in one run */ /* Find the longest names in one run */
for (j = 0; j < n; j++) { for (unsigned j = 0; j < n; j++) {
unsigned cputlen, pathtlen; maxtcpu = MAX(maxtcpu,
strlen(MAYBE_FORMAT_TIMESPAN((usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0)));
maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (array[j]->cpu_usage / NSEC_PER_USEC), 0); maxtpath = MAX(maxtpath,
cputlen = strlen(buffer); strlen(array[j]->path));
maxtcpu = MAX(maxtcpu, cputlen);
pathtlen = strlen(array[j]->path);
maxtpath = MAX(maxtpath, pathtlen);
} }
if (arg_cpu_type == CPU_PERCENT)
xsprintf(buffer, "%6s", "%CPU");
else
xsprintf(buffer, "%*s", maxtcpu, "CPU Time");
rows = lines(); rows = lines();
if (rows <= 10) if (rows <= 10)
rows = 10; rows = 10;
if (on_tty()) { if (on_tty()) {
const char *on, *off; const char *on, *off;
unsigned cpu_len = arg_cpu_type == CPU_PERCENT ? 6 : maxtcpu;
path_columns = columns() - 36 - strlen(buffer); path_columns = columns() - 36 - cpu_len;
if (path_columns < 10) if (path_columns < 10)
path_columns = 10; path_columns = 10;
on = ansi_highlight_underline(); on = ansi_highlight_underline();
off = ansi_underline(); off = ansi_underline();
printf("%s%s%-*s%s %s%7s%s %s%s%s %s%8s%s %s%8s%s %s%8s%s%s\n", printf("%s%s%-*s%s %s%7s%s %s%*s%s %s%8s%s %s%8s%s %s%8s%s%s\n",
ansi_underline(), ansi_underline(),
arg_order == ORDER_PATH ? on : "", path_columns, "Control Group", arg_order == ORDER_PATH ? on : "", path_columns, "Control Group",
arg_order == ORDER_PATH ? off : "", arg_order == ORDER_PATH ? off : "",
arg_order == ORDER_TASKS ? on : "", arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+", arg_order == ORDER_TASKS ? on : "",
arg_count == COUNT_PIDS ? "Tasks" : arg_count == COUNT_USERSPACE_PROCESSES ? "Procs" : "Proc+",
arg_order == ORDER_TASKS ? off : "", arg_order == ORDER_TASKS ? off : "",
arg_order == ORDER_CPU ? on : "", buffer, arg_order == ORDER_CPU ? on : "",
cpu_len,
arg_cpu_type == CPU_PERCENT ? "%CPU" : "CPU Time",
arg_order == ORDER_CPU ? off : "", arg_order == ORDER_CPU ? off : "",
arg_order == ORDER_MEMORY ? on : "", "Memory", arg_order == ORDER_MEMORY ? on : "", "Memory",
arg_order == ORDER_MEMORY ? off : "", arg_order == ORDER_MEMORY ? off : "",
@ -660,7 +662,7 @@ static void display(Hashmap *a) {
} else } else
path_columns = maxtpath; path_columns = maxtpath;
for (j = 0; j < n; j++) { for (unsigned j = 0; j < n; j++) {
_cleanup_free_ char *ellipsized = NULL; _cleanup_free_ char *ellipsized = NULL;
const char *path; const char *path;
@ -684,11 +686,11 @@ static void display(Hashmap *a) {
else else
fputs(" -", stdout); fputs(" -", stdout);
} else } else
printf(" %*s", maxtcpu, maybe_format_timespan(buffer, sizeof(buffer), (usec_t) (g->cpu_usage / NSEC_PER_USEC), 0)); printf(" %*s", maxtcpu, MAYBE_FORMAT_TIMESPAN((usec_t) (g->cpu_usage / NSEC_PER_USEC), 0));
printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->memory_valid, g->memory)); printf(" %8s", MAYBE_FORMAT_BYTES(g->memory_valid, g->memory));
printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_input_bps)); printf(" %8s", MAYBE_FORMAT_BYTES(g->io_valid, g->io_input_bps));
printf(" %8s", maybe_format_bytes(buffer, sizeof(buffer), g->io_valid, g->io_output_bps)); printf(" %8s", MAYBE_FORMAT_BYTES(g->io_valid, g->io_output_bps));
putchar('\n'); putchar('\n');
} }
@ -949,7 +951,6 @@ static int run(int argc, char *argv[]) {
while (!quit) { while (!quit) {
usec_t t; usec_t t;
char key; char key;
char h[FORMAT_TIMESPAN_MAX];
t = now(CLOCK_MONOTONIC); t = now(CLOCK_MONOTONIC);
@ -1055,7 +1056,7 @@ static int run(int argc, char *argv[]) {
case '+': case '+':
arg_delay = usec_add(arg_delay, arg_delay < USEC_PER_SEC ? USEC_PER_MSEC * 250 : USEC_PER_SEC); arg_delay = usec_add(arg_delay, arg_delay < USEC_PER_SEC ? USEC_PER_MSEC * 250 : USEC_PER_SEC);
fprintf(stdout, "\nIncreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0)); fprintf(stdout, "\nIncreased delay to %s.", FORMAT_TIMESPAN(arg_delay, 0));
fflush(stdout); fflush(stdout);
sleep(1); sleep(1);
break; break;
@ -1066,7 +1067,7 @@ static int run(int argc, char *argv[]) {
else else
arg_delay = usec_sub_unsigned(arg_delay, arg_delay < USEC_PER_MSEC * 1250 ? USEC_PER_MSEC * 250 : USEC_PER_SEC); arg_delay = usec_sub_unsigned(arg_delay, arg_delay < USEC_PER_MSEC * 1250 ? USEC_PER_MSEC * 250 : USEC_PER_SEC);
fprintf(stdout, "\nDecreased delay to %s.", format_timespan(h, sizeof(h), arg_delay, 0)); fprintf(stdout, "\nDecreased delay to %s.", FORMAT_TIMESPAN(arg_delay, 0));
fflush(stdout); fflush(stdout);
sleep(1); sleep(1);
break; break;

View File

@ -305,7 +305,6 @@ static int automount_coldplug(Unit *u) {
} }
static void automount_dump(Unit *u, FILE *f, const char *prefix) { static void automount_dump(Unit *u, FILE *f, const char *prefix) {
char time_string[FORMAT_TIMESPAN_MAX];
Automount *a = AUTOMOUNT(u); Automount *a = AUTOMOUNT(u);
assert(a); assert(a);
@ -320,7 +319,7 @@ static void automount_dump(Unit *u, FILE *f, const char *prefix) {
prefix, automount_result_to_string(a->result), prefix, automount_result_to_string(a->result),
prefix, a->where, prefix, a->where,
prefix, a->directory_mode, prefix, a->directory_mode,
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, a->timeout_idle_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(a->timeout_idle_usec, USEC_PER_SEC));
} }
static void automount_enter_dead(Automount *a, AutomountResult f) { static void automount_enter_dead(Automount *a, AutomountResult f) {

View File

@ -394,8 +394,6 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
CGroupSocketBindItem *bi; CGroupSocketBindItem *bi;
IPAddressAccessItem *iaai; IPAddressAccessItem *iaai;
char **path; char **path;
char q[FORMAT_TIMESPAN_MAX];
char v[FORMAT_TIMESPAN_MAX];
char cda[FORMAT_CGROUP_DIFF_MAX]; char cda[FORMAT_CGROUP_DIFF_MAX];
char cdb[FORMAT_CGROUP_DIFF_MAX]; char cdb[FORMAT_CGROUP_DIFF_MAX];
@ -460,8 +458,8 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
prefix, c->startup_cpu_weight, prefix, c->startup_cpu_weight,
prefix, c->cpu_shares, prefix, c->cpu_shares,
prefix, c->startup_cpu_shares, prefix, c->startup_cpu_shares,
prefix, format_timespan(q, sizeof(q), c->cpu_quota_per_sec_usec, 1), prefix, FORMAT_TIMESPAN(c->cpu_quota_per_sec_usec, 1),
prefix, format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1), prefix, FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1),
prefix, strempty(cpuset_cpus), prefix, strempty(cpuset_cpus),
prefix, strempty(cpuset_mems), prefix, strempty(cpuset_mems),
prefix, c->io_weight, prefix, c->io_weight,
@ -514,11 +512,9 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
"%sIODeviceLatencyTargetSec: %s %s\n", "%sIODeviceLatencyTargetSec: %s %s\n",
prefix, prefix,
l->path, l->path,
format_timespan(q, sizeof(q), l->target_usec, 1)); FORMAT_TIMESPAN(l->target_usec, 1));
LIST_FOREACH(device_limits, il, c->io_device_limits) {
char buf[FORMAT_BYTES_MAX];
LIST_FOREACH(device_limits, il, c->io_device_limits)
for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++)
if (il->limits[type] != cgroup_io_limit_defaults[type]) if (il->limits[type] != cgroup_io_limit_defaults[type])
fprintf(f, fprintf(f,
@ -526,8 +522,7 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
prefix, prefix,
cgroup_io_limit_type_to_string(type), cgroup_io_limit_type_to_string(type),
il->path, il->path,
format_bytes(buf, sizeof(buf), il->limits[type])); FORMAT_BYTES(il->limits[type]));
}
LIST_FOREACH(device_weights, w, c->blockio_device_weights) LIST_FOREACH(device_weights, w, c->blockio_device_weights)
fprintf(f, fprintf(f,
@ -537,20 +532,18 @@ void cgroup_context_dump(Unit *u, FILE* f, const char *prefix) {
w->weight); w->weight);
LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) { LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
char buf[FORMAT_BYTES_MAX];
if (b->rbps != CGROUP_LIMIT_MAX) if (b->rbps != CGROUP_LIMIT_MAX)
fprintf(f, fprintf(f,
"%sBlockIOReadBandwidth: %s %s\n", "%sBlockIOReadBandwidth: %s %s\n",
prefix, prefix,
b->path, b->path,
format_bytes(buf, sizeof(buf), b->rbps)); FORMAT_BYTES(b->rbps));
if (b->wbps != CGROUP_LIMIT_MAX) if (b->wbps != CGROUP_LIMIT_MAX)
fprintf(f, fprintf(f,
"%sBlockIOWriteBandwidth: %s %s\n", "%sBlockIOWriteBandwidth: %s %s\n",
prefix, prefix,
b->path, b->path,
format_bytes(buf, sizeof(buf), b->wbps)); FORMAT_BYTES(b->wbps));
} }
LIST_FOREACH(items, iaai, c->ip_address_allow) { LIST_FOREACH(items, iaai, c->ip_address_allow) {
@ -869,10 +862,9 @@ static usec_t cgroup_cpu_adjust_period_and_log(Unit *u, usec_t period, usec_t qu
new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC); new_period = cgroup_cpu_adjust_period(period, quota, USEC_PER_MSEC, USEC_PER_SEC);
if (new_period != period) { if (new_period != period) {
char v[FORMAT_TIMESPAN_MAX];
log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING, log_unit_full(u, u->warned_clamping_cpu_quota_period ? LOG_DEBUG : LOG_WARNING,
"Clamping CPU interval for cpu.max: period is now %s", "Clamping CPU interval for cpu.max: period is now %s",
format_timespan(v, sizeof(v), new_period, 1)); FORMAT_TIMESPAN(new_period, 1));
u->warned_clamping_cpu_quota_period = true; u->warned_clamping_cpu_quota_period = true;
} }

View File

@ -1114,12 +1114,10 @@ int bus_cgroup_set_property(
unit_invalidate_cgroup(u, CGROUP_MASK_CPU); unit_invalidate_cgroup(u, CGROUP_MASK_CPU);
if (c->cpu_quota_period_usec == USEC_INFINITY) if (c->cpu_quota_period_usec == USEC_INFINITY)
unit_write_setting(u, flags, "CPUQuotaPeriodSec", "CPUQuotaPeriodSec="); unit_write_setting(u, flags, "CPUQuotaPeriodSec", "CPUQuotaPeriodSec=");
else { else
char v[FORMAT_TIMESPAN_MAX];
unit_write_settingf(u, flags, "CPUQuotaPeriodSec", unit_write_settingf(u, flags, "CPUQuotaPeriodSec",
"CPUQuotaPeriodSec=%s", "CPUQuotaPeriodSec=%s",
format_timespan(v, sizeof(v), c->cpu_quota_period_usec, 1)); FORMAT_TIMESPAN(c->cpu_quota_period_usec, 1));
}
} }
return 1; return 1;
@ -1374,7 +1372,6 @@ int bus_cgroup_set_property(
if (!UNIT_WRITE_FLAGS_NOOP(flags)) { if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
_cleanup_free_ char *buf = NULL; _cleanup_free_ char *buf = NULL;
_cleanup_fclose_ FILE *f = NULL; _cleanup_fclose_ FILE *f = NULL;
char ts[FORMAT_TIMESPAN_MAX];
CGroupIODeviceLatency *a; CGroupIODeviceLatency *a;
size_t size = 0; size_t size = 0;
@ -1392,7 +1389,7 @@ int bus_cgroup_set_property(
fputs("IODeviceLatencyTargetSec=\n", f); fputs("IODeviceLatencyTargetSec=\n", f);
LIST_FOREACH(device_latencies, a, c->io_device_latencies) LIST_FOREACH(device_latencies, a, c->io_device_latencies)
fprintf(f, "IODeviceLatencyTargetSec=%s %s\n", fprintf(f, "IODeviceLatencyTargetSec=%s %s\n",
a->path, format_timespan(ts, sizeof(ts), a->target_usec, 1)); a->path, FORMAT_TIMESPAN(a->target_usec, 1));
r = fflush_and_check(f); r = fflush_and_check(f);
if (r < 0) if (r < 0)

View File

@ -1324,16 +1324,14 @@ static int verify_run_space(const char *message, sd_bus_error *error) {
available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize; available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize;
if (available < RELOAD_DISK_SPACE_MIN) { if (available < RELOAD_DISK_SPACE_MIN)
char fb_available[FORMAT_BYTES_MAX], fb_need[FORMAT_BYTES_MAX];
return sd_bus_error_setf(error, return sd_bus_error_setf(error,
BUS_ERROR_DISK_FULL, BUS_ERROR_DISK_FULL,
"%s, not enough space available on /run/systemd. " "%s, not enough space available on /run/systemd. "
"Currently, %s are free, but a safety buffer of %s is enforced.", "Currently, %s are free, but a safety buffer of %s is enforced.",
message, message,
format_bytes(fb_available, sizeof(fb_available), available), FORMAT_BYTES(available),
format_bytes(fb_need, sizeof(fb_need), RELOAD_DISK_SPACE_MIN)); FORMAT_BYTES(RELOAD_DISK_SPACE_MIN));
}
return 0; return 0;
} }
@ -1530,13 +1528,11 @@ static int method_switch_root(sd_bus_message *message, void *userdata, sd_bus_er
available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize; available = (uint64_t) svfs.f_bfree * (uint64_t) svfs.f_bsize;
if (available < RELOAD_DISK_SPACE_MIN) { if (available < RELOAD_DISK_SPACE_MIN)
char fb_available[FORMAT_BYTES_MAX], fb_need[FORMAT_BYTES_MAX];
log_warning("Dangerously low amount of free space on /run/systemd, root switching might fail.\n" log_warning("Dangerously low amount of free space on /run/systemd, root switching might fail.\n"
"Currently, %s are free, but %s are suggested. Proceeding anyway.", "Currently, %s are free, but %s are suggested. Proceeding anyway.",
format_bytes(fb_available, sizeof(fb_available), available), FORMAT_BYTES(available),
format_bytes(fb_need, sizeof(fb_need), RELOAD_DISK_SPACE_MIN)); FORMAT_BYTES(RELOAD_DISK_SPACE_MIN));
}
r = mac_selinux_access_check(message, "reboot", error); r = mac_selinux_access_check(message, "reboot", error);
if (r < 0) if (r < 0)

View File

@ -147,13 +147,12 @@ static int timer_add_one_monotonic_spec(
sd_bus_error *error) { sd_bus_error *error) {
if (!UNIT_WRITE_FLAGS_NOOP(flags)) { if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
char ts[FORMAT_TIMESPAN_MAX];
TimerValue *v; TimerValue *v;
unit_write_settingf(UNIT(t), flags|UNIT_ESCAPE_SPECIFIERS, name, unit_write_settingf(UNIT(t), flags|UNIT_ESCAPE_SPECIFIERS, name,
"%s=%s", "%s=%s",
timer_base_to_string(base), timer_base_to_string(base),
format_timespan(ts, sizeof ts, usec, USEC_PER_MSEC)); FORMAT_TIMESPAN(usec, USEC_PER_MSEC));
v = new(TimerValue, 1); v = new(TimerValue, 1);
if (!v) if (!v)

View File

@ -112,16 +112,13 @@ int bus_set_transient_usec_internal(
return r; return r;
if (!UNIT_WRITE_FLAGS_NOOP(flags)) { if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
char *n, ts[FORMAT_TIMESPAN_MAX];
if (fix_0) if (fix_0)
*p = v != 0 ? v: USEC_INFINITY; *p = v != 0 ? v: USEC_INFINITY;
else else
*p = v; *p = v;
n = strndupa(name, strlen(name) - 4); char *n = strndupa(name, strlen(name) - 4);
unit_write_settingf(u, flags, name, "%sSec=%s", n, unit_write_settingf(u, flags, name, "%sSec=%s", n, FORMAT_TIMESPAN(v, USEC_PER_MSEC));
format_timespan(ts, sizeof(ts), v, USEC_PER_MSEC));
} }
return 1; return 1;

View File

@ -5288,7 +5288,7 @@ static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv
} }
void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) { void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
char **e, **d, buf_clean[FORMAT_TIMESPAN_MAX]; char **e, **d;
int r; int r;
assert(c); assert(c);
@ -5406,24 +5406,16 @@ void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d); fprintf(f, "%s%s: %s\n", prefix, exec_directory_type_to_string(dt), *d);
} }
fprintf(f, fprintf(f, "%sTimeoutCleanSec: %s\n", prefix, FORMAT_TIMESPAN(c->timeout_clean_usec, USEC_PER_SEC));
"%sTimeoutCleanSec: %s\n",
prefix, format_timespan(buf_clean, sizeof(buf_clean), c->timeout_clean_usec, USEC_PER_SEC));
if (c->nice_set) if (c->nice_set)
fprintf(f, fprintf(f, "%sNice: %i\n", prefix, c->nice);
"%sNice: %i\n",
prefix, c->nice);
if (c->oom_score_adjust_set) if (c->oom_score_adjust_set)
fprintf(f, fprintf(f, "%sOOMScoreAdjust: %i\n", prefix, c->oom_score_adjust);
"%sOOMScoreAdjust: %i\n",
prefix, c->oom_score_adjust);
if (c->coredump_filter_set) if (c->coredump_filter_set)
fprintf(f, fprintf(f, "%sCoredumpFilter: 0x%"PRIx64"\n", prefix, c->coredump_filter);
"%sCoredumpFilter: 0x%"PRIx64"\n",
prefix, c->coredump_filter);
for (unsigned i = 0; i < RLIM_NLIMITS; i++) for (unsigned i = 0; i < RLIM_NLIMITS; i++)
if (c->rlimit[i]) { if (c->rlimit[i]) {
@ -5546,13 +5538,10 @@ void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t)); fprintf(f, "%sLogLevelMax: %s\n", prefix, strna(t));
} }
if (c->log_ratelimit_interval_usec > 0) { if (c->log_ratelimit_interval_usec > 0)
char buf_timespan[FORMAT_TIMESPAN_MAX];
fprintf(f, fprintf(f,
"%sLogRateLimitIntervalSec: %s\n", "%sLogRateLimitIntervalSec: %s\n",
prefix, format_timespan(buf_timespan, sizeof(buf_timespan), c->log_ratelimit_interval_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(c->log_ratelimit_interval_usec, USEC_PER_SEC));
}
if (c->log_ratelimit_burst > 0) if (c->log_ratelimit_burst > 0)
fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst); fprintf(f, "%sLogRateLimitBurst: %u\n", prefix, c->log_ratelimit_burst);
@ -5965,8 +5954,6 @@ void exec_status_reset(ExecStatus *s) {
} }
void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) { void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
char buf[FORMAT_TIMESTAMP_MAX];
assert(s); assert(s);
assert(f); assert(f);
@ -5982,14 +5969,14 @@ void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix) {
if (dual_timestamp_is_set(&s->start_timestamp)) if (dual_timestamp_is_set(&s->start_timestamp))
fprintf(f, fprintf(f,
"%sStart Timestamp: %s\n", "%sStart Timestamp: %s\n",
prefix, format_timestamp(buf, sizeof(buf), s->start_timestamp.realtime)); prefix, FORMAT_TIMESTAMP(s->start_timestamp.realtime));
if (dual_timestamp_is_set(&s->exit_timestamp)) if (dual_timestamp_is_set(&s->exit_timestamp))
fprintf(f, fprintf(f,
"%sExit Timestamp: %s\n" "%sExit Timestamp: %s\n"
"%sExit Code: %s\n" "%sExit Code: %s\n"
"%sExit Status: %i\n", "%sExit Status: %i\n",
prefix, format_timestamp(buf, sizeof(buf), s->exit_timestamp.realtime), prefix, FORMAT_TIMESTAMP(s->exit_timestamp.realtime),
prefix, sigchld_code_to_string(s->code), prefix, sigchld_code_to_string(s->code),
prefix, s->status); prefix, s->status);
} }

View File

@ -1616,12 +1616,9 @@ static void apply_clock_update(void) {
if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, arg_clock_usec)) < 0) if (clock_settime(CLOCK_REALTIME, timespec_store(&ts, arg_clock_usec)) < 0)
log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m"); log_error_errno(errno, "Failed to set system clock to time specified on kernel command line: %m");
else { else
char buf[FORMAT_TIMESTAMP_MAX];
log_info("Set system clock to %s, as specified on the kernel command line.", log_info("Set system clock to %s, as specified on the kernel command line.",
format_timestamp(buf, sizeof(buf), arg_clock_usec)); FORMAT_TIMESTAMP(arg_clock_usec));
}
} }
static void cmdline_take_random_seed(void) { static void cmdline_take_random_seed(void) {
@ -2578,7 +2575,6 @@ int main(int argc, char *argv[]) {
char *switch_root_dir = NULL, *switch_root_init = NULL; char *switch_root_dir = NULL, *switch_root_init = NULL;
usec_t before_startup, after_startup; usec_t before_startup, after_startup;
static char systemd[] = "systemd"; static char systemd[] = "systemd";
char timespan[FORMAT_TIMESPAN_MAX];
const char *shutdown_verb = NULL, *error_message = NULL; const char *shutdown_verb = NULL, *error_message = NULL;
int r, retval = EXIT_FAILURE; int r, retval = EXIT_FAILURE;
Manager *m = NULL; Manager *m = NULL;
@ -2870,7 +2866,7 @@ int main(int argc, char *argv[]) {
log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG, log_full(arg_action == ACTION_TEST ? LOG_INFO : LOG_DEBUG,
"Loaded units and determined initial transaction in %s.", "Loaded units and determined initial transaction in %s.",
format_timespan(timespan, sizeof(timespan), after_startup - before_startup, 100 * USEC_PER_MSEC)); FORMAT_TIMESPAN(after_startup - before_startup, 100 * USEC_PER_MSEC));
if (arg_action == ACTION_TEST) { if (arg_action == ACTION_TEST) {
manager_test_summary(m); manager_test_summary(m);

View File

@ -38,14 +38,13 @@ void manager_dump(Manager *m, FILE *f, const char *prefix) {
for (ManagerTimestamp q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) { for (ManagerTimestamp q = 0; q < _MANAGER_TIMESTAMP_MAX; q++) {
const dual_timestamp *t = m->timestamps + q; const dual_timestamp *t = m->timestamps + q;
char buf[CONST_MAX(FORMAT_TIMESPAN_MAX, FORMAT_TIMESTAMP_MAX)];
if (dual_timestamp_is_set(t)) if (dual_timestamp_is_set(t))
fprintf(f, "%sTimestamp %s: %s\n", fprintf(f, "%sTimestamp %s: %s\n",
strempty(prefix), strempty(prefix),
manager_timestamp_to_string(q), manager_timestamp_to_string(q),
timestamp_is_set(t->realtime) ? format_timestamp(buf, sizeof buf, t->realtime) : timestamp_is_set(t->realtime) ? FORMAT_TIMESTAMP(t->realtime) :
format_timespan(buf, sizeof buf, t->monotonic, 1)); FORMAT_TIMESPAN(t->monotonic, 1));
} }
manager_dump_units(m, f, prefix); manager_dump_units(m, f, prefix);

View File

@ -205,7 +205,6 @@ static void manager_print_jobs_in_progress(Manager *m) {
unsigned counter = 0, print_nr; unsigned counter = 0, print_nr;
char cylon[6 + CYLON_BUFFER_EXTRA + 1]; char cylon[6 + CYLON_BUFFER_EXTRA + 1];
unsigned cylon_pos; unsigned cylon_pos;
char time[FORMAT_TIMESPAN_MAX], limit[FORMAT_TIMESPAN_MAX] = "no limit";
uint64_t x; uint64_t x;
assert(m); assert(m);
@ -231,14 +230,11 @@ static void manager_print_jobs_in_progress(Manager *m) {
m->jobs_in_progress_iteration++; m->jobs_in_progress_iteration++;
if (m->n_running_jobs > 1) { if (m->n_running_jobs > 1)
if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0) if (asprintf(&job_of_n, "(%u of %u) ", counter, m->n_running_jobs) < 0)
job_of_n = NULL; job_of_n = NULL;
}
format_timespan(time, sizeof(time), now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC); bool have_timeout = job_get_timeout(j, &x) > 0;
if (job_get_timeout(j, &x) > 0)
format_timespan(limit, sizeof(limit), x - j->begin_usec, 1*USEC_PER_SEC);
/* We want to use enough information for the user to identify previous lines talking about the same /* We want to use enough information for the user to identify previous lines talking about the same
* unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting * unit, but keep the message as short as possible. So if 'Starting foo.service' or 'Starting
@ -252,7 +248,8 @@ static void manager_print_jobs_in_progress(Manager *m) {
strempty(job_of_n), strempty(job_of_n),
job_type_to_string(j->type), job_type_to_string(j->type),
ident, ident,
time, limit); FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - j->begin_usec, 1*USEC_PER_SEC),
have_timeout ? FORMAT_TIMESPAN(x - j->begin_usec, 1*USEC_PER_SEC) : "no limit");
} }
static int have_ask_password(void) { static int have_ask_password(void) {
@ -3905,14 +3902,12 @@ static void log_taint_string(Manager *m) {
} }
static void manager_notify_finished(Manager *m) { static void manager_notify_finished(Manager *m) {
char userspace[FORMAT_TIMESPAN_MAX], initrd[FORMAT_TIMESPAN_MAX], kernel[FORMAT_TIMESPAN_MAX], sum[FORMAT_TIMESPAN_MAX];
usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec; usec_t firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec;
if (MANAGER_IS_TEST_RUN(m)) if (MANAGER_IS_TEST_RUN(m))
return; return;
if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) { if (MANAGER_IS_SYSTEM(m) && detect_container() <= 0) {
char ts[FORMAT_TIMESPAN_MAX];
char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")] char buf[FORMAT_TIMESPAN_MAX + STRLEN(" (firmware) + ") + FORMAT_TIMESPAN_MAX + STRLEN(" (loader) + ")]
= {}; = {};
char *p = buf; char *p = buf;
@ -3928,9 +3923,9 @@ static void manager_notify_finished(Manager *m) {
total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic; total_usec = m->timestamps[MANAGER_TIMESTAMP_FIRMWARE].monotonic + m->timestamps[MANAGER_TIMESTAMP_FINISH].monotonic;
if (firmware_usec > 0) if (firmware_usec > 0)
size = strpcpyf(&p, size, "%s (firmware) + ", format_timespan(ts, sizeof(ts), firmware_usec, USEC_PER_MSEC)); size = strpcpyf(&p, size, "%s (firmware) + ", FORMAT_TIMESPAN(firmware_usec, USEC_PER_MSEC));
if (loader_usec > 0) if (loader_usec > 0)
size = strpcpyf(&p, size, "%s (loader) + ", format_timespan(ts, sizeof(ts), loader_usec, USEC_PER_MSEC)); size = strpcpyf(&p, size, "%s (loader) + ", FORMAT_TIMESPAN(loader_usec, USEC_PER_MSEC));
if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) { if (dual_timestamp_is_set(&m->timestamps[MANAGER_TIMESTAMP_INITRD])) {
@ -3945,10 +3940,10 @@ static void manager_notify_finished(Manager *m) {
"USERSPACE_USEC="USEC_FMT, userspace_usec, "USERSPACE_USEC="USEC_FMT, userspace_usec,
LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.", LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (initrd) + %s (userspace) = %s.",
buf, buf,
format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC), FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
format_timespan(initrd, sizeof(initrd), initrd_usec, USEC_PER_MSEC), FORMAT_TIMESPAN(initrd_usec, USEC_PER_MSEC),
format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC), FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
} else { } else {
/* The initrd-less case on bare-metal */ /* The initrd-less case on bare-metal */
@ -3961,9 +3956,9 @@ static void manager_notify_finished(Manager *m) {
"USERSPACE_USEC="USEC_FMT, userspace_usec, "USERSPACE_USEC="USEC_FMT, userspace_usec,
LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.", LOG_MESSAGE("Startup finished in %s%s (kernel) + %s (userspace) = %s.",
buf, buf,
format_timespan(kernel, sizeof(kernel), kernel_usec, USEC_PER_MSEC), FORMAT_TIMESPAN(kernel_usec, USEC_PER_MSEC),
format_timespan(userspace, sizeof(userspace), userspace_usec, USEC_PER_MSEC), FORMAT_TIMESPAN(userspace_usec, USEC_PER_MSEC),
format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
} }
} else { } else {
/* The container and --user case */ /* The container and --user case */
@ -3974,7 +3969,7 @@ static void manager_notify_finished(Manager *m) {
"MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR, "MESSAGE_ID=" SD_MESSAGE_USER_STARTUP_FINISHED_STR,
"USERSPACE_USEC="USEC_FMT, userspace_usec, "USERSPACE_USEC="USEC_FMT, userspace_usec,
LOG_MESSAGE("Startup finished in %s.", LOG_MESSAGE("Startup finished in %s.",
format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC))); FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC)));
} }
bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec); bus_manager_send_finished(m, firmware_usec, loader_usec, kernel_usec, initrd_usec, userspace_usec, total_usec);
@ -3983,7 +3978,7 @@ static void manager_notify_finished(Manager *m) {
m->ready_sent ? "STATUS=Startup finished in %s." m->ready_sent ? "STATUS=Startup finished in %s."
: "READY=1\n" : "READY=1\n"
"STATUS=Startup finished in %s.", "STATUS=Startup finished in %s.",
format_timespan(sum, sizeof(sum), total_usec, USEC_PER_MSEC)); FORMAT_TIMESPAN(total_usec, USEC_PER_MSEC));
m->ready_sent = true; m->ready_sent = true;
log_taint_string(m); log_taint_string(m);

View File

@ -770,7 +770,6 @@ static int mount_coldplug(Unit *u) {
} }
static void mount_dump(Unit *u, FILE *f, const char *prefix) { static void mount_dump(Unit *u, FILE *f, const char *prefix) {
char buf[FORMAT_TIMESPAN_MAX];
Mount *m = MOUNT(u); Mount *m = MOUNT(u);
MountParameters *p; MountParameters *p;
@ -811,7 +810,7 @@ static void mount_dump(Unit *u, FILE *f, const char *prefix) {
prefix, yes_no(m->lazy_unmount), prefix, yes_no(m->lazy_unmount),
prefix, yes_no(m->force_unmount), prefix, yes_no(m->force_unmount),
prefix, yes_no(m->read_write_only), prefix, yes_no(m->read_write_only),
prefix, format_timespan(buf, sizeof(buf), m->timeout_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(m->timeout_usec, USEC_PER_SEC));
if (m->control_pid > 0) if (m->control_pid > 0)
fprintf(f, fprintf(f,

View File

@ -255,7 +255,6 @@ static int scope_coldplug(Unit *u) {
static void scope_dump(Unit *u, FILE *f, const char *prefix) { static void scope_dump(Unit *u, FILE *f, const char *prefix) {
Scope *s = SCOPE(u); Scope *s = SCOPE(u);
char buf_runtime[FORMAT_TIMESPAN_MAX];
assert(s); assert(s);
assert(f); assert(f);
@ -266,7 +265,7 @@ static void scope_dump(Unit *u, FILE *f, const char *prefix) {
"%sRuntimeMaxSec: %s\n", "%sRuntimeMaxSec: %s\n",
prefix, scope_state_to_string(s->state), prefix, scope_state_to_string(s->state),
prefix, scope_result_to_string(s->result), prefix, scope_result_to_string(s->result),
prefix, format_timespan(buf_runtime, sizeof(buf_runtime), s->runtime_max_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC));
cgroup_context_dump(UNIT(s), f, prefix); cgroup_context_dump(UNIT(s), f, prefix);
kill_context_dump(&s->kill_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix);

View File

@ -64,7 +64,6 @@ int mac_selinux_setup(bool *loaded_policy) {
r = selinux_init_load_policy(&enforce); r = selinux_init_load_policy(&enforce);
if (r == 0) { if (r == 0) {
_cleanup_(mac_selinux_freep) char *label = NULL; _cleanup_(mac_selinux_freep) char *label = NULL;
char timespan[FORMAT_TIMESPAN_MAX];
mac_selinux_retest(); mac_selinux_retest();
@ -84,7 +83,7 @@ int mac_selinux_setup(bool *loaded_policy) {
after_load = now(CLOCK_MONOTONIC); after_load = now(CLOCK_MONOTONIC);
log_info("Successfully loaded SELinux policy in %s.", log_info("Successfully loaded SELinux policy in %s.",
format_timespan(timespan, sizeof(timespan), after_load - before_load, 0)); FORMAT_TIMESPAN(after_load - before_load, 0));
*loaded_policy = true; *loaded_policy = true;

View File

@ -768,8 +768,6 @@ static int service_load(Unit *u) {
} }
static void service_dump(Unit *u, FILE *f, const char *prefix) { static void service_dump(Unit *u, FILE *f, const char *prefix) {
char buf_restart[FORMAT_TIMESPAN_MAX], buf_start[FORMAT_TIMESPAN_MAX], buf_stop[FORMAT_TIMESPAN_MAX],
buf_runtime[FORMAT_TIMESPAN_MAX], buf_watchdog[FORMAT_TIMESPAN_MAX], buf_abort[FORMAT_TIMESPAN_MAX];
ServiceExecCommand c; ServiceExecCommand c;
Service *s = SERVICE(u); Service *s = SERVICE(u);
const char *prefix2; const char *prefix2;
@ -844,22 +842,22 @@ static void service_dump(Unit *u, FILE *f, const char *prefix) {
"%sTimeoutStopSec: %s\n" "%sTimeoutStopSec: %s\n"
"%sTimeoutStartFailureMode: %s\n" "%sTimeoutStartFailureMode: %s\n"
"%sTimeoutStopFailureMode: %s\n", "%sTimeoutStopFailureMode: %s\n",
prefix, format_timespan(buf_restart, sizeof(buf_restart), s->restart_usec, USEC_PER_SEC), prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC),
prefix, format_timespan(buf_start, sizeof(buf_start), s->timeout_start_usec, USEC_PER_SEC), prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC),
prefix, format_timespan(buf_stop, sizeof(buf_stop), s->timeout_stop_usec, USEC_PER_SEC), prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC),
prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode), prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode),
prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode)); prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode));
if (s->timeout_abort_set) if (s->timeout_abort_set)
fprintf(f, fprintf(f,
"%sTimeoutAbortSec: %s\n", "%sTimeoutAbortSec: %s\n",
prefix, format_timespan(buf_abort, sizeof(buf_abort), s->timeout_abort_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC));
fprintf(f, fprintf(f,
"%sRuntimeMaxSec: %s\n" "%sRuntimeMaxSec: %s\n"
"%sWatchdogSec: %s\n", "%sWatchdogSec: %s\n",
prefix, format_timespan(buf_runtime, sizeof(buf_runtime), s->runtime_max_usec, USEC_PER_SEC), prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC),
prefix, format_timespan(buf_watchdog, sizeof(buf_watchdog), s->watchdog_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC));
kill_context_dump(&s->kill_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix);
exec_context_dump(&s->exec_context, f, prefix); exec_context_dump(&s->exec_context, f, prefix);
@ -3893,12 +3891,11 @@ static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *us
break; break;
case SERVICE_AUTO_RESTART: case SERVICE_AUTO_RESTART:
if (s->restart_usec > 0) { if (s->restart_usec > 0)
char buf_restart[FORMAT_TIMESPAN_MAX];
log_unit_debug(UNIT(s), log_unit_debug(UNIT(s),
"Service RestartSec=%s expired, scheduling restart.", "Service RestartSec=%s expired, scheduling restart.",
format_timespan(buf_restart, sizeof buf_restart, s->restart_usec, USEC_PER_SEC)); FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC));
} else else
log_unit_debug(UNIT(s), log_unit_debug(UNIT(s),
"Service has no hold-off time (RestartSec=0), scheduling restart."); "Service has no hold-off time (RestartSec=0), scheduling restart.");
@ -3923,7 +3920,6 @@ static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *us
static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) { static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata) {
Service *s = SERVICE(userdata); Service *s = SERVICE(userdata);
char t[FORMAT_TIMESPAN_MAX];
usec_t watchdog_usec; usec_t watchdog_usec;
assert(s); assert(s);
@ -3933,12 +3929,12 @@ static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void
if (UNIT(s)->manager->service_watchdogs) { if (UNIT(s)->manager->service_watchdogs) {
log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!", log_unit_error(UNIT(s), "Watchdog timeout (limit %s)!",
format_timespan(t, sizeof(t), watchdog_usec, 1)); FORMAT_TIMESPAN(watchdog_usec, 1));
service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG); service_enter_signal(s, SERVICE_STOP_WATCHDOG, SERVICE_FAILURE_WATCHDOG);
} else } else
log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!", log_unit_warning(UNIT(s), "Watchdog disabled! Ignoring watchdog timeout (limit %s)!",
format_timespan(t, sizeof(t), watchdog_usec, 1)); FORMAT_TIMESPAN(watchdog_usec, 1));
return 0; return 0;
} }

View File

@ -563,8 +563,6 @@ _const_ static const char* listen_lookup(int family, int type) {
} }
static void socket_dump(Unit *u, FILE *f, const char *prefix) { static void socket_dump(Unit *u, FILE *f, const char *prefix) {
char time_string[FORMAT_TIMESPAN_MAX];
SocketExecCommand c;
Socket *s = SOCKET(u); Socket *s = SOCKET(u);
SocketPort *p; SocketPort *p;
const char *prefix2, *str; const char *prefix2, *str;
@ -723,12 +721,12 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) {
if (s->keep_alive_time > 0) if (s->keep_alive_time > 0)
fprintf(f, fprintf(f,
"%sKeepAliveTimeSec: %s\n", "%sKeepAliveTimeSec: %s\n",
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_time, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->keep_alive_time, USEC_PER_SEC));
if (s->keep_alive_interval > 0) if (s->keep_alive_interval > 0)
fprintf(f, fprintf(f,
"%sKeepAliveIntervalSec: %s\n", "%sKeepAliveIntervalSec: %s\n",
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->keep_alive_interval, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->keep_alive_interval, USEC_PER_SEC));
if (s->keep_alive_cnt > 0) if (s->keep_alive_cnt > 0)
fprintf(f, fprintf(f,
@ -738,7 +736,7 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) {
if (s->defer_accept > 0) if (s->defer_accept > 0)
fprintf(f, fprintf(f,
"%sDeferAcceptSec: %s\n", "%sDeferAcceptSec: %s\n",
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->defer_accept, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->defer_accept, USEC_PER_SEC));
LIST_FOREACH(port, p, s->ports) { LIST_FOREACH(port, p, s->ports) {
@ -774,7 +772,7 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) {
fprintf(f, fprintf(f,
"%sTriggerLimitIntervalSec: %s\n" "%sTriggerLimitIntervalSec: %s\n"
"%sTriggerLimitBurst: %u\n", "%sTriggerLimitBurst: %u\n",
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->trigger_limit.interval, USEC_PER_SEC), prefix, FORMAT_TIMESPAN(s->trigger_limit.interval, USEC_PER_SEC),
prefix, s->trigger_limit.burst); prefix, s->trigger_limit.burst);
str = ip_protocol_to_name(s->socket_protocol); str = ip_protocol_to_name(s->socket_protocol);
@ -793,12 +791,12 @@ static void socket_dump(Unit *u, FILE *f, const char *prefix) {
fprintf(f, fprintf(f,
"%sTimeoutSec: %s\n", "%sTimeoutSec: %s\n",
prefix, format_timespan(time_string, FORMAT_TIMESPAN_MAX, s->timeout_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
exec_context_dump(&s->exec_context, f, prefix); exec_context_dump(&s->exec_context, f, prefix);
kill_context_dump(&s->kill_context, f, prefix); kill_context_dump(&s->kill_context, f, prefix);
for (c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) { for (SocketExecCommand c = 0; c < _SOCKET_EXEC_COMMAND_MAX; c++) {
if (!s->exec_command[c]) if (!s->exec_command[c])
continue; continue;
@ -3260,11 +3258,9 @@ int socket_collect_fds(Socket *s, int **fds) {
return -ENOMEM; return -ENOMEM;
LIST_FOREACH(port, p, s->ports) { LIST_FOREACH(port, p, s->ports) {
size_t i;
if (p->fd >= 0) if (p->fd >= 0)
rfds[k++] = p->fd; rfds[k++] = p->fd;
for (i = 0; i < p->n_auxiliary_fds; ++i) for (size_t i = 0; i < p->n_auxiliary_fds; ++i)
rfds[k++] = p->auxiliary_fds[i]; rfds[k++] = p->auxiliary_fds[i];
} }

View File

@ -609,7 +609,6 @@ static int swap_coldplug(Unit *u) {
} }
static void swap_dump(Unit *u, FILE *f, const char *prefix) { static void swap_dump(Unit *u, FILE *f, const char *prefix) {
char buf[FORMAT_TIMESPAN_MAX];
Swap *s = SWAP(u); Swap *s = SWAP(u);
SwapParameters *p; SwapParameters *p;
@ -651,7 +650,7 @@ static void swap_dump(Unit *u, FILE *f, const char *prefix) {
fprintf(f, fprintf(f,
"%sTimeoutSec: %s\n", "%sTimeoutSec: %s\n",
prefix, format_timespan(buf, sizeof(buf), s->timeout_usec, USEC_PER_SEC)); prefix, FORMAT_TIMESPAN(s->timeout_usec, USEC_PER_SEC));
if (s->control_pid > 0) if (s->control_pid > 0)
fprintf(f, fprintf(f,

View File

@ -234,7 +234,6 @@ static int timer_load(Unit *u) {
} }
static void timer_dump(Unit *u, FILE *f, const char *prefix) { static void timer_dump(Unit *u, FILE *f, const char *prefix) {
char buf[FORMAT_TIMESPAN_MAX];
Timer *t = TIMER(u); Timer *t = TIMER(u);
Unit *trigger; Unit *trigger;
TimerValue *v; TimerValue *v;
@ -257,7 +256,7 @@ static void timer_dump(Unit *u, FILE *f, const char *prefix) {
prefix, trigger ? trigger->id : "n/a", prefix, trigger ? trigger->id : "n/a",
prefix, yes_no(t->persistent), prefix, yes_no(t->persistent),
prefix, yes_no(t->wake_system), prefix, yes_no(t->wake_system),
prefix, format_timespan(buf, sizeof(buf), t->accuracy_usec, 1), prefix, FORMAT_TIMESPAN(t->accuracy_usec, 1),
prefix, yes_no(t->remain_after_elapse), prefix, yes_no(t->remain_after_elapse),
prefix, yes_no(t->fixed_random_delay), prefix, yes_no(t->fixed_random_delay),
prefix, yes_no(t->on_clock_change), prefix, yes_no(t->on_clock_change),
@ -274,15 +273,12 @@ static void timer_dump(Unit *u, FILE *f, const char *prefix) {
prefix, prefix,
timer_base_to_string(v->base), timer_base_to_string(v->base),
strna(p)); strna(p));
} else { } else
char timespan1[FORMAT_TIMESPAN_MAX];
fprintf(f, fprintf(f,
"%s%s: %s\n", "%s%s: %s\n",
prefix, prefix,
timer_base_to_string(v->base), timer_base_to_string(v->base),
format_timespan(timespan1, sizeof(timespan1), v->value, 0)); FORMAT_TIMESPAN(v->value, 0));
}
} }
static void timer_set_state(Timer *t, TimerState state) { static void timer_set_state(Timer *t, TimerState state) {
@ -355,7 +351,6 @@ static void timer_enter_elapsed(Timer *t, bool leave_around) {
} }
static void add_random(Timer *t, usec_t *v) { static void add_random(Timer *t, usec_t *v) {
char s[FORMAT_TIMESPAN_MAX];
usec_t add; usec_t add;
assert(t); assert(t);
@ -373,7 +368,7 @@ static void add_random(Timer *t, usec_t *v) {
else else
*v += add; *v += add;
log_unit_debug(UNIT(t), "Adding %s random time.", format_timespan(s, sizeof(s), add, 0)); log_unit_debug(UNIT(t), "Adding %s random time.", FORMAT_TIMESPAN(add, 0));
} }
static void timer_enter_waiting(Timer *t, bool time_change) { static void timer_enter_waiting(Timer *t, bool time_change) {
@ -508,13 +503,12 @@ static void timer_enter_waiting(Timer *t, bool time_change) {
} }
if (found_monotonic) { if (found_monotonic) {
char buf[FORMAT_TIMESPAN_MAX];
usec_t left; usec_t left;
add_random(t, &t->next_elapse_monotonic_or_boottime); add_random(t, &t->next_elapse_monotonic_or_boottime);
left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t))); left = usec_sub_unsigned(t->next_elapse_monotonic_or_boottime, triple_timestamp_by_clock(&ts, TIMER_MONOTONIC_CLOCK(t)));
log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", format_timespan(buf, sizeof(buf), left, 0)); log_unit_debug(UNIT(t), "Monotonic timer elapses in %s.", FORMAT_TIMESPAN(left, 0));
if (t->monotonic_event_source) { if (t->monotonic_event_source) {
r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime); r = sd_event_source_set_time(t->monotonic_event_source, t->next_elapse_monotonic_or_boottime);
@ -546,11 +540,9 @@ static void timer_enter_waiting(Timer *t, bool time_change) {
} }
if (found_realtime) { if (found_realtime) {
char buf[FORMAT_TIMESTAMP_MAX];
add_random(t, &t->next_elapse_realtime); add_random(t, &t->next_elapse_realtime);
log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", format_timestamp(buf, sizeof(buf), t->next_elapse_realtime)); log_unit_debug(UNIT(t), "Realtime timer elapses at %s.", FORMAT_TIMESTAMP(t->next_elapse_realtime));
if (t->realtime_event_source) { if (t->realtime_event_source) {
r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime); r = sd_event_source_set_time(t->realtime_event_source, t->next_elapse_realtime);
@ -664,12 +656,9 @@ static int timer_start(Unit *u) {
ft = timespec_load(&st.st_mtim); ft = timespec_load(&st.st_mtim);
if (ft < now(CLOCK_REALTIME)) if (ft < now(CLOCK_REALTIME))
t->last_trigger.realtime = ft; t->last_trigger.realtime = ft;
else { else
char z[FORMAT_TIMESTAMP_MAX];
log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.", log_unit_warning(u, "Not using persistent file timestamp %s as it is in the future.",
format_timestamp(z, sizeof(z), ft)); FORMAT_TIMESTAMP(ft));
}
} else if (errno == ENOENT) } else if (errno == ENOENT)
/* The timer has never run before, make sure a stamp file exists. */ /* The timer has never run before, make sure a stamp file exists. */

View File

@ -602,7 +602,6 @@ static void print_unit_dependency_mask(FILE *f, const char *kind, UnitDependency
void unit_dump(Unit *u, FILE *f, const char *prefix) { void unit_dump(Unit *u, FILE *f, const char *prefix) {
char *t, **j; char *t, **j;
const char *prefix2; const char *prefix2;
char timestamp[5][FORMAT_TIMESTAMP_MAX], timespan[FORMAT_TIMESPAN_MAX];
Unit *following; Unit *following;
_cleanup_set_free_ Set *following_set = NULL; _cleanup_set_free_ Set *following_set = NULL;
CGroupMask m; CGroupMask m;
@ -640,11 +639,11 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) {
prefix, strna(u->instance), prefix, strna(u->instance),
prefix, unit_load_state_to_string(u->load_state), prefix, unit_load_state_to_string(u->load_state),
prefix, unit_active_state_to_string(unit_active_state(u)), prefix, unit_active_state_to_string(unit_active_state(u)),
prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->state_change_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->state_change_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp[1], sizeof(timestamp[1]), u->inactive_exit_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->inactive_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp[2], sizeof(timestamp[2]), u->active_enter_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->active_enter_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp[3], sizeof(timestamp[3]), u->active_exit_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->active_exit_timestamp.realtime)),
prefix, strna(format_timestamp(timestamp[4], sizeof(timestamp[4]), u->inactive_enter_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->inactive_enter_timestamp.realtime)),
prefix, yes_no(unit_may_gc(u)), prefix, yes_no(unit_may_gc(u)),
prefix, yes_no(unit_need_daemon_reload(u)), prefix, yes_no(unit_need_daemon_reload(u)),
prefix, yes_no(u->transient), prefix, yes_no(u->transient),
@ -741,7 +740,7 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) {
fprintf(f, "%s\tSuccess Action Exit Status: %i\n", prefix, u->success_action_exit_status); fprintf(f, "%s\tSuccess Action Exit Status: %i\n", prefix, u->success_action_exit_status);
if (u->job_timeout != USEC_INFINITY) if (u->job_timeout != USEC_INFINITY)
fprintf(f, "%s\tJob Timeout: %s\n", prefix, format_timespan(timespan, sizeof(timespan), u->job_timeout, 0)); fprintf(f, "%s\tJob Timeout: %s\n", prefix, FORMAT_TIMESPAN(u->job_timeout, 0));
if (u->job_timeout_action != EMERGENCY_ACTION_NONE) if (u->job_timeout_action != EMERGENCY_ACTION_NONE)
fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, emergency_action_to_string(u->job_timeout_action)); fprintf(f, "%s\tJob Timeout Action: %s\n", prefix, emergency_action_to_string(u->job_timeout_action));
@ -756,14 +755,14 @@ void unit_dump(Unit *u, FILE *f, const char *prefix) {
fprintf(f, fprintf(f,
"%s\tCondition Timestamp: %s\n" "%s\tCondition Timestamp: %s\n"
"%s\tCondition Result: %s\n", "%s\tCondition Result: %s\n",
prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->condition_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->condition_timestamp.realtime)),
prefix, yes_no(u->condition_result)); prefix, yes_no(u->condition_result));
if (dual_timestamp_is_set(&u->assert_timestamp)) if (dual_timestamp_is_set(&u->assert_timestamp))
fprintf(f, fprintf(f,
"%s\tAssert Timestamp: %s\n" "%s\tAssert Timestamp: %s\n"
"%s\tAssert Result: %s\n", "%s\tAssert Result: %s\n",
prefix, strna(format_timestamp(timestamp[0], sizeof(timestamp[0]), u->assert_timestamp.realtime)), prefix, strna(FORMAT_TIMESTAMP(u->assert_timestamp.realtime)),
prefix, yes_no(u->assert_result)); prefix, yes_no(u->assert_result));
for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) { for (UnitDependency d = 0; d < _UNIT_DEPENDENCY_MAX; d++) {

View File

@ -2273,8 +2273,6 @@ static int unit_log_resources(Unit *u) {
(void) unit_get_cpu_usage(u, &nsec); (void) unit_get_cpu_usage(u, &nsec);
if (nsec != NSEC_INFINITY) { if (nsec != NSEC_INFINITY) {
char buf[FORMAT_TIMESPAN_MAX] = "";
/* Format the CPU time for inclusion in the structured log message */ /* Format the CPU time for inclusion in the structured log message */
if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) { if (asprintf(&t, "CPU_USAGE_NSEC=%" PRIu64, nsec) < 0) {
r = log_oom(); r = log_oom();
@ -2283,8 +2281,7 @@ static int unit_log_resources(Unit *u) {
iovec[n_iovec++] = IOVEC_MAKE_STRING(t); iovec[n_iovec++] = IOVEC_MAKE_STRING(t);
/* Format the CPU time for inclusion in the human language message string */ /* Format the CPU time for inclusion in the human language message string */
format_timespan(buf, sizeof(buf), nsec / NSEC_PER_USEC, USEC_PER_MSEC); t = strjoin("consumed ", FORMAT_TIMESPAN(nsec / NSEC_PER_USEC, USEC_PER_MSEC), " CPU time");
t = strjoin("consumed ", buf, " CPU time");
if (!t) { if (!t) {
r = log_oom(); r = log_oom();
goto finish; goto finish;
@ -2298,7 +2295,6 @@ static int unit_log_resources(Unit *u) {
} }
for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) { for (CGroupIOAccountingMetric k = 0; k < _CGROUP_IO_ACCOUNTING_METRIC_MAX; k++) {
char buf[FORMAT_BYTES_MAX] = "";
uint64_t value = UINT64_MAX; uint64_t value = UINT64_MAX;
assert(io_fields[k]); assert(io_fields[k]);
@ -2322,14 +2318,14 @@ static int unit_log_resources(Unit *u) {
* for the bytes counters (and not for the operations counters) */ * for the bytes counters (and not for the operations counters) */
if (k == CGROUP_IO_READ_BYTES) { if (k == CGROUP_IO_READ_BYTES) {
assert(!rr); assert(!rr);
rr = strjoin("read ", format_bytes(buf, sizeof(buf), value), " from disk"); rr = strjoin("read ", strna(FORMAT_BYTES(value)), " from disk");
if (!rr) { if (!rr) {
r = log_oom(); r = log_oom();
goto finish; goto finish;
} }
} else if (k == CGROUP_IO_WRITE_BYTES) { } else if (k == CGROUP_IO_WRITE_BYTES) {
assert(!wr); assert(!wr);
wr = strjoin("written ", format_bytes(buf, sizeof(buf), value), " to disk"); wr = strjoin("written ", strna(FORMAT_BYTES(value)), " to disk");
if (!wr) { if (!wr) {
r = log_oom(); r = log_oom();
goto finish; goto finish;
@ -2363,7 +2359,6 @@ static int unit_log_resources(Unit *u) {
} }
for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) { for (CGroupIPAccountingMetric m = 0; m < _CGROUP_IP_ACCOUNTING_METRIC_MAX; m++) {
char buf[FORMAT_BYTES_MAX] = "";
uint64_t value = UINT64_MAX; uint64_t value = UINT64_MAX;
assert(ip_fields[m]); assert(ip_fields[m]);
@ -2387,14 +2382,14 @@ static int unit_log_resources(Unit *u) {
* bytes counters (and not for the packets counters) */ * bytes counters (and not for the packets counters) */
if (m == CGROUP_IP_INGRESS_BYTES) { if (m == CGROUP_IP_INGRESS_BYTES) {
assert(!igress); assert(!igress);
igress = strjoin("received ", format_bytes(buf, sizeof(buf), value), " IP traffic"); igress = strjoin("received ", strna(FORMAT_BYTES(value)), " IP traffic");
if (!igress) { if (!igress) {
r = log_oom(); r = log_oom();
goto finish; goto finish;
} }
} else if (m == CGROUP_IP_EGRESS_BYTES) { } else if (m == CGROUP_IP_EGRESS_BYTES) {
assert(!egress); assert(!egress);
egress = strjoin("sent ", format_bytes(buf, sizeof(buf), value), " IP traffic"); egress = strjoin("sent ", strna(FORMAT_BYTES(value)), " IP traffic");
if (!egress) { if (!egress) {
r = log_oom(); r = log_oom();
goto finish; goto finish;

View File

@ -645,15 +645,11 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) {
usec_t u; usec_t u;
r = safe_atou64(timestamp, &u); r = safe_atou64(timestamp, &u);
if (r >= 0) { if (r >= 0)
char absolute[FORMAT_TIMESTAMP_MAX], relative[FORMAT_TIMESPAN_MAX]; fprintf(file, " Timestamp: %s (%s)\n",
FORMAT_TIMESTAMP(u), FORMAT_TIMESTAMP_RELATIVE(u));
fprintf(file, else
" Timestamp: %s (%s)\n",
format_timestamp(absolute, sizeof(absolute), u),
format_timestamp_relative(relative, sizeof(relative), u));
} else
fprintf(file, " Timestamp: %s\n", timestamp); fprintf(file, " Timestamp: %s\n", timestamp);
} }
@ -697,7 +693,6 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) {
if (filename) { if (filename) {
const char *state = NULL, *color = NULL; const char *state = NULL, *color = NULL;
uint64_t size = UINT64_MAX; uint64_t size = UINT64_MAX;
char buf[FORMAT_BYTES_MAX];
analyze_coredump_file(filename, &state, &color, &size); analyze_coredump_file(filename, &state, &color, &size);
@ -712,9 +707,8 @@ static int print_info(FILE *file, sd_journal *j, bool need_space) {
ansi_normal()); ansi_normal());
if (size != UINT64_MAX) if (size != UINT64_MAX)
fprintf(file, fprintf(file, " Disk Size: %s\n", FORMAT_BYTES(size));
" Disk Size: %s\n",
format_bytes(buf, sizeof(buf), size));
} else if (coredump) } else if (coredump)
fprintf(file, " Storage: journal\n"); fprintf(file, " Storage: journal\n");
else else

View File

@ -385,10 +385,8 @@ static int action_dissect(DissectedImage *m, LoopDevice *d) {
if (ioctl(d->fd, BLKGETSIZE64, &size) < 0) if (ioctl(d->fd, BLKGETSIZE64, &size) < 0)
log_debug_errno(errno, "Failed to query size of loopback device: %m"); log_debug_errno(errno, "Failed to query size of loopback device: %m");
else if (arg_json_format_flags & JSON_FORMAT_OFF) { else if (arg_json_format_flags & JSON_FORMAT_OFF)
char s[FORMAT_BYTES_MAX]; printf(" Size: %s\n", FORMAT_BYTES(size));
printf(" Size: %s\n", format_bytes(s, sizeof(s), size));
}
if (arg_json_format_flags & JSON_FORMAT_OFF) if (arg_json_format_flags & JSON_FORMAT_OFF)
putc('\n', stdout); putc('\n', stdout);

View File

@ -196,7 +196,6 @@ static int write_timeout(
const char *variable) { const char *variable) {
_cleanup_free_ char *timeout = NULL; _cleanup_free_ char *timeout = NULL;
char timespan[FORMAT_TIMESPAN_MAX];
usec_t u; usec_t u;
int r; int r;
@ -212,7 +211,7 @@ static int write_timeout(
return 0; return 0;
} }
fprintf(f, "%s=%s\n", variable, format_timespan(timespan, sizeof(timespan), u, 0)); fprintf(f, "%s=%s\n", variable, FORMAT_TIMESPAN(u, 0));
return 0; return 0;
} }

View File

@ -1097,15 +1097,15 @@ static int home_ratelimit(Home *h, sd_bus_error *error) {
} }
if (ret == 0) { if (ret == 0) {
char buf[FORMAT_TIMESPAN_MAX];
usec_t t, n; usec_t t, n;
n = now(CLOCK_REALTIME); n = now(CLOCK_REALTIME);
t = user_record_ratelimit_next_try(h->record); t = user_record_ratelimit_next_try(h->record);
if (t != USEC_INFINITY && t > n) if (t != USEC_INFINITY && t > n)
return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again in %s!", return sd_bus_error_setf(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT,
format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC)); "Too many login attempts, please try again in %s!",
FORMAT_TIMESPAN(t - n, USEC_PER_SEC));
return sd_bus_error_set(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again later."); return sd_bus_error_set(error, BUS_ERROR_AUTHENTICATION_LIMIT_HIT, "Too many login attempts, please try again later.");
} }

View File

@ -949,7 +949,6 @@ int home_store_header_identity_luks(
} }
int run_fitrim(int root_fd) { int run_fitrim(int root_fd) {
char buf[FORMAT_BYTES_MAX];
struct fstrim_range range = { struct fstrim_range range = {
.len = UINT64_MAX, .len = UINT64_MAX,
}; };
@ -968,8 +967,7 @@ int run_fitrim(int root_fd) {
return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m"); return log_warning_errno(errno, "Failed to invoke FITRIM, ignoring: %m");
} }
log_info("Discarded unused %s.", log_info("Discarded unused %s.", FORMAT_BYTES(range.len));
format_bytes(buf, sizeof(buf), range.len));
return 1; return 1;
} }
@ -984,7 +982,6 @@ int run_fitrim_by_path(const char *root_path) {
} }
int run_fallocate(int backing_fd, const struct stat *st) { int run_fallocate(int backing_fd, const struct stat *st) {
char buf[FORMAT_BYTES_MAX];
struct stat stbuf; struct stat stbuf;
assert(backing_fd >= 0); assert(backing_fd >= 0);
@ -1023,7 +1020,7 @@ int run_fallocate(int backing_fd, const struct stat *st) {
} }
log_info("Allocated additional %s.", log_info("Allocated additional %s.",
format_bytes(buf, sizeof(buf), (DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512)); FORMAT_BYTES((DIV_ROUND_UP(st->st_size, 512) - st->st_blocks) * 512));
return 1; return 1;
} }
@ -1278,15 +1275,13 @@ fail:
} }
static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, struct statfs *sfs) { static void print_size_summary(uint64_t host_size, uint64_t encrypted_size, struct statfs *sfs) {
char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX], buffer4[FORMAT_BYTES_MAX];
assert(sfs); assert(sfs);
log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.", log_info("Image size is %s, file system size is %s, file system payload size is %s, file system free is %s.",
format_bytes(buffer1, sizeof(buffer1), host_size), FORMAT_BYTES(host_size),
format_bytes(buffer2, sizeof(buffer2), encrypted_size), FORMAT_BYTES(encrypted_size),
format_bytes(buffer3, sizeof(buffer3), (uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize), FORMAT_BYTES((uint64_t) sfs->f_blocks * (uint64_t) sfs->f_frsize),
format_bytes(buffer4, sizeof(buffer4), (uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize)); FORMAT_BYTES((uint64_t) sfs->f_bfree * (uint64_t) sfs->f_frsize));
} }
int home_activate_luks( int home_activate_luks(
@ -1793,7 +1788,6 @@ static int wait_for_devlink(const char *path) {
} }
static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t *ret) { static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t *ret) {
char buf[FORMAT_BYTES_MAX];
struct statfs sfs; struct statfs sfs;
uint64_t m; uint64_t m;
@ -1820,14 +1814,14 @@ static int calculate_disk_size(UserRecord *h, const char *parent_dir, uint64_t *
log_info("Sizing home to %u%% of available disk space, which is %s.", log_info("Sizing home to %u%% of available disk space, which is %s.",
USER_DISK_SIZE_DEFAULT_PERCENT, USER_DISK_SIZE_DEFAULT_PERCENT,
format_bytes(buf, sizeof(buf), *ret)); FORMAT_BYTES(*ret));
} else { } else {
*ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m * (double) h->disk_size_relative / (double) UINT32_MAX)); *ret = DISK_SIZE_ROUND_DOWN((uint64_t) ((double) m * (double) h->disk_size_relative / (double) UINT32_MAX));
log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.", log_info("Sizing home to %" PRIu64 ".%01" PRIu64 "%% of available disk space, which is %s.",
(h->disk_size_relative * 100) / UINT32_MAX, (h->disk_size_relative * 100) / UINT32_MAX,
((h->disk_size_relative * 1000) / UINT32_MAX) % 10, ((h->disk_size_relative * 1000) / UINT32_MAX) % 10,
format_bytes(buf, sizeof(buf), *ret)); FORMAT_BYTES(*ret));
} }
if (*ret < USER_DISK_SIZE_MIN) if (*ret < USER_DISK_SIZE_MIN)
@ -2631,8 +2625,6 @@ int home_resize_luks(
HomeSetup *setup, HomeSetup *setup,
UserRecord **ret_home) { UserRecord **ret_home) {
char buffer1[FORMAT_BYTES_MAX], buffer2[FORMAT_BYTES_MAX], buffer3[FORMAT_BYTES_MAX],
buffer4[FORMAT_BYTES_MAX], buffer5[FORMAT_BYTES_MAX], buffer6[FORMAT_BYTES_MAX];
uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, new_partition_size; uint64_t old_image_size, new_image_size, old_fs_size, new_fs_size, crypto_offset, new_partition_size;
_cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL; _cleanup_(user_record_unrefp) UserRecord *header_home = NULL, *embedded_home = NULL, *new_home = NULL;
_cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL; _cleanup_(fdisk_unref_tablep) struct fdisk_table *table = NULL;
@ -2770,12 +2762,12 @@ int home_resize_luks(
return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online."); return log_error_errno(SYNTHETIC_ERRNO(ETXTBSY), "File systems of this type can only be resized offline, but is currently online.");
log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.", log_info("Ready to resize image size %s → %s, partition size %s → %s, file system size %s → %s.",
format_bytes(buffer1, sizeof(buffer1), old_image_size), FORMAT_BYTES(old_image_size),
format_bytes(buffer2, sizeof(buffer2), new_image_size), FORMAT_BYTES(new_image_size),
format_bytes(buffer3, sizeof(buffer3), setup->partition_size), FORMAT_BYTES(setup->partition_size),
format_bytes(buffer4, sizeof(buffer4), new_partition_size), FORMAT_BYTES(new_partition_size),
format_bytes(buffer5, sizeof(buffer5), old_fs_size), FORMAT_BYTES(old_fs_size),
format_bytes(buffer6, sizeof(buffer6), new_fs_size)); FORMAT_BYTES(new_fs_size));
r = prepare_resize_partition( r = prepare_resize_partition(
image_fd, image_fd,

View File

@ -892,9 +892,8 @@ _public_ PAM_EXTERN int pam_sm_acct_mgmt(
usec_t n = now(CLOCK_REALTIME); usec_t n = now(CLOCK_REALTIME);
if (t > n) { if (t > n) {
char buf[FORMAT_TIMESPAN_MAX];
(void) pam_prompt(handle, PAM_ERROR_MSG, NULL, "Too many logins, try again in %s.", (void) pam_prompt(handle, PAM_ERROR_MSG, NULL, "Too many logins, try again in %s.",
format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC)); FORMAT_TIMESPAN(t - n, USEC_PER_SEC));
return PAM_MAXTRIES; return PAM_MAXTRIES;
} }

View File

@ -62,11 +62,8 @@ static void progress_show(ProgressInfo *p) {
if (p->size == 0) if (p->size == 0)
log_info("Copying tree, currently at '%s'...", p->path); log_info("Copying tree, currently at '%s'...", p->path);
else { else
char buffer[FORMAT_BYTES_MAX]; log_info("Copying tree, currently at '%s' (@%s)...", p->path, FORMAT_BYTES(p->size));
log_info("Copying tree, currently at '%s' (@%s)...", p->path, format_bytes(buffer, sizeof(buffer), p->size));
}
} }
static int progress_path(const char *path, const struct stat *st, void *userdata) { static int progress_path(const char *path, const struct stat *st, void *userdata) {

View File

@ -501,15 +501,12 @@ static size_t pull_job_header_callback(void *contents, size_t size, size_t nmemb
(void) safe_atou64(length, &j->content_length); (void) safe_atou64(length, &j->content_length);
if (j->content_length != UINT64_MAX) { if (j->content_length != UINT64_MAX) {
char bytes[FORMAT_BYTES_MAX];
if (j->content_length > j->compressed_max) { if (j->content_length > j->compressed_max) {
log_error("Content too large."); r = log_error_errno(SYNTHETIC_ERRNO(EFBIG), "Content too large.");
r = -EFBIG;
goto fail; goto fail;
} }
log_info("Downloading %s for %s.", format_bytes(bytes, sizeof(bytes), j->content_length), j->url); log_info("Downloading %s for %s.", FORMAT_BYTES(j->content_length), j->url);
} }
return sz; return sz;
@ -554,10 +551,8 @@ static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_o
if (n > j->last_status_usec + USEC_PER_SEC && if (n > j->last_status_usec + USEC_PER_SEC &&
percent != j->progress_percent && percent != j->progress_percent &&
dlnow < dltotal) { dlnow < dltotal) {
char buf[FORMAT_TIMESPAN_MAX];
if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) { if (n - j->start_usec > USEC_PER_SEC && dlnow > 0) {
char y[FORMAT_BYTES_MAX];
usec_t left, done; usec_t left, done;
done = n - j->start_usec; done = n - j->start_usec;
@ -566,8 +561,8 @@ static int pull_job_progress_callback(void *userdata, curl_off_t dltotal, curl_o
log_info("Got %u%% of %s. %s left at %s/s.", log_info("Got %u%% of %s. %s left at %s/s.",
percent, percent,
j->url, j->url,
format_timespan(buf, sizeof(buf), left, USEC_PER_SEC), FORMAT_TIMESPAN(left, USEC_PER_SEC),
format_bytes(y, sizeof(y), (uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC)))); FORMAT_BYTES((uint64_t) ((double) dlnow / ((double) done / (double) USEC_PER_SEC))));
} else } else
log_info("Got %u%% of %s.", percent, j->url); log_info("Got %u%% of %s.", percent, j->url);

View File

@ -1942,7 +1942,6 @@ static int setup_keys(void) {
if (hn) if (hn)
hostname_cleanup(hn); hostname_cleanup(hn);
char tsb[FORMAT_TIMESPAN_MAX];
fprintf(stderr, fprintf(stderr,
"\nNew keys have been generated for host %s%s" SD_ID128_FORMAT_STR ".\n" "\nNew keys have been generated for host %s%s" SD_ID128_FORMAT_STR ".\n"
"\n" "\n"
@ -1961,7 +1960,7 @@ static int setup_keys(void) {
SD_ID128_FORMAT_VAL(machine), SD_ID128_FORMAT_VAL(machine),
ansi_highlight(), ansi_normal(), ansi_highlight(), ansi_normal(),
p, p,
format_timespan(tsb, sizeof(tsb), arg_interval, 0), FORMAT_TIMESPAN(arg_interval, 0),
ansi_highlight(), ansi_normal(), ansi_highlight(), ansi_normal(),
ansi_highlight_red()); ansi_highlight_red());
fflush(stderr); fflush(stderr);
@ -2014,7 +2013,7 @@ static int verify(sd_journal *j) {
else if (k < 0) else if (k < 0)
r = log_warning_errno(k, "FAIL: %s (%m)", f->path); r = log_warning_errno(k, "FAIL: %s (%m)", f->path);
else { else {
char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX], c[FORMAT_TIMESPAN_MAX]; char a[FORMAT_TIMESTAMP_MAX], b[FORMAT_TIMESTAMP_MAX];
log_info("PASS: %s", f->path); log_info("PASS: %s", f->path);
if (arg_verify_key && JOURNAL_HEADER_SEALED(f->header)) { if (arg_verify_key && JOURNAL_HEADER_SEALED(f->header)) {
@ -2022,10 +2021,10 @@ static int verify(sd_journal *j) {
log_info("=> Validated from %s to %s, final %s entries not sealed.", log_info("=> Validated from %s to %s, final %s entries not sealed.",
format_timestamp_maybe_utc(a, sizeof(a), first), format_timestamp_maybe_utc(a, sizeof(a), first),
format_timestamp_maybe_utc(b, sizeof(b), validated), format_timestamp_maybe_utc(b, sizeof(b), validated),
format_timespan(c, sizeof(c), last > validated ? last - validated : 0, 0)); FORMAT_TIMESPAN(last > validated ? last - validated : 0, 0));
} else if (last > 0) } else if (last > 0)
log_info("=> No sealing yet, %s of entries not sealed.", log_info("=> No sealing yet, %s of entries not sealed.",
format_timespan(c, sizeof(c), last - first, 0)); FORMAT_TIMESPAN(last - first, 0));
else else
log_info("=> No sealing yet, no entries in file."); log_info("=> No sealing yet, no entries in file.");
} }
@ -2328,14 +2327,13 @@ int main(int argc, char *argv[]) {
case ACTION_DISK_USAGE: { case ACTION_DISK_USAGE: {
uint64_t bytes = 0; uint64_t bytes = 0;
char sbytes[FORMAT_BYTES_MAX];
r = sd_journal_get_usage(j, &bytes); r = sd_journal_get_usage(j, &bytes);
if (r < 0) if (r < 0)
goto finish; goto finish;
printf("Archived and active journals take up %s in the file system.\n", printf("Archived and active journals take up %s in the file system.\n",
format_bytes(sbytes, sizeof(sbytes), bytes)); FORMAT_BYTES(bytes));
goto finish; goto finish;
} }

View File

@ -199,10 +199,6 @@ static int determine_space(Server *s, uint64_t *available, uint64_t *limit) {
} }
void server_space_usage_message(Server *s, JournalStorage *storage) { void server_space_usage_message(Server *s, JournalStorage *storage) {
char fb1[FORMAT_BYTES_MAX], fb2[FORMAT_BYTES_MAX], fb3[FORMAT_BYTES_MAX],
fb4[FORMAT_BYTES_MAX], fb5[FORMAT_BYTES_MAX], fb6[FORMAT_BYTES_MAX];
JournalMetrics *metrics;
assert(s); assert(s);
if (!storage) if (!storage)
@ -211,32 +207,31 @@ void server_space_usage_message(Server *s, JournalStorage *storage) {
if (cache_space_refresh(s, storage) < 0) if (cache_space_refresh(s, storage) < 0)
return; return;
metrics = &storage->metrics; const JournalMetrics *metrics = &storage->metrics;
format_bytes(fb1, sizeof(fb1), storage->space.vfs_used);
format_bytes(fb2, sizeof(fb2), metrics->max_use); const char
format_bytes(fb3, sizeof(fb3), metrics->keep_free); *vfs_used = FORMAT_BYTES(storage->space.vfs_used),
format_bytes(fb4, sizeof(fb4), storage->space.vfs_available); *limit = FORMAT_BYTES(storage->space.limit),
format_bytes(fb5, sizeof(fb5), storage->space.limit); *available = FORMAT_BYTES(storage->space.available);
format_bytes(fb6, sizeof(fb6), storage->space.available);
server_driver_message(s, 0, server_driver_message(s, 0,
"MESSAGE_ID=" SD_MESSAGE_JOURNAL_USAGE_STR, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_USAGE_STR,
LOG_MESSAGE("%s (%s) is %s, max %s, %s free.", LOG_MESSAGE("%s (%s) is %s, max %s, %s free.",
storage->name, storage->path, fb1, fb5, fb6), storage->name, storage->path, vfs_used, limit, available),
"JOURNAL_NAME=%s", storage->name, "JOURNAL_NAME=%s", storage->name,
"JOURNAL_PATH=%s", storage->path, "JOURNAL_PATH=%s", storage->path,
"CURRENT_USE=%"PRIu64, storage->space.vfs_used, "CURRENT_USE=%"PRIu64, storage->space.vfs_used,
"CURRENT_USE_PRETTY=%s", fb1, "CURRENT_USE_PRETTY=%s", vfs_used,
"MAX_USE=%"PRIu64, metrics->max_use, "MAX_USE=%"PRIu64, metrics->max_use,
"MAX_USE_PRETTY=%s", fb2, "MAX_USE_PRETTY=%s", FORMAT_BYTES(metrics->max_use),
"DISK_KEEP_FREE=%"PRIu64, metrics->keep_free, "DISK_KEEP_FREE=%"PRIu64, metrics->keep_free,
"DISK_KEEP_FREE_PRETTY=%s", fb3, "DISK_KEEP_FREE_PRETTY=%s", FORMAT_BYTES(metrics->keep_free),
"DISK_AVAILABLE=%"PRIu64, storage->space.vfs_available, "DISK_AVAILABLE=%"PRIu64, storage->space.vfs_available,
"DISK_AVAILABLE_PRETTY=%s", fb4, "DISK_AVAILABLE_PRETTY=%s", FORMAT_BYTES(storage->space.vfs_available),
"LIMIT=%"PRIu64, storage->space.limit, "LIMIT=%"PRIu64, storage->space.limit,
"LIMIT_PRETTY=%s", fb5, "LIMIT_PRETTY=%s", limit,
"AVAILABLE=%"PRIu64, storage->space.available, "AVAILABLE=%"PRIu64, storage->space.available,
"AVAILABLE_PRETTY=%s", fb6, "AVAILABLE_PRETTY=%s", available,
NULL); NULL);
} }
@ -1113,7 +1108,6 @@ void server_dispatch_message(
} }
int server_flush_to_var(Server *s, bool require_flag_file) { int server_flush_to_var(Server *s, bool require_flag_file) {
char ts[FORMAT_TIMESPAN_MAX];
sd_journal *j = NULL; sd_journal *j = NULL;
const char *fn; const char *fn;
unsigned n = 0; unsigned n = 0;
@ -1206,7 +1200,7 @@ finish:
server_driver_message(s, 0, NULL, server_driver_message(s, 0, NULL,
LOG_MESSAGE("Time spent on flushing to %s is %s for %u entries.", LOG_MESSAGE("Time spent on flushing to %s is %s for %u entries.",
s->system_storage.path, s->system_storage.path,
format_timespan(ts, sizeof(ts), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0), FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0),
n), n),
NULL); NULL);

View File

@ -1686,7 +1686,6 @@ static int client_handle_ack(sd_dhcp_client *client, DHCPMessage *ack, size_t le
static int client_set_lease_timeouts(sd_dhcp_client *client) { static int client_set_lease_timeouts(sd_dhcp_client *client) {
usec_t time_now; usec_t time_now;
char time_string[FORMAT_TIMESPAN_MAX];
int r; int r;
assert(client); assert(client);
@ -1748,7 +1747,7 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) {
return 0; return 0;
log_dhcp_client(client, "lease expires in %s", log_dhcp_client(client, "lease expires in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->expire_time - time_now, USEC_PER_SEC)); FORMAT_TIMESPAN(client->expire_time - time_now, USEC_PER_SEC));
/* arm T2 timeout */ /* arm T2 timeout */
r = event_reset_time(client->event, &client->timeout_t2, r = event_reset_time(client->event, &client->timeout_t2,
@ -1764,7 +1763,7 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) {
return 0; return 0;
log_dhcp_client(client, "T2 expires in %s", log_dhcp_client(client, "T2 expires in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->t2_time - time_now, USEC_PER_SEC)); FORMAT_TIMESPAN(client->t2_time - time_now, USEC_PER_SEC));
/* arm T1 timeout */ /* arm T1 timeout */
r = event_reset_time(client->event, &client->timeout_t1, r = event_reset_time(client->event, &client->timeout_t1,
@ -1777,14 +1776,13 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) {
if (client->t1_time > time_now) if (client->t1_time > time_now)
log_dhcp_client(client, "T1 expires in %s", log_dhcp_client(client, "T1 expires in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->t1_time - time_now, USEC_PER_SEC)); FORMAT_TIMESPAN(client->t1_time - time_now, USEC_PER_SEC));
return 0; return 0;
} }
static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, int len) { static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, int len) {
DHCP_CLIENT_DONT_DESTROY(client); DHCP_CLIENT_DONT_DESTROY(client);
char time_string[FORMAT_TIMESPAN_MAX];
int r, notify_event; int r, notify_event;
assert(client); assert(client);
@ -1830,8 +1828,7 @@ static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, i
if (r < 0) if (r < 0)
goto error; goto error;
log_dhcp_client(client, "REBOOT in %s", format_timespan(time_string, FORMAT_TIMESPAN_MAX, log_dhcp_client(client, "REBOOT in %s", FORMAT_TIMESPAN(client->start_delay, USEC_PER_SEC));
client->start_delay, USEC_PER_SEC));
client->start_delay = CLAMP(client->start_delay * 2, client->start_delay = CLAMP(client->start_delay * 2,
RESTART_AFTER_NAK_MIN_USEC, RESTART_AFTER_NAK_MAX_USEC); RESTART_AFTER_NAK_MIN_USEC, RESTART_AFTER_NAK_MAX_USEC);

View File

@ -946,7 +946,6 @@ static int client_timeout_resend(sd_event_source *s, uint64_t usec, void *userda
usec_t time_now, init_retransmit_time = 0, max_retransmit_time = 0; usec_t time_now, init_retransmit_time = 0, max_retransmit_time = 0;
usec_t max_retransmit_duration = 0; usec_t max_retransmit_duration = 0;
uint8_t max_retransmit_count = 0; uint8_t max_retransmit_count = 0;
char time_string[FORMAT_TIMESPAN_MAX];
assert(s); assert(s);
assert(client); assert(client);
@ -1042,7 +1041,7 @@ static int client_timeout_resend(sd_event_source *s, uint64_t usec, void *userda
} }
log_dhcp6_client(client, "Next retransmission in %s", log_dhcp6_client(client, "Next retransmission in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX, client->retransmit_time, USEC_PER_SEC)); FORMAT_TIMESPAN(client->retransmit_time, USEC_PER_SEC));
r = event_reset_time(client->event, &client->timeout_resend, r = event_reset_time(client->event, &client->timeout_resend,
clock_boottime_or_monotonic(), clock_boottime_or_monotonic(),
@ -1566,7 +1565,6 @@ static int client_get_lifetime(sd_dhcp6_client *client, uint32_t *lifetime_t1,
static int client_start(sd_dhcp6_client *client, enum DHCP6State state) { static int client_start(sd_dhcp6_client *client, enum DHCP6State state) {
int r; int r;
usec_t timeout, time_now; usec_t timeout, time_now;
char time_string[FORMAT_TIMESPAN_MAX];
uint32_t lifetime_t1, lifetime_t2; uint32_t lifetime_t1, lifetime_t2;
assert_return(client, -EINVAL); assert_return(client, -EINVAL);
@ -1639,8 +1637,7 @@ static int client_start(sd_dhcp6_client *client, enum DHCP6State state) {
timeout = client_timeout_compute_random(lifetime_t1 * USEC_PER_SEC); timeout = client_timeout_compute_random(lifetime_t1 * USEC_PER_SEC);
log_dhcp6_client(client, "T1 expires in %s", log_dhcp6_client(client, "T1 expires in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC));
format_timespan(time_string, FORMAT_TIMESPAN_MAX, timeout, USEC_PER_SEC));
r = event_reset_time(client->event, &client->timeout_t1, r = event_reset_time(client->event, &client->timeout_t1,
clock_boottime_or_monotonic(), clock_boottime_or_monotonic(),
@ -1652,8 +1649,7 @@ static int client_start(sd_dhcp6_client *client, enum DHCP6State state) {
timeout = client_timeout_compute_random(lifetime_t2 * USEC_PER_SEC); timeout = client_timeout_compute_random(lifetime_t2 * USEC_PER_SEC);
log_dhcp6_client(client, "T2 expires in %s", log_dhcp6_client(client, "T2 expires in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC));
format_timespan(time_string, FORMAT_TIMESPAN_MAX, timeout, USEC_PER_SEC));
r = event_reset_time(client->event, &client->timeout_t2, r = event_reset_time(client->event, &client->timeout_t2,
clock_boottime_or_monotonic(), clock_boottime_or_monotonic(),

View File

@ -225,10 +225,8 @@ static int ipv4acd_on_timeout(sd_event_source *s, uint64_t usec, void *userdata)
ipv4acd_set_state(acd, IPV4ACD_STATE_WAITING_PROBE, true); ipv4acd_set_state(acd, IPV4ACD_STATE_WAITING_PROBE, true);
if (acd->n_conflict >= MAX_CONFLICTS) { if (acd->n_conflict >= MAX_CONFLICTS) {
char ts[FORMAT_TIMESPAN_MAX];
log_ipv4acd(acd, "Max conflicts reached, delaying by %s", log_ipv4acd(acd, "Max conflicts reached, delaying by %s",
format_timespan(ts, sizeof(ts), RATE_LIMIT_INTERVAL_USEC, 0)); FORMAT_TIMESPAN(RATE_LIMIT_INTERVAL_USEC, 0));
r = ipv4acd_set_next_wakeup(acd, RATE_LIMIT_INTERVAL_USEC, PROBE_WAIT_USEC); r = ipv4acd_set_next_wakeup(acd, RATE_LIMIT_INTERVAL_USEC, PROBE_WAIT_USEC);
} else } else
r = ipv4acd_set_next_wakeup(acd, 0, PROBE_WAIT_USEC); r = ipv4acd_set_next_wakeup(acd, 0, PROBE_WAIT_USEC);

View File

@ -279,7 +279,6 @@ static usec_t ndisc_timeout_compute_random(usec_t val) {
} }
static int ndisc_timeout(sd_event_source *s, uint64_t usec, void *userdata) { static int ndisc_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
char time_string[FORMAT_TIMESPAN_MAX];
sd_ndisc *nd = userdata; sd_ndisc *nd = userdata;
usec_t time_now; usec_t time_now;
int r; int r;
@ -314,8 +313,7 @@ static int ndisc_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
} }
log_ndisc(nd, "Sent Router Solicitation, next solicitation in %s", log_ndisc(nd, "Sent Router Solicitation, next solicitation in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX, FORMAT_TIMESPAN(nd->retransmit_time, USEC_PER_SEC));
nd->retransmit_time, USEC_PER_SEC));
return 0; return 0;

View File

@ -301,7 +301,6 @@ static int radv_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
usec_t min_timeout = SD_RADV_DEFAULT_MIN_TIMEOUT_USEC; usec_t min_timeout = SD_RADV_DEFAULT_MIN_TIMEOUT_USEC;
usec_t max_timeout = SD_RADV_DEFAULT_MAX_TIMEOUT_USEC; usec_t max_timeout = SD_RADV_DEFAULT_MAX_TIMEOUT_USEC;
usec_t time_now, timeout; usec_t time_now, timeout;
char time_string[FORMAT_TIMESPAN_MAX];
assert(s); assert(s);
assert(ra); assert(ra);
@ -329,10 +328,7 @@ static int radv_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
} }
timeout = radv_compute_timeout(min_timeout, max_timeout); timeout = radv_compute_timeout(min_timeout, max_timeout);
log_radv(ra, "Next Router Advertisement in %s", FORMAT_TIMESPAN(timeout, USEC_PER_SEC));
log_radv(ra, "Next Router Advertisement in %s",
format_timespan(time_string, FORMAT_TIMESPAN_MAX,
timeout, USEC_PER_SEC));
r = event_reset_time(ra->event, &ra->timeout_event_source, r = event_reset_time(ra->event, &ra->timeout_event_source,
clock_boottime_or_monotonic(), clock_boottime_or_monotonic(),
@ -545,8 +541,6 @@ _public_ int sd_radv_add_prefix(sd_radv *ra, sd_radv_prefix *p, int dynamic) {
sd_radv_prefix *cur; sd_radv_prefix *cur;
int r; int r;
_cleanup_free_ char *addr_p = NULL; _cleanup_free_ char *addr_p = NULL;
char time_string_preferred[FORMAT_TIMESPAN_MAX];
char time_string_valid[FORMAT_TIMESPAN_MAX];
usec_t time_now, valid, preferred, valid_until, preferred_until; usec_t time_now, valid, preferred, valid_until, preferred_until;
assert_return(ra, -EINVAL); assert_return(ra, -EINVAL);
@ -628,10 +622,8 @@ _public_ int sd_radv_add_prefix(sd_radv *ra, sd_radv_prefix *p, int dynamic) {
log_radv(ra, "Updated prefix %s preferred %s valid %s", log_radv(ra, "Updated prefix %s preferred %s valid %s",
strna(addr_p), strna(addr_p),
format_timespan(time_string_preferred, FORMAT_TIMESPAN_MAX, FORMAT_TIMESPAN(preferred, USEC_PER_SEC),
preferred, USEC_PER_SEC), FORMAT_TIMESPAN(valid, USEC_PER_SEC));
format_timespan(time_string_valid, FORMAT_TIMESPAN_MAX,
valid, USEC_PER_SEC));
return 0; return 0;
} }
@ -662,7 +654,6 @@ _public_ sd_radv_prefix *sd_radv_remove_prefix(sd_radv *ra,
} }
_public_ int sd_radv_add_route_prefix(sd_radv *ra, sd_radv_route_prefix *p, int dynamic) { _public_ int sd_radv_add_route_prefix(sd_radv *ra, sd_radv_route_prefix *p, int dynamic) {
char time_string_valid[FORMAT_TIMESPAN_MAX];
usec_t time_now, valid, valid_until; usec_t time_now, valid, valid_until;
_cleanup_free_ char *pretty = NULL; _cleanup_free_ char *pretty = NULL;
sd_radv_route_prefix *cur; sd_radv_route_prefix *cur;
@ -732,7 +723,7 @@ _public_ int sd_radv_add_route_prefix(sd_radv *ra, sd_radv_route_prefix *p, int
log_radv(ra, "Updated route prefix %s valid %s", log_radv(ra, "Updated route prefix %s valid %s",
strna(pretty), strna(pretty),
format_timespan(time_string_valid, FORMAT_TIMESPAN_MAX, valid, USEC_PER_SEC)); FORMAT_TIMESPAN(valid, USEC_PER_SEC));
return 0; return 0;
} }

View File

@ -31,7 +31,6 @@ static send_ra_t send_ra_function;
static void router_dump(sd_ndisc_router *rt) { static void router_dump(sd_ndisc_router *rt) {
struct in6_addr addr; struct in6_addr addr;
char buf[FORMAT_TIMESTAMP_MAX];
uint8_t hop_limit; uint8_t hop_limit;
uint64_t t, flags; uint64_t t, flags;
uint32_t mtu; uint32_t mtu;
@ -45,7 +44,7 @@ static void router_dump(sd_ndisc_router *rt) {
assert_se(sd_ndisc_router_get_address(rt, &addr) == -ENODATA); assert_se(sd_ndisc_router_get_address(rt, &addr) == -ENODATA);
assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_REALTIME, &t) >= 0); assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_REALTIME, &t) >= 0);
log_info("Timestamp: %s", format_timestamp(buf, sizeof(buf), t)); log_info("Timestamp: %s", FORMAT_TIMESTAMP(t));
assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_MONOTONIC, &t) >= 0); assert_se(sd_ndisc_router_get_timestamp(rt, CLOCK_MONOTONIC, &t) >= 0);
log_info("Monotonic: %" PRIu64, t); log_info("Monotonic: %" PRIu64, t);
@ -318,9 +317,6 @@ static int test_timeout_value(uint8_t flags) {
static usec_t last = 0; static usec_t last = 0;
sd_ndisc *nd = test_timeout_nd; sd_ndisc *nd = test_timeout_nd;
usec_t min, max; usec_t min, max;
char time_string_min[FORMAT_TIMESPAN_MAX];
char time_string_nd[FORMAT_TIMESPAN_MAX];
char time_string_max[FORMAT_TIMESPAN_MAX];
assert_se(nd); assert_se(nd);
assert_se(nd->event); assert_se(nd->event);
@ -348,17 +344,12 @@ static int test_timeout_value(uint8_t flags) {
NDISC_MAX_ROUTER_SOLICITATION_INTERVAL / 10; NDISC_MAX_ROUTER_SOLICITATION_INTERVAL / 10;
} }
format_timespan(time_string_min, FORMAT_TIMESPAN_MAX,
min, USEC_PER_MSEC);
format_timespan(time_string_nd, FORMAT_TIMESPAN_MAX,
nd->retransmit_time, USEC_PER_MSEC);
format_timespan(time_string_max, FORMAT_TIMESPAN_MAX,
max, USEC_PER_MSEC);
log_info("backoff timeout interval %2d %s%s <= %s <= %s", log_info("backoff timeout interval %2d %s%s <= %s <= %s",
count, count,
(last * 2 > NDISC_MAX_ROUTER_SOLICITATION_INTERVAL)? "(max) ": "", last * 2 > NDISC_MAX_ROUTER_SOLICITATION_INTERVAL ? "(max) ": "",
time_string_min, time_string_nd, time_string_max); FORMAT_TIMESPAN(min, USEC_PER_MSEC),
FORMAT_TIMESPAN(nd->retransmit_time, USEC_PER_MSEC),
FORMAT_TIMESPAN(max, USEC_PER_MSEC));
assert_se(min <= nd->retransmit_time); assert_se(min <= nd->retransmit_time);
assert_se(max >= nd->retransmit_time); assert_se(max >= nd->retransmit_time);

View File

@ -55,15 +55,11 @@ _public_ int sd_bus_message_dump(sd_bus_message *m, FILE *f, uint64_t flags) {
f = stdout; f = stdout;
if (flags & SD_BUS_MESSAGE_DUMP_WITH_HEADER) { if (flags & SD_BUS_MESSAGE_DUMP_WITH_HEADER) {
char buf[FORMAT_TIMESTAMP_MAX];
const char *p;
usec_t ts = m->realtime; usec_t ts = m->realtime;
if (ts == 0) if (ts == 0)
ts = now(CLOCK_REALTIME); ts = now(CLOCK_REALTIME);
p = format_timestamp_style(buf, sizeof(buf), ts, TIMESTAMP_US_UTC);
fprintf(f, fprintf(f,
"%s%s%s Type=%s%s%s Endian=%c Flags=%u Version=%u", "%s%s%s Type=%s%s%s Endian=%c Flags=%u Version=%u",
m->header->type == SD_BUS_MESSAGE_METHOD_ERROR ? ansi_highlight_red() : m->header->type == SD_BUS_MESSAGE_METHOD_ERROR ? ansi_highlight_red() :
@ -90,9 +86,7 @@ _public_ int sd_bus_message_dump(sd_bus_message *m, FILE *f, uint64_t flags) {
if (m->reply_cookie != 0) if (m->reply_cookie != 0)
fprintf(f, " ReplyCookie=%" PRIu64, m->reply_cookie); fprintf(f, " ReplyCookie=%" PRIu64, m->reply_cookie);
fprintf(f, " Timestamp=\"%s\"", strna(p)); fprintf(f, " Timestamp=\"%s\"\n", strna(FORMAT_TIMESTAMP_STYLE(ts, TIMESTAMP_US_UTC)));
fputs("\n", f);
if (m->sender) if (m->sender)
fprintf(f, " Sender=%s%s%s", ansi_highlight(), m->sender, ansi_normal()); fprintf(f, " Sender=%s%s%s", ansi_highlight(), m->sender, ansi_normal());
@ -395,10 +389,8 @@ int bus_creds_dump(sd_bus_creds *c, FILE *f, bool terse) {
fprintf(f, "%sFSGID=%s"GID_FMT"%s", prefix, color, c->fsgid, suffix); fprintf(f, "%sFSGID=%s"GID_FMT"%s", prefix, color, c->fsgid, suffix);
if (c->mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) { if (c->mask & SD_BUS_CREDS_SUPPLEMENTARY_GIDS) {
unsigned i;
fprintf(f, "%sSupplementaryGIDs=%s", prefix, color); fprintf(f, "%sSupplementaryGIDs=%s", prefix, color);
for (i = 0; i < c->n_supplementary_gids; i++) for (unsigned i = 0; i < c->n_supplementary_gids; i++)
fprintf(f, "%s" GID_FMT, i > 0 ? " " : "", c->supplementary_gids[i]); fprintf(f, "%s" GID_FMT, i > 0 ? " " : "", c->supplementary_gids[i]);
fprintf(f, "%s", suffix); fprintf(f, "%s", suffix);
} }

View File

@ -252,10 +252,15 @@ int bus_error_setfv(sd_bus_error *e, const char *name, const char *format, va_li
return -ENOMEM; return -ENOMEM;
} }
/* If we hit OOM on formatting the pretty message, we ignore if (format) {
* this, since we at least managed to write the error name */ _cleanup_free_ char *mesg = NULL;
if (format)
(void) vasprintf((char**) &e->message, format, ap); /* If we hit OOM on formatting the pretty message, we ignore
* this, since we at least managed to write the error name */
if (vasprintf(&mesg, format, ap) >= 0)
e->message = TAKE_PTR(mesg);
}
e->_need_free = 1; e->_need_free = 1;
} }

View File

@ -3269,20 +3269,12 @@ fail:
log_error("File corrupt"); log_error("File corrupt");
} }
static const char* format_timestamp_safe(char *buf, size_t l, usec_t t) { /* Note: the lifetime of the compound literal is the immediately surrounding block. */
const char *x; #define FORMAT_TIMESTAMP_SAFE(t) (FORMAT_TIMESTAMP(t) ?: " --- ")
x = format_timestamp(buf, l, t);
if (x)
return x;
return " --- ";
}
void journal_file_print_header(JournalFile *f) { void journal_file_print_header(JournalFile *f) {
char a[SD_ID128_STRING_MAX], b[SD_ID128_STRING_MAX], c[SD_ID128_STRING_MAX], d[SD_ID128_STRING_MAX]; char a[SD_ID128_STRING_MAX], b[SD_ID128_STRING_MAX], c[SD_ID128_STRING_MAX], d[SD_ID128_STRING_MAX];
char x[FORMAT_TIMESTAMP_MAX], y[FORMAT_TIMESTAMP_MAX], z[FORMAT_TIMESTAMP_MAX];
struct stat st; struct stat st;
char bytes[FORMAT_BYTES_MAX];
assert(f); assert(f);
assert(f->header); assert(f->header);
@ -3329,9 +3321,9 @@ void journal_file_print_header(JournalFile *f) {
yes_no(journal_file_rotate_suggested(f, 0)), yes_no(journal_file_rotate_suggested(f, 0)),
le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum), le64toh(f->header->head_entry_seqnum),
le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum), le64toh(f->header->tail_entry_seqnum),
format_timestamp_safe(x, sizeof(x), le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime), FORMAT_TIMESTAMP_SAFE(le64toh(f->header->head_entry_realtime)), le64toh(f->header->head_entry_realtime),
format_timestamp_safe(y, sizeof(y), le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime), FORMAT_TIMESTAMP_SAFE(le64toh(f->header->tail_entry_realtime)), le64toh(f->header->tail_entry_realtime),
format_timespan(z, sizeof(z), le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic), FORMAT_TIMESPAN(le64toh(f->header->tail_entry_monotonic), USEC_PER_MSEC), le64toh(f->header->tail_entry_monotonic),
le64toh(f->header->n_objects), le64toh(f->header->n_objects),
le64toh(f->header->n_entries)); le64toh(f->header->n_entries));
@ -3363,7 +3355,7 @@ void journal_file_print_header(JournalFile *f) {
f->header->data_hash_chain_depth); f->header->data_hash_chain_depth);
if (fstat(f->fd, &st) >= 0) if (fstat(f->fd, &st) >= 0)
printf("Disk usage: %s\n", format_bytes(bytes, sizeof(bytes), (uint64_t) st.st_blocks * 512ULL)); printf("Disk usage: %s\n", FORMAT_BYTES((uint64_t) st.st_blocks * 512ULL));
} }
static int journal_file_warn_btrfs(JournalFile *f) { static int journal_file_warn_btrfs(JournalFile *f) {
@ -3468,7 +3460,6 @@ int journal_file_open(
if (DEBUG_LOGGING) { if (DEBUG_LOGGING) {
static int last_seal = -1, last_compress = -1, last_keyed_hash = -1; static int last_seal = -1, last_compress = -1, last_keyed_hash = -1;
static uint64_t last_bytes = UINT64_MAX; static uint64_t last_bytes = UINT64_MAX;
char bytes[FORMAT_BYTES_MAX];
if (last_seal != f->seal || if (last_seal != f->seal ||
last_keyed_hash != f->keyed_hash || last_keyed_hash != f->keyed_hash ||
@ -3477,7 +3468,7 @@ int journal_file_open(
log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s", log_debug("Journal effective settings seal=%s keyed_hash=%s compress=%s compress_threshold_bytes=%s",
yes_no(f->seal), yes_no(f->keyed_hash), yes_no(JOURNAL_FILE_COMPRESS(f)), yes_no(f->seal), yes_no(f->keyed_hash), yes_no(JOURNAL_FILE_COMPRESS(f)),
format_bytes(bytes, sizeof bytes, f->compress_threshold_bytes)); FORMAT_BYTES(f->compress_threshold_bytes));
last_seal = f->seal; last_seal = f->seal;
last_keyed_hash = f->keyed_hash; last_keyed_hash = f->keyed_hash;
last_compress = JOURNAL_FILE_COMPRESS(f); last_compress = JOURNAL_FILE_COMPRESS(f);
@ -3977,7 +3968,6 @@ void journal_reset_metrics(JournalMetrics *m) {
} }
void journal_default_metrics(JournalMetrics *m, int fd) { void journal_default_metrics(JournalMetrics *m, int fd) {
char a[FORMAT_BYTES_MAX], b[FORMAT_BYTES_MAX], c[FORMAT_BYTES_MAX], d[FORMAT_BYTES_MAX], e[FORMAT_BYTES_MAX];
struct statvfs ss; struct statvfs ss;
uint64_t fs_size = 0; uint64_t fs_size = 0;
@ -4047,11 +4037,11 @@ void journal_default_metrics(JournalMetrics *m, int fd) {
m->n_max_files = DEFAULT_N_MAX_FILES; m->n_max_files = DEFAULT_N_MAX_FILES;
log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64, log_debug("Fixed min_use=%s max_use=%s max_size=%s min_size=%s keep_free=%s n_max_files=%" PRIu64,
format_bytes(a, sizeof(a), m->min_use), FORMAT_BYTES(m->min_use),
format_bytes(b, sizeof(b), m->max_use), FORMAT_BYTES(m->max_use),
format_bytes(c, sizeof(c), m->max_size), FORMAT_BYTES(m->max_size),
format_bytes(d, sizeof(d), m->min_size), FORMAT_BYTES(m->min_size),
format_bytes(e, sizeof(e), m->keep_free), FORMAT_BYTES(m->keep_free),
m->n_max_files); m->n_max_files);
} }

View File

@ -131,7 +131,6 @@ int journal_directory_vacuum(
_cleanup_closedir_ DIR *d = NULL; _cleanup_closedir_ DIR *d = NULL;
struct vacuum_info *list = NULL; struct vacuum_info *list = NULL;
usec_t retention_limit = 0; usec_t retention_limit = 0;
char sbytes[FORMAT_BYTES_MAX];
struct dirent *de; struct dirent *de;
int r; int r;
@ -148,7 +147,6 @@ int journal_directory_vacuum(
return -errno; return -errno;
FOREACH_DIRENT_ALL(de, d, r = -errno; goto finish) { FOREACH_DIRENT_ALL(de, d, r = -errno; goto finish) {
unsigned long long seqnum = 0, realtime; unsigned long long seqnum = 0, realtime;
_cleanup_free_ char *p = NULL; _cleanup_free_ char *p = NULL;
sd_id128_t seqnum_id; sd_id128_t seqnum_id;
@ -254,7 +252,7 @@ int journal_directory_vacuum(
if (r >= 0) { if (r >= 0) {
log_full(verbose ? LOG_INFO : LOG_DEBUG, log_full(verbose ? LOG_INFO : LOG_DEBUG,
"Deleted empty archived journal %s/%s (%s).", directory, p, format_bytes(sbytes, sizeof(sbytes), size)); "Deleted empty archived journal %s/%s (%s).", directory, p, FORMAT_BYTES(size));
freed += size; freed += size;
} else if (r != -ENOENT) } else if (r != -ENOENT)
@ -296,7 +294,8 @@ int journal_directory_vacuum(
r = unlinkat_deallocate(dirfd(d), list[i].filename, 0); r = unlinkat_deallocate(dirfd(d), list[i].filename, 0);
if (r >= 0) { if (r >= 0) {
log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).", directory, list[i].filename, format_bytes(sbytes, sizeof(sbytes), list[i].usage)); log_full(verbose ? LOG_INFO : LOG_DEBUG, "Deleted archived journal %s/%s (%s).",
directory, list[i].filename, FORMAT_BYTES(list[i].usage));
freed += list[i].usage; freed += list[i].usage;
if (list[i].usage < sum) if (list[i].usage < sum)
@ -318,7 +317,8 @@ finish:
free(list[i].filename); free(list[i].filename);
free(list); free(list);
log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals from %s.", format_bytes(sbytes, sizeof(sbytes), freed), directory); log_full(verbose ? LOG_INFO : LOG_DEBUG, "Vacuuming done, freed %s of archived journals from %s.",
FORMAT_BYTES(freed), directory);
return r; return r;
} }

View File

@ -57,9 +57,6 @@ int main(int argc, char *argv[]) {
JournalFile *f; JournalFile *f;
const char *verification_key = argv[1]; const char *verification_key = argv[1];
usec_t from = 0, to = 0, total = 0; usec_t from = 0, to = 0, total = 0;
char a[FORMAT_TIMESTAMP_MAX];
char b[FORMAT_TIMESTAMP_MAX];
char c[FORMAT_TIMESPAN_MAX];
struct stat st; struct stat st;
uint64_t p; uint64_t p;
@ -105,9 +102,9 @@ int main(int argc, char *argv[]) {
if (verification_key && JOURNAL_HEADER_SEALED(f->header)) if (verification_key && JOURNAL_HEADER_SEALED(f->header))
log_info("=> Validated from %s to %s, %s missing", log_info("=> Validated from %s to %s, %s missing",
format_timestamp(a, sizeof(a), from), FORMAT_TIMESTAMP(from),
format_timestamp(b, sizeof(b), to), FORMAT_TIMESTAMP(to),
format_timespan(c, sizeof(c), total > to ? total - to : 0, 0)); FORMAT_TIMESPAN(total > to ? total - to : 0, 0));
(void) journal_file_close(f); (void) journal_file_close(f);

View File

@ -450,8 +450,6 @@ static int print_session_status_info(sd_bus *bus, const char *path, bool *new_li
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
char since1[FORMAT_TIMESTAMP_RELATIVE_MAX];
char since2[FORMAT_TIMESTAMP_MAX];
const char *s1, *s2; const char *s1, *s2;
SessionStatusInfo i = {}; SessionStatusInfo i = {};
int r; int r;
@ -472,8 +470,8 @@ static int print_session_status_info(sd_bus *bus, const char *path, bool *new_li
else else
printf("%"PRIu32"\n", i.uid); printf("%"PRIu32"\n", i.uid);
s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime); s1 = FORMAT_TIMESTAMP_RELATIVE(i.timestamp.realtime);
s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime); s2 = FORMAT_TIMESTAMP(i.timestamp.realtime);
if (s1) if (s1)
printf("\t Since: %s; %s\n", s2, s1); printf("\t Since: %s; %s\n", s2, s1);
@ -581,8 +579,6 @@ static int print_user_status_info(sd_bus *bus, const char *path, bool *new_line)
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
char since1[FORMAT_TIMESTAMP_RELATIVE_MAX];
char since2[FORMAT_TIMESTAMP_MAX];
const char *s1, *s2; const char *s1, *s2;
_cleanup_(user_status_info_clear) UserStatusInfo i = {}; _cleanup_(user_status_info_clear) UserStatusInfo i = {};
int r; int r;
@ -601,8 +597,8 @@ static int print_user_status_info(sd_bus *bus, const char *path, bool *new_line)
else else
printf("%"PRIu32"\n", i.uid); printf("%"PRIu32"\n", i.uid);
s1 = format_timestamp_relative(since1, sizeof(since1), i.timestamp.realtime); s1 = FORMAT_TIMESTAMP_RELATIVE(i.timestamp.realtime);
s2 = format_timestamp(since2, sizeof(since2), i.timestamp.realtime); s2 = FORMAT_TIMESTAMP(i.timestamp.realtime);
if (s1) if (s1)
printf("\t Since: %s; %s\n", s2, s1); printf("\t Since: %s; %s\n", s2, s1);

View File

@ -867,13 +867,10 @@ void user_update_last_session_timer(User *u) {
if (r < 0) if (r < 0)
log_warning_errno(r, "Failed to enqueue user stop event source, ignoring: %m"); log_warning_errno(r, "Failed to enqueue user stop event source, ignoring: %m");
if (DEBUG_LOGGING) { if (DEBUG_LOGGING)
char s[FORMAT_TIMESPAN_MAX];
log_debug("Last session of user '%s' logged out, terminating user context in %s.", log_debug("Last session of user '%s' logged out, terminating user context in %s.",
u->user_record->user_name, u->user_record->user_name,
format_timespan(s, sizeof(s), user_stop_delay, USEC_PER_MSEC)); FORMAT_TIMESPAN(user_stop_delay, USEC_PER_MSEC));
}
} }
static const char* const user_state_table[_USER_STATE_MAX] = { static const char* const user_state_table[_USER_STATE_MAX] = {

View File

@ -58,7 +58,6 @@ bool logind_wall_tty_filter(const char *tty, void *userdata) {
} }
static int warn_wall(Manager *m, usec_t n) { static int warn_wall(Manager *m, usec_t n) {
char date[FORMAT_TIMESTAMP_MAX] = {};
_cleanup_free_ char *l = NULL, *username = NULL; _cleanup_free_ char *l = NULL, *username = NULL;
usec_t left; usec_t left;
int r; int r;
@ -75,7 +74,7 @@ static int warn_wall(Manager *m, usec_t n) {
isempty(m->wall_message) ? "" : "\n", isempty(m->wall_message) ? "" : "\n",
m->scheduled_shutdown_type, m->scheduled_shutdown_type,
left ? "at " : "NOW", left ? "at " : "NOW",
left ? format_timestamp(date, sizeof(date), m->scheduled_shutdown_timeout) : ""); left ? FORMAT_TIMESTAMP(m->scheduled_shutdown_timeout) : "");
if (r < 0) { if (r < 0) {
log_oom(); log_oom();
return 0; return 0;

View File

@ -507,8 +507,6 @@ static void machine_status_info_clear(MachineStatusInfo *info) {
} }
static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) { static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) {
char since1[FORMAT_TIMESTAMP_RELATIVE_MAX];
char since2[FORMAT_TIMESTAMP_MAX];
_cleanup_free_ char *addresses = NULL; _cleanup_free_ char *addresses = NULL;
const char *s1, *s2; const char *s1, *s2;
int ifi = -1; int ifi = -1;
@ -523,8 +521,8 @@ static void print_machine_status_info(sd_bus *bus, MachineStatusInfo *i) {
else else
putchar('\n'); putchar('\n');
s1 = format_timestamp_relative(since1, sizeof(since1), i->timestamp.realtime); s1 = FORMAT_TIMESTAMP_RELATIVE(i->timestamp.realtime);
s2 = format_timestamp(since2, sizeof(since2), i->timestamp.realtime); s2 = FORMAT_TIMESTAMP(i->timestamp.realtime);
if (s1) if (s1)
printf("\t Since: %s; %s\n", s2, s1); printf("\t Since: %s; %s\n", s2, s1);
@ -828,10 +826,6 @@ typedef struct ImageStatusInfo {
} ImageStatusInfo; } ImageStatusInfo;
static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) { static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) {
char ts_relative[FORMAT_TIMESTAMP_RELATIVE_MAX];
char ts_absolute[FORMAT_TIMESTAMP_MAX];
char bs[FORMAT_BYTES_MAX];
char bs_exclusive[FORMAT_BYTES_MAX];
const char *s1, *s2, *s3, *s4; const char *s1, *s2, *s3, *s4;
assert(bus); assert(bus);
@ -859,29 +853,29 @@ static void print_image_status_info(sd_bus *bus, ImageStatusInfo *i) {
i->read_only ? "read-only" : "writable", i->read_only ? "read-only" : "writable",
i->read_only ? ansi_normal() : ""); i->read_only ? ansi_normal() : "");
s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->crtime); s1 = FORMAT_TIMESTAMP_RELATIVE(i->crtime);
s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->crtime); s2 = FORMAT_TIMESTAMP(i->crtime);
if (s1 && s2) if (s1 && s2)
printf("\t Created: %s; %s\n", s2, s1); printf("\t Created: %s; %s\n", s2, s1);
else if (s2) else if (s2)
printf("\t Created: %s\n", s2); printf("\t Created: %s\n", s2);
s1 = format_timestamp_relative(ts_relative, sizeof(ts_relative), i->mtime); s1 = FORMAT_TIMESTAMP_RELATIVE(i->mtime);
s2 = format_timestamp(ts_absolute, sizeof(ts_absolute), i->mtime); s2 = FORMAT_TIMESTAMP(i->mtime);
if (s1 && s2) if (s1 && s2)
printf("\tModified: %s; %s\n", s2, s1); printf("\tModified: %s; %s\n", s2, s1);
else if (s2) else if (s2)
printf("\tModified: %s\n", s2); printf("\tModified: %s\n", s2);
s3 = format_bytes(bs, sizeof(bs), i->usage); s3 = FORMAT_BYTES(i->usage);
s4 = i->usage_exclusive != i->usage ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->usage_exclusive) : NULL; s4 = i->usage_exclusive != i->usage ? FORMAT_BYTES(i->usage_exclusive) : NULL;
if (s3 && s4) if (s3 && s4)
printf("\t Usage: %s (exclusive: %s)\n", s3, s4); printf("\t Usage: %s (exclusive: %s)\n", s3, s4);
else if (s3) else if (s3)
printf("\t Usage: %s\n", s3); printf("\t Usage: %s\n", s3);
s3 = format_bytes(bs, sizeof(bs), i->limit); s3 = FORMAT_BYTES(i->limit);
s4 = i->limit_exclusive != i->limit ? format_bytes(bs_exclusive, sizeof(bs_exclusive), i->limit_exclusive) : NULL; s4 = i->limit_exclusive != i->limit ? FORMAT_BYTES(i->limit_exclusive) : NULL;
if (s3 && s4) if (s3 && s4)
printf("\t Limit: %s (exclusive: %s)\n", s3, s4); printf("\t Limit: %s (exclusive: %s)\n", s3, s4);
else if (s3) else if (s3)
@ -940,16 +934,16 @@ typedef struct PoolStatusInfo {
} PoolStatusInfo; } PoolStatusInfo;
static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) { static void print_pool_status_info(sd_bus *bus, PoolStatusInfo *i) {
char bs[FORMAT_BYTES_MAX], *s; char *s;
if (i->path) if (i->path)
printf("\t Path: %s\n", i->path); printf("\t Path: %s\n", i->path);
s = format_bytes(bs, sizeof(bs), i->usage); s = FORMAT_BYTES(i->usage);
if (s) if (s)
printf("\t Usage: %s\n", s); printf("\t Usage: %s\n", s);
s = format_bytes(bs, sizeof(bs), i->limit); s = FORMAT_BYTES(i->limit);
if (s) if (s)
printf("\t Limit: %s\n", s); printf("\t Limit: %s\n", s);
} }
@ -2409,7 +2403,6 @@ static int clean_images(int argc, char *argv[], void *userdata) {
_cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL; _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
uint64_t usage, total = 0; uint64_t usage, total = 0;
char fb[FORMAT_BYTES_MAX];
sd_bus *bus = userdata; sd_bus *bus = userdata;
const char *name; const char *name;
unsigned c = 0; unsigned c = 0;
@ -2440,7 +2433,7 @@ static int clean_images(int argc, char *argv[], void *userdata) {
total = UINT64_MAX; total = UINT64_MAX;
} else { } else {
log_info("Removed image '%s'. Freed exclusive disk space: %s", log_info("Removed image '%s'. Freed exclusive disk space: %s",
name, format_bytes(fb, sizeof(fb), usage)); name, FORMAT_BYTES(usage));
if (total != UINT64_MAX) if (total != UINT64_MAX)
total += usage; total += usage;
} }
@ -2455,7 +2448,7 @@ static int clean_images(int argc, char *argv[], void *userdata) {
log_info("Removed %u images in total.", c); log_info("Removed %u images in total.", c);
else else
log_info("Removed %u images in total. Total freed exclusive disk space: %s.", log_info("Removed %u images in total. Total freed exclusive disk space: %s.",
c, format_bytes(fb, sizeof(fb), total)); c, FORMAT_BYTES(total));
return 0; return 0;
} }

View File

@ -2121,16 +2121,14 @@ static int link_status_one(
} }
if (info->has_bitrates) { if (info->has_bitrates) {
char tx[FORMAT_BYTES_MAX], rx[FORMAT_BYTES_MAX];
r = table_add_many(table, r = table_add_many(table,
TABLE_EMPTY, TABLE_EMPTY,
TABLE_STRING, "Bit Rate (Tx/Rx):"); TABLE_STRING, "Bit Rate (Tx/Rx):");
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
r = table_add_cell_stringf(table, NULL, "%sbps/%sbps", r = table_add_cell_stringf(table, NULL, "%sbps/%sbps",
format_bytes_full(tx, sizeof tx, info->tx_bitrate, 0), FORMAT_BYTES_FULL(info->tx_bitrate, 0),
format_bytes_full(rx, sizeof rx, info->rx_bitrate, 0)); FORMAT_BYTES_FULL(info->rx_bitrate, 0));
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
} }

View File

@ -622,7 +622,6 @@ int manager_has_address(Manager *manager, int family, const union in_addr_union
static void log_address_debug(const Address *address, const char *str, const Link *link) { static void log_address_debug(const Address *address, const char *str, const Link *link) {
_cleanup_free_ char *addr = NULL, *peer = NULL, *flags_str = NULL; _cleanup_free_ char *addr = NULL, *peer = NULL, *flags_str = NULL;
char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX];
const char *valid_str = NULL, *preferred_str = NULL; const char *valid_str = NULL, *preferred_str = NULL;
bool has_peer; bool has_peer;
@ -639,14 +638,10 @@ static void log_address_debug(const Address *address, const char *str, const Lin
(void) in_addr_to_string(address->family, &address->in_addr_peer, &peer); (void) in_addr_to_string(address->family, &address->in_addr_peer, &peer);
if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME) if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME)
valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, valid_str = FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC);
address->cinfo.ifa_valid * USEC_PER_SEC,
USEC_PER_SEC);
if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME)
preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX, preferred_str = FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC);
address->cinfo.ifa_prefered * USEC_PER_SEC,
USEC_PER_SEC);
(void) address_flags_to_string_alloc(address->flags, address->family, &flags_str); (void) address_flags_to_string_alloc(address->flags, address->family, &flags_str);

View File

@ -107,7 +107,6 @@ int can_set_netlink_message(Link *link, sd_netlink_message *m) {
} }
if (link->network->can_restart_us > 0) { if (link->network->can_restart_us > 0) {
char time_string[FORMAT_TIMESPAN_MAX];
uint64_t restart_ms; uint64_t restart_ms;
if (link->network->can_restart_us == USEC_INFINITY) if (link->network->can_restart_us == USEC_INFINITY)
@ -115,12 +114,11 @@ int can_set_netlink_message(Link *link, sd_netlink_message *m) {
else else
restart_ms = DIV_ROUND_UP(link->network->can_restart_us, USEC_PER_MSEC); restart_ms = DIV_ROUND_UP(link->network->can_restart_us, USEC_PER_MSEC);
format_timespan(time_string, FORMAT_TIMESPAN_MAX, restart_ms * 1000, MSEC_PER_SEC);
if (restart_ms > UINT32_MAX) if (restart_ms > UINT32_MAX)
return log_link_debug_errno(link, SYNTHETIC_ERRNO(ERANGE), "restart timeout (%s) too big.", time_string); return log_link_debug_errno(link, SYNTHETIC_ERRNO(ERANGE), "restart timeout (%s) too big.",
FORMAT_TIMESPAN(restart_ms * 1000, MSEC_PER_SEC));
log_link_debug(link, "Setting restart = %s", time_string); log_link_debug(link, "Setting restart = %s", FORMAT_TIMESPAN(restart_ms * 1000, MSEC_PER_SEC));
r = sd_netlink_message_append_u32(m, IFLA_CAN_RESTART_MS, restart_ms); r = sd_netlink_message_append_u32(m, IFLA_CAN_RESTART_MS, restart_ms);
if (r < 0) if (r < 0)

View File

@ -29,10 +29,8 @@ int manager_parse_config_file(Manager *m) {
return r; return r;
if (m->use_speed_meter && m->speed_meter_interval_usec < SPEED_METER_MINIMUM_TIME_INTERVAL) { if (m->use_speed_meter && m->speed_meter_interval_usec < SPEED_METER_MINIMUM_TIME_INTERVAL) {
char buf[FORMAT_TIMESPAN_MAX];
log_warning("SpeedMeterIntervalSec= is too small, using %s.", log_warning("SpeedMeterIntervalSec= is too small, using %s.",
format_timespan(buf, sizeof buf, SPEED_METER_MINIMUM_TIME_INTERVAL, USEC_PER_SEC)); FORMAT_TIMESPAN(SPEED_METER_MINIMUM_TIME_INTERVAL, USEC_PER_SEC));
m->speed_meter_interval_usec = SPEED_METER_MINIMUM_TIME_INTERVAL; m->speed_meter_interval_usec = SPEED_METER_MINIMUM_TIME_INTERVAL;
} }

View File

@ -373,7 +373,6 @@ static int dhcp6_pd_address_handler(sd_netlink *rtnl, sd_netlink_message *m, Lin
} }
static void log_dhcp6_pd_address(Link *link, const Address *address) { static void log_dhcp6_pd_address(Link *link, const Address *address) {
char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX];
const char *valid_str = NULL, *preferred_str = NULL; const char *valid_str = NULL, *preferred_str = NULL;
_cleanup_free_ char *buffer = NULL; _cleanup_free_ char *buffer = NULL;
int log_level; int log_level;
@ -388,13 +387,9 @@ static void log_dhcp6_pd_address(Link *link, const Address *address) {
(void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer); (void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer);
if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME) if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME)
valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, valid_str = FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC);
address->cinfo.ifa_valid * USEC_PER_SEC,
USEC_PER_SEC);
if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME)
preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX, preferred_str = FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC);
address->cinfo.ifa_prefered * USEC_PER_SEC,
USEC_PER_SEC);
log_link_full(link, log_level, "DHCPv6-PD address %s (valid %s%s, preferred %s%s)", log_link_full(link, log_level, "DHCPv6-PD address %s (valid %s%s, preferred %s%s)",
strna(buffer), strna(buffer),
@ -1061,8 +1056,6 @@ static int dhcp6_address_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *
} }
static void log_dhcp6_address(Link *link, const Address *address, char **ret) { static void log_dhcp6_address(Link *link, const Address *address, char **ret) {
char valid_buf[FORMAT_TIMESPAN_MAX], preferred_buf[FORMAT_TIMESPAN_MAX];
const char *valid_str = NULL, *preferred_str = NULL;
_cleanup_free_ char *buffer = NULL; _cleanup_free_ char *buffer = NULL;
bool by_ndisc = false; bool by_ndisc = false;
Address *existing; Address *existing;
@ -1074,14 +1067,11 @@ static void log_dhcp6_address(Link *link, const Address *address, char **ret) {
assert(address->family == AF_INET6); assert(address->family == AF_INET6);
(void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer); (void) in6_addr_prefix_to_string(&address->in_addr.in6, address->prefixlen, &buffer);
if (address->cinfo.ifa_valid != CACHE_INFO_INFINITY_LIFE_TIME)
valid_str = format_timespan(valid_buf, FORMAT_TIMESPAN_MAX, const char *valid_str = address->cinfo.ifa_valid == CACHE_INFO_INFINITY_LIFE_TIME ? NULL :
address->cinfo.ifa_valid * USEC_PER_SEC, FORMAT_TIMESPAN(address->cinfo.ifa_valid * USEC_PER_SEC, USEC_PER_SEC);
USEC_PER_SEC); const char *preferred_str = address->cinfo.ifa_prefered == CACHE_INFO_INFINITY_LIFE_TIME ? NULL :
if (address->cinfo.ifa_prefered != CACHE_INFO_INFINITY_LIFE_TIME) FORMAT_TIMESPAN(address->cinfo.ifa_prefered * USEC_PER_SEC, USEC_PER_SEC);
preferred_str = format_timespan(preferred_buf, FORMAT_TIMESPAN_MAX,
address->cinfo.ifa_prefered * USEC_PER_SEC,
USEC_PER_SEC);
r = address_get(link, address, &existing); r = address_get(link, address, &existing);
if (r < 0) { if (r < 0) {

View File

@ -15,6 +15,7 @@
#include "networkd-route.h" #include "networkd-route.h"
#include "parse-util.h" #include "parse-util.h"
#include "set.h" #include "set.h"
#include "stdio-util.h"
#include "string-util.h" #include "string-util.h"
NextHop *nexthop_free(NextHop *nexthop) { NextHop *nexthop_free(NextHop *nexthop) {
@ -368,7 +369,7 @@ set_manager:
} }
static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *str, const Link *link) { static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *str, const Link *link) {
_cleanup_free_ char *gw = NULL, *new_id = NULL, *group = NULL; _cleanup_free_ char *gw = NULL, *group = NULL;
struct nexthop_grp *nhg; struct nexthop_grp *nhg;
assert(nexthop); assert(nexthop);
@ -379,8 +380,9 @@ static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *s
if (!DEBUG_LOGGING) if (!DEBUG_LOGGING)
return; return;
char new_id[STRLEN("") + DECIMAL_STR_MAX(uint32_t)] = "";
if (nexthop->id != id) if (nexthop->id != id)
(void) asprintf(&new_id, "→%"PRIu32, id); xsprintf(new_id, "→%"PRIu32, id);
(void) in_addr_to_string(nexthop->family, &nexthop->gw, &gw); (void) in_addr_to_string(nexthop->family, &nexthop->gw, &gw);
@ -388,7 +390,7 @@ static void log_nexthop_debug(const NextHop *nexthop, uint32_t id, const char *s
(void) strextendf_with_separator(&group, ",", "%"PRIu32":%"PRIu32, nhg->id, nhg->weight+1); (void) strextendf_with_separator(&group, ",", "%"PRIu32":%"PRIu32, nhg->id, nhg->weight+1);
log_link_debug(link, "%s nexthop: id: %"PRIu32"%s, gw: %s, blackhole: %s, group: %s", log_link_debug(link, "%s nexthop: id: %"PRIu32"%s, gw: %s, blackhole: %s, group: %s",
str, nexthop->id, strempty(new_id), strna(gw), yes_no(nexthop->blackhole), strna(group)); str, nexthop->id, new_id, strna(gw), yes_no(nexthop->blackhole), strna(group));
} }
static int link_nexthop_remove_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) { static int link_nexthop_remove_handler(sd_netlink *rtnl, sd_netlink_message *m, Link *link) {

View File

@ -110,6 +110,7 @@ int manager_get_route_table_from_string(const Manager *m, const char *s, uint32_
int manager_get_route_table_to_string(const Manager *m, uint32_t table, char **ret) { int manager_get_route_table_to_string(const Manager *m, uint32_t table, char **ret) {
_cleanup_free_ char *str = NULL; _cleanup_free_ char *str = NULL;
const char *s; const char *s;
int r;
assert(m); assert(m);
assert(ret); assert(ret);
@ -121,17 +122,13 @@ int manager_get_route_table_to_string(const Manager *m, uint32_t table, char **r
if (!s) if (!s)
s = hashmap_get(m->route_table_names_by_number, UINT32_TO_PTR(table)); s = hashmap_get(m->route_table_names_by_number, UINT32_TO_PTR(table));
if (s) { if (s)
/* Currently, this is only used in debugging logs. To not confuse any bug /* Currently, this is only used in debugging logs. To not confuse any bug
* reports, let's include the table number. */ * reports, let's include the table number. */
if (asprintf(&str, "%s(%" PRIu32 ")", s, table) < 0) r = asprintf(&str, "%s(%" PRIu32 ")", s, table);
return -ENOMEM; else
r = asprintf(&str, "%" PRIu32, table);
*ret = TAKE_PTR(str); if (r < 0)
return 0;
}
if (asprintf(&str, "%" PRIu32, table) < 0)
return -ENOMEM; return -ENOMEM;
*ret = TAKE_PTR(str); *ret = TAKE_PTR(str);

View File

@ -442,7 +442,6 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t
OomdCGroupContext *t; OomdCGroupContext *t;
SET_FOREACH(t, targets) { SET_FOREACH(t, targets) {
_cleanup_free_ char *selected = NULL; _cleanup_free_ char *selected = NULL;
char ts[FORMAT_TIMESPAN_MAX];
/* Check if there was reclaim activity in the given interval. The concern is the following case: /* Check if there was reclaim activity in the given interval. The concern is the following case:
* Pressure climbed, a lot of high-frequency pages were reclaimed, and we killed the offending * Pressure climbed, a lot of high-frequency pages were reclaimed, and we killed the offending
@ -456,9 +455,7 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t
t->path, t->path,
LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10), LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10),
LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit), LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit),
format_timespan(ts, sizeof ts, FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC));
m->default_mem_pressure_duration_usec,
USEC_PER_SEC));
r = update_monitored_cgroup_contexts_candidates( r = update_monitored_cgroup_contexts_candidates(
m->monitored_mem_pressure_cgroup_contexts, &m->monitored_mem_pressure_cgroup_contexts_candidates); m->monitored_mem_pressure_cgroup_contexts, &m->monitored_mem_pressure_cgroup_contexts_candidates);
@ -483,9 +480,7 @@ static int monitor_memory_pressure_contexts_handler(sd_event_source *s, uint64_t
selected, t->path, selected, t->path,
LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10), LOAD_INT(t->memory_pressure.avg10), LOAD_FRAC(t->memory_pressure.avg10),
LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit), LOAD_INT(t->mem_pressure_limit), LOAD_FRAC(t->mem_pressure_limit),
format_timespan(ts, sizeof ts, FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC));
m->default_mem_pressure_duration_usec,
USEC_PER_SEC));
return 0; return 0;
} }
} }
@ -707,7 +702,6 @@ int manager_start(
int manager_get_dump_string(Manager *m, char **ret) { int manager_get_dump_string(Manager *m, char **ret) {
_cleanup_free_ char *dump = NULL; _cleanup_free_ char *dump = NULL;
_cleanup_fclose_ FILE *f = NULL; _cleanup_fclose_ FILE *f = NULL;
char buf[FORMAT_TIMESPAN_MAX];
OomdCGroupContext *c; OomdCGroupContext *c;
size_t size; size_t size;
char *key; char *key;
@ -729,7 +723,7 @@ int manager_get_dump_string(Manager *m, char **ret) {
yes_no(m->dry_run), yes_no(m->dry_run),
PERMYRIAD_AS_PERCENT_FORMAT_VAL(m->swap_used_limit_permyriad), PERMYRIAD_AS_PERCENT_FORMAT_VAL(m->swap_used_limit_permyriad),
LOAD_INT(m->default_mem_pressure_limit), LOAD_FRAC(m->default_mem_pressure_limit), LOAD_INT(m->default_mem_pressure_limit), LOAD_FRAC(m->default_mem_pressure_limit),
format_timespan(buf, sizeof(buf), m->default_mem_pressure_duration_usec, USEC_PER_SEC)); FORMAT_TIMESPAN(m->default_mem_pressure_duration_usec, USEC_PER_SEC));
oomd_dump_system_context(&m->system_context, f, "\t"); oomd_dump_system_context(&m->system_context, f, "\t");
fprintf(f, "Swap Monitored CGroups:\n"); fprintf(f, "Swap Monitored CGroups:\n");

View File

@ -503,8 +503,6 @@ void oomd_update_cgroup_contexts_between_hashmaps(Hashmap *old_h, Hashmap *curr_
} }
void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) { void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) {
char swap[FORMAT_BYTES_MAX];
assert(ctx); assert(ctx);
assert(f); assert(f);
@ -513,7 +511,7 @@ void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const
"%sPath: %s\n" "%sPath: %s\n"
"%s\tSwap Usage: %s\n", "%s\tSwap Usage: %s\n",
strempty(prefix), ctx->path, strempty(prefix), ctx->path,
strempty(prefix), format_bytes(swap, sizeof(swap), ctx->swap_usage)); strempty(prefix), FORMAT_BYTES(ctx->swap_usage));
else else
fprintf(f, fprintf(f,
"%sPath: %s\n" "%sPath: %s\n"
@ -523,9 +521,6 @@ void oomd_dump_swap_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const
} }
void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) { void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE *f, const char *prefix) {
char tbuf[FORMAT_TIMESPAN_MAX], mem_use[FORMAT_BYTES_MAX];
char mem_min[FORMAT_BYTES_MAX], mem_low[FORMAT_BYTES_MAX];
assert(ctx); assert(ctx);
assert(f); assert(f);
@ -540,8 +535,8 @@ void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE
LOAD_INT(ctx->memory_pressure.avg10), LOAD_FRAC(ctx->memory_pressure.avg10), LOAD_INT(ctx->memory_pressure.avg10), LOAD_FRAC(ctx->memory_pressure.avg10),
LOAD_INT(ctx->memory_pressure.avg60), LOAD_FRAC(ctx->memory_pressure.avg60), LOAD_INT(ctx->memory_pressure.avg60), LOAD_FRAC(ctx->memory_pressure.avg60),
LOAD_INT(ctx->memory_pressure.avg300), LOAD_FRAC(ctx->memory_pressure.avg300), LOAD_INT(ctx->memory_pressure.avg300), LOAD_FRAC(ctx->memory_pressure.avg300),
format_timespan(tbuf, sizeof(tbuf), ctx->memory_pressure.total, USEC_PER_SEC), FORMAT_TIMESPAN(ctx->memory_pressure.total, USEC_PER_SEC),
strempty(prefix), format_bytes(mem_use, sizeof(mem_use), ctx->current_memory_usage)); strempty(prefix), FORMAT_BYTES(ctx->current_memory_usage));
if (!empty_or_root(ctx->path)) if (!empty_or_root(ctx->path))
fprintf(f, fprintf(f,
@ -549,16 +544,13 @@ void oomd_dump_memory_pressure_cgroup_context(const OomdCGroupContext *ctx, FILE
"%s\tMemory Low: %s\n" "%s\tMemory Low: %s\n"
"%s\tPgscan: %" PRIu64 "\n" "%s\tPgscan: %" PRIu64 "\n"
"%s\tLast Pgscan: %" PRIu64 "\n", "%s\tLast Pgscan: %" PRIu64 "\n",
strempty(prefix), format_bytes_cgroup_protection(mem_min, sizeof(mem_min), ctx->memory_min), strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_min),
strempty(prefix), format_bytes_cgroup_protection(mem_low, sizeof(mem_low), ctx->memory_low), strempty(prefix), FORMAT_BYTES_CGROUP_PROTECTION(ctx->memory_low),
strempty(prefix), ctx->pgscan, strempty(prefix), ctx->pgscan,
strempty(prefix), ctx->last_pgscan); strempty(prefix), ctx->last_pgscan);
} }
void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char *prefix) { void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char *prefix) {
char mem_used[FORMAT_BYTES_MAX], mem_total[FORMAT_BYTES_MAX];
char swap_used[FORMAT_BYTES_MAX], swap_total[FORMAT_BYTES_MAX];
assert(ctx); assert(ctx);
assert(f); assert(f);
@ -566,9 +558,9 @@ void oomd_dump_system_context(const OomdSystemContext *ctx, FILE *f, const char
"%sMemory: Used: %s Total: %s\n" "%sMemory: Used: %s Total: %s\n"
"%sSwap: Used: %s Total: %s\n", "%sSwap: Used: %s Total: %s\n",
strempty(prefix), strempty(prefix),
format_bytes(mem_used, sizeof(mem_used), ctx->mem_used), FORMAT_BYTES(ctx->mem_used),
format_bytes(mem_total, sizeof(mem_total), ctx->mem_total), FORMAT_BYTES(ctx->mem_total),
strempty(prefix), strempty(prefix),
format_bytes(swap_used, sizeof(swap_used), ctx->swap_used), FORMAT_BYTES(ctx->swap_used),
format_bytes(swap_total, sizeof(swap_total), ctx->swap_total)); FORMAT_BYTES(ctx->swap_total));
} }

View File

@ -197,7 +197,6 @@ static int run(int argc, char *argv[]) {
_cleanup_close_ int mountfd = -1, devfd = -1; _cleanup_close_ int mountfd = -1, devfd = -1;
_cleanup_free_ char *devpath = NULL; _cleanup_free_ char *devpath = NULL;
uint64_t size, newsize; uint64_t size, newsize;
char fb[FORMAT_BYTES_MAX];
dev_t devno; dev_t devno;
int r; int r;
@ -248,11 +247,11 @@ static int run(int argc, char *argv[]) {
if (newsize == size) if (newsize == size)
log_info("Successfully resized \"%s\" to %s bytes.", log_info("Successfully resized \"%s\" to %s bytes.",
arg_target, arg_target,
format_bytes(fb, sizeof fb, newsize)); FORMAT_BYTES(newsize));
else else
log_info("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).", log_info("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
arg_target, arg_target,
format_bytes(fb, sizeof fb, newsize), FORMAT_BYTES(newsize),
size - newsize); size - newsize);
return 0; return 0;
} }

View File

@ -1932,29 +1932,24 @@ static void context_unload_partition_table(Context *context) {
} }
static int format_size_change(uint64_t from, uint64_t to, char **ret) { static int format_size_change(uint64_t from, uint64_t to, char **ret) {
char format_buffer1[FORMAT_BYTES_MAX], format_buffer2[FORMAT_BYTES_MAX], *buf; char *t;
if (from != UINT64_MAX)
format_bytes(format_buffer1, sizeof(format_buffer1), from);
if (to != UINT64_MAX)
format_bytes(format_buffer2, sizeof(format_buffer2), to);
if (from != UINT64_MAX) { if (from != UINT64_MAX) {
if (from == to || to == UINT64_MAX) if (from == to || to == UINT64_MAX)
buf = strdup(format_buffer1); t = strdup(FORMAT_BYTES(from));
else else
buf = strjoin(format_buffer1, " ", special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2); t = strjoin(FORMAT_BYTES(from), " ", special_glyph(SPECIAL_GLYPH_ARROW), " ", FORMAT_BYTES(to));
} else if (to != UINT64_MAX) } else if (to != UINT64_MAX)
buf = strjoin(special_glyph(SPECIAL_GLYPH_ARROW), " ", format_buffer2); t = strjoin(special_glyph(SPECIAL_GLYPH_ARROW), " ", FORMAT_BYTES(to));
else { else {
*ret = NULL; *ret = NULL;
return 0; return 0;
} }
if (!buf) if (!t)
return log_oom(); return log_oom();
*ret = TAKE_PTR(buf); *ret = t;
return 1; return 1;
} }
@ -2051,11 +2046,10 @@ static int context_dump_partitions(Context *context, const char *node) {
} }
if ((arg_json_format_flags & JSON_FORMAT_OFF) && (sum_padding > 0 || sum_size > 0)) { if ((arg_json_format_flags & JSON_FORMAT_OFF) && (sum_padding > 0 || sum_size > 0)) {
char s[FORMAT_BYTES_MAX];
const char *a, *b; const char *a, *b;
a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_size)); a = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_size));
b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", format_bytes(s, sizeof(s), sum_padding)); b = strjoina(special_glyph(SPECIAL_GLYPH_SIGMA), " = ", FORMAT_BYTES(sum_padding));
r = table_add_many( r = table_add_many(
t, t,
@ -2734,7 +2728,6 @@ static int context_copy_blocks(Context *context) {
_cleanup_(loop_device_unrefp) LoopDevice *d = NULL; _cleanup_(loop_device_unrefp) LoopDevice *d = NULL;
_cleanup_free_ char *encrypted = NULL; _cleanup_free_ char *encrypted = NULL;
_cleanup_close_ int encrypted_dev_fd = -1; _cleanup_close_ int encrypted_dev_fd = -1;
char buf[FORMAT_BYTES_MAX];
int target_fd; int target_fd;
if (p->copy_blocks_fd < 0) if (p->copy_blocks_fd < 0)
@ -2777,7 +2770,8 @@ static int context_copy_blocks(Context *context) {
target_fd = whole_fd; target_fd = whole_fd;
} }
log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64 ".", p->copy_blocks_path, format_bytes(buf, sizeof(buf), p->copy_blocks_size), p->partno); log_info("Copying in '%s' (%s) on block level into future partition %" PRIu64 ".",
p->copy_blocks_path, FORMAT_BYTES(p->copy_blocks_size), p->partno);
r = copy_bytes_full(p->copy_blocks_fd, target_fd, p->copy_blocks_size, 0, NULL, NULL, NULL, NULL); r = copy_bytes_full(p->copy_blocks_fd, target_fd, p->copy_blocks_size, 0, NULL, NULL, NULL, NULL);
if (r < 0) if (r < 0)
@ -4637,7 +4631,6 @@ static int resize_backing_fd(
const char *backing_file, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */ const char *backing_file, /* If the above refers to a loopback device, the backing regular file for that, which we can grow */
LoopDevice *loop_device) { LoopDevice *loop_device) {
char buf1[FORMAT_BYTES_MAX], buf2[FORMAT_BYTES_MAX];
_cleanup_close_ int writable_fd = -1; _cleanup_close_ int writable_fd = -1;
uint64_t current_size; uint64_t current_size;
struct stat st; struct stat st;
@ -4678,11 +4671,9 @@ static int resize_backing_fd(
current_size = st.st_size; current_size = st.st_size;
} }
assert_se(format_bytes(buf1, sizeof(buf1), current_size));
assert_se(format_bytes(buf2, sizeof(buf2), arg_size));
if (current_size >= arg_size) { if (current_size >= arg_size) {
log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)", node, buf1, buf2); log_info("File '%s' already is of requested size or larger, not growing. (%s >= %s)",
node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
return 0; return 0;
} }
@ -4705,7 +4696,8 @@ static int resize_backing_fd(
if ((uint64_t) st.st_size != current_size) if ((uint64_t) st.st_size != current_size)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Size of backing file '%s' of loopback block device '%s' don't match, refusing.", node, backing_file); "Size of backing file '%s' of loopback block device '%s' don't match, refusing.",
node, backing_file);
} else { } else {
assert(S_ISREG(st.st_mode)); assert(S_ISREG(st.st_mode));
assert(!backing_file); assert(!backing_file);
@ -4723,15 +4715,16 @@ static int resize_backing_fd(
if (fallocate(writable_fd, 0, 0, arg_size) < 0) { if (fallocate(writable_fd, 0, 0, arg_size) < 0) {
if (!ERRNO_IS_NOT_SUPPORTED(errno)) if (!ERRNO_IS_NOT_SUPPORTED(errno))
return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m", return log_error_errno(errno, "Failed to grow '%s' from %s to %s by allocation: %m",
node, buf1, buf2); node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
/* Fallback to truncation, if fallocate() is not supported. */ /* Fallback to truncation, if fallocate() is not supported. */
log_debug("Backing file system does not support fallocate(), falling back to ftruncate()."); log_debug("Backing file system does not support fallocate(), falling back to ftruncate().");
} else { } else {
if (current_size == 0) /* Likely regular file just created by us */ if (current_size == 0) /* Likely regular file just created by us */
log_info("Allocated %s for '%s'.", buf2, node); log_info("Allocated %s for '%s'.", FORMAT_BYTES(arg_size), node);
else else
log_info("File '%s' grown from %s to %s by allocation.", node, buf1, buf2); log_info("File '%s' grown from %s to %s by allocation.",
node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
goto done; goto done;
} }
@ -4739,12 +4732,13 @@ static int resize_backing_fd(
if (ftruncate(writable_fd, arg_size) < 0) if (ftruncate(writable_fd, arg_size) < 0)
return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m", return log_error_errno(errno, "Failed to grow '%s' from %s to %s by truncation: %m",
node, buf1, buf2); node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
if (current_size == 0) /* Likely regular file just created by us */ if (current_size == 0) /* Likely regular file just created by us */
log_info("Sized '%s' to %s.", node, buf2); log_info("Sized '%s' to %s.", node, FORMAT_BYTES(arg_size));
else else
log_info("File '%s' grown from %s to %s by truncation.", node, buf1, buf2); log_info("File '%s' grown from %s to %s by truncation.",
node, FORMAT_BYTES(current_size), FORMAT_BYTES(arg_size));
done: done:
r = resize_pt(writable_fd); r = resize_pt(writable_fd);
@ -4762,7 +4756,6 @@ done:
static int determine_auto_size(Context *c) { static int determine_auto_size(Context *c) {
uint64_t sum = round_up_size(GPT_METADATA_SIZE, 4096); uint64_t sum = round_up_size(GPT_METADATA_SIZE, 4096);
char buf[FORMAT_BYTES_MAX];
Partition *p; Partition *p;
assert_se(c); assert_se(c);
@ -4780,13 +4773,14 @@ static int determine_auto_size(Context *c) {
sum += m; sum += m;
} }
assert_se(format_bytes(buf, sizeof(buf), sum)); if (c->total != UINT64_MAX)
if (c->total != UINT64_MAX) { /* Image already allocated? Then show its size */ /* Image already allocated? Then show its size. */
char buf2[FORMAT_BYTES_MAX]; log_info("Automatically determined minimal disk image size as %s, current image size is %s.",
assert_se(format_bytes(buf2, sizeof(buf2), c->total)); FORMAT_BYTES(sum), FORMAT_BYTES(c->total));
log_info("Automatically determined minimal disk image size as %s, current image size is %s.", buf, buf2); else
} else /* If the image is being created right now, then it has no previous size, suppress any comment about it hence */ /* If the image is being created right now, then it has no previous size, suppress any comment about it hence. */
log_info("Automatically determined minimal disk image size as %s.", buf); log_info("Automatically determined minimal disk image size as %s.",
FORMAT_BYTES(sum));
arg_size = sum; arg_size = sum;
return 0; return 0;
@ -4962,11 +4956,9 @@ static int run(int argc, char *argv[]) {
break; /* Success! */ break; /* Success! */
if (!context_drop_one_priority(context)) { if (!context_drop_one_priority(context)) {
char buf[FORMAT_BYTES_MAX];
r = log_error_errno(SYNTHETIC_ERRNO(ENOSPC), r = log_error_errno(SYNTHETIC_ERRNO(ENOSPC),
"Can't fit requested partitions into available free space (%s), refusing.", "Can't fit requested partitions into available free space (%s), refusing.",
format_bytes(buf, sizeof(buf), largest_free_area)); FORMAT_BYTES(largest_free_area));
determine_auto_size(context); determine_auto_size(context);
return r; return r;
} }

View File

@ -150,8 +150,6 @@ int ifname_resolvconf_mangle(const char *s) {
} }
static void print_source(uint64_t flags, usec_t rtt) { static void print_source(uint64_t flags, usec_t rtt) {
char rtt_str[FORMAT_TIMESTAMP_MAX];
if (!arg_legend) if (!arg_legend)
return; return;
@ -167,11 +165,10 @@ static void print_source(uint64_t flags, usec_t rtt) {
flags & SD_RESOLVED_MDNS_IPV4 ? " mDNS/IPv4" : "", flags & SD_RESOLVED_MDNS_IPV4 ? " mDNS/IPv4" : "",
flags & SD_RESOLVED_MDNS_IPV6 ? " mDNS/IPv6" : ""); flags & SD_RESOLVED_MDNS_IPV6 ? " mDNS/IPv6" : "");
assert_se(format_timespan(rtt_str, sizeof(rtt_str), rtt, 100));
printf(" in %s.%s\n" printf(" in %s.%s\n"
"%s-- Data is authenticated: %s; Data was acquired via local or encrypted transport: %s%s\n", "%s-- Data is authenticated: %s; Data was acquired via local or encrypted transport: %s%s\n",
rtt_str, ansi_normal(), FORMAT_TIMESPAN(rtt, 100),
ansi_normal(),
ansi_grey(), ansi_grey(),
yes_no(flags & SD_RESOLVED_AUTHENTICATED), yes_no(flags & SD_RESOLVED_AUTHENTICATED),
yes_no(flags & SD_RESOLVED_CONFIDENTIAL), yes_no(flags & SD_RESOLVED_CONFIDENTIAL),

View File

@ -1322,34 +1322,25 @@ static int start_transient_service(
if (timestamp_is_set(c.inactive_enter_usec) && if (timestamp_is_set(c.inactive_enter_usec) &&
timestamp_is_set(c.inactive_exit_usec) && timestamp_is_set(c.inactive_exit_usec) &&
c.inactive_enter_usec > c.inactive_exit_usec) { c.inactive_enter_usec > c.inactive_exit_usec)
char ts[FORMAT_TIMESPAN_MAX];
log_info("Service runtime: %s", log_info("Service runtime: %s",
format_timespan(ts, sizeof ts, c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC)); FORMAT_TIMESPAN(c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC));
}
if (c.cpu_usage_nsec != NSEC_INFINITY) { if (c.cpu_usage_nsec != NSEC_INFINITY)
char ts[FORMAT_TIMESPAN_MAX];
log_info("CPU time consumed: %s", log_info("CPU time consumed: %s",
format_timespan(ts, sizeof ts, DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC)); FORMAT_TIMESPAN(DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC));
}
if (c.ip_ingress_bytes != UINT64_MAX) { if (c.ip_ingress_bytes != UINT64_MAX)
char bytes[FORMAT_BYTES_MAX]; log_info("IP traffic received: %s", FORMAT_BYTES(c.ip_ingress_bytes));
log_info("IP traffic received: %s", format_bytes(bytes, sizeof bytes, c.ip_ingress_bytes));
} if (c.ip_egress_bytes != UINT64_MAX)
if (c.ip_egress_bytes != UINT64_MAX) { log_info("IP traffic sent: %s", FORMAT_BYTES(c.ip_egress_bytes));
char bytes[FORMAT_BYTES_MAX];
log_info("IP traffic sent: %s", format_bytes(bytes, sizeof bytes, c.ip_egress_bytes)); if (c.io_read_bytes != UINT64_MAX)
} log_info("IO bytes read: %s", FORMAT_BYTES(c.io_read_bytes));
if (c.io_read_bytes != UINT64_MAX) {
char bytes[FORMAT_BYTES_MAX]; if (c.io_write_bytes != UINT64_MAX)
log_info("IO bytes read: %s", format_bytes(bytes, sizeof bytes, c.io_read_bytes)); log_info("IO bytes written: %s", FORMAT_BYTES(c.io_write_bytes));
}
if (c.io_write_bytes != UINT64_MAX) {
char bytes[FORMAT_BYTES_MAX];
log_info("IO bytes written: %s", format_bytes(bytes, sizeof bytes, c.io_write_bytes));
}
} }
/* Try to propagate the service's return value. But if the service defines /* Try to propagate the service's return value. But if the service defines

View File

@ -105,20 +105,14 @@ static int bus_print_property(const char *name, const char *expected_value, sd_b
* should it turn out to not be sufficient */ * should it turn out to not be sufficient */
if (endswith(name, "Timestamp") || if (endswith(name, "Timestamp") ||
STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec")) { STR_IN_SET(name, "NextElapseUSecRealtime", "LastTriggerUSec", "TimeUSec", "RTCTimeUSec"))
char timestamp[FORMAT_TIMESTAMP_MAX];
const char *t;
t = format_timestamp(timestamp, sizeof(timestamp), u); bus_print_property_value(name, expected_value, flags, FORMAT_TIMESTAMP(u));
bus_print_property_value(name, expected_value, flags, t);
} else if (strstr(name, "USec")) { else if (strstr(name, "USec"))
char timespan[FORMAT_TIMESPAN_MAX]; bus_print_property_value(name, expected_value, flags, FORMAT_TIMESPAN(u, 0));
(void) format_timespan(timespan, sizeof(timespan), u, 0); else if (streq(name, "CoredumpFilter"))
bus_print_property_value(name, expected_value, flags, timespan);
} else if (streq(name, "CoredumpFilter"))
bus_print_property_valuef(name, expected_value, flags, "0x%"PRIx64, u); bus_print_property_valuef(name, expected_value, flags, "0x%"PRIx64, u);
else if (streq(name, "RestrictNamespaces")) { else if (streq(name, "RestrictNamespaces")) {

View File

@ -506,12 +506,11 @@ static int device_wait_for_initialization_harder(
left = usec_sub_unsigned(deadline, start); left = usec_sub_unsigned(deadline, start);
if (DEBUG_LOGGING) { if (DEBUG_LOGGING) {
char buf[FORMAT_TIMESPAN_MAX];
const char *sn = NULL; const char *sn = NULL;
(void) sd_device_get_sysname(device, &sn); (void) sd_device_get_sysname(device, &sn);
log_device_debug(device, log_device_debug(device,
"Waiting for device '%s' to initialize for %s.", strna(sn), format_timespan(buf, sizeof(buf), left, 0)); "Waiting for device '%s' to initialize for %s.", strna(sn), FORMAT_TIMESPAN(left, 0));
} }
if (left != USEC_INFINITY) if (left != USEC_INFINITY)
@ -538,26 +537,22 @@ static int device_wait_for_initialization_harder(
r = device_wait_for_initialization(device, subsystem, local_deadline, ret); r = device_wait_for_initialization(device, subsystem, local_deadline, ret);
if (r >= 0 && DEBUG_LOGGING) { if (r >= 0 && DEBUG_LOGGING) {
char buf[FORMAT_TIMESPAN_MAX];
const char *sn = NULL; const char *sn = NULL;
(void) sd_device_get_sysname(device, &sn); (void) sd_device_get_sysname(device, &sn);
log_device_debug(device, log_device_debug(device,
"Successfully waited for device '%s' to initialize for %s.", "Successfully waited for device '%s' to initialize for %s.",
strna(sn), strna(sn),
format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
} }
if (r != -ETIMEDOUT || last_try) if (r != -ETIMEDOUT || last_try)
return r; return r;
if (DEBUG_LOGGING) { if (DEBUG_LOGGING)
char buf[FORMAT_TIMESPAN_MAX];
log_device_debug(device, log_device_debug(device,
"Device didn't initialize within %s, assuming lost event. Retriggering device.", "Device didn't initialize within %s, assuming lost event. Retriggering device.",
format_timespan(buf, sizeof(buf), usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0)); FORMAT_TIMESPAN(usec_sub_unsigned(now(CLOCK_MONOTONIC), start), 0));
}
r = sd_device_trigger(device, SD_DEVICE_CHANGE); r = sd_device_trigger(device, SD_DEVICE_CHANGE);
if (r < 0) if (r < 0)
@ -1497,7 +1492,6 @@ static int run_fsck(const char *node, const char *fstype) {
static int fs_grow(const char *node_path, const char *mount_path) { static int fs_grow(const char *node_path, const char *mount_path) {
_cleanup_close_ int mount_fd = -1, node_fd = -1; _cleanup_close_ int mount_fd = -1, node_fd = -1;
char fb[FORMAT_BYTES_MAX];
uint64_t size, newsize; uint64_t size, newsize;
int r; int r;
@ -1519,14 +1513,11 @@ static int fs_grow(const char *node_path, const char *mount_path) {
if (newsize == size) if (newsize == size)
log_debug("Successfully resized \"%s\" to %s bytes.", log_debug("Successfully resized \"%s\" to %s bytes.",
mount_path, mount_path, FORMAT_BYTES(newsize));
format_bytes(fb, sizeof fb, newsize));
else { else {
assert(newsize < size); assert(newsize < size);
log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).", log_debug("Successfully resized \"%s\" to %s bytes (%"PRIu64" bytes lost due to blocksize).",
mount_path, mount_path, FORMAT_BYTES(newsize), size - newsize);
format_bytes(fb, sizeof fb, newsize),
size - newsize);
} }
return 0; return 0;

View File

@ -1441,7 +1441,7 @@ static const char *table_data_format(Table *t, TableData *d, bool avoid_uppercas
_cleanup_free_ char *p = NULL; _cleanup_free_ char *p = NULL;
char *ret; char *ret;
p = new(char, FORMAT_TIMESTAMP_MAX); p = new(char, d->type == TABLE_TIMESTAMP_RELATIVE ? FORMAT_TIMESTAMP_RELATIVE_MAX : FORMAT_TIMESTAMP_MAX);
if (!p) if (!p)
return NULL; return NULL;
@ -1450,7 +1450,7 @@ static const char *table_data_format(Table *t, TableData *d, bool avoid_uppercas
else if (d->type == TABLE_TIMESTAMP_UTC) else if (d->type == TABLE_TIMESTAMP_UTC)
ret = format_timestamp_style(p, FORMAT_TIMESTAMP_MAX, d->timestamp, TIMESTAMP_UTC); ret = format_timestamp_style(p, FORMAT_TIMESTAMP_MAX, d->timestamp, TIMESTAMP_UTC);
else else
ret = format_timestamp_relative(p, FORMAT_TIMESTAMP_MAX, d->timestamp); ret = format_timestamp_relative(p, FORMAT_TIMESTAMP_RELATIVE_MAX, d->timestamp);
if (!ret) if (!ret)
return "n/a"; return "n/a";

View File

@ -17,6 +17,7 @@
#include "parse-util.h" #include "parse-util.h"
#include "process-util.h" #include "process-util.h"
#include "set.h" #include "set.h"
#include "stdio-util.h"
#include "string-util.h" #include "string-util.h"
#include "terminal-util.h" #include "terminal-util.h"
#include "util.h" #include "util.h"
@ -83,14 +84,13 @@ static void log_children_no_yet_killed(Set *pids) {
SET_FOREACH(p, pids) { SET_FOREACH(p, pids) {
_cleanup_free_ char *s = NULL; _cleanup_free_ char *s = NULL;
char fallback[DECIMAL_STR_MAX(pid_t)];
if (get_process_comm(PTR_TO_PID(p), &s) < 0) if (get_process_comm(PTR_TO_PID(p), &s) < 0)
(void) asprintf(&s, PID_FMT, PTR_TO_PID(p)); xsprintf(fallback, PID_FMT, PTR_TO_PID(p));
if (!strextend(&lst_child, ", ", s)) { if (!strextend(&lst_child, ", ", s ?: fallback))
log_oom(); return (void) log_oom();
return;
}
} }
if (isempty(lst_child)) if (isempty(lst_child))

View File

@ -579,10 +579,9 @@ static int output_short(
} }
} }
if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len)) { if (!(flags & OUTPUT_SHOW_ALL) && !utf8_is_printable(message, message_len))
char bytes[FORMAT_BYTES_MAX]; fprintf(f, "[%s blob data]\n", FORMAT_BYTES(message_len));
fprintf(f, "[%s blob data]\n", format_bytes(bytes, sizeof(bytes), message_len)); else {
} else {
/* URLify config_file string in message, if the message starts with it. /* URLify config_file string in message, if the message starts with it.
* Skip URLification if the highlighted pattern overlaps. */ * Skip URLification if the highlighted pattern overlaps. */
@ -726,16 +725,13 @@ static int output_verbose(
p, valuelen, p, valuelen,
NULL); NULL);
fputs(off, f); fputs(off, f);
} else { } else
char bytes[FORMAT_BYTES_MAX];
fprintf(f, " %s%.*s=[%s blob data]%s\n", fprintf(f, " %s%.*s=[%s blob data]%s\n",
on, on,
(int) (c - (const char*) data), (int) (c - (const char*) data),
(const char*) data, (const char*) data,
format_bytes(bytes, sizeof(bytes), length - (c - (const char *) data) - 1), FORMAT_BYTES(length - (c - (const char *) data) - 1),
off); off);
}
} }
if (r < 0) if (r < 0)

View File

@ -499,7 +499,6 @@ int mount_setup(bool loaded_policy, bool leave_propagation) {
* use the same label for all their files. */ * use the same label for all their files. */
if (loaded_policy) { if (loaded_policy) {
usec_t before_relabel, after_relabel; usec_t before_relabel, after_relabel;
char timespan[FORMAT_TIMESPAN_MAX];
const char *i; const char *i;
int n_extra; int n_extra;
@ -516,7 +515,7 @@ int mount_setup(bool loaded_policy, bool leave_propagation) {
log_info("Relabelled /dev, /dev/shm, /run, /sys/fs/cgroup%s in %s.", log_info("Relabelled /dev, /dev/shm, /run, /sys/fs/cgroup%s in %s.",
n_extra > 0 ? ", additional files" : "", n_extra > 0 ? ", additional files" : "",
format_timespan(timespan, sizeof(timespan), after_relabel - before_relabel, 0)); FORMAT_TIMESPAN(after_relabel - before_relabel, 0));
} }
#endif #endif

View File

@ -115,7 +115,6 @@ REENABLE_WARNING
static int open_label_db(void) { static int open_label_db(void) {
struct selabel_handle *hnd; struct selabel_handle *hnd;
usec_t before_timestamp, after_timestamp; usec_t before_timestamp, after_timestamp;
char timespan[FORMAT_TIMESPAN_MAX];
# if HAVE_GENERIC_MALLINFO # if HAVE_GENERIC_MALLINFO
generic_mallinfo before_mallinfo = generic_mallinfo_get(); generic_mallinfo before_mallinfo = generic_mallinfo_get();
@ -131,11 +130,11 @@ static int open_label_db(void) {
generic_mallinfo after_mallinfo = generic_mallinfo_get(); generic_mallinfo after_mallinfo = generic_mallinfo_get();
size_t l = LESS_BY((size_t) after_mallinfo.uordblks, (size_t) before_mallinfo.uordblks); size_t l = LESS_BY((size_t) after_mallinfo.uordblks, (size_t) before_mallinfo.uordblks);
log_debug("Successfully loaded SELinux database in %s, size on heap is %zuK.", log_debug("Successfully loaded SELinux database in %s, size on heap is %zuK.",
format_timespan(timespan, sizeof(timespan), after_timestamp - before_timestamp, 0), FORMAT_TIMESPAN(after_timestamp - before_timestamp, 0),
DIV_ROUND_UP(l, 1024)); DIV_ROUND_UP(l, 1024));
# else # else
log_debug("Successfully loaded SELinux database in %s.", log_debug("Successfully loaded SELinux database in %s.",
format_timespan(timespan, sizeof(timespan), after_timestamp - before_timestamp, 0)); FORMAT_TIMESPAN(after_timestamp - before_timestamp, 0));
# endif # endif
/* release memory after measurement */ /* release memory after measurement */

View File

@ -591,10 +591,8 @@ int tpm2_seal(
if (!hash) if (!hash)
return log_oom(); return log_oom();
if (DEBUG_LOGGING) { if (DEBUG_LOGGING)
char buf[FORMAT_TIMESPAN_MAX]; log_debug("Completed TPM2 key sealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
log_debug("Completed TPM2 key sealing in %s.", format_timespan(buf, sizeof(buf), now(CLOCK_MONOTONIC) - start, 1));
}
*ret_secret = TAKE_PTR(secret); *ret_secret = TAKE_PTR(secret);
*ret_secret_size = hmac_sensitive.sensitive.data.size; *ret_secret_size = hmac_sensitive.sensitive.data.size;
@ -726,10 +724,8 @@ int tpm2_unseal(
goto finish; goto finish;
} }
if (DEBUG_LOGGING) { if (DEBUG_LOGGING)
char buf[FORMAT_TIMESPAN_MAX]; log_debug("Completed TPM2 key unsealing in %s.", FORMAT_TIMESPAN(now(CLOCK_MONOTONIC) - start, 1));
log_debug("Completed TPM2 key unsealing in %s.", format_timespan(buf, sizeof(buf), now(CLOCK_MONOTONIC) - start, 1));
}
*ret_secret = TAKE_PTR(secret); *ret_secret = TAKE_PTR(secret);
*ret_secret_size = unsealed->size; *ret_secret_size = unsealed->size;

View File

@ -43,8 +43,7 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
printf(" Disposition: %s\n", user_disposition_to_string(user_record_disposition(hr))); printf(" Disposition: %s\n", user_disposition_to_string(user_record_disposition(hr)));
if (hr->last_change_usec != USEC_INFINITY) { if (hr->last_change_usec != USEC_INFINITY) {
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Last Change: %s\n", FORMAT_TIMESTAMP(hr->last_change_usec));
printf(" Last Change: %s\n", format_timestamp(buf, sizeof(buf), hr->last_change_usec));
if (hr->last_change_usec > now(CLOCK_REALTIME)) if (hr->last_change_usec > now(CLOCK_REALTIME))
printf(" %sModification time lies in the future, system clock wrong?%s\n", printf(" %sModification time lies in the future, system clock wrong?%s\n",
@ -52,10 +51,8 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
} }
if (hr->last_password_change_usec != USEC_INFINITY && if (hr->last_password_change_usec != USEC_INFINITY &&
hr->last_password_change_usec != hr->last_change_usec) { hr->last_password_change_usec != hr->last_change_usec)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Last Passw.: %s\n", FORMAT_TIMESTAMP(hr->last_password_change_usec));
printf(" Last Passw.: %s\n", format_timestamp(buf, sizeof(buf), hr->last_password_change_usec));
}
r = user_record_test_blocked(hr); r = user_record_test_blocked(hr);
switch (r) { switch (r) {
@ -238,15 +235,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
if (hr->locked >= 0) if (hr->locked >= 0)
printf(" Locked: %s\n", yes_no(hr->locked)); printf(" Locked: %s\n", yes_no(hr->locked));
if (hr->not_before_usec != UINT64_MAX) { if (hr->not_before_usec != UINT64_MAX)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Not Before: %s\n", FORMAT_TIMESTAMP(hr->not_before_usec));
printf(" Not Before: %s\n", format_timestamp(buf, sizeof(buf), hr->not_before_usec));
}
if (hr->not_after_usec != UINT64_MAX) { if (hr->not_after_usec != UINT64_MAX)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Not After: %s\n", FORMAT_TIMESTAMP(hr->not_after_usec));
printf(" Not After: %s\n", format_timestamp(buf, sizeof(buf), hr->not_after_usec));
}
if (hr->umask != MODE_INVALID) if (hr->umask != MODE_INVALID)
printf(" UMask: 0%03o\n", hr->umask); printf(" UMask: 0%03o\n", hr->umask);
@ -263,15 +256,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
if (hr->tasks_max != UINT64_MAX) if (hr->tasks_max != UINT64_MAX)
printf(" Tasks Max: %" PRIu64 "\n", hr->tasks_max); printf(" Tasks Max: %" PRIu64 "\n", hr->tasks_max);
if (hr->memory_high != UINT64_MAX) { if (hr->memory_high != UINT64_MAX)
char buf[FORMAT_BYTES_MAX]; printf(" Memory High: %s\n", FORMAT_BYTES(hr->memory_high));
printf(" Memory High: %s\n", format_bytes(buf, sizeof(buf), hr->memory_high));
}
if (hr->memory_max != UINT64_MAX) { if (hr->memory_max != UINT64_MAX)
char buf[FORMAT_BYTES_MAX]; printf(" Memory Max: %s\n", FORMAT_BYTES(hr->memory_max));
printf(" Memory Max: %s\n", format_bytes(buf, sizeof(buf), hr->memory_max));
}
if (hr->cpu_weight != UINT64_MAX) if (hr->cpu_weight != UINT64_MAX)
printf(" CPU Weight: %" PRIu64 "\n", hr->cpu_weight); printf(" CPU Weight: %" PRIu64 "\n", hr->cpu_weight);
@ -306,14 +295,11 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
printf(" PBKDF Type: %s\n", hr->luks_pbkdf_type); printf(" PBKDF Type: %s\n", hr->luks_pbkdf_type);
if (hr->luks_pbkdf_hash_algorithm) if (hr->luks_pbkdf_hash_algorithm)
printf(" PBKDF Hash: %s\n", hr->luks_pbkdf_hash_algorithm); printf(" PBKDF Hash: %s\n", hr->luks_pbkdf_hash_algorithm);
if (hr->luks_pbkdf_time_cost_usec != UINT64_MAX) { if (hr->luks_pbkdf_time_cost_usec != UINT64_MAX)
char buf[FORMAT_TIMESPAN_MAX]; printf(" PBKDF Time: %s\n", FORMAT_TIMESPAN(hr->luks_pbkdf_time_cost_usec, 0));
printf(" PBKDF Time: %s\n", format_timespan(buf, sizeof(buf), hr->luks_pbkdf_time_cost_usec, 0)); if (hr->luks_pbkdf_memory_cost != UINT64_MAX)
} printf(" PBKDF Bytes: %s\n", FORMAT_BYTES(hr->luks_pbkdf_memory_cost));
if (hr->luks_pbkdf_memory_cost != UINT64_MAX) {
char buf[FORMAT_BYTES_MAX];
printf(" PBKDF Bytes: %s\n", format_bytes(buf, sizeof(buf), hr->luks_pbkdf_memory_cost));
}
if (hr->luks_pbkdf_parallel_threads != UINT64_MAX) if (hr->luks_pbkdf_parallel_threads != UINT64_MAX)
printf("PBKDF Thread: %" PRIu64 "\n", hr->luks_pbkdf_parallel_threads); printf("PBKDF Thread: %" PRIu64 "\n", hr->luks_pbkdf_parallel_threads);
@ -337,28 +323,22 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
if (hr->skeleton_directory) if (hr->skeleton_directory)
printf(" Skel. Dir.: %s\n", user_record_skeleton_directory(hr)); printf(" Skel. Dir.: %s\n", user_record_skeleton_directory(hr));
if (hr->disk_size != UINT64_MAX) { if (hr->disk_size != UINT64_MAX)
char buf[FORMAT_BYTES_MAX]; printf(" Disk Size: %s\n", FORMAT_BYTES(hr->disk_size));
printf(" Disk Size: %s\n", format_bytes(buf, sizeof(buf), hr->disk_size));
}
if (hr->disk_usage != UINT64_MAX) { if (hr->disk_usage != UINT64_MAX) {
char buf[FORMAT_BYTES_MAX];
if (hr->disk_size != UINT64_MAX) { if (hr->disk_size != UINT64_MAX) {
unsigned permille; unsigned permille;
permille = (unsigned) DIV_ROUND_UP(hr->disk_usage * 1000U, hr->disk_size); /* Round up! */ permille = (unsigned) DIV_ROUND_UP(hr->disk_usage * 1000U, hr->disk_size); /* Round up! */
printf(" Disk Usage: %s (= %u.%01u%%)\n", printf(" Disk Usage: %s (= %u.%01u%%)\n",
format_bytes(buf, sizeof(buf), hr->disk_usage), FORMAT_BYTES(hr->disk_usage),
permille / 10, permille % 10); permille / 10, permille % 10);
} else } else
printf(" Disk Usage: %s\n", format_bytes(buf, sizeof(buf), hr->disk_usage)); printf(" Disk Usage: %s\n", FORMAT_BYTES(hr->disk_usage));
} }
if (hr->disk_free != UINT64_MAX) { if (hr->disk_free != UINT64_MAX) {
char buf[FORMAT_BYTES_MAX];
if (hr->disk_size != UINT64_MAX) { if (hr->disk_size != UINT64_MAX) {
const char *color_on, *color_off; const char *color_on, *color_off;
unsigned permille; unsigned permille;
@ -381,38 +361,30 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
printf(" Disk Free: %s%s (= %u.%01u%%)%s\n", printf(" Disk Free: %s%s (= %u.%01u%%)%s\n",
color_on, color_on,
format_bytes(buf, sizeof(buf), hr->disk_free), FORMAT_BYTES(hr->disk_free),
permille / 10, permille % 10, permille / 10, permille % 10,
color_off); color_off);
} else } else
printf(" Disk Free: %s\n", format_bytes(buf, sizeof(buf), hr->disk_free)); printf(" Disk Free: %s\n", FORMAT_BYTES(hr->disk_free));
} }
if (hr->disk_floor != UINT64_MAX) { if (hr->disk_floor != UINT64_MAX)
char buf[FORMAT_BYTES_MAX]; printf(" Disk Floor: %s\n", FORMAT_BYTES(hr->disk_floor));
printf(" Disk Floor: %s\n", format_bytes(buf, sizeof(buf), hr->disk_floor));
}
if (hr->disk_ceiling != UINT64_MAX) { if (hr->disk_ceiling != UINT64_MAX)
char buf[FORMAT_BYTES_MAX]; printf("Disk Ceiling: %s\n", FORMAT_BYTES(hr->disk_ceiling));
printf("Disk Ceiling: %s\n", format_bytes(buf, sizeof(buf), hr->disk_ceiling));
}
if (hr->good_authentication_counter != UINT64_MAX) if (hr->good_authentication_counter != UINT64_MAX)
printf(" Good Auth.: %" PRIu64 "\n", hr->good_authentication_counter); printf(" Good Auth.: %" PRIu64 "\n", hr->good_authentication_counter);
if (hr->last_good_authentication_usec != UINT64_MAX) { if (hr->last_good_authentication_usec != UINT64_MAX)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Last Good: %s\n", FORMAT_TIMESTAMP(hr->last_good_authentication_usec));
printf(" Last Good: %s\n", format_timestamp(buf, sizeof(buf), hr->last_good_authentication_usec));
}
if (hr->bad_authentication_counter != UINT64_MAX) if (hr->bad_authentication_counter != UINT64_MAX)
printf(" Bad Auth.: %" PRIu64 "\n", hr->bad_authentication_counter); printf(" Bad Auth.: %" PRIu64 "\n", hr->bad_authentication_counter);
if (hr->last_bad_authentication_usec != UINT64_MAX) { if (hr->last_bad_authentication_usec != UINT64_MAX)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Last Bad: %s\n", FORMAT_TIMESTAMP(hr->last_bad_authentication_usec));
printf(" Last Bad: %s\n", format_timestamp(buf, sizeof(buf), hr->last_bad_authentication_usec));
}
t = user_record_ratelimit_next_try(hr); t = user_record_ratelimit_next_try(hr);
if (t != USEC_INFINITY) { if (t != USEC_INFINITY) {
@ -420,20 +392,16 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
if (t <= n) if (t <= n)
printf(" Next Try: anytime\n"); printf(" Next Try: anytime\n");
else { else
char buf[FORMAT_TIMESPAN_MAX];
printf(" Next Try: %sin %s%s\n", printf(" Next Try: %sin %s%s\n",
ansi_highlight_red(), ansi_highlight_red(),
format_timespan(buf, sizeof(buf), t - n, USEC_PER_SEC), FORMAT_TIMESPAN(t - n, USEC_PER_SEC),
ansi_normal()); ansi_normal());
}
} }
if (storage != USER_CLASSIC) { if (storage != USER_CLASSIC)
char buf[FORMAT_TIMESPAN_MAX];
printf(" Auth. Limit: %" PRIu64 " attempts per %s\n", user_record_ratelimit_burst(hr), printf(" Auth. Limit: %" PRIu64 " attempts per %s\n", user_record_ratelimit_burst(hr),
format_timespan(buf, sizeof(buf), user_record_ratelimit_interval_usec(hr), 0)); FORMAT_TIMESPAN(user_record_ratelimit_interval_usec(hr), 0));
}
if (hr->enforce_password_policy >= 0) if (hr->enforce_password_policy >= 0)
printf(" Passwd Pol.: %s\n", yes_no(hr->enforce_password_policy)); printf(" Passwd Pol.: %s\n", yes_no(hr->enforce_password_policy));
@ -443,24 +411,23 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
hr->password_change_warn_usec != UINT64_MAX || hr->password_change_warn_usec != UINT64_MAX ||
hr->password_change_inactive_usec != UINT64_MAX) { hr->password_change_inactive_usec != UINT64_MAX) {
char buf[FORMAT_TIMESPAN_MAX];
printf(" Passwd Chg.:"); printf(" Passwd Chg.:");
if (hr->password_change_min_usec != UINT64_MAX) { if (hr->password_change_min_usec != UINT64_MAX) {
printf(" min %s", format_timespan(buf, sizeof(buf), hr->password_change_min_usec, 0)); printf(" min %s", FORMAT_TIMESPAN(hr->password_change_min_usec, 0));
if (hr->password_change_max_usec != UINT64_MAX) if (hr->password_change_max_usec != UINT64_MAX)
printf(""); printf("");
} }
if (hr->password_change_max_usec != UINT64_MAX) if (hr->password_change_max_usec != UINT64_MAX)
printf(" max %s", format_timespan(buf, sizeof(buf), hr->password_change_max_usec, 0)); printf(" max %s", FORMAT_TIMESPAN(hr->password_change_max_usec, 0));
if (hr->password_change_warn_usec != UINT64_MAX) if (hr->password_change_warn_usec != UINT64_MAX)
printf("/warn %s", format_timespan(buf, sizeof(buf), hr->password_change_warn_usec, 0)); printf("/warn %s", FORMAT_TIMESPAN(hr->password_change_warn_usec, 0));
if (hr->password_change_inactive_usec != UINT64_MAX) if (hr->password_change_inactive_usec != UINT64_MAX)
printf("/inactive %s", format_timespan(buf, sizeof(buf), hr->password_change_inactive_usec, 0)); printf("/inactive %s", FORMAT_TIMESPAN(hr->password_change_inactive_usec, 0));
printf("\n"); printf("\n");
} }
@ -496,10 +463,8 @@ void user_record_show(UserRecord *hr, bool show_full_group_info) {
if (hr->signed_locally >= 0) if (hr->signed_locally >= 0)
printf(" Local Sig.: %s\n", yes_no(hr->signed_locally)); printf(" Local Sig.: %s\n", yes_no(hr->signed_locally));
if (hr->stop_delay_usec != UINT64_MAX) { if (hr->stop_delay_usec != UINT64_MAX)
char buf[FORMAT_TIMESPAN_MAX]; printf(" Stop Delay: %s\n", FORMAT_TIMESPAN(hr->stop_delay_usec, 0));
printf(" Stop Delay: %s\n", format_timespan(buf, sizeof(buf), hr->stop_delay_usec, 0));
}
if (hr->auto_login >= 0) if (hr->auto_login >= 0)
printf("Autom. Login: %s\n", yes_no(hr->auto_login)); printf("Autom. Login: %s\n", yes_no(hr->auto_login));
@ -519,10 +484,8 @@ void group_record_show(GroupRecord *gr, bool show_full_user_info) {
printf(" Disposition: %s\n", user_disposition_to_string(group_record_disposition(gr))); printf(" Disposition: %s\n", user_disposition_to_string(group_record_disposition(gr)));
if (gr->last_change_usec != USEC_INFINITY) { if (gr->last_change_usec != USEC_INFINITY)
char buf[FORMAT_TIMESTAMP_MAX]; printf(" Last Change: %s\n", FORMAT_TIMESTAMP(gr->last_change_usec));
printf(" Last Change: %s\n", format_timestamp(buf, sizeof(buf), gr->last_change_usec));
}
if (gid_is_valid(gr->gid)) if (gid_is_valid(gr->gid))
printf(" GID: " GID_FMT "\n", gr->gid); printf(" GID: " GID_FMT "\n", gr->gid);

View File

@ -340,7 +340,6 @@ int utmp_wall(
void *userdata) { void *userdata) {
_cleanup_free_ char *text = NULL, *hn = NULL, *un = NULL, *stdin_tty = NULL; _cleanup_free_ char *text = NULL, *hn = NULL, *un = NULL, *stdin_tty = NULL;
char date[FORMAT_TIMESTAMP_MAX];
struct utmpx *u; struct utmpx *u;
int r; int r;
@ -364,7 +363,7 @@ int utmp_wall(
"%s\r\n\r\n", "%s\r\n\r\n",
un ?: username, hn, un ?: username, hn,
origin_tty ? " on " : "", strempty(origin_tty), origin_tty ? " on " : "", strempty(origin_tty),
format_timestamp(date, sizeof(date), now(CLOCK_REALTIME)), FORMAT_TIMESTAMP(now(CLOCK_REALTIME)),
message) < 0) message) < 0)
return -ENOMEM; return -ENOMEM;

View File

@ -2145,7 +2145,9 @@ int varlink_server_add_connection(VarlinkServer *server, int fd, Varlink **ret)
v->ucred_acquired = true; v->ucred_acquired = true;
} }
(void) asprintf(&v->description, "%s-%i", server->description ?: "varlink", v->fd); _cleanup_free_ char *desc = NULL;
if (asprintf(&desc, "%s-%i", server->description ?: "varlink", v->fd) >= 0)
v->description = TAKE_PTR(desc);
/* Link up the server and the connection, and take reference in both directions. Note that the /* Link up the server and the connection, and take reference in both directions. Note that the
* reference on the connection is left dangling. It will be dropped when the connection is closed, * reference on the connection is left dangling. It will be dropped when the connection is closed,

View File

@ -32,7 +32,6 @@ static int update_timeout(void) {
if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0) if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0)
return log_warning_errno(errno, "Failed to disable hardware watchdog: %m"); return log_warning_errno(errno, "Failed to disable hardware watchdog: %m");
} else { } else {
char buf[FORMAT_TIMESPAN_MAX];
int sec, flags; int sec, flags;
usec_t t; usec_t t;
@ -41,8 +40,7 @@ static int update_timeout(void) {
if (ioctl(watchdog_fd, WDIOC_SETTIMEOUT, &sec) < 0) if (ioctl(watchdog_fd, WDIOC_SETTIMEOUT, &sec) < 0)
return log_warning_errno(errno, "Failed to set timeout to %is: %m", sec); return log_warning_errno(errno, "Failed to set timeout to %is: %m", sec);
watchdog_timeout = (usec_t) sec * USEC_PER_SEC; log_info("Set hardware watchdog to %s.", FORMAT_TIMESPAN(sec * USEC_PER_SEC, 0));
log_info("Set hardware watchdog to %s.", format_timespan(buf, sizeof(buf), watchdog_timeout, 0));
flags = WDIOS_ENABLECARD; flags = WDIOS_ENABLECARD;
if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0) { if (ioctl(watchdog_fd, WDIOC_SETOPTIONS, &flags) < 0) {

View File

@ -266,7 +266,6 @@ static int execute(
static int execute_s2h(const SleepConfig *sleep_config) { static int execute_s2h(const SleepConfig *sleep_config) {
_cleanup_close_ int tfd = -1; _cleanup_close_ int tfd = -1;
char buf[FORMAT_TIMESPAN_MAX];
struct itimerspec ts = {}; struct itimerspec ts = {};
int r; int r;
@ -277,7 +276,7 @@ static int execute_s2h(const SleepConfig *sleep_config) {
return log_error_errno(errno, "Error creating timerfd: %m"); return log_error_errno(errno, "Error creating timerfd: %m");
log_debug("Set timerfd wake alarm for %s", log_debug("Set timerfd wake alarm for %s",
format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC)); FORMAT_TIMESPAN(sleep_config->hibernate_delay_sec, USEC_PER_SEC));
timespec_store(&ts.it_value, sleep_config->hibernate_delay_sec); timespec_store(&ts.it_value, sleep_config->hibernate_delay_sec);
@ -299,7 +298,7 @@ static int execute_s2h(const SleepConfig *sleep_config) {
/* If woken up after alarm time, hibernate */ /* If woken up after alarm time, hibernate */
log_debug("Attempting to hibernate after waking from %s timer", log_debug("Attempting to hibernate after waking from %s timer",
format_timespan(buf, sizeof(buf), sleep_config->hibernate_delay_sec, USEC_PER_SEC)); FORMAT_TIMESPAN(sleep_config->hibernate_delay_sec, USEC_PER_SEC));
r = execute(sleep_config, SLEEP_HIBERNATE, NULL); r = execute(sleep_config, SLEEP_HIBERNATE, NULL);
if (r < 0) { if (r < 0) {

View File

@ -296,7 +296,6 @@ int logind_schedule_shutdown(void) {
#if ENABLE_LOGIND #if ENABLE_LOGIND
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
char date[FORMAT_TIMESTAMP_MAX];
const char *action; const char *action;
const char *log_action; const char *log_action;
sd_bus *bus; sd_bus *bus;
@ -340,7 +339,9 @@ int logind_schedule_shutdown(void) {
return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r)); return log_warning_errno(r, "Failed to call ScheduleShutdown in logind, proceeding with immediate shutdown: %s", bus_error_message(&error, r));
if (!arg_quiet) if (!arg_quiet)
log_info("%s scheduled for %s, use 'shutdown -c' to cancel.", log_action, format_timestamp_style(date, sizeof(date), arg_when, arg_timestamp_style)); log_info("%s scheduled for %s, use 'shutdown -c' to cancel.",
log_action,
FORMAT_TIMESTAMP_STYLE(arg_when, arg_timestamp_style));
return 0; return 0;
#else #else
return log_error_errno(SYNTHETIC_ERRNO(ENOSYS), return log_error_errno(SYNTHETIC_ERRNO(ENOSYS),

View File

@ -300,7 +300,6 @@ static void print_status_info(
UnitStatusInfo *i, UnitStatusInfo *i,
bool *ellipsized) { bool *ellipsized) {
char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
const char *s1, *s2, *active_on, *active_off, *on, *off, *ss, *fs; const char *s1, *s2, *active_on, *active_off, *on, *off, *ss, *fs;
_cleanup_free_ char *formatted_path = NULL; _cleanup_free_ char *formatted_path = NULL;
ExecStatusInfo *p; ExecStatusInfo *p;
@ -419,9 +418,8 @@ static void print_status_info(
STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp : STRPTR_IN_SET(i->active_state, "activating") ? i->inactive_exit_timestamp :
i->active_exit_timestamp; i->active_exit_timestamp;
s1 = format_timestamp_relative(since1, sizeof(since1), timestamp); s1 = FORMAT_TIMESTAMP_RELATIVE(timestamp);
s2 = format_timestamp_style(since2, sizeof(since2), timestamp, arg_timestamp_style); s2 = FORMAT_TIMESTAMP_STYLE(timestamp, arg_timestamp_style);
if (s1) if (s1)
printf(" since %s; %s\n", s2, s1); printf(" since %s; %s\n", s2, s1);
else if (s2) else if (s2)
@ -442,24 +440,18 @@ static void print_status_info(
} }
if (endswith(i->id, ".timer")) { if (endswith(i->id, ".timer")) {
char tstamp1[FORMAT_TIMESTAMP_RELATIVE_MAX], const char *next_time;
tstamp2[FORMAT_TIMESTAMP_MAX]; dual_timestamp nw, next = {i->next_elapse_real, i->next_elapse_monotonic};
const char *next_rel_time, *next_time;
dual_timestamp nw, next = {i->next_elapse_real,
i->next_elapse_monotonic};
usec_t next_elapse; usec_t next_elapse;
printf(" Trigger: ");
dual_timestamp_get(&nw); dual_timestamp_get(&nw);
next_elapse = calc_next_elapse(&nw, &next); next_elapse = calc_next_elapse(&nw, &next);
next_rel_time = format_timestamp_relative(tstamp1, sizeof tstamp1, next_elapse); next_time = FORMAT_TIMESTAMP_STYLE(next_elapse, arg_timestamp_style);
next_time = format_timestamp_style(tstamp2, sizeof tstamp2, next_elapse, arg_timestamp_style);
if (next_time && next_rel_time) printf(" Trigger: %s%s%s\n",
printf("%s; %s\n", next_time, next_rel_time); strna(next_time),
else next_time ? "; " : "",
printf("n/a\n"); next_time ? strna(FORMAT_TIMESTAMP_RELATIVE(next_elapse)) : "");
} }
STRV_FOREACH(t, i->triggers) { STRV_FOREACH(t, i->triggers) {
@ -477,13 +469,13 @@ static void print_status_info(
if (!i->condition_result && i->condition_timestamp > 0) { if (!i->condition_result && i->condition_timestamp > 0) {
UnitCondition *c; UnitCondition *c;
int n = 0; int n = 0;
const char *rel;
s1 = format_timestamp_relative(since1, sizeof(since1), i->condition_timestamp); rel = FORMAT_TIMESTAMP_RELATIVE(i->condition_timestamp);
s2 = format_timestamp_style(since2, sizeof(since2), i->condition_timestamp, arg_timestamp_style);
printf(" Condition: start %scondition failed%s at %s%s%s\n", printf(" Condition: start %scondition failed%s at %s%s%s\n",
ansi_highlight_yellow(), ansi_normal(), ansi_highlight_yellow(), ansi_normal(),
s2, s1 ? "; " : "", strempty(s1)); FORMAT_TIMESTAMP_STYLE(i->condition_timestamp, arg_timestamp_style),
rel ? "; " : "", strempty(rel));
LIST_FOREACH(conditions, c, i->conditions) LIST_FOREACH(conditions, c, i->conditions)
if (c->tristate < 0) if (c->tristate < 0)
@ -500,12 +492,13 @@ static void print_status_info(
} }
if (!i->assert_result && i->assert_timestamp > 0) { if (!i->assert_result && i->assert_timestamp > 0) {
s1 = format_timestamp_relative(since1, sizeof(since1), i->assert_timestamp); const char *rel;
s2 = format_timestamp_style(since2, sizeof(since2), i->assert_timestamp, arg_timestamp_style);
rel = FORMAT_TIMESTAMP_RELATIVE(i->assert_timestamp);
printf(" Assert: start %sassertion failed%s at %s%s%s\n", printf(" Assert: start %sassertion failed%s at %s%s%s\n",
ansi_highlight_red(), ansi_normal(), ansi_highlight_red(), ansi_normal(),
s2, s1 ? "; " : "", strempty(s1)); FORMAT_TIMESTAMP_STYLE(i->assert_timestamp, arg_timestamp_style),
rel ? "; " : "", strempty(rel));
if (i->failed_assert_trigger) if (i->failed_assert_trigger)
printf(" none of the trigger assertions were met\n"); printf(" none of the trigger assertions were met\n");
else if (i->failed_assert) else if (i->failed_assert)
@ -651,21 +644,15 @@ static void print_status_info(
if (i->status_errno > 0) if (i->status_errno > 0)
printf(" Error: %i (%s)\n", i->status_errno, strerror_safe(i->status_errno)); printf(" Error: %i (%s)\n", i->status_errno, strerror_safe(i->status_errno));
if (i->ip_ingress_bytes != UINT64_MAX && i->ip_egress_bytes != UINT64_MAX) { if (i->ip_ingress_bytes != UINT64_MAX && i->ip_egress_bytes != UINT64_MAX)
char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
printf(" IP: %s in, %s out\n", printf(" IP: %s in, %s out\n",
format_bytes(buf_in, sizeof(buf_in), i->ip_ingress_bytes), FORMAT_BYTES(i->ip_ingress_bytes),
format_bytes(buf_out, sizeof(buf_out), i->ip_egress_bytes)); FORMAT_BYTES(i->ip_egress_bytes));
}
if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX) {
char buf_in[FORMAT_BYTES_MAX], buf_out[FORMAT_BYTES_MAX];
if (i->io_read_bytes != UINT64_MAX && i->io_write_bytes != UINT64_MAX)
printf(" IO: %s read, %s written\n", printf(" IO: %s read, %s written\n",
format_bytes(buf_in, sizeof(buf_in), i->io_read_bytes), FORMAT_BYTES(i->io_read_bytes),
format_bytes(buf_out, sizeof(buf_out), i->io_write_bytes)); FORMAT_BYTES(i->io_write_bytes));
}
if (i->tasks_current != UINT64_MAX) { if (i->tasks_current != UINT64_MAX) {
printf(" Tasks: %" PRIu64, i->tasks_current); printf(" Tasks: %" PRIu64, i->tasks_current);
@ -677,9 +664,7 @@ static void print_status_info(
} }
if (i->memory_current != UINT64_MAX) { if (i->memory_current != UINT64_MAX) {
char buf[FORMAT_BYTES_MAX]; printf(" Memory: %s", FORMAT_BYTES(i->memory_current));
printf(" Memory: %s", format_bytes(buf, sizeof(buf), i->memory_current));
if (i->memory_min > 0 || i->memory_low > 0 || if (i->memory_min > 0 || i->memory_low > 0 ||
i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX || i->memory_high != CGROUP_LIMIT_MAX || i->memory_max != CGROUP_LIMIT_MAX ||
@ -690,31 +675,31 @@ static void print_status_info(
printf(" ("); printf(" (");
if (i->memory_min > 0) { if (i->memory_min > 0) {
printf("%smin: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_min)); printf("%smin: %s", prefix, FORMAT_BYTES_CGROUP_PROTECTION(i->memory_min));
prefix = " "; prefix = " ";
} }
if (i->memory_low > 0) { if (i->memory_low > 0) {
printf("%slow: %s", prefix, format_bytes_cgroup_protection(buf, sizeof(buf), i->memory_low)); printf("%slow: %s", prefix, FORMAT_BYTES_CGROUP_PROTECTION(i->memory_low));
prefix = " "; prefix = " ";
} }
if (i->memory_high != CGROUP_LIMIT_MAX) { if (i->memory_high != CGROUP_LIMIT_MAX) {
printf("%shigh: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_high)); printf("%shigh: %s", prefix, FORMAT_BYTES(i->memory_high));
prefix = " "; prefix = " ";
} }
if (i->memory_max != CGROUP_LIMIT_MAX) { if (i->memory_max != CGROUP_LIMIT_MAX) {
printf("%smax: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_max)); printf("%smax: %s", prefix, FORMAT_BYTES(i->memory_max));
prefix = " "; prefix = " ";
} }
if (i->memory_swap_max != CGROUP_LIMIT_MAX) { if (i->memory_swap_max != CGROUP_LIMIT_MAX) {
printf("%sswap max: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_swap_max)); printf("%sswap max: %s", prefix, FORMAT_BYTES(i->memory_swap_max));
prefix = " "; prefix = " ";
} }
if (i->memory_limit != CGROUP_LIMIT_MAX) { if (i->memory_limit != CGROUP_LIMIT_MAX) {
printf("%slimit: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_limit)); printf("%slimit: %s", prefix, FORMAT_BYTES(i->memory_limit));
prefix = " "; prefix = " ";
} }
if (i->memory_available != CGROUP_LIMIT_MAX) { if (i->memory_available != CGROUP_LIMIT_MAX) {
printf("%savailable: %s", prefix, format_bytes(buf, sizeof(buf), i->memory_available)); printf("%savailable: %s", prefix, FORMAT_BYTES(i->memory_available));
prefix = " "; prefix = " ";
} }
printf(")"); printf(")");
@ -722,10 +707,8 @@ static void print_status_info(
printf("\n"); printf("\n");
} }
if (i->cpu_usage_nsec != UINT64_MAX) { if (i->cpu_usage_nsec != UINT64_MAX)
char buf[FORMAT_TIMESPAN_MAX]; printf(" CPU: %s\n", FORMAT_TIMESPAN(i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
printf(" CPU: %s\n", format_timespan(buf, sizeof(buf), i->cpu_usage_nsec / NSEC_PER_USEC, USEC_PER_MSEC));
}
if (i->control_group) { if (i->control_group) {
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
@ -1235,15 +1218,12 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
if (r < 0) if (r < 0)
return bus_log_parse_error(r); return bus_log_parse_error(r);
while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0) { while ((r = sd_bus_message_read(m, "(stt)", &base, &v, &next_elapse)) > 0)
char timespan1[FORMAT_TIMESPAN_MAX] = "n/a", timespan2[FORMAT_TIMESPAN_MAX] = "n/a";
(void) format_timespan(timespan1, sizeof timespan1, v, 0);
(void) format_timespan(timespan2, sizeof timespan2, next_elapse, 0);
bus_print_property_valuef(name, expected_value, flags, bus_print_property_valuef(name, expected_value, flags,
"{ %s=%s ; next_elapse=%s }", base, timespan1, timespan2); "{ %s=%s ; next_elapse=%s }",
} base,
strna(FORMAT_TIMESPAN(v, 0)),
strna(FORMAT_TIMESPAN(next_elapse, 0)));
if (r < 0) if (r < 0)
return bus_log_parse_error(r); return bus_log_parse_error(r);
@ -1261,13 +1241,10 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
if (r < 0) if (r < 0)
return bus_log_parse_error(r); return bus_log_parse_error(r);
while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0) { while ((r = sd_bus_message_read(m, "(sst)", &base, &spec, &next_elapse)) > 0)
char timestamp[FORMAT_TIMESTAMP_MAX] = "n/a";
(void) format_timestamp_style(timestamp, sizeof(timestamp), next_elapse, arg_timestamp_style);
bus_print_property_valuef(name, expected_value, flags, bus_print_property_valuef(name, expected_value, flags,
"{ %s=%s ; next_elapse=%s }", base, spec, timestamp); "{ %s=%s ; next_elapse=%s }", base, spec,
} FORMAT_TIMESTAMP_STYLE(next_elapse, arg_timestamp_style));
if (r < 0) if (r < 0)
return bus_log_parse_error(r); return bus_log_parse_error(r);
@ -1286,7 +1263,6 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
return bus_log_parse_error(r); return bus_log_parse_error(r);
while ((r = exec_status_info_deserialize(m, &info, is_ex_prop)) > 0) { while ((r = exec_status_info_deserialize(m, &info, is_ex_prop)) > 0) {
char timestamp1[FORMAT_TIMESTAMP_MAX], timestamp2[FORMAT_TIMESTAMP_MAX];
_cleanup_strv_free_ char **optv = NULL; _cleanup_strv_free_ char **optv = NULL;
_cleanup_free_ char *tt = NULL, *o = NULL; _cleanup_free_ char *tt = NULL, *o = NULL;
@ -1304,8 +1280,8 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
strna(info.path), strna(info.path),
strna(tt), strna(tt),
strna(o), strna(o),
strna(format_timestamp_style(timestamp1, sizeof(timestamp1), info.start_timestamp, arg_timestamp_style)), strna(FORMAT_TIMESTAMP_STYLE(info.start_timestamp, arg_timestamp_style)),
strna(format_timestamp_style(timestamp2, sizeof(timestamp2), info.exit_timestamp, arg_timestamp_style)), strna(FORMAT_TIMESTAMP_STYLE(info.exit_timestamp, arg_timestamp_style)),
info.pid, info.pid,
sigchld_code_to_string(info.code), sigchld_code_to_string(info.code),
info.status, info.status,
@ -1317,8 +1293,8 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
strna(info.path), strna(info.path),
strna(tt), strna(tt),
yes_no(info.ignore), yes_no(info.ignore),
strna(format_timestamp_style(timestamp1, sizeof(timestamp1), info.start_timestamp, arg_timestamp_style)), strna(FORMAT_TIMESTAMP_STYLE(info.start_timestamp, arg_timestamp_style)),
strna(format_timestamp_style(timestamp2, sizeof(timestamp2), info.exit_timestamp, arg_timestamp_style)), strna(FORMAT_TIMESTAMP_STYLE(info.exit_timestamp, arg_timestamp_style)),
info.pid, info.pid,
sigchld_code_to_string(info.code), sigchld_code_to_string(info.code),
info.status, info.status,
@ -1397,7 +1373,6 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
} else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN && } else if (contents[0] == SD_BUS_TYPE_STRUCT_BEGIN &&
streq(name, "IODeviceLatencyTargetUSec")) { streq(name, "IODeviceLatencyTargetUSec")) {
char ts[FORMAT_TIMESPAN_MAX];
const char *path; const char *path;
uint64_t target; uint64_t target;
@ -1407,7 +1382,7 @@ static int print_property(const char *name, const char *expected_value, sd_bus_m
while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0) while ((r = sd_bus_message_read(m, "(st)", &path, &target)) > 0)
bus_print_property_valuef(name, expected_value, flags, "%s %s", strna(path), bus_print_property_valuef(name, expected_value, flags, "%s %s", strna(path),
format_timespan(ts, sizeof(ts), target, 1)); FORMAT_TIMESPAN(target, 1));
if (r < 0) if (r < 0)
return bus_log_parse_error(r); return bus_log_parse_error(r);
@ -2021,7 +1996,6 @@ static int show_all(
} }
static int show_system_status(sd_bus *bus) { static int show_system_status(sd_bus *bus) {
char since1[FORMAT_TIMESTAMP_RELATIVE_MAX], since2[FORMAT_TIMESTAMP_MAX];
_cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
_cleanup_(machine_info_clear) struct machine_info mi = {}; _cleanup_(machine_info_clear) struct machine_info mi = {};
_cleanup_free_ char *hn = NULL; _cleanup_free_ char *hn = NULL;
@ -2064,8 +2038,8 @@ static int show_system_status(sd_bus *bus) {
printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units); printf(" Failed: %" PRIu32 " units\n", mi.n_failed_units);
printf(" Since: %s; %s\n", printf(" Since: %s; %s\n",
format_timestamp_style(since2, sizeof(since2), mi.timestamp, arg_timestamp_style), FORMAT_TIMESTAMP_STYLE(mi.timestamp, arg_timestamp_style),
format_timestamp_relative(since1, sizeof(since1), mi.timestamp)); FORMAT_TIMESTAMP_RELATIVE(mi.timestamp));
printf(" CGroup: %s\n", mi.control_group ?: "/"); printf(" CGroup: %s\n", mi.control_group ?: "/");
if (IN_SET(arg_transport, if (IN_SET(arg_transport,

View File

@ -44,6 +44,8 @@ test_dlopen_c = files('test-dlopen.c')
tests += [ tests += [
[['src/test/test-device-nodes.c']], [['src/test/test-device-nodes.c']],
[['src/test/test-ether-addr-util.c']],
[['src/test/test-engine.c'], [['src/test/test-engine.c'],
[libcore, [libcore,
libshared], libshared],

View File

@ -11,7 +11,6 @@
#include "util.h" #include "util.h"
static int test_acpi_fpdt(void) { static int test_acpi_fpdt(void) {
char ts_start[FORMAT_TIMESPAN_MAX], ts_exit[FORMAT_TIMESPAN_MAX], ts_span[FORMAT_TIMESPAN_MAX];
usec_t loader_start, loader_exit; usec_t loader_start, loader_exit;
int r; int r;
@ -24,14 +23,13 @@ static int test_acpi_fpdt(void) {
} }
log_info("ACPI FPDT: loader start=%s exit=%s duration=%s", log_info("ACPI FPDT: loader start=%s exit=%s duration=%s",
format_timespan(ts_start, sizeof(ts_start), loader_start, USEC_PER_MSEC), FORMAT_TIMESPAN(loader_start, USEC_PER_MSEC),
format_timespan(ts_exit, sizeof(ts_exit), loader_exit, USEC_PER_MSEC), FORMAT_TIMESPAN(loader_exit, USEC_PER_MSEC),
format_timespan(ts_span, sizeof(ts_span), loader_exit - loader_start, USEC_PER_MSEC)); FORMAT_TIMESPAN(loader_exit - loader_start, USEC_PER_MSEC));
return 1; return 1;
} }
static int test_efi_loader(void) { static int test_efi_loader(void) {
char ts_start[FORMAT_TIMESPAN_MAX], ts_exit[FORMAT_TIMESPAN_MAX], ts_span[FORMAT_TIMESPAN_MAX];
usec_t loader_start, loader_exit; usec_t loader_start, loader_exit;
int r; int r;
@ -44,14 +42,13 @@ static int test_efi_loader(void) {
} }
log_info("EFI Loader: start=%s exit=%s duration=%s", log_info("EFI Loader: start=%s exit=%s duration=%s",
format_timespan(ts_start, sizeof(ts_start), loader_start, USEC_PER_MSEC), FORMAT_TIMESPAN(loader_start, USEC_PER_MSEC),
format_timespan(ts_exit, sizeof(ts_exit), loader_exit, USEC_PER_MSEC), FORMAT_TIMESPAN(loader_exit, USEC_PER_MSEC),
format_timespan(ts_span, sizeof(ts_span), loader_exit - loader_start, USEC_PER_MSEC)); FORMAT_TIMESPAN(loader_exit - loader_start, USEC_PER_MSEC));
return 1; return 1;
} }
static int test_boot_timestamps(void) { static int test_boot_timestamps(void) {
char s[MAX(FORMAT_TIMESPAN_MAX, FORMAT_TIMESTAMP_MAX)];
dual_timestamp fw, l, k; dual_timestamp fw, l, k;
int r; int r;
@ -65,11 +62,11 @@ static int test_boot_timestamps(void) {
return ok ? 0 : r; return ok ? 0 : r;
} }
log_info("Firmware began %s before kernel.", format_timespan(s, sizeof(s), fw.monotonic, 0)); log_info("Firmware began %s before kernel.", FORMAT_TIMESPAN(fw.monotonic, 0));
log_info("Loader began %s before kernel.", format_timespan(s, sizeof(s), l.monotonic, 0)); log_info("Loader began %s before kernel.", FORMAT_TIMESPAN(l.monotonic, 0));
log_info("Firmware began %s.", format_timestamp(s, sizeof(s), fw.realtime)); log_info("Firmware began %s.", FORMAT_TIMESTAMP(fw.realtime));
log_info("Loader began %s.", format_timestamp(s, sizeof(s), l.realtime)); log_info("Loader began %s.", FORMAT_TIMESTAMP(l.realtime));
log_info("Kernel began %s.", format_timestamp(s, sizeof(s), k.realtime)); log_info("Kernel began %s.", FORMAT_TIMESTAMP(k.realtime));
return 1; return 1;
} }

View File

@ -18,14 +18,13 @@ int main(int argc, char *argv[]) {
if (fd < 0) if (fd < 0)
log_error_errno(errno, "Failed to open root directory: %m"); log_error_errno(errno, "Failed to open root directory: %m");
else { else {
char ts[FORMAT_TIMESTAMP_MAX], bs[FORMAT_BYTES_MAX];
BtrfsSubvolInfo info; BtrfsSubvolInfo info;
r = btrfs_subvol_get_info_fd(fd, 0, &info); r = btrfs_subvol_get_info_fd(fd, 0, &info);
if (r < 0) if (r < 0)
log_error_errno(r, "Failed to get subvolume info: %m"); log_error_errno(r, "Failed to get subvolume info: %m");
else { else {
log_info("otime: %s", format_timestamp(ts, sizeof(ts), info.otime)); log_info("otime: %s", FORMAT_TIMESTAMP(info.otime));
log_info("read-only (search): %s", yes_no(info.read_only)); log_info("read-only (search): %s", yes_no(info.read_only));
} }
@ -33,10 +32,10 @@ int main(int argc, char *argv[]) {
if (r < 0) if (r < 0)
log_error_errno(r, "Failed to get quota info: %m"); log_error_errno(r, "Failed to get quota info: %m");
else { else {
log_info("referenced: %s", strna(format_bytes(bs, sizeof(bs), quota.referenced))); log_info("referenced: %s", strna(FORMAT_BYTES(quota.referenced)));
log_info("exclusive: %s", strna(format_bytes(bs, sizeof(bs), quota.exclusive))); log_info("exclusive: %s", strna(FORMAT_BYTES(quota.exclusive)));
log_info("referenced_max: %s", strna(format_bytes(bs, sizeof(bs), quota.referenced_max))); log_info("referenced_max: %s", strna(FORMAT_BYTES(quota.referenced_max)));
log_info("exclusive_max: %s", strna(format_bytes(bs, sizeof(bs), quota.exclusive_max))); log_info("exclusive_max: %s", strna(FORMAT_BYTES(quota.exclusive_max)));
} }
r = btrfs_subvol_get_read_only_fd(fd); r = btrfs_subvol_get_read_only_fd(fd);

View File

@ -10,7 +10,6 @@ static void _test_one(int line, const char *input, const char *output) {
CalendarSpec *c; CalendarSpec *c;
_cleanup_free_ char *p = NULL, *q = NULL; _cleanup_free_ char *p = NULL, *q = NULL;
usec_t u; usec_t u;
char buf[FORMAT_TIMESTAMP_MAX];
int r; int r;
assert_se(calendar_spec_from_string(input, &c) >= 0); assert_se(calendar_spec_from_string(input, &c) >= 0);
@ -22,7 +21,7 @@ static void _test_one(int line, const char *input, const char *output) {
u = now(CLOCK_REALTIME); u = now(CLOCK_REALTIME);
r = calendar_spec_next_usec(c, u, &u); r = calendar_spec_next_usec(c, u, &u);
log_info("Next: %s", r < 0 ? strerror_safe(r) : format_timestamp(buf, sizeof buf, u)); log_info("Next: %s", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP(u));
calendar_spec_free(c); calendar_spec_free(c);
assert_se(calendar_spec_from_string(p, &c) >= 0); assert_se(calendar_spec_from_string(p, &c) >= 0);
@ -37,7 +36,6 @@ static void _test_next(int line, const char *input, const char *new_tz, usec_t a
CalendarSpec *c; CalendarSpec *c;
usec_t u; usec_t u;
char *old_tz; char *old_tz;
char buf[FORMAT_TIMESTAMP_MAX];
int r; int r;
old_tz = getenv("TZ"); old_tz = getenv("TZ");
@ -56,7 +54,7 @@ static void _test_next(int line, const char *input, const char *new_tz, usec_t a
u = after; u = after;
r = calendar_spec_next_usec(c, after, &u); r = calendar_spec_next_usec(c, after, &u);
log_info("At: %s", r < 0 ? strerror_safe(r) : format_timestamp_style(buf, sizeof buf, u, TIMESTAMP_US)); log_info("At: %s", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(u, TIMESTAMP_US));
if (expect != USEC_INFINITY) if (expect != USEC_INFINITY)
assert_se(r >= 0 && u == expect); assert_se(r >= 0 && u == expect);
else else
@ -93,18 +91,17 @@ static void test_timestamp(void) {
static void test_hourly_bug_4031(void) { static void test_hourly_bug_4031(void) {
CalendarSpec *c; CalendarSpec *c;
usec_t n, u, w; usec_t n, u, w;
char buf[FORMAT_TIMESTAMP_MAX], zaf[FORMAT_TIMESTAMP_MAX];
int r; int r;
assert_se(calendar_spec_from_string("hourly", &c) >= 0); assert_se(calendar_spec_from_string("hourly", &c) >= 0);
n = now(CLOCK_REALTIME); n = now(CLOCK_REALTIME);
assert_se((r = calendar_spec_next_usec(c, n, &u)) >= 0); assert_se((r = calendar_spec_next_usec(c, n, &u)) >= 0);
log_info("Now: %s (%"PRIu64")", format_timestamp_style(buf, sizeof buf, n, TIMESTAMP_US), n); log_info("Now: %s (%"PRIu64")", FORMAT_TIMESTAMP_STYLE(n, TIMESTAMP_US), n);
log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : format_timestamp_style(buf, sizeof buf, u, TIMESTAMP_US), u); log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(u, TIMESTAMP_US), u);
assert_se((r = calendar_spec_next_usec(c, u, &w)) >= 0); assert_se((r = calendar_spec_next_usec(c, u, &w)) >= 0);
log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : format_timestamp_style(zaf, sizeof zaf, w, TIMESTAMP_US), w); log_info("Next hourly: %s (%"PRIu64")", r < 0 ? strerror_safe(r) : FORMAT_TIMESTAMP_STYLE(w, TIMESTAMP_US), w);
assert_se(n < u); assert_se(n < u);
assert_se(u <= n + USEC_PER_HOUR); assert_se(u <= n + USEC_PER_HOUR);

View File

@ -15,12 +15,9 @@ static void test_should_pass(const char *p) {
log_info("\"%s\"\"%s\"", p, buf); log_info("\"%s\"\"%s\"", p, buf);
assert_se(parse_timestamp(buf, &q) >= 0); assert_se(parse_timestamp(buf, &q) >= 0);
if (q != t) { if (q != t)
char tmp[FORMAT_TIMESTAMP_MAX];
log_error("round-trip failed: \"%s\"\"%s\"", log_error("round-trip failed: \"%s\"\"%s\"",
buf, format_timestamp_style(tmp, sizeof(tmp), q, TIMESTAMP_US)); buf, FORMAT_TIMESTAMP_STYLE(q, TIMESTAMP_US));
}
assert_se(q == t); assert_se(q == t);
assert_se(format_timestamp_relative(buf_relative, sizeof(buf_relative), t)); assert_se(format_timestamp_relative(buf_relative, sizeof(buf_relative), t));

View File

@ -0,0 +1,42 @@
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "ether-addr-util.h"
#include "tests.h"
#define INFINIBAD_ADDR_1 ((const struct hw_addr_data){ .length = 20, .infiniband = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20} })
static void test_HW_ADDR_TO_STRING(void) {
log_info("/* %s */", __func__);
const char *s = HW_ADDR_TO_STR(&(const struct hw_addr_data){6});
log_info("null: %s", s);
log_info("null×2: %s, %s",
HW_ADDR_TO_STR(&(const struct hw_addr_data){6}),
HW_ADDR_TO_STR(&(const struct hw_addr_data){6}));
log_info("null×3: %s, %s, %s",
HW_ADDR_TO_STR(&(const struct hw_addr_data){6}),
s,
HW_ADDR_TO_STR(&(const struct hw_addr_data){6}));
log_info("infiniband: %s", HW_ADDR_TO_STR(&INFINIBAD_ADDR_1));
/* Let's nest function calls in a stupid way. */
_cleanup_free_ char *t = NULL;
log_info("infiniband×3: %s\n%14s%s\n%14s%s",
HW_ADDR_TO_STR(&(const struct hw_addr_data){20}), "",
t = strdup(HW_ADDR_TO_STR(&INFINIBAD_ADDR_1)), "",
HW_ADDR_TO_STR(&(const struct hw_addr_data){20}));
const char *p;
/* Let's use a separate selection statement */
if ((p = HW_ADDR_TO_STR(&(const struct hw_addr_data){6})))
log_info("joint: %s, %s", s, p);
}
int main(int argc, char *argv[]) {
test_setup_logging(LOG_INFO);
test_HW_ADDR_TO_STRING();
return 0;
}

View File

@ -4,6 +4,15 @@
#include "macro.h" #include "macro.h"
#include "string-util.h" #include "string-util.h"
/* Do some basic checks on STRLEN() and DECIMAL_STR_MAX() */
assert_cc(STRLEN("xxx") == 3);
assert_cc(STRLEN("") == 0);
assert_cc(DECIMAL_STR_MAX(uint8_t) == 5);
assert_cc(DECIMAL_STR_MAX(int8_t) == 5);
assert_cc(DECIMAL_STR_MAX(uint64_t) == 22);
assert_cc(DECIMAL_STR_MAX(char) == 5);
assert_cc(CONST_MAX(DECIMAL_STR_MAX(int8_t), STRLEN("xxx")) == 5);
static void test_format_bytes_one(uint64_t val, bool trailing_B, const char *iec_with_p, const char *iec_without_p, static void test_format_bytes_one(uint64_t val, bool trailing_B, const char *iec_with_p, const char *iec_without_p,
const char *si_with_p, const char *si_without_p) { const char *si_with_p, const char *si_without_p) {
char buf[FORMAT_BYTES_MAX]; char buf[FORMAT_BYTES_MAX];

View File

@ -752,7 +752,6 @@ static void test_hashmap_many(void) {
for (j = 0; j < ELEMENTSOF(tests); j++) { for (j = 0; j < ELEMENTSOF(tests); j++) {
usec_t ts = now(CLOCK_MONOTONIC), n; usec_t ts = now(CLOCK_MONOTONIC), n;
char b[FORMAT_TIMESPAN_MAX];
assert_se(h = hashmap_new(tests[j].ops)); assert_se(h = hashmap_new(tests[j].ops));
@ -779,7 +778,7 @@ static void test_hashmap_many(void) {
hashmap_free(h); hashmap_free(h);
n = now(CLOCK_MONOTONIC); n = now(CLOCK_MONOTONIC);
log_info("test took %s", format_timespan(b, sizeof b, n - ts, 0)); log_info("test took %s", FORMAT_TIMESPAN(n - ts, 0));
} }
} }
@ -790,7 +789,6 @@ static void test_hashmap_free(void) {
Hashmap *h; Hashmap *h;
bool slow = slow_tests_enabled(); bool slow = slow_tests_enabled();
usec_t ts, n; usec_t ts, n;
char b[FORMAT_TIMESPAN_MAX];
unsigned n_entries = slow ? 1 << 20 : 240; unsigned n_entries = slow ? 1 << 20 : 240;
const struct { const struct {
@ -824,7 +822,7 @@ static void test_hashmap_free(void) {
hashmap_free(h); hashmap_free(h);
n = now(CLOCK_MONOTONIC); n = now(CLOCK_MONOTONIC);
log_info("%s test took %s", tests[j].title, format_timespan(b, sizeof b, n - ts, 0)); log_info("%s test took %s", tests[j].title, FORMAT_TIMESPAN(n - ts, 0));
assert_se(custom_counter == tests[j].expect_counter); assert_se(custom_counter == tests[j].expect_counter);
} }

View File

@ -9,7 +9,6 @@
#include "tests.h" #include "tests.h"
int main(int argc, char *argv[]) { int main(int argc, char *argv[]) {
char buf[CONST_MAX(FORMAT_TIMESPAN_MAX, FORMAT_BYTES_MAX)];
nsec_t nsec; nsec_t nsec;
uint64_t v; uint64_t v;
int r; int r;
@ -18,10 +17,10 @@ int main(int argc, char *argv[]) {
log_open(); log_open();
assert_se(procfs_cpu_get_usage(&nsec) >= 0); assert_se(procfs_cpu_get_usage(&nsec) >= 0);
log_info("Current system CPU time: %s", format_timespan(buf, sizeof(buf), nsec/NSEC_PER_USEC, 1)); log_info("Current system CPU time: %s", FORMAT_TIMESPAN(nsec/NSEC_PER_USEC, 1));
assert_se(procfs_memory_get_used(&v) >= 0); assert_se(procfs_memory_get_used(&v) >= 0);
log_info("Current memory usage: %s", format_bytes(buf, sizeof(buf), v)); log_info("Current memory usage: %s", FORMAT_BYTES(v));
assert_se(procfs_tasks_get_current(&v) >= 0); assert_se(procfs_tasks_get_current(&v) >= 0);
log_info("Current number of tasks: %" PRIu64, v); log_info("Current number of tasks: %" PRIu64, v);

View File

@ -335,8 +335,7 @@ static void test_format_timestamp(void) {
char buf[MAX(FORMAT_TIMESTAMP_MAX, FORMAT_TIMESPAN_MAX)]; char buf[MAX(FORMAT_TIMESTAMP_MAX, FORMAT_TIMESPAN_MAX)];
usec_t x, y; usec_t x, y;
random_bytes(&x, sizeof(x)); x = random_u64_range(2147483600 * USEC_PER_SEC) + 1;
x = x % (2147483600 * USEC_PER_SEC) + 1;
assert_se(format_timestamp(buf, sizeof(buf), x)); assert_se(format_timestamp(buf, sizeof(buf), x));
log_debug("%s", buf); log_debug("%s", buf);
@ -370,6 +369,26 @@ static void test_format_timestamp(void) {
} }
} }
static void test_FORMAT_TIMESTAMP(void) {
log_info("/* %s */", __func__);
for (unsigned i = 0; i < 100; i++) {
_cleanup_free_ char *buf;
usec_t x, y;
x = random_u64_range(2147483600 * USEC_PER_SEC) + 1;
/* strbuf() is to test the macro in an argument to a function call. */
assert_se(buf = strdup(FORMAT_TIMESTAMP(x)));
log_debug("%s", buf);
assert_se(parse_timestamp(buf, &y) >= 0);
assert_se(x / USEC_PER_SEC == y / USEC_PER_SEC);
char *t = FORMAT_TIMESTAMP(x);
assert_se(streq(t, buf));
}
}
static void test_format_timestamp_relative(void) { static void test_format_timestamp_relative(void) {
log_info("/* %s */", __func__); log_info("/* %s */", __func__);
@ -624,6 +643,7 @@ int main(int argc, char *argv[]) {
test_usec_sub_signed(); test_usec_sub_signed();
test_usec_sub_unsigned(); test_usec_sub_unsigned();
test_format_timestamp(); test_format_timestamp();
test_FORMAT_TIMESTAMP();
test_format_timestamp_relative(); test_format_timestamp_relative();
test_format_timestamp_utc(); test_format_timestamp_utc();
test_deserialize_dual_timestamp(); test_deserialize_dual_timestamp();

View File

@ -321,7 +321,6 @@ static void test_raw_clone(void) {
static void test_physical_memory(void) { static void test_physical_memory(void) {
uint64_t p; uint64_t p;
char buf[FORMAT_BYTES_MAX];
log_info("/* %s */", __func__); log_info("/* %s */", __func__);
@ -330,7 +329,7 @@ static void test_physical_memory(void) {
assert_se(p < UINT64_MAX); assert_se(p < UINT64_MAX);
assert_se(p % page_size() == 0); assert_se(p % page_size() == 0);
log_info("Memory: %s (%" PRIu64 ")", format_bytes(buf, sizeof(buf), p), p); log_info("Memory: %s (%" PRIu64 ")", FORMAT_BYTES(p), p);
} }
static void test_physical_memory_scale(void) { static void test_physical_memory_scale(void) {

View File

@ -51,9 +51,7 @@ cleanup:
} }
static void test_getcrtime(void) { static void test_getcrtime(void) {
_cleanup_close_ int fd = -1; _cleanup_close_ int fd = -1;
char ts[FORMAT_TIMESTAMP_MAX];
const char *vt; const char *vt;
usec_t usec, k; usec_t usec, k;
int r; int r;
@ -67,7 +65,7 @@ static void test_getcrtime(void) {
if (r < 0) if (r < 0)
log_debug_errno(r, "btime: %m"); log_debug_errno(r, "btime: %m");
else else
log_debug("btime: %s", format_timestamp(ts, sizeof(ts), usec)); log_debug("btime: %s", FORMAT_TIMESTAMP(usec));
k = now(CLOCK_REALTIME); k = now(CLOCK_REALTIME);

View File

@ -359,8 +359,6 @@ DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(ntp_leap, uint32_t);
REENABLE_WARNING; REENABLE_WARNING;
static int print_ntp_status_info(NTPStatusInfo *i) { static int print_ntp_status_info(NTPStatusInfo *i) {
char ts[FORMAT_TIMESPAN_MAX], jitter[FORMAT_TIMESPAN_MAX],
tmin[FORMAT_TIMESPAN_MAX], tmax[FORMAT_TIMESPAN_MAX];
usec_t delay, t14, t23, offset, root_distance; usec_t delay, t14, t23, offset, root_distance;
_cleanup_(table_unrefp) Table *table = NULL; _cleanup_(table_unrefp) Table *table = NULL;
bool offset_sign; bool offset_sign;
@ -407,9 +405,9 @@ static int print_ntp_status_info(NTPStatusInfo *i) {
return table_log_add_error(r); return table_log_add_error(r);
r = table_add_cell_stringf(table, NULL, "%s (min: %s; max %s)", r = table_add_cell_stringf(table, NULL, "%s (min: %s; max %s)",
format_timespan(ts, sizeof(ts), i->poll_interval, 0), FORMAT_TIMESPAN(i->poll_interval, 0),
format_timespan(tmin, sizeof(tmin), i->poll_min, 0), FORMAT_TIMESPAN(i->poll_min, 0),
format_timespan(tmax, sizeof(tmax), i->poll_max, 0)); FORMAT_TIMESPAN(i->poll_max, 0));
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
@ -468,7 +466,7 @@ static int print_ntp_status_info(NTPStatusInfo *i) {
return table_log_add_error(r); return table_log_add_error(r);
r = table_add_cell_stringf(table, NULL, "%s (%" PRIi32 ")", r = table_add_cell_stringf(table, NULL, "%s (%" PRIi32 ")",
format_timespan(ts, sizeof(ts), DIV_ROUND_UP((nsec_t) (exp2(i->precision) * NSEC_PER_SEC), NSEC_PER_USEC), 0), FORMAT_TIMESPAN(DIV_ROUND_UP((nsec_t) (exp2(i->precision) * NSEC_PER_SEC), NSEC_PER_USEC), 0),
i->precision); i->precision);
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
@ -478,8 +476,8 @@ static int print_ntp_status_info(NTPStatusInfo *i) {
return table_log_add_error(r); return table_log_add_error(r);
r = table_add_cell_stringf(table, NULL, "%s (max: %s)", r = table_add_cell_stringf(table, NULL, "%s (max: %s)",
format_timespan(ts, sizeof(ts), root_distance, 0), FORMAT_TIMESPAN(root_distance, 0),
format_timespan(tmax, sizeof(tmax), i->root_distance_max, 0)); FORMAT_TIMESPAN(i->root_distance_max, 0));
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
@ -489,15 +487,15 @@ static int print_ntp_status_info(NTPStatusInfo *i) {
r = table_add_cell_stringf(table, NULL, "%s%s", r = table_add_cell_stringf(table, NULL, "%s%s",
offset_sign ? "+" : "-", offset_sign ? "+" : "-",
format_timespan(ts, sizeof(ts), offset, 0)); FORMAT_TIMESPAN(offset, 0));
if (r < 0) if (r < 0)
return table_log_add_error(r); return table_log_add_error(r);
r = table_add_many(table, r = table_add_many(table,
TABLE_STRING, "Delay:", TABLE_STRING, "Delay:",
TABLE_STRING, format_timespan(ts, sizeof(ts), delay, 0), TABLE_STRING, FORMAT_TIMESPAN(delay, 0),
TABLE_STRING, "Jitter:", TABLE_STRING, "Jitter:",
TABLE_STRING, format_timespan(jitter, sizeof(jitter), i->jitter, 0), TABLE_STRING, FORMAT_TIMESPAN(i->jitter, 0),
TABLE_STRING, "Packet count:", TABLE_STRING, "Packet count:",
TABLE_UINT64, i->packet_count); TABLE_UINT64, i->packet_count);
if (r < 0) if (r < 0)
@ -717,7 +715,6 @@ static int print_timesync_property(const char *name, const char *expected_value,
case SD_BUS_TYPE_STRUCT: case SD_BUS_TYPE_STRUCT:
if (streq(name, "NTPMessage")) { if (streq(name, "NTPMessage")) {
_cleanup_(ntp_status_info_clear) NTPStatusInfo i = {}; _cleanup_(ntp_status_info_clear) NTPStatusInfo i = {};
char ts[FORMAT_TIMESPAN_MAX], stamp[FORMAT_TIMESTAMP_MAX];
r = map_ntp_message(NULL, NULL, m, NULL, &i); r = map_ntp_message(NULL, NULL, m, NULL, &i);
if (r < 0) if (r < 0)
@ -733,28 +730,21 @@ static int print_timesync_property(const char *name, const char *expected_value,
printf("{ Leap=%u, Version=%u, Mode=%u, Stratum=%u, Precision=%i,", printf("{ Leap=%u, Version=%u, Mode=%u, Stratum=%u, Precision=%i,",
i.leap, i.version, i.mode, i.stratum, i.precision); i.leap, i.version, i.mode, i.stratum, i.precision);
printf(" RootDelay=%s,", printf(" RootDelay=%s,", FORMAT_TIMESPAN(i.root_delay, 0));
format_timespan(ts, sizeof(ts), i.root_delay, 0)); printf(" RootDispersion=%s,", FORMAT_TIMESPAN(i.root_dispersion, 0));
printf(" RootDispersion=%s,",
format_timespan(ts, sizeof(ts), i.root_dispersion, 0));
if (i.stratum == 1) if (i.stratum == 1)
printf(" Reference=%s,", i.reference.str); printf(" Reference=%s,", i.reference.str);
else else
printf(" Reference=%" PRIX32 ",", be32toh(i.reference.val)); printf(" Reference=%" PRIX32 ",", be32toh(i.reference.val));
printf(" OriginateTimestamp=%s,", printf(" OriginateTimestamp=%s,", FORMAT_TIMESTAMP(i.origin));
format_timestamp(stamp, sizeof(stamp), i.origin)); printf(" ReceiveTimestamp=%s,", FORMAT_TIMESTAMP(i.recv));
printf(" ReceiveTimestamp=%s,", printf(" TransmitTimestamp=%s,", FORMAT_TIMESTAMP(i.trans));
format_timestamp(stamp, sizeof(stamp), i.recv)); printf(" DestinationTimestamp=%s,", FORMAT_TIMESTAMP(i.dest));
printf(" TransmitTimestamp=%s,",
format_timestamp(stamp, sizeof(stamp), i.trans));
printf(" DestinationTimestamp=%s,",
format_timestamp(stamp, sizeof(stamp), i.dest));
printf(" Ignored=%s PacketCount=%" PRIu64 ",", printf(" Ignored=%s PacketCount=%" PRIu64 ",",
yes_no(i.spike), i.packet_count); yes_no(i.spike), i.packet_count);
printf(" Jitter=%s }\n", printf(" Jitter=%s }\n", FORMAT_TIMESPAN(i.jitter, 0));
format_timespan(ts, sizeof(ts), i.jitter, 0));
return 1; return 1;

View File

@ -100,9 +100,7 @@ static int clock_state_update(
ClockState *sp, ClockState *sp,
sd_event *event) { sd_event *event) {
char buf[MAX((size_t)FORMAT_TIMESTAMP_MAX, STRLEN("unrepresentable"))];
struct timex tx = {}; struct timex tx = {};
const char * ts;
usec_t t; usec_t t;
int r; int r;
@ -149,10 +147,9 @@ static int clock_state_update(
if (tx.status & STA_NANO) if (tx.status & STA_NANO)
tx.time.tv_usec /= 1000; tx.time.tv_usec /= 1000;
t = timeval_load(&tx.time); t = timeval_load(&tx.time);
ts = format_timestamp_style(buf, sizeof(buf), t, TIMESTAMP_US_UTC);
if (!ts) log_info("adjtime state %d status %x time %s", sp->adjtime_state, tx.status,
strcpy(buf, "unrepresentable"); FORMAT_TIMESTAMP_STYLE(t, TIMESTAMP_US_UTC) ?: "unrepresentable");
log_info("adjtime state %d status %x time %s", sp->adjtime_state, tx.status, ts);
sp->has_watchfile = access("/run/systemd/timesync/synchronized", F_OK) >= 0; sp->has_watchfile = access("/run/systemd/timesync/synchronized", F_OK) >= 0;
if (sp->has_watchfile) if (sp->has_watchfile)

View File

@ -544,22 +544,20 @@ static bool needs_cleanup(
bool is_dir) { bool is_dir) {
if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) { if (FLAGS_SET(age_by, AGE_BY_MTIME) && mtime != NSEC_INFINITY && mtime >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
/* Follows spelling in stat(1). */ /* Follows spelling in stat(1). */
log_debug("%s \"%s\": modify time %s is too new.", log_debug("%s \"%s\": modify time %s is too new.",
is_dir ? "Directory" : "File", is_dir ? "Directory" : "File",
sub_path, sub_path,
format_timestamp_style(a, sizeof(a), mtime / NSEC_PER_USEC, TIMESTAMP_US)); FORMAT_TIMESTAMP_STYLE(mtime / NSEC_PER_USEC, TIMESTAMP_US));
return false; return false;
} }
if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) { if (FLAGS_SET(age_by, AGE_BY_ATIME) && atime != NSEC_INFINITY && atime >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("%s \"%s\": access time %s is too new.", log_debug("%s \"%s\": access time %s is too new.",
is_dir ? "Directory" : "File", is_dir ? "Directory" : "File",
sub_path, sub_path,
format_timestamp_style(a, sizeof(a), atime / NSEC_PER_USEC, TIMESTAMP_US)); FORMAT_TIMESTAMP_STYLE(atime / NSEC_PER_USEC, TIMESTAMP_US));
return false; return false;
} }
@ -569,21 +567,19 @@ static bool needs_cleanup(
* by default for directories, because we change it when deleting. * by default for directories, because we change it when deleting.
*/ */
if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) { if (FLAGS_SET(age_by, AGE_BY_CTIME) && ctime != NSEC_INFINITY && ctime >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("%s \"%s\": change time %s is too new.", log_debug("%s \"%s\": change time %s is too new.",
is_dir ? "Directory" : "File", is_dir ? "Directory" : "File",
sub_path, sub_path,
format_timestamp_style(a, sizeof(a), ctime / NSEC_PER_USEC, TIMESTAMP_US)); FORMAT_TIMESTAMP_STYLE(ctime / NSEC_PER_USEC, TIMESTAMP_US));
return false; return false;
} }
if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) { if (FLAGS_SET(age_by, AGE_BY_BTIME) && btime != NSEC_INFINITY && btime >= cutoff) {
char a[FORMAT_TIMESTAMP_MAX];
log_debug("%s \"%s\": birth time %s is too new.", log_debug("%s \"%s\": birth time %s is too new.",
is_dir ? "Directory" : "File", is_dir ? "Directory" : "File",
sub_path, sub_path,
format_timestamp_style(a, sizeof(a), btime / NSEC_PER_USEC, TIMESTAMP_US)); FORMAT_TIMESTAMP_STYLE(btime / NSEC_PER_USEC, TIMESTAMP_US));
return false; return false;
} }
@ -810,13 +806,12 @@ static int dir_cleanup(
finish: finish:
if (deleted) { if (deleted) {
char a[FORMAT_TIMESTAMP_MAX], m[FORMAT_TIMESTAMP_MAX];
struct timespec ts[2]; struct timespec ts[2];
log_debug("Restoring access and modification time on \"%s\": %s, %s", log_debug("Restoring access and modification time on \"%s\": %s, %s",
p, p,
format_timestamp_style(a, sizeof(a), self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US), FORMAT_TIMESTAMP_STYLE(self_atime_nsec / NSEC_PER_USEC, TIMESTAMP_US),
format_timestamp_style(m, sizeof(m), self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US)); FORMAT_TIMESTAMP_STYLE(self_mtime_nsec / NSEC_PER_USEC, TIMESTAMP_US));
timespec_store_nsec(ts + 0, self_atime_nsec); timespec_store_nsec(ts + 0, self_atime_nsec);
timespec_store_nsec(ts + 1, self_mtime_nsec); timespec_store_nsec(ts + 1, self_mtime_nsec);
@ -2503,7 +2498,6 @@ static char *age_by_to_string(AgeBy ab, bool is_dir) {
} }
static int clean_item_instance(Item *i, const char* instance) { static int clean_item_instance(Item *i, const char* instance) {
char timestamp[FORMAT_TIMESTAMP_MAX];
_cleanup_closedir_ DIR *d = NULL; _cleanup_closedir_ DIR *d = NULL;
STRUCT_STATX_DEFINE(sx); STRUCT_STATX_DEFINE(sx);
int mountpoint, r; int mountpoint, r;
@ -2562,7 +2556,7 @@ static int clean_item_instance(Item *i, const char* instance) {
log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s", log_debug("Cleanup threshold for %s \"%s\" is %s; age-by: %s%s",
mountpoint ? "mount point" : "directory", mountpoint ? "mount point" : "directory",
instance, instance,
format_timestamp_style(timestamp, sizeof(timestamp), cutoff, TIMESTAMP_US), FORMAT_TIMESTAMP_STYLE(cutoff, TIMESTAMP_US),
ab_f, ab_d); ab_f, ab_d);
} }

View File

@ -600,7 +600,6 @@ reenable:
static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) { static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = userdata; Spawn *spawn = userdata;
char timeout[FORMAT_TIMESPAN_MAX];
assert(spawn); assert(spawn);
@ -610,20 +609,19 @@ static int on_spawn_timeout(sd_event_source *s, uint64_t usec, void *userdata) {
log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing", log_device_error(spawn->device, "Spawned process '%s' ["PID_FMT"] timed out after %s, killing",
spawn->cmd, spawn->pid, spawn->cmd, spawn->pid,
format_timespan(timeout, sizeof(timeout), spawn->timeout_usec, USEC_PER_SEC)); FORMAT_TIMESPAN(spawn->timeout_usec, USEC_PER_SEC));
return 1; return 1;
} }
static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) { static int on_spawn_timeout_warning(sd_event_source *s, uint64_t usec, void *userdata) {
Spawn *spawn = userdata; Spawn *spawn = userdata;
char timeout[FORMAT_TIMESPAN_MAX];
assert(spawn); assert(spawn);
log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete", log_device_warning(spawn->device, "Spawned process '%s' ["PID_FMT"] is taking longer than %s to complete",
spawn->cmd, spawn->pid, spawn->cmd, spawn->pid,
format_timespan(timeout, sizeof(timeout), spawn->timeout_warn_usec, USEC_PER_SEC)); FORMAT_TIMESPAN(spawn->timeout_warn_usec, USEC_PER_SEC));
return 1; return 1;
} }
@ -1080,10 +1078,8 @@ void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_s
log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command); log_device_debug_errno(event->dev, r, "Failed to run built-in command \"%s\", ignoring: %m", command);
} else { } else {
if (event->exec_delay_usec > 0) { if (event->exec_delay_usec > 0) {
char buf[FORMAT_TIMESPAN_MAX];
log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.", log_device_debug(event->dev, "Delaying execution of \"%s\" for %s.",
command, format_timespan(buf, sizeof(buf), event->exec_delay_usec, USEC_PER_SEC)); command, FORMAT_TIMESPAN(event->exec_delay_usec, USEC_PER_SEC));
(void) usleep(event->exec_delay_usec); (void) usleep(event->exec_delay_usec);
} }

View File

@ -503,18 +503,16 @@ static int run(int argc, char *argv[]) {
n = now(CLOCK_MONOTONIC); n = now(CLOCK_MONOTONIC);
if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) { if (n >= usec_add(start_time, RUNTIME_MAX_USEC)) {
char buf[FORMAT_TIMESPAN_MAX];
log_debug("Exiting worker, ran for %s, that's enough.", log_debug("Exiting worker, ran for %s, that's enough.",
format_timespan(buf, sizeof(buf), usec_sub_unsigned(n, start_time), 0)); FORMAT_TIMESPAN(usec_sub_unsigned(n, start_time), 0));
break; break;
} }
if (last_busy_usec == USEC_INFINITY) if (last_busy_usec == USEC_INFINITY)
last_busy_usec = n; last_busy_usec = n;
else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) { else if (listen_idle_usec != USEC_INFINITY && n >= usec_add(last_busy_usec, listen_idle_usec)) {
char buf[FORMAT_TIMESPAN_MAX];
log_debug("Exiting worker, been idle for %s.", log_debug("Exiting worker, been idle for %s.",
format_timespan(buf, sizeof(buf), usec_sub_unsigned(n, last_busy_usec), 0)); FORMAT_TIMESPAN(usec_sub_unsigned(n, last_busy_usec), 0));
break; break;
} }