This is an automated email from the ASF dual-hosted git repository.

GUIDINGLI pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/nuttx.git

commit 56b24dc19c9d10644bca9952d06d027a3e9daf39
Author: yangsong8 <[email protected]>
AuthorDate: Thu Apr 23 11:30:53 2026 +0800

    timers/ocu: add OCU (Output Compare Unit) driver framework
    
    Add a new upper-half OCU driver framework for output compare
    functionality. The OCU driver compares a free-running counter against
    a programmable threshold and performs configurable actions (pin toggle,
    notification callback) on match.
    
    New files:
    - include/nuttx/timers/ocu.h: Framework header with types, ioctl
      commands, and lower-half ops structure
    - drivers/timers/ocu.c: Upper-half driver with character device
      interface, ioctl dispatch, callback wrapper, and notification support
    - Documentation/os/drivers/character/timers/ocu.rst: Driver
      documentation
    
    Modified files:
    - include/nuttx/fs/ioctl.h: Add _OCUIOCBASE (0x4b00) and _OCUIOC()
    - drivers/timers/Kconfig: Add CONFIG_OCU
    - drivers/timers/CMakeLists.txt: Add ocu.c build entry
    - Documentation/os/drivers/character/timers/index.rst: Add ocu
    
    Supported ioctl commands:
    - OCUIOC_START/STOP: Channel start/stop control
    - OCUIOC_GETSTATUS: Get channel status (flags, counter, threshold)
    - OCUIOC_GETCOUNTER: Read current counter value
    - OCUIOC_SETABSTHRESHOLD: Set absolute compare threshold
    - OCUIOC_SETRELTHRESHOLD: Set threshold relative to current counter
    - OCUIOC_SETADVANCETHRESHOLD: Set threshold relative to current
      threshold
    - OCUIOC_SETPINSTATE/SETPINACTION: Output pin control
    - OCUIOC_NOTIFICATION: Signal-based notification for user space
    
    The driver uses the timer-style setcallback pattern: upper-half
    registers an internal wrapper callback with lower-half via
    ops->setcallback() and sends signal notifications.  Kernel drivers
    that need a direct callback use the OCU_SETCALLBACK() macro.
    
    Signed-off-by: yangsong8 <[email protected]>
---
 .../os/drivers/character/timers/index.rst          |   1 +
 Documentation/os/drivers/character/timers/ocu.rst  | 257 ++++++++++
 drivers/timers/CMakeLists.txt                      |   4 +
 drivers/timers/Kconfig                             |  11 +
 drivers/timers/ocu.c                               | 526 +++++++++++++++++++++
 include/nuttx/fs/ioctl.h                           |   8 +
 include/nuttx/timers/ocu.h                         | 394 +++++++++++++++
 7 files changed, 1201 insertions(+)

diff --git a/Documentation/os/drivers/character/timers/index.rst 
b/Documentation/os/drivers/character/timers/index.rst
index 51ce8415fda..7c979d0909c 100644
--- a/Documentation/os/drivers/character/timers/index.rst
+++ b/Documentation/os/drivers/character/timers/index.rst
@@ -8,6 +8,7 @@ Timers Drivers
   timer.rst
   oneshot.rst
   pwm.rst
+  ocu.rst
   pulsecount.rst
   watchdog.rst
   rtc.rst
diff --git a/Documentation/os/drivers/character/timers/ocu.rst 
b/Documentation/os/drivers/character/timers/ocu.rst
new file mode 100644
index 00000000000..c9cda7b9399
--- /dev/null
+++ b/Documentation/os/drivers/character/timers/ocu.rst
@@ -0,0 +1,257 @@
+===========
+OCU Drivers
+===========
+
+The OCU (Output Compare Unit) driver provides a standard interface for
+hardware output compare functionality.  An OCU channel compares a free-running
+counter against a programmable threshold and performs configurable actions
+(pin toggle, notification callback) on match.
+
+This interface is distinct from PWM, Timer, and Pulsecount drivers:
+
+- **PWM** outputs a continuous periodic waveform (frequency + duty cycle).
+- **Timer** fires after a relative time interval (countdown).
+- **Pulsecount** generates a finite pulse train (high_ns + low_ns × count)
+  and stops.  All pulses share the same parameters; no per-pulse variation or
+  static pin level control is supported.
+- **OCU** triggers at an absolute counter position and can dynamically update
+  the next trigger point from within the compare match ISR.  It also provides
+  direct pin level control (``SETPINSTATE``) independent of compare match
+  events.
+
+OCU is commonly used for precise time-based control such as engine ignition
+timing, camshaft angle control, and motor commutation where the trigger point
+must be programmed as an absolute position on a free-running counter.
+
+Driver Model
+============
+
+The NuttX OCU driver is split into two parts:
+
+#. An upper-half character driver that provides the common application
+   interface via ioctl commands.
+#. A lower-half platform driver that programs the hardware timer/compare
+   peripheral.  The lower-half holds a callback pointer and calls it directly
+   from the compare match ISR (timer-style ``setcallback`` pattern).
+
+Files supporting OCU can be found in the following locations:
+
+- ``include/nuttx/timers/ocu.h`` - public interface, types, ioctl commands,
+  and lower-half ops structure.
+- ``drivers/timers/ocu.c`` - generic upper-half driver.
+- ``arch/<architecture>/src/<chip>/*ocu*.c`` - platform lower-half drivers.
+
+Application Interface
+=====================
+
+Applications use the OCU driver through a character device such as
+``/dev/ocu0``.  Include the OCU header:
+
+.. code-block:: c
+
+   #include <nuttx/timers/ocu.h>
+
+The driver is controlled through ``ioctl`` commands:
+
+- ``OCUIOC_START`` - Start the channel, enabling compare match actions.
+- ``OCUIOC_STOP`` - Stop compare match actions (counter keeps running).
+- ``OCUIOC_GETSTATUS`` - Get channel status (flags, counter, threshold).
+- ``OCUIOC_GETCOUNTER`` - Read current counter value in ticks.
+- ``OCUIOC_SETABSTHRESHOLD`` - Set absolute compare threshold.
+- ``OCUIOC_SETRELTHRESHOLD`` - Set threshold relative to current counter.
+- ``OCUIOC_SETADVANCETHRESHOLD`` - Advance threshold by step from current 
threshold.
+- ``OCUIOC_SETPINSTATE`` - Set output pin level (only when stopped).
+- ``OCUIOC_SETPINACTION`` - Set automatic pin action on compare match.
+- ``OCUIOC_NOTIFICATION`` - Enable/disable signal notification to user space.
+
+Threshold Setting
+=================
+
+Three modes are available for setting the compare threshold, corresponding to
+AUTOSAR OCU specification SRS_Ocu_00010:
+
+**Absolute** (``OCUIOC_SETABSTHRESHOLD``):
+
+.. code-block:: c
+
+   uint32_t current_counter;
+   ioctl(fd, OCUIOC_GETCOUNTER, &current_counter);
+
+   struct ocu_abs_threshold_s t = {
+       .reference = current_counter,  /* Base for interval check */
+       .absolute  = 5000,             /* Trigger at tick 5000 */
+   };
+   ioctl(fd, OCUIOC_SETABSTHRESHOLD, &t);
+   /* t.result indicates if match is in current reference interval */
+
+**Relative to counter** (``OCUIOC_SETRELTHRESHOLD``):
+
+.. code-block:: c
+
+   struct ocu_rel_threshold_s t = { .relative = 1000 };
+   ioctl(fd, OCUIOC_SETRELTHRESHOLD, &t);
+   /* new_threshold = current_counter + 1000 */
+
+**Advance from current threshold** (``OCUIOC_SETADVANCETHRESHOLD``):
+
+.. code-block:: c
+
+   struct ocu_advance_threshold_s t = { .step = 500 };
+   ioctl(fd, OCUIOC_SETADVANCETHRESHOLD, &t);
+   /* new_threshold = current_threshold + 500 */
+
+The last mode is useful for evenly-spaced triggers that span counter rollover.
+
+Pin Control
+===========
+
+OCU channels may have an associated output pin.  The pin can be controlled in
+two ways:
+
+- ``OCUIOC_SETPINSTATE`` sets the pin level immediately (LOW or HIGH).  This
+  is only allowed when the channel is stopped.
+- ``OCUIOC_SETPINACTION`` configures the automatic action on compare match:
+  ``OCU_PINACTION_DISABLE``, ``OCU_PINACTION_SET_LOW``,
+  ``OCU_PINACTION_SET_HIGH``, or ``OCU_PINACTION_TOGGLE``.
+
+If the hardware does not have an output pin, these calls return ``-ENOTSUP``.
+
+Notification Mechanisms
+=======================
+
+Two notification paths exist for compare match events, following the same
+design pattern as the NuttX Timer driver (``TIMER_SETCALLBACK`` macro vs
+``TCIOC_NOTIFICATION`` ioctl):
+
+Kernel-Internal Callback (ISR Context)
+--------------------------------------
+
+For lowest latency, kernel drivers can register a callback directly with the
+lower-half using the ``OCU_SETCALLBACK()`` macro.  The callback runs in
+interrupt context and can atomically update the next threshold:
+
+.. code-block:: c
+
+   #include <nuttx/timers/ocu.h>
+
+   static bool my_handler(FAR uint32_t *next_threshold, FAR void *arg)
+   {
+       *next_threshold = (*next_threshold + STEP) % MAX;
+       return true;  /* Re-arm with new threshold */
+   }
+
+   /* Called from kernel code, NOT from user-space ioctl */
+   OCU_SETCALLBACK(lower, my_handler, priv);
+   OCU_NOTIFICATION(lower, true);   /* Enable the hardware compare match IRQ */
+
+.. important::
+
+   ``OCU_SETCALLBACK()`` and ``OCU_NOTIFICATION()`` are **separate**
+   operations and must be used together on the kernel-internal path:
+
+   - ``OCU_SETCALLBACK()`` only *stores* the callback pointer in the
+     lower-half.  It does **not** enable any hardware interrupt.
+   - ``OCU_NOTIFICATION(lower, true)`` enables the hardware compare-match
+     notification (e.g. ``Ocu_EnableNotification()`` on Infineon AURIX);
+     ``OCU_NOTIFICATION(lower, false)`` disables it.
+
+   A kernel driver that registers a callback via ``OCU_SETCALLBACK()`` but
+   forgets ``OCU_NOTIFICATION(lower, true)`` will **never** receive compare
+   match callbacks, because the hardware interrupt stays disabled.  To tear
+   down, disable first, then clear the callback::
+
+      OCU_NOTIFICATION(lower, false);
+      OCU_SETCALLBACK(lower, NULL, NULL);
+
+.. note::
+
+   ``OCU_SETCALLBACK()`` is a macro that calls ``lower->ops->setcallback()``
+   when the lower-half provides it (the call is skipped safely if the op is
+   ``NULL``).  It is only available to kernel-internal drivers (same pattern
+   as ``TIMER_SETCALLBACK``).  There is **no** ioctl for registering function
+   pointers from user space.  Neither ``start()`` nor ``stop()`` touches the
+   notification state; enabling/disabling the hardware interrupt is done
+   exclusively through ``OCU_NOTIFICATION()``.
+
+User-Space Signal Notification
+------------------------------
+
+User-space applications receive compare match events via signal notification,
+configured through ``OCUIOC_NOTIFICATION``:
+
+.. code-block:: c
+
+   struct ocu_notify_s n = {
+       .enable = true,
+       .pid    = getpid(),
+       .event  = { .sigev_signo = SIGUSR1 },
+   };
+   ioctl(fd, OCUIOC_NOTIFICATION, &n);
+
+When enabled, the ``OCUIOC_NOTIFICATION`` handler performs two steps: it
+registers an internal notifier callback (``ocu_notifier``) with the
+lower-half via ``setcallback()``, then enables the hardware compare-match
+notification via the ``notification()`` op.  On compare match, the hardware
+interrupt invokes ``ocu_notifier``, which sends a signal to the registered
+process.  Disabling reverses the order (disable hardware notification, then
+clear the callback).  The upper-half does **not** re-arm the threshold
+automatically — user space must explicitly set the next threshold via ioctl
+after receiving the signal.
+
+To disable notification:
+
+.. code-block:: c
+
+   struct ocu_notify_s n = { .enable = false };
+   ioctl(fd, OCUIOC_NOTIFICATION, &n);
+
+.. note::
+
+   The two paths are mutually exclusive on the same channel.  If a kernel
+   driver registers a callback via ``OCU_SETCALLBACK()``, it overrides any
+   user-space notification previously set up through ``OCUIOC_NOTIFICATION``.
+
+Lifecycle
+=========
+
+The OCU driver supports multiple opens via reference counting:
+
+- First ``open()`` calls ``ops->setup()`` to initialize hardware.
+- Last ``close()`` calls ``ops->stop()`` (if running) then
+  ``ops->shutdown()`` to release hardware.
+
+The channel state machine:
+
+.. code-block:: text
+
+   [CLOSED] --open()--> [STOPPED] --start()--> [RUNNING]
+                            ^                       |
+                            |------stop()-----------|
+   [STOPPED] --close(last fd)--> [CLOSED]
+
+Configuration
+=============
+
+- ``CONFIG_OCU`` - Enable the OCU driver framework.
+
+Lower-Half Interface
+====================
+
+Platform drivers implement ``struct ocu_ops_s`` and register with:
+
+.. code-block:: c
+
+   int ocu_register(FAR const char *devpath,
+                    FAR struct ocu_lowerhalf_s *lower);
+
+Required ops: ``setup``, ``shutdown``, ``start``, ``stop``, ``getstatus``,
+``getcounter``, ``setabsthreshold``, ``setrelthreshold``, ``setcallback``.
+
+Optional ops (NULL if unsupported): ``notification``, ``setadvancethreshold``,
+``setpinstate``, ``setpinaction``, ``ioctl``.
+
+The ``notification`` op enables/disables the hardware compare-match interrupt
+and is invoked by the upper-half from the ``OCUIOC_NOTIFICATION`` ioctl (and
+on ``close()``), paired with ``setcallback``.  If a lower-half leaves it
+``NULL``, ``OCU_NOTIFICATION()`` returns ``-ENOTSUP`` and hardware
+compare-match notification is unavailable.
diff --git a/drivers/timers/CMakeLists.txt b/drivers/timers/CMakeLists.txt
index 18859528be7..6a49e65337d 100644
--- a/drivers/timers/CMakeLists.txt
+++ b/drivers/timers/CMakeLists.txt
@@ -120,6 +120,10 @@ if(CONFIG_CAPTURE)
   endif()
 endif()
 
+if(CONFIG_OCU)
+  list(APPEND SRCS ocu.c)
+endif()
+
 if(CONFIG_GOLDFISH_TIMER)
   list(APPEND SRCS goldfish_timer.c)
 endif()
diff --git a/drivers/timers/Kconfig b/drivers/timers/Kconfig
index 2543218486c..776fa9f9f77 100644
--- a/drivers/timers/Kconfig
+++ b/drivers/timers/Kconfig
@@ -142,6 +142,17 @@ config DSHOT_NCHANNELS
 
 endif # DSHOT
 
+config OCU
+       bool "OCU (Output Compare Unit) Driver Support"
+       default n
+       ---help---
+               This selection enables building of the "upper-half" OCU driver.
+               The OCU driver provides a standard interface for hardware output
+               compare functionality. An OCU channel compares a free-running
+               counter against a programmable threshold and performs 
configurable
+               actions (pin toggle, notification callback) on match.
+               See include/nuttx/timers/ocu.h for further OCU driver 
information.
+
 config TIMER
        bool "Timer Support"
        default n
diff --git a/drivers/timers/ocu.c b/drivers/timers/ocu.c
new file mode 100644
index 00000000000..fbaa88f0178
--- /dev/null
+++ b/drivers/timers/ocu.c
@@ -0,0 +1,526 @@
+/****************************************************************************
+ * drivers/timers/ocu.c
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+
+#include <sys/types.h>
+#include <stdint.h>
+#include <stdbool.h>
+#include <string.h>
+#include <fcntl.h>
+#include <assert.h>
+#include <errno.h>
+#include <debug.h>
+
+#include <nuttx/arch.h>
+#include <nuttx/kmalloc.h>
+#include <nuttx/mutex.h>
+#include <nuttx/fs/fs.h>
+#include <nuttx/signal.h>
+#include <nuttx/timers/ocu.h>
+
+#include <nuttx/irq.h>
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+#ifdef CONFIG_DEBUG_TIMER_INFO
+#  define ocuinfo  _info
+#else
+#  define ocuinfo  _none
+#endif
+
+#ifdef CONFIG_DEBUG_TIMER_ERROR
+#  define ocuerr   _err
+#else
+#  define ocuerr   _none
+#endif
+
+/****************************************************************************
+ * Private Type Definitions
+ ****************************************************************************/
+
+/* This structure describes the state of the upper half driver */
+
+struct ocu_upperhalf_s
+{
+  uint8_t                     crefs;    /* The number of times the device
+                                         * has been opened */
+  volatile bool               started;  /* True: channel is running */
+  mutex_t                     lock;     /* Supports mutual exclusion */
+  FAR struct ocu_lowerhalf_s *lower;    /* lower-half state */
+  struct sigwork_s            work;     /* Signal work for deferred notify */
+  struct ocu_notify_s         notify;   /* Notification configuration */
+};
+
+/****************************************************************************
+ * Private Function Prototypes
+ ****************************************************************************/
+
+static int     ocu_open(FAR struct file *filep);
+static int     ocu_close(FAR struct file *filep);
+static ssize_t ocu_read(FAR struct file *filep, FAR char *buffer,
+                        size_t buflen);
+static ssize_t ocu_write(FAR struct file *filep, FAR const char *buffer,
+                         size_t buflen);
+static int     ocu_ioctl(FAR struct file *filep, int cmd,
+                         unsigned long arg);
+
+/****************************************************************************
+ * Private Data
+ ****************************************************************************/
+
+static const struct file_operations g_ocu_ops =
+{
+  ocu_open,   /* open */
+  ocu_close,  /* close */
+  ocu_read,   /* read */
+  ocu_write,  /* write */
+  NULL,       /* seek */
+  ocu_ioctl,  /* ioctl */
+};
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: ocu_notifier
+ *
+ * Description:
+ *   Internal callback registered with the lower-half driver when user-space
+ *   notification is enabled via OCUIOC_NOTIFICATION.  This function is
+ *   called from ISR context on compare match and sends a signal to the
+ *   registered process.
+ *
+ *   This follows the same pattern as timer_notifier() in timer.c:
+ *   the upper-half registers this as the lower-half callback and translates
+ *   the event into a user-space signal notification.
+ *
+ *   Kernel-internal drivers that need a direct callback should use the
+ *   OCU_SETCALLBACK() macro to register directly with the lower-half,
+ *   bypassing this upper-half entirely (same as TIMER_SETCALLBACK).
+ *
+ ****************************************************************************/
+
+static bool ocu_notifier(FAR uint32_t *next_threshold, FAR void *arg)
+{
+  FAR struct ocu_upperhalf_s *upper = (FAR struct ocu_upperhalf_s *)arg;
+
+  DEBUGASSERT(upper != NULL);
+
+  /* Signal the waiter */
+
+  nxsig_notification(upper->notify.pid, &upper->notify.event,
+                     SI_QUEUE, &upper->work);
+
+  /* Do not re-arm threshold from upper-half.  User-space must explicitly
+   * set the next threshold via ioctl after receiving the signal.
+   */
+
+  return false;
+}
+
+/****************************************************************************
+ * Name: ocu_open
+ ****************************************************************************/
+
+static int ocu_open(FAR struct file *filep)
+{
+  FAR struct inode           *inode = filep->f_inode;
+  FAR struct ocu_upperhalf_s *upper = inode->i_private;
+  int                         ret   = OK;
+  FAR struct ocu_lowerhalf_s *lower;
+  uint8_t                     tmp;
+
+  ocuinfo("crefs: %d\n", upper->crefs);
+
+  nxmutex_lock(&upper->lock);
+
+  tmp = upper->crefs + 1;
+  if (tmp == 0)
+    {
+      ret = -EMFILE;
+      goto errout_with_lock;
+    }
+
+  /* If this is the first open, call setup */
+
+  if (upper->crefs == 0)
+    {
+      lower = upper->lower;
+
+      if (lower->ops->setup != NULL)
+        {
+          ret = lower->ops->setup(lower);
+          if (ret < 0)
+            {
+              goto errout_with_lock;
+            }
+        }
+    }
+
+  upper->crefs = tmp;
+
+errout_with_lock:
+  nxmutex_unlock(&upper->lock);
+  return ret;
+}
+
+/****************************************************************************
+ * Name: ocu_close
+ ****************************************************************************/
+
+static int ocu_close(FAR struct file *filep)
+{
+  FAR struct inode           *inode = filep->f_inode;
+  FAR struct ocu_upperhalf_s *upper = inode->i_private;
+
+  ocuinfo("crefs: %d\n", upper->crefs);
+
+  nxmutex_lock(&upper->lock);
+
+  if (upper->crefs > 1)
+    {
+      upper->crefs--;
+    }
+  else
+    {
+      FAR struct ocu_lowerhalf_s *lower = upper->lower;
+
+      upper->crefs = 0;
+
+      /* Stop the channel if still running */
+
+      if (upper->started)
+        {
+          OCU_STOP(lower);
+          upper->started = false;
+        }
+
+      /* Disable hardware notification, unregister callback and shutdown */
+
+      OCU_NOTIFICATION(lower, false);
+      OCU_SETCALLBACK(lower, NULL, NULL);
+
+      if (lower->ops->shutdown != NULL)
+        {
+          lower->ops->shutdown(lower);
+        }
+    }
+
+  nxmutex_unlock(&upper->lock);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: ocu_read
+ ****************************************************************************/
+
+static ssize_t ocu_read(FAR struct file *filep, FAR char *buffer,
+                        size_t buflen)
+{
+  return 0;
+}
+
+/****************************************************************************
+ * Name: ocu_write
+ ****************************************************************************/
+
+static ssize_t ocu_write(FAR struct file *filep, FAR const char *buffer,
+                         size_t buflen)
+{
+  return 0;
+}
+
+/****************************************************************************
+ * Name: ocu_ioctl
+ ****************************************************************************/
+
+static int ocu_ioctl(FAR struct file *filep, int cmd, unsigned long arg)
+{
+  FAR struct inode           *inode = filep->f_inode;
+  FAR struct ocu_upperhalf_s *upper;
+  FAR struct ocu_lowerhalf_s *lower;
+  int                         ret;
+
+  ocuinfo("cmd: %d arg: %ld\n", cmd, arg);
+  upper = inode->i_private;
+  DEBUGASSERT(upper != NULL);
+  lower = upper->lower;
+  DEBUGASSERT(lower != NULL);
+
+  nxmutex_lock(&upper->lock);
+
+  switch (cmd)
+    {
+      /* OCUIOC_START - Start the OCU channel */
+
+      case OCUIOC_START:
+        {
+          ocuinfo("OCUIOC_START: started=%d\n", upper->started);
+
+          if (upper->started)
+            {
+              ret = -EBUSY;
+            }
+          else
+            {
+              ret = OCU_START(lower);
+              if (ret == OK)
+                {
+                  upper->started = true;
+                }
+            }
+        }
+        break;
+
+      /* OCUIOC_STOP - Stop the OCU channel */
+
+      case OCUIOC_STOP:
+        {
+          ocuinfo("OCUIOC_STOP: started=%d\n", upper->started);
+
+          if (upper->started)
+            {
+              ret = OCU_STOP(lower);
+              upper->started = false;
+            }
+          else
+            {
+              ret = OK;  /* Already stopped, not an error */
+            }
+        }
+        break;
+
+      /* OCUIOC_GETSTATUS - Get the current OCU channel status */
+
+      case OCUIOC_GETSTATUS:
+        {
+          FAR struct ocu_status_s *status =
+            (FAR struct ocu_status_s *)((uintptr_t)arg);
+          DEBUGASSERT(status != NULL);
+
+          /* Let the lower-half fill in the hardware/config-specific fields
+           * (counter, threshold, maxcounter and the PIN_AVAIL flag).  It
+           * zeroes status->flags, so the upper-half must OR in its own
+           * flags afterwards.
+           */
+
+          ret = OCU_GETSTATUS(lower, status);
+          if (ret == OK)
+            {
+              /* The running and notification states are tracked by the
+               * upper-half, so it fills those flags here instead of the
+               * lower-half duplicating them.
+               */
+
+              if (upper->started)
+                {
+                  status->flags |= OCUFLAGS_ACTIVE;
+                }
+
+              if (upper->notify.enable)
+                {
+                  status->flags |= OCUFLAGS_NOTIF_EN;
+                }
+            }
+        }
+        break;
+
+      /* OCUIOC_GETCOUNTER - Read the current counter value */
+
+      case OCUIOC_GETCOUNTER:
+        {
+          FAR uint32_t *counter = (FAR uint32_t *)((uintptr_t)arg);
+          DEBUGASSERT(counter != NULL);
+          ret = OCU_GETCOUNTER(lower, counter);
+        }
+        break;
+
+      /* OCUIOC_SETABSTHRESHOLD - Set absolute compare threshold */
+
+      case OCUIOC_SETABSTHRESHOLD:
+        {
+          FAR struct ocu_abs_threshold_s *threshold =
+            (FAR struct ocu_abs_threshold_s *)((uintptr_t)arg);
+          DEBUGASSERT(threshold != NULL);
+          ret = OCU_SETABSTHRESHOLD(lower, threshold);
+        }
+        break;
+
+      /* OCUIOC_SETRELTHRESHOLD - Set relative compare threshold */
+
+      case OCUIOC_SETRELTHRESHOLD:
+        {
+          FAR struct ocu_rel_threshold_s *threshold =
+            (FAR struct ocu_rel_threshold_s *)((uintptr_t)arg);
+          DEBUGASSERT(threshold != NULL);
+          ret = OCU_SETRELTHRESHOLD(lower, threshold);
+        }
+        break;
+
+      /* OCUIOC_SETPINSTATE - Set the output pin level */
+
+      case OCUIOC_SETPINSTATE:
+        {
+          enum ocu_pinstate_e state = (enum ocu_pinstate_e)arg;
+
+          if (upper->started)
+            {
+              ret = -EBUSY;  /* Cannot set pin state while running */
+            }
+          else
+            {
+              ret = OCU_SETPINSTATE(lower, state);
+            }
+        }
+        break;
+
+      /* OCUIOC_SETPINACTION - Set the automatic pin action */
+
+      case OCUIOC_SETPINACTION:
+        {
+          enum ocu_pinaction_e action = (enum ocu_pinaction_e)arg;
+          ret = OCU_SETPINACTION(lower, action);
+        }
+        break;
+
+      /* OCUIOC_SETADVANCETHRESHOLD - Advance threshold by step */
+
+      case OCUIOC_SETADVANCETHRESHOLD:
+        {
+          FAR struct ocu_advance_threshold_s *threshold =
+            (FAR struct ocu_advance_threshold_s *)((uintptr_t)arg);
+          DEBUGASSERT(threshold != NULL);
+          ret = OCU_SETADVANCETHRESHOLD(lower, threshold);
+        }
+        break;
+
+      /* OCUIOC_NOTIFICATION - Enable/disable signal notification.
+       *
+       * When enabled, the upper-half registers ocu_notifier() as the
+       * lower-half callback.  On compare match, the lower-half calls
+       * ocu_notifier() from ISR context, which sends a signal to the
+       * registered process.
+       *
+       * Kernel-internal callers that need a direct ISR callback should
+       * use the OCU_SETCALLBACK() macro instead of this ioctl.
+       */
+
+      case OCUIOC_NOTIFICATION:
+        {
+          FAR struct ocu_notify_s *notify =
+            (FAR struct ocu_notify_s *)((uintptr_t)arg);
+          DEBUGASSERT(notify != NULL);
+
+          if (notify->enable)
+            {
+              memcpy(&upper->notify, notify, sizeof(*notify));
+
+              /* Register the notifier callback, then enable the hardware
+               * compare-match notification.
+               */
+
+              OCU_SETCALLBACK(lower, ocu_notifier, upper);
+              ret = OCU_NOTIFICATION(lower, true);
+              if (ret < 0)
+                {
+                  /* Roll back the callback registration on failure */
+
+                  OCU_SETCALLBACK(lower, NULL, NULL);
+                  memset(&upper->notify, 0, sizeof(upper->notify));
+                }
+            }
+          else
+            {
+              /* Disable the hardware notification, then unregister the
+               * callback.
+               */
+
+              ret = OCU_NOTIFICATION(lower, false);
+              OCU_SETCALLBACK(lower, NULL, NULL);
+              memset(&upper->notify, 0, sizeof(upper->notify));
+            }
+        }
+        break;
+
+      /* Any unrecognized IOCTL commands are forwarded to the lower half */
+
+      default:
+        {
+          ocuinfo("Forwarding unrecognized cmd: %d arg: %ld\n", cmd, arg);
+          if (lower->ops->ioctl != NULL)
+            {
+              ret = lower->ops->ioctl(lower, cmd, arg);
+            }
+          else
+            {
+              ret = -ENOTTY;
+            }
+        }
+        break;
+    }
+
+  nxmutex_unlock(&upper->lock);
+  return ret;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: ocu_register
+ ****************************************************************************/
+
+int ocu_register(FAR const char *devpath,
+                 FAR struct ocu_lowerhalf_s *lower)
+{
+  FAR struct ocu_upperhalf_s *upper;
+
+  DEBUGASSERT(devpath != NULL && lower != NULL && lower->ops != NULL);
+
+  /* Allocate the upper-half data structure */
+
+  upper = kmm_zalloc(sizeof(struct ocu_upperhalf_s));
+  if (upper == NULL)
+    {
+      ocuerr("Allocation failed\n");
+      return -ENOMEM;
+    }
+
+  /* Initialize the OCU device structure */
+
+  nxmutex_init(&upper->lock);
+  upper->lower = lower;
+
+  /* Register the OCU device */
+
+  ocuinfo("Registering %s\n", devpath);
+  return register_driver(devpath, &g_ocu_ops, 0600, upper);
+}
diff --git a/include/nuttx/fs/ioctl.h b/include/nuttx/fs/ioctl.h
index 45159734701..9be52345a39 100644
--- a/include/nuttx/fs/ioctl.h
+++ b/include/nuttx/fs/ioctl.h
@@ -116,6 +116,7 @@
 #define _DSHOTIOCBASE   (0x4800) /* Dshot device ioctl commands */
 #define _PULSECOUNTBASE (0x4900) /* Pulse count driver ioctl commands */
 #define _NPZEROIOCBASE  (0x4a00) /* nPZero power-saving IC ioctl commands */
+#define _OCUIOCBASE     (0x4b00) /* OCU (Output Compare Unit) ioctl commands */
 #define _RPTUNBASE      (0x5000) /* Remote processor tunneling ioctl commands 
*/
 #define _VIRTIOBASE     (0x5100) /* VirtIO ioctl commands */
 #define _WLIOCBASE      (0x8b00) /* Wireless modules ioctl network commands */
@@ -869,6 +870,13 @@
 #define _NPZEROIOCVALID(c)     (_IOC_TYPE(c)==_NPZEROIOCBASE)
 #define _NPZEROIOC(nr)         _IOC(_NPZEROIOCBASE,nr)
 
+/* OCU (Output Compare Unit) ioctl definitions ******************************/
+
+/* see nuttx/include/nuttx/timers/ocu.h */
+
+#define _OCUIOCVALID(c)       (_IOC_TYPE(c)==_OCUIOCBASE)
+#define _OCUIOC(nr)           _IOC(_OCUIOCBASE,nr)
+
 /* Rptun drivers ************************************************************/
 
 #define _RPTUNIOCVALID(c)     (_IOC_TYPE(c)==_RPTUNBASE)
diff --git a/include/nuttx/timers/ocu.h b/include/nuttx/timers/ocu.h
new file mode 100644
index 00000000000..04f99ee7abf
--- /dev/null
+++ b/include/nuttx/timers/ocu.h
@@ -0,0 +1,394 @@
+/****************************************************************************
+ * include/nuttx/timers/ocu.h
+ *
+ * SPDX-License-Identifier: Apache-2.0
+ *
+ * Licensed to the Apache Software Foundation (ASF) under one or more
+ * contributor license agreements.  See the NOTICE file distributed with
+ * this work for additional information regarding copyright ownership.  The
+ * ASF licenses this file to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance with the
+ * License.  You may obtain a copy of the License at
+ *
+ *   http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
+ * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.  See the
+ * License for the specific language governing permissions and limitations
+ * under the License.
+ *
+ ****************************************************************************/
+
+/* The OCU (Output Compare Unit) driver provides a standard interface for
+ * hardware output compare functionality. An OCU channel compares a
+ * free-running counter against a programmable threshold and performs
+ * configurable actions (pin toggle, notification callback) on match.
+ *
+ * The driver is split into two parts:
+ *
+ * 1) An "upper half", generic driver that provides the common OCU interface
+ *    to application level code, and
+ * 2) A "lower half", platform-specific driver that implements the low-level
+ *    timer/compare controls to implement the OCU functionality.
+ */
+
+#ifndef __INCLUDE_NUTTX_TIMERS_OCU_H
+#define __INCLUDE_NUTTX_TIMERS_OCU_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+#include <nuttx/compiler.h>
+#include <nuttx/fs/ioctl.h>
+#include <nuttx/signal.h>
+
+#include <stdbool.h>
+#include <stdint.h>
+
+#ifdef CONFIG_OCU
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* IOCTL Commands ***********************************************************/
+
+/* The OCU module uses a standard character driver framework. The majority
+ * of the functionality is implemented in driver ioctl calls.
+ *
+ * OCUIOC_START              - Start the OCU channel, enabling compare match
+ *                             actions.
+ *                             Argument: Ignored
+ * OCUIOC_STOP               - Stop the OCU channel, halting compare match
+ *                             actions. The free-running counter is NOT
+ *                             stopped.
+ *                             Argument: Ignored
+ * OCUIOC_GETSTATUS          - Get the current status of the OCU channel.
+ *                             Argument: A writeable pointer to struct
+ *                             ocu_status_s.
+ * OCUIOC_GETCOUNTER         - Read the current counter value in ticks.
+ *                             Argument: A writeable pointer to uint32_t.
+ * OCUIOC_SETABSTHRESHOLD    - Set the compare threshold to an absolute
+ *                             value.
+ *                             Argument: A read-only pointer to struct
+ *                             ocu_abs_threshold_s.
+ * OCUIOC_SETRELTHRESHOLD    - Set the compare threshold relative to the
+ *                             current counter value.
+ *                             Argument: A read-only pointer to struct
+ *                             ocu_rel_threshold_s.
+ * OCUIOC_SETPINSTATE        - Set the output pin level immediately (only
+ *                             when channel is STOPPED).
+ *                             Argument: enum ocu_pinstate_e value.
+ * OCUIOC_SETPINACTION       - Set the automatic pin action on compare
+ *                             match.
+ *                             Argument: enum ocu_pinaction_e value.
+ * OCUIOC_SETADVANCETHRESHOLD- Set the compare threshold relative to the
+ *                             current threshold value (advance by step).
+ *                             new_threshold = current_threshold + step.
+ *                             Argument: A read-only pointer to struct
+ *                             ocu_advance_threshold_s.
+ * OCUIOC_NOTIFICATION       - Enable or disable compare match signal
+ *                             notification to user space.  When enabled,
+ *                             the upper-half automatically registers an
+ *                             internal notifier callback with the
+ *                             lower-half; on compare match, a signal is
+ *                             sent to the specified process.
+ *                             Argument: A read-only pointer to struct
+ *                             ocu_notify_s.
+ *
+ * NOTE: There is no OCUIOC_SETCALLBACK ioctl.  Kernel-internal drivers
+ * that need a direct ISR callback must use the OCU_SETCALLBACK() macro
+ * to register directly with the lower-half, bypassing the upper-half
+ * (same pattern as TIMER_SETCALLBACK in timer.h).
+ */
+
+#define OCUIOC_START               _OCUIOC(0x0001)
+#define OCUIOC_STOP                _OCUIOC(0x0002)
+#define OCUIOC_GETSTATUS           _OCUIOC(0x0003)
+#define OCUIOC_GETCOUNTER          _OCUIOC(0x0004)
+#define OCUIOC_SETABSTHRESHOLD     _OCUIOC(0x0005)
+#define OCUIOC_SETRELTHRESHOLD     _OCUIOC(0x0006)
+#define OCUIOC_SETADVANCETHRESHOLD _OCUIOC(0x0007)
+#define OCUIOC_SETPINSTATE         _OCUIOC(0x0008)
+#define OCUIOC_SETPINACTION        _OCUIOC(0x0009)
+#define OCUIOC_NOTIFICATION        _OCUIOC(0x000a)
+
+/* Bit Settings *************************************************************/
+
+/* Bit settings for the struct ocu_status_s flags field */
+
+#define OCUFLAGS_ACTIVE            (1 << 0) /* 1=The channel is running */
+#define OCUFLAGS_NOTIF_EN          (1 << 1) /* 1=Notification is enabled */
+#define OCUFLAGS_PIN_AVAIL         (1 << 2) /* 1=Output pin is available */
+
+/* Method access helper macros **********************************************/
+
+#define OCU_START(l)               ((l)->ops->start ? \
+                                    (l)->ops->start(l) : -ENOTSUP)
+#define OCU_STOP(l)                ((l)->ops->stop ? \
+                                    (l)->ops->stop(l) : -ENOTSUP)
+#define OCU_GETSTATUS(l,s)         ((l)->ops->getstatus ? \
+                                    (l)->ops->getstatus(l,s) : -ENOTSUP)
+#define OCU_GETCOUNTER(l,v)        ((l)->ops->getcounter ? \
+                                    (l)->ops->getcounter(l,v) : -ENOTSUP)
+#define OCU_SETABSTHRESHOLD(l,t)   ((l)->ops->setabsthreshold ? \
+                                    (l)->ops->setabsthreshold(l,t) : -ENOTSUP)
+#define OCU_SETRELTHRESHOLD(l,t)   ((l)->ops->setrelthreshold ? \
+                                    (l)->ops->setrelthreshold(l,t) : -ENOTSUP)
+#define OCU_SETPINSTATE(l,s)       ((l)->ops->setpinstate ? \
+                                    (l)->ops->setpinstate(l,s) : -ENOTSUP)
+#define OCU_SETPINACTION(l,a)      ((l)->ops->setpinaction ? \
+                                    (l)->ops->setpinaction(l,a) : -ENOTSUP)
+#define OCU_SETCALLBACK(l,c,a)     do \
+                                     { \
+                                       if ((l)->ops->setcallback) \
+                                         { \
+                                           (l)->ops->setcallback(l,c,a); \
+                                         } \
+                                     } \
+                                   while (0)
+#define OCU_NOTIFICATION(l,en)     ((l)->ops->notification ? \
+                                    (l)->ops->notification(l,en) : -ENOTSUP)
+#define OCU_SETADVANCETHRESHOLD(l,t) \
+                                   ((l)->ops->setadvancethreshold ? \
+                                    (l)->ops->setadvancethreshold(l,t) : \
+                                    -ENOTSUP)
+
+/****************************************************************************
+ * Public Types
+ ****************************************************************************/
+
+/* Output pin state */
+
+enum ocu_pinstate_e
+{
+  OCU_PINSTATE_LOW  = 0,  /* Output pin is LOW */
+  OCU_PINSTATE_HIGH = 1,  /* Output pin is HIGH */
+};
+
+/* Automatic pin action on compare match */
+
+enum ocu_pinaction_e
+{
+  OCU_PINACTION_DISABLE  = 0,  /* No pin action on compare match */
+  OCU_PINACTION_SET_LOW  = 1,  /* Set pin LOW on compare match */
+  OCU_PINACTION_SET_HIGH = 2,  /* Set pin HIGH on compare match */
+  OCU_PINACTION_TOGGLE   = 3,  /* Toggle pin on compare match */
+};
+
+/* Return type for threshold setting APIs */
+
+enum ocu_threshold_ret_e
+{
+  OCU_THRESHOLD_IN_REF_INTERVAL  = 0,  /* Compare match will occur in the
+                                        * current reference interval */
+  OCU_THRESHOLD_OUT_REF_INTERVAL = 1,  /* Compare match will NOT occur in the
+                                        * current reference interval */
+};
+
+/* OCU channel status */
+
+struct ocu_status_s
+{
+  uint32_t flags;           /* See OCUFLAGS_* definitions above */
+  uint32_t counter;         /* Current counter value in ticks */
+  uint32_t threshold;       /* Current threshold value in ticks */
+  uint32_t maxcounter;      /* Maximum counter value */
+};
+
+/* Absolute threshold setting */
+
+struct ocu_abs_threshold_s
+{
+  uint32_t reference;                   /* Reference value */
+  uint32_t absolute;                    /* Absolute threshold in ticks */
+  enum ocu_threshold_ret_e result;      /* [out] Match in ref interval? */
+};
+
+/* Relative threshold setting (relative to current counter) */
+
+struct ocu_rel_threshold_s
+{
+  uint32_t relative;                    /* Relative offset from counter */
+  enum ocu_threshold_ret_e result;      /* [out] Match in ref interval? */
+};
+
+/* Advance threshold setting (relative to current threshold) */
+
+struct ocu_advance_threshold_s
+{
+  uint32_t step;                        /* Step from current threshold */
+  enum ocu_threshold_ret_e result;      /* [out] Match in ref interval? */
+};
+
+/* Notification configuration */
+
+struct ocu_notify_s
+{
+  bool     enable;          /* true=enable, false=disable notification */
+  pid_t    pid;             /* PID of the task to notify */
+  struct sigevent event;    /* Signal event for notification */
+};
+
+/* Compare match callback type.
+ * Called from interrupt context when a compare match occurs.
+ * Returns true to automatically re-arm with the same threshold.
+ */
+
+typedef CODE bool (*ocu_callback_t)(FAR uint32_t *next_threshold,
+                                    FAR void *arg);
+
+/* This structure provides the "lower-half" driver operations available to
+ * the "upper-half" driver.
+ */
+
+struct ocu_lowerhalf_s;
+struct ocu_ops_s
+{
+  /* This method is called when the driver is first opened. The lower half
+   * driver should configure and initialize the hardware.
+   */
+
+  CODE int (*setup)(FAR struct ocu_lowerhalf_s *lower);
+
+  /* This method is called when the last file descriptor is closed. The
+   * lower half driver should stop output, free resources, and disable
+   * the timer hardware.
+   */
+
+  CODE int (*shutdown)(FAR struct ocu_lowerhalf_s *lower);
+
+  /* Start the OCU channel, enabling compare match actions. */
+
+  CODE int (*start)(FAR struct ocu_lowerhalf_s *lower);
+
+  /* Stop the OCU channel. The free-running counter is NOT stopped. */
+
+  CODE int (*stop)(FAR struct ocu_lowerhalf_s *lower);
+
+  /* Get the current status of the OCU channel. */
+
+  CODE int (*getstatus)(FAR struct ocu_lowerhalf_s *lower,
+                        FAR struct ocu_status_s *status);
+
+  /* Read the current counter value. */
+
+  CODE int (*getcounter)(FAR struct ocu_lowerhalf_s *lower,
+                         FAR uint32_t *counter);
+
+  /* Set the compare threshold to an absolute value. */
+
+  CODE int (*setabsthreshold)(FAR struct ocu_lowerhalf_s *lower,
+                              FAR struct ocu_abs_threshold_s *threshold);
+
+  /* Set the compare threshold relative to the current counter value. */
+
+  CODE int (*setrelthreshold)(FAR struct ocu_lowerhalf_s *lower,
+                              FAR struct ocu_rel_threshold_s *threshold);
+
+  /* Set the compare threshold relative to the current threshold value
+   * (advance by step).  new_threshold = current_threshold + step.
+   */
+
+  CODE int (*setadvancethreshold)(FAR struct ocu_lowerhalf_s *lower,
+                                  FAR struct ocu_advance_threshold_s *t);
+
+  /* Set the compare match callback (timer-style setcallback pattern).
+   * NOTE: Providing callback==NULL disables the callback.
+   * The lower-half driver holds the callback pointer and calls it directly
+   * from the compare match ISR.
+   */
+
+  CODE void (*setcallback)(FAR struct ocu_lowerhalf_s *lower,
+                           CODE ocu_callback_t callback, FAR void *arg);
+
+  /* Set the output pin level immediately (only when channel is STOPPED) */
+
+  CODE int (*setpinstate)(FAR struct ocu_lowerhalf_s *lower,
+                          enum ocu_pinstate_e state);
+
+  /* Set the automatic pin action on compare match */
+
+  CODE int (*setpinaction)(FAR struct ocu_lowerhalf_s *lower,
+                           enum ocu_pinaction_e action);
+
+  /* Enable or disable the hardware compare-match notification (interrupt).
+   * This is independent of setcallback(): the upper-half registers the
+   * notifier callback via setcallback() and then enables/disables the
+   * hardware notification via this method (both driven from the
+   * OCUIOC_NOTIFICATION ioctl).
+   */
+
+  CODE int (*notification)(FAR struct ocu_lowerhalf_s *lower, bool enable);
+
+  /* Any ioctl commands that are not recognized by the "upper-half" driver
+   * are forwarded to the lower half driver through this method.
+   */
+
+  CODE int (*ioctl)(FAR struct ocu_lowerhalf_s *lower, int cmd,
+                    unsigned long arg);
+};
+
+/* This structure provides the publicly visible representation of the
+ * "lower-half" driver state structure. "lower half" drivers will have an
+ * internal structure definition that will be cast-compatible with this
+ * structure definitions.
+ */
+
+struct ocu_lowerhalf_s
+{
+  /* Publicly visible portion of the "lower-half" driver state structure. */
+
+  FAR const struct ocu_ops_s *ops;  /* Lower half operations */
+};
+
+/****************************************************************************
+ * Public Data
+ ****************************************************************************/
+
+#ifdef __cplusplus
+#define EXTERN extern "C"
+extern "C"
+{
+#else
+#define EXTERN extern
+#endif
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: ocu_register
+ *
+ * Description:
+ *   This function binds an instance of a "lower half" OCU driver with the
+ *   "upper half" OCU device and registers that device so that it can be
+ *   used by application code.
+ *
+ * Input Parameters:
+ *   devpath - The full path to the driver to be registered in the NuttX
+ *     pseudo-filesystem. The recommended convention is to name all OCU
+ *     drivers as "/dev/ocu0", "/dev/ocu1", etc.
+ *   lower - A pointer to an instance of lower half OCU driver. This
+ *     instance is bound to the OCU driver and must persist as long as the
+ *     driver persists.
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int ocu_register(FAR const char *devpath,
+                 FAR struct ocu_lowerhalf_s *lower);
+
+#undef EXTERN
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* CONFIG_OCU */
+#endif /* __INCLUDE_NUTTX_TIMERS_OCU_H */

Reply via email to