nuttx watchdog理解

首先是wd_start函數,調用該函數是爲了設置一個watchdog定時器。

/****************************************************************************
 * Public Functions
 ****************************************************************************/

/****************************************************************************
 * Name: wd_start
 *
 * Description:
 *   This function adds a watchdog timer to the active timer queue.  The
 *   specified watchdog function at 'wdentry' will be called from the
 *   interrupt level after the specified number of ticks has elapsed.
 *   Watchdog timers may be started from the interrupt level.
 *
 *   Watchdog timers execute in the address environment that was in effect
 *   when wd_start() is called.
 *
 *   Watchdog timers execute only once.
 *
 *   To replace either the timeout delay or the function to be executed,
 *   call wd_start again with the same wdog; only the most recent wdStart()
 *   on a given watchdog ID has any effect.
 *
 * Input Parameters:
 *   wdog     - watchdog ID
 *   delay    - Delay count in clock ticks
 *   wdentry  - function to call on timeout
 *   parm1..4 - parameters to pass to wdentry
 *
 * Returned Value:
 *   Zero (OK) is returned on success; a negated errno value is return to
 *   indicate the nature of any failure.
 *
 * Assumptions:
 *   The watchdog routine runs in the context of the timer interrupt handler
 *   and is subject to all ISR restrictions.
 *
 ****************************************************************************/

int wd_start(WDOG_ID wdog, int32_t delay, wdentry_t wdentry,  int argc, ...)
{
  va_list ap;
  FAR struct wdog_s *curr;
  FAR struct wdog_s *prev;
  FAR struct wdog_s *next;
  int32_t now;
  irqstate_t flags;
  int i;

  /* Verify the wdog and setup parameters */

  if (wdog == NULL || argc > CONFIG_MAX_WDOGPARMS || delay < 0)
    {
      return -EINVAL;
    }

  /* Check if the watchdog has been started. If so, stop it.
   * NOTE:  There is a race condition here... the caller may receive
   * the watchdog between the time that wd_start is called and
   * the critical section is established.
   */

  flags = enter_critical_section();
  if (WDOG_ISACTIVE(wdog))
    {
      wd_cancel(wdog);
    }

  /* Save the data in the watchdog structure */

  wdog->func = wdentry;         /* Function to execute when delay expires */
  up_getpicbase(&wdog->picbase);
  wdog->argc = argc;

  va_start(ap, argc);
  for (i = 0; i < argc; i++)
    {
      wdog->parm[i] = va_arg(ap, wdparm_t);
    }

#ifdef CONFIG_DEBUG_FEATURES
  for (; i < CONFIG_MAX_WDOGPARMS; i++)
    {
      wdog->parm[i] = 0;
    }
#endif

  va_end(ap);

  /* Calculate delay+1, forcing the delay into a range that we can handle */

  if (delay <= 0)
    {
      delay = 1;
    }
  else if (++delay <= 0)
    {
      delay--;
    }

#ifdef CONFIG_SCHED_TICKLESS
  /* Cancel the interval timer that drives the timing events.  This will cause
   * wd_timer to be called which update the delay value for the first time
   * at the head of the timer list (there is a possibility that it could even
   * remove it).
   */

  ***(void)sched_timer_cancel();***
#endif

  /* Do the easy case first -- when the watchdog timer queue is empty. */

  if (g_wdactivelist.head == NULL)
    {
#ifdef CONFIG_SCHED_TICKLESS
      /* Update clock tickbase */

      g_wdtickbase = clock_systimer();
#endif

      /* Add the watchdog to the head == tail of the queue. */

      sq_addlast((FAR sq_entry_t *)wdog, &g_wdactivelist);
    }

  /* There are other active watchdogs in the timer queue */

  else
    {
      now = 0;
      prev = curr = (FAR struct wdog_s *)g_wdactivelist.head;

      /* Advance to positive time */

      while ((now += curr->lag) < 0 && curr->next)
        {
          prev = curr;
          curr = curr->next;
        }

      /* Advance past shorter delays */

      while (now <= delay && curr->next)
        {
          prev = curr;
          curr = curr->next;
          now += curr->lag;
        }

      /* Check if the new wdog must be inserted before the curr. */

      if (delay < now)
        {
          /* The relative delay time is smaller or equal to the current delay
           * time, so decrement the current delay time by the new relative
           * delay time.
           */

          delay -= (now - curr->lag);
          curr->lag -= delay;

          /* Insert the new watchdog in the list */

          if (curr == (FAR struct wdog_s *)g_wdactivelist.head)
            {
              /* Insert the watchdog at the head of the list */

              sq_addfirst((FAR sq_entry_t *)wdog, &g_wdactivelist);
            }
          else
            {
              /* Insert the watchdog in mid- or end-of-queue */

              sq_addafter((FAR sq_entry_t *)prev, (FAR sq_entry_t *)wdog,
                          &g_wdactivelist);
            }
        }

      /* The new watchdog delay time is greater than the curr delay time,
       * so the new wdog must be inserted after the curr. This only occurs
       * if the wdog is to be added to the end of the list.
       */

      else
        {
          delay -= now;
          if (!curr->next)
            {
              sq_addlast((FAR sq_entry_t *)wdog, &g_wdactivelist);
            }
          else
            {
              next = curr->next;
              next->lag -= delay;
              sq_addafter((FAR sq_entry_t *)curr, (FAR sq_entry_t *)wdog,
                          &g_wdactivelist);
            }
        }
    }

  /* Put the lag into the watchdog structure and mark it as active. */

  wdog->lag = delay;
  WDOG_SETACTIVE(wdog);

#ifdef CONFIG_SCHED_TICKLESS
  /* Resume the interval timer that will generate the next interval event.
   * If the timer at the head of the list changed, then this will pick that
   * new delay.
   */

  ***sched_timer_resume();***
#endif

  leave_critical_section(flags);
  return OK;
}

int wd_start(WDOG_ID wdog, int32_t delay, wdentry_t wdentry, int argc, ...)第一個參
數WDOG_ID wdog是watchdog ID, 第二個參數 int32_t delay是延時的時間,第三個
參數wdentry_t wdentry是watchdod的entry函數, int argc, …是指傳遞給
wdentry的參數列表。

      /* Advance to positive time */

      while ((now += curr->lag) < 0 && curr->next)
        {
          prev = curr;
          curr = curr->next;
        }

這部分代碼是在g_wdactivelist不爲空的情況下去找延時delay的存放節點,要找到
介於當前要設置的watchdog的間隔時間的節點。

#ifdef CONFIG_SCHED_TICKLESS
  /* Cancel the interval timer that drives the timing events.  This will cause
   * wd_timer to be called which update the delay value for the first time
   * at the head of the timer list (there is a possibility that it could even
   * remove it).
   */

  (void)sched_timer_cancel();                                                                                                                 
#endif
#ifdef CONFIG_SCHED_TICKLESS
  /* Cancel the interval timer that drives the timing events.  This will cause
   * wd_timer to be called which update the delay value for the first time
   * at the head of the timer list (there is a possibility that it could even
   * remove it).
   */

  (void)sched_timer_cancel();                                                                                                                 
#endif
#ifdef CONFIG_SCHED_TICKLESS                                                                                                                  
  /* Resume the interval timer that will generate the next interval event.
   * If the timer at the head of the list changed, then this will pick that
   * new delay.
   */

  sched_timer_resume();
#endif

sched_timer_cancel()函數和sched_timer_resume()是成對
的,sched_timer_cancel是暫停當前的計時活動。而sched_timer_resume則是重新評估下一個截止日期並重新啓動間隔計時器。
對於sched_timer_cancel()函數來說,其實現如下圖所示:

/****************************************************************************
 * Name:  sched_timer_cancel
 *
 * Description:
 *   Stop the current timing activity.  This is currently called just before
 *   a new entry is inserted at the head of a timer list and also as part
 *   of the processing of sched_timer_reassess().
 *
 *   This function(1) cancels the current timer, (2) determines how much of
 *   the interval has elapsed, (3) completes any partially timed events
 *   (including updating the delay of the timer at the head of the timer
 *   list), and (2) returns the number of ticks that would be needed to
 *   resume timing and complete this delay.
 *
 * Input Parameters:
 *   None
 *
 * Returned Value:
 *   Number of timer ticks that would be needed to complete the delay (zero
 *   if the timer was not active).
 *
 ****************************************************************************/

#ifdef CONFIG_SCHED_TICKLESS_ALARM
unsigned int sched_timer_cancel(void)
{
  struct timespec ts;
  unsigned int elapsed;

  /* Cancel the alarm and and get the time that the alarm was cancelled.
   * If the alarm was not enabled (or, perhaps, just expired since
   * interrupts were disabled), up_timer_cancel() will return the
   * current time.
   */

  ts.tv_sec  = g_stop_time.tv_sec;
  ts.tv_nsec = g_stop_time.tv_nsec;

  (void)up_alarm_cancel(&g_stop_time);

#ifdef CONFIG_SCHED_SPORADIC
  /* Save the last time that the scheduler ran */

  g_sched_time.tv_sec  = g_stop_time.tv_sec;
  g_sched_time.tv_nsec = g_stop_time.tv_nsec;
#endif

  /* Convert this to the elapsed time */

  clock_timespec_subtract(&g_stop_time, &ts, &ts);

  /* Convert to ticks */

#ifdef CONFIG_HAVE_LONG_LONG
  elapsed  = SEC2TICK((uint64_t)ts.tv_sec);
#else
  elapsed  = SEC2TICK(ts.tv_sec);
#endif
  elapsed += ts.tv_nsec / NSEC_PER_TICK;

  /* Correct g_stop_time cause of the elapsed have remainder */

  g_stop_time.tv_nsec -= ts.tv_nsec % NSEC_PER_TICK;
  if (g_stop_time.tv_nsec < 0)
    {
      g_stop_time.tv_nsec += NSEC_PER_SEC;
      g_stop_time.tv_sec--;
    }

  /* Process the timer ticks and return the next interval */

  return nxsched_timer_process(elapsed, true);
}
#else
unsigned int sched_timer_cancel(void)
{
  struct timespec ts;
  unsigned int ticks;
  unsigned int elapsed;

  /* Get the time remaining on the interval timer and cancel the timer. */

  (void)up_timer_cancel(&ts);

#ifdef CONFIG_SCHED_SPORADIC
  /* Save the last time that the scheduler ran */

  g_sched_time.tv_sec  = ts.tv_sec;
  g_sched_time.tv_nsec = ts.tv_nsec;
#endif

  /* Convert to ticks */

#ifdef CONFIG_HAVE_LONG_LONG
  ticks  = SEC2TICK((uint64_t)ts.tv_sec);
#else
  ticks  = SEC2TICK(ts.tv_sec);
#endif
  ticks += NSEC2TICK(ts.tv_nsec);
  DEBUGASSERT(ticks <= g_timer_interval);

  /* Handle the partial timer.  This will reassess all timer conditions and
   * re-start the interval timer with the correct delay.  Context switches
   * are not permitted in this case because we are not certain of the
   * calling conditions.
   */

  elapsed          = g_timer_interval - ticks;
  g_timer_interval = 0;

  /* Process the timer ticks and return the next interval */

  return nxsched_timer_process(elapsed, true);
}
#endif

sched_timer_resume()作用是重新評估下一個截止日期並重新啓動間隔計時器,其
實先函數如下所示:

/****************************************************************************
 * Name:  sched_timer_resume
 *
 * Description:
 *   Re-assess the next deadline and restart the interval timer.  This is
 *   called from wd_start() after it has inserted a new delay into the
 *   timer list.
 *
 * Input Parameters:
 *   None
 *
 * Returned Value:
 *   None.
 *
 * Assumptions:
 *   This function is called right after sched_timer_cancel().  If
 *   CONFIG_SCHED_TICKLESS_ALARM=y, then g_stop_time must be the value time
 *   when the timer was cancelled.
 *
 ****************************************************************************/

void sched_timer_resume(void)
{
  unsigned int nexttime;

#ifdef CONFIG_SCHED_SPORADIC
  /* Save the last time that the scheduler ran */

  (void)up_timer_gettime(&g_sched_time);
#endif

  /* Reassess the next deadline (by simply processing a zero ticks expired)
   * and set up the next interval (or not).
   */

  //nxsched_timer_process返回下一次watchdog timer要delay的時
  間,nxsched_timer_start是要啓動下一次的watchdog timer.
  nexttime = nxsched_timer_process(0, true);
  nxsched_timer_start(nexttime);
}

nxsched_timer_process()函數的實現如下所示,其功能是找出下一個節點的watchdog的有效delay時間,給nxsched_timer_start()用於啓動下一次的timer。

/****************************************************************************
 * Name:  nxsched_timer_process
 *
 * Description:
 *   Process events on timer expiration.
 *
 * Input Parameters:
 *   ticks - The number of ticks that have elapsed on the interval timer.
 *   noswitches - True: Can't do context switches now.
 *
 * Returned Value:
 *   The number of ticks to use when setting up the next timer.  Zero if
 *   there is no interesting event to be timed.
 *
 ****************************************************************************/

static unsigned int nxsched_timer_process(unsigned int ticks,
                                          bool noswitches)
{
  unsigned int cmptime = UINT_MAX;
  unsigned int rettime = 0;
  unsigned int tmp;

#ifdef CONFIG_CLOCK_TIMEKEEPING
  /* Process wall time */

  clock_update_wall_time();
#endif

  /* Process watchdogs */

  tmp = wd_timer(ticks);
  if (tmp > 0)
    {
      cmptime = tmp;
      rettime = tmp;
    }

  /* Check for operations specific to scheduling policy of the currently
   * active task.
   */

  tmp = nxsched_process_scheduler(ticks, noswitches);
  if (tmp > 0 && tmp < cmptime)
    {
      rettime = tmp;
    }

  return rettime;
}

wd_timer函數是用於找到下一個timer的時間,其實先如下:

/****************************************************************************
 * Name: wd_timer
 *
 * Description:
 *   This function is called from the timer interrupt handler to determine
 *   if it is time to execute a watchdog function.  If so, the watchdog
 *   function will be executed in the context of the timer interrupt
 *   handler.
 *
 * Input Parameters:
 *   ticks - If CONFIG_SCHED_TICKLESS is defined then the number of ticks
 *     in the interval that just expired is provided.  Otherwise,
 *     this function is called on each timer interrupt and a value of one
 *     is implicit.
 *
 * Returned Value:
 *   If CONFIG_SCHED_TICKLESS is defined then the number of ticks for the
 *   next delay is provided (zero if no delay).  Otherwise, this function
 *   has no returned value.
 *
 * Assumptions:
 *   Called from interrupt handler logic with interrupts disabled.
 *
 ****************************************************************************/

#ifdef CONFIG_SCHED_TICKLESS
unsigned int wd_timer(int ticks)
{
  FAR struct wdog_s *wdog;
#ifdef CONFIG_SMP
  irqstate_t flags;
#endif
  unsigned int ret;
  int decr;

#ifdef CONFIG_SMP
  /* We are in an interrupt handler as, as a consequence, interrupts are
   * disabled.  But in the SMP case, interrupts MAY be disabled only on
   * the local CPU since most architectures do not permit disabling
   * interrupts on other CPUS.
   *
   * Hence, we must follow rules for critical sections even here in the
   * SMP case.
   */

  flags = enter_critical_section();
#endif

  /* Check if there are any active watchdogs to process */

  while (g_wdactivelist.head != NULL && ticks > 0)
    {
      /* Get the watchdog at the head of the list */

      wdog = (FAR struct wdog_s *)g_wdactivelist.head;

#ifndef CONFIG_SCHED_TICKLESS_ALARM
      /* There is logic to handle the case where ticks is greater than
       * the watchdog lag, but if the scheduling is working properly
       * that should never happen.
       */

      DEBUGASSERT(ticks <= wdog->lag);
#endif
      /* Decrement the lag for this watchdog. */

      decr = MIN(wdog->lag, ticks);

      /* There are.  Decrement the lag counter */

      wdog->lag    -= decr;
      ticks        -= decr;
      g_wdtickbase += decr;

      /* Check if the watchdog at the head of the list is ready to run */

      wd_expiration();
    }

  /* Update clock tickbase */

  g_wdtickbase += ticks;

  /* Return the delay for the next watchdog to expire */

  ret = g_wdactivelist.head ?
          ((FAR struct wdog_s *)g_wdactivelist.head)->lag : 0;

#ifdef CONFIG_SMP
  leave_critical_section(flags);
#endif

  /* Return the delay for the next watchdog to expire */

  return ret;
}

#else
void wd_timer(void)
{
#ifdef CONFIG_SMP
  irqstate_t flags;

  /* We are in an interrupt handler as, as a consequence, interrupts are
   * disabled.  But in the SMP case, interrupts MAY be disabled only on
   * the local CPU since most architectures do not permit disabling
   * interrupts on other CPUS.
   *
   * Hence, we must follow rules for critical sections even here in the
   * SMP case.
   */

  flags = enter_critical_section();
#endif

  /* Check if there are any active watchdogs to process */

  if (g_wdactivelist.head)
    {
      /* There are.  Decrement the lag counter */

      --(((FAR struct wdog_s *)g_wdactivelist.head)->lag);

      /* Check if the watchdog at the head of the list is ready to run */

      wd_expiration();
    }

#ifdef CONFIG_SMP
  leave_critical_section(flags);
#endif
}
#endif /* CONFIG_SCHED_TICKLESS */

wd_expiration()函數用於檢查watchdog list head節點的是否準備好去運行了,其實先如下所示:

/****************************************************************************
 * Name: wd_expiration
 *
 * Description:
 *   Check if the timer for the watchdog at the head of list is ready to
 *   run.  If so, remove the watchdog from the list and execute it.
 *
 * Input Parameters:
 *   None
 *
 * Returned Value:
 *   None
 *
 ****************************************************************************/

static inline void wd_expiration(void)
{
  FAR struct wdog_s *wdog;

  /* Check if the watchdog at the head of the list is ready to run */

  if (((FAR struct wdog_s *)g_wdactivelist.head)->lag <= 0)
    {
      /* Process the watchdog at the head of the list as well as any
       * other watchdogs that became ready to run at this time
       */

      while (g_wdactivelist.head &&
             ((FAR struct wdog_s *)g_wdactivelist.head)->lag <= 0)
        {
          /* Remove the watchdog from the head of the list */

          wdog = (FAR struct wdog_s *)sq_remfirst(&g_wdactivelist);

          /* If there is another watchdog behind this one, update its
           * its lag (this shouldn't be necessary).
           */

          if (g_wdactivelist.head)
            {
              ((FAR struct wdog_s *)g_wdactivelist.head)->lag += wdog->lag;
            }

          /* Indicate that the watchdog is no longer active. */

          WDOG_CLRACTIVE(wdog);

          /* Execute the watchdog function */

          up_setpicbase(wdog->picbase);

#if CONFIG_MAX_WDOGPARMS == 0
          wdog->func(0);
#elif CONFIG_MAX_WDOGPARMS == 1
          wdog->func((int)wdog->argc,
                     wdog->parm[0]);
#elif CONFIG_MAX_WDOGPARMS == 2
          wdog->func((int)wdog->argc,
                     wdog->parm[0], wdog->parm[1]);
#elif CONFIG_MAX_WDOGPARMS == 3
          wdog->func((int)wdog->argc,
                     wdog->parm[0], wdog->parm[1], wdog->parm[2]);
#elif CONFIG_MAX_WDOGPARMS == 4
          wdog->func((int)wdog->argc,
                     wdog->parm[0], wdog->parm[1], wdog->parm[2],
                     wdog->parm[3]);
#else
#  error Missing support
#endif
        }
    }
}

nxsched_process_scheduler函數的功能是如果系統支持RR和sporadic調度,則算出這兩種調度所允許的調度時間去和
wd_timer函數返回的下一個watchdog list節點的delay時間做
比較,然後的出最小的時間去啓動下一次的timer. 如果系統支持的是FIFO調度,則該函數返回的是0。

/****************************************************************************
 * Name: nxsched_process_scheduler
 *
 * Description:
 *   Check for operations specific to scheduling policy of the currently
 *   active task on a single CPU.
 *
 * Input Parameters:
 *   ticks - The number of ticks that have elapsed on the interval timer.
 *   noswitches - True: Can't do context switches now.
 *
 * Returned Value:
 *   The number if ticks remaining until the next time slice expires.
 *   Zero is returned if there is no time slicing (i.e., the task at the
 *   head of the ready-to-run list does not support round robin
 *   scheduling).
 *
 *   The value one may returned under certain circumstances that probably
 *   can't happen.  The value one is the minimal timer setup and it means
 *   that a context switch is needed now, but cannot be performed because
 *   noswitches == true.
 *
 ****************************************************************************/

#if CONFIG_RR_INTERVAL > 0 || defined(CONFIG_SCHED_SPORADIC)
static uint32_t nxsched_process_scheduler(uint32_t ticks, bool noswitches)
{
#ifdef CONFIG_SMP
  uint32_t minslice = UINT32_MAX;
  uint32_t timeslice;
  irqstate_t flags;
  int i;

  /* If we are running on a single CPU architecture, then we know interrupts
   * a disabled an there is no need to explicitly call
   * enter_critical_section().  However, in the SMP case,
   * enter_critical_section() does much more than just disable interrupts on
   * the local CPU; it also manages spinlocks to assure the stability of the
   * TCB that we are manipulating.
   */

  flags = enter_critical_section();

  /* Perform scheduler operations on all CPUs */

  for (i = 0; i < CONFIG_SMP_NCPUS; i++)
    {
      timeslice = nxsched_cpu_scheduler(i, ticks, noswitches);
      if (timeslice > 0 && timeslice < minslice)
        {
          minslice = timeslice;
        }
    }

  leave_critical_section(flags);
  return minslice < UINT32_MAX ? minslice : 0;

#else
  /* Perform scheduler operations on the single CPUs */

  return nxsched_cpu_scheduler(0, ticks, noswitches);
#endif
}
#else
#  define nxsched_process_scheduler(t,n) (0)
#endif

sched_timer_resume重新評估下一個截止日期並重新啓動間隔計時器。

/****************************************************************************
 * Name:  sched_timer_resume
 *
 * Description:
 *   Re-assess the next deadline and restart the interval timer.  This is
 *   called from wd_start() after it has inserted a new delay into the
 *   timer list.
 *
 * Input Parameters:
 *   None
 *
 * Returned Value:
 *   None.
 *
 * Assumptions:
 *   This function is called right after sched_timer_cancel().  If
 *   CONFIG_SCHED_TICKLESS_ALARM=y, then g_stop_time must be the value time
 *   when the timer was cancelled.
 *
 ****************************************************************************/

void sched_timer_resume(void)
{
  unsigned int nexttime;

#ifdef CONFIG_SCHED_SPORADIC
  /* Save the last time that the scheduler ran */

  (void)up_timer_gettime(&g_sched_time);
#endif

  /* Reassess the next deadline (by simply processing a zero ticks expired)
   * and set up the next interval (or not).
   */

  nexttime = nxsched_timer_process(0, true);
  nxsched_timer_start(nexttime);
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章