blob: 50457877cd0e203c0f7c78cebf7d9c596f885862 [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
17#ifndef HIDL_MQ_H
18#define HIDL_MQ_H
19
20#include <android-base/logging.h>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080021#include <atomic>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080022#include <cutils/ashmem.h>
23#include <fmq/EventFlag.h>
24#include <hidl/MQDescriptor.h>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080025#include <new>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -080026#include <sys/mman.h>
27#include <utils/Log.h>
Hridya Valsaraju2abefb62017-01-19 13:06:58 -080028#include <utils/SystemClock.h>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080029
30namespace android {
31namespace hardware {
32
33template <typename T, MQFlavor flavor>
34struct MessageQueue {
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -080035 typedef MQDescriptor<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 */
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -080042 MessageQueue(const Descriptor& Desc, bool resetPointers = true);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080043
44 ~MessageQueue();
45
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 */
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -080054 MessageQueue(size_t numElementsInQueue, bool configureEventFlagWord = false);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -080055
56 /**
57 * @return Number of items of type T that can be written into the FMQ
58 * without a read.
59 */
60 size_t availableToWrite() const;
61
62 /**
63 * @return Number of items of type T that are waiting to be read from the
64 * FMQ.
65 */
66 size_t availableToRead() const;
67
68 /**
69 * Returns the size of type T in bytes.
70 *
71 * @param Size of T.
72 */
73 size_t getQuantumSize() const;
74
75 /**
76 * Returns the size of the FMQ in terms of the size of type T.
77 *
78 * @return Number of items of type T that will fit in the FMQ.
79 */
80 size_t getQuantumCount() const;
81
82 /**
83 * @return Whether the FMQ is configured correctly.
84 */
85 bool isValid() const;
86
87 /**
88 * Non-blocking write to FMQ.
89 *
90 * @param data Pointer to the object of type T to be written into the FMQ.
91 *
92 * @return Whether the write was successful.
93 */
94 bool write(const T* data);
95
96 /**
97 * Non-blocking read from FMQ.
98 *
99 * @param data Pointer to the memory where the object read from the FMQ is
100 * copied to.
101 *
102 * @return Whether the read was successful.
103 */
104 bool read(T* data);
105
106 /**
107 * Write some data into the FMQ without blocking.
108 *
109 * @param data Pointer to the array of items of type T.
110 * @param count Number of items in array.
111 *
112 * @return Whether the write was successful.
113 */
114 bool write(const T* data, size_t count);
115
116 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800117 * Perform a blocking write of 'count' items into the FMQ using EventFlags.
118 * Does not support partial writes.
119 *
120 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
121 * associated with the FMQ and it is used in that case.
122 *
123 * The application code must ensure that 'evFlag' used by the
124 * reader(s)/writer is based upon the same EventFlag word.
125 *
126 * The method will return false without blocking if any of the following
127 * conditions are true:
128 * - If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
129 * - If the flavor of the FMQ is synchronized and the 'readNotification' bit mask is zero.
130 * - If 'count' is greater than the FMQ size.
131 *
132 * If the flavor of the FMQ is synchronized and there is insufficient space
133 * available to write into it, the EventFlag bit mask 'readNotification' is
134 * is waited upon.
135 *
136 * Upon a successful write, wake is called on 'writeNotification' (if
137 * non-zero).
138 *
139 * @param data Pointer to the array of items of type T.
140 * @param count Number of items in array.
141 * @param readNotification The EventFlag bit mask to wait on if there is not
142 * enough space in FMQ to write 'count' items.
143 * @param writeNotification The EventFlag bit mask to call wake on
144 * a successful write. No wake is called if 'writeNotification' is zero.
145 * @param timeOutNanos Number of nanoseconds after which the blocking
146 * write attempt is aborted.
147 * @param evFlag The EventFlag object to be used for blocking. If nullptr,
148 * it is checked whether the FMQ owns an EventFlag object and that is used
149 * for blocking instead.
150 *
151 * @return Whether the write was successful.
152 */
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800153 bool writeBlocking(const T* data, size_t count, uint32_t readNotification,
154 uint32_t writeNotification, int64_t timeOutNanos = 0,
155 android::hardware::EventFlag* evFlag = nullptr);
156
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800157 bool writeBlocking(const T* data, size_t count, int64_t timeOutNanos = 0);
158
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800159 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800160 * Read some data from the FMQ without blocking.
161 *
162 * @param data Pointer to the array to which read data is to be written.
163 * @param count Number of items to be read.
164 *
165 * @return Whether the read was successful.
166 */
167 bool read(T* data, size_t count);
168
169 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800170 * Perform a blocking read operation of 'count' items from the FMQ. Does not
171 * perform a partial read.
172 *
173 * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
174 * associated with the FMQ and it is used in that case.
175 *
176 * The application code must ensure that 'evFlag' used by the
177 * reader(s)/writer is based upon the same EventFlag word.
178 *
179 * The method will return false without blocking if any of the following
180 * conditions are true:
181 * -If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
182 * -If the 'writeNotification' bit mask is zero.
183 * -If 'count' is greater than the FMQ size.
184 *
185 * If FMQ does not contain 'count' items, the eventFlag bit mask
186 * 'writeNotification' is waited upon. Upon a successful read from the FMQ,
187 * wake is called on 'readNotification' (if non-zero).
188 *
189 * @param data Pointer to the array to which read data is to be written.
190 * @param count Number of items to be read.
191 * @param readNotification The EventFlag bit mask to call wake on after
192 * a successful read. No wake is called if 'readNotification' is zero.
193 * @param writeNotification The EventFlag bit mask to call a wait on
194 * if there is insufficient data in the FMQ to be read.
195 * @param timeOutNanos Number of nanoseconds after which the blocking
196 * read attempt is aborted.
197 * @param evFlag The EventFlag object to be used for blocking.
198 *
199 * @return Whether the read was successful.
200 */
201 bool readBlocking(T* data, size_t count, uint32_t readNotification,
202 uint32_t writeNotification, int64_t timeOutNanos = 0,
203 android::hardware::EventFlag* evFlag = nullptr);
204
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800205 bool readBlocking(T* data, size_t count, int64_t timeOutNanos = 0);
206
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800207 /**
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800208 * Get a pointer to the MQDescriptor object that describes this FMQ.
209 *
210 * @return Pointer to the MQDescriptor associated with the FMQ.
211 */
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800212 const Descriptor* getDesc() const { return mDesc.get(); }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800213
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800214 /**
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800215 * Get a pointer to the EventFlag word if there is one associated with this FMQ.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800216 *
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800217 * @return Pointer to an EventFlag word, will return nullptr if not
218 * configured. This method does not transfer ownership. The EventFlag
219 * word will be unmapped by the MessageQueue destructor.
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800220 */
221 std::atomic<uint32_t>* getEventFlagWord() const { return mEvFlagWord; }
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800222
223 /**
224 * Describes a memory region in the FMQ.
225 */
226 struct MemRegion {
227 MemRegion() : MemRegion(nullptr, 0) {}
228
229 MemRegion(T* base, size_t size) : address(base), length(size) {}
230
231 MemRegion& operator=(const MemRegion &other) {
232 address = other.address;
233 length = other.length;
234 return *this;
235 }
236
237 /**
238 * Gets a pointer to the base address of the MemRegion.
239 */
240 inline T* getAddress() const { return address; }
241
242 /**
243 * Gets the length of the MemRegion. This would equal to the number
244 * of items of type T that can be read from/written into the MemRegion.
245 */
246 inline size_t getLength() const { return length; }
247
248 /**
249 * Gets the length of the MemRegion in bytes.
250 */
251 inline size_t getLengthInBytes() const { return length * sizeof(T); }
252
253 private:
254 /* Base address */
255 T* address;
256
257 /*
258 * Number of items of type T that can be written to/read from the base
259 * address.
260 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800261 size_t length;
262 };
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800263
264 /**
265 * Describes the memory regions to be used for a read or write.
266 * The struct contains two MemRegion objects since the FMQ is a ring
267 * buffer and a read or write operation can wrap around. A single message
268 * of type T will never be broken between the two MemRegions.
269 */
270 struct MemTransaction {
271 MemTransaction() : MemTransaction(MemRegion(), MemRegion()) {}
272
273 MemTransaction(const MemRegion& regionFirst, const MemRegion& regionSecond) :
274 first(regionFirst), second(regionSecond) {}
275
276 MemTransaction& operator=(const MemTransaction &other) {
277 first = other.first;
278 second = other.second;
279 return *this;
280 }
281
282 /**
283 * Helper method to calculate the address for a particular index for
284 * the MemTransaction object.
285 *
286 * @param idx Index of the slot to be read/written. If the
287 * MemTransaction object is representing the memory region to read/write
288 * N items of type T, the valid range of idx is between 0 and N-1.
289 *
290 * @return Pointer to the slot idx. Will be nullptr for an invalid idx.
291 */
292 T* getSlot(size_t idx);
293
294 /**
295 * Helper method to write 'nMessages' items of type T into the memory
296 * regions described by the object starting from 'startIdx'. This method
297 * uses memcpy() and is not to meant to be used for a zero copy operation.
298 * Partial writes are not supported.
299 *
300 * @param data Pointer to the source buffer.
301 * @param nMessages Number of items of type T.
302 * @param startIdx The slot number to begin the write from. If the
303 * MemTransaction object is representing the memory region to read/write
304 * N items of type T, the valid range of startIdx is between 0 and N-1;
305 *
306 * @return Whether the write operation of size 'nMessages' succeeded.
307 */
308 bool copyTo(const T* data, size_t startIdx, size_t nMessages = 1);
309
310 /*
311 * Helper method to read 'nMessages' items of type T from the memory
312 * regions described by the object starting from 'startIdx'. This method uses
313 * memcpy() and is not meant to be used for a zero copy operation. Partial reads
314 * are not supported.
315 *
316 * @param data Pointer to the destination buffer.
317 * @param nMessages Number of items of type T.
318 * @param startIdx The slot number to begin the read from. If the
319 * MemTransaction object is representing the memory region to read/write
320 * N items of type T, the valid range of startIdx is between 0 and N-1.
321 *
322 * @return Whether the read operation of size 'nMessages' succeeded.
323 */
324 bool copyFrom(T* data, size_t startIdx, size_t nMessages = 1);
325
326 /**
327 * Returns a const reference to the first MemRegion in the
328 * MemTransaction object.
329 */
330 inline const MemRegion& getFirstRegion() const { return first; }
331
332 /**
333 * Returns a const reference to the second MemRegion in the
334 * MemTransaction object.
335 */
336 inline const MemRegion& getSecondRegion() const { return second; }
337
338 private:
339 /*
340 * Given a start index and the number of messages to be
341 * read/written, this helper method calculates the
342 * number of messages that should should be written to both the first
343 * and second MemRegions and the base addresses to be used for
344 * the read/write operation.
345 *
346 * Returns false if the 'startIdx' and 'nMessages' is
347 * invalid for the MemTransaction object.
348 */
349 bool inline getMemRegionInfo(size_t idx,
350 size_t nMessages,
351 size_t& firstCount,
352 size_t& secondCount,
353 T** firstBaseAddress,
354 T** secondBaseAddress);
355 MemRegion first;
356 MemRegion second;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800357 };
358
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800359 /**
360 * Get a MemTransaction object to write 'nMessages' items of type T.
361 * Once the write is performed using the information from MemTransaction,
362 * the write operation is to be committed using a call to commitWrite().
363 *
364 * @param nMessages Number of messages of type T.
365 * @param Pointer to MemTransaction struct that describes memory to write 'nMessages'
366 * items of type T. If a write of size 'nMessages' is not possible, the base
367 * addresses in the MemTransaction object would be set to nullptr.
368 *
369 * @return Whether it is possible to write 'nMessages' items of type T
370 * into the FMQ.
371 */
372 bool beginWrite(size_t nMessages, MemTransaction* memTx) const;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800373
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800374 /**
375 * Commit a write of size 'nMessages'. To be only used after a call to beginWrite().
376 *
377 * @param nMessages number of messages of type T to be written.
378 *
379 * @return Whether the write operation of size 'nMessages' succeeded.
380 */
381 bool commitWrite(size_t nMessages);
382
383 /**
384 * Get a MemTransaction object to read 'nMessages' items of type T.
385 * Once the read is performed using the information from MemTransaction,
386 * the read operation is to be committed using a call to commitRead().
387 *
388 * @param nMessages Number of messages of type T.
389 * @param pointer to MemTransaction struct that describes memory to read 'nMessages'
390 * items of type T. If a read of size 'nMessages' is not possible, the base
391 * pointers in the MemTransaction object returned will be set to nullptr.
392 *
393 * @return bool Whether it is possible to read 'nMessages' items of type T
394 * from the FMQ.
395 */
396 bool beginRead(size_t nMessages, MemTransaction* memTx) const;
397
398 /**
399 * Commit a read of size 'nMessages'. To be only used after a call to beginRead().
400 * For the unsynchronized flavor of FMQ, this method will return a failure
401 * if a write overflow happened after beginRead() was invoked.
402 *
403 * @param nMessages number of messages of type T to be read.
404 *
405 * @return bool Whether the read operation of size 'nMessages' succeeded.
406 */
407 bool commitRead(size_t nMessages);
408
409private:
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800410
411 size_t availableToWriteBytes() const;
412 size_t availableToReadBytes() const;
413
414 MessageQueue(const MessageQueue& other) = delete;
415 MessageQueue& operator=(const MessageQueue& other) = delete;
416 MessageQueue();
417
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 /*
424 * These are only used internally by the blockingRead()/blockingWrite()
425 * methods and hence once other bit combinations are not required.
426 */
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800427 FMQ_NOT_FULL = 0x01,
428 FMQ_NOT_EMPTY = 0x02
429 };
430
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800431 std::unique_ptr<Descriptor> mDesc;
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800432 uint8_t* mRing = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800433 /*
434 * TODO(b/31550092): Change to 32 bit read and write pointer counters.
435 */
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800436 std::atomic<uint64_t>* mReadPtr = nullptr;
437 std::atomic<uint64_t>* mWritePtr = nullptr;
438
439 std::atomic<uint32_t>* mEvFlagWord = nullptr;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800440
441 /*
442 * This EventFlag object will be owned by the FMQ and will have the same
443 * lifetime.
444 */
445 android::hardware::EventFlag* mEventFlag = nullptr;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800446};
447
448template <typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800449T* MessageQueue<T, flavor>::MemTransaction::getSlot(size_t idx) {
450 size_t firstRegionLength = first.getLength();
451 size_t secondRegionLength = second.getLength();
452
453 if (idx > firstRegionLength + secondRegionLength) {
454 return nullptr;
455 }
456
457 if (idx < firstRegionLength) {
458 return first.getAddress() + idx;
459 }
460
461 return second.getAddress() + idx - firstRegionLength;
462}
463
464template <typename T, MQFlavor flavor>
465bool MessageQueue<T, flavor>::MemTransaction::getMemRegionInfo(size_t startIdx,
466 size_t nMessages,
467 size_t& firstCount,
468 size_t& secondCount,
469 T** firstBaseAddress,
470 T** secondBaseAddress) {
471 size_t firstRegionLength = first.getLength();
472 size_t secondRegionLength = second.getLength();
473
474 if (startIdx + nMessages > firstRegionLength + secondRegionLength) {
475 /*
476 * Return false if 'nMessages' starting at 'startIdx' cannot be
477 * accomodated by the MemTransaction object.
478 */
479 return false;
480 }
481
482 /* Number of messages to be read/written to the first MemRegion. */
483 firstCount = startIdx < firstRegionLength ?
484 std::min(nMessages, firstRegionLength - startIdx) : 0;
485
486 /* Number of messages to be read/written to the second MemRegion. */
487 secondCount = nMessages - firstCount;
488
489 if (firstCount != 0) {
490 *firstBaseAddress = first.getAddress() + startIdx;
491 }
492
493 if (secondCount != 0) {
494 size_t secondStartIdx = startIdx > firstRegionLength ? startIdx - firstRegionLength : 0;
495 *secondBaseAddress = second.getAddress() + secondStartIdx;
496 }
497
498 return true;
499}
500
501template <typename T, MQFlavor flavor>
502bool MessageQueue<T, flavor>::MemTransaction::copyFrom(T* data, size_t startIdx, size_t nMessages) {
503 if (data == nullptr) {
504 return false;
505 }
506
507 size_t firstReadCount = 0, secondReadCount = 0;
508 T* firstBaseAddress = nullptr, * secondBaseAddress = nullptr;
509
510 if (getMemRegionInfo(startIdx,
511 nMessages,
512 firstReadCount,
513 secondReadCount,
514 &firstBaseAddress,
515 &secondBaseAddress) == false) {
516 /*
517 * Returns false if 'startIdx' and 'nMessages' are invalid for this
518 * MemTransaction object.
519 */
520 return false;
521 }
522
523 if (firstReadCount != 0) {
524 memcpy(data, firstBaseAddress, firstReadCount * sizeof(T));
525 }
526
527 if (secondReadCount != 0) {
528 memcpy(data + firstReadCount,
529 secondBaseAddress,
530 secondReadCount * sizeof(T));
531 }
532
533 return true;
534}
535
536template <typename T, MQFlavor flavor>
537bool MessageQueue<T, flavor>::MemTransaction::copyTo(const T* data,
538 size_t startIdx,
539 size_t nMessages) {
540 if (data == nullptr) {
541 return false;
542 }
543
544 size_t firstWriteCount = 0, secondWriteCount = 0;
545 T * firstBaseAddress = nullptr, * secondBaseAddress = nullptr;
546
547 if (getMemRegionInfo(startIdx,
548 nMessages,
549 firstWriteCount,
550 secondWriteCount,
551 &firstBaseAddress,
552 &secondBaseAddress) == false) {
553 /*
554 * Returns false if 'startIdx' and 'nMessages' are invalid for this
555 * MemTransaction object.
556 */
557 return false;
558 }
559
560 if (firstWriteCount != 0) {
561 memcpy(firstBaseAddress, data, firstWriteCount * sizeof(T));
562 }
563
564 if (secondWriteCount != 0) {
565 memcpy(secondBaseAddress,
566 data + firstWriteCount,
567 secondWriteCount * sizeof(T));
568 }
569
570 return true;
571}
572
573template <typename T, MQFlavor flavor>
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800574void MessageQueue<T, flavor>::initMemory(bool resetPointers) {
575 /*
576 * Verify that the the Descriptor contains the minimum number of grantors
577 * the native_handle is valid and T matches quantum size.
578 */
579 if ((mDesc == nullptr) || !mDesc->isHandleValid() ||
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800580 (mDesc->countGrantors() < Descriptor::kMinGrantorCount) ||
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800581 (mDesc->getQuantum() != sizeof(T))) {
582 return;
583 }
584
585 if (flavor == kSynchronizedReadWrite) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800586 mReadPtr = reinterpret_cast<std::atomic<uint64_t>*>(
587 mapGrantorDescr(Descriptor::READPTRPOS));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800588 } else {
589 /*
590 * The unsynchronized write flavor of the FMQ may have multiple readers
591 * and each reader would have their own read pointer counter.
592 */
593 mReadPtr = new (std::nothrow) std::atomic<uint64_t>;
594 }
595
596 CHECK(mReadPtr != nullptr);
597
598 mWritePtr =
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800599 reinterpret_cast<std::atomic<uint64_t>*>(mapGrantorDescr(Descriptor::WRITEPTRPOS));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800600 CHECK(mWritePtr != nullptr);
601
602 if (resetPointers) {
603 mReadPtr->store(0, std::memory_order_release);
604 mWritePtr->store(0, std::memory_order_release);
605 } else if (flavor != kSynchronizedReadWrite) {
606 // Always reset the read pointer.
607 mReadPtr->store(0, std::memory_order_release);
608 }
609
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800610 mRing = reinterpret_cast<uint8_t*>(mapGrantorDescr(Descriptor::DATAPTRPOS));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800611 CHECK(mRing != nullptr);
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800612
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800613 mEvFlagWord = static_cast<std::atomic<uint32_t>*>(mapGrantorDescr(Descriptor::EVFLAGWORDPOS));
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800614 if (mEvFlagWord != nullptr) {
615 android::hardware::EventFlag::createEventFlag(mEvFlagWord, &mEventFlag);
616 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800617}
618
619template <typename T, MQFlavor flavor>
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800620MessageQueue<T, flavor>::MessageQueue(const Descriptor& Desc, bool resetPointers) {
621 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(Desc));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800622 if (mDesc == nullptr) {
623 return;
624 }
625
626 initMemory(resetPointers);
627}
628
629template <typename T, MQFlavor flavor>
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800630MessageQueue<T, flavor>::MessageQueue(size_t numElementsInQueue, bool configureEventFlagWord) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800631 /*
632 * The FMQ needs to allocate memory for the ringbuffer as well as for the
Hridya Valsaraju92b79dc2016-12-19 14:57:44 -0800633 * read and write pointer counters. If an EventFlag word is to be configured,
634 * we also need to allocate memory for the same/
635 */
636 size_t kQueueSizeBytes = numElementsInQueue * sizeof(T);
637 size_t kMetaDataSize = 2 * sizeof(android::hardware::RingBufferPosition);
638
639 if (configureEventFlagWord) {
640 kMetaDataSize+= sizeof(std::atomic<uint32_t>);
641 }
642
643 /*
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800644 * Ashmem memory region size needs to be specified in page-aligned bytes.
645 * kQueueSizeBytes needs to be aligned to word boundary so that all offsets
646 * in the grantorDescriptor will be word aligned.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800647 */
648 size_t kAshmemSizePageAligned =
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800649 (Descriptor::alignToWordBoundary(kQueueSizeBytes) + kMetaDataSize + PAGE_SIZE - 1) &
650 ~(PAGE_SIZE - 1);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800651
652 /*
653 * Create an ashmem region to map the memory for the ringbuffer,
654 * read counter and write counter.
655 */
656 int ashmemFd = ashmem_create_region("MessageQueue", kAshmemSizePageAligned);
657 ashmem_set_prot_region(ashmemFd, PROT_READ | PROT_WRITE);
658
659 /*
660 * The native handle will contain the fds to be mapped.
661 */
662 native_handle_t* mqHandle =
663 native_handle_create(1 /* numFds */, 0 /* numInts */);
664 if (mqHandle == nullptr) {
665 return;
666 }
667
668 mqHandle->data[0] = ashmemFd;
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800669 mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(kQueueSizeBytes,
670 mqHandle,
671 sizeof(T),
672 configureEventFlagWord));
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800673 if (mDesc == nullptr) {
674 return;
675 }
676 initMemory(true);
677}
678
679template <typename T, MQFlavor flavor>
680MessageQueue<T, flavor>::~MessageQueue() {
681 if (flavor == kUnsynchronizedWrite) {
682 delete mReadPtr;
683 } else {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800684 unmapGrantorDescr(mReadPtr, Descriptor::READPTRPOS);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800685 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800686 if (mWritePtr != nullptr) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800687 unmapGrantorDescr(mWritePtr, Descriptor::WRITEPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800688 }
689 if (mRing != nullptr) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800690 unmapGrantorDescr(mRing, Descriptor::DATAPTRPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800691 }
692 if (mEvFlagWord != nullptr) {
Hridya Valsaraju7fd43e32017-01-06 10:19:52 -0800693 unmapGrantorDescr(mEvFlagWord, Descriptor::EVFLAGWORDPOS);
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800694 android::hardware::EventFlag::deleteEventFlag(&mEventFlag);
695 }
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800696}
697
698template <typename T, MQFlavor flavor>
699bool MessageQueue<T, flavor>::write(const T* data) {
700 return write(data, 1);
701}
702
703template <typename T, MQFlavor flavor>
704bool MessageQueue<T, flavor>::read(T* data) {
705 return read(data, 1);
706}
707
708template <typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800709bool MessageQueue<T, flavor>::write(const T* data, size_t nMessages) {
710 MemTransaction tx;
711 return beginWrite(nMessages, &tx) &&
712 tx.copyTo(data, 0 /* startIdx */, nMessages) &&
713 commitWrite(nMessages);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -0800714}
715
716template <typename T, MQFlavor flavor>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800717bool MessageQueue<T, flavor>::writeBlocking(const T* data,
718 size_t count,
719 uint32_t readNotification,
720 uint32_t writeNotification,
721 int64_t timeOutNanos,
722 android::hardware::EventFlag* evFlag) {
723 /*
724 * If evFlag is null and the FMQ does not have its own EventFlag object
725 * return false;
726 * If the flavor is kSynchronizedReadWrite and the readNotification
727 * bit mask is zero return false;
728 * If the count is greater than queue size, return false
729 * to prevent blocking until timeOut.
730 */
731 if (evFlag == nullptr) {
732 evFlag = mEventFlag;
733 if (evFlag == nullptr) {
734 return false;
735 }
736 }
737
738 if ((readNotification == 0 && flavor == kSynchronizedReadWrite) ||
739 (count > getQuantumCount())) {
740 return false;
741 }
742
743 /*
744 * There is no need to wait for a readNotification if the flavor
745 * of the queue is kUnsynchronizedWrite or sufficient space to write
746 * is already present in the FMQ. The latter would be the case when
747 * read operations read more number of messages than
748 * write operations write. In other words, a single large read may clear the FMQ
749 * after multiple small writes. This would fail to clear a pending
750 * readNotification bit since EventFlag bits can only be cleared
751 * by a wait() call, however the bit would be correctly cleared by the next
752 * blockingWrite() call.
753 */
754
755 bool result = write(data, count);
756 if (result) {
757 if (writeNotification) {
758 evFlag->wake(writeNotification);
759 }
760 return result;
761 }
762
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800763 bool shouldTimeOut = timeOutNanos != 0;
764 int64_t prevTimeNs = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
765
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800766 bool endWait = false;
767 while (endWait == false) {
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800768 /* It is not require to adjust 'timeOutNanos' if 'shouldTimeOut' is true */
769 if (shouldTimeOut) {
770 int64_t currentTimeNs = android::elapsedRealtimeNano();
771 /*
772 * Decrement TimeOutNanos to account for the time taken to complete the last
773 * iteration of the while loop.
774 */
775 timeOutNanos -= currentTimeNs - prevTimeNs;
776 prevTimeNs = currentTimeNs;
777 if (timeOutNanos <= 0) {
778 /*
779 * Attempt write in case a context switch happened outside of
780 * evFlag->wait().
781 */
782 result = write(data, count);
783 break;
784 }
785 }
786
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800787 /*
788 * wait() will return immediately if there was a pending read
789 * notification.
790 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800791 uint32_t efState = 0;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800792 status_t status = evFlag->wait(readNotification, &efState, timeOutNanos);
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800793 switch (status) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800794 case android::NO_ERROR:
795 /*
796 * If wait() returns NO_ERROR, break and check efState.
797 */
798 break;
799 case android::TIMED_OUT:
800 /*
801 * If wait() returns android::TIMEDOUT, break out of the while loop
802 * and return false;
803 */
804 endWait = true;
805 continue;
806 case -EAGAIN:
807 case -EINTR:
808 /*
809 * For errors -EAGAIN and -EINTR, go back to wait.
810 */
811 continue;
812 default:
813 /*
814 * Throw an error for any other error code since it is unexpected.
815 */
816
817 endWait = true;
818 ALOGE("Unexpected error code from EventFlag Wait %d", status);
819 continue;
820 }
821
822 /*
823 * If the wake() was not due to the readNotification bit or if
824 * there is still insufficient space to write to the FMQ,
825 * keep waiting for another readNotification.
826 */
827 if ((efState & readNotification) && write(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800828 result = true;
829 endWait = true;
830 }
831 }
832
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800833 if (result && writeNotification != 0) {
834 evFlag->wake(writeNotification);
835 }
836
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800837 return result;
838}
839
840template <typename T, MQFlavor flavor>
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800841bool MessageQueue<T, flavor>::writeBlocking(const T* data,
842 size_t count,
843 int64_t timeOutNanos) {
844 return writeBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
845}
846
847template <typename T, MQFlavor flavor>
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800848bool MessageQueue<T, flavor>::readBlocking(T* data,
849 size_t count,
850 uint32_t readNotification,
851 uint32_t writeNotification,
852 int64_t timeOutNanos,
853 android::hardware::EventFlag* evFlag) {
854 /*
855 * If evFlag is null and the FMQ does not own its own EventFlag object
856 * return false;
857 * If the writeNotification bit mask is zero return false;
858 * If the count is greater than queue size, return false to prevent
859 * blocking until timeOut.
860 */
861 if (evFlag == nullptr) {
862 evFlag = mEventFlag;
863 if (evFlag == nullptr) {
864 return false;
865 }
866 }
867
868 if (writeNotification == 0 || count > getQuantumCount()) {
869 return false;
870 }
871
872 /*
873 * There is no need to wait for a write notification if sufficient
874 * data to read is already present in the FMQ. This would be the
875 * case when read operations read lesser number of messages than
876 * a write operation and multiple reads would be required to clear the queue
877 * after a single write operation. This check would fail to clear a pending
878 * writeNotification bit since EventFlag bits can only be cleared
879 * by a wait() call, however the bit would be correctly cleared by the next
880 * readBlocking() call.
881 */
882
883 bool result = read(data, count);
884 if (result) {
885 if (readNotification) {
886 evFlag->wake(readNotification);
887 }
888 return result;
889 }
890
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800891 bool shouldTimeOut = timeOutNanos != 0;
892 int64_t prevTimeNs = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
893
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800894 bool endWait = false;
895 while (endWait == false) {
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800896 /* It is not require to adjust 'timeOutNanos' if 'shouldTimeOut' is true */
897 if (shouldTimeOut) {
898 int64_t currentTimeNs = android::elapsedRealtimeNano();
899 /*
900 * Decrement TimeOutNanos to account for the time taken to complete the last
901 * iteration of the while loop.
902 */
903 timeOutNanos -= currentTimeNs - prevTimeNs;
904 prevTimeNs = currentTimeNs;
905
906 if (timeOutNanos <= 0) {
907 /*
908 * Attempt read in case a context switch happened outside of
909 * evFlag->wait().
910 */
911 result = read(data, count);
912 break;
913 }
914 }
915
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800916 /*
917 * wait() will return immediately if there was a pending write
918 * notification.
919 */
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800920 uint32_t efState = 0;
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800921 status_t status = evFlag->wait(writeNotification, &efState, timeOutNanos);
Hridya Valsaraju2fb3a0c2017-01-10 14:31:43 -0800922 switch (status) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800923 case android::NO_ERROR:
924 /*
925 * If wait() returns NO_ERROR, break and check efState.
926 */
927 break;
928 case android::TIMED_OUT:
929 /*
930 * If wait() returns android::TIMEDOUT, break out of the while loop
931 * and return false;
932 */
933 endWait = true;
934 continue;
935 case -EAGAIN:
936 case -EINTR:
937 /*
938 * For errors -EAGAIN and -EINTR, go back to wait.
939 */
940 continue;
941 default:
942 /*
943 * Throw an error for any other error code since it is unexpected.
944 */
945
946 endWait = true;
947 ALOGE("Unexpected error code from EventFlag Wait %d", status);
948 continue;
949 }
950
951 /*
952 * If the wake() was not due to the writeNotification bit being set
953 * or if the data in FMQ is still insufficient, go back to waiting
954 * for another write notification.
955 */
956 if ((efState & writeNotification) && read(data, count)) {
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800957 result = true;
958 endWait = true;
959 }
960 }
961
Hridya Valsaraju2abefb62017-01-19 13:06:58 -0800962 if (result && readNotification != 0) {
963 evFlag->wake(readNotification);
964 }
Hridya Valsarajuf0ffb832016-12-28 08:46:42 -0800965 return result;
966}
967
968template <typename T, MQFlavor flavor>
Hridya Valsaraju4486ad02017-01-13 20:49:39 -0800969bool MessageQueue<T, flavor>::readBlocking(T* data, size_t count, int64_t timeOutNanos) {
970 return readBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
971}
972
973template <typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -0800974size_t MessageQueue<T, flavor>::availableToWriteBytes() const {
975 return mDesc->getSize() - availableToReadBytes();
976}
977
978template <typename T, MQFlavor flavor>
979size_t MessageQueue<T, flavor>::availableToWrite() const {
980 return availableToWriteBytes() / sizeof(T);
981}
982
983template <typename T, MQFlavor flavor>
984size_t MessageQueue<T, flavor>::availableToRead() const {
985 return availableToReadBytes() / sizeof(T);
986}
987
988template <typename T, MQFlavor flavor>
989bool MessageQueue<T, flavor>::beginWrite(size_t nMessages, MemTransaction* result) const {
990 /*
991 * If nMessages is greater than size of FMQ or in case of the synchronized
992 * FMQ flavor, if there is not enough space to write nMessages, then return
993 * result with null addresses.
994 */
995 if ((flavor == kSynchronizedReadWrite && (availableToWrite() < nMessages)) ||
996 nMessages > getQuantumCount()) {
997 *result = MemTransaction();
998 return false;
999 }
1000
1001 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1002 size_t writeOffset = writePtr % mDesc->getSize();
1003
1004 /*
1005 * From writeOffset, the number of messages that can be written
1006 * contiguously without wrapping around the ring buffer are calculated.
1007 */
1008 size_t contiguousMessages = (mDesc->getSize() - writeOffset) / sizeof(T);
1009
1010 if (contiguousMessages < nMessages) {
1011 /*
1012 * Wrap around is required. Both result.first and result.second are
1013 * populated.
1014 */
1015 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + writeOffset),
1016 contiguousMessages),
1017 MemRegion(reinterpret_cast<T*>(mRing),
1018 nMessages - contiguousMessages));
1019 } else {
1020 /*
1021 * A wrap around is not required to write nMessages. Only result.first
1022 * is populated.
1023 */
1024 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + writeOffset), nMessages),
1025 MemRegion());
1026 }
1027
1028 return true;
1029}
1030
1031template <typename T, MQFlavor flavor>
1032/*
1033 * Disable integer sanitization since integer overflow here is allowed
1034 * and legal.
1035 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001036__attribute__((no_sanitize("integer")))
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001037bool MessageQueue<T, flavor>::commitWrite(size_t nMessages) {
1038 size_t nBytesWritten = nMessages * sizeof(T);
1039 auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1040 writePtr += nBytesWritten;
1041 mWritePtr->store(writePtr, std::memory_order_release);
1042 /*
1043 * This method cannot fail now since we are only incrementing the writePtr
1044 * counter.
1045 */
1046 return true;
1047}
1048
1049template <typename T, MQFlavor flavor>
1050size_t MessageQueue<T, flavor>::availableToReadBytes() const {
1051 /*
1052 * This method is invoked by implementations of both read() and write() and
1053 * hence requries a memory_order_acquired load for both mReadPtr and
1054 * mWritePtr.
1055 */
1056 return mWritePtr->load(std::memory_order_acquire) -
1057 mReadPtr->load(std::memory_order_acquire);
1058}
1059
1060template <typename T, MQFlavor flavor>
1061bool MessageQueue<T, flavor>::read(T* data, size_t nMessages) {
1062 MemTransaction tx;
1063 return beginRead(nMessages, &tx) &&
1064 tx.copyFrom(data, 0 /* startIdx */, nMessages) &&
1065 commitRead(nMessages);
1066}
1067
1068template <typename T, MQFlavor flavor>
1069/*
1070 * Disable integer sanitization since integer overflow here is allowed
1071 * and legal.
1072 */
1073__attribute__((no_sanitize("integer")))
1074bool MessageQueue<T, flavor>::beginRead(size_t nMessages, MemTransaction* result) const {
1075 *result = MemTransaction();
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001076 /*
1077 * If it is detected that the data in the queue was overwritten
1078 * due to the reader process being too slow, the read pointer counter
1079 * is set to the same as the write pointer counter to indicate error
1080 * and the read returns false;
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001081 * Need acquire/release memory ordering for mWritePtr.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001082 */
Hridya Valsaraju04cdd2c2016-12-21 08:38:57 -08001083 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1084 /*
1085 * A relaxed load is sufficient for mReadPtr since there will be no
1086 * stores to mReadPtr from a different thread.
1087 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001088 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
1089
1090 if (writePtr - readPtr > mDesc->getSize()) {
1091 mReadPtr->store(writePtr, std::memory_order_release);
1092 return false;
1093 }
1094
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001095 size_t nBytesDesired = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001096 /*
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001097 * Return if insufficient data to read in FMQ.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001098 */
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001099 if (writePtr - readPtr < nBytesDesired) {
1100 return false;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001101 }
1102
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001103 size_t readOffset = readPtr % mDesc->getSize();
1104 /*
1105 * From readOffset, the number of messages that can be read contiguously
1106 * without wrapping around the ring buffer are calculated.
1107 */
1108 size_t contiguousMessages = (mDesc->getSize() - readOffset) / sizeof(T);
1109
1110 if (contiguousMessages < nMessages) {
1111 /*
1112 * A wrap around is required. Both result.first and result.second
1113 * are populated.
1114 */
1115 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + readOffset),
1116 contiguousMessages),
1117 MemRegion(reinterpret_cast<T*>(mRing),
1118 nMessages - contiguousMessages));
1119 } else {
1120 /*
1121 * A wrap around is not required. Only result.first need to be
1122 * populated.
1123 */
1124 *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + readOffset), nMessages),
1125 MemRegion());
1126 }
1127
1128 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001129}
1130
1131template <typename T, MQFlavor flavor>
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001132/*
1133 * Disable integer sanitization since integer overflow here is allowed
1134 * and legal.
1135 */
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001136__attribute__((no_sanitize("integer")))
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001137bool MessageQueue<T, flavor>::commitRead(size_t nMessages) {
1138 // TODO: Use a local copy of readPtr to avoid relazed mReadPtr loads.
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001139 auto readPtr = mReadPtr->load(std::memory_order_relaxed);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001140 auto writePtr = mWritePtr->load(std::memory_order_acquire);
1141 /*
1142 * If the flavor is unsynchronized, it is possible that a write overflow may
1143 * have occured between beginRead() and commitRead().
1144 */
1145 if (writePtr - readPtr > mDesc->getSize()) {
1146 mReadPtr->store(writePtr, std::memory_order_release);
1147 return false;
1148 }
1149
1150 size_t nBytesRead = nMessages * sizeof(T);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001151 readPtr += nBytesRead;
1152 mReadPtr->store(readPtr, std::memory_order_release);
Hridya Valsaraju8f0e8e52017-01-09 07:57:00 -08001153 return true;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001154}
1155
1156template <typename T, MQFlavor flavor>
1157size_t MessageQueue<T, flavor>::getQuantumSize() const {
1158 return mDesc->getQuantum();
1159}
1160
1161template <typename T, MQFlavor flavor>
1162size_t MessageQueue<T, flavor>::getQuantumCount() const {
1163 return mDesc->getSize() / mDesc->getQuantum();
1164}
1165
1166template <typename T, MQFlavor flavor>
1167bool MessageQueue<T, flavor>::isValid() const {
1168 return mRing != nullptr && mReadPtr != nullptr && mWritePtr != nullptr;
1169}
1170
1171template <typename T, MQFlavor flavor>
1172void* MessageQueue<T, flavor>::mapGrantorDescr(uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001173 const native_handle_t* handle = mDesc->handle();
1174 auto grantors = mDesc->grantors();
1175 if ((handle == nullptr) || (grantorIdx >= grantors.size())) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001176 return nullptr;
1177 }
1178
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001179 int fdIndex = grantors[grantorIdx].fdIndex;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001180 /*
1181 * Offset for mmap must be a multiple of PAGE_SIZE.
1182 */
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001183 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001184 int mapLength =
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001185 grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001186
1187 void* address = mmap(0, mapLength, PROT_READ | PROT_WRITE, MAP_SHARED,
1188 handle->data[fdIndex], mapOffset);
1189 return (address == MAP_FAILED)
1190 ? nullptr
1191 : reinterpret_cast<uint8_t*>(address) +
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001192 (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001193}
1194
1195template <typename T, MQFlavor flavor>
1196void MessageQueue<T, flavor>::unmapGrantorDescr(void* address,
1197 uint32_t grantorIdx) {
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001198 auto grantors = mDesc->grantors();
1199 if ((address == nullptr) || (grantorIdx >= grantors.size())) {
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001200 return;
1201 }
1202
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001203 int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001204 int mapLength =
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001205 grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001206 void* baseAddress = reinterpret_cast<uint8_t*>(address) -
Hridya Valsaraju6ba72a52017-02-24 10:59:55 -08001207 (grantors[grantorIdx].offset - mapOffset);
Hridya Valsaraju8b0d5a52016-12-16 10:29:03 -08001208 if (baseAddress) munmap(baseAddress, mapLength);
1209}
1210
1211} // namespace hardware
1212} // namespace android
1213#endif // HIDL_MQ_H