sched/clock: 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.

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 commit is contained in:
dongjiuzhu1
2025-03-20 18:20:26 +08:00
committed by Alan C. Assis
parent 314cccf166
commit 1c643b5cc3
3 changed files with 101 additions and 25 deletions
+2 -2
View File
@@ -827,7 +827,7 @@ unsigned long perf_getfreq(void);
*
****************************************************************************/
void nxclock_settime(clockid_t clock_id, FAR const struct timespec *tp);
int nxclock_settime(clockid_t clock_id, FAR const struct timespec *tp);
/****************************************************************************
* Name: nxclock_gettime
@@ -837,7 +837,7 @@ void nxclock_settime(clockid_t clock_id, FAR const struct timespec *tp);
*
****************************************************************************/
void nxclock_gettime(clockid_t clock_id, FAR struct timespec *tp);
int nxclock_gettime(clockid_t clock_id, FAR struct timespec *tp);
#undef EXTERN
#ifdef __cplusplus