• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
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 #pragma once
18 
19 #include <android-base/unique_fd.h>
20 #include <cutils/ashmem.h>
21 #include <fmq/EventFlag.h>
22 #include <sys/mman.h>
23 #include <sys/user.h>
24 #include <utils/Log.h>
25 #include <utils/SystemClock.h>
26 #include <atomic>
27 #include <new>
28 
29 using android::hardware::kSynchronizedReadWrite;
30 using android::hardware::kUnsynchronizedWrite;
31 using android::hardware::MQFlavor;
32 
33 namespace android {
34 
35 template <template <typename, MQFlavor> class MQDescriptorType, typename T, MQFlavor flavor>
36 struct MessageQueueBase {
37     typedef MQDescriptorType<T, flavor> Descriptor;
38 
39     /**
40      * @param Desc MQDescriptor describing the FMQ.
41      * @param resetPointers bool indicating whether the read/write pointers
42      * should be reset or not.
43      */
44     MessageQueueBase(const Descriptor& Desc, bool resetPointers = true);
45 
46     ~MessageQueueBase();
47 
48     /**
49      * This constructor uses Ashmem shared memory to create an FMQ
50      * that can contain a maximum of 'numElementsInQueue' elements of type T.
51      *
52      * @param numElementsInQueue Capacity of the MessageQueue in terms of T.
53      * @param configureEventFlagWord Boolean that specifies if memory should
54      * also be allocated and mapped for an EventFlag word.
55      * @param bufferFd User-supplied file descriptor to map the memory for the ringbuffer
56      * By default, bufferFd=-1 means library will allocate ashmem region for ringbuffer.
57      * MessageQueue takes ownership of the file descriptor.
58      * @param bufferSize size of buffer in bytes that bufferFd represents. This
59      * size must be larger than or equal to (numElementsInQueue * sizeof(T)).
60      * Otherwise, operations will cause out-of-bounds memory access.
61      */
62 
63     MessageQueueBase(size_t numElementsInQueue, bool configureEventFlagWord,
64                      android::base::unique_fd bufferFd, size_t bufferSize);
65 
66     MessageQueueBase(size_t numElementsInQueue, bool configureEventFlagWord = false)
67         : MessageQueueBase(numElementsInQueue, configureEventFlagWord, android::base::unique_fd(),
68                            0) {}
69 
70     /**
71      * @return Number of items of type T that can be written into the FMQ
72      * without a read.
73      */
74     size_t availableToWrite() const;
75 
76     /**
77      * @return Number of items of type T that are waiting to be read from the
78      * FMQ.
79      */
80     size_t availableToRead() const;
81 
82     /**
83      * Returns the size of type T in bytes.
84      *
85      * @param Size of T.
86      */
87     size_t getQuantumSize() const;
88 
89     /**
90      * Returns the size of the FMQ in terms of the size of type T.
91      *
92      * @return Number of items of type T that will fit in the FMQ.
93      */
94     size_t getQuantumCount() const;
95 
96     /**
97      * @return Whether the FMQ is configured correctly.
98      */
99     bool isValid() const;
100 
101     /**
102      * Non-blocking write to FMQ.
103      *
104      * @param data Pointer to the object of type T to be written into the FMQ.
105      *
106      * @return Whether the write was successful.
107      */
108     bool write(const T* data);
109 
110     /**
111      * Non-blocking read from FMQ.
112      *
113      * @param data Pointer to the memory where the object read from the FMQ is
114      * copied to.
115      *
116      * @return Whether the read was successful.
117      */
118     bool read(T* data);
119 
120     /**
121      * Write some data into the FMQ without blocking.
122      *
123      * @param data Pointer to the array of items of type T.
124      * @param count Number of items in array.
125      *
126      * @return Whether the write was successful.
127      */
128     bool write(const T* data, size_t count);
129 
130     /**
131      * Perform a blocking write of 'count' items into the FMQ using EventFlags.
132      * Does not support partial writes.
133      *
134      * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
135      * associated with the FMQ and it is used in that case.
136      *
137      * The application code must ensure that 'evFlag' used by the
138      * reader(s)/writer is based upon the same EventFlag word.
139      *
140      * The method will return false without blocking if any of the following
141      * conditions are true:
142      * - If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
143      * - If the 'readNotification' bit mask is zero.
144      * - If 'count' is greater than the FMQ size.
145      *
146      * If the there is insufficient space available to write into it, the
147      * EventFlag bit mask 'readNotification' is is waited upon.
148      *
149      * This method should only be used with a MessageQueue of the flavor
150      * 'kSynchronizedReadWrite'.
151      *
152      * Upon a successful write, wake is called on 'writeNotification' (if
153      * non-zero).
154      *
155      * @param data Pointer to the array of items of type T.
156      * @param count Number of items in array.
157      * @param readNotification The EventFlag bit mask to wait on if there is not
158      * enough space in FMQ to write 'count' items.
159      * @param writeNotification The EventFlag bit mask to call wake on
160      * a successful write. No wake is called if 'writeNotification' is zero.
161      * @param timeOutNanos Number of nanoseconds after which the blocking
162      * write attempt is aborted.
163      * @param evFlag The EventFlag object to be used for blocking. If nullptr,
164      * it is checked whether the FMQ owns an EventFlag object and that is used
165      * for blocking instead.
166      *
167      * @return Whether the write was successful.
168      */
169     bool writeBlocking(const T* data, size_t count, uint32_t readNotification,
170                        uint32_t writeNotification, int64_t timeOutNanos = 0,
171                        android::hardware::EventFlag* evFlag = nullptr);
172 
173     bool writeBlocking(const T* data, size_t count, int64_t timeOutNanos = 0);
174 
175     /**
176      * Read some data from the FMQ without blocking.
177      *
178      * @param data Pointer to the array to which read data is to be written.
179      * @param count Number of items to be read.
180      *
181      * @return Whether the read was successful.
182      */
183     bool read(T* data, size_t count);
184 
185     /**
186      * Perform a blocking read operation of 'count' items from the FMQ. Does not
187      * perform a partial read.
188      *
189      * If 'evFlag' is nullptr, it is checked whether there is an EventFlag object
190      * associated with the FMQ and it is used in that case.
191      *
192      * The application code must ensure that 'evFlag' used by the
193      * reader(s)/writer is based upon the same EventFlag word.
194      *
195      * The method will return false without blocking if any of the following
196      * conditions are true:
197      * -If 'evFlag' is nullptr and the FMQ does not own an EventFlag object.
198      * -If the 'writeNotification' bit mask is zero.
199      * -If 'count' is greater than the FMQ size.
200      *
201      * This method should only be used with a MessageQueue of the flavor
202      * 'kSynchronizedReadWrite'.
203 
204      * If FMQ does not contain 'count' items, the eventFlag bit mask
205      * 'writeNotification' is waited upon. Upon a successful read from the FMQ,
206      * wake is called on 'readNotification' (if non-zero).
207      *
208      * @param data Pointer to the array to which read data is to be written.
209      * @param count Number of items to be read.
210      * @param readNotification The EventFlag bit mask to call wake on after
211      * a successful read. No wake is called if 'readNotification' is zero.
212      * @param writeNotification The EventFlag bit mask to call a wait on
213      * if there is insufficient data in the FMQ to be read.
214      * @param timeOutNanos Number of nanoseconds after which the blocking
215      * read attempt is aborted.
216      * @param evFlag The EventFlag object to be used for blocking.
217      *
218      * @return Whether the read was successful.
219      */
220     bool readBlocking(T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
221                       int64_t timeOutNanos = 0, android::hardware::EventFlag* evFlag = nullptr);
222 
223     bool readBlocking(T* data, size_t count, int64_t timeOutNanos = 0);
224 
225     /**
226      * Get a pointer to the MQDescriptor object that describes this FMQ.
227      *
228      * @return Pointer to the MQDescriptor associated with the FMQ.
229      */
getDescMessageQueueBase230     const Descriptor* getDesc() const { return mDesc.get(); }
231 
232     /**
233      * Get a pointer to the EventFlag word if there is one associated with this FMQ.
234      *
235      * @return Pointer to an EventFlag word, will return nullptr if not
236      * configured. This method does not transfer ownership. The EventFlag
237      * word will be unmapped by the MessageQueue destructor.
238      */
getEventFlagWordMessageQueueBase239     std::atomic<uint32_t>* getEventFlagWord() const { return mEvFlagWord; }
240 
241     /**
242      * Describes a memory region in the FMQ.
243      */
244     struct MemRegion {
MemRegionMessageQueueBase::MemRegion245         MemRegion() : MemRegion(nullptr, 0) {}
246 
MemRegionMessageQueueBase::MemRegion247         MemRegion(T* base, size_t size) : address(base), length(size) {}
248 
249         MemRegion& operator=(const MemRegion& other) {
250             address = other.address;
251             length = other.length;
252             return *this;
253         }
254 
255         /**
256          * Gets a pointer to the base address of the MemRegion.
257          */
getAddressMessageQueueBase::MemRegion258         inline T* getAddress() const { return address; }
259 
260         /**
261          * Gets the length of the MemRegion. This would equal to the number
262          * of items of type T that can be read from/written into the MemRegion.
263          */
getLengthMessageQueueBase::MemRegion264         inline size_t getLength() const { return length; }
265 
266         /**
267          * Gets the length of the MemRegion in bytes.
268          */
getLengthInBytesMessageQueueBase::MemRegion269         inline size_t getLengthInBytes() const { return length * sizeof(T); }
270 
271       private:
272         /* Base address */
273         T* address;
274 
275         /*
276          * Number of items of type T that can be written to/read from the base
277          * address.
278          */
279         size_t length;
280     };
281 
282     /**
283      * Describes the memory regions to be used for a read or write.
284      * The struct contains two MemRegion objects since the FMQ is a ring
285      * buffer and a read or write operation can wrap around. A single message
286      * of type T will never be broken between the two MemRegions.
287      */
288     struct MemTransaction {
MemTransactionMessageQueueBase::MemTransaction289         MemTransaction() : MemTransaction(MemRegion(), MemRegion()) {}
290 
MemTransactionMessageQueueBase::MemTransaction291         MemTransaction(const MemRegion& regionFirst, const MemRegion& regionSecond)
292             : first(regionFirst), second(regionSecond) {}
293 
294         MemTransaction& operator=(const MemTransaction& other) {
295             first = other.first;
296             second = other.second;
297             return *this;
298         }
299 
300         /**
301          * Helper method to calculate the address for a particular index for
302          * the MemTransaction object.
303          *
304          * @param idx Index of the slot to be read/written. If the
305          * MemTransaction object is representing the memory region to read/write
306          * N items of type T, the valid range of idx is between 0 and N-1.
307          *
308          * @return Pointer to the slot idx. Will be nullptr for an invalid idx.
309          */
310         T* getSlot(size_t idx);
311 
312         /**
313          * Helper method to write 'nMessages' items of type T into the memory
314          * regions described by the object starting from 'startIdx'. This method
315          * uses memcpy() and is not to meant to be used for a zero copy operation.
316          * Partial writes are not supported.
317          *
318          * @param data Pointer to the source buffer.
319          * @param nMessages Number of items of type T.
320          * @param startIdx The slot number to begin the write from. If the
321          * MemTransaction object is representing the memory region to read/write
322          * N items of type T, the valid range of startIdx is between 0 and N-1;
323          *
324          * @return Whether the write operation of size 'nMessages' succeeded.
325          */
326         bool copyTo(const T* data, size_t startIdx, size_t nMessages = 1);
327 
328         /*
329          * Helper method to read 'nMessages' items of type T from the memory
330          * regions described by the object starting from 'startIdx'. This method uses
331          * memcpy() and is not meant to be used for a zero copy operation. Partial reads
332          * are not supported.
333          *
334          * @param data Pointer to the destination buffer.
335          * @param nMessages Number of items of type T.
336          * @param startIdx The slot number to begin the read from. If the
337          * MemTransaction object is representing the memory region to read/write
338          * N items of type T, the valid range of startIdx is between 0 and N-1.
339          *
340          * @return Whether the read operation of size 'nMessages' succeeded.
341          */
342         bool copyFrom(T* data, size_t startIdx, size_t nMessages = 1);
343 
344         /**
345          * Returns a const reference to the first MemRegion in the
346          * MemTransaction object.
347          */
getFirstRegionMessageQueueBase::MemTransaction348         inline const MemRegion& getFirstRegion() const { return first; }
349 
350         /**
351          * Returns a const reference to the second MemRegion in the
352          * MemTransaction object.
353          */
getSecondRegionMessageQueueBase::MemTransaction354         inline const MemRegion& getSecondRegion() const { return second; }
355 
356       private:
357         /*
358          * Given a start index and the number of messages to be
359          * read/written, this helper method calculates the
360          * number of messages that should should be written to both the first
361          * and second MemRegions and the base addresses to be used for
362          * the read/write operation.
363          *
364          * Returns false if the 'startIdx' and 'nMessages' is
365          * invalid for the MemTransaction object.
366          */
367         bool inline getMemRegionInfo(size_t idx, size_t nMessages, size_t& firstCount,
368                                      size_t& secondCount, T** firstBaseAddress,
369                                      T** secondBaseAddress);
370         MemRegion first;
371         MemRegion second;
372     };
373 
374     /**
375      * Get a MemTransaction object to write 'nMessages' items of type T.
376      * Once the write is performed using the information from MemTransaction,
377      * the write operation is to be committed using a call to commitWrite().
378      *
379      * @param nMessages Number of messages of type T.
380      * @param Pointer to MemTransaction struct that describes memory to write 'nMessages'
381      * items of type T. If a write of size 'nMessages' is not possible, the base
382      * addresses in the MemTransaction object would be set to nullptr.
383      *
384      * @return Whether it is possible to write 'nMessages' items of type T
385      * into the FMQ.
386      */
387     bool beginWrite(size_t nMessages, MemTransaction* memTx) const;
388 
389     /**
390      * Commit a write of size 'nMessages'. To be only used after a call to beginWrite().
391      *
392      * @param nMessages number of messages of type T to be written.
393      *
394      * @return Whether the write operation of size 'nMessages' succeeded.
395      */
396     bool commitWrite(size_t nMessages);
397 
398     /**
399      * Get a MemTransaction object to read 'nMessages' items of type T.
400      * Once the read is performed using the information from MemTransaction,
401      * the read operation is to be committed using a call to commitRead().
402      *
403      * @param nMessages Number of messages of type T.
404      * @param pointer to MemTransaction struct that describes memory to read 'nMessages'
405      * items of type T. If a read of size 'nMessages' is not possible, the base
406      * pointers in the MemTransaction object returned will be set to nullptr.
407      *
408      * @return bool Whether it is possible to read 'nMessages' items of type T
409      * from the FMQ.
410      */
411     bool beginRead(size_t nMessages, MemTransaction* memTx) const;
412 
413     /**
414      * Commit a read of size 'nMessages'. To be only used after a call to beginRead().
415      * For the unsynchronized flavor of FMQ, this method will return a failure
416      * if a write overflow happened after beginRead() was invoked.
417      *
418      * @param nMessages number of messages of type T to be read.
419      *
420      * @return bool Whether the read operation of size 'nMessages' succeeded.
421      */
422     bool commitRead(size_t nMessages);
423 
424   private:
425     size_t availableToWriteBytes() const;
426     size_t availableToReadBytes() const;
427 
428     MessageQueueBase(const MessageQueueBase& other) = delete;
429     MessageQueueBase& operator=(const MessageQueueBase& other) = delete;
430 
431     void* mapGrantorDescr(uint32_t grantorIdx);
432     void unmapGrantorDescr(void* address, uint32_t grantorIdx);
433     void initMemory(bool resetPointers);
434 
435     enum DefaultEventNotification : uint32_t {
436         /*
437          * These are only used internally by the readBlocking()/writeBlocking()
438          * methods and hence once other bit combinations are not required.
439          */
440         FMQ_NOT_FULL = 0x01,
441         FMQ_NOT_EMPTY = 0x02
442     };
443     std::unique_ptr<Descriptor> mDesc;
444     uint8_t* mRing = nullptr;
445     /*
446      * TODO(b/31550092): Change to 32 bit read and write pointer counters.
447      */
448     std::atomic<uint64_t>* mReadPtr = nullptr;
449     std::atomic<uint64_t>* mWritePtr = nullptr;
450 
451     std::atomic<uint32_t>* mEvFlagWord = nullptr;
452 
453     /*
454      * This EventFlag object will be owned by the FMQ and will have the same
455      * lifetime.
456      */
457     android::hardware::EventFlag* mEventFlag = nullptr;
458 };
459 
460 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
getSlot(size_t idx)461 T* MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getSlot(size_t idx) {
462     size_t firstRegionLength = first.getLength();
463     size_t secondRegionLength = second.getLength();
464 
465     if (idx > firstRegionLength + secondRegionLength) {
466         return nullptr;
467     }
468 
469     if (idx < firstRegionLength) {
470         return first.getAddress() + idx;
471     }
472 
473     return second.getAddress() + idx - firstRegionLength;
474 }
475 
476 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
getMemRegionInfo(size_t startIdx,size_t nMessages,size_t & firstCount,size_t & secondCount,T ** firstBaseAddress,T ** secondBaseAddress)477 bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::getMemRegionInfo(
478         size_t startIdx, size_t nMessages, size_t& firstCount, size_t& secondCount,
479         T** firstBaseAddress, T** secondBaseAddress) {
480     size_t firstRegionLength = first.getLength();
481     size_t secondRegionLength = second.getLength();
482 
483     if (startIdx + nMessages > firstRegionLength + secondRegionLength) {
484         /*
485          * Return false if 'nMessages' starting at 'startIdx' cannot be
486          * accommodated by the MemTransaction object.
487          */
488         return false;
489     }
490 
491     /* Number of messages to be read/written to the first MemRegion. */
492     firstCount =
493             startIdx < firstRegionLength ? std::min(nMessages, firstRegionLength - startIdx) : 0;
494 
495     /* Number of messages to be read/written to the second MemRegion. */
496     secondCount = nMessages - firstCount;
497 
498     if (firstCount != 0) {
499         *firstBaseAddress = first.getAddress() + startIdx;
500     }
501 
502     if (secondCount != 0) {
503         size_t secondStartIdx = startIdx > firstRegionLength ? startIdx - firstRegionLength : 0;
504         *secondBaseAddress = second.getAddress() + secondStartIdx;
505     }
506 
507     return true;
508 }
509 
510 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
copyFrom(T * data,size_t startIdx,size_t nMessages)511 bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyFrom(T* data,
512                                                                              size_t startIdx,
513                                                                              size_t nMessages) {
514     if (data == nullptr) {
515         return false;
516     }
517 
518     size_t firstReadCount = 0, secondReadCount = 0;
519     T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
520 
521     if (getMemRegionInfo(startIdx, nMessages, firstReadCount, secondReadCount, &firstBaseAddress,
522                          &secondBaseAddress) == false) {
523         /*
524          * Returns false if 'startIdx' and 'nMessages' are invalid for this
525          * MemTransaction object.
526          */
527         return false;
528     }
529 
530     if (firstReadCount != 0) {
531         memcpy(data, firstBaseAddress, firstReadCount * sizeof(T));
532     }
533 
534     if (secondReadCount != 0) {
535         memcpy(data + firstReadCount, secondBaseAddress, secondReadCount * sizeof(T));
536     }
537 
538     return true;
539 }
540 
541 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
copyTo(const T * data,size_t startIdx,size_t nMessages)542 bool MessageQueueBase<MQDescriptorType, T, flavor>::MemTransaction::copyTo(const T* data,
543                                                                            size_t startIdx,
544                                                                            size_t nMessages) {
545     if (data == nullptr) {
546         return false;
547     }
548 
549     size_t firstWriteCount = 0, secondWriteCount = 0;
550     T *firstBaseAddress = nullptr, *secondBaseAddress = nullptr;
551 
552     if (getMemRegionInfo(startIdx, nMessages, firstWriteCount, secondWriteCount, &firstBaseAddress,
553                          &secondBaseAddress) == false) {
554         /*
555          * Returns false if 'startIdx' and 'nMessages' are invalid for this
556          * MemTransaction object.
557          */
558         return false;
559     }
560 
561     if (firstWriteCount != 0) {
562         memcpy(firstBaseAddress, data, firstWriteCount * sizeof(T));
563     }
564 
565     if (secondWriteCount != 0) {
566         memcpy(secondBaseAddress, data + firstWriteCount, secondWriteCount * sizeof(T));
567     }
568 
569     return true;
570 }
571 
572 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
initMemory(bool resetPointers)573 void MessageQueueBase<MQDescriptorType, T, flavor>::initMemory(bool resetPointers) {
574     /*
575      * Verify that the Descriptor contains the minimum number of grantors
576      * the native_handle is valid and T matches quantum size.
577      */
578     if ((mDesc == nullptr) || !mDesc->isHandleValid() ||
579         (mDesc->countGrantors() < hardware::details::kMinGrantorCount)) {
580         return;
581     }
582     if (mDesc->getQuantum() != sizeof(T)) {
583         hardware::details::logError(
584                 "Payload size differs between the queue instantiation and the "
585                 "MQDescriptor.");
586         return;
587     }
588 
589     const auto& grantors = mDesc->grantors();
590     for (const auto& grantor : grantors) {
591         if (hardware::details::isAlignedToWordBoundary(grantor.offset) == false) {
592 #ifdef __BIONIC__
593             __assert(__FILE__, __LINE__, "Grantor offsets need to be aligned");
594 #endif
595         }
596     }
597 
598     if (flavor == kSynchronizedReadWrite) {
599         mReadPtr = reinterpret_cast<std::atomic<uint64_t>*>(
600                 mapGrantorDescr(hardware::details::READPTRPOS));
601     } else {
602         /*
603          * The unsynchronized write flavor of the FMQ may have multiple readers
604          * and each reader would have their own read pointer counter.
605          */
606         mReadPtr = new (std::nothrow) std::atomic<uint64_t>;
607     }
608     if (mReadPtr == nullptr) {
609 #ifdef __BIONIC__
610         __assert(__FILE__, __LINE__, "mReadPtr is null");
611 #endif
612     }
613 
614     mWritePtr = reinterpret_cast<std::atomic<uint64_t>*>(
615             mapGrantorDescr(hardware::details::WRITEPTRPOS));
616     if (mWritePtr == nullptr) {
617 #ifdef __BIONIC__
618         __assert(__FILE__, __LINE__, "mWritePtr is null");
619 #endif
620     }
621 
622     if (resetPointers) {
623         mReadPtr->store(0, std::memory_order_release);
624         mWritePtr->store(0, std::memory_order_release);
625     } else if (flavor != kSynchronizedReadWrite) {
626         // Always reset the read pointer.
627         mReadPtr->store(0, std::memory_order_release);
628     }
629 
630     mRing = reinterpret_cast<uint8_t*>(mapGrantorDescr(hardware::details::DATAPTRPOS));
631     if (mRing == nullptr) {
632 #ifdef __BIONIC__
633         __assert(__FILE__, __LINE__, "mRing is null");
634 #endif
635     }
636 
637     if (mDesc->countGrantors() > hardware::details::EVFLAGWORDPOS) {
638         mEvFlagWord = static_cast<std::atomic<uint32_t>*>(
639                 mapGrantorDescr(hardware::details::EVFLAGWORDPOS));
640         if (mEvFlagWord != nullptr) {
641             android::hardware::EventFlag::createEventFlag(mEvFlagWord, &mEventFlag);
642         } else {
643 #ifdef __BIONIC__
644             __assert(__FILE__, __LINE__, "mEvFlagWord is null");
645 #endif
646         }
647     }
648 }
649 
650 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
MessageQueueBase(const Descriptor & Desc,bool resetPointers)651 MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(const Descriptor& Desc,
652                                                                 bool resetPointers) {
653     mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(Desc));
654     if (mDesc == nullptr) {
655         return;
656     }
657 
658     initMemory(resetPointers);
659 }
660 
661 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
MessageQueueBase(size_t numElementsInQueue,bool configureEventFlagWord,android::base::unique_fd bufferFd,size_t bufferSize)662 MessageQueueBase<MQDescriptorType, T, flavor>::MessageQueueBase(size_t numElementsInQueue,
663                                                                 bool configureEventFlagWord,
664                                                                 android::base::unique_fd bufferFd,
665                                                                 size_t bufferSize) {
666     // Check if the buffer size would not overflow size_t
667     if (numElementsInQueue > SIZE_MAX / sizeof(T)) {
668         hardware::details::logError("Requested message queue size too large. Size of elements: " +
669                                     std::to_string(sizeof(T)) +
670                                     ". Number of elements: " + std::to_string(numElementsInQueue));
671         return;
672     }
673     if (bufferFd != -1 && numElementsInQueue * sizeof(T) > bufferSize) {
674         hardware::details::logError("The supplied buffer size(" + std::to_string(bufferSize) +
675                                     ") is smaller than the required size(" +
676                                     std::to_string(numElementsInQueue * sizeof(T)) + ").");
677         return;
678     }
679     /*
680      * The FMQ needs to allocate memory for the ringbuffer as well as for the
681      * read and write pointer counters. If an EventFlag word is to be configured,
682      * we also need to allocate memory for the same/
683      */
684     size_t kQueueSizeBytes = numElementsInQueue * sizeof(T);
685     size_t kMetaDataSize = 2 * sizeof(android::hardware::details::RingBufferPosition);
686 
687     if (configureEventFlagWord) {
688         kMetaDataSize += sizeof(std::atomic<uint32_t>);
689     }
690 
691     /*
692      * Ashmem memory region size needs to be specified in page-aligned bytes.
693      * kQueueSizeBytes needs to be aligned to word boundary so that all offsets
694      * in the grantorDescriptor will be word aligned.
695      */
696     size_t kAshmemSizePageAligned;
697     if (bufferFd != -1) {
698         // Allocate read counter and write counter only. User-supplied memory will be used for the
699         // ringbuffer.
700         kAshmemSizePageAligned = (kMetaDataSize + PAGE_SIZE - 1) & ~(PAGE_SIZE - 1);
701     } else {
702         // Allocate ringbuffer, read counter and write counter.
703         kAshmemSizePageAligned = (hardware::details::alignToWordBoundary(kQueueSizeBytes) +
704                                   kMetaDataSize + PAGE_SIZE - 1) &
705                                  ~(PAGE_SIZE - 1);
706     }
707 
708     /*
709      * The native handle will contain the fds to be mapped.
710      */
711     int numFds = (bufferFd != -1) ? 2 : 1;
712     native_handle_t* mqHandle = native_handle_create(numFds, 0 /* numInts */);
713     if (mqHandle == nullptr) {
714         return;
715     }
716 
717     /*
718      * Create an ashmem region to map the memory.
719      */
720     int ashmemFd = ashmem_create_region("MessageQueue", kAshmemSizePageAligned);
721     ashmem_set_prot_region(ashmemFd, PROT_READ | PROT_WRITE);
722     mqHandle->data[0] = ashmemFd;
723 
724     if (bufferFd != -1) {
725         // Use user-supplied file descriptor for fdIndex 1
726         mqHandle->data[1] = bufferFd.get();
727         // release ownership of fd. mqHandle owns it now.
728         if (bufferFd.release() < 0) {
729             hardware::details::logError("Error releasing supplied bufferFd");
730         }
731 
732         std::vector<android::hardware::GrantorDescriptor> grantors;
733         grantors.resize(configureEventFlagWord ? hardware::details::kMinGrantorCountForEvFlagSupport
734                                                : hardware::details::kMinGrantorCount);
735 
736         size_t memSize[] = {
737                 sizeof(hardware::details::RingBufferPosition), /* memory to be allocated for read
738                                                                   pointer counter */
739                 sizeof(hardware::details::RingBufferPosition), /* memory to be allocated for write
740                                                                   pointer counter */
741                 kQueueSizeBytes,              /* memory to be allocated for data buffer */
742                 sizeof(std::atomic<uint32_t>) /* memory to be allocated for EventFlag word */
743         };
744 
745         for (size_t grantorPos = 0, offset = 0; grantorPos < grantors.size(); grantorPos++) {
746             uint32_t grantorFdIndex;
747             size_t grantorOffset;
748             if (grantorPos == hardware::details::DATAPTRPOS) {
749                 grantorFdIndex = 1;
750                 grantorOffset = 0;
751             } else {
752                 grantorFdIndex = 0;
753                 grantorOffset = offset;
754                 offset += memSize[grantorPos];
755             }
756             grantors[grantorPos] = {
757                     0 /* grantor flags */, grantorFdIndex,
758                     static_cast<uint32_t>(hardware::details::alignToWordBoundary(grantorOffset)),
759                     memSize[grantorPos]};
760         }
761 
762         mDesc = std::unique_ptr<Descriptor>(new (std::nothrow)
763                                                     Descriptor(grantors, mqHandle, sizeof(T)));
764     } else {
765         mDesc = std::unique_ptr<Descriptor>(new (std::nothrow) Descriptor(
766                 kQueueSizeBytes, mqHandle, sizeof(T), configureEventFlagWord));
767     }
768     if (mDesc == nullptr) {
769         native_handle_close(mqHandle);
770         native_handle_delete(mqHandle);
771         return;
772     }
773     initMemory(true);
774 }
775 
776 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
~MessageQueueBase()777 MessageQueueBase<MQDescriptorType, T, flavor>::~MessageQueueBase() {
778     if (flavor == kUnsynchronizedWrite && mReadPtr != nullptr) {
779         delete mReadPtr;
780     } else if (mReadPtr != nullptr) {
781         unmapGrantorDescr(mReadPtr, hardware::details::READPTRPOS);
782     }
783     if (mWritePtr != nullptr) {
784         unmapGrantorDescr(mWritePtr, hardware::details::WRITEPTRPOS);
785     }
786     if (mRing != nullptr) {
787         unmapGrantorDescr(mRing, hardware::details::DATAPTRPOS);
788     }
789     if (mEvFlagWord != nullptr) {
790         unmapGrantorDescr(mEvFlagWord, hardware::details::EVFLAGWORDPOS);
791         android::hardware::EventFlag::deleteEventFlag(&mEventFlag);
792     }
793 }
794 
795 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
write(const T * data)796 bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data) {
797     return write(data, 1);
798 }
799 
800 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
read(T * data)801 bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data) {
802     return read(data, 1);
803 }
804 
805 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
write(const T * data,size_t nMessages)806 bool MessageQueueBase<MQDescriptorType, T, flavor>::write(const T* data, size_t nMessages) {
807     MemTransaction tx;
808     return beginWrite(nMessages, &tx) && tx.copyTo(data, 0 /* startIdx */, nMessages) &&
809            commitWrite(nMessages);
810 }
811 
812 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
writeBlocking(const T * data,size_t count,uint32_t readNotification,uint32_t writeNotification,int64_t timeOutNanos,android::hardware::EventFlag * evFlag)813 bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(
814         const T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
815         int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
816     static_assert(flavor == kSynchronizedReadWrite,
817                   "writeBlocking can only be used with the "
818                   "kSynchronizedReadWrite flavor.");
819     /*
820      * If evFlag is null and the FMQ does not have its own EventFlag object
821      * return false;
822      * If the flavor is kSynchronizedReadWrite and the readNotification
823      * bit mask is zero return false;
824      * If the count is greater than queue size, return false
825      * to prevent blocking until timeOut.
826      */
827     if (evFlag == nullptr) {
828         evFlag = mEventFlag;
829         if (evFlag == nullptr) {
830             hardware::details::logError(
831                     "writeBlocking failed: called on MessageQueue with no Eventflag"
832                     "configured or provided");
833             return false;
834         }
835     }
836 
837     if (readNotification == 0 || (count > getQuantumCount())) {
838         return false;
839     }
840 
841     /*
842      * There is no need to wait for a readNotification if there is sufficient
843      * space to write is already present in the FMQ. The latter would be the case when
844      * read operations read more number of messages than write operations write.
845      * In other words, a single large read may clear the FMQ after multiple small
846      * writes. This would fail to clear a pending readNotification bit since
847      * EventFlag bits can only be cleared by a wait() call, however the bit would
848      * be correctly cleared by the next writeBlocking() call.
849      */
850 
851     bool result = write(data, count);
852     if (result) {
853         if (writeNotification) {
854             evFlag->wake(writeNotification);
855         }
856         return result;
857     }
858 
859     bool shouldTimeOut = timeOutNanos != 0;
860     int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
861 
862     while (true) {
863         /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
864         if (shouldTimeOut) {
865             /*
866              * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
867              * to Nanoseconds)
868              */
869             int64_t currentTimeNs = android::elapsedRealtimeNano();
870             /*
871              * Decrement 'timeOutNanos' to account for the time taken to complete the last
872              * iteration of the while loop.
873              */
874             timeOutNanos -= currentTimeNs - prevTimeNanos;
875             prevTimeNanos = currentTimeNs;
876 
877             if (timeOutNanos <= 0) {
878                 /*
879                  * Attempt write in case a context switch happened outside of
880                  * evFlag->wait().
881                  */
882                 result = write(data, count);
883                 break;
884             }
885         }
886 
887         /*
888          * wait() will return immediately if there was a pending read
889          * notification.
890          */
891         uint32_t efState = 0;
892         status_t status = evFlag->wait(readNotification, &efState, timeOutNanos,
893                                        true /* retry on spurious wake */);
894 
895         if (status != android::TIMED_OUT && status != android::NO_ERROR) {
896             hardware::details::logError("Unexpected error code from EventFlag Wait status " +
897                                         std::to_string(status));
898             break;
899         }
900 
901         if (status == android::TIMED_OUT) {
902             break;
903         }
904 
905         /*
906          * If there is still insufficient space to write to the FMQ,
907          * keep waiting for another readNotification.
908          */
909         if ((efState & readNotification) && write(data, count)) {
910             result = true;
911             break;
912         }
913     }
914 
915     if (result && writeNotification != 0) {
916         evFlag->wake(writeNotification);
917     }
918 
919     return result;
920 }
921 
922 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
writeBlocking(const T * data,size_t count,int64_t timeOutNanos)923 bool MessageQueueBase<MQDescriptorType, T, flavor>::writeBlocking(const T* data, size_t count,
924                                                                   int64_t timeOutNanos) {
925     return writeBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
926 }
927 
928 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
readBlocking(T * data,size_t count,uint32_t readNotification,uint32_t writeNotification,int64_t timeOutNanos,android::hardware::EventFlag * evFlag)929 bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(
930         T* data, size_t count, uint32_t readNotification, uint32_t writeNotification,
931         int64_t timeOutNanos, android::hardware::EventFlag* evFlag) {
932     static_assert(flavor == kSynchronizedReadWrite,
933                   "readBlocking can only be used with the "
934                   "kSynchronizedReadWrite flavor.");
935 
936     /*
937      * If evFlag is null and the FMQ does not own its own EventFlag object
938      * return false;
939      * If the writeNotification bit mask is zero return false;
940      * If the count is greater than queue size, return false to prevent
941      * blocking until timeOut.
942      */
943     if (evFlag == nullptr) {
944         evFlag = mEventFlag;
945         if (evFlag == nullptr) {
946             hardware::details::logError(
947                     "readBlocking failed: called on MessageQueue with no Eventflag"
948                     "configured or provided");
949             return false;
950         }
951     }
952 
953     if (writeNotification == 0 || count > getQuantumCount()) {
954         return false;
955     }
956 
957     /*
958      * There is no need to wait for a write notification if sufficient
959      * data to read is already present in the FMQ. This would be the
960      * case when read operations read lesser number of messages than
961      * a write operation and multiple reads would be required to clear the queue
962      * after a single write operation. This check would fail to clear a pending
963      * writeNotification bit since EventFlag bits can only be cleared
964      * by a wait() call, however the bit would be correctly cleared by the next
965      * readBlocking() call.
966      */
967 
968     bool result = read(data, count);
969     if (result) {
970         if (readNotification) {
971             evFlag->wake(readNotification);
972         }
973         return result;
974     }
975 
976     bool shouldTimeOut = timeOutNanos != 0;
977     int64_t prevTimeNanos = shouldTimeOut ? android::elapsedRealtimeNano() : 0;
978 
979     while (true) {
980         /* It is not required to adjust 'timeOutNanos' if 'shouldTimeOut' is false */
981         if (shouldTimeOut) {
982             /*
983              * The current time and 'prevTimeNanos' are both CLOCK_BOOTTIME clock values(converted
984              * to Nanoseconds)
985              */
986             int64_t currentTimeNs = android::elapsedRealtimeNano();
987             /*
988              * Decrement 'timeOutNanos' to account for the time taken to complete the last
989              * iteration of the while loop.
990              */
991             timeOutNanos -= currentTimeNs - prevTimeNanos;
992             prevTimeNanos = currentTimeNs;
993 
994             if (timeOutNanos <= 0) {
995                 /*
996                  * Attempt read in case a context switch happened outside of
997                  * evFlag->wait().
998                  */
999                 result = read(data, count);
1000                 break;
1001             }
1002         }
1003 
1004         /*
1005          * wait() will return immediately if there was a pending write
1006          * notification.
1007          */
1008         uint32_t efState = 0;
1009         status_t status = evFlag->wait(writeNotification, &efState, timeOutNanos,
1010                                        true /* retry on spurious wake */);
1011 
1012         if (status != android::TIMED_OUT && status != android::NO_ERROR) {
1013             hardware::details::logError("Unexpected error code from EventFlag Wait status " +
1014                                         std::to_string(status));
1015             break;
1016         }
1017 
1018         if (status == android::TIMED_OUT) {
1019             break;
1020         }
1021 
1022         /*
1023          * If the data in FMQ is still insufficient, go back to waiting
1024          * for another write notification.
1025          */
1026         if ((efState & writeNotification) && read(data, count)) {
1027             result = true;
1028             break;
1029         }
1030     }
1031 
1032     if (result && readNotification != 0) {
1033         evFlag->wake(readNotification);
1034     }
1035     return result;
1036 }
1037 
1038 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
readBlocking(T * data,size_t count,int64_t timeOutNanos)1039 bool MessageQueueBase<MQDescriptorType, T, flavor>::readBlocking(T* data, size_t count,
1040                                                                  int64_t timeOutNanos) {
1041     return readBlocking(data, count, FMQ_NOT_FULL, FMQ_NOT_EMPTY, timeOutNanos);
1042 }
1043 
1044 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
availableToWriteBytes()1045 size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWriteBytes() const {
1046     return mDesc->getSize() - availableToReadBytes();
1047 }
1048 
1049 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
availableToWrite()1050 size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToWrite() const {
1051     return availableToWriteBytes() / sizeof(T);
1052 }
1053 
1054 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
availableToRead()1055 size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToRead() const {
1056     return availableToReadBytes() / sizeof(T);
1057 }
1058 
1059 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
beginWrite(size_t nMessages,MemTransaction * result)1060 bool MessageQueueBase<MQDescriptorType, T, flavor>::beginWrite(size_t nMessages,
1061                                                                MemTransaction* result) const {
1062     /*
1063      * If nMessages is greater than size of FMQ or in case of the synchronized
1064      * FMQ flavor, if there is not enough space to write nMessages, then return
1065      * result with null addresses.
1066      */
1067     if ((flavor == kSynchronizedReadWrite && (availableToWrite() < nMessages)) ||
1068         nMessages > getQuantumCount()) {
1069         *result = MemTransaction();
1070         return false;
1071     }
1072 
1073     auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1074     if (writePtr % sizeof(T) != 0) {
1075         hardware::details::logError(
1076                 "The write pointer has become misaligned. Writing to the queue is no longer "
1077                 "possible.");
1078         hardware::details::errorWriteLog(0x534e4554, "184963385");
1079         return false;
1080     }
1081     size_t writeOffset = writePtr % mDesc->getSize();
1082 
1083     /*
1084      * From writeOffset, the number of messages that can be written
1085      * contiguously without wrapping around the ring buffer are calculated.
1086      */
1087     size_t contiguousMessages = (mDesc->getSize() - writeOffset) / sizeof(T);
1088 
1089     if (contiguousMessages < nMessages) {
1090         /*
1091          * Wrap around is required. Both result.first and result.second are
1092          * populated.
1093          */
1094         *result = MemTransaction(
1095                 MemRegion(reinterpret_cast<T*>(mRing + writeOffset), contiguousMessages),
1096                 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
1097     } else {
1098         /*
1099          * A wrap around is not required to write nMessages. Only result.first
1100          * is populated.
1101          */
1102         *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + writeOffset), nMessages),
1103                                  MemRegion());
1104     }
1105 
1106     return true;
1107 }
1108 
1109 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
1110 /*
1111  * Disable integer sanitization since integer overflow here is allowed
1112  * and legal.
1113  */
1114 __attribute__((no_sanitize("integer"))) bool
commitWrite(size_t nMessages)1115 MessageQueueBase<MQDescriptorType, T, flavor>::commitWrite(size_t nMessages) {
1116     size_t nBytesWritten = nMessages * sizeof(T);
1117     auto writePtr = mWritePtr->load(std::memory_order_relaxed);
1118     writePtr += nBytesWritten;
1119     mWritePtr->store(writePtr, std::memory_order_release);
1120     /*
1121      * This method cannot fail now since we are only incrementing the writePtr
1122      * counter.
1123      */
1124     return true;
1125 }
1126 
1127 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
availableToReadBytes()1128 size_t MessageQueueBase<MQDescriptorType, T, flavor>::availableToReadBytes() const {
1129     /*
1130      * This method is invoked by implementations of both read() and write() and
1131      * hence requires a memory_order_acquired load for both mReadPtr and
1132      * mWritePtr.
1133      */
1134     return mWritePtr->load(std::memory_order_acquire) - mReadPtr->load(std::memory_order_acquire);
1135 }
1136 
1137 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
read(T * data,size_t nMessages)1138 bool MessageQueueBase<MQDescriptorType, T, flavor>::read(T* data, size_t nMessages) {
1139     MemTransaction tx;
1140     return beginRead(nMessages, &tx) && tx.copyFrom(data, 0 /* startIdx */, nMessages) &&
1141            commitRead(nMessages);
1142 }
1143 
1144 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
1145 /*
1146  * Disable integer sanitization since integer overflow here is allowed
1147  * and legal.
1148  */
1149 __attribute__((no_sanitize("integer"))) bool
beginRead(size_t nMessages,MemTransaction * result)1150 MessageQueueBase<MQDescriptorType, T, flavor>::beginRead(size_t nMessages,
1151                                                          MemTransaction* result) const {
1152     *result = MemTransaction();
1153     /*
1154      * If it is detected that the data in the queue was overwritten
1155      * due to the reader process being too slow, the read pointer counter
1156      * is set to the same as the write pointer counter to indicate error
1157      * and the read returns false;
1158      * Need acquire/release memory ordering for mWritePtr.
1159      */
1160     auto writePtr = mWritePtr->load(std::memory_order_acquire);
1161     /*
1162      * A relaxed load is sufficient for mReadPtr since there will be no
1163      * stores to mReadPtr from a different thread.
1164      */
1165     auto readPtr = mReadPtr->load(std::memory_order_relaxed);
1166     if (writePtr % sizeof(T) != 0 || readPtr % sizeof(T) != 0) {
1167         hardware::details::logError(
1168                 "The write or read pointer has become misaligned. Reading from the queue is no "
1169                 "longer possible.");
1170         hardware::details::errorWriteLog(0x534e4554, "184963385");
1171         return false;
1172     }
1173 
1174     if (writePtr - readPtr > mDesc->getSize()) {
1175         mReadPtr->store(writePtr, std::memory_order_release);
1176         return false;
1177     }
1178 
1179     size_t nBytesDesired = nMessages * sizeof(T);
1180     /*
1181      * Return if insufficient data to read in FMQ.
1182      */
1183     if (writePtr - readPtr < nBytesDesired) {
1184         return false;
1185     }
1186 
1187     size_t readOffset = readPtr % mDesc->getSize();
1188     /*
1189      * From readOffset, the number of messages that can be read contiguously
1190      * without wrapping around the ring buffer are calculated.
1191      */
1192     size_t contiguousMessages = (mDesc->getSize() - readOffset) / sizeof(T);
1193 
1194     if (contiguousMessages < nMessages) {
1195         /*
1196          * A wrap around is required. Both result.first and result.second
1197          * are populated.
1198          */
1199         *result = MemTransaction(
1200                 MemRegion(reinterpret_cast<T*>(mRing + readOffset), contiguousMessages),
1201                 MemRegion(reinterpret_cast<T*>(mRing), nMessages - contiguousMessages));
1202     } else {
1203         /*
1204          * A wrap around is not required. Only result.first need to be
1205          * populated.
1206          */
1207         *result = MemTransaction(MemRegion(reinterpret_cast<T*>(mRing + readOffset), nMessages),
1208                                  MemRegion());
1209     }
1210 
1211     return true;
1212 }
1213 
1214 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
1215 /*
1216  * Disable integer sanitization since integer overflow here is allowed
1217  * and legal.
1218  */
1219 __attribute__((no_sanitize("integer"))) bool
commitRead(size_t nMessages)1220 MessageQueueBase<MQDescriptorType, T, flavor>::commitRead(size_t nMessages) {
1221     // TODO: Use a local copy of readPtr to avoid relazed mReadPtr loads.
1222     auto readPtr = mReadPtr->load(std::memory_order_relaxed);
1223     auto writePtr = mWritePtr->load(std::memory_order_acquire);
1224     /*
1225      * If the flavor is unsynchronized, it is possible that a write overflow may
1226      * have occurred between beginRead() and commitRead().
1227      */
1228     if (writePtr - readPtr > mDesc->getSize()) {
1229         mReadPtr->store(writePtr, std::memory_order_release);
1230         return false;
1231     }
1232 
1233     size_t nBytesRead = nMessages * sizeof(T);
1234     readPtr += nBytesRead;
1235     mReadPtr->store(readPtr, std::memory_order_release);
1236     return true;
1237 }
1238 
1239 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
getQuantumSize()1240 size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumSize() const {
1241     return mDesc->getQuantum();
1242 }
1243 
1244 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
getQuantumCount()1245 size_t MessageQueueBase<MQDescriptorType, T, flavor>::getQuantumCount() const {
1246     return mDesc->getSize() / mDesc->getQuantum();
1247 }
1248 
1249 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
isValid()1250 bool MessageQueueBase<MQDescriptorType, T, flavor>::isValid() const {
1251     return mRing != nullptr && mReadPtr != nullptr && mWritePtr != nullptr;
1252 }
1253 
1254 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
mapGrantorDescr(uint32_t grantorIdx)1255 void* MessageQueueBase<MQDescriptorType, T, flavor>::mapGrantorDescr(uint32_t grantorIdx) {
1256     const native_handle_t* handle = mDesc->handle();
1257     auto grantors = mDesc->grantors();
1258     if (handle == nullptr) {
1259         hardware::details::logError("mDesc->handle is null");
1260         return nullptr;
1261     }
1262 
1263     if (grantorIdx >= grantors.size()) {
1264         hardware::details::logError(std::string("grantorIdx must be less than ") +
1265                                     std::to_string(grantors.size()));
1266         return nullptr;
1267     }
1268 
1269     int fdIndex = grantors[grantorIdx].fdIndex;
1270     /*
1271      * Offset for mmap must be a multiple of PAGE_SIZE.
1272      */
1273     int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
1274     int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
1275 
1276     void* address = mmap(0, mapLength, PROT_READ | PROT_WRITE, MAP_SHARED, handle->data[fdIndex],
1277                          mapOffset);
1278     if (address == MAP_FAILED) {
1279         hardware::details::logError(std::string("mmap failed: ") + std::to_string(errno));
1280         return nullptr;
1281     }
1282     return reinterpret_cast<uint8_t*>(address) + (grantors[grantorIdx].offset - mapOffset);
1283 }
1284 
1285 template <template <typename, MQFlavor> typename MQDescriptorType, typename T, MQFlavor flavor>
unmapGrantorDescr(void * address,uint32_t grantorIdx)1286 void MessageQueueBase<MQDescriptorType, T, flavor>::unmapGrantorDescr(void* address,
1287                                                                       uint32_t grantorIdx) {
1288     auto grantors = mDesc->grantors();
1289     if ((address == nullptr) || (grantorIdx >= grantors.size())) {
1290         return;
1291     }
1292 
1293     int mapOffset = (grantors[grantorIdx].offset / PAGE_SIZE) * PAGE_SIZE;
1294     int mapLength = grantors[grantorIdx].offset - mapOffset + grantors[grantorIdx].extent;
1295     void* baseAddress =
1296             reinterpret_cast<uint8_t*>(address) - (grantors[grantorIdx].offset - mapOffset);
1297     if (baseAddress) munmap(baseAddress, mapLength);
1298 }
1299 
1300 }  // namespace hardware
1301