blob: 4659cbcf1db6caa4d0ebafd03bd0be18189a09e2 [file] [log] [blame]
Calin Juravle4d77b6a2015-12-01 18:38:09 +00001/*
2 * Copyright (C) 2015 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "profile_saver.h"
18
Calin Juravle86a9ebe2016-02-24 10:13:09 +000019#include <sys/types.h>
20#include <sys/stat.h>
21#include <fcntl.h>
22
Calin Juravle4d77b6a2015-12-01 18:38:09 +000023#include "art_method-inl.h"
24#include "scoped_thread_state_change.h"
25#include "oat_file_manager.h"
26
27namespace art {
28
Calin Juravle932a0512016-01-19 14:32:26 -080029// An arbitrary value to throttle save requests. Set to 2s for now.
Calin Juravle4d77b6a2015-12-01 18:38:09 +000030static constexpr const uint64_t kMilisecondsToNano = 1000000;
Calin Juravle932a0512016-01-19 14:32:26 -080031static constexpr const uint64_t kMinimumTimeBetweenCodeCacheUpdatesNs = 2000 * kMilisecondsToNano;
Calin Juravle4d77b6a2015-12-01 18:38:09 +000032
33// TODO: read the constants from ProfileOptions,
34// Add a random delay each time we go to sleep so that we don't hammer the CPU
35// with all profile savers running at the same time.
Calin Juravle932a0512016-01-19 14:32:26 -080036static constexpr const uint64_t kRandomDelayMaxMs = 20 * 1000; // 20 seconds
37static constexpr const uint64_t kMaxBackoffMs = 5 * 60 * 1000; // 5 minutes
38static constexpr const uint64_t kSavePeriodMs = 10 * 1000; // 10 seconds
Calin Juravle4d77b6a2015-12-01 18:38:09 +000039static constexpr const double kBackoffCoef = 1.5;
40
41static constexpr const uint32_t kMinimumNrOrMethodsToSave = 10;
42
43ProfileSaver* ProfileSaver::instance_ = nullptr;
44pthread_t ProfileSaver::profiler_pthread_ = 0U;
45
46ProfileSaver::ProfileSaver(const std::string& output_filename,
47 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +000048 const std::vector<std::string>& code_paths,
49 const std::string& foreign_dex_profile_path,
50 const std::string& app_data_dir)
Calin Juravleb4eddd22016-01-13 15:52:33 -080051 : jit_code_cache_(jit_code_cache),
Calin Juravle86a9ebe2016-02-24 10:13:09 +000052 foreign_dex_profile_path_(foreign_dex_profile_path),
Calin Juravle4d77b6a2015-12-01 18:38:09 +000053 code_cache_last_update_time_ns_(0),
54 shutting_down_(false),
55 wait_lock_("ProfileSaver wait lock"),
56 period_condition_("ProfileSaver period condition", wait_lock_) {
Calin Juravleb4eddd22016-01-13 15:52:33 -080057 AddTrackedLocations(output_filename, code_paths);
Calin Juravle86a9ebe2016-02-24 10:13:09 +000058 app_data_dir_ = "";
59 if (!app_data_dir.empty()) {
60 // The application directory is used to determine which dex files are owned by app.
61 // Since it could be a symlink (e.g. /data/data instead of /data/user/0), and we
62 // don't have control over how the dex files are actually loaded (symlink or canonical path),
63 // store it's canonical form to be sure we use the same base when comparing.
64 UniqueCPtr<const char[]> app_data_dir_real_path(realpath(app_data_dir.c_str(), nullptr));
65 if (app_data_dir_real_path != nullptr) {
66 app_data_dir_.assign(app_data_dir_real_path.get());
67 } else {
68 LOG(WARNING) << "Failed to get the real path for app dir: " << app_data_dir_
69 << ". The app dir will not be used to determine which dex files belong to the app";
70 }
71 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +000072}
73
74void ProfileSaver::Run() {
75 srand(MicroTime() * getpid());
76 Thread* self = Thread::Current();
77
78 uint64_t save_period_ms = kSavePeriodMs;
79 VLOG(profiler) << "Save profiling information every " << save_period_ms << " ms";
80 while (true) {
81 if (ShuttingDown(self)) {
82 break;
83 }
84
85 uint64_t random_sleep_delay_ms = rand() % kRandomDelayMaxMs;
86 uint64_t sleep_time_ms = save_period_ms + random_sleep_delay_ms;
87 {
88 MutexLock mu(self, wait_lock_);
89 period_condition_.TimedWait(self, sleep_time_ms, 0);
90 }
91
92 if (ShuttingDown(self)) {
93 break;
94 }
95
96 if (!ProcessProfilingInfo() && save_period_ms < kMaxBackoffMs) {
97 // If we don't need to save now it is less likely that we will need to do
98 // so in the future. Increase the time between saves according to the
99 // kBackoffCoef, but make it no larger than kMaxBackoffMs.
100 save_period_ms = static_cast<uint64_t>(kBackoffCoef * save_period_ms);
101 } else {
102 // Reset the period to the initial value as it's highly likely to JIT again.
103 save_period_ms = kSavePeriodMs;
104 }
105 }
106}
107
108bool ProfileSaver::ProcessProfilingInfo() {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000109 uint64_t last_update_time_ns = jit_code_cache_->GetLastUpdateTimeNs();
110 if (last_update_time_ns - code_cache_last_update_time_ns_
Calin Juravle877fd962016-01-05 14:29:29 +0000111 < kMinimumTimeBetweenCodeCacheUpdatesNs) {
112 VLOG(profiler) << "Not enough time has passed since the last code cache update."
113 << "Last update: " << last_update_time_ns
114 << " Last save: " << code_cache_last_update_time_ns_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000115 return false;
116 }
117
118 uint64_t start = NanoTime();
119 code_cache_last_update_time_ns_ = last_update_time_ns;
Calin Juravleb4eddd22016-01-13 15:52:33 -0800120 SafeMap<std::string, std::set<std::string>> tracked_locations;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000121 {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800122 // Make a copy so that we don't hold the lock while doing I/O.
123 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
124 tracked_locations = tracked_dex_base_locations_;
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000125 }
Calin Juravleb4eddd22016-01-13 15:52:33 -0800126 for (const auto& it : tracked_locations) {
127 if (ShuttingDown(Thread::Current())) {
128 return true;
129 }
130 const std::string& filename = it.first;
131 const std::set<std::string>& locations = it.second;
132 std::vector<ArtMethod*> methods;
133 {
134 ScopedObjectAccess soa(Thread::Current());
135 jit_code_cache_->GetCompiledArtMethods(locations, methods);
136 }
137 if (methods.size() < kMinimumNrOrMethodsToSave) {
138 VLOG(profiler) << "Not enough information to save to: " << filename
139 <<" Nr of methods: " << methods.size();
140 return false;
141 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000142
Calin Juravleb4eddd22016-01-13 15:52:33 -0800143 if (!ProfileCompilationInfo::SaveProfilingInfo(filename, methods)) {
144 LOG(WARNING) << "Could not save profiling info to " << filename;
145 return false;
146 }
147
148 VLOG(profiler) << "Profile process time: " << PrettyDuration(NanoTime() - start);
149 }
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000150 return true;
151}
152
153void* ProfileSaver::RunProfileSaverThread(void* arg) {
154 Runtime* runtime = Runtime::Current();
155 ProfileSaver* profile_saver = reinterpret_cast<ProfileSaver*>(arg);
156
157 CHECK(runtime->AttachCurrentThread("Profile Saver",
158 /*as_daemon*/true,
159 runtime->GetSystemThreadGroup(),
160 /*create_peer*/true));
161 profile_saver->Run();
162
163 runtime->DetachCurrentThread();
164 VLOG(profiler) << "Profile saver shutdown";
165 return nullptr;
166}
167
168void ProfileSaver::Start(const std::string& output_filename,
169 jit::JitCodeCache* jit_code_cache,
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000170 const std::vector<std::string>& code_paths,
171 const std::string& foreign_dex_profile_path,
172 const std::string& app_data_dir) {
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000173 DCHECK(Runtime::Current()->UseJit());
174 DCHECK(!output_filename.empty());
175 DCHECK(jit_code_cache != nullptr);
176
177 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000178 if (instance_ != nullptr) {
Calin Juravleb4eddd22016-01-13 15:52:33 -0800179 // If we already have an instance, make sure it uses the same jit_code_cache.
180 // This may be called multiple times via Runtime::registerAppInfo (e.g. for
181 // apps which share the same runtime).
182 DCHECK_EQ(instance_->jit_code_cache_, jit_code_cache);
183 // Add the code_paths to the tracked locations.
184 instance_->AddTrackedLocations(output_filename, code_paths);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000185 return;
186 }
187
188 VLOG(profiler) << "Starting profile saver using output file: " << output_filename
189 << ". Tracking: " << Join(code_paths, ':');
190
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000191 instance_ = new ProfileSaver(output_filename,
192 jit_code_cache,
193 code_paths,
194 foreign_dex_profile_path,
195 app_data_dir);
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000196
197 // Create a new thread which does the saving.
198 CHECK_PTHREAD_CALL(
199 pthread_create,
200 (&profiler_pthread_, nullptr, &RunProfileSaverThread, reinterpret_cast<void*>(instance_)),
201 "Profile saver thread");
202}
203
204void ProfileSaver::Stop() {
205 ProfileSaver* profile_saver = nullptr;
206 pthread_t profiler_pthread = 0U;
207
208 {
209 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
Calin Juravleb4eddd22016-01-13 15:52:33 -0800210 VLOG(profiler) << "Stopping profile saver thread";
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000211 profile_saver = instance_;
212 profiler_pthread = profiler_pthread_;
213 if (instance_ == nullptr) {
214 DCHECK(false) << "Tried to stop a profile saver which was not started";
215 return;
216 }
217 if (instance_->shutting_down_) {
218 DCHECK(false) << "Tried to stop the profile saver twice";
219 return;
220 }
221 instance_->shutting_down_ = true;
222 }
223
224 {
225 // Wake up the saver thread if it is sleeping to allow for a clean exit.
226 MutexLock wait_mutex(Thread::Current(), profile_saver->wait_lock_);
227 profile_saver->period_condition_.Signal(Thread::Current());
228 }
229
230 // Wait for the saver thread to stop.
231 CHECK_PTHREAD_CALL(pthread_join, (profiler_pthread, nullptr), "profile saver thread shutdown");
232
233 {
234 MutexLock profiler_mutex(Thread::Current(), *Locks::profiler_lock_);
235 instance_ = nullptr;
236 profiler_pthread_ = 0U;
237 }
238 delete profile_saver;
239}
240
241bool ProfileSaver::ShuttingDown(Thread* self) {
242 MutexLock mu(self, *Locks::profiler_lock_);
243 return shutting_down_;
244}
245
246bool ProfileSaver::IsStarted() {
247 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
248 return instance_ != nullptr;
249}
250
Calin Juravleb4eddd22016-01-13 15:52:33 -0800251void ProfileSaver::AddTrackedLocations(const std::string& output_filename,
252 const std::vector<std::string>& code_paths) {
253 auto it = tracked_dex_base_locations_.find(output_filename);
254 if (it == tracked_dex_base_locations_.end()) {
255 tracked_dex_base_locations_.Put(output_filename,
256 std::set<std::string>(code_paths.begin(), code_paths.end()));
257 } else {
258 it->second.insert(code_paths.begin(), code_paths.end());
259 }
260}
261
Calin Juravle86a9ebe2016-02-24 10:13:09 +0000262void ProfileSaver::NotifyDexUse(const std::string& dex_location) {
263 std::set<std::string> app_code_paths;
264 std::string foreign_dex_profile_path;
265 std::string app_data_dir;
266 {
267 MutexLock mu(Thread::Current(), *Locks::profiler_lock_);
268 DCHECK(instance_ != nullptr);
269 // Make a copy so that we don't hold the lock while doing I/O.
270 for (const auto& it : instance_->tracked_dex_base_locations_) {
271 app_code_paths.insert(it.second.begin(), it.second.end());
272 }
273 foreign_dex_profile_path = instance_->foreign_dex_profile_path_;
274 app_data_dir = instance_->app_data_dir_;
275 }
276
277 MaybeRecordDexUseInternal(dex_location,
278 app_code_paths,
279 foreign_dex_profile_path,
280 app_data_dir);
281}
282
283void ProfileSaver::MaybeRecordDexUseInternal(
284 const std::string& dex_location,
285 const std::set<std::string>& app_code_paths,
286 const std::string& foreign_dex_profile_path,
287 const std::string& app_data_dir) {
288 if (foreign_dex_profile_path.empty()) {
289 LOG(WARNING) << "Asked to record foreign dex use without a valid profile path ";
290 return;
291 }
292
293 UniqueCPtr<const char[]> dex_location_real_path(realpath(dex_location.c_str(), nullptr));
294 std::string dex_location_real_path_str(dex_location_real_path.get());
295
296 if (dex_location_real_path_str.compare(0, app_data_dir.length(), app_data_dir) == 0) {
297 // The dex location is under the application folder. Nothing to record.
298 return;
299 }
300
301 if (app_code_paths.find(dex_location) != app_code_paths.end()) {
302 // The dex location belongs to the application code paths. Nothing to record.
303 return;
304 }
305 // Do another round of checks with the real paths.
306 // Note that we could cache all the real locations in the saver (since it's an expensive
307 // operation). However we expect that app_code_paths is small (usually 1 element), and
308 // NotifyDexUse is called just a few times in the app lifetime. So we make the compromise
309 // to save some bytes of memory usage.
310 for (const auto& app_code_location : app_code_paths) {
311 UniqueCPtr<const char[]> real_app_code_location(realpath(app_code_location.c_str(), nullptr));
312 std::string real_app_code_location_str(real_app_code_location.get());
313 if (real_app_code_location_str == dex_location_real_path_str) {
314 // The dex location belongs to the application code paths. Nothing to record.
315 return;
316 }
317 }
318
319 // For foreign dex files we record a flag on disk. PackageManager will (potentially) take this
320 // into account when deciding how to optimize the loaded dex file.
321 // The expected flag name is the canonical path of the apk where '/' is substituted to '@'.
322 // (it needs to be kept in sync with
323 // frameworks/base/services/core/java/com/android/server/pm/PackageDexOptimizer.java)
324 std::replace(dex_location_real_path_str.begin(), dex_location_real_path_str.end(), '/', '@');
325 std::string flag_path = foreign_dex_profile_path + "/" + dex_location_real_path_str;
326 // No need to give any sort of access to flag_path. The system has enough permissions
327 // to test for its existence.
328 int fd = TEMP_FAILURE_RETRY(open(flag_path.c_str(), O_CREAT | O_EXCL, 0));
329 if (fd != -1) {
330 if (close(fd) != 0) {
331 PLOG(WARNING) << "Could not close file after flagging foreign dex use " << flag_path;
332 }
333 } else {
334 if (errno != EEXIST) {
335 // Another app could have already created the file.
336 PLOG(WARNING) << "Could not create foreign dex use mark " << flag_path;
337 }
338 }
339}
340
Calin Juravle4d77b6a2015-12-01 18:38:09 +0000341} // namespace art