Add ChangeLog entries for recent commits.
[gnulib.git] / lib / nanosleep.c
1 /* Provide a replacement for the POSIX nanosleep function.
2
3    Copyright (C) 1999-2000, 2002, 2004-2010 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
51      problems.  The worst known case of this is cygwin 1.5.x, which
52      can't sleep more than 49.7 days (2**32 milliseconds).  Solve this
53      by breaking the sleep up into smaller chunks.  Verify that time_t
54      is large enough.  */
55   verify (TYPE_MAXIMUM (time_t) / 49 / 24 / 60 / 60);
56   const time_t limit = 49 * 24 * 60 * 60;
57   time_t seconds = requested_delay->tv_sec;
58   struct timespec intermediate;
59   intermediate.tv_nsec = 0;
60
61   while (limit < seconds)
62     {
63       int result;
64       intermediate.tv_sec = limit;
65       result = nanosleep (&intermediate, remaining_delay);
66       seconds -= limit;
67       if (result)
68         {
69           if (remaining_delay)
70             {
71               remaining_delay->tv_sec += seconds;
72               remaining_delay->tv_nsec += requested_delay->tv_nsec;
73               if (BILLION <= requested_delay->tv_nsec)
74                 {
75                   remaining_delay->tv_sec++;
76                   remaining_delay->tv_nsec -= BILLION;
77                 }
78             }
79           return result;
80         }
81     }
82   intermediate.tv_sec = seconds;
83   intermediate.tv_nsec = requested_delay->tv_nsec;
84   return nanosleep (&intermediate, remaining_delay);
85 }
86
87 #elif (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
88 /* Windows platforms.  */
89
90 # define WIN32_LEAN_AND_MEAN
91 # include <windows.h>
92
93 /* The Win32 function Sleep() has a resolution of about 15 ms and takes
94    at least 5 ms to execute.  We use this function for longer time periods.
95    Additionally, we use busy-looping over short time periods, to get a
96    resolution of about 0.01 ms.  In order to measure such short timespans,
97    we use the QueryPerformanceCounter() function.  */
98
99 int
100 nanosleep (const struct timespec *requested_delay,
101            struct timespec *remaining_delay)
102 {
103   static bool initialized;
104   /* Number of performance counter increments per nanosecond,
105      or zero if it could not be determined.  */
106   static double ticks_per_nanosecond;
107
108   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
109     {
110       errno = EINVAL;
111       return -1;
112     }
113
114   /* For requested delays of one second or more, 15ms resolution is
115      sufficient.  */
116   if (requested_delay->tv_sec == 0)
117     {
118       if (!initialized)
119         {
120           /* Initialize ticks_per_nanosecond.  */
121           LARGE_INTEGER ticks_per_second;
122
123           if (QueryPerformanceFrequency (&ticks_per_second))
124             ticks_per_nanosecond =
125               (double) ticks_per_second.QuadPart / 1000000000.0;
126
127           initialized = true;
128         }
129       if (ticks_per_nanosecond)
130         {
131           /* QueryPerformanceFrequency worked.  We can use
132              QueryPerformanceCounter.  Use a combination of Sleep and
133              busy-looping.  */
134           /* Number of milliseconds to pass to the Sleep function.
135              Since Sleep can take up to 8 ms less or 8 ms more than requested
136              (or maybe more if the system is loaded), we subtract 10 ms.  */
137           int sleep_millis = (int) requested_delay->tv_nsec / 1000000 - 10;
138           /* Determine how many ticks to delay.  */
139           LONGLONG wait_ticks = requested_delay->tv_nsec * ticks_per_nanosecond;
140           /* Start.  */
141           LARGE_INTEGER counter_before;
142           if (QueryPerformanceCounter (&counter_before))
143             {
144               /* Wait until the performance counter has reached this value.
145                  We don't need to worry about overflow, because the performance
146                  counter is reset at reboot, and with a frequency of 3.6E6
147                  ticks per second 63 bits suffice for over 80000 years.  */
148               LONGLONG wait_until = counter_before.QuadPart + wait_ticks;
149               /* Use Sleep for the longest part.  */
150               if (sleep_millis > 0)
151                 Sleep (sleep_millis);
152               /* Busy-loop for the rest.  */
153               for (;;)
154                 {
155                   LARGE_INTEGER counter_after;
156                   if (!QueryPerformanceCounter (&counter_after))
157                     /* QueryPerformanceCounter failed, but succeeded earlier.
158                        Should not happen.  */
159                     break;
160                   if (counter_after.QuadPart >= wait_until)
161                     /* The requested time has elapsed.  */
162                     break;
163                 }
164               goto done;
165             }
166         }
167     }
168   /* Implementation for long delays and as fallback.  */
169   Sleep (requested_delay->tv_sec * 1000 + requested_delay->tv_nsec / 1000000);
170
171  done:
172   /* Sleep is not interruptible.  So there is no remaining delay.  */
173   if (remaining_delay != NULL)
174     {
175       remaining_delay->tv_sec = 0;
176       remaining_delay->tv_nsec = 0;
177     }
178   return 0;
179 }
180
181 #else
182 /* Unix platforms lacking nanosleep. */
183
184 /* Some systems (MSDOS) don't have SIGCONT.
185    Using SIGTERM here turns the signal-handling code below
186    into a no-op on such systems. */
187 # ifndef SIGCONT
188 #  define SIGCONT SIGTERM
189 # endif
190
191 static sig_atomic_t volatile suspended;
192
193 /* Handle SIGCONT. */
194
195 static void
196 sighandler (int sig)
197 {
198   suspended = 1;
199 }
200
201 /* Suspend execution for at least *TS_DELAY seconds.  */
202
203 static void
204 my_usleep (const struct timespec *ts_delay)
205 {
206   struct timeval tv_delay;
207   tv_delay.tv_sec = ts_delay->tv_sec;
208   tv_delay.tv_usec = (ts_delay->tv_nsec + 999) / 1000;
209   if (tv_delay.tv_usec == 1000000)
210     {
211       time_t t1 = tv_delay.tv_sec + 1;
212       if (t1 < tv_delay.tv_sec)
213         tv_delay.tv_usec = 1000000 - 1; /* close enough */
214       else
215         {
216           tv_delay.tv_sec = t1;
217           tv_delay.tv_usec = 0;
218         }
219     }
220   select (0, NULL, NULL, NULL, &tv_delay);
221 }
222
223 /* Suspend execution for at least *REQUESTED_DELAY seconds.  The
224    *REMAINING_DELAY part isn't implemented yet.  */
225
226 int
227 nanosleep (const struct timespec *requested_delay,
228            struct timespec *remaining_delay)
229 {
230   static bool initialized;
231
232   if (requested_delay->tv_nsec < 0 || BILLION <= requested_delay->tv_nsec)
233     {
234       errno = EINVAL;
235       return -1;
236     }
237
238   /* set up sig handler */
239   if (! initialized)
240     {
241       struct sigaction oldact;
242
243       sigaction (SIGCONT, NULL, &oldact);
244       if (get_handler (&oldact) != SIG_IGN)
245         {
246           struct sigaction newact;
247
248           newact.sa_handler = sighandler;
249           sigemptyset (&newact.sa_mask);
250           newact.sa_flags = 0;
251           sigaction (SIGCONT, &newact, NULL);
252         }
253       initialized = true;
254     }
255
256   suspended = 0;
257
258   my_usleep (requested_delay);
259
260   if (suspended)
261     {
262       /* Calculate time remaining.  */
263       /* FIXME: the code in sleep doesn't use this, so there's no
264          rush to implement it.  */
265
266       errno = EINTR;
267     }
268
269   /* FIXME: Restore sig handler?  */
270
271   return suspended;
272 }
273 #endif