1 /*
2  * Copyright (C) 2010 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #define ATRACE_TAG ATRACE_TAG_GRAPHICS
18 
19 #include <inttypes.h>
20 #include <math.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <sys/types.h>
26 
27 #include <utils/Errors.h>
28 #include <utils/misc.h>
29 #include <utils/NativeHandle.h>
30 #include <utils/String8.h>
31 #include <utils/Thread.h>
32 #include <utils/Trace.h>
33 #include <utils/Vector.h>
34 
35 #include <ui/GraphicBuffer.h>
36 
37 #include <hardware/hardware.h>
38 #include <hardware/hwcomposer.h>
39 
40 #include <android/configuration.h>
41 
42 #include <cutils/log.h>
43 #include <cutils/properties.h>
44 
45 #include "HWComposer.h"
46 
47 #include "../Layer.h"           // needed only for debugging
48 #include "../SurfaceFlinger.h"
49 
50 namespace android {
51 
52 #define MIN_HWC_HEADER_VERSION HWC_HEADER_VERSION
53 
hwcApiVersion(const hwc_composer_device_1_t * hwc)54 static uint32_t hwcApiVersion(const hwc_composer_device_1_t* hwc) {
55     uint32_t hwcVersion = hwc->common.version;
56     return hwcVersion & HARDWARE_API_VERSION_2_MAJ_MIN_MASK;
57 }
58 
hwcHeaderVersion(const hwc_composer_device_1_t * hwc)59 static uint32_t hwcHeaderVersion(const hwc_composer_device_1_t* hwc) {
60     uint32_t hwcVersion = hwc->common.version;
61     return hwcVersion & HARDWARE_API_VERSION_2_HEADER_MASK;
62 }
63 
hwcHasApiVersion(const hwc_composer_device_1_t * hwc,uint32_t version)64 static bool hwcHasApiVersion(const hwc_composer_device_1_t* hwc,
65         uint32_t version) {
66     return hwcApiVersion(hwc) >= (version & HARDWARE_API_VERSION_2_MAJ_MIN_MASK);
67 }
68 
69 // ---------------------------------------------------------------------------
70 
71 struct HWComposer::cb_context {
72     struct callbacks : public hwc_procs_t {
73         // these are here to facilitate the transition when adding
74         // new callbacks (an implementation can check for NULL before
75         // calling a new callback).
76         void (*zero[4])(void);
77     };
78     callbacks procs;
79     HWComposer* hwc;
80 };
81 
82 // ---------------------------------------------------------------------------
83 
HWComposer(const sp<SurfaceFlinger> & flinger,EventHandler & handler)84 HWComposer::HWComposer(
85         const sp<SurfaceFlinger>& flinger,
86         EventHandler& handler)
87     : mFlinger(flinger),
88       mFbDev(0), mHwc(0), mNumDisplays(1),
89       mCBContext(new cb_context),
90       mEventHandler(handler),
91       mDebugForceFakeVSync(false)
92 {
93     for (size_t i =0 ; i<MAX_HWC_DISPLAYS ; i++) {
94         mLists[i] = 0;
95     }
96 
97     for (size_t i=0 ; i<HWC_NUM_PHYSICAL_DISPLAY_TYPES ; i++) {
98         mLastHwVSync[i] = 0;
99         mVSyncCounts[i] = 0;
100     }
101 
102     char value[PROPERTY_VALUE_MAX];
103     property_get("debug.sf.no_hw_vsync", value, "0");
104     mDebugForceFakeVSync = atoi(value);
105 
106     bool needVSyncThread = true;
107 
108     // Note: some devices may insist that the FB HAL be opened before HWC.
109     int fberr = loadFbHalModule();
110     loadHwcModule();
111 
112     if (mFbDev && mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
113         // close FB HAL if we don't needed it.
114         // FIXME: this is temporary until we're not forced to open FB HAL
115         // before HWC.
116         framebuffer_close(mFbDev);
117         mFbDev = NULL;
118     }
119 
120     // If we have no HWC, or a pre-1.1 HWC, an FB dev is mandatory.
121     if ((!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
122             && !mFbDev) {
123         ALOGE("ERROR: failed to open framebuffer (%s), aborting",
124                 strerror(-fberr));
125         abort();
126     }
127 
128     // these display IDs are always reserved
129     for (size_t i=0 ; i<NUM_BUILTIN_DISPLAYS ; i++) {
130         mAllocatedDisplayIDs.markBit(i);
131     }
132 
133     if (mHwc) {
134         ALOGI("Using %s version %u.%u", HWC_HARDWARE_COMPOSER,
135               (hwcApiVersion(mHwc) >> 24) & 0xff,
136               (hwcApiVersion(mHwc) >> 16) & 0xff);
137         if (mHwc->registerProcs) {
138             mCBContext->hwc = this;
139             mCBContext->procs.invalidate = &hook_invalidate;
140             mCBContext->procs.vsync = &hook_vsync;
141             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
142                 mCBContext->procs.hotplug = &hook_hotplug;
143             else
144                 mCBContext->procs.hotplug = NULL;
145             memset(mCBContext->procs.zero, 0, sizeof(mCBContext->procs.zero));
146             mHwc->registerProcs(mHwc, &mCBContext->procs);
147         }
148 
149         // don't need a vsync thread if we have a hardware composer
150         needVSyncThread = false;
151         // always turn vsync off when we start
152         eventControl(HWC_DISPLAY_PRIMARY, HWC_EVENT_VSYNC, 0);
153 
154         // the number of displays we actually have depends on the
155         // hw composer version
156         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
157             // 1.3 adds support for virtual displays
158             mNumDisplays = MAX_HWC_DISPLAYS;
159         } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
160             // 1.1 adds support for multiple displays
161             mNumDisplays = NUM_BUILTIN_DISPLAYS;
162         } else {
163             mNumDisplays = 1;
164         }
165     }
166 
167     if (mFbDev) {
168         ALOG_ASSERT(!(mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)),
169                 "should only have fbdev if no hwc or hwc is 1.0");
170 
171         DisplayData& disp(mDisplayData[HWC_DISPLAY_PRIMARY]);
172         disp.connected = true;
173         disp.format = mFbDev->format;
174         DisplayConfig config = DisplayConfig();
175         config.width = mFbDev->width;
176         config.height = mFbDev->height;
177         config.xdpi = mFbDev->xdpi;
178         config.ydpi = mFbDev->ydpi;
179         config.refresh = nsecs_t(1e9 / mFbDev->fps);
180         disp.configs.push_back(config);
181         disp.currentConfig = 0;
182     } else if (mHwc) {
183         // here we're guaranteed to have at least HWC 1.1
184         for (size_t i =0 ; i<NUM_BUILTIN_DISPLAYS ; i++) {
185             queryDisplayProperties(i);
186         }
187     }
188 
189     if (needVSyncThread) {
190         // we don't have VSYNC support, we need to fake it
191         mVSyncThread = new VSyncThread(*this);
192     }
193 }
194 
~HWComposer()195 HWComposer::~HWComposer() {
196     if (mHwc) {
197         eventControl(HWC_DISPLAY_PRIMARY, HWC_EVENT_VSYNC, 0);
198     }
199     if (mVSyncThread != NULL) {
200         mVSyncThread->requestExitAndWait();
201     }
202     if (mHwc) {
203         hwc_close_1(mHwc);
204     }
205     if (mFbDev) {
206         framebuffer_close(mFbDev);
207     }
208     delete mCBContext;
209 }
210 
211 // Load and prepare the hardware composer module.  Sets mHwc.
loadHwcModule()212 void HWComposer::loadHwcModule()
213 {
214     hw_module_t const* module;
215 
216     if (hw_get_module(HWC_HARDWARE_MODULE_ID, &module) != 0) {
217         ALOGE("%s module not found", HWC_HARDWARE_MODULE_ID);
218         return;
219     }
220 
221     int err = hwc_open_1(module, &mHwc);
222     if (err) {
223         ALOGE("%s device failed to initialize (%s)",
224               HWC_HARDWARE_COMPOSER, strerror(-err));
225         return;
226     }
227 
228     if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_0) ||
229             hwcHeaderVersion(mHwc) < MIN_HWC_HEADER_VERSION ||
230             hwcHeaderVersion(mHwc) > HWC_HEADER_VERSION) {
231         ALOGE("%s device version %#x unsupported, will not be used",
232               HWC_HARDWARE_COMPOSER, mHwc->common.version);
233         hwc_close_1(mHwc);
234         mHwc = NULL;
235         return;
236     }
237 }
238 
239 // Load and prepare the FB HAL, which uses the gralloc module.  Sets mFbDev.
loadFbHalModule()240 int HWComposer::loadFbHalModule()
241 {
242     hw_module_t const* module;
243 
244     int err = hw_get_module(GRALLOC_HARDWARE_MODULE_ID, &module);
245     if (err != 0) {
246         ALOGE("%s module not found", GRALLOC_HARDWARE_MODULE_ID);
247         return err;
248     }
249 
250     return framebuffer_open(module, &mFbDev);
251 }
252 
initCheck() const253 status_t HWComposer::initCheck() const {
254     return mHwc ? NO_ERROR : NO_INIT;
255 }
256 
hook_invalidate(const struct hwc_procs * procs)257 void HWComposer::hook_invalidate(const struct hwc_procs* procs) {
258     cb_context* ctx = reinterpret_cast<cb_context*>(
259             const_cast<hwc_procs_t*>(procs));
260     ctx->hwc->invalidate();
261 }
262 
hook_vsync(const struct hwc_procs * procs,int disp,int64_t timestamp)263 void HWComposer::hook_vsync(const struct hwc_procs* procs, int disp,
264         int64_t timestamp) {
265     cb_context* ctx = reinterpret_cast<cb_context*>(
266             const_cast<hwc_procs_t*>(procs));
267     ctx->hwc->vsync(disp, timestamp);
268 }
269 
hook_hotplug(const struct hwc_procs * procs,int disp,int connected)270 void HWComposer::hook_hotplug(const struct hwc_procs* procs, int disp,
271         int connected) {
272     cb_context* ctx = reinterpret_cast<cb_context*>(
273             const_cast<hwc_procs_t*>(procs));
274     ctx->hwc->hotplug(disp, connected);
275 }
276 
invalidate()277 void HWComposer::invalidate() {
278     mFlinger->repaintEverything();
279 }
280 
vsync(int disp,int64_t timestamp)281 void HWComposer::vsync(int disp, int64_t timestamp) {
282     if (uint32_t(disp) < HWC_NUM_PHYSICAL_DISPLAY_TYPES) {
283         {
284             Mutex::Autolock _l(mLock);
285 
286             // There have been reports of HWCs that signal several vsync events
287             // with the same timestamp when turning the display off and on. This
288             // is a bug in the HWC implementation, but filter the extra events
289             // out here so they don't cause havoc downstream.
290             if (timestamp == mLastHwVSync[disp]) {
291                 ALOGW("Ignoring duplicate VSYNC event from HWC (t=%" PRId64 ")",
292                         timestamp);
293                 return;
294             }
295 
296             mLastHwVSync[disp] = timestamp;
297         }
298 
299         char tag[16];
300         snprintf(tag, sizeof(tag), "HW_VSYNC_%1u", disp);
301         ATRACE_INT(tag, ++mVSyncCounts[disp] & 1);
302 
303         mEventHandler.onVSyncReceived(disp, timestamp);
304     }
305 }
306 
hotplug(int disp,int connected)307 void HWComposer::hotplug(int disp, int connected) {
308     if (disp >= VIRTUAL_DISPLAY_ID_BASE) {
309         ALOGE("hotplug event received for invalid display: disp=%d connected=%d",
310                 disp, connected);
311         return;
312     }
313     queryDisplayProperties(disp);
314     // Do not teardown or recreate the primary display
315     if (disp != HWC_DISPLAY_PRIMARY) {
316         mEventHandler.onHotplugReceived(disp, bool(connected));
317     }
318 }
319 
getDefaultDensity(uint32_t width,uint32_t height)320 static float getDefaultDensity(uint32_t width, uint32_t height) {
321     // Default density is based on TVs: 1080p displays get XHIGH density,
322     // lower-resolution displays get TV density. Maybe eventually we'll need
323     // to update it for 4K displays, though hopefully those just report
324     // accurate DPI information to begin with. This is also used for virtual
325     // displays and even primary displays with older hwcomposers, so be
326     // careful about orientation.
327 
328     uint32_t h = width < height ? width : height;
329     if (h >= 1080) return ACONFIGURATION_DENSITY_XHIGH;
330     else           return ACONFIGURATION_DENSITY_TV;
331 }
332 
333 static const uint32_t DISPLAY_ATTRIBUTES[] = {
334     HWC_DISPLAY_VSYNC_PERIOD,
335     HWC_DISPLAY_WIDTH,
336     HWC_DISPLAY_HEIGHT,
337     HWC_DISPLAY_DPI_X,
338     HWC_DISPLAY_DPI_Y,
339     HWC_DISPLAY_NO_ATTRIBUTE,
340 };
341 #define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
342 
queryDisplayProperties(int disp)343 status_t HWComposer::queryDisplayProperties(int disp) {
344 
345     LOG_ALWAYS_FATAL_IF(!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
346 
347     // use zero as default value for unspecified attributes
348     int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
349     memset(values, 0, sizeof(values));
350 
351     const size_t MAX_NUM_CONFIGS = 128;
352     uint32_t configs[MAX_NUM_CONFIGS] = {0};
353     size_t numConfigs = MAX_NUM_CONFIGS;
354     status_t err = mHwc->getDisplayConfigs(mHwc, disp, configs, &numConfigs);
355     if (err != NO_ERROR) {
356         // this can happen if an unpluggable display is not connected
357         mDisplayData[disp].connected = false;
358         return err;
359     }
360 
361     mDisplayData[disp].currentConfig = 0;
362     for (size_t c = 0; c < numConfigs; ++c) {
363         err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
364                 DISPLAY_ATTRIBUTES, values);
365         if (err != NO_ERROR) {
366             // we can't get this display's info. turn it off.
367             mDisplayData[disp].connected = false;
368             return err;
369         }
370 
371         DisplayConfig config = DisplayConfig();
372         for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
373             switch (DISPLAY_ATTRIBUTES[i]) {
374                 case HWC_DISPLAY_VSYNC_PERIOD:
375                     config.refresh = nsecs_t(values[i]);
376                     break;
377                 case HWC_DISPLAY_WIDTH:
378                     config.width = values[i];
379                     break;
380                 case HWC_DISPLAY_HEIGHT:
381                     config.height = values[i];
382                     break;
383                 case HWC_DISPLAY_DPI_X:
384                     config.xdpi = values[i] / 1000.0f;
385                     break;
386                 case HWC_DISPLAY_DPI_Y:
387                     config.ydpi = values[i] / 1000.0f;
388                     break;
389                 default:
390                     ALOG_ASSERT(false, "unknown display attribute[%zu] %#x",
391                             i, DISPLAY_ATTRIBUTES[i]);
392                     break;
393             }
394         }
395 
396         if (config.xdpi == 0.0f || config.ydpi == 0.0f) {
397             float dpi = getDefaultDensity(config.width, config.height);
398             config.xdpi = dpi;
399             config.ydpi = dpi;
400         }
401 
402         mDisplayData[disp].configs.push_back(config);
403     }
404 
405     // FIXME: what should we set the format to?
406     mDisplayData[disp].format = HAL_PIXEL_FORMAT_RGBA_8888;
407     mDisplayData[disp].connected = true;
408     return NO_ERROR;
409 }
410 
setVirtualDisplayProperties(int32_t id,uint32_t w,uint32_t h,uint32_t format)411 status_t HWComposer::setVirtualDisplayProperties(int32_t id,
412         uint32_t w, uint32_t h, uint32_t format) {
413     if (id < VIRTUAL_DISPLAY_ID_BASE || id >= int32_t(mNumDisplays) ||
414             !mAllocatedDisplayIDs.hasBit(id)) {
415         return BAD_INDEX;
416     }
417     size_t configId = mDisplayData[id].currentConfig;
418     mDisplayData[id].format = format;
419     DisplayConfig& config = mDisplayData[id].configs.editItemAt(configId);
420     config.width = w;
421     config.height = h;
422     config.xdpi = config.ydpi = getDefaultDensity(w, h);
423     return NO_ERROR;
424 }
425 
allocateDisplayId()426 int32_t HWComposer::allocateDisplayId() {
427     if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
428         return NO_MEMORY;
429     }
430     int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
431     mAllocatedDisplayIDs.markBit(id);
432     mDisplayData[id].connected = true;
433     mDisplayData[id].configs.resize(1);
434     mDisplayData[id].currentConfig = 0;
435     return id;
436 }
437 
freeDisplayId(int32_t id)438 status_t HWComposer::freeDisplayId(int32_t id) {
439     if (id < NUM_BUILTIN_DISPLAYS) {
440         // cannot free the reserved IDs
441         return BAD_VALUE;
442     }
443     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
444         return BAD_INDEX;
445     }
446     mAllocatedDisplayIDs.clearBit(id);
447     mDisplayData[id].connected = false;
448     return NO_ERROR;
449 }
450 
getRefreshTimestamp(int disp) const451 nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
452     // this returns the last refresh timestamp.
453     // if the last one is not available, we estimate it based on
454     // the refresh period and whatever closest timestamp we have.
455     Mutex::Autolock _l(mLock);
456     nsecs_t now = systemTime(CLOCK_MONOTONIC);
457     size_t configId = mDisplayData[disp].currentConfig;
458     return now - ((now - mLastHwVSync[disp]) %
459             mDisplayData[disp].configs[configId].refresh);
460 }
461 
getDisplayFence(int disp) const462 sp<Fence> HWComposer::getDisplayFence(int disp) const {
463     return mDisplayData[disp].lastDisplayFence;
464 }
465 
getFormat(int disp) const466 uint32_t HWComposer::getFormat(int disp) const {
467     if (static_cast<uint32_t>(disp) >= MAX_HWC_DISPLAYS || !mAllocatedDisplayIDs.hasBit(disp)) {
468         return HAL_PIXEL_FORMAT_RGBA_8888;
469     } else {
470         return mDisplayData[disp].format;
471     }
472 }
473 
isConnected(int disp) const474 bool HWComposer::isConnected(int disp) const {
475     return mDisplayData[disp].connected;
476 }
477 
getWidth(int disp) const478 uint32_t HWComposer::getWidth(int disp) const {
479     size_t currentConfig = mDisplayData[disp].currentConfig;
480     return mDisplayData[disp].configs[currentConfig].width;
481 }
482 
getHeight(int disp) const483 uint32_t HWComposer::getHeight(int disp) const {
484     size_t currentConfig = mDisplayData[disp].currentConfig;
485     return mDisplayData[disp].configs[currentConfig].height;
486 }
487 
getDpiX(int disp) const488 float HWComposer::getDpiX(int disp) const {
489     size_t currentConfig = mDisplayData[disp].currentConfig;
490     return mDisplayData[disp].configs[currentConfig].xdpi;
491 }
492 
getDpiY(int disp) const493 float HWComposer::getDpiY(int disp) const {
494     size_t currentConfig = mDisplayData[disp].currentConfig;
495     return mDisplayData[disp].configs[currentConfig].ydpi;
496 }
497 
getRefreshPeriod(int disp) const498 nsecs_t HWComposer::getRefreshPeriod(int disp) const {
499     size_t currentConfig = mDisplayData[disp].currentConfig;
500     return mDisplayData[disp].configs[currentConfig].refresh;
501 }
502 
getConfigs(int disp) const503 const Vector<HWComposer::DisplayConfig>& HWComposer::getConfigs(int disp) const {
504     return mDisplayData[disp].configs;
505 }
506 
getCurrentConfig(int disp) const507 size_t HWComposer::getCurrentConfig(int disp) const {
508     return mDisplayData[disp].currentConfig;
509 }
510 
eventControl(int disp,int event,int enabled)511 void HWComposer::eventControl(int disp, int event, int enabled) {
512     if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
513         ALOGD("eventControl ignoring event %d on unallocated disp %d (en=%d)",
514               event, disp, enabled);
515         return;
516     }
517     if (event != EVENT_VSYNC) {
518         ALOGW("eventControl got unexpected event %d (disp=%d en=%d)",
519               event, disp, enabled);
520         return;
521     }
522     status_t err = NO_ERROR;
523     if (mHwc && !mDebugForceFakeVSync) {
524         // NOTE: we use our own internal lock here because we have to call
525         // into the HWC with the lock held, and we want to make sure
526         // that even if HWC blocks (which it shouldn't), it won't
527         // affect other threads.
528         Mutex::Autolock _l(mEventControlLock);
529         const int32_t eventBit = 1UL << event;
530         const int32_t newValue = enabled ? eventBit : 0;
531         const int32_t oldValue = mDisplayData[disp].events & eventBit;
532         if (newValue != oldValue) {
533             ATRACE_CALL();
534             err = mHwc->eventControl(mHwc, disp, event, enabled);
535             if (!err) {
536                 int32_t& events(mDisplayData[disp].events);
537                 events = (events & ~eventBit) | newValue;
538 
539                 char tag[16];
540                 snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", disp);
541                 ATRACE_INT(tag, enabled);
542             }
543         }
544         // error here should not happen -- not sure what we should
545         // do if it does.
546         ALOGE_IF(err, "eventControl(%d, %d) failed %s",
547                 event, enabled, strerror(-err));
548     }
549 
550     if (err == NO_ERROR && mVSyncThread != NULL) {
551         mVSyncThread->setEnabled(enabled);
552     }
553 }
554 
createWorkList(int32_t id,size_t numLayers)555 status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
556     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
557         return BAD_INDEX;
558     }
559 
560     if (mHwc) {
561         DisplayData& disp(mDisplayData[id]);
562         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
563             // we need space for the HWC_FRAMEBUFFER_TARGET
564             numLayers++;
565         }
566         if (disp.capacity < numLayers || disp.list == NULL) {
567             size_t size = sizeof(hwc_display_contents_1_t)
568                     + numLayers * sizeof(hwc_layer_1_t);
569             free(disp.list);
570             disp.list = (hwc_display_contents_1_t*)malloc(size);
571             disp.capacity = numLayers;
572         }
573         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
574             disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
575             memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
576             const DisplayConfig& currentConfig =
577                     disp.configs[disp.currentConfig];
578             const hwc_rect_t r = { 0, 0,
579                     (int) currentConfig.width, (int) currentConfig.height };
580             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
581             disp.framebufferTarget->hints = 0;
582             disp.framebufferTarget->flags = 0;
583             disp.framebufferTarget->handle = disp.fbTargetHandle;
584             disp.framebufferTarget->transform = 0;
585             disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
586             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
587                 disp.framebufferTarget->sourceCropf.left = 0;
588                 disp.framebufferTarget->sourceCropf.top = 0;
589                 disp.framebufferTarget->sourceCropf.right =
590                         currentConfig.width;
591                 disp.framebufferTarget->sourceCropf.bottom =
592                         currentConfig.height;
593             } else {
594                 disp.framebufferTarget->sourceCrop = r;
595             }
596             disp.framebufferTarget->displayFrame = r;
597             disp.framebufferTarget->visibleRegionScreen.numRects = 1;
598             disp.framebufferTarget->visibleRegionScreen.rects =
599                 &disp.framebufferTarget->displayFrame;
600             disp.framebufferTarget->acquireFenceFd = -1;
601             disp.framebufferTarget->releaseFenceFd = -1;
602             disp.framebufferTarget->planeAlpha = 0xFF;
603         }
604         disp.list->retireFenceFd = -1;
605         disp.list->flags = HWC_GEOMETRY_CHANGED;
606         disp.list->numHwLayers = numLayers;
607     }
608     return NO_ERROR;
609 }
610 
setFramebufferTarget(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buf)611 status_t HWComposer::setFramebufferTarget(int32_t id,
612         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
613     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
614         return BAD_INDEX;
615     }
616     DisplayData& disp(mDisplayData[id]);
617     if (!disp.framebufferTarget) {
618         // this should never happen, but apparently eglCreateWindowSurface()
619         // triggers a Surface::queueBuffer()  on some
620         // devices (!?) -- log and ignore.
621         ALOGE("HWComposer: framebufferTarget is null");
622         return NO_ERROR;
623     }
624 
625     int acquireFenceFd = -1;
626     if (acquireFence->isValid()) {
627         acquireFenceFd = acquireFence->dup();
628     }
629 
630     // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
631     disp.fbTargetHandle = buf->handle;
632     disp.framebufferTarget->handle = disp.fbTargetHandle;
633     disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
634     return NO_ERROR;
635 }
636 
prepare()637 status_t HWComposer::prepare() {
638     Mutex::Autolock _l(mDisplayLock);
639     for (size_t i=0 ; i<mNumDisplays ; i++) {
640         DisplayData& disp(mDisplayData[i]);
641         if (disp.framebufferTarget) {
642             // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
643             // DO NOT reset the handle field to NULL, because it's possible
644             // that we have nothing to redraw (eg: eglSwapBuffers() not called)
645             // in which case, we should continue to use the same buffer.
646             LOG_FATAL_IF(disp.list == NULL);
647             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
648         }
649         if (!disp.connected && disp.list != NULL) {
650             ALOGW("WARNING: disp %zu: connected, non-null list, layers=%zu",
651                   i, disp.list->numHwLayers);
652         }
653         mLists[i] = disp.list;
654         if (mLists[i]) {
655             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
656                 mLists[i]->outbuf = disp.outbufHandle;
657                 mLists[i]->outbufAcquireFenceFd = -1;
658             } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
659                 // garbage data to catch improper use
660                 mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
661                 mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
662             } else {
663                 mLists[i]->dpy = EGL_NO_DISPLAY;
664                 mLists[i]->sur = EGL_NO_SURFACE;
665             }
666         }
667     }
668 
669     int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
670     ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
671 
672     if (err == NO_ERROR) {
673         // here we're just making sure that "skip" layers are set
674         // to HWC_FRAMEBUFFER and we're also counting how many layers
675         // we have of each type.
676         //
677         // If there are no window layers, we treat the display has having FB
678         // composition, because SurfaceFlinger will use GLES to draw the
679         // wormhole region.
680         for (size_t i=0 ; i<mNumDisplays ; i++) {
681             DisplayData& disp(mDisplayData[i]);
682             disp.hasFbComp = false;
683             disp.hasOvComp = false;
684             if (disp.list) {
685                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
686                     hwc_layer_1_t& l = disp.list->hwLayers[i];
687 
688                     //ALOGD("prepare: %d, type=%d, handle=%p",
689                     //        i, l.compositionType, l.handle);
690 
691                     if (l.flags & HWC_SKIP_LAYER) {
692                         l.compositionType = HWC_FRAMEBUFFER;
693                     }
694                     if (l.compositionType == HWC_FRAMEBUFFER) {
695                         disp.hasFbComp = true;
696                     }
697                     if (l.compositionType == HWC_OVERLAY) {
698                         disp.hasOvComp = true;
699                     }
700                     if (l.compositionType == HWC_CURSOR_OVERLAY) {
701                         disp.hasOvComp = true;
702                     }
703                 }
704                 if (disp.list->numHwLayers == (disp.framebufferTarget ? 1 : 0)) {
705                     disp.hasFbComp = true;
706                 }
707             } else {
708                 disp.hasFbComp = true;
709             }
710         }
711     }
712     return (status_t)err;
713 }
714 
hasHwcComposition(int32_t id) const715 bool HWComposer::hasHwcComposition(int32_t id) const {
716     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
717         return false;
718     return mDisplayData[id].hasOvComp;
719 }
720 
hasGlesComposition(int32_t id) const721 bool HWComposer::hasGlesComposition(int32_t id) const {
722     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
723         return true;
724     return mDisplayData[id].hasFbComp;
725 }
726 
getAndResetReleaseFence(int32_t id)727 sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
728     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
729         return Fence::NO_FENCE;
730 
731     int fd = INVALID_OPERATION;
732     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
733         const DisplayData& disp(mDisplayData[id]);
734         if (disp.framebufferTarget) {
735             fd = disp.framebufferTarget->releaseFenceFd;
736             disp.framebufferTarget->acquireFenceFd = -1;
737             disp.framebufferTarget->releaseFenceFd = -1;
738         }
739     }
740     return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
741 }
742 
commit()743 status_t HWComposer::commit() {
744     int err = NO_ERROR;
745     if (mHwc) {
746         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
747             // On version 1.0, the OpenGL ES target surface is communicated
748             // by the (dpy, sur) fields and we are guaranteed to have only
749             // a single display.
750             mLists[0]->dpy = eglGetCurrentDisplay();
751             mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
752         }
753 
754         for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
755             DisplayData& disp(mDisplayData[i]);
756             if (disp.outbufHandle) {
757                 mLists[i]->outbuf = disp.outbufHandle;
758                 mLists[i]->outbufAcquireFenceFd =
759                         disp.outbufAcquireFence->dup();
760             }
761         }
762 
763         err = mHwc->set(mHwc, mNumDisplays, mLists);
764 
765         for (size_t i=0 ; i<mNumDisplays ; i++) {
766             DisplayData& disp(mDisplayData[i]);
767             disp.lastDisplayFence = disp.lastRetireFence;
768             disp.lastRetireFence = Fence::NO_FENCE;
769             if (disp.list) {
770                 if (disp.list->retireFenceFd != -1) {
771                     disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
772                     disp.list->retireFenceFd = -1;
773                 }
774                 disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
775             }
776         }
777     }
778     return (status_t)err;
779 }
780 
setPowerMode(int disp,int mode)781 status_t HWComposer::setPowerMode(int disp, int mode) {
782     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
783     if (mHwc) {
784         if (mode == HWC_POWER_MODE_OFF) {
785             eventControl(disp, HWC_EVENT_VSYNC, 0);
786         }
787         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
788             return (status_t)mHwc->setPowerMode(mHwc, disp, mode);
789         } else {
790             return (status_t)mHwc->blank(mHwc, disp,
791                     mode == HWC_POWER_MODE_OFF ? 1 : 0);
792         }
793     }
794     return NO_ERROR;
795 }
796 
setActiveConfig(int disp,int mode)797 status_t HWComposer::setActiveConfig(int disp, int mode) {
798     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
799     DisplayData& dd(mDisplayData[disp]);
800     dd.currentConfig = mode;
801     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
802         return (status_t)mHwc->setActiveConfig(mHwc, disp, mode);
803     } else {
804         LOG_FATAL_IF(mode != 0);
805     }
806     return NO_ERROR;
807 }
808 
disconnectDisplay(int disp)809 void HWComposer::disconnectDisplay(int disp) {
810     LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
811     DisplayData& dd(mDisplayData[disp]);
812     free(dd.list);
813     dd.list = NULL;
814     dd.framebufferTarget = NULL;    // points into dd.list
815     dd.fbTargetHandle = NULL;
816     dd.outbufHandle = NULL;
817     dd.lastRetireFence = Fence::NO_FENCE;
818     dd.lastDisplayFence = Fence::NO_FENCE;
819     dd.outbufAcquireFence = Fence::NO_FENCE;
820     // clear all the previous configs and repopulate when a new
821     // device is added
822     dd.configs.clear();
823 }
824 
getVisualID() const825 int HWComposer::getVisualID() const {
826     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
827         // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
828         // is supported by the implementation. we can only be in this case
829         // if we have HWC 1.1
830         return HAL_PIXEL_FORMAT_RGBA_8888;
831         //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
832     } else {
833         return mFbDev->format;
834     }
835 }
836 
supportsFramebufferTarget() const837 bool HWComposer::supportsFramebufferTarget() const {
838     return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
839 }
840 
fbPost(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buffer)841 int HWComposer::fbPost(int32_t id,
842         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
843     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
844         return setFramebufferTarget(id, acquireFence, buffer);
845     } else {
846         acquireFence->waitForever("HWComposer::fbPost");
847         return mFbDev->post(mFbDev, buffer->handle);
848     }
849 }
850 
fbCompositionComplete()851 int HWComposer::fbCompositionComplete() {
852     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
853         return NO_ERROR;
854 
855     if (mFbDev->compositionComplete) {
856         return mFbDev->compositionComplete(mFbDev);
857     } else {
858         return INVALID_OPERATION;
859     }
860 }
861 
fbDump(String8 & result)862 void HWComposer::fbDump(String8& result) {
863     if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
864         const size_t SIZE = 4096;
865         char buffer[SIZE];
866         mFbDev->dump(mFbDev, buffer, SIZE);
867         result.append(buffer);
868     }
869 }
870 
setOutputBuffer(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buf)871 status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
872         const sp<GraphicBuffer>& buf) {
873     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
874         return BAD_INDEX;
875     if (id < VIRTUAL_DISPLAY_ID_BASE)
876         return INVALID_OPERATION;
877 
878     DisplayData& disp(mDisplayData[id]);
879     disp.outbufHandle = buf->handle;
880     disp.outbufAcquireFence = acquireFence;
881     return NO_ERROR;
882 }
883 
getLastRetireFence(int32_t id) const884 sp<Fence> HWComposer::getLastRetireFence(int32_t id) const {
885     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
886         return Fence::NO_FENCE;
887     return mDisplayData[id].lastRetireFence;
888 }
889 
setCursorPositionAsync(int32_t id,const Rect & pos)890 status_t HWComposer::setCursorPositionAsync(int32_t id, const Rect& pos)
891 {
892     if (mHwc->setCursorPositionAsync) {
893         return (status_t)mHwc->setCursorPositionAsync(mHwc, id, pos.left, pos.top);
894     }
895     else {
896         return NO_ERROR;
897     }
898 }
899 
900 /*
901  * Helper template to implement a concrete HWCLayer
902  * This holds the pointer to the concrete hwc layer type
903  * and implements the "iterable" side of HWCLayer.
904  */
905 template<typename CONCRETE, typename HWCTYPE>
906 class Iterable : public HWComposer::HWCLayer {
907 protected:
908     HWCTYPE* const mLayerList;
909     HWCTYPE* mCurrentLayer;
Iterable(HWCTYPE * layer)910     Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
getLayer() const911     inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
getLayer()912     inline HWCTYPE* getLayer() { return mCurrentLayer; }
~Iterable()913     virtual ~Iterable() { }
914 private:
915     // returns a copy of ourselves
dup()916     virtual HWComposer::HWCLayer* dup() {
917         return new CONCRETE( static_cast<const CONCRETE&>(*this) );
918     }
setLayer(size_t index)919     virtual status_t setLayer(size_t index) {
920         mCurrentLayer = &mLayerList[index];
921         return NO_ERROR;
922     }
923 };
924 
925 /*
926  * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
927  * This implements the HWCLayer side of HWCIterableLayer.
928  */
929 class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
930     struct hwc_composer_device_1* mHwc;
931 public:
HWCLayerVersion1(struct hwc_composer_device_1 * hwc,hwc_layer_1_t * layer)932     HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer)
933         : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc) { }
934 
getCompositionType() const935     virtual int32_t getCompositionType() const {
936         return getLayer()->compositionType;
937     }
getHints() const938     virtual uint32_t getHints() const {
939         return getLayer()->hints;
940     }
getAndResetReleaseFence()941     virtual sp<Fence> getAndResetReleaseFence() {
942         int fd = getLayer()->releaseFenceFd;
943         getLayer()->releaseFenceFd = -1;
944         return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
945     }
setAcquireFenceFd(int fenceFd)946     virtual void setAcquireFenceFd(int fenceFd) {
947         getLayer()->acquireFenceFd = fenceFd;
948     }
setPerFrameDefaultState()949     virtual void setPerFrameDefaultState() {
950         //getLayer()->compositionType = HWC_FRAMEBUFFER;
951     }
setPlaneAlpha(uint8_t alpha)952     virtual void setPlaneAlpha(uint8_t alpha) {
953         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
954             getLayer()->planeAlpha = alpha;
955         } else {
956             if (alpha < 0xFF) {
957                 getLayer()->flags |= HWC_SKIP_LAYER;
958             }
959         }
960     }
setDefaultState()961     virtual void setDefaultState() {
962         hwc_layer_1_t* const l = getLayer();
963         l->compositionType = HWC_FRAMEBUFFER;
964         l->hints = 0;
965         l->flags = HWC_SKIP_LAYER;
966         l->handle = 0;
967         l->transform = 0;
968         l->blending = HWC_BLENDING_NONE;
969         l->visibleRegionScreen.numRects = 0;
970         l->visibleRegionScreen.rects = NULL;
971         l->acquireFenceFd = -1;
972         l->releaseFenceFd = -1;
973         l->planeAlpha = 0xFF;
974     }
setSkip(bool skip)975     virtual void setSkip(bool skip) {
976         if (skip) {
977             getLayer()->flags |= HWC_SKIP_LAYER;
978         } else {
979             getLayer()->flags &= ~HWC_SKIP_LAYER;
980         }
981     }
setIsCursorLayerHint(bool isCursor)982     virtual void setIsCursorLayerHint(bool isCursor) {
983         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
984             if (isCursor) {
985                 getLayer()->flags |= HWC_IS_CURSOR_LAYER;
986             }
987             else {
988                 getLayer()->flags &= ~HWC_IS_CURSOR_LAYER;
989             }
990         }
991     }
setBlending(uint32_t blending)992     virtual void setBlending(uint32_t blending) {
993         getLayer()->blending = blending;
994     }
setTransform(uint32_t transform)995     virtual void setTransform(uint32_t transform) {
996         getLayer()->transform = transform;
997     }
setFrame(const Rect & frame)998     virtual void setFrame(const Rect& frame) {
999         getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
1000     }
setCrop(const FloatRect & crop)1001     virtual void setCrop(const FloatRect& crop) {
1002         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1003             getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
1004         } else {
1005             /*
1006              * Since h/w composer didn't support a flot crop rect before version 1.3,
1007              * using integer coordinates instead produces a different output from the GL code in
1008              * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
1009              * window size ratio is large and a window crop is defined
1010              * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
1011              */
1012             hwc_rect_t& r = getLayer()->sourceCrop;
1013             r.left  = int(ceilf(crop.left));
1014             r.top   = int(ceilf(crop.top));
1015             r.right = int(floorf(crop.right));
1016             r.bottom= int(floorf(crop.bottom));
1017         }
1018     }
setVisibleRegionScreen(const Region & reg)1019     virtual void setVisibleRegionScreen(const Region& reg) {
1020         // Region::getSharedBuffer creates a reference to the underlying
1021         // SharedBuffer of this Region, this reference is freed
1022         // in onDisplayed()
1023         hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1024         SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
1025         visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
1026     }
setSurfaceDamage(const Region & reg)1027     virtual void setSurfaceDamage(const Region& reg) {
1028         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_5)) {
1029             return;
1030         }
1031         hwc_region_t& surfaceDamage = getLayer()->surfaceDamage;
1032         // We encode default full-screen damage as INVALID_RECT upstream, but as
1033         // 0 rects for HWComposer
1034         if (reg.isRect() && reg.getBounds() == Rect::INVALID_RECT) {
1035             surfaceDamage.numRects = 0;
1036             surfaceDamage.rects = NULL;
1037             return;
1038         }
1039         SharedBuffer const* sb = reg.getSharedBuffer(&surfaceDamage.numRects);
1040         surfaceDamage.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
1041     }
setSidebandStream(const sp<NativeHandle> & stream)1042     virtual void setSidebandStream(const sp<NativeHandle>& stream) {
1043         ALOG_ASSERT(stream->handle() != NULL);
1044         getLayer()->compositionType = HWC_SIDEBAND;
1045         getLayer()->sidebandStream = stream->handle();
1046     }
setBuffer(const sp<GraphicBuffer> & buffer)1047     virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
1048         if (buffer == 0 || buffer->handle == 0) {
1049             getLayer()->compositionType = HWC_FRAMEBUFFER;
1050             getLayer()->flags |= HWC_SKIP_LAYER;
1051             getLayer()->handle = 0;
1052         } else {
1053             if (getLayer()->compositionType == HWC_SIDEBAND) {
1054                 // If this was a sideband layer but the stream was removed, reset
1055                 // it to FRAMEBUFFER. The HWC can change it to OVERLAY in prepare.
1056                 getLayer()->compositionType = HWC_FRAMEBUFFER;
1057             }
1058             getLayer()->handle = buffer->handle;
1059         }
1060     }
onDisplayed()1061     virtual void onDisplayed() {
1062         hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1063         SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
1064         if (sb) {
1065             sb->release();
1066             // not technically needed but safer
1067             visibleRegion.numRects = 0;
1068             visibleRegion.rects = NULL;
1069         }
1070 
1071         getLayer()->acquireFenceFd = -1;
1072 
1073         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_5)) {
1074             return;
1075         }
1076 
1077         hwc_region_t& surfaceDamage = getLayer()->surfaceDamage;
1078         sb = SharedBuffer::bufferFromData(surfaceDamage.rects);
1079         if (sb) {
1080             sb->release();
1081             surfaceDamage.numRects = 0;
1082             surfaceDamage.rects = NULL;
1083         }
1084     }
1085 };
1086 
1087 /*
1088  * returns an iterator initialized at a given index in the layer list
1089  */
getLayerIterator(int32_t id,size_t index)1090 HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
1091     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
1092         return LayerListIterator();
1093     }
1094     const DisplayData& disp(mDisplayData[id]);
1095     if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
1096         return LayerListIterator();
1097     }
1098     return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers), index);
1099 }
1100 
1101 /*
1102  * returns an iterator on the beginning of the layer list
1103  */
begin(int32_t id)1104 HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
1105     return getLayerIterator(id, 0);
1106 }
1107 
1108 /*
1109  * returns an iterator on the end of the layer list
1110  */
end(int32_t id)1111 HWComposer::LayerListIterator HWComposer::end(int32_t id) {
1112     size_t numLayers = 0;
1113     if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
1114         const DisplayData& disp(mDisplayData[id]);
1115         if (mHwc && disp.list) {
1116             numLayers = disp.list->numHwLayers;
1117             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
1118                 // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
1119                 // which we ignore when iterating through the layer list.
1120                 ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
1121                 if (numLayers) {
1122                     numLayers--;
1123                 }
1124             }
1125         }
1126     }
1127     return getLayerIterator(id, numLayers);
1128 }
1129 
1130 // Converts a PixelFormat to a human-readable string.  Max 11 chars.
1131 // (Could use a table of prefab String8 objects.)
getFormatStr(PixelFormat format)1132 static String8 getFormatStr(PixelFormat format) {
1133     switch (format) {
1134     case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
1135     case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
1136     case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
1137     case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
1138     case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
1139     case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1140                                     return String8("ImplDef");
1141     default:
1142         String8 result;
1143         result.appendFormat("? %08x", format);
1144         return result;
1145     }
1146 }
1147 
dump(String8 & result) const1148 void HWComposer::dump(String8& result) const {
1149     Mutex::Autolock _l(mDisplayLock);
1150     if (mHwc) {
1151         result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
1152         result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
1153         for (size_t i=0 ; i<mNumDisplays ; i++) {
1154             const DisplayData& disp(mDisplayData[i]);
1155             if (!disp.connected)
1156                 continue;
1157 
1158             const Vector< sp<Layer> >& visibleLayersSortedByZ =
1159                     mFlinger->getLayerSortedByZForHwcDisplay(i);
1160 
1161 
1162             result.appendFormat("  Display[%zd] configurations (* current):\n", i);
1163             for (size_t c = 0; c < disp.configs.size(); ++c) {
1164                 const DisplayConfig& config(disp.configs[c]);
1165                 result.appendFormat("    %s%zd: %ux%u, xdpi=%f, ydpi=%f, refresh=%" PRId64 "\n",
1166                         c == disp.currentConfig ? "* " : "", c, config.width, config.height,
1167                         config.xdpi, config.ydpi, config.refresh);
1168             }
1169 
1170             if (disp.list) {
1171                 result.appendFormat(
1172                         "  numHwLayers=%zu, flags=%08x\n",
1173                         disp.list->numHwLayers, disp.list->flags);
1174 
1175                 result.append(
1176                         "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
1177                         "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
1178                 //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
1179                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
1180                     const hwc_layer_1_t&l = disp.list->hwLayers[i];
1181                     int32_t format = -1;
1182                     String8 name("unknown");
1183 
1184                     if (i < visibleLayersSortedByZ.size()) {
1185                         const sp<Layer>& layer(visibleLayersSortedByZ[i]);
1186                         const sp<GraphicBuffer>& buffer(
1187                                 layer->getActiveBuffer());
1188                         if (buffer != NULL) {
1189                             format = buffer->getPixelFormat();
1190                         }
1191                         name = layer->getName();
1192                     }
1193 
1194                     int type = l.compositionType;
1195                     if (type == HWC_FRAMEBUFFER_TARGET) {
1196                         name = "HWC_FRAMEBUFFER_TARGET";
1197                         format = disp.format;
1198                     }
1199 
1200                     static char const* compositionTypeName[] = {
1201                             "GLES",
1202                             "HWC",
1203                             "BKGND",
1204                             "FB TARGET",
1205                             "SIDEBAND",
1206                             "HWC_CURSOR",
1207                             "UNKNOWN"};
1208                     if (type >= NELEM(compositionTypeName))
1209                         type = NELEM(compositionTypeName) - 1;
1210 
1211                     String8 formatStr = getFormatStr(format);
1212                     if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1213                         result.appendFormat(
1214                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
1215                                         compositionTypeName[type],
1216                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1217                                         l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
1218                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1219                                         name.string());
1220                     } else {
1221                         result.appendFormat(
1222                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
1223                                         compositionTypeName[type],
1224                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1225                                         l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
1226                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1227                                         name.string());
1228                     }
1229                 }
1230             }
1231         }
1232     }
1233 
1234     if (mHwc && mHwc->dump) {
1235         const size_t SIZE = 4096;
1236         char buffer[SIZE];
1237         mHwc->dump(mHwc, buffer, SIZE);
1238         result.append(buffer);
1239     }
1240 }
1241 
1242 // ---------------------------------------------------------------------------
1243 
VSyncThread(HWComposer & hwc)1244 HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1245     : mHwc(hwc), mEnabled(false),
1246       mNextFakeVSync(0),
1247       mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1248 {
1249 }
1250 
setEnabled(bool enabled)1251 void HWComposer::VSyncThread::setEnabled(bool enabled) {
1252     Mutex::Autolock _l(mLock);
1253     if (mEnabled != enabled) {
1254         mEnabled = enabled;
1255         mCondition.signal();
1256     }
1257 }
1258 
onFirstRef()1259 void HWComposer::VSyncThread::onFirstRef() {
1260     run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1261 }
1262 
threadLoop()1263 bool HWComposer::VSyncThread::threadLoop() {
1264     { // scope for lock
1265         Mutex::Autolock _l(mLock);
1266         while (!mEnabled) {
1267             mCondition.wait(mLock);
1268         }
1269     }
1270 
1271     const nsecs_t period = mRefreshPeriod;
1272     const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1273     nsecs_t next_vsync = mNextFakeVSync;
1274     nsecs_t sleep = next_vsync - now;
1275     if (sleep < 0) {
1276         // we missed, find where the next vsync should be
1277         sleep = (period - ((now - next_vsync) % period));
1278         next_vsync = now + sleep;
1279     }
1280     mNextFakeVSync = next_vsync + period;
1281 
1282     struct timespec spec;
1283     spec.tv_sec  = next_vsync / 1000000000;
1284     spec.tv_nsec = next_vsync % 1000000000;
1285 
1286     int err;
1287     do {
1288         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1289     } while (err<0 && errno == EINTR);
1290 
1291     if (err == 0) {
1292         mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1293     }
1294 
1295     return true;
1296 }
1297 
DisplayData()1298 HWComposer::DisplayData::DisplayData()
1299 :   configs(),
1300     currentConfig(0),
1301     format(HAL_PIXEL_FORMAT_RGBA_8888),
1302     connected(false),
1303     hasFbComp(false), hasOvComp(false),
1304     capacity(0), list(NULL),
1305     framebufferTarget(NULL), fbTargetHandle(0),
1306     lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1307     outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
1308     events(0)
1309 {}
1310 
~DisplayData()1311 HWComposer::DisplayData::~DisplayData() {
1312     free(list);
1313 }
1314 
1315 // ---------------------------------------------------------------------------
1316 }; // namespace android
1317