Precision Timing
The precision timing subsystem provides a small set of reusable mechanisms for
PTP, gPTP, and other users that control high-resolution clocks. Enable it with
CONFIG_PRECISION_TIMING.
Note
The API is at experimental maturity and may still change. A protocol does not change maturity by using this subsystem.
The subsystem deliberately does not implement synchronization policy. PTP and gPTP continue to own their protocol state machines, clock selection, step thresholds, sample acceptance, lock detection, source-loss handling, and diagnostics.
Precision time
precision_time_t is a signed 64-bit nanosecond value. Checked
addition and subtraction helpers report overflow. The type does not identify a
time domain or timescale; modelling TAI, UTC, PHCs, monotonic time, and protocol
relationships is outside this API.
Precision clock
precision_clock dispatches four mandatory clock operations:
read the current time;
set an absolute time;
apply a phase adjustment; and
set a rate offset from the nominal frequency as parts per million with a 16-bit binary fractional field.
All operations must be implemented by a clock adapter. Adjustment ranges and other hardware constraints remain the responsibility of the underlying clock implementation.
precision_clock_ptp_adapter exposes an existing Zephyr PTP clock
device through this interface. It performs the required conversion between
net_ptp_time and precision_time_t; it does not add generic
capability discovery or synchronization state.
PI controller
precision_pi is an instance-based proportional-integral controller.
Each instance stores its own gains, limits and integral term.
precision_pi_update_interval() takes an error sample and the interval
since the previous sample; the update is equivalent to:
integral = clamp(integral + (ki / interval) * error, integral_limit);
output = clamp((kp / interval) * error + integral, output_limit);
The gains are given for an interval of 1. When the plant integrates the output
over the interval, as a clock does with a rate correction, the loop gain per
sample is then the same for any interval. precision_pi_update() is the
same update with an interval of 1.
precision_pi_set_limits() sets the two limits; a limit of 0 disables it,
which is the state after precision_pi_init(). While the output is at its
limit, the integral term keeps its value instead of moving further towards the
limit, so it does not wind up.
The controller does not decide whether an error should be stepped, rejected, or used for rate adjustment. It also does not track synchronization, acquisition, lock, holdover, source timeout, or clock faults. Callers own those decisions and reset the accumulated integral term when their policy requires it.
The PTP and gPTP integrations initialize their controllers from
CONFIG_PRECISION_TIMING_PI_KP and
CONFIG_PRECISION_TIMING_PI_KI, with the limits from
CONFIG_PRECISION_TIMING_PI_INTEGRAL_LIMIT_PPM and
CONFIG_PRECISION_TIMING_PI_OUTPUT_LIMIT_PPM. The integer gain
values express the gains in thousandths. Direct users of
precision_pi_init() may provide different gains for each controller
instance.
The PTP servo scales its gains by the time since its previous update when
CONFIG_PTP_SERVO_SCALE_GAINS_BY_SYNC_INTERVAL is enabled.
CONFIG_PTP_SERVO_STEP_THRESHOLD_MS and
CONFIG_PTP_SERVO_OUTLIER_THRESHOLD_MS set the offsets above
which the PTP servo steps the clock and, while locked, rejects a sample. Before
the servo locks, it also steps offsets above a fixed 100 ms.
Scheduled clock output
CONFIG_PRECISION_CLOCK_OUTPUT adds optional scheduled-output
operations to precision_clock. The
precision_clock_output_get_caps() query returns the channel count and a
read-only table of precision_clock_output_channel_caps, so callers
can discover outputs without first choosing a channel. Limits and supported
features may differ between channels. The provider owns the table; its address
and contents remain valid and unchanged for the initialized clock’s lifetime.
No caller allocation or copying of the table is required. Each missing output
callback returns -ENOTSUP independently.
Scheduled output and the autonomous PPS service are experimental features:
CONFIG_PRECISION_CLOCK_OUTPUT and
CONFIG_PRECISION_CLOCK_PPS select
CONFIG_EXPERIMENTAL. The shared
CONFIG_PRECISION_TIMING core does not select it, so enabling
gPTP without either output feature does not introduce an experimental-feature
dependency.
precision_clock_output_start() accepts a
precision_clock_output_config containing the output kind and its
configuration. The supported kind, PRECISION_CLOCK_OUTPUT_KIND_WAVEFORM,
describes an absolute first rising edge, a period, and either a provider-default
or exact high-pulse width. All absolute times are precision_time_t
values interpreted in the owning clock’s timescale. Periods and widths are
nanoseconds and must meet the limits and resolution reported for the channel.
PPS uses this same waveform API with a one-second period; it does not require
a separate hardware driver or CONFIG_PRECISION_CLOCK_PPS.
The channel, first edge, period, and width are supplied at runtime for each
request. The generic operations are implemented in
subsys/precision_timing/precision_clock_output.c; the base clock
operations do not depend on the PPS service.
Channel indices are provider-defined and zero-based; they do not imply
output-only hardware resources. A channel may share hardware with another
device function, such as input capture, or be reserved by the driver.
Starting a waveform may return -EBUSY if the channel is already configured
for output, is in use by another device function, or is reserved by the driver.
The driver arbitrates access to shared channels.
precision_clock_output_next_start_time() finds the next period-aligned
start that satisfies a requested lead time using checked arithmetic. Use
precision_clock_output_get_status() to inspect an accepted
precision_clock_output_config, and
precision_clock_output_stop() to disable a channel. Status queries
delegate directly to the provider: a capability-query failure does not prevent
status reporting, and an accepted first edge may already be in the past.
configured describes provider ownership; hardware_active is meaningful
only when hardware_active_valid is set. It reports whether the hardware
output generator is armed or running for the accepted configuration, including
before a future first edge and during the low portion of a waveform. It does
not report the instantaneous pin level or whether an edge is occurring. When
hardware state is unobservable, the accepted configuration remains the source
of truth.
The generated waveform follows its underlying clock. A hard clock set or phase step can cross an edge or make the waveform discontinuous, so the clock owner must stop and rearm output when its policy requires that. Scheduled output does not imply PTP lock, UTC correctness, grandmaster health, or PPS accuracy. PPS input and external timestamp capture are outside this API.
Driver providers
The scheduled-output API and its precision_clock_output_provider
contract share include/zephyr/precision_timing/precision_clock_output.h.
Both use nanosecond values in the device clock’s own timescale. A PTP clock driver can
reference a provider, and precision_clock_ptp_adapter dispatches its
operations without probing it during adapter initialization.
Provider operations are called only from thread context and may block. Providers may document additional, more restrictive context requirements.
Generic start validation checks the requested waveform against the selected channel’s advertised limits and validates the first edge’s lead time using checked arithmetic. Providers must return valid capabilities and consistent status; the subsystem does not revalidate provider-owned metadata. Providers also validate channel indices for stop and status operations.
The provider remains responsible for hardware-specific constraints and channel ownership. It must check that the first edge still meets its programming lead time: time can advance or the clock can be stepped after the subsystem’s preliminary start check.
A successful start gives the caller ownership. If programming fails and the provider
cannot safely release the channel, it returns -EINPROGRESS and retains the
configuration. This result means cleanup is required, not that the start is
completing asynchronously. The caller must stop the channel successfully before
retrying or releasing the device. No other error gives the caller ownership.
In particular, -ETIME is a lead-time rejection and can be retried with a
new start time without stopping the channel.
The extension deliberately uses a protocol-neutral contract rather than adding
a ptp_clock periodic-output call: non-PTP clocks can reuse the same provider
interface and output data types. The PTP driver API only forward declares the
provider, so drivers without output support do not need precision-timing headers
or runtime support. Output providers use the public
precision_clock_output_config and
precision_clock_output_status directly; the PTP adapter needs neither
duplicate structures nor member-by-member conversions.
Autonomous PPS output
CONFIG_PRECISION_CLOCK_PPS enables an instance-based service
that maintains a fixed one-second waveform on a caller-selected precision clock
and channel. It requires multithreading and a system clock. It is an optional
layer over direct scheduled-output operations and does not discover clocks or
inspect synchronization protocol state.
It monitors recovery conditions, not pulse edges, and does not generate pulses
by polling. Applications that only need to configure a waveform can leave it
disabled and use the scheduled-output API directly.
The configuration is supplied per instance at runtime. The channel, width,
guard, step-limit, and poll-interval Kconfig options only populate
PRECISION_CLOCK_PPS_CONFIG_DEFAULTS; applications may override those
values or initialize precision_clock_pps_config directly. They
are not device-wide driver settings.
precision_clock_pps_init() takes the caller-owned instance, its clock,
and a configuration that includes the optional event callback and its user
data. It validates the selected channel once against the clock’s immutable
capabilities. Unsupported configurations therefore fail at init, before a
workqueue thread is started. precision_clock_pps_start() starts the
shared workqueue on first use and schedules the first poll. The workqueue
stack is statically allocated. Configure its size and the thread priority with
CONFIG_PRECISION_CLOCK_PPS_WORKQUEUE_STACK_SIZE and
CONFIG_PRECISION_CLOCK_PPS_WORKQUEUE_PRIORITY.
Poll-time provider operations and callbacks across instances are serialized on that shared workqueue. The capability query during init and the provider stop during stop run on the caller’s thread and can overlap another instance’s poll; the workqueue does not serialize lifecycle operations across instances.
The service can adopt a matching configured waveform. A detected clock step, missing or mismatched configuration, or reported inactive output causes a stop and rearm at a whole-second boundary. Transient read and status errors are reported and retried. Two consecutive status errors trigger one stop and rearm. If arming succeeds, further status errors alone do not interrupt that waveform until a successful status query ends the outage. Clock steps still trigger recovery.
precision_clock_pps_state_get() reports the lifecycle phase, the
accepted waveform when active, and an event mask. A configured callback gets
only the instance pointer. It can read the state and its event mask without
consuming them, and find its user data in pps->config.user_data. Without a
callback, events accumulate until a state read returns and clears them; repeat
occurrences of the same event coalesce into one bit. These events describe
service transitions, not physical pulse edges. They provide neither edge
timestamps nor waveform-synchronized notifications.
Clock reads are bracketed by monotonic timestamps, including the fresh read after stopping an output. The hard-step threshold applies only to the elapsed-time discrepancy that remains after accounting for both reads’ sampling intervals. This prevents slow or preempted reads from falsely triggering a stop and rearm. A real step hidden within the sampling uncertainty may go undetected.
A started instance requires exclusive management of its clock/channel pair.
precision_clock_pps_stop() synchronously cancels polling and stops the
provider. Cancellation waits for a poll that is already running, including its
callback, to finish on the workqueue before the provider channel is stopped, so
the callback’s final access to its user data is complete when stop returns. If
provider stop fails, the instance remains started so its clock lifetime cannot
be released accidentally. Calling stop from the instance’s own callback returns
-EDEADLK. The instance embeds the work-sync object used for this
cancellation, so when CONFIG_KERNEL_COHERENCE is enabled the
instance storage must reside in coherent memory.
Shell control
CONFIG_PRECISION_TIMING_SHELL enables the precision_clock
command. It requires CONFIG_SHELL and
CONFIG_CBPRINTF_FULL_INTEGRAL to print 64-bit clock and
waveform values.
Clocks are registered statically at build time with
PRECISION_TIMING_SHELL_REGISTER, which creates an immutable,
linker-collected entry referencing a lifetime-static precision_clock.
There is no runtime register or unregister API.
For example, a PTP adapter can expose its embedded clock at file scope:
static struct precision_clock_ptp_adapter phc_adapter;
PRECISION_TIMING_SHELL_REGISTER(phc, &phc_adapter.precision_clk);
Initialize the adapter before allowing concurrent shell access, and keep it valid for the lifetime of the application. Entries cannot be removed at runtime.
The shell can list and read registered clocks:
precision_clock list
precision_clock get <name>
When scheduled output is enabled, discover channels and control their output:
precision_clock output caps <name>
precision_clock output get <name> <channel>
precision_clock output waveform <name> <channel> <first_rising_ns> <period_ns> [pulse_width_ns]
precision_clock output stop <name> <channel>
precision_clock pps start <name> <channel> [pulse_width_ns]
precision_clock pps stop <name> <channel>
The caps command lists the channel count and each channel’s capabilities
and limits. The other commands select a provider-defined channel index.
The absolute time arguments are nanoseconds in the registered clock’s timescale.
The PPS convenience command chooses a whole-second start with an additional
scheduling guard and arms the waveform once. It does not run the autonomous
precision_clock_pps service: there is no hard-step monitoring,
health polling, automatic rearming, or output-loss recovery. It does not check
protocol synchronization state. Use precision_clock_pps for
continuous PPS with automatic recovery.
The PPS command checks that the channel is unconfigured before attempting a
start. An existing configuration returns -EBUSY; a failed status query
returns its error without starting or stopping the output. Stop the channel
explicitly before reconfiguring it. Stopping a channel that a running
precision_clock_pps instance owns does not stop the service: the
service rearms the channel on its next poll.
If the first start fails with -ETIME, the PPS command retries once with a
fresh clock reading and does not stop the channel. The status query is only a
preliminary check; another caller may start the output after it. If either
pps start or output waveform receives -EINPROGRESS from its start
attempt, it stops only the configuration retained by that attempt, including
on the final attempt. It does not retry a retained failure. The command returns
-EIO if cleanup succeeded, or the stop error if cleanup failed. If cleanup
failed, stop the channel explicitly before retrying.
Protocol integration
PTP and the gPTP default clock-update path keep their existing policy and use a
precision_pi for the shared calculation. They initialize a
PTP-clock adapter once and use precision_clock operations to access
the PHC. Scheduled output remains independent of those protocol state machines.
Sample
The Precision timing sample demonstrates checked time arithmetic, a software-backed precision clock, and PI-driven rate adjustment.