1 /*
2 * Copyright (C) 2020 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 #define LOG_TAG "DMABUFHEAPS"
18
19 #include <BufferAllocator/BufferAllocator.h>
20
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <ion/ion.h>
24 #include <linux/dma-buf.h>
25 #include <linux/dma-heap.h>
26 #include <linux/ion_4.12.h>
27 #include <stdlib.h>
28 #include <sys/types.h>
29 #include <unistd.h>
30
31 #include <shared_mutex>
32 #include <string>
33 #include <unordered_set>
34
35 #include <android-base/logging.h>
36 #include <android-base/unique_fd.h>
37
38 static constexpr char kDmaHeapRoot[] = "/dev/dma_heap/";
39 static constexpr char kIonDevice[] = "/dev/ion";
40 static constexpr char kIonSystemHeapName[] = "ion_system_heap";
41
LogInterface(const std::string & interface)42 void BufferAllocator::LogInterface(const std::string& interface) {
43 if (!logged_interface_) {
44 LOG(INFO) << "Using : " << interface;
45 logged_interface_ = true;
46 }
47 }
48
OpenDmabufHeap(const std::string & heap_name)49 int BufferAllocator::OpenDmabufHeap(const std::string& heap_name) {
50 std::shared_lock<std::shared_mutex> slock(dmabuf_heap_fd_mutex_);
51
52 /* Check if heap has already been opened. */
53 auto it = dmabuf_heap_fds_.find(heap_name);
54 if (it != dmabuf_heap_fds_.end())
55 return it->second;
56
57 slock.unlock();
58
59 /*
60 * Heap device needs to be opened, use a unique_lock since dmabuf_heap_fd_
61 * needs to be modified.
62 */
63 std::unique_lock<std::shared_mutex> ulock(dmabuf_heap_fd_mutex_);
64
65 /*
66 * Check if we already opened this heap again to prevent racing threads from
67 * opening the heap device multiple times.
68 */
69 it = dmabuf_heap_fds_.find(heap_name);
70 if (it != dmabuf_heap_fds_.end()) return it->second;
71
72 std::string heap_path = kDmaHeapRoot + heap_name;
73 int fd = TEMP_FAILURE_RETRY(open(heap_path.c_str(), O_RDONLY | O_CLOEXEC));
74 if (fd < 0) return -errno;
75
76 LOG(INFO) << "Using DMA-BUF heap named: " << heap_name;
77
78 auto ret = dmabuf_heap_fds_.insert({heap_name, android::base::unique_fd(fd)});
79 CHECK(ret.second);
80 return fd;
81 }
82
QueryIonHeaps()83 void BufferAllocator::QueryIonHeaps() {
84 uses_legacy_ion_iface_ = ion_is_legacy(ion_fd_);
85 if (uses_legacy_ion_iface_) {
86 LogInterface("Legacy ion heaps");
87 MapNameToIonMask(kDmabufSystemHeapName, ION_HEAP_SYSTEM_MASK, ION_FLAG_CACHED);
88 MapNameToIonMask(kDmabufSystemUncachedHeapName, ION_HEAP_SYSTEM_MASK);
89 return;
90 }
91
92 int heap_count;
93 int ret = ion_query_heap_cnt(ion_fd_, &heap_count);
94 if (ret == 0) {
95 ion_heap_info_.resize(heap_count, {});
96 ret = ion_query_get_heaps(ion_fd_, heap_count, ion_heap_info_.data());
97 }
98
99 // Abort if heap query fails
100 CHECK(ret == 0)
101 << "Non-legacy ION implementation must support heap information queries";
102 LogInterface("Non-legacy ION heaps");
103
104 /*
105 * No error checking here, it is possible that devices may have used another name for
106 * the ion system heap.
107 */
108 MapNameToIonName(kDmabufSystemHeapName, kIonSystemHeapName, ION_FLAG_CACHED);
109 MapNameToIonName(kDmabufSystemUncachedHeapName, kIonSystemHeapName);
110 }
111
BufferAllocator()112 BufferAllocator::BufferAllocator() {
113 ion_fd_.reset(TEMP_FAILURE_RETRY(open(kIonDevice, O_RDONLY| O_CLOEXEC)));
114 if (ion_fd_ >= 0)
115 QueryIonHeaps();
116 }
117
MapNameToIonMask(const std::string & heap_name,unsigned int ion_heap_mask,unsigned int ion_heap_flags)118 int BufferAllocator::MapNameToIonMask(const std::string& heap_name, unsigned int ion_heap_mask,
119 unsigned int ion_heap_flags) {
120 if (!ion_heap_mask)
121 return -EINVAL;
122 IonHeapConfig heap_config = { ion_heap_mask, ion_heap_flags };
123
124 std::unique_lock<std::shared_mutex> ulock(heap_name_to_config_mutex_);
125 heap_name_to_config_[heap_name] = heap_config;
126 return 0;
127 }
128
GetIonHeapIdByName(const std::string & heap_name,unsigned int * heap_id)129 int BufferAllocator::GetIonHeapIdByName(const std::string& heap_name, unsigned int* heap_id) {
130 for (auto& it : ion_heap_info_) {
131 if (heap_name == it.name) {
132 *heap_id = it.heap_id;
133 return 0;
134 }
135 }
136
137 LOG(ERROR) << "No ion heap of name " << heap_name << " exists";
138 return -EINVAL;
139 }
140
MapNameToIonName(const std::string & heap_name,const std::string & ion_heap_name,unsigned int ion_heap_flags)141 int BufferAllocator::MapNameToIonName(const std::string& heap_name,
142 const std::string& ion_heap_name,
143 unsigned int ion_heap_flags) {
144 unsigned int ion_heap_id = 0;
145 auto ret = GetIonHeapIdByName(ion_heap_name, &ion_heap_id);
146 if (ret < 0)
147 return ret;
148
149 unsigned int ion_heap_mask = 1 << ion_heap_id;
150 IonHeapConfig heap_config = { ion_heap_mask, ion_heap_flags };
151
152 std::unique_lock<std::shared_mutex> ulock(heap_name_to_config_mutex_);
153 heap_name_to_config_[heap_name] = heap_config;
154
155 return 0;
156 }
157
MapNameToIonHeap(const std::string & heap_name,const std::string & ion_heap_name,unsigned int ion_heap_flags,unsigned int legacy_ion_heap_mask,unsigned int legacy_ion_heap_flags)158 int BufferAllocator::MapNameToIonHeap(const std::string& heap_name,
159 const std::string& ion_heap_name,
160 unsigned int ion_heap_flags,
161 unsigned int legacy_ion_heap_mask,
162 unsigned int legacy_ion_heap_flags) {
163 /* if the DMA-BUF Heap exists, we can ignore ion mappings */
164 int ret = OpenDmabufHeap(heap_name);
165 if (ret >= 0)
166 return 0;
167
168 /* If ION support is not detected, ignore the mappings */
169 if (ion_fd_ < 0) return 0;
170
171 if (uses_legacy_ion_iface_ || ion_heap_name == "") {
172 ret = MapNameToIonMask(heap_name, legacy_ion_heap_mask, legacy_ion_heap_flags);
173 } else if (!ion_heap_name.empty()) {
174 ret = MapNameToIonName(heap_name, ion_heap_name, ion_heap_flags);
175 }
176
177 return ret;
178 }
179
GetIonConfig(const std::string & heap_name,IonHeapConfig & heap_config)180 int BufferAllocator::GetIonConfig(const std::string& heap_name, IonHeapConfig& heap_config) {
181 int ret = 0;
182
183 std::shared_lock<std::shared_mutex> slock(heap_name_to_config_mutex_);
184
185 auto it = heap_name_to_config_.find(heap_name);
186 if (it != heap_name_to_config_.end()) {
187 heap_config = it->second;
188 return ret;
189 }
190
191 slock.unlock();
192
193 if (uses_legacy_ion_iface_) {
194 ret = -EINVAL;
195 } else {
196 unsigned int heap_id;
197 ret = GetIonHeapIdByName(heap_name, &heap_id);
198 if (ret == 0) {
199 heap_config.mask = 1 << heap_id;
200 heap_config.flags = 0;
201 /* save it so that this lookup does not need to happen again */
202 std::unique_lock<std::shared_mutex> ulock(heap_name_to_config_mutex_);
203 heap_name_to_config_[heap_name] = heap_config;
204 }
205 }
206
207 if (ret)
208 LOG(ERROR) << "No ion heap of name " << heap_name << " exists";
209 return ret;
210 }
211
DmabufAlloc(const std::string & heap_name,size_t len)212 int BufferAllocator::DmabufAlloc(const std::string& heap_name, size_t len) {
213 int fd = OpenDmabufHeap(heap_name);
214 if (fd < 0) return fd;
215
216 struct dma_heap_allocation_data heap_data{
217 .len = len, // length of data to be allocated in bytes
218 .fd_flags = O_RDWR | O_CLOEXEC, // permissions for the memory to be allocated
219 };
220
221 auto ret = TEMP_FAILURE_RETRY(ioctl(fd, DMA_HEAP_IOCTL_ALLOC, &heap_data));
222 if (ret < 0) {
223 PLOG(ERROR) << "Unable to allocate from DMA-BUF heap: " << heap_name;
224 return ret;
225 }
226
227 return heap_data.fd;
228 }
229
IonAlloc(const std::string & heap_name,size_t len,unsigned int heap_flags,size_t legacy_align)230 int BufferAllocator::IonAlloc(const std::string& heap_name, size_t len,
231 unsigned int heap_flags, size_t legacy_align) {
232 IonHeapConfig heap_config;
233 auto ret = GetIonConfig(heap_name, heap_config);
234 if (ret)
235 return ret;
236
237 int alloc_fd = -1;
238 unsigned int flags = heap_config.flags | heap_flags;
239 ret = ion_alloc_fd(ion_fd_, len, legacy_align, heap_config.mask, flags, &alloc_fd);
240 if (ret) {
241 PLOG(ERROR) << "allocation fails for ion heap with mask: " << heap_config.mask
242 << " and flags: " << flags;
243 return ret;
244 }
245 return alloc_fd;
246 }
247
Alloc(const std::string & heap_name,size_t len,unsigned int heap_flags,size_t legacy_align)248 int BufferAllocator::Alloc(const std::string& heap_name, size_t len,
249 unsigned int heap_flags, size_t legacy_align) {
250 int fd = DmabufAlloc(heap_name, len);
251
252 if (fd < 0)
253 fd = IonAlloc(heap_name, len, heap_flags, legacy_align);
254
255 return fd;
256 }
257
AllocSystem(bool cpu_access_needed,size_t len,unsigned int heap_flags,size_t legacy_align)258 int BufferAllocator::AllocSystem(bool cpu_access_needed, size_t len, unsigned int heap_flags,
259 size_t legacy_align) {
260 if (!cpu_access_needed) {
261 /*
262 * CPU does not need to access allocated buffer so we try to allocate in
263 * the 'system-uncached' heap after querying for its existence.
264 */
265 static bool uncached_dmabuf_system_heap_support = [this]() -> bool {
266 auto dmabuf_heap_list = this->GetDmabufHeapList();
267 return (dmabuf_heap_list.find(kDmabufSystemUncachedHeapName) != dmabuf_heap_list.end());
268 }();
269
270 if (uncached_dmabuf_system_heap_support)
271 return DmabufAlloc(kDmabufSystemUncachedHeapName, len);
272
273 static bool uncached_ion_system_heap_support = [this]() -> bool {
274 IonHeapConfig heap_config;
275 auto ret = this->GetIonConfig(kDmabufSystemUncachedHeapName, heap_config);
276 return (ret == 0);
277 }();
278
279 if (uncached_ion_system_heap_support)
280 return IonAlloc(kDmabufSystemUncachedHeapName, len, heap_flags, legacy_align);
281 }
282
283 /*
284 * Either 1) CPU needs to access allocated buffer OR 2) CPU does not need to
285 * access allocated buffer but the "system-uncached" heap is unsupported.
286 */
287 return Alloc(kDmabufSystemHeapName, len, heap_flags, legacy_align);
288 }
289
LegacyIonCpuSync(unsigned int dmabuf_fd,const CustomCpuSyncLegacyIon & legacy_ion_cpu_sync_custom,void * legacy_ion_custom_data)290 int BufferAllocator::LegacyIonCpuSync(unsigned int dmabuf_fd,
291 const CustomCpuSyncLegacyIon& legacy_ion_cpu_sync_custom,
292 void *legacy_ion_custom_data) {
293 if (!legacy_ion_cpu_sync_custom)
294 return ion_sync_fd(ion_fd_, dmabuf_fd);
295
296 // dup ion_fd_ so that we retain its ownership.
297 int new_ion_fd = TEMP_FAILURE_RETRY(dup(ion_fd_.get()));
298 if (new_ion_fd < 0) {
299 PLOG(ERROR) << "Unable to dup ion fd. error: " << new_ion_fd;
300 return new_ion_fd;
301 }
302
303 int ret = legacy_ion_cpu_sync_custom(new_ion_fd, dmabuf_fd, legacy_ion_custom_data);
304
305 close(new_ion_fd);
306 return ret;
307 }
308
DoSync(unsigned int dmabuf_fd,bool start,SyncType sync_type,const CustomCpuSyncLegacyIon & legacy_ion_cpu_sync_custom,void * legacy_ion_custom_data)309 int BufferAllocator::DoSync(unsigned int dmabuf_fd, bool start, SyncType sync_type,
310 const CustomCpuSyncLegacyIon& legacy_ion_cpu_sync_custom,
311 void *legacy_ion_custom_data) {
312 if (uses_legacy_ion_iface_) {
313 return LegacyIonCpuSync(dmabuf_fd, legacy_ion_cpu_sync_custom,
314 legacy_ion_custom_data);
315 }
316
317 struct dma_buf_sync sync = {
318 .flags = (start ? DMA_BUF_SYNC_START : DMA_BUF_SYNC_END) |
319 static_cast<uint64_t>(sync_type),
320 };
321 return TEMP_FAILURE_RETRY(ioctl(dmabuf_fd, DMA_BUF_IOCTL_SYNC, &sync));
322 }
323
CpuSyncStart(unsigned int dmabuf_fd,SyncType sync_type,const CustomCpuSyncLegacyIon & legacy_ion_cpu_sync_custom,void * legacy_ion_custom_data)324 int BufferAllocator::CpuSyncStart(unsigned int dmabuf_fd, SyncType sync_type,
325 const CustomCpuSyncLegacyIon& legacy_ion_cpu_sync_custom,
326 void *legacy_ion_custom_data) {
327 int ret = DoSync(dmabuf_fd, true /* start */, sync_type, legacy_ion_cpu_sync_custom,
328 legacy_ion_custom_data);
329
330 if (ret) PLOG(ERROR) << "CpuSyncStart() failure";
331 return ret;
332 }
333
CpuSyncEnd(unsigned int dmabuf_fd,SyncType sync_type,const CustomCpuSyncLegacyIon & legacy_ion_cpu_sync_custom,void * legacy_ion_custom_data)334 int BufferAllocator::CpuSyncEnd(unsigned int dmabuf_fd, SyncType sync_type,
335 const CustomCpuSyncLegacyIon& legacy_ion_cpu_sync_custom,
336 void* legacy_ion_custom_data) {
337 int ret = DoSync(dmabuf_fd, false /* start */, sync_type, legacy_ion_cpu_sync_custom,
338 legacy_ion_custom_data);
339 if (ret) PLOG(ERROR) << "CpuSyncEnd() failure";
340
341 return ret;
342 }
343
GetDmabufHeapList()344 std::unordered_set<std::string> BufferAllocator::GetDmabufHeapList() {
345 std::unordered_set<std::string> heap_list;
346 std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir(kDmaHeapRoot), closedir);
347
348 if (dir) {
349 struct dirent* dent;
350 while ((dent = readdir(dir.get()))) {
351 if (!strcmp(dent->d_name, ".") || !strcmp(dent->d_name, "..")) continue;
352
353 heap_list.insert(dent->d_name);
354 }
355 }
356
357 return heap_list;
358 }
359
CheckIonSupport()360 bool BufferAllocator::CheckIonSupport() {
361 static bool ion_support = (access(kIonDevice, R_OK) == 0);
362
363 return ion_support;
364 }
365