Skip to contentSkip to conversation

fs: multigrain timestamp redux

PATCH Superseded Jeff Layton 7 participants 37 messages Sep 14, 2024 – Oct 2, 2024

Subsystems (11)

v8 of 10 Superseded Latest is v10 →

lore
Share & tools
lore

Jeff Layton

author maintainer
#0 lore raw

v8 cover fs: multigrain timestamp redux

This is a fairly small update to the v7 set. It seems to pass all of my testing. Again, most of the changes are in the first two patches, but there are some differences in the patch that adds percpu counters as well.

Since the report of a performance regression came just before the merge window, it looks like we're going to have to wait for yet another release, so consider this version v6.13 material.

---
Changes in v8:
- drop the cookie handling from the new timekeeper interfaces
- add back the floor_swaps percpu counter
- comment updates and minor cleanups
- Link to v7: https://lore.kernel.org/r/[email protected]

Changes in v7:
- move the floor value handling into timekeeper for better performance
- Link to v6: https://lore.kernel.org/r/[email protected]

Changes in v6:
- Normalize timespec64 in inode_set_ctime_to_ts
- use DEFINE_PER_CPU counters for better vfs consistency
- skip ctime cmpxchg if the result means nothing will change
- add trace_ctime_xchg_skip to track skipped ctime updates
- use __print_flags in ctime_ns_xchg tracepoint
- Link to v5: https://lore.kernel.org/r/[email protected]

Changes in v5:
- refetch coarse time in coarse_ctime if not returning floor
- timestamp_truncate before swapping new ctime value into place
- track floor value as atomic64_t
- cleanups to Documentation file
- Link to v4: https://lore.kernel.org/r/[email protected]

Changes in v4:
- reordered tracepoint fields for better packing
- rework percpu counters again to also count fine grained timestamps
- switch to try_cmpxchg for better efficiency
- Link to v3: https://lore.kernel.org/r/[email protected]

Changes in v3:
- Drop the conversion of i_ctime fields to ktime_t, and use an unused bit of the i_ctime_nsec field as QUERIED flag.
- Better tracepoints for tracking floor and ctime updates
- Reworked percpu counters to be more useful
- Track floor as monotonic value, which eliminates clock-jump problem

Changes in v2:
- Added Documentation file
- Link to v1: https://lore.kernel.org/r/[email protected]

---
Jeff Layton (11):
timekeeping: move multigrain timestamp floor handling into timekeeper
fs: add infrastructure for multigrain timestamps
fs: have setattr_copy handle multigrain timestamps appropriately
fs: handle delegated timestamps in setattr_copy_mgtime
fs: tracepoints around multigrain timestamp events
fs: add percpu counters for significant multigrain timestamp events
Documentation: add a new file documenting multigrain timestamps
xfs: switch to multigrain timestamps
ext4: switch to multigrain timestamps
btrfs: convert to multigrain timestamps
tmpfs: add support for multigrain timestamps

 Documentation/filesystems/index.rst         |   1 +
 Documentation/filesystems/multigrain-ts.rst | 121 ++++++++++++
 fs/attr.c                                   |  60 +++++-
 fs/btrfs/file.c                             |  25 +--
 fs/btrfs/super.c                            |   3 +-
 fs/ext4/super.c                             |   2 +-
 fs/inode.c                                  | 278 +++++++++++++++++++++++++---
 fs/stat.c                                   |  42 ++++-
 fs/xfs/libxfs/xfs_trans_inode.c             |   6 +-
 fs/xfs/xfs_iops.c                           |  10 +-
 fs/xfs/xfs_super.c                          |   2 +-
 include/linux/fs.h                          |  36 +++-
 include/linux/timekeeping.h                 |   5 +
 include/trace/events/timestamp.h            | 124 +++++++++++++
 kernel/time/timekeeping.c                   |  83 +++++++++
 kernel/time/timekeeping_debug.c             |  12 ++
 kernel/time/timekeeping_internal.h          |   3 +
 mm/shmem.c                                  |   2 +-
 18 files changed, 742 insertions(+), 73 deletions(-)

---
base-commit: da3ea35007d0af457a0afc87e84fddaebc4e0b63
change-id: 20240913-mgtime-20c98bcda88e

Best regards,

Signature · 1 line
Jeff Layton <[email protected]>
author maintainer
#1 lore raw

PATCH v8 1/11 timekeeping: move multigrain timestamp floor handling into timekeeper

For multigrain timestamps, we must keep track of the latest timestamp that has ever been handed out, and never hand out a coarse time below that value.

Add a static singleton atomic64_t into timekeeper.c that we can use to keep track of the latest fine-grained time ever handed out. This is tracked as a monotonic ktime_t value to ensure that it isn't affected by clock jumps.

Add two new public interfaces:

- ktime_get_coarse_real_ts64_mg() fills a timespec64 with the later of the coarse-grained clock and the floor time

- ktime_get_real_ts64_mg() gets the fine-grained clock value, and tries to swap it into the floor. A timespec64 is filled with the result.

Since the floor is global, we take great pains to avoid updating it unless it's absolutely necessary. If we do the cmpxchg and find that the value has been updated since we fetched it, then we discard the fine-grained time that was fetched in favor of the recent update.

To maximize the window of this occurring when multiple tasks are racing to update the floor, ktime_get_coarse_real_ts64_mg returns a cookie value that represents the state of the floor tracking word, and ktime_get_real_ts64_mg accepts a cookie value that it uses as the "old" value when calling cmpxchg().

---
 include/linux/timekeeping.h |  4 +++
 kernel/time/timekeeping.c   | 82 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 86 insertions(+)
include/linux/timekeeping.h +4 -0
index fc12a9ba2c88..7aa85246c183 100644
@@ -45,6 +45,10 @@ extern void ktime_get_real_ts64(struct timespec64 *tv);
 extern void ktime_get_coarse_ts64(struct timespec64 *ts);
 extern void ktime_get_coarse_real_ts64(struct timespec64 *ts);
 
+/* Multigrain timestamp interfaces */
+extern void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts);
+extern void ktime_get_real_ts64_mg(struct timespec64 *ts);
+
 void getboottime64(struct timespec64 *ts);
 
 /*
kernel/time/timekeeping.c +82 -0

94 lines not on this page · raw message

Signature · 1 line
2.46.0
maintainer Acked-by on v8 1/11
#2 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 23 lines · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp that has ever been handed out, and never hand out a coarse time below that value.

Add a static singleton atomic64_t into timekeeper.c that we can use to keep track of the latest fine-grained time ever handed out. This is tracked as a monotonic ktime_t value to ensure that it isn't affected by clock jumps.

Add two new public interfaces:

- ktime_get_coarse_real_ts64_mg() fills a timespec64 with the later of the coarse-grained clock and the floor time

- ktime_get_real_ts64_mg() gets the fine-grained clock value, and tries to swap it into the floor. A timespec64 is filled with the result.

Since the floor is global, we take great pains to avoid updating it unless it's absolutely necessary. If we do the cmpxchg and find that the value has been updated since we fetched it, then we discard the fine-grained time that was fetched in favor of the recent update.

Quoted 5 lines

To maximize the window of this occurring when multiple tasks are racing to update the floor, ktime_get_coarse_real_ts64_mg returns a cookie value that represents the state of the floor tracking word, and ktime_get_real_ts64_mg accepts a cookie value that it uses as the "old" value when calling cmpxchg().

This last bit seems out of date.

Quoted 72 lines
---
 include/linux/timekeeping.h |  4 +++
 kernel/time/timekeeping.c   | 82 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 86 insertions(+)
include/linux/timekeeping.h +4 -0
index fc12a9ba2c88..7aa85246c183 100644
@@ -45,6 +45,10 @@ extern void ktime_get_real_ts64(struct timespec64 *tv);
 extern void ktime_get_coarse_ts64(struct timespec64 *ts);
 extern void ktime_get_coarse_real_ts64(struct timespec64 *ts);
 
+/* Multigrain timestamp interfaces */
+extern void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts);
+extern void ktime_get_real_ts64_mg(struct timespec64 *ts);
+
 void getboottime64(struct timespec64 *ts);
 
 /*
kernel/time/timekeeping.c +37 -0
index 5391e4167d60..16937242b904 100644
@@ -114,6 +114,13 @@ static struct tk_fast tk_fast_raw  ____cacheline_aligned = {
        .base[1] = FAST_TK_INIT,
 };
 
+/*
+ * This represents the latest fine-grained time that we have handed out as a
+ * timestamp on the system. Tracked as a monotonic ktime_t, and converted to the
+ * realtime clock on an as-needed basis.
+ */
+static __cacheline_aligned_in_smp atomic64_t mg_floor;
+
 static inline void tk_normalize_xtime(struct timekeeper *tk)
 {
        while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
@@ -2394,6 +2401,81 @@ void ktime_get_coarse_real_ts64(struct timespec64 *ts)
 }
 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
 
+/**
+ * ktime_get_coarse_real_ts64_mg - get later of coarse grained time or floor
+ * @ts: timespec64 to be filled
+ *
+ * Adjust floor to realtime and compare it to the coarse time. Fill
+ * @ts with the latest one. Note that this is a filesystem-specific
+ * interface and should be avoided outside of that context.
+ */
+void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
+{
+       struct timekeeper *tk = &tk_core.timekeeper;
+       u64 floor = atomic64_read(&mg_floor);
+       ktime_t f_real, offset, coarse;
+       unsigned int seq;
+
+       WARN_ON(timekeeping_suspended);
+
+       do {
+               seq = read_seqcount_begin(&tk_core.seq);
+               *ts = tk_xtime(tk);
+               offset = *offsets[TK_OFFS_REAL];
+       } while (read_seqcount_retry(&tk_core.seq, seq));
+
+       coarse = timespec64_to_ktime(*ts);
+       f_real = ktime_add(floor, offset);
+       if (ktime_after(f_real, coarse))
+               *ts = ktime_to_timespec64(f_real);
+}
+EXPORT_SYMBOL_GPL(ktime_get_coarse_real_ts64_mg);
+

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2443

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+/**
+ * ktime_get_real_ts64_mg - attempt to update floor value and return result
+ * @ts:                pointer to the timespec to be set
+ *
+ * Get a current monotonic fine-grained time value and attempt to swap
+ * it into the floor. @ts will be filled with the resulting floor value,
+ * regardless of the outcome of the swap. Note that this is a filesystem
+ * specific interface and should be avoided outside of that context.
+ */
+void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)

Still passing a cookie. It doesn't match the header definition, so I'm surprised this builds.

Quoted 24 lines
kernel/time/timekeeping.c +24 -0
+{
+       struct timekeeper *tk = &tk_core.timekeeper;
+       ktime_t old = atomic64_read(&mg_floor);
+       ktime_t offset, mono;
+       unsigned int seq;
+       u64 nsecs;
+
+       WARN_ON(timekeeping_suspended);
+
+       do {
+               seq = read_seqcount_begin(&tk_core.seq);
+
+               ts->tv_sec = tk->xtime_sec;
+               mono = tk->tkr_mono.base;
+               nsecs = timekeeping_get_ns(&tk->tkr_mono);
+               offset = *offsets[TK_OFFS_REAL];
+       } while (read_seqcount_retry(&tk_core.seq, seq));
+
+       mono = ktime_add_ns(mono, nsecs);
+
+       if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
+               ts->tv_nsec = 0;
+               timespec64_add_ns(ts, nsecs);
+       } else {

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2477

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+               /*
+                * Something has changed mg_floor since "old" was
+                * fetched. "old" has now been updated with the
+                * current value of mg_floor, so use that to return
+                * the current coarse floor value.
+                */
+               *ts = ktime_to_timespec64(ktime_add(old, offset));
+       }
+}
+EXPORT_SYMBOL_GPL(ktime_get_real_ts64_mg);

Other than those issues, I'm ok with it. Thanks again for working through my concerns!

Since I'm traveling for LPC soon, to save the next cycle, once the fixes above are sorted:

thanks
-john

author maintainer
#3 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 24 lines · John Stultz
Quoted 23 lines · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp that has ever been handed out, and never hand out a coarse time below that value.

Add a static singleton atomic64_t into timekeeper.c that we can use to keep track of the latest fine-grained time ever handed out. This is tracked as a monotonic ktime_t value to ensure that it isn't affected by clock jumps.

Add two new public interfaces:

- ktime_get_coarse_real_ts64_mg() fills a timespec64 with the later of the coarse-grained clock and the floor time

- ktime_get_real_ts64_mg() gets the fine-grained clock value, and tries to swap it into the floor. A timespec64 is filled with the result.

Since the floor is global, we take great pains to avoid updating it unless it's absolutely necessary. If we do the cmpxchg and find that the value has been updated since we fetched it, then we discard the fine-grained time that was fetched in favor of the recent update.

Quoted 8 lines
Quoted 5 lines

To maximize the window of this occurring when multiple tasks are racing to update the floor, ktime_get_coarse_real_ts64_mg returns a cookie value that represents the state of the floor tracking word, and ktime_get_real_ts64_mg accepts a cookie value that it uses as the "old" value when calling cmpxchg().

This last bit seems out of date.

Thanks. Dropped the last paragraph.

Quoted 77 lines
Quoted 77 lines
---
 include/linux/timekeeping.h |  4 +++
 kernel/time/timekeeping.c   | 82 +++++++++++++++++++++++++++++++++++++++++++++
 2 files changed, 86 insertions(+)
include/linux/timekeeping.h +4 -0
index fc12a9ba2c88..7aa85246c183 100644
@@ -45,6 +45,10 @@ extern void ktime_get_real_ts64(struct timespec64 *tv);
 extern void ktime_get_coarse_ts64(struct timespec64 *ts);
 extern void ktime_get_coarse_real_ts64(struct timespec64 *ts);
 
+/* Multigrain timestamp interfaces */
+extern void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts);
+extern void ktime_get_real_ts64_mg(struct timespec64 *ts);
+
 void getboottime64(struct timespec64 *ts);
 
 /*
kernel/time/timekeeping.c +42 -0
index 5391e4167d60..16937242b904 100644
@@ -114,6 +114,13 @@ static struct tk_fast tk_fast_raw  ____cacheline_aligned = {
        .base[1] = FAST_TK_INIT,
 };
 
+/*
+ * This represents the latest fine-grained time that we have handed out as a
+ * timestamp on the system. Tracked as a monotonic ktime_t, and converted to the
+ * realtime clock on an as-needed basis.
+ */
+static __cacheline_aligned_in_smp atomic64_t mg_floor;
+
 static inline void tk_normalize_xtime(struct timekeeper *tk)
 {
        while (tk->tkr_mono.xtime_nsec >= ((u64)NSEC_PER_SEC << tk->tkr_mono.shift)) {
@@ -2394,6 +2401,81 @@ void ktime_get_coarse_real_ts64(struct timespec64 *ts)
 }
 EXPORT_SYMBOL(ktime_get_coarse_real_ts64);
 
+/**
+ * ktime_get_coarse_real_ts64_mg - get later of coarse grained time or floor
+ * @ts: timespec64 to be filled
+ *
+ * Adjust floor to realtime and compare it to the coarse time. Fill
+ * @ts with the latest one. Note that this is a filesystem-specific
+ * interface and should be avoided outside of that context.
+ */
+void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
+{
+       struct timekeeper *tk = &tk_core.timekeeper;
+       u64 floor = atomic64_read(&mg_floor);
+       ktime_t f_real, offset, coarse;
+       unsigned int seq;
+
+       WARN_ON(timekeeping_suspended);
+
+       do {
+               seq = read_seqcount_begin(&tk_core.seq);
+               *ts = tk_xtime(tk);
+               offset = *offsets[TK_OFFS_REAL];
+       } while (read_seqcount_retry(&tk_core.seq, seq));
+
+       coarse = timespec64_to_ktime(*ts);
+       f_real = ktime_add(floor, offset);
+       if (ktime_after(f_real, coarse))
+               *ts = ktime_to_timespec64(f_real);
+}
+EXPORT_SYMBOL_GPL(ktime_get_coarse_real_ts64_mg);
+
+/**
+ * ktime_get_real_ts64_mg - attempt to update floor value and return result
+ * @ts:                pointer to the timespec to be set
+ *
+ * Get a current monotonic fine-grained time value and attempt to swap
Quoted 9 lines

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2443

Quoted 5 lines
kernel/time/timekeeping.c +5 -0
+ * it into the floor. @ts will be filled with the resulting floor value,
+ * regardless of the outcome of the swap. Note that this is a filesystem
+ * specific interface and should be avoided outside of that context.
+ */
+void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)

Still passing a cookie. It doesn't match the header definition, so I'm surprised this builds.

Yeah, I didn't see a warning when I built it. Luckily the extra parameter is ignored anyway, so it no harm. I've fixed that up in my tree.

Quoted 38 lines
Quoted 24 lines
kernel/time/timekeeping.c +24 -0
+{
+       struct timekeeper *tk = &tk_core.timekeeper;
+       ktime_t old = atomic64_read(&mg_floor);
+       ktime_t offset, mono;
+       unsigned int seq;
+       u64 nsecs;
+
+       WARN_ON(timekeeping_suspended);
+
+       do {
+               seq = read_seqcount_begin(&tk_core.seq);
+
+               ts->tv_sec = tk->xtime_sec;
+               mono = tk->tkr_mono.base;
+               nsecs = timekeeping_get_ns(&tk->tkr_mono);
+               offset = *offsets[TK_OFFS_REAL];
+       } while (read_seqcount_retry(&tk_core.seq, seq));
+
+       mono = ktime_add_ns(mono, nsecs);
+
+       if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
+               ts->tv_nsec = 0;
+               timespec64_add_ns(ts, nsecs);
+       } else {

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2477

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+               /*
+                * Something has changed mg_floor since "old" was
+                * fetched. "old" has now been updated with the
+                * current value of mg_floor, so use that to return
+                * the current coarse floor value.
+                */
+               *ts = ktime_to_timespec64(ktime_add(old, offset));
+       }
+}
+EXPORT_SYMBOL_GPL(ktime_get_real_ts64_mg);

Other than those issues, I'm ok with it. Thanks again for working through my concerns!

Quoted 4 lines

Since I'm traveling for LPC soon, to save the next cycle, once the fixes above are sorted:

Thanks for the review!

Signature · 1 line
Jeff Layton <[email protected]>
#4 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

In reply to Jeff Layton
Quoted 1 line · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp

What is a multgrain timestamp? Can you please describe the concept behind it? I'm not going to chase random documentation or whatever because change logs have to self contained.

And again 'we' do nothing. Describe the problem in technical terms and do not impersonate code.

Quoted 5 lines

To maximize the window of this occurring when multiple tasks are racing to update the floor, ktime_get_coarse_real_ts64_mg returns a cookie value that represents the state of the floor tracking word, and ktime_get_real_ts64_mg accepts a cookie value that it uses as the "old" value when calling cmpxchg().

Clearly:

Quoted 1 line

+void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)

Can you please get your act together?

Quoted 6 lines

+/**
+ * ktime_get_coarse_real_ts64_mg - get later of coarse grained time or floor
+ * @ts: timespec64 to be filled
+ *
+ * Adjust floor to realtime and compare it to the coarse time. Fill
+ * @ts with the latest one.

This explains nothing.

Quoted 6 lines

Note that this is a filesystem-specific
+ * interface and should be avoided outside of that context.
+ */

kernel/time/timekeeping.c +3 -0
+void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts)
+{
+	struct timekeeper *tk = &tk_core.timekeeper;

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2424

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+	u64 floor = atomic64_read(&mg_floor);
+	ktime_t f_real, offset, coarse;
+	unsigned int seq;
+
+	WARN_ON(timekeeping_suspended);
+
+	do {
+		seq = read_seqcount_begin(&tk_core.seq);
+		*ts = tk_xtime(tk);
+		offset = *offsets[TK_OFFS_REAL];

Why this indirection? What's wrong with using
tk_core.timekeeper.offs_real directly?

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2428

Quoted 4 lines
kernel/time/timekeeping.c +4 -0
+	} while (read_seqcount_retry(&tk_core.seq, seq));
+
+	coarse = timespec64_to_ktime(*ts);
+	f_real = ktime_add(floor, offset);

How is any of this synchronized against concurrent updates of the floor value or the offset? I'm failing to see anything which keeps this consistent. If this is magically consistent then it wants a big fat comment in the code which explains it.

Quoted 1 line

+void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)

What is this cookie argument for and how does that match the declaration?

Quoted 1 line

+extern void ktime_get_real_ts64_mg(struct timespec64 *ts);

This does not even build.

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2451

Quoted 8 lines
kernel/time/timekeeping.c +8 -0
+{
+	struct timekeeper *tk = &tk_core.timekeeper;
+	ktime_t old = atomic64_read(&mg_floor);
+	ktime_t offset, mono;
+	unsigned int seq;
+	u64 nsecs;
+
+	WARN_ON(timekeeping_suspended);

WARN_ON_ONCE() if at all.

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+	do {
+		seq = read_seqcount_begin(&tk_core.seq);
+
+		ts->tv_sec = tk->xtime_sec;
+		mono = tk->tkr_mono.base;
+		nsecs = timekeeping_get_ns(&tk->tkr_mono);
+		offset = *offsets[TK_OFFS_REAL];
+	} while (read_seqcount_retry(&tk_core.seq, seq));
+
+	mono = ktime_add_ns(mono, nsecs);

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2472

Quoted 10 lines
kernel/time/timekeeping.c +10 -0
+
+	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
+		ts->tv_nsec = 0;
+		timespec64_add_ns(ts, nsecs);
+	} else {
+		/*
+		 * Something has changed mg_floor since "old" was
+		 * fetched. "old" has now been updated with the
+		 * current value of mg_floor, so use that to return
+		 * the current coarse floor value.

'Something has changed' is a truly understandable technical explanation.

I'm not going to accept this voodoo which makes everyone scratch his head who wasn't involved in this.

Thanks,

tglx

#5 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 16 lines · Thomas Gleixner
Quoted 15 lines · Jeff Layton
kernel/time/timekeeping.c +15 -0
+	do {
+		seq = read_seqcount_begin(&tk_core.seq);
+
+		ts->tv_sec = tk->xtime_sec;
+		mono = tk->tkr_mono.base;
+		nsecs = timekeeping_get_ns(&tk->tkr_mono);
+		offset = *offsets[TK_OFFS_REAL];
+	} while (read_seqcount_retry(&tk_core.seq, seq));
+
+	mono = ktime_add_ns(mono, nsecs);
+
+	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
+		ts->tv_nsec = 0;
+		timespec64_add_ns(ts, nsecs);
+	} else {
Quoted 8 lines

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2472

Quoted 5 lines
kernel/time/timekeeping.c +5 -0
+		/*
+		 * Something has changed mg_floor since "old" was
+		 * fetched. "old" has now been updated with the
+		 * current value of mg_floor, so use that to return
+		 * the current coarse floor value.

'Something has changed' is a truly understandable technical explanation.

old = mg_floor
mono = T1;
mg_floor = mono
preemption

     do {
        mono = T2;
     }

     cmpxchg fails and the function returns a value based on T1

No?

Thanks,

tglx

author maintainer
#6 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 31 lines · Thomas Gleixner
Quoted 16 lines · Thomas Gleixner
Quoted 15 lines · Jeff Layton
kernel/time/timekeeping.c +15 -0
+	do {
+		seq = read_seqcount_begin(&tk_core.seq);
+
+		ts->tv_sec = tk->xtime_sec;
+		mono = tk->tkr_mono.base;
+		nsecs = timekeeping_get_ns(&tk->tkr_mono);
+		offset = *offsets[TK_OFFS_REAL];
+	} while (read_seqcount_retry(&tk_core.seq, seq));
+
+	mono = ktime_add_ns(mono, nsecs);
+
+	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
+		ts->tv_nsec = 0;
+		timespec64_add_ns(ts, nsecs);
+	} else {
Quoted 8 lines

kernel/time/timekeeping.c void ktime_get_coarse_real_ts64(struct timespec64 *ts) · line 2472

Quoted 5 lines
kernel/time/timekeeping.c +5 -0
+		/*
+		 * Something has changed mg_floor since "old" was
+		 * fetched. "old" has now been updated with the
+		 * current value of mg_floor, so use that to return
+		 * the current coarse floor value.

'Something has changed' is a truly understandable technical explanation.

old = mg_floor
mono = T1;
mg_floor = mono
preemption

Quoted 9 lines
     do {
        mono = T2;
     }

     cmpxchg fails and the function returns a value based on T1

No?

Packing for LPC, so I can't respond to all of these just now, but I will later. You're correct, but either outcome is OK.

The requirement is that we don't hand out any values that were below the floor at the time that the task entered the kernel. Since the time changed while the task was already inside the kernel, either T1 or T2 would be valid timestamps.

Signature · 1 line
Jeff Layton <[email protected]>
#7 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 19 lines · Jeff Layton
Quoted 8 lines · Thomas Gleixner
Quoted 2 lines

'Something has changed' is a truly understandable technical explanation.

old = mg_floor
mono = T1;
mg_floor = mono
preemption

Quoted 9 lines
     do {
        mono = T2;
     }

     cmpxchg fails and the function returns a value based on T1

No?

Quoted 7 lines

Packing for LPC, so I can't respond to all of these just now, but I will later. You're correct, but either outcome is OK.

The requirement is that we don't hand out any values that were below the floor at the time that the task entered the kernel. Since the time changed while the task was already inside the kernel, either T1 or T2 would be valid timestamps.

That really needs to be documented. A similar scenario exists vs. ktime_get_coarse_real_ts64_mg().

Thanks,

tglx

author maintainer
#8 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 23 lines · Thomas Gleixner
Quoted 22 lines · Jeff Layton
Quoted 8 lines · Thomas Gleixner
Quoted 2 lines

'Something has changed' is a truly understandable technical explanation.

old = mg_floor
mono = T1;
mg_floor = mono
preemption

Quoted 9 lines
     do {
        mono = T2;
     }

     cmpxchg fails and the function returns a value based on T1

No?

Packing for LPC, so I can't respond to all of these just now, but I will later. You're correct, but either outcome is OK.

Quoted 8 lines
Quoted 4 lines

The requirement is that we don't hand out any values that were below the floor at the time that the task entered the kernel. Since the time changed while the task was already inside the kernel, either T1 or T2 would be valid timestamps.

That really needs to be documented. A similar scenario exists vs. ktime_get_coarse_real_ts64_mg().

Yes.

I have the following section in the multigrain-ts.rst file that gets added in patch 7 of this series. I'll also plan to add some extra wording about how backward realtime clock jumps can affect ordering:

Inode Timestamp Ordering
========================

In addition to providing info about changes to individual files, file timestamps also serve an important purpose in applications like "make". These programs measure timestamps in order to determine whether source files might be newer than cached objects.

Userland applications like make can only determine ordering based on operational boundaries. For a syscall those are the syscall entry and exit points. For io_uring or nfsd operations, that's the request submission and response. In the case of concurrent operations, userland can make no determination about the order in which things will occur.

For instance, if a single thread modifies one file, and then another file in sequence, the second file must show an equal or later mtime than the first. The same is true if two threads are issuing similar operations that do not overlap in time.

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

Signature · 1 line
Jeff Layton <[email protected]>
#9 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 4 lines · Jeff Layton

On Mon, 2024-09-30 at 21:16 +0200, Thomas Gleixner wrote:
I have the following section in the multigrain-ts.rst file that gets added in patch 7 of this series. I'll also plan to add some extra wording about how backward realtime clock jumps can affect ordering:

Please also add comments into the code / interface.

Quoted 19 lines

Inode Timestamp Ordering
========================

In addition to providing info about changes to individual files, file timestamps also serve an important purpose in applications like "make". These programs measure timestamps in order to determine whether source files might be newer than cached objects.

Userland applications like make can only determine ordering based on operational boundaries. For a syscall those are the syscall entry and exit points. For io_uring or nfsd operations, that's the request submission and response. In the case of concurrent operations, userland can make no determination about the order in which things will occur.

For instance, if a single thread modifies one file, and then another file in sequence, the second file must show an equal or later mtime than the first. The same is true if two threads are issuing similar operations that do not overlap in time.

Quoted 4 lines

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

That makes me ask a question. Are the timestamps always taken in thread (syscall) context or can they be taken in other contexts (worker, [soft]interrupt, etc.) too?

Thanks,

tglx

author maintainer
#10 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 8 lines · Thomas Gleixner
Quoted 4 lines · Jeff Layton

On Mon, 2024-09-30 at 21:16 +0200, Thomas Gleixner wrote:
I have the following section in the multigrain-ts.rst file that gets added in patch 7 of this series. I'll also plan to add some extra wording about how backward realtime clock jumps can affect ordering:

Please also add comments into the code / interface.

Will do.

Quoted 19 lines
Quoted 19 lines

Inode Timestamp Ordering
========================

In addition to providing info about changes to individual files, file timestamps also serve an important purpose in applications like "make". These programs measure timestamps in order to determine whether source files might be newer than cached objects.

Userland applications like make can only determine ordering based on operational boundaries. For a syscall those are the syscall entry and exit points. For io_uring or nfsd operations, that's the request submission and response. In the case of concurrent operations, userland can make no determination about the order in which things will occur.

For instance, if a single thread modifies one file, and then another file in sequence, the second file must show an equal or later mtime than the first. The same is true if two threads are issuing similar operations that do not overlap in time.

Quoted 9 lines
Quoted 4 lines

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

That makes me ask a question. Are the timestamps always taken in thread (syscall) context or can they be taken in other contexts (worker, [soft]interrupt, etc.) too?

That's a good question.

The main place we do this is inode_set_ctime_current(). That is mostly called in the context of a syscall or similar sort of operation (io_uring, nfsd RPC request, etc.).

I certainly wouldn't rule out a workqueue job calling that function, but this is something we do while dirtying an inode, and that's not typically done in interrupt context.

Signature · 1 line
Jeff Layton <[email protected]>
#11 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 14 lines · Jeff Layton
Quoted 10 lines · Thomas Gleixner
Quoted 4 lines · Jeff Layton

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

That makes me ask a question. Are the timestamps always taken in thread (syscall) context or can they be taken in other contexts (worker, [soft]interrupt, etc.) too?

That's a good question.

Quoted 7 lines

The main place we do this is inode_set_ctime_current(). That is mostly called in the context of a syscall or similar sort of operation (io_uring, nfsd RPC request, etc.).

I certainly wouldn't rule out a workqueue job calling that function, but this is something we do while dirtying an inode, and that's not typically done in interrupt context.

The reason I'm asking is that if it's always syscall context, i.e. write() or io_uring()/RPC request etc., then you can avoid the whole global floor value dance and make it strictly per thread, which simplifies the exercise significantly.

But even if it's not syscall/thread context then the worker or io_uring state machine might just require to serialize against itself and not coordinate with something else. But what do I know.

Thanks,

tglx

author maintainer
#12 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 19 lines · Thomas Gleixner
Quoted 18 lines · Jeff Layton
Quoted 10 lines · Thomas Gleixner
Quoted 4 lines · Jeff Layton

If however, two threads have racing syscalls that overlap in time, then there is no such guarantee, and the second file may appear to have been modified before, after or at the same time as the first, regardless of which one was submitted first.

That makes me ask a question. Are the timestamps always taken in thread (syscall) context or can they be taken in other contexts (worker, [soft]interrupt, etc.) too?

That's a good question.

The main place we do this is inode_set_ctime_current(). That is mostly called in the context of a syscall or similar sort of operation (io_uring, nfsd RPC request, etc.).

Quoted 9 lines
Quoted 3 lines

I certainly wouldn't rule out a workqueue job calling that function, but this is something we do while dirtying an inode, and that's not typically done in interrupt context.

The reason I'm asking is that if it's always syscall context, i.e. write() or io_uring()/RPC request etc., then you can avoid the whole global floor value dance and make it strictly per thread, which simplifies the exercise significantly.

I'm not sure I follow what you're proposing here.

Consider two threads doing writes serially to different files. IOW, the second thread enters the write() syscall after the first thread returns from its write(). In that situation, the second timestamp mustn't appear to be earlier than the first (assuming no backward clock jump, of course).

How would we ensure that with only per-thread structures?

Quoted 3 lines

But even if it's not syscall/thread context then the worker or io_uring state machine might just require to serialize against itself and not coordinate with something else. But what do I know.

Signature · 1 line
Jeff Layton <[email protected]>
#13 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 13 lines · Jeff Layton
Quoted 9 lines · Thomas Gleixner
Quoted 3 lines

I certainly wouldn't rule out a workqueue job calling that function, but this is something we do while dirtying an inode, and that's not typically done in interrupt context.

The reason I'm asking is that if it's always syscall context, i.e. write() or io_uring()/RPC request etc., then you can avoid the whole global floor value dance and make it strictly per thread, which simplifies the exercise significantly.

I'm not sure I follow what you're proposing here.

Quoted 7 lines

Consider two threads doing writes serially to different files. IOW, the second thread enters the write() syscall after the first thread returns from its write(). In that situation, the second timestamp mustn't appear to be earlier than the first (assuming no backward clock jump, of course).

How would we ensure that with only per-thread structures?

Bah. Right. Ignore my sleep deprived rambling.

author maintainer
#14 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 20 lines · Thomas Gleixner
Quoted 19 lines · Jeff Layton
Quoted 9 lines · Thomas Gleixner
Quoted 3 lines

I certainly wouldn't rule out a workqueue job calling that function, but this is something we do while dirtying an inode, and that's not typically done in interrupt context.

The reason I'm asking is that if it's always syscall context, i.e. write() or io_uring()/RPC request etc., then you can avoid the whole global floor value dance and make it strictly per thread, which simplifies the exercise significantly.

I'm not sure I follow what you're proposing here.

Consider two threads doing writes serially to different files. IOW, the second thread enters the write() syscall after the first thread returns from its write(). In that situation, the second timestamp mustn't appear to be earlier than the first (assuming no backward clock jump, of course).

Quoted 3 lines
Quoted 1 line

How would we ensure that with only per-thread structures?

Bah. Right. Ignore my sleep deprived rambling.

No worries. My one big takeaway from working on all of this is that anything dealing with clocks and time is just difficult to conceptualize.

Could I trouble you for an Acked-by on this patch? I think this series should probably go in via Christian's tree, but I don't think he wants to merge it without an explicit ack from the timekeeping maintainers.

Thanks again for the review!

Signature · 1 line
Jeff Layton <[email protected]>
author maintainer
#15 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

In reply to Thomas Gleixner
Quoted 10 lines · Thomas Gleixner
Quoted 1 line · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp

What is a multgrain timestamp? Can you please describe the concept behind it? I'm not going to chase random documentation or whatever because change logs have to self contained.

And again 'we' do nothing. Describe the problem in technical terms and do not impersonate code.

Hi Thomas!

Sorry for the delay in responding. I'll try to summarize below, but I'll also note that patch #7 in the v8 series adds a file to Documentation/ that explains this in a bit more depth:

Currently the kernel always stamps files (mtime, ctime, etc.) using the coarse-grained clock. This is usually a good thing, since it reduces the number of metadata updates, but means that you can't reliably use file timestamps to detect whether there have been changes to the file since it was last checked. This is particularly a problem for NFSv3 clients, which use timestamps to know when to invalidate their pagecache for an inode [1].

The idea is to allow the kernel to use fine-grained timestamps (mtime and ctime) on files when they are under direct observation. When a task does a ->getattr against an inode for STATX_MTIME or STATX_CTIME, a flag is set in the inode that tells the kernel to use the fine-grained clock for the timestamp update iff the current coarse-grained clock value would not cause a change to the mtime/ctime.

This works, but there is a problem:

It's possible for one inode to get a fine-grained timestamp, and then another to get a coarse-grained timestamp. If this happens within a single coarse-grained timer tick, then the files may appear to have been modified in reverse order, which breaks POSIX guarantees (and obscure programs like "make").

The fix for this is to establish a floor value for the coarse-grained clock. When stamping a file with a fine-grained timestamp, we update the floor value with the current monotonic time (using cmpxchg). Then later, when a coarse-grained timestamp is requested, check whether the floor is later than the current coarse-grained time. If it is, then the kernel will return the floor value (converted to realtime) instead of the current coarse-grained clock. That allows us to maintain the ordering guarantees.

My original implementation of this tracked the floor value in fs/inode.c (also using cmpxchg), but that caused a performance regression, mostly due to multiple calls into the timekeeper functions with seqcount loops. By adding the floor to the timekeeper we can get that back down to 1 seqcount loop.

Let me know if you have more questions about this, or suggestions about how to do this better. The timekeeping code is not my area of expertise (obviously) so I'm open to doing this a better way if there is one.

Thanks for the review so far!

[1]: NFSv4 mandates an opaque change attribute (usually using inode->i_version), but only some filesystems have a proper implementation of it (XFS being the notable exception). For the others, we end up using the ctime to generate a change attribute, which means that NFSv4 has the same problem on those filesystems. i_version also doesn't help NFSv3 clients and servers.

Signature · 1 line
Jeff Layton <[email protected]>
#16 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 15 lines · Jeff Layton

The fix for this is to establish a floor value for the coarse-grained clock. When stamping a file with a fine-grained timestamp, we update the floor value with the current monotonic time (using cmpxchg). Then later, when a coarse-grained timestamp is requested, check whether the floor is later than the current coarse-grained time. If it is, then the kernel will return the floor value (converted to realtime) instead of the current coarse-grained clock. That allows us to maintain the ordering guarantees.

My original implementation of this tracked the floor value in fs/inode.c (also using cmpxchg), but that caused a performance regression, mostly due to multiple calls into the timekeeper functions with seqcount loops. By adding the floor to the timekeeper we can get that back down to 1 seqcount loop.

Quoted 3 lines

Let me know if you have more questions about this, or suggestions about how to do this better. The timekeeping code is not my area of expertise (obviously) so I'm open to doing this a better way if there is one.

The comments I made about races and the clock_settime() inconsistency vs. the change log aside, I don't see room for improvement there.

What worries me is the atomic_cmpxchg() under contention on large machines, but as it is not a cmpxchg() loop it might be not completely horrible.

Thanks,

tglx

author maintainer
#17 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 20 lines · Thomas Gleixner
Quoted 15 lines · Jeff Layton

The fix for this is to establish a floor value for the coarse-grained clock. When stamping a file with a fine-grained timestamp, we update the floor value with the current monotonic time (using cmpxchg). Then later, when a coarse-grained timestamp is requested, check whether the floor is later than the current coarse-grained time. If it is, then the kernel will return the floor value (converted to realtime) instead of the current coarse-grained clock. That allows us to maintain the ordering guarantees.

My original implementation of this tracked the floor value in fs/inode.c (also using cmpxchg), but that caused a performance regression, mostly due to multiple calls into the timekeeper functions with seqcount loops. By adding the floor to the timekeeper we can get that back down to 1 seqcount loop.

Quoted 3 lines

Let me know if you have more questions about this, or suggestions about how to do this better. The timekeeping code is not my area of expertise (obviously) so I'm open to doing this a better way if there is one.

Quoted 7 lines

The comments I made about races and the clock_settime() inconsistency vs. the change log aside, I don't see room for improvement there.

What worries me is the atomic_cmpxchg() under contention on large machines, but as it is not a cmpxchg() loop it might be not completely horrible.

Thanks for taking a look.

The code does try to avoid requesting a fine-grained timestamp unless there is no other option. In practice, that means that a write()+stat()+write() has to occur within the same coarse-grained timer tick. That obviously does happen, but I'm hoping it's not very frequent on real-world workloads.

The main place where we see a performance hit from this set is the will-it-scale pipe test, which does 1-byte writes and reads on a pipe as fast as possible.

The previous patchset tracked the floor inside fs/inode.c, and each timestamp update on the pipe inode could make multiple trips into the timekeeper seqcount loops. That added extra barriers and slowed things down.

This patchset moves the code into the timekeeper, which means only a single barrier. That gets the cost down, but it's not entirely free. There is some small cost to dealing with the floor, regardless.

Signature · 1 line
Jeff Layton <[email protected]>
#18 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

In reply to Jeff Layton
Quoted 3 lines · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp that has ever been handed out, and never hand out a coarse time below that value.

How is that correct when the clock is off by an hour and then set back to the correct value? Then you'd get the same stale timestamp for an hour unless something invokes ktime_get_real_ts64_mg() which will set the "latest" timestamp back to a time before the previous one.

Quoted 4 lines

Add a static singleton atomic64_t into timekeeper.c that we can use to keep track of the latest fine-grained time ever handed out. This is tracked as a monotonic ktime_t value to ensure that it isn't affected by clock jumps.

That's just wishful thinking.

ktime_get_real_ts64_mg(ts)
ts = Tmono_1 + offset_1; // TReal_1
floor = Tmono_1;

                                // newtime < TReal_1                                
                                clock_settime(REALTIME, newtime);
                                   xtime = newtime; // TReal_2
                                   offset_2 = offset_1 + Treal_2 - TReal(now);
                                   --> offset_2 < offset_1

ktime_get_coarse_real_ts64_mg(ts)

    ts = tk_xtime();       // TReal_2
    offs = offset_2;

    if (Tmono_1 + offset_2 > ts)
       ts = Tmono_1 + offset_2; // Not taken

So this returns T_Real_2 because

    offset_2 < offset_1

and therefore

    Tmono_1 + offset_2 < TReal_2

so the returned time will jump backwards vs. TReal_1 as it should because that's the actual time, no?

So if that's the intended behaviour then the changelog is misleading at best.

If the intention is to never return a value < TReal_1 then this does not work. You can make it work by using the Realtime timestamp as floor, but that'd be more than questionable vs. clock_settime() making the clock go backwards.

Thanks,

tglx

author maintainer
#19 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 46 lines · Thomas Gleixner
Quoted 3 lines · Jeff Layton

For multigrain timestamps, we must keep track of the latest timestamp that has ever been handed out, and never hand out a coarse time below that value.

How is that correct when the clock is off by an hour and then set back to the correct value? Then you'd get the same stale timestamp for an hour unless something invokes ktime_get_real_ts64_mg() which will set the "latest" timestamp back to a time before the previous one.

Quoted 4 lines

Add a static singleton atomic64_t into timekeeper.c that we can use to keep track of the latest fine-grained time ever handed out. This is tracked as a monotonic ktime_t value to ensure that it isn't affected by clock jumps.

That's just wishful thinking.

ktime_get_real_ts64_mg(ts)
ts = Tmono_1 + offset_1; // TReal_1
floor = Tmono_1;

                                // newtime < TReal_1                                
                                clock_settime(REALTIME, newtime);
                                   xtime = newtime; // TReal_2
                                   offset_2 = offset_1 + Treal_2 - TReal(now);
                                   --> offset_2 < offset_1

ktime_get_coarse_real_ts64_mg(ts)

    ts = tk_xtime();       // TReal_2
    offs = offset_2;

    if (Tmono_1 + offset_2 > ts)
       ts = Tmono_1 + offset_2; // Not taken

So this returns T_Real_2 because

    offset_2 < offset_1

and therefore

    Tmono_1 + offset_2 < TReal_2

so the returned time will jump backwards vs. TReal_1 as it should because that's the actual time, no?

Quoted 8 lines

So if that's the intended behaviour then the changelog is misleading at best.

If the intention is to never return a value < TReal_1 then this does not work. You can make it work by using the Realtime timestamp as floor, but that'd be more than questionable vs. clock_settime() making the clock go backwards.

That is the intended behavior and I'll plan to fix the changelog to clarify this point:

If someone jumps the realtime clock backward by a large value, then the realtime timestamp _can_ appear to go backward. This is a problem today even without this patchset.

If two files get stamped and a realtime clock jump backward happens in between them, all bets are off as to which one will appear to have been modified first. I don't think that is something we can reasonably prevent, since we must stamp files according to the realtime clock.

The main thing I'm trying to prevent is the timestamps being misordered in the absence of such a clock jump. Without tracking the floor as I am here, that's a possibility.

Signature · 1 line
Jeff Layton <[email protected]>
#20 lore raw

Re: [PATCH v8 01/11] timekeeping: move multigrain timestamp floor handling into timekeeper

Quoted 10 lines · Jeff Layton
Quoted 2 lines · Thomas Gleixner

So if that's the intended behaviour then the changelog is misleading at best.

That is the intended behavior and I'll plan to fix the changelog to clarify this point:

If someone jumps the realtime clock backward by a large value, then the realtime timestamp _can_ appear to go backward. This is a problem today even without this patchset.

Correct.

Quoted 4 lines

If two files get stamped and a realtime clock jump backward happens in between them, all bets are off as to which one will appear to have been modified first. I don't think that is something we can reasonably prevent, since we must stamp files according to the realtime clock.

True. I just was utterly confused about the changelog.

Quoted 3 lines

The main thing I'm trying to prevent is the timestamps being misordered in the absence of such a clock jump. Without tracking the floor as I am here, that's a possibility.

Correct.

author maintainer
#21 lore raw

PATCH v8 2/11 fs: add infrastructure for multigrain timestamps

In reply to Jeff Layton

The VFS has always used coarse-grained timestamps when updating the ctime and mtime after a change. This has the benefit of allowing filesystems to optimize away a lot metadata updates, down to around 1 per jiffy, even when a file is under heavy writes.

Unfortunately, this has always been an issue when we're exporting via NFSv3, which relies on timestamps to validate caches. A lot of changes can happen in a jiffy, so timestamps aren't sufficient to help the client decide when to invalidate the cache. Even with NFSv4, a lot of exported filesystems don't properly support a change attribute and are subject to the same problems with timestamp granularity. Other applications have similar issues with timestamps (e.g backup applications).

If we were to always use fine-grained timestamps, that would improve the situation, but that becomes rather expensive, as the underlying filesystem would have to log a lot more metadata updates.

What we need is a way to only use fine-grained timestamps when they are being actively queried. Use the (unused) top bit in inode->i_ctime_nsec as a flag that indicates whether the current timestamps have been queried via stat() or the like. When it's set, we allow the kernel to use a fine-grained timestamp iff it's necessary to make the ctime show a different value.

This solves the problem of being able to distinguish the timestamp between updates, but introduces a new problem: it's now possible for a file being changed to get a fine-grained timestamp. A file that is altered just a bit later can then get a coarse-grained one that appears older than the earlier fine-grained time. This violates timestamp ordering guarantees.

To remedy this, keep a global monotonic atomic64_t value that acts as a timestamp floor. When we go to stamp a file, we first get the latter of the current floor value and the current coarse-grained time. If the inode ctime hasn't been queried then we just attempt to stamp it with that value.

If it has been queried, then first see whether the current coarse time is later than the existing ctime. If it is, then we accept that value. If it isn't, then we get a fine-grained timestamp.

Filesystems can opt into this by setting the FS_MGTIME fstype flag. Others should be unaffected (other than being subject to the same floor value as multigrain filesystems).

---
 fs/inode.c         | 137 +++++++++++++++++++++++++++++++++++++++++++----------
 fs/stat.c          |  39 ++++++++++++++-
 include/linux/fs.h |  34 +++++++++----
 3 files changed, 175 insertions(+), 35 deletions(-)
fs/inode.c +112 -25
index 10c4619faeef..232b474218e6 100644
@@ -2172,19 +2172,58 @@ int file_remove_privs(struct file *file)
 }
 EXPORT_SYMBOL(file_remove_privs);
 
+/**
+ * current_time - Return FS time (possibly fine-grained)
+ * @inode: inode.
+ *
+ * Return the current time truncated to the time granularity supported by
+ * the fs, as suitable for a ctime/mtime change. If the ctime is flagged
+ * as having been QUERIED, get a fine-grained timestamp, but don't update
+ * the floor.
+ *
+ * For a multigrain inode, this is effectively an estimate of the timestamp
+ * that a file would receive. An actual update must go through
+ * inode_set_ctime_current().
+ */
+struct timespec64 current_time(struct inode *inode)
+{
+	struct timespec64 now;
+	u32 cns;
+
+	ktime_get_coarse_real_ts64_mg(&now);
+
+	if (!is_mgtime(inode))
+		goto out;
+
+	/* If nothing has queried it, then coarse time is fine */
+	cns = smp_load_acquire(&inode->i_ctime_nsec);
+	if (cns & I_CTIME_QUERIED) {
+		/*
+		 * If there is no apparent change, then get a fine-grained
+		 * timestamp.
+		 */
+		if (now.tv_nsec == (cns & ~I_CTIME_QUERIED))
+			ktime_get_real_ts64(&now);
+	}
+out:
+	return timestamp_truncate(now, inode);
+}
+EXPORT_SYMBOL(current_time);
+
 static int inode_needs_update_time(struct inode *inode)
 {
+	struct timespec64 now, ts;
 	int sync_it = 0;
-	struct timespec64 now = current_time(inode);
-	struct timespec64 ts;
 
 	/* First try to exhaust all avenues to not sync */
 	if (IS_NOCMTIME(inode))
 		return 0;
 
+	now = current_time(inode);
+
 	ts = inode_get_mtime(inode);
 	if (!timespec64_equal(&ts, &now))
-		sync_it = S_MTIME;
+		sync_it |= S_MTIME;
 
 	ts = inode_get_ctime(inode);
 	if (!timespec64_equal(&ts, &now))
@@ -2562,6 +2601,15 @@ void inode_nohighmem(struct inode *inode)
 }
 EXPORT_SYMBOL(inode_nohighmem);
 
+struct timespec64 inode_set_ctime_to_ts(struct inode *inode, struct timespec64 ts)
+{
+	set_normalized_timespec64(&ts, ts.tv_sec, ts.tv_nsec);
+	inode->i_ctime_sec = ts.tv_sec;
+	inode->i_ctime_nsec = ts.tv_nsec;
+	return ts;
+}
+EXPORT_SYMBOL(inode_set_ctime_to_ts);
+
 /**
  * timestamp_truncate - Truncate timespec to a granularity
  * @t: Timespec
@@ -2594,36 +2642,75 @@ struct timespec64 timestamp_truncate(struct timespec64 t, struct inode *inode)
 EXPORT_SYMBOL(timestamp_truncate);
 
 /**
- * current_time - Return FS time
- * @inode: inode.
+ * inode_set_ctime_current - set the ctime to current_time
+ * @inode: inode
  *
- * Return the current time truncated to the time granularity supported by
- * the fs.
+ * Set the inode's ctime to the current value for the inode. Returns the
+ * current value that was assigned. If this is not a multigrain inode, then we
+ * set it to the later of the coarse time and floor value.
  *
- * Note that inode and inode->sb cannot be NULL.
- * Otherwise, the function warns and returns time without truncation.
+ * If it is multigrain, then we first see if the coarse-grained timestamp is
+ * distinct from what we have. If so, then we'll just use that. If we have to
+ * get a fine-grained timestamp, then do so, and try to swap it into the floor.
+ * We accept the new floor value regardless of the outcome of the cmpxchg.
+ * After that, we try to swap the new value into i_ctime_nsec. Again, we take
+ * the resulting ctime, regardless of the outcome of the swap.
  */
-struct timespec64 current_time(struct inode *inode)
+struct timespec64 inode_set_ctime_current(struct inode *inode)
 {
 	struct timespec64 now;
+	u32 cns, cur;
 
-	ktime_get_coarse_real_ts64(&now);
-	return timestamp_truncate(now, inode);
-}
-EXPORT_SYMBOL(current_time);
+	ktime_get_coarse_real_ts64_mg(&now);
+	now = timestamp_truncate(now, inode);
 
-/**
- * inode_set_ctime_current - set the ctime to current_time
- * @inode: inode
- *
- * Set the inode->i_ctime to the current value for the inode. Returns
- * the current value that was assigned to i_ctime.
- */
-struct timespec64 inode_set_ctime_current(struct inode *inode)
-{
-	struct timespec64 now = current_time(inode);
+	/* Just return that if this is not a multigrain fs */
+	if (!is_mgtime(inode)) {
+		inode_set_ctime_to_ts(inode, now);
+		goto out;
+	}
 
-	inode_set_ctime_to_ts(inode, now);
+	/*
+	 * We only need a fine-grained time if someone has queried it,
+	 * and the current coarse grained time isn't later than what's
+	 * already there.
+	 */
+	cns = smp_load_acquire(&inode->i_ctime_nsec);
+	if (cns & I_CTIME_QUERIED) {
+		struct timespec64 ctime = { .tv_sec = inode->i_ctime_sec,
+					    .tv_nsec = cns & ~I_CTIME_QUERIED };
+
+		if (timespec64_compare(&now, &ctime) <= 0) {
+			ktime_get_real_ts64_mg(&now);
+			now = timestamp_truncate(now, inode);
+		}
+	}
+
+	/* No need to cmpxchg if it's exactly the same */
+	if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec)
+		goto out;
+	cur = cns;
+retry:
+	/* Try to swap the nsec value into place. */
+	if (try_cmpxchg(&inode->i_ctime_nsec, &cur, now.tv_nsec)) {
+		/* If swap occurred, then we're (mostly) done */
+		inode->i_ctime_sec = now.tv_sec;
+	} else {
+		/*
+		 * Was the change due to someone marking the old ctime QUERIED?
+		 * If so then retry the swap. This can only happen once since
+		 * the only way to clear I_CTIME_QUERIED is to stamp the inode
+		 * with a new ctime.
+		 */
+		if (!(cns & I_CTIME_QUERIED) && (cns | I_CTIME_QUERIED) == cur) {
+			cns = cur;
+			goto retry;
+		}
+		/* Otherwise, keep the existing ctime */
+		now.tv_sec = inode->i_ctime_sec;
+		now.tv_nsec = cur & ~I_CTIME_QUERIED;
+	}
+out:
 	return now;
 }
 EXPORT_SYMBOL(inode_set_ctime_current);
fs/stat.c +37 -2
index 89ce1be56310..a449626fd460 100644
@@ -26,6 +26,35 @@
 #include "internal.h"
 #include "mount.h"
 
+/**
+ * fill_mg_cmtime - Fill in the mtime and ctime and flag ctime as QUERIED
+ * @stat: where to store the resulting values
+ * @request_mask: STATX_* values requested
+ * @inode: inode from which to grab the c/mtime
+ *
+ * Given @inode, grab the ctime and mtime out if it and store the result
+ * in @stat. When fetching the value, flag it as QUERIED (if not already)
+ * so the next write will record a distinct timestamp.
+ */
+void fill_mg_cmtime(struct kstat *stat, u32 request_mask, struct inode *inode)
+{
+	atomic_t *pcn = (atomic_t *)&inode->i_ctime_nsec;
+
+	/* If neither time was requested, then don't report them */
+	if (!(request_mask & (STATX_CTIME|STATX_MTIME))) {
+		stat->result_mask &= ~(STATX_CTIME|STATX_MTIME);
+		return;
+	}
+
+	stat->mtime = inode_get_mtime(inode);
+	stat->ctime.tv_sec = inode->i_ctime_sec;
+	stat->ctime.tv_nsec = (u32)atomic_read(pcn);
+	if (!(stat->ctime.tv_nsec & I_CTIME_QUERIED))
+		stat->ctime.tv_nsec = ((u32)atomic_fetch_or(I_CTIME_QUERIED, pcn));
+	stat->ctime.tv_nsec &= ~I_CTIME_QUERIED;
+}
+EXPORT_SYMBOL(fill_mg_cmtime);
+
 /**
  * generic_fillattr - Fill in the basic attributes from the inode struct
  * @idmap:		idmap of the mount the inode was found from
@@ -58,8 +87,14 @@ void generic_fillattr(struct mnt_idmap *idmap, u32 request_mask,
 	stat->rdev = inode->i_rdev;
 	stat->size = i_size_read(inode);
 	stat->atime = inode_get_atime(inode);
-	stat->mtime = inode_get_mtime(inode);
-	stat->ctime = inode_get_ctime(inode);
+
+	if (is_mgtime(inode)) {
+		fill_mg_cmtime(stat, request_mask, inode);
+	} else {
+		stat->ctime = inode_get_ctime(inode);
+		stat->mtime = inode_get_mtime(inode);
+	}
+
 	stat->blksize = i_blocksize(inode);
 	stat->blocks = inode->i_blocks;
 
include/linux/fs.h +26 -8
index 6ca11e241a24..eff688e75f2f 100644
@@ -1613,6 +1613,17 @@ static inline struct timespec64 inode_set_mtime(struct inode *inode,
 	return inode_set_mtime_to_ts(inode, ts);
 }
 
+/*
+ * Multigrain timestamps
+ *
+ * Conditionally use fine-grained ctime and mtime timestamps when there
+ * are users actively observing them via getattr. The primary use-case
+ * for this is NFS clients that use the ctime to distinguish between
+ * different states of the file, and that are often fooled by multiple
+ * operations that occur in the same coarse-grained timer tick.
+ */
+#define I_CTIME_QUERIED		((u32)BIT(31))
+
 static inline time64_t inode_get_ctime_sec(const struct inode *inode)
 {
 	return inode->i_ctime_sec;
@@ -1620,7 +1631,7 @@ static inline time64_t inode_get_ctime_sec(const struct inode *inode)
 
 static inline long inode_get_ctime_nsec(const struct inode *inode)
 {
-	return inode->i_ctime_nsec;
+	return inode->i_ctime_nsec & ~I_CTIME_QUERIED;
 }
 
 static inline struct timespec64 inode_get_ctime(const struct inode *inode)
@@ -1631,13 +1642,7 @@ static inline struct timespec64 inode_get_ctime(const struct inode *inode)
 	return ts;
 }
 
-static inline struct timespec64 inode_set_ctime_to_ts(struct inode *inode,
-						      struct timespec64 ts)
-{
-	inode->i_ctime_sec = ts.tv_sec;
-	inode->i_ctime_nsec = ts.tv_nsec;
-	return ts;
-}
+struct timespec64 inode_set_ctime_to_ts(struct inode *inode, struct timespec64 ts);
 
 /**
  * inode_set_ctime - set the ctime in the inode
@@ -2500,6 +2505,7 @@ struct file_system_type {
 #define FS_USERNS_MOUNT		8	/* Can be mounted by userns root */
 #define FS_DISALLOW_NOTIFY_PERM	16	/* Disable fanotify permission events */
 #define FS_ALLOW_IDMAP         32      /* FS has been updated to handle vfs idmappings. */
+#define FS_MGTIME		64	/* FS uses multigrain timestamps */
 #define FS_RENAME_DOES_D_MOVE	32768	/* FS will handle d_move() during rename() internally. */
 	int (*init_fs_context)(struct fs_context *);
 	const struct fs_parameter_spec *parameters;
@@ -2523,6 +2529,17 @@ struct file_system_type {
 
 #define MODULE_ALIAS_FS(NAME) MODULE_ALIAS("fs-" NAME)
 
+/**
+ * is_mgtime: is this inode using multigrain timestamps
+ * @inode: inode to test for multigrain timestamps
+ *
+ * Return true if the inode uses multigrain timestamps, false otherwise.
+ */
+static inline bool is_mgtime(const struct inode *inode)
+{
+	return inode->i_sb->s_type->fs_flags & FS_MGTIME;
+}
+
 extern struct dentry *mount_bdev(struct file_system_type *fs_type,
 	int flags, const char *dev_name, void *data,
 	int (*fill_super)(struct super_block *, void *, int));
@@ -3262,6 +3279,7 @@ extern void page_put_link(void *);
 extern int page_symlink(struct inode *inode, const char *symname, int len);
 extern const struct inode_operations page_symlink_inode_operations;
 extern void kfree_link(void *);
+void fill_mg_cmtime(struct kstat *stat, u32 request_mask, struct inode *inode);
 void generic_fillattr(struct mnt_idmap *, u32, struct inode *, struct kstat *);
 void generic_fill_statx_attr(struct inode *inode, struct kstat *stat);
 void generic_fill_statx_atomic_writes(struct kstat *stat,
Signature · 1 line
2.46.0
author maintainer
#22 lore raw

PATCH v8 3/11 fs: have setattr_copy handle multigrain timestamps appropriately

In reply to Jeff Layton

The setattr codepath is still using coarse-grained timestamps, even on multigrain filesystems. To fix this, we need to fetch the timestamp for ctime updates later, at the point where the assignment occurs in setattr_copy.

On a multigrain inode, ignore the ia_ctime in the attrs, and always update the ctime to the current clock value. Update the atime and mtime with the same value (if needed) unless they are being set to other specific values, a'la utimes().

Note that we don't want to do this universally however, as some filesystems (e.g. most networked fs) want to do an explicit update elsewhere before updating the local inode.

---
 fs/attr.c | 52 ++++++++++++++++++++++++++++++++++++++++++++++------
 1 file changed, 46 insertions(+), 6 deletions(-)
fs/attr.c +46 -6
index c04d19b58f12..3bcbc45708a3 100644
@@ -271,6 +271,42 @@ int inode_newsize_ok(const struct inode *inode, loff_t offset)
 }
 EXPORT_SYMBOL(inode_newsize_ok);
 
+/**
+ * setattr_copy_mgtime - update timestamps for mgtime inodes
+ * @inode: inode timestamps to be updated
+ * @attr: attrs for the update
+ *
+ * With multigrain timestamps, we need to take more care to prevent races
+ * when updating the ctime. Always update the ctime to the very latest
+ * using the standard mechanism, and use that to populate the atime and
+ * mtime appropriately (unless we're setting those to specific values).
+ */
+static void setattr_copy_mgtime(struct inode *inode, const struct iattr *attr)
+{
+	unsigned int ia_valid = attr->ia_valid;
+	struct timespec64 now;
+
+	/*
+	 * If the ctime isn't being updated then nothing else should be
+	 * either.
+	 */
+	if (!(ia_valid & ATTR_CTIME)) {
+		WARN_ON_ONCE(ia_valid & (ATTR_ATIME|ATTR_MTIME));
+		return;
+	}
+
+	now = inode_set_ctime_current(inode);
+	if (ia_valid & ATTR_ATIME_SET)
+		inode_set_atime_to_ts(inode, attr->ia_atime);
+	else if (ia_valid & ATTR_ATIME)
+		inode_set_atime_to_ts(inode, now);
+
+	if (ia_valid & ATTR_MTIME_SET)
+		inode_set_mtime_to_ts(inode, attr->ia_mtime);
+	else if (ia_valid & ATTR_MTIME)
+		inode_set_mtime_to_ts(inode, now);
+}
+
 /**
  * setattr_copy - copy simple metadata updates into the generic inode
  * @idmap:	idmap of the mount the inode was found from
@@ -303,12 +339,6 @@ void setattr_copy(struct mnt_idmap *idmap, struct inode *inode,
 
 	i_uid_update(idmap, attr, inode);
 	i_gid_update(idmap, attr, inode);
-	if (ia_valid & ATTR_ATIME)
-		inode_set_atime_to_ts(inode, attr->ia_atime);
-	if (ia_valid & ATTR_MTIME)
-		inode_set_mtime_to_ts(inode, attr->ia_mtime);
-	if (ia_valid & ATTR_CTIME)
-		inode_set_ctime_to_ts(inode, attr->ia_ctime);
 	if (ia_valid & ATTR_MODE) {
 		umode_t mode = attr->ia_mode;
 		if (!in_group_or_capable(idmap, inode,
@@ -316,6 +346,16 @@ void setattr_copy(struct mnt_idmap *idmap, struct inode *inode,
 			mode &= ~S_ISGID;
 		inode->i_mode = mode;
 	}
+
+	if (is_mgtime(inode))
+		return setattr_copy_mgtime(inode, attr);
+
+	if (ia_valid & ATTR_ATIME)
+		inode_set_atime_to_ts(inode, attr->ia_atime);
+	if (ia_valid & ATTR_MTIME)
+		inode_set_mtime_to_ts(inode, attr->ia_mtime);
+	if (ia_valid & ATTR_CTIME)
+		inode_set_ctime_to_ts(inode, attr->ia_ctime);
 }
 EXPORT_SYMBOL(setattr_copy);
 
Signature · 1 line
2.46.0
author maintainer
#23 lore raw

PATCH v8 4/11 fs: handle delegated timestamps in setattr_copy_mgtime

In reply to Jeff Layton

When updating the ctime on an inode for a SETATTR with a multigrain filesystem, we usually want to take the latest time we can get for the ctime. The exception to this rule is when there is a nfsd write delegation and the server is proxying timestamps from the client.

When nfsd gets a CB_GETATTR response, we want to update the timestamp value in the inode to the values that the client is tracking. The client doesn't send a ctime value (since that's always determined by the exported filesystem), but it can send a mtime value. In the case where it does, then we may need to update the ctime to a value commensurate with that instead of the current time.

If ATTR_DELEG is set, then use ia_ctime value instead of setting the timestamp to the current time.

With the addition of delegated timestamps we can also receive a request to update only the atime, but we may not need to set the ctime. Trust the ATTR_CTIME flag in the update and only update the ctime when it's set.

---
 fs/attr.c          | 28 +++++++++++++--------
 fs/inode.c         | 72 ++++++++++++++++++++++++++++++++++++++++++++++++++++++
 include/linux/fs.h |  2 ++
 3 files changed, 92 insertions(+), 10 deletions(-)
fs/attr.c +18 -10
index 3bcbc45708a3..392eb62aa609 100644
@@ -286,16 +286,20 @@ static void setattr_copy_mgtime(struct inode *inode, const struct iattr *attr)
 	unsigned int ia_valid = attr->ia_valid;
 	struct timespec64 now;
 
-	/*
-	 * If the ctime isn't being updated then nothing else should be
-	 * either.
-	 */
-	if (!(ia_valid & ATTR_CTIME)) {
-		WARN_ON_ONCE(ia_valid & (ATTR_ATIME|ATTR_MTIME));
-		return;
+	if (ia_valid & ATTR_CTIME) {
+		/*
+		 * In the case of an update for a write delegation, we must respect
+		 * the value in ia_ctime and not use the current time.
+		 */
+		if (ia_valid & ATTR_DELEG)
+			now = inode_set_ctime_deleg(inode, attr->ia_ctime);
+		else
+			now = inode_set_ctime_current(inode);
+	} else {
+		/* If ATTR_CTIME isn't set, then ATTR_MTIME shouldn't be either. */
+		WARN_ON_ONCE(ia_valid & ATTR_MTIME);
 	}
 
-	now = inode_set_ctime_current(inode);
 	if (ia_valid & ATTR_ATIME_SET)
 		inode_set_atime_to_ts(inode, attr->ia_atime);
 	else if (ia_valid & ATTR_ATIME)
@@ -354,8 +358,12 @@ void setattr_copy(struct mnt_idmap *idmap, struct inode *inode,
 		inode_set_atime_to_ts(inode, attr->ia_atime);
 	if (ia_valid & ATTR_MTIME)
 		inode_set_mtime_to_ts(inode, attr->ia_mtime);
-	if (ia_valid & ATTR_CTIME)
-		inode_set_ctime_to_ts(inode, attr->ia_ctime);
+	if (ia_valid & ATTR_CTIME) {
+		if (ia_valid & ATTR_DELEG)
+			inode_set_ctime_deleg(inode, attr->ia_ctime);
+		else
+			inode_set_ctime_to_ts(inode, attr->ia_ctime);
+	}
 }
 EXPORT_SYMBOL(setattr_copy);
 
fs/inode.c +72 -0

78 lines not on this page · raw message

include/linux/fs.h +2 -0
index eff688e75f2f..ea7ed437d2b1 100644
@@ -1544,6 +1544,8 @@ static inline bool fsuidgid_has_mapping(struct super_block *sb,
 
 struct timespec64 current_time(struct inode *inode);
 struct timespec64 inode_set_ctime_current(struct inode *inode);
+struct timespec64 inode_set_ctime_deleg(struct inode *inode,
+					struct timespec64 update);
 
 static inline time64_t inode_get_atime_sec(const struct inode *inode)
 {
Signature · 1 line
2.46.0
author maintainer
#24 lore raw

PATCH v8 5/11 fs: tracepoints around multigrain timestamp events

In reply to Jeff Layton

Add some tracepoints around various multigrain timestamp events.

---
 fs/inode.c                       |   9 ++-
 fs/stat.c                        |   3 +
 include/trace/events/timestamp.h | 124 +++++++++++++++++++++++++++++++++++++++
 3 files changed, 135 insertions(+), 1 deletion(-)
fs/inode.c +8 -1
index 614d0402e9ad..d7da9d06921f 100644
@@ -22,6 +22,9 @@
 #include <linux/iversion.h>
 #include <linux/rw_hint.h>
 #include <trace/events/writeback.h>
+#define CREATE_TRACE_POINTS
+#include <trace/events/timestamp.h>
+
 #include "internal.h"
 
 /*
@@ -2603,6 +2606,7 @@ EXPORT_SYMBOL(inode_nohighmem);
 
 struct timespec64 inode_set_ctime_to_ts(struct inode *inode, struct timespec64 ts)
 {
+	trace_inode_set_ctime_to_ts(inode, &ts);
 	set_normalized_timespec64(&ts, ts.tv_sec, ts.tv_nsec);
 	inode->i_ctime_sec = ts.tv_sec;
 	inode->i_ctime_nsec = ts.tv_nsec;
@@ -2687,14 +2691,17 @@ struct timespec64 inode_set_ctime_current(struct inode *inode)
 	}
 
 	/* No need to cmpxchg if it's exactly the same */
-	if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec)
+	if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec) {
+		trace_ctime_xchg_skip(inode, &now);
 		goto out;
+	}
 	cur = cns;
 retry:
 	/* Try to swap the nsec value into place. */
 	if (try_cmpxchg(&inode->i_ctime_nsec, &cur, now.tv_nsec)) {
 		/* If swap occurred, then we're (mostly) done */
 		inode->i_ctime_sec = now.tv_sec;
+		trace_ctime_ns_xchg(inode, cns, now.tv_nsec, cur);
 	} else {
 		/*
 		 * Was the change due to someone marking the old ctime QUERIED?
fs/stat.c +3 -0
index a449626fd460..9eb6d9b2d010 100644
@@ -23,6 +23,8 @@
 #include <linux/uaccess.h>
 #include <asm/unistd.h>
 
+#include <trace/events/timestamp.h>
+
 #include "internal.h"
 #include "mount.h"
 
@@ -52,6 +54,7 @@ void fill_mg_cmtime(struct kstat *stat, u32 request_mask, struct inode *inode)
 	if (!(stat->ctime.tv_nsec & I_CTIME_QUERIED))
 		stat->ctime.tv_nsec = ((u32)atomic_fetch_or(I_CTIME_QUERIED, pcn));
 	stat->ctime.tv_nsec &= ~I_CTIME_QUERIED;
+	trace_fill_mg_cmtime(inode, &stat->ctime, &stat->mtime);
 }
 EXPORT_SYMBOL(fill_mg_cmtime);
 
include/trace/events/timestamp.h new file +124 -0

124 lines not on this page · raw message

Signature · 1 line
2.46.0
maintainer Reviewed-by on v8 5/11
#25 lore raw

Re: [PATCH v8 05/11] fs: tracepoints around multigrain timestamp events

Quoted 7 lines · On Sat, 14 Sep 2024 13:07:18 -0400 Jeff Layton <[email protected]> wrote:

Add some tracepoints around various multigrain timestamp events.

---

From a tracing POV, nothing looks out of ordinary.

-- Steve

author maintainer
#26 lore raw

PATCH v8 6/11 fs: add percpu counters for significant multigrain timestamp events

In reply to Jeff Layton

New percpu counters for counting various stats around mgtimes, and a new debugfs file for displaying them when CONFIG_DEBUG_FS is enabled:

- number of attempted ctime updates
- number of successful i_ctime_nsec swaps
- number of fine-grained timestamp fetches
- number of coarse-grained floor swaps

---
 fs/inode.c                         | 76 ++++++++++++++++++++++++++++++++++++--
 include/linux/timekeeping.h        |  1 +
 kernel/time/timekeeping.c          |  3 +-
 kernel/time/timekeeping_debug.c    | 12 ++++++
 kernel/time/timekeeping_internal.h |  3 ++
 5 files changed, 90 insertions(+), 5 deletions(-)
fs/inode.c +72 -4
index d7da9d06921f..1f0487104c71 100644
@@ -21,6 +21,8 @@
 #include <linux/list_lru.h>
 #include <linux/iversion.h>
 #include <linux/rw_hint.h>
+#include <linux/seq_file.h>
+#include <linux/debugfs.h>
 #include <trace/events/writeback.h>
 #define CREATE_TRACE_POINTS
 #include <trace/events/timestamp.h>
@@ -101,6 +103,70 @@ long get_nr_dirty_inodes(void)
 	return nr_dirty > 0 ? nr_dirty : 0;
 }
 
+#ifdef CONFIG_DEBUG_FS
+static DEFINE_PER_CPU(long, mg_ctime_updates);
+static DEFINE_PER_CPU(long, mg_fine_stamps);
+static DEFINE_PER_CPU(long, mg_ctime_swaps);
+
+static long get_mg_ctime_updates(void)
+{
+	int i;
+	long sum = 0;
+
+	for_each_possible_cpu(i)
+		sum += per_cpu(mg_ctime_updates, i);
+	return sum < 0 ? 0 : sum;
+}
+
+static long get_mg_fine_stamps(void)
+{
+	int i;
+	long sum = 0;
+
+	for_each_possible_cpu(i)
+		sum += per_cpu(mg_fine_stamps, i);
+	return sum < 0 ? 0 : sum;
+}
+
+static long get_mg_ctime_swaps(void)
+{
+	int i;
+	long sum = 0;
+
+	for_each_possible_cpu(i)
+		sum += per_cpu(mg_ctime_swaps, i);
+	return sum < 0 ? 0 : sum;
+}
+
+#define mgtime_counter_inc(__var)	this_cpu_inc(__var)
+
+static int mgts_show(struct seq_file *s, void *p)
+{
+	long ctime_updates = get_mg_ctime_updates();
+	long ctime_swaps = get_mg_ctime_swaps();
+	long fine_stamps = get_mg_fine_stamps();
+	long floor_swaps = get_mg_floor_swaps();
+
+	seq_printf(s, "%ld %ld %ld %ld\n",
+		   ctime_updates, ctime_swaps, fine_stamps, floor_swaps);
+	return 0;
+}
+
+DEFINE_SHOW_ATTRIBUTE(mgts);
+
+static int __init mg_debugfs_init(void)
+{
+	debugfs_create_file("multigrain_timestamps", S_IFREG | S_IRUGO, NULL, NULL, &mgts_fops);
+	return 0;
+}
+late_initcall(mg_debugfs_init);
+
+#else /* ! CONFIG_DEBUG_FS */
+
+#define mgtime_counter_inc()	do { } while (0)
+
+#endif /* CONFIG_DEBUG_FS */
+
 /*
  * Handle nr_inode sysctl
  */
@@ -2655,10 +2721,9 @@ EXPORT_SYMBOL(timestamp_truncate);
  *
  * If it is multigrain, then we first see if the coarse-grained timestamp is
  * distinct from what we have. If so, then we'll just use that. If we have to
- * get a fine-grained timestamp, then do so, and try to swap it into the floor.
- * We accept the new floor value regardless of the outcome of the cmpxchg.
- * After that, we try to swap the new value into i_ctime_nsec. Again, we take
- * the resulting ctime, regardless of the outcome of the swap.
+ * get a fine-grained timestamp, then do so. After that, we try to swap the new
+ * value into i_ctime_nsec. We take the resulting ctime, regardless of the
+ * outcome of the swap.
  */
 struct timespec64 inode_set_ctime_current(struct inode *inode)
 {
@@ -2687,8 +2752,10 @@ struct timespec64 inode_set_ctime_current(struct inode *inode)
 		if (timespec64_compare(&now, &ctime) <= 0) {
 			ktime_get_real_ts64_mg(&now);
 			now = timestamp_truncate(now, inode);
+			mgtime_counter_inc(mg_fine_stamps);
 		}
 	}
+	mgtime_counter_inc(mg_ctime_updates);
 
 	/* No need to cmpxchg if it's exactly the same */
 	if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec) {
@@ -2702,6 +2769,7 @@ struct timespec64 inode_set_ctime_current(struct inode *inode)
 		/* If swap occurred, then we're (mostly) done */
 		inode->i_ctime_sec = now.tv_sec;
 		trace_ctime_ns_xchg(inode, cns, now.tv_nsec, cur);
+		mgtime_counter_inc(mg_ctime_swaps);
 	} else {
 		/*
 		 * Was the change due to someone marking the old ctime QUERIED?
include/linux/timekeeping.h +1 -0
index 7aa85246c183..b9c8c597a073 100644
@@ -48,6 +48,7 @@ extern void ktime_get_coarse_real_ts64(struct timespec64 *ts);
 /* Multigrain timestamp interfaces */
 extern void ktime_get_coarse_real_ts64_mg(struct timespec64 *ts);
 extern void ktime_get_real_ts64_mg(struct timespec64 *ts);
+extern long get_mg_floor_swaps(void);
 
 void getboottime64(struct timespec64 *ts);
 
kernel/time/timekeeping.c +2 -1
index 16937242b904..94b0219955a2 100644
@@ -2440,7 +2440,7 @@ EXPORT_SYMBOL_GPL(ktime_get_coarse_real_ts64_mg);
  * regardless of the outcome of the swap. Note that this is a filesystem
  * specific interface and should be avoided outside of that context.
  */
-void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)
+void ktime_get_real_ts64_mg(struct timespec64 *ts)
 {
 	struct timekeeper *tk = &tk_core.timekeeper;
 	ktime_t old = atomic64_read(&mg_floor);
@@ -2464,6 +2464,7 @@ void ktime_get_real_ts64_mg(struct timespec64 *ts, u64 cookie)
 	if (atomic64_try_cmpxchg(&mg_floor, &old, mono)) {
 		ts->tv_nsec = 0;
 		timespec64_add_ns(ts, nsecs);
+		mgtime_counter_inc(mg_floor_swaps);
 	} else {
 		/*
 		 * Something has changed mg_floor since "old" was
kernel/time/timekeeping_debug.c +12 -0
index b73e8850e58d..9a3792072762 100644
@@ -17,6 +17,9 @@
 
 #define NUM_BINS 32
 
+/* incremented every time mg_floor is updated */
+DEFINE_PER_CPU(long, mg_floor_swaps);
+
 static unsigned int sleep_time_bin[NUM_BINS] = {0};
 
 static int tk_debug_sleep_time_show(struct seq_file *s, void *data)
@@ -53,3 +56,12 @@ void tk_debug_account_sleep_time(const struct timespec64 *t)
 			   (s64)t->tv_sec, t->tv_nsec / NSEC_PER_MSEC);
 }
 
+long get_mg_floor_swaps(void)
+{
+	int i;
+	long sum = 0;
+
+	for_each_possible_cpu(i)
+		sum += per_cpu(mg_floor_swaps, i);
+	return sum < 0 ? 0 : sum;
+}
kernel/time/timekeeping_internal.h +3 -0
index 4ca2787d1642..2b49332b45a5 100644
@@ -11,8 +11,11 @@
  */
 #ifdef CONFIG_DEBUG_FS
 extern void tk_debug_account_sleep_time(const struct timespec64 *t);
+DECLARE_PER_CPU(long, mg_floor_swaps);
+#define mgtime_counter_inc(__var)	this_cpu_inc(__var)
 #else
 #define tk_debug_account_sleep_time(x)
+#define mgtime_counter_inc()	do { } while (0)
 #endif
 
 #ifdef CONFIG_CLOCKSOURCE_VALIDATE_LAST_CYCLE
Signature · 1 line
2.46.0
#27 lore raw

Re: [PATCH v8 06/11] fs: add percpu counters for significant multigrain timestamp events

Quoted 5 lines · Jeff Layton
 fs/inode.c                         | 76 ++++++++++++++++++++++++++++++++++++--
 include/linux/timekeeping.h        |  1 +
 kernel/time/timekeeping.c          |  3 +-
 kernel/time/timekeeping_debug.c    | 12 ++++++
 kernel/time/timekeeping_internal.h |  3 ++

So the subject says 'fs:'. This is not how it works.

Provide the timekeeping changes in a separate patch and then add the fs voodoo. Documentation is pretty clear about this, no?

kernel/time/timekeeping_debug.c line 20

Quoted 9 lines
kernel/time/timekeeping_debug.c +1 -0
index b73e8850e58d..9a3792072762 100644
@@ -17,6 +17,9 @@
 
 #define NUM_BINS 32
 
+/* incremented every time mg_floor is updated */

Sentences start with a uppercase letter.

kernel/time/timekeeping_debug.c line 21

Quoted 1 line
kernel/time/timekeeping_debug.c +1 -0
+DEFINE_PER_CPU(long, mg_floor_swaps);

Why is this long? This is a counter which always counts up..

kernel/time/timekeeping_debug.c void tk_debug_account_sleep_time(const struct timespec64 *t) · line 59

Quoted 8 lines
kernel/time/timekeeping_debug.c +1 -0
 static unsigned int sleep_time_bin[NUM_BINS] = {0};
 
 static int tk_debug_sleep_time_show(struct seq_file *s, void *data)
@@ -53,3 +56,12 @@ void tk_debug_account_sleep_time(const struct timespec64 *t)
 			   (s64)t->tv_sec, t->tv_nsec / NSEC_PER_MSEC);
 }
 
+long get_mg_floor_swaps(void)

Can we please have a proper subsystem prefix and not this get_*() notation. It's horrible to grep for. timekeeping_mg_get_...() makes it clear where this function belongs to, no?

kernel/time/timekeeping_debug.c void tk_debug_account_sleep_time(const struct timespec64 *t) · line 62

Quoted 3 lines
kernel/time/timekeeping_debug.c +3 -0
+{
+	int i;
+	long sum = 0;

https://www.kernel.org/doc/html/latest/process/maintainer-tip.html#variable-declarations

Also please use 'cpu' instead of 'i'. Self explanatory variable names have a value.

kernel/time/timekeeping_debug.c void tk_debug_account_sleep_time(const struct timespec64 *t) · line 65

Quoted 2 lines
kernel/time/timekeeping_debug.c +2 -0
+	for_each_possible_cpu(i)
+		sum += per_cpu(mg_floor_swaps, i);

This needs annotation for kcsan as this is a racy access.

kernel/time/timekeeping_internal.h line 15

Quoted 12 lines
kernel/time/timekeeping_debug.c +2 -0
+	return sum < 0 ? 0 : sum;
+}
kernel/time/timekeeping_internal.h +2 -0
index 4ca2787d1642..2b49332b45a5 100644
@@ -11,8 +11,11 @@
  */
 #ifdef CONFIG_DEBUG_FS
 extern void tk_debug_account_sleep_time(const struct timespec64 *t);
+DECLARE_PER_CPU(long, mg_floor_swaps);
+#define mgtime_counter_inc(__var)	this_cpu_inc(__var)

Please use static inlines for this.

Thanks,

tglx

#28 lore raw

Re: [PATCH v8 06/11] fs: add percpu counters for significant multigrain timestamp events

In reply to Jeff Layton
kernel test robot noticed the following build errors:

Hi Jeff,

kernel test robot noticed the following build errors:

[auto build test ERROR on da3ea35007d0af457a0afc87e84fddaebc4e0b63]

url:    https://github.com/intel-lab-lkp/linux/commits/Jeff-Layton/timekeeping-move-multigrain-timestamp-floor-handling-into-timekeeper/20240915-010919
base:   da3ea35007d0af457a0afc87e84fddaebc4e0b63
patch link:    https://lore.kernel.org/r/20240914-mgtime-v8-6-5bd872330bed%40kernel.org
patch subject: [PATCH v8 06/11] fs: add percpu counters for significant multigrain timestamp events
config: x86_64-allnoconfig (https://download.01.org/0day-ci/archive/20240917/[email protected]/config)
compiler: clang version 18.1.8 (https://github.com/llvm/llvm-project 3b5b5c1ec4a3095ab096dd780e84d7ab81f3d7ff)
reproduce (this is a W=1 build): (https://download.01.org/0day-ci/archive/20240917/[email protected]/reproduce)

If you fix the issue in a separate patch/commit (i.e. not just a new version of the same patch/commit), kindly add following tags
| Reported-by: kernel test robot <[email protected]>
| Closes: https://lore.kernel.org/oe-kbuild-all/[email protected]/

All error/warnings (new ones prefixed by >>):

>> fs/inode.c:2755:23: error: too many arguments provided to function-like macro invocation
    2755 |                         mgtime_counter_inc(mg_fine_stamps);
         |                                            ^
   fs/inode.c:166:9: note: macro 'mgtime_counter_inc' defined here
     166 | #define mgtime_counter_inc()    do { } while (0)
         |         ^
>> fs/inode.c:2755:4: error: use of undeclared identifier 'mgtime_counter_inc'; did you mean 'percpu_counter_inc'?
    2755 |                         mgtime_counter_inc(mg_fine_stamps);
         |                         ^~~~~~~~~~~~~~~~~~
         |                         percpu_counter_inc
   include/linux/percpu_counter.h:265:20: note: 'percpu_counter_inc' declared here
     265 | static inline void percpu_counter_inc(struct percpu_counter *fbc)
         |                    ^
   fs/inode.c:2758:21: error: too many arguments provided to function-like macro invocation
    2758 |         mgtime_counter_inc(mg_ctime_updates);
         |                            ^
   fs/inode.c:166:9: note: macro 'mgtime_counter_inc' defined here
     166 | #define mgtime_counter_inc()    do { } while (0)
         |         ^
   fs/inode.c:2758:2: error: use of undeclared identifier 'mgtime_counter_inc'; did you mean 'percpu_counter_inc'?
    2758 |         mgtime_counter_inc(mg_ctime_updates);
         |         ^~~~~~~~~~~~~~~~~~
         |         percpu_counter_inc
   include/linux/percpu_counter.h:265:20: note: 'percpu_counter_inc' declared here
     265 | static inline void percpu_counter_inc(struct percpu_counter *fbc)
         |                    ^
   fs/inode.c:2772:22: error: too many arguments provided to function-like macro invocation
    2772 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                                    ^
   fs/inode.c:166:9: note: macro 'mgtime_counter_inc' defined here
     166 | #define mgtime_counter_inc()    do { } while (0)
         |         ^
   fs/inode.c:2772:3: error: use of undeclared identifier 'mgtime_counter_inc'; did you mean 'percpu_counter_inc'?
    2772 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                 ^~~~~~~~~~~~~~~~~~
         |                 percpu_counter_inc
   include/linux/percpu_counter.h:265:20: note: 'percpu_counter_inc' declared here
     265 | static inline void percpu_counter_inc(struct percpu_counter *fbc)
         |                    ^
>> fs/inode.c:2755:4: warning: expression result unused [-Wunused-value]
    2755 |                         mgtime_counter_inc(mg_fine_stamps);
         |                         ^~~~~~~~~~~~~~~~~~
   fs/inode.c:2758:2: warning: expression result unused [-Wunused-value]
    2758 |         mgtime_counter_inc(mg_ctime_updates);
         |         ^~~~~~~~~~~~~~~~~~
   fs/inode.c:2772:3: warning: expression result unused [-Wunused-value]
    2772 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                 ^~~~~~~~~~~~~~~~~~
   fs/inode.c:2845:22: error: too many arguments provided to function-like macro invocation
    2845 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                                    ^
   fs/inode.c:166:9: note: macro 'mgtime_counter_inc' defined here
     166 | #define mgtime_counter_inc()    do { } while (0)
         |         ^
   fs/inode.c:2845:3: error: use of undeclared identifier 'mgtime_counter_inc'; did you mean 'percpu_counter_inc'?
    2845 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                 ^~~~~~~~~~~~~~~~~~
         |                 percpu_counter_inc
   include/linux/percpu_counter.h:265:20: note: 'percpu_counter_inc' declared here
     265 | static inline void percpu_counter_inc(struct percpu_counter *fbc)
         |                    ^
   fs/inode.c:2845:3: warning: expression result unused [-Wunused-value]
    2845 |                 mgtime_counter_inc(mg_ctime_swaps);
         |                 ^~~~~~~~~~~~~~~~~~
   4 warnings and 8 errors generated.
--
>> kernel/time/timekeeping.c:2467:22: error: too many arguments provided to function-like macro invocation
    2467 |                 mgtime_counter_inc(mg_floor_swaps);
         |                                    ^
   kernel/time/timekeeping_internal.h:18:9: note: macro 'mgtime_counter_inc' defined here
      18 | #define mgtime_counter_inc()    do { } while (0)
         |         ^
>> kernel/time/timekeeping.c:2467:3: error: use of undeclared identifier 'mgtime_counter_inc'; did you mean 'percpu_counter_inc'?
    2467 |                 mgtime_counter_inc(mg_floor_swaps);
         |                 ^~~~~~~~~~~~~~~~~~
         |                 percpu_counter_inc
   include/linux/percpu_counter.h:265:20: note: 'percpu_counter_inc' declared here
     265 | static inline void percpu_counter_inc(struct percpu_counter *fbc)
         |                    ^
>> kernel/time/timekeeping.c:2467:3: warning: expression result unused [-Wunused-value]
    2467 |                 mgtime_counter_inc(mg_floor_swaps);
         |                 ^~~~~~~~~~~~~~~~~~

1 warning and 2 errors generated.

vim +2755 fs/inode.c

2713
2714 /**
2715 * inode_set_ctime_current - set the ctime to current_time
2716 * @inode: inode
2717 *
2718 * Set the inode's ctime to the current value for the inode. Returns the
2719 * current value that was assigned. If this is not a multigrain inode, then we
2720 * set it to the later of the coarse time and floor value.
2721 *
2722 * If it is multigrain, then we first see if the coarse-grained timestamp is
2723 * distinct from what we have. If so, then we'll just use that. If we have to
2724 * get a fine-grained timestamp, then do so. After that, we try to swap the new
2725 * value into i_ctime_nsec. We take the resulting ctime, regardless of the
2726 * outcome of the swap.
2727 */
2728 struct timespec64 inode_set_ctime_current(struct inode *inode)
2729 {
2730 struct timespec64 now;
2731 u32 cns, cur;
2732
2733 ktime_get_coarse_real_ts64_mg(&now);
2734 now = timestamp_truncate(now, inode);
2735
2736 /* Just return that if this is not a multigrain fs */
2737 if (!is_mgtime(inode)) {
2738 inode_set_ctime_to_ts(inode, now);
2739 goto out;
2740 }
2741
2742 /*
2743 * We only need a fine-grained time if someone has queried it,
2744 * and the current coarse grained time isn't later than what's
2745 * already there.
2746 */
2747 cns = smp_load_acquire(&inode->i_ctime_nsec);
2748 if (cns & I_CTIME_QUERIED) {
2749 struct timespec64 ctime = { .tv_sec = inode->i_ctime_sec,
2750 .tv_nsec = cns & ~I_CTIME_QUERIED };
2751
2752 if (timespec64_compare(&now, &ctime) <= 0) {
2753 ktime_get_real_ts64_mg(&now);
2754 now = timestamp_truncate(now, inode);

> 2755				mgtime_counter_inc(mg_fine_stamps);

2756 }
2757 }
2758 mgtime_counter_inc(mg_ctime_updates);
2759
2760 /* No need to cmpxchg if it's exactly the same */
2761 if (cns == now.tv_nsec && inode->i_ctime_sec == now.tv_sec) {
2762 trace_ctime_xchg_skip(inode, &now);
2763 goto out;
2764 }
2765 cur = cns;
2766 retry:
2767 /* Try to swap the nsec value into place. */
2768 if (try_cmpxchg(&inode->i_ctime_nsec, &cur, now.tv_nsec)) {
2769 /* If swap occurred, then we're (mostly) done */
2770 inode->i_ctime_sec = now.tv_sec;
2771 trace_ctime_ns_xchg(inode, cns, now.tv_nsec, cur);
2772 mgtime_counter_inc(mg_ctime_swaps);
2773 } else {
2774 /*
2775 * Was the change due to someone marking the old ctime QUERIED?
2776 * If so then retry the swap. This can only happen once since
2777 * the only way to clear I_CTIME_QUERIED is to stamp the inode
2778 * with a new ctime.
2779 */
2780 if (!(cns & I_CTIME_QUERIED) && (cns | I_CTIME_QUERIED) == cur) {
2781 cns = cur;
2782 goto retry;
2783 }
2784 /* Otherwise, keep the existing ctime */
2785 now.tv_sec = inode->i_ctime_sec;
2786 now.tv_nsec = cur & ~I_CTIME_QUERIED;
2787 }
2788 out:
2789 return now;
2790 }
2791 EXPORT_SYMBOL(inode_set_ctime_current);
2792

Signature · 2 lines
0-DAY CI Kernel Test Service
https://github.com/intel/lkp-tests/wiki
author maintainer
#29 lore raw

PATCH v8 7/11 Documentation: add a new file documenting multigrain timestamps

In reply to Jeff Layton

Add a high-level document that describes how multigrain timestamps work, rationale for them, and some info about implementation and tradeoffs.

---
 Documentation/filesystems/index.rst         |   1 +
 Documentation/filesystems/multigrain-ts.rst | 121 ++++++++++++++++++++++++++++
 2 files changed, 122 insertions(+)
Documentation/filesystems/index.rst +1 -0
index e8e496d23e1d..44e9e77ffe0d 100644
@@ -29,6 +29,7 @@ algorithms work.
    fiemap
    files
    locks
+   multigrain-ts
    mount_api
    quota
    seq_file
Documentation/filesystems/multigrain-ts.rst new file +121 -0

121 lines not on this page · raw message

Signature · 1 line
2.46.0
#30 lore raw

Re: [PATCH v8 07/11] Documentation: add a new file documenting multigrain timestamps

Documentation/filesystems/multigrain-ts.rst line 31

Quoted 3 lines · Jeff Layton
Documentation/filesystems/multigrain-ts.rst new file +3 -0
+Multigrain timestamps aim to remedy this by selectively using fine-grained
+timestamps when a file has had its timestamps queried recently, and the current
+coarse-grained time does not cause a change.

Do you mean using fine-grained timestamps when timestamps of a file has been recently queried/modified BUT its coarse-grained timestamps aren't changed?

Confused...

Signature · 1 line
An old man doll... just what I always wanted! - Clara
author maintainer
#31 lore raw

Re: [PATCH v8 07/11] Documentation: add a new file documenting multigrain timestamps

Quoted 10 lines · Bagas Sanjaya

Documentation/filesystems/multigrain-ts.rst line 31

Quoted 3 lines · Jeff Layton
Documentation/filesystems/multigrain-ts.rst new file +3 -0
+Multigrain timestamps aim to remedy this by selectively using fine-grained
+timestamps when a file has had its timestamps queried recently, and the current
+coarse-grained time does not cause a change.

Do you mean using fine-grained timestamps when timestamps of a file has been recently queried/modified BUT its coarse-grained timestamps aren't changed?

Confused...

Yes, I'll do an s/and/but/ there in the Documentation. Basically, we want to avoid updating the floor whenever we can (since it's a global variable), so we only get a fine-grained time if there is no other way to effect a change to the timestamps.

Thanks!

Signature · 1 line
Jeff Layton <[email protected]>
author maintainer
#32 lore raw

PATCH v8 8/11 xfs: switch to multigrain timestamps

In reply to Jeff Layton

Enable multigrain timestamps, which should ensure that there is an apparent change to the timestamp whenever it has been written after being actively observed via getattr.

Also, anytime the mtime changes, the ctime must also change, and those are now the only two options for xfs_trans_ichgtime. Have that function unconditionally bump the ctime, and ASSERT that XFS_ICHGTIME_CHG is always set.

Finally, stop setting STATX_CHANGE_COOKIE in getattr, since the ctime should give us better semantics now.

---
 fs/xfs/libxfs/xfs_trans_inode.c |  6 +++---
 fs/xfs/xfs_iops.c               | 10 +++-------
 fs/xfs/xfs_super.c              |  2 +-
 3 files changed, 7 insertions(+), 11 deletions(-)
fs/xfs/libxfs/xfs_trans_inode.c +3 -3
index 3c40f37e82c7..c962ad64b0c1 100644
@@ -62,12 +62,12 @@ xfs_trans_ichgtime(
 	ASSERT(tp);
 	xfs_assert_ilocked(ip, XFS_ILOCK_EXCL);
 
-	tv = current_time(inode);
+	/* If the mtime changes, then ctime must also change */
+	ASSERT(flags & XFS_ICHGTIME_CHG);
 
+	tv = inode_set_ctime_current(inode);
 	if (flags & XFS_ICHGTIME_MOD)
 		inode_set_mtime_to_ts(inode, tv);
-	if (flags & XFS_ICHGTIME_CHG)
-		inode_set_ctime_to_ts(inode, tv);
 	if (flags & XFS_ICHGTIME_ACCESS)
 		inode_set_atime_to_ts(inode, tv);
 	if (flags & XFS_ICHGTIME_CREATE)
fs/xfs/xfs_iops.c +3 -7
index 1cdc8034f54d..a1c4a350a6db 100644
@@ -597,8 +597,9 @@ xfs_vn_getattr(
 	stat->gid = vfsgid_into_kgid(vfsgid);
 	stat->ino = ip->i_ino;
 	stat->atime = inode_get_atime(inode);
-	stat->mtime = inode_get_mtime(inode);
-	stat->ctime = inode_get_ctime(inode);
+
+	fill_mg_cmtime(stat, request_mask, inode);
+
 	stat->blocks = XFS_FSB_TO_BB(mp, ip->i_nblocks + ip->i_delayed_blks);
 
 	if (xfs_has_v3inodes(mp)) {
@@ -608,11 +609,6 @@ xfs_vn_getattr(
 		}
 	}
 
-	if ((request_mask & STATX_CHANGE_COOKIE) && IS_I_VERSION(inode)) {
-		stat->change_cookie = inode_query_iversion(inode);
-		stat->result_mask |= STATX_CHANGE_COOKIE;
-	}
-
 	/*
 	 * Note: If you add another clause to set an attribute flag, please
 	 * update attributes_mask below.
fs/xfs/xfs_super.c +1 -1
index 27e9f749c4c7..210481b03fdb 100644
@@ -2052,7 +2052,7 @@ static struct file_system_type xfs_fs_type = {
 	.init_fs_context	= xfs_init_fs_context,
 	.parameters		= xfs_fs_parameters,
 	.kill_sb		= xfs_kill_sb,
-	.fs_flags		= FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
+	.fs_flags		= FS_REQUIRES_DEV | FS_ALLOW_IDMAP | FS_MGTIME,
 };
 MODULE_ALIAS_FS("xfs");
 
Signature · 1 line
2.46.0
author maintainer
#33 lore raw

PATCH v8 9/11 ext4: switch to multigrain timestamps

In reply to Jeff Layton

Enable multigrain timestamps, which should ensure that there is an apparent change to the timestamp whenever it has been written after being actively observed via getattr.

For ext4, we only need to enable the FS_MGTIME flag.

---
 fs/ext4/super.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
fs/ext4/super.c +1 -1
index e72145c4ae5a..a125d9435b8a 100644
@@ -7298,7 +7298,7 @@ static struct file_system_type ext4_fs_type = {
 	.init_fs_context	= ext4_init_fs_context,
 	.parameters		= ext4_param_specs,
 	.kill_sb		= ext4_kill_sb,
-	.fs_flags		= FS_REQUIRES_DEV | FS_ALLOW_IDMAP,
+	.fs_flags		= FS_REQUIRES_DEV | FS_ALLOW_IDMAP | FS_MGTIME,
 };
 MODULE_ALIAS_FS("ext4");
 
Signature · 1 line
2.46.0
author maintainer
#34 lore raw

PATCH v8 10/11 btrfs: convert to multigrain timestamps

In reply to Jeff Layton

Enable multigrain timestamps, which should ensure that there is an apparent change to the timestamp whenever it has been written after being actively observed via getattr.

Beyond enabling the FS_MGTIME flag, this patch eliminates update_time_for_write, which goes to great pains to avoid in-memory stores. Just have it overwrite the timestamps unconditionally.

Note that this also drops the IS_I_VERSION check and unconditionally bumps the change attribute, since SB_I_VERSION is always set on btrfs.

---
 fs/btrfs/file.c  | 25 ++++---------------------
 fs/btrfs/super.c |  3 ++-
 2 files changed, 6 insertions(+), 22 deletions(-)
fs/btrfs/file.c +4 -21
index 2aeb8116549c..1656ad7498b8 100644
@@ -1120,26 +1120,6 @@ void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
 	btrfs_drew_write_unlock(&inode->root->snapshot_lock);
 }
 
-static void update_time_for_write(struct inode *inode)
-{
-	struct timespec64 now, ts;
-
-	if (IS_NOCMTIME(inode))
-		return;
-
-	now = current_time(inode);
-	ts = inode_get_mtime(inode);
-	if (!timespec64_equal(&ts, &now))
-		inode_set_mtime_to_ts(inode, now);
-
-	ts = inode_get_ctime(inode);
-	if (!timespec64_equal(&ts, &now))
-		inode_set_ctime_to_ts(inode, now);
-
-	if (IS_I_VERSION(inode))
-		inode_inc_iversion(inode);
-}
-
 int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from, size_t count)
 {
 	struct file *file = iocb->ki_filp;
@@ -1170,7 +1150,10 @@ int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from, size_t count)
 	 * need to start yet another transaction to update the inode as we will
 	 * update the inode when we finish writing whatever data we write.
 	 */
-	update_time_for_write(inode);
+	if (!IS_NOCMTIME(inode)) {
+		inode_set_mtime_to_ts(inode, inode_set_ctime_current(inode));
+		inode_inc_iversion(inode);
+	}
 
 	start_pos = round_down(pos, fs_info->sectorsize);
 	oldsize = i_size_read(inode);
fs/btrfs/super.c +2 -1
index 98fa0f382480..d423acfe11d0 100644
@@ -2198,7 +2198,8 @@ static struct file_system_type btrfs_fs_type = {
 	.init_fs_context	= btrfs_init_fs_context,
 	.parameters		= btrfs_fs_parameters,
 	.kill_sb		= btrfs_kill_super,
-	.fs_flags		= FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA | FS_ALLOW_IDMAP,
+	.fs_flags		= FS_REQUIRES_DEV | FS_BINARY_MOUNTDATA |
+				  FS_ALLOW_IDMAP | FS_MGTIME,
  };
 
 MODULE_ALIAS_FS("btrfs");
Signature · 1 line
2.46.0
author maintainer
#35 lore raw

PATCH v8 11/11 tmpfs: add support for multigrain timestamps

In reply to Jeff Layton

Enable multigrain timestamps, which should ensure that there is an apparent change to the timestamp whenever it has been written after being actively observed via getattr.

tmpfs only requires the FS_MGTIME flag.

---
 mm/shmem.c | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)
mm/shmem.c +1 -1
index 5a77acf6ac6a..5f17eaaa32e2 100644
@@ -4804,7 +4804,7 @@ static struct file_system_type shmem_fs_type = {
 	.parameters	= shmem_fs_parameters,
 #endif
 	.kill_sb	= kill_litter_super,
-	.fs_flags	= FS_USERNS_MOUNT | FS_ALLOW_IDMAP,
+	.fs_flags	= FS_USERNS_MOUNT | FS_ALLOW_IDMAP | FS_MGTIME,
 };
 
 void __init shmem_init(void)
Signature · 1 line
2.46.0
reviewer Tested-by on the v8 series
#36 lore raw
In reply to Jeff Layton

Hi Jeff,

Quoted 45 lines · Jeff Layton

This is a fairly small update to the v7 set. It seems to pass all of my testing. Again, most of the changes are in the first two patches, but there are some differences in the patch that adds percpu counters as well.

Since the report of a performance regression came just before the merge window, it looks like we're going to have to wait for yet another release, so consider this version v6.13 material.

---

---
Jeff Layton (11):
timekeeping: move multigrain timestamp floor handling into timekeeper
fs: add infrastructure for multigrain timestamps
fs: have setattr_copy handle multigrain timestamps appropriately
fs: handle delegated timestamps in setattr_copy_mgtime
fs: tracepoints around multigrain timestamp events
fs: add percpu counters for significant multigrain timestamp events
Documentation: add a new file documenting multigrain timestamps
xfs: switch to multigrain timestamps
ext4: switch to multigrain timestamps
btrfs: convert to multigrain timestamps
tmpfs: add support for multigrain timestamps

 Documentation/filesystems/index.rst         |   1 +
 Documentation/filesystems/multigrain-ts.rst | 121 ++++++++++++
 fs/attr.c                                   |  60 +++++-
 fs/btrfs/file.c                             |  25 +--
 fs/btrfs/super.c                            |   3 +-
 fs/ext4/super.c                             |   2 +-
 fs/inode.c                                  | 278 +++++++++++++++++++++++++---
 fs/stat.c                                   |  42 ++++-
 fs/xfs/libxfs/xfs_trans_inode.c             |   6 +-
 fs/xfs/xfs_iops.c                           |  10 +-
 fs/xfs/xfs_super.c                          |   2 +-
 include/linux/fs.h                          |  36 +++-
 include/linux/timekeeping.h                 |   5 +
 include/trace/events/timestamp.h            | 124 +++++++++++++
 kernel/time/timekeeping.c                   |  83 +++++++++
 kernel/time/timekeeping_debug.c             |  12 ++
 kernel/time/timekeeping_internal.h          |   3 +
 mm/shmem.c                                  |   2 +-
 18 files changed, 742 insertions(+), 73 deletions(-)
Quoted 2 lines

---
base-commit: da3ea35007d0af457a0afc87e84fddaebc4e0b63

IME it would be better to make this series apply to linux-next-($latest) instead of base mainline Linux. for integration reasons.

You can add

for all patches if you want to.

Quoted 3 lines

change-id: 20240913-mgtime-20c98bcda88e

Best regards,