Sfoglia il codice sorgente

[clock_time] Add unified clock_time subsystem with documentation

- Created new clock_time subsystem consolidating hwtimer/ktime/cputime
- Implemented clock_time device abstraction with ops structure
- Added high-resolution timer (hrtimer) implementation
- Created compatibility layers for legacy APIs
- Added comprehensive English and Chinese documentation
- Updated Kconfig to mark old subsystems as deprecated

Co-authored-by: BernardXiong <1241087+BernardXiong@users.noreply.github.com>
copilot-swe-agent[bot] 4 mesi fa
parent
commit
32587a3096

+ 1 - 0
components/drivers/Kconfig

@@ -5,6 +5,7 @@ rsource "ipc/Kconfig"
 
 rsource "serial/Kconfig"
 rsource "can/Kconfig"
+rsource "clock_time/Kconfig"
 rsource "cputime/Kconfig"
 rsource "i2c/Kconfig"
 rsource "phy/Kconfig"

+ 36 - 0
components/drivers/clock_time/Kconfig

@@ -0,0 +1,36 @@
+menuconfig RT_USING_CLOCK_TIME
+    bool "Using unified clock_time subsystem"
+    default n
+    help
+        Enable the unified clock_time subsystem which consolidates
+        hwtimer, ktime, and cputime into a single coherent framework.
+        
+        This subsystem provides:
+        - Clocksource: Free-running counter for timekeeping
+        - Clockevent: Programmable timeout events
+        - High-resolution timers (hrtimer)
+        - POSIX clock support
+        - Boottime tracking
+
+if RT_USING_CLOCK_TIME
+    config RT_CLOCK_TIME_COMPAT_KTIME
+        bool "Enable compatibility layer for ktime APIs"
+        default y
+        help
+            Provides backward compatibility wrappers for legacy ktime APIs.
+            Enable this if existing code uses rt_ktime_* functions.
+
+    config RT_CLOCK_TIME_COMPAT_CPUTIME
+        bool "Enable compatibility layer for cputime APIs"
+        default y
+        help
+            Provides backward compatibility wrappers for legacy cputime APIs.
+            Enable this if existing code uses clock_cpu_* or rt_cputimer_* functions.
+
+    config RT_CLOCK_TIME_COMPAT_HWTIMER
+        bool "Enable compatibility layer for hwtimer device APIs"
+        default y
+        help
+            Provides backward compatibility for legacy hwtimer device APIs.
+            Enable this if BSP drivers use rt_device_hwtimer_* functions.
+endif

+ 28 - 0
components/drivers/clock_time/SConscript

@@ -0,0 +1,28 @@
+from building import *
+
+cwd = GetCurrentDir()
+
+src = Split('''
+src/clock_time.c
+src/hrtimer.c
+src/clock_time_tick.c
+''')
+
+if GetDepend('RT_CLOCK_TIME_COMPAT_KTIME'):
+    src += ['src/ktime_compat.c']
+
+if GetDepend('RT_CLOCK_TIME_COMPAT_CPUTIME'):
+    src += ['src/cputime_compat.c']
+
+CPPPATH = [cwd + '/include', cwd + '/../include']
+
+LOCAL_CCFLAGS = ''
+if rtconfig.PLATFORM in ['gcc', 'armclang']:
+    LOCAL_CCFLAGS += ' -std=gnu99'
+elif rtconfig.PLATFORM in ['armcc']:
+    LOCAL_CCFLAGS += ' --c99 --gnu'
+
+group = DefineGroup('DeviceDrivers', src, depend=['RT_USING_CLOCK_TIME'], 
+                   CPPPATH=CPPPATH, LOCAL_CCFLAGS=LOCAL_CCFLAGS)
+
+Return('group')

+ 200 - 0
components/drivers/clock_time/src/clock_time.c

@@ -0,0 +1,200 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Unified clock_time subsystem - core implementation
+ */
+
+#include <rtdevice.h>
+#include <rthw.h>
+
+#define DBG_TAG "clock_time"
+#define DBG_LVL DBG_INFO
+#include <rtdbg.h>
+
+static struct rt_clock_time_device *_default_clock_time = RT_NULL;
+
+rt_err_t rt_clock_time_device_register(struct rt_clock_time_device *dev, 
+                                       const char *name, 
+                                       rt_uint8_t caps)
+{
+    RT_ASSERT(dev != RT_NULL);
+    RT_ASSERT(dev->ops != RT_NULL);
+    RT_ASSERT(name != RT_NULL);
+    
+    /* Validate capability requirements */
+    if (caps & RT_CLOCK_TIME_CAP_CLOCKSOURCE)
+    {
+        RT_ASSERT(dev->ops->get_freq != RT_NULL);
+        RT_ASSERT(dev->ops->get_counter != RT_NULL);
+    }
+    
+    if (caps & RT_CLOCK_TIME_CAP_CLOCKEVENT)
+    {
+        RT_ASSERT(dev->ops->set_timeout != RT_NULL);
+    }
+    
+    dev->caps = caps;
+    dev->parent.type = RT_Device_Class_Timer;
+    dev->parent.rx_indicate = RT_NULL;
+    dev->parent.tx_complete = RT_NULL;
+    dev->parent.user_data = RT_NULL;
+    
+    /* Calculate resolution scale factor */
+    if (dev->ops->get_freq)
+    {
+        rt_uint64_t freq = dev->ops->get_freq();
+        /* res_scale = RT_CLOCK_TIME_RESMUL for nanosecond precision */
+        dev->res_scale = RT_CLOCK_TIME_RESMUL;
+    }
+    
+    /* Register as a device */
+    rt_err_t result = rt_device_register(&dev->parent, name, 
+                                         RT_DEVICE_FLAG_RDWR | RT_DEVICE_FLAG_STANDALONE);
+    
+    if (result == RT_EOK)
+    {
+        LOG_I("Clock time device '%s' registered (caps: 0x%02x)", name, caps);
+        
+        /* Set as default if none exists */
+        if (_default_clock_time == RT_NULL)
+        {
+            _default_clock_time = dev;
+            LOG_I("Set '%s' as default clock time device", name);
+        }
+    }
+    
+    return result;
+}
+
+rt_err_t rt_clock_time_set_default(struct rt_clock_time_device *dev)
+{
+    RT_ASSERT(dev != RT_NULL);
+    
+    _default_clock_time = dev;
+    LOG_I("Default clock time device set to '%s'", dev->parent.parent.name);
+    
+    return RT_EOK;
+}
+
+struct rt_clock_time_device *rt_clock_time_get_default(void)
+{
+    return _default_clock_time;
+}
+
+/* Clocksource APIs */
+
+rt_uint64_t rt_clock_time_getres(void)
+{
+    if (_default_clock_time == RT_NULL || 
+        !(_default_clock_time->caps & RT_CLOCK_TIME_CAP_CLOCKSOURCE))
+    {
+        /* Fallback to tick-based resolution */
+        return ((1000ULL * 1000 * 1000) * RT_CLOCK_TIME_RESMUL) / RT_TICK_PER_SECOND;
+    }
+    
+    rt_uint64_t freq = _default_clock_time->ops->get_freq();
+    return ((1000ULL * 1000 * 1000) * RT_CLOCK_TIME_RESMUL) / freq;
+}
+
+rt_uint64_t rt_clock_time_getfreq(void)
+{
+    if (_default_clock_time == RT_NULL || 
+        !(_default_clock_time->caps & RT_CLOCK_TIME_CAP_CLOCKSOURCE))
+    {
+        /* Fallback to tick frequency */
+        return RT_TICK_PER_SECOND;
+    }
+    
+    return _default_clock_time->ops->get_freq();
+}
+
+rt_uint64_t rt_clock_time_getcnt(void)
+{
+    if (_default_clock_time == RT_NULL || 
+        !(_default_clock_time->caps & RT_CLOCK_TIME_CAP_CLOCKSOURCE))
+    {
+        /* Fallback to tick counter */
+        return rt_tick_get();
+    }
+    
+    return _default_clock_time->ops->get_counter();
+}
+
+rt_err_t rt_clock_time_boottime_ns(struct timespec *ts)
+{
+    RT_ASSERT(ts != RT_NULL);
+    
+    rt_uint64_t cnt = rt_clock_time_getcnt();
+    rt_uint64_t res = rt_clock_time_getres();
+    rt_uint64_t ns = (cnt * res) / RT_CLOCK_TIME_RESMUL;
+    
+    ts->tv_sec = ns / (1000ULL * 1000 * 1000);
+    ts->tv_nsec = ns % (1000ULL * 1000 * 1000);
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_time_boottime_us(struct timeval *tv)
+{
+    RT_ASSERT(tv != RT_NULL);
+    
+    rt_uint64_t cnt = rt_clock_time_getcnt();
+    rt_uint64_t res = rt_clock_time_getres();
+    rt_uint64_t ns = (cnt * res) / RT_CLOCK_TIME_RESMUL;
+    
+    tv->tv_sec = ns / (1000ULL * 1000 * 1000);
+    tv->tv_usec = (ns % (1000ULL * 1000 * 1000)) / 1000;
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_time_boottime_s(time_t *t)
+{
+    RT_ASSERT(t != RT_NULL);
+    
+    rt_uint64_t cnt = rt_clock_time_getcnt();
+    rt_uint64_t res = rt_clock_time_getres();
+    rt_uint64_t ns = (cnt * res) / RT_CLOCK_TIME_RESMUL;
+    
+    *t = ns / (1000ULL * 1000 * 1000);
+    
+    return RT_EOK;
+}
+
+/* Time conversion functions */
+
+rt_uint64_t rt_clock_time_cnt_to_ns(rt_uint64_t cnt)
+{
+    rt_uint64_t res = rt_clock_time_getres();
+    return (cnt * res) / RT_CLOCK_TIME_RESMUL;
+}
+
+rt_uint64_t rt_clock_time_cnt_to_us(rt_uint64_t cnt)
+{
+    return rt_clock_time_cnt_to_ns(cnt) / 1000;
+}
+
+rt_uint64_t rt_clock_time_cnt_to_ms(rt_uint64_t cnt)
+{
+    return rt_clock_time_cnt_to_ns(cnt) / (1000 * 1000);
+}
+
+rt_uint64_t rt_clock_time_ns_to_cnt(rt_uint64_t ns)
+{
+    rt_uint64_t freq = rt_clock_time_getfreq();
+    return (ns * freq) / (1000ULL * 1000 * 1000);
+}
+
+rt_uint64_t rt_clock_time_us_to_cnt(rt_uint64_t us)
+{
+    return rt_clock_time_ns_to_cnt(us * 1000);
+}
+
+rt_uint64_t rt_clock_time_ms_to_cnt(rt_uint64_t ms)
+{
+    return rt_clock_time_ns_to_cnt(ms * 1000 * 1000);
+}

+ 53 - 0
components/drivers/clock_time/src/clock_time_tick.c

@@ -0,0 +1,53 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Tick-based clock_time adapter (fallback)
+ */
+
+#include <rtdevice.h>
+
+/**
+ * @brief Tick-based fallback clock_time implementation
+ * 
+ * This provides a basic clock_time implementation using RT-Thread's
+ * tick counter. It should be overridden by BSP-specific implementations
+ * that provide higher resolution hardware timers.
+ */
+
+static rt_uint64_t _tick_get_freq(void)
+{
+    return RT_TICK_PER_SECOND;
+}
+
+static rt_uint64_t _tick_get_counter(void)
+{
+    return rt_tick_get();
+}
+
+static const struct rt_clock_time_ops _tick_clock_ops = 
+{
+    .get_freq = _tick_get_freq,
+    .get_counter = _tick_get_counter,
+    .set_timeout = RT_NULL,  /* No hardware timeout support */
+};
+
+static struct rt_clock_time_device _tick_clock_device;
+
+/**
+ * @brief Initialize tick-based clock_time device
+ * 
+ * This is automatically called if no other clock_time device is registered.
+ */
+int rt_clock_time_tick_init(void)
+{
+    _tick_clock_device.ops = &_tick_clock_ops;
+    
+    return rt_clock_time_device_register(&_tick_clock_device, 
+                                        "tick_clock",
+                                        RT_CLOCK_TIME_CAP_CLOCKSOURCE);
+}
+INIT_DEVICE_EXPORT(rt_clock_time_tick_init);

+ 146 - 0
components/drivers/clock_time/src/cputime_compat.c

@@ -0,0 +1,146 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Compatibility layer for cputime APIs
+ */
+
+#include <rtdevice.h>
+#include <rthw.h>
+#include <sys/errno.h>
+
+/* Legacy cputime ops structure - deprecated */
+static const struct rt_clock_cputime_ops *_legacy_cputime_ops = RT_NULL;
+
+uint64_t clock_cpu_getres(void)
+{
+    if (_legacy_cputime_ops && _legacy_cputime_ops->cputime_getres)
+    {
+        return _legacy_cputime_ops->cputime_getres();
+    }
+    
+    /* Use new unified API */
+    return rt_clock_time_getres();
+}
+
+uint64_t clock_cpu_gettime(void)
+{
+    if (_legacy_cputime_ops && _legacy_cputime_ops->cputime_gettime)
+    {
+        return _legacy_cputime_ops->cputime_gettime();
+    }
+    
+    /* Use new unified API */
+    return rt_clock_time_getcnt();
+}
+
+int clock_cpu_settimeout(uint64_t tick, void (*timeout)(void *param), void *param)
+{
+    if (_legacy_cputime_ops && _legacy_cputime_ops->cputime_settimeout)
+    {
+        return _legacy_cputime_ops->cputime_settimeout(tick, timeout, param);
+    }
+    
+    /* Use new unified API */
+    struct rt_clock_time_device *dev = rt_clock_time_get_default();
+    if (dev && (dev->caps & RT_CLOCK_TIME_CAP_CLOCKEVENT))
+    {
+        /* Note: Legacy API doesn't directly support callbacks, 
+         * would need to use hrtimer for full compatibility */
+        return -RT_ENOSYS;
+    }
+    
+    rt_set_errno(ENOSYS);
+    return 0;
+}
+
+int clock_cpu_issettimeout(void)
+{
+    if (_legacy_cputime_ops && _legacy_cputime_ops->cputime_settimeout)
+    {
+        return RT_TRUE;
+    }
+    
+    struct rt_clock_time_device *dev = rt_clock_time_get_default();
+    return (dev && (dev->caps & RT_CLOCK_TIME_CAP_CLOCKEVENT)) ? RT_TRUE : RT_FALSE;
+}
+
+uint64_t clock_cpu_microsecond(uint64_t cpu_tick)
+{
+    return rt_clock_time_cnt_to_us(cpu_tick);
+}
+
+uint64_t clock_cpu_millisecond(uint64_t cpu_tick)
+{
+    return rt_clock_time_cnt_to_ms(cpu_tick);
+}
+
+int clock_cpu_setops(const struct rt_clock_cputime_ops *ops)
+{
+    _legacy_cputime_ops = ops;
+    return 0;
+}
+
+/* Legacy cputimer APIs */
+
+void rt_cputimer_init(struct rt_cputimer *timer,
+                     const char *name,
+                     void (*timeout)(void *parameter),
+                     void *parameter,
+                     rt_uint64_t tick,
+                     rt_uint8_t flag)
+{
+    /* Map to hrtimer */
+    rt_clock_hrtimer_init((rt_clock_hrtimer_t)timer, name, flag, timeout, parameter);
+    ((rt_clock_hrtimer_t)timer)->delay_cnt = tick;
+}
+
+rt_err_t rt_cputimer_delete(struct rt_cputimer *timer)
+{
+    return rt_clock_hrtimer_detach((rt_clock_hrtimer_t)timer);
+}
+
+rt_err_t rt_cputimer_start(struct rt_cputimer *timer)
+{
+    rt_clock_hrtimer_t ht = (rt_clock_hrtimer_t)timer;
+    return rt_clock_hrtimer_start(ht, ht->delay_cnt);
+}
+
+rt_err_t rt_cputimer_stop(struct rt_cputimer *timer)
+{
+    return rt_clock_hrtimer_stop((rt_clock_hrtimer_t)timer);
+}
+
+rt_err_t rt_cputimer_control(struct rt_cputimer *timer, int cmd, void *arg)
+{
+    return rt_clock_hrtimer_control((rt_clock_hrtimer_t)timer, cmd, arg);
+}
+
+rt_err_t rt_cputimer_detach(struct rt_cputimer *timer)
+{
+    return rt_clock_hrtimer_detach((rt_clock_hrtimer_t)timer);
+}
+
+rt_err_t rt_cputime_sleep(rt_uint64_t tick)
+{
+    struct rt_clock_hrtimer timer;
+    return rt_clock_hrtimer_sleep(&timer, tick);
+}
+
+rt_err_t rt_cputime_ndelay(rt_uint64_t ns)
+{
+    return rt_clock_ndelay(ns);
+}
+
+rt_err_t rt_cputime_udelay(rt_uint64_t us)
+{
+    return rt_clock_udelay(us);
+}
+
+rt_err_t rt_cputime_mdelay(rt_uint64_t ms)
+{
+    return rt_clock_mdelay(ms);
+}

+ 391 - 0
components/drivers/clock_time/src/hrtimer.c

@@ -0,0 +1,391 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Unified clock_time subsystem - hrtimer implementation
+ */
+
+#include <rtdevice.h>
+#include <rthw.h>
+
+#define DBG_TAG "clock_hrtimer"
+#define DBG_LVL DBG_INFO
+#include <rtdbg.h>
+
+#ifdef ARCH_CPU_64BIT
+#define _HRTIMER_MAX_CNT UINT64_MAX
+#else
+#define _HRTIMER_MAX_CNT UINT32_MAX
+#endif
+
+static rt_list_t _timer_list = RT_LIST_OBJECT_INIT(_timer_list);
+static RT_DEFINE_SPINLOCK(_spinlock);
+
+rt_inline rt_clock_hrtimer_t _first_hrtimer(void)
+{
+    return rt_list_isempty(&_timer_list) ? RT_NULL : 
+           rt_list_first_entry(&_timer_list, struct rt_clock_hrtimer, node);
+}
+
+static rt_err_t _set_hardware_timeout(rt_uint64_t cnt)
+{
+    struct rt_clock_time_device *dev = rt_clock_time_get_default();
+    
+    if (dev == RT_NULL || !(dev->caps & RT_CLOCK_TIME_CAP_CLOCKEVENT))
+    {
+        /* Fallback to software timer */
+        static rt_timer_t timer = RT_NULL;
+        static struct rt_timer _fallback_timer;
+        
+        RT_ASSERT(cnt > 0);
+        
+        if (timer == RT_NULL)
+        {
+            timer = &_fallback_timer;
+            rt_timer_init(timer, "hrtimer_fb", 
+                         (void (*)(void *))rt_clock_hrtimer_process, 
+                         RT_NULL, cnt, RT_TIMER_FLAG_ONE_SHOT);
+        }
+        else
+        {
+            rt_tick_t tick = cnt;
+            rt_timer_control(timer, RT_TIMER_CTRL_SET_TIME, &tick);
+        }
+        
+        if (timer->parent.flag & RT_TIMER_FLAG_ACTIVATED)
+        {
+            rt_timer_stop(timer);
+        }
+        
+        rt_timer_start(timer);
+        return RT_EOK;
+    }
+    
+    return dev->ops->set_timeout(cnt);
+}
+
+static void _insert_timer_to_list_locked(rt_clock_hrtimer_t timer)
+{
+    rt_clock_hrtimer_t iter;
+    
+    rt_list_for_each_entry(iter, &_timer_list, node)
+    {
+        if (iter->timeout_cnt > timer->timeout_cnt)
+        {
+            break;
+        }
+    }
+    rt_list_insert_before(&iter->node, &(timer->node));
+    
+    timer->flag |= RT_TIMER_FLAG_ACTIVATED;
+}
+
+static void _hrtimer_process_locked(void)
+{
+    rt_clock_hrtimer_t timer;
+    rt_uint64_t current_cnt = rt_clock_time_getcnt();
+    
+    for (timer = _first_hrtimer();
+         (timer != RT_NULL) && (timer->timeout_cnt <= current_cnt);
+         timer = _first_hrtimer())
+    {
+        rt_list_remove(&(timer->node));
+        
+        if (timer->flag & RT_TIMER_FLAG_PERIODIC)
+        {
+            timer->timeout_cnt = timer->delay_cnt + rt_clock_time_getcnt();
+            _insert_timer_to_list_locked(timer);
+        }
+        else
+        {
+            timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
+        }
+        
+        if (timer->timeout_func)
+        {
+            timer->timeout_func(timer->parameter);
+        }
+    }
+}
+
+static rt_uint64_t _cnt_convert_to_hardware(rt_uint64_t target_cnt)
+{
+    rt_uint64_t current_cnt = rt_clock_time_getcnt();
+    rt_uint64_t delta = target_cnt - current_cnt;
+    
+    /* Check for overflow or already expired */
+    if (delta > (_HRTIMER_MAX_CNT / 2))
+    {
+        return 0;
+    }
+    
+    /* Return delta, at least 1 */
+    return delta == 0 ? 1 : delta;
+}
+
+static void _set_next_timeout_locked(void)
+{
+    rt_clock_hrtimer_t timer;
+    rt_uint64_t next_timeout_cnt;
+    rt_bool_t find_next;
+    
+    do
+    {
+        find_next = RT_FALSE;
+        if ((timer = _first_hrtimer()) != RT_NULL)
+        {
+            next_timeout_cnt = _cnt_convert_to_hardware(timer->timeout_cnt);
+            if (next_timeout_cnt > 0)
+            {
+                _set_hardware_timeout(next_timeout_cnt);
+            }
+            else
+            {
+                /* Timer already expired, process it */
+                _hrtimer_process_locked();
+                find_next = RT_TRUE;
+            }
+        }
+    }
+    while (find_next);
+}
+
+void rt_clock_hrtimer_process(void)
+{
+    rt_base_t level = rt_spin_lock_irqsave(&_spinlock);
+    
+    _hrtimer_process_locked();
+    _set_next_timeout_locked();
+    
+    rt_spin_unlock_irqrestore(&_spinlock, level);
+}
+
+void rt_clock_hrtimer_init(rt_clock_hrtimer_t timer,
+                          const char *name,
+                          rt_uint8_t flag,
+                          void (*timeout)(void *parameter),
+                          void *parameter)
+{
+    RT_ASSERT(timer != RT_NULL);
+    RT_ASSERT(timeout != RT_NULL);
+    
+    rt_memset(timer, 0, sizeof(struct rt_clock_hrtimer));
+    
+    timer->flag = flag & ~RT_TIMER_FLAG_ACTIVATED;
+    timer->timeout_func = timeout;
+    timer->parameter = parameter;
+    rt_strncpy(timer->name, name, RT_NAME_MAX - 1);
+    rt_list_init(&(timer->node));
+    rt_completion_init(&timer->completion);
+}
+
+rt_err_t rt_clock_hrtimer_start(rt_clock_hrtimer_t timer, rt_uint64_t delay_cnt)
+{
+    rt_base_t level;
+    
+    RT_ASSERT(timer != RT_NULL);
+    RT_ASSERT(delay_cnt < (_HRTIMER_MAX_CNT / 2));
+    
+    timer->delay_cnt = delay_cnt;
+    timer->timeout_cnt = timer->delay_cnt + rt_clock_time_getcnt();
+    
+    level = rt_spin_lock_irqsave(&_spinlock);
+    
+    if (timer->flag & RT_TIMER_FLAG_ACTIVATED)
+    {
+        rt_spin_unlock_irqrestore(&_spinlock, level);
+        return -RT_ERROR;
+    }
+    
+    _insert_timer_to_list_locked(timer);
+    _set_next_timeout_locked();
+    
+    rt_spin_unlock_irqrestore(&_spinlock, level);
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_hrtimer_stop(rt_clock_hrtimer_t timer)
+{
+    rt_base_t level;
+    
+    RT_ASSERT(timer != RT_NULL);
+    
+    level = rt_spin_lock_irqsave(&_spinlock);
+    
+    if (!(timer->flag & RT_TIMER_FLAG_ACTIVATED))
+    {
+        rt_spin_unlock_irqrestore(&_spinlock, level);
+        return -RT_ERROR;
+    }
+    
+    rt_list_remove(&timer->node);
+    timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
+    _set_next_timeout_locked();
+    
+    rt_spin_unlock_irqrestore(&_spinlock, level);
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_hrtimer_control(rt_clock_hrtimer_t timer, int cmd, void *arg)
+{
+    rt_base_t level;
+    
+    RT_ASSERT(timer != RT_NULL);
+    
+    level = rt_spin_lock_irqsave(&_spinlock);
+    
+    switch (cmd)
+    {
+    case RT_TIMER_CTRL_GET_TIME:
+        *(rt_uint64_t *)arg = timer->delay_cnt;
+        break;
+        
+    case RT_TIMER_CTRL_SET_TIME:
+        RT_ASSERT((*(rt_uint64_t *)arg) < (_HRTIMER_MAX_CNT / 2));
+        timer->delay_cnt = *(rt_uint64_t *)arg;
+        timer->timeout_cnt = *(rt_uint64_t *)arg + rt_clock_time_getcnt();
+        break;
+        
+    case RT_TIMER_CTRL_SET_ONESHOT:
+        timer->flag &= ~RT_TIMER_FLAG_PERIODIC;
+        break;
+        
+    case RT_TIMER_CTRL_SET_PERIODIC:
+        timer->flag |= RT_TIMER_FLAG_PERIODIC;
+        break;
+        
+    case RT_TIMER_CTRL_GET_STATE:
+        if (timer->flag & RT_TIMER_FLAG_ACTIVATED)
+        {
+            *(rt_uint32_t *)arg = RT_TIMER_FLAG_ACTIVATED;
+        }
+        else
+        {
+            *(rt_uint32_t *)arg = RT_TIMER_FLAG_DEACTIVATED;
+        }
+        break;
+        
+    case RT_TIMER_CTRL_GET_REMAIN_TIME:
+        *(rt_uint64_t *)arg = timer->timeout_cnt;
+        break;
+        
+    case RT_TIMER_CTRL_GET_FUNC:
+        arg = (void *)timer->timeout_func;
+        break;
+        
+    case RT_TIMER_CTRL_SET_FUNC:
+        timer->timeout_func = (void (*)(void *))arg;
+        break;
+        
+    case RT_TIMER_CTRL_GET_PARM:
+        *(void **)arg = timer->parameter;
+        break;
+        
+    case RT_TIMER_CTRL_SET_PARM:
+        timer->parameter = arg;
+        break;
+        
+    default:
+        rt_spin_unlock_irqrestore(&_spinlock, level);
+        return -RT_ERROR;
+    }
+    
+    rt_spin_unlock_irqrestore(&_spinlock, level);
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_hrtimer_detach(rt_clock_hrtimer_t timer)
+{
+    rt_base_t level;
+    
+    RT_ASSERT(timer != RT_NULL);
+    
+    level = rt_spin_lock_irqsave(&_spinlock);
+    
+    if (timer->flag & RT_TIMER_FLAG_ACTIVATED)
+    {
+        rt_list_remove(&timer->node);
+        timer->flag &= ~RT_TIMER_FLAG_ACTIVATED;
+        _set_next_timeout_locked();
+    }
+    
+    rt_spin_unlock_irqrestore(&_spinlock, level);
+    
+    rt_completion_detach(&timer->completion);
+    
+    return RT_EOK;
+}
+
+/* Delay functions */
+
+static void _sleep_timeout(void *parameter)
+{
+    struct rt_clock_hrtimer *timer = parameter;
+    rt_completion_done(&timer->completion);
+}
+
+rt_err_t rt_clock_hrtimer_sleep(rt_clock_hrtimer_t timer, rt_uint64_t cnt)
+{
+    RT_ASSERT(timer != RT_NULL);
+    
+    if (cnt == 0)
+    {
+        return -RT_EINVAL;
+    }
+    
+    rt_clock_hrtimer_init(timer, "hrt_sleep", RT_TIMER_FLAG_ONE_SHOT, 
+                         _sleep_timeout, timer);
+    
+    rt_err_t result = rt_clock_hrtimer_start(timer, cnt);
+    if (result != RT_EOK)
+    {
+        return result;
+    }
+    
+    rt_completion_wait(&timer->completion, RT_WAITING_FOREVER);
+    rt_clock_hrtimer_detach(timer);
+    
+    return RT_EOK;
+}
+
+rt_err_t rt_clock_hrtimer_ndelay(rt_clock_hrtimer_t timer, rt_uint64_t ns)
+{
+    rt_uint64_t cnt = rt_clock_time_ns_to_cnt(ns);
+    return rt_clock_hrtimer_sleep(timer, cnt);
+}
+
+rt_err_t rt_clock_hrtimer_udelay(rt_clock_hrtimer_t timer, rt_uint64_t us)
+{
+    return rt_clock_hrtimer_ndelay(timer, us * 1000);
+}
+
+rt_err_t rt_clock_hrtimer_mdelay(rt_clock_hrtimer_t timer, rt_uint64_t ms)
+{
+    return rt_clock_hrtimer_ndelay(timer, ms * 1000 * 1000);
+}
+
+/* Simple delay functions with internal timer */
+
+rt_err_t rt_clock_ndelay(rt_uint64_t ns)
+{
+    struct rt_clock_hrtimer timer;
+    return rt_clock_hrtimer_ndelay(&timer, ns);
+}
+
+rt_err_t rt_clock_udelay(rt_uint64_t us)
+{
+    struct rt_clock_hrtimer timer;
+    return rt_clock_hrtimer_udelay(&timer, us);
+}
+
+rt_err_t rt_clock_mdelay(rt_uint64_t ms)
+{
+    struct rt_clock_hrtimer timer;
+    return rt_clock_hrtimer_mdelay(&timer, ms);
+}

+ 136 - 0
components/drivers/clock_time/src/ktime_compat.c

@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Compatibility layer for ktime APIs
+ */
+
+#include <rtdevice.h>
+#include <rthw.h>
+
+/* Legacy ktime API wrappers */
+
+rt_err_t rt_ktime_boottime_get_us(struct timeval *tv)
+{
+    return rt_clock_time_boottime_us(tv);
+}
+
+rt_err_t rt_ktime_boottime_get_s(time_t *t)
+{
+    return rt_clock_time_boottime_s(t);
+}
+
+rt_err_t rt_ktime_boottime_get_ns(struct timespec *ts)
+{
+    return rt_clock_time_boottime_ns(ts);
+}
+
+rt_uint64_t rt_ktime_cputimer_getres(void)
+{
+    return rt_clock_time_getres();
+}
+
+unsigned long rt_ktime_cputimer_getfrq(void)
+{
+    return (unsigned long)rt_clock_time_getfreq();
+}
+
+unsigned long rt_ktime_cputimer_getcnt(void)
+{
+    return (unsigned long)rt_clock_time_getcnt();
+}
+
+void rt_ktime_cputimer_init(void)
+{
+    /* No initialization needed with unified clock_time */
+}
+
+rt_uint64_t rt_ktime_hrtimer_getres(void)
+{
+    return rt_clock_time_getres();
+}
+
+unsigned long rt_ktime_hrtimer_getfrq(void)
+{
+    return (unsigned long)rt_clock_time_getfreq();
+}
+
+rt_err_t rt_ktime_hrtimer_settimeout(unsigned long cnt)
+{
+    struct rt_clock_time_device *dev = rt_clock_time_get_default();
+    
+    if (dev && (dev->caps & RT_CLOCK_TIME_CAP_CLOCKEVENT))
+    {
+        return dev->ops->set_timeout(cnt);
+    }
+    
+    return -RT_ENOSYS;
+}
+
+void rt_ktime_hrtimer_process(void)
+{
+    rt_clock_hrtimer_process();
+}
+
+void rt_ktime_hrtimer_init(struct rt_ktime_hrtimer *timer,
+                          const char *name,
+                          rt_uint8_t flag,
+                          void (*timeout)(void *parameter),
+                          void *parameter)
+{
+    rt_clock_hrtimer_init((rt_clock_hrtimer_t)timer, name, flag, timeout, parameter);
+}
+
+rt_err_t rt_ktime_hrtimer_start(struct rt_ktime_hrtimer *timer, unsigned long cnt)
+{
+    return rt_clock_hrtimer_start((rt_clock_hrtimer_t)timer, cnt);
+}
+
+rt_err_t rt_ktime_hrtimer_stop(struct rt_ktime_hrtimer *timer)
+{
+    return rt_clock_hrtimer_stop((rt_clock_hrtimer_t)timer);
+}
+
+rt_err_t rt_ktime_hrtimer_control(struct rt_ktime_hrtimer *timer, int cmd, void *arg)
+{
+    return rt_clock_hrtimer_control((rt_clock_hrtimer_t)timer, cmd, arg);
+}
+
+rt_err_t rt_ktime_hrtimer_detach(struct rt_ktime_hrtimer *timer)
+{
+    return rt_clock_hrtimer_detach((rt_clock_hrtimer_t)timer);
+}
+
+void rt_ktime_hrtimer_delay_init(struct rt_ktime_hrtimer *timer)
+{
+    rt_clock_hrtimer_init((rt_clock_hrtimer_t)timer, "delay", 
+                         RT_TIMER_FLAG_ONE_SHOT, RT_NULL, RT_NULL);
+}
+
+void rt_ktime_hrtimer_delay_detach(struct rt_ktime_hrtimer *timer)
+{
+    rt_clock_hrtimer_detach((rt_clock_hrtimer_t)timer);
+}
+
+rt_err_t rt_ktime_hrtimer_sleep(struct rt_ktime_hrtimer *timer, unsigned long cnt)
+{
+    return rt_clock_hrtimer_sleep((rt_clock_hrtimer_t)timer, cnt);
+}
+
+rt_err_t rt_ktime_hrtimer_ndelay(struct rt_ktime_hrtimer *timer, unsigned long ns)
+{
+    return rt_clock_hrtimer_ndelay((rt_clock_hrtimer_t)timer, ns);
+}
+
+rt_err_t rt_ktime_hrtimer_udelay(struct rt_ktime_hrtimer *timer, unsigned long us)
+{
+    return rt_clock_hrtimer_udelay((rt_clock_hrtimer_t)timer, us);
+}
+
+rt_err_t rt_ktime_hrtimer_mdelay(struct rt_ktime_hrtimer *timer, unsigned long ms)
+{
+    return rt_clock_hrtimer_mdelay((rt_clock_hrtimer_t)timer, ms);
+}

+ 8 - 1
components/drivers/cputime/Kconfig

@@ -1,7 +1,14 @@
 config RT_USING_CPUTIME
-    bool "Enable CPU time for high resolution clock counter"
+    bool "Enable CPU time for high resolution clock counter (DEPRECATED - use RT_USING_CLOCK_TIME instead)"
     default n
     help
+        WARNING: This subsystem is deprecated. Please use the unified
+        RT_USING_CLOCK_TIME subsystem instead, which provides all the
+        functionality of cputime with better design and compatibility.
+        
+        Enable RT_CLOCK_TIME_COMPAT_CPUTIME for backward compatibility.
+        
+        Original help text:
         When enable this option, the BSP should provide a rt_clock_cputime_ops
         for CPU time by:
         const static struct rt_clock_cputime_ops _ops = {...};

+ 7 - 1
components/drivers/hwtimer/Kconfig

@@ -1,6 +1,12 @@
 menuconfig RT_USING_HWTIMER
-    bool "Using Hardware Timer device drivers"
+    bool "Using Hardware Timer device drivers (DEPRECATED - use RT_USING_CLOCK_TIME instead)"
     default n
+    help
+        WARNING: This subsystem is deprecated. Please use the unified
+        RT_USING_CLOCK_TIME subsystem instead, which provides better
+        integration and design for hardware timers.
+        
+        Enable RT_CLOCK_TIME_COMPAT_HWTIMER for backward compatibility.
 
 config RT_HWTIMER_ARM_ARCH
     bool "ARM ARCH Timer"

+ 221 - 0
components/drivers/include/drivers/clock_time.h

@@ -0,0 +1,221 @@
+/*
+ * Copyright (c) 2006-2024, RT-Thread Development Team
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Change Logs:
+ * Date           Author       Notes
+ * 2024-12-04     RT-Thread    Unified clock_time subsystem
+ */
+
+#ifndef __CLOCK_TIME_H__
+#define __CLOCK_TIME_H__
+
+#include <rtthread.h>
+#include <sys/time.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define RT_CLOCK_TIME_RESMUL (1000000ULL)
+
+/* Capabilities flags */
+#define RT_CLOCK_TIME_CAP_CLOCKSOURCE   (1 << 0)  /* Provides free-running counter */
+#define RT_CLOCK_TIME_CAP_CLOCKEVENT    (1 << 1)  /* Supports oneshot timeout events */
+
+/**
+ * @brief Clock time device operations
+ * 
+ * This structure defines the operations that a clock time device must support.
+ * At minimum, get_freq and get_counter must be implemented for clocksource capability.
+ * For clockevent capability, set_timeout must also be implemented.
+ */
+struct rt_clock_time_ops
+{
+    rt_uint64_t (*get_freq)(void);                  /* Get counting frequency in Hz */
+    rt_uint64_t (*get_counter)(void);               /* Get current free-running counter value */
+    rt_err_t    (*set_timeout)(rt_uint64_t delta);  /* Set relative timeout in counter units, 0 to cancel */
+};
+
+/**
+ * @brief Clock time device structure
+ * 
+ * This represents a unified time device that can provide both clocksource
+ * (continuous time counter) and clockevent (programmable timeout) capabilities.
+ */
+struct rt_clock_time_device
+{
+    struct rt_device parent;                        /* Inherit from rt_device */
+    const struct rt_clock_time_ops *ops;           /* Device operations */
+    rt_uint64_t res_scale;                         /* Resolution scale factor (ns * scale / freq -> cnt) */
+    rt_uint8_t  caps;                              /* Capability flags */
+};
+typedef struct rt_clock_time_device *rt_clock_time_t;
+
+/**
+ * @brief Register a clock time device
+ * 
+ * @param dev Clock time device to register
+ * @param name Device name
+ * @param caps Capability flags (RT_CLOCK_TIME_CAP_CLOCKSOURCE | RT_CLOCK_TIME_CAP_CLOCKEVENT)
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_time_device_register(struct rt_clock_time_device *dev, 
+                                       const char *name, 
+                                       rt_uint8_t caps);
+
+/**
+ * @brief Set the system default clock time device
+ * 
+ * @param dev Clock time device to set as default
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_time_set_default(struct rt_clock_time_device *dev);
+
+/**
+ * @brief Get the system default clock time device
+ * 
+ * @return Pointer to default clock time device, or RT_NULL if none set
+ */
+struct rt_clock_time_device *rt_clock_time_get_default(void);
+
+/* Clocksource APIs - Get time information */
+
+/**
+ * @brief Get clock resolution in nanoseconds
+ * 
+ * @return Resolution value multiplied by RT_CLOCK_TIME_RESMUL
+ */
+rt_uint64_t rt_clock_time_getres(void);
+
+/**
+ * @brief Get clock frequency in Hz
+ * 
+ * @return Frequency in Hz
+ */
+rt_uint64_t rt_clock_time_getfreq(void);
+
+/**
+ * @brief Get current counter value
+ * 
+ * @return Current counter value
+ */
+rt_uint64_t rt_clock_time_getcnt(void);
+
+/**
+ * @brief Get boottime (time since boot) in various formats
+ */
+rt_err_t rt_clock_time_boottime_ns(struct timespec *ts);
+rt_err_t rt_clock_time_boottime_us(struct timeval *tv);
+rt_err_t rt_clock_time_boottime_s(time_t *t);
+
+/**
+ * @brief Convert counter ticks to time units
+ */
+rt_uint64_t rt_clock_time_cnt_to_ns(rt_uint64_t cnt);
+rt_uint64_t rt_clock_time_cnt_to_us(rt_uint64_t cnt);
+rt_uint64_t rt_clock_time_cnt_to_ms(rt_uint64_t cnt);
+
+/**
+ * @brief Convert time units to counter ticks
+ */
+rt_uint64_t rt_clock_time_ns_to_cnt(rt_uint64_t ns);
+rt_uint64_t rt_clock_time_us_to_cnt(rt_uint64_t us);
+rt_uint64_t rt_clock_time_ms_to_cnt(rt_uint64_t ms);
+
+/* High-resolution timer (hrtimer) APIs */
+
+struct rt_clock_hrtimer
+{
+    rt_uint8_t           flag;                      /* Timer flags (compatible with rt_timer) */
+    char                 name[RT_NAME_MAX];        /* Timer name */
+    rt_list_t            node;                      /* List node */
+    void                *parameter;                 /* User parameter */
+    rt_uint64_t          delay_cnt;                /* Delay in counter ticks */
+    rt_uint64_t          timeout_cnt;              /* Absolute timeout counter value */
+    rt_err_t             error;                     /* Error code */
+    struct rt_completion completion;                /* Completion for blocking waits */
+    void (*timeout_func)(void *parameter);         /* Timeout callback */
+};
+typedef struct rt_clock_hrtimer *rt_clock_hrtimer_t;
+
+/**
+ * @brief Initialize a high-resolution timer
+ * 
+ * @param timer Timer structure to initialize
+ * @param name Timer name
+ * @param flag Timer flags (RT_TIMER_FLAG_ONE_SHOT or RT_TIMER_FLAG_PERIODIC)
+ * @param timeout Timeout callback function
+ * @param parameter Parameter passed to timeout callback
+ */
+void rt_clock_hrtimer_init(rt_clock_hrtimer_t timer,
+                          const char *name,
+                          rt_uint8_t flag,
+                          void (*timeout)(void *parameter),
+                          void *parameter);
+
+/**
+ * @brief Start a high-resolution timer
+ * 
+ * @param timer Timer to start
+ * @param delay_cnt Delay in counter ticks
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_hrtimer_start(rt_clock_hrtimer_t timer, rt_uint64_t delay_cnt);
+
+/**
+ * @brief Stop a high-resolution timer
+ * 
+ * @param timer Timer to stop
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_hrtimer_stop(rt_clock_hrtimer_t timer);
+
+/**
+ * @brief Control a high-resolution timer
+ * 
+ * @param timer Timer to control
+ * @param cmd Control command
+ * @param arg Command argument
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_hrtimer_control(rt_clock_hrtimer_t timer, int cmd, void *arg);
+
+/**
+ * @brief Detach a high-resolution timer
+ * 
+ * @param timer Timer to detach
+ * @return RT_EOK on success, error code otherwise
+ */
+rt_err_t rt_clock_hrtimer_detach(rt_clock_hrtimer_t timer);
+
+/**
+ * @brief High-precision delay functions
+ */
+rt_err_t rt_clock_hrtimer_sleep(rt_clock_hrtimer_t timer, rt_uint64_t cnt);
+rt_err_t rt_clock_hrtimer_ndelay(rt_clock_hrtimer_t timer, rt_uint64_t ns);
+rt_err_t rt_clock_hrtimer_udelay(rt_clock_hrtimer_t timer, rt_uint64_t us);
+rt_err_t rt_clock_hrtimer_mdelay(rt_clock_hrtimer_t timer, rt_uint64_t ms);
+
+/**
+ * @brief Simple delay functions (use internal timer)
+ */
+rt_err_t rt_clock_ndelay(rt_uint64_t ns);
+rt_err_t rt_clock_udelay(rt_uint64_t us);
+rt_err_t rt_clock_mdelay(rt_uint64_t ms);
+
+/**
+ * @brief Process hrtimer timeouts (called from device driver ISR)
+ */
+void rt_clock_hrtimer_process(void);
+
+/* POSIX clock support */
+#define CLOCK_REALTIME_ALARM    8
+#define CLOCK_BOOTTIME_ALARM    9
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __CLOCK_TIME_H__ */

+ 7 - 1
components/drivers/ktime/Kconfig

@@ -1,3 +1,9 @@
 menuconfig RT_USING_KTIME
-    bool "Ktime: kernel time"
+    bool "Ktime: kernel time (DEPRECATED - use RT_USING_CLOCK_TIME instead)"
     default n
+    help
+        WARNING: This subsystem is deprecated. Please use the unified
+        RT_USING_CLOCK_TIME subsystem instead, which provides all the
+        functionality of ktime with better design and compatibility.
+        
+        Enable RT_CLOCK_TIME_COMPAT_KTIME for backward compatibility.

+ 371 - 0
documentation/6.components/device-driver/clock_time.md

@@ -0,0 +1,371 @@
+# Clock Time Device
+
+## Introduction
+
+The `clock_time` subsystem provides a unified framework for time management in RT-Thread, consolidating the functionality of the legacy `hwtimer`, `ktime`, and `cputime` subsystems into a single, coherent API.
+
+### Key Features
+
+- **Clocksource**: Free-running counter for timekeeping and timestamps
+- **Clockevent**: Programmable timeout events for high-precision timing
+- **High-Resolution Timers (hrtimer)**: Efficient timer management with linked-list scheduling
+- **POSIX Clock Support**: Compatible with standard POSIX clock APIs
+- **Boottime Tracking**: Monotonic time since system boot
+- **Backward Compatibility**: Compatibility layers for legacy APIs
+
+### Design Philosophy
+
+The clock_time subsystem follows RT-Thread's C-OOP (Object-Oriented Programming in C) design pattern:
+
+1. **Unified Device Abstraction**: `rt_clock_time_device` encapsulates hardware timer capabilities
+2. **Operations Structure**: `rt_clock_time_ops` defines hardware-specific operations
+3. **Capability Flags**: Explicitly indicates clocksource and clockevent support
+4. **Flexible Integration**: Works with both MCU and MPU platforms
+
+## Architecture
+
+```
+┌─────────────────────────────────────────────────────────┐
+│                   Application Layer                      │
+│  (POSIX APIs, Delays, Timekeeping, High-Res Timers)    │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│              clock_time Subsystem                        │
+│  ┌─────────────┐  ┌──────────┐  ┌──────────────────┐   │
+│  │ Clocksource │  │ Boottime │  │ High-Res Timers │   │
+│  └─────────────┘  └──────────┘  └──────────────────┘   │
+│  ┌─────────────┐  ┌──────────────────────────────┐     │
+│  │ Clockevent  │  │    Compatibility Layers      │     │
+│  └─────────────┘  └──────────────────────────────┘     │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│           Hardware Timer Abstraction                     │
+│        (rt_clock_time_device + ops)                     │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│              BSP Timer Driver                           │
+│   (SysTick, ARM Arch Timer, RISC-V Timer, etc.)        │
+└─────────────────────────────────────────────────────────┘
+```
+
+## Usage
+
+### Registering a Clock Time Device
+
+BSP drivers should implement the `rt_clock_time_ops` and register a device:
+
+```c
+#include <rtdevice.h>
+
+static rt_uint64_t my_timer_get_freq(void)
+{
+    return 1000000; /* 1MHz timer */
+}
+
+static rt_uint64_t my_timer_get_counter(void)
+{
+    return MY_TIMER->CNT; /* Read hardware counter */
+}
+
+static rt_err_t my_timer_set_timeout(rt_uint64_t delta)
+{
+    if (delta == 0)
+    {
+        /* Cancel timeout */
+        MY_TIMER->CR &= ~TIMER_ENABLE;
+        return RT_EOK;
+    }
+    
+    MY_TIMER->CMP = MY_TIMER->CNT + delta;
+    MY_TIMER->CR |= TIMER_ENABLE | TIMER_INT_ENABLE;
+    return RT_EOK;
+}
+
+static const struct rt_clock_time_ops my_timer_ops =
+{
+    .get_freq = my_timer_get_freq,
+    .get_counter = my_timer_get_counter,
+    .set_timeout = my_timer_set_timeout,
+};
+
+static struct rt_clock_time_device my_clock_device;
+
+int my_timer_init(void)
+{
+    /* Initialize hardware timer */
+    my_clock_device.ops = &my_timer_ops;
+    
+    /* Register with both clocksource and clockevent capabilities */
+    rt_clock_time_device_register(&my_clock_device, 
+                                  "hw_timer",
+                                  RT_CLOCK_TIME_CAP_CLOCKSOURCE | 
+                                  RT_CLOCK_TIME_CAP_CLOCKEVENT);
+    
+    return 0;
+}
+INIT_DEVICE_EXPORT(my_timer_init);
+
+/* Timer ISR should call rt_clock_hrtimer_process() */
+void MY_TIMER_IRQHandler(void)
+{
+    /* Clear interrupt flag */
+    MY_TIMER->SR = 0;
+    
+    /* Process hrtimer timeouts */
+    rt_clock_hrtimer_process();
+}
+```
+
+### Using Clocksource APIs
+
+#### Get Time Information
+
+```c
+/* Get clock resolution (in ns, scaled by RT_CLOCK_TIME_RESMUL) */
+rt_uint64_t res = rt_clock_time_getres();
+
+/* Get clock frequency in Hz */
+rt_uint64_t freq = rt_clock_time_getfreq();
+
+/* Get current counter value */
+rt_uint64_t cnt = rt_clock_time_getcnt();
+```
+
+#### Get Boottime
+
+```c
+struct timespec ts;
+rt_clock_time_boottime_ns(&ts);
+rt_kprintf("Boot time: %d.%09d seconds\n", ts.tv_sec, ts.tv_nsec);
+
+struct timeval tv;
+rt_clock_time_boottime_us(&tv);
+
+time_t t;
+rt_clock_time_boottime_s(&t);
+```
+
+#### Time Conversion
+
+```c
+rt_uint64_t cnt = 1000000; /* counter ticks */
+
+/* Convert to time units */
+rt_uint64_t ns = rt_clock_time_cnt_to_ns(cnt);
+rt_uint64_t us = rt_clock_time_cnt_to_us(cnt);
+rt_uint64_t ms = rt_clock_time_cnt_to_ms(cnt);
+
+/* Convert from time units */
+cnt = rt_clock_time_ns_to_cnt(1000000); /* 1ms in nanoseconds */
+cnt = rt_clock_time_us_to_cnt(1000);    /* 1ms in microseconds */
+cnt = rt_clock_time_ms_to_cnt(1);       /* 1ms */
+```
+
+### Using High-Resolution Timers
+
+#### Create and Start a Timer
+
+```c
+#include <rtdevice.h>
+
+static void timeout_callback(void *param)
+{
+    rt_kprintf("Timer timeout!\n");
+}
+
+void hrtimer_example(void)
+{
+    struct rt_clock_hrtimer timer;
+    
+    /* Initialize timer */
+    rt_clock_hrtimer_init(&timer, "my_timer", 
+                         RT_TIMER_FLAG_ONE_SHOT,
+                         timeout_callback, 
+                         RT_NULL);
+    
+    /* Start timer with 1ms delay */
+    rt_uint64_t delay_cnt = rt_clock_time_ms_to_cnt(1);
+    rt_clock_hrtimer_start(&timer, delay_cnt);
+    
+    /* ... */
+    
+    /* Stop timer if needed */
+    rt_clock_hrtimer_stop(&timer);
+    
+    /* Cleanup */
+    rt_clock_hrtimer_detach(&timer);
+}
+```
+
+#### Periodic Timer
+
+```c
+static void periodic_callback(void *param)
+{
+    rt_kprintf("Periodic tick\n");
+}
+
+void periodic_timer_example(void)
+{
+    struct rt_clock_hrtimer timer;
+    
+    rt_clock_hrtimer_init(&timer, "periodic", 
+                         RT_TIMER_FLAG_PERIODIC,
+                         periodic_callback, 
+                         RT_NULL);
+    
+    /* Start with 100ms period */
+    rt_uint64_t period_cnt = rt_clock_time_ms_to_cnt(100);
+    rt_clock_hrtimer_start(&timer, period_cnt);
+}
+```
+
+### High-Precision Delays
+
+```c
+/* Delay in nanoseconds */
+rt_clock_ndelay(1000);  /* 1 microsecond */
+
+/* Delay in microseconds */
+rt_clock_udelay(1000);  /* 1 millisecond */
+
+/* Delay in milliseconds */
+rt_clock_mdelay(100);   /* 100 milliseconds */
+
+/* Using a custom timer for delays */
+struct rt_clock_hrtimer timer;
+rt_clock_hrtimer_mdelay(&timer, 50);  /* 50ms delay */
+```
+
+## Migration Guide
+
+### From ktime
+
+The clock_time subsystem provides direct API compatibility when `RT_CLOCK_TIME_COMPAT_KTIME` is enabled:
+
+| Old ktime API | New clock_time API |
+|--------------|-------------------|
+| `rt_ktime_boottime_get_ns()` | `rt_clock_time_boottime_ns()` |
+| `rt_ktime_cputimer_getres()` | `rt_clock_time_getres()` |
+| `rt_ktime_cputimer_getcnt()` | `rt_clock_time_getcnt()` |
+| `rt_ktime_hrtimer_init()` | `rt_clock_hrtimer_init()` |
+| `rt_ktime_hrtimer_start()` | `rt_clock_hrtimer_start()` |
+
+### From cputime
+
+When `RT_CLOCK_TIME_COMPAT_CPUTIME` is enabled:
+
+| Old cputime API | New clock_time API |
+|----------------|-------------------|
+| `clock_cpu_gettime()` | `rt_clock_time_getcnt()` |
+| `clock_cpu_getres()` | `rt_clock_time_getres()` |
+| `rt_cputime_sleep()` | `rt_clock_mdelay()` or use hrtimer |
+| `rt_cputime_udelay()` | `rt_clock_udelay()` |
+
+### From hwtimer
+
+Hardware timer devices should be migrated to the new clock_time device model:
+
+**Old hwtimer approach:**
+```c
+static const struct rt_hwtimer_ops my_ops = { ... };
+static struct rt_hwtimer_device my_device;
+my_device.ops = &my_ops;
+rt_device_hwtimer_register(&my_device, "timer0", RT_NULL);
+```
+
+**New clock_time approach:**
+```c
+static const struct rt_clock_time_ops my_ops = { ... };
+static struct rt_clock_time_device my_device;
+my_device.ops = &my_ops;
+rt_clock_time_device_register(&my_device, "timer0",
+    RT_CLOCK_TIME_CAP_CLOCKSOURCE | RT_CLOCK_TIME_CAP_CLOCKEVENT);
+```
+
+## Configuration
+
+### Kconfig Options
+
+```
+RT_USING_CLOCK_TIME              - Enable clock_time subsystem
+RT_CLOCK_TIME_COMPAT_KTIME       - Enable ktime compatibility layer
+RT_CLOCK_TIME_COMPAT_CPUTIME     - Enable cputime compatibility layer
+RT_CLOCK_TIME_COMPAT_HWTIMER     - Enable hwtimer compatibility layer
+```
+
+### Typical Configuration
+
+For new projects:
+```
+CONFIG_RT_USING_CLOCK_TIME=y
+# Compatibility layers not needed
+```
+
+For migrating projects:
+```
+CONFIG_RT_USING_CLOCK_TIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_KTIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_CPUTIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_HWTIMER=y
+```
+
+## Best Practices
+
+### For MCU Scenarios
+
+1. **Use SysTick or similar**: For basic timekeeping, SysTick provides adequate resolution
+2. **Hardware timers for precision**: Use dedicated hardware timers for microsecond-level precision
+3. **Consider power**: Minimize timer wakeups in low-power applications
+
+### For MPU Scenarios
+
+1. **Architecture timers**: Use ARM Generic Timer or RISC-V timer for best performance
+2. **SMP safety**: The hrtimer implementation uses spinlocks for SMP systems
+3. **High-frequency sources**: MPUs can handle higher frequency timers (MHz range)
+
+### General Guidelines
+
+1. **Single default device**: Register one primary clock_time device as the system default
+2. **ISR efficiency**: Keep `rt_clock_hrtimer_process()` call in ISR short
+3. **Resolution vs. overhead**: Higher resolution timers have higher overhead
+4. **Fallback support**: The tick-based fallback ensures functionality even without hardware timer
+
+## API Reference
+
+See the complete API documentation in `/components/drivers/include/drivers/clock_time.h`.
+
+## Examples
+
+Complete examples can be found in:
+- `/examples/clock_time/` - Basic usage examples
+- BSP timer driver implementations for reference
+
+## Troubleshooting
+
+### Timer not firing
+
+- Verify hardware timer is properly configured
+- Check that ISR calls `rt_clock_hrtimer_process()`
+- Ensure timer interrupt is enabled
+
+### Poor precision
+
+- Verify timer frequency is appropriate for your use case
+- Check for interrupt latency issues
+- Consider using a higher frequency timer
+
+### Compatibility issues
+
+- Enable appropriate compatibility layer in Kconfig
+- Check for API signature changes in migration
+- Verify BSP-specific timer implementation
+
+## See Also
+
+- [Timer Management](timer.md)
+- [Real-Time Clock (RTC)](rtc.md)
+- [Device Driver Framework](framework.md)

+ 371 - 0
documentation/6.components/device-driver/clock_time_zh.md

@@ -0,0 +1,371 @@
+# 时钟时间设备
+
+## 简介
+
+`clock_time` 子系统为 RT-Thread 提供了统一的时间管理框架,将原有的 `hwtimer`、`ktime` 和 `cputime` 子系统的功能整合到一个一致的 API 中。
+
+### 主要特性
+
+- **时钟源(Clocksource)**:用于计时和时间戳的自由运行计数器
+- **时钟事件(Clockevent)**:可编程超时事件,用于高精度定时
+- **高分辨率定时器(hrtimer)**:采用链表调度的高效定时器管理
+- **POSIX 时钟支持**:与标准 POSIX 时钟 API 兼容
+- **启动时间追踪**:记录系统启动以来的单调时间
+- **向后兼容**:为旧 API 提供兼容层
+
+### 设计理念
+
+clock_time 子系统遵循 RT-Thread 的 C-OOP(C 语言中的面向对象编程)设计模式:
+
+1. **统一设备抽象**:`rt_clock_time_device` 封装硬件定时器能力
+2. **操作结构**:`rt_clock_time_ops` 定义硬件特定操作
+3. **能力标志**:明确指示时钟源和时钟事件支持
+4. **灵活集成**:同时适用于 MCU 和 MPU 平台
+
+## 架构
+
+```
+┌─────────────────────────────────────────────────────────┐
+│                     应用层                               │
+│  (POSIX API、延时、计时、高分辨率定时器)                │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│              clock_time 子系统                           │
+│  ┌─────────────┐  ┌──────────┐  ┌──────────────────┐   │
+│  │   时钟源    │  │  启动时间 │  │ 高分辨率定时器   │   │
+│  └─────────────┘  └──────────┘  └──────────────────┘   │
+│  ┌─────────────┐  ┌──────────────────────────────┐     │
+│  │  时钟事件   │  │       兼容层                 │     │
+│  └─────────────┘  └──────────────────────────────┘     │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│            硬件定时器抽象                                │
+│        (rt_clock_time_device + ops)                     │
+└──────────────────┬──────────────────────────────────────┘
+                   │
+┌──────────────────▼──────────────────────────────────────┐
+│              BSP 定时器驱动                              │
+│   (SysTick、ARM 架构定时器、RISC-V 定时器等)            │
+└─────────────────────────────────────────────────────────┘
+```
+
+## 使用方法
+
+### 注册时钟时间设备
+
+BSP 驱动应实现 `rt_clock_time_ops` 并注册设备:
+
+```c
+#include <rtdevice.h>
+
+static rt_uint64_t my_timer_get_freq(void)
+{
+    return 1000000; /* 1MHz 定时器 */
+}
+
+static rt_uint64_t my_timer_get_counter(void)
+{
+    return MY_TIMER->CNT; /* 读取硬件计数器 */
+}
+
+static rt_err_t my_timer_set_timeout(rt_uint64_t delta)
+{
+    if (delta == 0)
+    {
+        /* 取消超时 */
+        MY_TIMER->CR &= ~TIMER_ENABLE;
+        return RT_EOK;
+    }
+    
+    MY_TIMER->CMP = MY_TIMER->CNT + delta;
+    MY_TIMER->CR |= TIMER_ENABLE | TIMER_INT_ENABLE;
+    return RT_EOK;
+}
+
+static const struct rt_clock_time_ops my_timer_ops =
+{
+    .get_freq = my_timer_get_freq,
+    .get_counter = my_timer_get_counter,
+    .set_timeout = my_timer_set_timeout,
+};
+
+static struct rt_clock_time_device my_clock_device;
+
+int my_timer_init(void)
+{
+    /* 初始化硬件定时器 */
+    my_clock_device.ops = &my_timer_ops;
+    
+    /* 注册设备,同时支持时钟源和时钟事件能力 */
+    rt_clock_time_device_register(&my_clock_device, 
+                                  "hw_timer",
+                                  RT_CLOCK_TIME_CAP_CLOCKSOURCE | 
+                                  RT_CLOCK_TIME_CAP_CLOCKEVENT);
+    
+    return 0;
+}
+INIT_DEVICE_EXPORT(my_timer_init);
+
+/* 定时器中断服务程序应调用 rt_clock_hrtimer_process() */
+void MY_TIMER_IRQHandler(void)
+{
+    /* 清除中断标志 */
+    MY_TIMER->SR = 0;
+    
+    /* 处理 hrtimer 超时 */
+    rt_clock_hrtimer_process();
+}
+```
+
+### 使用时钟源 API
+
+#### 获取时间信息
+
+```c
+/* 获取时钟分辨率(以纳秒为单位,按 RT_CLOCK_TIME_RESMUL 缩放)*/
+rt_uint64_t res = rt_clock_time_getres();
+
+/* 获取时钟频率(Hz)*/
+rt_uint64_t freq = rt_clock_time_getfreq();
+
+/* 获取当前计数器值 */
+rt_uint64_t cnt = rt_clock_time_getcnt();
+```
+
+#### 获取启动时间
+
+```c
+struct timespec ts;
+rt_clock_time_boottime_ns(&ts);
+rt_kprintf("启动时间: %d.%09d 秒\n", ts.tv_sec, ts.tv_nsec);
+
+struct timeval tv;
+rt_clock_time_boottime_us(&tv);
+
+time_t t;
+rt_clock_time_boottime_s(&t);
+```
+
+#### 时间转换
+
+```c
+rt_uint64_t cnt = 1000000; /* 计数器滴答 */
+
+/* 转换为时间单位 */
+rt_uint64_t ns = rt_clock_time_cnt_to_ns(cnt);
+rt_uint64_t us = rt_clock_time_cnt_to_us(cnt);
+rt_uint64_t ms = rt_clock_time_cnt_to_ms(cnt);
+
+/* 从时间单位转换 */
+cnt = rt_clock_time_ns_to_cnt(1000000); /* 1ms(纳秒)*/
+cnt = rt_clock_time_us_to_cnt(1000);    /* 1ms(微秒)*/
+cnt = rt_clock_time_ms_to_cnt(1);       /* 1ms */
+```
+
+### 使用高分辨率定时器
+
+#### 创建并启动定时器
+
+```c
+#include <rtdevice.h>
+
+static void timeout_callback(void *param)
+{
+    rt_kprintf("定时器超时!\n");
+}
+
+void hrtimer_example(void)
+{
+    struct rt_clock_hrtimer timer;
+    
+    /* 初始化定时器 */
+    rt_clock_hrtimer_init(&timer, "my_timer", 
+                         RT_TIMER_FLAG_ONE_SHOT,
+                         timeout_callback, 
+                         RT_NULL);
+    
+    /* 以 1ms 延迟启动定时器 */
+    rt_uint64_t delay_cnt = rt_clock_time_ms_to_cnt(1);
+    rt_clock_hrtimer_start(&timer, delay_cnt);
+    
+    /* ... */
+    
+    /* 如果需要可以停止定时器 */
+    rt_clock_hrtimer_stop(&timer);
+    
+    /* 清理 */
+    rt_clock_hrtimer_detach(&timer);
+}
+```
+
+#### 周期定时器
+
+```c
+static void periodic_callback(void *param)
+{
+    rt_kprintf("周期滴答\n");
+}
+
+void periodic_timer_example(void)
+{
+    struct rt_clock_hrtimer timer;
+    
+    rt_clock_hrtimer_init(&timer, "periodic", 
+                         RT_TIMER_FLAG_PERIODIC,
+                         periodic_callback, 
+                         RT_NULL);
+    
+    /* 以 100ms 周期启动 */
+    rt_uint64_t period_cnt = rt_clock_time_ms_to_cnt(100);
+    rt_clock_hrtimer_start(&timer, period_cnt);
+}
+```
+
+### 高精度延时
+
+```c
+/* 纳秒延时 */
+rt_clock_ndelay(1000);  /* 1 微秒 */
+
+/* 微秒延时 */
+rt_clock_udelay(1000);  /* 1 毫秒 */
+
+/* 毫秒延时 */
+rt_clock_mdelay(100);   /* 100 毫秒 */
+
+/* 使用自定义定时器进行延时 */
+struct rt_clock_hrtimer timer;
+rt_clock_hrtimer_mdelay(&timer, 50);  /* 50ms 延时 */
+```
+
+## 迁移指南
+
+### 从 ktime 迁移
+
+当启用 `RT_CLOCK_TIME_COMPAT_KTIME` 时,clock_time 子系统提供直接的 API 兼容性:
+
+| 旧 ktime API | 新 clock_time API |
+|--------------|-------------------|
+| `rt_ktime_boottime_get_ns()` | `rt_clock_time_boottime_ns()` |
+| `rt_ktime_cputimer_getres()` | `rt_clock_time_getres()` |
+| `rt_ktime_cputimer_getcnt()` | `rt_clock_time_getcnt()` |
+| `rt_ktime_hrtimer_init()` | `rt_clock_hrtimer_init()` |
+| `rt_ktime_hrtimer_start()` | `rt_clock_hrtimer_start()` |
+
+### 从 cputime 迁移
+
+当启用 `RT_CLOCK_TIME_COMPAT_CPUTIME` 时:
+
+| 旧 cputime API | 新 clock_time API |
+|----------------|-------------------|
+| `clock_cpu_gettime()` | `rt_clock_time_getcnt()` |
+| `clock_cpu_getres()` | `rt_clock_time_getres()` |
+| `rt_cputime_sleep()` | `rt_clock_mdelay()` 或使用 hrtimer |
+| `rt_cputime_udelay()` | `rt_clock_udelay()` |
+
+### 从 hwtimer 迁移
+
+硬件定时器设备应迁移到新的 clock_time 设备模型:
+
+**旧 hwtimer 方式:**
+```c
+static const struct rt_hwtimer_ops my_ops = { ... };
+static struct rt_hwtimer_device my_device;
+my_device.ops = &my_ops;
+rt_device_hwtimer_register(&my_device, "timer0", RT_NULL);
+```
+
+**新 clock_time 方式:**
+```c
+static const struct rt_clock_time_ops my_ops = { ... };
+static struct rt_clock_time_device my_device;
+my_device.ops = &my_ops;
+rt_clock_time_device_register(&my_device, "timer0",
+    RT_CLOCK_TIME_CAP_CLOCKSOURCE | RT_CLOCK_TIME_CAP_CLOCKEVENT);
+```
+
+## 配置
+
+### Kconfig 选项
+
+```
+RT_USING_CLOCK_TIME              - 启用 clock_time 子系统
+RT_CLOCK_TIME_COMPAT_KTIME       - 启用 ktime 兼容层
+RT_CLOCK_TIME_COMPAT_CPUTIME     - 启用 cputime 兼容层
+RT_CLOCK_TIME_COMPAT_HWTIMER     - 启用 hwtimer 兼容层
+```
+
+### 典型配置
+
+对于新项目:
+```
+CONFIG_RT_USING_CLOCK_TIME=y
+# 不需要兼容层
+```
+
+对于迁移项目:
+```
+CONFIG_RT_USING_CLOCK_TIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_KTIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_CPUTIME=y
+CONFIG_RT_CLOCK_TIME_COMPAT_HWTIMER=y
+```
+
+## 最佳实践
+
+### MCU 场景
+
+1. **使用 SysTick 或类似定时器**:对于基本计时,SysTick 提供足够的分辨率
+2. **硬件定时器提供精度**:使用专用硬件定时器实现微秒级精度
+3. **考虑功耗**:在低功耗应用中最小化定时器唤醒
+
+### MPU 场景
+
+1. **架构定时器**:使用 ARM 通用定时器或 RISC-V 定时器以获得最佳性能
+2. **SMP 安全**:hrtimer 实现使用自旋锁支持 SMP 系统
+3. **高频率源**:MPU 可以处理更高频率的定时器(MHz 范围)
+
+### 通用准则
+
+1. **单一默认设备**:注册一个主要的 clock_time 设备作为系统默认
+2. **中断服务程序效率**:在 ISR 中保持 `rt_clock_hrtimer_process()` 调用简短
+3. **分辨率与开销**:更高分辨率的定时器有更高的开销
+4. **回退支持**:基于滴答的回退确保即使没有硬件定时器也能正常工作
+
+## API 参考
+
+完整的 API 文档请参阅 `/components/drivers/include/drivers/clock_time.h`。
+
+## 示例
+
+完整示例可在以下位置找到:
+- `/examples/clock_time/` - 基本使用示例
+- BSP 定时器驱动实现供参考
+
+## 故障排除
+
+### 定时器不触发
+
+- 验证硬件定时器配置正确
+- 检查 ISR 是否调用 `rt_clock_hrtimer_process()`
+- 确保定时器中断已启用
+
+### 精度差
+
+- 验证定时器频率适合您的用例
+- 检查中断延迟问题
+- 考虑使用更高频率的定时器
+
+### 兼容性问题
+
+- 在 Kconfig 中启用适当的兼容层
+- 检查迁移中的 API 签名更改
+- 验证 BSP 特定的定时器实现
+
+## 另请参阅
+
+- [定时器管理](timer.md)
+- [实时时钟(RTC)](rtc.md)
+- [设备驱动框架](framework.md)