1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "chrome/browser/chromeos/power/cpu_data_collector.h"
10 #include "base/files/file_util.h"
11 #include "base/logging.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/strings/string_split.h"
14 #include "base/strings/string_util.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/sys_info.h"
17 #include "chrome/browser/chromeos/power/power_data_collector.h"
18 #include "content/public/browser/browser_thread.h"
23 // The sampling of CPU idle or CPU freq data should not take more than this
25 const int kSamplingDurationLimitMs
= 500;
27 // The CPU data is sampled every |kCpuDataSamplePeriodSec| seconds.
28 const int kCpuDataSamplePeriodSec
= 30;
30 // The value in the file /sys/devices/system/cpu/cpu<n>/online which indicates
31 // that CPU-n is online.
32 const int kCpuOnlineStatus
= 1;
34 // The base of the path to the files and directories which contain CPU data in
36 const char kCpuDataPathBase
[] = "/sys/devices/system/cpu";
38 // Suffix of the path to the file listing the range of possible CPUs on the
40 const char kPossibleCpuPathSuffix
[] = "/possible";
42 // Format of the suffix of the path to the file which contains information
43 // about a particular CPU being online or offline.
44 const char kCpuOnlinePathSuffixFormat
[] = "/cpu%d/online";
46 // Format of the suffix of the path to the file which contains freq state
47 // information of a CPU.
48 const char kCpuFreqTimeInStatePathSuffixFormat
[] =
49 "/cpu%d/cpufreq/stats/time_in_state";
51 // Format of the suffix of the path to the directory which contains information
52 // about an idle state of a CPU on the system.
53 const char kCpuIdleStateDirPathSuffixFormat
[] = "/cpu%d/cpuidle/state%d";
55 // Format of the suffix of the path to the file which contains the name of an
56 // idle state of a CPU.
57 const char kCpuIdleStateNamePathSuffixFormat
[] = "/cpu%d/cpuidle/state%d/name";
59 // Format of the suffix of the path which contains information about time spent
60 // in an idle state on a CPU.
61 const char kCpuIdleStateTimePathSuffixFormat
[] = "/cpu%d/cpuidle/state%d/time";
63 // Returns the index at which |str| is in |vector|. If |str| is not present in
64 // |vector|, then it is added to it before its index is returned.
65 size_t IndexInVector(const std::string
& str
,
66 std::vector
<std::string
>* vector
) {
67 for (size_t i
= 0; i
< vector
->size(); ++i
) {
68 if (str
== (*vector
)[i
])
72 // If this is reached, then it means |str| is not present in vector. Add it.
73 vector
->push_back(str
);
74 return vector
->size() - 1;
77 // Returns true if the |i|-th CPU is online; false otherwise.
78 bool CpuIsOnline(const int i
) {
79 const std::string online_file_format
= base::StringPrintf(
80 "%s%s", kCpuDataPathBase
, kCpuOnlinePathSuffixFormat
);
81 const std::string cpu_online_file
= base::StringPrintf(
82 online_file_format
.c_str(), i
);
83 if (!base::PathExists(base::FilePath(cpu_online_file
))) {
84 // If the 'online' status file is missing, then it means that the CPU is
85 // not hot-pluggable and hence is always online.
90 std::string cpu_online_string
;
91 if (base::ReadFileToString(base::FilePath(cpu_online_file
),
92 &cpu_online_string
)) {
93 base::TrimWhitespace(cpu_online_string
, base::TRIM_ALL
, &cpu_online_string
);
94 if (base::StringToInt(cpu_online_string
, &online
))
95 return online
== kCpuOnlineStatus
;
98 LOG(ERROR
) << "Bad format or error reading " << cpu_online_file
<< ". "
99 << "Assuming offline.";
103 // Samples the CPU idle state information from sysfs. |cpu_count| is the number
104 // of possible CPUs on the system. Sample at index i in |idle_samples|
105 // corresponds to the idle state information of the i-th CPU.
106 void SampleCpuIdleData(
108 std::vector
<std::string
>* cpu_idle_state_names
,
109 std::vector
<CpuDataCollector::StateOccupancySample
>* idle_samples
) {
110 base::Time start_time
= base::Time::Now();
111 for (int cpu
= 0; cpu
< cpu_count
; ++cpu
) {
112 CpuDataCollector::StateOccupancySample idle_sample
;
113 idle_sample
.time
= base::Time::Now();
114 idle_sample
.time_in_state
.reserve(cpu_idle_state_names
->size());
116 if (!CpuIsOnline(cpu
)) {
117 idle_sample
.cpu_online
= false;
119 idle_sample
.cpu_online
= true;
121 const std::string idle_state_dir_format
= base::StringPrintf(
122 "%s%s", kCpuDataPathBase
, kCpuIdleStateDirPathSuffixFormat
);
123 for (int state_count
= 0; ; ++state_count
) {
124 std::string idle_state_dir
= base::StringPrintf(
125 idle_state_dir_format
.c_str(), cpu
, state_count
);
126 // This insures us from the unlikely case wherein the 'cpuidle_stats'
127 // kernel module is not loaded. This could happen on a VM.
128 if (!base::DirectoryExists(base::FilePath(idle_state_dir
)))
131 const std::string name_file_format
= base::StringPrintf(
132 "%s%s", kCpuDataPathBase
, kCpuIdleStateNamePathSuffixFormat
);
133 const std::string name_file_path
= base::StringPrintf(
134 name_file_format
.c_str(), cpu
, state_count
);
135 DCHECK(base::PathExists(base::FilePath(name_file_path
)));
137 const std::string time_file_format
= base::StringPrintf(
138 "%s%s", kCpuDataPathBase
, kCpuIdleStateTimePathSuffixFormat
);
139 const std::string time_file_path
= base::StringPrintf(
140 time_file_format
.c_str(), cpu
, state_count
);
141 DCHECK(base::PathExists(base::FilePath(time_file_path
)));
143 std::string state_name
, occupancy_time_string
;
144 int64 occupancy_time_usec
;
145 if (!base::ReadFileToString(base::FilePath(name_file_path
),
147 !base::ReadFileToString(base::FilePath(time_file_path
),
148 &occupancy_time_string
)) {
149 // If an error occurs reading/parsing single state data, drop all the
150 // samples as an incomplete sample can mislead consumers of this
152 LOG(ERROR
) << "Error reading idle state from "
153 << idle_state_dir
<< ". Dropping sample.";
154 idle_samples
->clear();
158 base::TrimWhitespace(state_name
, base::TRIM_ALL
, &state_name
);
159 base::TrimWhitespace(
160 occupancy_time_string
, base::TRIM_ALL
, &occupancy_time_string
);
161 if (base::StringToInt64(occupancy_time_string
, &occupancy_time_usec
)) {
162 // idle state occupancy time in sysfs is recorded in microseconds.
163 int64 time_in_state_ms
= occupancy_time_usec
/ 1000;
164 size_t index
= IndexInVector(state_name
, cpu_idle_state_names
);
165 if (index
>= idle_sample
.time_in_state
.size())
166 idle_sample
.time_in_state
.resize(index
+ 1);
167 idle_sample
.time_in_state
[index
] = time_in_state_ms
;
169 LOG(ERROR
) << "Bad format in " << time_file_path
<< ". "
170 << "Dropping sample.";
171 idle_samples
->clear();
177 idle_samples
->push_back(idle_sample
);
180 // If there was an interruption in sampling (like system suspended),
181 // discard the samples!
183 base::TimeDelta(base::Time::Now() - start_time
).InMilliseconds();
184 if (delay
> kSamplingDurationLimitMs
) {
185 idle_samples
->clear();
186 LOG(WARNING
) << "Dropped an idle state sample due to excessive time delay: "
187 << delay
<< "milliseconds.";
191 // Samples the CPU freq state information from sysfs. |cpu_count| is the number
192 // of possible CPUs on the system. Sample at index i in |freq_samples|
193 // corresponds to the freq state information of the i-th CPU.
194 void SampleCpuFreqData(
196 std::vector
<std::string
>* cpu_freq_state_names
,
197 std::vector
<CpuDataCollector::StateOccupancySample
>* freq_samples
) {
198 base::Time start_time
= base::Time::Now();
199 for (int cpu
= 0; cpu
< cpu_count
; ++cpu
) {
200 CpuDataCollector::StateOccupancySample freq_sample
;
201 freq_sample
.time_in_state
.reserve(cpu_freq_state_names
->size());
203 if (!CpuIsOnline(cpu
)) {
204 freq_sample
.time
= base::Time::Now();
205 freq_sample
.cpu_online
= false;
207 freq_sample
.cpu_online
= true;
209 const std::string time_in_state_path_format
= base::StringPrintf(
210 "%s%s", kCpuDataPathBase
, kCpuFreqTimeInStatePathSuffixFormat
);
211 const std::string time_in_state_path
= base::StringPrintf(
212 time_in_state_path_format
.c_str(), cpu
);
213 if (!base::PathExists(base::FilePath(time_in_state_path
))) {
214 // If the path to the 'time_in_state' for a single CPU is missing,
215 // then 'time_in_state' for all CPUs is missing. This could happen
216 // on a VM where the 'cpufreq_stats' kernel module is not loaded.
217 LOG_IF(ERROR
, base::SysInfo::IsRunningOnChromeOS())
218 << "CPU freq stats not available in sysfs.";
219 freq_samples
->clear();
223 std::string time_in_state_string
;
224 // Note time as close to reading the file as possible. This is not
225 // possible for idle state samples as the information for each state there
226 // is recorded in different files.
227 base::Time now
= base::Time::Now();
228 if (!base::ReadFileToString(base::FilePath(time_in_state_path
),
229 &time_in_state_string
)) {
230 LOG(ERROR
) << "Error reading " << time_in_state_path
<< ". "
231 << "Dropping sample.";
232 freq_samples
->clear();
236 freq_sample
.time
= now
;
238 std::vector
<base::StringPiece
> lines
=
239 base::SplitStringPiece(time_in_state_string
, "\n",
240 base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
241 // The last line could end with '\n'. Ignore the last empty string in
243 size_t state_count
= lines
.size();
244 if (state_count
> 0 && lines
.back().empty())
246 for (size_t state
= 0; state
< state_count
; ++state
) {
248 int64 occupancy_time_centisecond
;
250 // Occupancy of each state is in the format "<state> <time>"
251 std::vector
<base::StringPiece
> pair
= base::SplitStringPiece(
252 lines
[state
], " ", base::TRIM_WHITESPACE
, base::SPLIT_WANT_ALL
);
253 if (pair
.size() == 2 &&
254 base::StringToInt(pair
[0], &freq_in_khz
) &&
255 base::StringToInt64(pair
[1], &occupancy_time_centisecond
)) {
256 const std::string state_name
= base::IntToString(freq_in_khz
/ 1000);
257 size_t index
= IndexInVector(state_name
, cpu_freq_state_names
);
258 if (index
>= freq_sample
.time_in_state
.size())
259 freq_sample
.time_in_state
.resize(index
+ 1);
260 // The occupancy time is in units of centiseconds.
261 freq_sample
.time_in_state
[index
] = occupancy_time_centisecond
* 10;
263 LOG(ERROR
) << "Bad format in " << time_in_state_path
<< ". "
264 << "Dropping sample.";
265 freq_samples
->clear();
271 freq_samples
->push_back(freq_sample
);
274 // If there was an interruption in sampling (like system suspended),
275 // discard the samples!
277 base::TimeDelta(base::Time::Now() - start_time
).InMilliseconds();
278 if (delay
> kSamplingDurationLimitMs
) {
279 freq_samples
->clear();
280 LOG(WARNING
) << "Dropped a freq state sample due to excessive time delay: "
281 << delay
<< "milliseconds.";
285 // Samples CPU idle and CPU freq data from sysfs. This function should run on
286 // the blocking pool as reading from sysfs is a blocking task. Elements at
287 // index i in |idle_samples| and |freq_samples| correspond to the idle and
288 // freq samples of CPU i. This also function reads the number of CPUs from
289 // sysfs if *|cpu_count| < 0.
290 void SampleCpuStateOnBlockingPool(
292 std::vector
<std::string
>* cpu_idle_state_names
,
293 std::vector
<CpuDataCollector::StateOccupancySample
>* idle_samples
,
294 std::vector
<std::string
>* cpu_freq_state_names
,
295 std::vector
<CpuDataCollector::StateOccupancySample
>* freq_samples
) {
296 DCHECK(!content::BrowserThread::CurrentlyOn(content::BrowserThread::UI
));
298 if (*cpu_count
< 0) {
299 // Set |cpu_count_| to 1. If it is something else, it will get corrected
300 // later. A system will at least have one CPU. Hence, a value of 1 here
301 // will serve as a default value in case of errors.
303 const std::string possible_cpu_path
= base::StringPrintf(
304 "%s%s", kCpuDataPathBase
, kPossibleCpuPathSuffix
);
305 if (!base::PathExists(base::FilePath(possible_cpu_path
))) {
306 LOG(ERROR
) << "File listing possible CPUs missing. "
307 << "Defaulting CPU count to 1.";
309 std::string possible_string
;
310 if (base::ReadFileToString(base::FilePath(possible_cpu_path
),
313 // The possible CPUs are listed in the format "0-N". Hence, N is present
314 // in the substring starting at offset 2.
315 base::TrimWhitespace(possible_string
, base::TRIM_ALL
, &possible_string
);
316 if (possible_string
.find("-") != std::string::npos
&&
317 possible_string
.length() > 2 &&
318 base::StringToInt(possible_string
.substr(2), &max_cpu
)) {
319 *cpu_count
= max_cpu
+ 1;
321 LOG(ERROR
) << "Unknown format in the file listing possible CPUs. "
322 << "Defaulting CPU count to 1.";
325 LOG(ERROR
) << "Error reading the file listing possible CPUs. "
326 << "Defaulting CPU count to 1.";
331 // Initialize the deques in the data vectors.
332 SampleCpuIdleData(*cpu_count
, cpu_idle_state_names
, idle_samples
);
333 SampleCpuFreqData(*cpu_count
, cpu_freq_state_names
, freq_samples
);
338 // Set |cpu_count_| to -1 and let SampleCpuStateOnBlockingPool discover the
339 // correct number of CPUs.
340 CpuDataCollector::CpuDataCollector() : cpu_count_(-1), weak_ptr_factory_(this) {
343 CpuDataCollector::~CpuDataCollector() {
346 void CpuDataCollector::Start() {
347 timer_
.Start(FROM_HERE
,
348 base::TimeDelta::FromSeconds(kCpuDataSamplePeriodSec
),
350 &CpuDataCollector::PostSampleCpuState
);
353 void CpuDataCollector::PostSampleCpuState() {
354 int* cpu_count
= new int(cpu_count_
);
355 std::vector
<std::string
>* cpu_idle_state_names
=
356 new std::vector
<std::string
>(cpu_idle_state_names_
);
357 std::vector
<StateOccupancySample
>* idle_samples
=
358 new std::vector
<StateOccupancySample
>;
359 std::vector
<std::string
>* cpu_freq_state_names
=
360 new std::vector
<std::string
>(cpu_freq_state_names_
);
361 std::vector
<StateOccupancySample
>* freq_samples
=
362 new std::vector
<StateOccupancySample
>;
364 content::BrowserThread::PostBlockingPoolTaskAndReply(
366 base::Bind(&SampleCpuStateOnBlockingPool
,
367 base::Unretained(cpu_count
),
368 base::Unretained(cpu_idle_state_names
),
369 base::Unretained(idle_samples
),
370 base::Unretained(cpu_freq_state_names
),
371 base::Unretained(freq_samples
)),
372 base::Bind(&CpuDataCollector::SaveCpuStateSamplesOnUIThread
,
373 weak_ptr_factory_
.GetWeakPtr(),
374 base::Owned(cpu_count
),
375 base::Owned(cpu_idle_state_names
),
376 base::Owned(idle_samples
),
377 base::Owned(cpu_freq_state_names
),
378 base::Owned(freq_samples
)));
381 void CpuDataCollector::SaveCpuStateSamplesOnUIThread(
382 const int* cpu_count
,
383 const std::vector
<std::string
>* cpu_idle_state_names
,
384 const std::vector
<CpuDataCollector::StateOccupancySample
>* idle_samples
,
385 const std::vector
<std::string
>* cpu_freq_state_names
,
386 const std::vector
<CpuDataCollector::StateOccupancySample
>* freq_samples
) {
387 DCHECK_CURRENTLY_ON(content::BrowserThread::UI
);
389 cpu_count_
= *cpu_count
;
391 // |idle_samples| or |freq_samples| could be empty sometimes (for example, if
392 // sampling was interrupted due to system suspension). Iff they are not empty,
393 // they will have one sample each for each of the CPUs.
395 if (!idle_samples
->empty()) {
396 // When committing the first sample, resize the data vector to the number of
397 // CPUs on the system. This number should be the same as the number of
398 // samples in |idle_samples|.
399 if (cpu_idle_state_data_
.empty()) {
400 cpu_idle_state_data_
.resize(idle_samples
->size());
402 DCHECK_EQ(idle_samples
->size(), cpu_idle_state_data_
.size());
404 for (size_t i
= 0; i
< cpu_idle_state_data_
.size(); ++i
)
405 AddSample(&cpu_idle_state_data_
[i
], (*idle_samples
)[i
]);
407 cpu_idle_state_names_
= *cpu_idle_state_names
;
410 if (!freq_samples
->empty()) {
411 // As with idle samples, resize the data vector before committing the first
413 if (cpu_freq_state_data_
.empty()) {
414 cpu_freq_state_data_
.resize(freq_samples
->size());
416 DCHECK_EQ(freq_samples
->size(), cpu_freq_state_data_
.size());
418 for (size_t i
= 0; i
< cpu_freq_state_data_
.size(); ++i
)
419 AddSample(&cpu_freq_state_data_
[i
], (*freq_samples
)[i
]);
421 cpu_freq_state_names_
= *cpu_freq_state_names
;
425 CpuDataCollector::StateOccupancySample::StateOccupancySample()
426 : cpu_online(false) {
429 CpuDataCollector::StateOccupancySample::~StateOccupancySample() {
432 } // namespace chromeos