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__platform_invalidate_fd(uv_loop_t* loop, int fd) {
101 struct uv__epoll_event* events;
105 assert(loop->watchers != NULL);
107 events = (struct uv__epoll_event*) loop->watchers[loop->nwatchers];
108 nfds = (uintptr_t) loop->watchers[loop->nwatchers + 1];
112 /* Invalidate events with same file descriptor */
113 for (i = 0; i < nfds; i++)
114 if ((int) events[i].data == fd)
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;
134 if (loop->nfds == 0) {
135 assert(ngx_queue_empty(&loop->watcher_queue));
139 while (!ngx_queue_empty(&loop->watcher_queue)) {
140 q = ngx_queue_head(&loop->watcher_queue);
144 w = ngx_queue_data(q, uv__io_t, watcher_queue);
145 assert(w->pevents != 0);
147 assert(w->fd < (int) loop->nwatchers);
149 e.events = w->pevents;
153 op = UV__EPOLL_CTL_ADD;
155 op = UV__EPOLL_CTL_MOD;
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().
160 if (uv__epoll_ctl(loop->backend_fd, op, w->fd, &e)) {
164 assert(op == UV__EPOLL_CTL_ADD);
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))
171 w->events = w->pevents;
174 assert(timeout >= -1);
176 count = 48; /* Benchmarks suggest this gives the best throughput. */
179 nfds = uv__epoll_wait(loop->backend_fd,
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.
188 SAVE_ERRNO(uv__update_time(loop));
191 assert(timeout != -1);
205 /* Interrupted by a signal. Update timeout and poll again. */
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++) {
218 /* Skip invalidated events, see uv__platform_invalidate_fd */
223 assert((unsigned) fd < loop->nwatchers);
225 w = loop->watchers[fd];
228 /* File descriptor that we've stopped watching, disarm it.
230 * Ignore all errors because we may be racing with another thread
231 * when the file descriptor is closed.
233 uv__epoll_ctl(loop->backend_fd, UV__EPOLL_CTL_DEL, fd, pe);
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.
242 pe->events &= w->pevents | UV__POLLERR | UV__POLLHUP;
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.
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.
259 if (pe->events == UV__EPOLLERR || pe->events == UV__EPOLLHUP)
260 pe->events |= w->pevents & (UV__EPOLLIN | UV__EPOLLOUT);
262 if (pe->events != 0) {
263 w->cb(loop, w, pe->events);
267 loop->watchers[loop->nwatchers] = NULL;
268 loop->watchers[loop->nwatchers + 1] = NULL;
271 if (nfds == ARRAY_SIZE(events) && --count != 0) {
272 /* Poll for more events but don't block this time. */
288 diff = loop->time - base;
289 if (diff >= (uint64_t) timeout)
297 uint64_t uv__hrtime(void) {
299 clock_gettime(CLOCK_MONOTONIC, &ts);
300 return (((uint64_t) ts.tv_sec) * NANOSEC + ts.tv_nsec);
304 void uv_loadavg(double avg[3]) {
307 if (sysinfo(&info) < 0) return;
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;
315 int uv_exepath(char* buffer, size_t* size) {
318 if (!buffer || !size) {
322 n = readlink("/proc/self/exe", buffer, *size - 1);
323 if (n <= 0) return -1;
331 uint64_t uv_get_free_memory(void) {
332 return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_AVPHYS_PAGES);
336 uint64_t uv_get_total_memory(void) {
337 return (uint64_t) sysconf(_SC_PAGESIZE) * sysconf(_SC_PHYS_PAGES);
341 uv_err_t uv_resident_set_memory(size_t* rss) {
350 fd = open("/proc/self/stat", O_RDONLY);
351 while (fd == -1 && errno == EINTR);
354 return uv__new_sys_error(errno);
357 n = read(fd, buf, sizeof(buf) - 1);
358 while (n == -1 && errno == EINTR);
360 SAVE_ERRNO(close(fd));
362 return uv__new_sys_error(errno);
365 s = strchr(buf, ' ');
377 for (i = 1; i <= 22; i++) {
378 s = strchr(s + 1, ' ');
384 val = strtol(s, NULL, 10);
390 *rss = val * getpagesize();
394 return uv__new_artificial_error(UV_EINVAL);
398 uv_err_t uv_uptime(double* uptime) {
399 static volatile int no_clock_boottime;
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
407 if (no_clock_boottime) {
408 retry: r = clock_gettime(CLOCK_MONOTONIC, &now);
410 else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
411 no_clock_boottime = 1;
416 return uv__new_sys_error(errno);
418 *uptime = now.tv_sec;
419 *uptime += (double)now.tv_nsec / 1000000000.0;
424 uv_err_t uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
425 unsigned int numcpus;
431 numcpus = sysconf(_SC_NPROCESSORS_ONLN);
432 assert(numcpus != (unsigned int) -1);
433 assert(numcpus != 0);
435 ci = calloc(numcpus, sizeof(*ci));
437 return uv__new_sys_error(ENOMEM);
439 if (read_models(numcpus, ci)) {
440 SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
441 return uv__new_sys_error(errno);
444 if (read_times(numcpus, ci)) {
445 SAVE_ERRNO(uv_free_cpu_info(ci, numcpus));
446 return uv__new_sys_error(errno);
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.
452 if (ci[0].speed == 0)
453 read_speeds(numcpus, ci);
462 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
465 for (num = 0; num < numcpus; num++)
466 ci[num].speed = read_cpufreq(num) / 1000;
470 /* Also reads the CPU frequency on x86. The other architectures only have
471 * a BogoMIPS field, which may not be very accurate.
473 * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
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;
485 /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
486 (void) &model_marker;
487 (void) &speed_marker;
496 #if defined(__arm__) || \
497 defined(__i386__) || \
498 defined(__mips__) || \
500 fp = fopen("/proc/cpuinfo", "r");
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. */
513 ci[model_idx++].model = model;
517 #if defined(__arm__) || defined(__mips__)
518 if (model_idx < numcpus) {
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: ";
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. */
532 ci[model_idx++].model = model;
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);
543 #endif /* __arm__ || __mips__ */
547 #endif /* __arm__ || __i386__ || __mips__ || __x86_64__ */
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.
553 inferred_model = "unknown";
555 inferred_model = ci[model_idx - 1].model;
557 while (model_idx < numcpus) {
558 model = strndup(inferred_model, strlen(inferred_model));
561 ci[model_idx++].model = model;
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;
582 clock_ticks = sysconf(_SC_CLK_TCK);
583 assert(clock_ticks != (unsigned long) -1);
584 assert(clock_ticks != 0);
586 fp = fopen("/proc/stat", "r");
590 if (!fgets(buf, sizeof(buf), fp))
595 while (fgets(buf, sizeof(buf), fp)) {
599 if (strncmp(buf, "cpu", 3))
602 /* skip "cpu<num> " marker */
604 unsigned int n = num;
605 for (len = sizeof("cpu0"); n /= 10; len++);
606 assert(sscanf(buf, "cpu%u ", &n) == 1 && n == num);
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.
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.
615 if (6 != sscanf(buf + len,
616 "%lu %lu %lu %lu %lu %lu",
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;
638 static unsigned long read_cpufreq(unsigned int cpunum) {
645 "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
648 fp = fopen(buf, "r");
652 if (fscanf(fp, "%lu", &val) != 1)
661 void uv_free_cpu_info(uv_cpu_info_t* cpu_infos, int count) {
664 for (i = 0; i < count; i++) {
665 free(cpu_infos[i].model);
672 uv_err_t uv_interface_addresses(uv_interface_address_t** addresses,
674 #ifndef HAVE_IFADDRS_H
675 return uv__new_artificial_error(UV_ENOSYS);
677 struct ifaddrs *addrs, *ent;
678 char ip[INET6_ADDRSTRLEN];
679 uv_interface_address_t* address;
681 if (getifaddrs(&addrs) != 0) {
682 return uv__new_sys_error(errno);
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)) {
698 *addresses = (uv_interface_address_t*)
699 malloc(*count * sizeof(uv_interface_address_t));
701 return uv__new_artificial_error(UV_ENOMEM);
704 address = *addresses;
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)) {
712 if (ent->ifa_addr == NULL) {
717 * On Linux getifaddrs returns information related to the raw underlying
718 * devices. We're not interested in this information.
720 if (ent->ifa_addr->sa_family == PF_PACKET) {
724 address->name = strdup(ent->ifa_name);
726 if (ent->ifa_addr->sa_family == AF_INET6) {
727 address->address.address6 = *((struct sockaddr_in6 *)ent->ifa_addr);
729 address->address.address4 = *((struct sockaddr_in *)ent->ifa_addr);
732 address->is_internal = ent->ifa_flags & IFF_LOOPBACK ? 1 : 0;
744 void uv_free_interface_addresses(uv_interface_address_t* addresses,
748 for (i = 0; i < count; i++) {
749 free(addresses[i].name);
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. */