blob: c34a4ffd388c8e453fc8e9889f2621a144a70d87 [file] [log] [blame]
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001/*
2 * Copyright (C) 2016 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
Devin Moore9a27da52020-07-06 14:01:21 -070017#pragma once
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080018
Devin Moored7e702b2021-01-18 16:10:37 -080019#include <android-base/unique_fd.h>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080020#include <cutils/ashmem.h>
21#include <fmq/EventFlag.h>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080022#include <sys/mman.h>
Devin Mooreef38ed62021-04-07 10:10:36 -070023#include <sys/user.h>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080024#include <utils/Log.h>
Hridya Valsaraju2abefb62017-01-19 13:06:58 -080025#include <utils/SystemClock.h>
Devin Moore77d279e2020-07-07 10:38:52 -070026#include <atomic>
27#include <new>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080028
Devin Moore133cb5e2020-07-07 16:31:22 -070029using android::hardware::kSynchronizedReadWrite;
30using android::hardware::kUnsynchronizedWrite;
31using android::hardware::MQFlavor;
32
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080033namespace android {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080034
Devin Moore133cb5e2020-07-07 16:31:22 -070035template <template <typename, MQFlavor> class MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -070036struct MessageQueueBase {
37 typedef MQDescriptorType<T, flavor> Descriptor;
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -080038
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080039 /**
40 * @param Desc MQDescriptor describing the FMQ.
41 * @param resetPointers bool indicating whether the read/write pointers
42 * should be reset or not.
43 */
Devin Moore9a27da52020-07-06 14:01:21 -070044 MessageQueueBase(const Descriptor& Desc, bool resetPointers = true);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080045
Devin Moore9a27da52020-07-06 14:01:21 -070046 ~MessageQueueBase();
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080047
48 /**
49 * This constructor uses Ashmem shared memory to create an FMQ
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080050 * that can contain a maximum of 'numElementsInQueue' elements of type T.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080051 *
52 * @param numElementsInQueue Capacity of the MessageQueue in terms of T.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -080053 * @param configureEventFlagWord Boolean that specifies if memory should
54 * also be allocated and mapped for an EventFlag word.
Gareth Fenn1af25462020-11-11 20:46:32 +000055 * @param bufferFd User-supplied file descriptor to map the memory for the ringbuffer
56 * By default, bufferFd=-1 means library will allocate ashmem region for ringbuffer.
57 * MessageQueue takes ownership of the file descriptor.
Devin Moored7e702b2021-01-18 16:10:37 -080058 * @param bufferSize size of buffer in bytes that bufferFd represents. This
59 * size must be larger than or equal to (numElementsInQueue * sizeof(T)).
60 * Otherwise, operations will cause out-of-bounds memory access.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080061 */
Devin Moore9a27da52020-07-06 14:01:21 -070062
Devin Moored7e702b2021-01-18 16:10:37 -080063 MessageQueueBase(size_t numElementsInQueue, bool configureEventFlagWord,
64 android::base::unique_fd bufferFd, size_t bufferSize);
65
66 MessageQueueBase(size_t numElementsInQueue, bool configureEventFlagWord = false)
67 : MessageQueueBase(numElementsInQueue, configureEventFlagWord, android::base::unique_fd(),
68 0) {}
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080069
70 /**
71 * @return Number of items of type T that can be written into the FMQ
72 * without a read.
73 */
74 size_t availableToWrite() const;
75
76 /**
77 * @return Number of items of type T that are waiting to be read from the
78 * FMQ.
79 */
80 size_t availableToRead() const;
81
82 /**
83 * Returns the size of type T in bytes.
84 *
85 * @param Size of T.
86 */
87 size_t getQuantumSize() const;
88
89 /**
90 * Returns the size of the FMQ in terms of the size of type T.
91 *
92 * @return Number of items of type T that will fit in the FMQ.
93 */
94 size_t getQuantumCount() const;
95
96 /**
97 * @return Whether the FMQ is configured correctly.
98 */
99 bool isValid() const;
100
101 /**
102 * Non-blocking write to FMQ.
103 *
104 * @param data Pointer to the object of type T to be written into the FMQ.
105 *
106 * @return Whether the write was successful.
107 */
108 bool write(const T* data);
109
110 /**
111 * Non-blocking read from FMQ.
112 *
113 * @param data Pointer to the memory where the object read from the FMQ is
114 * copied to.
115 *
116 * @return Whether the read was successful.
117 */
118 bool read(T* data);
119
120 /**
121 * Write some data into the FMQ without blocking.
122 *
123 * @param data Pointer to the array of items of type T.
124 * @param count Number of items in array.
125 *
126 * @return Whether the write was successful.
127 */
128 bool write(const T* data, size_t count);
129
130 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800131 * Perform a blocking write of 'count' items into the FMQ using EventFlags.
132 * Does not support partial writes.
133 *
134 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
135 * associated with the FMQ and it is used in that case.
136 *
137 * The application code must ensure that 'evFlag' used by the
138 * reader(s)/writer is based upon the same EventFlag word.
139 *
140 * The method will return false without blocking if any of the following
141 * conditions are true:
142 * - If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700143 * - If the 'readNotification' bit mask is zero.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800144 * - If 'count' is greater than the FMQ size.
145 *
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700146 * If the there is insufficient space available to write into it, the
147 * EventFlag bit mask 'readNotification' is is waited upon.
148 *
149 * This method should only be used with a MessageQueue of the flavor
Devin Moore133cb5e2020-07-07 16:31:22 -0700150 * 'kSynchronizedReadWrite'.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800151 *
152 * Upon a successful write, wake is called on 'writeNotification' (if
153 * non-zero).
154 *
155 * @param data Pointer to the array of items of type T.
156 * @param count Number of items in array.
157 * @param readNotification The EventFlag bit mask to wait on if there is not
158 * enough space in FMQ to write 'count' items.
159 * @param writeNotification The EventFlag bit mask to call wake on
160 * a successful write. No wake is called if 'writeNotification' is zero.
161 * @param timeOutNanos Number of nanoseconds after which the blocking
162 * write attempt is aborted.
163 * @param evFlag The EventFlag object to be used for blocking. If nullptr,
164 * it is checked whether the FMQ owns an EventFlag object and that is used
165 * for blocking instead.
166 *
167 * @return Whether the write was successful.
168 */
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800169 bool writeBlocking(const T* data, size_t count, uint32_t readNotification,
170 uint32_t writeNotification, int64_t timeOutNanos = 0,
171 android::hardware::EventFlag* evFlag = nullptr);
172
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800173 bool writeBlocking(const T* data, size_t count, int64_t timeOutNanos = 0);
174
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800175 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800176 * Read some data from the FMQ without blocking.
177 *
178 * @param data Pointer to the array to which read data is to be written.
179 * @param count Number of items to be read.
180 *
181 * @return Whether the read was successful.
182 */
183 bool read(T* data, size_t count);
184
185 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800186 * Perform a blocking read operation of 'count' items from the FMQ. Does not
187 * perform a partial read.
188 *
189 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
190 * associated with the FMQ and it is used in that case.
191 *
192 * The application code must ensure that 'evFlag' used by the
193 * reader(s)/writer is based upon the same EventFlag word.
194 *
195 * The method will return false without blocking if any of the following
196 * conditions are true:
197 * -If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
198 * -If the 'writeNotification' bit mask is zero.
199 * -If 'count' is greater than the FMQ size.
200 *
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700201 * This method should only be used with a MessageQueue of the flavor
Devin Moore133cb5e2020-07-07 16:31:22 -0700202 * 'kSynchronizedReadWrite'.
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700203
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800204 * If FMQ does not contain 'count' items, the eventFlag bit mask
205 * 'writeNotification' is waited upon. Upon a successful read from the FMQ,
206 * wake is called on 'readNotification' (if non-zero).
207 *
208 * @param data Pointer to the array to which read data is to be written.
209 * @param count Number of items to be read.
210 * @param readNotification The EventFlag bit mask to call wake on after
211 * a successful read. No wake is called if 'readNotification' is zero.
212 * @param writeNotification The EventFlag bit mask to call a wait on
213 * if there is insufficient data in the FMQ to be read.
214 * @param timeOutNanos Number of nanoseconds after which the blocking
215 * read attempt is aborted.
216 * @param evFlag The EventFlag object to be used for blocking.
217 *
218 * @return Whether the read was successful.
219 */
Devin Moore77d279e2020-07-07 10:38:52 -0700220 bool readBlocking(T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
221 int64_t timeOutNanos = 0, android::hardware::EventFlag* evFlag = nullptr);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800222
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800223 bool readBlocking(T* data, size_t count, int64_t timeOutNanos = 0);
224
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800225 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800226 * Get a pointer to the MQDescriptor object that describes this FMQ.
227 *
228 * @return Pointer to the MQDescriptor associated with the FMQ.
229 */
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800230 const Descriptor* getDesc() const { return mDesc.get(); }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800231
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800232 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800233 * Get a pointer to the EventFlag word if there is one associated with this FMQ.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800234 *
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800235 * @return Pointer to an EventFlag word, will return nullptr if not
236 * configured. This method does not transfer ownership. The EventFlag
237 * word will be unmapped by the MessageQueue destructor.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800238 */
239 std::atomic<uint32_t>* getEventFlagWord() const { return mEvFlagWord; }
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800240
241 /**
242 * Describes a memory region in the FMQ.
243 */
244 struct MemRegion {
245 MemRegion() : MemRegion(nullptr, 0) {}
246
247 MemRegion(T* base, size_t size) : address(base), length(size) {}
248
Devin Moore77d279e2020-07-07 10:38:52 -0700249 MemRegion& operator=(const MemRegion& other) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800250 address = other.address;
251 length = other.length;
252 return *this;
253 }
254
255 /**
256 * Gets a pointer to the base address of the MemRegion.
257 */
258 inline T* getAddress() const { return address; }
259
260 /**
261 * Gets the length of the MemRegion. This would equal to the number
262 * of items of type T that can be read from/written into the MemRegion.
263 */
264 inline size_t getLength() const { return length; }
265
266 /**
267 * Gets the length of the MemRegion in bytes.
268 */
269 inline size_t getLengthInBytes() const { return length * sizeof(T); }
270
Devin Moore77d279e2020-07-07 10:38:52 -0700271 private:
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800272 /* Base address */
273 T* address;
274
275 /*
276 * Number of items of type T that can be written to/read from the base
277 * address.
278 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800279 size_t length;
280 };
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800281
282 /**
283 * Describes the memory regions to be used for a read or write.
284 * The struct contains two MemRegion objects since the FMQ is a ring
285 * buffer and a read or write operation can wrap around. A single message
286 * of type T will never be broken between the two MemRegions.
287 */
288 struct MemTransaction {
289 MemTransaction() : MemTransaction(MemRegion(), MemRegion()) {}
290
Devin Moore77d279e2020-07-07 10:38:52 -0700291 MemTransaction(const MemRegion& regionFirst, const MemRegion& regionSecond)
292 : first(regionFirst), second(regionSecond) {}
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800293
Devin Moore77d279e2020-07-07 10:38:52 -0700294 MemTransaction& operator=(const MemTransaction& other) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800295 first = other.first;
296 second = other.second;
297 return *this;
298 }
299
300 /**
301 * Helper method to calculate the address for a particular index for
302 * the MemTransaction object.
303 *
304 * @param idx Index of the slot to be read/written. If the
305 * MemTransaction object is representing the memory region to read/write
306 * N items of type T, the valid range of idx is between 0 and N-1.
307 *
308 * @return Pointer to the slot idx. Will be nullptr for an invalid idx.
309 */
310 T* getSlot(size_t idx);
311
312 /**
313 * Helper method to write 'nMessages' items of type T into the memory
314 * regions described by the object starting from 'startIdx'. This method
315 * uses memcpy() and is not to meant to be used for a zero copy operation.
316 * Partial writes are not supported.
317 *
318 * @param data Pointer to the source buffer.
319 * @param nMessages Number of items of type T.
320 * @param startIdx The slot number to begin the write from. If the
321 * MemTransaction object is representing the memory region to read/write
322 * N items of type T, the valid range of startIdx is between 0 and N-1;
323 *
324 * @return Whether the write operation of size 'nMessages' succeeded.
325 */
326 bool copyTo(const T* data, size_t startIdx, size_t nMessages = 1);
327
328 /*
329 * Helper method to read 'nMessages' items of type T from the memory
330 * regions described by the object starting from 'startIdx'. This method uses
331 * memcpy() and is not meant to be used for a zero copy operation. Partial reads
332 * are not supported.
333 *
334 * @param data Pointer to the destination buffer.
335 * @param nMessages Number of items of type T.
336 * @param startIdx The slot number to begin the read from. If the
337 * MemTransaction object is representing the memory region to read/write
338 * N items of type T, the valid range of startIdx is between 0 and N-1.
339 *
340 * @return Whether the read operation of size 'nMessages' succeeded.
341 */
342 bool copyFrom(T* data, size_t startIdx, size_t nMessages = 1);
343
344 /**
345 * Returns a const reference to the first MemRegion in the
346 * MemTransaction object.
347 */
348 inline const MemRegion& getFirstRegion() const { return first; }
349
350 /**
351 * Returns a const reference to the second MemRegion in the
352 * MemTransaction object.
353 */
354 inline const MemRegion& getSecondRegion() const { return second; }
355
Devin Moore77d279e2020-07-07 10:38:52 -0700356 private:
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800357 /*
358 * Given a start index and the number of messages to be
359 * read/written, this helper method calculates the
360 * number of messages that should should be written to both the first
361 * and second MemRegions and the base addresses to be used for
362 * the read/write operation.
363 *
364 * Returns false if the 'startIdx' and 'nMessages' is
365 * invalid for the MemTransaction object.
366 */
Devin Moore77d279e2020-07-07 10:38:52 -0700367 bool inline getMemRegionInfo(size_t idx, size_t nMessages, size_t& firstCount,
368 size_t& secondCount, T** firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800369 T** secondBaseAddress);
370 MemRegion first;
371 MemRegion second;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800372 };
373
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800374 /**
375 * Get a MemTransaction object to write 'nMessages' items of type T.
376 * Once the write is performed using the information from MemTransaction,
377 * the write operation is to be committed using a call to commitWrite().
378 *
379 * @param nMessages Number of messages of type T.
380 * @param Pointer to MemTransaction struct that describes memory to write 'nMessages'
381 * items of type T. If a write of size 'nMessages' is not possible, the base
382 * addresses in the MemTransaction object would be set to nullptr.
383 *
384 * @return Whether it is possible to write 'nMessages' items of type T
385 * into the FMQ.
386 */
387 bool beginWrite(size_t nMessages, MemTransaction* memTx) const;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800388
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800389 /**
390 * Commit a write of size 'nMessages'. To be only used after a call to beginWrite().
391 *
392 * @param nMessages number of messages of type T to be written.
393 *
394 * @return Whether the write operation of size 'nMessages' succeeded.
395 */
396 bool commitWrite(size_t nMessages);
397
398 /**
399 * Get a MemTransaction object to read 'nMessages' items of type T.
400 * Once the read is performed using the information from MemTransaction,
401 * the read operation is to be committed using a call to commitRead().
402 *
403 * @param nMessages Number of messages of type T.
404 * @param pointer to MemTransaction struct that describes memory to read 'nMessages'
405 * items of type T. If a read of size 'nMessages' is not possible, the base
406 * pointers in the MemTransaction object returned will be set to nullptr.
407 *
408 * @return bool Whether it is possible to read 'nMessages' items of type T
409 * from the FMQ.
410 */
411 bool beginRead(size_t nMessages, MemTransaction* memTx) const;
412
413 /**
414 * Commit a read of size 'nMessages'. To be only used after a call to beginRead().
415 * For the unsynchronized flavor of FMQ, this method will return a failure
416 * if a write overflow happened after beginRead() was invoked.
417 *
418 * @param nMessages number of messages of type T to be read.
419 *
420 * @return bool Whether the read operation of size 'nMessages' succeeded.
421 */
422 bool commitRead(size_t nMessages);
423
Devin Moore77d279e2020-07-07 10:38:52 -0700424 private:
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800425 size_t availableToWriteBytes() const;
426 size_t availableToReadBytes() const;
427
Devin Moore9a27da52020-07-06 14:01:21 -0700428 MessageQueueBase(const MessageQueueBase& other) = delete;
429 MessageQueueBase& operator=(const MessageQueueBase& other) = delete;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800430
431 void* mapGrantorDescr(uint32_t grantorIdx);
432 void unmapGrantorDescr(void* address, uint32_t grantorIdx);
433 void initMemory(bool resetPointers);
434
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800435 enum DefaultEventNotification : uint32_t {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800436 /*
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700437 * These are only used internally by the readBlocking()/writeBlocking()
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800438 * methods and hence once other bit combinations are not required.
439 */
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700440 FMQ_NOT_FULL = 0x01,
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800441 FMQ_NOT_EMPTY = 0x02
442 };
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800443 std::unique_ptr<Descriptor> mDesc;
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800444 uint8_t* mRing = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800445 /*
446 * TODO(b/31550092): Change to 32 bit read and write pointer counters.
447 */
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800448 std::atomic<uint64_t>* mReadPtr = nullptr;
449 std::atomic<uint64_t>* mWritePtr = nullptr;
450
451 std::atomic<uint32_t>* mEvFlagWord = nullptr;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800452
453 /*
454 * This EventFlag object will be owned by the FMQ and will have the same
455 * lifetime.
456 */
457 android::hardware::EventFlag* mEventFlag = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800458};
459
Devin Moore133cb5e2020-07-07 16:31:22 -0700460template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700461T* MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getSlot(size_t idx) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800462 size_t firstRegionLength = first.getLength();
463 size_t secondRegionLength = second.getLength();
464
465 if (idx > firstRegionLength + secondRegionLength) {
466 return nullptr;
467 }
468
469 if (idx < firstRegionLength) {
470 return first.getAddress() + idx;
471 }
472
473 return second.getAddress() + idx - firstRegionLength;
474}
475
Devin Moore133cb5e2020-07-07 16:31:22 -0700476template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700477bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getMemRegionInfo(
478 size_t startIdx, size_t nMessages, size_t& firstCount, size_t& secondCount,
479 T** firstBaseAddress, T** secondBaseAddress) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800480 size_t firstRegionLength = first.getLength();
481 size_t secondRegionLength = second.getLength();
482
483 if (startIdx + nMessages > firstRegionLength + secondRegionLength) {
484 /*
485 * Return false if 'nMessages' starting at 'startIdx' cannot be
Devin Moored7e702b2021-01-18 16:10:37 -0800486 * accommodated by the MemTransaction object.
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800487 */
488 return false;
489 }
490
491 /* Number of messages to be read/written to the first MemRegion. */
Devin Moore77d279e2020-07-07 10:38:52 -0700492 firstCount =
493 startIdx < firstRegionLength ? std::min(nMessages, firstRegionLength - startIdx) : 0;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800494
495 /* Number of messages to be read/written to the second MemRegion. */
496 secondCount = nMessages - firstCount;
497
498 if (firstCount != 0) {
499 *firstBaseAddress = first.getAddress() + startIdx;
500 }
501
502 if (secondCount != 0) {
503 size_t secondStartIdx = startIdx > firstRegionLength ? startIdx - firstRegionLength : 0;
504 *secondBaseAddress = second.getAddress() + secondStartIdx;
505 }
506
507 return true;
508}
509
Devin Moore133cb5e2020-07-07 16:31:22 -0700510template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700511bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyFrom(T* data,
512 size_t startIdx,
513 size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800514 if (data == nullptr) {
515 return false;
516 }
517
518 size_t firstReadCount = 0, secondReadCount = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700519 T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800520
Devin Moore77d279e2020-07-07 10:38:52 -0700521 if (getMemRegionInfo(startIdx, nMessages, firstReadCount, secondReadCount, &firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800522 &secondBaseAddress) == false) {
523 /*
524 * Returns false if 'startIdx' and 'nMessages' are invalid for this
525 * MemTransaction object.
526 */
527 return false;
528 }
529
530 if (firstReadCount != 0) {
531 memcpy(data, firstBaseAddress, firstReadCount * sizeof(T));
532 }
533
534 if (secondReadCount != 0) {
Devin Moore77d279e2020-07-07 10:38:52 -0700535 memcpy(data + firstReadCount, secondBaseAddress, secondReadCount * sizeof(T));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800536 }
537
538 return true;
539}
540
Devin Moore133cb5e2020-07-07 16:31:22 -0700541template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700542bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyTo(const T* data,
543 size_t startIdx,
544 size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800545 if (data == nullptr) {
546 return false;
547 }
548
549 size_t firstWriteCount = 0, secondWriteCount = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700550 T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800551
Devin Moore77d279e2020-07-07 10:38:52 -0700552 if (getMemRegionInfo(startIdx, nMessages, firstWriteCount, secondWriteCount, &firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800553 &secondBaseAddress) == false) {
554 /*
555 * Returns false if 'startIdx' and 'nMessages' are invalid for this
556 * MemTransaction object.
557 */
558 return false;
559 }
560
561 if (firstWriteCount != 0) {
562 memcpy(firstBaseAddress, data, firstWriteCount * sizeof(T));
563 }
564
565 if (secondWriteCount != 0) {
Devin Moore77d279e2020-07-07 10:38:52 -0700566 memcpy(secondBaseAddress, data + firstWriteCount, secondWriteCount * sizeof(T));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800567 }
568
569 return true;
570}
571
Devin Moore133cb5e2020-07-07 16:31:22 -0700572template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700573void MessageQueueBase<MQDescriptorType, T, flavor>::initMemory(bool resetPointers) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800574 /*
Devin Moore9a27da52020-07-06 14:01:21 -0700575 * Verify that the Descriptor contains the minimum number of grantors
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800576 * the native_handle is valid and T matches quantum size.
577 */
578 if ((mDesc == nullptr) || !mDesc->isHandleValid() ||
Devin Mooreb00fb7d2020-08-05 14:09:05 -0700579 (mDesc->countGrantors() < hardware::details::kMinGrantorCount)) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800580 return;
581 }
Devin Mooreb00fb7d2020-08-05 14:09:05 -0700582 if (mDesc->getQuantum() != sizeof(T)) {
583 hardware::details::logError(
584 "Payload size differs between the queue instantiation and the "
585 "MQDescriptor.");
586 return;
587 }
588
Devin Moore133cb5e2020-07-07 16:31:22 -0700589 const auto& grantors = mDesc->grantors();
590 for (const auto& grantor : grantors) {
Devin Moore19bde112021-07-21 17:14:01 +0000591 hardware::details::check(hardware::details::isAlignedToWordBoundary(grantor.offset) == true,
592 "Grantor offsets need to be aligned");
Devin Moore133cb5e2020-07-07 16:31:22 -0700593 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800594
Devin Moore133cb5e2020-07-07 16:31:22 -0700595 if (flavor == kSynchronizedReadWrite) {
596 mReadPtr = reinterpret_cast<std::atomic<uint64_t>*>(
597 mapGrantorDescr(hardware::details::READPTRPOS));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800598 } else {
599 /*
600 * The unsynchronized write flavor of the FMQ may have multiple readers
601 * and each reader would have their own read pointer counter.
602 */
603 mReadPtr = new (std::nothrow) std::atomic<uint64_t>;
604 }
Devin Moore19bde112021-07-21 17:14:01 +0000605 hardware::details::check(mReadPtr != nullptr, "mReadPtr is null");
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800606
Devin Moore133cb5e2020-07-07 16:31:22 -0700607 mWritePtr = reinterpret_cast<std::atomic<uint64_t>*>(
608 mapGrantorDescr(hardware::details::WRITEPTRPOS));
Devin Moore19bde112021-07-21 17:14:01 +0000609 hardware::details::check(mWritePtr != nullptr, "mWritePtr is null");
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800610
611 if (resetPointers) {
612 mReadPtr->store(0, std::memory_order_release);
613 mWritePtr->store(0, std::memory_order_release);
Devin Moore133cb5e2020-07-07 16:31:22 -0700614 } else if (flavor != kSynchronizedReadWrite) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800615 // Always reset the read pointer.
616 mReadPtr->store(0, std::memory_order_release);
617 }
618
Devin Moore133cb5e2020-07-07 16:31:22 -0700619 mRing = reinterpret_cast<uint8_t*>(mapGrantorDescr(hardware::details::DATAPTRPOS));
Devin Moore19bde112021-07-21 17:14:01 +0000620 hardware::details::check(mRing != nullptr, "mRing is null");
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800621
Mikhail Naganov9017c2e2021-03-29 14:56:12 -0700622 if (mDesc->countGrantors() > hardware::details::EVFLAGWORDPOS) {
623 mEvFlagWord = static_cast<std::atomic<uint32_t>*>(
624 mapGrantorDescr(hardware::details::EVFLAGWORDPOS));
Devin Moore19bde112021-07-21 17:14:01 +0000625 hardware::details::check(mEvFlagWord != nullptr, "mEvFlagWord is null");
626 android::hardware::EventFlag::createEventFlag(mEvFlagWord, &mEventFlag);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800627 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800628}
629
Devin Moore133cb5e2020-07-07 16:31:22 -0700630template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700631MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(const Descriptor& Desc,
632 bool resetPointers) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800633 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(Desc));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800634 if (mDesc == nullptr) {
635 return;
636 }
637
638 initMemory(resetPointers);
639}
640
Devin Moore133cb5e2020-07-07 16:31:22 -0700641template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700642MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(size_t numElementsInQueue,
Gareth Fenn1af25462020-11-11 20:46:32 +0000643 bool configureEventFlagWord,
Devin Moored7e702b2021-01-18 16:10:37 -0800644 android::base::unique_fd bufferFd,
645 size_t bufferSize) {
Kevin Rocard1d6e40f2017-04-03 11:51:13 -0700646 // Check if the buffer size would not overflow size_t
647 if (numElementsInQueue > SIZE_MAX / sizeof(T)) {
Devin Moored7e702b2021-01-18 16:10:37 -0800648 hardware::details::logError("Requested message queue size too large. Size of elements: " +
649 std::to_string(sizeof(T)) +
650 ". Number of elements: " + std::to_string(numElementsInQueue));
651 return;
652 }
653 if (bufferFd != -1 && numElementsInQueue * sizeof(T) > bufferSize) {
654 hardware::details::logError("The supplied buffer size(" + std::to_string(bufferSize) +
655 ") is smaller than the required size(" +
656 std::to_string(numElementsInQueue * sizeof(T)) + ").");
Kevin Rocard1d6e40f2017-04-03 11:51:13 -0700657 return;
658 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800659 /*
660 * The FMQ needs to allocate memory for the ringbuffer as well as for the
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800661 * read and write pointer counters. If an EventFlag word is to be configured,
662 * we also need to allocate memory for the same/
663 */
664 size_t kQueueSizeBytes = numElementsInQueue * sizeof(T);
Devin Moore133cb5e2020-07-07 16:31:22 -0700665 size_t kMetaDataSize = 2 * sizeof(android::hardware::details::RingBufferPosition);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800666
667 if (configureEventFlagWord) {
Devin Moore77d279e2020-07-07 10:38:52 -0700668 kMetaDataSize += sizeof(std::atomic<uint32_t>);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800669 }
670
671 /*
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800672 * Ashmem memory region size needs to be specified in page-aligned bytes.
673 * kQueueSizeBytes needs to be aligned to word boundary so that all offsets
674 * in the grantorDescriptor will be word aligned.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800675 */
Gareth Fenn1af25462020-11-11 20:46:32 +0000676 size_t kAshmemSizePageAligned;
677 if (bufferFd != -1) {
678 // Allocate read counter and write counter only. User-supplied memory will be used for the
679 // ringbuffer.
680 kAshmemSizePageAligned = (kMetaDataSize + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
681 } else {
682 // Allocate ringbuffer, read counter and write counter.
683 kAshmemSizePageAligned = (hardware::details::alignToWordBoundary(kQueueSizeBytes) +
684 kMetaDataSize + PAGE_SIZE - 1) &
685 ~(PAGE_SIZE - 1);
686 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800687
688 /*
689 * The native handle will contain the fds to be mapped.
690 */
Gareth Fenn1af25462020-11-11 20:46:32 +0000691 int numFds = (bufferFd != -1) ? 2 : 1;
692 native_handle_t* mqHandle = native_handle_create(numFds, 0 /* numInts */);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800693 if (mqHandle == nullptr) {
694 return;
695 }
696
Gareth Fenn1af25462020-11-11 20:46:32 +0000697 /*
698 * Create an ashmem region to map the memory.
699 */
700 int ashmemFd = ashmem_create_region("MessageQueue", kAshmemSizePageAligned);
701 ashmem_set_prot_region(ashmemFd, PROT_READ | PROT_WRITE);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800702 mqHandle->data[0] = ashmemFd;
Gareth Fenn1af25462020-11-11 20:46:32 +0000703
704 if (bufferFd != -1) {
705 // Use user-supplied file descriptor for fdIndex 1
Devin Moored7e702b2021-01-18 16:10:37 -0800706 mqHandle->data[1] = bufferFd.get();
707 // release ownership of fd. mqHandle owns it now.
708 if (bufferFd.release() < 0) {
709 hardware::details::logError("Error releasing supplied bufferFd");
710 }
Gareth Fenn1af25462020-11-11 20:46:32 +0000711
712 std::vector<android::hardware::GrantorDescriptor> grantors;
713 grantors.resize(configureEventFlagWord ? hardware::details::kMinGrantorCountForEvFlagSupport
714 : hardware::details::kMinGrantorCount);
715
716 size_t memSize[] = {
717 sizeof(hardware::details::RingBufferPosition), /* memory to be allocated for read
718 pointer counter */
719 sizeof(hardware::details::RingBufferPosition), /* memory to be allocated for write
720 pointer counter */
721 kQueueSizeBytes, /* memory to be allocated for data buffer */
722 sizeof(std::atomic<uint32_t>) /* memory to be allocated for EventFlag word */
723 };
724
725 for (size_t grantorPos = 0, offset = 0; grantorPos < grantors.size(); grantorPos++) {
726 uint32_t grantorFdIndex;
727 size_t grantorOffset;
728 if (grantorPos == hardware::details::DATAPTRPOS) {
729 grantorFdIndex = 1;
730 grantorOffset = 0;
731 } else {
732 grantorFdIndex = 0;
733 grantorOffset = offset;
734 offset += memSize[grantorPos];
735 }
736 grantors[grantorPos] = {
737 0 /* grantor flags */, grantorFdIndex,
738 static_cast<uint32_t>(hardware::details::alignToWordBoundary(grantorOffset)),
739 memSize[grantorPos]};
740 }
741
742 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow)
743 Descriptor(grantors, mqHandle, sizeof(T)));
744 } else {
745 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(
746 kQueueSizeBytes, mqHandle, sizeof(T), configureEventFlagWord));
747 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800748 if (mDesc == nullptr) {
Gareth Fenn1af25462020-11-11 20:46:32 +0000749 native_handle_close(mqHandle);
750 native_handle_delete(mqHandle);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800751 return;
752 }
753 initMemory(true);
754}
755
Devin Moore133cb5e2020-07-07 16:31:22 -0700756template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700757MessageQueueBase<MQDescriptorType, T, flavor>::~MessageQueueBase() {
Devin Moored7e702b2021-01-18 16:10:37 -0800758 if (flavor == kUnsynchronizedWrite && mReadPtr != nullptr) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800759 delete mReadPtr;
Devin Moored7e702b2021-01-18 16:10:37 -0800760 } else if (mReadPtr != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700761 unmapGrantorDescr(mReadPtr, hardware::details::READPTRPOS);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800762 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800763 if (mWritePtr != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700764 unmapGrantorDescr(mWritePtr, hardware::details::WRITEPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800765 }
766 if (mRing != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700767 unmapGrantorDescr(mRing, hardware::details::DATAPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800768 }
769 if (mEvFlagWord != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700770 unmapGrantorDescr(mEvFlagWord, hardware::details::EVFLAGWORDPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800771 android::hardware::EventFlag::deleteEventFlag(&mEventFlag);
772 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800773}
774
Devin Moore133cb5e2020-07-07 16:31:22 -0700775template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700776bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800777 return write(data, 1);
778}
779
Devin Moore133cb5e2020-07-07 16:31:22 -0700780template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700781bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800782 return read(data, 1);
783}
784
Devin Moore133cb5e2020-07-07 16:31:22 -0700785template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700786bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data, size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800787 MemTransaction tx;
Devin Moore77d279e2020-07-07 10:38:52 -0700788 return beginWrite(nMessages, &tx) && tx.copyTo(data, 0 /* startIdx */, nMessages) &&
789 commitWrite(nMessages);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800790}
791
Devin Moore133cb5e2020-07-07 16:31:22 -0700792template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700793bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(
794 const T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
795 int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700796 static_assert(flavor == kSynchronizedReadWrite,
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700797 "writeBlocking can only be used with the "
Devin Moore133cb5e2020-07-07 16:31:22 -0700798 "kSynchronizedReadWrite flavor.");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800799 /*
800 * If evFlag is null and the FMQ does not have its own EventFlag object
801 * return false;
Devin Moore133cb5e2020-07-07 16:31:22 -0700802 * If the flavor is kSynchronizedReadWrite and the readNotification
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800803 * bit mask is zero return false;
804 * If the count is greater than queue size, return false
805 * to prevent blocking until timeOut.
806 */
807 if (evFlag == nullptr) {
808 evFlag = mEventFlag;
809 if (evFlag == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -0700810 hardware::details::logError(
Devin Moore77d279e2020-07-07 10:38:52 -0700811 "writeBlocking failed: called on MessageQueue with no Eventflag"
812 "configured or provided");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800813 return false;
814 }
815 }
816
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700817 if (readNotification == 0 || (count > getQuantumCount())) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800818 return false;
819 }
820
821 /*
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700822 * There is no need to wait for a readNotification if there is sufficient
823 * space to write is already present in the FMQ. The latter would be the case when
824 * read operations read more number of messages than write operations write.
825 * In other words, a single large read may clear the FMQ after multiple small
826 * writes. This would fail to clear a pending readNotification bit since
827 * EventFlag bits can only be cleared by a wait() call, however the bit would
828 * be correctly cleared by the next writeBlocking() call.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800829 */
830
831 bool result = write(data, count);
832 if (result) {
833 if (writeNotification) {
834 evFlag->wake(writeNotification);
835 }
836 return result;
837 }
838
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800839 bool shouldTimeOut = timeOutNanos != 0;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700840 int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800841
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700842 while (true) {
843 /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800844 if (shouldTimeOut) {
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700845 /*
846 * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
847 * to Nanoseconds)
848 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800849 int64_t currentTimeNs = android::elapsedRealtimeNano();
850 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700851 * Decrement 'timeOutNanos' to account for the time taken to complete the last
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800852 * iteration of the while loop.
853 */
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700854 timeOutNanos -= currentTimeNs - prevTimeNanos;
855 prevTimeNanos = currentTimeNs;
856
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800857 if (timeOutNanos <= 0) {
858 /*
859 * Attempt write in case a context switch happened outside of
860 * evFlag->wait().
861 */
862 result = write(data, count);
863 break;
864 }
865 }
866
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800867 /*
868 * wait() will return immediately if there was a pending read
869 * notification.
870 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800871 uint32_t efState = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700872 status_t status = evFlag->wait(readNotification, &efState, timeOutNanos,
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700873 true /* retry on spurious wake */);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800874
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700875 if (status != android::TIMED_OUT && status != android::NO_ERROR) {
Devin Moore9a27da52020-07-06 14:01:21 -0700876 hardware::details::logError("Unexpected error code from EventFlag Wait status " +
877 std::to_string(status));
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700878 break;
879 }
880
881 if (status == android::TIMED_OUT) {
882 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800883 }
884
885 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700886 * If there is still insufficient space to write to the FMQ,
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800887 * keep waiting for another readNotification.
888 */
889 if ((efState & readNotification) && write(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800890 result = true;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700891 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800892 }
893 }
894
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800895 if (result && writeNotification != 0) {
896 evFlag->wake(writeNotification);
897 }
898
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800899 return result;
900}
901
Devin Moore133cb5e2020-07-07 16:31:22 -0700902template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700903bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(const T* data, size_t count,
904 int64_t timeOutNanos) {
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800905 return writeBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
906}
907
Devin Moore133cb5e2020-07-07 16:31:22 -0700908template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700909bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(
910 T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
911 int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700912 static_assert(flavor == kSynchronizedReadWrite,
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700913 "readBlocking can only be used with the "
Devin Moore133cb5e2020-07-07 16:31:22 -0700914 "kSynchronizedReadWrite flavor.");
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700915
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800916 /*
917 * If evFlag is null and the FMQ does not own its own EventFlag object
918 * return false;
919 * If the writeNotification bit mask is zero return false;
920 * If the count is greater than queue size, return false to prevent
921 * blocking until timeOut.
922 */
923 if (evFlag == nullptr) {
924 evFlag = mEventFlag;
925 if (evFlag == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -0700926 hardware::details::logError(
Devin Moore77d279e2020-07-07 10:38:52 -0700927 "readBlocking failed: called on MessageQueue with no Eventflag"
928 "configured or provided");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800929 return false;
930 }
931 }
932
933 if (writeNotification == 0 || count > getQuantumCount()) {
934 return false;
935 }
936
937 /*
938 * There is no need to wait for a write notification if sufficient
939 * data to read is already present in the FMQ. This would be the
940 * case when read operations read lesser number of messages than
941 * a write operation and multiple reads would be required to clear the queue
942 * after a single write operation. This check would fail to clear a pending
943 * writeNotification bit since EventFlag bits can only be cleared
944 * by a wait() call, however the bit would be correctly cleared by the next
945 * readBlocking() call.
946 */
947
948 bool result = read(data, count);
949 if (result) {
950 if (readNotification) {
951 evFlag->wake(readNotification);
952 }
953 return result;
954 }
955
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800956 bool shouldTimeOut = timeOutNanos != 0;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700957 int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800958
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700959 while (true) {
960 /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800961 if (shouldTimeOut) {
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700962 /*
963 * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
964 * to Nanoseconds)
965 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800966 int64_t currentTimeNs = android::elapsedRealtimeNano();
967 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700968 * Decrement 'timeOutNanos' to account for the time taken to complete the last
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800969 * iteration of the while loop.
970 */
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700971 timeOutNanos -= currentTimeNs - prevTimeNanos;
972 prevTimeNanos = currentTimeNs;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800973
974 if (timeOutNanos <= 0) {
975 /*
976 * Attempt read in case a context switch happened outside of
977 * evFlag->wait().
978 */
979 result = read(data, count);
980 break;
981 }
982 }
983
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800984 /*
985 * wait() will return immediately if there was a pending write
986 * notification.
987 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800988 uint32_t efState = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700989 status_t status = evFlag->wait(writeNotification, &efState, timeOutNanos,
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700990 true /* retry on spurious wake */);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800991
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700992 if (status != android::TIMED_OUT && status != android::NO_ERROR) {
Devin Moore9a27da52020-07-06 14:01:21 -0700993 hardware::details::logError("Unexpected error code from EventFlag Wait status " +
994 std::to_string(status));
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700995 break;
996 }
997
998 if (status == android::TIMED_OUT) {
999 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -08001000 }
1001
1002 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -07001003 * If the data in FMQ is still insufficient, go back to waiting
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -08001004 * for another write notification.
1005 */
1006 if ((efState & writeNotification) && read(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -08001007 result = true;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -07001008 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -08001009 }
1010 }
1011
Hridya Valsaraju2abefb62017-01-19 13:06:58 -08001012 if (result && readNotification != 0) {
1013 evFlag->wake(readNotification);
1014 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -08001015 return result;
1016}
1017
Devin Moore133cb5e2020-07-07 16:31:22 -07001018template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001019bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(T* data, size_t count,
1020 int64_t timeOutNanos) {
Hridya Valsaraju4486ad02017-01-13 20:49:39 -08001021 return readBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
1022}
1023
Devin Moore133cb5e2020-07-07 16:31:22 -07001024template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001025size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWriteBytes() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001026 return mDesc->getSize() - availableToReadBytes();
1027}
1028
Devin Moore133cb5e2020-07-07 16:31:22 -07001029template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001030size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWrite() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001031 return availableToWriteBytes() / sizeof(T);
1032}
1033
Devin Moore133cb5e2020-07-07 16:31:22 -07001034template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001035size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToRead() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001036 return availableToReadBytes() / sizeof(T);
1037}
1038
Devin Moore133cb5e2020-07-07 16:31:22 -07001039template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001040bool MessageQueueBase<MQDescriptorType, T, flavor>::beginWrite(size_t nMessages,
1041 MemTransaction* result) const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001042 /*
1043 * If nMessages is greater than size of FMQ or in case of the synchronized
1044 * FMQ flavor, if there is not enough space to write nMessages, then return
1045 * result with null addresses.
1046 */
Devin Moore133cb5e2020-07-07 16:31:22 -07001047 if ((flavor == kSynchronizedReadWrite && (availableToWrite() < nMessages)) ||
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001048 nMessages > getQuantumCount()) {
1049 *result = MemTransaction();
1050 return false;
1051 }
1052
1053 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
Devin Moorea8b62612021-04-09 09:10:28 -07001054 if (writePtr % sizeof(T) != 0) {
1055 hardware::details::logError(
1056 "The write pointer has become misaligned. Writing to the queue is no longer "
1057 "possible.");
Devin Moore2741a812021-04-29 16:22:51 -07001058 hardware::details::errorWriteLog(0x534e4554, "184963385");
Devin Moorea8b62612021-04-09 09:10:28 -07001059 return false;
1060 }
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001061 size_t writeOffset = writePtr % mDesc->getSize();
1062
1063 /*
1064 * From writeOffset, the number of messages that can be written
1065 * contiguously without wrapping around the ring buffer are calculated.
1066 */
1067 size_t contiguousMessages = (mDesc->getSize() - writeOffset) / sizeof(T);
1068
1069 if (contiguousMessages < nMessages) {
1070 /*
1071 * Wrap around is required. Both result.first and result.second are
1072 * populated.
1073 */
Devin Moore77d279e2020-07-07 10:38:52 -07001074 *result = MemTransaction(
1075 MemRegion(reinterpret_cast<T*>(mRing + writeOffset), contiguousMessages),
1076 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001077 } else {
1078 /*
1079 * A wrap around is not required to write nMessages. Only result.first
1080 * is populated.
1081 */
1082 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + writeOffset), nMessages),
1083 MemRegion());
1084 }
1085
1086 return true;
1087}
1088
Devin Moore133cb5e2020-07-07 16:31:22 -07001089template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001090/*
1091 * Disable integer sanitization since integer overflow here is allowed
1092 * and legal.
1093 */
Devin Moore9a27da52020-07-06 14:01:21 -07001094__attribute__((no_sanitize("integer"))) bool
1095MessageQueueBase<MQDescriptorType, T, flavor>::commitWrite(size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001096 size_t nBytesWritten = nMessages * sizeof(T);
1097 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1098 writePtr += nBytesWritten;
1099 mWritePtr->store(writePtr, std::memory_order_release);
1100 /*
1101 * This method cannot fail now since we are only incrementing the writePtr
1102 * counter.
1103 */
1104 return true;
1105}
1106
Devin Moore133cb5e2020-07-07 16:31:22 -07001107template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001108size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToReadBytes() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001109 /*
1110 * This method is invoked by implementations of both read() and write() and
Devin Moore9a27da52020-07-06 14:01:21 -07001111 * hence requires a memory_order_acquired load for both mReadPtr and
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001112 * mWritePtr.
1113 */
Devin Moore77d279e2020-07-07 10:38:52 -07001114 return mWritePtr->load(std::memory_order_acquire) - mReadPtr->load(std::memory_order_acquire);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001115}
1116
Devin Moore133cb5e2020-07-07 16:31:22 -07001117template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001118bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data, size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001119 MemTransaction tx;
Devin Moore77d279e2020-07-07 10:38:52 -07001120 return beginRead(nMessages, &tx) && tx.copyFrom(data, 0 /* startIdx */, nMessages) &&
1121 commitRead(nMessages);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001122}
1123
Devin Moore133cb5e2020-07-07 16:31:22 -07001124template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001125/*
1126 * Disable integer sanitization since integer overflow here is allowed
1127 * and legal.
1128 */
Devin Moore9a27da52020-07-06 14:01:21 -07001129__attribute__((no_sanitize("integer"))) bool
1130MessageQueueBase<MQDescriptorType, T, flavor>::beginRead(size_t nMessages,
1131 MemTransaction* result) const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001132 *result = MemTransaction();
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001133 /*
1134 * If it is detected that the data in the queue was overwritten
1135 * due to the reader process being too slow, the read pointer counter
1136 * is set to the same as the write pointer counter to indicate error
1137 * and the read returns false;
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001138 * Need acquire/release memory ordering for mWritePtr.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001139 */
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001140 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1141 /*
1142 * A relaxed load is sufficient for mReadPtr since there will be no
1143 * stores to mReadPtr from a different thread.
1144 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001145 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
Devin Moorea8b62612021-04-09 09:10:28 -07001146 if (writePtr % sizeof(T) != 0 || readPtr % sizeof(T) != 0) {
1147 hardware::details::logError(
1148 "The write or read pointer has become misaligned. Reading from the queue is no "
1149 "longer possible.");
Devin Moore2741a812021-04-29 16:22:51 -07001150 hardware::details::errorWriteLog(0x534e4554, "184963385");
Devin Moorea8b62612021-04-09 09:10:28 -07001151 return false;
1152 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001153
1154 if (writePtr - readPtr > mDesc->getSize()) {
1155 mReadPtr->store(writePtr, std::memory_order_release);
1156 return false;
1157 }
1158
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001159 size_t nBytesDesired = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001160 /*
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001161 * Return if insufficient data to read in FMQ.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001162 */
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001163 if (writePtr - readPtr < nBytesDesired) {
1164 return false;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001165 }
1166
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001167 size_t readOffset = readPtr % mDesc->getSize();
1168 /*
1169 * From readOffset, the number of messages that can be read contiguously
1170 * without wrapping around the ring buffer are calculated.
1171 */
1172 size_t contiguousMessages = (mDesc->getSize() - readOffset) / sizeof(T);
1173
1174 if (contiguousMessages < nMessages) {
1175 /*
1176 * A wrap around is required. Both result.first and result.second
1177 * are populated.
1178 */
Devin Moore77d279e2020-07-07 10:38:52 -07001179 *result = MemTransaction(
1180 MemRegion(reinterpret_cast<T*>(mRing + readOffset), contiguousMessages),
1181 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001182 } else {
1183 /*
1184 * A wrap around is not required. Only result.first need to be
1185 * populated.
1186 */
1187 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + readOffset), nMessages),
1188 MemRegion());
1189 }
1190
1191 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001192}
1193
Devin Moore133cb5e2020-07-07 16:31:22 -07001194template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001195/*
1196 * Disable integer sanitization since integer overflow here is allowed
1197 * and legal.
1198 */
Devin Moore9a27da52020-07-06 14:01:21 -07001199__attribute__((no_sanitize("integer"))) bool
1200MessageQueueBase<MQDescriptorType, T, flavor>::commitRead(size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001201 // TODO: Use a local copy of readPtr to avoid relazed mReadPtr loads.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001202 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001203 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1204 /*
1205 * If the flavor is unsynchronized, it is possible that a write overflow may
Devin Moore9a27da52020-07-06 14:01:21 -07001206 * have occurred between beginRead() and commitRead().
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001207 */
1208 if (writePtr - readPtr > mDesc->getSize()) {
1209 mReadPtr->store(writePtr, std::memory_order_release);
1210 return false;
1211 }
1212
1213 size_t nBytesRead = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001214 readPtr += nBytesRead;
1215 mReadPtr->store(readPtr, std::memory_order_release);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001216 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001217}
1218
Devin Moore133cb5e2020-07-07 16:31:22 -07001219template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001220size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumSize() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001221 return mDesc->getQuantum();
1222}
1223
Devin Moore133cb5e2020-07-07 16:31:22 -07001224template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001225size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumCount() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001226 return mDesc->getSize() / mDesc->getQuantum();
1227}
1228
Devin Moore133cb5e2020-07-07 16:31:22 -07001229template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001230bool MessageQueueBase<MQDescriptorType, T, flavor>::isValid() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001231 return mRing != nullptr && mReadPtr != nullptr && mWritePtr != nullptr;
1232}
1233
Devin Moore133cb5e2020-07-07 16:31:22 -07001234template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001235void* MessageQueueBase<MQDescriptorType, T, flavor>::mapGrantorDescr(uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001236 const native_handle_t* handle = mDesc->handle();
1237 auto grantors = mDesc->grantors();
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001238 if (handle == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -07001239 hardware::details::logError("mDesc->handle is null");
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001240 return nullptr;
1241 }
1242
1243 if (grantorIdx >= grantors.size()) {
Devin Moore9a27da52020-07-06 14:01:21 -07001244 hardware::details::logError(std::string("grantorIdx must be less than ") +
1245 std::to_string(grantors.size()));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001246 return nullptr;
1247 }
1248
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001249 int fdIndex = grantors[grantorIdx].fdIndex;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001250 /*
1251 * Offset for mmap must be a multiple of PAGE_SIZE.
1252 */
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001253 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Devin Moore77d279e2020-07-07 10:38:52 -07001254 int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001255
Devin Moore77d279e2020-07-07 10:38:52 -07001256 void* address = mmap(0, mapLength, PROT_READ | PROT_WRITE, MAP_SHARED, handle->data[fdIndex],
1257 mapOffset);
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001258 if (address == MAP_FAILED) {
Devin Moore9a27da52020-07-06 14:01:21 -07001259 hardware::details::logError(std::string("mmap failed: ") + std::to_string(errno));
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001260 return nullptr;
1261 }
1262 return reinterpret_cast<uint8_t*>(address) + (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001263}
1264
Devin Moore133cb5e2020-07-07 16:31:22 -07001265template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001266void MessageQueueBase<MQDescriptorType, T, flavor>::unmapGrantorDescr(void* address,
1267 uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001268 auto grantors = mDesc->grantors();
1269 if ((address == nullptr) || (grantorIdx >= grantors.size())) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001270 return;
1271 }
1272
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001273 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Devin Moore77d279e2020-07-07 10:38:52 -07001274 int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
1275 void* baseAddress =
1276 reinterpret_cast<uint8_t*>(address) - (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001277 if (baseAddress) munmap(baseAddress, mapLength);
1278}
1279
1280} // namespace hardware