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 #ifndef _FMSGQ_DESCRIPTOR_H
18 #define _FMSGQ_DESCRIPTOR_H
19 
20 #include <unistd.h>
21 
22 #include <cutils/native_handle.h>
23 #include <hidl/HidlInternal.h>
24 #include <hidl/HidlSupport.h>
25 
26 namespace android {
27 namespace hardware {
28 
29 typedef uint64_t RingBufferPosition;
30 
31 struct GrantorDescriptor {
32     uint32_t flags __attribute__ ((aligned(4)));
33     uint32_t fdIndex __attribute__ ((aligned(4)));
34     uint32_t offset __attribute__ ((aligned(4)));
35     uint64_t extent __attribute__ ((aligned(8)));
36 };
37 
38 static_assert(offsetof(GrantorDescriptor, flags) == 0, "wrong offset");
39 static_assert(offsetof(GrantorDescriptor, fdIndex) == 4, "wrong offset");
40 static_assert(offsetof(GrantorDescriptor, offset) == 8, "wrong offset");
41 static_assert(offsetof(GrantorDescriptor, extent) == 16, "wrong offset");
42 static_assert(sizeof(GrantorDescriptor) == 24, "wrong size");
43 static_assert(__alignof(GrantorDescriptor) == 8, "wrong alignment");
44 
45 enum MQFlavor : uint32_t {
46   /*
47    * kSynchronizedReadWrite represents the wait-free synchronized flavor of the
48    * FMQ. It is intended to be have a single reader and single writer.
49    * Attempts to overflow/underflow returns a failure.
50    */
51   kSynchronizedReadWrite = 0x01,
52   /*
53    * kUnsynchronizedWrite represents the flavor of FMQ where writes always
54    * succeed. This flavor allows one writer and many readers. A read operation
55    * can detect an overwrite and reset the read counter.
56    */
57   kUnsynchronizedWrite = 0x02
58 };
59 
60 template <typename T, MQFlavor flavor>
61 struct MQDescriptor {
62     // Takes ownership of handle
63     MQDescriptor(
64             const std::vector<GrantorDescriptor>& grantors,
65             native_handle_t* nHandle, size_t size);
66 
67     // Takes ownership of handle
68     MQDescriptor(size_t bufferSize, native_handle_t* nHandle,
69                  size_t messageSize, bool configureEventFlag = false);
70 
71     MQDescriptor();
72     ~MQDescriptor();
73 
MQDescriptorMQDescriptor74     explicit MQDescriptor(const MQDescriptor& other) : MQDescriptor() { *this = other; }
75     MQDescriptor& operator=(const MQDescriptor& other);
76 
77     size_t getSize() const;
78 
79     size_t getQuantum() const;
80 
81     int32_t getFlags() const;
82 
isHandleValidMQDescriptor83     bool isHandleValid() const { return mHandle != nullptr; }
countGrantorsMQDescriptor84     size_t countGrantors() const { return mGrantors.size(); }
85 
grantorsMQDescriptor86     inline const ::android::hardware::hidl_vec<GrantorDescriptor> &grantors() const {
87         return mGrantors;
88     }
89 
grantorsMQDescriptor90     inline ::android::hardware::hidl_vec<GrantorDescriptor> &grantors() {
91         return mGrantors;
92     }
93 
handleMQDescriptor94     inline const ::native_handle_t *handle() const {
95         return mHandle;
96     }
97 
handleMQDescriptor98     inline ::native_handle_t *handle() {
99         return mHandle;
100     }
101 
102     static const size_t kOffsetOfGrantors;
103     static const size_t kOffsetOfHandle;
104     enum GrantorType : int { READPTRPOS = 0, WRITEPTRPOS, DATAPTRPOS, EVFLAGWORDPOS };
105 
106     /*
107      * There should at least be GrantorDescriptors for the read counter, write
108      * counter and data buffer. A GrantorDescriptor for an EventFlag word is
109      * not required if there is no need for blocking FMQ operations.
110      */
111     static constexpr int32_t kMinGrantorCount = DATAPTRPOS + 1;
112 
113     /*
114      * Minimum number of GrantorDescriptors required if EventFlag support is
115      * needed for blocking FMQ operations.
116      */
117     static constexpr int32_t kMinGrantorCountForEvFlagSupport = EVFLAGWORDPOS + 1;
118 
119     //TODO(b/34160777) Identify a better solution that supports remoting.
alignToWordBoundaryMQDescriptor120     static inline size_t alignToWordBoundary(size_t length) {
121         constexpr size_t kAlignmentSize = 64;
122         if (kAlignmentSize % __WORDSIZE != 0) {
123             details::logAlwaysFatal("Incompatible word size");
124         }
125 
126         /*
127          * Check if alignment to word boundary would cause an overflow.
128          */
129         if (length > SIZE_MAX - kAlignmentSize/8 + 1) {
130             details::logAlwaysFatal("Queue size too large");
131         }
132 
133         return (length + kAlignmentSize/8 - 1) & ~(kAlignmentSize/8 - 1U);
134     }
135 
isAlignedToWordBoundaryMQDescriptor136     static inline size_t isAlignedToWordBoundary(size_t offset) {
137         constexpr size_t kAlignmentSize = 64;
138         return (offset & (kAlignmentSize/8 - 1)) == 0;
139     }
140 private:
141     ::android::hardware::hidl_vec<GrantorDescriptor> mGrantors;
142     ::android::hardware::details::hidl_pointer<native_handle_t> mHandle;
143     uint32_t mQuantum;
144     uint32_t mFlags;
145 };
146 
147 template<typename T, MQFlavor flavor>
148 const size_t MQDescriptor<T, flavor>::kOffsetOfGrantors = offsetof(MQDescriptor, mGrantors);
149 
150 template<typename T, MQFlavor flavor>
151 const size_t MQDescriptor<T, flavor>::kOffsetOfHandle = offsetof(MQDescriptor, mHandle);
152 
153 /*
154  * MQDescriptorSync will describe the wait-free synchronized
155  * flavor of FMQ.
156  */
157 template<typename T>
158 using MQDescriptorSync = MQDescriptor<T, kSynchronizedReadWrite>;
159 
160 /*
161  * MQDescriptorUnsync will describe the unsynchronized write
162  * flavor of FMQ.
163  */
164 template<typename T>
165 using MQDescriptorUnsync = MQDescriptor<T, kUnsynchronizedWrite>;
166 
167 template <typename T, MQFlavor flavor>
MQDescriptor(const std::vector<GrantorDescriptor> & grantors,native_handle_t * nhandle,size_t size)168 MQDescriptor<T, flavor>::MQDescriptor(const std::vector<GrantorDescriptor>& grantors,
169                                       native_handle_t* nhandle, size_t size)
170     : mHandle(nhandle), mQuantum(static_cast<uint32_t>(size)), mFlags(flavor) {
171     mGrantors.resize(grantors.size());
172     for (size_t i = 0; i < grantors.size(); ++i) {
173         if (isAlignedToWordBoundary(grantors[i].offset) == false) {
174             details::logAlwaysFatal("Grantor offsets need to be aligned");
175         }
176         mGrantors[i] = grantors[i];
177     }
178 }
179 
180 template <typename T, MQFlavor flavor>
MQDescriptor(size_t bufferSize,native_handle_t * nHandle,size_t messageSize,bool configureEventFlag)181 MQDescriptor<T, flavor>::MQDescriptor(size_t bufferSize, native_handle_t* nHandle,
182                                       size_t messageSize, bool configureEventFlag)
183     : mHandle(nHandle), mQuantum(static_cast<uint32_t>(messageSize)), mFlags(flavor) {
184     /*
185      * If configureEventFlag is true, allocate an additional spot in mGrantor
186      * for containing the fd and offset for mmapping the EventFlag word.
187      */
188     mGrantors.resize(configureEventFlag? kMinGrantorCountForEvFlagSupport : kMinGrantorCount);
189 
190     size_t memSize[] = {
191         sizeof(RingBufferPosition),  /* memory to be allocated for read pointer counter */
192         sizeof(RingBufferPosition),  /* memory to be allocated for write pointer counter */
193         bufferSize,                  /* memory to be allocated for data buffer */
194         sizeof(std::atomic<uint32_t>)/* memory to be allocated for EventFlag word */
195     };
196 
197     /*
198      * Create a default grantor descriptor for read, write pointers and
199      * the data buffer. fdIndex parameter is set to 0 by default and
200      * the offset for each grantor is contiguous.
201      */
202     for (size_t grantorPos = 0, offset = 0;
203          grantorPos < mGrantors.size();
204          offset += memSize[grantorPos++]) {
205         mGrantors[grantorPos] = {
206             0 /* grantor flags */,
207             0 /* fdIndex */,
208             static_cast<uint32_t>(alignToWordBoundary(offset)),
209             memSize[grantorPos]
210         };
211     }
212 }
213 
214 template <typename T, MQFlavor flavor>
215 MQDescriptor<T, flavor>& MQDescriptor<T, flavor>::operator=(const MQDescriptor& other) {
216     mGrantors = other.mGrantors;
217     if (mHandle != nullptr) {
218         native_handle_close(mHandle);
219         native_handle_delete(mHandle);
220         mHandle = nullptr;
221     }
222     mQuantum = other.mQuantum;
223     mFlags = other.mFlags;
224 
225     if (other.mHandle != nullptr) {
226         mHandle = native_handle_create(
227                 other.mHandle->numFds, other.mHandle->numInts);
228 
229         for (int i = 0; i < other.mHandle->numFds; ++i) {
230             mHandle->data[i] = dup(other.mHandle->data[i]);
231         }
232 
233         memcpy(&mHandle->data[other.mHandle->numFds], &other.mHandle->data[other.mHandle->numFds],
234                static_cast<size_t>(other.mHandle->numInts) * sizeof(int));
235     }
236 
237     return *this;
238 }
239 
240 template<typename T, MQFlavor flavor>
MQDescriptor()241 MQDescriptor<T, flavor>::MQDescriptor() : MQDescriptor(
242         std::vector<android::hardware::GrantorDescriptor>(),
243         nullptr /* nHandle */,
244         0 /* size */) {}
245 
246 template<typename T, MQFlavor flavor>
~MQDescriptor()247 MQDescriptor<T, flavor>::~MQDescriptor() {
248     if (mHandle != nullptr) {
249         native_handle_close(mHandle);
250         native_handle_delete(mHandle);
251     }
252 }
253 
254 template<typename T, MQFlavor flavor>
getSize()255 size_t MQDescriptor<T, flavor>::getSize() const {
256     return static_cast<size_t>(mGrantors[DATAPTRPOS].extent);
257 }
258 
259 template<typename T, MQFlavor flavor>
getQuantum()260 size_t MQDescriptor<T, flavor>::getQuantum() const { return mQuantum; }
261 
262 template<typename T, MQFlavor flavor>
getFlags()263 int32_t MQDescriptor<T, flavor>::getFlags() const { return mFlags; }
264 
265 template<typename T, MQFlavor flavor>
toString(const MQDescriptor<T,flavor> & q)266 std::string toString(const MQDescriptor<T, flavor> &q) {
267     std::string os;
268     if (flavor & kSynchronizedReadWrite) {
269         os += "fmq_sync";
270     }
271     if (flavor & kUnsynchronizedWrite) {
272         os += "fmq_unsync";
273     }
274     os += " {"
275        + toString(q.grantors().size()) + " grantor(s), "
276        + "size = " + toString(q.getSize())
277        + ", .handle = " + toString(q.handle())
278        + ", .quantum = " + toString(q.getQuantum()) + "}";
279     return os;
280 }
281 
282 }  // namespace hardware
283 }  // namespace android
284 
285 #endif  // FMSGQ_DESCRIPTOR_H
286