blob: c4c096da2ddb9edafe2b89b1bfb07b9c75d6ac72 [file] [log] [blame]
Michael Butler8fc48962021-01-08 17:21:27 -08001/*
2 * Copyright (C) 2019 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
Michael Butler137ee992021-11-01 16:40:31 -070017#include "BurstUtils.h"
Michael Butler8fc48962021-01-08 17:21:27 -080018
19#include <android-base/logging.h>
Michael Butler76e491f2020-12-19 01:55:32 -080020#include <android-base/properties.h>
Michael Butler8fc48962021-01-08 17:21:27 -080021#include <android/hardware/neuralnetworks/1.0/types.h>
22#include <android/hardware/neuralnetworks/1.1/types.h>
23#include <android/hardware/neuralnetworks/1.2/types.h>
24#include <fmq/MessageQueue.h>
25#include <hidl/MQDescriptor.h>
Michael Butler76e491f2020-12-19 01:55:32 -080026#include <nnapi/Result.h>
27#include <nnapi/Types.h>
Michael Butlere8645c32021-10-15 18:42:32 -070028#include <nnapi/hal/1.0/ProtectCallback.h>
Michael Butler8fc48962021-01-08 17:21:27 -080029
30#include <atomic>
31#include <chrono>
32#include <memory>
33#include <thread>
34#include <tuple>
35#include <utility>
36#include <vector>
37
38namespace android::hardware::neuralnetworks::V1_2::utils {
39namespace {
40
41constexpr V1_2::Timing kNoTiming = {std::numeric_limits<uint64_t>::max(),
42 std::numeric_limits<uint64_t>::max()};
43
Michael Butler76e491f2020-12-19 01:55:32 -080044std::chrono::microseconds getPollingTimeWindow(const std::string& property) {
45 constexpr int32_t kDefaultPollingTimeWindow = 0;
46#ifdef NN_DEBUGGABLE
47 constexpr int32_t kMinPollingTimeWindow = 0;
48 const int32_t selectedPollingTimeWindow =
49 base::GetIntProperty(property, kDefaultPollingTimeWindow, kMinPollingTimeWindow);
50 return std::chrono::microseconds(selectedPollingTimeWindow);
51#else
52 (void)property;
53 return std::chrono::microseconds(kDefaultPollingTimeWindow);
54#endif // NN_DEBUGGABLE
55}
56
57} // namespace
58
59std::chrono::microseconds getBurstControllerPollingTimeWindow() {
60 return getPollingTimeWindow("debug.nn.burst-controller-polling-window");
61}
62
63std::chrono::microseconds getBurstServerPollingTimeWindow() {
64 return getPollingTimeWindow("debug.nn.burst-server-polling-window");
Michael Butler8fc48962021-01-08 17:21:27 -080065}
66
67// serialize a request into a packet
68std::vector<FmqRequestDatum> serialize(const V1_0::Request& request, V1_2::MeasureTiming measure,
69 const std::vector<int32_t>& slots) {
70 // count how many elements need to be sent for a request
Michael Butler76e491f2020-12-19 01:55:32 -080071 size_t count = 2 + request.inputs.size() + request.outputs.size() + slots.size();
Michael Butler8fc48962021-01-08 17:21:27 -080072 for (const auto& input : request.inputs) {
73 count += input.dimensions.size();
74 }
75 for (const auto& output : request.outputs) {
76 count += output.dimensions.size();
77 }
Michael Butler76e491f2020-12-19 01:55:32 -080078 CHECK_LE(count, std::numeric_limits<uint32_t>::max());
Michael Butler8fc48962021-01-08 17:21:27 -080079
80 // create buffer to temporarily store elements
81 std::vector<FmqRequestDatum> data;
82 data.reserve(count);
83
84 // package packetInfo
Michael Butler76e491f2020-12-19 01:55:32 -080085 data.emplace_back();
86 data.back().packetInformation(
87 {.packetSize = static_cast<uint32_t>(count),
88 .numberOfInputOperands = static_cast<uint32_t>(request.inputs.size()),
89 .numberOfOutputOperands = static_cast<uint32_t>(request.outputs.size()),
90 .numberOfPools = static_cast<uint32_t>(slots.size())});
Michael Butler8fc48962021-01-08 17:21:27 -080091
92 // package input data
93 for (const auto& input : request.inputs) {
94 // package operand information
Michael Butler76e491f2020-12-19 01:55:32 -080095 data.emplace_back();
96 data.back().inputOperandInformation(
97 {.hasNoValue = input.hasNoValue,
98 .location = input.location,
99 .numberOfDimensions = static_cast<uint32_t>(input.dimensions.size())});
Michael Butler8fc48962021-01-08 17:21:27 -0800100
101 // package operand dimensions
102 for (uint32_t dimension : input.dimensions) {
Michael Butler76e491f2020-12-19 01:55:32 -0800103 data.emplace_back();
104 data.back().inputOperandDimensionValue(dimension);
Michael Butler8fc48962021-01-08 17:21:27 -0800105 }
106 }
107
108 // package output data
109 for (const auto& output : request.outputs) {
110 // package operand information
Michael Butler76e491f2020-12-19 01:55:32 -0800111 data.emplace_back();
112 data.back().outputOperandInformation(
113 {.hasNoValue = output.hasNoValue,
114 .location = output.location,
115 .numberOfDimensions = static_cast<uint32_t>(output.dimensions.size())});
Michael Butler8fc48962021-01-08 17:21:27 -0800116
117 // package operand dimensions
118 for (uint32_t dimension : output.dimensions) {
Michael Butler76e491f2020-12-19 01:55:32 -0800119 data.emplace_back();
120 data.back().outputOperandDimensionValue(dimension);
Michael Butler8fc48962021-01-08 17:21:27 -0800121 }
122 }
123
124 // package pool identifier
125 for (int32_t slot : slots) {
Michael Butler76e491f2020-12-19 01:55:32 -0800126 data.emplace_back();
127 data.back().poolIdentifier(slot);
Michael Butler8fc48962021-01-08 17:21:27 -0800128 }
129
130 // package measureTiming
Michael Butler76e491f2020-12-19 01:55:32 -0800131 data.emplace_back();
132 data.back().measureTiming(measure);
133
134 CHECK_EQ(data.size(), count);
Michael Butler8fc48962021-01-08 17:21:27 -0800135
136 // return packet
137 return data;
138}
139
140// serialize result
141std::vector<FmqResultDatum> serialize(V1_0::ErrorStatus errorStatus,
142 const std::vector<V1_2::OutputShape>& outputShapes,
143 V1_2::Timing timing) {
144 // count how many elements need to be sent for a request
145 size_t count = 2 + outputShapes.size();
146 for (const auto& outputShape : outputShapes) {
147 count += outputShape.dimensions.size();
148 }
149
150 // create buffer to temporarily store elements
151 std::vector<FmqResultDatum> data;
152 data.reserve(count);
153
154 // package packetInfo
Michael Butler76e491f2020-12-19 01:55:32 -0800155 data.emplace_back();
156 data.back().packetInformation({.packetSize = static_cast<uint32_t>(count),
157 .errorStatus = errorStatus,
158 .numberOfOperands = static_cast<uint32_t>(outputShapes.size())});
Michael Butler8fc48962021-01-08 17:21:27 -0800159
160 // package output shape data
161 for (const auto& operand : outputShapes) {
162 // package operand information
Michael Butler76e491f2020-12-19 01:55:32 -0800163 data.emplace_back();
164 data.back().operandInformation(
165 {.isSufficient = operand.isSufficient,
166 .numberOfDimensions = static_cast<uint32_t>(operand.dimensions.size())});
Michael Butler8fc48962021-01-08 17:21:27 -0800167
168 // package operand dimensions
169 for (uint32_t dimension : operand.dimensions) {
Michael Butler76e491f2020-12-19 01:55:32 -0800170 data.emplace_back();
171 data.back().operandDimensionValue(dimension);
Michael Butler8fc48962021-01-08 17:21:27 -0800172 }
173 }
174
175 // package executionTiming
Michael Butler76e491f2020-12-19 01:55:32 -0800176 data.emplace_back();
177 data.back().executionTiming(timing);
178
179 CHECK_EQ(data.size(), count);
Michael Butler8fc48962021-01-08 17:21:27 -0800180
181 // return result
182 return data;
183}
184
185// deserialize request
Michael Butler76e491f2020-12-19 01:55:32 -0800186nn::Result<std::tuple<V1_0::Request, std::vector<int32_t>, V1_2::MeasureTiming>> deserialize(
Michael Butler8fc48962021-01-08 17:21:27 -0800187 const std::vector<FmqRequestDatum>& data) {
188 using discriminator = FmqRequestDatum::hidl_discriminator;
189
190 size_t index = 0;
191
192 // validate packet information
Michael Butler611648f2022-11-14 19:00:25 -0800193 if (index >= data.size() ||
194 data.at(index).getDiscriminator() != discriminator::packetInformation) {
Michael Butler76e491f2020-12-19 01:55:32 -0800195 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800196 }
197
198 // unpackage packet information
Michael Butler611648f2022-11-14 19:00:25 -0800199 const FmqRequestDatum::PacketInformation& packetInfo = data.at(index).packetInformation();
Michael Butler8fc48962021-01-08 17:21:27 -0800200 index++;
201 const uint32_t packetSize = packetInfo.packetSize;
202 const uint32_t numberOfInputOperands = packetInfo.numberOfInputOperands;
203 const uint32_t numberOfOutputOperands = packetInfo.numberOfOutputOperands;
204 const uint32_t numberOfPools = packetInfo.numberOfPools;
205
206 // verify packet size
207 if (data.size() != packetSize) {
Michael Butler76e491f2020-12-19 01:55:32 -0800208 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800209 }
210
211 // unpackage input operands
212 std::vector<V1_0::RequestArgument> inputs;
213 inputs.reserve(numberOfInputOperands);
214 for (size_t operand = 0; operand < numberOfInputOperands; ++operand) {
215 // validate input operand information
Michael Butler611648f2022-11-14 19:00:25 -0800216 if (index >= data.size() ||
217 data.at(index).getDiscriminator() != discriminator::inputOperandInformation) {
Michael Butler76e491f2020-12-19 01:55:32 -0800218 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800219 }
220
221 // unpackage operand information
222 const FmqRequestDatum::OperandInformation& operandInfo =
Michael Butler611648f2022-11-14 19:00:25 -0800223 data.at(index).inputOperandInformation();
Michael Butler8fc48962021-01-08 17:21:27 -0800224 index++;
225 const bool hasNoValue = operandInfo.hasNoValue;
226 const V1_0::DataLocation location = operandInfo.location;
227 const uint32_t numberOfDimensions = operandInfo.numberOfDimensions;
228
229 // unpackage operand dimensions
230 std::vector<uint32_t> dimensions;
231 dimensions.reserve(numberOfDimensions);
232 for (size_t i = 0; i < numberOfDimensions; ++i) {
233 // validate dimension
Michael Butler611648f2022-11-14 19:00:25 -0800234 if (index >= data.size() ||
235 data.at(index).getDiscriminator() != discriminator::inputOperandDimensionValue) {
Michael Butler76e491f2020-12-19 01:55:32 -0800236 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800237 }
238
239 // unpackage dimension
Michael Butler611648f2022-11-14 19:00:25 -0800240 const uint32_t dimension = data.at(index).inputOperandDimensionValue();
Michael Butler8fc48962021-01-08 17:21:27 -0800241 index++;
242
243 // store result
244 dimensions.push_back(dimension);
245 }
246
247 // store result
248 inputs.push_back(
Michael Butler76e491f2020-12-19 01:55:32 -0800249 {.hasNoValue = hasNoValue, .location = location, .dimensions = dimensions});
Michael Butler8fc48962021-01-08 17:21:27 -0800250 }
251
252 // unpackage output operands
253 std::vector<V1_0::RequestArgument> outputs;
254 outputs.reserve(numberOfOutputOperands);
255 for (size_t operand = 0; operand < numberOfOutputOperands; ++operand) {
256 // validate output operand information
Michael Butler611648f2022-11-14 19:00:25 -0800257 if (index >= data.size() ||
258 data.at(index).getDiscriminator() != discriminator::outputOperandInformation) {
Michael Butler76e491f2020-12-19 01:55:32 -0800259 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800260 }
261
262 // unpackage operand information
263 const FmqRequestDatum::OperandInformation& operandInfo =
Michael Butler611648f2022-11-14 19:00:25 -0800264 data.at(index).outputOperandInformation();
Michael Butler8fc48962021-01-08 17:21:27 -0800265 index++;
266 const bool hasNoValue = operandInfo.hasNoValue;
267 const V1_0::DataLocation location = operandInfo.location;
268 const uint32_t numberOfDimensions = operandInfo.numberOfDimensions;
269
270 // unpackage operand dimensions
271 std::vector<uint32_t> dimensions;
272 dimensions.reserve(numberOfDimensions);
273 for (size_t i = 0; i < numberOfDimensions; ++i) {
274 // validate dimension
Michael Butler611648f2022-11-14 19:00:25 -0800275 if (index >= data.size() ||
276 data.at(index).getDiscriminator() != discriminator::outputOperandDimensionValue) {
Michael Butler76e491f2020-12-19 01:55:32 -0800277 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800278 }
279
280 // unpackage dimension
Michael Butler611648f2022-11-14 19:00:25 -0800281 const uint32_t dimension = data.at(index).outputOperandDimensionValue();
Michael Butler8fc48962021-01-08 17:21:27 -0800282 index++;
283
284 // store result
285 dimensions.push_back(dimension);
286 }
287
288 // store result
289 outputs.push_back(
Michael Butler76e491f2020-12-19 01:55:32 -0800290 {.hasNoValue = hasNoValue, .location = location, .dimensions = dimensions});
Michael Butler8fc48962021-01-08 17:21:27 -0800291 }
292
293 // unpackage pools
294 std::vector<int32_t> slots;
295 slots.reserve(numberOfPools);
296 for (size_t pool = 0; pool < numberOfPools; ++pool) {
297 // validate input operand information
Michael Butler611648f2022-11-14 19:00:25 -0800298 if (index >= data.size() ||
299 data.at(index).getDiscriminator() != discriminator::poolIdentifier) {
Michael Butler76e491f2020-12-19 01:55:32 -0800300 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800301 }
302
303 // unpackage operand information
Michael Butler611648f2022-11-14 19:00:25 -0800304 const int32_t poolId = data.at(index).poolIdentifier();
Michael Butler8fc48962021-01-08 17:21:27 -0800305 index++;
306
307 // store result
308 slots.push_back(poolId);
309 }
310
311 // validate measureTiming
Michael Butler611648f2022-11-14 19:00:25 -0800312 if (index >= data.size() || data.at(index).getDiscriminator() != discriminator::measureTiming) {
Michael Butler76e491f2020-12-19 01:55:32 -0800313 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800314 }
315
316 // unpackage measureTiming
Michael Butler611648f2022-11-14 19:00:25 -0800317 const V1_2::MeasureTiming measure = data.at(index).measureTiming();
Michael Butler8fc48962021-01-08 17:21:27 -0800318 index++;
319
320 // validate packet information
321 if (index != packetSize) {
Michael Butler611648f2022-11-14 19:00:25 -0800322 return NN_ERROR() << "FMQ Request packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800323 }
324
325 // return request
Michael Butler76e491f2020-12-19 01:55:32 -0800326 V1_0::Request request = {.inputs = inputs, .outputs = outputs, .pools = {}};
Michael Butler8fc48962021-01-08 17:21:27 -0800327 return std::make_tuple(std::move(request), std::move(slots), measure);
328}
329
330// deserialize a packet into the result
Michael Butler76e491f2020-12-19 01:55:32 -0800331nn::Result<std::tuple<V1_0::ErrorStatus, std::vector<V1_2::OutputShape>, V1_2::Timing>> deserialize(
332 const std::vector<FmqResultDatum>& data) {
Michael Butler8fc48962021-01-08 17:21:27 -0800333 using discriminator = FmqResultDatum::hidl_discriminator;
Michael Butler8fc48962021-01-08 17:21:27 -0800334 size_t index = 0;
335
336 // validate packet information
Michael Butler611648f2022-11-14 19:00:25 -0800337 if (index >= data.size() ||
338 data.at(index).getDiscriminator() != discriminator::packetInformation) {
Michael Butler76e491f2020-12-19 01:55:32 -0800339 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800340 }
341
342 // unpackage packet information
Michael Butler611648f2022-11-14 19:00:25 -0800343 const FmqResultDatum::PacketInformation& packetInfo = data.at(index).packetInformation();
Michael Butler8fc48962021-01-08 17:21:27 -0800344 index++;
345 const uint32_t packetSize = packetInfo.packetSize;
346 const V1_0::ErrorStatus errorStatus = packetInfo.errorStatus;
347 const uint32_t numberOfOperands = packetInfo.numberOfOperands;
348
349 // verify packet size
350 if (data.size() != packetSize) {
Michael Butler76e491f2020-12-19 01:55:32 -0800351 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800352 }
353
354 // unpackage operands
Michael Butler76e491f2020-12-19 01:55:32 -0800355 std::vector<V1_2::OutputShape> outputShapes;
356 outputShapes.reserve(numberOfOperands);
Michael Butler8fc48962021-01-08 17:21:27 -0800357 for (size_t operand = 0; operand < numberOfOperands; ++operand) {
358 // validate operand information
Michael Butler611648f2022-11-14 19:00:25 -0800359 if (index >= data.size() ||
360 data.at(index).getDiscriminator() != discriminator::operandInformation) {
Michael Butler76e491f2020-12-19 01:55:32 -0800361 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800362 }
363
364 // unpackage operand information
Michael Butler611648f2022-11-14 19:00:25 -0800365 const FmqResultDatum::OperandInformation& operandInfo = data.at(index).operandInformation();
Michael Butler8fc48962021-01-08 17:21:27 -0800366 index++;
367 const bool isSufficient = operandInfo.isSufficient;
368 const uint32_t numberOfDimensions = operandInfo.numberOfDimensions;
369
370 // unpackage operand dimensions
371 std::vector<uint32_t> dimensions;
372 dimensions.reserve(numberOfDimensions);
373 for (size_t i = 0; i < numberOfDimensions; ++i) {
374 // validate dimension
Michael Butler611648f2022-11-14 19:00:25 -0800375 if (index >= data.size() ||
376 data.at(index).getDiscriminator() != discriminator::operandDimensionValue) {
Michael Butler76e491f2020-12-19 01:55:32 -0800377 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800378 }
379
380 // unpackage dimension
Michael Butler611648f2022-11-14 19:00:25 -0800381 const uint32_t dimension = data.at(index).operandDimensionValue();
Michael Butler8fc48962021-01-08 17:21:27 -0800382 index++;
383
384 // store result
385 dimensions.push_back(dimension);
386 }
387
388 // store result
Michael Butler76e491f2020-12-19 01:55:32 -0800389 outputShapes.push_back({.dimensions = dimensions, .isSufficient = isSufficient});
Michael Butler8fc48962021-01-08 17:21:27 -0800390 }
391
392 // validate execution timing
Michael Butler611648f2022-11-14 19:00:25 -0800393 if (index >= data.size() ||
394 data.at(index).getDiscriminator() != discriminator::executionTiming) {
Michael Butler76e491f2020-12-19 01:55:32 -0800395 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800396 }
397
398 // unpackage execution timing
Michael Butler611648f2022-11-14 19:00:25 -0800399 const V1_2::Timing timing = data.at(index).executionTiming();
Michael Butler8fc48962021-01-08 17:21:27 -0800400 index++;
401
402 // validate packet information
403 if (index != packetSize) {
Michael Butler76e491f2020-12-19 01:55:32 -0800404 return NN_ERROR() << "FMQ Result packet ill-formed";
Michael Butler8fc48962021-01-08 17:21:27 -0800405 }
406
407 // return result
408 return std::make_tuple(errorStatus, std::move(outputShapes), timing);
409}
410
Michael Butler8fc48962021-01-08 17:21:27 -0800411// RequestChannelSender methods
412
Michael Butler76e491f2020-12-19 01:55:32 -0800413nn::GeneralResult<
414 std::pair<std::unique_ptr<RequestChannelSender>, const MQDescriptorSync<FmqRequestDatum>*>>
Michael Butler8fc48962021-01-08 17:21:27 -0800415RequestChannelSender::create(size_t channelLength) {
Michael Butler76e491f2020-12-19 01:55:32 -0800416 auto requestChannelSender =
417 std::make_unique<RequestChannelSender>(PrivateConstructorTag{}, channelLength);
418 if (!requestChannelSender->mFmqRequestChannel.isValid()) {
419 return NN_ERROR() << "Unable to create RequestChannelSender";
Michael Butler8fc48962021-01-08 17:21:27 -0800420 }
421
Michael Butler76e491f2020-12-19 01:55:32 -0800422 const MQDescriptorSync<FmqRequestDatum>* descriptor =
423 requestChannelSender->mFmqRequestChannel.getDesc();
424 return std::make_pair(std::move(requestChannelSender), descriptor);
Michael Butler8fc48962021-01-08 17:21:27 -0800425}
426
Michael Butler76e491f2020-12-19 01:55:32 -0800427RequestChannelSender::RequestChannelSender(PrivateConstructorTag /*tag*/, size_t channelLength)
428 : mFmqRequestChannel(channelLength, /*configureEventFlagWord=*/true) {}
Michael Butler8fc48962021-01-08 17:21:27 -0800429
Michael Butler76e491f2020-12-19 01:55:32 -0800430nn::Result<void> RequestChannelSender::send(const V1_0::Request& request,
431 V1_2::MeasureTiming measure,
432 const std::vector<int32_t>& slots) {
Michael Butler8fc48962021-01-08 17:21:27 -0800433 const std::vector<FmqRequestDatum> serialized = serialize(request, measure, slots);
434 return sendPacket(serialized);
435}
436
Michael Butler76e491f2020-12-19 01:55:32 -0800437nn::Result<void> RequestChannelSender::sendPacket(const std::vector<FmqRequestDatum>& packet) {
Michael Butler8fc48962021-01-08 17:21:27 -0800438 if (!mValid) {
Michael Butler76e491f2020-12-19 01:55:32 -0800439 return NN_ERROR() << "FMQ object is invalid";
Michael Butler8fc48962021-01-08 17:21:27 -0800440 }
441
Michael Butler76e491f2020-12-19 01:55:32 -0800442 if (packet.size() > mFmqRequestChannel.availableToWrite()) {
443 return NN_ERROR()
444 << "RequestChannelSender::sendPacket -- packet size exceeds size available in FMQ";
Michael Butler8fc48962021-01-08 17:21:27 -0800445 }
446
Michael Butler76e491f2020-12-19 01:55:32 -0800447 // Always send the packet with "blocking" because this signals the futex and unblocks the
448 // consumer if it is waiting on the futex.
449 const bool success = mFmqRequestChannel.writeBlocking(packet.data(), packet.size());
450 if (!success) {
451 return NN_ERROR()
452 << "RequestChannelSender::sendPacket -- FMQ's writeBlocking returned an error";
453 }
454
455 return {};
Michael Butler8fc48962021-01-08 17:21:27 -0800456}
457
Michael Butler76e491f2020-12-19 01:55:32 -0800458void RequestChannelSender::notifyAsDeadObject() {
Michael Butler8fc48962021-01-08 17:21:27 -0800459 mValid = false;
460}
461
462// RequestChannelReceiver methods
463
Michael Butler76e491f2020-12-19 01:55:32 -0800464nn::GeneralResult<std::unique_ptr<RequestChannelReceiver>> RequestChannelReceiver::create(
465 const MQDescriptorSync<FmqRequestDatum>& requestChannel,
466 std::chrono::microseconds pollingTimeWindow) {
467 auto requestChannelReceiver = std::make_unique<RequestChannelReceiver>(
468 PrivateConstructorTag{}, requestChannel, pollingTimeWindow);
Michael Butler8fc48962021-01-08 17:21:27 -0800469
Michael Butler76e491f2020-12-19 01:55:32 -0800470 if (!requestChannelReceiver->mFmqRequestChannel.isValid()) {
471 return NN_ERROR() << "Unable to create RequestChannelReceiver";
Michael Butler8fc48962021-01-08 17:21:27 -0800472 }
Michael Butler76e491f2020-12-19 01:55:32 -0800473 if (requestChannelReceiver->mFmqRequestChannel.getEventFlagWord() == nullptr) {
474 return NN_ERROR()
475 << "RequestChannelReceiver::create was passed an MQDescriptor without an EventFlag";
Michael Butler8fc48962021-01-08 17:21:27 -0800476 }
477
Michael Butler76e491f2020-12-19 01:55:32 -0800478 return requestChannelReceiver;
Michael Butler8fc48962021-01-08 17:21:27 -0800479}
480
Michael Butler76e491f2020-12-19 01:55:32 -0800481RequestChannelReceiver::RequestChannelReceiver(
482 PrivateConstructorTag /*tag*/, const MQDescriptorSync<FmqRequestDatum>& requestChannel,
483 std::chrono::microseconds pollingTimeWindow)
484 : mFmqRequestChannel(requestChannel), kPollingTimeWindow(pollingTimeWindow) {}
Michael Butler8fc48962021-01-08 17:21:27 -0800485
Michael Butler76e491f2020-12-19 01:55:32 -0800486nn::Result<std::tuple<V1_0::Request, std::vector<int32_t>, V1_2::MeasureTiming>>
Michael Butler8fc48962021-01-08 17:21:27 -0800487RequestChannelReceiver::getBlocking() {
Michael Butler76e491f2020-12-19 01:55:32 -0800488 const auto packet = NN_TRY(getPacketBlocking());
489 return deserialize(packet);
Michael Butler8fc48962021-01-08 17:21:27 -0800490}
491
492void RequestChannelReceiver::invalidate() {
493 mTeardown = true;
494
495 // force unblock
Michael Butler76e491f2020-12-19 01:55:32 -0800496 // ExecutionBurstServer is by default waiting on a request packet. If the client process
497 // destroys its burst object, the server may still be waiting on the futex. This force unblock
498 // wakes up any thread waiting on the futex.
499 const auto data = serialize(V1_0::Request{}, V1_2::MeasureTiming::NO, {});
500 mFmqRequestChannel.writeBlocking(data.data(), data.size());
Michael Butler8fc48962021-01-08 17:21:27 -0800501}
502
Michael Butler76e491f2020-12-19 01:55:32 -0800503nn::Result<std::vector<FmqRequestDatum>> RequestChannelReceiver::getPacketBlocking() {
Michael Butler8fc48962021-01-08 17:21:27 -0800504 if (mTeardown) {
Michael Butler76e491f2020-12-19 01:55:32 -0800505 return NN_ERROR() << "FMQ object is being torn down";
Michael Butler8fc48962021-01-08 17:21:27 -0800506 }
507
Michael Butler76e491f2020-12-19 01:55:32 -0800508 // First spend time polling if results are available in FMQ instead of waiting on the futex.
509 // Polling is more responsive (yielding lower latencies), but can take up more power, so only
510 // poll for a limited period of time.
Michael Butler8fc48962021-01-08 17:21:27 -0800511
512 auto& getCurrentTime = std::chrono::high_resolution_clock::now;
513 const auto timeToStopPolling = getCurrentTime() + kPollingTimeWindow;
514
515 while (getCurrentTime() < timeToStopPolling) {
516 // if class is being torn down, immediately return
517 if (mTeardown.load(std::memory_order_relaxed)) {
Michael Butler76e491f2020-12-19 01:55:32 -0800518 return NN_ERROR() << "FMQ object is being torn down";
Michael Butler8fc48962021-01-08 17:21:27 -0800519 }
520
Michael Butler76e491f2020-12-19 01:55:32 -0800521 // Check if data is available. If it is, immediately retrieve it and return.
522 const size_t available = mFmqRequestChannel.availableToRead();
Michael Butler8fc48962021-01-08 17:21:27 -0800523 if (available > 0) {
Michael Butler8fc48962021-01-08 17:21:27 -0800524 std::vector<FmqRequestDatum> packet(available);
Michael Butler76e491f2020-12-19 01:55:32 -0800525 const bool success = mFmqRequestChannel.readBlocking(packet.data(), available);
Michael Butler8fc48962021-01-08 17:21:27 -0800526 if (!success) {
Michael Butler76e491f2020-12-19 01:55:32 -0800527 return NN_ERROR() << "Error receiving packet";
Michael Butler8fc48962021-01-08 17:21:27 -0800528 }
Michael Butler76e491f2020-12-19 01:55:32 -0800529 return packet;
Michael Butler8fc48962021-01-08 17:21:27 -0800530 }
Michael Butler0252d5f2021-03-30 20:13:49 -0700531
532 std::this_thread::yield();
Michael Butler8fc48962021-01-08 17:21:27 -0800533 }
534
Michael Butler76e491f2020-12-19 01:55:32 -0800535 // If we get to this point, we either stopped polling because it was taking too long or polling
536 // was not allowed. Instead, perform a blocking call which uses a futex to save power.
Michael Butler8fc48962021-01-08 17:21:27 -0800537
538 // wait for request packet and read first element of request packet
539 FmqRequestDatum datum;
Michael Butler76e491f2020-12-19 01:55:32 -0800540 bool success = mFmqRequestChannel.readBlocking(&datum, 1);
Michael Butler8fc48962021-01-08 17:21:27 -0800541
542 // retrieve remaining elements
Michael Butler76e491f2020-12-19 01:55:32 -0800543 // NOTE: all of the data is already available at this point, so there's no need to do a blocking
544 // wait to wait for more data. This is known because in FMQ, all writes are published (made
545 // available) atomically. Currently, the producer always publishes the entire packet in one
546 // function call, so if the first element of the packet is available, the remaining elements are
547 // also available.
548 const size_t count = mFmqRequestChannel.availableToRead();
Michael Butler8fc48962021-01-08 17:21:27 -0800549 std::vector<FmqRequestDatum> packet(count + 1);
550 std::memcpy(&packet.front(), &datum, sizeof(datum));
Michael Butler76e491f2020-12-19 01:55:32 -0800551 success &= mFmqRequestChannel.read(packet.data() + 1, count);
Michael Butler8fc48962021-01-08 17:21:27 -0800552
553 // terminate loop
554 if (mTeardown) {
Michael Butler76e491f2020-12-19 01:55:32 -0800555 return NN_ERROR() << "FMQ object is being torn down";
Michael Butler8fc48962021-01-08 17:21:27 -0800556 }
557
558 // ensure packet was successfully received
559 if (!success) {
Michael Butler76e491f2020-12-19 01:55:32 -0800560 return NN_ERROR() << "Error receiving packet";
Michael Butler8fc48962021-01-08 17:21:27 -0800561 }
562
Michael Butler76e491f2020-12-19 01:55:32 -0800563 return packet;
Michael Butler8fc48962021-01-08 17:21:27 -0800564}
565
566// ResultChannelSender methods
567
Michael Butler76e491f2020-12-19 01:55:32 -0800568nn::GeneralResult<std::unique_ptr<ResultChannelSender>> ResultChannelSender::create(
569 const MQDescriptorSync<FmqResultDatum>& resultChannel) {
570 auto resultChannelSender =
571 std::make_unique<ResultChannelSender>(PrivateConstructorTag{}, resultChannel);
Michael Butler8fc48962021-01-08 17:21:27 -0800572
Michael Butler76e491f2020-12-19 01:55:32 -0800573 if (!resultChannelSender->mFmqResultChannel.isValid()) {
574 return NN_ERROR() << "Unable to create RequestChannelSender";
Michael Butler8fc48962021-01-08 17:21:27 -0800575 }
Michael Butler76e491f2020-12-19 01:55:32 -0800576 if (resultChannelSender->mFmqResultChannel.getEventFlagWord() == nullptr) {
577 return NN_ERROR()
578 << "ResultChannelSender::create was passed an MQDescriptor without an EventFlag";
Michael Butler8fc48962021-01-08 17:21:27 -0800579 }
580
Michael Butler76e491f2020-12-19 01:55:32 -0800581 return resultChannelSender;
Michael Butler8fc48962021-01-08 17:21:27 -0800582}
583
Michael Butler76e491f2020-12-19 01:55:32 -0800584ResultChannelSender::ResultChannelSender(PrivateConstructorTag /*tag*/,
585 const MQDescriptorSync<FmqResultDatum>& resultChannel)
586 : mFmqResultChannel(resultChannel) {}
Michael Butler8fc48962021-01-08 17:21:27 -0800587
Michael Butler76e491f2020-12-19 01:55:32 -0800588void ResultChannelSender::send(V1_0::ErrorStatus errorStatus,
Michael Butler8fc48962021-01-08 17:21:27 -0800589 const std::vector<V1_2::OutputShape>& outputShapes,
590 V1_2::Timing timing) {
591 const std::vector<FmqResultDatum> serialized = serialize(errorStatus, outputShapes, timing);
Michael Butler76e491f2020-12-19 01:55:32 -0800592 sendPacket(serialized);
Michael Butler8fc48962021-01-08 17:21:27 -0800593}
594
Michael Butler76e491f2020-12-19 01:55:32 -0800595void ResultChannelSender::sendPacket(const std::vector<FmqResultDatum>& packet) {
596 if (packet.size() > mFmqResultChannel.availableToWrite()) {
Michael Butler8fc48962021-01-08 17:21:27 -0800597 LOG(ERROR)
598 << "ResultChannelSender::sendPacket -- packet size exceeds size available in FMQ";
599 const std::vector<FmqResultDatum> errorPacket =
600 serialize(V1_0::ErrorStatus::GENERAL_FAILURE, {}, kNoTiming);
601
Michael Butler76e491f2020-12-19 01:55:32 -0800602 // Always send the packet with "blocking" because this signals the futex and unblocks the
603 // consumer if it is waiting on the futex.
604 mFmqResultChannel.writeBlocking(errorPacket.data(), errorPacket.size());
605 } else {
606 // Always send the packet with "blocking" because this signals the futex and unblocks the
607 // consumer if it is waiting on the futex.
608 mFmqResultChannel.writeBlocking(packet.data(), packet.size());
Michael Butler8fc48962021-01-08 17:21:27 -0800609 }
Michael Butler8fc48962021-01-08 17:21:27 -0800610}
611
612// ResultChannelReceiver methods
613
Michael Butler76e491f2020-12-19 01:55:32 -0800614nn::GeneralResult<
615 std::pair<std::unique_ptr<ResultChannelReceiver>, const MQDescriptorSync<FmqResultDatum>*>>
Michael Butler8fc48962021-01-08 17:21:27 -0800616ResultChannelReceiver::create(size_t channelLength, std::chrono::microseconds pollingTimeWindow) {
Michael Butler76e491f2020-12-19 01:55:32 -0800617 auto resultChannelReceiver = std::make_unique<ResultChannelReceiver>(
618 PrivateConstructorTag{}, channelLength, pollingTimeWindow);
619 if (!resultChannelReceiver->mFmqResultChannel.isValid()) {
620 return NN_ERROR() << "Unable to create ResultChannelReceiver";
Michael Butler8fc48962021-01-08 17:21:27 -0800621 }
622
Michael Butler76e491f2020-12-19 01:55:32 -0800623 const MQDescriptorSync<FmqResultDatum>* descriptor =
624 resultChannelReceiver->mFmqResultChannel.getDesc();
625 return std::make_pair(std::move(resultChannelReceiver), descriptor);
Michael Butler8fc48962021-01-08 17:21:27 -0800626}
627
Michael Butler76e491f2020-12-19 01:55:32 -0800628ResultChannelReceiver::ResultChannelReceiver(PrivateConstructorTag /*tag*/, size_t channelLength,
Michael Butler8fc48962021-01-08 17:21:27 -0800629 std::chrono::microseconds pollingTimeWindow)
Michael Butler76e491f2020-12-19 01:55:32 -0800630 : mFmqResultChannel(channelLength, /*configureEventFlagWord=*/true),
631 kPollingTimeWindow(pollingTimeWindow) {}
Michael Butler8fc48962021-01-08 17:21:27 -0800632
Michael Butler76e491f2020-12-19 01:55:32 -0800633nn::Result<std::tuple<V1_0::ErrorStatus, std::vector<V1_2::OutputShape>, V1_2::Timing>>
Michael Butler8fc48962021-01-08 17:21:27 -0800634ResultChannelReceiver::getBlocking() {
Michael Butler76e491f2020-12-19 01:55:32 -0800635 const auto packet = NN_TRY(getPacketBlocking());
636 return deserialize(packet);
Michael Butler8fc48962021-01-08 17:21:27 -0800637}
638
Michael Butler76e491f2020-12-19 01:55:32 -0800639void ResultChannelReceiver::notifyAsDeadObject() {
Michael Butler8fc48962021-01-08 17:21:27 -0800640 mValid = false;
641
642 // force unblock
Michael Butler76e491f2020-12-19 01:55:32 -0800643 // ExecutionBurstController waits on a result packet after sending a request. If the driver
644 // containing ExecutionBurstServer crashes, the controller may be waiting on the futex. This
645 // force unblock wakes up any thread waiting on the futex.
646 const auto data = serialize(V1_0::ErrorStatus::GENERAL_FAILURE, {}, kNoTiming);
647 mFmqResultChannel.writeBlocking(data.data(), data.size());
Michael Butler8fc48962021-01-08 17:21:27 -0800648}
649
Michael Butler76e491f2020-12-19 01:55:32 -0800650nn::Result<std::vector<FmqResultDatum>> ResultChannelReceiver::getPacketBlocking() {
Michael Butler8fc48962021-01-08 17:21:27 -0800651 if (!mValid) {
Michael Butler76e491f2020-12-19 01:55:32 -0800652 return NN_ERROR() << "FMQ object is invalid";
Michael Butler8fc48962021-01-08 17:21:27 -0800653 }
654
Michael Butler76e491f2020-12-19 01:55:32 -0800655 // First spend time polling if results are available in FMQ instead of waiting on the futex.
656 // Polling is more responsive (yielding lower latencies), but can take up more power, so only
657 // poll for a limited period of time.
Michael Butler8fc48962021-01-08 17:21:27 -0800658
659 auto& getCurrentTime = std::chrono::high_resolution_clock::now;
660 const auto timeToStopPolling = getCurrentTime() + kPollingTimeWindow;
661
662 while (getCurrentTime() < timeToStopPolling) {
663 // if class is being torn down, immediately return
664 if (!mValid.load(std::memory_order_relaxed)) {
Michael Butler76e491f2020-12-19 01:55:32 -0800665 return NN_ERROR() << "FMQ object is invalid";
Michael Butler8fc48962021-01-08 17:21:27 -0800666 }
667
Michael Butler76e491f2020-12-19 01:55:32 -0800668 // Check if data is available. If it is, immediately retrieve it and return.
669 const size_t available = mFmqResultChannel.availableToRead();
Michael Butler8fc48962021-01-08 17:21:27 -0800670 if (available > 0) {
671 std::vector<FmqResultDatum> packet(available);
Michael Butler76e491f2020-12-19 01:55:32 -0800672 const bool success = mFmqResultChannel.readBlocking(packet.data(), available);
Michael Butler8fc48962021-01-08 17:21:27 -0800673 if (!success) {
Michael Butler76e491f2020-12-19 01:55:32 -0800674 return NN_ERROR() << "Error receiving packet";
Michael Butler8fc48962021-01-08 17:21:27 -0800675 }
Michael Butler76e491f2020-12-19 01:55:32 -0800676 return packet;
Michael Butler8fc48962021-01-08 17:21:27 -0800677 }
Michael Butler0252d5f2021-03-30 20:13:49 -0700678
679 std::this_thread::yield();
Michael Butler8fc48962021-01-08 17:21:27 -0800680 }
681
Michael Butler76e491f2020-12-19 01:55:32 -0800682 // If we get to this point, we either stopped polling because it was taking too long or polling
683 // was not allowed. Instead, perform a blocking call which uses a futex to save power.
Michael Butler8fc48962021-01-08 17:21:27 -0800684
685 // wait for result packet and read first element of result packet
686 FmqResultDatum datum;
Michael Butler76e491f2020-12-19 01:55:32 -0800687 bool success = mFmqResultChannel.readBlocking(&datum, 1);
Michael Butler8fc48962021-01-08 17:21:27 -0800688
689 // retrieve remaining elements
Michael Butler76e491f2020-12-19 01:55:32 -0800690 // NOTE: all of the data is already available at this point, so there's no need to do a blocking
691 // wait to wait for more data. This is known because in FMQ, all writes are published (made
692 // available) atomically. Currently, the producer always publishes the entire packet in one
693 // function call, so if the first element of the packet is available, the remaining elements are
694 // also available.
695 const size_t count = mFmqResultChannel.availableToRead();
Michael Butler8fc48962021-01-08 17:21:27 -0800696 std::vector<FmqResultDatum> packet(count + 1);
697 std::memcpy(&packet.front(), &datum, sizeof(datum));
Michael Butler76e491f2020-12-19 01:55:32 -0800698 success &= mFmqResultChannel.read(packet.data() + 1, count);
Michael Butler8fc48962021-01-08 17:21:27 -0800699
700 if (!mValid) {
Michael Butler76e491f2020-12-19 01:55:32 -0800701 return NN_ERROR() << "FMQ object is invalid";
Michael Butler8fc48962021-01-08 17:21:27 -0800702 }
703
704 // ensure packet was successfully received
705 if (!success) {
Michael Butler76e491f2020-12-19 01:55:32 -0800706 return NN_ERROR() << "Error receiving packet";
Michael Butler8fc48962021-01-08 17:21:27 -0800707 }
708
Michael Butler76e491f2020-12-19 01:55:32 -0800709 return packet;
Michael Butler8fc48962021-01-08 17:21:27 -0800710}
711
712} // namespace android::hardware::neuralnetworks::V1_2::utils