Bump Standards-Version to 3.9.2 (no changes)
[gnulib.git] / lib / nanosleep.c
1 /* Provide a replacement for the POSIX nanosleep function.
2
3    Copyright (C) 1999-2000, 2002, 2004-2011 Free Software Foundation, Inc.
4
5    This program is free software: you can redistribute it and/or modify
6    it under the terms of the GNU General Public License as published by
7    the Free Software Foundation; either version 3 of the License, or
8    (at your option) any later version.
9
10    This program is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13    GNU General Public License for more details.
14
15    You should have received a copy of the GNU General Public License
16    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
17
18 /* written by Jim Meyering
19    and Bruno Haible for the Woe32 part */
20
21 #include <config.h>
22
23 #include <time.h>
24
25 #include "intprops.h"
26 #include "sig-handler.h"
27 #include "verify.h"
28
29 #include <stdbool.h>
30 #include <stdio.h>
31 #include <sys/types.h>
32 #include <sys/select.h>
33 #include <signal.h>
34
35 #include <sys/time.h>
36 #include <errno.h>
37
38 #include <unistd.h>
39
40
41 enum { BILLION = 1000 * 1000 * 1000 };
42
43 #if HAVE_BUG_BIG_NANOSLEEP
44
45 int
46 nanosleep (const struct timespec *requested_delay,
47            struct timespec *remaining_delay)
48 # undef nanosleep
49 {
50   /* nanosleep mishandles large sleeps due to internal overflow problems.
51      The worst known case of this is Linux 2.6.9 with glibc 2.3.4, which
52      can't sleep more than 24.85 days (2^31 milliseconds).  Similarly,
53      cygwin 1.5.x, which can't sleep more than 49.7 days (2^32 milliseconds).
54      Solve this by breaking the sleep up into smaller chunks.  */
55
56   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
57     {
58       errno = EINVAL;
59       return -1;
60     }
61
62   {
63     /* Verify that time_t is large enough.  */
64     verify (TYPE_MAXIMUM (time_t) / 24 / 24 / 60 / 60);
65     const time_t limit = 24 * 24 * 60 * 60;
66     time_t seconds = requested_delay->tv_sec;
67     struct timespec intermediate;
68     intermediate.tv_nsec = 0;
69
70     while (limit < seconds)
71       {
72         int result;
73         intermediate.tv_sec = limit;
74         result = nanosleep (&intermediate, remaining_delay);
75         seconds -= limit;
76         if (result)
77           {
78             if (remaining_delay)
79               {
80                 remaining_delay->tv_sec += seconds;
81                 remaining_delay->tv_nsec += requested_delay->tv_nsec;
82                 if (BILLION <= requested_delay->tv_nsec)
83                   {
84                     remaining_delay->tv_sec++;
85                     remaining_delay->tv_nsec -= BILLION;
86                   }
87               }
88             return result;
89           }
90       }
91     intermediate.tv_sec = seconds;
92     intermediate.tv_nsec = requested_delay->tv_nsec;
93     return nanosleep (&intermediate, remaining_delay);
94   }
95 }
96
97 #elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
98 /* Windows platforms.  */
99
100 # define WIN32_LEAN_AND_MEAN
101 # include <windows.h>
102
103 /* The Win32 function Sleep() has a resolution of about 15 ms and takes
104    at least 5 ms to execute.  We use this function for longer time periods.
105    Additionally, we use busy-looping over short time periods, to get a
106    resolution of about 0.01 ms.  In order to measure such short timespans,
107    we use the QueryPerformanceCounter() function.  */
108
109 int
110 nanosleep (const struct timespec *requested_delay,
111            struct timespec *remaining_delay)
112 {
113   static bool initialized;
114   /* Number of performance counter increments per nanosecond,
115      or zero if it could not be determined.  */
116   static double ticks_per_nanosecond;
117
118   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
119     {
120       errno = EINVAL;
121       return -1;
122     }
123
124   /* For requested delays of one second or more, 15ms resolution is
125      sufficient.  */
126   if (requested_delay->tv_sec == 0)
127     {
128       if (!initialized)
129         {
130           /* Initialize ticks_per_nanosecond.  */
131           LARGE_INTEGER ticks_per_second;
132
133           if (QueryPerformanceFrequency (&ticks_per_second))
134             ticks_per_nanosecond =
135               (double) ticks_per_second.QuadPart / 1000000000.0;
136
137           initialized = true;
138         }
139       if (ticks_per_nanosecond)
140         {
141           /* QueryPerformanceFrequency worked.  We can use
142              QueryPerformanceCounter.  Use a combination of Sleep and
143              busy-looping.  */
144           /* Number of milliseconds to pass to the Sleep function.
145              Since Sleep can take up to 8 ms less or 8 ms more than requested
146              (or maybe more if the system is loaded), we subtract 10 ms.  */
147           int sleep_millis = (int) requested_delay->tv_nsec / 1000000 - 10;
148           /* Determine how many ticks to delay.  */
149           LONGLONG wait_ticks = requested_delay->tv_nsec * ticks_per_nanosecond;
150           /* Start.  */
151           LARGE_INTEGER counter_before;
152           if (QueryPerformanceCounter (&counter_before))
153             {
154               /* Wait until the performance counter has reached this value.
155                  We don't need to worry about overflow, because the performance
156                  counter is reset at reboot, and with a frequency of 3.6E6
157                  ticks per second 63 bits suffice for over 80000 years.  */
158               LONGLONG wait_until = counter_before.QuadPart + wait_ticks;
159               /* Use Sleep for the longest part.  */
160               if (sleep_millis > 0)
161                 Sleep (sleep_millis);
162               /* Busy-loop for the rest.  */
163               for (;;)
164                 {
165                   LARGE_INTEGER counter_after;
166                   if (!QueryPerformanceCounter (&counter_after))
167                     /* QueryPerformanceCounter failed, but succeeded earlier.
168                        Should not happen.  */
169                     break;
170                   if (counter_after.QuadPart >= wait_until)
171                     /* The requested time has elapsed.  */
172                     break;
173                 }
174               goto done;
175             }
176         }
177     }
178   /* Implementation for long delays and as fallback.  */
179   Sleep (requested_delay->tv_sec * 1000 + requested_delay->tv_nsec / 1000000);
180
181  done:
182   /* Sleep is not interruptible.  So there is no remaining delay.  */
183   if (remaining_delay != NULL)
184     {
185       remaining_delay->tv_sec = 0;
186       remaining_delay->tv_nsec = 0;
187     }
188   return 0;
189 }
190
191 #else
192 /* Unix platforms lacking nanosleep. */
193
194 /* Some systems (MSDOS) don't have SIGCONT.
195    Using SIGTERM here turns the signal-handling code below
196    into a no-op on such systems. */
197 # ifndef SIGCONT
198 #  define SIGCONT SIGTERM
199 # endif
200
201 static sig_atomic_t volatile suspended;
202
203 /* Handle SIGCONT. */
204
205 static void
206 sighandler (int sig)
207 {
208   suspended = 1;
209 }
210
211 /* Suspend execution for at least *TS_DELAY seconds.  */
212
213 static void
214 my_usleep (const struct timespec *ts_delay)
215 {
216   struct timeval tv_delay;
217   tv_delay.tv_sec = ts_delay->tv_sec;
218   tv_delay.tv_usec = (ts_delay->tv_nsec + 999) / 1000;
219   if (tv_delay.tv_usec == 1000000)
220     {
221       time_t t1 = tv_delay.tv_sec + 1;
222       if (t1 < tv_delay.tv_sec)
223         tv_delay.tv_usec = 1000000 - 1; /* close enough */
224       else
225         {
226           tv_delay.tv_sec = t1;
227           tv_delay.tv_usec = 0;
228         }
229     }
230   select (0, NULL, NULL, NULL, &tv_delay);
231 }
232
233 /* Suspend execution for at least *REQUESTED_DELAY seconds.  The
234    *REMAINING_DELAY part isn't implemented yet.  */
235
236 int
237 nanosleep (const struct timespec *requested_delay,
238            struct timespec *remaining_delay)
239 {
240   static bool initialized;
241
242   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
243     {
244       errno = EINVAL;
245       return -1;
246     }
247
248   /* set up sig handler */
249   if (! initialized)
250     {
251       struct sigaction oldact;
252
253       sigaction (SIGCONT, NULL, &oldact);
254       if (get_handler (&oldact) != SIG_IGN)
255         {
256           struct sigaction newact;
257
258           newact.sa_handler = sighandler;
259           sigemptyset (&newact.sa_mask);
260           newact.sa_flags = 0;
261           sigaction (SIGCONT, &newact, NULL);
262         }
263       initialized = true;
264     }
265
266   suspended = 0;
267
268   my_usleep (requested_delay);
269
270   if (suspended)
271     {
272       /* Calculate time remaining.  */
273       /* FIXME: the code in sleep doesn't use this, so there's no
274          rush to implement it.  */
275
276       errno = EINTR;
277     }
278
279   /* FIXME: Restore sig handler?  */
280
281   return suspended;
282 }
283 #endif