HWComposer.cpp revision a099a24c93bfa599fc5c36a647e946c26f68514f
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 "HWC2.h"
51#include "ComposerHal.h"
52
53#include "../Layer.h"           // needed only for debugging
54#include "../SurfaceFlinger.h"
55
56namespace android {
57
58#define MIN_HWC_HEADER_VERSION HWC_HEADER_VERSION
59
60// ---------------------------------------------------------------------------
61
62HWComposer::HWComposer(const std::string& serviceName)
63    : mHwcDevice(),
64      mDisplayData(2),
65      mFreeDisplaySlots(),
66      mHwcDisplaySlots(),
67      mCBContext(),
68      mEventHandler(nullptr),
69      mVSyncCounts(),
70      mRemainingHwcVirtualDisplays(0)
71{
72    for (size_t i=0 ; i<HWC_NUM_PHYSICAL_DISPLAY_TYPES ; i++) {
73        mLastHwVSync[i] = 0;
74        mVSyncCounts[i] = 0;
75    }
76
77    loadHwcModule(serviceName);
78}
79
80HWComposer::~HWComposer() {}
81
82void HWComposer::setEventHandler(EventHandler* handler)
83{
84    if (handler == nullptr) {
85        ALOGE("setEventHandler: Rejected attempt to clear handler");
86        return;
87    }
88
89    bool wasNull = (mEventHandler == nullptr);
90    mEventHandler = handler;
91
92    if (wasNull) {
93        auto hotplugHook = std::bind(&HWComposer::hotplug, this,
94                std::placeholders::_1, std::placeholders::_2);
95        mHwcDevice->registerHotplugCallback(hotplugHook);
96        auto invalidateHook = std::bind(&HWComposer::invalidate, this,
97                std::placeholders::_1);
98        mHwcDevice->registerRefreshCallback(invalidateHook);
99        auto vsyncHook = std::bind(&HWComposer::vsync, this,
100                std::placeholders::_1, std::placeholders::_2);
101        mHwcDevice->registerVsyncCallback(vsyncHook);
102    }
103}
104
105// Load and prepare the hardware composer module.  Sets mHwc.
106void HWComposer::loadHwcModule(const std::string& serviceName)
107{
108    ALOGV("loadHwcModule");
109    mHwcDevice = std::make_unique<HWC2::Device>(serviceName);
110
111    mRemainingHwcVirtualDisplays = mHwcDevice->getMaxVirtualDisplayCount();
112}
113
114bool HWComposer::hasCapability(HWC2::Capability capability) const
115{
116    return mHwcDevice->getCapabilities().count(capability) > 0;
117}
118
119bool HWComposer::isValidDisplay(int32_t displayId) const {
120    return static_cast<size_t>(displayId) < mDisplayData.size() &&
121            mDisplayData[displayId].hwcDisplay;
122}
123
124void HWComposer::validateChange(HWC2::Composition from, HWC2::Composition to) {
125    bool valid = true;
126    switch (from) {
127        case HWC2::Composition::Client:
128            valid = false;
129            break;
130        case HWC2::Composition::Device:
131        case HWC2::Composition::SolidColor:
132            valid = (to == HWC2::Composition::Client);
133            break;
134        case HWC2::Composition::Cursor:
135        case HWC2::Composition::Sideband:
136            valid = (to == HWC2::Composition::Client ||
137                    to == HWC2::Composition::Device);
138            break;
139        default:
140            break;
141    }
142
143    if (!valid) {
144        ALOGE("Invalid layer type change: %s --> %s", to_string(from).c_str(),
145                to_string(to).c_str());
146    }
147}
148
149void HWComposer::hotplug(const std::shared_ptr<HWC2::Display>& display,
150        HWC2::Connection connected) {
151    ALOGV("hotplug: %" PRIu64 ", %s", display->getId(),
152            to_string(connected).c_str());
153    int32_t disp = 0;
154    if (!mDisplayData[0].hwcDisplay) {
155        ALOGE_IF(connected != HWC2::Connection::Connected, "Assumed primary"
156                " display would be connected");
157        mDisplayData[0].hwcDisplay = display;
158        mHwcDisplaySlots[display->getId()] = 0;
159        disp = DisplayDevice::DISPLAY_PRIMARY;
160    } else {
161        // Disconnect is handled through HWComposer::disconnectDisplay via
162        // SurfaceFlinger's onHotplugReceived callback handling
163        if (connected == HWC2::Connection::Connected) {
164            mDisplayData[1].hwcDisplay = display;
165            mHwcDisplaySlots[display->getId()] = 1;
166        }
167        disp = DisplayDevice::DISPLAY_EXTERNAL;
168    }
169    mEventHandler->onHotplugReceived(this, disp,
170            connected == HWC2::Connection::Connected);
171}
172
173void HWComposer::invalidate(const std::shared_ptr<HWC2::Display>& /*display*/) {
174    mEventHandler->onInvalidateReceived(this);
175}
176
177void HWComposer::vsync(const std::shared_ptr<HWC2::Display>& display,
178        int64_t timestamp) {
179    auto displayType = HWC2::DisplayType::Invalid;
180    auto error = display->getType(&displayType);
181    if (error != HWC2::Error::None) {
182        ALOGE("vsync: Failed to determine type of display %" PRIu64,
183                display->getId());
184        return;
185    }
186
187    if (displayType == HWC2::DisplayType::Virtual) {
188        ALOGE("Virtual display %" PRIu64 " passed to vsync callback",
189                display->getId());
190        return;
191    }
192
193    if (mHwcDisplaySlots.count(display->getId()) == 0) {
194        ALOGE("Unknown physical display %" PRIu64 " passed to vsync callback",
195                display->getId());
196        return;
197    }
198
199    int32_t disp = mHwcDisplaySlots[display->getId()];
200    {
201        Mutex::Autolock _l(mLock);
202
203        // There have been reports of HWCs that signal several vsync events
204        // with the same timestamp when turning the display off and on. This
205        // is a bug in the HWC implementation, but filter the extra events
206        // out here so they don't cause havoc downstream.
207        if (timestamp == mLastHwVSync[disp]) {
208            ALOGW("Ignoring duplicate VSYNC event from HWC (t=%" PRId64 ")",
209                    timestamp);
210            return;
211        }
212
213        mLastHwVSync[disp] = timestamp;
214    }
215
216    char tag[16];
217    snprintf(tag, sizeof(tag), "HW_VSYNC_%1u", disp);
218    ATRACE_INT(tag, ++mVSyncCounts[disp] & 1);
219
220    mEventHandler->onVSyncReceived(this, disp, timestamp);
221}
222
223status_t HWComposer::allocateVirtualDisplay(uint32_t width, uint32_t height,
224        android_pixel_format_t* format, int32_t *outId) {
225    if (mRemainingHwcVirtualDisplays == 0) {
226        ALOGE("allocateVirtualDisplay: No remaining virtual displays");
227        return NO_MEMORY;
228    }
229
230    if (SurfaceFlinger::maxVirtualDisplaySize != 0 &&
231        (width > SurfaceFlinger::maxVirtualDisplaySize ||
232         height > SurfaceFlinger::maxVirtualDisplaySize)) {
233        ALOGE("createVirtualDisplay: Can't create a virtual display with"
234                      " a dimension > %" PRIu64 " (tried %u x %u)",
235              SurfaceFlinger::maxVirtualDisplaySize, width, height);
236        return INVALID_OPERATION;
237    }
238
239    std::shared_ptr<HWC2::Display> display;
240    auto error = mHwcDevice->createVirtualDisplay(width, height, format,
241            &display);
242    if (error != HWC2::Error::None) {
243        ALOGE("allocateVirtualDisplay: Failed to create HWC virtual display");
244        return NO_MEMORY;
245    }
246
247    size_t displaySlot = 0;
248    if (!mFreeDisplaySlots.empty()) {
249        displaySlot = *mFreeDisplaySlots.begin();
250        mFreeDisplaySlots.erase(displaySlot);
251    } else if (mDisplayData.size() < INT32_MAX) {
252        // Don't bother allocating a slot larger than we can return
253        displaySlot = mDisplayData.size();
254        mDisplayData.resize(displaySlot + 1);
255    } else {
256        ALOGE("allocateVirtualDisplay: Unable to allocate a display slot");
257        return NO_MEMORY;
258    }
259
260    mDisplayData[displaySlot].hwcDisplay = display;
261
262    --mRemainingHwcVirtualDisplays;
263    *outId = static_cast<int32_t>(displaySlot);
264
265    return NO_ERROR;
266}
267
268std::shared_ptr<HWC2::Layer> HWComposer::createLayer(int32_t displayId) {
269    if (!isValidDisplay(displayId)) {
270        ALOGE("Failed to create layer on invalid display %d", displayId);
271        return nullptr;
272    }
273    auto display = mDisplayData[displayId].hwcDisplay;
274    std::shared_ptr<HWC2::Layer> layer;
275    auto error = display->createLayer(&layer);
276    if (error != HWC2::Error::None) {
277        ALOGE("Failed to create layer on display %d: %s (%d)", displayId,
278                to_string(error).c_str(), static_cast<int32_t>(error));
279        return nullptr;
280    }
281    return layer;
282}
283
284nsecs_t HWComposer::getRefreshTimestamp(int32_t displayId) const {
285    // this returns the last refresh timestamp.
286    // if the last one is not available, we estimate it based on
287    // the refresh period and whatever closest timestamp we have.
288    Mutex::Autolock _l(mLock);
289    nsecs_t now = systemTime(CLOCK_MONOTONIC);
290    auto vsyncPeriod = getActiveConfig(displayId)->getVsyncPeriod();
291    return now - ((now - mLastHwVSync[displayId]) % vsyncPeriod);
292}
293
294bool HWComposer::isConnected(int32_t displayId) const {
295    if (!isValidDisplay(displayId)) {
296        ALOGE("isConnected: Attempted to access invalid display %d", displayId);
297        return false;
298    }
299    return mDisplayData[displayId].hwcDisplay->isConnected();
300}
301
302std::vector<std::shared_ptr<const HWC2::Display::Config>>
303        HWComposer::getConfigs(int32_t displayId) const {
304    if (!isValidDisplay(displayId)) {
305        ALOGE("getConfigs: Attempted to access invalid display %d", displayId);
306        return {};
307    }
308    auto& displayData = mDisplayData[displayId];
309    auto configs = mDisplayData[displayId].hwcDisplay->getConfigs();
310    if (displayData.configMap.empty()) {
311        for (size_t i = 0; i < configs.size(); ++i) {
312            displayData.configMap[i] = configs[i];
313        }
314    }
315    return configs;
316}
317
318std::shared_ptr<const HWC2::Display::Config>
319        HWComposer::getActiveConfig(int32_t displayId) const {
320    if (!isValidDisplay(displayId)) {
321        ALOGV("getActiveConfigs: Attempted to access invalid display %d",
322                displayId);
323        return nullptr;
324    }
325    std::shared_ptr<const HWC2::Display::Config> config;
326    auto error = mDisplayData[displayId].hwcDisplay->getActiveConfig(&config);
327    if (error == HWC2::Error::BadConfig) {
328        ALOGE("getActiveConfig: No config active, returning null");
329        return nullptr;
330    } else if (error != HWC2::Error::None) {
331        ALOGE("getActiveConfig failed for display %d: %s (%d)", displayId,
332                to_string(error).c_str(), static_cast<int32_t>(error));
333        return nullptr;
334    } else if (!config) {
335        ALOGE("getActiveConfig returned an unknown config for display %d",
336                displayId);
337        return nullptr;
338    }
339
340    return config;
341}
342
343std::vector<android_color_mode_t> HWComposer::getColorModes(int32_t displayId) const {
344    std::vector<android_color_mode_t> modes;
345
346    if (!isValidDisplay(displayId)) {
347        ALOGE("getColorModes: Attempted to access invalid display %d",
348                displayId);
349        return modes;
350    }
351    const std::shared_ptr<HWC2::Display>& hwcDisplay =
352            mDisplayData[displayId].hwcDisplay;
353
354    auto error = hwcDisplay->getColorModes(&modes);
355    if (error != HWC2::Error::None) {
356        ALOGE("getColorModes failed for display %d: %s (%d)", displayId,
357                to_string(error).c_str(), static_cast<int32_t>(error));
358        return std::vector<android_color_mode_t>();
359    }
360
361    return modes;
362}
363
364status_t HWComposer::setActiveColorMode(int32_t displayId, android_color_mode_t mode) {
365    if (!isValidDisplay(displayId)) {
366        ALOGE("setActiveColorMode: Display %d is not valid", displayId);
367        return BAD_INDEX;
368    }
369
370    auto& displayData = mDisplayData[displayId];
371    auto error = displayData.hwcDisplay->setColorMode(mode);
372    if (error != HWC2::Error::None) {
373        ALOGE("setActiveConfig: Failed to set color mode %d on display %d: "
374                "%s (%d)", mode, displayId, to_string(error).c_str(),
375                static_cast<int32_t>(error));
376        return UNKNOWN_ERROR;
377    }
378
379    return NO_ERROR;
380}
381
382
383void HWComposer::setVsyncEnabled(int32_t displayId, HWC2::Vsync enabled) {
384    if (displayId < 0 || displayId >= HWC_DISPLAY_VIRTUAL) {
385        ALOGD("setVsyncEnabled: Ignoring for virtual display %d", displayId);
386        return;
387    }
388
389    if (!isValidDisplay(displayId)) {
390        ALOGE("setVsyncEnabled: Attempted to access invalid display %d",
391               displayId);
392        return;
393    }
394
395    // NOTE: we use our own internal lock here because we have to call
396    // into the HWC with the lock held, and we want to make sure
397    // that even if HWC blocks (which it shouldn't), it won't
398    // affect other threads.
399    Mutex::Autolock _l(mVsyncLock);
400    auto& displayData = mDisplayData[displayId];
401    if (enabled != displayData.vsyncEnabled) {
402        ATRACE_CALL();
403        auto error = displayData.hwcDisplay->setVsyncEnabled(enabled);
404        if (error == HWC2::Error::None) {
405            displayData.vsyncEnabled = enabled;
406
407            char tag[16];
408            snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", displayId);
409            ATRACE_INT(tag, enabled == HWC2::Vsync::Enable ? 1 : 0);
410        } else {
411            ALOGE("setVsyncEnabled: Failed to set vsync to %s on %d/%" PRIu64
412                    ": %s (%d)", to_string(enabled).c_str(), displayId,
413                    mDisplayData[displayId].hwcDisplay->getId(),
414                    to_string(error).c_str(), static_cast<int32_t>(error));
415        }
416    }
417}
418
419status_t HWComposer::setClientTarget(int32_t displayId, uint32_t slot,
420        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& target,
421        android_dataspace_t dataspace) {
422    if (!isValidDisplay(displayId)) {
423        return BAD_INDEX;
424    }
425
426    ALOGV("setClientTarget for display %d", displayId);
427    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
428    auto error = hwcDisplay->setClientTarget(slot, target, acquireFence, dataspace);
429    if (error != HWC2::Error::None) {
430        ALOGE("Failed to set client target for display %d: %s (%d)", displayId,
431                to_string(error).c_str(), static_cast<int32_t>(error));
432        return BAD_VALUE;
433    }
434
435    return NO_ERROR;
436}
437
438status_t HWComposer::prepare(DisplayDevice& displayDevice) {
439    ATRACE_CALL();
440
441    Mutex::Autolock _l(mDisplayLock);
442    auto displayId = displayDevice.getHwcDisplayId();
443    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
444        ALOGV("Skipping HWComposer prepare for non-HWC display");
445        return NO_ERROR;
446    }
447    if (!isValidDisplay(displayId)) {
448        return BAD_INDEX;
449    }
450
451    auto& displayData = mDisplayData[displayId];
452    auto& hwcDisplay = displayData.hwcDisplay;
453    if (!hwcDisplay->isConnected()) {
454        return NO_ERROR;
455    }
456
457    uint32_t numTypes = 0;
458    uint32_t numRequests = 0;
459
460    HWC2::Error error = HWC2::Error::None;
461
462    // First try to skip validate altogether if the HWC supports it.
463    displayData.validateWasSkipped = false;
464    if (hasCapability(HWC2::Capability::SkipValidate) &&
465            !displayData.hasClientComposition) {
466        sp<android::Fence> outPresentFence;
467        uint32_t state = UINT32_MAX;
468        error = hwcDisplay->presentOrValidate(&numTypes, &numRequests, &outPresentFence , &state);
469        if (error != HWC2::Error::None && error != HWC2::Error::HasChanges) {
470            ALOGV("skipValidate: Failed to Present or Validate");
471            return UNKNOWN_ERROR;
472        }
473        if (state == 1) { //Present Succeeded.
474            std::unordered_map<std::shared_ptr<HWC2::Layer>, sp<Fence>> releaseFences;
475            error = hwcDisplay->getReleaseFences(&releaseFences);
476            displayData.releaseFences = std::move(releaseFences);
477            displayData.lastPresentFence = outPresentFence;
478            displayData.validateWasSkipped = true;
479            displayData.presentError = error;
480            return NO_ERROR;
481        }
482        // Present failed but Validate ran.
483    } else {
484        error = hwcDisplay->validate(&numTypes, &numRequests);
485    }
486    ALOGV("SkipValidate failed, Falling back to SLOW validate/present");
487    if (error != HWC2::Error::None && error != HWC2::Error::HasChanges) {
488        ALOGE("prepare: validate failed for display %d: %s (%d)", displayId,
489                to_string(error).c_str(), static_cast<int32_t>(error));
490        return BAD_INDEX;
491    }
492
493    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::Composition>
494        changedTypes;
495    changedTypes.reserve(numTypes);
496    error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
497    if (error != HWC2::Error::None) {
498        ALOGE("prepare: getChangedCompositionTypes failed on display %d: "
499                "%s (%d)", displayId, to_string(error).c_str(),
500                static_cast<int32_t>(error));
501        return BAD_INDEX;
502    }
503
504
505    displayData.displayRequests = static_cast<HWC2::DisplayRequest>(0);
506    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::LayerRequest>
507        layerRequests;
508    layerRequests.reserve(numRequests);
509    error = hwcDisplay->getRequests(&displayData.displayRequests,
510            &layerRequests);
511    if (error != HWC2::Error::None) {
512        ALOGE("prepare: getRequests failed on display %d: %s (%d)", displayId,
513                to_string(error).c_str(), static_cast<int32_t>(error));
514        return BAD_INDEX;
515    }
516
517    displayData.hasClientComposition = false;
518    displayData.hasDeviceComposition = false;
519    for (auto& layer : displayDevice.getVisibleLayersSortedByZ()) {
520        auto hwcLayer = layer->getHwcLayer(displayId);
521
522        if (changedTypes.count(hwcLayer) != 0) {
523            // We pass false so we only update our state and don't call back
524            // into the HWC device
525            validateChange(layer->getCompositionType(displayId),
526                    changedTypes[hwcLayer]);
527            layer->setCompositionType(displayId, changedTypes[hwcLayer], false);
528        }
529
530        switch (layer->getCompositionType(displayId)) {
531            case HWC2::Composition::Client:
532                displayData.hasClientComposition = true;
533                break;
534            case HWC2::Composition::Device:
535            case HWC2::Composition::SolidColor:
536            case HWC2::Composition::Cursor:
537            case HWC2::Composition::Sideband:
538                displayData.hasDeviceComposition = true;
539                break;
540            default:
541                break;
542        }
543
544        if (layerRequests.count(hwcLayer) != 0 &&
545                layerRequests[hwcLayer] ==
546                        HWC2::LayerRequest::ClearClientTarget) {
547            layer->setClearClientTarget(displayId, true);
548        } else {
549            if (layerRequests.count(hwcLayer) != 0) {
550                ALOGE("prepare: Unknown layer request: %s",
551                        to_string(layerRequests[hwcLayer]).c_str());
552            }
553            layer->setClearClientTarget(displayId, false);
554        }
555    }
556
557    error = hwcDisplay->acceptChanges();
558    if (error != HWC2::Error::None) {
559        ALOGE("prepare: acceptChanges failed: %s", to_string(error).c_str());
560        return BAD_INDEX;
561    }
562
563    return NO_ERROR;
564}
565
566bool HWComposer::hasDeviceComposition(int32_t displayId) const {
567    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
568        // Displays without a corresponding HWC display are never composed by
569        // the device
570        return false;
571    }
572    if (!isValidDisplay(displayId)) {
573        ALOGE("hasDeviceComposition: Invalid display %d", displayId);
574        return false;
575    }
576    return mDisplayData[displayId].hasDeviceComposition;
577}
578
579bool HWComposer::hasClientComposition(int32_t displayId) const {
580    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
581        // Displays without a corresponding HWC display are always composed by
582        // the client
583        return true;
584    }
585    if (!isValidDisplay(displayId)) {
586        ALOGE("hasClientComposition: Invalid display %d", displayId);
587        return true;
588    }
589    return mDisplayData[displayId].hasClientComposition;
590}
591
592sp<Fence> HWComposer::getPresentFence(int32_t displayId) const {
593    if (!isValidDisplay(displayId)) {
594        ALOGE("getPresentFence failed for invalid display %d", displayId);
595        return Fence::NO_FENCE;
596    }
597    return mDisplayData[displayId].lastPresentFence;
598}
599
600sp<Fence> HWComposer::getLayerReleaseFence(int32_t displayId,
601        const std::shared_ptr<HWC2::Layer>& layer) const {
602    if (!isValidDisplay(displayId)) {
603        ALOGE("getLayerReleaseFence: Invalid display");
604        return Fence::NO_FENCE;
605    }
606    auto displayFences = mDisplayData[displayId].releaseFences;
607    if (displayFences.count(layer) == 0) {
608        ALOGV("getLayerReleaseFence: Release fence not found");
609        return Fence::NO_FENCE;
610    }
611    return displayFences[layer];
612}
613
614status_t HWComposer::presentAndGetReleaseFences(int32_t displayId) {
615    ATRACE_CALL();
616
617    if (!isValidDisplay(displayId)) {
618        return BAD_INDEX;
619    }
620
621    auto& displayData = mDisplayData[displayId];
622    auto& hwcDisplay = displayData.hwcDisplay;
623
624    if (displayData.validateWasSkipped) {
625        hwcDisplay->discardCommands();
626        auto error = displayData.presentError;
627        if (error != HWC2::Error::None) {
628            ALOGE("skipValidate: failed for display %d: %s (%d)",
629                  displayId, to_string(error).c_str(), static_cast<int32_t>(error));
630            return UNKNOWN_ERROR;
631        }
632        return NO_ERROR;
633    }
634
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    return getComposer()->isUsingVrComposer();
874}
875
876void HWComposer::dump(String8& result) const {
877    // TODO: In order to provide a dump equivalent to HWC1, we need to shadow
878    // all the state going into the layers. This is probably better done in
879    // Layer itself, but it's going to take a bit of work to get there.
880    result.append(mHwcDevice->dump().c_str());
881}
882
883// ---------------------------------------------------------------------------
884
885HWComposer::DisplayData::DisplayData()
886  : hasClientComposition(false),
887    hasDeviceComposition(false),
888    hwcDisplay(),
889    lastPresentFence(Fence::NO_FENCE),
890    outbufHandle(nullptr),
891    outbufAcquireFence(Fence::NO_FENCE),
892    vsyncEnabled(HWC2::Vsync::Disable) {
893    ALOGV("Created new DisplayData");
894}
895
896HWComposer::DisplayData::~DisplayData() {
897}
898
899void HWComposer::DisplayData::reset() {
900    ALOGV("DisplayData reset");
901    *this = DisplayData();
902}
903
904// ---------------------------------------------------------------------------
905}; // namespace android
906