Skip to content

Conversation

@Donny9
Copy link
Contributor

@Donny9 Donny9 commented Dec 14, 2025

Summary

  1. PTP driver Model

This patch introduces the foundational PTP (Precision Time Protocol) clock
driver framework for NuttX, enabling precise time synchronization support
based on IEEE 1588 standard.

This framework provides the base for PTP clock implementations, allowing
hardware-specific drivers to register and provide precise time services
through a standardized interface.

Key changes include:

1). New PTP clock driver infrastructure:
- Added drivers/timers/ptp_clock.c implementing upper-half driver
- Created include/nuttx/timers/ptp_clock.h with PTP clock interfaces
- Implemented upper/lower half driver architecture for hardware abstraction

2). Core functionality:
- Clock time get/set operations (gettime, settime)
- Frequency adjustment support (adjtime, adjfine)
- Phase adjustment capabilities
- System-device cross-timestamping for precise synchronization

3). IOCTL commands:
- PTP_CLOCK_SETTIME/GETTIME for time manipulation
- PTP_CLOCK_GETRES for resolution queries
- PTP_CLOCK_ADJTIME for time adjustment
- PTP_CLOCK_GETCAPS for capability queries
- PTP_SYS_OFFSET* for system offset measurements

3). Supporting structures:
- struct ptp_lowerhalf_s: lower-half driver interface
- struct ptp_clock_caps: clock capabilities descriptor
- struct ptp_sys_offset: system time offset measurement
- Added timex structures in include/sys/timex.h for ADJ_* operations

  1. ptp clock dummy driver:

This patch adds a dummy PTP clock driver implementation that provides
a software-based PTP clock for testing and development purposes.

This dummy driver enables development and testing of PTP clock applications
on platforms without dedicated PTP hardware support.

  1. support using CLOCKFD to call clock_gettime/settime

This patch implements POSIX-compliant CLOCKFD support, enabling user
applications to access dynamic PTP clocks through file descriptors
combined with clock_gettime() and clock_settime() system calls.

  1. sched/clock: support using CLOCKFD to call clock_getres

    This patch extends CLOCKFD support to clock_getres(), allowing
    applications to query the resolution of PTP clocks through file
    descriptors using the standard POSIX clock API.

  2. sched/clock: support using CLOCKFD to call clock_adjtime

    This patch implements clock_adjtime() with CLOCKFD support, enabling
    precise time and frequency adjustments for PTP clocks through the
    standard POSIX clock API.

  3. Documentation: Add PTP clock driver framework documentation

    This patch adds comprehensive documentation for the PTP (Precision Time
    Protocol) clock driver framework in NuttX.

Impact

New ptp driver model
change api: clock_gettime/clock_settime/clock_adjtime/clock_getres/....

Testing

posix clock test and ptp test case、ptpd demon test pass

@github-actions github-actions bot added Area: Documentation Improvements or additions to documentation Area: Drivers Drivers issues Area: File System File System issues Area: OS Components OS Components issues Size: XL The size of the change in this PR is very large. Consider breaking down the PR into smaller pieces. labels Dec 14, 2025
This patch introduces the foundational PTP (Precision Time Protocol) clock
driver framework for NuttX, enabling precise time synchronization support
based on IEEE 1588 standard.

Key changes include:

1. New PTP clock driver infrastructure:
   - Added drivers/timers/ptp_clock.c implementing upper-half driver
   - Created include/nuttx/timers/ptp_clock.h with PTP clock interfaces
   - Implemented upper/lower half driver architecture for hardware abstraction

2. Core functionality:
   - Clock time get/set operations (gettime, settime)
   - Frequency adjustment support (adjtime, adjfine)
   - Phase adjustment capabilities
   - System-device cross-timestamping for precise synchronization

3. IOCTL commands:
   - PTP_CLOCK_SETTIME/GETTIME for time manipulation
   - PTP_CLOCK_GETRES for resolution queries
   - PTP_CLOCK_ADJTIME for time adjustment
   - PTP_CLOCK_GETCAPS for capability queries
   - PTP_SYS_OFFSET* for system offset measurements

4. Supporting structures:
   - struct ptp_lowerhalf_s: lower-half driver interface
   - struct ptp_clock_caps: clock capabilities descriptor
   - struct ptp_sys_offset: system time offset measurement
   - Added timex structures in include/sys/timex.h for ADJ_* operations

5. Build system integration:
   - Added CONFIG_PTP_CLOCK Kconfig option
   - Updated CMakeLists.txt and Make.defs
   - Added PTPCLK debug macros in include/debug.h

This framework provides the base for PTP clock implementations, allowing
hardware-specific drivers to register and provide precise time services
through a standardized interface.

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
This patch adds a dummy PTP clock driver implementation that provides
a software-based PTP clock for testing and development purposes.

Key changes include:

1. Dummy PTP clock driver implementation:
   - Added drivers/timers/ptp_clock_dummy.c
   - Provides software-based PTP clock using system monotonic clock
   - Implements all required lower-half driver operations

2. Lower-half driver operations:
   - adjfine: Frequency adjustment (stores adjustment value)
   - adjtime: Time offset adjustment (applies delta to base time)
   - gettime: Returns current PTP clock time
   - settime: Sets PTP clock time
   - getcaps: Reports clock capabilities (1 billion PPB max adjustment)
   - getcrosststamp: Provides system/device cross-timestamp

3. Driver initialization:
   - Added ptp_clock_dummy_init() in drivers/drivers_initialize.c
   - Auto-registration under CONFIG_PTP_CLOCK_DUMMY configuration
   - Creates /dev/ptp0 character device node

4. Build system integration:
   - Added CONFIG_PTP_CLOCK_DUMMY Kconfig option (depends on PTP_CLOCK)
   - Updated CMakeLists.txt and Make.defs
   - Added include/nuttx/timers/ptp_clock_dummy.h header

5. Implementation details:
   - Uses clock_gettime(CLOCK_MONOTONIC) as time base
   - Tracks time offset and frequency adjustment internally
   - Suitable for testing PTP clock applications without hardware

This dummy driver enables development and testing of PTP clock applications
on platforms without dedicated PTP hardware support.

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
This patch implements POSIX-compliant CLOCKFD support, enabling user
applications to access dynamic PTP clocks through file descriptors
combined with clock_gettime() and clock_settime() system calls.

Key changes include:

1. CLOCKFD macro support:
   - Added CLOCKFD() macro in include/nuttx/clock.h
   - Allows encoding file descriptor into clockid_t: CLOCKFD(fd)
   - Enables accessing PTP clocks via: clock_gettime(CLOCKFD(fd), &ts)

2. clock_gettime() enhancements:
   - Modified sched/clock/clock_gettime.c to detect CLOCKFD clockids
   - Extracts file descriptor from clockid using CLOCKFD_TO_FD()
   - Validates file descriptor and calls file_ioctl() with PTP_CLOCK_GETTIME
   - Falls back to standard clock handling for non-CLOCKFD clockids

3. clock_settime() enhancements:
   - Modified sched/clock/clock_settime.c to support CLOCKFD clockids
   - Extracts file descriptor and validates accessibility
   - Issues PTP_CLOCK_SETTIME ioctl to underlying PTP clock device
   - Maintains backward compatibility with standard POSIX clocks

4. File descriptor validation:
   - Checks file descriptor validity using fs_getfilep()
   - Ensures proper reference counting with fs_putfilep()
   - Returns appropriate error codes (EINVAL, EBADF) on failures

5. Integration with PTP clock framework:
   - Seamlessly integrates with PTP clock driver's ioctl interface
   - Enables standard POSIX clock API usage for dynamic PTP clocks
   - No changes required to existing applications using standard clocks

Usage example:
  int fd = open("/dev/ptp0", O_RDONLY);
  struct timespec ts;
  clock_gettime(CLOCKFD(fd), &ts);  /* Get PTP clock time */
  clock_settime(CLOCKFD(fd), &ts);  /* Set PTP clock time */
  close(fd);

This implementation follows the Linux kernel's PTP clock model, providing
a familiar interface for developers working with PTP hardware.

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
This patch extends CLOCKFD support to clock_getres(), allowing
applications to query the resolution of PTP clocks through file
descriptors using the standard POSIX clock API.

Key changes include:

1. Move clock_getres() from libc to kernel:
   - Relocated from libs/libc/sched/clock_getres.c to sched/clock/
   - Enables direct kernel-level file descriptor handling
   - Maintains POSIX compliance while adding CLOCKFD support

2. CLOCKFD support in clock_getres():
   - Detects CLOCKFD-encoded clockids using CLOCKFD_TO_FD() check
   - Extracts file descriptor from clockid parameter
   - Validates file descriptor through fs_getfilep()
   - Issues PTP_CLOCK_GETRES ioctl to query clock resolution

3. PTP clock resolution query:
   - Retrieves resolution from PTP clock device via ioctl
   - Returns nanosecond-precision timing resolution
   - Enables applications to determine clock accuracy capabilities
   - Falls back to standard clock resolution for non-CLOCKFD clockids

4. Error handling:
   - Returns EINVAL for invalid CLOCKFD file descriptors
   - Properly manages file reference counting with fs_putfilep()
   - Maintains backward compatibility with existing clock types

5. Build system updates:
   - Updated libs/libc/sched/CMakeLists.txt and Make.defs
   - Updated sched/clock/CMakeLists.txt to include clock_getres.c
   - Ensures proper compilation in kernel context

Usage example:
  int fd = open("/dev/ptp0", O_RDONLY);
  struct timespec res;
  clock_getres(CLOCKFD(fd), &res);  /* Query PTP clock resolution */
  printf("Resolution: %ld.%09ld sec\n", res.tv_sec, res.tv_nsec);
  close(fd);

This completes the basic POSIX clock API support for dynamic PTP clocks,
providing applications with comprehensive clock information access.

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
This patch implements clock_adjtime() with CLOCKFD support, enabling
precise time and frequency adjustments for PTP clocks through the
standard POSIX clock API.

Key changes include:

1. New clock_adjtime() system call:
   - Added sched/clock/clock_adjtime.c implementation
   - Provides POSIX-compliant time adjustment interface
   - Supports both standard clocks and CLOCKFD-based dynamic clocks
   - Added CONFIG_CLOCK_ADJTIME Kconfig option

2. CLOCKFD support in clock_adjtime():
   - Detects CLOCKFD-encoded clockids via CLOCKFD_TO_FD() check
   - Extracts file descriptor and validates through fs_getfilep()
   - Issues PTP_CLOCK_ADJTIME ioctl to underlying PTP clock device
   - Returns clock status and adjustment results via struct timex

3. Enhanced struct timex support:
   - Extended include/sys/timex.h with additional ADJ_* flags
   - Added ADJ_OFFSET, ADJ_FREQUENCY, ADJ_MAXERROR, ADJ_ESTERROR
   - Added ADJ_STATUS, ADJ_TIMECONST, ADJ_TAI, ADJ_SETOFFSET
   - Added ADJ_MICRO, ADJ_NANO for time unit selection
   - Added STA_* status flags for clock state reporting

4. Clock operations supported:
   - ADJ_SETOFFSET: Apply time offset adjustment
   - ADJ_FREQUENCY: Adjust clock frequency (PPM)
   - ADJ_MAXERROR: Set maximum error estimate
   - ADJ_ESTERROR: Set estimated error
   - ADJ_STATUS: Modify clock status bits
   - ADJ_NANO: Use nanosecond resolution
   - ADJ_SETOFFSET: Set absolute time offset

5. API declarations:
   - Added clock_adjtime() prototype in include/nuttx/clock.h
   - Enabled by CONFIG_CLOCK_ADJTIME configuration
   - Compatible with Linux clock_adjtime() interface

Usage example:
  int fd = open("/dev/ptp0", O_RDWR);
  struct timex tx = {0};
  tx.modes = ADJ_FREQUENCY;
  tx.freq = 10000000;  /* Adjust frequency by 10 PPM */
  clock_adjtime(CLOCKFD(fd), &tx);
  close(fd);

This completes the PTP clock framework's POSIX clock API integration,
providing comprehensive time control capabilities for precision timing
applications including PTP synchronization daemons (ptp4l, timemaster).

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
This patch adds comprehensive documentation for the PTP (Precision Time
Protocol) clock driver framework in NuttX.

The documentation covers:

1. Overview and Architecture:
   - IEEE 1588 PTP clock framework introduction
   - Upper-half and lower-half driver architecture
   - Integration with POSIX clock APIs

2. Configuration Options:
   - CONFIG_PTP_CLOCK: Main framework configuration
   - CONFIG_PTP_CLOCK_DUMMY: Dummy driver for testing
   - CONFIG_CLOCK_ADJTIME: clock_adjtime() system call support

3. Device Interface:
   - Character device interface (/dev/ptpN)
   - IOCTL commands: PTP_CLOCK_GETTIME, PTP_CLOCK_SETTIME,
     PTP_CLOCK_GETRES, PTP_CLOCK_ADJTIME, PTP_CLOCK_GETCAPS,
     PTP_SYS_OFFSET, PTP_SYS_OFFSET_PRECISE

4. POSIX Clock API (CLOCKFD):
   - Using CLOCKFD() macro to access PTP clocks
   - clock_gettime(), clock_settime(), clock_getres() examples
   - clock_adjtime() with various adjustment modes
   - ADJ_OFFSET, ADJ_FREQUENCY, ADJ_SETOFFSET support

5. Dummy PTP Clock Driver:
   - Software-based implementation for testing
   - Features and initialization details

6. Example Usage:
   - Basic time operations
   - Frequency adjustment examples
   - Time offset adjustment examples

7. Implementing Lower-Half Drivers:
   - Step-by-step guide for hardware driver implementation
   - Required operations and structures
   - Registration process

8. Integration with PTP Daemons:
   - ptp4l, timemaster, ptpd compatibility
   - Standard POSIX clock API usage

9. Performance Considerations:
   - Hardware timestamping requirements
   - Cross-timestamping support
   - Frequency adjustment resolution

10. Debugging:
    - Debug configuration options
    - Debug output examples

The documentation is added to:
- Documentation/components/drivers/special/ptp.rst (new file)
- Documentation/components/drivers/special/index.rst (updated)

This provides developers with complete reference material for using
and implementing PTP clock drivers in NuttX.

Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
Signed-off-by: dongjiuzhu1 <dongjiuzhu1@xiaomi.com>
Copy link
Contributor

@acassis acassis left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nice work @Donny9 !!! This is a very useful feature that together with hrtimer will allow NuttX to be used in systems where are precision time synchronization is required!

@acassis
Copy link
Contributor

acassis commented Dec 14, 2025

Hi @robertobucher and @ppisa I think this feature should be useful for your projects!
ping @PetteriAimonen since you contributed ptpd to apps some time ago!

@PetteriAimonen
Copy link
Contributor

I wonder about the relation of the new nxclock_adjtime() and clock_adjtime() to the existing adjtime(). It seems that clock_adjtime() does nothing if PTP clock is not enabled, while for CLOCK_REALTIME it would make sense to call adjtime().

I also think it could be useful for ptp.rst documentation to mention the nuttx-apps ptpd which has lower total accuracy (practically around 100 µs), but less hardware requirements.

@Donny9
Copy link
Contributor Author

Donny9 commented Dec 15, 2025

I wonder about the relation of the new nxclock_adjtime() and clock_adjtime() to the existing adjtime(). It seems that clock_adjtime() does nothing if PTP clock is not enabled, while for CLOCK_REALTIME it would make sense to call adjtime().

I also think it could be useful for ptp.rst documentation to mention the nuttx-apps ptpd which has lower total accuracy (practically around 100 µs), but less hardware requirements.

@PetteriAimonen please review the PR apache/nuttx-apps#3247 PTPd Service Enhancement, including instructions on how to use the new PTP device driver in PTPd

@xiaoxiang781216
Copy link
Contributor

@Donny9 please fix the style check:

78d2216b2a drivers/ptp: add set/get statistics interface for driver
eeab8886dd drivers/ptp_clock: pass ppb to driver to adjust frequency
4742a80224 Documentation: Add PTP clock driver framework documentation
4d7ac1b403 sched/clock: support using CLOCKFD to call clock_adjtime
36b68c6a41 sched/clock: support using CLOCKFD to call clock_getres
89fbac97de sched/clock: support using CLOCKFD to call clock_gettime/settime
b8072e6cd0 drivers/timers/ptp: support ptp clock dummy driver
27c18ab8c5 drivers/timers/ptp: support ptp clock driver model
../nuttx/tools/checkpatch.sh -c -u -m -g a87ad9834323b8acb58a0560244e4574adb0c208..HEAD
❌ Missing git commit message
❌ Missing git commit message

@acassis
Copy link
Contributor

acassis commented Dec 23, 2025

@Donny9 please include commit log message to fix the CI issue:

../nuttx/tools/checkpatch.sh -c -u -m -g a87ad98..HEAD
❌ Missing git commit message
❌ Missing git commit message
Used config files:
1: .codespellrc
Some checks failed. For contributing guidelines, see:
https://github.com/apache/nuttx/blob/master/CONTRIBUTING.md
Error: Process completed with exit code 1.

@acassis
Copy link
Contributor

acassis commented Dec 24, 2025

@simbit18 have you seen this error before:

 + python3 -m pytest -m 'common or sim' ./ -B sim -P -L /github/workspace/sources/nuttx/boards/sim/sim/sim/configs/citest/logs/sim/sim -R sim -C --json=/github/workspace/sources/nuttx/boards/sim/sim/sim/configs/citest/logs/sim/sim/pytest.json
/usr/local/lib/python3.10/dist-packages/_pytest/config/__init__.py:318: PluggyTeardownRaisedWarning: A plugin raised an exception during an old-style hookwrapper teardown.
Plugin: helpconfig, Hook: pytest_cmdline_parse
UsageError: usage: __main__.py [options] [file_or_dir] [file_or_dir] [...]
__main__.py: error: argument -P: expected one argument
For more information see https://pluggy.readthedocs.io/en/stable/api_reference.html#pluggy.PluggyTeardownRaisedWarning
  config = pluginmanager.hook.pytest_cmdline_parse(
ERROR: usage: __main__.py [options] [file_or_dir] [file_or_dir] [...]
__main__.py: error: argument -P: expected one argument

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Area: Documentation Improvements or additions to documentation Area: Drivers Drivers issues Area: File System File System issues Area: OS Components OS Components issues Size: XL The size of the change in this PR is very large. Consider breaking down the PR into smaller pieces.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants