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

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

commit ca1cc6bf7621a8f97a8e4ea95be3578aa806c4e1
Author: yangsong8 <[email protected]>
AuthorDate: Fri Sep 4 16:48:09 2026 +0800

    drivers/timers: add i.MX GPT OCU lower-half driver
    
    Add the i.MX GPT shared core and Output Compare Unit lower-half
    driver. The shared core maps the MMIO block, starts the free-running
    counter and owns the single interrupt that dispatches compare-match
    events; the OCU lower-half registers each channel as /dev/ocuN and
    plugs into the generic ocu upper-half. The channel count is
    configurable via TIMER_IMX_GPT_NUM_OCU (range 1-3, default 1).
    
    Assisted-by: Kiro:claude-opus-5-5
    Signed-off-by: yangsong8 <[email protected]>
---
 drivers/timers/CMakeLists.txt  |   7 +
 drivers/timers/Kconfig         |  32 +++
 drivers/timers/Make.defs       |   9 +
 drivers/timers/imx_gpt.c       | 212 ++++++++++++++++++
 drivers/timers/ocu_imx_gpt.c   | 492 +++++++++++++++++++++++++++++++++++++++++
 include/nuttx/timers/imx_gpt.h | 243 ++++++++++++++++++++
 6 files changed, 995 insertions(+)

diff --git a/drivers/timers/CMakeLists.txt b/drivers/timers/CMakeLists.txt
index 96a66cd6563..ad4284aeb64 100644
--- a/drivers/timers/CMakeLists.txt
+++ b/drivers/timers/CMakeLists.txt
@@ -128,6 +128,13 @@ if(CONFIG_OCU)
   list(APPEND SRCS ocu.c)
 endif()
 
+if(CONFIG_TIMER_IMX_GPT)
+  list(APPEND SRCS imx_gpt.c)
+  if(CONFIG_TIMER_IMX_GPT_OCU)
+    list(APPEND SRCS ocu_imx_gpt.c)
+  endif()
+endif()
+
 if(CONFIG_GOLDFISH_TIMER)
   list(APPEND SRCS goldfish_timer.c)
 endif()
diff --git a/drivers/timers/Kconfig b/drivers/timers/Kconfig
index b547b192c9c..5526054ee41 100644
--- a/drivers/timers/Kconfig
+++ b/drivers/timers/Kconfig
@@ -164,6 +164,38 @@ config OCU
                actions (pin toggle, notification callback) on match.
                See include/nuttx/timers/ocu.h for further OCU driver 
information.
 
+config TIMER_IMX_GPT
+       bool "i.MX GPT Driver"
+       default n
+       ---help---
+               Enable the i.MX GPT (General Purpose Timer) lower-half driver
+               core: one free-running counter and one shared interrupt.  A 
single
+               GPT block can expose an Output Compare Unit (/dev/ocuN) and/or 
an
+               Input Capture Unit (/dev/capN); enable either or both below.
+               Instances are created from the device tree ("fsl,imx-gpt") by 
the
+               board bring-up code via imx_gpt_initialize().
+
+if TIMER_IMX_GPT
+
+config TIMER_IMX_GPT_OCU
+       bool "Output Compare Unit (OCU) support"
+       default y
+       select OCU
+       ---help---
+               Register the GPT output-compare channels as /dev/ocuN and plug
+               them into the generic ocu upper-half driver.
+
+config TIMER_IMX_GPT_NUM_OCU
+       int "Number of OCU (output compare) channels"
+       depends on TIMER_IMX_GPT_OCU
+       default 1
+       range 1 3
+       ---help---
+               Number of Output Compare Unit channels to register as /dev/ocuN.
+               The i.MX GPT hardware provides up to 3 output compare channels.
+
+endif # TIMER_IMX_GPT
+
 config TIMER
        bool "Timer Support"
        default n
diff --git a/drivers/timers/Make.defs b/drivers/timers/Make.defs
index c787b08d53e..e4734a5e55c 100644
--- a/drivers/timers/Make.defs
+++ b/drivers/timers/Make.defs
@@ -177,6 +177,15 @@ ifeq ($(CONFIG_CAPTURE),y)
   TMRVPATH = :timers
 endif
 
+ifeq ($(CONFIG_TIMER_IMX_GPT),y)
+  CSRCS += imx_gpt.c
+ifeq ($(CONFIG_TIMER_IMX_GPT_OCU),y)
+  CSRCS += ocu_imx_gpt.c
+endif
+  TMRDEPPATH = --dep-path timers
+  TMRVPATH = :timers
+endif
+
 ifeq ($(CONFIG_GOLDFISH_TIMER),y)
   CSRCS += goldfish_timer.c
   TMRDEPPATH = --dep-path timers
diff --git a/drivers/timers/imx_gpt.c b/drivers/timers/imx_gpt.c
new file mode 100644
index 00000000000..ad2de9a2105
--- /dev/null
+++ b/drivers/timers/imx_gpt.c
@@ -0,0 +1,212 @@
+/****************************************************************************
+ * drivers/timers/imx_gpt.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 <assert.h>
+#include <debug.h>
+#include <errno.h>
+#include <stdio.h>
+
+#include <nuttx/arch.h>
+#include <nuttx/irq.h>
+#include <nuttx/kmalloc.h>
+#include <nuttx/spinlock.h>
+#include <nuttx/timers/imx_gpt.h>
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: imx_gpt_interrupt
+ *
+ * Description:
+ *   The single interrupt service routine shared by all channels.  Reads the
+ *   status register, dispatches to the per-channel handlers, then clears
+ *   (write-1-to-clear) exactly the bits it serviced.
+ *
+ ****************************************************************************/
+
+static int imx_gpt_interrupt(int irq, FAR void *context, FAR void *arg)
+{
+  FAR struct imx_gpt_dev_s *dev = (FAR struct imx_gpt_dev_s *)arg;
+  irqstate_t flags;
+  uint32_t status;
+  uint32_t handled = 0;
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+  int ch;
+#endif
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  /* Only act on sources that are both pending and enabled. */
+
+  status = imx_gpt_getreg(dev, IMX_GPT_SR) & imx_gpt_getreg(dev, IMX_GPT_IR);
+
+  /* OCU compare-match channels. */
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+  for (ch = 0; ch < IMX_GPT_NUM_OCU; ch++)
+    {
+      if ((status & GPT_SR_OF(ch)) != 0)
+        {
+          handled |= GPT_SR_OF(ch);
+          if (dev->ocu[ch] != NULL)
+            {
+              imx_gpt_ocu_on_match(dev->ocu[ch]);
+            }
+        }
+    }
+#endif
+
+  /* Counter roll-over accounting. */
+
+  if ((status & GPT_SR_ROV) != 0)
+    {
+      handled |= GPT_SR_ROV;
+      dev->rollover++;
+    }
+
+  /* Write-1-to-clear the serviced status bits. */
+
+  if (handled != 0)
+    {
+      imx_gpt_putreg(dev, IMX_GPT_SR, handled);
+    }
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: imx_gpt_hw_init
+ *
+ * Description:
+ *   Software-reset the block and start the shared free-running counter:
+ *   no prescaler divide, any non-zero CLKSRC (the QEMU virt model uses the
+ *   qdev clock-in), free-run mode, ENMOD so the counter restarts from 0,
+ *   and finally EN.  All per-channel OM bits stay disabled and IR is
+ *   cleared; channels enable their own bits on start.
+ *
+ ****************************************************************************/
+
+static void imx_gpt_hw_init(FAR struct imx_gpt_dev_s *dev)
+{
+  /* Software reset (self-clearing) and wait for it to complete. */
+
+  imx_gpt_putreg(dev, IMX_GPT_CR, GPT_CR_SWR);
+  while ((imx_gpt_getreg(dev, IMX_GPT_CR) & GPT_CR_SWR) != 0)
+    {
+    }
+
+  /* Mask and clear all interrupt sources. */
+
+  imx_gpt_putreg(dev, IMX_GPT_IR, 0);
+  imx_gpt_putreg(dev, IMX_GPT_SR, 0x3f);
+
+  /* No prescaler division (tick freq == input clock). */
+
+  imx_gpt_putreg(dev, IMX_GPT_PR, 0);
+
+  /* CLKSRC = 1 (peripheral clock), free-run, restart-from-zero, enable. */
+
+  imx_gpt_putreg(dev, IMX_GPT_CR,
+                 (1 << GPT_CR_CLKSRC_SHIFT) | GPT_CR_FRR |
+                 GPT_CR_ENMOD | GPT_CR_EN);
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: imx_gpt_initialize
+ ****************************************************************************/
+
+int imx_gpt_initialize(uintptr_t base, int irq, uint32_t freq,
+                       int ocu_bus, int cap_bus)
+{
+  FAR struct imx_gpt_dev_s *dev;
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+  char devpath[20];
+  int ch;
+#endif
+  int ret;
+
+  DEBUGASSERT(base != 0);
+  UNUSED(cap_bus);
+#ifndef CONFIG_TIMER_IMX_GPT_OCU
+  UNUSED(ocu_bus);
+#endif
+
+  dev = kmm_zalloc(sizeof(*dev));
+  if (dev == NULL)
+    {
+      return -ENOMEM;
+    }
+
+  dev->base = base;
+  dev->irq  = irq;
+  dev->freq = freq;
+  spin_lock_init(&dev->lock);
+
+  /* Bring up the shared counter before touching any channel. */
+
+  imx_gpt_hw_init(dev);
+
+  /* Register the OCU channels as /dev/ocu<ocu_bus + ch>. */
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+  for (ch = 0; ch < IMX_GPT_NUM_OCU; ch++)
+    {
+      snprintf(devpath, sizeof(devpath), "/dev/ocu%d", ocu_bus + ch);
+      dev->ocu[ch] = imx_gpt_ocu_register(dev, ch, devpath);
+      if (dev->ocu[ch] == NULL)
+        {
+          tmrerr("ERROR: failed to register %s\n", devpath);
+          ret = -ENODEV;
+          goto err;
+        }
+    }
+#endif
+
+  /* Attach and enable the shared interrupt now that all channels exist. */
+
+  ret = irq_attach(irq, imx_gpt_interrupt, dev);
+  if (ret < 0)
+    {
+      tmrerr("ERROR: irq_attach failed: %d\n", ret);
+      goto err;
+    }
+
+  up_enable_irq(irq);
+  return OK;
+
+err:
+  kmm_free(dev);
+  return ret;
+}
diff --git a/drivers/timers/ocu_imx_gpt.c b/drivers/timers/ocu_imx_gpt.c
new file mode 100644
index 00000000000..68c30285aea
--- /dev/null
+++ b/drivers/timers/ocu_imx_gpt.c
@@ -0,0 +1,492 @@
+/****************************************************************************
+ * drivers/timers/ocu_imx_gpt.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 <debug.h>
+#include <errno.h>
+
+#include <nuttx/irq.h>
+#include <nuttx/kmalloc.h>
+#include <nuttx/spinlock.h>
+#include <nuttx/timers/ocu.h>
+#include <nuttx/timers/imx_gpt.h>
+
+/****************************************************************************
+ * Private Function Prototypes
+ ****************************************************************************/
+
+static int  imx_gpt_ocu_setup(FAR struct ocu_lowerhalf_s *lower);
+static int  imx_gpt_ocu_shutdown(FAR struct ocu_lowerhalf_s *lower);
+static int  imx_gpt_ocu_start(FAR struct ocu_lowerhalf_s *lower);
+static int  imx_gpt_ocu_stop(FAR struct ocu_lowerhalf_s *lower);
+static int  imx_gpt_ocu_getstatus(FAR struct ocu_lowerhalf_s *lower,
+              FAR struct ocu_status_s *status);
+static int  imx_gpt_ocu_getcounter(FAR struct ocu_lowerhalf_s *lower,
+              FAR uint32_t *counter);
+static int  imx_gpt_ocu_setabsthreshold(FAR struct ocu_lowerhalf_s *lower,
+              FAR struct ocu_abs_threshold_s *t);
+static int  imx_gpt_ocu_setrelthreshold(FAR struct ocu_lowerhalf_s *lower,
+              FAR struct ocu_rel_threshold_s *t);
+static int  imx_gpt_ocu_setadvancethreshold(
+              FAR struct ocu_lowerhalf_s *lower,
+              FAR struct ocu_advance_threshold_s *t);
+static void imx_gpt_ocu_setcallback(FAR struct ocu_lowerhalf_s *lower,
+              CODE ocu_callback_t callback, FAR void *arg);
+static int  imx_gpt_ocu_setpinstate(FAR struct ocu_lowerhalf_s *lower,
+              enum ocu_pinstate_e state);
+static int  imx_gpt_ocu_setpinaction(FAR struct ocu_lowerhalf_s *lower,
+              enum ocu_pinaction_e action);
+static int  imx_gpt_ocu_notification(FAR struct ocu_lowerhalf_s *lower,
+              bool enable);
+
+/****************************************************************************
+ * Private Data
+ ****************************************************************************/
+
+static const struct ocu_ops_s g_imx_gpt_ocu_ops =
+{
+  .setup               = imx_gpt_ocu_setup,
+  .shutdown            = imx_gpt_ocu_shutdown,
+  .start               = imx_gpt_ocu_start,
+  .stop                = imx_gpt_ocu_stop,
+  .getstatus           = imx_gpt_ocu_getstatus,
+  .getcounter          = imx_gpt_ocu_getcounter,
+  .setabsthreshold     = imx_gpt_ocu_setabsthreshold,
+  .setrelthreshold     = imx_gpt_ocu_setrelthreshold,
+  .setadvancethreshold = imx_gpt_ocu_setadvancethreshold,
+  .setcallback         = imx_gpt_ocu_setcallback,
+  .setpinstate         = imx_gpt_ocu_setpinstate,
+  .setpinaction        = imx_gpt_ocu_setpinaction,
+  .notification        = imx_gpt_ocu_notification,
+  .ioctl               = NULL,
+};
+
+/****************************************************************************
+ * Private Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_om_from_action
+ *
+ * Description:
+ *   Map a generic OCU pin action to the GPT OMx field encoding.
+ *
+ ****************************************************************************/
+
+static uint32_t imx_gpt_ocu_om_from_action(enum ocu_pinaction_e action)
+{
+  switch (action)
+    {
+      case OCU_PINACTION_TOGGLE:
+        return GPT_OM_TOGGLE;
+
+      case OCU_PINACTION_SET_LOW:
+        return GPT_OM_CLEAR;
+
+      case OCU_PINACTION_SET_HIGH:
+        return GPT_OM_SET;
+
+      case OCU_PINACTION_DISABLE:
+      default:
+        return GPT_OM_DISCONNECT;
+    }
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_update_ie
+ *
+ * Description:
+ *   Recompute and apply the compare-match interrupt enable for this
+ *   channel.  The interrupt is wanted only while the channel is active and
+ *   either a callback is registered or user notification is enabled.
+ *   Must be called with dev->lock held.
+ *
+ ****************************************************************************/
+
+static void imx_gpt_ocu_update_ie(FAR struct imx_gpt_ocu_s *priv)
+{
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  bool want = priv->active && (priv->notify_en || priv->callback != NULL);
+
+  if (want)
+    {
+      imx_gpt_modreg(dev, IMX_GPT_IR, 0, GPT_IR_OF(priv->ch));
+    }
+  else
+    {
+      imx_gpt_modreg(dev, IMX_GPT_IR, GPT_IR_OF(priv->ch), 0);
+    }
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_setup / imx_gpt_ocu_shutdown
+ ****************************************************************************/
+
+static int imx_gpt_ocu_setup(FAR struct ocu_lowerhalf_s *lower)
+{
+  /* The shared core already attached the interrupt; nothing to do. */
+
+  return OK;
+}
+
+static int imx_gpt_ocu_shutdown(FAR struct ocu_lowerhalf_s *lower)
+{
+  return imx_gpt_ocu_stop(lower);
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_start / imx_gpt_ocu_stop
+ ****************************************************************************/
+
+static int imx_gpt_ocu_start(FAR struct ocu_lowerhalf_s *lower)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  /* Enable the configured pin action; the free-running counter keeps
+   * running independently.
+   */
+
+  imx_gpt_modreg(dev, IMX_GPT_CR, GPT_CR_OM_MASK(priv->ch),
+                 imx_gpt_ocu_om_from_action(priv->action) <<
+                 GPT_CR_OM_SHIFT(priv->ch));
+
+  priv->active = true;
+  imx_gpt_ocu_update_ie(priv);
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+static int imx_gpt_ocu_stop(FAR struct ocu_lowerhalf_s *lower)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  priv->active = false;
+
+  /* Disconnect the pin and disable this channel's interrupt.  The shared
+   * counter is deliberately left running.
+   */
+
+  imx_gpt_modreg(dev, IMX_GPT_CR, GPT_CR_OM_MASK(priv->ch),
+                 GPT_OM_DISCONNECT << GPT_CR_OM_SHIFT(priv->ch));
+  imx_gpt_ocu_update_ie(priv);
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_getstatus / imx_gpt_ocu_getcounter
+ ****************************************************************************/
+
+static int imx_gpt_ocu_getstatus(FAR struct ocu_lowerhalf_s *lower,
+                                 FAR struct ocu_status_s *status)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+
+  /* The upper-half owns ACTIVE / NOTIF_EN; the lower-half reports the
+   * hardware capability (an output pin is always present per channel) and
+   * the hardware-specific counter / threshold values.
+   */
+
+  status->flags      = OCUFLAGS_PIN_AVAIL;
+  status->counter    = imx_gpt_getreg(dev, IMX_GPT_CNT);
+  status->threshold  = priv->last_threshold;
+  status->maxcounter = GPT_TIMER_MAX;
+  return OK;
+}
+
+static int imx_gpt_ocu_getcounter(FAR struct ocu_lowerhalf_s *lower,
+                                  FAR uint32_t *counter)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+
+  *counter = imx_gpt_getreg(priv->dev, IMX_GPT_CNT);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_setabsthreshold / setrelthreshold / setadvancethreshold
+ ****************************************************************************/
+
+static int imx_gpt_ocu_setabsthreshold(FAR struct ocu_lowerhalf_s *lower,
+                                       FAR struct ocu_abs_threshold_s *t)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  imx_gpt_putreg(dev, IMX_GPT_OCR(priv->ch), t->absolute);
+  priv->last_threshold = t->absolute;
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+
+  /* A free-running up-counter reaches the target within the current
+   * reference interval when the target is at or ahead of the reference.
+   */
+
+  t->result = (t->absolute >= t->reference) ?
+              OCU_THRESHOLD_IN_REF_INTERVAL :
+              OCU_THRESHOLD_OUT_REF_INTERVAL;
+  return OK;
+}
+
+static int imx_gpt_ocu_setrelthreshold(FAR struct ocu_lowerhalf_s *lower,
+                                       FAR struct ocu_rel_threshold_s *t)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+  uint32_t counter;
+  uint32_t threshold;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  counter   = imx_gpt_getreg(dev, IMX_GPT_CNT);
+  threshold = counter + t->relative;
+  imx_gpt_putreg(dev, IMX_GPT_OCR(priv->ch), threshold);
+  priv->last_threshold = threshold;
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+
+  /* If the addition wrapped past the 32-bit maximum the match falls into
+   * the next reference interval.
+   */
+
+  t->result = (threshold >= counter) ?
+              OCU_THRESHOLD_IN_REF_INTERVAL :
+              OCU_THRESHOLD_OUT_REF_INTERVAL;
+  return OK;
+}
+
+static int imx_gpt_ocu_setadvancethreshold(FAR struct ocu_lowerhalf_s *lower,
+                                       FAR struct ocu_advance_threshold_s *t)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+  uint32_t old_threshold;
+  uint32_t threshold;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  old_threshold = priv->last_threshold;
+  threshold     = old_threshold + t->step;
+  imx_gpt_putreg(dev, IMX_GPT_OCR(priv->ch), threshold);
+  priv->last_threshold = threshold;
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+
+  /* A wrap past the 32-bit maximum pushes the match into the next
+   * reference interval.
+   */
+
+  t->result = (threshold >= old_threshold) ?
+              OCU_THRESHOLD_IN_REF_INTERVAL :
+              OCU_THRESHOLD_OUT_REF_INTERVAL;
+  return OK;
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_setcallback
+ ****************************************************************************/
+
+static void imx_gpt_ocu_setcallback(FAR struct ocu_lowerhalf_s *lower,
+                                    CODE ocu_callback_t callback,
+                                    FAR void *arg)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  priv->callback = callback;
+  priv->cbarg    = arg;
+  imx_gpt_ocu_update_ie(priv);
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_setpinstate / imx_gpt_ocu_setpinaction
+ ****************************************************************************/
+
+static int imx_gpt_ocu_setpinstate(FAR struct ocu_lowerhalf_s *lower,
+                                   enum ocu_pinstate_e state)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+  uint32_t om;
+
+  /* The upper-half only permits this while the channel is stopped.  Drive
+   * the pin to the requested level by programming the matching output mode
+   * and issuing a forced compare (FOx self-clears after acting).
+   */
+
+  om = (state == OCU_PINSTATE_HIGH) ? GPT_OM_SET : GPT_OM_CLEAR;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  imx_gpt_modreg(dev, IMX_GPT_CR, GPT_CR_OM_MASK(priv->ch),
+                 om << GPT_CR_OM_SHIFT(priv->ch));
+  imx_gpt_modreg(dev, IMX_GPT_CR, 0, GPT_CR_FO(priv->ch));
+
+  /* Restore the disconnected state so the forced level is not re-driven on
+   * the next compare match while stopped.
+   */
+
+  imx_gpt_modreg(dev, IMX_GPT_CR, GPT_CR_OM_MASK(priv->ch),
+                 GPT_OM_DISCONNECT << GPT_CR_OM_SHIFT(priv->ch));
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+static int imx_gpt_ocu_setpinaction(FAR struct ocu_lowerhalf_s *lower,
+                                    enum ocu_pinaction_e action)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  priv->action = action;
+
+  /* Apply immediately if the channel is already running. */
+
+  if (priv->active)
+    {
+      imx_gpt_modreg(dev, IMX_GPT_CR, GPT_CR_OM_MASK(priv->ch),
+                     imx_gpt_ocu_om_from_action(action) <<
+                     GPT_CR_OM_SHIFT(priv->ch));
+    }
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_notification
+ ****************************************************************************/
+
+static int imx_gpt_ocu_notification(FAR struct ocu_lowerhalf_s *lower,
+                                    bool enable)
+{
+  FAR struct imx_gpt_ocu_s *priv = (FAR struct imx_gpt_ocu_s *)lower;
+  FAR struct imx_gpt_dev_s *dev = priv->dev;
+  irqstate_t flags;
+
+  flags = spin_lock_irqsave(&dev->lock);
+
+  priv->notify_en = enable;
+  imx_gpt_ocu_update_ie(priv);
+
+  spin_unlock_irqrestore(&dev->lock, flags);
+  return OK;
+}
+
+/****************************************************************************
+ * Public Functions
+ ****************************************************************************/
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_on_match
+ *
+ * Description:
+ *   Compare-match interrupt handler for one OCU channel.  Invoked from the
+ *   shared core ISR with dev->lock already held.  Runs the registered
+ *   callback and, if it asks to reload, re-arms the compare register with
+ *   the returned absolute threshold.
+ *
+ ****************************************************************************/
+
+void imx_gpt_ocu_on_match(FAR struct imx_gpt_ocu_s *ocu)
+{
+  uint32_t next = ocu->last_threshold;
+
+  if (ocu->callback != NULL)
+    {
+      if (ocu->callback(&next, ocu->cbarg))
+        {
+          imx_gpt_putreg(ocu->dev, IMX_GPT_OCR(ocu->ch), next);
+          ocu->last_threshold = next;
+        }
+    }
+}
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_register
+ *
+ * Description:
+ *   Allocate, initialise and register one OCU channel as an /dev/ocuN
+ *   character device.  Called by the shared core during initialisation.
+ *
+ ****************************************************************************/
+
+FAR struct imx_gpt_ocu_s *
+imx_gpt_ocu_register(FAR struct imx_gpt_dev_s *dev, int ch,
+                     FAR const char *devpath)
+{
+  FAR struct imx_gpt_ocu_s *priv;
+  int ret;
+
+  priv = kmm_zalloc(sizeof(*priv));
+  if (priv == NULL)
+    {
+      return NULL;
+    }
+
+  priv->lower.ops      = &g_imx_gpt_ocu_ops;
+  priv->dev            = dev;
+  priv->ch             = (uint8_t)ch;
+  priv->action         = OCU_PINACTION_TOGGLE;
+  priv->last_threshold = GPT_TIMER_MAX;
+
+  ret = ocu_register(devpath, &priv->lower);
+  if (ret < 0)
+    {
+      tmrerr("ERROR: ocu_register(%s) failed: %d\n", devpath, ret);
+      kmm_free(priv);
+      return NULL;
+    }
+
+  return priv;
+}
diff --git a/include/nuttx/timers/imx_gpt.h b/include/nuttx/timers/imx_gpt.h
new file mode 100644
index 00000000000..dd47589d908
--- /dev/null
+++ b/include/nuttx/timers/imx_gpt.h
@@ -0,0 +1,243 @@
+/****************************************************************************
+ * include/nuttx/timers/imx_gpt.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 i.MX GPT (General Purpose Timer) exposes a single free-running
+ * counter shared by an Output Compare Unit (OCU) and an Input Capture Unit
+ * (ICU).  A single MMIO block and a single interrupt line serve all
+ * channels.  This driver implements a shared "core" (imx_gpt.c) that owns
+ * the MMIO mapping, counter initialisation and the one and only interrupt
+ * service routine, plus "lower-half" adaptations that plug into the generic
+ * NuttX ocu (OCU) and capture (ICU) upper-half drivers.
+ */
+
+#ifndef __INCLUDE_NUTTX_TIMERS_IMX_GPT_H
+#define __INCLUDE_NUTTX_TIMERS_IMX_GPT_H
+
+/****************************************************************************
+ * Included Files
+ ****************************************************************************/
+
+#include <nuttx/config.h>
+#include <nuttx/spinlock.h>
+#include <nuttx/timers/ocu.h>
+
+#include <stdint.h>
+#include <stdbool.h>
+
+/****************************************************************************
+ * Pre-processor Definitions
+ ****************************************************************************/
+
+/* Channel counts (configurable, bounded by the hardware). */
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+#define IMX_GPT_NUM_OCU  CONFIG_TIMER_IMX_GPT_NUM_OCU
+#endif
+
+/* Register offsets (32-bit, little-endian, 4-byte access). */
+
+#define IMX_GPT_CR       0x00  /* Control register */
+#define IMX_GPT_PR       0x04  /* Prescaler register */
+#define IMX_GPT_SR       0x08  /* Status register (W1C) */
+#define IMX_GPT_IR       0x0c  /* Interrupt enable register */
+#define IMX_GPT_OCR1     0x10  /* Output compare register 1 (OCU ch0) */
+#define IMX_GPT_OCR2     0x14  /* Output compare register 2 (OCU ch1) */
+#define IMX_GPT_OCR3     0x18  /* Output compare register 3 (OCU ch2) */
+#define IMX_GPT_ICR1     0x1c  /* Input capture register 1 (ICU ch0) */
+#define IMX_GPT_ICR2     0x20  /* Input capture register 2 (ICU ch1) */
+#define IMX_GPT_CNT      0x24  /* Counter (free-running, shared time base) */
+
+/* Per-channel register helpers. */
+
+#define IMX_GPT_OCR(ch)  (IMX_GPT_OCR1 + ((ch) * 4)) /* ch = 0..2 */
+
+/* GPT_CR bit definitions. */
+
+#define GPT_CR_EN           (1 << 0)   /* Counter enable */
+#define GPT_CR_ENMOD        (1 << 1)   /* Reset counter when EN 0->1 */
+#define GPT_CR_CLKSRC_SHIFT (6)        /* Clock source select */
+#define GPT_CR_CLKSRC_MASK  (0x7 << GPT_CR_CLKSRC_SHIFT)
+#define GPT_CR_FRR          (1 << 9)   /* Free-run (1) / restart (0) */
+#define GPT_CR_SWR          (1 << 15)  /* Software reset */
+
+/* Output compare mode (3 bits/channel):
+ * 0=disconnect 1=toggle 2=clear(low) 3=set(high) 4=low-pulse.
+ */
+
+#define GPT_CR_OM_SHIFT(ch) (20 + ((ch) * 3))
+#define GPT_CR_OM_MASK(ch)  (0x7 << GPT_CR_OM_SHIFT(ch))
+#define GPT_OM_DISCONNECT   0
+#define GPT_OM_TOGGLE       1
+#define GPT_OM_CLEAR        2
+#define GPT_OM_SET          3
+
+/* Force output compare (write 1, self-clearing), one bit per OCU channel. */
+
+#define GPT_CR_FO(ch)       (1 << (29 + (ch)))
+
+/* GPT_SR / GPT_IR share the same bit layout. */
+
+#define GPT_SR_OF(ch)       (1 << (ch))        /* OCU compare match, ch 0..2 */
+#define GPT_SR_ROV          (1 << 5)           /* Counter roll-over */
+
+#define GPT_IR_OF(ch)       GPT_SR_OF(ch)
+#define GPT_IR_ROV          GPT_SR_ROV
+
+#define GPT_TIMER_MAX       0xffffffffu
+
+/****************************************************************************
+ * Public Types
+ ****************************************************************************/
+
+struct imx_gpt_dev_s;
+
+/* OCU (output compare) per-channel lower-half. Defined here so the shared
+ * core ISR can dispatch directly to it.
+ */
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+struct imx_gpt_ocu_s
+{
+  struct ocu_lowerhalf_s     lower;          /* Must be first (cast-compat) */
+  FAR struct imx_gpt_dev_s  *dev;            /* Back-pointer to shared core */
+  uint8_t                    ch;             /* OCU channel index 0..2 */
+  bool                       active;         /* Compare actions enabled */
+  bool                       notify_en;      /* HW notification enabled */
+  enum ocu_pinaction_e       action;         /* Pin action on match */
+  uint32_t                   last_threshold; /* Last programmed OCR value */
+  ocu_callback_t             callback;       /* ISR match callback */
+  FAR void                  *cbarg;          /* Callback argument */
+};
+#endif
+
+/* Shared "core" device: one MMIO block, one IRQ, one counter. */
+
+struct imx_gpt_dev_s
+{
+  uintptr_t                  base;           /* MMIO base address */
+  int                        irq;            /* Interrupt number */
+  uint32_t                   freq;           /* Effective tick freq (Hz) */
+  spinlock_t                 lock;           /* Protects CR/SR RMW */
+  volatile uint32_t          rollover;       /* ROV accounting */
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+  FAR struct imx_gpt_ocu_s  *ocu[IMX_GPT_NUM_OCU];
+#endif
+};
+
+/****************************************************************************
+ * Inline Register Access Helpers
+ ****************************************************************************/
+
+static inline uint32_t imx_gpt_getreg(FAR struct imx_gpt_dev_s *dev,
+                                      unsigned int offset)
+{
+  return *((FAR volatile uint32_t *)(dev->base + offset));
+}
+
+static inline void imx_gpt_putreg(FAR struct imx_gpt_dev_s *dev,
+                                  unsigned int offset, uint32_t value)
+{
+  *((FAR volatile uint32_t *)(dev->base + offset)) = value;
+}
+
+static inline void imx_gpt_modreg(FAR struct imx_gpt_dev_s *dev,
+                                  unsigned int offset, uint32_t clrbits,
+                                  uint32_t setbits)
+{
+  FAR volatile uint32_t *addr =
+    (FAR volatile uint32_t *)(dev->base + offset);
+  *addr = (*addr & ~clrbits) | setbits;
+}
+
+/****************************************************************************
+ * Public Function Prototypes
+ ****************************************************************************/
+
+#ifdef __cplusplus
+#define EXTERN extern "C"
+extern "C"
+{
+#else
+#define EXTERN extern
+#endif
+
+/****************************************************************************
+ * Name: imx_gpt_initialize
+ *
+ * Description:
+ *   Initialise a single i.MX GPT instance: map the MMIO block, configure
+ *   and start the shared free-running counter, attach the interrupt, and
+ *   register the OCU channels as /dev/ocu<ocu_bus + n>.
+ *
+ * Input Parameters:
+ *   base    - MMIO base address of the GPT block (from FDT).
+ *   irq     - Interrupt number of the GPT block (from FDT).
+ *   freq    - Counter input clock in Hz (from FDT clock-frequency).
+ *   ocu_bus - Starting /dev/ocuN index for the OCU channels.
+ *   cap_bus - Starting /dev/capN index for the ICU channels (unused until
+ *             ICU support is added).
+ *
+ * Returned Value:
+ *   Zero (OK) on success; a negated errno value on failure.
+ *
+ ****************************************************************************/
+
+int imx_gpt_initialize(uintptr_t base, int irq, uint32_t freq,
+                       int ocu_bus, int cap_bus);
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_register
+ *
+ * Description:
+ *   Internal helper implemented by the OCU lower-half source file.  Called
+ *   from imx_gpt_initialize() to build and register one channel.  Returns
+ *   the allocated channel object (stored by the core in dev->ocu[]) or NULL
+ *   on failure.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+FAR struct imx_gpt_ocu_s *
+imx_gpt_ocu_register(FAR struct imx_gpt_dev_s *dev, int ch,
+                     FAR const char *devpath);
+#endif
+
+/****************************************************************************
+ * Name: imx_gpt_ocu_on_match
+ *
+ * Description:
+ *   Per-channel compare-match interrupt handler, implemented by the OCU
+ *   lower-half source file and invoked from the shared core ISR when the
+ *   associated status bit is set.  Called in interrupt context.
+ *
+ ****************************************************************************/
+
+#ifdef CONFIG_TIMER_IMX_GPT_OCU
+void imx_gpt_ocu_on_match(FAR struct imx_gpt_ocu_s *ocu);
+#endif
+
+#undef EXTERN
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* __INCLUDE_NUTTX_TIMERS_IMX_GPT_H */

Reply via email to