HWComposer.cpp revision 3cfac28462910d3f976aebac54ac7301aca7e434
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.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(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    std::shared_ptr<HWC2::Display> display;
270    auto error = mHwcDevice->createVirtualDisplay(width, height, format,
271            &display);
272    if (error != HWC2::Error::None) {
273        ALOGE("allocateVirtualDisplay: Failed to create HWC virtual display");
274        return NO_MEMORY;
275    }
276
277    size_t displaySlot = 0;
278    if (!mFreeDisplaySlots.empty()) {
279        displaySlot = *mFreeDisplaySlots.begin();
280        mFreeDisplaySlots.erase(displaySlot);
281    } else if (mDisplayData.size() < INT32_MAX) {
282        // Don't bother allocating a slot larger than we can return
283        displaySlot = mDisplayData.size();
284        mDisplayData.resize(displaySlot + 1);
285    } else {
286        ALOGE("allocateVirtualDisplay: Unable to allocate a display slot");
287        return NO_MEMORY;
288    }
289
290    mDisplayData[displaySlot].hwcDisplay = display;
291
292    --mRemainingHwcVirtualDisplays;
293    *outId = static_cast<int32_t>(displaySlot);
294
295    return NO_ERROR;
296}
297
298std::shared_ptr<HWC2::Layer> HWComposer::createLayer(int32_t displayId) {
299    if (!isValidDisplay(displayId)) {
300        ALOGE("Failed to create layer on invalid display %d", displayId);
301        return nullptr;
302    }
303    auto display = mDisplayData[displayId].hwcDisplay;
304    std::shared_ptr<HWC2::Layer> layer;
305    auto error = display->createLayer(&layer);
306    if (error != HWC2::Error::None) {
307        ALOGE("Failed to create layer on display %d: %s (%d)", displayId,
308                to_string(error).c_str(), static_cast<int32_t>(error));
309        return nullptr;
310    }
311    return layer;
312}
313
314nsecs_t HWComposer::getRefreshTimestamp(int32_t displayId) const {
315    // this returns the last refresh timestamp.
316    // if the last one is not available, we estimate it based on
317    // the refresh period and whatever closest timestamp we have.
318    Mutex::Autolock _l(mLock);
319    nsecs_t now = systemTime(CLOCK_MONOTONIC);
320    auto vsyncPeriod = getActiveConfig(displayId)->getVsyncPeriod();
321    return now - ((now - mLastHwVSync[displayId]) % vsyncPeriod);
322}
323
324bool HWComposer::isConnected(int32_t displayId) const {
325    if (!isValidDisplay(displayId)) {
326        ALOGE("isConnected: Attempted to access invalid display %d", displayId);
327        return false;
328    }
329    return mDisplayData[displayId].hwcDisplay->isConnected();
330}
331
332std::vector<std::shared_ptr<const HWC2::Display::Config>>
333        HWComposer::getConfigs(int32_t displayId) const {
334    if (!isValidDisplay(displayId)) {
335        ALOGE("getConfigs: Attempted to access invalid display %d", displayId);
336        return {};
337    }
338    auto& displayData = mDisplayData[displayId];
339    auto configs = mDisplayData[displayId].hwcDisplay->getConfigs();
340    if (displayData.configMap.empty()) {
341        for (size_t i = 0; i < configs.size(); ++i) {
342            displayData.configMap[i] = configs[i];
343        }
344    }
345    return configs;
346}
347
348std::shared_ptr<const HWC2::Display::Config>
349        HWComposer::getActiveConfig(int32_t displayId) const {
350    if (!isValidDisplay(displayId)) {
351        ALOGV("getActiveConfigs: Attempted to access invalid display %d",
352                displayId);
353        return nullptr;
354    }
355    std::shared_ptr<const HWC2::Display::Config> config;
356    auto error = mDisplayData[displayId].hwcDisplay->getActiveConfig(&config);
357    if (error == HWC2::Error::BadConfig) {
358        ALOGE("getActiveConfig: No config active, returning null");
359        return nullptr;
360    } else if (error != HWC2::Error::None) {
361        ALOGE("getActiveConfig failed for display %d: %s (%d)", displayId,
362                to_string(error).c_str(), static_cast<int32_t>(error));
363        return nullptr;
364    } else if (!config) {
365        ALOGE("getActiveConfig returned an unknown config for display %d",
366                displayId);
367        return nullptr;
368    }
369
370    return config;
371}
372
373std::vector<android_color_mode_t> HWComposer::getColorModes(int32_t displayId) const {
374    std::vector<android_color_mode_t> modes;
375
376    if (!isValidDisplay(displayId)) {
377        ALOGE("getColorModes: Attempted to access invalid display %d",
378                displayId);
379        return modes;
380    }
381    const std::shared_ptr<HWC2::Display>& hwcDisplay =
382            mDisplayData[displayId].hwcDisplay;
383
384    auto error = hwcDisplay->getColorModes(&modes);
385    if (error != HWC2::Error::None) {
386        ALOGE("getColorModes failed for display %d: %s (%d)", displayId,
387                to_string(error).c_str(), static_cast<int32_t>(error));
388        return std::vector<android_color_mode_t>();
389    }
390
391    return modes;
392}
393
394status_t HWComposer::setActiveColorMode(int32_t displayId, android_color_mode_t mode) {
395    if (!isValidDisplay(displayId)) {
396        ALOGE("setActiveColorMode: Display %d is not valid", displayId);
397        return BAD_INDEX;
398    }
399
400    auto& displayData = mDisplayData[displayId];
401    auto error = displayData.hwcDisplay->setColorMode(mode);
402    if (error != HWC2::Error::None) {
403        ALOGE("setActiveConfig: Failed to set color mode %d on display %d: "
404                "%s (%d)", mode, displayId, to_string(error).c_str(),
405                static_cast<int32_t>(error));
406        return UNKNOWN_ERROR;
407    }
408
409    return NO_ERROR;
410}
411
412
413void HWComposer::setVsyncEnabled(int32_t displayId, HWC2::Vsync enabled) {
414    if (displayId < 0 || displayId >= HWC_DISPLAY_VIRTUAL) {
415        ALOGD("setVsyncEnabled: Ignoring for virtual display %d", displayId);
416        return;
417    }
418
419    if (!isValidDisplay(displayId)) {
420        ALOGE("setVsyncEnabled: Attempted to access invalid display %d",
421               displayId);
422        return;
423    }
424
425    // NOTE: we use our own internal lock here because we have to call
426    // into the HWC with the lock held, and we want to make sure
427    // that even if HWC blocks (which it shouldn't), it won't
428    // affect other threads.
429    Mutex::Autolock _l(mVsyncLock);
430    auto& displayData = mDisplayData[displayId];
431    if (enabled != displayData.vsyncEnabled) {
432        ATRACE_CALL();
433        auto error = displayData.hwcDisplay->setVsyncEnabled(enabled);
434        if (error == HWC2::Error::None) {
435            displayData.vsyncEnabled = enabled;
436
437            char tag[16];
438            snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", displayId);
439            ATRACE_INT(tag, enabled == HWC2::Vsync::Enable ? 1 : 0);
440        } else {
441            ALOGE("setVsyncEnabled: Failed to set vsync to %s on %d/%" PRIu64
442                    ": %s (%d)", to_string(enabled).c_str(), displayId,
443                    mDisplayData[displayId].hwcDisplay->getId(),
444                    to_string(error).c_str(), static_cast<int32_t>(error));
445        }
446    }
447}
448
449status_t HWComposer::setClientTarget(int32_t displayId, uint32_t slot,
450        const sp<Fence>& acquireFence, const sp<GraphicBuffer>& target,
451        android_dataspace_t dataspace) {
452    if (!isValidDisplay(displayId)) {
453        return BAD_INDEX;
454    }
455
456    ALOGV("setClientTarget for display %d", displayId);
457    auto& hwcDisplay = mDisplayData[displayId].hwcDisplay;
458    buffer_handle_t handle = nullptr;
459    if ((target != nullptr) && target->getNativeBuffer()) {
460        handle = target->getNativeBuffer()->handle;
461    }
462    auto error = hwcDisplay->setClientTarget(slot, handle,
463            acquireFence, dataspace);
464    if (error != HWC2::Error::None) {
465        ALOGE("Failed to set client target for display %d: %s (%d)", displayId,
466                to_string(error).c_str(), static_cast<int32_t>(error));
467        return BAD_VALUE;
468    }
469
470    return NO_ERROR;
471}
472
473status_t HWComposer::prepare(DisplayDevice& displayDevice) {
474    ATRACE_CALL();
475
476    Mutex::Autolock _l(mDisplayLock);
477    auto displayId = displayDevice.getHwcDisplayId();
478    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
479        ALOGV("Skipping HWComposer prepare for non-HWC display");
480        return NO_ERROR;
481    }
482    if (!isValidDisplay(displayId)) {
483        return BAD_INDEX;
484    }
485
486    auto& displayData = mDisplayData[displayId];
487    auto& hwcDisplay = displayData.hwcDisplay;
488    if (!hwcDisplay->isConnected()) {
489        return NO_ERROR;
490    }
491
492    uint32_t numTypes = 0;
493    uint32_t numRequests = 0;
494    auto error = hwcDisplay->validate(&numTypes, &numRequests);
495    if (error != HWC2::Error::None && error != HWC2::Error::HasChanges) {
496        ALOGE("prepare: validate failed for display %d: %s (%d)", displayId,
497                to_string(error).c_str(), static_cast<int32_t>(error));
498        return BAD_INDEX;
499    }
500
501    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::Composition>
502        changedTypes;
503    changedTypes.reserve(numTypes);
504    error = hwcDisplay->getChangedCompositionTypes(&changedTypes);
505    if (error != HWC2::Error::None) {
506        ALOGE("prepare: getChangedCompositionTypes failed on display %d: "
507                "%s (%d)", displayId, to_string(error).c_str(),
508                static_cast<int32_t>(error));
509        return BAD_INDEX;
510    }
511
512
513    displayData.displayRequests = static_cast<HWC2::DisplayRequest>(0);
514    std::unordered_map<std::shared_ptr<HWC2::Layer>, HWC2::LayerRequest>
515        layerRequests;
516    layerRequests.reserve(numRequests);
517    error = hwcDisplay->getRequests(&displayData.displayRequests,
518            &layerRequests);
519    if (error != HWC2::Error::None) {
520        ALOGE("prepare: getRequests failed on display %d: %s (%d)", displayId,
521                to_string(error).c_str(), static_cast<int32_t>(error));
522        return BAD_INDEX;
523    }
524
525    displayData.hasClientComposition = false;
526    displayData.hasDeviceComposition = false;
527    for (auto& layer : displayDevice.getVisibleLayersSortedByZ()) {
528        auto hwcLayer = layer->getHwcLayer(displayId);
529
530        if (changedTypes.count(hwcLayer) != 0) {
531            // We pass false so we only update our state and don't call back
532            // into the HWC device
533            validateChange(layer->getCompositionType(displayId),
534                    changedTypes[hwcLayer]);
535            layer->setCompositionType(displayId, changedTypes[hwcLayer], false);
536        }
537
538        switch (layer->getCompositionType(displayId)) {
539            case HWC2::Composition::Client:
540                displayData.hasClientComposition = true;
541                break;
542            case HWC2::Composition::Device:
543            case HWC2::Composition::SolidColor:
544            case HWC2::Composition::Cursor:
545            case HWC2::Composition::Sideband:
546                displayData.hasDeviceComposition = true;
547                break;
548            default:
549                break;
550        }
551
552        if (layerRequests.count(hwcLayer) != 0 &&
553                layerRequests[hwcLayer] ==
554                        HWC2::LayerRequest::ClearClientTarget) {
555            layer->setClearClientTarget(displayId, true);
556        } else {
557            if (layerRequests.count(hwcLayer) != 0) {
558                ALOGE("prepare: Unknown layer request: %s",
559                        to_string(layerRequests[hwcLayer]).c_str());
560            }
561            layer->setClearClientTarget(displayId, false);
562        }
563    }
564
565    error = hwcDisplay->acceptChanges();
566    if (error != HWC2::Error::None) {
567        ALOGE("prepare: acceptChanges failed: %s", to_string(error).c_str());
568        return BAD_INDEX;
569    }
570
571    return NO_ERROR;
572}
573
574bool HWComposer::hasDeviceComposition(int32_t displayId) const {
575    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
576        // Displays without a corresponding HWC display are never composed by
577        // the device
578        return false;
579    }
580    if (!isValidDisplay(displayId)) {
581        ALOGE("hasDeviceComposition: Invalid display %d", displayId);
582        return false;
583    }
584    return mDisplayData[displayId].hasDeviceComposition;
585}
586
587bool HWComposer::hasClientComposition(int32_t displayId) const {
588    if (displayId == DisplayDevice::DISPLAY_ID_INVALID) {
589        // Displays without a corresponding HWC display are always composed by
590        // the client
591        return true;
592    }
593    if (!isValidDisplay(displayId)) {
594        ALOGE("hasClientComposition: Invalid display %d", displayId);
595        return true;
596    }
597    return mDisplayData[displayId].hasClientComposition;
598}
599
600sp<Fence> HWComposer::getPresentFence(int32_t displayId) const {
601    if (!isValidDisplay(displayId)) {
602        ALOGE("getPresentFence failed for invalid display %d", displayId);
603        return Fence::NO_FENCE;
604    }
605    return mDisplayData[displayId].lastPresentFence;
606}
607
608bool HWComposer::presentFenceRepresentsStartOfScanout() const {
609    return mAdapter ? false : true;
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
908void HWComposerBufferCache::clear()
909{
910    mBuffers.clear();
911}
912
913void HWComposerBufferCache::getHwcBuffer(int slot,
914        const sp<GraphicBuffer>& buffer,
915        uint32_t* outSlot, sp<GraphicBuffer>* outBuffer)
916{
917    if (slot == BufferQueue::INVALID_BUFFER_SLOT || slot < 0) {
918        // default to slot 0
919        slot = 0;
920    }
921
922    if (static_cast<size_t>(slot) >= mBuffers.size()) {
923        mBuffers.resize(slot + 1);
924    }
925
926    *outSlot = slot;
927
928    if (mBuffers[slot] == buffer) {
929        // already cached in HWC, skip sending the buffer
930        *outBuffer = nullptr;
931    } else {
932        *outBuffer = buffer;
933
934        // update cache
935        mBuffers[slot] = buffer;
936    }
937}
938
939// ---------------------------------------------------------------------------
940}; // namespace android
941