ptp: Add PHC timestamp quality attributes
Subsystems (7)
Arthur Kiyanovski
maintainerv5 cover ptp: Add PHC timestamp quality attributes
This series adds quality attributes to PTP Hardware Clock (PHC) timestamps, allowing userspace to obtain error bound, clock status, timescale, and system counter values alongside timestamps in a single call.
Motivation
----------
The existing PTP APIs return timestamps without any indication of their quality. Applications that need clock accuracy and synchronization status commonly rely on external tools such as ptp4l, which implement synchronization logic and can export their measurement of clock accuracy. For managed PHC devices — such as the ENA network adapter, whose clock is synchronized by the device without userspace involvement — these tools are not available, and the existing APIs lack a way to report quality metrics to consumers of time.
This was previously proposed as an RFC [1] with a single ioctl. Based on community feedback, the design was reworked to cover both the extended (multi-sample) and precise (cross-timestamp) paths.
Design
------
The UAPI was redesigned based on Thomas Gleixner's proposal [2]:
- A unified data structure (struct ptp_sys_offset_attrs) is used for both extended and precise ioctls.
- A u32 valid bitmask in struct ptp_clock_attrs indicates which attributes are populated, replacing sentinel values. Drivers set only the bits for attributes they provide.
- System counter values (cycles + counter_id) are carried in struct ptp_sys_time alongside each system timestamp. These are populated by the timekeeping core cross-timestamp infrastructure, which is now merged in net-next [3] — drivers do not fill them. This series therefore applies directly to net-next with no out-of-tree dependency.
- Graceful degradation: the attrs ioctls work even on devices without attrs callbacks, falling back to gettimex64 / getcrosststamp and returning attrs.valid = 0.
A capability flag is added to ptp_clock_caps so userspace can discover attributes support.
Patches 2-3 add testptp support for the new ioctls.
Patch 4 implements the attributes for ptp_vmclock, reporting error bound, clock status, and timescale.
Patches 5-7 implement the attributes for the ENA driver, reporting error bound from the device's PHC layer.
v5:
- ptp: simplify ptp_sys_offset_{extended,precise}_attrs() to copy the request header onto the stack and allocate the result buffer once, instead of memdup_user() + kfree() + kzalloc(). (Saeed Bshara)
- ptp: deduplicate the kernel-doc for gettimexattrs64 / getcrosststampattrs by referencing the base gettimex64 / getcrosststamp callbacks. (Saeed Bshara)
- ptp: add missing kernel-doc member descriptions for struct ptp_timestamp and struct ptp_sys_offset_attrs.
- selftests/ptp: map the clockid to a name and print once instead of three duplicated printfs. (Saeed Bshara)
- selftests/ptp: make -a a modifier on -x/-X instead of an exclusive option; drop -A (use -X -a); trim the unknown-clock output; print "not reported" for attributes the device does not report. (Saeed Bshara)
- ptp_vmclock: scope the local 'st' inside the SUPPORT_KVMCLOCK block to fix an unused-variable warning on !CONFIG_KVM_GUEST. (kernel test robot)
- No UAPI changes; the ioctl structures are unchanged from v4.
v4:
- Complete UAPI redesign per Thomas Gleixner's proposal [2]:
unified data structure with u32 valid bitmask, system counter in ptp_sys_time (populated by core, not drivers), graceful degradation for devices without attrs callbacks. (Thomas Gleixner, David Woodhouse)
- Counter values moved from driver attrs callback to timekeeping core infrastructure — drivers no longer set counter_id or counter_value.
- Flexible array member for timestamps[] (kernel bounds the copy, userspace allocates for num_samples requested).
- Drop separate ptp_clock_attributes kernel struct — driver callbacks fill the UAPI ptp_clock_attrs directly.
v3:
- Remove patch 5/8 from v2 (return-code bugfix) — sent separately as [PATCH net] to the net tree.
- Zero-initialize struct ptp_clock_attributes in PTP core ioctl handlers to prevent stack leak of unset fields. (Simon Horman, sashiko)
- ptp_vmclock: validate counter_period_shift < 128 to prevent undefined behavior on untrusted hypervisor input. (sashiko)
- ptp_vmclock: add overflow check on err_hi * NSEC_PER_SEC to prevent silent wraparound producing erroneously small error bound. (sashiko)
- ptp_vmclock: report PTP_TIMESCALE_TAI after tai_adjust() to avoid timescale mismatch. (sashiko)
- ENA: set counter_id = 0, counter_value = 0 in gettimexattrs64 for defense-in-depth. (sashiko)
v2:
- Fix build bisectability: move ena_com.c consumer updates into patch 6/8 and ena_phc.c caller update into patch 7/8 so each patch compiles independently.
- Add missing Cc for Amit Bernstein (co-author of ENA patches).
[1] https://lore.kernel.org/netdev/[email protected]/
[2] https://lore.kernel.org/all/87se7ht25o.ffs@tglx/
[3] https://lore.kernel.org/all/[email protected]/
Arthur Kiyanovski (7):
ptp: Add ioctls for PHC timestamps with quality attributes selftests/ptp: Extract print_system_timestamp helper in testptp selftests/ptp: Add testptp support for attributes ioctls
ptp: ptp_vmclock: Implement attributes ioctls
net: ena: Update PHC admin interface for error bound support
net: ena: Add error bound to PHC communication layer
net: ena: Implement gettimexattrs64 callback for PTP attributes
.../device_drivers/ethernet/amazon/ena.rst | 2 + .../net/ethernet/amazon/ena/ena_admin_defs.h | 17 +- drivers/net/ethernet/amazon/ena/ena_com.c | 51 ++-- drivers/net/ethernet/amazon/ena/ena_com.h | 5 +- drivers/net/ethernet/amazon/ena/ena_debugfs.c | 3 + drivers/net/ethernet/amazon/ena/ena_phc.c | 61 +++- drivers/ptp/ptp_chardev.c | 165 ++++++++++- drivers/ptp/ptp_clock.c | 4 +- drivers/ptp/ptp_vmclock.c | 197 +++++++++++-- include/linux/ptp_clock_kernel.h | 19 ++ include/uapi/linux/ptp_clock.h | 265 +++++++++++++++++- tools/testing/selftests/ptp/testptp.c | 189 ++++++++++--- 12 files changed, 868 insertions(+), 110 deletions(-)
base-commit: f6f3b36c15ed44de1fbb44e645e4fae8c4a4453e
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 1/7 ptp: Add ioctls for PHC timestamps with quality attributes
Introduce two new ioctls that extend existing PTP timestamp interfaces with clock quality information:
- PTP_SYS_OFFSET_EXTENDED_ATTRS: Extends PTP_SYS_OFFSET_EXTENDED
- PTP_SYS_OFFSET_PRECISE_ATTRS: Extends PTP_SYS_OFFSET_PRECISE
These ioctls provide quality attributes alongside timestamps:
1. error_bound: Maximum deviation from true time (nanoseconds), based on device's internal clock state
2. clock_status: Synchronization state (unknown, initializing, synchronized, free-running, unreliable)
3. timescale: Time reference (TAI, UTC, etc.)
4. counter_value: Raw system counter (e.g. TSC ticks) captured by the timekeeping core alongside each system timestamp
5. counter_id: Identifies the counter source (e.g. TSC, ARM arch counter)
This supports three use cases:
1. Managed PHC devices (e.g., ENA, vmclock) that maintain their own synchronization and can report quality metrics directly to userspace without requiring ptp4l
2. Applications that need complete time quality information in a single call, regardless of how the PHC is synchronized
3. VMMs that need raw system counter values paired
with PTP timestamps for feed-forward clock calibration, avoiding the feedback loop inherent in NTP-style synchronization
Timescale definitions use a Continuity/Discipline framework to describe timeline properties and steering behavior consistently across all entries.
This implementation is based on the original RFC and the UAPI design discussion linked below.
--- drivers/ptp/ptp_chardev.c | 165 +++++++++++++++++-- drivers/ptp/ptp_clock.c | 4 +- include/linux/ptp_clock_kernel.h | 19 +++ include/uapi/linux/ptp_clock.h | 265 ++++++++++++++++++++++++++++++- 4 files changed, 438 insertions(+), 15 deletions(-)
drivers/ptp/ptp_chardev.c +152 -13
@@ -190,6 +190,8 @@ static long ptp_clock_getcaps(struct ptp_clock *ptp, void __user *arg) .cross_timestamping = ptp->info->getcrosststamp != NULL, .adjust_phase = ptp->info->adjphase != NULL && ptp->info->getmaxphase != NULL, + .extended_attrs = ptp->info->gettimexattrs64 != NULL, + .precise_attrs = ptp->info->getcrosststampattrs != NULL, };if (caps.adjust_phase)
@@ -347,11 +349,28 @@ typedef int (*ptp_gettimex_fn)(struct ptp_clock_info *, struct timespec64 *, struct ptp_system_timestamp *); +static int ptp_validate_sys_offset_clockid (__kernel_clockid_t clockid) +{ +switch (clockid) { +case CLOCK_REALTIME : +case CLOCK_MONOTONIC : +case CLOCK_MONOTONIC_RAW : +return 0 ; + case CLOCK_AUX ... CLOCK_AUX_LAST: +if (IS_ENABLED (CONFIG_POSIX_AUX_CLOCKS )) +return 0 ; + fallthrough; +default : +return -EINVAL ; + } +} +static long ptp_sys_offset_extended (struct ptp_clock *ptp,void __user *arg,ptp_gettimex_fn gettimex_fn) { struct ptp_sys_offset_extended *extoff __free(kfree) = NULL;struct ptp_system_timestamp sts; +int err;if (!gettimex_fn)return -EOPNOTSUPP ;
@@ -363,23 +382,13 @@ static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg,if (extoff->n_samples >PTP_MAX_SAMPLES || extoff->rsv[0 ] || extoff->rsv[1 ])return -EINVAL ; -switch (extoff->clockid) { -case CLOCK_REALTIME : -case CLOCK_MONOTONIC : -case CLOCK_MONOTONIC_RAW : -break ; - case CLOCK_AUX ... CLOCK_AUX_LAST: -if (IS_ENABLED (CONFIG_POSIX_AUX_CLOCKS )) -break ; - fallthrough; -default : -return -EINVAL ; - } + err =ptp_validate_sys_offset_clockid (extoff->clockid); +if (err) +return err; sts.clockid = extoff->clockid;for (unsigned int i =0 ; i < extoff->n_samples; i++) {struct timespec64 ts; -int err; err =gettimex_fn (ptp->info, &ts, &sts);if (err)
@@ -404,6 +413,130 @@ static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg,return copy_to_user (arg, extoff,sizeof (*extoff)) ? -EFAULT :0 ; } +static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts; +unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples; + +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; + +/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid) +return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime = +ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles; + data->timestamps[i].pre_systime.sys_counter_id = + sts.pre_sts.cs_id; + data->timestamps[i].devtime.device_time.sec = ts.tv_sec; + data->timestamps[i].devtime.device_time.nsec = ts.tv_nsec; + data->timestamps[i].devtime.attrs = att; + data->timestamps[i].post_systime.sys_time = +ktime_to_ns (sts.post_sts.systime); + data->timestamps[i].post_systime.sys_rawtime = +ktime_to_ns (sts.post_sts.monoraw); + data->timestamps[i].post_systime.sys_counter = + sts.post_sts.cycles; + data->timestamps[i].post_systime.sys_counter_id = + sts.post_sts.cs_id; + } + +return copy_to_user (arg, data, +struct_size (data, timestamps, n_samples)) ? -EFAULT :0 ; +} + +static long ptp_sys_offset_precise_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct system_device_crosststamp xtstamp; +struct ptp_attrs_request request; +struct ptp_clock_attrs att = {}; +struct timespec64 ts; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples !=1 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + data =kzalloc (struct_size (data, timestamps,1 ),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + +if (ptp->info->getcrosststampattrs) + err = ptp->info->getcrosststampattrs (ptp->info, &xtstamp, &att); +else if (ptp->info->getcrosststamp) + err = ptp->info->getcrosststamp (ptp->info, &xtstamp); +else +return -EOPNOTSUPP ; + +if (err) +return err; + + ts =ktime_to_timespec64 (xtstamp.device); + data->timestamps[0 ].systime.sys_time = +ktime_to_ns (xtstamp.sys_systime); + data->timestamps[0 ].systime.sys_rawtime = +ktime_to_ns (xtstamp.sys_monoraw); + data->timestamps[0 ].systime.sys_counter = + xtstamp.sys_counter.cycles; + data->timestamps[0 ].systime.sys_counter_id = + xtstamp.sys_counter.cs_id; + data->timestamps[0 ].devtime.device_time.sec = ts.tv_sec; + data->timestamps[0 ].devtime.device_time.nsec = ts.tv_nsec; + data->timestamps[0 ].devtime.attrs = att; + +return copy_to_user (arg, data, +struct_size (data, timestamps,1 )) ? -EFAULT :0 ; +} +static long ptp_sys_offset (struct ptp_clock *ptp,void __user *arg) { struct ptp_sys_offset *sysoff __free(kfree) = NULL;
@@ -539,11 +672,17 @@ long ptp_ioctl(struct posix_clock_context *pccontext, unsigned int cmd,return ptp_sys_offset_precise (ptp, argptr, ptp->info->getcrosststamp); +case PTP_SYS_OFFSET_PRECISE_ATTRS : +return ptp_sys_offset_precise_attrs (ptp, argptr); +case PTP_SYS_OFFSET_EXTENDED :case PTP_SYS_OFFSET_EXTENDED2 :return ptp_sys_offset_extended (ptp, argptr, ptp->info->gettimex64); +case PTP_SYS_OFFSET_EXTENDED_ATTRS : +return ptp_sys_offset_extended_attrs (ptp, argptr); +case PTP_SYS_OFFSET :case PTP_SYS_OFFSET2 :return ptp_sys_offset (ptp, argptr);
drivers/ptp/ptp_clock.c +3 -1
@@ -112,7 +112,9 @@ static int ptp_clock_gettime(struct posix_clock *pc, struct timespec64 *tp) struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);int err; -if (ptp->info->gettimex64) +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, tp,NULL ,NULL ); +else if (ptp->info->gettimex64) err = ptp->info->gettimex64 (ptp->info, tp,NULL );else err = ptp->info->gettime64 (ptp->info, tp);
include/linux/ptp_clock_kernel.h +19 -0
@@ -123,11 +123,23 @@ struct ptp_system_timestamp {* reading the lowest bits of the PHC timestamp and the second * reading immediately follows that. * +* @gettimexattrs64: Same as @gettimex64, but also fills @att (if not NULL) +* with the maximum error bound for the returned PHC +* timestamp in nanoseconds, the timescale for the returned +* PHC timestamp and the clock's qualitative synchronization +* status. +* * @getcrosststamp: Reads the current time from the hardware clock and * system clock simultaneously. * parameter cts: Contains timestamp (device,system) pair, * where system time is realtime and monotonic. * +* @getcrosststampattrs: Same as @getcrosststamp, but also fills @att (if not +* NULL) with the maximum error bound for the returned +* PHC timestamp in nanoseconds, the timescale for the +* returned PHC timestamp and the clock's qualitative +* synchronization status. +* * @settime64: Set the current time on the hardware clock. * parameter ts: Time value to set. *
@@ -209,8 +221,15 @@ struct ptp_clock_info {int (*gettime64)(struct ptp_clock_info *ptp,struct timespec64 *ts);int (*gettimex64)(struct ptp_clock_info *ptp,struct timespec64 *ts,struct ptp_system_timestamp *sts); +int (*gettimexattrs64)(struct ptp_clock_info *ptp, +struct timespec64 *ts, +struct ptp_system_timestamp *sts, +struct ptp_clock_attrs *att);int (*getcrosststamp)(struct ptp_clock_info *ptp,struct system_device_crosststamp *cts); +int (*getcrosststampattrs)(struct ptp_clock_info *ptp, +struct system_device_crosststamp *cts, +struct ptp_clock_attrs *att);int (*settime64)(struct ptp_clock_info *p,const struct timespec64 *ts);int (*getcycles64)(struct ptp_clock_info *ptp,struct timespec64 *ts); int (*getcyclesx64)(struct ptp_clock_info *ptp, struct timespec64 *ts,
include/uapi/linux/ptp_clock.h +264 -1
289 lines not on this page · raw message
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 2/7 selftests/ptp: Extract print_system_timestamp helper in testptp
In reply to Arthur KiyanovskiExtract the repeated switch-on-clockid pattern used for printing system timestamps into a reusable helper function. This removes code duplication in the -x (PTP_SYS_OFFSET_EXTENDED) output path and prepares for additional callers.
The "after" timestamp lines now include the sample number prefix for consistency with the "before" lines, slightly changing the output format.
--- tools/testing/selftests/ptp/testptp.c | 76 +++++++++++++-------------- 1 file changed, 38 insertions(+), 38 deletions(-)
tools/testing/selftests/ptp/testptp.c +38 -38
@@ -153,6 +153,34 @@ static void usage(char *progname) progname, PTP_MAX_SAMPLES); } +static void print_system_timestamp (int sample_num,__kernel_clockid_t clockid, +long long sec,unsigned int nsec, +const char *when) +{ +const char *name; + +switch (clockid) { +case CLOCK_REALTIME : + name ="real" ; +break ; +case CLOCK_MONOTONIC : + name ="monotonic" ; +break ; +case CLOCK_MONOTONIC_RAW : + name ="monotonic-raw" ; +break ; +default : + name =NULL ; +break ; + } + +if (!name) +return ; + +printf ("sample #%2d: %s time %s: %lld.%09u\n" , + sample_num, name, when, sec, nsec); +} +int main (int argc,char *argv[]) {struct ptp_clock_caps caps;
@@ -608,46 +636,18 @@ int main(int argc, char *argv[]) getextended);for (i =0 ; i < getextended; i++) { -switch (ext_clockid) { -case CLOCK_REALTIME : -printf ("sample #%2d: real time before: %lld.%09u\n" , - i, soe->ts[i][0 ].sec, - soe->ts[i][0 ].nsec); -break ; -case CLOCK_MONOTONIC : -printf ("sample #%2d: monotonic time before: %lld.%09u\n" , - i, soe->ts[i][0 ].sec, - soe->ts[i][0 ].nsec); -break ; -case CLOCK_MONOTONIC_RAW : -printf ("sample #%2d: monotonic-raw time before: %lld.%09u\n" , - i, soe->ts[i][0 ].sec, - soe->ts[i][0 ].nsec); -break ; -default : -break ; - } +print_system_timestamp (i, ext_clockid, + soe->ts[i][0 ].sec, + soe->ts[i][0 ].nsec, +"before" ); +printf (" phc time: %lld.%09u\n" , soe->ts[i][1 ].sec, soe->ts[i][1 ].nsec); -switch (ext_clockid) { -case CLOCK_REALTIME : -printf (" real time after: %lld.%09u\n" , - soe->ts[i][2 ].sec, - soe->ts[i][2 ].nsec); -break ; -case CLOCK_MONOTONIC : -printf (" monotonic time after: %lld.%09u\n" , - soe->ts[i][2 ].sec, - soe->ts[i][2 ].nsec); -break ; -case CLOCK_MONOTONIC_RAW : -printf (" monotonic-raw time after: %lld.%09u\n" , - soe->ts[i][2 ].sec, - soe->ts[i][2 ].nsec); -break ; -default : -break ; - } + +print_system_timestamp (i, ext_clockid, + soe->ts[i][2 ].sec, + soe->ts[i][2 ].nsec, +"after" ); } }
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 3/7 selftests/ptp: Add testptp support for attributes ioctls
In reply to Arthur KiyanovskiAdd support for testing the new PTP_SYS_OFFSET_EXTENDED_ATTRS and PTP_SYS_OFFSET_PRECISE_ATTRS ioctls in the testptp utility.
Add a "-a" modifier that requests clock quality attributes (error_bound, status, timescale) alongside the existing extended (-x) and precise (-X) offset requests:
-x N -a: extended offset with attributes (N samples)
-X -a: precise cross-timestamp with attributes
When the device does not report a given attribute, print an explicit "not reported" line so all attributes are always accounted for.
These options allow testing and validation of PHC devices that provide clock quality information alongside timestamps.
Also display the new clock_attrs capability in the -c output, and update print_system_timestamp to print unrecognized clock types instead of silently dropping them.
--- tools/testing/selftests/ptp/testptp.c | 115 +++++++++++++++++++++++++- 1 file changed, 111 insertions(+), 4 deletions(-)
tools/testing/selftests/ptp/testptp.c +111 -4
@@ -148,6 +148,8 @@ static void usage(char *progname)" -T val set the ptp clock time to 'val' seconds\n" " -x val get an extended ptp clock time with the desired number of samples (up to %d)\n" " -X get a ptp clock cross timestamp\n" +" -a also report clock quality attributes (error_bound,\n" +" status, timescale); use together with -x or -X\n" " -y val pre/post tstamp timebase to use {realtime|monotonic|monotonic-raw}\n" " -z test combinations of rising/falling external time stamp flags\n" , progname, PTP_MAX_SAMPLES);
@@ -174,8 +176,10 @@ static void print_system_timestamp(int sample_num, __kernel_clockid_t clockid,break ; } -if (!name) +if (!name) { +printf ("sample #%2d: unknown clock %d\n" , sample_num, clockid);return ; + }printf ("sample #%2d: %s time %s: %lld.%09u\n" , sample_num, name, when, sec, nsec);
@@ -194,6 +198,7 @@ int main(int argc, char *argv[])struct ptp_sys_offset *sysoff;struct ptp_sys_offset_extended *soe;struct ptp_sys_offset_precise *xts; +struct ptp_sys_offset_attrs *attrs_data;char *progname;unsigned int i;
@@ -215,6 +220,7 @@ int main(int argc, char *argv[])int pct_offset =0 ;int getextended =0 ;int getcross =0 ; +int use_attrs =0 ;int n_samples =0 ;int pin_index =-1 , pin_func;int pps =-1 ;
@@ -232,7 +238,8 @@ int main(int argc, char *argv[]) progname =strrchr (argv[0 ],'/' ); progname = progname ?1 +progname : argv[0 ]; -while (EOF != (c =getopt (argc, argv,"cd:e:E:f:F:ghH:i:k:lL:n:o:p:P:rsSt:T:w:x:Xy:z" ))) { +while (EOF != (c =getopt (argc, argv, +"acd:e:E:f:F:ghH:i:k:lL:n:o:p:P:rsSt:T:w:x:Xy:z" ))) {switch (c) {case 'c' : capabilities =1 ;
@@ -317,6 +324,9 @@ int main(int argc, char *argv[])return -1 ; }break ; +case 'a' : + use_attrs =1 ; +break ;case 'X' : getcross =1 ;break ;
@@ -373,6 +383,8 @@ int main(int argc, char *argv[])" %d programmable pins\n" " %d cross timestamping\n" " %d adjust_phase\n" +" %d extended_attrs\n" +" %d precise_attrs\n" " %d maximum phase adjustment (ns)\n" , caps.max_adj, caps.n_alarm,
@@ -382,6 +394,8 @@ int main(int argc, char *argv[]) caps.n_pins, caps.cross_timestamping, caps.adjust_phase, + caps.extended_attrs, + caps.precise_attrs, caps.max_phase_adj); } }
@@ -619,7 +633,7 @@ int main(int argc, char *argv[])free (sysoff); } -if (getextended) { +if (getextended && !use_attrs) { soe =calloc (1 ,sizeof (*soe));if (!soe) {perror ("calloc" );
@@ -654,7 +668,56 @@ int main(int argc, char *argv[])free (soe); } -if (getcross) { +if (getextended && use_attrs) { + attrs_data =calloc (1 ,sizeof (*attrs_data) + + getextended *sizeof (struct ptp_timestamp )); +if (!attrs_data) { +perror ("calloc" ); +return -1 ; + } + + attrs_data->request.num_samples = getextended; + attrs_data->request.clock_id = ext_clockid; + +if (ioctl (fd,PTP_SYS_OFFSET_EXTENDED_ATTRS , attrs_data)) { +perror ("PTP_SYS_OFFSET_EXTENDED_ATTRS" ); + }else { +printf ("extended attrs timestamp request returned %d samples\n" , + getextended); + +for (i =0 ; i < getextended; i++) { +struct ptp_timestamp *ts = &attrs_data->timestamps[i]; + +printf (" sample #%u:\n" , i); +printf (" sys before: %lld ns\n" , + (long long )ts->pre_systime.sys_time); +printf (" phc time: %lld.%09u\n" , + ts->devtime.device_time.sec, + ts->devtime.device_time.nsec); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_ERROR_BOUND ) +printf (" error_bound: %u ns\n" , + ts->devtime.attrs.error_bound); +else +printf (" error_bound: not reported\n" ); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_STATUS ) +printf (" status: %u\n" , + ts->devtime.attrs.status); +else +printf (" status: not reported\n" ); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_TIMESCALE ) +printf (" timescale: %u\n" , + ts->devtime.attrs.timescale); +else +printf (" timescale: not reported\n" ); +printf (" sys after: %lld ns\n" , + (long long )ts->post_systime.sys_time); + } + } + +free (attrs_data); + } + +if (getcross && !use_attrs) { xts =calloc (1 ,sizeof (*xts));if (!xts) {perror ("calloc" );
@@ -677,6 +740,50 @@ int main(int argc, char *argv[])free (xts); } +if (getcross && use_attrs) { + attrs_data =calloc (1 ,sizeof (*attrs_data) + +sizeof (struct ptp_timestamp )); +if (!attrs_data) { +perror ("calloc" ); +return -1 ; + } + + attrs_data->request.num_samples =1 ; + attrs_data->request.clock_id = ext_clockid; + +if (ioctl (fd,PTP_SYS_OFFSET_PRECISE_ATTRS , attrs_data)) { +perror ("PTP_SYS_OFFSET_PRECISE_ATTRS" ); + }else { +struct ptp_timestamp *ts = &attrs_data->timestamps[0 ]; + +puts ("precise attrs crosstimestamp request okay" ); +printf ("device time: %lld.%09u\n" , + ts->devtime.device_time.sec, + ts->devtime.device_time.nsec); +printf ("system time: %lld ns\n" , + (long long )ts->systime.sys_time); +printf ("raw time: %lld ns\n" , + (long long )ts->systime.sys_rawtime); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_ERROR_BOUND ) +printf ("error_bound: %u ns\n" , + ts->devtime.attrs.error_bound); +else +printf ("error_bound: not reported\n" ); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_STATUS ) +printf ("status: %u\n" , + ts->devtime.attrs.status); +else +printf ("status: not reported\n" ); +if (ts->devtime.attrs.valid &PTP_ATTRS_VALID_TIMESCALE ) +printf ("timescale: %u\n" , + ts->devtime.attrs.timescale); +else +printf ("timescale: not reported\n" ); + } + +free (attrs_data); + } +if (channel >=0 ) {if (ioctl (fd,PTP_MASK_CLEAR_ALL )) {perror ("PTP_MASK_CLEAR_ALL" );
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 4/7 ptp: ptp_vmclock: Implement attributes ioctls
In reply to Arthur KiyanovskiImplement the gettimexattrs64 and getcrosststampattrs callbacks in the ptp_vmclock driver to provide clock quality attributes through the new PTP_SYS_OFFSET_EXTENDED_ATTRS and PTP_SYS_OFFSET_PRECISE_ATTRS ioctls.
The ptp_vmclock device exposes:
- error_bound: Derived from time_maxerror_nanosec, accumulated with counter frequency error (counter_period_maxerror_rate_frac_sec) over elapsed counter ticks
- clock_status: Mapped from the device's clock_status field
- timescale: Always reports TAI (UTC sources are converted by tai_adjust() before the attributes are populated)
The legacy ioctls return -EINVAL when clock_status is UNRELIABLE since they have no way to communicate clock state to userspace. The attrs ioctls have a status field for this purpose, so they treat UNRELIABLE as success and let userspace check the status field.
To avoid a race where the hypervisor could update clock_status between the timestamp call and the UNRELIABLE check, the clock state is captured inside the seq_count loop for a consistent snapshot with the timestamp.
--- drivers/ptp/ptp_vmclock.c | 197 ++++++++++++++++++++++++++++++++++---- 1 file changed, 181 insertions(+), 16 deletions(-)
drivers/ptp/ptp_vmclock.c +181 -16
@@ -53,6 +53,17 @@ struct vmclock_state {char *name; }; +/** +* struct vmclock_crosststamp_ctx - context for get_device_system_crosststamp() +* @st: vmclock device state +* @attrs: optional output for PTP clock attributes, populated inside the +* seq_count loop for a consistent snapshot with the timestamp +*/ +struct vmclock_crosststamp_ctx { +struct vmclock_state *st; +struct ptp_clock_attrs *attrs; +}; +#define VMCLOCK_MAX_WAIT ms_to_ktime(100)/* Require at least the flags field to be present. All else can be optional. */
@@ -95,13 +106,111 @@ static bool tai_adjust(struct vmclock_abi *clk, uint64_t *sec)return false; } +static uint8_t vmclock_get_ptp_timescale (uint8_t vmclock_time_type) +{ +switch (vmclock_time_type) { +case VMCLOCK_TIME_UTC : +return PTP_TIMESCALE_UTC ; +case VMCLOCK_TIME_TAI : +return PTP_TIMESCALE_TAI ; +case VMCLOCK_TIME_MONOTONIC : +return PTP_TIMESCALE_MONOTONIC ; +default : +return PTP_TIMESCALE_UNKNOWN ; + } +} + +static uint8_t vmclock_get_ptp_status (uint8_t vmclock_status) +{ +switch (vmclock_status) { +case VMCLOCK_STATUS_UNKNOWN : +return PTP_CLOCK_STATUS_UNKNOWN ; +case VMCLOCK_STATUS_INITIALIZING : +return PTP_CLOCK_STATUS_INITIALIZING ; +case VMCLOCK_STATUS_SYNCHRONIZED : +return PTP_CLOCK_STATUS_SYNCED ; +case VMCLOCK_STATUS_FREERUNNING : +return PTP_CLOCK_STATUS_FREE_RUNNING ; +case VMCLOCK_STATUS_UNRELIABLE : +return PTP_CLOCK_STATUS_UNRELIABLE ; +default : +return PTP_CLOCK_STATUS_UNKNOWN ; + } +} + +static void vmclock_populate_ptp_attributes (struct vmclock_state *st, +struct ptp_clock_attrs *att, +uint64_t delta) +{ +uint64_t maxerror_ns =UINT_MAX ; + +if (!att) +return ; + +/* Only calculate if the base error is flagged as valid +* by the hypervisor. +*/ +if (VMCLOCK_FIELD_PRESENT (st->clk, time_maxerror_nanosec) && + (le64_to_cpu (st->clk->flags) &VMCLOCK_FLAG_TIME_MAXERROR_VALID )) { + maxerror_ns =le64_to_cpu (st->clk->time_maxerror_nanosec); + +/* If frequency error is also valid, accumulate it +* over the delta. +*/ +if (VMCLOCK_FIELD_PRESENT (st->clk, counter_period_maxerror_rate_frac_sec) && + (le64_to_cpu (st->clk->flags) &VMCLOCK_FLAG_PERIOD_MAXERROR_VALID )) { +uint64_t maxerror_rate, err_hi, err_frac, growth_ns; + +if (st->clk->counter_period_shift >=128 ) { + maxerror_ns =U64_MAX ; + goto saturate; + } + + maxerror_rate =le64_to_cpu (st->clk->counter_period_maxerror_rate_frac_sec); + err_frac =mul_u64_u64_shr_add_u64 (&err_hi, delta, + maxerror_rate, + st->clk->counter_period_shift, +0 ); + +if (err_hi >=U64_MAX /NSEC_PER_SEC ) { + maxerror_ns =U64_MAX ; + goto saturate; + } + + growth_ns = (err_hi *NSEC_PER_SEC ) + +mul_u64_u64_shr (err_frac,NSEC_PER_SEC ,64 ); + +/* Guard against overflow */ +if (U64_MAX - growth_ns < maxerror_ns) + maxerror_ns =U64_MAX ; +else + maxerror_ns += growth_ns; + } + } + +saturate: +/* PTP UAPI error_bound is 32-bit nanoseconds */ + att->error_bound = (maxerror_ns >UINT_MAX ) ? +UINT_MAX : (uint32_t )maxerror_ns; + att->valid |=PTP_ATTRS_VALID_ERROR_BOUND ; + att->timescale =vmclock_get_ptp_timescale (st->clk->time_type); +/* tai_adjust() already converted UTC to TAI before we're called */ +if (st->clk->time_type ==VMCLOCK_TIME_UTC ) + att->timescale =PTP_TIMESCALE_TAI ; + att->valid |=PTP_ATTRS_VALID_TIMESCALE ; + att->status =vmclock_get_ptp_status (st->clk->clock_status); + att->valid |=PTP_ATTRS_VALID_STATUS ; +} +static int vmclock_get_crosststamp (struct vmclock_state *st,struct ptp_system_timestamp *sts,struct system_counterval_t *system_counter, -struct timespec64 *tspec) +struct timespec64 *tspec, +struct ptp_clock_attrs *attrs) {ktime_t deadline =ktime_add (ktime_get (),VMCLOCK_MAX_WAIT );uint64_t cycle, delta, seq, frac_sec; +uint8_t clock_status =VMCLOCK_STATUS_UNKNOWN ;#ifdef CONFIG_X86 /*
@@ -121,9 +230,6 @@ static int vmclock_get_crosststamp(struct vmclock_state *st,*/ virt_rmb (); -if (st->clk->clock_status ==VMCLOCK_STATUS_UNRELIABLE ) -return -EINVAL ; -/* * When invoked for gettimex64(), fill in the pre/post system * times. The simple case is when system time is based on the
@@ -164,6 +270,17 @@ static int vmclock_get_crosststamp(struct vmclock_state *st,if (!tai_adjust (st->clk, &tspec->tv_sec))return -EINVAL ; +/* +* Capture clock state inside the seq_count loop for a +* consistent snapshot with the timestamp. The attrs path +* reports it to userspace via the status field; the legacy +* path saves it for the UNRELIABLE check after the loop. +*/ +if (attrs) +vmclock_populate_ptp_attributes (st, attrs, delta); +else + clock_status = st->clk->clock_status; +/* * This pairs with a write barrier in the hypervisor * which populates this structure.
@@ -181,6 +298,17 @@ static int vmclock_get_crosststamp(struct vmclock_state *st, system_counter->cs_id = st->cs_id; } +/* +* If attrs is set, attributes were already populated inside the +* seq_count loop. Return success even for UNRELIABLE — the attrs +* ioctl can report the status to userspace. +*/ +if (attrs) +return 0 ; + +if (clock_status ==VMCLOCK_STATUS_UNRELIABLE ) +return -EINVAL ; +return 0 ; }
@@ -193,7 +321,8 @@ static int vmclock_get_crosststamp(struct vmclock_state *st,static int vmclock_get_crosststamp_kvmclock (struct vmclock_state *st,struct ptp_system_timestamp *sts,struct system_counterval_t *system_counter, -struct timespec64 *tspec) +struct timespec64 *tspec, +struct ptp_clock_attrs *attrs) {struct pvclock_vcpu_time_info *pvti =this_cpu_pvti ();unsigned int pvti_ver;
@@ -204,7 +333,8 @@ static int vmclock_get_crosststamp_kvmclock(struct vmclock_state *st, do { pvti_ver = pvclock_read_begin(pvti); - ret = vmclock_get_crosststamp(st, sts, system_counter, tspec); + ret = vmclock_get_crosststamp(st, sts, system_counter, tspec, + attrs); if (ret) break;
@@ -233,17 +363,19 @@ static int ptp_vmclock_get_time_fn(ktime_t *device_time,struct system_counterval_t *system_counter, void *ctx) { - struct vmclock_state *st = ctx; + struct vmclock_crosststamp_ctx *vctx = ctx; +struct vmclock_state *st = vctx->st;struct timespec64 tspec;int ret;#ifdef SUPPORT_KVMCLOCK if (READ_ONCE (st->sys_cs_id) ==CSID_X86_KVM_CLK ) ret =vmclock_get_crosststamp_kvmclock (st,NULL , system_counter, - &tspec); + &tspec, vctx->attrs); else#endif - ret =vmclock_get_crosststamp (st,NULL , system_counter, &tspec); + ret =vmclock_get_crosststamp (st,NULL , system_counter, &tspec, + vctx->attrs);if (!ret) *device_time =timespec64_to_ktime (tspec);
@@ -251,12 +383,10 @@ static int ptp_vmclock_get_time_fn(ktime_t *device_time,return ret; } -static int ptp_vmclock_getcrosststamp (struct ptp_clock_info *ptp, -struct system_device_crosststamp *xtstamp) +static int ptp_vmclock_do_getcrosststamp (struct vmclock_crosststamp_ctx *vctx, +struct system_device_crosststamp *xtstamp) { - struct vmclock_state *st = container_of(ptp, struct vmclock_state, - ptp_clock_info); -int ret =get_device_system_crosststamp (ptp_vmclock_get_time_fn, st, +int ret =get_device_system_crosststamp (ptp_vmclock_get_time_fn, vctx,NULL , xtstamp);#ifdef SUPPORT_KVMCLOCK /*
@@ -265,6 +395,7 @@ static int ptp_vmclock_getcrosststamp(struct ptp_clock_info *ptp,* timestamp that get_device_system_crosststamp() *can* handle. */ if (ret == -ENODEV ) { +struct vmclock_state *st = vctx->st;struct system_time_snapshot systime_snapshot;ktime_get_snapshot_id (CLOCK_REALTIME , &systime_snapshot);
@@ -273,13 +404,23 @@ static int ptp_vmclock_getcrosststamp(struct ptp_clock_info *ptp, systime_snapshot.cs_id == CSID_X86_KVM_CLK) {WRITE_ONCE (st->sys_cs_id, systime_snapshot.cs_id); ret =get_device_system_crosststamp (ptp_vmclock_get_time_fn, - st,NULL , xtstamp); + vctx,NULL , xtstamp); } }#endif return ret; } +static int ptp_vmclock_getcrosststamp (struct ptp_clock_info *ptp, +struct system_device_crosststamp *xtstamp) +{ + struct vmclock_state *st = container_of(ptp, struct vmclock_state, + ptp_clock_info); +struct vmclock_crosststamp_ctx vctx = { .st = st }; + +return ptp_vmclock_do_getcrosststamp (&vctx, xtstamp); +} +/* * PTP clock operations */
@@ -306,7 +447,29 @@ static int ptp_vmclock_gettimex(struct ptp_clock_info *ptp, struct timespec64 *t struct vmclock_state *st = container_of(ptp, struct vmclock_state, ptp_clock_info); -return vmclock_get_crosststamp (st, sts,NULL , ts); +return vmclock_get_crosststamp (st, sts,NULL , ts,NULL ); +} + +static int ptp_vmclock_gettimexattrs (struct ptp_clock_info *ptp, +struct timespec64 *ts, +struct ptp_system_timestamp *sts, +struct ptp_clock_attrs *att) +{ + struct vmclock_state *st = container_of(ptp, struct vmclock_state, + ptp_clock_info); + +return vmclock_get_crosststamp (st, sts,NULL , ts, att); +} + +static int ptp_vmclock_getcrosststampattrs (struct ptp_clock_info *ptp, +struct system_device_crosststamp *xtstamp, +struct ptp_clock_attrs *att) +{ + struct vmclock_state *st = container_of(ptp, struct vmclock_state, + ptp_clock_info); +struct vmclock_crosststamp_ctx vctx = { .st = st, .attrs = att }; + +return ptp_vmclock_do_getcrosststamp (&vctx, xtstamp); } static int ptp_vmclock_enable(struct ptp_clock_info *ptp,
@@ -324,9 +487,11 @@ static const struct ptp_clock_info ptp_vmclock_info = { .adjfine = ptp_vmclock_adjfine, .adjtime = ptp_vmclock_adjtime, .gettimex64 = ptp_vmclock_gettimex, + .gettimexattrs64 = ptp_vmclock_gettimexattrs, .settime64 = ptp_vmclock_settime, .enable = ptp_vmclock_enable, .getcrosststamp = ptp_vmclock_getcrosststamp, + .getcrosststampattrs = ptp_vmclock_getcrosststampattrs, }; static struct ptp_clock *vmclock_ptp_register(struct device *dev,
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 5/7 net: ena: Update PHC admin interface for error bound support
In reply to Arthur KiyanovskiExtend the ENA admin interface to support error bound.
Add error_bound to the PHC response structure.
Introduce a feature version mechanism to indicate device supports error_bound, and add an error flag for error_bound retrieval failures.
This enables the driver to retrieve error_bound information from the device alongside timestamps.
--- .../net/ethernet/amazon/ena/ena_admin_defs.h | 17 +++++++++++------ drivers/net/ethernet/amazon/ena/ena_com.c | 11 ++++++----- 2 files changed, 17 insertions(+), 11 deletions(-)
drivers/net/ethernet/amazon/ena/ena_admin_defs.h +11 -6
@@ -128,12 +128,14 @@ enum ena_admin_get_stats_scope { ENA_ADMIN_ETH_TRAFFIC = 1, }; -enum ena_admin_phc_type { -ENA_ADMIN_PHC_TYPE_READLESS =0 , +enum ena_admin_phc_feature_version { +/* Readless with error_bound */ +ENA_ADMIN_PHC_FEATURE_VERSION_0 =0 , };enum ena_admin_phc_error_flags {ENA_ADMIN_PHC_ERROR_FLAG_TIMESTAMP =BIT (0 ), +ENA_ADMIN_PHC_ERROR_FLAG_ERROR_BOUND =BIT (1 ), };/* ENA SRD configuration for ENI */
@@ -1035,10 +1037,10 @@ struct ena_admin_queue_ext_feature_desc { };struct ena_admin_feature_phc_desc { -/* PHC type as defined in enum ena_admin_get_phc_type, -* used only for GET command. +/* PHC version as defined in enum ena_admin_phc_feature_version, +* used only for GET command as max supported PHC version by the device. */ -u8 type; +u8 version;/* Reserved - MBZ */ u8 reserved1[3 ];
@@ -1224,7 +1226,10 @@ struct ena_admin_phc_resp {/* PHC timestamp (nsec) */ u64 timestamp; -u8 reserved2[12 ]; +u8 reserved2[8 ]; + +/* Timestamp error limit (nsec) */ +u32 error_bound;/* Bit field of enum ena_admin_phc_error_flags */ u32 error_flags;
drivers/net/ethernet/amazon/ena/ena_com.c +6 -5
@@ -1682,11 +1682,11 @@ int ena_com_phc_config(struct ena_com_dev *ena_dev)struct ena_admin_set_feat_cmd set_feat_cmd;int ret =0 ; -/* Get device PHC default configuration */ +/* Get default device PHC configuration */ ret =ena_com_get_feature (ena_dev, &get_feat_resp,ENA_ADMIN_PHC_CONFIG , -0 ); +ENA_ADMIN_PHC_FEATURE_VERSION_0 );if (unlikely (ret)) { netdev_err(ena_dev->net_device, "Failed to get PHC feature configuration, error: %d\n",
@@ -1694,10 +1694,11 @@ int ena_com_phc_config(struct ena_com_dev *ena_dev)return ret; } -/* Supporting only readless PHC retrieval */ -if (get_feat_resp.u.phc.type !=ENA_ADMIN_PHC_TYPE_READLESS ) { +/* Supporting only PHC V0 (readless mode with error bound) */ +if (get_feat_resp.u.phc.version !=ENA_ADMIN_PHC_FEATURE_VERSION_0 ) {netdev_err (ena_dev->net_device, -"Unsupported PHC type, error: %d\n" , +"Unsupported PHC version (0x%X), error: %d\n" , + get_feat_resp.u.phc.version, -EOPNOTSUPP );return -EOPNOTSUPP ; }
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 6/7 net: ena: Add error bound to PHC communication layer
Extend the ENA PHC communication layer to retrieve error bound from the device.
Update ena_com_phc_get_timestamp() to retrieve error_bound alongside timestamps.
Add error handling and statistics for error_bound retrieval failures.
--- .../device_drivers/ethernet/amazon/ena.rst | 2 + drivers/net/ethernet/amazon/ena/ena_com.c | 40 ++++++++++++------- drivers/net/ethernet/amazon/ena/ena_com.h | 5 ++- drivers/net/ethernet/amazon/ena/ena_debugfs.c | 3 ++ drivers/net/ethernet/amazon/ena/ena_phc.c | 3 +- 5 files changed, 36 insertions(+), 17 deletions(-)
Documentation/networking/device_drivers/ethernet/amazon/ena.rst +2 -0
@@ -306,6 +306,8 @@ PHC errors must remain below 1% of all PHC requests to maintain the desired leve **phc_err_dv** | Number of failed get time attempts due to device errors (entering into block state). **phc_err_ts** | Number of failed get time attempts due to timestamp errors (entering into block state), | This occurs if driver exceeded the request limit or device received an invalid timestamp. +**phc_err_eb** | Number of failed get time attempts due to error bound errors (entering into block state), + | This occurs if device received an excessively high or invalid error bound. ================= ====================================================== PHC timeouts:
drivers/net/ethernet/amazon/ena/ena_com.c +25 -15
@@ -45,7 +45,8 @@#define ENA_PHC_DEFAULT_EXPIRE_TIMEOUT_USEC 10#define ENA_PHC_DEFAULT_BLOCK_TIMEOUT_USEC 1000#define ENA_PHC_REQ_ID_OFFSET 0xDEAD -#define ENA_PHC_ERROR_FLAGS (ENA_ADMIN_PHC_ERROR_FLAG_TIMESTAMP) +#define ENA_PHC_ERROR_FLAGS (ENA_ADMIN_PHC_ERROR_FLAG_TIMESTAMP | \ + ENA_ADMIN_PHC_ERROR_FLAG_ERROR_BOUND)/*****************************************************************************/ /*****************************************************************************/
@@ -1726,7 +1727,7 @@ int ena_com_phc_config(struct ena_com_dev *ena_dev)if (phc->expire_timeout_usec > phc->block_timeout_usec) phc->expire_timeout_usec = phc->block_timeout_usec; -/* Prepare PHC feature command */ +/* Prepare PHC config feature command */ memset (&set_feat_cmd,0x0 ,sizeof (set_feat_cmd)); set_feat_cmd.aq_common_descriptor.opcode =ENA_ADMIN_SET_FEATURE ; set_feat_cmd.feat_common.feature_id =ENA_ADMIN_PHC_CONFIG ;
@@ -1781,7 +1782,8 @@ void ena_com_phc_destroy(struct ena_com_dev *ena_dev) phc->virt_addr =NULL ; } -int ena_com_phc_get_timestamp (struct ena_com_dev *ena_dev,u64 *timestamp) +int ena_com_phc_get_timestamp (struct ena_com_dev *ena_dev,u64 *timestamp, +u32 *error_bound) {const ktime_t zero_system_time =ktime_set (0 ,0 );struct ena_com_phc_info *phc = &ena_dev->phc;
@@ -1828,6 +1830,8 @@ int ena_com_phc_get_timestamp(struct ena_com_dev *ena_dev, u64 *timestamp)* a PHC error, this occurs if device: * - exceeded the get time request limit * - received an invalid timestamp +* - received an excessively high error bound +* - received an invalid error bound */ netdev_err(ena_dev->net_device, "PHC get time request 0x%x failed (error 0x%x)\n",
@@ -1835,9 +1839,11 @@ int ena_com_phc_get_timestamp(struct ena_com_dev *ena_dev, u64 *timestamp) resp->error_flags); phc->stats.phc_err_ts += !!(resp->error_flags &ENA_ADMIN_PHC_ERROR_FLAG_TIMESTAMP ); + phc->stats.phc_err_eb += !!(resp->error_flags & +ENA_ADMIN_PHC_ERROR_FLAG_ERROR_BOUND ); }else {/* Device updated req_id during blocking time -* with valid timestamp +* with valid timestamp and error bound */ phc->stats.phc_exp++; }
@@ -1864,9 +1870,9 @@ int ena_com_phc_get_timestamp(struct ena_com_dev *ena_dev, u64 *timestamp)/* Stalling until the device updates req_id */ while (1 ) {if (unlikely (ktime_after (ktime_get (), expire_time))) { -/* Gave up waiting for updated req_id, PHC enters into -* blocked state until passing blocking time, -* during this time any get PHC timestamp will fail with +/* Gave up waiting for updated req_id, +* PHC enters into blocked state until passing blocking +* time, during this time, any request will fail with * device busy error */ ret = -EBUSY ;
@@ -1881,20 +1887,21 @@ int ena_com_phc_get_timestamp(struct ena_com_dev *ena_dev, u64 *timestamp)continue ; } -/* Ensure PHC payload (timestamp, error_flags) is read -* after req_id update is observed +/* Ensure PHC payload (timestamp, error_bound, error_flags) +* is read after req_id update is observed */ dma_rmb ();/* req_id was updated by the device which indicates that -* PHC timestamp and error_flags are updated too, -* checking errors before retrieving timestamp +* PHC timestamp, error_bound and error_flags are updated too, +* checking error flags before retrieving timestamp and +* error_bound values */ if (unlikely (resp->error_flags &ENA_PHC_ERROR_FLAGS )) { -/* Retrieved invalid PHC timestamp, PHC enters into -* blocked state until passing blocking time, -* during this time any get PHC timestamp requests -* will fail with device busy error +/* Retrieved timestamp or error bound errors, +* PHC enters into blocked state until passing blocking +* time, during this time, any request will fail with +* device busy error */ ret = -EBUSY ;break ;
@@ -1902,12 +1909,15 @@ int ena_com_phc_get_timestamp(struct ena_com_dev *ena_dev, u64 *timestamp)/* PHC timestamp value is returned to the caller */ *timestamp = resp->timestamp; +if (error_bound) + *error_bound = resp->error_bound;/* Update statistic on valid PHC timestamp retrieval */ phc->stats.phc_cnt++;/* This indicates PHC state is active */ phc->system_time = zero_system_time; +break ; }
drivers/net/ethernet/amazon/ena/ena_com.h +4 -1
@@ -216,6 +216,7 @@ struct ena_com_stats_phc {u64 phc_skp;u64 phc_err_dv;u64 phc_err_ts; +u64 phc_err_eb; };struct ena_com_admin_queue {
@@ -462,9 +463,11 @@ void ena_com_phc_destroy(struct ena_com_dev *ena_dev);/* ena_com_phc_get_timestamp - Retrieve PHC timestamp * @ena_dev: ENA communication layer struct * @timestamp: Retrieved PHC timestamp +* @error_bound: maximum possible deviation of the timestamp (nanosecond) * @return - 0 on success, negative value on failure */ -int ena_com_phc_get_timestamp (struct ena_com_dev *ena_dev,u64 *timestamp); +int ena_com_phc_get_timestamp (struct ena_com_dev *ena_dev,u64 *timestamp, +u32 *error_bound);/* ena_com_set_mmio_read_mode - Enable/disable the indirect mmio reg read mechanism * @ena_dev: ENA communication layer struct
drivers/net/ethernet/amazon/ena/ena_debugfs.c +3 -0
@@ -32,6 +32,9 @@ static int phc_stats_show(struct seq_file *file, void *priv)seq_printf (file,"phc_err_ts: %llu\n" , adapter->ena_dev->phc.stats.phc_err_ts); +seq_printf (file, +"phc_err_eb: %llu\n" , + adapter->ena_dev->phc.stats.phc_err_eb);return 0 ; }
drivers/net/ethernet/amazon/ena/ena_phc.c +2 -1
@@ -40,7 +40,8 @@ static int ena_phc_gettimex64(struct ptp_clock_info *clock_info,ptp_read_system_prets (sts); rc =ena_com_phc_get_timestamp (phc_info->adapter->ena_dev, - ×tamp_nsec); + ×tamp_nsec, +NULL );ptp_read_system_postts (sts);
Signature · 1 line
2.47.3
Arthur Kiyanovski
maintainerPATCH v5 7/7 net: ena: Implement gettimexattrs64 callback for PTP attributes
In reply to Arthur KiyanovskiImplement the gettimexattrs64 callback in the ENA driver to support the PTP_SYS_OFFSET_EXTENDED_ATTRS ioctl.
This enables applications to retrieve PHC timestamps with quality attributes through the standard PTP ioctl interface.
The ENA device currently reports only error_bound (valid bit set). Other attributes are not reported (valid bits unset).
--- drivers/net/ethernet/amazon/ena/ena_phc.c | 58 +++++++++++++++++++---- 1 file changed, 48 insertions(+), 10 deletions(-)
drivers/net/ethernet/amazon/ena/ena_phc.c +48 -10
@@ -25,6 +25,43 @@ static int ena_phc_feature_enable(struct ptp_clock_info *clock_info,return -EOPNOTSUPP ; } +static int ena_phc_gettimexattrs64 (struct ptp_clock_info *clock_info, +struct timespec64 *ts, +struct ptp_system_timestamp *sts, +struct ptp_clock_attrs *att) +{ +struct ena_phc_info *phc_info = + container_of(clock_info, struct ena_phc_info, clock_info); +u32 error_bound_nsec; +unsigned long flags; +u64 timestamp_nsec; +int rc; + +spin_lock_irqsave (&phc_info->lock, flags); + +ptp_read_system_prets (sts); + + rc =ena_com_phc_get_timestamp (phc_info->adapter->ena_dev, + ×tamp_nsec, + &error_bound_nsec); + +ptp_read_system_postts (sts); + +spin_unlock_irqrestore (&phc_info->lock, flags); + +if (rc) +return rc; + + *ts =ns_to_timespec64 (timestamp_nsec); + +if (att) { + att->error_bound = error_bound_nsec; + att->valid |=PTP_ATTRS_VALID_ERROR_BOUND ; + } + +return 0 ; +} +static int ena_phc_gettimex64 (struct ptp_clock_info *clock_info,struct timespec64 *ts,struct ptp_system_timestamp *sts)
@@ -62,16 +99,17 @@ static int ena_phc_settime64(struct ptp_clock_info *clock_info, }static struct ptp_clock_info ena_ptp_clock_info = { - .owner =THIS_MODULE , - .n_alarm =0 , - .n_ext_ts =0 , - .n_per_out =0 , - .pps =0 , - .adjtime = ena_phc_adjtime, - .adjfine = ena_phc_adjfine, - .gettimex64 = ena_phc_gettimex64, - .settime64 = ena_phc_settime64, - .enable = ena_phc_feature_enable, + .owner =THIS_MODULE , + .n_alarm =0 , + .n_ext_ts =0 , + .n_per_out =0 , + .pps =0 , + .adjtime = ena_phc_adjtime, + .adjfine = ena_phc_adjfine, + .gettimexattrs64 = ena_phc_gettimexattrs64, + .gettimex64 = ena_phc_gettimex64, + .settime64 = ena_phc_settime64, + .enable = ena_phc_feature_enable, };/* Enable/Disable PHC by the kernel, affects on the next init flow */
Signature · 1 line
2.47.3
David Woodhouse
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
In reply to Arthur KiyanovskiQuoted 41 lines · Arthur Kiyanovski
Introduce two new ioctls that extend existing PTP timestamp interfaces with clock quality information:
-
PTP_SYS_OFFSET_EXTENDED_ATTRS: ExtendsPTP_SYS_OFFSET_EXTENDED
-PTP_SYS_OFFSET_PRECISE_ATTRS: ExtendsPTP_SYS_OFFSET_PRECISEThese ioctls provide quality attributes alongside timestamps:
1.
error_bound: Maximum deviation from true time (nanoseconds), based on device's internal clock state
2.clock_status: Synchronization state (unknown, initializing, synchronized, free-running, unreliable)
3. timescale: Time reference (TAI, UTC, etc.)
4.counter_value: Raw system counter (e.g. TSC ticks) captured by the timekeeping core alongside each system timestamp
5.counter_id: Identifies the counter source (e.g. TSC, ARM arch counter)This supports three use cases:
1. Managed PHC devices (e.g., ENA, vmclock) that maintain their own synchronization and can report quality metrics directly to userspace without requiring ptp4l
2. Applications that need complete time quality information in a single call, regardless of how the PHC is synchronized
3. VMMs that need raw system counter values paired
with PTP timestamps for feed-forward clock calibration, avoiding the feedback loop inherent in NTP-style synchronizationTimescale definitions use a Continuity/Discipline framework to describe timeline properties and steering behavior consistently across all entries.
This implementation is based on the original RFC and the UAPI design discussion linked below.
...
Quoted 44 lines
drivers/ptp/ptp_chardev.c +44
-0+static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts; +unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples; + +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; +
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 469
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid) +return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime = +ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles;
I hate all this line wrapping, btw. I'll defer to the net coding style if they insist, but my preference would just be just to have longer lines. Especially when it's a block of assignments like this, the wrapped form is *much* harder to read.
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 471
Quoted 2 lines
drivers/ptp/ptp_chardev.c +2
-0+ data->timestamps[i].pre_systime.sys_counter_id = + sts.pre_sts.cs_id;
You added PTP_COUNTER_* constants as we discussed¹... but didn't you forget to *map* to them here?
¹ https://lore.kernel.org/all/877boqtg3g.ffs@tglx/
Arguably, if the timestamps have a hw_csid then you should be returning that in place of the main one which will be kvmclock or hyperv nonsense. You can do that here for extended_attrs but precise_attrs will need a bit more work (as system_device_crosststamp doesn't have the hw_* fields). I won't randomise you further by asking you to handle that though. I'll do it in a follow-up.
You can either map KVMCLOCK to unknown or give it a PTP_COUNTER_KVMCLOCK if you prefer. I suggest the former, as nobody who cares about time should be using kvmclock. And it means my promised follow-up will be providing counter data which previously wasn't provided, rather than *changing* what's provided.
Re: [PATCH v5 net-next 2/7] selftests/ptp: Extract print_system_timestamp helper in testptp
In reply to Arthur KiyanovskiQuoted 10 lines · Arthur Kiyanovski
Extract the repeated switch-on-clockid pattern used for printing system timestamps into a reusable helper function. This removes code duplication in the -x (
PTP_SYS_OFFSET_EXTENDED) output path and prepares for additional callers.The "after" timestamp lines now include the sample number prefix for consistency with the "before" lines, slightly changing the output format.
Signed-off-by Arthur Kiyanovski <[email protected]>
Re: [PATCH v5 net-next 3/7] selftests/ptp: Add testptp support for attributes ioctls
In reply to Arthur KiyanovskiQuoted 15 lines · Arthur Kiyanovski
Add support for testing the new
PTP_SYS_OFFSET_EXTENDED_ATTRSandPTP_SYS_OFFSET_PRECISE_ATTRSioctls in the testptp utility.Add a "-a" modifier that requests clock quality attributes (
error_bound, status, timescale) alongside the existing extended (-x) and precise (-X) offset requests:
-x N -a: extended offset with attributes (N samples)
-X -a: precise cross-timestamp with attributesWhen the device does not report a given attribute, print an explicit "not reported" line so all attributes are always accounted for.
These options allow testing and validation of PHC devices that provide clock quality information alongside timestamps.
Quoted 6 lines
Also display the new
clock_attrscapability in the -c output, and updateprint_system_timestampto print unrecognized clock types instead of silently dropping them.Signed-off-by Amit Bernstein <[email protected]>Signed-off-by Arthur Kiyanovski <[email protected]>
Re: [PATCH v5 net-next 4/7] ptp: ptp_vmclock: Implement attributes ioctls
In reply to Arthur KiyanovskiQuoted 17 lines · Arthur Kiyanovski
Implement the gettimexattrs64 and getcrosststampattrs callbacks in the
ptp_vmclockdriver to provide clock quality attributes through the newPTP_SYS_OFFSET_EXTENDED_ATTRSandPTP_SYS_OFFSET_PRECISE_ATTRSioctls.The
ptp_vmclockdevice exposes:
-error_bound: Derived fromtime_maxerror_nanosec, accumulated with counter frequency error (counter_period_maxerror_rate_frac_sec) over elapsed counter ticks
-clock_status: Mapped from the device'sclock_statusfield
- timescale: Always reports TAI (UTC sources are converted bytai_adjust()before the attributes are populated)The legacy ioctls return
-EINVALwhenclock_statusis UNRELIABLE since they have no way to communicate clock state to userspace. The attrs ioctls have a status field for this purpose, so they treat UNRELIABLE as success and let userspace check the status field.
Quoted 5 lines
To avoid a race where the hypervisor could update
clock_statusbetween the timestamp call and the UNRELIABLE check, the clock state is captured inside theseq_countloop for a consistent snapshot with the timestamp.Signed-off-by Arthur Kiyanovski <[email protected]>
Re: [PATCH v5 net-next 5/7] net: ena: Update PHC admin interface for error bound support
In reply to Arthur KiyanovskiQuoted 11 lines · Arthur Kiyanovski
Extend the ENA admin interface to support error bound.
Add
error_boundto the PHC response structure.
Introduce a feature version mechanism to indicate device supportserror_bound, and add an error flag forerror_boundretrieval failures.This enables the driver to retrieve
error_boundinformation from the device alongside timestamps.Signed-off-by Amit Bernstein <[email protected]>Signed-off-by Arthur Kiyanovski <[email protected]>
Re: [PATCH v5 net-next 6/7] net: ena: Add error bound to PHC communication layer
In reply to Arthur KiyanovskiQuoted 9 lines · Arthur Kiyanovski
Extend the ENA PHC communication layer to retrieve error bound from the device.
Update
ena_com_phc_get_timestamp()to retrieveerror_boundalongside timestamps.
Add error handling and statistics forerror_boundretrieval failures.Signed-off-by Amit Bernstein <[email protected]>Signed-off-by Arthur Kiyanovski <[email protected]>
Re: [PATCH v5 net-next 7/7] net: ena: Implement gettimexattrs64 callback for PTP attributes
In reply to Arthur KiyanovskiQuoted 11 lines · Arthur Kiyanovski
Implement the gettimexattrs64 callback in the ENA driver to support the
PTP_SYS_OFFSET_EXTENDED_ATTRSioctl.This enables applications to retrieve PHC timestamps with quality attributes through the standard PTP ioctl interface.
The ENA device currently reports only
error_bound(valid bit set). Other attributes are not reported (valid bits unset).Signed-off-by Amit Bernstein <[email protected]>Signed-off-by Arthur Kiyanovski <[email protected]>
David Woodhouse
maintainerQuoted 4 lines · Arthur Kiyanovski
This series adds quality attributes to PTP Hardware Clock (PHC) timestamps, allowing userspace to obtain error bound, clock status, timescale, and system counter values alongside timestamps in a single call.
I've reworked my linux-phc extraction to sit on top of this (using temporary commits for now; I assume I'll rebase on top of net-next when this lands there).
It (almost, qv) passes a basic smoke test, feeding vmclock in QEMU with synthesised error-bound data, which ends up correctly visible to userspace — apart from the csid.
Re: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
In reply to David WoodhouseQuoted 51 lines
Quoted 51 lines
drivers/ptp/ptp_chardev.c +51
-0+static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts; +unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples; + +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; + +/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid) +return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime =
Quoted 8 lines
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 469
Quoted 3 lines
drivers/ptp/ptp_chardev.c +3
-0+ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles;I hate all this line wrapping, btw. I'll defer to the net coding style if they insist, but my preference would just be just to have longer lines. Especially when it's a block of assignments like this, the wrapped form is *much* harder to read.
This is a long function, probably longer than the coding style suggests. So one option is to move the code within the for loop into a helper. That might then allow unwrapped lines?
That is kind of the point of the line length limit, to make you break code up into lots of small functions which do one thing.
Andrew
David Woodhouse
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
Quoted 6 lines · Andrew Lunn
Quoted 4 lines
I hate all this line wrapping, btw. I'll defer to the net coding style if they insist, but my preference would just be just to have longer lines. Especially when it's a block of assignments like this, the wrapped form is *much* harder to read.
Quoted 6 lines
This is a long function, probably longer than the coding style suggests. So one option is to move the code within the for loop into a helper. That might then allow unwrapped lines?
That is kind of the point of the line length limit, to make you break code up into lots of small functions which do one thing.
Huh? Are we looking at the same function? The version of ptp_sys_offset_extended_attrs() I'm looking at, having fixed up the gratuitous line wrapping, is about 60 lines — none of which are wider than 100 characters. It's a simple setup and then loop over n_samples of data captures. A helper function would only serve to obfuscate it.
static long ptp_sys_offset_extended_attrs(struct ptp_clock *ptp, void __user *arg)
{
struct ptp_sys_offset_attrs *data __free(kfree) = NULL;
struct ptp_attrs_request request;
struct ptp_system_timestamp sts;
unsigned int n_samples;
int err;
if (copy_from_user(&request, arg, sizeof(request)))
return -EFAULT;
if (request.valid ||
request.num_samples > PTP_MAX_SAMPLES ||
request.num_samples == 0)
return -EINVAL;
err = ptp_validate_sys_offset_clockid(request.clock_id);
if (err)
return err;
n_samples = request.num_samples;
sts.clockid = request.clock_id;
data = kzalloc(struct_size(data, timestamps, n_samples), GFP_KERNEL);
if (!data)
return -ENOMEM;
data->request.num_samples = n_samples;
for (unsigned int i = 0; i < n_samples; i++) {
struct ptp_clock_attrs att = {};
struct timespec64 ts;
if (ptp->info->gettimexattrs64)
err = ptp->info->gettimexattrs64(ptp->info, &ts,
&sts, &att);
else if (ptp->info->gettimex64)
err = ptp->info->gettimex64(ptp->info, &ts, &sts);
else
return -EOPNOTSUPP;
if (err)
return err;
/* Filter out disabled or unavailable clocks */
if (!sts.pre_sts.valid || !sts.post_sts.valid)
return -EINVAL;
data->timestamps[i].pre_systime.sys_time = ktime_to_ns(sts.pre_sts.systime);
data->timestamps[i].pre_systime.sys_rawtime = ktime_to_ns(sts.pre_sts.monoraw);
data->timestamps[i].pre_systime.sys_counter = sts.pre_sts.cycles;
data->timestamps[i].pre_systime.sys_counter_id = sts.pre_sts.cs_id;
data->timestamps[i].devtime.device_time.sec = ts.tv_sec;
data->timestamps[i].devtime.device_time.nsec = ts.tv_nsec;
data->timestamps[i].devtime.attrs = att;
data->timestamps[i].post_systime.sys_time = ktime_to_ns(sts.post_sts.systime);
data->timestamps[i].post_systime.sys_rawtime = ktime_to_ns(sts.post_sts.monoraw);
data->timestamps[i].post_systime.sys_counter = sts.post_sts.cycles;
data->timestamps[i].post_systime.sys_counter_id = sts.post_sts.cs_id;
}
return copy_to_user(arg, data,
struct_size(data, timestamps, n_samples)) ? -EFAULT : 0;
}Jakub Kicinski
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
Quoted 9 lines · On Mon, 27 Jul 2026 14:32:23 +0100 David Woodhouse wrote:
Quoted 9 lines
Quoted 4 lines
I hate all this line wrapping, btw. I'll defer to the net coding style if they insist, but my preference would just be just to have longer lines. Especially when it's a block of assignments like this, the wrapped form is *much* harder to read.
This is a long function, probably longer than the coding style suggests. So one option is to move the code within the for loop into a helper. That might then allow unwrapped lines?
Quoted 8 lines
Quoted 2 lines
That is kind of the point of the line length limit, to make you break code up into lots of small functions which do one thing.
Huh? Are we looking at the same function? The version of
ptp_sys_offset_extended_attrs()I'm looking at, having fixed up the gratuitous line wrapping, is about 60 lines — none of which are wider than 100 characters. It's a simple setup and then loop overn_samplesof data captures. A helper function would only serve to obfuscate it.
1. temporary variables for long deref chains help both readability and the compiler
2. our 80 char rule is obviously negotiable.
But more often than not the best solution is to refactor the code.
Jakub Kicinski
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
In reply to Arthur KiyanovskiThis is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
ptp: Add ioctls for PHC timestamps with quality attributes
This introduces PTP_SYS_OFFSET_EXTENDED_ATTRS and PTP_SYS_OFFSET_PRECISE_ATTRS, extending the existing extended/precise offset ioctls with clock quality attributes (error bound, timescale, sync status) and raw system counter fields. New driver callbacks gettimexattrs64 and getcrosststampattrs are added to ptp_clock_info.
A few questions inline below.
drivers/ptp/ptp_chardev.c static long ptp_clock_getcaps(struct ptp_clock *ptp, void __user *arg) · line 195
Quoted 11 lines
drivers/ptp/ptp_chardev.c +2
-0@@ -190,6 +190,8 @@ static long ptp_clock_getcaps(struct ptp_clock *ptp, void __user *arg) .cross_timestamping = ptp->info->getcrosststamp != NULL, .adjust_phase = ptp->info->adjphase != NULL && ptp->info->getmaxphase != NULL, + .extended_attrs = ptp->info->gettimexattrs64 != NULL, + .precise_attrs = ptp->info->getcrosststampattrs != NULL, };
[Medium]
Are the capability bits consistent with what the ioctls will actually accept?
The caps are set based only on the presence of the new *_attrs callbacks, but the ioctl handlers fall back to gettimex64/getcrosststamp when the *_attrs callback is absent:
if (ptp->info->gettimexattrs64)
err = ptp->info->gettimexattrs64(ptp->info, &ts, &sts, &att);
else if (ptp->info->gettimex64)
err = ptp->info->gettimex64(ptp->info, &ts, &sts);
else
return -EOPNOTSUPP;A userspace that respects the capability bits would refuse to call the new ioctl on drivers that would in fact serve it via the fallback. Is the fallback intended, and if so, should the caps advertise it? The commit message does not describe this behavior.
[ ... ]
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 420
Quoted 9 lines
drivers/ptp/ptp_chardev.c +5
-0@@ -404,6 +413,130 @@ static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg,return copy_to_user (arg, extoff,sizeof (*extoff)) ? -EFAULT :0 ; } +static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts;
[Medium]
Can this leak uninitialized stack contents to userspace?
Only sts.clockid is initialized below, and sts is reused across loop iterations. If any driver's gettimex64/gettimexattrs64 returns success without touching pre_sts/post_sts on the sts pointer, sts.pre_sts.valid is either uninitialized (first iteration) or stale (later iterations), and the "if (!sts.pre_sts.valid || !sts.post_sts.valid)" gate can admit a partially-populated snapshot.
On the success path the code then copies pre_sts.cycles, pre_sts.cs_id, pre_sts.monoraw, pre_sts.systime and the post_sts equivalents to userspace. The pre-existing ptp_sys_offset_extended() has the same shape but only copied systime, so the exposed surface is now wider. Would something like:
struct ptp_system_timestamp sts = {};inside the loop (or at declaration) be safer?
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 430
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ;
[Medium]
Should this also reject non-zero request.rsv[]?
The kernel-doc for struct ptp_attrs_request says "Reserved for future use, must be zero", but rsv[3] is never validated. The neighboring ptp_sys_offset_extended() enforces the same contract on its own reserved fields:
if (extoff->n_samples > PTP_MAX_SAMPLES || extoff->rsv[0] || extoff->rsv[1])
return -EINVAL;Without a similar check, existing userspace binaries can start sending garbage in rsv[], which then blocks any future repurposing of those bytes.
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 443
Quoted 13 lines
drivers/ptp/ptp_chardev.c +13
-0+ + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples;
[Low]
This is a _IOWR ioctl and the whole struct (including data->request) is copied back to userspace at the end, but only data->request.num_samples is populated. data->request.valid, data->request.clock_id and data->request.rsv[] therefore always come back as zero, silently overwriting the values userspace put in the request buffer.
Is that intentional? It is not mentioned in the commit message, and it locks in a slightly surprising contract for future extensions.
Quoted 18 lines
drivers/ptp/ptp_chardev.c +18
-0+ +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; + +/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid)
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 471
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime = +ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles; + data->timestamps[i].pre_systime.sys_counter_id = + sts.pre_sts.cs_id;
[Critical]
Does the sys_counter_id assignment produce the correct UAPI value?
sts.pre_sts.cs_id is enum clocksource_ids frominclude/linux/clocksource_ids.h:
CSID_GENERIC = 0,
CSID_ARM_ARCH_COUNTER = 1,
CSID_S390_TOD = 2,
CSID_X86_TSC_EARLY = 3,
CSID_X86_TSC = 4,
CSID_X86_KVM_CLK = 5,
CSID_X86_ART = 6,But sys_counter_id is documented as enum ptp_counter_id from the UAPI:
PTP_COUNTER_UNKNOWN = 0,
PTP_COUNTER_X86_TSC = 1,
PTP_COUNTER_ARM_ARCH = 2,
With this direct assignment, on ARM sts.pre_sts.cs_id == 1 (CSID_ARM_ARCH_COUNTER) is reported to userspace as PTP_COUNTER_X86_TSC. On x86, real CSID_X86_TSC (4) has no defined UAPI meaning. On s390, CSID_S390_TOD (2) is reported as PTP_COUNTER_ARM_ARCH.
Should the ioctl translate cs_id into the UAPI enum before copying it out? Once released, later adding a translation layer would break any userspace that started decoding the raw kernel values.
[High]
On clocksources that are derived/virtualised (kvm-clock, scaled arch counter, ART, ...), the raw underlying counter identity is exposed by system_time_snapshot as hw_cycles/hw_csid rather than cycles/cs_id. The new UAPI only propagates cycles/cs_id.
The commit message says one motivation is:
3. VMMs that need raw system counter values paired with PTP timestamps for feed-forward clock calibration ...
but a guest on a derived clocksource will not see the underlying hardware counter identity or value here. Should the UAPI also expose hw_cycles/hw_csid, given that the struct is frozen once merged?
Quoted 3 lines
drivers/ptp/ptp_chardev.c +3
-0+ data->timestamps[i].devtime.device_time.sec = ts.tv_sec; + data->timestamps[i].devtime.device_time.nsec = ts.tv_nsec; + data->timestamps[i].devtime.attrs = att;
[ ... ]
Quoted 22 lines
drivers/ptp/ptp_chardev.c +22
-0+} + +static long ptp_sys_offset_precise_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct system_device_crosststamp xtstamp; +struct ptp_attrs_request request; +struct ptp_clock_attrs att = {}; +struct timespec64 ts; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples !=1 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; +
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 518
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+ data =kzalloc (struct_size (data, timestamps,1 ),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + +if (ptp->info->getcrosststampattrs) + err = ptp->info->getcrosststampattrs (ptp->info, &xtstamp, &att); +else if (ptp->info->getcrosststamp) + err = ptp->info->getcrosststamp (ptp->info, &xtstamp); +else +return -EOPNOTSUPP ;
[High]
Can any driver using get_device_system_crosststamp() actually serve this ioctl?
xtstamp is declared without an initializer, so xtstamp.clock_id holds whatever was on the stack. The pre-existing ptp_sys_offset_precise() explicitly sets it:
struct system_device_crosststamp xtstamp = {
.clock_id = CLOCK_REALTIME,
};Drivers commonly forward xtstamp to get_device_system_crosststamp() in kernel/time/timekeeping.c, which switches on xtstamp->clock_id and falls through to:
default:
WARN_ON_ONCE(1);
return -ENODEV;So on most drivers implementing getcrosststamp (kvm, mlx5, ice, igc, bnxt, s390, ...), an unprivileged caller of PTP_SYS_OFFSET_PRECISE_ATTRS would trigger a first-hit WARN and get -ENODEV.
In addition, request.clock_id is validated by ptp_validate_sys_offset_clockid() but never assigned to xtstamp.clock_id, so the userspace-selected clock is silently dropped even for the paths documented in the UAPI header (CLOCK_MONOTONIC, CLOCK_MONOTONIC_RAW, CLOCK_AUX...).
Should xtstamp.clock_id be set from request.clock_id (and xtstamp zeroed before use)?
[ ... ]
Quoted 5 lines
drivers/ptp/ptp_clock.c +0
-0
drivers/ptp/ptp_clock.c static int ptp_clock_gettime(struct posix_clock *pc, struct timespec64 *tp) · line 120
Quoted 10 lines
drivers/ptp/ptp_clock.c +3
-1@@ -112,7 +112,9 @@ static int ptp_clock_gettime(struct posix_clock *pc, struct timespec64 *tp) struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);int err; -if (ptp->info->gettimex64) +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, tp,NULL ,NULL ); +else if (ptp->info->gettimex64) err = ptp->info->gettimex64 (ptp->info, tp,NULL );else err = ptp->info->gettime64 (ptp->info, tp);
[Low]
This call site passes both sts and att as NULL, but the kernel-doc for gettimexattrs64 only documents that att may be NULL ("fills @att (if not NULL)"). The dual-NULL contract on sts is implicitly inherited from gettimex64 but is not stated.
Would it be worth spelling out in the kernel-doc that both sts and att may be NULL, so a new driver author does not skip the NULL check on sts?
[ ... ]
Signature · 1 line
pw-bot: cr
Arthur Kiyanovski
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
In reply to David WoodhouseQuoted 97 lines · David Woodhouse
Quoted 41 lines · Arthur Kiyanovski
Introduce two new ioctls that extend existing PTP timestamp interfaces with clock quality information:
-
PTP_SYS_OFFSET_EXTENDED_ATTRS: ExtendsPTP_SYS_OFFSET_EXTENDED
-PTP_SYS_OFFSET_PRECISE_ATTRS: ExtendsPTP_SYS_OFFSET_PRECISEThese ioctls provide quality attributes alongside timestamps:
1.
error_bound: Maximum deviation from true time (nanoseconds), based on device's internal clock state
2.clock_status: Synchronization state (unknown, initializing, synchronized, free-running, unreliable)
3. timescale: Time reference (TAI, UTC, etc.)
4.counter_value: Raw system counter (e.g. TSC ticks) captured by the timekeeping core alongside each system timestamp
5.counter_id: Identifies the counter source (e.g. TSC, ARM arch counter)This supports three use cases:
1. Managed PHC devices (e.g., ENA, vmclock) that maintain their own synchronization and can report quality metrics directly to userspace without requiring ptp4l
2. Applications that need complete time quality information in a single call, regardless of how the PHC is synchronized
3. VMMs that need raw system counter values paired
with PTP timestamps for feed-forward clock calibration, avoiding the feedback loop inherent in NTP-style synchronizationTimescale definitions use a Continuity/Discipline framework to describe timeline properties and steering behavior consistently across all entries.
This implementation is based on the original RFC and the UAPI design discussion linked below.
...
Quoted 51 lines
drivers/ptp/ptp_chardev.c +51
-0+static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts; +unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples; + +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; + +/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid) +return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime =
Quoted 9 lines
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 469
Quoted 3 lines
drivers/ptp/ptp_chardev.c +3
-0+ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles;I hate all this line wrapping, btw. I'll defer to the net coding style if they insist, but my preference would just be just to have longer lines. Especially when it's a block of assignments like this, the wrapped form is *much* harder to read.
Agreed — I'll reduce the wrapping in v6 (a local temp var + a small helper make that block read much better). Thanks.
Quoted 8 lines
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 471
Quoted 2 lines
drivers/ptp/ptp_chardev.c +2
-0+ data->timestamps[i].pre_systime.sys_counter_id = + sts.pre_sts.cs_id;You added PTP_COUNTER_* constants as we discussed¹... but didn't you forget to *map* to them here?
Good catch — you're right, that's a bug. I'll add the csid→PTP_COUNTER_* mapping in v6.
Quoted 8 lines
Arguably, if the timestamps have a
hw_csidthen you should be returning that in place of the main one which will be kvmclock or hyperv nonsense. You can do that here forextended_attrsbutprecise_attrswill need a bit more work (assystem_device_crosststampdoesn't have the hw_* fields). I won't randomise you further by asking you to handle that though. I'll do it in a follow-up.
Thanks — I'll leave the hw_csid part for your follow-up as you offered. This series exposes the base cs_id and leaves room to add it without an ABI change.
Quoted 5 lines
You can either map KVMCLOCK to unknown or give it a
PTP_COUNTER_KVMCLOCKif you prefer. I suggest the former, as nobody who cares about time should be using kvmclock. And it means my promised follow-up will be providing counter data which previously wasn't provided, rather than *changing* what's provided.
Will do the former in v6 — map KVMCLOCK to UNKNOWN — so your follow-up adds new counter data rather than changing existing values. Thanks.
Arthur Kiyanovski
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
In reply to Jakub KicinskiQuoted 43 lines · Jakub Kicinski
This is an AI-generated review of your patch. The human sending this email has considered the AI review valid, or at least plausible.
---
ptp: Add ioctls for PHC timestamps with quality attributesThis introduces
PTP_SYS_OFFSET_EXTENDED_ATTRSandPTP_SYS_OFFSET_PRECISE_ATTRS, extending the existing extended/precise offset ioctls with clock quality attributes (error bound, timescale, sync status) and raw system counter fields. New driver callbacks gettimexattrs64 and getcrosststampattrs are added toptp_clock_info.A few questions inline below.
drivers/ptp/ptp_chardev.c static long ptp_clock_getcaps(struct ptp_clock *ptp, void __user *arg) · line 195
Quoted 11 lines
drivers/ptp/ptp_chardev.c +2
-0@@ -190,6 +190,8 @@ static long ptp_clock_getcaps(struct ptp_clock *ptp, void __user *arg) .cross_timestamping = ptp->info->getcrosststamp != NULL, .adjust_phase = ptp->info->adjphase != NULL && ptp->info->getmaxphase != NULL, + .extended_attrs = ptp->info->gettimexattrs64 != NULL, + .precise_attrs = ptp->info->getcrosststampattrs != NULL, };[Medium]
Are the capability bits consistent with what the ioctls will actually accept?The caps are set based only on the presence of the new
*_attrscallbacks, but the ioctl handlers fall back to gettimex64/getcrosststamp when the*_attrscallback is absent:if (ptp->info->gettimexattrs64) err = ptp->info->gettimexattrs64(ptp->info, &ts, &sts, &att); else if (ptp->info->gettimex64) err = ptp->info->gettimex64(ptp->info, &ts, &sts); else return -EOPNOTSUPP;
Quoted 5 lines
A userspace that respects the capability bits would refuse to call the new ioctl on drivers that would in fact serve it via the fallback. Is the fallback intended, and if so, should the caps advertise it? The commit message does not describe this behavior.
The fallback is intentional. I'll widen the caps in v6 so they advertise it (gettimexattrs64 || gettimex64, getcrosststampattrs || getcrosststamp) and document the behavior in the commit message. Thanks.
Quoted 28 lines
[ ... ]
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 420
Quoted 9 lines
drivers/ptp/ptp_chardev.c +5
-0@@ -404,6 +413,130 @@ static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg,return copy_to_user (arg, extoff,sizeof (*extoff)) ? -EFAULT :0 ; } +static long ptp_sys_offset_extended_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct ptp_attrs_request request; +struct ptp_system_timestamp sts;[Medium]
Can this leak uninitialized stack contents to userspace?Only sts.clockid is initialized below, and sts is reused across loop iterations. If any driver's gettimex64/gettimexattrs64 returns success without touching pre_sts/post_sts on the sts pointer, sts.pre_sts.valid is either uninitialized (first iteration) or stale (later iterations), and the "if (!sts.pre_sts.valid || !sts.post_sts.valid)" gate can admit a partially-populated snapshot.
On the success path the code then copies pre_sts.cycles, pre_sts.cs_id, pre_sts.monoraw, pre_sts.systime and the
post_stsequivalents to userspace. The pre-existingptp_sys_offset_extended()has the same shape but only copied systime, so the exposed surface is now wider. Would something like:
Quoted 4 lines
struct ptp_system_timestamp sts = {};inside the loop (or at declaration) be safer?
Yes — I'll zero-initialize sts per loop iteration in v6, so nothing uninitialized or stale can reach userspace. Thanks.
Quoted 19 lines
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 430
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+unsigned int n_samples; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples >PTP_MAX_SAMPLES || + request.num_samples ==0 ) +return -EINVAL ;[Medium]
Should this also reject non-zero request.rsv[]?The kernel-doc for struct
ptp_attrs_requestsays "Reserved for future use, must be zero", but rsv[3] is never validated. The neighboringptp_sys_offset_extended()enforces the same contract on its own reserved fields:
Quoted 7 lines
if (extoff->n_samples > PTP_MAX_SAMPLES || extoff->rsv[0] || extoff->rsv[1]) return -EINVAL;Without a similar check, existing userspace binaries can start sending garbage in rsv[], which then blocks any future repurposing of those bytes.
Agreed — v6 will reject a non-zero rsv[], matching ptp_sys_offset_extended(). Thanks.
Quoted 21 lines
drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 443
Quoted 13 lines
drivers/ptp/ptp_chardev.c +13
-0+ + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; + + n_samples = request.num_samples; + sts.clockid = request.clock_id; + + data =kzalloc (struct_size (data, timestamps, n_samples),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + + data->request.num_samples = n_samples;[Low]
This is a_IOWRioctl and the whole struct (includingdata->request) is copied back to userspace at the end, but onlydata->request.num_samplesis populated.data->request.valid,data->request.clock_idand data->request.rsv[] therefore always come back as zero, silently overwriting the values userspace put in the request buffer.
Quoted 3 lines
Is that intentional? It is not mentioned in the commit message, and it locks in a slightly surprising contract for future extensions.
Not intentional — v6 will echo the full request back so valid/clock_id/num_samples/rsv round-trip as submitted. Thanks.
Quoted 49 lines
Quoted 18 lines
drivers/ptp/ptp_chardev.c +18
-0+ +for (unsigned int i =0 ; i < n_samples; i++) { +struct ptp_clock_attrs att = {}; +struct timespec64 ts; + +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, &ts, + &sts, &att); +else if (ptp->info->gettimex64) + err = ptp->info->gettimex64 (ptp->info, &ts, &sts); +else +return -EOPNOTSUPP ; + +if (err) +return err; + +/* Filter out disabled or unavailable clocks */ +if (!sts.pre_sts.valid || !sts.post_sts.valid)drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 471
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+return -EINVAL ; + + data->timestamps[i].pre_systime.sys_time = +ktime_to_ns (sts.pre_sts.systime); + data->timestamps[i].pre_systime.sys_rawtime = +ktime_to_ns (sts.pre_sts.monoraw); + data->timestamps[i].pre_systime.sys_counter = + sts.pre_sts.cycles; + data->timestamps[i].pre_systime.sys_counter_id = + sts.pre_sts.cs_id;[Critical]
Does thesys_counter_idassignment produce the correct UAPI value?sts.pre_sts.cs_id is enum
clocksource_idsfrominclude/linux/clocksource_ids.h:CSID_GENERIC = 0, CSID_ARM_ARCH_COUNTER = 1, CSID_S390_TOD = 2, CSID_X86_TSC_EARLY = 3, CSID_X86_TSC = 4, CSID_X86_KVM_CLK = 5, CSID_X86_ART = 6,But
sys_counter_idis documented as enumptp_counter_idfrom the UAPI:
PTP_COUNTER_UNKNOWN= 0,
PTP_COUNTER_X86_TSC= 1,
PTP_COUNTER_ARM_ARCH= 2,
Quoted 9 lines
With this direct assignment, on ARM sts.pre_sts.cs_id == 1 (
CSID_ARM_ARCH_COUNTER) is reported to userspace asPTP_COUNTER_X86_TSC. On x86, realCSID_X86_TSC(4) has no defined UAPI meaning. On s390,CSID_S390_TOD(2) is reported asPTP_COUNTER_ARM_ARCH.Should the ioctl translate
cs_idinto the UAPI enum before copying it out? Once released, later adding a translation layer would break any userspace that started decoding the raw kernel values.
Good catch — that's a bug. v6 will translate enum clocksource_ids to the UAPI enum ptp_counter_id before copying out. Thanks.
Quoted 6 lines
[High]
On clocksources that are derived/virtualised (kvm-clock, scaled arch counter, ART, ...), the raw underlying counter identity is exposed bysystem_time_snapshotas hw_cycles/hw_csid rather than cycles/cs_id. The new UAPI only propagates cycles/cs_id.
Quoted 9 lines
The commit message says one motivation is:
3. VMMs that need raw system counter values paired with PTP timestamps for feed-forward clock calibration ...
but a guest on a derived clocksource will not see the underlying hardware counter identity or value here. Should the UAPI also expose hw_cycles/hw_csid, given that the struct is frozen once merged?
This is being handled as a follow-up (David Woodhouse offered on-list to take the hw_csid side). This series exposes the base cs_id/cycles, and the UAPI leaves room to add the hw_* values without an ABI change.
Quoted 63 lines
Quoted 3 lines
drivers/ptp/ptp_chardev.c +3
-0+ data->timestamps[i].devtime.device_time.sec = ts.tv_sec; + data->timestamps[i].devtime.device_time.nsec = ts.tv_nsec; + data->timestamps[i].devtime.attrs = att;[ ... ]
Quoted 22 lines
drivers/ptp/ptp_chardev.c +22
-0+} + +static long ptp_sys_offset_precise_attrs (struct ptp_clock *ptp,void __user *arg) +{ + struct ptp_sys_offset_attrs *data __free(kfree) = NULL; +struct system_device_crosststamp xtstamp; +struct ptp_attrs_request request; +struct ptp_clock_attrs att = {}; +struct timespec64 ts; +int err; + +if (copy_from_user (&request, arg,sizeof (request))) +return -EFAULT ; + +if (request.valid || + request.num_samples !=1 ) +return -EINVAL ; + + err =ptp_validate_sys_offset_clockid (request.clock_id); +if (err) +return err; +drivers/ptp/ptp_chardev.c static long ptp_sys_offset_extended(struct ptp_clock *ptp, void __user *arg, · line 518
Quoted 10 lines
drivers/ptp/ptp_chardev.c +10
-0+ data =kzalloc (struct_size (data, timestamps,1 ),GFP_KERNEL ); +if (!data) +return -ENOMEM ; + +if (ptp->info->getcrosststampattrs) + err = ptp->info->getcrosststampattrs (ptp->info, &xtstamp, &att); +else if (ptp->info->getcrosststamp) + err = ptp->info->getcrosststamp (ptp->info, &xtstamp); +else +return -EOPNOTSUPP ;[High]
Can any driver usingget_device_system_crosststamp()actually serve this ioctl?xtstamp is declared without an initializer, so xtstamp.clock_id holds whatever was on the stack. The pre-existing
ptp_sys_offset_precise()explicitly sets it:struct system_device_crosststamp xtstamp = { .clock_id = CLOCK_REALTIME, };Drivers commonly forward xtstamp to
get_device_system_crosststamp()inkernel/time/timekeeping.c, which switches onxtstamp->clock_idand falls through to:default: WARN_ON_ONCE(1); return -ENODEV;So on most drivers implementing getcrosststamp (kvm, mlx5, ice, igc, bnxt, s390, ...), an unprivileged caller of
PTP_SYS_OFFSET_PRECISE_ATTRSwould trigger a first-hit WARN and get-ENODEV.
Quoted 9 lines
In addition, request.clock_id is validated by
ptp_validate_sys_offset_clockid()but never assigned to xtstamp.clock_id, so the userspace-selected clock is silently dropped even for the paths documented in the UAPI header (CLOCK_MONOTONIC,CLOCK_MONOTONIC_RAW,CLOCK_AUX...).Should xtstamp.clock_id be set from request.clock_id (and xtstamp zeroed before use)?
Real bug, thanks. v6 zero-initializes xtstamp and sets clock_id from the validated request. To avoid the get_device_system_crosststamp() default WARN, precise will validate clock_id against a dedicated allowlist (REALTIME
+ AUX) and return -EINVAL for anything else.
Quoted 24 lines
[ ... ]
Quoted 5 lines
drivers/ptp/ptp_clock.c +0
-0drivers/ptp/ptp_clock.c static int ptp_clock_gettime(struct posix_clock *pc, struct timespec64 *tp) · line 120
Quoted 10 lines
drivers/ptp/ptp_clock.c +3
-1@@ -112,7 +112,9 @@ static int ptp_clock_gettime(struct posix_clock *pc, struct timespec64 *tp) struct ptp_clock *ptp = container_of(pc, struct ptp_clock, clock);int err; -if (ptp->info->gettimex64) +if (ptp->info->gettimexattrs64) + err = ptp->info->gettimexattrs64 (ptp->info, tp,NULL ,NULL ); +else if (ptp->info->gettimex64) err = ptp->info->gettimex64 (ptp->info, tp,NULL );else err = ptp->info->gettime64 (ptp->info, tp);[Low]
This call site passes both sts and att as NULL, but the kernel-doc for gettimexattrs64 only documents that att may be NULL ("fills @att (if not NULL)"). The dual-NULL contract on sts is implicitly inherited from gettimex64 but is not stated.
Quoted 3 lines
Would it be worth spelling out in the kernel-doc that both sts and att may be NULL, so a new driver author does not skip the NULL check on sts?
Yes — v6 will state that both sts and att may be NULL. Thanks.
Quoted 2 lines
[ ... ]
David Woodhouse
maintainerRe: [PATCH v5 net-next 1/7] ptp: Add ioctls for PHC timestamps with quality attributes
Quoted 14 lines · Arthur Kiyanovski
Quoted 7 lines
if (
ptp->info->gettimexattrs64)
err =ptp->info->gettimexattrs64(ptp->info, &ts, &sts, &att); else if (ptp->info->gettimex64)
err =ptp->info->gettimex64(ptp->info, &ts, &sts); else
return-EOPNOTSUPP;Quoted 5 lines
A userspace that respects the capability bits would refuse to call the new ioctl on drivers that would in fact serve it via the fallback. Is the fallback intended, and if so, should the caps advertise it? The commit message does not describe this behavior.
Quoted 3 lines
The fallback is intentional. I'll widen the caps in v6 so they advertise it (gettimexattrs64 || gettimex64, getcrosststampattrs || getcrosststamp) and document the behavior in the commit message. Thanks.
FWIW I kind of hate this pattern. I understand it's how PTP does things, so I'm not suggesting you change it now, but these are all *kernel* functions not userspace API, so why not just add the new argument to the existing function rather than adding a new function?
In the linux-phc rework it basically all collapses down to *one* function that's needed to read a clock, with a bunch of optional arguments. (Which I guess means that in a very short period of time, I'll stop caring how awful it is in the PTP code...)