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
21 /* We lean on the fact that POLL{IN,OUT,ERR,HUP} correspond with their
22 * EPOLL* counterparts. We use the POLL* variants in this file because that
23 * is what libuv uses elsewhere.
38 #include <sys/epoll.h>
39 #include <sys/param.h>
40 #include <sys/prctl.h>
41 #include <sys/sysinfo.h>
46 #define HAVE_IFADDRS_H 1
48 # if defined(__ANDROID_API__) && __ANDROID_API__ < 24
49 # undef HAVE_IFADDRS_H
53 # if __UCLIBC_MAJOR__ < 0 && __UCLIBC_MINOR__ < 9 && __UCLIBC_SUBLEVEL__ < 32
54 # undef HAVE_IFADDRS_H
60 # include <sys/socket.h>
61 # include <net/ethernet.h>
62 # include <netpacket/packet.h>
63 #endif /* HAVE_IFADDRS_H */
65 /* Available from 2.6.32 onwards. */
66 #ifndef CLOCK_MONOTONIC_COARSE
67 # define CLOCK_MONOTONIC_COARSE 6
70 /* This is rather annoying: CLOCK_BOOTTIME lives in <linux/time.h> but we can't
71 * include that file because it conflicts with <time.h>. We'll just have to
72 * define it ourselves.
74 #ifndef CLOCK_BOOTTIME
75 # define CLOCK_BOOTTIME 7
78 static int read_models(unsigned int numcpus, uv_cpu_info_t* ci);
79 static int read_times(FILE* statfile_fp,
82 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci);
83 static uint64_t read_cpufreq(unsigned int cpunum);
85 int uv__platform_loop_init(uv_loop_t* loop) {
87 loop->inotify_fd = -1;
88 loop->inotify_watchers = NULL;
90 return uv__epoll_init(loop);
94 int uv__io_fork(uv_loop_t* loop) {
98 old_watchers = loop->inotify_watchers;
100 uv__close(loop->backend_fd);
101 loop->backend_fd = -1;
102 uv__platform_loop_delete(loop);
104 err = uv__platform_loop_init(loop);
108 return uv__inotify_fork(loop, old_watchers);
112 void uv__platform_loop_delete(uv_loop_t* loop) {
113 if (loop->inotify_fd == -1) return;
114 uv__io_stop(loop, &loop->inotify_read_watcher, POLLIN);
115 uv__close(loop->inotify_fd);
116 loop->inotify_fd = -1;
121 uint64_t uv__hrtime(uv_clocktype_t type) {
122 static clock_t fast_clock_id = -1;
126 /* Prefer CLOCK_MONOTONIC_COARSE if available but only when it has
127 * millisecond granularity or better. CLOCK_MONOTONIC_COARSE is
128 * serviced entirely from the vDSO, whereas CLOCK_MONOTONIC may
129 * decide to make a costly system call.
131 /* TODO(bnoordhuis) Use CLOCK_MONOTONIC_COARSE for UV_CLOCK_PRECISE
132 * when it has microsecond granularity or better (unlikely).
134 clock_id = CLOCK_MONOTONIC;
135 if (type != UV_CLOCK_FAST)
138 clock_id = uv__load_relaxed(&fast_clock_id);
142 clock_id = CLOCK_MONOTONIC;
143 if (0 == clock_getres(CLOCK_MONOTONIC_COARSE, &t))
144 if (t.tv_nsec <= 1 * 1000 * 1000)
145 clock_id = CLOCK_MONOTONIC_COARSE;
147 uv__store_relaxed(&fast_clock_id, clock_id);
151 if (clock_gettime(clock_id, &t))
152 return 0; /* Not really possible. */
154 return t.tv_sec * (uint64_t) 1e9 + t.tv_nsec;
158 int uv_resident_set_memory(size_t* rss) {
167 fd = open("/proc/self/stat", O_RDONLY);
168 while (fd == -1 && errno == EINTR);
171 return UV__ERR(errno);
174 n = read(fd, buf, sizeof(buf) - 1);
175 while (n == -1 && errno == EINTR);
179 return UV__ERR(errno);
182 s = strchr(buf, ' ');
194 for (i = 1; i <= 22; i++) {
195 s = strchr(s + 1, ' ');
201 val = strtol(s, NULL, 10);
207 *rss = val * getpagesize();
214 int uv_uptime(double* uptime) {
215 static volatile int no_clock_boottime;
220 /* Try /proc/uptime first, then fallback to clock_gettime(). */
222 if (0 == uv__slurp("/proc/uptime", buf, sizeof(buf)))
223 if (1 == sscanf(buf, "%lf", uptime))
226 /* Try CLOCK_BOOTTIME first, fall back to CLOCK_MONOTONIC if not available
227 * (pre-2.6.39 kernels). CLOCK_MONOTONIC doesn't increase when the system
230 if (no_clock_boottime) {
231 retry_clock_gettime: r = clock_gettime(CLOCK_MONOTONIC, &now);
233 else if ((r = clock_gettime(CLOCK_BOOTTIME, &now)) && errno == EINVAL) {
234 no_clock_boottime = 1;
235 goto retry_clock_gettime;
239 return UV__ERR(errno);
241 *uptime = now.tv_sec;
246 static int uv__cpu_num(FILE* statfile_fp, unsigned int* numcpus) {
250 if (!fgets(buf, sizeof(buf), statfile_fp))
254 while (fgets(buf, sizeof(buf), statfile_fp)) {
255 if (strncmp(buf, "cpu", 3))
268 int uv_cpu_info(uv_cpu_info_t** cpu_infos, int* count) {
269 unsigned int numcpus;
277 statfile_fp = uv__open_file("/proc/stat");
278 if (statfile_fp == NULL)
279 return UV__ERR(errno);
281 err = uv__cpu_num(statfile_fp, &numcpus);
286 ci = uv__calloc(numcpus, sizeof(*ci));
290 err = read_models(numcpus, ci);
292 err = read_times(statfile_fp, numcpus, ci);
295 uv_free_cpu_info(ci, numcpus);
299 /* read_models() on x86 also reads the CPU speed from /proc/cpuinfo.
300 * We don't check for errors here. Worst case, the field is left zero.
302 if (ci[0].speed == 0)
303 read_speeds(numcpus, ci);
311 if (fclose(statfile_fp))
312 if (errno != EINTR && errno != EINPROGRESS)
319 static void read_speeds(unsigned int numcpus, uv_cpu_info_t* ci) {
322 for (num = 0; num < numcpus; num++)
323 ci[num].speed = read_cpufreq(num) / 1000;
327 /* Also reads the CPU frequency on ppc and x86. The other architectures only
328 * have a BogoMIPS field, which may not be very accurate.
330 * Note: Simply returns on error, uv_cpu_info() takes care of the cleanup.
332 static int read_models(unsigned int numcpus, uv_cpu_info_t* ci) {
334 static const char model_marker[] = "cpu\t\t: ";
335 static const char speed_marker[] = "clock\t\t: ";
337 static const char model_marker[] = "model name\t: ";
338 static const char speed_marker[] = "cpu MHz\t\t: ";
340 const char* inferred_model;
341 unsigned int model_idx;
342 unsigned int speed_idx;
343 unsigned int part_idx;
349 /* Most are unused on non-ARM, non-MIPS and non-x86 architectures. */
350 (void) &model_marker;
351 (void) &speed_marker;
363 #if defined(__arm__) || \
364 defined(__i386__) || \
365 defined(__mips__) || \
366 defined(__aarch64__) || \
367 defined(__PPC__) || \
369 fp = uv__open_file("/proc/cpuinfo");
371 return UV__ERR(errno);
373 while (fgets(buf, sizeof(buf), fp)) {
374 if (model_idx < numcpus) {
375 if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
376 model = buf + sizeof(model_marker) - 1;
377 model = uv__strndup(model, strlen(model) - 1); /* Strip newline. */
382 ci[model_idx++].model = model;
386 #if defined(__arm__) || defined(__mips__) || defined(__aarch64__)
387 if (model_idx < numcpus) {
389 /* Fallback for pre-3.8 kernels. */
390 static const char model_marker[] = "Processor\t: ";
391 #elif defined(__aarch64__)
392 static const char part_marker[] = "CPU part\t: ";
394 /* Adapted from: https://github.com/karelzak/util-linux */
400 static const struct vendor_part arm_chips[] = {
408 { 0xa20, "ARM1020" },
409 { 0xa22, "ARM1022" },
410 { 0xa26, "ARM1026" },
411 { 0xb02, "ARM11 MPCore" },
412 { 0xb36, "ARM1136" },
413 { 0xb56, "ARM1156" },
414 { 0xb76, "ARM1176" },
415 { 0xc05, "Cortex-A5" },
416 { 0xc07, "Cortex-A7" },
417 { 0xc08, "Cortex-A8" },
418 { 0xc09, "Cortex-A9" },
419 { 0xc0d, "Cortex-A17" }, /* Originally A12 */
420 { 0xc0f, "Cortex-A15" },
421 { 0xc0e, "Cortex-A17" },
422 { 0xc14, "Cortex-R4" },
423 { 0xc15, "Cortex-R5" },
424 { 0xc17, "Cortex-R7" },
425 { 0xc18, "Cortex-R8" },
426 { 0xc20, "Cortex-M0" },
427 { 0xc21, "Cortex-M1" },
428 { 0xc23, "Cortex-M3" },
429 { 0xc24, "Cortex-M4" },
430 { 0xc27, "Cortex-M7" },
431 { 0xc60, "Cortex-M0+" },
432 { 0xd01, "Cortex-A32" },
433 { 0xd03, "Cortex-A53" },
434 { 0xd04, "Cortex-A35" },
435 { 0xd05, "Cortex-A55" },
436 { 0xd06, "Cortex-A65" },
437 { 0xd07, "Cortex-A57" },
438 { 0xd08, "Cortex-A72" },
439 { 0xd09, "Cortex-A73" },
440 { 0xd0a, "Cortex-A75" },
441 { 0xd0b, "Cortex-A76" },
442 { 0xd0c, "Neoverse-N1" },
443 { 0xd0d, "Cortex-A77" },
444 { 0xd0e, "Cortex-A76AE" },
445 { 0xd13, "Cortex-R52" },
446 { 0xd20, "Cortex-M23" },
447 { 0xd21, "Cortex-M33" },
448 { 0xd41, "Cortex-A78" },
449 { 0xd42, "Cortex-A78AE" },
450 { 0xd4a, "Neoverse-E1" },
451 { 0xd4b, "Cortex-A78C" },
454 if (strncmp(buf, part_marker, sizeof(part_marker) - 1) == 0) {
455 model = buf + sizeof(part_marker) - 1;
458 model_id = strtol(model, NULL, 16);
459 if ((errno != 0) || model_id < 0) {
464 for (part_idx = 0; part_idx < ARRAY_SIZE(arm_chips); part_idx++) {
465 if (model_id == arm_chips[part_idx].id) {
466 model = uv__strdup(arm_chips[part_idx].name);
471 ci[model_idx++].model = model;
476 #else /* defined(__mips__) */
477 static const char model_marker[] = "cpu model\t\t: ";
479 if (strncmp(buf, model_marker, sizeof(model_marker) - 1) == 0) {
480 model = buf + sizeof(model_marker) - 1;
481 model = uv__strndup(model, strlen(model) - 1); /* Strip newline. */
486 ci[model_idx++].model = model;
490 #else /* !__arm__ && !__mips__ && !__aarch64__ */
491 if (speed_idx < numcpus) {
492 if (strncmp(buf, speed_marker, sizeof(speed_marker) - 1) == 0) {
493 ci[speed_idx++].speed = atoi(buf + sizeof(speed_marker) - 1);
497 #endif /* __arm__ || __mips__ || __aarch64__ */
501 #endif /* __arm__ || __i386__ || __mips__ || __PPC__ || __x86_64__ || __aarch__ */
503 /* Now we want to make sure that all the models contain *something* because
504 * it's not safe to leave them as null. Copy the last entry unless there
505 * isn't one, in that case we simply put "unknown" into everything.
507 inferred_model = "unknown";
509 inferred_model = ci[model_idx - 1].model;
511 while (model_idx < numcpus) {
512 model = uv__strndup(inferred_model, strlen(inferred_model));
515 ci[model_idx++].model = model;
522 static int read_times(FILE* statfile_fp,
523 unsigned int numcpus,
525 struct uv_cpu_times_s ts;
527 unsigned int multiplier;
538 ticks = (unsigned int)sysconf(_SC_CLK_TCK);
539 assert(ticks != (unsigned int) -1);
541 multiplier = ((uint64_t)1000L / ticks);
545 if (!fgets(buf, sizeof(buf), statfile_fp))
550 while (fgets(buf, sizeof(buf), statfile_fp)) {
554 if (strncmp(buf, "cpu", 3))
557 /* skip "cpu<num> " marker */
560 int r = sscanf(buf, "cpu%u ", &n);
562 (void) r; /* silence build warning */
563 for (len = sizeof("cpu0"); n /= 10; len++);
566 /* Line contains user, nice, system, idle, iowait, irq, softirq, steal,
567 * guest, guest_nice but we're only interested in the first four + irq.
569 * Don't use %*s to skip fields or %ll to read straight into the uint64_t
570 * fields, they're not allowed in C89 mode.
572 if (6 != sscanf(buf + len,
573 "%" PRIu64 " %" PRIu64 " %" PRIu64
574 "%" PRIu64 " %" PRIu64 " %" PRIu64,
583 ts.user = user * multiplier;
584 ts.nice = nice * multiplier;
585 ts.sys = sys * multiplier;
586 ts.idle = idle * multiplier;
587 ts.irq = irq * multiplier;
588 ci[num++].cpu_times = ts;
590 assert(num == numcpus);
596 static uint64_t read_cpufreq(unsigned int cpunum) {
603 "/sys/devices/system/cpu/cpu%u/cpufreq/scaling_cur_freq",
606 fp = uv__open_file(buf);
610 if (fscanf(fp, "%" PRIu64, &val) != 1)
619 #ifdef HAVE_IFADDRS_H
620 static int uv__ifaddr_exclude(struct ifaddrs *ent, int exclude_type) {
621 if (!((ent->ifa_flags & IFF_UP) && (ent->ifa_flags & IFF_RUNNING)))
623 if (ent->ifa_addr == NULL)
626 * On Linux getifaddrs returns information related to the raw underlying
627 * devices. We're not interested in this information yet.
629 if (ent->ifa_addr->sa_family == PF_PACKET)
631 return !exclude_type;
635 int uv_interface_addresses(uv_interface_address_t** addresses, int* count) {
636 #ifndef HAVE_IFADDRS_H
641 struct ifaddrs *addrs, *ent;
642 uv_interface_address_t* address;
644 struct sockaddr_ll *sll;
649 if (getifaddrs(&addrs))
650 return UV__ERR(errno);
652 /* Count the number of interfaces */
653 for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
654 if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFADDR))
665 /* Make sure the memory is initiallized to zero using calloc() */
666 *addresses = uv__calloc(*count, sizeof(**addresses));
672 address = *addresses;
674 for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
675 if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFADDR))
678 address->name = uv__strdup(ent->ifa_name);
680 if (ent->ifa_addr->sa_family == AF_INET6) {
681 address->address.address6 = *((struct sockaddr_in6*) ent->ifa_addr);
683 address->address.address4 = *((struct sockaddr_in*) ent->ifa_addr);
686 if (ent->ifa_netmask->sa_family == AF_INET6) {
687 address->netmask.netmask6 = *((struct sockaddr_in6*) ent->ifa_netmask);
689 address->netmask.netmask4 = *((struct sockaddr_in*) ent->ifa_netmask);
692 address->is_internal = !!(ent->ifa_flags & IFF_LOOPBACK);
697 /* Fill in physical addresses for each interface */
698 for (ent = addrs; ent != NULL; ent = ent->ifa_next) {
699 if (uv__ifaddr_exclude(ent, UV__EXCLUDE_IFPHYS))
702 address = *addresses;
704 for (i = 0; i < (*count); i++) {
705 size_t namelen = strlen(ent->ifa_name);
706 /* Alias interface share the same physical address */
707 if (strncmp(address->name, ent->ifa_name, namelen) == 0 &&
708 (address->name[namelen] == 0 || address->name[namelen] == ':')) {
709 sll = (struct sockaddr_ll*)ent->ifa_addr;
710 memcpy(address->phys_addr, sll->sll_addr, sizeof(address->phys_addr));
723 void uv_free_interface_addresses(uv_interface_address_t* addresses,
727 for (i = 0; i < count; i++) {
728 uv__free(addresses[i].name);
735 void uv__set_process_title(const char* title) {
736 #if defined(PR_SET_NAME)
737 prctl(PR_SET_NAME, title); /* Only copies first 16 characters. */
742 static uint64_t uv__read_proc_meminfo(const char* what) {
745 char buf[4096]; /* Large enough to hold all of /proc/meminfo. */
747 if (uv__slurp("/proc/meminfo", buf, sizeof(buf)))
750 p = strstr(buf, what);
758 sscanf(p, "%" PRIu64 " kB", &rc);
764 uint64_t uv_get_free_memory(void) {
768 rc = uv__read_proc_meminfo("MemAvailable:");
773 if (0 == sysinfo(&info))
774 return (uint64_t) info.freeram * info.mem_unit;
780 uint64_t uv_get_total_memory(void) {
784 rc = uv__read_proc_meminfo("MemTotal:");
789 if (0 == sysinfo(&info))
790 return (uint64_t) info.totalram * info.mem_unit;
796 static uint64_t uv__read_cgroups_uint64(const char* cgroup, const char* param) {
798 char buf[32]; /* Large enough to hold an encoded uint64_t. */
802 snprintf(filename, sizeof(filename), "/sys/fs/cgroup/%s/%s", cgroup, param);
803 if (0 == uv__slurp(filename, buf, sizeof(buf)))
804 sscanf(buf, "%" PRIu64, &rc);
810 uint64_t uv_get_constrained_memory(void) {
812 * This might return 0 if there was a problem getting the memory limit from
813 * cgroups. This is OK because a return value of 0 signifies that the memory
816 return uv__read_cgroups_uint64("memory", "memory.limit_in_bytes");
820 void uv_loadavg(double avg[3]) {
822 char buf[128]; /* Large enough to hold all of /proc/loadavg. */
824 if (0 == uv__slurp("/proc/loadavg", buf, sizeof(buf)))
825 if (3 == sscanf(buf, "%lf %lf %lf", &avg[0], &avg[1], &avg[2]))
828 if (sysinfo(&info) < 0)
831 avg[0] = (double) info.loads[0] / 65536.0;
832 avg[1] = (double) info.loads[1] / 65536.0;
833 avg[2] = (double) info.loads[2] / 65536.0;