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:
9 * The above copyright notice and this permission notice shall be included in
10 * all copies or substantial portions of the Software.
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
32 #include <sys/param.h>
33 #include <sys/prctl.h>
34 #include <sys/sysinfo.h>
39 #define HAVE_IFADDRS_H 1
41 # if __UCLIBC_MAJOR__ < 0 || __UCLIBC_MINOR__ < 9 || __UCLIBC_SUBLEVEL__ < 32
42 # undef HAVE_IFADDRS_H
50 #define NANOSEC ((uint64_t) 1e9)
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.
56 #ifndef CLOCK_BOOTTIME
57 # define CLOCK_BOOTTIME 7
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);
66 int uv__platform_loop_init(uv_loop_t* loop, int default_loop) {
69 fd = uv__epoll_create1(UV__EPOLL_CLOEXEC);
71 /* epoll_create1() can fail either because it's not implemented (old kernel)
72 * or because it doesn't understand the EPOLL_CLOEXEC flag.
74 if (fd == -1 && (errno == ENOSYS || errno == EINVAL)) {
75 fd = uv__epoll_create(256);
81 loop->backend_fd = fd;
82 loop->inotify_fd = -1;
83 loop->inotify_watchers = NULL;
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;
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;
115 if (loop->nfds == 0) {
116 assert(ngx_queue_empty(&loop->watcher_queue));
120 while (!ngx_queue_empty(&loop->watcher_queue)) {
121 q = ngx_queue_head(&loop->watcher_queue);
125 w = ngx_queue_data(q, uv__io_t, watcher_queue);
126 assert(w->pevents != 0);
128 assert(w->fd < (int) loop->nwatchers);
130 e.events = w->pevents;
134 op = UV__EPOLL_CTL_ADD;
136 op = UV__EPOLL_CTL_MOD;
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().
141 if (uv__epoll_ctl(loop->backend_fd, op, w->fd, &e)) {
145 assert(op == UV__EPOLL_CTL_ADD);
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))
152 w->events = w->pevents;
155 assert(timeout >= -1);
157 count = 48; /* Benchmarks suggest this gives the best throughput. */
160 nfds = uv__epoll_wait(loop->backend_fd,
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.
169 SAVE_ERRNO(uv__update_time(loop));
172 assert(timeout != -1);
186 /* Interrupted by a signal. Update timeout and poll again. */
192 for (i = 0; i < nfds; i++) {
197 assert((unsigned) fd < loop->nwatchers);
199 w = loop->watchers[fd];
202 /* File descriptor that we've stopped watching, disarm it.
204 * Ignore all errors because we may be racing with another thread
205 * when the file descriptor is closed.
207 uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, pe);
211 w->cb(loop, w, pe->events);
216 if (nfds == ARRAY_SIZE(events) && --count != 0) {
217 /* Poll for more events but don't block this time. */
233 diff = loop->time - base;
234 if (diff >= (uint64_t) timeout)
242 uint64_t uv__hrtime(void) {
244 clock_gettime(CLOCK_MONOTONIC, &ts);
245 return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
249 void uv_loadavg(double avg[3]) {
252 if (sysinfo(&info) < 0) return;
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;
260 int uv_exepath(char* buffer, size_t* size) {
263 if (!buffer || !size) {
267 n = readlink("/proc/self/exe", buffer, *size - 1);
268 if (n <= 0) return -1;
276 uint64_t uv_get_free_memory(void) {
277 return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
281 uint64_t uv_get_total_memory(void) {
282 return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
286 uv_err_t uv_resident_set_memory(size_t* rss) {
295 fd = open("/proc/self/stat", O_RDONLY);
296 while (fd == -1 && errno == EINTR);
299 return uv__new_sys_error(errno);
302 n = read(fd, buf, sizeof(buf) - 1);
303 while (n == -1 && errno == EINTR);
305 SAVE_ERRNO(close(fd));
307 return uv__new_sys_error(errno);
310 s = strchr(buf, ' ');
322 for (i = 1; i <= 22; i++) {
323 s = strchr(s + 1, ' ');
329 val = strtol(s, NULL, 10);
335 *rss = val * getpagesize();
339 return uv__new_artificial_error(UV_EINVAL);
343 uv_err_t uv_uptime(double* uptime) {
344 static volatile int no_clock_boottime;
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
352 if (no_clock_boottime) {
353 retry: r = clock_gettime(CLOCK_MONOTONIC, &now);
355 else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
356 no_clock_boottime = 1;
361 return uv__new_sys_error(errno);
363 *uptime = now.tv_sec;
364 *uptime += (double)now.tv_nsec / 1000000000.0;
369 uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
370 unsigned int numcpus;
376 numcpus = sysconf(_SC_NPROCESSORS_ONLN);
377 assert(numcpus != (unsigned int) -1);
378 assert(numcpus != 0);
380 ci = calloc(numcpus, sizeof(*ci));
382 return uv__new_sys_error(ENOMEM);
384 if (read_models(numcpus, ci)) {
385 SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
386 return uv__new_sys_error(errno);
389 if (read_times(numcpus, ci)) {
390 SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
391 return uv__new_sys_error(errno);
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.
397 if (ci[0].speed == 0)
398 read_speeds(numcpus, ci);
407 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
410 for (num = 0; num < numcpus; num++)
411 ci[num].speed = read_cpufreq(num) / 1000;
415 /* Also reads the CPU frequency on x86. The other architectures only have
416 * a BogoMIPS field, which may not be very accurate.
418 * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
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;
430 /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
431 (void) &model_marker;
432 (void) &speed_marker;
441 #if defined(__arm__) || \
442 defined(__i386__) || \
443 defined(__mips__) || \
445 fp = fopen("/proc/cpuinfo", "r");
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. */
458 ci[model_idx++].model = model;
462 #if defined(__arm__) || defined(__mips__)
463 if (model_idx < numcpus) {
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: ";
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. */
477 ci[model_idx++].model = model;
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);
488 #endif /* __arm__ || __mips__ */
492 #endif /* __arm__ || __i386__ || __mips__ || __x86_64__ */
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.
498 inferred_model = "unknown";
500 inferred_model = ci[model_idx - 1].model;
502 while (model_idx < numcpus) {
503 model = strndup(inferred_model, strlen(inferred_model));
506 ci[model_idx++].model = model;
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;
527 clock_ticks = sysconf(_SC_CLK_TCK);
528 assert(clock_ticks != (unsigned long) -1);
529 assert(clock_ticks != 0);
531 fp = fopen("/proc/stat", "r");
535 if (!fgets(buf, sizeof(buf), fp))
540 while (fgets(buf, sizeof(buf), fp)) {
544 if (strncmp(buf, "cpu", 3))
547 /* skip "cpu<num> " marker */
549 unsigned int n = num;
550 for (len = sizeof("cpu0"); n /= 10; len++);
551 assert(sscanf(buf, "cpu%u ", &n) == 1 && n == num);
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.
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.
560 if (6 != sscanf(buf + len,
561 "%lu %lu %lu %lu %lu %lu",
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;
583 static unsigned long read_cpufreq(unsigned int cpunum) {
590 "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
593 fp = fopen(buf, "r");
597 if (fscanf(fp, "%lu", &val) != 1)
606 void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
609 for (i = 0; i < count; i++) {
610 free(cpu_infos[i].model);
617 uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
619 #ifndef HAVE_IFADDRS_H
620 return uv__new_artificial_error(UV_ENOSYS);
622 struct ifaddrs *addrs, *ent;
623 char ip[INET6_ADDRSTRLEN];
624 uv_interface_address_t* address;
626 if (getifaddrs(&addrs) != 0) {
627 return uv__new_sys_error(errno);
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)) {
643 *addresses = (uv_interface_address_t*)
644 malloc(*count * sizeof(uv_interface_address_t));
646 return uv__new_artificial_error(UV_ENOMEM);
649 address = *addresses;
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)) {
657 if (ent->ifa_addr == NULL) {
662 * On Linux getifaddrs returns information related to the raw underlying
663 * devices. We're not interested in this information.
665 if (ent->ifa_addr->sa_family == PF_PACKET) {
669 address->name = strdup(ent->ifa_name);
671 if (ent->ifa_addr->sa_family == AF_INET6) {
672 address->address.address6 = *((struct sockaddr_in6 *)ent->ifa_addr);
674 address->address.address4 = *((struct sockaddr_in *)ent->ifa_addr);
677 address->is_internal = ent->ifa_flags & IFF_LOOPBACK ? 1 : 0;
689 void uv_free_interface_addresses(uv_interface_address_t* addresses,
693 for (i = 0; i < count; i++) {
694 free(addresses[i].name);
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. */