1 /*
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 
17 #define LOG_TAG "ExecutionBurstServer"
18 
19 #include "ExecutionBurstServer.h"
20 
21 #include <android-base/logging.h>
22 
23 #include <algorithm>
24 #include <cstring>
25 #include <limits>
26 #include <map>
27 #include <memory>
28 #include <thread>
29 #include <tuple>
30 #include <utility>
31 #include <vector>
32 
33 #include "HalInterfaces.h"
34 #include "Tracing.h"
35 #include "Utils.h"
36 
37 namespace android::nn {
38 namespace {
39 
40 using hardware::MQDescriptorSync;
41 using V1_2::FmqRequestDatum;
42 using V1_2::FmqResultDatum;
43 using V1_2::IBurstCallback;
44 using V1_2::IBurstContext;
45 
46 constexpr V1_2::Timing kNoTiming = {std::numeric_limits<uint64_t>::max(),
47                                     std::numeric_limits<uint64_t>::max()};
48 
49 // DefaultBurstExecutorWithCache adapts an IPreparedModel so that it can be
50 // used as an IBurstExecutorWithCache. Specifically, the cache simply stores the
51 // hidl_memory object, and the execution forwards calls to the provided
52 // IPreparedModel's "executeSynchronously" method. With this class, hidl_memory
53 // must be mapped and unmapped for each execution.
54 class DefaultBurstExecutorWithCache : public ExecutionBurstServer::IBurstExecutorWithCache {
55    public:
DefaultBurstExecutorWithCache(V1_2::IPreparedModel * preparedModel)56     DefaultBurstExecutorWithCache(V1_2::IPreparedModel* preparedModel)
57         : mpPreparedModel(preparedModel) {}
58 
isCacheEntryPresent(int32_t slot) const59     bool isCacheEntryPresent(int32_t slot) const override {
60         const auto it = mMemoryCache.find(slot);
61         return (it != mMemoryCache.end()) && it->second.valid();
62     }
63 
addCacheEntry(const hardware::hidl_memory & memory,int32_t slot)64     void addCacheEntry(const hardware::hidl_memory& memory, int32_t slot) override {
65         mMemoryCache[slot] = memory;
66     }
67 
removeCacheEntry(int32_t slot)68     void removeCacheEntry(int32_t slot) override { mMemoryCache.erase(slot); }
69 
execute(const V1_0::Request & request,const std::vector<int32_t> & slots,V1_2::MeasureTiming measure)70     std::tuple<V1_0::ErrorStatus, hardware::hidl_vec<V1_2::OutputShape>, V1_2::Timing> execute(
71             const V1_0::Request& request, const std::vector<int32_t>& slots,
72             V1_2::MeasureTiming measure) override {
73         // convert slots to pools
74         hardware::hidl_vec<hardware::hidl_memory> pools(slots.size());
75         std::transform(slots.begin(), slots.end(), pools.begin(),
76                        [this](int32_t slot) { return mMemoryCache[slot]; });
77 
78         // create full request
79         V1_0::Request fullRequest = request;
80         fullRequest.pools = std::move(pools);
81 
82         // setup execution
83         V1_0::ErrorStatus returnedStatus = V1_0::ErrorStatus::GENERAL_FAILURE;
84         hardware::hidl_vec<V1_2::OutputShape> returnedOutputShapes;
85         V1_2::Timing returnedTiming;
86         auto cb = [&returnedStatus, &returnedOutputShapes, &returnedTiming](
87                           V1_0::ErrorStatus status,
88                           const hardware::hidl_vec<V1_2::OutputShape>& outputShapes,
89                           const V1_2::Timing& timing) {
90             returnedStatus = status;
91             returnedOutputShapes = outputShapes;
92             returnedTiming = timing;
93         };
94 
95         // execute
96         const hardware::Return<void> ret =
97                 mpPreparedModel->executeSynchronously(fullRequest, measure, cb);
98         if (!ret.isOk() || returnedStatus != V1_0::ErrorStatus::NONE) {
99             LOG(ERROR) << "IPreparedModelAdapter::execute -- Error executing";
100             return {returnedStatus, std::move(returnedOutputShapes), kNoTiming};
101         }
102 
103         return std::make_tuple(returnedStatus, std::move(returnedOutputShapes), returnedTiming);
104     }
105 
106    private:
107     V1_2::IPreparedModel* const mpPreparedModel;
108     std::map<int32_t, hardware::hidl_memory> mMemoryCache;
109 };
110 
111 }  // anonymous namespace
112 
113 // serialize result
serialize(V1_0::ErrorStatus errorStatus,const std::vector<V1_2::OutputShape> & outputShapes,V1_2::Timing timing)114 std::vector<FmqResultDatum> serialize(V1_0::ErrorStatus errorStatus,
115                                       const std::vector<V1_2::OutputShape>& outputShapes,
116                                       V1_2::Timing timing) {
117     // count how many elements need to be sent for a request
118     size_t count = 2 + outputShapes.size();
119     for (const auto& outputShape : outputShapes) {
120         count += outputShape.dimensions.size();
121     }
122 
123     // create buffer to temporarily store elements
124     std::vector<FmqResultDatum> data;
125     data.reserve(count);
126 
127     // package packetInfo
128     {
129         FmqResultDatum datum;
130         datum.packetInformation({/*.packetSize=*/static_cast<uint32_t>(count),
131                                  /*.errorStatus=*/errorStatus,
132                                  /*.numberOfOperands=*/static_cast<uint32_t>(outputShapes.size())});
133         data.push_back(datum);
134     }
135 
136     // package output shape data
137     for (const auto& operand : outputShapes) {
138         // package operand information
139         FmqResultDatum::OperandInformation info{};
140         info.isSufficient = operand.isSufficient;
141         info.numberOfDimensions = static_cast<uint32_t>(operand.dimensions.size());
142 
143         FmqResultDatum datum;
144         datum.operandInformation(info);
145         data.push_back(datum);
146 
147         // package operand dimensions
148         for (uint32_t dimension : operand.dimensions) {
149             FmqResultDatum datum;
150             datum.operandDimensionValue(dimension);
151             data.push_back(datum);
152         }
153     }
154 
155     // package executionTiming
156     {
157         FmqResultDatum datum;
158         datum.executionTiming(timing);
159         data.push_back(datum);
160     }
161 
162     // return result
163     return data;
164 }
165 
166 // deserialize request
deserialize(const std::vector<FmqRequestDatum> & data)167 std::optional<std::tuple<V1_0::Request, std::vector<int32_t>, V1_2::MeasureTiming>> deserialize(
168         const std::vector<FmqRequestDatum>& data) {
169     using discriminator = FmqRequestDatum::hidl_discriminator;
170 
171     size_t index = 0;
172 
173     // validate packet information
174     if (data.size() == 0 || data[index].getDiscriminator() != discriminator::packetInformation) {
175         LOG(ERROR) << "FMQ Request packet ill-formed";
176         return std::nullopt;
177     }
178 
179     // unpackage packet information
180     const FmqRequestDatum::PacketInformation& packetInfo = data[index].packetInformation();
181     index++;
182     const uint32_t packetSize = packetInfo.packetSize;
183     const uint32_t numberOfInputOperands = packetInfo.numberOfInputOperands;
184     const uint32_t numberOfOutputOperands = packetInfo.numberOfOutputOperands;
185     const uint32_t numberOfPools = packetInfo.numberOfPools;
186 
187     // verify packet size
188     if (data.size() != packetSize) {
189         LOG(ERROR) << "FMQ Request packet ill-formed";
190         return std::nullopt;
191     }
192 
193     // unpackage input operands
194     std::vector<V1_0::RequestArgument> inputs;
195     inputs.reserve(numberOfInputOperands);
196     for (size_t operand = 0; operand < numberOfInputOperands; ++operand) {
197         // validate input operand information
198         if (data[index].getDiscriminator() != discriminator::inputOperandInformation) {
199             LOG(ERROR) << "FMQ Request packet ill-formed";
200             return std::nullopt;
201         }
202 
203         // unpackage operand information
204         const FmqRequestDatum::OperandInformation& operandInfo =
205                 data[index].inputOperandInformation();
206         index++;
207         const bool hasNoValue = operandInfo.hasNoValue;
208         const V1_0::DataLocation location = operandInfo.location;
209         const uint32_t numberOfDimensions = operandInfo.numberOfDimensions;
210 
211         // unpackage operand dimensions
212         std::vector<uint32_t> dimensions;
213         dimensions.reserve(numberOfDimensions);
214         for (size_t i = 0; i < numberOfDimensions; ++i) {
215             // validate dimension
216             if (data[index].getDiscriminator() != discriminator::inputOperandDimensionValue) {
217                 LOG(ERROR) << "FMQ Request packet ill-formed";
218                 return std::nullopt;
219             }
220 
221             // unpackage dimension
222             const uint32_t dimension = data[index].inputOperandDimensionValue();
223             index++;
224 
225             // store result
226             dimensions.push_back(dimension);
227         }
228 
229         // store result
230         inputs.push_back(
231                 {/*.hasNoValue=*/hasNoValue, /*.location=*/location, /*.dimensions=*/dimensions});
232     }
233 
234     // unpackage output operands
235     std::vector<V1_0::RequestArgument> outputs;
236     outputs.reserve(numberOfOutputOperands);
237     for (size_t operand = 0; operand < numberOfOutputOperands; ++operand) {
238         // validate output operand information
239         if (data[index].getDiscriminator() != discriminator::outputOperandInformation) {
240             LOG(ERROR) << "FMQ Request packet ill-formed";
241             return std::nullopt;
242         }
243 
244         // unpackage operand information
245         const FmqRequestDatum::OperandInformation& operandInfo =
246                 data[index].outputOperandInformation();
247         index++;
248         const bool hasNoValue = operandInfo.hasNoValue;
249         const V1_0::DataLocation location = operandInfo.location;
250         const uint32_t numberOfDimensions = operandInfo.numberOfDimensions;
251 
252         // unpackage operand dimensions
253         std::vector<uint32_t> dimensions;
254         dimensions.reserve(numberOfDimensions);
255         for (size_t i = 0; i < numberOfDimensions; ++i) {
256             // validate dimension
257             if (data[index].getDiscriminator() != discriminator::outputOperandDimensionValue) {
258                 LOG(ERROR) << "FMQ Request packet ill-formed";
259                 return std::nullopt;
260             }
261 
262             // unpackage dimension
263             const uint32_t dimension = data[index].outputOperandDimensionValue();
264             index++;
265 
266             // store result
267             dimensions.push_back(dimension);
268         }
269 
270         // store result
271         outputs.push_back(
272                 {/*.hasNoValue=*/hasNoValue, /*.location=*/location, /*.dimensions=*/dimensions});
273     }
274 
275     // unpackage pools
276     std::vector<int32_t> slots;
277     slots.reserve(numberOfPools);
278     for (size_t pool = 0; pool < numberOfPools; ++pool) {
279         // validate input operand information
280         if (data[index].getDiscriminator() != discriminator::poolIdentifier) {
281             LOG(ERROR) << "FMQ Request packet ill-formed";
282             return std::nullopt;
283         }
284 
285         // unpackage operand information
286         const int32_t poolId = data[index].poolIdentifier();
287         index++;
288 
289         // store result
290         slots.push_back(poolId);
291     }
292 
293     // validate measureTiming
294     if (data[index].getDiscriminator() != discriminator::measureTiming) {
295         LOG(ERROR) << "FMQ Request packet ill-formed";
296         return std::nullopt;
297     }
298 
299     // unpackage measureTiming
300     const V1_2::MeasureTiming measure = data[index].measureTiming();
301     index++;
302 
303     // validate packet information
304     if (index != packetSize) {
305         LOG(ERROR) << "FMQ Result packet ill-formed";
306         return std::nullopt;
307     }
308 
309     // return request
310     V1_0::Request request = {/*.inputs=*/inputs, /*.outputs=*/outputs, /*.pools=*/{}};
311     return std::make_tuple(std::move(request), std::move(slots), measure);
312 }
313 
314 // RequestChannelReceiver methods
315 
create(const FmqRequestDescriptor & requestChannel,std::chrono::microseconds pollingTimeWindow)316 std::unique_ptr<RequestChannelReceiver> RequestChannelReceiver::create(
317         const FmqRequestDescriptor& requestChannel, std::chrono::microseconds pollingTimeWindow) {
318     std::unique_ptr<FmqRequestChannel> fmqRequestChannel =
319             std::make_unique<FmqRequestChannel>(requestChannel);
320 
321     if (!fmqRequestChannel->isValid()) {
322         LOG(ERROR) << "Unable to create RequestChannelReceiver";
323         return nullptr;
324     }
325     if (fmqRequestChannel->getEventFlagWord() == nullptr) {
326         LOG(ERROR)
327                 << "RequestChannelReceiver::create was passed an MQDescriptor without an EventFlag";
328         return nullptr;
329     }
330 
331     return std::make_unique<RequestChannelReceiver>(std::move(fmqRequestChannel),
332                                                     pollingTimeWindow);
333 }
334 
RequestChannelReceiver(std::unique_ptr<FmqRequestChannel> fmqRequestChannel,std::chrono::microseconds pollingTimeWindow)335 RequestChannelReceiver::RequestChannelReceiver(std::unique_ptr<FmqRequestChannel> fmqRequestChannel,
336                                                std::chrono::microseconds pollingTimeWindow)
337     : mFmqRequestChannel(std::move(fmqRequestChannel)), kPollingTimeWindow(pollingTimeWindow) {}
338 
339 std::optional<std::tuple<V1_0::Request, std::vector<int32_t>, V1_2::MeasureTiming>>
getBlocking()340 RequestChannelReceiver::getBlocking() {
341     const auto packet = getPacketBlocking();
342     if (!packet) {
343         return std::nullopt;
344     }
345 
346     return deserialize(*packet);
347 }
348 
invalidate()349 void RequestChannelReceiver::invalidate() {
350     mTeardown = true;
351 
352     // force unblock
353     // ExecutionBurstServer is by default waiting on a request packet. If the
354     // client process destroys its burst object, the server may still be waiting
355     // on the futex. This force unblock wakes up any thread waiting on the
356     // futex.
357     // TODO: look for a different/better way to signal/notify the futex to wake
358     // up any thread waiting on it
359     FmqRequestDatum datum;
360     datum.packetInformation({/*.packetSize=*/0, /*.numberOfInputOperands=*/0,
361                              /*.numberOfOutputOperands=*/0, /*.numberOfPools=*/0});
362     mFmqRequestChannel->writeBlocking(&datum, 1);
363 }
364 
getPacketBlocking()365 std::optional<std::vector<FmqRequestDatum>> RequestChannelReceiver::getPacketBlocking() {
366 
367     if (mTeardown) {
368         return std::nullopt;
369     }
370 
371     // First spend time polling if results are available in FMQ instead of
372     // waiting on the futex. Polling is more responsive (yielding lower
373     // latencies), but can take up more power, so only poll for a limited period
374     // of time.
375 
376     auto& getCurrentTime = std::chrono::high_resolution_clock::now;
377     const auto timeToStopPolling = getCurrentTime() + kPollingTimeWindow;
378 
379     while (getCurrentTime() < timeToStopPolling) {
380         // if class is being torn down, immediately return
381         if (mTeardown.load(std::memory_order_relaxed)) {
382             return std::nullopt;
383         }
384 
385         // Check if data is available. If it is, immediately retrieve it and
386         // return.
387         const size_t available = mFmqRequestChannel->availableToRead();
388         if (available > 0) {
389             // This is the first point when we know an execution is occurring,
390             // so begin to collect systraces. Note that a similar systrace does
391             // not exist at the corresponding point in
392             // ResultChannelReceiver::getPacketBlocking because the execution is
393             // already in flight.
394             NNTRACE_FULL(NNTRACE_LAYER_IPC, NNTRACE_PHASE_EXECUTION,
395                          "ExecutionBurstServer getting packet");
396             std::vector<FmqRequestDatum> packet(available);
397             const bool success = mFmqRequestChannel->read(packet.data(), available);
398             if (!success) {
399                 LOG(ERROR) << "Error receiving packet";
400                 return std::nullopt;
401             }
402             return std::make_optional(std::move(packet));
403         }
404 
405         std::this_thread::yield();
406     }
407 
408     // If we get to this point, we either stopped polling because it was taking
409     // too long or polling was not allowed. Instead, perform a blocking call
410     // which uses a futex to save power.
411 
412     // wait for request packet and read first element of request packet
413     FmqRequestDatum datum;
414     bool success = mFmqRequestChannel->readBlocking(&datum, 1);
415 
416     // This is the first point when we know an execution is occurring, so begin
417     // to collect systraces. Note that a similar systrace does not exist at the
418     // corresponding point in ResultChannelReceiver::getPacketBlocking because
419     // the execution is already in flight.
420     NNTRACE_FULL(NNTRACE_LAYER_IPC, NNTRACE_PHASE_EXECUTION, "ExecutionBurstServer getting packet");
421 
422     // retrieve remaining elements
423     // NOTE: all of the data is already available at this point, so there's no
424     // need to do a blocking wait to wait for more data. This is known because
425     // in FMQ, all writes are published (made available) atomically. Currently,
426     // the producer always publishes the entire packet in one function call, so
427     // if the first element of the packet is available, the remaining elements
428     // are also available.
429     const size_t count = mFmqRequestChannel->availableToRead();
430     std::vector<FmqRequestDatum> packet(count + 1);
431     std::memcpy(&packet.front(), &datum, sizeof(datum));
432     success &= mFmqRequestChannel->read(packet.data() + 1, count);
433 
434     // terminate loop
435     if (mTeardown) {
436         return std::nullopt;
437     }
438 
439     // ensure packet was successfully received
440     if (!success) {
441         LOG(ERROR) << "Error receiving packet";
442         return std::nullopt;
443     }
444 
445     return std::make_optional(std::move(packet));
446 }
447 
448 // ResultChannelSender methods
449 
create(const FmqResultDescriptor & resultChannel)450 std::unique_ptr<ResultChannelSender> ResultChannelSender::create(
451         const FmqResultDescriptor& resultChannel) {
452     std::unique_ptr<FmqResultChannel> fmqResultChannel =
453             std::make_unique<FmqResultChannel>(resultChannel);
454 
455     if (!fmqResultChannel->isValid()) {
456         LOG(ERROR) << "Unable to create RequestChannelSender";
457         return nullptr;
458     }
459     if (fmqResultChannel->getEventFlagWord() == nullptr) {
460         LOG(ERROR) << "ResultChannelSender::create was passed an MQDescriptor without an EventFlag";
461         return nullptr;
462     }
463 
464     return std::make_unique<ResultChannelSender>(std::move(fmqResultChannel));
465 }
466 
ResultChannelSender(std::unique_ptr<FmqResultChannel> fmqResultChannel)467 ResultChannelSender::ResultChannelSender(std::unique_ptr<FmqResultChannel> fmqResultChannel)
468     : mFmqResultChannel(std::move(fmqResultChannel)) {}
469 
send(V1_0::ErrorStatus errorStatus,const std::vector<V1_2::OutputShape> & outputShapes,V1_2::Timing timing)470 bool ResultChannelSender::send(V1_0::ErrorStatus errorStatus,
471                                const std::vector<V1_2::OutputShape>& outputShapes,
472                                V1_2::Timing timing) {
473     const std::vector<FmqResultDatum> serialized = serialize(errorStatus, outputShapes, timing);
474     return sendPacket(serialized);
475 }
476 
sendPacket(const std::vector<FmqResultDatum> & packet)477 bool ResultChannelSender::sendPacket(const std::vector<FmqResultDatum>& packet) {
478     if (packet.size() > mFmqResultChannel->availableToWrite()) {
479         LOG(ERROR)
480                 << "ResultChannelSender::sendPacket -- packet size exceeds size available in FMQ";
481         const std::vector<FmqResultDatum> errorPacket =
482                 serialize(V1_0::ErrorStatus::GENERAL_FAILURE, {}, kNoTiming);
483 
484         // Always send the packet with "blocking" because this signals the futex
485         // and unblocks the consumer if it is waiting on the futex.
486         return mFmqResultChannel->writeBlocking(errorPacket.data(), errorPacket.size());
487     }
488 
489     // Always send the packet with "blocking" because this signals the futex and
490     // unblocks the consumer if it is waiting on the futex.
491     return mFmqResultChannel->writeBlocking(packet.data(), packet.size());
492 }
493 
494 // ExecutionBurstServer methods
495 
create(const sp<IBurstCallback> & callback,const MQDescriptorSync<FmqRequestDatum> & requestChannel,const MQDescriptorSync<FmqResultDatum> & resultChannel,std::shared_ptr<IBurstExecutorWithCache> executorWithCache,std::chrono::microseconds pollingTimeWindow)496 sp<ExecutionBurstServer> ExecutionBurstServer::create(
497         const sp<IBurstCallback>& callback, const MQDescriptorSync<FmqRequestDatum>& requestChannel,
498         const MQDescriptorSync<FmqResultDatum>& resultChannel,
499         std::shared_ptr<IBurstExecutorWithCache> executorWithCache,
500         std::chrono::microseconds pollingTimeWindow) {
501     // check inputs
502     if (callback == nullptr || executorWithCache == nullptr) {
503         LOG(ERROR) << "ExecutionBurstServer::create passed a nullptr";
504         return nullptr;
505     }
506 
507     // create FMQ objects
508     std::unique_ptr<RequestChannelReceiver> requestChannelReceiver =
509             RequestChannelReceiver::create(requestChannel, pollingTimeWindow);
510     std::unique_ptr<ResultChannelSender> resultChannelSender =
511             ResultChannelSender::create(resultChannel);
512 
513     // check FMQ objects
514     if (!requestChannelReceiver || !resultChannelSender) {
515         LOG(ERROR) << "ExecutionBurstServer::create failed to create FastMessageQueue";
516         return nullptr;
517     }
518 
519     // make and return context
520     return new ExecutionBurstServer(callback, std::move(requestChannelReceiver),
521                                     std::move(resultChannelSender), std::move(executorWithCache));
522 }
523 
create(const sp<IBurstCallback> & callback,const MQDescriptorSync<FmqRequestDatum> & requestChannel,const MQDescriptorSync<FmqResultDatum> & resultChannel,V1_2::IPreparedModel * preparedModel,std::chrono::microseconds pollingTimeWindow)524 sp<ExecutionBurstServer> ExecutionBurstServer::create(
525         const sp<IBurstCallback>& callback, const MQDescriptorSync<FmqRequestDatum>& requestChannel,
526         const MQDescriptorSync<FmqResultDatum>& resultChannel, V1_2::IPreparedModel* preparedModel,
527         std::chrono::microseconds pollingTimeWindow) {
528     // check relevant input
529     if (preparedModel == nullptr) {
530         LOG(ERROR) << "ExecutionBurstServer::create passed a nullptr";
531         return nullptr;
532     }
533 
534     // adapt IPreparedModel to have caching
535     const std::shared_ptr<DefaultBurstExecutorWithCache> preparedModelAdapter =
536             std::make_shared<DefaultBurstExecutorWithCache>(preparedModel);
537 
538     // make and return context
539     return ExecutionBurstServer::create(callback, requestChannel, resultChannel,
540                                         preparedModelAdapter, pollingTimeWindow);
541 }
542 
ExecutionBurstServer(const sp<IBurstCallback> & callback,std::unique_ptr<RequestChannelReceiver> requestChannel,std::unique_ptr<ResultChannelSender> resultChannel,std::shared_ptr<IBurstExecutorWithCache> executorWithCache)543 ExecutionBurstServer::ExecutionBurstServer(
544         const sp<IBurstCallback>& callback, std::unique_ptr<RequestChannelReceiver> requestChannel,
545         std::unique_ptr<ResultChannelSender> resultChannel,
546         std::shared_ptr<IBurstExecutorWithCache> executorWithCache)
547     : mCallback(callback),
548       mRequestChannelReceiver(std::move(requestChannel)),
549       mResultChannelSender(std::move(resultChannel)),
550       mExecutorWithCache(std::move(executorWithCache)) {
551     // TODO: highly document the threading behavior of this class
552     mWorker = std::thread([this] { task(); });
553 }
554 
~ExecutionBurstServer()555 ExecutionBurstServer::~ExecutionBurstServer() {
556     // set teardown flag
557     mTeardown = true;
558     mRequestChannelReceiver->invalidate();
559 
560     // wait for task thread to end
561     mWorker.join();
562 }
563 
freeMemory(int32_t slot)564 hardware::Return<void> ExecutionBurstServer::freeMemory(int32_t slot) {
565     std::lock_guard<std::mutex> hold(mMutex);
566     mExecutorWithCache->removeCacheEntry(slot);
567     return hardware::Void();
568 }
569 
ensureCacheEntriesArePresentLocked(const std::vector<int32_t> & slots)570 void ExecutionBurstServer::ensureCacheEntriesArePresentLocked(const std::vector<int32_t>& slots) {
571     const auto slotIsKnown = [this](int32_t slot) {
572         return mExecutorWithCache->isCacheEntryPresent(slot);
573     };
574 
575     // find unique unknown slots
576     std::vector<int32_t> unknownSlots = slots;
577     auto unknownSlotsEnd = unknownSlots.end();
578     std::sort(unknownSlots.begin(), unknownSlotsEnd);
579     unknownSlotsEnd = std::unique(unknownSlots.begin(), unknownSlotsEnd);
580     unknownSlotsEnd = std::remove_if(unknownSlots.begin(), unknownSlotsEnd, slotIsKnown);
581     unknownSlots.erase(unknownSlotsEnd, unknownSlots.end());
582 
583     // quick-exit if all slots are known
584     if (unknownSlots.empty()) {
585         return;
586     }
587 
588     V1_0::ErrorStatus errorStatus = V1_0::ErrorStatus::GENERAL_FAILURE;
589     std::vector<hardware::hidl_memory> returnedMemories;
590     auto cb = [&errorStatus, &returnedMemories](
591                       V1_0::ErrorStatus status,
592                       const hardware::hidl_vec<hardware::hidl_memory>& memories) {
593         errorStatus = status;
594         returnedMemories = memories;
595     };
596 
597     const hardware::Return<void> ret = mCallback->getMemories(unknownSlots, cb);
598 
599     if (!ret.isOk() || errorStatus != V1_0::ErrorStatus::NONE ||
600         returnedMemories.size() != unknownSlots.size()) {
601         LOG(ERROR) << "Error retrieving memories";
602         return;
603     }
604 
605     // add memories to unknown slots
606     for (size_t i = 0; i < unknownSlots.size(); ++i) {
607         mExecutorWithCache->addCacheEntry(returnedMemories[i], unknownSlots[i]);
608     }
609 }
610 
task()611 void ExecutionBurstServer::task() {
612     // loop until the burst object is being destroyed
613     while (!mTeardown) {
614         // receive request
615         auto arguments = mRequestChannelReceiver->getBlocking();
616 
617         // if the request packet was not properly received, return a generic
618         // error and skip the execution
619         //
620         // if the  burst is being torn down, skip the execution exection so the
621         // "task" function can end
622         if (!arguments) {
623             if (!mTeardown) {
624                 mResultChannelSender->send(V1_0::ErrorStatus::GENERAL_FAILURE, {}, kNoTiming);
625             }
626             continue;
627         }
628 
629         // otherwise begin tracing execution
630         NNTRACE_FULL(NNTRACE_LAYER_IPC, NNTRACE_PHASE_EXECUTION,
631                      "ExecutionBurstServer getting memory, executing, and returning results");
632 
633         // unpack the arguments; types are Request, std::vector<int32_t>, and
634         // MeasureTiming, respectively
635         const auto [requestWithoutPools, slotsOfPools, measure] = std::move(*arguments);
636 
637         // ensure executor with cache has required memory
638         std::lock_guard<std::mutex> hold(mMutex);
639         ensureCacheEntriesArePresentLocked(slotsOfPools);
640 
641         // perform computation; types are ErrorStatus, hidl_vec<OutputShape>,
642         // and Timing, respectively
643         const auto [errorStatus, outputShapes, returnedTiming] =
644                 mExecutorWithCache->execute(requestWithoutPools, slotsOfPools, measure);
645 
646         // return result
647         mResultChannelSender->send(errorStatus, outputShapes, returnedTiming);
648     }
649 }
650 
651 }  // namespace android::nn
652