1 /*
2 * Copyright (C) 2017 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 "ProfileDataContainer.h"
18
19 #include <errno.h>
20
21 #include <cutils/ashmem.h>
22 #include <log/log.h>
23
24 #include <errno.h>
25 #include <sys/mman.h>
26
27 namespace android {
28 namespace uirenderer {
29
freeData()30 void ProfileDataContainer::freeData() REQUIRES(mJankDataMutex) {
31 if (mIsMapped) {
32 munmap(mData, sizeof(ProfileData));
33 } else {
34 delete mData;
35 }
36 mIsMapped = false;
37 mData = nullptr;
38 }
39
rotateStorage()40 void ProfileDataContainer::rotateStorage() {
41 std::lock_guard lock(mJankDataMutex);
42
43 // If we are mapped we want to stop using the ashmem backend and switch to malloc
44 // We are expecting a switchStorageToAshmem call to follow this, but it's not guaranteed
45 // If we aren't sitting on top of ashmem then just do a reset() as it's functionally
46 // equivalent do a free, malloc, reset.
47 if (mIsMapped) {
48 freeData();
49 mData = new ProfileData;
50 }
51 mData->reset();
52 }
53
switchStorageToAshmem(int ashmemfd)54 void ProfileDataContainer::switchStorageToAshmem(int ashmemfd) {
55 std::lock_guard lock(mJankDataMutex);
56 int regionSize = ashmem_get_size_region(ashmemfd);
57 if (regionSize < 0) {
58 int err = errno;
59 ALOGW("Failed to get ashmem region size from fd %d, err %d %s", ashmemfd, err,
60 strerror(err));
61 return;
62 }
63 if (regionSize < static_cast<int>(sizeof(ProfileData))) {
64 ALOGW("Ashmem region is too small! Received %d, required %u", regionSize,
65 static_cast<unsigned int>(sizeof(ProfileData)));
66 return;
67 }
68 ProfileData* newData = reinterpret_cast<ProfileData*>(
69 mmap(NULL, sizeof(ProfileData), PROT_READ | PROT_WRITE, MAP_SHARED, ashmemfd, 0));
70 if (newData == MAP_FAILED) {
71 int err = errno;
72 ALOGW("Failed to move profile data to ashmem fd %d, error = %d", ashmemfd, err);
73 return;
74 }
75
76 if (mData != nullptr) {
77 newData->mergeWith(*mData);
78 }
79 freeData();
80 mData = newData;
81 mIsMapped = true;
82 }
83
84 } /* namespace uirenderer */
85 } /* namespace android */
86