blob: 79c4b086aa33888352338889a3f080a6001a3dae [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
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080019#include <cutils/ashmem.h>
20#include <fmq/EventFlag.h>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080021#include <sys/mman.h>
22#include <utils/Log.h>
Hridya Valsaraju2abefb62017-01-19 13:06:58 -080023#include <utils/SystemClock.h>
Devin Moore77d279e2020-07-07 10:38:52 -070024#include <atomic>
25#include <new>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080026
Devin Moore133cb5e2020-07-07 16:31:22 -070027using android::hardware::kSynchronizedReadWrite;
28using android::hardware::kUnsynchronizedWrite;
29using android::hardware::MQFlavor;
30
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080031namespace android {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080032
Devin Moore133cb5e2020-07-07 16:31:22 -070033template <template <typename, MQFlavor> class MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -070034struct MessageQueueBase {
35 typedef MQDescriptorType<T, flavor> Descriptor;
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -080036
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080037 /**
38 * @param Desc MQDescriptor describing the FMQ.
39 * @param resetPointers bool indicating whether the read/write pointers
40 * should be reset or not.
41 */
Devin Moore9a27da52020-07-06 14:01:21 -070042 MessageQueueBase(const Descriptor& Desc, bool resetPointers = true);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080043
Devin Moore9a27da52020-07-06 14:01:21 -070044 ~MessageQueueBase();
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080045
46 /**
47 * This constructor uses Ashmem shared memory to create an FMQ
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080048 * that can contain a maximum of 'numElementsInQueue' elements of type T.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080049 *
50 * @param numElementsInQueue Capacity of the MessageQueue in terms of T.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -080051 * @param configureEventFlagWord Boolean that specifies if memory should
52 * also be allocated and mapped for an EventFlag word.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080053 */
Devin Moore9a27da52020-07-06 14:01:21 -070054
55 MessageQueueBase(size_t numElementsInQueue, bool configureEventFlagWord = false);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080056
57 /**
58 * @return Number of items of type T that can be written into the FMQ
59 * without a read.
60 */
61 size_t availableToWrite() const;
62
63 /**
64 * @return Number of items of type T that are waiting to be read from the
65 * FMQ.
66 */
67 size_t availableToRead() const;
68
69 /**
70 * Returns the size of type T in bytes.
71 *
72 * @param Size of T.
73 */
74 size_t getQuantumSize() const;
75
76 /**
77 * Returns the size of the FMQ in terms of the size of type T.
78 *
79 * @return Number of items of type T that will fit in the FMQ.
80 */
81 size_t getQuantumCount() const;
82
83 /**
84 * @return Whether the FMQ is configured correctly.
85 */
86 bool isValid() const;
87
88 /**
89 * Non-blocking write to FMQ.
90 *
91 * @param data Pointer to the object of type T to be written into the FMQ.
92 *
93 * @return Whether the write was successful.
94 */
95 bool write(const T* data);
96
97 /**
98 * Non-blocking read from FMQ.
99 *
100 * @param data Pointer to the memory where the object read from the FMQ is
101 * copied to.
102 *
103 * @return Whether the read was successful.
104 */
105 bool read(T* data);
106
107 /**
108 * Write some data into the FMQ without blocking.
109 *
110 * @param data Pointer to the array of items of type T.
111 * @param count Number of items in array.
112 *
113 * @return Whether the write was successful.
114 */
115 bool write(const T* data, size_t count);
116
117 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800118 * Perform a blocking write of 'count' items into the FMQ using EventFlags.
119 * Does not support partial writes.
120 *
121 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
122 * associated with the FMQ and it is used in that case.
123 *
124 * The application code must ensure that 'evFlag' used by the
125 * reader(s)/writer is based upon the same EventFlag word.
126 *
127 * The method will return false without blocking if any of the following
128 * conditions are true:
129 * - If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700130 * - If the 'readNotification' bit mask is zero.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800131 * - If 'count' is greater than the FMQ size.
132 *
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700133 * If the there is insufficient space available to write into it, the
134 * EventFlag bit mask 'readNotification' is is waited upon.
135 *
136 * This method should only be used with a MessageQueue of the flavor
Devin Moore133cb5e2020-07-07 16:31:22 -0700137 * 'kSynchronizedReadWrite'.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800138 *
139 * Upon a successful write, wake is called on 'writeNotification' (if
140 * non-zero).
141 *
142 * @param data Pointer to the array of items of type T.
143 * @param count Number of items in array.
144 * @param readNotification The EventFlag bit mask to wait on if there is not
145 * enough space in FMQ to write 'count' items.
146 * @param writeNotification The EventFlag bit mask to call wake on
147 * a successful write. No wake is called if 'writeNotification' is zero.
148 * @param timeOutNanos Number of nanoseconds after which the blocking
149 * write attempt is aborted.
150 * @param evFlag The EventFlag object to be used for blocking. If nullptr,
151 * it is checked whether the FMQ owns an EventFlag object and that is used
152 * for blocking instead.
153 *
154 * @return Whether the write was successful.
155 */
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800156 bool writeBlocking(const T* data, size_t count, uint32_t readNotification,
157 uint32_t writeNotification, int64_t timeOutNanos = 0,
158 android::hardware::EventFlag* evFlag = nullptr);
159
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800160 bool writeBlocking(const T* data, size_t count, int64_t timeOutNanos = 0);
161
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800162 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800163 * Read some data from the FMQ without blocking.
164 *
165 * @param data Pointer to the array to which read data is to be written.
166 * @param count Number of items to be read.
167 *
168 * @return Whether the read was successful.
169 */
170 bool read(T* data, size_t count);
171
172 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800173 * Perform a blocking read operation of 'count' items from the FMQ. Does not
174 * perform a partial read.
175 *
176 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
177 * associated with the FMQ and it is used in that case.
178 *
179 * The application code must ensure that 'evFlag' used by the
180 * reader(s)/writer is based upon the same EventFlag word.
181 *
182 * The method will return false without blocking if any of the following
183 * conditions are true:
184 * -If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
185 * -If the 'writeNotification' bit mask is zero.
186 * -If 'count' is greater than the FMQ size.
187 *
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700188 * This method should only be used with a MessageQueue of the flavor
Devin Moore133cb5e2020-07-07 16:31:22 -0700189 * 'kSynchronizedReadWrite'.
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700190
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800191 * If FMQ does not contain 'count' items, the eventFlag bit mask
192 * 'writeNotification' is waited upon. Upon a successful read from the FMQ,
193 * wake is called on 'readNotification' (if non-zero).
194 *
195 * @param data Pointer to the array to which read data is to be written.
196 * @param count Number of items to be read.
197 * @param readNotification The EventFlag bit mask to call wake on after
198 * a successful read. No wake is called if 'readNotification' is zero.
199 * @param writeNotification The EventFlag bit mask to call a wait on
200 * if there is insufficient data in the FMQ to be read.
201 * @param timeOutNanos Number of nanoseconds after which the blocking
202 * read attempt is aborted.
203 * @param evFlag The EventFlag object to be used for blocking.
204 *
205 * @return Whether the read was successful.
206 */
Devin Moore77d279e2020-07-07 10:38:52 -0700207 bool readBlocking(T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
208 int64_t timeOutNanos = 0, android::hardware::EventFlag* evFlag = nullptr);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800209
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800210 bool readBlocking(T* data, size_t count, int64_t timeOutNanos = 0);
211
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800212 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800213 * Get a pointer to the MQDescriptor object that describes this FMQ.
214 *
215 * @return Pointer to the MQDescriptor associated with the FMQ.
216 */
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800217 const Descriptor* getDesc() const { return mDesc.get(); }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800218
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800219 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800220 * Get a pointer to the EventFlag word if there is one associated with this FMQ.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800221 *
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800222 * @return Pointer to an EventFlag word, will return nullptr if not
223 * configured. This method does not transfer ownership. The EventFlag
224 * word will be unmapped by the MessageQueue destructor.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800225 */
226 std::atomic<uint32_t>* getEventFlagWord() const { return mEvFlagWord; }
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800227
228 /**
229 * Describes a memory region in the FMQ.
230 */
231 struct MemRegion {
232 MemRegion() : MemRegion(nullptr, 0) {}
233
234 MemRegion(T* base, size_t size) : address(base), length(size) {}
235
Devin Moore77d279e2020-07-07 10:38:52 -0700236 MemRegion& operator=(const MemRegion& other) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800237 address = other.address;
238 length = other.length;
239 return *this;
240 }
241
242 /**
243 * Gets a pointer to the base address of the MemRegion.
244 */
245 inline T* getAddress() const { return address; }
246
247 /**
248 * Gets the length of the MemRegion. This would equal to the number
249 * of items of type T that can be read from/written into the MemRegion.
250 */
251 inline size_t getLength() const { return length; }
252
253 /**
254 * Gets the length of the MemRegion in bytes.
255 */
256 inline size_t getLengthInBytes() const { return length * sizeof(T); }
257
Devin Moore77d279e2020-07-07 10:38:52 -0700258 private:
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800259 /* Base address */
260 T* address;
261
262 /*
263 * Number of items of type T that can be written to/read from the base
264 * address.
265 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800266 size_t length;
267 };
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800268
269 /**
270 * Describes the memory regions to be used for a read or write.
271 * The struct contains two MemRegion objects since the FMQ is a ring
272 * buffer and a read or write operation can wrap around. A single message
273 * of type T will never be broken between the two MemRegions.
274 */
275 struct MemTransaction {
276 MemTransaction() : MemTransaction(MemRegion(), MemRegion()) {}
277
Devin Moore77d279e2020-07-07 10:38:52 -0700278 MemTransaction(const MemRegion& regionFirst, const MemRegion& regionSecond)
279 : first(regionFirst), second(regionSecond) {}
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800280
Devin Moore77d279e2020-07-07 10:38:52 -0700281 MemTransaction& operator=(const MemTransaction& other) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800282 first = other.first;
283 second = other.second;
284 return *this;
285 }
286
287 /**
288 * Helper method to calculate the address for a particular index for
289 * the MemTransaction object.
290 *
291 * @param idx Index of the slot to be read/written. If the
292 * MemTransaction object is representing the memory region to read/write
293 * N items of type T, the valid range of idx is between 0 and N-1.
294 *
295 * @return Pointer to the slot idx. Will be nullptr for an invalid idx.
296 */
297 T* getSlot(size_t idx);
298
299 /**
300 * Helper method to write 'nMessages' items of type T into the memory
301 * regions described by the object starting from 'startIdx'. This method
302 * uses memcpy() and is not to meant to be used for a zero copy operation.
303 * Partial writes are not supported.
304 *
305 * @param data Pointer to the source buffer.
306 * @param nMessages Number of items of type T.
307 * @param startIdx The slot number to begin the write from. If the
308 * MemTransaction object is representing the memory region to read/write
309 * N items of type T, the valid range of startIdx is between 0 and N-1;
310 *
311 * @return Whether the write operation of size 'nMessages' succeeded.
312 */
313 bool copyTo(const T* data, size_t startIdx, size_t nMessages = 1);
314
315 /*
316 * Helper method to read 'nMessages' items of type T from the memory
317 * regions described by the object starting from 'startIdx'. This method uses
318 * memcpy() and is not meant to be used for a zero copy operation. Partial reads
319 * are not supported.
320 *
321 * @param data Pointer to the destination buffer.
322 * @param nMessages Number of items of type T.
323 * @param startIdx The slot number to begin the read from. If the
324 * MemTransaction object is representing the memory region to read/write
325 * N items of type T, the valid range of startIdx is between 0 and N-1.
326 *
327 * @return Whether the read operation of size 'nMessages' succeeded.
328 */
329 bool copyFrom(T* data, size_t startIdx, size_t nMessages = 1);
330
331 /**
332 * Returns a const reference to the first MemRegion in the
333 * MemTransaction object.
334 */
335 inline const MemRegion& getFirstRegion() const { return first; }
336
337 /**
338 * Returns a const reference to the second MemRegion in the
339 * MemTransaction object.
340 */
341 inline const MemRegion& getSecondRegion() const { return second; }
342
Devin Moore77d279e2020-07-07 10:38:52 -0700343 private:
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800344 /*
345 * Given a start index and the number of messages to be
346 * read/written, this helper method calculates the
347 * number of messages that should should be written to both the first
348 * and second MemRegions and the base addresses to be used for
349 * the read/write operation.
350 *
351 * Returns false if the 'startIdx' and 'nMessages' is
352 * invalid for the MemTransaction object.
353 */
Devin Moore77d279e2020-07-07 10:38:52 -0700354 bool inline getMemRegionInfo(size_t idx, size_t nMessages, size_t& firstCount,
355 size_t& secondCount, T** firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800356 T** secondBaseAddress);
357 MemRegion first;
358 MemRegion second;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800359 };
360
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800361 /**
362 * Get a MemTransaction object to write 'nMessages' items of type T.
363 * Once the write is performed using the information from MemTransaction,
364 * the write operation is to be committed using a call to commitWrite().
365 *
366 * @param nMessages Number of messages of type T.
367 * @param Pointer to MemTransaction struct that describes memory to write 'nMessages'
368 * items of type T. If a write of size 'nMessages' is not possible, the base
369 * addresses in the MemTransaction object would be set to nullptr.
370 *
371 * @return Whether it is possible to write 'nMessages' items of type T
372 * into the FMQ.
373 */
374 bool beginWrite(size_t nMessages, MemTransaction* memTx) const;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800375
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800376 /**
377 * Commit a write of size 'nMessages'. To be only used after a call to beginWrite().
378 *
379 * @param nMessages number of messages of type T to be written.
380 *
381 * @return Whether the write operation of size 'nMessages' succeeded.
382 */
383 bool commitWrite(size_t nMessages);
384
385 /**
386 * Get a MemTransaction object to read 'nMessages' items of type T.
387 * Once the read is performed using the information from MemTransaction,
388 * the read operation is to be committed using a call to commitRead().
389 *
390 * @param nMessages Number of messages of type T.
391 * @param pointer to MemTransaction struct that describes memory to read 'nMessages'
392 * items of type T. If a read of size 'nMessages' is not possible, the base
393 * pointers in the MemTransaction object returned will be set to nullptr.
394 *
395 * @return bool Whether it is possible to read 'nMessages' items of type T
396 * from the FMQ.
397 */
398 bool beginRead(size_t nMessages, MemTransaction* memTx) const;
399
400 /**
401 * Commit a read of size 'nMessages'. To be only used after a call to beginRead().
402 * For the unsynchronized flavor of FMQ, this method will return a failure
403 * if a write overflow happened after beginRead() was invoked.
404 *
405 * @param nMessages number of messages of type T to be read.
406 *
407 * @return bool Whether the read operation of size 'nMessages' succeeded.
408 */
409 bool commitRead(size_t nMessages);
410
Devin Moore77d279e2020-07-07 10:38:52 -0700411 private:
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800412 size_t availableToWriteBytes() const;
413 size_t availableToReadBytes() const;
414
Devin Moore9a27da52020-07-06 14:01:21 -0700415 MessageQueueBase(const MessageQueueBase& other) = delete;
416 MessageQueueBase& operator=(const MessageQueueBase& other) = delete;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800417
418 void* mapGrantorDescr(uint32_t grantorIdx);
419 void unmapGrantorDescr(void* address, uint32_t grantorIdx);
420 void initMemory(bool resetPointers);
421
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800422 enum DefaultEventNotification : uint32_t {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800423 /*
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700424 * These are only used internally by the readBlocking()/writeBlocking()
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800425 * methods and hence once other bit combinations are not required.
426 */
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700427 FMQ_NOT_FULL = 0x01,
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800428 FMQ_NOT_EMPTY = 0x02
429 };
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800430 std::unique_ptr<Descriptor> mDesc;
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800431 uint8_t* mRing = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800432 /*
433 * TODO(b/31550092): Change to 32 bit read and write pointer counters.
434 */
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800435 std::atomic<uint64_t>* mReadPtr = nullptr;
436 std::atomic<uint64_t>* mWritePtr = nullptr;
437
438 std::atomic<uint32_t>* mEvFlagWord = nullptr;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800439
440 /*
441 * This EventFlag object will be owned by the FMQ and will have the same
442 * lifetime.
443 */
444 android::hardware::EventFlag* mEventFlag = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800445};
446
Devin Moore133cb5e2020-07-07 16:31:22 -0700447template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700448T* MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getSlot(size_t idx) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800449 size_t firstRegionLength = first.getLength();
450 size_t secondRegionLength = second.getLength();
451
452 if (idx > firstRegionLength + secondRegionLength) {
453 return nullptr;
454 }
455
456 if (idx < firstRegionLength) {
457 return first.getAddress() + idx;
458 }
459
460 return second.getAddress() + idx - firstRegionLength;
461}
462
Devin Moore133cb5e2020-07-07 16:31:22 -0700463template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700464bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getMemRegionInfo(
465 size_t startIdx, size_t nMessages, size_t& firstCount, size_t& secondCount,
466 T** firstBaseAddress, T** secondBaseAddress) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800467 size_t firstRegionLength = first.getLength();
468 size_t secondRegionLength = second.getLength();
469
470 if (startIdx + nMessages > firstRegionLength + secondRegionLength) {
471 /*
472 * Return false if 'nMessages' starting at 'startIdx' cannot be
473 * accomodated by the MemTransaction object.
474 */
475 return false;
476 }
477
478 /* Number of messages to be read/written to the first MemRegion. */
Devin Moore77d279e2020-07-07 10:38:52 -0700479 firstCount =
480 startIdx < firstRegionLength ? std::min(nMessages, firstRegionLength - startIdx) : 0;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800481
482 /* Number of messages to be read/written to the second MemRegion. */
483 secondCount = nMessages - firstCount;
484
485 if (firstCount != 0) {
486 *firstBaseAddress = first.getAddress() + startIdx;
487 }
488
489 if (secondCount != 0) {
490 size_t secondStartIdx = startIdx > firstRegionLength ? startIdx - firstRegionLength : 0;
491 *secondBaseAddress = second.getAddress() + secondStartIdx;
492 }
493
494 return true;
495}
496
Devin Moore133cb5e2020-07-07 16:31:22 -0700497template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700498bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyFrom(T* data,
499 size_t startIdx,
500 size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800501 if (data == nullptr) {
502 return false;
503 }
504
505 size_t firstReadCount = 0, secondReadCount = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700506 T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800507
Devin Moore77d279e2020-07-07 10:38:52 -0700508 if (getMemRegionInfo(startIdx, nMessages, firstReadCount, secondReadCount, &firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800509 &secondBaseAddress) == false) {
510 /*
511 * Returns false if 'startIdx' and 'nMessages' are invalid for this
512 * MemTransaction object.
513 */
514 return false;
515 }
516
517 if (firstReadCount != 0) {
518 memcpy(data, firstBaseAddress, firstReadCount * sizeof(T));
519 }
520
521 if (secondReadCount != 0) {
Devin Moore77d279e2020-07-07 10:38:52 -0700522 memcpy(data + firstReadCount, secondBaseAddress, secondReadCount * sizeof(T));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800523 }
524
525 return true;
526}
527
Devin Moore133cb5e2020-07-07 16:31:22 -0700528template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700529bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyTo(const T* data,
530 size_t startIdx,
531 size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800532 if (data == nullptr) {
533 return false;
534 }
535
536 size_t firstWriteCount = 0, secondWriteCount = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700537 T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800538
Devin Moore77d279e2020-07-07 10:38:52 -0700539 if (getMemRegionInfo(startIdx, nMessages, firstWriteCount, secondWriteCount, &firstBaseAddress,
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800540 &secondBaseAddress) == false) {
541 /*
542 * Returns false if 'startIdx' and 'nMessages' are invalid for this
543 * MemTransaction object.
544 */
545 return false;
546 }
547
548 if (firstWriteCount != 0) {
549 memcpy(firstBaseAddress, data, firstWriteCount * sizeof(T));
550 }
551
552 if (secondWriteCount != 0) {
Devin Moore77d279e2020-07-07 10:38:52 -0700553 memcpy(secondBaseAddress, data + firstWriteCount, secondWriteCount * sizeof(T));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800554 }
555
556 return true;
557}
558
Devin Moore133cb5e2020-07-07 16:31:22 -0700559template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700560void MessageQueueBase<MQDescriptorType, T, flavor>::initMemory(bool resetPointers) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800561 /*
Devin Moore9a27da52020-07-06 14:01:21 -0700562 * Verify that the Descriptor contains the minimum number of grantors
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800563 * the native_handle is valid and T matches quantum size.
564 */
565 if ((mDesc == nullptr) || !mDesc->isHandleValid() ||
Devin Moore133cb5e2020-07-07 16:31:22 -0700566 (mDesc->countGrantors() < hardware::details::kMinGrantorCount) ||
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800567 (mDesc->getQuantum() != sizeof(T))) {
568 return;
569 }
Devin Moore133cb5e2020-07-07 16:31:22 -0700570 const auto& grantors = mDesc->grantors();
571 for (const auto& grantor : grantors) {
572 if (hardware::details::isAlignedToWordBoundary(grantor.offset) == false) {
573 __assert(__FILE__, __LINE__, "Grantor offsets need to be aligned");
574 }
575 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800576
Devin Moore133cb5e2020-07-07 16:31:22 -0700577 if (flavor == kSynchronizedReadWrite) {
578 mReadPtr = reinterpret_cast<std::atomic<uint64_t>*>(
579 mapGrantorDescr(hardware::details::READPTRPOS));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800580 } else {
581 /*
582 * The unsynchronized write flavor of the FMQ may have multiple readers
583 * and each reader would have their own read pointer counter.
584 */
585 mReadPtr = new (std::nothrow) std::atomic<uint64_t>;
586 }
587
Devin Moore9a27da52020-07-06 14:01:21 -0700588 hardware::details::check(mReadPtr != nullptr);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800589
Devin Moore133cb5e2020-07-07 16:31:22 -0700590 mWritePtr = reinterpret_cast<std::atomic<uint64_t>*>(
591 mapGrantorDescr(hardware::details::WRITEPTRPOS));
Devin Moore9a27da52020-07-06 14:01:21 -0700592 hardware::details::check(mWritePtr != nullptr);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800593
594 if (resetPointers) {
595 mReadPtr->store(0, std::memory_order_release);
596 mWritePtr->store(0, std::memory_order_release);
Devin Moore133cb5e2020-07-07 16:31:22 -0700597 } else if (flavor != kSynchronizedReadWrite) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800598 // Always reset the read pointer.
599 mReadPtr->store(0, std::memory_order_release);
600 }
601
Devin Moore133cb5e2020-07-07 16:31:22 -0700602 mRing = reinterpret_cast<uint8_t*>(mapGrantorDescr(hardware::details::DATAPTRPOS));
Devin Moore9a27da52020-07-06 14:01:21 -0700603 hardware::details::check(mRing != nullptr);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800604
Devin Moore133cb5e2020-07-07 16:31:22 -0700605 mEvFlagWord =
606 static_cast<std::atomic<uint32_t>*>(mapGrantorDescr(hardware::details::EVFLAGWORDPOS));
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800607 if (mEvFlagWord != nullptr) {
608 android::hardware::EventFlag::createEventFlag(mEvFlagWord, &mEventFlag);
609 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800610}
611
Devin Moore133cb5e2020-07-07 16:31:22 -0700612template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700613MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(const Descriptor& Desc,
614 bool resetPointers) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800615 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(Desc));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800616 if (mDesc == nullptr) {
617 return;
618 }
619
620 initMemory(resetPointers);
621}
622
Devin Moore133cb5e2020-07-07 16:31:22 -0700623template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700624MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(size_t numElementsInQueue,
625 bool configureEventFlagWord) {
Kevin Rocard1d6e40f2017-04-03 11:51:13 -0700626 // Check if the buffer size would not overflow size_t
627 if (numElementsInQueue > SIZE_MAX / sizeof(T)) {
628 return;
629 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800630 /*
631 * The FMQ needs to allocate memory for the ringbuffer as well as for the
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800632 * read and write pointer counters. If an EventFlag word is to be configured,
633 * we also need to allocate memory for the same/
634 */
635 size_t kQueueSizeBytes = numElementsInQueue * sizeof(T);
Devin Moore133cb5e2020-07-07 16:31:22 -0700636 size_t kMetaDataSize = 2 * sizeof(android::hardware::details::RingBufferPosition);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800637
638 if (configureEventFlagWord) {
Devin Moore77d279e2020-07-07 10:38:52 -0700639 kMetaDataSize += sizeof(std::atomic<uint32_t>);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800640 }
641
642 /*
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800643 * Ashmem memory region size needs to be specified in page-aligned bytes.
644 * kQueueSizeBytes needs to be aligned to word boundary so that all offsets
645 * in the grantorDescriptor will be word aligned.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800646 */
Devin Moore133cb5e2020-07-07 16:31:22 -0700647 size_t kAshmemSizePageAligned = (hardware::details::alignToWordBoundary(kQueueSizeBytes) +
648 kMetaDataSize + PAGE_SIZE - 1) &
649 ~(PAGE_SIZE - 1);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800650
651 /*
652 * Create an ashmem region to map the memory for the ringbuffer,
653 * read counter and write counter.
654 */
655 int ashmemFd = ashmem_create_region("MessageQueue", kAshmemSizePageAligned);
656 ashmem_set_prot_region(ashmemFd, PROT_READ | PROT_WRITE);
657
658 /*
659 * The native handle will contain the fds to be mapped.
660 */
Devin Moore77d279e2020-07-07 10:38:52 -0700661 native_handle_t* mqHandle = native_handle_create(1 /* numFds */, 0 /* numInts */);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800662 if (mqHandle == nullptr) {
663 return;
664 }
665
666 mqHandle->data[0] = ashmemFd;
Devin Moore77d279e2020-07-07 10:38:52 -0700667 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(
668 kQueueSizeBytes, mqHandle, sizeof(T), configureEventFlagWord));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800669 if (mDesc == nullptr) {
670 return;
671 }
672 initMemory(true);
673}
674
Devin Moore133cb5e2020-07-07 16:31:22 -0700675template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700676MessageQueueBase<MQDescriptorType, T, flavor>::~MessageQueueBase() {
Devin Moore133cb5e2020-07-07 16:31:22 -0700677 if (flavor == kUnsynchronizedWrite) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800678 delete mReadPtr;
679 } else {
Devin Moore133cb5e2020-07-07 16:31:22 -0700680 unmapGrantorDescr(mReadPtr, hardware::details::READPTRPOS);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800681 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800682 if (mWritePtr != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700683 unmapGrantorDescr(mWritePtr, hardware::details::WRITEPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800684 }
685 if (mRing != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700686 unmapGrantorDescr(mRing, hardware::details::DATAPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800687 }
688 if (mEvFlagWord != nullptr) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700689 unmapGrantorDescr(mEvFlagWord, hardware::details::EVFLAGWORDPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800690 android::hardware::EventFlag::deleteEventFlag(&mEventFlag);
691 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800692}
693
Devin Moore133cb5e2020-07-07 16:31:22 -0700694template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700695bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800696 return write(data, 1);
697}
698
Devin Moore133cb5e2020-07-07 16:31:22 -0700699template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700700bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800701 return read(data, 1);
702}
703
Devin Moore133cb5e2020-07-07 16:31:22 -0700704template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700705bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data, size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800706 MemTransaction tx;
Devin Moore77d279e2020-07-07 10:38:52 -0700707 return beginWrite(nMessages, &tx) && tx.copyTo(data, 0 /* startIdx */, nMessages) &&
708 commitWrite(nMessages);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800709}
710
Devin Moore133cb5e2020-07-07 16:31:22 -0700711template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700712bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(
713 const T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
714 int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700715 static_assert(flavor == kSynchronizedReadWrite,
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700716 "writeBlocking can only be used with the "
Devin Moore133cb5e2020-07-07 16:31:22 -0700717 "kSynchronizedReadWrite flavor.");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800718 /*
719 * If evFlag is null and the FMQ does not have its own EventFlag object
720 * return false;
Devin Moore133cb5e2020-07-07 16:31:22 -0700721 * If the flavor is kSynchronizedReadWrite and the readNotification
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800722 * bit mask is zero return false;
723 * If the count is greater than queue size, return false
724 * to prevent blocking until timeOut.
725 */
726 if (evFlag == nullptr) {
727 evFlag = mEventFlag;
728 if (evFlag == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -0700729 hardware::details::logError(
Devin Moore77d279e2020-07-07 10:38:52 -0700730 "writeBlocking failed: called on MessageQueue with no Eventflag"
731 "configured or provided");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800732 return false;
733 }
734 }
735
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700736 if (readNotification == 0 || (count > getQuantumCount())) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800737 return false;
738 }
739
740 /*
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700741 * There is no need to wait for a readNotification if there is sufficient
742 * space to write is already present in the FMQ. The latter would be the case when
743 * read operations read more number of messages than write operations write.
744 * In other words, a single large read may clear the FMQ after multiple small
745 * writes. This would fail to clear a pending readNotification bit since
746 * EventFlag bits can only be cleared by a wait() call, however the bit would
747 * be correctly cleared by the next writeBlocking() call.
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800748 */
749
750 bool result = write(data, count);
751 if (result) {
752 if (writeNotification) {
753 evFlag->wake(writeNotification);
754 }
755 return result;
756 }
757
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800758 bool shouldTimeOut = timeOutNanos != 0;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700759 int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800760
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700761 while (true) {
762 /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800763 if (shouldTimeOut) {
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700764 /*
765 * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
766 * to Nanoseconds)
767 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800768 int64_t currentTimeNs = android::elapsedRealtimeNano();
769 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700770 * Decrement 'timeOutNanos' to account for the time taken to complete the last
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800771 * iteration of the while loop.
772 */
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700773 timeOutNanos -= currentTimeNs - prevTimeNanos;
774 prevTimeNanos = currentTimeNs;
775
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800776 if (timeOutNanos <= 0) {
777 /*
778 * Attempt write in case a context switch happened outside of
779 * evFlag->wait().
780 */
781 result = write(data, count);
782 break;
783 }
784 }
785
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800786 /*
787 * wait() will return immediately if there was a pending read
788 * notification.
789 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800790 uint32_t efState = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700791 status_t status = evFlag->wait(readNotification, &efState, timeOutNanos,
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700792 true /* retry on spurious wake */);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800793
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700794 if (status != android::TIMED_OUT && status != android::NO_ERROR) {
Devin Moore9a27da52020-07-06 14:01:21 -0700795 hardware::details::logError("Unexpected error code from EventFlag Wait status " +
796 std::to_string(status));
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700797 break;
798 }
799
800 if (status == android::TIMED_OUT) {
801 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800802 }
803
804 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700805 * If there is still insufficient space to write to the FMQ,
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800806 * keep waiting for another readNotification.
807 */
808 if ((efState & readNotification) && write(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800809 result = true;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700810 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800811 }
812 }
813
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800814 if (result && writeNotification != 0) {
815 evFlag->wake(writeNotification);
816 }
817
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800818 return result;
819}
820
Devin Moore133cb5e2020-07-07 16:31:22 -0700821template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700822bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(const T* data, size_t count,
823 int64_t timeOutNanos) {
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800824 return writeBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
825}
826
Devin Moore133cb5e2020-07-07 16:31:22 -0700827template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700828bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(
829 T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
830 int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
Devin Moore133cb5e2020-07-07 16:31:22 -0700831 static_assert(flavor == kSynchronizedReadWrite,
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700832 "readBlocking can only be used with the "
Devin Moore133cb5e2020-07-07 16:31:22 -0700833 "kSynchronizedReadWrite flavor.");
Jayant Chowdhary8819e812017-08-28 15:01:42 -0700834
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800835 /*
836 * If evFlag is null and the FMQ does not own its own EventFlag object
837 * return false;
838 * If the writeNotification bit mask is zero return false;
839 * If the count is greater than queue size, return false to prevent
840 * blocking until timeOut.
841 */
842 if (evFlag == nullptr) {
843 evFlag = mEventFlag;
844 if (evFlag == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -0700845 hardware::details::logError(
Devin Moore77d279e2020-07-07 10:38:52 -0700846 "readBlocking failed: called on MessageQueue with no Eventflag"
847 "configured or provided");
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800848 return false;
849 }
850 }
851
852 if (writeNotification == 0 || count > getQuantumCount()) {
853 return false;
854 }
855
856 /*
857 * There is no need to wait for a write notification if sufficient
858 * data to read is already present in the FMQ. This would be the
859 * case when read operations read lesser number of messages than
860 * a write operation and multiple reads would be required to clear the queue
861 * after a single write operation. This check would fail to clear a pending
862 * writeNotification bit since EventFlag bits can only be cleared
863 * by a wait() call, however the bit would be correctly cleared by the next
864 * readBlocking() call.
865 */
866
867 bool result = read(data, count);
868 if (result) {
869 if (readNotification) {
870 evFlag->wake(readNotification);
871 }
872 return result;
873 }
874
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800875 bool shouldTimeOut = timeOutNanos != 0;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700876 int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800877
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700878 while (true) {
879 /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800880 if (shouldTimeOut) {
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700881 /*
882 * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
883 * to Nanoseconds)
884 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800885 int64_t currentTimeNs = android::elapsedRealtimeNano();
886 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700887 * Decrement 'timeOutNanos' to account for the time taken to complete the last
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800888 * iteration of the while loop.
889 */
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700890 timeOutNanos -= currentTimeNs - prevTimeNanos;
891 prevTimeNanos = currentTimeNs;
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800892
893 if (timeOutNanos <= 0) {
894 /*
895 * Attempt read in case a context switch happened outside of
896 * evFlag->wait().
897 */
898 result = read(data, count);
899 break;
900 }
901 }
902
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800903 /*
904 * wait() will return immediately if there was a pending write
905 * notification.
906 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800907 uint32_t efState = 0;
Devin Moore77d279e2020-07-07 10:38:52 -0700908 status_t status = evFlag->wait(writeNotification, &efState, timeOutNanos,
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700909 true /* retry on spurious wake */);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800910
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700911 if (status != android::TIMED_OUT && status != android::NO_ERROR) {
Devin Moore9a27da52020-07-06 14:01:21 -0700912 hardware::details::logError("Unexpected error code from EventFlag Wait status " +
913 std::to_string(status));
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700914 break;
915 }
916
917 if (status == android::TIMED_OUT) {
918 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800919 }
920
921 /*
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700922 * If the data in FMQ is still insufficient, go back to waiting
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800923 * for another write notification.
924 */
925 if ((efState & writeNotification) && read(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800926 result = true;
Hridya Valsarajuf542b5a2017-03-21 11:33:33 -0700927 break;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800928 }
929 }
930
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800931 if (result && readNotification != 0) {
932 evFlag->wake(readNotification);
933 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800934 return result;
935}
936
Devin Moore133cb5e2020-07-07 16:31:22 -0700937template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700938bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(T* data, size_t count,
939 int64_t timeOutNanos) {
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800940 return readBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
941}
942
Devin Moore133cb5e2020-07-07 16:31:22 -0700943template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700944size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWriteBytes() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800945 return mDesc->getSize() - availableToReadBytes();
946}
947
Devin Moore133cb5e2020-07-07 16:31:22 -0700948template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700949size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWrite() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800950 return availableToWriteBytes() / sizeof(T);
951}
952
Devin Moore133cb5e2020-07-07 16:31:22 -0700953template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700954size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToRead() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800955 return availableToReadBytes() / sizeof(T);
956}
957
Devin Moore133cb5e2020-07-07 16:31:22 -0700958template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -0700959bool MessageQueueBase<MQDescriptorType, T, flavor>::beginWrite(size_t nMessages,
960 MemTransaction* result) const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800961 /*
962 * If nMessages is greater than size of FMQ or in case of the synchronized
963 * FMQ flavor, if there is not enough space to write nMessages, then return
964 * result with null addresses.
965 */
Devin Moore133cb5e2020-07-07 16:31:22 -0700966 if ((flavor == kSynchronizedReadWrite && (availableToWrite() < nMessages)) ||
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800967 nMessages > getQuantumCount()) {
968 *result = MemTransaction();
969 return false;
970 }
971
972 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
973 size_t writeOffset = writePtr % mDesc->getSize();
974
975 /*
976 * From writeOffset, the number of messages that can be written
977 * contiguously without wrapping around the ring buffer are calculated.
978 */
979 size_t contiguousMessages = (mDesc->getSize() - writeOffset) / sizeof(T);
980
981 if (contiguousMessages < nMessages) {
982 /*
983 * Wrap around is required. Both result.first and result.second are
984 * populated.
985 */
Devin Moore77d279e2020-07-07 10:38:52 -0700986 *result = MemTransaction(
987 MemRegion(reinterpret_cast<T*>(mRing + writeOffset), contiguousMessages),
988 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800989 } else {
990 /*
991 * A wrap around is not required to write nMessages. Only result.first
992 * is populated.
993 */
994 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + writeOffset), nMessages),
995 MemRegion());
996 }
997
998 return true;
999}
1000
Devin Moore133cb5e2020-07-07 16:31:22 -07001001template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001002/*
1003 * Disable integer sanitization since integer overflow here is allowed
1004 * and legal.
1005 */
Devin Moore9a27da52020-07-06 14:01:21 -07001006__attribute__((no_sanitize("integer"))) bool
1007MessageQueueBase<MQDescriptorType, T, flavor>::commitWrite(size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001008 size_t nBytesWritten = nMessages * sizeof(T);
1009 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1010 writePtr += nBytesWritten;
1011 mWritePtr->store(writePtr, std::memory_order_release);
1012 /*
1013 * This method cannot fail now since we are only incrementing the writePtr
1014 * counter.
1015 */
1016 return true;
1017}
1018
Devin Moore133cb5e2020-07-07 16:31:22 -07001019template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001020size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToReadBytes() const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001021 /*
1022 * This method is invoked by implementations of both read() and write() and
Devin Moore9a27da52020-07-06 14:01:21 -07001023 * hence requires a memory_order_acquired load for both mReadPtr and
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001024 * mWritePtr.
1025 */
Devin Moore77d279e2020-07-07 10:38:52 -07001026 return mWritePtr->load(std::memory_order_acquire) - mReadPtr->load(std::memory_order_acquire);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001027}
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 -07001030bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data, size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001031 MemTransaction tx;
Devin Moore77d279e2020-07-07 10:38:52 -07001032 return beginRead(nMessages, &tx) && tx.copyFrom(data, 0 /* startIdx */, nMessages) &&
1033 commitRead(nMessages);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001034}
1035
Devin Moore133cb5e2020-07-07 16:31:22 -07001036template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001037/*
1038 * Disable integer sanitization since integer overflow here is allowed
1039 * and legal.
1040 */
Devin Moore9a27da52020-07-06 14:01:21 -07001041__attribute__((no_sanitize("integer"))) bool
1042MessageQueueBase<MQDescriptorType, T, flavor>::beginRead(size_t nMessages,
1043 MemTransaction* result) const {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001044 *result = MemTransaction();
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001045 /*
1046 * If it is detected that the data in the queue was overwritten
1047 * due to the reader process being too slow, the read pointer counter
1048 * is set to the same as the write pointer counter to indicate error
1049 * and the read returns false;
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001050 * Need acquire/release memory ordering for mWritePtr.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001051 */
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001052 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1053 /*
1054 * A relaxed load is sufficient for mReadPtr since there will be no
1055 * stores to mReadPtr from a different thread.
1056 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001057 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
1058
1059 if (writePtr - readPtr > mDesc->getSize()) {
1060 mReadPtr->store(writePtr, std::memory_order_release);
1061 return false;
1062 }
1063
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001064 size_t nBytesDesired = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001065 /*
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001066 * Return if insufficient data to read in FMQ.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001067 */
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001068 if (writePtr - readPtr < nBytesDesired) {
1069 return false;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001070 }
1071
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001072 size_t readOffset = readPtr % mDesc->getSize();
1073 /*
1074 * From readOffset, the number of messages that can be read contiguously
1075 * without wrapping around the ring buffer are calculated.
1076 */
1077 size_t contiguousMessages = (mDesc->getSize() - readOffset) / sizeof(T);
1078
1079 if (contiguousMessages < nMessages) {
1080 /*
1081 * A wrap around is required. Both result.first and result.second
1082 * are populated.
1083 */
Devin Moore77d279e2020-07-07 10:38:52 -07001084 *result = MemTransaction(
1085 MemRegion(reinterpret_cast<T*>(mRing + readOffset), contiguousMessages),
1086 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001087 } else {
1088 /*
1089 * A wrap around is not required. Only result.first need to be
1090 * populated.
1091 */
1092 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + readOffset), nMessages),
1093 MemRegion());
1094 }
1095
1096 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001097}
1098
Devin Moore133cb5e2020-07-07 16:31:22 -07001099template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001100/*
1101 * Disable integer sanitization since integer overflow here is allowed
1102 * and legal.
1103 */
Devin Moore9a27da52020-07-06 14:01:21 -07001104__attribute__((no_sanitize("integer"))) bool
1105MessageQueueBase<MQDescriptorType, T, flavor>::commitRead(size_t nMessages) {
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001106 // TODO: Use a local copy of readPtr to avoid relazed mReadPtr loads.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001107 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001108 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1109 /*
1110 * If the flavor is unsynchronized, it is possible that a write overflow may
Devin Moore9a27da52020-07-06 14:01:21 -07001111 * have occurred between beginRead() and commitRead().
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001112 */
1113 if (writePtr - readPtr > mDesc->getSize()) {
1114 mReadPtr->store(writePtr, std::memory_order_release);
1115 return false;
1116 }
1117
1118 size_t nBytesRead = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001119 readPtr += nBytesRead;
1120 mReadPtr->store(readPtr, std::memory_order_release);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001121 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001122}
1123
Devin Moore133cb5e2020-07-07 16:31:22 -07001124template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001125size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumSize() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001126 return mDesc->getQuantum();
1127}
1128
Devin Moore133cb5e2020-07-07 16:31:22 -07001129template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001130size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumCount() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001131 return mDesc->getSize() / mDesc->getQuantum();
1132}
1133
Devin Moore133cb5e2020-07-07 16:31:22 -07001134template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001135bool MessageQueueBase<MQDescriptorType, T, flavor>::isValid() const {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001136 return mRing != nullptr && mReadPtr != nullptr && mWritePtr != nullptr;
1137}
1138
Devin Moore133cb5e2020-07-07 16:31:22 -07001139template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001140void* MessageQueueBase<MQDescriptorType, T, flavor>::mapGrantorDescr(uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001141 const native_handle_t* handle = mDesc->handle();
1142 auto grantors = mDesc->grantors();
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001143 if (handle == nullptr) {
Devin Moore9a27da52020-07-06 14:01:21 -07001144 hardware::details::logError("mDesc->handle is null");
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001145 return nullptr;
1146 }
1147
1148 if (grantorIdx >= grantors.size()) {
Devin Moore9a27da52020-07-06 14:01:21 -07001149 hardware::details::logError(std::string("grantorIdx must be less than ") +
1150 std::to_string(grantors.size()));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001151 return nullptr;
1152 }
1153
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001154 int fdIndex = grantors[grantorIdx].fdIndex;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001155 /*
1156 * Offset for mmap must be a multiple of PAGE_SIZE.
1157 */
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001158 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Devin Moore77d279e2020-07-07 10:38:52 -07001159 int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001160
Devin Moore77d279e2020-07-07 10:38:52 -07001161 void* address = mmap(0, mapLength, PROT_READ | PROT_WRITE, MAP_SHARED, handle->data[fdIndex],
1162 mapOffset);
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001163 if (address == MAP_FAILED) {
Devin Moore9a27da52020-07-06 14:01:21 -07001164 hardware::details::logError(std::string("mmap failed: ") + std::to_string(errno));
Hridya Valsarajudf73d422020-06-10 15:36:03 -07001165 return nullptr;
1166 }
1167 return reinterpret_cast<uint8_t*>(address) + (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001168}
1169
Devin Moore133cb5e2020-07-07 16:31:22 -07001170template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
Devin Moore9a27da52020-07-06 14:01:21 -07001171void MessageQueueBase<MQDescriptorType, T, flavor>::unmapGrantorDescr(void* address,
1172 uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001173 auto grantors = mDesc->grantors();
1174 if ((address == nullptr) || (grantorIdx >= grantors.size())) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001175 return;
1176 }
1177
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001178 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Devin Moore77d279e2020-07-07 10:38:52 -07001179 int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
1180 void* baseAddress =
1181 reinterpret_cast<uint8_t*>(address) - (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001182 if (baseAddress) munmap(baseAddress, mapLength);
1183}
1184
1185} // namespace hardware