root/lib/nanosleep.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. nanosleep
  2. nanosleep
  3. nanosleep

     1 /* Provide a replacement for the POSIX nanosleep function.
     2 
     3    Copyright (C) 1999-2000, 2002, 2004-2023 Free Software Foundation,
     4    Inc.
     5 
     6    This file is free software: you can redistribute it and/or modify
     7    it under the terms of the GNU Lesser General Public License as
     8    published by the Free Software Foundation; either version 2.1 of the
     9    License, or (at your option) any later version.
    10 
    11    This file is distributed in the hope that it will be useful,
    12    but WITHOUT ANY WARRANTY; without even the implied warranty of
    13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    14    GNU Lesser General Public License for more details.
    15 
    16    You should have received a copy of the GNU Lesser General Public License
    17    along with this program.  If not, see <https://www.gnu.org/licenses/>.  */
    18 
    19 /* written by Jim Meyering
    20    and Bruno Haible for the native Windows part */
    21 
    22 #include <config.h>
    23 
    24 #include <time.h>
    25 
    26 #include "intprops.h"
    27 
    28 #include <stdio.h>
    29 #include <sys/types.h>
    30 #include <sys/select.h>
    31 #include <signal.h>
    32 
    33 #include <errno.h>
    34 
    35 #include <unistd.h>
    36 
    37 
    38 enum { BILLION = 1000 * 1000 * 1000 };
    39 
    40 #if HAVE_BUG_BIG_NANOSLEEP
    41 
    42 int
    43 nanosleep (const struct timespec *requested_delay,
    44            struct timespec *remaining_delay)
    45 # undef nanosleep
    46 {
    47   /* nanosleep mishandles large sleeps due to internal overflow problems.
    48      The worst known case of this is Linux 2.6.9 with glibc 2.3.4, which
    49      can't sleep more than 24.85 days (2^31 milliseconds).  Similarly,
    50      cygwin 1.5.x, which can't sleep more than 49.7 days (2^32 milliseconds).
    51      Solve this by breaking the sleep up into smaller chunks.  */
    52 
    53   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
    54     {
    55       errno = EINVAL;
    56       return -1;
    57     }
    58 
    59   {
    60     /* Verify that time_t is large enough.  */
    61     static_assert (TYPE_MAXIMUM (time_t) / 24 / 24 / 60 / 60);
    62     const time_t limit = 24 * 24 * 60 * 60;
    63     time_t seconds = requested_delay->tv_sec;
    64     struct timespec intermediate;
    65     intermediate.tv_nsec = requested_delay->tv_nsec;
    66 
    67     while (limit < seconds)
    68       {
    69         int result;
    70         intermediate.tv_sec = limit;
    71         result = nanosleep (&intermediate, remaining_delay);
    72         seconds -= limit;
    73         if (result)
    74           {
    75             if (remaining_delay)
    76               remaining_delay->tv_sec += seconds;
    77             return result;
    78           }
    79         intermediate.tv_nsec = 0;
    80       }
    81     intermediate.tv_sec = seconds;
    82     return nanosleep (&intermediate, remaining_delay);
    83   }
    84 }
    85 
    86 #elif defined _WIN32 && ! defined __CYGWIN__
    87 /* Native Windows platforms.  */
    88 
    89 # define WIN32_LEAN_AND_MEAN
    90 # include <windows.h>
    91 
    92 /* The Windows API function Sleep() has a resolution of about 15 ms and takes
    93    at least 5 ms to execute.  We use this function for longer time periods.
    94    Additionally, we use busy-looping over short time periods, to get a
    95    resolution of about 0.01 ms.  In order to measure such short timespans,
    96    we use the QueryPerformanceCounter() function.  */
    97 
    98 int
    99 nanosleep (const struct timespec *requested_delay,
   100            struct timespec *remaining_delay)
   101 {
   102   static bool initialized;
   103   /* Number of performance counter increments per nanosecond,
   104      or zero if it could not be determined.  */
   105   static double ticks_per_nanosecond;
   106 
   107   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
   108     {
   109       errno = EINVAL;
   110       return -1;
   111     }
   112 
   113   /* For requested delays of one second or more, 15ms resolution is
   114      sufficient.  */
   115   if (requested_delay->tv_sec == 0)
   116     {
   117       if (!initialized)
   118         {
   119           /* Initialize ticks_per_nanosecond.  */
   120           LARGE_INTEGER ticks_per_second;
   121 
   122           if (QueryPerformanceFrequency (&ticks_per_second))
   123             ticks_per_nanosecond =
   124               (double) ticks_per_second.QuadPart / 1000000000.0;
   125 
   126           initialized = true;
   127         }
   128       if (ticks_per_nanosecond)
   129         {
   130           /* QueryPerformanceFrequency worked.  We can use
   131              QueryPerformanceCounter.  Use a combination of Sleep and
   132              busy-looping.  */
   133           /* Number of milliseconds to pass to the Sleep function.
   134              Since Sleep can take up to 8 ms less or 8 ms more than requested
   135              (or maybe more if the system is loaded), we subtract 10 ms.  */
   136           int sleep_millis = (int) requested_delay->tv_nsec / 1000000 - 10;
   137           /* Determine how many ticks to delay.  */
   138           LONGLONG wait_ticks = requested_delay->tv_nsec * ticks_per_nanosecond;
   139           /* Start.  */
   140           LARGE_INTEGER counter_before;
   141           if (QueryPerformanceCounter (&counter_before))
   142             {
   143               /* Wait until the performance counter has reached this value.
   144                  We don't need to worry about overflow, because the performance
   145                  counter is reset at reboot, and with a frequency of 3.6E6
   146                  ticks per second 63 bits suffice for over 80000 years.  */
   147               LONGLONG wait_until = counter_before.QuadPart + wait_ticks;
   148               /* Use Sleep for the longest part.  */
   149               if (sleep_millis > 0)
   150                 Sleep (sleep_millis);
   151               /* Busy-loop for the rest.  */
   152               for (;;)
   153                 {
   154                   LARGE_INTEGER counter_after;
   155                   if (!QueryPerformanceCounter (&counter_after))
   156                     /* QueryPerformanceCounter failed, but succeeded earlier.
   157                        Should not happen.  */
   158                     break;
   159                   if (counter_after.QuadPart >= wait_until)
   160                     /* The requested time has elapsed.  */
   161                     break;
   162                 }
   163               goto done;
   164             }
   165         }
   166     }
   167   /* Implementation for long delays and as fallback.  */
   168   Sleep (requested_delay->tv_sec * 1000 + requested_delay->tv_nsec / 1000000);
   169 
   170  done:
   171   /* Sleep is not interruptible.  So there is no remaining delay.  */
   172   if (remaining_delay != NULL)
   173     {
   174       remaining_delay->tv_sec = 0;
   175       remaining_delay->tv_nsec = 0;
   176     }
   177   return 0;
   178 }
   179 
   180 #else
   181 /* Other platforms lacking nanosleep.
   182    It's not clear whether these are still practical porting targets.
   183    For now, just fall back on pselect.  */
   184 
   185 /* Suspend execution for at least *REQUESTED_DELAY seconds.  The
   186    *REMAINING_DELAY part isn't implemented yet.  */
   187 
   188 int
   189 nanosleep (const struct timespec *requested_delay,
   190            struct timespec *remaining_delay)
   191 {
   192   return pselect (0, NULL, NULL, NULL, requested_delay, NULL);
   193 }
   194 #endif

/* [<][>][^][v][top][bottom][index][help] */