1/*
2 * Copyright 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#undef LOG_TAG
18#define LOG_TAG "HwcComposer"
19
20#include <inttypes.h>
21#include <log/log.h>
22
23#include "ComposerHal.h"
24
25#include <android/hardware/graphics/composer/2.2/IComposer.h>
26#include <composer-command-buffer/2.2/ComposerCommandBuffer.h>
27#include <gui/BufferQueue.h>
28#include <hidl/HidlTransportUtils.h>
29
30namespace android {
31
32using hardware::Return;
33using hardware::hidl_vec;
34using hardware::hidl_handle;
35
36namespace Hwc2 {
37
38Composer::~Composer() = default;
39
40namespace {
41
42class BufferHandle {
43public:
44    BufferHandle(const native_handle_t* buffer)
45    {
46        // nullptr is not a valid handle to HIDL
47        mHandle = (buffer) ? buffer : native_handle_init(mStorage, 0, 0);
48    }
49
50    operator const hidl_handle&() const
51    {
52        return mHandle;
53    }
54
55private:
56    NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 0, 0);
57    hidl_handle mHandle;
58};
59
60class FenceHandle
61{
62public:
63    FenceHandle(int fd, bool owned)
64        : mOwned(owned)
65    {
66        native_handle_t* handle;
67        if (fd >= 0) {
68            handle = native_handle_init(mStorage, 1, 0);
69            handle->data[0] = fd;
70        } else {
71            // nullptr is not a valid handle to HIDL
72            handle = native_handle_init(mStorage, 0, 0);
73        }
74        mHandle = handle;
75    }
76
77    ~FenceHandle()
78    {
79        if (mOwned) {
80            native_handle_close(mHandle);
81        }
82    }
83
84    operator const hidl_handle&() const
85    {
86        return mHandle;
87    }
88
89private:
90    bool mOwned;
91    NATIVE_HANDLE_DECLARE_STORAGE(mStorage, 1, 0);
92    hidl_handle mHandle;
93};
94
95// assume NO_RESOURCES when Status::isOk returns false
96constexpr Error kDefaultError = Error::NO_RESOURCES;
97
98template<typename T, typename U>
99T unwrapRet(Return<T>& ret, const U& default_val)
100{
101    return (ret.isOk()) ? static_cast<T>(ret) :
102        static_cast<T>(default_val);
103}
104
105Error unwrapRet(Return<Error>& ret)
106{
107    return unwrapRet(ret, kDefaultError);
108}
109
110} // anonymous namespace
111
112namespace impl {
113
114Composer::CommandWriter::CommandWriter(uint32_t initialMaxSize)
115    : CommandWriterBase(initialMaxSize) {}
116
117Composer::CommandWriter::~CommandWriter()
118{
119}
120
121void Composer::CommandWriter::setLayerInfo(uint32_t type, uint32_t appId)
122{
123    constexpr uint16_t kSetLayerInfoLength = 2;
124    beginCommand(static_cast<V2_1::IComposerClient::Command>(
125                         IVrComposerClient::VrCommand::SET_LAYER_INFO),
126                 kSetLayerInfoLength);
127    write(type);
128    write(appId);
129    endCommand();
130}
131
132void Composer::CommandWriter::setClientTargetMetadata(
133        const IVrComposerClient::BufferMetadata& metadata)
134{
135    constexpr uint16_t kSetClientTargetMetadataLength = 7;
136    beginCommand(static_cast<V2_1::IComposerClient::Command>(
137                         IVrComposerClient::VrCommand::SET_CLIENT_TARGET_METADATA),
138                 kSetClientTargetMetadataLength);
139    writeBufferMetadata(metadata);
140    endCommand();
141}
142
143void Composer::CommandWriter::setLayerBufferMetadata(
144        const IVrComposerClient::BufferMetadata& metadata)
145{
146    constexpr uint16_t kSetLayerBufferMetadataLength = 7;
147    beginCommand(static_cast<V2_1::IComposerClient::Command>(
148                         IVrComposerClient::VrCommand::SET_LAYER_BUFFER_METADATA),
149                 kSetLayerBufferMetadataLength);
150    writeBufferMetadata(metadata);
151    endCommand();
152}
153
154void Composer::CommandWriter::writeBufferMetadata(
155        const IVrComposerClient::BufferMetadata& metadata)
156{
157    write(metadata.width);
158    write(metadata.height);
159    write(metadata.stride);
160    write(metadata.layerCount);
161    writeSigned(static_cast<int32_t>(metadata.format));
162    write64(metadata.usage);
163}
164
165Composer::Composer(const std::string& serviceName)
166    : mWriter(kWriterInitialSize),
167      mIsUsingVrComposer(serviceName == std::string("vr"))
168{
169    mComposer = V2_1::IComposer::getService(serviceName);
170
171    if (mComposer == nullptr) {
172        LOG_ALWAYS_FATAL("failed to get hwcomposer service");
173    }
174
175    mComposer->createClient(
176            [&](const auto& tmpError, const auto& tmpClient)
177            {
178                if (tmpError == Error::NONE) {
179                    mClient = tmpClient;
180                }
181            });
182    if (mClient == nullptr) {
183        LOG_ALWAYS_FATAL("failed to create composer client");
184    }
185
186    // 2.2 support is optional
187    sp<IComposer> composer_2_2 = IComposer::castFrom(mComposer);
188    if (composer_2_2 != nullptr) {
189        mClient_2_2 = IComposerClient::castFrom(mClient);
190        LOG_ALWAYS_FATAL_IF(mClient_2_2 == nullptr, "IComposer 2.2 did not return IComposerClient 2.2");
191    }
192
193    if (mIsUsingVrComposer) {
194        sp<IVrComposerClient> vrClient = IVrComposerClient::castFrom(mClient);
195        if (vrClient == nullptr) {
196            LOG_ALWAYS_FATAL("failed to create vr composer client");
197        }
198    }
199}
200
201Composer::~Composer() = default;
202
203std::vector<IComposer::Capability> Composer::getCapabilities()
204{
205    std::vector<IComposer::Capability> capabilities;
206    mComposer->getCapabilities(
207            [&](const auto& tmpCapabilities) {
208                capabilities = tmpCapabilities;
209            });
210
211    return capabilities;
212}
213
214std::string Composer::dumpDebugInfo()
215{
216    std::string info;
217    mComposer->dumpDebugInfo([&](const auto& tmpInfo) {
218        info = tmpInfo.c_str();
219    });
220
221    return info;
222}
223
224void Composer::registerCallback(const sp<IComposerCallback>& callback)
225{
226    auto ret = mClient->registerCallback(callback);
227    if (!ret.isOk()) {
228        ALOGE("failed to register IComposerCallback");
229    }
230}
231
232bool Composer::isRemote() {
233    return mClient->isRemote();
234}
235
236void Composer::resetCommands() {
237    mWriter.reset();
238}
239
240Error Composer::executeCommands() {
241    return execute();
242}
243
244uint32_t Composer::getMaxVirtualDisplayCount()
245{
246    auto ret = mClient->getMaxVirtualDisplayCount();
247    return unwrapRet(ret, 0);
248}
249
250Error Composer::createVirtualDisplay(uint32_t width, uint32_t height,
251            PixelFormat* format, Display* outDisplay)
252{
253    const uint32_t bufferSlotCount = 1;
254    Error error = kDefaultError;
255    if (mClient_2_2) {
256        mClient_2_2->createVirtualDisplay_2_2(width, height, *format, bufferSlotCount,
257                [&](const auto& tmpError, const auto& tmpDisplay,
258                    const auto& tmpFormat) {
259                    error = tmpError;
260                    if (error != Error::NONE) {
261                        return;
262                    }
263
264                    *outDisplay = tmpDisplay;
265                    *format = tmpFormat;
266                });
267    } else {
268        mClient->createVirtualDisplay(width, height,
269                static_cast<types::V1_0::PixelFormat>(*format), bufferSlotCount,
270                [&](const auto& tmpError, const auto& tmpDisplay,
271                    const auto& tmpFormat) {
272                    error = tmpError;
273                    if (error != Error::NONE) {
274                        return;
275                    }
276
277                    *outDisplay = tmpDisplay;
278                    *format = static_cast<PixelFormat>(tmpFormat);
279            });
280    }
281
282    return error;
283}
284
285Error Composer::destroyVirtualDisplay(Display display)
286{
287    auto ret = mClient->destroyVirtualDisplay(display);
288    return unwrapRet(ret);
289}
290
291Error Composer::acceptDisplayChanges(Display display)
292{
293    mWriter.selectDisplay(display);
294    mWriter.acceptDisplayChanges();
295    return Error::NONE;
296}
297
298Error Composer::createLayer(Display display, Layer* outLayer)
299{
300    Error error = kDefaultError;
301    mClient->createLayer(display, BufferQueue::NUM_BUFFER_SLOTS,
302            [&](const auto& tmpError, const auto& tmpLayer) {
303                error = tmpError;
304                if (error != Error::NONE) {
305                    return;
306                }
307
308                *outLayer = tmpLayer;
309            });
310
311    return error;
312}
313
314Error Composer::destroyLayer(Display display, Layer layer)
315{
316    auto ret = mClient->destroyLayer(display, layer);
317    return unwrapRet(ret);
318}
319
320Error Composer::getActiveConfig(Display display, Config* outConfig)
321{
322    Error error = kDefaultError;
323    mClient->getActiveConfig(display,
324            [&](const auto& tmpError, const auto& tmpConfig) {
325                error = tmpError;
326                if (error != Error::NONE) {
327                    return;
328                }
329
330                *outConfig = tmpConfig;
331            });
332
333    return error;
334}
335
336Error Composer::getChangedCompositionTypes(Display display,
337        std::vector<Layer>* outLayers,
338        std::vector<IComposerClient::Composition>* outTypes)
339{
340    mReader.takeChangedCompositionTypes(display, outLayers, outTypes);
341    return Error::NONE;
342}
343
344Error Composer::getColorModes(Display display,
345        std::vector<ColorMode>* outModes)
346{
347    Error error = kDefaultError;
348
349    if (mClient_2_2) {
350        mClient_2_2->getColorModes_2_2(display,
351                [&](const auto& tmpError, const auto& tmpModes) {
352                    error = tmpError;
353                    if (error != Error::NONE) {
354                        return;
355                    }
356
357                    *outModes = tmpModes;
358                });
359    } else {
360        mClient->getColorModes(display,
361                [&](const auto& tmpError, const auto& tmpModes) {
362                    error = tmpError;
363                    if (error != Error::NONE) {
364                        return;
365                    }
366                    for (types::V1_0::ColorMode colorMode : tmpModes) {
367                        outModes->push_back(static_cast<ColorMode>(colorMode));
368                    }
369                });
370    }
371
372    return error;
373}
374
375Error Composer::getDisplayAttribute(Display display, Config config,
376        IComposerClient::Attribute attribute, int32_t* outValue)
377{
378    Error error = kDefaultError;
379    mClient->getDisplayAttribute(display, config, attribute,
380            [&](const auto& tmpError, const auto& tmpValue) {
381                error = tmpError;
382                if (error != Error::NONE) {
383                    return;
384                }
385
386                *outValue = tmpValue;
387            });
388
389    return error;
390}
391
392Error Composer::getDisplayConfigs(Display display,
393        std::vector<Config>* outConfigs)
394{
395    Error error = kDefaultError;
396    mClient->getDisplayConfigs(display,
397            [&](const auto& tmpError, const auto& tmpConfigs) {
398                error = tmpError;
399                if (error != Error::NONE) {
400                    return;
401                }
402
403                *outConfigs = tmpConfigs;
404            });
405
406    return error;
407}
408
409Error Composer::getDisplayName(Display display, std::string* outName)
410{
411    Error error = kDefaultError;
412    mClient->getDisplayName(display,
413            [&](const auto& tmpError, const auto& tmpName) {
414                error = tmpError;
415                if (error != Error::NONE) {
416                    return;
417                }
418
419                *outName = tmpName.c_str();
420            });
421
422    return error;
423}
424
425Error Composer::getDisplayRequests(Display display,
426        uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
427        std::vector<uint32_t>* outLayerRequestMasks)
428{
429    mReader.takeDisplayRequests(display, outDisplayRequestMask,
430            outLayers, outLayerRequestMasks);
431    return Error::NONE;
432}
433
434Error Composer::getDisplayType(Display display,
435        IComposerClient::DisplayType* outType)
436{
437    Error error = kDefaultError;
438    mClient->getDisplayType(display,
439            [&](const auto& tmpError, const auto& tmpType) {
440                error = tmpError;
441                if (error != Error::NONE) {
442                    return;
443                }
444
445                *outType = tmpType;
446            });
447
448    return error;
449}
450
451Error Composer::getDozeSupport(Display display, bool* outSupport)
452{
453    Error error = kDefaultError;
454    mClient->getDozeSupport(display,
455            [&](const auto& tmpError, const auto& tmpSupport) {
456                error = tmpError;
457                if (error != Error::NONE) {
458                    return;
459                }
460
461                *outSupport = tmpSupport;
462            });
463
464    return error;
465}
466
467Error Composer::getHdrCapabilities(Display display,
468        std::vector<Hdr>* outTypes, float* outMaxLuminance,
469        float* outMaxAverageLuminance, float* outMinLuminance)
470{
471    Error error = kDefaultError;
472    mClient->getHdrCapabilities(display,
473            [&](const auto& tmpError, const auto& tmpTypes,
474                const auto& tmpMaxLuminance,
475                const auto& tmpMaxAverageLuminance,
476                const auto& tmpMinLuminance) {
477                error = tmpError;
478                if (error != Error::NONE) {
479                    return;
480                }
481
482                *outTypes = tmpTypes;
483                *outMaxLuminance = tmpMaxLuminance;
484                *outMaxAverageLuminance = tmpMaxAverageLuminance;
485                *outMinLuminance = tmpMinLuminance;
486            });
487
488    return error;
489}
490
491Error Composer::getReleaseFences(Display display,
492        std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
493{
494    mReader.takeReleaseFences(display, outLayers, outReleaseFences);
495    return Error::NONE;
496}
497
498Error Composer::presentDisplay(Display display, int* outPresentFence)
499{
500    mWriter.selectDisplay(display);
501    mWriter.presentDisplay();
502
503    Error error = execute();
504    if (error != Error::NONE) {
505        return error;
506    }
507
508    mReader.takePresentFence(display, outPresentFence);
509
510    return Error::NONE;
511}
512
513Error Composer::setActiveConfig(Display display, Config config)
514{
515    auto ret = mClient->setActiveConfig(display, config);
516    return unwrapRet(ret);
517}
518
519Error Composer::setClientTarget(Display display, uint32_t slot,
520        const sp<GraphicBuffer>& target,
521        int acquireFence, Dataspace dataspace,
522        const std::vector<IComposerClient::Rect>& damage)
523{
524    mWriter.selectDisplay(display);
525    if (mIsUsingVrComposer && target.get()) {
526        IVrComposerClient::BufferMetadata metadata = {
527            .width = target->getWidth(),
528            .height = target->getHeight(),
529            .stride = target->getStride(),
530            .layerCount = target->getLayerCount(),
531            .format = static_cast<types::V1_0::PixelFormat>(target->getPixelFormat()),
532            .usage = target->getUsage(),
533        };
534        mWriter.setClientTargetMetadata(metadata);
535    }
536
537    const native_handle_t* handle = nullptr;
538    if (target.get()) {
539        handle = target->getNativeBuffer()->handle;
540    }
541
542    mWriter.setClientTarget(slot, handle, acquireFence, dataspace, damage);
543    return Error::NONE;
544}
545
546Error Composer::setColorMode(Display display, ColorMode mode,
547        RenderIntent renderIntent)
548{
549    hardware::Return<Error> ret(kDefaultError);
550    if (mClient_2_2) {
551        ret = mClient_2_2->setColorMode_2_2(display, mode, renderIntent);
552    } else {
553        ret = mClient->setColorMode(display,
554                static_cast<types::V1_0::ColorMode>(mode));
555    }
556    return unwrapRet(ret);
557}
558
559Error Composer::setColorTransform(Display display, const float* matrix,
560        ColorTransform hint)
561{
562    mWriter.selectDisplay(display);
563    mWriter.setColorTransform(matrix, hint);
564    return Error::NONE;
565}
566
567Error Composer::setOutputBuffer(Display display, const native_handle_t* buffer,
568        int releaseFence)
569{
570    mWriter.selectDisplay(display);
571    mWriter.setOutputBuffer(0, buffer, dup(releaseFence));
572    return Error::NONE;
573}
574
575Error Composer::setPowerMode(Display display, IComposerClient::PowerMode mode) {
576    Return<Error> ret(Error::UNSUPPORTED);
577    if (mClient_2_2) {
578        ret = mClient_2_2->setPowerMode_2_2(display, mode);
579    } else if (mode != IComposerClient::PowerMode::ON_SUSPEND) {
580        ret = mClient->setPowerMode(display, static_cast<V2_1::IComposerClient::PowerMode>(mode));
581    }
582
583    return unwrapRet(ret);
584}
585
586Error Composer::setVsyncEnabled(Display display, IComposerClient::Vsync enabled)
587{
588    auto ret = mClient->setVsyncEnabled(display, enabled);
589    return unwrapRet(ret);
590}
591
592Error Composer::setClientTargetSlotCount(Display display)
593{
594    const uint32_t bufferSlotCount = BufferQueue::NUM_BUFFER_SLOTS;
595    auto ret = mClient->setClientTargetSlotCount(display, bufferSlotCount);
596    return unwrapRet(ret);
597}
598
599Error Composer::validateDisplay(Display display, uint32_t* outNumTypes,
600        uint32_t* outNumRequests)
601{
602    mWriter.selectDisplay(display);
603    mWriter.validateDisplay();
604
605    Error error = execute();
606    if (error != Error::NONE) {
607        return error;
608    }
609
610    mReader.hasChanges(display, outNumTypes, outNumRequests);
611
612    return Error::NONE;
613}
614
615Error Composer::presentOrValidateDisplay(Display display, uint32_t* outNumTypes,
616                               uint32_t* outNumRequests, int* outPresentFence, uint32_t* state) {
617   mWriter.selectDisplay(display);
618   mWriter.presentOrvalidateDisplay();
619
620   Error error = execute();
621   if (error != Error::NONE) {
622       return error;
623   }
624
625   mReader.takePresentOrValidateStage(display, state);
626
627   if (*state == 1) { // Present succeeded
628       mReader.takePresentFence(display, outPresentFence);
629   }
630
631   if (*state == 0) { // Validate succeeded.
632       mReader.hasChanges(display, outNumTypes, outNumRequests);
633   }
634
635   return Error::NONE;
636}
637
638Error Composer::setCursorPosition(Display display, Layer layer,
639        int32_t x, int32_t y)
640{
641    mWriter.selectDisplay(display);
642    mWriter.selectLayer(layer);
643    mWriter.setLayerCursorPosition(x, y);
644    return Error::NONE;
645}
646
647Error Composer::setLayerBuffer(Display display, Layer layer,
648        uint32_t slot, const sp<GraphicBuffer>& buffer, int acquireFence)
649{
650    mWriter.selectDisplay(display);
651    mWriter.selectLayer(layer);
652    if (mIsUsingVrComposer && buffer.get()) {
653        IVrComposerClient::BufferMetadata metadata = {
654            .width = buffer->getWidth(),
655            .height = buffer->getHeight(),
656            .stride = buffer->getStride(),
657            .layerCount = buffer->getLayerCount(),
658            .format = static_cast<types::V1_0::PixelFormat>(buffer->getPixelFormat()),
659            .usage = buffer->getUsage(),
660        };
661        mWriter.setLayerBufferMetadata(metadata);
662    }
663
664    const native_handle_t* handle = nullptr;
665    if (buffer.get()) {
666        handle = buffer->getNativeBuffer()->handle;
667    }
668
669    mWriter.setLayerBuffer(slot, handle, acquireFence);
670    return Error::NONE;
671}
672
673Error Composer::setLayerSurfaceDamage(Display display, Layer layer,
674        const std::vector<IComposerClient::Rect>& damage)
675{
676    mWriter.selectDisplay(display);
677    mWriter.selectLayer(layer);
678    mWriter.setLayerSurfaceDamage(damage);
679    return Error::NONE;
680}
681
682Error Composer::setLayerBlendMode(Display display, Layer layer,
683        IComposerClient::BlendMode mode)
684{
685    mWriter.selectDisplay(display);
686    mWriter.selectLayer(layer);
687    mWriter.setLayerBlendMode(mode);
688    return Error::NONE;
689}
690
691Error Composer::setLayerColor(Display display, Layer layer,
692        const IComposerClient::Color& color)
693{
694    mWriter.selectDisplay(display);
695    mWriter.selectLayer(layer);
696    mWriter.setLayerColor(color);
697    return Error::NONE;
698}
699
700Error Composer::setLayerCompositionType(Display display, Layer layer,
701        IComposerClient::Composition type)
702{
703    mWriter.selectDisplay(display);
704    mWriter.selectLayer(layer);
705    mWriter.setLayerCompositionType(type);
706    return Error::NONE;
707}
708
709Error Composer::setLayerDataspace(Display display, Layer layer,
710        Dataspace dataspace)
711{
712    mWriter.selectDisplay(display);
713    mWriter.selectLayer(layer);
714    mWriter.setLayerDataspace(dataspace);
715    return Error::NONE;
716}
717
718Error Composer::setLayerDisplayFrame(Display display, Layer layer,
719        const IComposerClient::Rect& frame)
720{
721    mWriter.selectDisplay(display);
722    mWriter.selectLayer(layer);
723    mWriter.setLayerDisplayFrame(frame);
724    return Error::NONE;
725}
726
727Error Composer::setLayerPlaneAlpha(Display display, Layer layer,
728        float alpha)
729{
730    mWriter.selectDisplay(display);
731    mWriter.selectLayer(layer);
732    mWriter.setLayerPlaneAlpha(alpha);
733    return Error::NONE;
734}
735
736Error Composer::setLayerSidebandStream(Display display, Layer layer,
737        const native_handle_t* stream)
738{
739    mWriter.selectDisplay(display);
740    mWriter.selectLayer(layer);
741    mWriter.setLayerSidebandStream(stream);
742    return Error::NONE;
743}
744
745Error Composer::setLayerSourceCrop(Display display, Layer layer,
746        const IComposerClient::FRect& crop)
747{
748    mWriter.selectDisplay(display);
749    mWriter.selectLayer(layer);
750    mWriter.setLayerSourceCrop(crop);
751    return Error::NONE;
752}
753
754Error Composer::setLayerTransform(Display display, Layer layer,
755        Transform transform)
756{
757    mWriter.selectDisplay(display);
758    mWriter.selectLayer(layer);
759    mWriter.setLayerTransform(transform);
760    return Error::NONE;
761}
762
763Error Composer::setLayerVisibleRegion(Display display, Layer layer,
764        const std::vector<IComposerClient::Rect>& visible)
765{
766    mWriter.selectDisplay(display);
767    mWriter.selectLayer(layer);
768    mWriter.setLayerVisibleRegion(visible);
769    return Error::NONE;
770}
771
772Error Composer::setLayerZOrder(Display display, Layer layer, uint32_t z)
773{
774    mWriter.selectDisplay(display);
775    mWriter.selectLayer(layer);
776    mWriter.setLayerZOrder(z);
777    return Error::NONE;
778}
779
780Error Composer::setLayerInfo(Display display, Layer layer, uint32_t type,
781                             uint32_t appId)
782{
783    if (mIsUsingVrComposer) {
784        mWriter.selectDisplay(display);
785        mWriter.selectLayer(layer);
786        mWriter.setLayerInfo(type, appId);
787    }
788    return Error::NONE;
789}
790
791Error Composer::execute()
792{
793    // prepare input command queue
794    bool queueChanged = false;
795    uint32_t commandLength = 0;
796    hidl_vec<hidl_handle> commandHandles;
797    if (!mWriter.writeQueue(&queueChanged, &commandLength, &commandHandles)) {
798        mWriter.reset();
799        return Error::NO_RESOURCES;
800    }
801
802    // set up new input command queue if necessary
803    if (queueChanged) {
804        auto ret = mClient->setInputCommandQueue(*mWriter.getMQDescriptor());
805        auto error = unwrapRet(ret);
806        if (error != Error::NONE) {
807            mWriter.reset();
808            return error;
809        }
810    }
811
812    if (commandLength == 0) {
813        mWriter.reset();
814        return Error::NONE;
815    }
816
817    Error error = kDefaultError;
818    hardware::Return<void> ret;
819    auto hidl_callback = [&](const auto& tmpError, const auto& tmpOutChanged,
820                             const auto& tmpOutLength, const auto& tmpOutHandles)
821                         {
822                             error = tmpError;
823
824                             // set up new output command queue if necessary
825                             if (error == Error::NONE && tmpOutChanged) {
826                                 error = kDefaultError;
827                                 mClient->getOutputCommandQueue(
828                                     [&](const auto& tmpError,
829                                         const auto& tmpDescriptor)
830                                     {
831                                         error = tmpError;
832                                         if (error != Error::NONE) {
833                                             return;
834                                     }
835
836                                     mReader.setMQDescriptor(tmpDescriptor);
837                                 });
838                             }
839
840                             if (error != Error::NONE) {
841                                 return;
842                             }
843
844                             if (mReader.readQueue(tmpOutLength, tmpOutHandles)) {
845                                 error = mReader.parse();
846                                 mReader.reset();
847                             } else {
848                                 error = Error::NO_RESOURCES;
849                             }
850                         };
851    if (mClient_2_2) {
852        ret = mClient_2_2->executeCommands_2_2(commandLength, commandHandles, hidl_callback);
853    } else {
854        ret = mClient->executeCommands(commandLength, commandHandles, hidl_callback);
855    }
856    // executeCommands can fail because of out-of-fd and we do not want to
857    // abort() in that case
858    if (!ret.isOk()) {
859        ALOGE("executeCommands failed because of %s", ret.description().c_str());
860    }
861
862    if (error == Error::NONE) {
863        std::vector<CommandReader::CommandError> commandErrors =
864            mReader.takeErrors();
865
866        for (const auto& cmdErr : commandErrors) {
867            auto command =
868                    static_cast<IComposerClient::Command>(mWriter.getCommand(cmdErr.location));
869
870            if (command == IComposerClient::Command::VALIDATE_DISPLAY ||
871                command == IComposerClient::Command::PRESENT_DISPLAY ||
872                command == IComposerClient::Command::PRESENT_OR_VALIDATE_DISPLAY) {
873                error = cmdErr.error;
874            } else {
875                ALOGW("command 0x%x generated error %d",
876                        command, cmdErr.error);
877            }
878        }
879    }
880
881    mWriter.reset();
882
883    return error;
884}
885
886// Composer HAL 2.2
887
888Error Composer::setLayerPerFrameMetadata(Display display, Layer layer,
889        const std::vector<IComposerClient::PerFrameMetadata>& perFrameMetadatas) {
890    if (!mClient_2_2) {
891        return Error::UNSUPPORTED;
892    }
893
894    mWriter.selectDisplay(display);
895    mWriter.selectLayer(layer);
896    mWriter.setLayerPerFrameMetadata(perFrameMetadatas);
897    return Error::NONE;
898}
899
900Error Composer::getPerFrameMetadataKeys(
901        Display display, std::vector<IComposerClient::PerFrameMetadataKey>* outKeys) {
902    if (!mClient_2_2) {
903        return Error::UNSUPPORTED;
904    }
905
906    Error error = kDefaultError;
907    mClient_2_2->getPerFrameMetadataKeys(display, [&](const auto& tmpError, const auto& tmpKeys) {
908        error = tmpError;
909        if (error != Error::NONE) {
910            return;
911        }
912
913        *outKeys = tmpKeys;
914    });
915
916    return error;
917}
918
919Error Composer::getRenderIntents(Display display, ColorMode colorMode,
920        std::vector<RenderIntent>* outRenderIntents) {
921    if (!mClient_2_2) {
922        outRenderIntents->push_back(RenderIntent::COLORIMETRIC);
923        return Error::NONE;
924    }
925
926    Error error = kDefaultError;
927    mClient_2_2->getRenderIntents(display, colorMode,
928            [&](const auto& tmpError, const auto& tmpKeys) {
929        error = tmpError;
930        if (error != Error::NONE) {
931            return;
932        }
933
934        *outRenderIntents = tmpKeys;
935    });
936
937    return error;
938}
939
940Error Composer::getDataspaceSaturationMatrix(Dataspace dataspace, mat4* outMatrix)
941{
942    if (!mClient_2_2) {
943        *outMatrix = mat4();
944        return Error::NONE;
945    }
946
947    Error error = kDefaultError;
948    mClient_2_2->getDataspaceSaturationMatrix(dataspace, [&](const auto& tmpError, const auto& tmpMatrix) {
949        error = tmpError;
950        if (error != Error::NONE) {
951            return;
952        }
953
954        *outMatrix = mat4(tmpMatrix.data());
955    });
956
957    return error;
958}
959
960CommandReader::~CommandReader()
961{
962    resetData();
963}
964
965Error CommandReader::parse()
966{
967    resetData();
968
969    IComposerClient::Command command;
970    uint16_t length = 0;
971
972    while (!isEmpty()) {
973        auto command_2_1 = reinterpret_cast<V2_1::IComposerClient::Command*>(&command);
974        if (!beginCommand(command_2_1, &length)) {
975            break;
976        }
977
978        bool parsed = false;
979        switch (command) {
980        case IComposerClient::Command::SELECT_DISPLAY:
981            parsed = parseSelectDisplay(length);
982            break;
983        case IComposerClient::Command::SET_ERROR:
984            parsed = parseSetError(length);
985            break;
986        case IComposerClient::Command::SET_CHANGED_COMPOSITION_TYPES:
987            parsed = parseSetChangedCompositionTypes(length);
988            break;
989        case IComposerClient::Command::SET_DISPLAY_REQUESTS:
990            parsed = parseSetDisplayRequests(length);
991            break;
992        case IComposerClient::Command::SET_PRESENT_FENCE:
993            parsed = parseSetPresentFence(length);
994            break;
995        case IComposerClient::Command::SET_RELEASE_FENCES:
996            parsed = parseSetReleaseFences(length);
997            break;
998        case IComposerClient::Command ::SET_PRESENT_OR_VALIDATE_DISPLAY_RESULT:
999            parsed = parseSetPresentOrValidateDisplayResult(length);
1000            break;
1001        default:
1002            parsed = false;
1003            break;
1004        }
1005
1006        endCommand();
1007
1008        if (!parsed) {
1009            ALOGE("failed to parse command 0x%x length %" PRIu16,
1010                    command, length);
1011            break;
1012        }
1013    }
1014
1015    return isEmpty() ? Error::NONE : Error::NO_RESOURCES;
1016}
1017
1018bool CommandReader::parseSelectDisplay(uint16_t length)
1019{
1020    if (length != CommandWriterBase::kSelectDisplayLength) {
1021        return false;
1022    }
1023
1024    mCurrentReturnData = &mReturnData[read64()];
1025
1026    return true;
1027}
1028
1029bool CommandReader::parseSetError(uint16_t length)
1030{
1031    if (length != CommandWriterBase::kSetErrorLength) {
1032        return false;
1033    }
1034
1035    auto location = read();
1036    auto error = static_cast<Error>(readSigned());
1037
1038    mErrors.emplace_back(CommandError{location, error});
1039
1040    return true;
1041}
1042
1043bool CommandReader::parseSetChangedCompositionTypes(uint16_t length)
1044{
1045    // (layer id, composition type) pairs
1046    if (length % 3 != 0 || !mCurrentReturnData) {
1047        return false;
1048    }
1049
1050    uint32_t count = length / 3;
1051    mCurrentReturnData->changedLayers.reserve(count);
1052    mCurrentReturnData->compositionTypes.reserve(count);
1053    while (count > 0) {
1054        auto layer = read64();
1055        auto type = static_cast<IComposerClient::Composition>(readSigned());
1056
1057        mCurrentReturnData->changedLayers.push_back(layer);
1058        mCurrentReturnData->compositionTypes.push_back(type);
1059
1060        count--;
1061    }
1062
1063    return true;
1064}
1065
1066bool CommandReader::parseSetDisplayRequests(uint16_t length)
1067{
1068    // display requests followed by (layer id, layer requests) pairs
1069    if (length % 3 != 1 || !mCurrentReturnData) {
1070        return false;
1071    }
1072
1073    mCurrentReturnData->displayRequests = read();
1074
1075    uint32_t count = (length - 1) / 3;
1076    mCurrentReturnData->requestedLayers.reserve(count);
1077    mCurrentReturnData->requestMasks.reserve(count);
1078    while (count > 0) {
1079        auto layer = read64();
1080        auto layerRequestMask = read();
1081
1082        mCurrentReturnData->requestedLayers.push_back(layer);
1083        mCurrentReturnData->requestMasks.push_back(layerRequestMask);
1084
1085        count--;
1086    }
1087
1088    return true;
1089}
1090
1091bool CommandReader::parseSetPresentFence(uint16_t length)
1092{
1093    if (length != CommandWriterBase::kSetPresentFenceLength ||
1094            !mCurrentReturnData) {
1095        return false;
1096    }
1097
1098    if (mCurrentReturnData->presentFence >= 0) {
1099        close(mCurrentReturnData->presentFence);
1100    }
1101    mCurrentReturnData->presentFence = readFence();
1102
1103    return true;
1104}
1105
1106bool CommandReader::parseSetReleaseFences(uint16_t length)
1107{
1108    // (layer id, release fence index) pairs
1109    if (length % 3 != 0 || !mCurrentReturnData) {
1110        return false;
1111    }
1112
1113    uint32_t count = length / 3;
1114    mCurrentReturnData->releasedLayers.reserve(count);
1115    mCurrentReturnData->releaseFences.reserve(count);
1116    while (count > 0) {
1117        auto layer = read64();
1118        auto fence = readFence();
1119
1120        mCurrentReturnData->releasedLayers.push_back(layer);
1121        mCurrentReturnData->releaseFences.push_back(fence);
1122
1123        count--;
1124    }
1125
1126    return true;
1127}
1128
1129bool CommandReader::parseSetPresentOrValidateDisplayResult(uint16_t length)
1130{
1131    if (length != CommandWriterBase::kPresentOrValidateDisplayResultLength || !mCurrentReturnData) {
1132        return false;
1133    }
1134    mCurrentReturnData->presentOrValidateState = read();
1135    return true;
1136}
1137
1138void CommandReader::resetData()
1139{
1140    mErrors.clear();
1141
1142    for (auto& data : mReturnData) {
1143        if (data.second.presentFence >= 0) {
1144            close(data.second.presentFence);
1145        }
1146        for (auto fence : data.second.releaseFences) {
1147            if (fence >= 0) {
1148                close(fence);
1149            }
1150        }
1151    }
1152
1153    mReturnData.clear();
1154    mCurrentReturnData = nullptr;
1155}
1156
1157std::vector<CommandReader::CommandError> CommandReader::takeErrors()
1158{
1159    return std::move(mErrors);
1160}
1161
1162bool CommandReader::hasChanges(Display display,
1163        uint32_t* outNumChangedCompositionTypes,
1164        uint32_t* outNumLayerRequestMasks) const
1165{
1166    auto found = mReturnData.find(display);
1167    if (found == mReturnData.end()) {
1168        *outNumChangedCompositionTypes = 0;
1169        *outNumLayerRequestMasks = 0;
1170        return false;
1171    }
1172
1173    const ReturnData& data = found->second;
1174
1175    *outNumChangedCompositionTypes = data.compositionTypes.size();
1176    *outNumLayerRequestMasks = data.requestMasks.size();
1177
1178    return !(data.compositionTypes.empty() && data.requestMasks.empty());
1179}
1180
1181void CommandReader::takeChangedCompositionTypes(Display display,
1182        std::vector<Layer>* outLayers,
1183        std::vector<IComposerClient::Composition>* outTypes)
1184{
1185    auto found = mReturnData.find(display);
1186    if (found == mReturnData.end()) {
1187        outLayers->clear();
1188        outTypes->clear();
1189        return;
1190    }
1191
1192    ReturnData& data = found->second;
1193
1194    *outLayers = std::move(data.changedLayers);
1195    *outTypes = std::move(data.compositionTypes);
1196}
1197
1198void CommandReader::takeDisplayRequests(Display display,
1199        uint32_t* outDisplayRequestMask, std::vector<Layer>* outLayers,
1200        std::vector<uint32_t>* outLayerRequestMasks)
1201{
1202    auto found = mReturnData.find(display);
1203    if (found == mReturnData.end()) {
1204        *outDisplayRequestMask = 0;
1205        outLayers->clear();
1206        outLayerRequestMasks->clear();
1207        return;
1208    }
1209
1210    ReturnData& data = found->second;
1211
1212    *outDisplayRequestMask = data.displayRequests;
1213    *outLayers = std::move(data.requestedLayers);
1214    *outLayerRequestMasks = std::move(data.requestMasks);
1215}
1216
1217void CommandReader::takeReleaseFences(Display display,
1218        std::vector<Layer>* outLayers, std::vector<int>* outReleaseFences)
1219{
1220    auto found = mReturnData.find(display);
1221    if (found == mReturnData.end()) {
1222        outLayers->clear();
1223        outReleaseFences->clear();
1224        return;
1225    }
1226
1227    ReturnData& data = found->second;
1228
1229    *outLayers = std::move(data.releasedLayers);
1230    *outReleaseFences = std::move(data.releaseFences);
1231}
1232
1233void CommandReader::takePresentFence(Display display, int* outPresentFence)
1234{
1235    auto found = mReturnData.find(display);
1236    if (found == mReturnData.end()) {
1237        *outPresentFence = -1;
1238        return;
1239    }
1240
1241    ReturnData& data = found->second;
1242
1243    *outPresentFence = data.presentFence;
1244    data.presentFence = -1;
1245}
1246
1247void CommandReader::takePresentOrValidateStage(Display display, uint32_t* state) {
1248    auto found = mReturnData.find(display);
1249    if (found == mReturnData.end()) {
1250        *state= -1;
1251        return;
1252    }
1253    ReturnData& data = found->second;
1254    *state = data.presentOrValidateState;
1255}
1256
1257} // namespace impl
1258
1259} // namespace Hwc2
1260
1261} // namespace android
1262