HWComposer.cpp revision 15b27e0e63dc1528ab2ddf1875f4d5a029059e5a
1/*
2 * Copyright (C) 2010 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_NDEBUG 0
18
19#undef LOG_TAG
20#define LOG_TAG "HWComposer"
21#define ATRACE_TAG ATRACE_TAG_GRAPHICS
22
23#include <inttypes.h>
24#include <math.h>
25#include <stdint.h>
26#include <stdio.h>
27#include <stdlib.h>
28#include <string.h>
29#include <sys/types.h>
30
31#include <utils/Errors.h>
32#include <utils/misc.h>
33#include <utils/NativeHandle.h>
34#include <utils/String8.h>
35#include <utils/Thread.h>
36#include <utils/Trace.h>
37#include <utils/Vector.h>
38
39#include <ui/GraphicBuffer.h>
40
41#include <hardware/hardware.h>
42#include <hardware/hwcomposer.h>
43
44#include <android/configuration.h>
45
46#include <cutils/properties.h>
47#include <log/log.h>
48
49#include "HWComposer.h"
50#include "hwc2on1adapter/HWC2On1Adapter.h"
51#include "HWC2.h"
52#include "ComposerHal.h"
53
54#include "../Layer.h"           // needed only for debugging
55#include "../SurfaceFlinger.h"
56
57namespace android {
58
59#define MIN_HWC_HEADER_VERSION HWC_HEADER_VERSION
60
61// ---------------------------------------------------------------------------
62
63HWComposer::HWComposer(bool useVrComposer)
64    : mAdapter(),
65      mHwcDevice(),
66      mDisplayData(2),
67      mFreeDisplaySlots(),
68      mHwcDisplaySlots(),
69      mCBContext(),
70      mEventHandler(nullptr),
71      mVSyncCounts(),
72      mRemainingHwcVirtualDisplays(0)
73{
74    for (size_t i=0 ; i<HWC_NUM_PHYSICAL_DISPLAY_TYPES ; i++) {
75        mLastHwVSync[i] = 0;
76        mVSyncCounts[i] = 0;
77    }
78
79    loadHwcModule(useVrComposer);
80}
81
82HWComposer::~HWComposer() {}
83
84void HWComposer::setEventHandler(EventHandler* handler)
85{
86    if (handler == nullptr) {
87        ALOGE("setEventHandler: Rejected attempt to clear handler");
88        return;
89    }
90
91    bool wasNull = (mEventHandler == nullptr);
92    mEventHandler = handler;
93
94    if (wasNull) {
95        auto hotplugHook = std::bind(&HWComposer::hotplug, this,
96                std::placeholders::_1, std::placeholders::_2);
97        mHwcDevice->registerHotplugCallback(hotplugHook);
98        auto invalidateHook = std::bind(&HWComposer::invalidate, this,
99                std::placeholders::_1);
100        mHwcDevice->registerRefreshCallback(invalidateHook);
101        auto vsyncHook = std::bind(&HWComposer::vsync, this,
102                std::placeholders::_1, std::placeholders::_2);
103        mHwcDevice->registerVsyncCallback(vsyncHook);
104    }
105}
106
107// Load and prepare the hardware composer module.  Sets mHwc.
108void HWComposer::loadHwcModule(bool useVrComposer)
109{
110    ALOGV("loadHwcModule");
111
112#ifdef BYPASS_IHWC
113    (void)useVrComposer; // Silence unused parameter warning.
114
115    hw_module_t const* module;
116
117    if (hw_get_module(HWC_HARDWARE_MODULE_ID, &module) != 0) {
118        ALOGE("%s module not found, aborting", HWC_HARDWARE_MODULE_ID);
119        abort();
120    }
121
122    hw_device_t* device = nullptr;
123    int error = module->methods->open(module, HWC_HARDWARE_COMPOSER, &device);
124    if (error != 0) {
125        ALOGE("Failed to open HWC device (%s), aborting", strerror(-error));
126        abort();
127    }
128
129    uint32_t majorVersion = (device->version >> 24) & 0xF;
130    if (majorVersion == 2) {
131        mHwcDevice = std::make_unique<HWC2::Device>(
132                reinterpret_cast<hwc2_device_t*>(device));
133    } else {
134        mAdapter = std::make_unique<HWC2On1Adapter>(
135                reinterpret_cast<hwc_composer_device_1_t*>(device));
136        uint8_t minorVersion = mAdapter->getHwc1MinorVersion();
137        if (minorVersion < 1) {
138            ALOGE("Cannot adapt to HWC version %d.%d",
139                    static_cast<int32_t>((minorVersion >> 8) & 0xF),
140                    static_cast<int32_t>(minorVersion & 0xF));
141            abort();
142        }
143        mHwcDevice = std::make_unique<HWC2::Device>(
144                static_cast<hwc2_device_t*>(mAdapter.get()));
145    }
146#else
147    mHwcDevice = std::make_unique<HWC2::Device>(useVrComposer);
148#endif
149
150    mRemainingHwcVirtualDisplays = mHwcDevice->getMaxVirtualDisplayCount();
151}
152
153bool HWComposer::hasCapability(HWC2::Capability capability) const
154{
155    return mHwcDevice->getCapabilities().count(capability) > 0;
156}
157
158bool HWComposer::isValidDisplay(int32_t displayId) const {
159    return static_cast<size_t>(displayId) < mDisplayData.size() &&
160            mDisplayData[displayId].hwcDisplay;
161}
162
163void HWComposer::validateChange(HWC2::Composition from, HWC2::Composition to) {
164    bool valid = true;
165    switch (from) {
166        case HWC2::Composition::Client:
167            valid = false;
168            break;
169        case HWC2::Composition::Device:
170        case HWC2::Composition::SolidColor:
171            valid = (to == HWC2::Composition::Client);
172            break;
173        case HWC2::Composition::Cursor:
174        case HWC2::Composition::Sideband:
175            valid = (to == HWC2::Composition::Client ||
176                    to == HWC2::Composition::Device);
177            break;
178        default:
179            break;
180    }
181
182    if (!valid) {
183        ALOGE("Invalid layer type change: %s --> %s", to_string(from).c_str(),
184                to_string(to).c_str());
185    }
186}
187
188void HWComposer::hotplug(const std::shared_ptr<HWC2::Display>& display,
189        HWC2::Connection connected) {
190    ALOGV("hotplug: %" PRIu64 ", %s", display->getId(),
191            to_string(connected).c_str());
192    int32_t disp = 0;
193    if (!mDisplayData[0].hwcDisplay) {
194        ALOGE_IF(connected != HWC2::Connection::Connected, "Assumed primary"
195                " display would be connected");
196        mDisplayData[0].hwcDisplay = display;
197        mHwcDisplaySlots[display->getId()] = 0;
198        disp = DisplayDevice::DISPLAY_PRIMARY;
199    } else {
200        // Disconnect is handled through HWComposer::disconnectDisplay via
201        // SurfaceFlinger's onHotplugReceived callback handling
202        if (connected == HWC2::Connection::Connected) {
203            mDisplayData[1].hwcDisplay = display;
204            mHwcDisplaySlots[display->getId()] = 1;
205        }
206        disp = DisplayDevice::DISPLAY_EXTERNAL;
207    }
208    mEventHandler->onHotplugReceived(this, disp,
209            connected == HWC2::Connection::Connected);
210}
211
212void HWComposer::invalidate(const std::shared_ptr<HWC2::Display>& /*display*/) {
213    mEventHandler->onInvalidateReceived(this);
214}
215
216void HWComposer::vsync(const std::shared_ptr<HWC2::Display>& display,
217        int64_t timestamp) {
218    auto displayType = HWC2::DisplayType::Invalid;
219    auto error = display->getType(&displayType);
220    if (error != HWC2::Error::None) {
221        ALOGE("vsync: Failed to determine type of display %" PRIu64,
222                display->getId());
223        return;
224    }
225
226    if (displayType == HWC2::DisplayType::Virtual) {
227        ALOGE("Virtual display %" PRIu64 " passed to vsync callback",
228                display->getId());
229        return;
230    }
231
232    if (mHwcDisplaySlots.count(display->getId()) == 0) {
233        ALOGE("Unknown physical display %" PRIu64 " passed to vsync callback",
234                display->getId());
235        return;
236    }
237
238    int32_t disp = mHwcDisplaySlots[display->getId()];
239    {
240        Mutex::Autolock _l(mLock);
241
242        // There have been reports of HWCs that signal several vsync events
243        // with the same timestamp when turning the display off and on. This
244        // is a bug in the HWC implementation, but filter the extra events
245        // out here so they don't cause havoc downstream.
246        if (timestamp == mLastHwVSync[disp]) {
247            ALOGW("Ignoring duplicate VSYNC event from HWC (t=%" PRId64 ")",
248                    timestamp);
249            return;
250        }
251
252        mLastHwVSync[disp] = timestamp;
253    }
254
255    char tag[16];
256    snprintf(tag, sizeof(tag), "HW_VSYNC_%1u", disp);
257    ATRACE_INT(tag, ++mVSyncCounts[disp] & 1);
258
259    mEventHandler->onVSyncReceived(this, disp, timestamp);
260}
261
262status_t HWComposer::allocateVirtualDisplay(uint32_t width, uint32_t height,
263        android_pixel_format_t* format, int32_t *outId) {
264    if (mRemainingHwcVirtualDisplays == 0) {
265        ALOGE("allocateVirtualDisplay: No remaining virtual displays");
266        return NO_MEMORY;
267    }
268
269    if (SurfaceFlinger::maxVirtualDisplaySize != 0 &&
270        (width > SurfaceFlinger::maxVirtualDisplaySize ||
271         height > SurfaceFlinger::maxVirtualDisplaySize)) {
272        ALOGE("createVirtualDisplay: Can't create a virtual display with"
273                      " a dimension > %" PRIu64 " (tried %u x %u)",
274              SurfaceFlinger::maxVirtualDisplaySize, width, height);
275        return INVALID_OPERATION;
276    }
277
278    std::shared_ptr<HWC2::Display> display;
279    auto error = mHwcDevice->createVirtualDisplay(width, height, format,
280            &display);
281    if (error != HWC2::Error::None) {
282        ALOGE("allocateVirtualDisplay: Failed to create HWC virtual display");
283        return NO_MEMORY;
284    }
285
286    size_t displaySlot = 0;
287    if (!mFreeDisplaySlots.empty()) {
288        displaySlot = *mFreeDisplaySlots.begin();
289        mFreeDisplaySlots.erase(displaySlot);
290    } else if (mDisplayData.size() < INT32_MAX) {
291        // Don't bother allocating a slot larger than we can return
292        displaySlot = mDisplayData.size();
293        mDisplayData.resize(displaySlot + 1);
294    } else {
295        ALOGE("allocateVirtualDisplay: Unable to allocate a display slot");
296        return NO_MEMORY;
297    }
298
299    mDisplayData[displaySlot].hwcDisplay = display;
300
301    --mRemainingHwcVirtualDisplays;
302    *outId = static_cast<int32_t>(displaySlot);
303
304    return NO_ERROR;
305}
306
307std::shared_ptr<HWC2::Layer> HWComposer::createLayer(int32_t displayId) {
308    if (!isValidDisplay(displayId)) {
309        ALOGE("Failed to create layer on invalid display %d", displayId);
310        return nullptr;
311    }
312    auto display = mDisplayData[displayId].hwcDisplay;
313    std::shared_ptr<HWC2::Layer> layer;
314    auto error = display->createLayer(&layer);
315    if (error != HWC2::Error::None) {
316        ALOGE("Failed to create layer on display %d: %s (%d)", displayId,
317                to_string(error).c_str(), static_cast<int32_t>(error));
318        return nullptr;
319    }
320    return layer;
321}
322
323nsecs_t HWComposer::getRefreshTimestamp(int32_t displayId) const {
324    // this returns the last refresh timestamp.
325    // if the last one is not available, we estimate it based on
326    // the refresh period and whatever closest timestamp we have.
327    Mutex::Autolock _l(mLock);
328    nsecs_t now = systemTime(CLOCK_MONOTONIC);
329    auto vsyncPeriod = getActiveConfig(displayId)->getVsyncPeriod();
330    return now - ((now - mLastHwVSync[displayId]) % vsyncPeriod);
331}
332
333bool HWComposer::isConnected(int32_t displayId) const {
334    if (!isValidDisplay(displayId)) {
335        ALOGE("isConnected: Attempted to access invalid display %d", displayId);
336        return false;
337    }
338    return mDisplayData[displayId].hwcDisplay->isConnected();
339}
340
341std::vector<std::shared_ptr<const HWC2::Display::Config>>
342        HWComposer::getConfigs(int32_t displayId) const {
343    if (!isValidDisplay(displayId)) {
344        ALOGE("getConfigs: Attempted to access invalid display %d", displayId);
345        return {};
346    }
347    auto& displayData = mDisplayData[displayId];
348    auto configs = mDisplayData[displayId].hwcDisplay->getConfigs();
349    if (displayData.configMap.empty()) {
350        for (size_t i = 0; i < configs.size(); ++i) {
351            displayData.configMap[i] = configs[i];
352        }
353    }
354    return configs;
355}
356
357std::shared_ptr<const HWC2::Display::Config>
358        HWComposer::getActiveConfig(int32_t displayId) const {
359    if (!isValidDisplay(displayId)) {
360        ALOGV("getActiveConfigs: Attempted to access invalid display %d",
361                displayId);
362        return nullptr;
363    }
364    std::shared_ptr<const HWC2::Display::Config> config;
365    auto error = mDisplayData[displayId].hwcDisplay->getActiveConfig(&config);
366    if (error == HWC2::Error::BadConfig) {
367        ALOGE("getActiveConfig: No config active, returning null");
368        return nullptr;
369    } else if (error != HWC2::Error::None) {
370        ALOGE("getActiveConfig failed for display %d: %s (%d)", displayId,
371                to_string(error).c_str(), static_cast<int32_t>(error));
372        return nullptr;
373    } else if (!config) {
374        ALOGE("getActiveConfig returned an unknown config for display %d",
375                displayId);
376        return nullptr;
377    }
378
379    return config;
380}
381
382std::vector<android_color_mode_t> HWComposer::getColorModes(int32_t displayId) const {
383    std::vector<android_color_mode_t> modes;
384
385    if (!isValidDisplay(displayId)) {
386        ALOGE("getColorModes: Attempted to access invalid display %d",
387                displayId);
388        return modes;
389    }
390    const std::shared_ptr<HWC2::Display>& hwcDisplay =
391            mDisplayData[displayId].hwcDisplay;
392
393    auto error = hwcDisplay->getColorModes(&modes);
394    if (error != HWC2::Error::None) {
395        ALOGE("getColorModes failed for display %d: %s (%d)", displayId,
396                to_string(error).c_str(), static_cast<int32_t>(error));
397        return std::vector<android_color_mode_t>();
398    }
399
400    return modes;
401}
402
403status_t HWComposer::setActiveColorMode(int32_t displayId, android_color_mode_t mode) {
404    if (!isValidDisplay(displayId)) {
405        ALOGE("setActiveColorMode: Display %d is not valid", displayId);
406        return BAD_INDEX;
407    }
408
409    auto& displayData = mDisplayData[displayId];
410    auto error = displayData.hwcDisplay->setColorMode(mode);
411    if (error != HWC2::Error::None) {
412        ALOGE("setActiveConfig: Failed to set color mode %d on display %d: "
413                "%s (%d)", mode, displayId, to_string(error).c_str(),
414                static_cast<int32_t>(error));
415        return UNKNOWN_ERROR;
416    }
417
418    return NO_ERROR;
419}
420
421
422void HWComposer::setVsyncEnabled(int32_t displayId, HWC2::Vsync enabled) {
423    if (displayId < 0 || displayId >= HWC_DISPLAY_VIRTUAL) {
424        ALOGD("setVsyncEnabled: Ignoring for virtual display %d", displayId);
425        return;
426    }
427
428    if (!isValidDisplay(displayId)) {
429        ALOGE("setVsyncEnabled: Attempted to access invalid display %d",
430               displayId);
431        return;
432    }
433
434    // NOTE: we use our own internal lock here because we have to call
435    // into the HWC with the lock held, and we want to make sure
436    // that even if HWC blocks (which it shouldn't), it won't
437    // affect other threads.
438    Mutex::Autolock _l(mVsyncLock);
439    auto& displayData = mDisplayData[displayId];
440    if (enabled != displayData.vsyncEnabled) {
441        ATRACE_CALL();
442        auto error = displayData.hwcDisplay->setVsyncEnabled(enabled);
443        if (error == HWC2::Error::None) {
444            displayData.vsyncEnabled = enabled;
445
446            char tag[16];
447            snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", displayId);
448            ATRACE_INT(tag, enabled == HWC2::Vsync::Enable ? 1 : 0);
449        } else {
450            ALOGE("setVsyncEnabled: Failed to set vsync to %s on %d/%" PRIu64
451                    ": %s (%d)", to_string(enabled).c_str(), displayId,
452                    mDisplayData[displayId].hwcDisplay->getId(),
453                    to_string(error).c_str(), static_cast<int32_t>(error));
454        }
455    }
456}
457
458status_t HWComposer::setClientTarget(int32_t displayId, uint32_t slot,
459        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& target,
460        android_dataspace_t dataspace) {
461    if (!isValidDisplay(displayId)) {
462        return BAD_INDEX;
463    }
464
465    ALOGV("setClientTarget for display %d", displayId);
466    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
467    auto error = hwcDisplay->setClientTarget(slot, target, acquireFence, dataspace);
468    if (error != HWC2::Error::None) {
469        ALOGE("Failed to set client target for display %d: %s (%d)", displayId,
470                to_string(error).c_str(), static_cast<int32_t>(error));
471        return BAD_VALUE;
472    }
473
474    return NO_ERROR;
475}
476
477status_t HWComposer::prepare(DisplayDevice& displayDevice) {
478    ATRACE_CALL();
479
480    Mutex::Autolock _l(mDisplayLock);
481    auto displayId = displayDevice.getHwcDisplayId();
482    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
483        ALOGV("Skipping HWComposer prepare for non-HWC display");
484        return NO_ERROR;
485    }
486    if (!isValidDisplay(displayId)) {
487        return BAD_INDEX;
488    }
489
490    auto& displayData = mDisplayData[displayId];
491    auto& hwcDisplay = displayData.hwcDisplay;
492    if (!hwcDisplay->isConnected()) {
493        return NO_ERROR;
494    }
495
496    uint32_t numTypes = 0;
497    uint32_t numRequests = 0;
498    auto error = hwcDisplay->validate(&numTypes, &numRequests);
499    if (error != HWC2::Error::None && error != HWC2::Error::HasChanges) {
500        ALOGE("prepare: validate failed for display %d: %s (%d)", displayId,
501                to_string(error).c_str(), static_cast<int32_t>(error));
502        return BAD_INDEX;
503    }
504
505    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::Composition>
506        changedTypes;
507    changedTypes.reserve(numTypes);
508    error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
509    if (error != HWC2::Error::None) {
510        ALOGE("prepare: getChangedCompositionTypes failed on display %d: "
511                "%s (%d)", displayId, to_string(error).c_str(),
512                static_cast<int32_t>(error));
513        return BAD_INDEX;
514    }
515
516
517    displayData.displayRequests = static_cast<HWC2::DisplayRequest>(0);
518    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::LayerRequest>
519        layerRequests;
520    layerRequests.reserve(numRequests);
521    error = hwcDisplay->getRequests(&displayData.displayRequests,
522            &layerRequests);
523    if (error != HWC2::Error::None) {
524        ALOGE("prepare: getRequests failed on display %d: %s (%d)", displayId,
525                to_string(error).c_str(), static_cast<int32_t>(error));
526        return BAD_INDEX;
527    }
528
529    displayData.hasClientComposition = false;
530    displayData.hasDeviceComposition = false;
531    for (auto& layer : displayDevice.getVisibleLayersSortedByZ()) {
532        auto hwcLayer = layer->getHwcLayer(displayId);
533
534        if (changedTypes.count(hwcLayer) != 0) {
535            // We pass false so we only update our state and don't call back
536            // into the HWC device
537            validateChange(layer->getCompositionType(displayId),
538                    changedTypes[hwcLayer]);
539            layer->setCompositionType(displayId, changedTypes[hwcLayer], false);
540        }
541
542        switch (layer->getCompositionType(displayId)) {
543            case HWC2::Composition::Client:
544                displayData.hasClientComposition = true;
545                break;
546            case HWC2::Composition::Device:
547            case HWC2::Composition::SolidColor:
548            case HWC2::Composition::Cursor:
549            case HWC2::Composition::Sideband:
550                displayData.hasDeviceComposition = true;
551                break;
552            default:
553                break;
554        }
555
556        if (layerRequests.count(hwcLayer) != 0 &&
557                layerRequests[hwcLayer] ==
558                        HWC2::LayerRequest::ClearClientTarget) {
559            layer->setClearClientTarget(displayId, true);
560        } else {
561            if (layerRequests.count(hwcLayer) != 0) {
562                ALOGE("prepare: Unknown layer request: %s",
563                        to_string(layerRequests[hwcLayer]).c_str());
564            }
565            layer->setClearClientTarget(displayId, false);
566        }
567    }
568
569    error = hwcDisplay->acceptChanges();
570    if (error != HWC2::Error::None) {
571        ALOGE("prepare: acceptChanges failed: %s", to_string(error).c_str());
572        return BAD_INDEX;
573    }
574
575    return NO_ERROR;
576}
577
578bool HWComposer::hasDeviceComposition(int32_t displayId) const {
579    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
580        // Displays without a corresponding HWC display are never composed by
581        // the device
582        return false;
583    }
584    if (!isValidDisplay(displayId)) {
585        ALOGE("hasDeviceComposition: Invalid display %d", displayId);
586        return false;
587    }
588    return mDisplayData[displayId].hasDeviceComposition;
589}
590
591bool HWComposer::hasClientComposition(int32_t displayId) const {
592    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
593        // Displays without a corresponding HWC display are always composed by
594        // the client
595        return true;
596    }
597    if (!isValidDisplay(displayId)) {
598        ALOGE("hasClientComposition: Invalid display %d", displayId);
599        return true;
600    }
601    return mDisplayData[displayId].hasClientComposition;
602}
603
604sp<Fence> HWComposer::getPresentFence(int32_t displayId) const {
605    if (!isValidDisplay(displayId)) {
606        ALOGE("getPresentFence failed for invalid display %d", displayId);
607        return Fence::NO_FENCE;
608    }
609    return mDisplayData[displayId].lastPresentFence;
610}
611
612sp<Fence> HWComposer::getLayerReleaseFence(int32_t displayId,
613        const std::shared_ptr<HWC2::Layer>& layer) const {
614    if (!isValidDisplay(displayId)) {
615        ALOGE("getLayerReleaseFence: Invalid display");
616        return Fence::NO_FENCE;
617    }
618    auto displayFences = mDisplayData[displayId].releaseFences;
619    if (displayFences.count(layer) == 0) {
620        ALOGV("getLayerReleaseFence: Release fence not found");
621        return Fence::NO_FENCE;
622    }
623    return displayFences[layer];
624}
625
626status_t HWComposer::presentAndGetReleaseFences(int32_t displayId) {
627    ATRACE_CALL();
628
629    if (!isValidDisplay(displayId)) {
630        return BAD_INDEX;
631    }
632
633    auto& displayData = mDisplayData[displayId];
634    auto& hwcDisplay = displayData.hwcDisplay;
635    auto error = hwcDisplay->present(&displayData.lastPresentFence);
636    if (error != HWC2::Error::None) {
637        ALOGE("presentAndGetReleaseFences: failed for display %d: %s (%d)",
638              displayId, to_string(error).c_str(), static_cast<int32_t>(error));
639        return UNKNOWN_ERROR;
640    }
641
642    std::unordered_map<std::shared_ptr<HWC2::Layer>, sp<Fence>> releaseFences;
643    error = hwcDisplay->getReleaseFences(&releaseFences);
644    if (error != HWC2::Error::None) {
645        ALOGE("presentAndGetReleaseFences: Failed to get release fences "
646              "for display %d: %s (%d)",
647                displayId, to_string(error).c_str(),
648                static_cast<int32_t>(error));
649        return UNKNOWN_ERROR;
650    }
651
652    displayData.releaseFences = std::move(releaseFences);
653
654    return NO_ERROR;
655}
656
657status_t HWComposer::setPowerMode(int32_t displayId, int32_t intMode) {
658    ALOGV("setPowerMode(%d, %d)", displayId, intMode);
659    if (!isValidDisplay(displayId)) {
660        ALOGE("setPowerMode: Bad display");
661        return BAD_INDEX;
662    }
663    if (displayId >= VIRTUAL_DISPLAY_ID_BASE) {
664        ALOGE("setPowerMode: Virtual display %d passed in, returning",
665                displayId);
666        return BAD_INDEX;
667    }
668
669    auto mode = static_cast<HWC2::PowerMode>(intMode);
670    if (mode == HWC2::PowerMode::Off) {
671        setVsyncEnabled(displayId, HWC2::Vsync::Disable);
672    }
673
674    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
675    switch (mode) {
676        case HWC2::PowerMode::Off:
677        case HWC2::PowerMode::On:
678            ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
679            {
680                auto error = hwcDisplay->setPowerMode(mode);
681                if (error != HWC2::Error::None) {
682                    ALOGE("setPowerMode: Unable to set power mode %s for "
683                            "display %d: %s (%d)", to_string(mode).c_str(),
684                            displayId, to_string(error).c_str(),
685                            static_cast<int32_t>(error));
686                }
687            }
688            break;
689        case HWC2::PowerMode::Doze:
690        case HWC2::PowerMode::DozeSuspend:
691            ALOGV("setPowerMode: Calling HWC %s", to_string(mode).c_str());
692            {
693                bool supportsDoze = false;
694                auto error = hwcDisplay->supportsDoze(&supportsDoze);
695                if (error != HWC2::Error::None) {
696                    ALOGE("setPowerMode: Unable to query doze support for "
697                            "display %d: %s (%d)", displayId,
698                            to_string(error).c_str(),
699                            static_cast<int32_t>(error));
700                }
701                if (!supportsDoze) {
702                    mode = HWC2::PowerMode::On;
703                }
704
705                error = hwcDisplay->setPowerMode(mode);
706                if (error != HWC2::Error::None) {
707                    ALOGE("setPowerMode: Unable to set power mode %s for "
708                            "display %d: %s (%d)", to_string(mode).c_str(),
709                            displayId, to_string(error).c_str(),
710                            static_cast<int32_t>(error));
711                }
712            }
713            break;
714        default:
715            ALOGV("setPowerMode: Not calling HWC");
716            break;
717    }
718
719    return NO_ERROR;
720}
721
722status_t HWComposer::setActiveConfig(int32_t displayId, size_t configId) {
723    if (!isValidDisplay(displayId)) {
724        ALOGE("setActiveConfig: Display %d is not valid", displayId);
725        return BAD_INDEX;
726    }
727
728    auto& displayData = mDisplayData[displayId];
729    if (displayData.configMap.count(configId) == 0) {
730        ALOGE("setActiveConfig: Invalid config %zd", configId);
731        return BAD_INDEX;
732    }
733
734    auto error = displayData.hwcDisplay->setActiveConfig(
735            displayData.configMap[configId]);
736    if (error != HWC2::Error::None) {
737        ALOGE("setActiveConfig: Failed to set config %zu on display %d: "
738                "%s (%d)", configId, displayId, to_string(error).c_str(),
739                static_cast<int32_t>(error));
740        return UNKNOWN_ERROR;
741    }
742
743    return NO_ERROR;
744}
745
746status_t HWComposer::setColorTransform(int32_t displayId,
747        const mat4& transform) {
748    if (!isValidDisplay(displayId)) {
749        ALOGE("setColorTransform: Display %d is not valid", displayId);
750        return BAD_INDEX;
751    }
752
753    auto& displayData = mDisplayData[displayId];
754    bool isIdentity = transform == mat4();
755    auto error = displayData.hwcDisplay->setColorTransform(transform,
756            isIdentity ? HAL_COLOR_TRANSFORM_IDENTITY :
757            HAL_COLOR_TRANSFORM_ARBITRARY_MATRIX);
758    if (error != HWC2::Error::None) {
759        ALOGE("setColorTransform: Failed to set transform on display %d: "
760                "%s (%d)", displayId, to_string(error).c_str(),
761                static_cast<int32_t>(error));
762        return UNKNOWN_ERROR;
763    }
764
765    return NO_ERROR;
766}
767
768void HWComposer::disconnectDisplay(int displayId) {
769    LOG_ALWAYS_FATAL_IF(displayId < 0);
770    auto& displayData = mDisplayData[displayId];
771
772    auto displayType = HWC2::DisplayType::Invalid;
773    auto error = displayData.hwcDisplay->getType(&displayType);
774    if (error != HWC2::Error::None) {
775        ALOGE("disconnectDisplay: Failed to determine type of display %d",
776                displayId);
777        return;
778    }
779
780    // If this was a virtual display, add its slot back for reuse by future
781    // virtual displays
782    if (displayType == HWC2::DisplayType::Virtual) {
783        mFreeDisplaySlots.insert(displayId);
784        ++mRemainingHwcVirtualDisplays;
785    }
786
787    auto hwcId = displayData.hwcDisplay->getId();
788    mHwcDisplaySlots.erase(hwcId);
789    displayData.reset();
790}
791
792status_t HWComposer::setOutputBuffer(int32_t displayId,
793        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
794    if (!isValidDisplay(displayId)) {
795        ALOGE("setOutputBuffer: Display %d is not valid", displayId);
796        return BAD_INDEX;
797    }
798
799    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
800    auto displayType = HWC2::DisplayType::Invalid;
801    auto error = hwcDisplay->getType(&displayType);
802    if (error != HWC2::Error::None) {
803        ALOGE("setOutputBuffer: Failed to determine type of display %d",
804                displayId);
805        return NAME_NOT_FOUND;
806    }
807
808    if (displayType != HWC2::DisplayType::Virtual) {
809        ALOGE("setOutputBuffer: Display %d is not virtual", displayId);
810        return INVALID_OPERATION;
811    }
812
813    error = hwcDisplay->setOutputBuffer(buffer, acquireFence);
814    if (error != HWC2::Error::None) {
815        ALOGE("setOutputBuffer: Failed to set buffer on display %d: %s (%d)",
816                displayId, to_string(error).c_str(),
817                static_cast<int32_t>(error));
818        return UNKNOWN_ERROR;
819    }
820
821    return NO_ERROR;
822}
823
824void HWComposer::clearReleaseFences(int32_t displayId) {
825    if (!isValidDisplay(displayId)) {
826        ALOGE("clearReleaseFences: Display %d is not valid", displayId);
827        return;
828    }
829    mDisplayData[displayId].releaseFences.clear();
830}
831
832std::unique_ptr<HdrCapabilities> HWComposer::getHdrCapabilities(
833        int32_t displayId) {
834    if (!isValidDisplay(displayId)) {
835        ALOGE("getHdrCapabilities: Display %d is not valid", displayId);
836        return nullptr;
837    }
838
839    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
840    std::unique_ptr<HdrCapabilities> capabilities;
841    auto error = hwcDisplay->getHdrCapabilities(&capabilities);
842    if (error != HWC2::Error::None) {
843        ALOGE("getOutputCapabilities: Failed to get capabilities on display %d:"
844                " %s (%d)", displayId, to_string(error).c_str(),
845                static_cast<int32_t>(error));
846        return nullptr;
847    }
848
849    return capabilities;
850}
851
852// Converts a PixelFormat to a human-readable string.  Max 11 chars.
853// (Could use a table of prefab String8 objects.)
854/*
855static String8 getFormatStr(PixelFormat format) {
856    switch (format) {
857    case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
858    case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
859    case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
860    case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
861    case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
862    case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
863                                    return String8("ImplDef");
864    default:
865        String8 result;
866        result.appendFormat("? %08x", format);
867        return result;
868    }
869}
870*/
871
872bool HWComposer::isUsingVrComposer() const {
873#ifdef BYPASS_IHWC
874    return false;
875#else
876    return getComposer()->isUsingVrComposer();
877#endif
878}
879
880void HWComposer::dump(String8& result) const {
881    // TODO: In order to provide a dump equivalent to HWC1, we need to shadow
882    // all the state going into the layers. This is probably better done in
883    // Layer itself, but it's going to take a bit of work to get there.
884    result.append(mHwcDevice->dump().c_str());
885}
886
887// ---------------------------------------------------------------------------
888
889HWComposer::DisplayData::DisplayData()
890  : hasClientComposition(false),
891    hasDeviceComposition(false),
892    hwcDisplay(),
893    lastPresentFence(Fence::NO_FENCE),
894    outbufHandle(nullptr),
895    outbufAcquireFence(Fence::NO_FENCE),
896    vsyncEnabled(HWC2::Vsync::Disable) {
897    ALOGV("Created new DisplayData");
898}
899
900HWComposer::DisplayData::~DisplayData() {
901}
902
903void HWComposer::DisplayData::reset() {
904    ALOGV("DisplayData reset");
905    *this = DisplayData();
906}
907
908// ---------------------------------------------------------------------------
909}; // namespace android
910