• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2015 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 "HWC2On1Adapter"
21 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
22 
23 #include "HWC2On1Adapter.h"
24 
25 #include <hardware/hwcomposer.h>
26 #include <log/log.h>
27 #include <utils/Trace.h>
28 
29 #include <cstdlib>
30 #include <chrono>
31 #include <inttypes.h>
32 #include <sstream>
33 
34 using namespace std::chrono_literals;
35 
operator ==(const hwc_color_t & lhs,const hwc_color_t & rhs)36 static bool operator==(const hwc_color_t& lhs, const hwc_color_t& rhs) {
37     return lhs.r == rhs.r &&
38             lhs.g == rhs.g &&
39             lhs.b == rhs.b &&
40             lhs.a == rhs.a;
41 }
42 
operator ==(const hwc_rect_t & lhs,const hwc_rect_t & rhs)43 static bool operator==(const hwc_rect_t& lhs, const hwc_rect_t& rhs) {
44     return lhs.left == rhs.left &&
45             lhs.top == rhs.top &&
46             lhs.right == rhs.right &&
47             lhs.bottom == rhs.bottom;
48 }
49 
operator ==(const hwc_frect_t & lhs,const hwc_frect_t & rhs)50 static bool operator==(const hwc_frect_t& lhs, const hwc_frect_t& rhs) {
51     return lhs.left == rhs.left &&
52             lhs.top == rhs.top &&
53             lhs.right == rhs.right &&
54             lhs.bottom == rhs.bottom;
55 }
56 
57 template <typename T>
operator !=(const T & lhs,const T & rhs)58 static inline bool operator!=(const T& lhs, const T& rhs)
59 {
60     return !(lhs == rhs);
61 }
62 
getMinorVersion(struct hwc_composer_device_1 * device)63 static uint8_t getMinorVersion(struct hwc_composer_device_1* device)
64 {
65     auto version = device->common.version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
66     return (version >> 16) & 0xF;
67 }
68 
69 template <typename PFN, typename T>
asFP(T function)70 static hwc2_function_pointer_t asFP(T function)
71 {
72     static_assert(std::is_same<PFN, T>::value, "Incompatible function pointer");
73     return reinterpret_cast<hwc2_function_pointer_t>(function);
74 }
75 
76 using namespace HWC2;
77 
78 static constexpr Attribute ColorMode = static_cast<Attribute>(6);
79 
80 namespace android {
81 
operator ()(hwc_display_contents_1_t * contents)82 void HWC2On1Adapter::DisplayContentsDeleter::operator()(
83         hwc_display_contents_1_t* contents)
84 {
85     if (contents != nullptr) {
86         for (size_t l = 0; l < contents->numHwLayers; ++l) {
87             auto& layer = contents->hwLayers[l];
88             std::free(const_cast<hwc_rect_t*>(layer.visibleRegionScreen.rects));
89         }
90     }
91     std::free(contents);
92 }
93 
94 class HWC2On1Adapter::Callbacks : public hwc_procs_t {
95     public:
Callbacks(HWC2On1Adapter & adapter)96         Callbacks(HWC2On1Adapter& adapter) : mAdapter(adapter) {
97             invalidate = &invalidateHook;
98             vsync = &vsyncHook;
99             hotplug = &hotplugHook;
100         }
101 
invalidateHook(const hwc_procs_t * procs)102         static void invalidateHook(const hwc_procs_t* procs) {
103             auto callbacks = static_cast<const Callbacks*>(procs);
104             callbacks->mAdapter.hwc1Invalidate();
105         }
106 
vsyncHook(const hwc_procs_t * procs,int display,int64_t timestamp)107         static void vsyncHook(const hwc_procs_t* procs, int display,
108                 int64_t timestamp) {
109             auto callbacks = static_cast<const Callbacks*>(procs);
110             callbacks->mAdapter.hwc1Vsync(display, timestamp);
111         }
112 
hotplugHook(const hwc_procs_t * procs,int display,int connected)113         static void hotplugHook(const hwc_procs_t* procs, int display,
114                 int connected) {
115             auto callbacks = static_cast<const Callbacks*>(procs);
116             callbacks->mAdapter.hwc1Hotplug(display, connected);
117         }
118 
119     private:
120         HWC2On1Adapter& mAdapter;
121 };
122 
closeHook(hw_device_t *)123 static int closeHook(hw_device_t* /*device*/)
124 {
125     // Do nothing, since the real work is done in the class destructor, but we
126     // need to provide a valid function pointer for hwc2_close to call
127     return 0;
128 }
129 
HWC2On1Adapter(hwc_composer_device_1_t * hwc1Device)130 HWC2On1Adapter::HWC2On1Adapter(hwc_composer_device_1_t* hwc1Device)
131   : mDumpString(),
132     mHwc1Device(hwc1Device),
133     mHwc1MinorVersion(getMinorVersion(hwc1Device)),
134     mHwc1SupportsVirtualDisplays(false),
135     mHwc1Callbacks(std::make_unique<Callbacks>(*this)),
136     mCapabilities(),
137     mLayers(),
138     mHwc1VirtualDisplay(),
139     mStateMutex(),
140     mCallbacks(),
141     mHasPendingInvalidate(false),
142     mPendingVsyncs(),
143     mPendingHotplugs(),
144     mDisplays(),
145     mHwc1DisplayMap()
146 {
147     common.close = closeHook;
148     getCapabilities = getCapabilitiesHook;
149     getFunction = getFunctionHook;
150     populateCapabilities();
151     populatePrimary();
152     mHwc1Device->registerProcs(mHwc1Device,
153             static_cast<const hwc_procs_t*>(mHwc1Callbacks.get()));
154 }
155 
~HWC2On1Adapter()156 HWC2On1Adapter::~HWC2On1Adapter() {
157     hwc_close_1(mHwc1Device);
158 }
159 
doGetCapabilities(uint32_t * outCount,int32_t * outCapabilities)160 void HWC2On1Adapter::doGetCapabilities(uint32_t* outCount,
161         int32_t* outCapabilities)
162 {
163     if (outCapabilities == nullptr) {
164         *outCount = mCapabilities.size();
165         return;
166     }
167 
168     auto capabilityIter = mCapabilities.cbegin();
169     for (size_t written = 0; written < *outCount; ++written) {
170         if (capabilityIter == mCapabilities.cend()) {
171             return;
172         }
173         outCapabilities[written] = static_cast<int32_t>(*capabilityIter);
174         ++capabilityIter;
175     }
176 }
177 
doGetFunction(FunctionDescriptor descriptor)178 hwc2_function_pointer_t HWC2On1Adapter::doGetFunction(
179         FunctionDescriptor descriptor)
180 {
181     switch (descriptor) {
182         // Device functions
183         case FunctionDescriptor::CreateVirtualDisplay:
184             return asFP<HWC2_PFN_CREATE_VIRTUAL_DISPLAY>(
185                     createVirtualDisplayHook);
186         case FunctionDescriptor::DestroyVirtualDisplay:
187             return asFP<HWC2_PFN_DESTROY_VIRTUAL_DISPLAY>(
188                     destroyVirtualDisplayHook);
189         case FunctionDescriptor::Dump:
190             return asFP<HWC2_PFN_DUMP>(dumpHook);
191         case FunctionDescriptor::GetMaxVirtualDisplayCount:
192             return asFP<HWC2_PFN_GET_MAX_VIRTUAL_DISPLAY_COUNT>(
193                     getMaxVirtualDisplayCountHook);
194         case FunctionDescriptor::RegisterCallback:
195             return asFP<HWC2_PFN_REGISTER_CALLBACK>(registerCallbackHook);
196 
197         // Display functions
198         case FunctionDescriptor::AcceptDisplayChanges:
199             return asFP<HWC2_PFN_ACCEPT_DISPLAY_CHANGES>(
200                     displayHook<decltype(&Display::acceptChanges),
201                     &Display::acceptChanges>);
202         case FunctionDescriptor::CreateLayer:
203             return asFP<HWC2_PFN_CREATE_LAYER>(
204                     displayHook<decltype(&Display::createLayer),
205                     &Display::createLayer, hwc2_layer_t*>);
206         case FunctionDescriptor::DestroyLayer:
207             return asFP<HWC2_PFN_DESTROY_LAYER>(
208                     displayHook<decltype(&Display::destroyLayer),
209                     &Display::destroyLayer, hwc2_layer_t>);
210         case FunctionDescriptor::GetActiveConfig:
211             return asFP<HWC2_PFN_GET_ACTIVE_CONFIG>(
212                     displayHook<decltype(&Display::getActiveConfig),
213                     &Display::getActiveConfig, hwc2_config_t*>);
214         case FunctionDescriptor::GetChangedCompositionTypes:
215             return asFP<HWC2_PFN_GET_CHANGED_COMPOSITION_TYPES>(
216                     displayHook<decltype(&Display::getChangedCompositionTypes),
217                     &Display::getChangedCompositionTypes, uint32_t*,
218                     hwc2_layer_t*, int32_t*>);
219         case FunctionDescriptor::GetColorModes:
220             return asFP<HWC2_PFN_GET_COLOR_MODES>(
221                     displayHook<decltype(&Display::getColorModes),
222                     &Display::getColorModes, uint32_t*, int32_t*>);
223         case FunctionDescriptor::GetDisplayAttribute:
224             return asFP<HWC2_PFN_GET_DISPLAY_ATTRIBUTE>(
225                     getDisplayAttributeHook);
226         case FunctionDescriptor::GetDisplayConfigs:
227             return asFP<HWC2_PFN_GET_DISPLAY_CONFIGS>(
228                     displayHook<decltype(&Display::getConfigs),
229                     &Display::getConfigs, uint32_t*, hwc2_config_t*>);
230         case FunctionDescriptor::GetDisplayName:
231             return asFP<HWC2_PFN_GET_DISPLAY_NAME>(
232                     displayHook<decltype(&Display::getName),
233                     &Display::getName, uint32_t*, char*>);
234         case FunctionDescriptor::GetDisplayRequests:
235             return asFP<HWC2_PFN_GET_DISPLAY_REQUESTS>(
236                     displayHook<decltype(&Display::getRequests),
237                     &Display::getRequests, int32_t*, uint32_t*, hwc2_layer_t*,
238                     int32_t*>);
239         case FunctionDescriptor::GetDisplayType:
240             return asFP<HWC2_PFN_GET_DISPLAY_TYPE>(
241                     displayHook<decltype(&Display::getType),
242                     &Display::getType, int32_t*>);
243         case FunctionDescriptor::GetDozeSupport:
244             return asFP<HWC2_PFN_GET_DOZE_SUPPORT>(
245                     displayHook<decltype(&Display::getDozeSupport),
246                     &Display::getDozeSupport, int32_t*>);
247         case FunctionDescriptor::GetHdrCapabilities:
248             return asFP<HWC2_PFN_GET_HDR_CAPABILITIES>(
249                     displayHook<decltype(&Display::getHdrCapabilities),
250                     &Display::getHdrCapabilities, uint32_t*, int32_t*, float*,
251                     float*, float*>);
252         case FunctionDescriptor::GetReleaseFences:
253             return asFP<HWC2_PFN_GET_RELEASE_FENCES>(
254                     displayHook<decltype(&Display::getReleaseFences),
255                     &Display::getReleaseFences, uint32_t*, hwc2_layer_t*,
256                     int32_t*>);
257         case FunctionDescriptor::PresentDisplay:
258             return asFP<HWC2_PFN_PRESENT_DISPLAY>(
259                     displayHook<decltype(&Display::present),
260                     &Display::present, int32_t*>);
261         case FunctionDescriptor::SetActiveConfig:
262             return asFP<HWC2_PFN_SET_ACTIVE_CONFIG>(
263                     displayHook<decltype(&Display::setActiveConfig),
264                     &Display::setActiveConfig, hwc2_config_t>);
265         case FunctionDescriptor::SetClientTarget:
266             return asFP<HWC2_PFN_SET_CLIENT_TARGET>(
267                     displayHook<decltype(&Display::setClientTarget),
268                     &Display::setClientTarget, buffer_handle_t, int32_t,
269                     int32_t, hwc_region_t>);
270         case FunctionDescriptor::SetColorMode:
271             return asFP<HWC2_PFN_SET_COLOR_MODE>(setColorModeHook);
272         case FunctionDescriptor::SetColorTransform:
273             return asFP<HWC2_PFN_SET_COLOR_TRANSFORM>(setColorTransformHook);
274         case FunctionDescriptor::SetOutputBuffer:
275             return asFP<HWC2_PFN_SET_OUTPUT_BUFFER>(
276                     displayHook<decltype(&Display::setOutputBuffer),
277                     &Display::setOutputBuffer, buffer_handle_t, int32_t>);
278         case FunctionDescriptor::SetPowerMode:
279             return asFP<HWC2_PFN_SET_POWER_MODE>(setPowerModeHook);
280         case FunctionDescriptor::SetVsyncEnabled:
281             return asFP<HWC2_PFN_SET_VSYNC_ENABLED>(setVsyncEnabledHook);
282         case FunctionDescriptor::ValidateDisplay:
283             return asFP<HWC2_PFN_VALIDATE_DISPLAY>(
284                     displayHook<decltype(&Display::validate),
285                     &Display::validate, uint32_t*, uint32_t*>);
286 
287         // Layer functions
288         case FunctionDescriptor::SetCursorPosition:
289             return asFP<HWC2_PFN_SET_CURSOR_POSITION>(
290                     layerHook<decltype(&Layer::setCursorPosition),
291                     &Layer::setCursorPosition, int32_t, int32_t>);
292         case FunctionDescriptor::SetLayerBuffer:
293             return asFP<HWC2_PFN_SET_LAYER_BUFFER>(
294                     layerHook<decltype(&Layer::setBuffer), &Layer::setBuffer,
295                     buffer_handle_t, int32_t>);
296         case FunctionDescriptor::SetLayerSurfaceDamage:
297             return asFP<HWC2_PFN_SET_LAYER_SURFACE_DAMAGE>(
298                     layerHook<decltype(&Layer::setSurfaceDamage),
299                     &Layer::setSurfaceDamage, hwc_region_t>);
300 
301         // Layer state functions
302         case FunctionDescriptor::SetLayerBlendMode:
303             return asFP<HWC2_PFN_SET_LAYER_BLEND_MODE>(
304                     setLayerBlendModeHook);
305         case FunctionDescriptor::SetLayerColor:
306             return asFP<HWC2_PFN_SET_LAYER_COLOR>(
307                     layerHook<decltype(&Layer::setColor), &Layer::setColor,
308                     hwc_color_t>);
309         case FunctionDescriptor::SetLayerCompositionType:
310             return asFP<HWC2_PFN_SET_LAYER_COMPOSITION_TYPE>(
311                     setLayerCompositionTypeHook);
312         case FunctionDescriptor::SetLayerDataspace:
313             return asFP<HWC2_PFN_SET_LAYER_DATASPACE>(setLayerDataspaceHook);
314         case FunctionDescriptor::SetLayerDisplayFrame:
315             return asFP<HWC2_PFN_SET_LAYER_DISPLAY_FRAME>(
316                     layerHook<decltype(&Layer::setDisplayFrame),
317                     &Layer::setDisplayFrame, hwc_rect_t>);
318         case FunctionDescriptor::SetLayerPlaneAlpha:
319             return asFP<HWC2_PFN_SET_LAYER_PLANE_ALPHA>(
320                     layerHook<decltype(&Layer::setPlaneAlpha),
321                     &Layer::setPlaneAlpha, float>);
322         case FunctionDescriptor::SetLayerSidebandStream:
323             return asFP<HWC2_PFN_SET_LAYER_SIDEBAND_STREAM>(
324                     layerHook<decltype(&Layer::setSidebandStream),
325                     &Layer::setSidebandStream, const native_handle_t*>);
326         case FunctionDescriptor::SetLayerSourceCrop:
327             return asFP<HWC2_PFN_SET_LAYER_SOURCE_CROP>(
328                     layerHook<decltype(&Layer::setSourceCrop),
329                     &Layer::setSourceCrop, hwc_frect_t>);
330         case FunctionDescriptor::SetLayerTransform:
331             return asFP<HWC2_PFN_SET_LAYER_TRANSFORM>(setLayerTransformHook);
332         case FunctionDescriptor::SetLayerVisibleRegion:
333             return asFP<HWC2_PFN_SET_LAYER_VISIBLE_REGION>(
334                     layerHook<decltype(&Layer::setVisibleRegion),
335                     &Layer::setVisibleRegion, hwc_region_t>);
336         case FunctionDescriptor::SetLayerZOrder:
337             return asFP<HWC2_PFN_SET_LAYER_Z_ORDER>(setLayerZOrderHook);
338 
339         default:
340             ALOGE("doGetFunction: Unknown function descriptor: %d (%s)",
341                     static_cast<int32_t>(descriptor),
342                     to_string(descriptor).c_str());
343             return nullptr;
344     }
345 }
346 
347 // Device functions
348 
createVirtualDisplay(uint32_t width,uint32_t height,hwc2_display_t * outDisplay)349 Error HWC2On1Adapter::createVirtualDisplay(uint32_t width,
350         uint32_t height, hwc2_display_t* outDisplay)
351 {
352     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
353 
354     if (mHwc1VirtualDisplay) {
355         // We have already allocated our only HWC1 virtual display
356         ALOGE("createVirtualDisplay: HWC1 virtual display already allocated");
357         return Error::NoResources;
358     }
359 
360     if (MAX_VIRTUAL_DISPLAY_DIMENSION != 0 &&
361             (width > MAX_VIRTUAL_DISPLAY_DIMENSION ||
362             height > MAX_VIRTUAL_DISPLAY_DIMENSION)) {
363         ALOGE("createVirtualDisplay: Can't create a virtual display with"
364                 " a dimension > %u (tried %u x %u)",
365                 MAX_VIRTUAL_DISPLAY_DIMENSION, width, height);
366         return Error::NoResources;
367     }
368 
369     mHwc1VirtualDisplay = std::make_shared<HWC2On1Adapter::Display>(*this,
370             HWC2::DisplayType::Virtual);
371     mHwc1VirtualDisplay->populateConfigs(width, height);
372     const auto displayId = mHwc1VirtualDisplay->getId();
373     mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL] = displayId;
374     mHwc1VirtualDisplay->setHwc1Id(HWC_DISPLAY_VIRTUAL);
375     mDisplays.emplace(displayId, mHwc1VirtualDisplay);
376     *outDisplay = displayId;
377 
378     return Error::None;
379 }
380 
destroyVirtualDisplay(hwc2_display_t displayId)381 Error HWC2On1Adapter::destroyVirtualDisplay(hwc2_display_t displayId)
382 {
383     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
384 
385     if (!mHwc1VirtualDisplay || (mHwc1VirtualDisplay->getId() != displayId)) {
386         return Error::BadDisplay;
387     }
388 
389     mHwc1VirtualDisplay.reset();
390     mHwc1DisplayMap.erase(HWC_DISPLAY_VIRTUAL);
391     mDisplays.erase(displayId);
392 
393     return Error::None;
394 }
395 
dump(uint32_t * outSize,char * outBuffer)396 void HWC2On1Adapter::dump(uint32_t* outSize, char* outBuffer)
397 {
398     if (outBuffer != nullptr) {
399         auto copiedBytes = mDumpString.copy(outBuffer, *outSize);
400         *outSize = static_cast<uint32_t>(copiedBytes);
401         return;
402     }
403 
404     std::stringstream output;
405 
406     output << "-- HWC2On1Adapter --\n";
407 
408     output << "Adapting to a HWC 1." << static_cast<int>(mHwc1MinorVersion) <<
409             " device\n";
410 
411     // Attempt to acquire the lock for 1 second, but proceed without the lock
412     // after that, so we can still get some information if we're deadlocked
413     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex,
414             std::defer_lock);
415     lock.try_lock_for(1s);
416 
417     if (mCapabilities.empty()) {
418         output << "Capabilities: None\n";
419     } else {
420         output << "Capabilities:\n";
421         for (auto capability : mCapabilities) {
422             output << "  " << to_string(capability) << '\n';
423         }
424     }
425 
426     output << "Displays:\n";
427     for (const auto& element : mDisplays) {
428         const auto& display = element.second;
429         output << display->dump();
430     }
431     output << '\n';
432 
433     // Release the lock before calling into HWC1, and since we no longer require
434     // mutual exclusion to access mCapabilities or mDisplays
435     lock.unlock();
436 
437     if (mHwc1Device->dump) {
438         output << "HWC1 dump:\n";
439         std::vector<char> hwc1Dump(4096);
440         // Call with size - 1 to preserve a null character at the end
441         mHwc1Device->dump(mHwc1Device, hwc1Dump.data(),
442                 static_cast<int>(hwc1Dump.size() - 1));
443         output << hwc1Dump.data();
444     }
445 
446     mDumpString = output.str();
447     *outSize = static_cast<uint32_t>(mDumpString.size());
448 }
449 
getMaxVirtualDisplayCount()450 uint32_t HWC2On1Adapter::getMaxVirtualDisplayCount()
451 {
452     return mHwc1SupportsVirtualDisplays ? 1 : 0;
453 }
454 
isValid(Callback descriptor)455 static bool isValid(Callback descriptor) {
456     switch (descriptor) {
457         case Callback::Hotplug: // Fall-through
458         case Callback::Refresh: // Fall-through
459         case Callback::Vsync: return true;
460         default: return false;
461     }
462 }
463 
registerCallback(Callback descriptor,hwc2_callback_data_t callbackData,hwc2_function_pointer_t pointer)464 Error HWC2On1Adapter::registerCallback(Callback descriptor,
465         hwc2_callback_data_t callbackData, hwc2_function_pointer_t pointer)
466 {
467     if (!isValid(descriptor)) {
468         return Error::BadParameter;
469     }
470 
471     ALOGV("registerCallback(%s, %p, %p)", to_string(descriptor).c_str(),
472             callbackData, pointer);
473 
474     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
475 
476     mCallbacks[descriptor] = {callbackData, pointer};
477 
478     bool hasPendingInvalidate = false;
479     std::vector<hwc2_display_t> displayIds;
480     std::vector<std::pair<hwc2_display_t, int64_t>> pendingVsyncs;
481     std::vector<std::pair<hwc2_display_t, int>> pendingHotplugs;
482 
483     if (descriptor == Callback::Refresh) {
484         hasPendingInvalidate = mHasPendingInvalidate;
485         if (hasPendingInvalidate) {
486             for (auto& displayPair : mDisplays) {
487                 displayIds.emplace_back(displayPair.first);
488             }
489         }
490         mHasPendingInvalidate = false;
491     } else if (descriptor == Callback::Vsync) {
492         for (auto pending : mPendingVsyncs) {
493             auto hwc1DisplayId = pending.first;
494             if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
495                 ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d",
496                         hwc1DisplayId);
497                 continue;
498             }
499             auto displayId = mHwc1DisplayMap[hwc1DisplayId];
500             auto timestamp = pending.second;
501             pendingVsyncs.emplace_back(displayId, timestamp);
502         }
503         mPendingVsyncs.clear();
504     } else if (descriptor == Callback::Hotplug) {
505         // Hotplug the primary display
506         pendingHotplugs.emplace_back(mHwc1DisplayMap[HWC_DISPLAY_PRIMARY],
507                 static_cast<int32_t>(Connection::Connected));
508 
509         for (auto pending : mPendingHotplugs) {
510             auto hwc1DisplayId = pending.first;
511             if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
512                 ALOGE("hwc1Hotplug: Couldn't find display for HWC1 id %d",
513                         hwc1DisplayId);
514                 continue;
515             }
516             auto displayId = mHwc1DisplayMap[hwc1DisplayId];
517             auto connected = pending.second;
518             pendingHotplugs.emplace_back(displayId, connected);
519         }
520     }
521 
522     // Call pending callbacks without the state lock held
523     lock.unlock();
524 
525     if (hasPendingInvalidate) {
526         auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(pointer);
527         for (auto displayId : displayIds) {
528             refresh(callbackData, displayId);
529         }
530     }
531     if (!pendingVsyncs.empty()) {
532         auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(pointer);
533         for (auto& pendingVsync : pendingVsyncs) {
534             vsync(callbackData, pendingVsync.first, pendingVsync.second);
535         }
536     }
537     if (!pendingHotplugs.empty()) {
538         auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(pointer);
539         for (auto& pendingHotplug : pendingHotplugs) {
540             hotplug(callbackData, pendingHotplug.first, pendingHotplug.second);
541         }
542     }
543     return Error::None;
544 }
545 
546 // Display functions
547 
548 std::atomic<hwc2_display_t> HWC2On1Adapter::Display::sNextId(1);
549 
Display(HWC2On1Adapter & device,HWC2::DisplayType type)550 HWC2On1Adapter::Display::Display(HWC2On1Adapter& device, HWC2::DisplayType type)
551   : mId(sNextId++),
552     mDevice(device),
553     mDirtyCount(0),
554     mStateMutex(),
555     mZIsDirty(false),
556     mHwc1RequestedContents(nullptr),
557     mHwc1ReceivedContents(nullptr),
558     mRetireFence(),
559     mChanges(),
560     mHwc1Id(-1),
561     mConfigs(),
562     mActiveConfig(nullptr),
563     mName(),
564     mType(type),
565     mPowerMode(PowerMode::Off),
566     mVsyncEnabled(Vsync::Invalid),
567     mClientTarget(),
568     mOutputBuffer(),
569     mHasColorTransform(false),
570     mLayers(),
571     mHwc1LayerMap() {}
572 
acceptChanges()573 Error HWC2On1Adapter::Display::acceptChanges()
574 {
575     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
576 
577     if (!mChanges) {
578         ALOGV("[%" PRIu64 "] acceptChanges failed, not validated", mId);
579         return Error::NotValidated;
580     }
581 
582     ALOGV("[%" PRIu64 "] acceptChanges", mId);
583 
584     for (auto& change : mChanges->getTypeChanges()) {
585         auto layerId = change.first;
586         auto type = change.second;
587         auto layer = mDevice.mLayers[layerId];
588         layer->setCompositionType(type);
589     }
590 
591     mChanges->clearTypeChanges();
592 
593     mHwc1RequestedContents = std::move(mHwc1ReceivedContents);
594 
595     return Error::None;
596 }
597 
createLayer(hwc2_layer_t * outLayerId)598 Error HWC2On1Adapter::Display::createLayer(hwc2_layer_t* outLayerId)
599 {
600     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
601 
602     auto layer = *mLayers.emplace(std::make_shared<Layer>(*this));
603     mDevice.mLayers.emplace(std::make_pair(layer->getId(), layer));
604     *outLayerId = layer->getId();
605     ALOGV("[%" PRIu64 "] created layer %" PRIu64, mId, *outLayerId);
606     return Error::None;
607 }
608 
destroyLayer(hwc2_layer_t layerId)609 Error HWC2On1Adapter::Display::destroyLayer(hwc2_layer_t layerId)
610 {
611     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
612 
613     const auto mapLayer = mDevice.mLayers.find(layerId);
614     if (mapLayer == mDevice.mLayers.end()) {
615         ALOGV("[%" PRIu64 "] destroyLayer(%" PRIu64 ") failed: no such layer",
616                 mId, layerId);
617         return Error::BadLayer;
618     }
619     const auto layer = mapLayer->second;
620     mDevice.mLayers.erase(mapLayer);
621     const auto zRange = mLayers.equal_range(layer);
622     for (auto current = zRange.first; current != zRange.second; ++current) {
623         if (**current == *layer) {
624             current = mLayers.erase(current);
625             break;
626         }
627     }
628     ALOGV("[%" PRIu64 "] destroyed layer %" PRIu64, mId, layerId);
629     return Error::None;
630 }
631 
getActiveConfig(hwc2_config_t * outConfig)632 Error HWC2On1Adapter::Display::getActiveConfig(hwc2_config_t* outConfig)
633 {
634     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
635 
636     if (!mActiveConfig) {
637         ALOGV("[%" PRIu64 "] getActiveConfig --> %s", mId,
638                 to_string(Error::BadConfig).c_str());
639         return Error::BadConfig;
640     }
641     auto configId = mActiveConfig->getId();
642     ALOGV("[%" PRIu64 "] getActiveConfig --> %u", mId, configId);
643     *outConfig = configId;
644     return Error::None;
645 }
646 
getAttribute(hwc2_config_t configId,Attribute attribute,int32_t * outValue)647 Error HWC2On1Adapter::Display::getAttribute(hwc2_config_t configId,
648         Attribute attribute, int32_t* outValue)
649 {
650     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
651 
652     if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
653         ALOGV("[%" PRIu64 "] getAttribute failed: bad config (%u)", mId,
654                 configId);
655         return Error::BadConfig;
656     }
657     *outValue = mConfigs[configId]->getAttribute(attribute);
658     ALOGV("[%" PRIu64 "] getAttribute(%u, %s) --> %d", mId, configId,
659             to_string(attribute).c_str(), *outValue);
660     return Error::None;
661 }
662 
getChangedCompositionTypes(uint32_t * outNumElements,hwc2_layer_t * outLayers,int32_t * outTypes)663 Error HWC2On1Adapter::Display::getChangedCompositionTypes(
664         uint32_t* outNumElements, hwc2_layer_t* outLayers, int32_t* outTypes)
665 {
666     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
667 
668     if (!mChanges) {
669         ALOGE("[%" PRIu64 "] getChangedCompositionTypes failed: not validated",
670                 mId);
671         return Error::NotValidated;
672     }
673 
674     if ((outLayers == nullptr) || (outTypes == nullptr)) {
675         *outNumElements = mChanges->getTypeChanges().size();
676         return Error::None;
677     }
678 
679     uint32_t numWritten = 0;
680     for (const auto& element : mChanges->getTypeChanges()) {
681         if (numWritten == *outNumElements) {
682             break;
683         }
684         auto layerId = element.first;
685         auto intType = static_cast<int32_t>(element.second);
686         ALOGV("Adding %" PRIu64 " %s", layerId,
687                 to_string(element.second).c_str());
688         outLayers[numWritten] = layerId;
689         outTypes[numWritten] = intType;
690         ++numWritten;
691     }
692     *outNumElements = numWritten;
693 
694     return Error::None;
695 }
696 
getColorModes(uint32_t * outNumModes,int32_t * outModes)697 Error HWC2On1Adapter::Display::getColorModes(uint32_t* outNumModes,
698         int32_t* outModes)
699 {
700     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
701 
702     if (!outModes) {
703         *outNumModes = mColorModes.size();
704         return Error::None;
705     }
706     uint32_t numModes = std::min(*outNumModes,
707             static_cast<uint32_t>(mColorModes.size()));
708     std::copy_n(mColorModes.cbegin(), numModes, outModes);
709     *outNumModes = numModes;
710     return Error::None;
711 }
712 
getConfigs(uint32_t * outNumConfigs,hwc2_config_t * outConfigs)713 Error HWC2On1Adapter::Display::getConfigs(uint32_t* outNumConfigs,
714         hwc2_config_t* outConfigs)
715 {
716     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
717 
718     if (!outConfigs) {
719         *outNumConfigs = mConfigs.size();
720         return Error::None;
721     }
722     uint32_t numWritten = 0;
723     for (const auto& config : mConfigs) {
724         if (numWritten == *outNumConfigs) {
725             break;
726         }
727         outConfigs[numWritten] = config->getId();
728         ++numWritten;
729     }
730     *outNumConfigs = numWritten;
731     return Error::None;
732 }
733 
getDozeSupport(int32_t * outSupport)734 Error HWC2On1Adapter::Display::getDozeSupport(int32_t* outSupport)
735 {
736     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
737 
738     if (mDevice.mHwc1MinorVersion < 4 || mHwc1Id != 0) {
739         *outSupport = 0;
740     } else {
741         *outSupport = 1;
742     }
743     return Error::None;
744 }
745 
getHdrCapabilities(uint32_t * outNumTypes,int32_t *,float *,float *,float *)746 Error HWC2On1Adapter::Display::getHdrCapabilities(uint32_t* outNumTypes,
747         int32_t* /*outTypes*/, float* /*outMaxLuminance*/,
748         float* /*outMaxAverageLuminance*/, float* /*outMinLuminance*/)
749 {
750     // This isn't supported on HWC1, so per the HWC2 header, return numTypes = 0
751     *outNumTypes = 0;
752     return Error::None;
753 }
754 
getName(uint32_t * outSize,char * outName)755 Error HWC2On1Adapter::Display::getName(uint32_t* outSize, char* outName)
756 {
757     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
758 
759     if (!outName) {
760         *outSize = mName.size();
761         return Error::None;
762     }
763     auto numCopied = mName.copy(outName, *outSize);
764     *outSize = numCopied;
765     return Error::None;
766 }
767 
getReleaseFences(uint32_t * outNumElements,hwc2_layer_t * outLayers,int32_t * outFences)768 Error HWC2On1Adapter::Display::getReleaseFences(uint32_t* outNumElements,
769         hwc2_layer_t* outLayers, int32_t* outFences)
770 {
771     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
772 
773     uint32_t numWritten = 0;
774     bool outputsNonNull = (outLayers != nullptr) && (outFences != nullptr);
775     for (const auto& layer : mLayers) {
776         if (outputsNonNull && (numWritten == *outNumElements)) {
777             break;
778         }
779 
780         auto releaseFence = layer->getReleaseFence();
781         if (releaseFence != Fence::NO_FENCE) {
782             if (outputsNonNull) {
783                 outLayers[numWritten] = layer->getId();
784                 outFences[numWritten] = releaseFence->dup();
785             }
786             ++numWritten;
787         }
788     }
789     *outNumElements = numWritten;
790 
791     return Error::None;
792 }
793 
getRequests(int32_t * outDisplayRequests,uint32_t * outNumElements,hwc2_layer_t * outLayers,int32_t * outLayerRequests)794 Error HWC2On1Adapter::Display::getRequests(int32_t* outDisplayRequests,
795         uint32_t* outNumElements, hwc2_layer_t* outLayers,
796         int32_t* outLayerRequests)
797 {
798     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
799 
800     if (!mChanges) {
801         return Error::NotValidated;
802     }
803 
804     if (outLayers == nullptr || outLayerRequests == nullptr) {
805         *outNumElements = mChanges->getNumLayerRequests();
806         return Error::None;
807     }
808 
809     *outDisplayRequests = mChanges->getDisplayRequests();
810     uint32_t numWritten = 0;
811     for (const auto& request : mChanges->getLayerRequests()) {
812         if (numWritten == *outNumElements) {
813             break;
814         }
815         outLayers[numWritten] = request.first;
816         outLayerRequests[numWritten] = static_cast<int32_t>(request.second);
817         ++numWritten;
818     }
819 
820     return Error::None;
821 }
822 
getType(int32_t * outType)823 Error HWC2On1Adapter::Display::getType(int32_t* outType)
824 {
825     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
826 
827     *outType = static_cast<int32_t>(mType);
828     return Error::None;
829 }
830 
present(int32_t * outRetireFence)831 Error HWC2On1Adapter::Display::present(int32_t* outRetireFence)
832 {
833     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
834 
835     if (mChanges) {
836         Error error = mDevice.setAllDisplays();
837         if (error != Error::None) {
838             ALOGE("[%" PRIu64 "] present: setAllDisplaysFailed (%s)", mId,
839                     to_string(error).c_str());
840             return error;
841         }
842     }
843 
844     *outRetireFence = mRetireFence.get()->dup();
845     ALOGV("[%" PRIu64 "] present returning retire fence %d", mId,
846             *outRetireFence);
847 
848     return Error::None;
849 }
850 
setActiveConfig(hwc2_config_t configId)851 Error HWC2On1Adapter::Display::setActiveConfig(hwc2_config_t configId)
852 {
853     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
854 
855     auto config = getConfig(configId);
856     if (!config) {
857         return Error::BadConfig;
858     }
859     if (config == mActiveConfig) {
860         return Error::None;
861     }
862 
863     if (mDevice.mHwc1MinorVersion >= 4) {
864         uint32_t hwc1Id = 0;
865         auto error = config->getHwc1IdForColorMode(mActiveColorMode, &hwc1Id);
866         if (error != Error::None) {
867             return error;
868         }
869 
870         int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
871                 mHwc1Id, static_cast<int>(hwc1Id));
872         if (intError != 0) {
873             ALOGE("setActiveConfig: Failed to set active config on HWC1 (%d)",
874                 intError);
875             return Error::BadConfig;
876         }
877         mActiveConfig = config;
878     }
879 
880     return Error::None;
881 }
882 
setClientTarget(buffer_handle_t target,int32_t acquireFence,int32_t,hwc_region_t)883 Error HWC2On1Adapter::Display::setClientTarget(buffer_handle_t target,
884         int32_t acquireFence, int32_t /*dataspace*/, hwc_region_t /*damage*/)
885 {
886     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
887 
888     ALOGV("[%" PRIu64 "] setClientTarget(%p, %d)", mId, target, acquireFence);
889     mClientTarget.setBuffer(target);
890     mClientTarget.setFence(acquireFence);
891     // dataspace and damage can't be used by HWC1, so ignore them
892     return Error::None;
893 }
894 
setColorMode(android_color_mode_t mode)895 Error HWC2On1Adapter::Display::setColorMode(android_color_mode_t mode)
896 {
897     std::unique_lock<std::recursive_mutex> lock (mStateMutex);
898 
899     ALOGV("[%" PRIu64 "] setColorMode(%d)", mId, mode);
900 
901     if (mode == mActiveColorMode) {
902         return Error::None;
903     }
904     if (mColorModes.count(mode) == 0) {
905         ALOGE("[%" PRIu64 "] Mode %d not found in mColorModes", mId, mode);
906         return Error::Unsupported;
907     }
908 
909     uint32_t hwc1Config = 0;
910     auto error = mActiveConfig->getHwc1IdForColorMode(mode, &hwc1Config);
911     if (error != Error::None) {
912         return error;
913     }
914 
915     ALOGV("[%" PRIu64 "] Setting HWC1 config %u", mId, hwc1Config);
916     int intError = mDevice.mHwc1Device->setActiveConfig(mDevice.mHwc1Device,
917             mHwc1Id, hwc1Config);
918     if (intError != 0) {
919         ALOGE("[%" PRIu64 "] Failed to set HWC1 config (%d)", mId, intError);
920         return Error::Unsupported;
921     }
922 
923     mActiveColorMode = mode;
924     return Error::None;
925 }
926 
setColorTransform(android_color_transform_t hint)927 Error HWC2On1Adapter::Display::setColorTransform(android_color_transform_t hint)
928 {
929     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
930 
931     ALOGV("%" PRIu64 "] setColorTransform(%d)", mId,
932             static_cast<int32_t>(hint));
933     mHasColorTransform = (hint != HAL_COLOR_TRANSFORM_IDENTITY);
934     return Error::None;
935 }
936 
setOutputBuffer(buffer_handle_t buffer,int32_t releaseFence)937 Error HWC2On1Adapter::Display::setOutputBuffer(buffer_handle_t buffer,
938         int32_t releaseFence)
939 {
940     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
941 
942     ALOGV("[%" PRIu64 "] setOutputBuffer(%p, %d)", mId, buffer, releaseFence);
943     mOutputBuffer.setBuffer(buffer);
944     mOutputBuffer.setFence(releaseFence);
945     return Error::None;
946 }
947 
isValid(PowerMode mode)948 static bool isValid(PowerMode mode)
949 {
950     switch (mode) {
951         case PowerMode::Off: // Fall-through
952         case PowerMode::DozeSuspend: // Fall-through
953         case PowerMode::Doze: // Fall-through
954         case PowerMode::On: return true;
955         default: return false;
956     }
957 }
958 
getHwc1PowerMode(PowerMode mode)959 static int getHwc1PowerMode(PowerMode mode)
960 {
961     switch (mode) {
962         case PowerMode::Off: return HWC_POWER_MODE_OFF;
963         case PowerMode::DozeSuspend: return HWC_POWER_MODE_DOZE_SUSPEND;
964         case PowerMode::Doze: return HWC_POWER_MODE_DOZE;
965         case PowerMode::On: return HWC_POWER_MODE_NORMAL;
966         default: return HWC_POWER_MODE_OFF;
967     }
968 }
969 
setPowerMode(PowerMode mode)970 Error HWC2On1Adapter::Display::setPowerMode(PowerMode mode)
971 {
972     if (!isValid(mode)) {
973         return Error::BadParameter;
974     }
975     if (mode == mPowerMode) {
976         return Error::None;
977     }
978 
979     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
980 
981     int error = 0;
982     if (mDevice.mHwc1MinorVersion < 4) {
983         error = mDevice.mHwc1Device->blank(mDevice.mHwc1Device, mHwc1Id,
984                 mode == PowerMode::Off);
985     } else {
986         error = mDevice.mHwc1Device->setPowerMode(mDevice.mHwc1Device,
987                 mHwc1Id, getHwc1PowerMode(mode));
988     }
989     ALOGE_IF(error != 0, "setPowerMode: Failed to set power mode on HWC1 (%d)",
990             error);
991 
992     ALOGV("[%" PRIu64 "] setPowerMode(%s)", mId, to_string(mode).c_str());
993     mPowerMode = mode;
994     return Error::None;
995 }
996 
isValid(Vsync enable)997 static bool isValid(Vsync enable) {
998     switch (enable) {
999         case Vsync::Enable: // Fall-through
1000         case Vsync::Disable: return true;
1001         default: return false;
1002     }
1003 }
1004 
setVsyncEnabled(Vsync enable)1005 Error HWC2On1Adapter::Display::setVsyncEnabled(Vsync enable)
1006 {
1007     if (!isValid(enable)) {
1008         return Error::BadParameter;
1009     }
1010     if (enable == mVsyncEnabled) {
1011         return Error::None;
1012     }
1013 
1014     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1015 
1016     int error = mDevice.mHwc1Device->eventControl(mDevice.mHwc1Device,
1017             mHwc1Id, HWC_EVENT_VSYNC, enable == Vsync::Enable);
1018     ALOGE_IF(error != 0, "setVsyncEnabled: Failed to set vsync on HWC1 (%d)",
1019             error);
1020 
1021     mVsyncEnabled = enable;
1022     return Error::None;
1023 }
1024 
validate(uint32_t * outNumTypes,uint32_t * outNumRequests)1025 Error HWC2On1Adapter::Display::validate(uint32_t* outNumTypes,
1026         uint32_t* outNumRequests)
1027 {
1028     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1029 
1030     ALOGV("[%" PRIu64 "] Entering validate", mId);
1031 
1032     if (!mChanges) {
1033         if (!mDevice.prepareAllDisplays()) {
1034             return Error::BadDisplay;
1035         }
1036     }
1037 
1038     *outNumTypes = mChanges->getNumTypes();
1039     *outNumRequests = mChanges->getNumLayerRequests();
1040     ALOGV("[%" PRIu64 "] validate --> %u types, %u requests", mId, *outNumTypes,
1041             *outNumRequests);
1042     for (auto request : mChanges->getTypeChanges()) {
1043         ALOGV("Layer %" PRIu64 " --> %s", request.first,
1044                 to_string(request.second).c_str());
1045     }
1046     return *outNumTypes > 0 ? Error::HasChanges : Error::None;
1047 }
1048 
1049 // Display helpers
1050 
updateLayerZ(hwc2_layer_t layerId,uint32_t z)1051 Error HWC2On1Adapter::Display::updateLayerZ(hwc2_layer_t layerId, uint32_t z)
1052 {
1053     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1054 
1055     const auto mapLayer = mDevice.mLayers.find(layerId);
1056     if (mapLayer == mDevice.mLayers.end()) {
1057         ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer", mId);
1058         return Error::BadLayer;
1059     }
1060 
1061     const auto layer = mapLayer->second;
1062     const auto zRange = mLayers.equal_range(layer);
1063     bool layerOnDisplay = false;
1064     for (auto current = zRange.first; current != zRange.second; ++current) {
1065         if (**current == *layer) {
1066             if ((*current)->getZ() == z) {
1067                 // Don't change anything if the Z hasn't changed
1068                 return Error::None;
1069             }
1070             current = mLayers.erase(current);
1071             layerOnDisplay = true;
1072             break;
1073         }
1074     }
1075 
1076     if (!layerOnDisplay) {
1077         ALOGE("[%" PRIu64 "] updateLayerZ failed to find layer on display",
1078                 mId);
1079         return Error::BadLayer;
1080     }
1081 
1082     layer->setZ(z);
1083     mLayers.emplace(std::move(layer));
1084     mZIsDirty = true;
1085 
1086     return Error::None;
1087 }
1088 
1089 static constexpr uint32_t ATTRIBUTES_WITH_COLOR[] = {
1090     HWC_DISPLAY_VSYNC_PERIOD,
1091     HWC_DISPLAY_WIDTH,
1092     HWC_DISPLAY_HEIGHT,
1093     HWC_DISPLAY_DPI_X,
1094     HWC_DISPLAY_DPI_Y,
1095     HWC_DISPLAY_COLOR_TRANSFORM,
1096     HWC_DISPLAY_NO_ATTRIBUTE,
1097 };
1098 
1099 static constexpr uint32_t ATTRIBUTES_WITHOUT_COLOR[] = {
1100     HWC_DISPLAY_VSYNC_PERIOD,
1101     HWC_DISPLAY_WIDTH,
1102     HWC_DISPLAY_HEIGHT,
1103     HWC_DISPLAY_DPI_X,
1104     HWC_DISPLAY_DPI_Y,
1105     HWC_DISPLAY_NO_ATTRIBUTE,
1106 };
1107 
1108 static constexpr size_t NUM_ATTRIBUTES_WITH_COLOR =
1109         sizeof(ATTRIBUTES_WITH_COLOR) / sizeof(uint32_t);
1110 static_assert(sizeof(ATTRIBUTES_WITH_COLOR) > sizeof(ATTRIBUTES_WITHOUT_COLOR),
1111         "Attribute tables have unexpected sizes");
1112 
1113 static constexpr uint32_t ATTRIBUTE_MAP_WITH_COLOR[] = {
1114     6, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1115     0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1116     1, // HWC_DISPLAY_WIDTH = 2,
1117     2, // HWC_DISPLAY_HEIGHT = 3,
1118     3, // HWC_DISPLAY_DPI_X = 4,
1119     4, // HWC_DISPLAY_DPI_Y = 5,
1120     5, // HWC_DISPLAY_COLOR_TRANSFORM = 6,
1121 };
1122 
1123 static constexpr uint32_t ATTRIBUTE_MAP_WITHOUT_COLOR[] = {
1124     5, // HWC_DISPLAY_NO_ATTRIBUTE = 0
1125     0, // HWC_DISPLAY_VSYNC_PERIOD = 1,
1126     1, // HWC_DISPLAY_WIDTH = 2,
1127     2, // HWC_DISPLAY_HEIGHT = 3,
1128     3, // HWC_DISPLAY_DPI_X = 4,
1129     4, // HWC_DISPLAY_DPI_Y = 5,
1130 };
1131 
1132 template <uint32_t attribute>
attributesMatch()1133 static constexpr bool attributesMatch()
1134 {
1135     bool match = (attribute ==
1136             ATTRIBUTES_WITH_COLOR[ATTRIBUTE_MAP_WITH_COLOR[attribute]]);
1137     if (attribute == HWC_DISPLAY_COLOR_TRANSFORM) {
1138         return match;
1139     }
1140 
1141     return match && (attribute ==
1142             ATTRIBUTES_WITHOUT_COLOR[ATTRIBUTE_MAP_WITHOUT_COLOR[attribute]]);
1143 }
1144 static_assert(attributesMatch<HWC_DISPLAY_VSYNC_PERIOD>(),
1145         "Tables out of sync");
1146 static_assert(attributesMatch<HWC_DISPLAY_WIDTH>(), "Tables out of sync");
1147 static_assert(attributesMatch<HWC_DISPLAY_HEIGHT>(), "Tables out of sync");
1148 static_assert(attributesMatch<HWC_DISPLAY_DPI_X>(), "Tables out of sync");
1149 static_assert(attributesMatch<HWC_DISPLAY_DPI_Y>(), "Tables out of sync");
1150 static_assert(attributesMatch<HWC_DISPLAY_COLOR_TRANSFORM>(),
1151         "Tables out of sync");
1152 
populateConfigs()1153 void HWC2On1Adapter::Display::populateConfigs()
1154 {
1155     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1156 
1157     ALOGV("[%" PRIu64 "] populateConfigs", mId);
1158 
1159     if (mHwc1Id == -1) {
1160         ALOGE("populateConfigs: HWC1 ID not set");
1161         return;
1162     }
1163 
1164     const size_t MAX_NUM_CONFIGS = 128;
1165     uint32_t configs[MAX_NUM_CONFIGS] = {};
1166     size_t numConfigs = MAX_NUM_CONFIGS;
1167     mDevice.mHwc1Device->getDisplayConfigs(mDevice.mHwc1Device, mHwc1Id,
1168             configs, &numConfigs);
1169 
1170     for (size_t c = 0; c < numConfigs; ++c) {
1171         uint32_t hwc1ConfigId = configs[c];
1172         auto newConfig = std::make_shared<Config>(*this);
1173 
1174         int32_t values[NUM_ATTRIBUTES_WITH_COLOR] = {};
1175         bool hasColor = true;
1176         auto result = mDevice.mHwc1Device->getDisplayAttributes(
1177                 mDevice.mHwc1Device, mHwc1Id, hwc1ConfigId,
1178                 ATTRIBUTES_WITH_COLOR, values);
1179         if (result != 0) {
1180             mDevice.mHwc1Device->getDisplayAttributes(mDevice.mHwc1Device,
1181                     mHwc1Id, hwc1ConfigId, ATTRIBUTES_WITHOUT_COLOR, values);
1182             hasColor = false;
1183         }
1184 
1185         auto attributeMap = hasColor ?
1186                 ATTRIBUTE_MAP_WITH_COLOR : ATTRIBUTE_MAP_WITHOUT_COLOR;
1187 
1188         newConfig->setAttribute(Attribute::VsyncPeriod,
1189                 values[attributeMap[HWC_DISPLAY_VSYNC_PERIOD]]);
1190         newConfig->setAttribute(Attribute::Width,
1191                 values[attributeMap[HWC_DISPLAY_WIDTH]]);
1192         newConfig->setAttribute(Attribute::Height,
1193                 values[attributeMap[HWC_DISPLAY_HEIGHT]]);
1194         newConfig->setAttribute(Attribute::DpiX,
1195                 values[attributeMap[HWC_DISPLAY_DPI_X]]);
1196         newConfig->setAttribute(Attribute::DpiY,
1197                 values[attributeMap[HWC_DISPLAY_DPI_Y]]);
1198         if (hasColor) {
1199             // In HWC1, color modes are referred to as color transforms. To avoid confusion with
1200             // the HWC2 concept of color transforms, we internally refer to them as color modes for
1201             // both HWC1 and 2.
1202             newConfig->setAttribute(ColorMode,
1203                     values[attributeMap[HWC_DISPLAY_COLOR_TRANSFORM]]);
1204         }
1205 
1206         // We can only do this after attempting to read the color mode
1207         newConfig->setHwc1Id(hwc1ConfigId);
1208 
1209         for (auto& existingConfig : mConfigs) {
1210             if (existingConfig->merge(*newConfig)) {
1211                 ALOGV("Merged config %d with existing config %u: %s",
1212                         hwc1ConfigId, existingConfig->getId(),
1213                         existingConfig->toString().c_str());
1214                 newConfig.reset();
1215                 break;
1216             }
1217         }
1218 
1219         // If it wasn't merged with any existing config, add it to the end
1220         if (newConfig) {
1221             newConfig->setId(static_cast<hwc2_config_t>(mConfigs.size()));
1222             ALOGV("Found new config %u: %s", newConfig->getId(),
1223                     newConfig->toString().c_str());
1224             mConfigs.emplace_back(std::move(newConfig));
1225         }
1226     }
1227 
1228     initializeActiveConfig();
1229     populateColorModes();
1230 }
1231 
populateConfigs(uint32_t width,uint32_t height)1232 void HWC2On1Adapter::Display::populateConfigs(uint32_t width, uint32_t height)
1233 {
1234     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1235 
1236     mConfigs.emplace_back(std::make_shared<Config>(*this));
1237     auto& config = mConfigs[0];
1238 
1239     config->setAttribute(Attribute::Width, static_cast<int32_t>(width));
1240     config->setAttribute(Attribute::Height, static_cast<int32_t>(height));
1241     config->setHwc1Id(0);
1242     config->setId(0);
1243     mActiveConfig = config;
1244 }
1245 
prepare()1246 bool HWC2On1Adapter::Display::prepare()
1247 {
1248     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1249 
1250     // Only prepare display contents for displays HWC1 knows about
1251     if (mHwc1Id == -1) {
1252         return true;
1253     }
1254 
1255     // It doesn't make sense to prepare a display for which there is no active
1256     // config, so return early
1257     if (!mActiveConfig) {
1258         ALOGE("[%" PRIu64 "] Attempted to prepare, but no config active", mId);
1259         return false;
1260     }
1261 
1262     ALOGV("[%" PRIu64 "] Entering prepare", mId);
1263 
1264     auto currentCount = mHwc1RequestedContents ?
1265             mHwc1RequestedContents->numHwLayers : 0;
1266     auto requiredCount = mLayers.size() + 1;
1267     ALOGV("[%" PRIu64 "]   Requires %zd layers, %zd allocated in %p", mId,
1268             requiredCount, currentCount, mHwc1RequestedContents.get());
1269 
1270     bool layerCountChanged = (currentCount != requiredCount);
1271     if (layerCountChanged) {
1272         reallocateHwc1Contents();
1273     }
1274 
1275     bool applyAllState = false;
1276     if (layerCountChanged || mZIsDirty) {
1277         assignHwc1LayerIds();
1278         mZIsDirty = false;
1279         applyAllState = true;
1280     }
1281 
1282     mHwc1RequestedContents->retireFenceFd = -1;
1283     mHwc1RequestedContents->flags = 0;
1284     if (isDirty() || applyAllState) {
1285         mHwc1RequestedContents->flags |= HWC_GEOMETRY_CHANGED;
1286     }
1287 
1288     for (auto& layer : mLayers) {
1289         auto& hwc1Layer = mHwc1RequestedContents->hwLayers[layer->getHwc1Id()];
1290         hwc1Layer.releaseFenceFd = -1;
1291         layer->applyState(hwc1Layer, applyAllState);
1292     }
1293 
1294     mHwc1RequestedContents->outbuf = mOutputBuffer.getBuffer();
1295     mHwc1RequestedContents->outbufAcquireFenceFd = mOutputBuffer.getFence();
1296 
1297     prepareFramebufferTarget();
1298 
1299     return true;
1300 }
1301 
cloneHWCRegion(hwc_region_t & region)1302 static void cloneHWCRegion(hwc_region_t& region)
1303 {
1304     auto size = sizeof(hwc_rect_t) * region.numRects;
1305     auto newRects = static_cast<hwc_rect_t*>(std::malloc(size));
1306     std::copy_n(region.rects, region.numRects, newRects);
1307     region.rects = newRects;
1308 }
1309 
1310 HWC2On1Adapter::Display::HWC1Contents
cloneRequestedContents() const1311         HWC2On1Adapter::Display::cloneRequestedContents() const
1312 {
1313     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1314 
1315     size_t size = sizeof(hwc_display_contents_1_t) +
1316             sizeof(hwc_layer_1_t) * (mHwc1RequestedContents->numHwLayers);
1317     auto contents = static_cast<hwc_display_contents_1_t*>(std::malloc(size));
1318     std::memcpy(contents, mHwc1RequestedContents.get(), size);
1319     for (size_t layerId = 0; layerId < contents->numHwLayers; ++layerId) {
1320         auto& layer = contents->hwLayers[layerId];
1321         // Deep copy the regions to avoid double-frees
1322         cloneHWCRegion(layer.visibleRegionScreen);
1323         cloneHWCRegion(layer.surfaceDamage);
1324     }
1325     return HWC1Contents(contents);
1326 }
1327 
setReceivedContents(HWC1Contents contents)1328 void HWC2On1Adapter::Display::setReceivedContents(HWC1Contents contents)
1329 {
1330     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1331 
1332     mHwc1ReceivedContents = std::move(contents);
1333 
1334     mChanges.reset(new Changes);
1335 
1336     size_t numLayers = mHwc1ReceivedContents->numHwLayers;
1337     for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1338         const auto& receivedLayer = mHwc1ReceivedContents->hwLayers[hwc1Id];
1339         if (mHwc1LayerMap.count(hwc1Id) == 0) {
1340             ALOGE_IF(receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET,
1341                     "setReceivedContents: HWC1 layer %zd doesn't have a"
1342                     " matching HWC2 layer, and isn't the framebuffer target",
1343                     hwc1Id);
1344             continue;
1345         }
1346 
1347         Layer& layer = *mHwc1LayerMap[hwc1Id];
1348         updateTypeChanges(receivedLayer, layer);
1349         updateLayerRequests(receivedLayer, layer);
1350     }
1351 }
1352 
hasChanges() const1353 bool HWC2On1Adapter::Display::hasChanges() const
1354 {
1355     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1356     return mChanges != nullptr;
1357 }
1358 
set(hwc_display_contents_1 & hwcContents)1359 Error HWC2On1Adapter::Display::set(hwc_display_contents_1& hwcContents)
1360 {
1361     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1362 
1363     if (!mChanges || (mChanges->getNumTypes() > 0)) {
1364         ALOGE("[%" PRIu64 "] set failed: not validated", mId);
1365         return Error::NotValidated;
1366     }
1367 
1368     // Set up the client/framebuffer target
1369     auto numLayers = hwcContents.numHwLayers;
1370 
1371     // Close acquire fences on FRAMEBUFFER layers, since they will not be used
1372     // by HWC
1373     for (size_t l = 0; l < numLayers - 1; ++l) {
1374         auto& layer = hwcContents.hwLayers[l];
1375         if (layer.compositionType == HWC_FRAMEBUFFER) {
1376             ALOGV("Closing fence %d for layer %zd", layer.acquireFenceFd, l);
1377             close(layer.acquireFenceFd);
1378             layer.acquireFenceFd = -1;
1379         }
1380     }
1381 
1382     auto& clientTargetLayer = hwcContents.hwLayers[numLayers - 1];
1383     if (clientTargetLayer.compositionType == HWC_FRAMEBUFFER_TARGET) {
1384         clientTargetLayer.handle = mClientTarget.getBuffer();
1385         clientTargetLayer.acquireFenceFd = mClientTarget.getFence();
1386     } else {
1387         ALOGE("[%" PRIu64 "] set: last HWC layer wasn't FRAMEBUFFER_TARGET",
1388                 mId);
1389     }
1390 
1391     mChanges.reset();
1392 
1393     return Error::None;
1394 }
1395 
addRetireFence(int fenceFd)1396 void HWC2On1Adapter::Display::addRetireFence(int fenceFd)
1397 {
1398     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1399     mRetireFence.add(fenceFd);
1400 }
1401 
addReleaseFences(const hwc_display_contents_1_t & hwcContents)1402 void HWC2On1Adapter::Display::addReleaseFences(
1403         const hwc_display_contents_1_t& hwcContents)
1404 {
1405     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1406 
1407     size_t numLayers = hwcContents.numHwLayers;
1408     for (size_t hwc1Id = 0; hwc1Id < numLayers; ++hwc1Id) {
1409         const auto& receivedLayer = hwcContents.hwLayers[hwc1Id];
1410         if (mHwc1LayerMap.count(hwc1Id) == 0) {
1411             if (receivedLayer.compositionType != HWC_FRAMEBUFFER_TARGET) {
1412                 ALOGE("addReleaseFences: HWC1 layer %zd doesn't have a"
1413                         " matching HWC2 layer, and isn't the framebuffer"
1414                         " target", hwc1Id);
1415             }
1416             // Close the framebuffer target release fence since we will use the
1417             // display retire fence instead
1418             if (receivedLayer.releaseFenceFd != -1) {
1419                 close(receivedLayer.releaseFenceFd);
1420             }
1421             continue;
1422         }
1423 
1424         Layer& layer = *mHwc1LayerMap[hwc1Id];
1425         ALOGV("Adding release fence %d to layer %" PRIu64,
1426                 receivedLayer.releaseFenceFd, layer.getId());
1427         layer.addReleaseFence(receivedLayer.releaseFenceFd);
1428     }
1429 }
1430 
hasColorTransform() const1431 bool HWC2On1Adapter::Display::hasColorTransform() const
1432 {
1433     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1434     return mHasColorTransform;
1435 }
1436 
hwc1CompositionString(int32_t type)1437 static std::string hwc1CompositionString(int32_t type)
1438 {
1439     switch (type) {
1440         case HWC_FRAMEBUFFER: return "Framebuffer";
1441         case HWC_OVERLAY: return "Overlay";
1442         case HWC_BACKGROUND: return "Background";
1443         case HWC_FRAMEBUFFER_TARGET: return "FramebufferTarget";
1444         case HWC_SIDEBAND: return "Sideband";
1445         case HWC_CURSOR_OVERLAY: return "CursorOverlay";
1446         default:
1447             return std::string("Unknown (") + std::to_string(type) + ")";
1448     }
1449 }
1450 
hwc1TransformString(int32_t transform)1451 static std::string hwc1TransformString(int32_t transform)
1452 {
1453     switch (transform) {
1454         case 0: return "None";
1455         case HWC_TRANSFORM_FLIP_H: return "FlipH";
1456         case HWC_TRANSFORM_FLIP_V: return "FlipV";
1457         case HWC_TRANSFORM_ROT_90: return "Rotate90";
1458         case HWC_TRANSFORM_ROT_180: return "Rotate180";
1459         case HWC_TRANSFORM_ROT_270: return "Rotate270";
1460         case HWC_TRANSFORM_FLIP_H_ROT_90: return "FlipHRotate90";
1461         case HWC_TRANSFORM_FLIP_V_ROT_90: return "FlipVRotate90";
1462         default:
1463             return std::string("Unknown (") + std::to_string(transform) + ")";
1464     }
1465 }
1466 
hwc1BlendModeString(int32_t mode)1467 static std::string hwc1BlendModeString(int32_t mode)
1468 {
1469     switch (mode) {
1470         case HWC_BLENDING_NONE: return "None";
1471         case HWC_BLENDING_PREMULT: return "Premultiplied";
1472         case HWC_BLENDING_COVERAGE: return "Coverage";
1473         default:
1474             return std::string("Unknown (") + std::to_string(mode) + ")";
1475     }
1476 }
1477 
rectString(hwc_rect_t rect)1478 static std::string rectString(hwc_rect_t rect)
1479 {
1480     std::stringstream output;
1481     output << "[" << rect.left << ", " << rect.top << ", ";
1482     output << rect.right << ", " << rect.bottom << "]";
1483     return output.str();
1484 }
1485 
approximateFloatString(float f)1486 static std::string approximateFloatString(float f)
1487 {
1488     if (static_cast<int32_t>(f) == f) {
1489         return std::to_string(static_cast<int32_t>(f));
1490     }
1491     int32_t truncated = static_cast<int32_t>(f * 10);
1492     bool approximate = (static_cast<float>(truncated) != f * 10);
1493     const size_t BUFFER_SIZE = 32;
1494     char buffer[BUFFER_SIZE] = {};
1495     auto bytesWritten = snprintf(buffer, BUFFER_SIZE,
1496             "%s%.1f", approximate ? "~" : "", f);
1497     return std::string(buffer, bytesWritten);
1498 }
1499 
frectString(hwc_frect_t frect)1500 static std::string frectString(hwc_frect_t frect)
1501 {
1502     std::stringstream output;
1503     output << "[" << approximateFloatString(frect.left) << ", ";
1504     output << approximateFloatString(frect.top) << ", ";
1505     output << approximateFloatString(frect.right) << ", ";
1506     output << approximateFloatString(frect.bottom) << "]";
1507     return output.str();
1508 }
1509 
colorString(hwc_color_t color)1510 static std::string colorString(hwc_color_t color)
1511 {
1512     std::stringstream output;
1513     output << "RGBA [";
1514     output << static_cast<int32_t>(color.r) << ", ";
1515     output << static_cast<int32_t>(color.g) << ", ";
1516     output << static_cast<int32_t>(color.b) << ", ";
1517     output << static_cast<int32_t>(color.a) << "]";
1518     return output.str();
1519 }
1520 
alphaString(float f)1521 static std::string alphaString(float f)
1522 {
1523     const size_t BUFFER_SIZE = 8;
1524     char buffer[BUFFER_SIZE] = {};
1525     auto bytesWritten = snprintf(buffer, BUFFER_SIZE, "%.3f", f);
1526     return std::string(buffer, bytesWritten);
1527 }
1528 
to_string(const hwc_layer_1_t & hwcLayer,int32_t hwc1MinorVersion)1529 static std::string to_string(const hwc_layer_1_t& hwcLayer,
1530         int32_t hwc1MinorVersion)
1531 {
1532     const char* fill = "          ";
1533 
1534     std::stringstream output;
1535 
1536     output << "  Composition: " <<
1537             hwc1CompositionString(hwcLayer.compositionType);
1538 
1539     if (hwcLayer.compositionType == HWC_BACKGROUND) {
1540         output << "  Color: " << colorString(hwcLayer.backgroundColor) << '\n';
1541     } else if (hwcLayer.compositionType == HWC_SIDEBAND) {
1542         output << "  Stream: " << hwcLayer.sidebandStream << '\n';
1543     } else {
1544         output << "  Buffer: " << hwcLayer.handle << "/" <<
1545                 hwcLayer.acquireFenceFd << '\n';
1546     }
1547 
1548     output << fill << "Display frame: " << rectString(hwcLayer.displayFrame) <<
1549             '\n';
1550 
1551     output << fill << "Source crop: ";
1552     if (hwc1MinorVersion >= 3) {
1553         output << frectString(hwcLayer.sourceCropf) << '\n';
1554     } else {
1555         output << rectString(hwcLayer.sourceCropi) << '\n';
1556     }
1557 
1558     output << fill << "Transform: " << hwc1TransformString(hwcLayer.transform);
1559     output << "  Blend mode: " << hwc1BlendModeString(hwcLayer.blending);
1560     if (hwcLayer.planeAlpha != 0xFF) {
1561         output << "  Alpha: " << alphaString(hwcLayer.planeAlpha / 255.0f);
1562     }
1563     output << '\n';
1564 
1565     if (hwcLayer.hints != 0) {
1566         output << fill << "Hints:";
1567         if ((hwcLayer.hints & HWC_HINT_TRIPLE_BUFFER) != 0) {
1568             output << " TripleBuffer";
1569         }
1570         if ((hwcLayer.hints & HWC_HINT_CLEAR_FB) != 0) {
1571             output << " ClearFB";
1572         }
1573         output << '\n';
1574     }
1575 
1576     if (hwcLayer.flags != 0) {
1577         output << fill << "Flags:";
1578         if ((hwcLayer.flags & HWC_SKIP_LAYER) != 0) {
1579             output << " SkipLayer";
1580         }
1581         if ((hwcLayer.flags & HWC_IS_CURSOR_LAYER) != 0) {
1582             output << " IsCursorLayer";
1583         }
1584         output << '\n';
1585     }
1586 
1587     return output.str();
1588 }
1589 
to_string(const hwc_display_contents_1_t & hwcContents,int32_t hwc1MinorVersion)1590 static std::string to_string(const hwc_display_contents_1_t& hwcContents,
1591         int32_t hwc1MinorVersion)
1592 {
1593     const char* fill = "      ";
1594 
1595     std::stringstream output;
1596     output << fill << "Geometry changed: " <<
1597             ((hwcContents.flags & HWC_GEOMETRY_CHANGED) != 0 ? "Y\n" : "N\n");
1598 
1599     output << fill << hwcContents.numHwLayers << " Layer" <<
1600             ((hwcContents.numHwLayers == 1) ? "\n" : "s\n");
1601     for (size_t layer = 0; layer < hwcContents.numHwLayers; ++layer) {
1602         output << fill << "  Layer " << layer;
1603         output << to_string(hwcContents.hwLayers[layer], hwc1MinorVersion);
1604     }
1605 
1606     if (hwcContents.outbuf != nullptr) {
1607         output << fill << "Output buffer: " << hwcContents.outbuf << "/" <<
1608                 hwcContents.outbufAcquireFenceFd << '\n';
1609     }
1610 
1611     return output.str();
1612 }
1613 
dump() const1614 std::string HWC2On1Adapter::Display::dump() const
1615 {
1616     std::unique_lock<std::recursive_mutex> lock(mStateMutex);
1617 
1618     std::stringstream output;
1619 
1620     output << "  Display " << mId << ": ";
1621     output << to_string(mType) << "  ";
1622     output << "HWC1 ID: " << mHwc1Id << "  ";
1623     output << "Power mode: " << to_string(mPowerMode) << "  ";
1624     output << "Vsync: " << to_string(mVsyncEnabled) << '\n';
1625 
1626     output << "    Color modes [active]:";
1627     for (const auto& mode : mColorModes) {
1628         if (mode == mActiveColorMode) {
1629             output << " [" << mode << ']';
1630         } else {
1631             output << " " << mode;
1632         }
1633     }
1634     output << '\n';
1635 
1636     output << "    " << mConfigs.size() << " Config" <<
1637             (mConfigs.size() == 1 ? "" : "s") << " (* active)\n";
1638     for (const auto& config : mConfigs) {
1639         output << (config == mActiveConfig ? "    * " : "      ");
1640         output << config->toString(true) << '\n';
1641     }
1642 
1643     output << "    " << mLayers.size() << " Layer" <<
1644             (mLayers.size() == 1 ? "" : "s") << '\n';
1645     for (const auto& layer : mLayers) {
1646         output << layer->dump();
1647     }
1648 
1649     output << "    Client target: " << mClientTarget.getBuffer() << '\n';
1650 
1651     if (mOutputBuffer.getBuffer() != nullptr) {
1652         output << "    Output buffer: " << mOutputBuffer.getBuffer() << '\n';
1653     }
1654 
1655     if (mHwc1ReceivedContents) {
1656         output << "    Last received HWC1 state\n";
1657         output << to_string(*mHwc1ReceivedContents, mDevice.mHwc1MinorVersion);
1658     } else if (mHwc1RequestedContents) {
1659         output << "    Last requested HWC1 state\n";
1660         output << to_string(*mHwc1RequestedContents, mDevice.mHwc1MinorVersion);
1661     }
1662 
1663     return output.str();
1664 }
1665 
setAttribute(HWC2::Attribute attribute,int32_t value)1666 void HWC2On1Adapter::Display::Config::setAttribute(HWC2::Attribute attribute,
1667         int32_t value)
1668 {
1669     mAttributes[attribute] = value;
1670 }
1671 
getAttribute(Attribute attribute) const1672 int32_t HWC2On1Adapter::Display::Config::getAttribute(Attribute attribute) const
1673 {
1674     if (mAttributes.count(attribute) == 0) {
1675         return -1;
1676     }
1677     return mAttributes.at(attribute);
1678 }
1679 
setHwc1Id(uint32_t id)1680 void HWC2On1Adapter::Display::Config::setHwc1Id(uint32_t id)
1681 {
1682     android_color_mode_t colorMode = static_cast<android_color_mode_t>(getAttribute(ColorMode));
1683     mHwc1Ids.emplace(colorMode, id);
1684 }
1685 
hasHwc1Id(uint32_t id) const1686 bool HWC2On1Adapter::Display::Config::hasHwc1Id(uint32_t id) const
1687 {
1688     for (const auto& idPair : mHwc1Ids) {
1689         if (id == idPair.second) {
1690             return true;
1691         }
1692     }
1693     return false;
1694 }
1695 
getColorModeForHwc1Id(uint32_t id,android_color_mode_t * outMode) const1696 Error HWC2On1Adapter::Display::Config::getColorModeForHwc1Id(
1697         uint32_t id, android_color_mode_t* outMode) const
1698 {
1699     for (const auto& idPair : mHwc1Ids) {
1700         if (id == idPair.second) {
1701             *outMode = idPair.first;
1702             return Error::None;
1703         }
1704     }
1705     ALOGE("Unable to find color mode for HWC ID %" PRIu32 " on config %u", id, mId);
1706     return Error::BadParameter;
1707 }
1708 
getHwc1IdForColorMode(android_color_mode_t mode,uint32_t * outId) const1709 Error HWC2On1Adapter::Display::Config::getHwc1IdForColorMode(android_color_mode_t mode,
1710         uint32_t* outId) const
1711 {
1712     for (const auto& idPair : mHwc1Ids) {
1713         if (mode == idPair.first) {
1714             *outId = idPair.second;
1715             return Error::None;
1716         }
1717     }
1718     ALOGE("Unable to find HWC1 ID for color mode %d on config %u", mode, mId);
1719     return Error::BadParameter;
1720 }
1721 
merge(const Config & other)1722 bool HWC2On1Adapter::Display::Config::merge(const Config& other)
1723 {
1724     auto attributes = {HWC2::Attribute::Width, HWC2::Attribute::Height,
1725             HWC2::Attribute::VsyncPeriod, HWC2::Attribute::DpiX,
1726             HWC2::Attribute::DpiY};
1727     for (auto attribute : attributes) {
1728         if (getAttribute(attribute) != other.getAttribute(attribute)) {
1729             return false;
1730         }
1731     }
1732     android_color_mode_t otherColorMode =
1733             static_cast<android_color_mode_t>(other.getAttribute(ColorMode));
1734     if (mHwc1Ids.count(otherColorMode) != 0) {
1735         ALOGE("Attempted to merge two configs (%u and %u) which appear to be "
1736                 "identical", mHwc1Ids.at(otherColorMode),
1737                 other.mHwc1Ids.at(otherColorMode));
1738         return false;
1739     }
1740     mHwc1Ids.emplace(otherColorMode,
1741             other.mHwc1Ids.at(otherColorMode));
1742     return true;
1743 }
1744 
getColorModes() const1745 std::set<android_color_mode_t> HWC2On1Adapter::Display::Config::getColorModes() const
1746 {
1747     std::set<android_color_mode_t> colorModes;
1748     for (const auto& idPair : mHwc1Ids) {
1749         colorModes.emplace(idPair.first);
1750     }
1751     return colorModes;
1752 }
1753 
toString(bool splitLine) const1754 std::string HWC2On1Adapter::Display::Config::toString(bool splitLine) const
1755 {
1756     std::string output;
1757 
1758     const size_t BUFFER_SIZE = 100;
1759     char buffer[BUFFER_SIZE] = {};
1760     auto writtenBytes = snprintf(buffer, BUFFER_SIZE,
1761             "%u x %u", mAttributes.at(HWC2::Attribute::Width),
1762             mAttributes.at(HWC2::Attribute::Height));
1763     output.append(buffer, writtenBytes);
1764 
1765     if (mAttributes.count(HWC2::Attribute::VsyncPeriod) != 0) {
1766         std::memset(buffer, 0, BUFFER_SIZE);
1767         writtenBytes = snprintf(buffer, BUFFER_SIZE, " @ %.1f Hz",
1768                 1e9 / mAttributes.at(HWC2::Attribute::VsyncPeriod));
1769         output.append(buffer, writtenBytes);
1770     }
1771 
1772     if (mAttributes.count(HWC2::Attribute::DpiX) != 0 &&
1773             mAttributes.at(HWC2::Attribute::DpiX) != -1) {
1774         std::memset(buffer, 0, BUFFER_SIZE);
1775         writtenBytes = snprintf(buffer, BUFFER_SIZE,
1776                 ", DPI: %.1f x %.1f",
1777                 mAttributes.at(HWC2::Attribute::DpiX) / 1000.0f,
1778                 mAttributes.at(HWC2::Attribute::DpiY) / 1000.0f);
1779         output.append(buffer, writtenBytes);
1780     }
1781 
1782     std::memset(buffer, 0, BUFFER_SIZE);
1783     if (splitLine) {
1784         writtenBytes = snprintf(buffer, BUFFER_SIZE,
1785                 "\n        HWC1 ID/Color transform:");
1786     } else {
1787         writtenBytes = snprintf(buffer, BUFFER_SIZE,
1788                 ", HWC1 ID/Color transform:");
1789     }
1790     output.append(buffer, writtenBytes);
1791 
1792 
1793     for (const auto& id : mHwc1Ids) {
1794         android_color_mode_t colorMode = id.first;
1795         uint32_t hwc1Id = id.second;
1796         std::memset(buffer, 0, BUFFER_SIZE);
1797         if (colorMode == mDisplay.mActiveColorMode) {
1798             writtenBytes = snprintf(buffer, BUFFER_SIZE, " [%u/%d]", hwc1Id,
1799                     colorMode);
1800         } else {
1801             writtenBytes = snprintf(buffer, BUFFER_SIZE, " %u/%d", hwc1Id,
1802                     colorMode);
1803         }
1804         output.append(buffer, writtenBytes);
1805     }
1806 
1807     return output;
1808 }
1809 
1810 std::shared_ptr<const HWC2On1Adapter::Display::Config>
getConfig(hwc2_config_t configId) const1811         HWC2On1Adapter::Display::getConfig(hwc2_config_t configId) const
1812 {
1813     if (configId > mConfigs.size() || !mConfigs[configId]->isOnDisplay(*this)) {
1814         return nullptr;
1815     }
1816     return mConfigs[configId];
1817 }
1818 
populateColorModes()1819 void HWC2On1Adapter::Display::populateColorModes()
1820 {
1821     mColorModes = mConfigs[0]->getColorModes();
1822     for (const auto& config : mConfigs) {
1823         std::set<android_color_mode_t> intersection;
1824         auto configModes = config->getColorModes();
1825         std::set_intersection(mColorModes.cbegin(), mColorModes.cend(),
1826                 configModes.cbegin(), configModes.cend(),
1827                 std::inserter(intersection, intersection.begin()));
1828         std::swap(intersection, mColorModes);
1829     }
1830 }
1831 
initializeActiveConfig()1832 void HWC2On1Adapter::Display::initializeActiveConfig()
1833 {
1834     if (mDevice.mHwc1Device->getActiveConfig == nullptr) {
1835         ALOGV("getActiveConfig is null, choosing config 0");
1836         mActiveConfig = mConfigs[0];
1837         mActiveColorMode = HAL_COLOR_MODE_NATIVE;
1838         return;
1839     }
1840 
1841     auto activeConfig = mDevice.mHwc1Device->getActiveConfig(
1842             mDevice.mHwc1Device, mHwc1Id);
1843     if (activeConfig >= 0) {
1844         for (const auto& config : mConfigs) {
1845             if (config->hasHwc1Id(activeConfig)) {
1846                 ALOGV("Setting active config to %d for HWC1 config %u",
1847                         config->getId(), activeConfig);
1848                 mActiveConfig = config;
1849                 if (config->getColorModeForHwc1Id(activeConfig, &mActiveColorMode) != Error::None) {
1850                     // This should never happen since we checked for the config's presence before
1851                     // setting it as active.
1852                     ALOGE("Unable to find color mode for active HWC1 config %d",
1853                             config->getId());
1854                     mActiveColorMode = HAL_COLOR_MODE_NATIVE;
1855                 }
1856                 break;
1857             }
1858         }
1859         if (!mActiveConfig) {
1860             ALOGV("Unable to find active HWC1 config %u, defaulting to "
1861                     "config 0", activeConfig);
1862             mActiveConfig = mConfigs[0];
1863             mActiveColorMode = HAL_COLOR_MODE_NATIVE;
1864         }
1865     }
1866 }
1867 
reallocateHwc1Contents()1868 void HWC2On1Adapter::Display::reallocateHwc1Contents()
1869 {
1870     // Allocate an additional layer for the framebuffer target
1871     auto numLayers = mLayers.size() + 1;
1872     size_t size = sizeof(hwc_display_contents_1_t) +
1873             sizeof(hwc_layer_1_t) * numLayers;
1874     ALOGV("[%" PRIu64 "] reallocateHwc1Contents creating %zd layer%s", mId,
1875             numLayers, numLayers != 1 ? "s" : "");
1876     auto contents =
1877             static_cast<hwc_display_contents_1_t*>(std::calloc(size, 1));
1878     contents->numHwLayers = numLayers;
1879     mHwc1RequestedContents.reset(contents);
1880 }
1881 
assignHwc1LayerIds()1882 void HWC2On1Adapter::Display::assignHwc1LayerIds()
1883 {
1884     mHwc1LayerMap.clear();
1885     size_t nextHwc1Id = 0;
1886     for (auto& layer : mLayers) {
1887         mHwc1LayerMap[nextHwc1Id] = layer;
1888         layer->setHwc1Id(nextHwc1Id++);
1889     }
1890 }
1891 
updateTypeChanges(const hwc_layer_1_t & hwc1Layer,const Layer & layer)1892 void HWC2On1Adapter::Display::updateTypeChanges(const hwc_layer_1_t& hwc1Layer,
1893         const Layer& layer)
1894 {
1895     auto layerId = layer.getId();
1896     switch (hwc1Layer.compositionType) {
1897         case HWC_FRAMEBUFFER:
1898             if (layer.getCompositionType() != Composition::Client) {
1899                 mChanges->addTypeChange(layerId, Composition::Client);
1900             }
1901             break;
1902         case HWC_OVERLAY:
1903             if (layer.getCompositionType() != Composition::Device) {
1904                 mChanges->addTypeChange(layerId, Composition::Device);
1905             }
1906             break;
1907         case HWC_BACKGROUND:
1908             ALOGE_IF(layer.getCompositionType() != Composition::SolidColor,
1909                     "updateTypeChanges: HWC1 requested BACKGROUND, but HWC2"
1910                     " wasn't expecting SolidColor");
1911             break;
1912         case HWC_FRAMEBUFFER_TARGET:
1913             // Do nothing, since it shouldn't be modified by HWC1
1914             break;
1915         case HWC_SIDEBAND:
1916             ALOGE_IF(layer.getCompositionType() != Composition::Sideband,
1917                     "updateTypeChanges: HWC1 requested SIDEBAND, but HWC2"
1918                     " wasn't expecting Sideband");
1919             break;
1920         case HWC_CURSOR_OVERLAY:
1921             ALOGE_IF(layer.getCompositionType() != Composition::Cursor,
1922                     "updateTypeChanges: HWC1 requested CURSOR_OVERLAY, but"
1923                     " HWC2 wasn't expecting Cursor");
1924             break;
1925     }
1926 }
1927 
updateLayerRequests(const hwc_layer_1_t & hwc1Layer,const Layer & layer)1928 void HWC2On1Adapter::Display::updateLayerRequests(
1929         const hwc_layer_1_t& hwc1Layer, const Layer& layer)
1930 {
1931     if ((hwc1Layer.hints & HWC_HINT_CLEAR_FB) != 0) {
1932         mChanges->addLayerRequest(layer.getId(),
1933                 LayerRequest::ClearClientTarget);
1934     }
1935 }
1936 
prepareFramebufferTarget()1937 void HWC2On1Adapter::Display::prepareFramebufferTarget()
1938 {
1939     // We check that mActiveConfig is valid in Display::prepare
1940     int32_t width = mActiveConfig->getAttribute(Attribute::Width);
1941     int32_t height = mActiveConfig->getAttribute(Attribute::Height);
1942 
1943     auto& hwc1Target = mHwc1RequestedContents->hwLayers[mLayers.size()];
1944     hwc1Target.compositionType = HWC_FRAMEBUFFER_TARGET;
1945     hwc1Target.releaseFenceFd = -1;
1946     hwc1Target.hints = 0;
1947     hwc1Target.flags = 0;
1948     hwc1Target.transform = 0;
1949     hwc1Target.blending = HWC_BLENDING_PREMULT;
1950     if (mDevice.getHwc1MinorVersion() < 3) {
1951         hwc1Target.sourceCropi = {0, 0, width, height};
1952     } else {
1953         hwc1Target.sourceCropf = {0.0f, 0.0f, static_cast<float>(width),
1954                 static_cast<float>(height)};
1955     }
1956     hwc1Target.displayFrame = {0, 0, width, height};
1957     hwc1Target.planeAlpha = 255;
1958     hwc1Target.visibleRegionScreen.numRects = 1;
1959     auto rects = static_cast<hwc_rect_t*>(std::malloc(sizeof(hwc_rect_t)));
1960     rects[0].left = 0;
1961     rects[0].top = 0;
1962     rects[0].right = width;
1963     rects[0].bottom = height;
1964     hwc1Target.visibleRegionScreen.rects = rects;
1965 
1966     // We will set this to the correct value in set
1967     hwc1Target.acquireFenceFd = -1;
1968 }
1969 
1970 // Layer functions
1971 
1972 std::atomic<hwc2_layer_t> HWC2On1Adapter::Layer::sNextId(1);
1973 
Layer(Display & display)1974 HWC2On1Adapter::Layer::Layer(Display& display)
1975   : mId(sNextId++),
1976     mDisplay(display),
1977     mDirtyCount(0),
1978     mBuffer(),
1979     mSurfaceDamage(),
1980     mBlendMode(*this, BlendMode::None),
1981     mColor(*this, {0, 0, 0, 0}),
1982     mCompositionType(*this, Composition::Invalid),
1983     mDisplayFrame(*this, {0, 0, -1, -1}),
1984     mPlaneAlpha(*this, 0.0f),
1985     mSidebandStream(*this, nullptr),
1986     mSourceCrop(*this, {0.0f, 0.0f, -1.0f, -1.0f}),
1987     mTransform(*this, Transform::None),
1988     mVisibleRegion(*this, std::vector<hwc_rect_t>()),
1989     mZ(0),
1990     mReleaseFence(),
1991     mHwc1Id(0),
1992     mHasUnsupportedDataspace(false),
1993     mHasUnsupportedPlaneAlpha(false) {}
1994 
operator ()(const std::shared_ptr<Layer> & lhs,const std::shared_ptr<Layer> & rhs)1995 bool HWC2On1Adapter::SortLayersByZ::operator()(
1996         const std::shared_ptr<Layer>& lhs, const std::shared_ptr<Layer>& rhs)
1997 {
1998     return lhs->getZ() < rhs->getZ();
1999 }
2000 
setBuffer(buffer_handle_t buffer,int32_t acquireFence)2001 Error HWC2On1Adapter::Layer::setBuffer(buffer_handle_t buffer,
2002         int32_t acquireFence)
2003 {
2004     ALOGV("Setting acquireFence to %d for layer %" PRIu64, acquireFence, mId);
2005     mBuffer.setBuffer(buffer);
2006     mBuffer.setFence(acquireFence);
2007     return Error::None;
2008 }
2009 
setCursorPosition(int32_t x,int32_t y)2010 Error HWC2On1Adapter::Layer::setCursorPosition(int32_t x, int32_t y)
2011 {
2012     if (mCompositionType.getValue() != Composition::Cursor) {
2013         return Error::BadLayer;
2014     }
2015 
2016     if (mDisplay.hasChanges()) {
2017         return Error::NotValidated;
2018     }
2019 
2020     auto displayId = mDisplay.getHwc1Id();
2021     auto hwc1Device = mDisplay.getDevice().getHwc1Device();
2022     hwc1Device->setCursorPositionAsync(hwc1Device, displayId, x, y);
2023     return Error::None;
2024 }
2025 
setSurfaceDamage(hwc_region_t damage)2026 Error HWC2On1Adapter::Layer::setSurfaceDamage(hwc_region_t damage)
2027 {
2028     mSurfaceDamage.resize(damage.numRects);
2029     std::copy_n(damage.rects, damage.numRects, mSurfaceDamage.begin());
2030     return Error::None;
2031 }
2032 
2033 // Layer state functions
2034 
setBlendMode(BlendMode mode)2035 Error HWC2On1Adapter::Layer::setBlendMode(BlendMode mode)
2036 {
2037     mBlendMode.setPending(mode);
2038     return Error::None;
2039 }
2040 
setColor(hwc_color_t color)2041 Error HWC2On1Adapter::Layer::setColor(hwc_color_t color)
2042 {
2043     mColor.setPending(color);
2044     return Error::None;
2045 }
2046 
setCompositionType(Composition type)2047 Error HWC2On1Adapter::Layer::setCompositionType(Composition type)
2048 {
2049     mCompositionType.setPending(type);
2050     return Error::None;
2051 }
2052 
setDataspace(android_dataspace_t dataspace)2053 Error HWC2On1Adapter::Layer::setDataspace(android_dataspace_t dataspace)
2054 {
2055     mHasUnsupportedDataspace = (dataspace != HAL_DATASPACE_UNKNOWN);
2056     return Error::None;
2057 }
2058 
setDisplayFrame(hwc_rect_t frame)2059 Error HWC2On1Adapter::Layer::setDisplayFrame(hwc_rect_t frame)
2060 {
2061     mDisplayFrame.setPending(frame);
2062     return Error::None;
2063 }
2064 
setPlaneAlpha(float alpha)2065 Error HWC2On1Adapter::Layer::setPlaneAlpha(float alpha)
2066 {
2067     mPlaneAlpha.setPending(alpha);
2068     return Error::None;
2069 }
2070 
setSidebandStream(const native_handle_t * stream)2071 Error HWC2On1Adapter::Layer::setSidebandStream(const native_handle_t* stream)
2072 {
2073     mSidebandStream.setPending(stream);
2074     return Error::None;
2075 }
2076 
setSourceCrop(hwc_frect_t crop)2077 Error HWC2On1Adapter::Layer::setSourceCrop(hwc_frect_t crop)
2078 {
2079     mSourceCrop.setPending(crop);
2080     return Error::None;
2081 }
2082 
setTransform(Transform transform)2083 Error HWC2On1Adapter::Layer::setTransform(Transform transform)
2084 {
2085     mTransform.setPending(transform);
2086     return Error::None;
2087 }
2088 
setVisibleRegion(hwc_region_t rawVisible)2089 Error HWC2On1Adapter::Layer::setVisibleRegion(hwc_region_t rawVisible)
2090 {
2091     std::vector<hwc_rect_t> visible(rawVisible.rects,
2092             rawVisible.rects + rawVisible.numRects);
2093     mVisibleRegion.setPending(std::move(visible));
2094     return Error::None;
2095 }
2096 
setZ(uint32_t z)2097 Error HWC2On1Adapter::Layer::setZ(uint32_t z)
2098 {
2099     mZ = z;
2100     return Error::None;
2101 }
2102 
addReleaseFence(int fenceFd)2103 void HWC2On1Adapter::Layer::addReleaseFence(int fenceFd)
2104 {
2105     ALOGV("addReleaseFence %d to layer %" PRIu64, fenceFd, mId);
2106     mReleaseFence.add(fenceFd);
2107 }
2108 
getReleaseFence() const2109 const sp<Fence>& HWC2On1Adapter::Layer::getReleaseFence() const
2110 {
2111     return mReleaseFence.get();
2112 }
2113 
applyState(hwc_layer_1_t & hwc1Layer,bool applyAllState)2114 void HWC2On1Adapter::Layer::applyState(hwc_layer_1_t& hwc1Layer,
2115         bool applyAllState)
2116 {
2117     applyCommonState(hwc1Layer, applyAllState);
2118     auto compositionType = mCompositionType.getPendingValue();
2119     if (compositionType == Composition::SolidColor) {
2120         applySolidColorState(hwc1Layer, applyAllState);
2121     } else if (compositionType == Composition::Sideband) {
2122         applySidebandState(hwc1Layer, applyAllState);
2123     } else {
2124         applyBufferState(hwc1Layer);
2125     }
2126     applyCompositionType(hwc1Layer, applyAllState);
2127 }
2128 
2129 // Layer dump helpers
2130 
regionStrings(const std::vector<hwc_rect_t> & visibleRegion,const std::vector<hwc_rect_t> & surfaceDamage)2131 static std::string regionStrings(const std::vector<hwc_rect_t>& visibleRegion,
2132         const std::vector<hwc_rect_t>& surfaceDamage)
2133 {
2134     std::string regions;
2135     regions += "        Visible Region";
2136     regions.resize(40, ' ');
2137     regions += "Surface Damage\n";
2138 
2139     size_t numPrinted = 0;
2140     size_t maxSize = std::max(visibleRegion.size(), surfaceDamage.size());
2141     while (numPrinted < maxSize) {
2142         std::string line("        ");
2143         if (visibleRegion.empty() && numPrinted == 0) {
2144             line += "None";
2145         } else if (numPrinted < visibleRegion.size()) {
2146             line += rectString(visibleRegion[numPrinted]);
2147         }
2148         line.resize(40, ' ');
2149         if (surfaceDamage.empty() && numPrinted == 0) {
2150             line += "None";
2151         } else if (numPrinted < surfaceDamage.size()) {
2152             line += rectString(surfaceDamage[numPrinted]);
2153         }
2154         line += '\n';
2155         regions += line;
2156         ++numPrinted;
2157     }
2158     return regions;
2159 }
2160 
dump() const2161 std::string HWC2On1Adapter::Layer::dump() const
2162 {
2163     std::stringstream output;
2164     const char* fill = "      ";
2165 
2166     output << fill << to_string(mCompositionType.getPendingValue());
2167     output << " Layer  HWC2/1: " << mId << "/" << mHwc1Id << "  ";
2168     output << "Z: " << mZ;
2169     if (mCompositionType.getValue() == HWC2::Composition::SolidColor) {
2170         output << "  " << colorString(mColor.getValue());
2171     } else if (mCompositionType.getValue() == HWC2::Composition::Sideband) {
2172         output << "  Handle: " << mSidebandStream.getValue() << '\n';
2173     } else {
2174         output << "  Buffer: " << mBuffer.getBuffer() << "/" <<
2175                 mBuffer.getFence() << '\n';
2176         output << fill << "  Display frame [LTRB]: " <<
2177                 rectString(mDisplayFrame.getValue()) << '\n';
2178         output << fill << "  Source crop: " <<
2179                 frectString(mSourceCrop.getValue()) << '\n';
2180         output << fill << "  Transform: " << to_string(mTransform.getValue());
2181         output << "  Blend mode: " << to_string(mBlendMode.getValue());
2182         if (mPlaneAlpha.getValue() != 1.0f) {
2183             output << "  Alpha: " <<
2184                 alphaString(mPlaneAlpha.getValue()) << '\n';
2185         } else {
2186             output << '\n';
2187         }
2188         output << regionStrings(mVisibleRegion.getValue(), mSurfaceDamage);
2189     }
2190     return output.str();
2191 }
2192 
getHwc1Blending(HWC2::BlendMode blendMode)2193 static int getHwc1Blending(HWC2::BlendMode blendMode)
2194 {
2195     switch (blendMode) {
2196         case BlendMode::Coverage: return HWC_BLENDING_COVERAGE;
2197         case BlendMode::Premultiplied: return HWC_BLENDING_PREMULT;
2198         default: return HWC_BLENDING_NONE;
2199     }
2200 }
2201 
applyCommonState(hwc_layer_1_t & hwc1Layer,bool applyAllState)2202 void HWC2On1Adapter::Layer::applyCommonState(hwc_layer_1_t& hwc1Layer,
2203         bool applyAllState)
2204 {
2205     auto minorVersion = mDisplay.getDevice().getHwc1MinorVersion();
2206     if (applyAllState || mBlendMode.isDirty()) {
2207         hwc1Layer.blending = getHwc1Blending(mBlendMode.getPendingValue());
2208         mBlendMode.latch();
2209     }
2210     if (applyAllState || mDisplayFrame.isDirty()) {
2211         hwc1Layer.displayFrame = mDisplayFrame.getPendingValue();
2212         mDisplayFrame.latch();
2213     }
2214     if (applyAllState || mPlaneAlpha.isDirty()) {
2215         auto pendingAlpha = mPlaneAlpha.getPendingValue();
2216         if (minorVersion < 2) {
2217             mHasUnsupportedPlaneAlpha = pendingAlpha < 1.0f;
2218         } else {
2219             hwc1Layer.planeAlpha =
2220                     static_cast<uint8_t>(255.0f * pendingAlpha + 0.5f);
2221         }
2222         mPlaneAlpha.latch();
2223     }
2224     if (applyAllState || mSourceCrop.isDirty()) {
2225         if (minorVersion < 3) {
2226             auto pending = mSourceCrop.getPendingValue();
2227             hwc1Layer.sourceCropi.left =
2228                     static_cast<int32_t>(std::ceil(pending.left));
2229             hwc1Layer.sourceCropi.top =
2230                     static_cast<int32_t>(std::ceil(pending.top));
2231             hwc1Layer.sourceCropi.right =
2232                     static_cast<int32_t>(std::floor(pending.right));
2233             hwc1Layer.sourceCropi.bottom =
2234                     static_cast<int32_t>(std::floor(pending.bottom));
2235         } else {
2236             hwc1Layer.sourceCropf = mSourceCrop.getPendingValue();
2237         }
2238         mSourceCrop.latch();
2239     }
2240     if (applyAllState || mTransform.isDirty()) {
2241         hwc1Layer.transform =
2242                 static_cast<uint32_t>(mTransform.getPendingValue());
2243         mTransform.latch();
2244     }
2245     if (applyAllState || mVisibleRegion.isDirty()) {
2246         auto& hwc1VisibleRegion = hwc1Layer.visibleRegionScreen;
2247 
2248         std::free(const_cast<hwc_rect_t*>(hwc1VisibleRegion.rects));
2249 
2250         auto pending = mVisibleRegion.getPendingValue();
2251         hwc_rect_t* newRects = static_cast<hwc_rect_t*>(
2252                 std::malloc(sizeof(hwc_rect_t) * pending.size()));
2253         std::copy(pending.begin(), pending.end(), newRects);
2254         hwc1VisibleRegion.rects = const_cast<const hwc_rect_t*>(newRects);
2255         hwc1VisibleRegion.numRects = pending.size();
2256         mVisibleRegion.latch();
2257     }
2258 }
2259 
applySolidColorState(hwc_layer_1_t & hwc1Layer,bool applyAllState)2260 void HWC2On1Adapter::Layer::applySolidColorState(hwc_layer_1_t& hwc1Layer,
2261         bool applyAllState)
2262 {
2263     if (applyAllState || mColor.isDirty()) {
2264         hwc1Layer.backgroundColor = mColor.getPendingValue();
2265         mColor.latch();
2266     }
2267 }
2268 
applySidebandState(hwc_layer_1_t & hwc1Layer,bool applyAllState)2269 void HWC2On1Adapter::Layer::applySidebandState(hwc_layer_1_t& hwc1Layer,
2270         bool applyAllState)
2271 {
2272     if (applyAllState || mSidebandStream.isDirty()) {
2273         hwc1Layer.sidebandStream = mSidebandStream.getPendingValue();
2274         mSidebandStream.latch();
2275     }
2276 }
2277 
applyBufferState(hwc_layer_1_t & hwc1Layer)2278 void HWC2On1Adapter::Layer::applyBufferState(hwc_layer_1_t& hwc1Layer)
2279 {
2280     hwc1Layer.handle = mBuffer.getBuffer();
2281     hwc1Layer.acquireFenceFd = mBuffer.getFence();
2282 }
2283 
applyCompositionType(hwc_layer_1_t & hwc1Layer,bool applyAllState)2284 void HWC2On1Adapter::Layer::applyCompositionType(hwc_layer_1_t& hwc1Layer,
2285         bool applyAllState)
2286 {
2287     // HWC1 never supports color transforms or dataspaces and only sometimes
2288     // supports plane alpha (depending on the version). These require us to drop
2289     // some or all layers to client composition.
2290     if (mHasUnsupportedDataspace || mHasUnsupportedPlaneAlpha ||
2291             mDisplay.hasColorTransform()) {
2292         hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2293         hwc1Layer.flags = HWC_SKIP_LAYER;
2294         return;
2295     }
2296 
2297     if (applyAllState || mCompositionType.isDirty()) {
2298         hwc1Layer.flags = 0;
2299         switch (mCompositionType.getPendingValue()) {
2300             case Composition::Client:
2301                 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2302                 hwc1Layer.flags |= HWC_SKIP_LAYER;
2303                 break;
2304             case Composition::Device:
2305                 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2306                 break;
2307             case Composition::SolidColor:
2308                 hwc1Layer.compositionType = HWC_BACKGROUND;
2309                 break;
2310             case Composition::Cursor:
2311                 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2312                 if (mDisplay.getDevice().getHwc1MinorVersion() >= 4) {
2313                     hwc1Layer.hints |= HWC_IS_CURSOR_LAYER;
2314                 }
2315                 break;
2316             case Composition::Sideband:
2317                 if (mDisplay.getDevice().getHwc1MinorVersion() < 4) {
2318                     hwc1Layer.compositionType = HWC_SIDEBAND;
2319                 } else {
2320                     hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2321                     hwc1Layer.flags |= HWC_SKIP_LAYER;
2322                 }
2323                 break;
2324             default:
2325                 hwc1Layer.compositionType = HWC_FRAMEBUFFER;
2326                 hwc1Layer.flags |= HWC_SKIP_LAYER;
2327                 break;
2328         }
2329         ALOGV("Layer %" PRIu64 " %s set to %d", mId,
2330                 to_string(mCompositionType.getPendingValue()).c_str(),
2331                 hwc1Layer.compositionType);
2332         ALOGV_IF(hwc1Layer.flags & HWC_SKIP_LAYER, "    and skipping");
2333         mCompositionType.latch();
2334     }
2335 }
2336 
2337 // Adapter helpers
2338 
populateCapabilities()2339 void HWC2On1Adapter::populateCapabilities()
2340 {
2341     ALOGV("populateCapabilities");
2342     if (mHwc1MinorVersion >= 3U) {
2343         int supportedTypes = 0;
2344         auto result = mHwc1Device->query(mHwc1Device,
2345                 HWC_DISPLAY_TYPES_SUPPORTED, &supportedTypes);
2346         if ((result == 0) && ((supportedTypes & HWC_DISPLAY_VIRTUAL_BIT) != 0)) {
2347             ALOGI("Found support for HWC virtual displays");
2348             mHwc1SupportsVirtualDisplays = true;
2349         }
2350     }
2351     if (mHwc1MinorVersion >= 4U) {
2352         mCapabilities.insert(Capability::SidebandStream);
2353     }
2354 }
2355 
getDisplay(hwc2_display_t id)2356 HWC2On1Adapter::Display* HWC2On1Adapter::getDisplay(hwc2_display_t id)
2357 {
2358     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2359 
2360     auto display = mDisplays.find(id);
2361     if (display == mDisplays.end()) {
2362         return nullptr;
2363     }
2364 
2365     return display->second.get();
2366 }
2367 
getLayer(hwc2_display_t displayId,hwc2_layer_t layerId)2368 std::tuple<HWC2On1Adapter::Layer*, Error> HWC2On1Adapter::getLayer(
2369         hwc2_display_t displayId, hwc2_layer_t layerId)
2370 {
2371     auto display = getDisplay(displayId);
2372     if (!display) {
2373         return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadDisplay);
2374     }
2375 
2376     auto layerEntry = mLayers.find(layerId);
2377     if (layerEntry == mLayers.end()) {
2378         return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2379     }
2380 
2381     auto layer = layerEntry->second;
2382     if (layer->getDisplay().getId() != displayId) {
2383         return std::make_tuple(static_cast<Layer*>(nullptr), Error::BadLayer);
2384     }
2385     return std::make_tuple(layer.get(), Error::None);
2386 }
2387 
populatePrimary()2388 void HWC2On1Adapter::populatePrimary()
2389 {
2390     ALOGV("populatePrimary");
2391 
2392     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2393 
2394     auto display =
2395             std::make_shared<Display>(*this, HWC2::DisplayType::Physical);
2396     mHwc1DisplayMap[HWC_DISPLAY_PRIMARY] = display->getId();
2397     display->setHwc1Id(HWC_DISPLAY_PRIMARY);
2398     display->populateConfigs();
2399     mDisplays.emplace(display->getId(), std::move(display));
2400 }
2401 
prepareAllDisplays()2402 bool HWC2On1Adapter::prepareAllDisplays()
2403 {
2404     ATRACE_CALL();
2405 
2406     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2407 
2408     for (const auto& displayPair : mDisplays) {
2409         auto& display = displayPair.second;
2410         if (!display->prepare()) {
2411             return false;
2412         }
2413     }
2414 
2415     if (mHwc1DisplayMap.count(0) == 0) {
2416         ALOGE("prepareAllDisplays: Unable to find primary HWC1 display");
2417         return false;
2418     }
2419 
2420     // Always push the primary display
2421     std::vector<HWC2On1Adapter::Display::HWC1Contents> requestedContents;
2422     auto primaryDisplayId = mHwc1DisplayMap[HWC_DISPLAY_PRIMARY];
2423     auto& primaryDisplay = mDisplays[primaryDisplayId];
2424     auto primaryDisplayContents = primaryDisplay->cloneRequestedContents();
2425     requestedContents.push_back(std::move(primaryDisplayContents));
2426 
2427     // Push the external display, if present
2428     if (mHwc1DisplayMap.count(HWC_DISPLAY_EXTERNAL) != 0) {
2429         auto externalDisplayId = mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL];
2430         auto& externalDisplay = mDisplays[externalDisplayId];
2431         auto externalDisplayContents =
2432                 externalDisplay->cloneRequestedContents();
2433         requestedContents.push_back(std::move(externalDisplayContents));
2434     } else {
2435         // Even if an external display isn't present, we still need to send
2436         // at least two displays down to HWC1
2437         requestedContents.push_back(nullptr);
2438     }
2439 
2440     // Push the hardware virtual display, if supported and present
2441     if (mHwc1MinorVersion >= 3) {
2442         if (mHwc1DisplayMap.count(HWC_DISPLAY_VIRTUAL) != 0) {
2443             auto virtualDisplayId = mHwc1DisplayMap[HWC_DISPLAY_VIRTUAL];
2444             auto& virtualDisplay = mDisplays[virtualDisplayId];
2445             auto virtualDisplayContents =
2446                     virtualDisplay->cloneRequestedContents();
2447             requestedContents.push_back(std::move(virtualDisplayContents));
2448         } else {
2449             requestedContents.push_back(nullptr);
2450         }
2451     }
2452 
2453     mHwc1Contents.clear();
2454     for (auto& displayContents : requestedContents) {
2455         mHwc1Contents.push_back(displayContents.get());
2456         if (!displayContents) {
2457             continue;
2458         }
2459 
2460         ALOGV("Display %zd layers:", mHwc1Contents.size() - 1);
2461         for (size_t l = 0; l < displayContents->numHwLayers; ++l) {
2462             auto& layer = displayContents->hwLayers[l];
2463             ALOGV("  %zd: %d", l, layer.compositionType);
2464         }
2465     }
2466 
2467     ALOGV("Calling HWC1 prepare");
2468     {
2469         ATRACE_NAME("HWC1 prepare");
2470         mHwc1Device->prepare(mHwc1Device, mHwc1Contents.size(),
2471                 mHwc1Contents.data());
2472     }
2473 
2474     for (size_t c = 0; c < mHwc1Contents.size(); ++c) {
2475         auto& contents = mHwc1Contents[c];
2476         if (!contents) {
2477             continue;
2478         }
2479         ALOGV("Display %zd layers:", c);
2480         for (size_t l = 0; l < contents->numHwLayers; ++l) {
2481             ALOGV("  %zd: %d", l, contents->hwLayers[l].compositionType);
2482         }
2483     }
2484 
2485     // Return the received contents to their respective displays
2486     for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2487         if (mHwc1Contents[hwc1Id] == nullptr) {
2488             continue;
2489         }
2490 
2491         auto displayId = mHwc1DisplayMap[hwc1Id];
2492         auto& display = mDisplays[displayId];
2493         display->setReceivedContents(std::move(requestedContents[hwc1Id]));
2494     }
2495 
2496     return true;
2497 }
2498 
setAllDisplays()2499 Error HWC2On1Adapter::setAllDisplays()
2500 {
2501     ATRACE_CALL();
2502 
2503     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2504 
2505     // Make sure we're ready to validate
2506     for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2507         if (mHwc1Contents[hwc1Id] == nullptr) {
2508             continue;
2509         }
2510 
2511         auto displayId = mHwc1DisplayMap[hwc1Id];
2512         auto& display = mDisplays[displayId];
2513         Error error = display->set(*mHwc1Contents[hwc1Id]);
2514         if (error != Error::None) {
2515             ALOGE("setAllDisplays: Failed to set display %zd: %s", hwc1Id,
2516                     to_string(error).c_str());
2517             return error;
2518         }
2519     }
2520 
2521     ALOGV("Calling HWC1 set");
2522     {
2523         ATRACE_NAME("HWC1 set");
2524         mHwc1Device->set(mHwc1Device, mHwc1Contents.size(),
2525                 mHwc1Contents.data());
2526     }
2527 
2528     // Add retire and release fences
2529     for (size_t hwc1Id = 0; hwc1Id < mHwc1Contents.size(); ++hwc1Id) {
2530         if (mHwc1Contents[hwc1Id] == nullptr) {
2531             continue;
2532         }
2533 
2534         auto displayId = mHwc1DisplayMap[hwc1Id];
2535         auto& display = mDisplays[displayId];
2536         auto retireFenceFd = mHwc1Contents[hwc1Id]->retireFenceFd;
2537         ALOGV("setAllDisplays: Adding retire fence %d to display %zd",
2538                 retireFenceFd, hwc1Id);
2539         display->addRetireFence(mHwc1Contents[hwc1Id]->retireFenceFd);
2540         display->addReleaseFences(*mHwc1Contents[hwc1Id]);
2541     }
2542 
2543     return Error::None;
2544 }
2545 
hwc1Invalidate()2546 void HWC2On1Adapter::hwc1Invalidate()
2547 {
2548     ALOGV("Received hwc1Invalidate");
2549 
2550     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2551 
2552     // If the HWC2-side callback hasn't been registered yet, buffer this until
2553     // it is registered
2554     if (mCallbacks.count(Callback::Refresh) == 0) {
2555         mHasPendingInvalidate = true;
2556         return;
2557     }
2558 
2559     const auto& callbackInfo = mCallbacks[Callback::Refresh];
2560     std::vector<hwc2_display_t> displays;
2561     for (const auto& displayPair : mDisplays) {
2562         displays.emplace_back(displayPair.first);
2563     }
2564 
2565     // Call back without the state lock held
2566     lock.unlock();
2567 
2568     auto refresh = reinterpret_cast<HWC2_PFN_REFRESH>(callbackInfo.pointer);
2569     for (auto display : displays) {
2570         refresh(callbackInfo.data, display);
2571     }
2572 }
2573 
hwc1Vsync(int hwc1DisplayId,int64_t timestamp)2574 void HWC2On1Adapter::hwc1Vsync(int hwc1DisplayId, int64_t timestamp)
2575 {
2576     ALOGV("Received hwc1Vsync(%d, %" PRId64 ")", hwc1DisplayId, timestamp);
2577 
2578     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2579 
2580     // If the HWC2-side callback hasn't been registered yet, buffer this until
2581     // it is registered
2582     if (mCallbacks.count(Callback::Vsync) == 0) {
2583         mPendingVsyncs.emplace_back(hwc1DisplayId, timestamp);
2584         return;
2585     }
2586 
2587     if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2588         ALOGE("hwc1Vsync: Couldn't find display for HWC1 id %d", hwc1DisplayId);
2589         return;
2590     }
2591 
2592     const auto& callbackInfo = mCallbacks[Callback::Vsync];
2593     auto displayId = mHwc1DisplayMap[hwc1DisplayId];
2594 
2595     // Call back without the state lock held
2596     lock.unlock();
2597 
2598     auto vsync = reinterpret_cast<HWC2_PFN_VSYNC>(callbackInfo.pointer);
2599     vsync(callbackInfo.data, displayId, timestamp);
2600 }
2601 
hwc1Hotplug(int hwc1DisplayId,int connected)2602 void HWC2On1Adapter::hwc1Hotplug(int hwc1DisplayId, int connected)
2603 {
2604     ALOGV("Received hwc1Hotplug(%d, %d)", hwc1DisplayId, connected);
2605 
2606     if (hwc1DisplayId != HWC_DISPLAY_EXTERNAL) {
2607         ALOGE("hwc1Hotplug: Received hotplug for non-external display");
2608         return;
2609     }
2610 
2611     std::unique_lock<std::recursive_timed_mutex> lock(mStateMutex);
2612 
2613     // If the HWC2-side callback hasn't been registered yet, buffer this until
2614     // it is registered
2615     if (mCallbacks.count(Callback::Hotplug) == 0) {
2616         mPendingHotplugs.emplace_back(hwc1DisplayId, connected);
2617         return;
2618     }
2619 
2620     hwc2_display_t displayId = UINT64_MAX;
2621     if (mHwc1DisplayMap.count(hwc1DisplayId) == 0) {
2622         if (connected == 0) {
2623             ALOGW("hwc1Hotplug: Received disconnect for unconnected display");
2624             return;
2625         }
2626 
2627         // Create a new display on connect
2628         auto display = std::make_shared<HWC2On1Adapter::Display>(*this,
2629                 HWC2::DisplayType::Physical);
2630         display->setHwc1Id(HWC_DISPLAY_EXTERNAL);
2631         display->populateConfigs();
2632         displayId = display->getId();
2633         mHwc1DisplayMap[HWC_DISPLAY_EXTERNAL] = displayId;
2634         mDisplays.emplace(displayId, std::move(display));
2635     } else {
2636         if (connected != 0) {
2637             ALOGW("hwc1Hotplug: Received connect for previously connected "
2638                     "display");
2639             return;
2640         }
2641 
2642         // Disconnect an existing display
2643         displayId = mHwc1DisplayMap[hwc1DisplayId];
2644         mHwc1DisplayMap.erase(HWC_DISPLAY_EXTERNAL);
2645         mDisplays.erase(displayId);
2646     }
2647 
2648     const auto& callbackInfo = mCallbacks[Callback::Hotplug];
2649 
2650     // Call back without the state lock held
2651     lock.unlock();
2652 
2653     auto hotplug = reinterpret_cast<HWC2_PFN_HOTPLUG>(callbackInfo.pointer);
2654     auto hwc2Connected = (connected == 0) ?
2655             HWC2::Connection::Disconnected : HWC2::Connection::Connected;
2656     hotplug(callbackInfo.data, displayId, static_cast<int32_t>(hwc2Connected));
2657 }
2658 
2659 } // namespace android
2660