+#if KERNEL_LINUX
+static void cpufreq_read_stats(int cpu) {
+ char filename[PATH_MAX];
+ /* Read total transitions for cpu frequency */
+ snprintf(filename, sizeof(filename),
+ "/sys/devices/system/cpu/cpu%d/cpufreq/stats/total_trans", cpu);
+
+ value_t v;
+ if (parse_value_file(filename, &v, DS_TYPE_DERIVE) != 0) {
+ ERROR("cpufreq plugin: Reading \"%s\" failed.", filename);
+ return;
+ }
+ cpufreq_submit(cpu, "transitions", NULL, &v);
+
+ /* Determine percentage time in each state for cpu during previous
+ * interval. */
+ snprintf(filename, sizeof(filename),
+ "/sys/devices/system/cpu/cpu%d/cpufreq/stats/time_in_state", cpu);
+
+ FILE *fh = fopen(filename, "r");
+ if (fh == NULL) {
+ ERROR("cpufreq plugin: Reading \"%s\" failed.", filename);
+ return;
+ }
+
+ int state_index = 0;
+ cdtime_t now = cdtime();
+ char buffer[DATA_MAX_NAME_LEN];
+
+ while (fgets(buffer, sizeof(buffer), fh) != NULL) {
+ unsigned int frequency;
+ unsigned long long time;
+
+ /*
+ * State time units is 10ms. To get rate of seconds per second
+ * we have to divide by 100. To get percents we have to multiply it
+ * by 100 back. So, just use parsed value directly.
+ */
+ if (!sscanf(buffer, "%u%llu", &frequency, &time)) {
+ ERROR("cpufreq plugin: Reading \"%s\" failed.", filename);
+ break;
+ }
+
+ char state[DATA_MAX_NAME_LEN];
+ snprintf(state, sizeof(state), "%u", frequency);
+
+ if (state_index >= MAX_AVAIL_FREQS) {
+ NOTICE("cpufreq plugin: Found too many frequency states (%d > %d). "
+ "Plugin needs to be recompiled. Please open a bug report for "
+ "this.",
+ (state_index + 1), MAX_AVAIL_FREQS);
+ break;
+ }
+
+ gauge_t g;
+ if (value_to_rate(&g, (value_t){.derive = time}, DS_TYPE_DERIVE, now,
+ &(cpu_data[cpu].time_state[state_index])) == 0) {
+ /*
+ * Due to some inaccuracy reported value can be a bit greatrer than 100.1.
+ * That produces gaps on charts.
+ */
+ if (g > 100.1)
+ g = 100.1;
+ cpufreq_submit(cpu, "percent", state, &(value_t){.gauge = g});
+ }
+ state_index++;
+ }
+ fclose(fh);
+}
+#endif /* KERNEL_LINUX */
+