From: Florian Forster Date: Tue, 19 May 2015 15:40:36 +0000 (+0200) Subject: Merge remote-tracking branch 'github/pr/1009' X-Git-Tag: collectd-5.5.0~22 X-Git-Url: https://git.octo.it/?p=collectd.git;a=commitdiff_plain;h=0c88d3b2d330c152be0bc6af8faecef0211a705e;hp=7b0f362e1766ff7f04fd5466680d3606140b6ddc Merge remote-tracking branch 'github/pr/1009' --- diff --git a/AUTHORS b/AUTHORS index 9ee3bd19..3f63c3dc 100644 --- a/AUTHORS +++ b/AUTHORS @@ -283,6 +283,9 @@ Tommie Gannert Vincent Bernat - smart plugin. +Vincent Brillault + - turbostat plugin, based on Len Brown kernel tool + Vincent Stehlé - hddtemp plugin. diff --git a/README b/README index 5582e51d..9604fda3 100644 --- a/README +++ b/README @@ -352,6 +352,10 @@ Features Reads the number of records and file size from a running Tokyo Tyrant server. + - turbostat + Reads CPU frequency and C-state residency on modern Intel + turbo-capable processors. + - uptime System uptime statistics. @@ -635,6 +639,12 @@ Prerequisites Used by the `smart' plugin. + * libcap (optional) + The `turbostat' plugin can optionally build Linux Capabilities support, + which avoids full privileges requirement (aka. running as root) to read + values. + + * libclntsh (optional) Used by the `oracle' plugin. diff --git a/configure.ac b/configure.ac index 2d5ce60a..87d1502b 100644 --- a/configure.ac +++ b/configure.ac @@ -589,13 +589,44 @@ AC_CHECK_HEADERS(net/pfvar.h, have_termios_h="no" AC_CHECK_HEADERS(termios.h, [have_termios_h="yes"]) +# For the turbostat plugin +have_asm_msrindex_h="no" +AC_CHECK_HEADERS(asm/msr-index.h, [have_asm_msrindex_h="yes"]) + +if test "x$have_asm_msrindex_h" = "xyes" +then + AC_CACHE_CHECK([whether asm/msr-index.h has MSR_CORE_C3_RESIDENCY], + [c_cv_have_usable_asm_msrindex_h], + AC_COMPILE_IFELSE([AC_LANG_PROGRAM( +[[[ +#include +]]], +[[[ +int y = MSR_CORE_C3_RESIDENCY; +return(y); +]]] + )], + [c_cv_have_usable_asm_msrindex_h="yes"], + [c_cv_have_usable_asm_msrindex_h="no"], + ) + ) +fi + +have_cpuid_h="no" +AC_CHECK_HEADERS(cpuid.h, [have_cpuid_h="yes"]) + +AC_CHECK_HEADERS(sys/capability.h) # # Checks for typedefs, structures, and compiler characteristics. # AC_C_CONST +AC_C_INLINE +AC_TYPE_OFF_T AC_TYPE_PID_T AC_TYPE_SIZE_T +AC_TYPE_SSIZE_T AC_TYPE_UID_T +AC_TYPE_UINT32_T AC_HEADER_TIME # @@ -1190,6 +1221,7 @@ FILE *fh; struct mntent *me; fh = setmntent ("/etc/mtab", "r"); me = getmntent (fh); +return(me->mnt_passno); ]]] )], [c_cv_have_one_getmntent="yes"], @@ -1209,6 +1241,7 @@ me = getmntent (fh); int status; fh = fopen ("/etc/mnttab", "r"); status = getmntent (fh, &mt); + return(status); ]]] )], [c_cv_have_two_getmntent="yes"], @@ -2084,6 +2117,10 @@ fi # --with-java {{{ with_java_home="$JAVA_HOME" +if test "x$with_java_home" = "x" +then + with_java_home="/usr/lib/jvm" +fi with_java_vmtype="client" with_java_cflags="" with_java_libs="" @@ -2108,7 +2145,7 @@ then if test -d "$with_java_home" then AC_MSG_CHECKING([for jni.h]) - TMPVAR=`find "$with_java_home" -name jni.h -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` + TMPVAR=`find -L "$with_java_home" -name jni.h -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` if test "x$TMPVAR" != "x" then AC_MSG_RESULT([found in $TMPVAR]) @@ -2118,7 +2155,7 @@ then fi AC_MSG_CHECKING([for jni_md.h]) - TMPVAR=`find "$with_java_home" -name jni_md.h -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` + TMPVAR=`find -L "$with_java_home" -name jni_md.h -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` if test "x$TMPVAR" != "x" then AC_MSG_RESULT([found in $TMPVAR]) @@ -2128,7 +2165,7 @@ then fi AC_MSG_CHECKING([for libjvm.so]) - TMPVAR=`find "$with_java_home" -name libjvm.so -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` + TMPVAR=`find -L "$with_java_home" -name libjvm.so -type f -exec 'dirname' '{}' ';' 2>/dev/null | head -n 1` if test "x$TMPVAR" != "x" then AC_MSG_RESULT([found in $TMPVAR]) @@ -2140,7 +2177,7 @@ then if test "x$JAVAC" = "x" then AC_MSG_CHECKING([for javac]) - TMPVAR=`find "$with_java_home" -name javac -type f 2>/dev/null | head -n 1` + TMPVAR=`find -L "$with_java_home" -name javac -type f 2>/dev/null | head -n 1` if test "x$TMPVAR" != "x" then JAVAC="$TMPVAR" @@ -2152,7 +2189,7 @@ then if test "x$JAR" = "x" then AC_MSG_CHECKING([for jar]) - TMPVAR=`find "$with_java_home" -name jar -type f 2>/dev/null | head -n 1` + TMPVAR=`find -L "$with_java_home" -name jar -type f 2>/dev/null | head -n 1` if test "x$TMPVAR" != "x" then JAR="$TMPVAR" @@ -3172,6 +3209,7 @@ then ]]], [[[ int val = PCAP_ERROR_IFACE_NOT_UP; + return(val); ]]] )], [c_cv_libpcap_have_pcap_error_iface_not_up="yes"], @@ -3722,6 +3760,7 @@ AC_ARG_WITH(librdkafka, [AS_HELP_STRING([--with-librdkafka@<:@=PREFIX@:>@], [Pat then with_librdkafka_cppflags="-I$withval/include" with_librdkafka_ldflags="-L$withval/lib" + with_librdkafka_rpath="$withval/lib" with_librdkafka="yes" else with_librdkafka="$withval" @@ -3733,6 +3772,9 @@ AC_ARG_WITH(librdkafka, [AS_HELP_STRING([--with-librdkafka@<:@=PREFIX@:>@], [Pat SAVE_CPPFLAGS="$CPPFLAGS" SAVE_LDFLAGS="$LDFLAGS" +CPPFLAGS="$CPPFLAGS $with_librdkafka_cppflags" +LDFLAGS="$LDFLAGS $with_librdkafka_ldflags" + if test "x$with_librdkafka" = "xyes" then AC_CHECK_HEADERS(librdkafka/rdkafka.h, [with_librdkafka="yes"], [with_librdkafka="no (librdkafka/rdkafka.h not found)"]) @@ -3748,7 +3790,12 @@ if test "x$with_librdkafka" = "xyes" then BUILD_WITH_LIBRDKAFKA_CPPFLAGS="$with_librdkafka_cppflags" BUILD_WITH_LIBRDKAFKA_LDFLAGS="$with_librdkafka_ldflags" - BUILD_WITH_LIBRDKAFKA_LIBS="-lrdkafka" + if test "x$with_librdkafka_rpath" != "x" + then + BUILD_WITH_LIBRDKAFKA_LIBS="-Wl,-rpath,$with_librdkafka_rpath -lrdkafka" + else + BUILD_WITH_LIBRDKAFKA_LIBS="-lrdkafka" + fi AC_SUBST(BUILD_WITH_LIBRDKAFKA_CPPFLAGS) AC_SUBST(BUILD_WITH_LIBRDKAFKA_LDFLAGS) AC_SUBST(BUILD_WITH_LIBRDKAFKA_LIBS) @@ -5139,6 +5186,7 @@ plugin_tape="no" plugin_tcpconns="no" plugin_ted="no" plugin_thermal="no" +plugin_turbostat="no" plugin_uptime="no" plugin_users="no" plugin_virt="no" @@ -5185,6 +5233,10 @@ then then plugin_ipvs="yes" fi + if test "x$c_cv_have_usable_asm_msrindex_h" = "xyes" && test "x$have_cpuid_h" = "xyes" + then + plugin_turbostat="yes" + fi fi if test "x$ac_system" = "xOpenBSD" @@ -5236,6 +5288,7 @@ fi if test "x$with_kstat" = "xyes" then plugin_nfs="yes" + plugin_processes="yes" plugin_uptime="yes" plugin_zfs_arc="yes" fi @@ -5582,6 +5635,7 @@ AC_PLUGIN([ted], [$plugin_ted], [Read The Energy Detective values AC_PLUGIN([thermal], [$plugin_thermal], [Linux ACPI thermal zone statistics]) AC_PLUGIN([threshold], [yes], [Threshold checking plugin]) AC_PLUGIN([tokyotyrant], [$with_libtokyotyrant], [TokyoTyrant database statistics]) +AC_PLUGIN([turbostat], [$plugin_turbostat], [Advanced statistic on Intel cpu states]) AC_PLUGIN([unixsock], [yes], [Unixsock communication plugin]) AC_PLUGIN([uptime], [$plugin_uptime], [Uptime statistics]) AC_PLUGIN([users], [$plugin_users], [User statistics]) @@ -5958,6 +6012,7 @@ Configuration: thermal . . . . . . . $enable_thermal threshold . . . . . . $enable_threshold tokyotyrant . . . . . $enable_tokyotyrant + turbostat . . . . . . $enable_turbostat unixsock . . . . . . $enable_unixsock uptime . . . . . . . $enable_uptime users . . . . . . . . $enable_users diff --git a/contrib/redhat/collectd.spec b/contrib/redhat/collectd.spec index 421b9557..5315870f 100644 --- a/contrib/redhat/collectd.spec +++ b/contrib/redhat/collectd.spec @@ -52,6 +52,7 @@ %{?el6:%global _has_iproute 1} %{?el6:%global _has_atasmart 1} %{?el6:%global _has_hiredis 1} +%{?el6:%global _has_asm_msr_index 1} %{?el7:%global _has_libyajl 1} %{?el7:%global _has_recent_libpcap 1} @@ -66,6 +67,7 @@ %{?el7:%global _has_iproute 1} %{?el7:%global _has_atasmart 1} %{?el7:%global _has_hiredis 1} +%{?el7:%global _has_asm_msr_index 1} # plugins enabled by default %define with_aggregation 0%{!?_without_aggregation:1} @@ -158,6 +160,7 @@ %define with_ted 0%{!?_without_ted:1} %define with_thermal 0%{!?_without_thermal:1} %define with_threshold 0%{!?_without_threshold:1} +%define with_turbostat 0%{!?_without_turbostat:0%{?_has_asm_msr_index}} %define with_unixsock 0%{!?_without_unixsock:1} %define with_uptime 0%{!?_without_uptime:1} %define with_users 0%{!?_without_users:1} @@ -212,7 +215,7 @@ # plugin xmms disabled, requires xmms %define with_xmms 0%{!?_without_xmms:0} -Summary: Statistics collection daemon for filling RRD files +Summary: statistics collection and monitoring daemon Name: collectd Version: 5.4.2 Release: 1%{?dist} @@ -221,7 +224,7 @@ Source: http://collectd.org/files/%{name}-%{version}.tar.bz2 License: GPLv2 Group: System Environment/Daemons BuildRoot: %{_tmppath}/%{name}-%{version}-root -BuildRequires: libgcrypt-devel, kernel-headers, libtool-ltdl-devel +BuildRequires: libgcrypt-devel, kernel-headers, libtool-ltdl-devel, libcap-devel Vendor: collectd development team %if 0%{?el7:1} @@ -949,7 +952,7 @@ Collectd utilities %if %{with_dbi} %define _with_dbi --enable-dbi %else -%define _with_dbi --disable-dbi --without-libdbi +%define _with_dbi --disable-dbi %endif %if %{with_df} @@ -1207,7 +1210,7 @@ Collectd utilities %if %{with_notify_email} %define _with_notify_email --enable-notify_email %else -%define _with_notify_email --disable-notify_email --without-libesmpt +%define _with_notify_email --disable-notify_email %endif %if %{with_ntpd} @@ -1261,7 +1264,7 @@ Collectd utilities %if %{with_perl} %define _with_perl --enable-perl --with-perl-bindings="INSTALLDIRS=vendor" %else -%define _with_perl --disable-perl --without-libperl +%define _with_perl --disable-perl %endif %if %{with_pf} @@ -1448,6 +1451,12 @@ Collectd utilities %define _with_tokyotyrant --disable-tokyotyrant %endif +%if %{with_turbostat} +%define _with_turbostat --enable-turbostat +%else +%define _with_turbostat --disable-turbostat +%endif + %if %{with_unixsock} %define _with_unixsock --enable-unixsock %else @@ -1523,7 +1532,7 @@ Collectd utilities %if %{with_write_mongodb} %define _with_write_mongodb --enable-write_mongodb %else -%define _with_write_mongodb --disable-write_mongodb --without-libmongoc +%define _with_write_mongodb --disable-write_mongodb %endif %if %{with_write_redis} @@ -1693,6 +1702,7 @@ Collectd utilities %{?_with_ted} \ %{?_with_thermal} \ %{?_with_threshold} \ + %{?_with_turbostat} \ %{?_with_unixsock} \ %{?_with_uptime} \ %{?_with_users} \ @@ -1993,9 +2003,12 @@ fi %if %{with_thermal} %{_libdir}/%{name}/thermal.so %endif -%if %{with_load} +%if %{with_threshold} %{_libdir}/%{name}/threshold.so %endif +%if %{with_turbostat} +%{_libdir}/%{name}/turbostat.so +%endif %if %{with_unixsock} %{_libdir}/%{name}/unixsock.so %endif @@ -2324,12 +2337,13 @@ fi %changelog # * TODO 5.5.0-1 # - New upstream version -# - New plugins enabled by default: ceph, drbd, log_logstash, write_tsdb, smart, openldap, redis, write_redis, zookeeper, write_log, write_sensu, ipc +# - New plugins enabled by default: ceph, drbd, log_logstash, write_tsdb, smart, openldap, redis, write_redis, zookeeper, write_log, write_sensu, ipc, turbostat # - New plugins disabled by default: barometer, write_kafka # - Enable zfs_arc, now supported on Linux # - Install disk plugin in a dedicated package, as it depends on libudev # - use systemd on EL7, sysvinit on EL6 & EL5 # - Install collectdctl, collectd-tg and collectd-nagios in collectd-utils.rpm +# - Add build-dependency on libcap-devel * Mon Aug 19 2013 Marc Fournier 5.4.0-1 - New upstream version diff --git a/src/Makefile.am b/src/Makefile.am index a95dbca7..08b8d525 100644 --- a/src/Makefile.am +++ b/src/Makefile.am @@ -1082,6 +1082,12 @@ tokyotyrant_la_LIBADD += -lsocket endif endif +if BUILD_PLUGIN_TURBOSTAT +pkglib_LTLIBRARIES += turbostat.la +turbostat_la_SOURCES = turbostat.c +turbostat_la_LDFLAGS = $(PLUGIN_LDFLAGS) +endif + if BUILD_PLUGIN_UNIXSOCK pkglib_LTLIBRARIES += unixsock.la unixsock_la_SOURCES = unixsock.c \ @@ -1194,6 +1200,7 @@ write_kafka_la_SOURCES = write_kafka.c \ utils_format_json.c utils_format_json.h \ utils_cmd_putval.c utils_cmd_putval.h \ utils_crc32.c utils_crc32.h +write_kafka_la_CPPFLAGS = $(AM_CPPFLAGS) $(BUILD_WITH_LIBRDKAFKA_CPPFLAGS) write_kafka_la_LDFLAGS = $(PLUGIN_LDFLAGS) $(BUILD_WITH_LIBRDKAFKA_LDFLAGS) write_kafka_la_LIBADD = $(BUILD_WITH_LIBRDKAFKA_LIBS) endif diff --git a/src/collectd.conf.in b/src/collectd.conf.in index a09ed2be..5132cb4a 100644 --- a/src/collectd.conf.in +++ b/src/collectd.conf.in @@ -184,6 +184,7 @@ #@BUILD_PLUGIN_TED_TRUE@LoadPlugin ted #@BUILD_PLUGIN_THERMAL_TRUE@LoadPlugin thermal #@BUILD_PLUGIN_TOKYOTYRANT_TRUE@LoadPlugin tokyotyrant +#@BUILD_PLUGIN_TURBOSTAT_TRUE@LoadPlugin turbostat #@BUILD_PLUGIN_UNIXSOCK_TRUE@LoadPlugin unixsock #@BUILD_PLUGIN_UPTIME_TRUE@LoadPlugin uptime #@BUILD_PLUGIN_USERS_TRUE@LoadPlugin users @@ -1210,6 +1211,25 @@ # Port "1978" # +# +## None of the following option should be set manually +## This plugin automatically detect most optimal options +## Only set values here if: +## - The module ask you to +## - You want to disable the collection of some data +## - Your (intel) CPU is not supported (yet) by the module +## - The module generate a lot of errors 'MSR offset 0x... read failed' +## In the last two cases, please open a bug request +# +# TCCActivationTemp "100" +# CoreCstates "392" +# PackageCstates "396" +# SystemManagementInterrupt true +# DigitalTemperatureSensor true +# PackageThermalManagement true +# RunningAveragePowerLimit "7" +# + # # SocketFile "@prefix@/var/run/@PACKAGE_NAME@-unixsock" # SocketGroup "collectd" diff --git a/src/collectd.conf.pod b/src/collectd.conf.pod index 11bc7fa5..0c8e1e20 100644 --- a/src/collectd.conf.pod +++ b/src/collectd.conf.pod @@ -6608,6 +6608,79 @@ Default: B<1978> =back +=head2 Plugin C + +The I reads CPU frequency and C-state residency on modern +Intel processors by using the new Model Specific Registers. + +=over 4 + +=item B I + +Bitmask of the list of core C states supported by the processor. +This option should only be used if the automated detection fails. +Default value extracted from the cpu model and family. + +Currently supported C-states (by this plugin): 3, 6, 7 + +Example: (1<<3)+(1<<6)+(1<<7) = 392 for all states + +=item B I + +Bitmask of the list of pacages C states supported by the processor. +This option should only be used if the automated detection fails. +Default value extracted from the cpu model and family. + +Currently supported C-states (by this plugin): 2, 3, 6, 7, 8, 9, 10 + +Example: (1<<2)+(1<<3)+(1<<6)+(1<<7) = 396 for states 2, 3, 6 and 7 + +=item B I|I + +Boolean enabling the collection of the I/O System-Management Interrupt +counter'. This option should only be used if the automated detection +fails or if you want to disable this feature. + +=item B I|I + +Boolean enabling the collection of the temperature of each core. +This option should only be used if the automated detectionfails or +if you want to disable this feature. + +=item B I|I + +Boolean enabling the collection of the temperature of each package. +This option should only be used if the automated detectionfails or +if you want to disable this feature. + +=item B I + +Thermal Control Circuit Activation Temperature of the installed +CPU. This temperature is used when collecting the temperature of +cores or packages. This option should only be used if the automated +detection fails. Default value extracted from B + +=item B I + +Bitmask of the list of elements to be thermally monitored. This option +should only be used if the automated detection fails or if you want to +disable some collections. The different bits of this bitmask accepted +by this plugin are: + +=over 4 + +=item 0 ('1'): Package + +=item 1 ('2'): DRAM + +=item 2 ('4'): Cores + +=item 3 ('8'): Embedded graphic device + +=back + +=back + =head2 Plugin C =over 4 diff --git a/src/daemon/meta_data.c b/src/daemon/meta_data.c index d3da9bb5..6ee8446b 100644 --- a/src/daemon/meta_data.c +++ b/src/daemon/meta_data.c @@ -494,7 +494,7 @@ int meta_data_get_string (meta_data_t *md, /* {{{ */ if (e->type != MD_TYPE_STRING) { - ERROR ("meta_data_get_signed_int: Type mismatch for key `%s'", e->key); + ERROR ("meta_data_get_string: Type mismatch for key `%s'", e->key); pthread_mutex_unlock (&md->lock); return (-ENOENT); } diff --git a/src/java.c b/src/java.c index d0423be9..2f1efbf1 100644 --- a/src/java.c +++ b/src/java.c @@ -3078,10 +3078,8 @@ static int cjni_init (void) /* {{{ */ if (config_block != NULL) { - cjni_config_perform (config_block); oconfig_free (config_block); - config_block = NULL; } if (jvm == NULL) diff --git a/src/libcollectdclient/network.c b/src/libcollectdclient/network.c index ddb3b5b9..c390a1ce 100644 --- a/src/libcollectdclient/network.c +++ b/src/libcollectdclient/network.c @@ -1,6 +1,6 @@ /** * collectd - src/libcollectdclient/network.c - * Copyright (C) 2005-2013 Florian Forster + * Copyright (C) 2005-2015 Florian Forster * Copyright (C) 2010 Max Henkel * * Permission is hereby granted, free of charge, to any person obtaining a @@ -219,7 +219,13 @@ static int server_send_buffer (lcc_server_t *srv) /* {{{ */ memset (buffer, 0, sizeof (buffer)); buffer_size = sizeof (buffer); - lcc_network_buffer_finalize (srv->buffer); + status = lcc_network_buffer_finalize (srv->buffer); + if (status != 0) + { + lcc_network_buffer_initialize (srv->buffer); + return (status); + } + status = lcc_network_buffer_get (srv->buffer, buffer, &buffer_size); lcc_network_buffer_initialize (srv->buffer); diff --git a/src/libcollectdclient/network_buffer.c b/src/libcollectdclient/network_buffer.c index 61c7c22e..343c285a 100644 --- a/src/libcollectdclient/network_buffer.c +++ b/src/libcollectdclient/network_buffer.c @@ -1,6 +1,6 @@ /** * collectd - src/libcollectdclient/network_buffer.c - * Copyright (C) 2010-2012 Florian octo Forster + * Copyright (C) 2010-2015 Florian octo Forster * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), @@ -792,9 +792,9 @@ int lcc_network_buffer_finalize (lcc_network_buffer_t *nb) /* {{{ */ #if HAVE_LIBGCRYPT if (nb->seclevel == SIGN) - nb_add_signature (nb); + return nb_add_signature (nb); else if (nb->seclevel == ENCRYPT) - nb_add_encryption (nb); + return nb_add_encryption (nb); #endif return (0); diff --git a/src/liboconfig/oconfig.c b/src/liboconfig/oconfig.c index 539c9d35..bf21b90e 100644 --- a/src/liboconfig/oconfig.c +++ b/src/liboconfig/oconfig.c @@ -195,7 +195,7 @@ oconfig_item_t *oconfig_clone (const oconfig_item_t *ci_orig) return (ci_copy); } /* oconfig_item_t *oconfig_clone */ -void oconfig_free (oconfig_item_t *ci) +void oconfig_free_all (oconfig_item_t *ci) { int i; @@ -214,12 +214,19 @@ void oconfig_free (oconfig_item_t *ci) free (ci->values); for (i = 0; i < ci->children_num; i++) - oconfig_free (ci->children + i); + oconfig_free_all (ci->children + i); if (ci->children != NULL) free (ci->children); } +void oconfig_free (oconfig_item_t *ci) +{ + oconfig_free_all (ci); + free (ci); + ci = NULL; +} + /* * vim:shiftwidth=2:tabstop=8:softtabstop=2:fdm=marker */ diff --git a/src/processes.c b/src/processes.c index 68f30a5a..0649eab2 100644 --- a/src/processes.c +++ b/src/processes.c @@ -112,7 +112,22 @@ /* #endif HAVE_PROCINFO_H */ #elif KERNEL_SOLARIS +/* Hack: Avoid #error when building a 32-bit binary with + * _FILE_OFFSET_BITS=64. There is a reason for this #error, as one + * of the structures in uses an off_t, but that + * isn't relevant to our usage of procfs. */ +#if !defined(_LP64) && _FILE_OFFSET_BITS == 64 +# define SAVE_FOB_64 +# undef _FILE_OFFSET_BITS +#endif + # include + +#ifdef SAVE_FOB_64 +# define _FILE_OFFSET_BITS 64 +# undef SAVE_FOB_64 +#endif + # include /* #endif KERNEL_SOLARIS */ @@ -1199,17 +1214,17 @@ static int read_fork_rate () #endif /*KERNEL_LINUX */ #if KERNEL_SOLARIS -static const char *ps_get_cmdline (pid_t pid, /* {{{ */ +static const char *ps_get_cmdline (long pid, /* {{{ */ char *buffer, size_t buffer_size) { char path[PATH_MAX]; psinfo_t info; int status; - snprintf(path, sizeof (path), "/proc/%i/psinfo", pid); + snprintf(path, sizeof (path), "/proc/%li/psinfo", pid); status = read_file_contents (path, (void *) &info, sizeof (info)); - if (status != ((int) buffer_size)) + if (status != sizeof (info)) { ERROR ("processes plugin: Unexpected return value " "while reading \"%s\": " @@ -1230,7 +1245,7 @@ static const char *ps_get_cmdline (pid_t pid, /* {{{ */ * The values for input and ouput chars are calculated "by hand" * Added a few "solaris" specific process states as well */ -static int ps_read_process(int pid, procstat_t *ps, char *state) +static int ps_read_process(long pid, procstat_t *ps, char *state) { char filename[64]; char f_psinfo[64], f_usage[64]; @@ -1240,9 +1255,9 @@ static int ps_read_process(int pid, procstat_t *ps, char *state) psinfo_t *myInfo; prusage_t *myUsage; - snprintf(filename, sizeof (filename), "/proc/%i/status", pid); - snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%i/psinfo", pid); - snprintf(f_usage, sizeof (f_usage), "/proc/%i/usage", pid); + snprintf(filename, sizeof (filename), "/proc/%li/status", pid); + snprintf(f_psinfo, sizeof (f_psinfo), "/proc/%li/psinfo", pid); + snprintf(f_usage, sizeof (f_usage), "/proc/%li/usage", pid); buffer = malloc(sizeof (pstatus_t)); @@ -1791,7 +1806,7 @@ static int ps_read (void) int wait = 0; kvm_t *kd; - char errbuf[1024]; + char errbuf[_POSIX2_LINE_MAX]; struct kinfo_proc *procs; /* array of processes */ struct kinfo_proc *proc_ptr = NULL; int count; /* returns number of processes */ @@ -1803,7 +1818,7 @@ static int ps_read (void) ps_list_reset (); /* Open the kvm interface, get a descriptor */ - kd = kvm_open (NULL, NULL, NULL, 0, errbuf); + kd = kvm_openfiles (NULL, "/dev/null", NULL, 0, errbuf); if (kd == NULL) { ERROR ("processes plugin: Cannot open kvm interface: %s", @@ -2224,14 +2239,16 @@ static int ps_read (void) while ((ent = readdir(proc)) != NULL) { - int pid; + long pid; struct procstat ps; procstat_entry_t pse; + char *endptr; if (!isdigit ((int) ent->d_name[0])) continue; - if ((pid = atoi (ent->d_name)) < 1) + pid = strtol (ent->d_name, &endptr, 10); + if (*endptr != 0) /* value didn't completely parse as a number */ continue; status = ps_read_process (pid, &ps, &state); @@ -2281,8 +2298,7 @@ static int ps_read (void) ps_list_add (ps.name, - ps_get_cmdline ((pid_t) pid, - cmdline, sizeof (cmdline)), + ps_get_cmdline (pid, cmdline, sizeof (cmdline)), &pse); } /* while(readdir) */ closedir (proc); diff --git a/src/swap.c b/src/swap.c index 8af18f4b..a8276c7d 100644 --- a/src/swap.c +++ b/src/swap.c @@ -157,6 +157,8 @@ static int swap_init (void) /* {{{ */ /* #endif defined(VM_SWAPUSAGE) */ #elif HAVE_LIBKVM_GETSWAPINFO + char errbuf[_POSIX2_LINE_MAX]; + if (kvm_obj != NULL) { kvm_close (kvm_obj); @@ -165,14 +167,11 @@ static int swap_init (void) /* {{{ */ kvm_pagesize = getpagesize (); - if ((kvm_obj = kvm_open (NULL, /* execfile */ - NULL, /* corefile */ - NULL, /* swapfile */ - O_RDONLY, /* flags */ - NULL)) /* errstr */ - == NULL) + kvm_obj = kvm_openfiles (NULL, "/dev/null", NULL, O_RDONLY, errbuf); + + if (kvm_obj == NULL) { - ERROR ("swap plugin: kvm_open failed."); + ERROR ("swap plugin: kvm_openfiles failed, %s", errbuf); return (-1); } /* #endif HAVE_LIBKVM_GETSWAPINFO */ diff --git a/src/turbostat.c b/src/turbostat.c new file mode 100644 index 00000000..80650dff --- /dev/null +++ b/src/turbostat.c @@ -0,0 +1,1611 @@ +/* + * turbostat -- Log CPU frequency and C-state residency + * on modern Intel turbo-capable processors for collectd. + * + * Based on the 'turbostat' tool of the Linux kernel, found at + * linux/tools/power/x86/turbostat/turbostat.c: + * ---- + * Copyright (c) 2013 Intel Corporation. + * Len Brown + * + * This program is free software; you can redistribute it and/or modify it + * under the terms and conditions of the GNU General Public License, + * version 2, as published by the Free Software Foundation. + * + * This program is distributed in the hope it will be useful, but WITHOUT + * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or + * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for + * more details. + * + * You should have received a copy of the GNU General Public License along with + * this program; if not, write to the Free Software Foundation, Inc., + * 51 Franklin St - Fifth Floor, Boston, MA 02110-1301 USA. + * ---- + * Ported to collectd by Vincent Brillault + */ + +/* + * _GNU_SOURCE is required because of the following functions: + * - CPU_ISSET_S + * - CPU_ZERO_S + * - CPU_SET_S + * - CPU_FREE + * - CPU_ALLOC + * - CPU_ALLOC_SIZE + */ +#define _GNU_SOURCE + +#include "collectd.h" +#include "common.h" +#include "plugin.h" +#include "utils_time.h" + +#include +#include +#ifdef HAVE_SYS_CAPABILITY_H +#include +#endif /* HAVE_SYS_CAPABILITY_H */ + +#define PLUGIN_NAME "turbostat" + +/* + * This tool uses the Model-Specific Registers (MSRs) present on Intel processors. + * The general description each of these registers, depending on the architecture, + * can be found in the Intel® 64 and IA-32 Architectures Software Developer Manual, + * Volume 3 Chapter 35. + */ + +/* + * If set, aperf_mperf_unstable disables a/mperf based stats. + * This includes: C0 & C1 states, frequency + * + * This value is automatically set if mperf or aperf go backward + */ +static _Bool aperf_mperf_unstable; + +/* + * Bitmask of the list of core C states supported by the processor. + * Currently supported C-states (by this plugin): 3, 6, 7 + */ +static unsigned int do_core_cstate; +static unsigned int config_core_cstate; +static _Bool apply_config_core_cstate; + +/* + * Bitmask of the list of pacages C states supported by the processor. + * Currently supported C-states (by this plugin): 2, 3, 6, 7, 8, 9, 10 + */ +static unsigned int do_pkg_cstate; +static unsigned int config_pkg_cstate; +static _Bool apply_config_pkg_cstate; + +/* + * Boolean indicating if the processor supports 'I/O System-Management Interrupt counter' + */ +static _Bool do_smi; +static _Bool config_smi; +static _Bool apply_config_smi; + +/* + * Boolean indicating if the processor supports 'Digital temperature sensor' + * This feature enables the monitoring of the temperature of each core + * + * This feature has two limitations: + * - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature might be wrong + * - Temperatures above the tcc_activation_temp are not recorded + */ +static _Bool do_dts; +static _Bool config_dts; +static _Bool apply_config_dts; + +/* + * Boolean indicating if the processor supports 'Package thermal management' + * This feature allows the monitoring of the temperature of each package + * + * This feature has two limitations: + * - if MSR_IA32_TEMPERATURE_TARGET is not supported, the absolute temperature might be wrong + * - Temperatures above the tcc_activation_temp are not recorded + */ +static _Bool do_ptm; +static _Bool config_ptm; +static _Bool apply_config_ptm; + +/* + * Thermal Control Circuit Activation Temperature as configured by the user. + * This override the automated detection via MSR_IA32_TEMPERATURE_TARGET + * and should only be used if the automated detection fails. + */ +static unsigned int tcc_activation_temp; + +static unsigned int do_rapl; +static unsigned int config_rapl; +static _Bool apply_config_rapl; +static double rapl_energy_units; + +#define RAPL_PKG (1 << 0) + /* 0x610 MSR_PKG_POWER_LIMIT */ + /* 0x611 MSR_PKG_ENERGY_STATUS */ +#define RAPL_DRAM (1 << 1) + /* 0x618 MSR_DRAM_POWER_LIMIT */ + /* 0x619 MSR_DRAM_ENERGY_STATUS */ + /* 0x61c MSR_DRAM_POWER_INFO */ +#define RAPL_CORES (1 << 2) + /* 0x638 MSR_PP0_POWER_LIMIT */ + /* 0x639 MSR_PP0_ENERGY_STATUS */ + +#define RAPL_GFX (1 << 3) + /* 0x640 MSR_PP1_POWER_LIMIT */ + /* 0x641 MSR_PP1_ENERGY_STATUS */ + /* 0x642 MSR_PP1_POLICY */ +#define TJMAX_DEFAULT 100 + +static cpu_set_t *cpu_present_set, *cpu_affinity_set, *cpu_saved_affinity_set; +static size_t cpu_present_setsize, cpu_affinity_setsize, cpu_saved_affinity_setsize; + +static struct thread_data { + unsigned long long tsc; + unsigned long long aperf; + unsigned long long mperf; + unsigned long long c1; + unsigned int smi_count; + unsigned int cpu_id; + unsigned int flags; +#define CPU_IS_FIRST_THREAD_IN_CORE 0x2 +#define CPU_IS_FIRST_CORE_IN_PACKAGE 0x4 +} *thread_delta, *thread_even, *thread_odd; + +static struct core_data { + unsigned long long c3; + unsigned long long c6; + unsigned long long c7; + unsigned int core_temp_c; + unsigned int core_id; +} *core_delta, *core_even, *core_odd; + +static struct pkg_data { + unsigned long long pc2; + unsigned long long pc3; + unsigned long long pc6; + unsigned long long pc7; + unsigned long long pc8; + unsigned long long pc9; + unsigned long long pc10; + unsigned int package_id; + uint32_t energy_pkg; /* MSR_PKG_ENERGY_STATUS */ + uint32_t energy_dram; /* MSR_DRAM_ENERGY_STATUS */ + uint32_t energy_cores; /* MSR_PP0_ENERGY_STATUS */ + uint32_t energy_gfx; /* MSR_PP1_ENERGY_STATUS */ + unsigned int tcc_activation_temp; + unsigned int pkg_temp_c; +} *package_delta, *package_even, *package_odd; + +#define DELTA_COUNTERS thread_delta, core_delta, package_delta +#define ODD_COUNTERS thread_odd, core_odd, package_odd +#define EVEN_COUNTERS thread_even, core_even, package_even +static _Bool is_even = 1; + +static _Bool allocated = 0; +static _Bool initialized = 0; + +#define GET_THREAD(thread_base, thread_no, core_no, pkg_no) \ + (thread_base + \ + (pkg_no) * topology.num_cores * topology.num_threads + \ + (core_no) * topology.num_threads + \ + (thread_no)) +#define GET_CORE(core_base, core_no, pkg_no) \ + (core_base + \ + (pkg_no) * topology.num_cores + \ + (core_no)) +#define GET_PKG(pkg_base, pkg_no) (pkg_base + pkg_no) + +struct cpu_topology { + unsigned int package_id; + unsigned int core_id; + _Bool first_core_in_package; + _Bool first_thread_in_core; +}; + +static struct topology { + unsigned int max_cpu_id; + unsigned int num_packages; + unsigned int num_cores; + unsigned int num_threads; + struct cpu_topology *cpus; +} topology; + +static cdtime_t time_even, time_odd, time_delta; + +static const char *config_keys[] = +{ + "CoreCstates", + "PackageCstates", + "SystemManagementInterrupt", + "DigitalTemperatureSensor", + "PackageThermalManagement", + "TCCActivationTemp", + "RunningAveragePowerLimit", +}; +static const int config_keys_num = STATIC_ARRAY_SIZE (config_keys); + +/***************************** + * MSR Manipulation helpers * + *****************************/ + +/* + * Open a MSR device for reading + * Can change the scheduling affinity of the current process if multiple_read is 1 + */ +static int __attribute__((warn_unused_result)) +open_msr(unsigned int cpu, _Bool multiple_read) +{ + char pathname[32]; + int fd; + + /* + * If we need to do multiple read, let's migrate to the CPU + * Otherwise, we would lose time calling functions on another CPU + * + * If we are not yet initialized (cpu_affinity_setsize = 0), + * we need to skip this optimisation. + */ + if (multiple_read && cpu_affinity_setsize) { + CPU_ZERO_S(cpu_affinity_setsize, cpu_affinity_set); + CPU_SET_S(cpu, cpu_affinity_setsize, cpu_affinity_set); + if (sched_setaffinity(0, cpu_affinity_setsize, cpu_affinity_set) == -1) { + ERROR("turbostat plugin: Could not migrate to CPU %d", cpu); + return -1; + } + } + + ssnprintf(pathname, sizeof(pathname), "/dev/cpu/%d/msr", cpu); + fd = open(pathname, O_RDONLY); + if (fd < 0) { + ERROR("turbostat plugin: failed to open %s", pathname); + return -1; + } + return fd; +} + +/* + * Read a single MSR from an open file descriptor + */ +static int __attribute__((warn_unused_result)) +read_msr(int fd, off_t offset, unsigned long long *msr) +{ + ssize_t retval; + + retval = pread(fd, msr, sizeof *msr, offset); + + if (retval != sizeof *msr) { + ERROR("turbostat plugin: MSR offset 0x%llx read failed", + (unsigned long long)offset); + return -1; + } + return 0; +} + +/* + * Open a MSR device for reading, read the value asked for and close it. + * This call will not affect the scheduling affinity of this thread. + */ +static ssize_t __attribute__((warn_unused_result)) +get_msr(unsigned int cpu, off_t offset, unsigned long long *msr) +{ + ssize_t retval; + int fd; + + fd = open_msr(cpu, 0); + if (fd < 0) + return fd; + retval = read_msr(fd, offset, msr); + close(fd); + return retval; +} + + +/******************************** + * Raw data acquisition (1 CPU) * + ********************************/ + +/* + * Read every data avalaible for a single CPU + * + * Core data is shared for all threads in one core: extracted only for the first thread + * Package data is shared for all core in one package: extracted only for the first thread of the first core + * + * Side effect: migrates to the targeted CPU + */ +static int __attribute__((warn_unused_result)) +get_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p) +{ + unsigned int cpu = t->cpu_id; + unsigned long long msr; + int msr_fd; + int retval = 0; + + msr_fd = open_msr(cpu, 1); + if (msr_fd < 0) + return msr_fd; + +#define READ_MSR(msr, dst) \ +do { \ + if (read_msr(msr_fd, msr, dst)) { \ + ERROR("turbostat plugin: Unable to read " #msr); \ + retval = -1; \ + goto out; \ + } \ +} while (0) + + READ_MSR(MSR_IA32_TSC, &t->tsc); + + READ_MSR(MSR_IA32_APERF, &t->aperf); + READ_MSR(MSR_IA32_MPERF, &t->mperf); + + if (do_smi) { + READ_MSR(MSR_SMI_COUNT, &msr); + t->smi_count = msr & 0xFFFFFFFF; + } + + /* collect core counters only for 1st thread in core */ + if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE)) { + retval = 0; + goto out; + } + + if (do_core_cstate & (1 << 3)) + READ_MSR(MSR_CORE_C3_RESIDENCY, &c->c3); + if (do_core_cstate & (1 << 6)) + READ_MSR(MSR_CORE_C6_RESIDENCY, &c->c6); + if (do_core_cstate & (1 << 7)) + READ_MSR(MSR_CORE_C7_RESIDENCY, &c->c7); + + if (do_dts) { + READ_MSR(MSR_IA32_THERM_STATUS, &msr); + c->core_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F); + } + + /* collect package counters only for 1st core in package */ + if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) { + retval = 0; + goto out; + } + + if (do_pkg_cstate & (1 << 2)) + READ_MSR(MSR_PKG_C2_RESIDENCY, &p->pc2); + if (do_pkg_cstate & (1 << 3)) + READ_MSR(MSR_PKG_C3_RESIDENCY, &p->pc3); + if (do_pkg_cstate & (1 << 6)) + READ_MSR(MSR_PKG_C6_RESIDENCY, &p->pc6); + if (do_pkg_cstate & (1 << 7)) + READ_MSR(MSR_PKG_C7_RESIDENCY, &p->pc7); + if (do_pkg_cstate & (1 << 8)) + READ_MSR(MSR_PKG_C8_RESIDENCY, &p->pc8); + if (do_pkg_cstate & (1 << 9)) + READ_MSR(MSR_PKG_C9_RESIDENCY, &p->pc9); + if (do_pkg_cstate & (1 << 10)) + READ_MSR(MSR_PKG_C10_RESIDENCY, &p->pc10); + + if (do_rapl & RAPL_PKG) { + READ_MSR(MSR_PKG_ENERGY_STATUS, &msr); + p->energy_pkg = msr & 0xFFFFFFFF; + } + if (do_rapl & RAPL_CORES) { + READ_MSR(MSR_PP0_ENERGY_STATUS, &msr); + p->energy_cores = msr & 0xFFFFFFFF; + } + if (do_rapl & RAPL_DRAM) { + READ_MSR(MSR_DRAM_ENERGY_STATUS, &msr); + p->energy_dram = msr & 0xFFFFFFFF; + } + if (do_rapl & RAPL_GFX) { + READ_MSR(MSR_PP1_ENERGY_STATUS, &msr); + p->energy_gfx = msr & 0xFFFFFFFF; + } + if (do_ptm) { + READ_MSR(MSR_IA32_PACKAGE_THERM_STATUS, &msr); + p->pkg_temp_c = p->tcc_activation_temp - ((msr >> 16) & 0x7F); + } + +out: + close(msr_fd); + return retval; +} + + +/********************************** + * Evaluating the changes (1 CPU) * + **********************************/ + +/* + * Extract the evolution old->new in delta at a package level + * (some are not new-delta, e.g. temperature) + */ +static inline void +delta_package(struct pkg_data *delta, const struct pkg_data *new, const struct pkg_data *old) +{ + delta->pc2 = new->pc2 - old->pc2; + delta->pc3 = new->pc3 - old->pc3; + delta->pc6 = new->pc6 - old->pc6; + delta->pc7 = new->pc7 - old->pc7; + delta->pc8 = new->pc8 - old->pc8; + delta->pc9 = new->pc9 - old->pc9; + delta->pc10 = new->pc10 - old->pc10; + delta->pkg_temp_c = new->pkg_temp_c; + + delta->energy_pkg = new->energy_pkg - old->energy_pkg; + delta->energy_cores = new->energy_cores - old->energy_cores; + delta->energy_gfx = new->energy_gfx - old->energy_gfx; + delta->energy_dram = new->energy_dram - old->energy_dram; +} + +/* + * Extract the evolution old->new in delta at a core level + * (some are not new-delta, e.g. temperature) + */ +static inline void +delta_core(struct core_data *delta, const struct core_data *new, const struct core_data *old) +{ + delta->c3 = new->c3 - old->c3; + delta->c6 = new->c6 - old->c6; + delta->c7 = new->c7 - old->c7; + delta->core_temp_c = new->core_temp_c; +} + +/* + * Extract the evolution old->new in delta at a package level + * core_delta is required for c1 estimation (tsc - c0 - all core cstates) + */ +static inline int __attribute__((warn_unused_result)) +delta_thread(struct thread_data *delta, const struct thread_data *new, const struct thread_data *old, + const struct core_data *core_delta) +{ + delta->tsc = new->tsc - old->tsc; + + /* check for TSC < 1 Mcycles over interval */ + if (delta->tsc < (1000 * 1000)) { + WARNING("turbostat plugin: Insanely slow TSC rate, TSC stops " + "in idle? You can disable all c-states by booting with" + " 'idle=poll' or just the deep ones with" + " 'processor.max_cstate=1'"); + return -1; + } + + delta->c1 = new->c1 - old->c1; + + if ((new->aperf > old->aperf) && (new->mperf > old->mperf)) { + delta->aperf = new->aperf - old->aperf; + delta->mperf = new->mperf - old->mperf; + } else { + if (!aperf_mperf_unstable) { + WARNING("turbostat plugin: APERF or MPERF went " + "backwards. Frequency results do not cover " + "the entire interval. Fix this by running " + "Linux-2.6.30 or later."); + + aperf_mperf_unstable = 1; + } + } + + /* + * As counter collection is not atomic, + * it is possible for mperf's non-halted cycles + idle states + * to exceed TSC's all cycles: show c1 = 0% in that case. + */ + if ((delta->mperf + core_delta->c3 + core_delta->c6 + core_delta->c7) > delta->tsc) + delta->c1 = 0; + else { + /* normal case, derive c1 */ + delta->c1 = delta->tsc - delta->mperf - core_delta->c3 + - core_delta->c6 - core_delta->c7; + } + + if (delta->mperf == 0) { + WARNING("turbostat plugin: cpu%d MPERF 0!", old->cpu_id); + delta->mperf = 1; /* divide by 0 protection */ + } + + if (do_smi) + delta->smi_count = new->smi_count - old->smi_count; + + return 0; +} + +/********************************** + * Submitting the results (1 CPU) * + **********************************/ + +/* + * Submit one gauge value + */ +static void +turbostat_submit (const char *plugin_instance, + const char *type, const char *type_instance, + gauge_t value) +{ + value_list_t vl = VALUE_LIST_INIT; + value_t v; + + v.gauge = value; + vl.values = &v; + vl.values_len = 1; + sstrncpy (vl.host, hostname_g, sizeof (vl.host)); + sstrncpy (vl.plugin, PLUGIN_NAME, sizeof (vl.plugin)); + if (plugin_instance != NULL) + sstrncpy (vl.plugin_instance, plugin_instance, sizeof (vl.plugin_instance)); + sstrncpy (vl.type, type, sizeof (vl.type)); + if (type_instance != NULL) + sstrncpy (vl.type_instance, type_instance, sizeof (vl.type_instance)); + + plugin_dispatch_values (&vl); +} + +/* + * Submit every data for a single CPU + * + * Core data is shared for all threads in one core: submitted only for the first thread + * Package data is shared for all core in one package: submitted only for the first thread of the first core + */ +static int +submit_counters(struct thread_data *t, struct core_data *c, struct pkg_data *p) +{ + char name[DATA_MAX_NAME_LEN]; + double interval_float; + + interval_float = CDTIME_T_TO_DOUBLE(time_delta); + + ssnprintf(name, sizeof(name), "cpu%02d", t->cpu_id); + + if (!aperf_mperf_unstable) + turbostat_submit(name, "percent", "c0", 100.0 * t->mperf/t->tsc); + if (!aperf_mperf_unstable) + turbostat_submit(name, "percent", "c1", 100.0 * t->c1/t->tsc); + + turbostat_submit(name, "frequency", "average", 1.0 / 1000000 * t->aperf / interval_float); + + if ((!aperf_mperf_unstable) || (!(t->aperf > t->tsc || t->mperf > t->tsc))) + turbostat_submit(name, "frequency", "busy", 1.0 * t->tsc / 1000000 * t->aperf / t->mperf / interval_float); + + /* Sanity check (should stay stable) */ + turbostat_submit(name, "gauge", "TSC", 1.0 * t->tsc / 1000000 / interval_float); + + /* SMI */ + if (do_smi) + turbostat_submit(name, "count", NULL, t->smi_count); + + /* submit per-core data only for 1st thread in core */ + if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE)) + goto done; + + ssnprintf(name, sizeof(name), "core%02d", c->core_id); + + if (do_core_cstate & (1 << 3)) + turbostat_submit(name, "percent", "c3", 100.0 * c->c3/t->tsc); + if (do_core_cstate & (1 << 6)) + turbostat_submit(name, "percent", "c6", 100.0 * c->c6/t->tsc); + if (do_core_cstate & (1 << 7)) + turbostat_submit(name, "percent", "c7", 100.0 * c->c7/t->tsc); + + if (do_dts) + turbostat_submit(name, "temperature", NULL, c->core_temp_c); + + /* submit per-package data only for 1st core in package */ + if (!(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) + goto done; + + ssnprintf(name, sizeof(name), "pkg%02d", p->package_id); + + if (do_ptm) + turbostat_submit(name, "temperature", NULL, p->pkg_temp_c); + + if (do_pkg_cstate & (1 << 2)) + turbostat_submit(name, "percent", "pc2", 100.0 * p->pc2/t->tsc); + if (do_pkg_cstate & (1 << 3)) + turbostat_submit(name, "percent", "pc3", 100.0 * p->pc3/t->tsc); + if (do_pkg_cstate & (1 << 6)) + turbostat_submit(name, "percent", "pc6", 100.0 * p->pc6/t->tsc); + if (do_pkg_cstate & (1 << 7)) + turbostat_submit(name, "percent", "pc7", 100.0 * p->pc7/t->tsc); + if (do_pkg_cstate & (1 << 8)) + turbostat_submit(name, "percent", "pc8", 100.0 * p->pc8/t->tsc); + if (do_pkg_cstate & (1 << 9)) + turbostat_submit(name, "percent", "pc9", 100.0 * p->pc9/t->tsc); + if (do_pkg_cstate & (1 << 10)) + turbostat_submit(name, "percent", "pc10", 100.0 * p->pc10/t->tsc); + + if (do_rapl) { + if (do_rapl & RAPL_PKG) + turbostat_submit(name, "power", "pkg", p->energy_pkg * rapl_energy_units / interval_float); + if (do_rapl & RAPL_CORES) + turbostat_submit(name, "power", "cores", p->energy_cores * rapl_energy_units / interval_float); + if (do_rapl & RAPL_GFX) + turbostat_submit(name, "power", "GFX", p->energy_gfx * rapl_energy_units / interval_float); + if (do_rapl & RAPL_DRAM) + turbostat_submit(name, "power", "DRAM", p->energy_dram * rapl_energy_units / interval_float); + } +done: + return 0; +} + + +/********************************** + * Looping function over all CPUs * + **********************************/ + +/* + * Check if a given cpu id is in our compiled list of existing CPUs + */ +static int +cpu_is_not_present(unsigned int cpu) +{ + return !CPU_ISSET_S(cpu, cpu_present_setsize, cpu_present_set); +} + +/* + * Loop on all CPUs in topological order + * + * Skip non-present cpus + * Return the error code at the first error or 0 + */ +static int __attribute__((warn_unused_result)) +for_all_cpus(int (func)(struct thread_data *, struct core_data *, struct pkg_data *), + struct thread_data *thread_base, struct core_data *core_base, struct pkg_data *pkg_base) +{ + int retval; + unsigned int pkg_no, core_no, thread_no; + + for (pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) { + for (core_no = 0; core_no < topology.num_cores; ++core_no) { + for (thread_no = 0; thread_no < topology.num_threads; ++thread_no) { + struct thread_data *t; + struct core_data *c; + struct pkg_data *p; + + t = GET_THREAD(thread_base, thread_no, core_no, pkg_no); + + if (cpu_is_not_present(t->cpu_id)) + continue; + + c = GET_CORE(core_base, core_no, pkg_no); + p = GET_PKG(pkg_base, pkg_no); + + retval = func(t, c, p); + if (retval) + return retval; + } + } + } + return 0; +} + +/* + * Dedicated loop: Extract every data evolution for all CPU + * + * Skip non-present cpus + * Return the error code at the first error or 0 + * + * Core data is shared for all threads in one core: extracted only for the first thread + * Package data is shared for all core in one package: extracted only for the first thread of the first core + */ +static int __attribute__((warn_unused_result)) +for_all_cpus_delta(const struct thread_data *thread_new_base, const struct core_data *core_new_base, const struct pkg_data *pkg_new_base, + const struct thread_data *thread_old_base, const struct core_data *core_old_base, const struct pkg_data *pkg_old_base) +{ + int retval; + unsigned int pkg_no, core_no, thread_no; + + for (pkg_no = 0; pkg_no < topology.num_packages; ++pkg_no) { + for (core_no = 0; core_no < topology.num_cores; ++core_no) { + for (thread_no = 0; thread_no < topology.num_threads; ++thread_no) { + struct thread_data *t_delta; + const struct thread_data *t_old, *t_new; + struct core_data *c_delta; + + /* Get correct pointers for threads */ + t_delta = GET_THREAD(thread_delta, thread_no, core_no, pkg_no); + t_new = GET_THREAD(thread_new_base, thread_no, core_no, pkg_no); + t_old = GET_THREAD(thread_old_base, thread_no, core_no, pkg_no); + + /* Skip threads that disappeared */ + if (cpu_is_not_present(t_delta->cpu_id)) + continue; + + /* c_delta is always required for delta_thread */ + c_delta = GET_CORE(core_delta, core_no, pkg_no); + + /* calculate core delta only for 1st thread in core */ + if (t_new->flags & CPU_IS_FIRST_THREAD_IN_CORE) { + const struct core_data *c_old, *c_new; + + c_new = GET_CORE(core_new_base, core_no, pkg_no); + c_old = GET_CORE(core_old_base, core_no, pkg_no); + + delta_core(c_delta, c_new, c_old); + } + + /* Always calculate thread delta */ + retval = delta_thread(t_delta, t_new, t_old, c_delta); + if (retval) + return retval; + + /* calculate package delta only for 1st core in package */ + if (t_new->flags & CPU_IS_FIRST_CORE_IN_PACKAGE) { + struct pkg_data *p_delta; + const struct pkg_data *p_old, *p_new; + + p_delta = GET_PKG(package_delta, pkg_no); + p_new = GET_PKG(pkg_new_base, pkg_no); + p_old = GET_PKG(pkg_old_base, pkg_no); + + delta_package(p_delta, p_new, p_old); + } + } + } + } + return 0; +} + + +/*************** + * CPU Probing * + ***************/ + +/* + * MSR_IA32_TEMPERATURE_TARGET indicates the temperature where + * the Thermal Control Circuit (TCC) activates. + * This is usually equal to tjMax. + * + * Older processors do not have this MSR, so there we guess, + * but also allow conficuration over-ride with "TCCActivationTemp". + * + * Several MSR temperature values are in units of degrees-C + * below this value, including the Digital Thermal Sensor (DTS), + * Package Thermal Management Sensor (PTM), and thermal event thresholds. + */ +static int __attribute__((warn_unused_result)) +set_temperature_target(struct thread_data *t, struct core_data *c, struct pkg_data *p) +{ + unsigned long long msr; + unsigned int target_c_local; + + /* tcc_activation_temp is used only for dts or ptm */ + if (!(do_dts || do_ptm)) + return 0; + + /* this is a per-package concept */ + if (!(t->flags & CPU_IS_FIRST_THREAD_IN_CORE) || !(t->flags & CPU_IS_FIRST_CORE_IN_PACKAGE)) + return 0; + + if (tcc_activation_temp != 0) { + p->tcc_activation_temp = tcc_activation_temp; + return 0; + } + + if (get_msr(t->cpu_id, MSR_IA32_TEMPERATURE_TARGET, &msr)) + goto guess; + + target_c_local = (msr >> 16) & 0xFF; + + if (!target_c_local) + goto guess; + + p->tcc_activation_temp = target_c_local; + + return 0; + +guess: + p->tcc_activation_temp = TJMAX_DEFAULT; + WARNING("turbostat plugin: cpu%d: Guessing tjMax %d C," + " Please use TCCActivationTemp to specify it.", + t->cpu_id, p->tcc_activation_temp); + + return 0; +} + +/* + * Identify the functionality of the CPU + */ +static int __attribute__((warn_unused_result)) +probe_cpu() +{ + unsigned int eax, ebx, ecx, edx, max_level; + unsigned int fms, family, model; + + /* CPUID(0): + * - EAX: Maximum Input Value for Basic CPUID Information + * - EBX: "Genu" (0x756e6547) + * - EDX: "ineI" (0x49656e69) + * - ECX: "ntel" (0x6c65746e) + */ + max_level = ebx = ecx = edx = 0; + __get_cpuid(0, &max_level, &ebx, &ecx, &edx); + if (ebx != 0x756e6547 && edx != 0x49656e69 && ecx != 0x6c65746e) { + ERROR("turbostat plugin: Unsupported CPU (not Intel)"); + return -1; + } + + /* CPUID(1): + * - EAX: Version Information: Type, Family, Model, and Stepping ID + * + 4-7: Model ID + * + 8-11: Family ID + * + 12-13: Processor type + * + 16-19: Extended Model ID + * + 20-27: Extended Family ID + * - EDX: Feature Information: + * + 5: Support for MSR read/write operations + */ + fms = ebx = ecx = edx = 0; + __get_cpuid(1, &fms, &ebx, &ecx, &edx); + family = (fms >> 8) & 0xf; + model = (fms >> 4) & 0xf; + if (family == 0xf) + family += (fms >> 20) & 0xf; + if (family == 6 || family == 0xf) + model += ((fms >> 16) & 0xf) << 4; + if (!(edx & (1 << 5))) { + ERROR("turbostat plugin: Unsupported CPU (no MSR support)"); + return -1; + } + + /* + * CPUID(6): + * - EAX: + * + 0: Digital temperature sensor is supported if set + * + 6: Package thermal management is supported if set + * - ECX: + * + 0: Hardware Coordination Feedback Capability (Presence of IA32_MPERF and IA32_APERF). + * + 3: The processor supports performance-energy bias preference if set. + * It also implies the presence of a new architectural MSR called IA32_ENERGY_PERF_BIAS + * + * This check is valid for both Intel and AMD + */ + eax = ebx = ecx = edx = 0; + __get_cpuid(0x6, &eax, &ebx, &ecx, &edx); + do_dts = eax & (1 << 0); + do_ptm = eax & (1 << 6); + if (!(ecx & (1 << 0))) { + ERROR("turbostat plugin: Unsupported CPU (No APERF)"); + return -1; + } + + /* + * Enable or disable C states depending on the model and family + */ + if (family == 6) { + switch (model) { + /* Atom (partial) */ + case 0x27: + do_smi = 0; + do_core_cstate = 0; + do_pkg_cstate = (1 << 2) | (1 << 4) | (1 << 6); + break; + /* Silvermont */ + case 0x37: /* BYT */ + case 0x4D: /* AVN */ + do_smi = 1; + do_core_cstate = (1 << 1) | (1 << 6); + do_pkg_cstate = (1 << 6); + break; + /* Nehalem */ + case 0x1A: /* Core i7, Xeon 5500 series - Bloomfield, Gainstown NHM-EP */ + case 0x1E: /* Core i7 and i5 Processor - Clarksfield, Lynnfield, Jasper Forest */ + case 0x1F: /* Core i7 and i5 Processor - Nehalem */ + case 0x2E: /* Nehalem-EX Xeon - Beckton */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6); + do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7); + break; + /* Westmere */ + case 0x25: /* Westmere Client - Clarkdale, Arrandale */ + case 0x2C: /* Westmere EP - Gulftown */ + case 0x2F: /* Westmere-EX Xeon - Eagleton */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6); + do_pkg_cstate = (1 << 3) | (1 << 6) | (1 << 7); + break; + /* Sandy Bridge */ + case 0x2A: /* SNB */ + case 0x2D: /* SNB Xeon */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7); + break; + /* Ivy Bridge */ + case 0x3A: /* IVB */ + case 0x3E: /* IVB Xeon */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7); + break; + /* Haswell Bridge */ + case 0x3C: /* HSW */ + case 0x3F: /* HSW */ + case 0x46: /* HSW */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7); + break; + case 0x45: /* HSW */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10); + break; + /* Broadwel */ + case 0x4F: /* BDW */ + case 0x56: /* BDX-DE */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7); + break; + case 0x3D: /* BDW */ + do_smi = 1; + do_core_cstate = (1 << 3) | (1 << 6) | (1 << 7); + do_pkg_cstate = (1 << 2) | (1 << 3) | (1 << 6) | (1 << 7) | (1 << 8) | (1 << 9) | (1 << 10); + break; + default: + do_smi = 0; + do_core_cstate = 0; + do_pkg_cstate = 0; + break; + } + switch (model) { + case 0x2A: /* SNB */ + case 0x3A: /* IVB */ + case 0x3C: /* HSW */ + case 0x45: /* HSW */ + case 0x46: /* HSW */ + case 0x3D: /* BDW */ + do_rapl = RAPL_PKG | RAPL_CORES | RAPL_GFX; + break; + case 0x3F: /* HSX */ + case 0x4F: /* BDX */ + case 0x56: /* BDX-DE */ + do_rapl = RAPL_PKG | RAPL_DRAM ; + break; + case 0x2D: /* SNB Xeon */ + case 0x3E: /* IVB Xeon */ + do_rapl = RAPL_PKG | RAPL_CORES | RAPL_DRAM; + break; + case 0x37: /* BYT */ + case 0x4D: /* AVN */ + do_rapl = RAPL_PKG | RAPL_CORES; + break; + default: + do_rapl = 0; + } + } else { + ERROR("turbostat plugin: Unsupported CPU (family: %#x, " + "model: %#x)", family, model); + return -1; + } + + /* Override detected values with configuration */ + if (apply_config_core_cstate) + do_core_cstate = config_core_cstate; + if (apply_config_pkg_cstate) + do_pkg_cstate = config_pkg_cstate; + if (apply_config_smi) + do_smi = config_smi; + if (apply_config_dts) + do_dts = config_dts; + if (apply_config_ptm) + do_ptm = config_ptm; + if (apply_config_rapl) + do_rapl = config_rapl; + + if (do_rapl) { + unsigned long long msr; + if (get_msr(0, MSR_RAPL_POWER_UNIT, &msr)) + return 0; + + if (model == 0x37) + rapl_energy_units = 1.0 * (1 << (msr >> 8 & 0x1F)) / 1000000; + else + rapl_energy_units = 1.0 / (1 << (msr >> 8 & 0x1F)); + } + + return 0; +} + + +/******************** + * Topology Probing * + ********************/ + +/* + * Read a single int from a file. + */ +static int __attribute__ ((format(printf,1,2))) +parse_int_file(const char *fmt, ...) +{ + va_list args; + char path[PATH_MAX]; + FILE *filep; + int len, value; + + va_start(args, fmt); + len = vsnprintf(path, sizeof(path), fmt, args); + va_end(args); + if (len < 0 || len >= PATH_MAX) { + ERROR("turbostat plugin: path truncated: '%s'", path); + return -1; + } + + filep = fopen(path, "r"); + if (!filep) { + ERROR("turbostat plugin: Failed to open '%s'", path); + return -1; + } + if (fscanf(filep, "%d", &value) != 1) { + ERROR("turbostat plugin: Failed to parse number from '%s'", path); + return -1; + } + fclose(filep); + return value; +} + +static int +get_threads_on_core(unsigned int cpu) +{ + char path[80]; + FILE *filep; + int sib1, sib2; + int matches; + char character; + + ssnprintf(path, sizeof(path), "/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", cpu); + filep = fopen(path, "r"); + if (!filep) { + ERROR("turbostat plugin: Failed to open '%s'", path); + return -1; + } + /* + * file format: + * if a pair of number with a character between: 2 siblings (eg. 1-2, or 1,4) + * otherwinse 1 sibling (self). + */ + matches = fscanf(filep, "%d%c%d\n", &sib1, &character, &sib2); + + fclose(filep); + + if (matches == 3) + return 2; + else + return 1; +} + +/* + * run func(cpu) on every cpu in /proc/stat + * return max_cpu number + */ +static int __attribute__((warn_unused_result)) +for_all_proc_cpus(int (func)(unsigned int)) +{ + FILE *fp; + unsigned int cpu_num; + int retval; + + fp = fopen("/proc/stat", "r"); + if (!fp) { + ERROR("turbostat plugin: Failed to open /proc/stat"); + return -1; + } + + retval = fscanf(fp, "cpu %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n"); + if (retval != 0) { + ERROR("turbostat plugin: Failed to parse /proc/stat"); + fclose(fp); + return -1; + } + + while (1) { + retval = fscanf(fp, "cpu%u %*d %*d %*d %*d %*d %*d %*d %*d %*d %*d\n", &cpu_num); + if (retval != 1) + break; + + retval = func(cpu_num); + if (retval) { + fclose(fp); + return(retval); + } + } + fclose(fp); + return 0; +} + +/* + * Update the stored topology.max_cpu_id + */ +static int +update_max_cpu_id(unsigned int cpu) +{ + if (topology.max_cpu_id < cpu) + topology.max_cpu_id = cpu; + return 0; +} + +static int +mark_cpu_present(unsigned int cpu) +{ + CPU_SET_S(cpu, cpu_present_setsize, cpu_present_set); + return 0; +} + +static int __attribute__((warn_unused_result)) +allocate_cpu_set(cpu_set_t ** set, size_t * size) { + *set = CPU_ALLOC(topology.max_cpu_id + 1); + if (*set == NULL) { + ERROR("turbostat plugin: Unable to allocate CPU state"); + return -1; + } + *size = CPU_ALLOC_SIZE(topology.max_cpu_id + 1); + CPU_ZERO_S(*size, *set); + return 0; +} + +/* + * Build a local representation of the cpu distribution + */ +static int __attribute__((warn_unused_result)) +topology_probe() +{ + unsigned int i; + int ret; + unsigned int max_package_id, max_core_id, max_threads; + max_package_id = max_core_id = max_threads = 0; + + /* Clean topology */ + free(topology.cpus); + memset(&topology, 0, sizeof(topology)); + + ret = for_all_proc_cpus(update_max_cpu_id); + if (ret != 0) + goto err; + + topology.cpus = calloc(1, (topology.max_cpu_id + 1) * sizeof(struct cpu_topology)); + if (topology.cpus == NULL) { + ERROR("turbostat plugin: Unable to allocate memory for CPU topology"); + return -1; + } + + ret = allocate_cpu_set(&cpu_present_set, &cpu_present_setsize); + if (ret != 0) + goto err; + ret = allocate_cpu_set(&cpu_affinity_set, &cpu_affinity_setsize); + if (ret != 0) + goto err; + ret = allocate_cpu_set(&cpu_saved_affinity_set, &cpu_saved_affinity_setsize); + if (ret != 0) + goto err; + + ret = for_all_proc_cpus(mark_cpu_present); + if (ret != 0) + goto err; + + /* + * For online cpus + * find max_core_id, max_package_id + */ + for (i = 0; i <= topology.max_cpu_id; ++i) { + unsigned int num_threads; + struct cpu_topology *cpu = &topology.cpus[i]; + + if (cpu_is_not_present(i)) { + WARNING("turbostat plugin: cpu%d NOT PRESENT", i); + continue; + } + + ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/physical_package_id", i); + if (ret < 0) + goto err; + else + cpu->package_id = (unsigned int) ret; + if (cpu->package_id > max_package_id) + max_package_id = cpu->package_id; + + ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_id", i); + if (ret < 0) + goto err; + else + cpu->core_id = (unsigned int) ret; + if (cpu->core_id > max_core_id) + max_core_id = cpu->core_id; + ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/core_siblings_list", i); + if (ret < 0) + goto err; + else if ((unsigned int) ret == i) + cpu->first_core_in_package = 1; + + ret = get_threads_on_core(i); + if (ret < 0) + goto err; + else + num_threads = (unsigned int) ret; + if (num_threads > max_threads) + max_threads = num_threads; + ret = parse_int_file("/sys/devices/system/cpu/cpu%d/topology/thread_siblings_list", i); + if (ret < 0) + goto err; + else if ((unsigned int) ret == i) + cpu->first_thread_in_core = 1; + + DEBUG("turbostat plugin: cpu %d pkg %d core %d\n", + i, cpu->package_id, cpu->core_id); + } + /* Num is max + 1 (need to count 0) */ + topology.num_packages = max_package_id + 1; + topology.num_cores = max_core_id + 1; + topology.num_threads = max_threads; + + return 0; +err: + free(topology.cpus); + return ret; +} + + +/************************ + * Main alloc/init/free * + ************************/ + +static int +allocate_counters(struct thread_data **threads, struct core_data **cores, struct pkg_data **packages) +{ + unsigned int i; + unsigned int total_threads, total_cores; + + total_threads = topology.num_threads * topology.num_cores * topology.num_packages; + *threads = calloc(total_threads, sizeof(struct thread_data)); + if (*threads == NULL) + goto err; + + for (i = 0; i < total_threads; ++i) + (*threads)[i].cpu_id = topology.max_cpu_id + 1; + + total_cores = topology.num_cores * topology.num_packages; + *cores = calloc(total_cores, sizeof(struct core_data)); + if (*cores == NULL) + goto err_clean_threads; + + *packages = calloc(topology.num_packages, sizeof(struct pkg_data)); + if (*packages == NULL) + goto err_clean_cores; + + return 0; + +err_clean_cores: + free(*cores); +err_clean_threads: + free(*threads); +err: + ERROR("turbostat plugin: Failled to allocate memory for counters"); + return -1; +} + +static void +init_counter(struct thread_data *thread_base, struct core_data *core_base, + struct pkg_data *pkg_base, unsigned int cpu_id) +{ + struct thread_data *t; + struct core_data *c; + struct pkg_data *p; + struct cpu_topology *cpu = &topology.cpus[cpu_id]; + + t = GET_THREAD(thread_base, !(cpu->first_thread_in_core), cpu->core_id, cpu->package_id); + c = GET_CORE(core_base, cpu->core_id, cpu->package_id); + p = GET_PKG(pkg_base, cpu->package_id); + + t->cpu_id = cpu_id; + if (cpu->first_thread_in_core) + t->flags |= CPU_IS_FIRST_THREAD_IN_CORE; + if (cpu->first_core_in_package) + t->flags |= CPU_IS_FIRST_CORE_IN_PACKAGE; + + c->core_id = cpu->core_id; + p->package_id = cpu->package_id; +} + +static void +initialize_counters(void) +{ + unsigned int cpu_id; + + for (cpu_id = 0; cpu_id <= topology.max_cpu_id; ++cpu_id) { + if (cpu_is_not_present(cpu_id)) + continue; + init_counter(EVEN_COUNTERS, cpu_id); + init_counter(ODD_COUNTERS, cpu_id); + init_counter(DELTA_COUNTERS, cpu_id); + } +} + + + +static void +free_all_buffers(void) +{ + allocated = 0; + initialized = 0; + + CPU_FREE(cpu_present_set); + cpu_present_set = NULL; + cpu_present_set = 0; + + CPU_FREE(cpu_affinity_set); + cpu_affinity_set = NULL; + cpu_affinity_setsize = 0; + + CPU_FREE(cpu_saved_affinity_set); + cpu_saved_affinity_set = NULL; + cpu_saved_affinity_setsize = 0; + + free(thread_even); + free(core_even); + free(package_even); + + thread_even = NULL; + core_even = NULL; + package_even = NULL; + + free(thread_odd); + free(core_odd); + free(package_odd); + + thread_odd = NULL; + core_odd = NULL; + package_odd = NULL; + + free(thread_delta); + free(core_delta); + free(package_delta); + + thread_delta = NULL; + core_delta = NULL; + package_delta = NULL; +} + + +/********************** + * Collectd functions * + **********************/ + +#define DO_OR_GOTO_ERR(something) \ +do { \ + ret = (something); \ + if (ret < 0) \ + goto err; \ +} while (0) + +static int setup_all_buffers(void) +{ + int ret; + + DO_OR_GOTO_ERR(topology_probe()); + DO_OR_GOTO_ERR(allocate_counters(&thread_even, &core_even, &package_even)); + DO_OR_GOTO_ERR(allocate_counters(&thread_odd, &core_odd, &package_odd)); + DO_OR_GOTO_ERR(allocate_counters(&thread_delta, &core_delta, &package_delta)); + initialize_counters(); + DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, EVEN_COUNTERS)); + DO_OR_GOTO_ERR(for_all_cpus(set_temperature_target, ODD_COUNTERS)); + + allocated = 1; + return 0; +err: + free_all_buffers(); + return ret; +} + +static int +turbostat_read(void) +{ + int ret; + + if (!allocated) { + if ((ret = setup_all_buffers()) < 0) + return ret; + } + + if (for_all_proc_cpus(cpu_is_not_present)) { + free_all_buffers(); + if ((ret = setup_all_buffers()) < 0) + return ret; + if (for_all_proc_cpus(cpu_is_not_present)) { + ERROR("turbostat plugin: CPU appeared just after " + "initialization"); + return -1; + } + } + + /* Saving the scheduling affinity, as it will be modified by get_counters */ + if (sched_getaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set) != 0) { + ERROR("turbostat plugin: Unable to save the CPU affinity"); + return -1; + } + + if (!initialized) { + if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0) + goto out; + time_even = cdtime(); + is_even = 1; + initialized = 1; + ret = 0; + goto out; + } + + if (is_even) { + if ((ret = for_all_cpus(get_counters, ODD_COUNTERS)) < 0) + goto out; + time_odd = cdtime(); + is_even = 0; + time_delta = time_odd - time_even; + if ((ret = for_all_cpus_delta(ODD_COUNTERS, EVEN_COUNTERS)) < 0) + goto out; + if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0) + goto out; + } else { + if ((ret = for_all_cpus(get_counters, EVEN_COUNTERS)) < 0) + goto out; + time_even = cdtime(); + is_even = 1; + time_delta = time_even - time_odd; + if ((ret = for_all_cpus_delta(EVEN_COUNTERS, ODD_COUNTERS)) < 0) + goto out; + if ((ret = for_all_cpus(submit_counters, DELTA_COUNTERS)) < 0) + goto out; + } + ret = 0; +out: + /* + * Let's restore the affinity + * This might fail if the number of CPU changed, but we can't do anything in that case.. + */ + (void)sched_setaffinity(0, cpu_saved_affinity_setsize, cpu_saved_affinity_set); + return ret; +} + +static int +check_permissions(void) +{ +#ifdef HAVE_SYS_CAPABILITY_H + struct __user_cap_header_struct cap_header_data; + cap_user_header_t cap_header = &cap_header_data; + struct __user_cap_data_struct cap_data_data; + cap_user_data_t cap_data = &cap_data_data; + int ret = 0; +#endif /* HAVE_SYS_CAPABILITY_H */ + + if (getuid() == 0) { + /* We have everything we need */ + return 0; +#ifndef HAVE_SYS_CAPABILITY_H + } else { + ERROR("turbostat plugin: Initialization failed: this plugin " + "requires collectd to run as root"); + return -1; + } +#else /* HAVE_SYS_CAPABILITY_H */ + } + + /* check for CAP_SYS_RAWIO */ + cap_header->pid = getpid(); + cap_header->version = _LINUX_CAPABILITY_VERSION; + if (capget(cap_header, cap_data) < 0) { + ERROR("turbostat plugin: capget failed"); + return -1; + } + + if ((cap_data->effective & (1 << CAP_SYS_RAWIO)) == 0) { + WARNING("turbostat plugin: Collectd doesn't have the " + "CAP_SYS_RAWIO capability. If you don't want to run " + "collectd as root, try running \"setcap " + "cap_sys_rawio=ep\" on collectd binary"); + ret = -1; + } + + if (euidaccess("/dev/cpu/0/msr", R_OK)) { + WARNING("turbostat plugin: Collectd cannot open" + "/dev/cpu/0/msr. If you don't want to run collectd as " + "root, you need to change the ownership (chown) and " + "permissions on /dev/cpu/*/msr to allow such access"); + ret = -1; + } + + if (ret != 0) + ERROR("turbostat plugin: Initialization failed: this plugin " + "requires collectd to either to run as root or give " + "collectd a special capability (CAP_SYS_RAWIO) and read " + "access to /dev/cpu/*/msr (see previous warnings)"); + return ret; +#endif /* HAVE_SYS_CAPABILITY_H */ +} + +static int +turbostat_init(void) +{ + struct stat sb; + int ret; + + if (stat("/dev/cpu/0/msr", &sb)) { + ERROR("turbostat plugin: Initialization failed: /dev/cpu/0/msr" + " does not exist while the CPU supports MSR. You may be " + "missing the corresponding kernel module, please try '# " + "modprobe msr'"); + return -1; + } + + DO_OR_GOTO_ERR(check_permissions()); + + DO_OR_GOTO_ERR(probe_cpu()); + + DO_OR_GOTO_ERR(setup_all_buffers()); + + plugin_register_read(PLUGIN_NAME, turbostat_read); + + return 0; +err: + free_all_buffers(); + return ret; +} + +static int +turbostat_config(const char *key, const char *value) +{ + long unsigned int tmp_val; + char *end; + + if (strcasecmp("CoreCstates", key) == 0) { + tmp_val = strtoul(value, &end, 0); + if (*end != '\0' || tmp_val > UINT_MAX) { + ERROR("turbostat plugin: Invalid CoreCstates '%s'", + value); + return -1; + } + config_core_cstate = (unsigned int) tmp_val; + apply_config_core_cstate = 1; + } else if (strcasecmp("PackageCstates", key) == 0) { + tmp_val = strtoul(value, &end, 0); + if (*end != '\0' || tmp_val > UINT_MAX) { + ERROR("turbostat plugin: Invalid PackageCstates '%s'", + value); + return -1; + } + config_pkg_cstate = (unsigned int) tmp_val; + apply_config_pkg_cstate = 1; + } else if (strcasecmp("SystemManagementInterrupt", key) == 0) { + config_smi = IS_TRUE(value); + apply_config_smi = 1; + } else if (strcasecmp("DigitalTemperatureSensor", key) == 0) { + config_dts = IS_TRUE(value); + apply_config_dts = 1; + } else if (strcasecmp("PackageThermalManagement", key) == 0) { + config_ptm = IS_TRUE(value); + apply_config_ptm = 1; + } else if (strcasecmp("RunningAveragePowerLimit", key) == 0) { + tmp_val = strtoul(value, &end, 0); + if (*end != '\0' || tmp_val > UINT_MAX) { + ERROR("turbostat plugin: Invalid RunningAveragePowerLimit '%s'", + value); + return -1; + } + config_rapl = (unsigned int) tmp_val; + apply_config_rapl = 1; + } else if (strcasecmp("TCCActivationTemp", key) == 0) { + tmp_val = strtoul(value, &end, 0); + if (*end != '\0' || tmp_val > UINT_MAX) { + ERROR("turbostat plugin: Invalid TCCActivationTemp '%s'", + value); + return -1; + } + tcc_activation_temp = (unsigned int) tmp_val; + } else { + ERROR("turbostat plugin: Invalid configuration option '%s'", + key); + return -1; + } + return 0; +} + +void module_register(void) +{ + plugin_register_init(PLUGIN_NAME, turbostat_init); + plugin_register_config(PLUGIN_NAME, turbostat_config, config_keys, config_keys_num); +} diff --git a/src/write_kafka.c b/src/write_kafka.c index ccc4784e..b6e89618 100644 --- a/src/write_kafka.c +++ b/src/write_kafka.c @@ -38,6 +38,7 @@ #include #include #include +#include struct kafka_topic_context { #define KAFKA_FORMAT_JSON 0 @@ -48,6 +49,7 @@ struct kafka_topic_context { _Bool store_rates; rd_kafka_topic_conf_t *conf; rd_kafka_topic_t *topic; + rd_kafka_conf_t *kafka_conf; rd_kafka_t *kafka; int has_key; u_int32_t key; @@ -55,8 +57,10 @@ struct kafka_topic_context { char *postfix; char escape_char; char *topic_name; + pthread_mutex_t lock; }; +static int kafka_handle(struct kafka_topic_context *); static int kafka_write(const data_set_t *, const value_list_t *, user_data_t *); static int32_t kafka_partition(const rd_kafka_topic_t *, const void *, size_t, int32_t, void *, void *); @@ -85,6 +89,60 @@ static int32_t kafka_partition(const rd_kafka_topic_t *rkt, return target; } +static int kafka_handle(struct kafka_topic_context *ctx) /* {{{ */ +{ + char errbuf[1024]; + rd_kafka_conf_t *conf; + rd_kafka_topic_conf_t *topic_conf; + + if (ctx->kafka != NULL && ctx->topic != NULL) + return(0); + + if (ctx->kafka == NULL) { + if ((conf = rd_kafka_conf_dup(ctx->kafka_conf)) == NULL) { + ERROR("write_kafka plugin: cannot duplicate kafka config"); + return(1); + } + + if ((ctx->kafka = rd_kafka_new(RD_KAFKA_PRODUCER, conf, + errbuf, sizeof(errbuf))) == NULL) { + ERROR("write_kafka plugin: cannot create kafka handle."); + return 1; + } + + rd_kafka_conf_destroy(ctx->kafka_conf); + ctx->kafka_conf = NULL; + + INFO ("write_kafka plugin: created KAFKA handle : %s", rd_kafka_name(ctx->kafka)); + +#ifdef HAVE_LIBRDKAFKA_LOGGER + rd_kafka_set_logger(ctx->kafka, kafka_log); +#endif + } + + if (ctx->topic == NULL ) { + if ((topic_conf = rd_kafka_topic_conf_dup(ctx->conf)) == NULL) { + ERROR("write_kafka plugin: cannot duplicate kafka topic config"); + return 1; + } + + if ((ctx->topic = rd_kafka_topic_new(ctx->kafka, ctx->topic_name, + topic_conf)) == NULL) { + ERROR("write_kafka plugin: cannot create topic : %s\n", + rd_kafka_err2str(rd_kafka_errno2err(errno))); + return errno; + } + + rd_kafka_topic_conf_destroy(ctx->conf); + ctx->conf = NULL; + + INFO ("write_kafka plugin: handle created for topic : %s", rd_kafka_topic_name(ctx->topic)); + } + + return(0); + +} /* }}} int kafka_handle */ + static int kafka_write(const data_set_t *ds, /* {{{ */ const value_list_t *vl, user_data_t *ud) @@ -100,6 +158,12 @@ static int kafka_write(const data_set_t *ds, /* {{{ */ if ((ds == NULL) || (vl == NULL) || (ctx == NULL)) return EINVAL; + pthread_mutex_lock (&ctx->lock); + status = kafka_handle(ctx); + pthread_mutex_unlock (&ctx->lock); + if( status != 0 ) + return status; + bzero(buffer, sizeof(buffer)); switch (ctx->format) { @@ -164,6 +228,10 @@ static void kafka_topic_context_free(void *p) /* {{{ */ rd_kafka_topic_destroy(ctx->topic); if (ctx->conf != NULL) rd_kafka_topic_conf_destroy(ctx->conf); + if (ctx->kafka_conf != NULL) + rd_kafka_conf_destroy(ctx->kafka_conf); + if (ctx->kafka != NULL) + rd_kafka_destroy(ctx->kafka); sfree(ctx); } /* }}} void kafka_topic_context_free */ @@ -190,22 +258,18 @@ static void kafka_config_topic(rd_kafka_conf_t *conf, oconfig_item_t *ci) /* {{{ tctx->store_rates = 1; tctx->format = KAFKA_FORMAT_JSON; -#ifdef HAVE_LIBRDKAFKA_LOG_CB - rd_kafka_conf_set_log_cb(conf, kafka_log); -#endif - if ((tctx->kafka = rd_kafka_new(RD_KAFKA_PRODUCER, conf, - errbuf, sizeof(errbuf))) == NULL) { + if ((tctx->kafka_conf = rd_kafka_conf_dup(conf)) == NULL) { sfree(tctx); - ERROR("write_kafka plugin: cannot create kafka handle."); + ERROR("write_kafka plugin: cannot allocate memory for kafka config"); return; } -#ifdef HAVE_LIBRDKAFKA_LOGGER - rd_kafka_set_logger(tctx->kafka, kafka_log); + +#ifdef HAVE_LIBRDKAFKA_LOG_CB + rd_kafka_conf_set_log_cb(tctx->kafka_conf, kafka_log); #endif - conf = NULL; if ((tctx->conf = rd_kafka_topic_conf_new()) == NULL) { - rd_kafka_destroy(tctx->kafka); + rd_kafka_conf_destroy(tctx->kafka_conf); sfree(tctx); ERROR ("write_kafka plugin: cannot create topic configuration."); return; @@ -327,13 +391,6 @@ static void kafka_config_topic(rd_kafka_conf_t *conf, oconfig_item_t *ci) /* {{{ rd_kafka_topic_conf_set_partitioner_cb(tctx->conf, kafka_partition); rd_kafka_topic_conf_set_opaque(tctx->conf, tctx); - if ((tctx->topic = rd_kafka_topic_new(tctx->kafka, tctx->topic_name, - tctx->conf)) == NULL) { - ERROR("write_kafka plugin: cannot create topic."); - goto errout; - } - tctx->conf = NULL; - ssnprintf(callback_name, sizeof(callback_name), "write_kafka/%s", tctx->topic_name); @@ -347,18 +404,17 @@ static void kafka_config_topic(rd_kafka_conf_t *conf, oconfig_item_t *ci) /* {{{ callback_name, status); goto errout; } + + pthread_mutex_init (&tctx->lock, /* attr = */ NULL); + return; errout: - if (conf != NULL) - rd_kafka_conf_destroy(conf); - if (tctx->kafka != NULL) - rd_kafka_destroy(tctx->kafka); - if (tctx->topic != NULL) - rd_kafka_topic_destroy(tctx->topic); if (tctx->topic_name != NULL) free(tctx->topic_name); if (tctx->conf != NULL) rd_kafka_topic_conf_destroy(tctx->conf); + if (tctx->kafka_conf != NULL) + rd_kafka_conf_destroy(tctx->kafka_conf); sfree(tctx); } /* }}} int kafka_config_topic */ @@ -367,7 +423,6 @@ static int kafka_config(oconfig_item_t *ci) /* {{{ */ int i; oconfig_item_t *child; rd_kafka_conf_t *conf; - rd_kafka_conf_t *cloned; rd_kafka_conf_res_t ret; char errbuf[1024]; @@ -375,16 +430,11 @@ static int kafka_config(oconfig_item_t *ci) /* {{{ */ WARNING("cannot allocate kafka configuration."); return -1; } - for (i = 0; i < ci->children_num; i++) { child = &ci->children[i]; if (strcasecmp("Topic", child->key) == 0) { - if ((cloned = rd_kafka_conf_dup(conf)) == NULL) { - WARNING("write_kafka plugin: cannot allocate memory for kafka config"); - goto errout; - } - kafka_config_topic (cloned, child); + kafka_config_topic (conf, child); } else if (strcasecmp(child->key, "Property") == 0) { char *key = NULL; char *val = NULL; diff --git a/src/write_sensu.c b/src/write_sensu.c index 35db4f7b..cb0c2fe2 100644 --- a/src/write_sensu.c +++ b/src/write_sensu.c @@ -484,18 +484,29 @@ static char *sensu_value_to_json(struct sensu_host const *host, /* {{{ */ return NULL; } } else { - int64_t tmp_v; - if (ds->ds[index].type == DS_TYPE_DERIVE) - tmp_v = (int64_t) vl->values[index].derive; - else if (ds->ds[index].type == DS_TYPE_ABSOLUTE) - tmp_v = (int64_t) vl->values[index].absolute; - else - tmp_v = (int64_t) vl->values[index].counter; - res = asprintf(&value_str, "%ld", tmp_v); - if (res == -1) { - free(ret_str); - ERROR("write_sensu plugin: Unable to alloc memory"); - return NULL; + if (ds->ds[index].type == DS_TYPE_DERIVE) { + res = asprintf(&value_str, "%"PRIi64, vl->values[index].derive); + if (res == -1) { + free(ret_str); + ERROR("write_sensu plugin: Unable to alloc memory"); + return NULL; + } + } + else if (ds->ds[index].type == DS_TYPE_ABSOLUTE) { + res = asprintf(&value_str, "%"PRIu64, vl->values[index].absolute); + if (res == -1) { + free(ret_str); + ERROR("write_sensu plugin: Unable to alloc memory"); + return NULL; + } + } + else { + res = asprintf(&value_str, "%llu", vl->values[index].counter); + if (res == -1) { + free(ret_str); + ERROR("write_sensu plugin: Unable to alloc memory"); + return NULL; + } } } diff --git a/src/zfs_arc.c b/src/zfs_arc.c index b784ee3a..f0d23239 100644 --- a/src/zfs_arc.c +++ b/src/zfs_arc.c @@ -251,7 +251,14 @@ static int za_read (void) /* Sizes */ za_read_gauge (ksp, "size", "cache_size", "arc"); - za_read_gauge (ksp, "l2_size", "cache_size", "L2"); + + /* The "l2_size" value has disappeared from Solaris some time in + * early 2013, and has only reappeared recently in Solaris 11.2. + * Stop trying if we ever fail to read it, so we don't spam the log. + */ + static int l2_size_avail = 1; + if (l2_size_avail && za_read_gauge (ksp, "l2_size", "cache_size", "L2") != 0) + l2_size_avail = 0; /* Operations */ za_read_derive (ksp, "deleted", "cache_operation", "deleted"); diff --git a/version-gen.sh b/version-gen.sh index 7b573ab7..460c6e9d 100755 --- a/version-gen.sh +++ b/version-gen.sh @@ -10,4 +10,4 @@ fi VERSION="`echo \"$VERSION\" | sed -e 's/-/./g'`" -echo -n "$VERSION" +printf "%s" "$VERSION"