e4c34a180837041771f7fe508ec6d7b33c272768
[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__io_poll(uv_loop_t* loop, int timeout) {
101   struct uv__epoll_event events[1024];
102   struct uv__epoll_event* pe;
103   struct uv__epoll_event e;
104   ngx_queue_t* q;
105   uv__io_t* w;
106   uint64_t base;
107   uint64_t diff;
108   int nevents;
109   int count;
110   int nfds;
111   int fd;
112   int op;
113   int i;
114
115   if (loop->nfds == 0) {
116     assert(ngx_queue_empty(&loop->watcher_queue));
117     return;
118   }
119
120   while (!ngx_queue_empty(&loop->watcher_queue)) {
121     q = ngx_queue_head(&loop->watcher_queue);
122     ngx_queue_remove(q);
123     ngx_queue_init(q);
124
125     w = ngx_queue_data(q, uv__io_t, watcher_queue);
126     assert(w->pevents != 0);
127     assert(w->fd >= 0);
128     assert(w->fd < (int) loop->nwatchers);
129
130     e.events = w->pevents;
131     e.data = w->fd;
132
133     if (w->events == 0)
134       op = UV__EPOLL_CTL_ADD;
135     else
136       op = UV__EPOLL_CTL_MOD;
137
138     /* XXX Future optimization: do EPOLL_CTL_MOD lazily if we stop watching
139      * events, skip the syscall and squelch the events after epoll_wait().
140      */
141     if (uv__epoll_ctl(loop->backend_fd, op, w->fd, &e)) {
142       if (errno != EEXIST)
143         abort();
144
145       assert(op == UV__EPOLL_CTL_ADD);
146
147       /* We've reactivated a file descriptor that's been watched before. */
148       if (uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_MOD, w->fd, &e))
149         abort();
150     }
151
152     w->events = w->pevents;
153   }
154
155   assert(timeout >= -1);
156   base = loop->time;
157   count = 48; /* Benchmarks suggest this gives the best throughput. */
158
159   for (;;) {
160     nfds = uv__epoll_wait(loop->backend_fd,
161                           events,
162                           ARRAY_SIZE(events),
163                           timeout);
164
165     /* Update loop->time unconditionally. It's tempting to skip the update when
166      * timeout == 0 (i.e. non-blocking poll) but there is no guarantee that the
167      * operating system didn't reschedule our process while in the syscall.
168      */
169     SAVE_ERRNO(uv__update_time(loop));
170
171     if (nfds == 0) {
172       assert(timeout != -1);
173       return;
174     }
175
176     if (nfds == -1) {
177       if (errno != EINTR)
178         abort();
179
180       if (timeout == -1)
181         continue;
182
183       if (timeout == 0)
184         return;
185
186       /* Interrupted by a signal. Update timeout and poll again. */
187       goto update_timeout;
188     }
189
190     nevents = 0;
191
192     for (i = 0; i < nfds; i++) {
193       pe = events + i;
194       fd = pe->data;
195
196       assert(fd >= 0);
197       assert((unsigned) fd < loop->nwatchers);
198
199       w = loop->watchers[fd];
200
201       if (w == NULL) {
202         /* File descriptor that we've stopped watching, disarm it.
203          *
204          * Ignore all errors because we may be racing with another thread
205          * when the file descriptor is closed.
206          */
207         uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, pe);
208         continue;
209       }
210
211       w->cb(loop, w, pe->events);
212       nevents++;
213     }
214
215     if (nevents != 0) {
216       if (nfds == ARRAY_SIZE(events) && --count != 0) {
217         /* Poll for more events but don't block this time. */
218         timeout = 0;
219         continue;
220       }
221       return;
222     }
223
224     if (timeout == 0)
225       return;
226
227     if (timeout == -1)
228       continue;
229
230 update_timeout:
231     assert(timeout > 0);
232
233     diff = loop->time - base;
234     if (diff >= (uint64_t) timeout)
235       return;
236
237     timeout -= diff;
238   }
239 }
240
241
242 uint64_t uv__hrtime(void) {
243   struct timespec ts;
244   clock_gettime(CLOCK_MONOTONIC, &ts);
245   return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
246 }
247
248
249 void uv_loadavg(double avg[3]) {
250   struct sysinfo info;
251
252   if (sysinfo(&info) < 0) return;
253
254   avg[0] = (double) info.loads[0] / 65536.0;
255   avg[1] = (double) info.loads[1] / 65536.0;
256   avg[2] = (double) info.loads[2] / 65536.0;
257 }
258
259
260 int uv_exepath(char* buffer, size_t* size) {
261   ssize_t n;
262
263   if (!buffer || !size) {
264     return -1;
265   }
266
267   n = readlink("/proc/self/exe", buffer, *size - 1);
268   if (n <= 0) return -1;
269   buffer[n] = '\0';
270   *size = n;
271
272   return 0;
273 }
274
275
276 uint64_t uv_get_free_memory(void) {
277   return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
278 }
279
280
281 uint64_t uv_get_total_memory(void) {
282   return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
283 }
284
285
286 uv_err_t uv_resident_set_memory(size_t* rss) {
287   char buf[1024];
288   const char* s;
289   ssize_t n;
290   long val;
291   int fd;
292   int i;
293
294   do
295     fd = open("/proc/self/stat", O_RDONLY);
296   while (fd == -1 && errno == EINTR);
297
298   if (fd == -1)
299     return uv__new_sys_error(errno);
300
301   do
302     n = read(fd, buf, sizeof(buf) - 1);
303   while (n == -1 && errno == EINTR);
304
305   SAVE_ERRNO(close(fd));
306   if (n == -1)
307     return uv__new_sys_error(errno);
308   buf[n] = '\0';
309
310   s = strchr(buf, ' ');
311   if (s == NULL)
312     goto err;
313
314   s += 1;
315   if (*s != '(')
316     goto err;
317
318   s = strchr(s, ')');
319   if (s == NULL)
320     goto err;
321
322   for (i = 1; i <= 22; i++) {
323     s = strchr(s + 1, ' ');
324     if (s == NULL)
325       goto err;
326   }
327
328   errno = 0;
329   val = strtol(s, NULL, 10);
330   if (errno != 0)
331     goto err;
332   if (val < 0)
333     goto err;
334
335   *rss = val * getpagesize();
336   return uv_ok_;
337
338 err:
339   return uv__new_artificial_error(UV_EINVAL);
340 }
341
342
343 uv_err_t uv_uptime(double* uptime) {
344   static volatile int no_clock_boottime;
345   struct timespec now;
346   int r;
347
348   /* Try CLOCK_BOOTTIME first, fall back to CLOCK_MONOTONIC if not available
349    * (pre-2.6.39 kernels). CLOCK_MONOTONIC doesn't increase when the system
350    * is suspended.
351    */
352   if (no_clock_boottime) {
353     retry: r = clock_gettime(CLOCK_MONOTONIC, &now);
354   }
355   else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
356     no_clock_boottime = 1;
357     goto retry;
358   }
359
360   if (r)
361     return uv__new_sys_error(errno);
362
363   *uptime = now.tv_sec;
364   *uptime += (double)now.tv_nsec / 1000000000.0;
365   return uv_ok_;
366 }
367
368
369 uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
370   unsigned int numcpus;
371   uv_cpu_info_t* ci;
372
373   *cpu_infos = NULL;
374   *count = 0;
375
376   numcpus = sysconf(_SC_NPROCESSORS_ONLN);
377   assert(numcpus != (unsigned int) -1);
378   assert(numcpus != 0);
379
380   ci = calloc(numcpus, sizeof(*ci));
381   if (ci == NULL)
382     return uv__new_sys_error(ENOMEM);
383
384   if (read_models(numcpus, ci)) {
385     SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
386     return uv__new_sys_error(errno);
387   }
388
389   if (read_times(numcpus, ci)) {
390     SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
391     return uv__new_sys_error(errno);
392   }
393
394   /* read_models() on x86 also reads the CPU speed from /proc/cpuinfo.
395    * We don't check for errors here. Worst case, the field is left zero.
396    */
397   if (ci[0].speed == 0)
398     read_speeds(numcpus, ci);
399
400   *cpu_infos = ci;
401   *count = numcpus;
402
403   return uv_ok_;
404 }
405
406
407 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
408   unsigned int num;
409
410   for (num = 0; num < numcpus; num++)
411     ci[num].speed = read_cpufreq(num) / 1000;
412 }
413
414
415 /* Also reads the CPU frequency on x86. The other architectures only have
416  * a BogoMIPS field, which may not be very accurate.
417  *
418  * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
419  */
420 static int read_models(unsigned int numcpus, uv_cpu_info_t* ci) {
421   static const char model_marker[] = "model name\t: ";
422   static const char speed_marker[] = "cpu MHz\t\t: ";
423   const char* inferred_model;
424   unsigned int model_idx;
425   unsigned int speed_idx;
426   char buf[1024];
427   char* model;
428   FILE* fp;
429
430   /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
431   (void) &model_marker;
432   (void) &speed_marker;
433   (void) &speed_idx;
434   (void) &model;
435   (void) &buf;
436   (void) &fp;
437
438   model_idx = 0;
439   speed_idx = 0;
440
441 #if defined(__arm__) || \
442     defined(__i386__) || \
443     defined(__mips__) || \
444     defined(__x86_64__)
445   fp = fopen("/proc/cpuinfo", "r");
446   if (fp == NULL)
447     return -1;
448
449   while (fgets(buf, sizeof(buf), fp)) {
450     if (model_idx < numcpus) {
451       if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
452         model = buf + sizeof(model_marker) - 1;
453         model = strndup(model, strlen(model) - 1);  /* Strip newline. */
454         if (model == NULL) {
455           fclose(fp);
456           return -1;
457         }
458         ci[model_idx++].model = model;
459         continue;
460       }
461     }
462 #if defined(__arm__) || defined(__mips__)
463     if (model_idx < numcpus) {
464 #if defined(__arm__)
465       /* Fallback for pre-3.8 kernels. */
466       static const char model_marker[] = "Processor\t: ";
467 #else   /* defined(__mips__) */
468       static const char model_marker[] = "cpu model\t\t: ";
469 #endif
470       if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
471         model = buf + sizeof(model_marker) - 1;
472         model = strndup(model, strlen(model) - 1);  /* Strip newline. */
473         if (model == NULL) {
474           fclose(fp);
475           return -1;
476         }
477         ci[model_idx++].model = model;
478         continue;
479       }
480     }
481 #else  /* !__arm__ && !__mips__ */
482     if (speed_idx < numcpus) {
483       if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
484         ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
485         continue;
486       }
487     }
488 #endif  /* __arm__ || __mips__ */
489   }
490
491   fclose(fp);
492 #endif  /* __arm__ || __i386__ || __mips__ || __x86_64__ */
493
494   /* Now we want to make sure that all the models contain *something* because
495    * it's not safe to leave them as null. Copy the last entry unless there
496    * isn't one, in that case we simply put "unknown" into everything.
497    */
498   inferred_model = "unknown";
499   if (model_idx > 0)
500     inferred_model = ci[model_idx - 1].model;
501
502   while (model_idx < numcpus) {
503     model = strndup(inferred_model, strlen(inferred_model));
504     if (model == NULL)
505       return -1;
506     ci[model_idx++].model = model;
507   }
508
509   return 0;
510 }
511
512
513 static int read_times(unsigned int numcpus, uv_cpu_info_t* ci) {
514   unsigned long clock_ticks;
515   struct uv_cpu_times_s ts;
516   unsigned long user;
517   unsigned long nice;
518   unsigned long sys;
519   unsigned long idle;
520   unsigned long dummy;
521   unsigned long irq;
522   unsigned int num;
523   unsigned int len;
524   char buf[1024];
525   FILE* fp;
526
527   clock_ticks = sysconf(_SC_CLK_TCK);
528   assert(clock_ticks != (unsigned long) -1);
529   assert(clock_ticks != 0);
530
531   fp = fopen("/proc/stat", "r");
532   if (fp == NULL)
533     return -1;
534
535   if (!fgets(buf, sizeof(buf), fp))
536     abort();
537
538   num = 0;
539
540   while (fgets(buf, sizeof(buf), fp)) {
541     if (num >= numcpus)
542       break;
543
544     if (strncmp(buf, "cpu", 3))
545       break;
546
547     /* skip "cpu<num> " marker */
548     {
549       unsigned int n = num;
550       for (len = sizeof("cpu0"); n /= 10; len++);
551       assert(sscanf(buf, "cpu%u ", &n) == 1 && n == num);
552     }
553
554     /* Line contains user, nice, system, idle, iowait, irq, softirq, steal,
555      * guest, guest_nice but we're only interested in the first four + irq.
556      *
557      * Don't use %*s to skip fields or %ll to read straight into the uint64_t
558      * fields, they're not allowed in C89 mode.
559      */
560     if (6 != sscanf(buf + len,
561                     "%lu %lu %lu %lu %lu %lu",
562                     &user,
563                     &nice,
564                     &sys,
565                     &idle,
566                     &dummy,
567                     &irq))
568       abort();
569
570     ts.user = clock_ticks * user;
571     ts.nice = clock_ticks * nice;
572     ts.sys  = clock_ticks * sys;
573     ts.idle = clock_ticks * idle;
574     ts.irq  = clock_ticks * irq;
575     ci[num++].cpu_times = ts;
576   }
577   fclose(fp);
578
579   return 0;
580 }
581
582
583 static unsigned long read_cpufreq(unsigned int cpunum) {
584   unsigned long val;
585   char buf[1024];
586   FILE* fp;
587
588   snprintf(buf,
589            sizeof(buf),
590            "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
591            cpunum);
592
593   fp = fopen(buf, "r");
594   if (fp == NULL)
595     return 0;
596
597   if (fscanf(fp, "%lu", &val) != 1)
598     val = 0;
599
600   fclose(fp);
601
602   return val;
603 }
604
605
606 void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
607   int i;
608
609   for (i = 0; i < count; i++) {
610     free(cpu_infos[i].model);
611   }
612
613   free(cpu_infos);
614 }
615
616
617 uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
618   int* count) {
619 #ifndef HAVE_IFADDRS_H
620   return uv__new_artificial_error(UV_ENOSYS);
621 #else
622   struct ifaddrs *addrs, *ent;
623   char ip[INET6_ADDRSTRLEN];
624   uv_interface_address_t* address;
625
626   if (getifaddrs(&addrs) != 0) {
627     return uv__new_sys_error(errno);
628   }
629
630   *count = 0;
631
632   /* Count the number of interfaces */
633   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
634     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING) ||
635         (ent->ifa_addr == NULL) ||
636         (ent->ifa_addr->sa_family == PF_PACKET)) {
637       continue;
638     }
639
640     (*count)++;
641   }
642
643   *addresses = (uv_interface_address_t*)
644     malloc(*count * sizeof(uv_interface_address_t));
645   if (!(*addresses)) {
646     return uv__new_artificial_error(UV_ENOMEM);
647   }
648
649   address = *addresses;
650
651   for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
652     bzero(&ip, sizeof (ip));
653     if (!(ent->ifa_flags & IFF_UP && ent->ifa_flags & IFF_RUNNING)) {
654       continue;
655     }
656
657     if (ent->ifa_addr == NULL) {
658       continue;
659     }
660
661     /*
662      * On Linux getifaddrs returns information related to the raw underlying
663      * devices. We're not interested in this information.
664      */
665     if (ent->ifa_addr->sa_family == PF_PACKET) {
666       continue;
667     }
668
669     address->name = strdup(ent->ifa_name);
670
671     if (ent->ifa_addr->sa_family == AF_INET6) {
672       address->address.address6 = *((struct sockaddr_in6 *)ent->ifa_addr);
673     } else {
674       address->address.address4 = *((struct sockaddr_in *)ent->ifa_addr);
675     }
676
677     address->is_internal = ent->ifa_flags & IFF_LOOPBACK ? 1 : 0;
678
679     address++;
680   }
681
682   freeifaddrs(addrs);
683
684   return uv_ok_;
685 #endif
686 }
687
688
689 void uv_free_interface_addresses(uv_interface_address_t* addresses,
690   int count) {
691   int i;
692
693   for (i = 0; i < count; i++) {
694     free(addresses[i].name);
695   }
696
697   free(addresses);
698 }
699
700
701 void uv__set_process_title(const char* title) {
702 #if defined(PR_SET_NAME)
703   prctl(PR_SET_NAME, title);  /* Only copies first 16 characters. */
704 #endif
705 }