1 /*
2 * Copyright (C) 2014 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 "swap_space.h"
18
19 #include <algorithm>
20 #include <numeric>
21 #include <sys/mman.h>
22
23 #include "base/logging.h"
24 #include "base/macros.h"
25 #include "base/mutex.h"
26 #include "thread-inl.h"
27
28 namespace art {
29
30 // The chunk size by which the swap file is increased and mapped.
31 static constexpr size_t kMininumMapSize = 16 * MB;
32
33 static constexpr bool kCheckFreeMaps = false;
34
35 template <typename FreeBySizeSet>
DumpFreeMap(const FreeBySizeSet & free_by_size)36 static void DumpFreeMap(const FreeBySizeSet& free_by_size) {
37 size_t last_size = static_cast<size_t>(-1);
38 for (const auto& entry : free_by_size) {
39 if (last_size != entry.size) {
40 last_size = entry.size;
41 LOG(INFO) << "Size " << last_size;
42 }
43 LOG(INFO) << " 0x" << std::hex << entry.free_by_start_entry->Start()
44 << " size=" << std::dec << entry.free_by_start_entry->size;
45 }
46 }
47
RemoveChunk(FreeBySizeSet::const_iterator free_by_size_pos)48 void SwapSpace::RemoveChunk(FreeBySizeSet::const_iterator free_by_size_pos) {
49 auto free_by_start_pos = free_by_size_pos->free_by_start_entry;
50 free_by_size_.erase(free_by_size_pos);
51 free_by_start_.erase(free_by_start_pos);
52 }
53
InsertChunk(const SpaceChunk & chunk)54 inline void SwapSpace::InsertChunk(const SpaceChunk& chunk) {
55 DCHECK_NE(chunk.size, 0u);
56 auto insert_result = free_by_start_.insert(chunk);
57 DCHECK(insert_result.second);
58 free_by_size_.emplace(chunk.size, insert_result.first);
59 }
60
SwapSpace(int fd,size_t initial_size)61 SwapSpace::SwapSpace(int fd, size_t initial_size)
62 : fd_(fd),
63 size_(0),
64 lock_("SwapSpace lock", static_cast<LockLevel>(LockLevel::kDefaultMutexLevel - 1)) {
65 // Assume that the file is unlinked.
66
67 InsertChunk(NewFileChunk(initial_size));
68 }
69
~SwapSpace()70 SwapSpace::~SwapSpace() {
71 // Unmap all mmapped chunks. Nothing should be allocated anymore at
72 // this point, so there should be only full size chunks in free_by_start_.
73 for (const SpaceChunk& chunk : free_by_start_) {
74 if (munmap(chunk.ptr, chunk.size) != 0) {
75 PLOG(ERROR) << "Failed to unmap swap space chunk at "
76 << static_cast<const void*>(chunk.ptr) << " size=" << chunk.size;
77 }
78 }
79 // All arenas are backed by the same file. Just close the descriptor.
80 close(fd_);
81 }
82
83 template <typename FreeByStartSet, typename FreeBySizeSet>
CollectFree(const FreeByStartSet & free_by_start,const FreeBySizeSet & free_by_size)84 static size_t CollectFree(const FreeByStartSet& free_by_start, const FreeBySizeSet& free_by_size) {
85 if (free_by_start.size() != free_by_size.size()) {
86 LOG(FATAL) << "Size: " << free_by_start.size() << " vs " << free_by_size.size();
87 }
88
89 // Calculate over free_by_size.
90 size_t sum1 = 0;
91 for (const auto& entry : free_by_size) {
92 sum1 += entry.free_by_start_entry->size;
93 }
94
95 // Calculate over free_by_start.
96 size_t sum2 = 0;
97 for (const auto& entry : free_by_start) {
98 sum2 += entry.size;
99 }
100
101 if (sum1 != sum2) {
102 LOG(FATAL) << "Sum: " << sum1 << " vs " << sum2;
103 }
104 return sum1;
105 }
106
Alloc(size_t size)107 void* SwapSpace::Alloc(size_t size) {
108 MutexLock lock(Thread::Current(), lock_);
109 size = RoundUp(size, 8U);
110
111 // Check the free list for something that fits.
112 // TODO: Smarter implementation. Global biggest chunk, ...
113 auto it = free_by_start_.empty()
114 ? free_by_size_.end()
115 : free_by_size_.lower_bound(FreeBySizeEntry { size, free_by_start_.begin() });
116 if (it != free_by_size_.end()) {
117 auto entry = it->free_by_start_entry;
118 SpaceChunk old_chunk = *entry;
119 if (old_chunk.size == size) {
120 RemoveChunk(it);
121 } else {
122 // Try to avoid deallocating and allocating the std::set<> nodes.
123 // This would be much simpler if we could use replace() from Boost.Bimap.
124
125 // The free_by_start_ map contains disjoint intervals ordered by the `ptr`.
126 // Shrinking the interval does not affect the ordering.
127 it->free_by_start_entry->ptr += size;
128 it->free_by_start_entry->size -= size;
129
130 // The free_by_size_ map is ordered by the `size` and then `free_by_start_entry->ptr`.
131 // Adjusting the `ptr` above does not change that ordering but decreasing `size` can
132 // push the node before the previous node(s).
133 if (it == free_by_size_.begin()) {
134 it->size -= size;
135 } else {
136 auto prev = it;
137 --prev;
138 FreeBySizeEntry new_value(old_chunk.size - size, entry);
139 if (free_by_size_.key_comp()(*prev, new_value)) {
140 it->size -= size;
141 } else {
142 // Changing in place would break the std::set<> ordering, we need to remove and insert.
143 free_by_size_.erase(it);
144 free_by_size_.insert(new_value);
145 }
146 }
147 }
148 return old_chunk.ptr;
149 } else {
150 // Not a big enough free chunk, need to increase file size.
151 SpaceChunk new_chunk = NewFileChunk(size);
152 if (new_chunk.size != size) {
153 // Insert the remainder.
154 SpaceChunk remainder = { new_chunk.ptr + size, new_chunk.size - size };
155 InsertChunk(remainder);
156 }
157 return new_chunk.ptr;
158 }
159 }
160
NewFileChunk(size_t min_size)161 SwapSpace::SpaceChunk SwapSpace::NewFileChunk(size_t min_size) {
162 #if !defined(__APPLE__)
163 size_t next_part = std::max(RoundUp(min_size, kPageSize), RoundUp(kMininumMapSize, kPageSize));
164 int result = TEMP_FAILURE_RETRY(ftruncate64(fd_, size_ + next_part));
165 if (result != 0) {
166 PLOG(FATAL) << "Unable to increase swap file.";
167 }
168 uint8_t* ptr = reinterpret_cast<uint8_t*>(
169 mmap(nullptr, next_part, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, size_));
170 if (ptr == MAP_FAILED) {
171 LOG(ERROR) << "Unable to mmap new swap file chunk.";
172 LOG(ERROR) << "Current size: " << size_ << " requested: " << next_part << "/" << min_size;
173 LOG(ERROR) << "Free list:";
174 DumpFreeMap(free_by_size_);
175 LOG(ERROR) << "In free list: " << CollectFree(free_by_start_, free_by_size_);
176 LOG(FATAL) << "Aborting...";
177 }
178 size_ += next_part;
179 SpaceChunk new_chunk = {ptr, next_part};
180 return new_chunk;
181 #else
182 UNUSED(min_size, kMininumMapSize);
183 LOG(FATAL) << "No swap file support on the Mac.";
184 UNREACHABLE();
185 #endif
186 }
187
188 // TODO: Full coalescing.
Free(void * ptr,size_t size)189 void SwapSpace::Free(void* ptr, size_t size) {
190 MutexLock lock(Thread::Current(), lock_);
191 size = RoundUp(size, 8U);
192
193 size_t free_before = 0;
194 if (kCheckFreeMaps) {
195 free_before = CollectFree(free_by_start_, free_by_size_);
196 }
197
198 SpaceChunk chunk = { reinterpret_cast<uint8_t*>(ptr), size };
199 auto it = free_by_start_.lower_bound(chunk);
200 if (it != free_by_start_.begin()) {
201 auto prev = it;
202 --prev;
203 CHECK_LE(prev->End(), chunk.Start());
204 if (prev->End() == chunk.Start()) {
205 // Merge *prev with this chunk.
206 chunk.size += prev->size;
207 chunk.ptr -= prev->size;
208 auto erase_pos = free_by_size_.find(FreeBySizeEntry { prev->size, prev });
209 DCHECK(erase_pos != free_by_size_.end());
210 RemoveChunk(erase_pos);
211 // "prev" is invalidated but "it" remains valid.
212 }
213 }
214 if (it != free_by_start_.end()) {
215 CHECK_LE(chunk.End(), it->Start());
216 if (chunk.End() == it->Start()) {
217 // Merge *it with this chunk.
218 chunk.size += it->size;
219 auto erase_pos = free_by_size_.find(FreeBySizeEntry { it->size, it });
220 DCHECK(erase_pos != free_by_size_.end());
221 RemoveChunk(erase_pos);
222 // "it" is invalidated but we don't need it anymore.
223 }
224 }
225 InsertChunk(chunk);
226
227 if (kCheckFreeMaps) {
228 size_t free_after = CollectFree(free_by_start_, free_by_size_);
229
230 if (free_after != free_before + size) {
231 DumpFreeMap(free_by_size_);
232 CHECK_EQ(free_after, free_before + size) << "Should be " << size << " difference from " << free_before;
233 }
234 }
235 }
236
237 } // namespace art
238