uv: Upgrade to v0.10.19
[platform/upstream/nodejs.git] / deps / uv / src / unix / linux-core.c
1 /* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
2  * Permission is hereby granted, free of charge, to any person obtaining a copy
3  * of this software and associated documentation files (the "Software"), to
4  * deal in the Software without restriction, including without limitation the
5  * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
6  * sell copies of the Software, and to permit persons to whom the Software is
7  * furnished to do so, subject to the following conditions:
8  *
9  * The above copyright notice and this permission notice shall be included in
10  * all copies or substantial portions of the Software.
11  *
12  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
13  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
15  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
16  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
17  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
18  * IN THE SOFTWARE.
19  */
20
21 #include "uv.h"
22 #include "internal.h"
23
24 #include <stdint.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <assert.h>
29 #include <errno.h>
30
31 #include <net/if.h>
32 #include <sys/param.h>
33 #include <sys/prctl.h>
34 #include <sys/sysinfo.h>
35 #include <unistd.h>
36 #include <fcntl.h>
37 #include <time.h>
38
39 #define HAVE_IFADDRS_H 1
40 #ifdef __UCLIBC__
41 # if __UCLIBC_MAJOR__ < 0 || __UCLIBC_MINOR__ < 9 || __UCLIBC_SUBLEVEL__ < 32
42 #  undef HAVE_IFADDRS_H
43 # endif
44 #endif
45 #ifdef HAVE_IFADDRS_H
46 # include <ifaddrs.h>
47 #endif
48
49 #undef NANOSEC
50 #define NANOSEC ((uint64_t) 1e9)
51
52 /* This is rather annoying: CLOCK_BOOTTIME lives in <linux/time.h> but we can't
53  * include that file because it conflicts with <time.h>. We'll just have to
54  * define it ourselves.
55  */
56 #ifndef CLOCK_BOOTTIME
57 # define CLOCK_BOOTTIME 7
58 #endif
59
60 static int read_models(unsigned int numcpus, uv_cpu_info_t* ci);
61 static int read_times(unsigned int numcpus, uv_cpu_info_t* ci);
62 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci);
63 static unsigned long read_cpufreq(unsigned int cpunum);
64
65
66 int uv__platform_loop_init(uv_loop_t* loop, int default_loop) {
67   int fd;
68
69   fd = uv__epoll_create1(UV__EPOLL_CLOEXEC);
70
71   /* epoll_create1() can fail either because it's not implemented (old kernel)
72    * or because it doesn't understand the EPOLL_CLOEXEC flag.
73    */
74   if (fd == -1 && (errno == ENOSYS || errno == EINVAL)) {
75     fd = uv__epoll_create(256);
76
77     if (fd != -1)
78       uv__cloexec(fd, 1);
79   }
80
81   loop->backend_fd = fd;
82   loop->inotify_fd = -1;
83   loop->inotify_watchers = NULL;
84
85   if (fd == -1)
86     return -1;
87
88   return 0;
89 }
90
91
92 void uv__platform_loop_delete(uv_loop_t* loop) {
93   if (loop->inotify_fd == -1) return;
94   uv__io_stop(loop, &loop->inotify_read_watcher, UV__POLLIN);
95   close(loop->inotify_fd);
96   loop->inotify_fd = -1;
97 }
98
99
100 void uv__platform_invalidate_fd(uv_loop_t* loop, int fd) {
101   struct uv__epoll_event* events;
102   uintptr_t i;
103   uintptr_t nfds;
104
105   assert(loop->watchers != NULL);
106
107   events = (struct uv__epoll_event*) loop->watchers[loop->nwatchers];
108   nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
109   if (events == NULL)
110     return;
111
112   /* Invalidate events with same file descriptor */
113   for (i = 0; i < nfds; i++)
114     if ((int) events[i].data == fd)
115       events[i].data = -1;
116 }
117
118
119 void uv__io_poll(uv_loop_t* loop, int timeout) {
120   struct uv__epoll_event events[1024];
121   struct uv__epoll_event* pe;
122   struct uv__epoll_event e;
123   ngx_queue_t* q;
124   uv__io_t* w;
125   uint64_t base;
126   uint64_t diff;
127   int nevents;
128   int count;
129   int nfds;
130   int fd;
131   int op;
132   int i;
133
134   if (loop->nfds == 0) {
135     assert(ngx_queue_empty(&loop->watcher_queue));
136     return;
137   }
138
139   while (!ngx_queue_empty(&loop->watcher_queue)) {
140     q = ngx_queue_head(&loop->watcher_queue);
141     ngx_queue_remove(q);
142     ngx_queue_init(q);
143
144     w = ngx_queue_data(q, uv__io_t, watcher_queue);
145     assert(w->pevents != 0);
146     assert(w->fd >= 0);
147     assert(w->fd < (int) loop->nwatchers);
148
149     e.events = w->pevents;
150     e.data = w->fd;
151
152     if (w->events == 0)
153       op = UV__EPOLL_CTL_ADD;
154     else
155       op = UV__EPOLL_CTL_MOD;
156
157     /* XXX Future optimization: do EPOLL_CTL_MOD lazily if we stop watching
158      * events, skip the syscall and squelch the events after epoll_wait().
159      */
160     if (uv__epoll_ctl(loop->backend_fd, op, w->fd, &e)) {
161       if (errno != EEXIST)
162         abort();
163
164       assert(op == UV__EPOLL_CTL_ADD);
165
166       /* We've reactivated a file descriptor that's been watched before. */
167       if (uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_MOD, w->fd, &e))
168         abort();
169     }
170
171     w->events = w->pevents;
172   }
173
174   assert(timeout >= -1);
175   base = loop->time;
176   count = 48; /* Benchmarks suggest this gives the best throughput. */
177
178   for (;;) {
179     nfds = uv__epoll_wait(loop->backend_fd,
180                           events,
181                           ARRAY_SIZE(events),
182                           timeout);
183
184     /* Update loop->time unconditionally. It's tempting to skip the update when
185      * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
186      * operating system didn't reschedule our process while in the syscall.
187      */
188     SAVE_ERRNO(uv__update_time(loop));
189
190     if (nfds == 0) {
191       assert(timeout != -1);
192       return;
193     }
194
195     if (nfds == -1) {
196       if (errno != EINTR)
197         abort();
198
199       if (timeout == -1)
200         continue;
201
202       if (timeout == 0)
203         return;
204
205       /* Interrupted by a signal. Update timeout and poll again. */
206       goto update_timeout;
207     }
208
209     nevents = 0;
210
211     assert(loop->watchers != NULL);
212     loop->watchers[loop->nwatchers] = (void*) events;
213     loop->watchers[loop->nwatchers + 1] = (void*) (uintptr_t) nfds;
214     for (i = 0; i < nfds; i++) {
215       pe = events + i;
216       fd = pe->data;
217
218       /* Skip invalidated events, see uv__platform_invalidate_fd */
219       if (fd == -1)
220         continue;
221
222       assert(fd >= 0);
223       assert((unsigned) fd < loop->nwatchers);
224
225       w = loop->watchers[fd];
226
227       if (w == NULL) {
228         /* File descriptor that we've stopped watching, disarm it.
229          *
230          * Ignore all errors because we may be racing with another thread
231          * when the file descriptor is closed.
232          */
233         uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, pe);
234         continue;
235       }
236
237       /* Give users only events they're interested in. Prevents spurious
238        * callbacks when previous callback invocation in this loop has stopped
239        * the current watcher. Also, filters out events that users has not
240        * requested us to watch.
241        */
242       pe->events &= w->pevents | UV__POLLERR | UV__POLLHUP;
243
244       /* Work around an epoll quirk where it sometimes reports just the
245        * EPOLLERR or EPOLLHUP event.  In order to force the event loop to
246        * move forward, we merge in the read/write events that the watcher
247        * is interested in; uv__read() and uv__write() will then deal with
248        * the error or hangup in the usual fashion.
249        *
250        * Note to self: happens when epoll reports EPOLLIN|EPOLLHUP, the user
251        * reads the available data, calls uv_read_stop(), then sometime later
252        * calls uv_read_start() again.  By then, libuv has forgotten about the
253        * hangup and the kernel won't report EPOLLIN again because there's
254        * nothing left to read.  If anything, libuv is to blame here.  The
255        * current hack is just a quick bandaid; to properly fix it, libuv
256        * needs to remember the error/hangup event.  We should get that for
257        * free when we switch over to edge-triggered I/O.
258        */
259       if (pe->events == UV__EPOLLERR || pe->events == UV__EPOLLHUP)
260         pe->events |= w->pevents & (UV__EPOLLIN | UV__EPOLLOUT);
261
262       if (pe->events != 0) {
263         w->cb(loop, w, pe->events);
264         nevents++;
265       }
266     }
267     loop->watchers[loop->nwatchers] = NULL;
268     loop->watchers[loop->nwatchers + 1] = NULL;
269
270     if (nevents != 0) {
271       if (nfds == ARRAY_SIZE(events) && --count != 0) {
272         /* Poll for more events but don't block this time. */
273         timeout = 0;
274         continue;
275       }
276       return;
277     }
278
279     if (timeout == 0)
280       return;
281
282     if (timeout == -1)
283       continue;
284
285 update_timeout:
286     assert(timeout > 0);
287
288     diff = loop->time - base;
289     if (diff >= (uint64_t) timeout)
290       return;
291
292     timeout -= diff;
293   }
294 }
295
296
297 uint64_t uv__hrtime(void) {
298   struct timespec ts;
299   clock_gettime(CLOCK_MONOTONIC, &ts);
300   return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
301 }
302
303
304 void uv_loadavg(double avg[3]) {
305   struct sysinfo info;
306
307   if (sysinfo(&info) < 0) return;
308
309   avg[0] = (double) info.loads[0] / 65536.0;
310   avg[1] = (double) info.loads[1] / 65536.0;
311   avg[2] = (double) info.loads[2] / 65536.0;
312 }
313
314
315 int uv_exepath(char* buffer, size_t* size) {
316   ssize_t n;
317
318   if (!buffer || !size) {
319     return -1;
320   }
321
322   n = readlink("/proc/self/exe", buffer, *size - 1);
323   if (n <= 0) return -1;
324   buffer[n] = '\0';
325   *size = n;
326
327   return 0;
328 }
329
330
331 uint64_t uv_get_free_memory(void) {
332   return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
333 }
334
335
336 uint64_t uv_get_total_memory(void) {
337   return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
338 }
339
340
341 uv_err_t uv_resident_set_memory(size_t* rss) {
342   char buf[1024];
343   const char* s;
344   ssize_t n;
345   long val;
346   int fd;
347   int i;
348
349   do
350     fd = open("/proc/self/stat", O_RDONLY);
351   while (fd == -1 && errno == EINTR);
352
353   if (fd == -1)
354     return uv__new_sys_error(errno);
355
356   do
357     n = read(fd, buf, sizeof(buf) - 1);
358   while (n == -1 && errno == EINTR);
359
360   SAVE_ERRNO(close(fd));
361   if (n == -1)
362     return uv__new_sys_error(errno);
363   buf[n] = '\0';
364
365   s = strchr(buf, ' ');
366   if (s == NULL)
367     goto err;
368
369   s += 1;
370   if (*s != '(')
371     goto err;
372
373   s = strchr(s, ')');
374   if (s == NULL)
375     goto err;
376
377   for (i = 1; i <= 22; i++) {
378     s = strchr(s + 1, ' ');
379     if (s == NULL)
380       goto err;
381   }
382
383   errno = 0;
384   val = strtol(s, NULL, 10);
385   if (errno != 0)
386     goto err;
387   if (val < 0)
388     goto err;
389
390   *rss = val * getpagesize();
391   return uv_ok_;
392
393 err:
394   return uv__new_artificial_error(UV_EINVAL);
395 }
396
397
398 uv_err_t uv_uptime(double* uptime) {
399   static volatile int no_clock_boottime;
400   struct timespec now;
401   int r;
402
403   /* Try CLOCK_BOOTTIME first, fall back to CLOCK_MONOTONIC if not available
404    * (pre-2.6.39 kernels). CLOCK_MONOTONIC doesn't increase when the system
405    * is suspended.
406    */
407   if (no_clock_boottime) {
408     retry: r = clock_gettime(CLOCK_MONOTONIC, &now);
409   }
410   else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
411     no_clock_boottime = 1;
412     goto retry;
413   }
414
415   if (r)
416     return uv__new_sys_error(errno);
417
418   *uptime = now.tv_sec;
419   *uptime += (double)now.tv_nsec / 1000000000.0;
420   return uv_ok_;
421 }
422
423
424 uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
425   unsigned int numcpus;
426   uv_cpu_info_t* ci;
427
428   *cpu_infos = NULL;
429   *count = 0;
430
431   numcpus = sysconf(_SC_NPROCESSORS_ONLN);
432   assert(numcpus != (unsigned int) -1);
433   assert(numcpus != 0);
434
435   ci = calloc(numcpus, sizeof(*ci));
436   if (ci == NULL)
437     return uv__new_sys_error(ENOMEM);
438
439   if (read_models(numcpus, ci)) {
440     SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
441     return uv__new_sys_error(errno);
442   }
443
444   if (read_times(numcpus, ci)) {
445     SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
446     return uv__new_sys_error(errno);
447   }
448
449   /* read_models() on x86 also reads the CPU speed from /proc/cpuinfo.
450    * We don't check for errors here. Worst case, the field is left zero.
451    */
452   if (ci[0].speed == 0)
453     read_speeds(numcpus, ci);
454
455   *cpu_infos = ci;
456   *count = numcpus;
457
458   return uv_ok_;
459 }
460
461
462 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
463   unsigned int num;
464
465   for (num = 0; num < numcpus; num++)
466     ci[num].speed = read_cpufreq(num) / 1000;
467 }
468
469
470 /* Also reads the CPU frequency on x86. The other architectures only have
471  * a BogoMIPS field, which may not be very accurate.
472  *
473  * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
474  */
475 static int read_models(unsigned int numcpus, uv_cpu_info_t* ci) {
476   static const char model_marker[] = "model name\t: ";
477   static const char speed_marker[] = "cpu MHz\t\t: ";
478   const char* inferred_model;
479   unsigned int model_idx;
480   unsigned int speed_idx;
481   char buf[1024];
482   char* model;
483   FILE* fp;
484
485   /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
486   (void) &model_marker;
487   (void) &speed_marker;
488   (void) &speed_idx;
489   (void) &model;
490   (void) &buf;
491   (void) &fp;
492
493   model_idx = 0;
494   speed_idx = 0;
495
496 #if defined(__arm__) || \
497     defined(__i386__) || \
498     defined(__mips__) || \
499     defined(__x86_64__)
500   fp = fopen("/proc/cpuinfo", "r");
501   if (fp == NULL)
502     return -1;
503
504   while (fgets(buf, sizeof(buf), fp)) {
505     if (model_idx < numcpus) {
506       if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
507         model = buf + sizeof(model_marker) - 1;
508         model = strndup(model, strlen(model) - 1);  /* Strip newline. */
509         if (model == NULL) {
510           fclose(fp);
511           return -1;
512         }
513         ci[model_idx++].model = model;
514         continue;
515       }
516     }
517 #if defined(__arm__) || defined(__mips__)
518     if (model_idx < numcpus) {
519 #if defined(__arm__)
520       /* Fallback for pre-3.8 kernels. */
521       static const char model_marker[] = "Processor\t: ";
522 #else   /* defined(__mips__) */
523       static const char model_marker[] = "cpu model\t\t: ";
524 #endif
525       if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
526         model = buf + sizeof(model_marker) - 1;
527         model = strndup(model, strlen(model) - 1);  /* Strip newline. */
528         if (model == NULL) {
529           fclose(fp);
530           return -1;
531         }
532         ci[model_idx++].model = model;
533         continue;
534       }
535     }
536 #else  /* !__arm__ && !__mips__ */
537     if (speed_idx < numcpus) {
538       if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
539         ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
540         continue;
541       }
542     }
543 #endif  /* __arm__ || __mips__ */
544   }
545
546   fclose(fp);
547 #endif  /* __arm__ || __i386__ || __mips__ || __x86_64__ */
548
549   /* Now we want to make sure that all the models contain *something* because
550    * it's not safe to leave them as null. Copy the last entry unless there
551    * isn't one, in that case we simply put "unknown" into everything.
552    */
553   inferred_model = "unknown";
554   if (model_idx > 0)
555     inferred_model = ci[model_idx - 1].model;
556
557   while (model_idx < numcpus) {
558     model = strndup(inferred_model, strlen(inferred_model));
559     if (model == NULL)
560       return -1;
561     ci[model_idx++].model = model;
562   }
563
564   return 0;
565 }
566
567
568 static int read_times(unsigned int numcpus, uv_cpu_info_t* ci) {
569   unsigned long clock_ticks;
570   struct uv_cpu_times_s ts;
571   unsigned long user;
572   unsigned long nice;
573   unsigned long sys;
574   unsigned long idle;
575   unsigned long dummy;
576   unsigned long irq;
577   unsigned int num;
578   unsigned int len;
579   char buf[1024];
580   FILE* fp;
581
582   clock_ticks = sysconf(_SC_CLK_TCK);
583   assert(clock_ticks != (unsigned long) -1);
584   assert(clock_ticks != 0);
585
586   fp = fopen("/proc/stat", "r");
587   if (fp == NULL)
588     return -1;
589
590   if (!fgets(buf, sizeof(buf), fp))
591     abort();
592
593   num = 0;
594
595   while (fgets(buf, sizeof(buf), fp)) {
596     if (num >= numcpus)
597       break;
598
599     if (strncmp(buf, "cpu", 3))
600       break;
601
602     /* skip "cpu<num> " marker */
603     {
604       unsigned int n = num;
605       for (len = sizeof("cpu0"); n /= 10; len++);
606       assert(sscanf(buf, "cpu%u ", &n) == 1 && n == num);
607     }
608
609     /* Line contains user, nice, system, idle, iowait, irq, softirq, steal,
610      * guest, guest_nice but we're only interested in the first four + irq.
611      *
612      * Don't use %*s to skip fields or %ll to read straight into the uint64_t
613      * fields, they're not allowed in C89 mode.
614      */
615     if (6 != sscanf(buf + len,
616                     "%lu %lu %lu %lu %lu %lu",
617                     &user,
618                     &nice,
619                     &sys,
620                     &idle,
621                     &dummy,
622                     &irq))
623       abort();
624
625     ts.user = clock_ticks * user;
626     ts.nice = clock_ticks * nice;
627     ts.sys  = clock_ticks * sys;
628     ts.idle = clock_ticks * idle;
629     ts.irq  = clock_ticks * irq;
630     ci[num++].cpu_times = ts;
631   }
632   fclose(fp);
633
634   return 0;
635 }
636
637
638 static unsigned long read_cpufreq(unsigned int cpunum) {
639   unsigned long val;
640   char buf[1024];
641   FILE* fp;
642
643   snprintf(buf,
644            sizeof(buf),
645            "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
646            cpunum);
647
648   fp = fopen(buf, "r");
649   if (fp == NULL)
650     return 0;
651
652   if (fscanf(fp, "%lu", &val) != 1)
653     val = 0;
654
655   fclose(fp);
656
657   return val;
658 }
659
660
661 void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
662   int i;
663
664   for (i = 0; i < count; i++) {
665     free(cpu_infos[i].model);
666   }
667
668   free(cpu_infos);
669 }
670
671
672 uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
673   int* count) {
674 #ifndef HAVE_IFADDRS_H
675   return uv__new_artificial_error(UV_ENOSYS);
676 #else
677   struct ifaddrs *addrs, *ent;
678   char ip[INET6_ADDRSTRLEN];
679   uv_interface_address_t* address;
680
681   if (getifaddrs(&addrs) != 0) {
682     return uv__new_sys_error(errno);
683   }
684
685   *count = 0;
686
687   /* Count the number of interfaces */
688   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
689     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING) ||
690         (ent->ifa_addr == NULL) ||
691         (ent->ifa_addr->sa_family == PF_PACKET)) {
692       continue;
693     }
694
695     (*count)++;
696   }
697
698   *addresses = (uv_interface_address_t*)
699     malloc(*count * sizeof(uv_interface_address_t));
700   if (!(*addresses)) {
701     return uv__new_artificial_error(UV_ENOMEM);
702   }
703
704   address = *addresses;
705
706   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
707     bzero(&ip, sizeof (ip));
708     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING)) {
709       continue;
710     }
711
712     if (ent->ifa_addr == NULL) {
713       continue;
714     }
715
716     /*
717      * On Linux getifaddrs returns information related to the raw underlying
718      * devices. We're not interested in this information.
719      */
720     if (ent->ifa_addr->sa_family == PF_PACKET) {
721       continue;
722     }
723
724     address->name = strdup(ent->ifa_name);
725
726     if (ent->ifa_addr->sa_family == AF_INET6) {
727       address->address.address6 = *((struct sockaddr_in6 *)ent->ifa_addr);
728     } else {
729       address->address.address4 = *((struct sockaddr_in *)ent->ifa_addr);
730     }
731
732     address->is_internal = ent->ifa_flags & IFF_LOOPBACK ? 1 : 0;
733
734     address++;
735   }
736
737   freeifaddrs(addrs);
738
739   return uv_ok_;
740 #endif
741 }
742
743
744 void uv_free_interface_addresses(uv_interface_address_t* addresses,
745   int count) {
746   int i;
747
748   for (i = 0; i < count; i++) {
749     free(addresses[i].name);
750   }
751
752   free(addresses);
753 }
754
755
756 void uv__set_process_title(const char* title) {
757 #if defined(PR_SET_NAME)
758   prctl(PR_SET_NAME, title);  /* Only copies first 16 characters. */
759 #endif
760 }