• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 == HWC_DISPLAY_PRIMARY || 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     mEventHandler.onHotplugReceived(disp, bool(connected));
315 }
316 
getDefaultDensity(uint32_t width,uint32_t height)317 static float getDefaultDensity(uint32_t width, uint32_t height) {
318     // Default density is based on TVs: 1080p displays get XHIGH density,
319     // lower-resolution displays get TV density. Maybe eventually we'll need
320     // to update it for 4K displays, though hopefully those just report
321     // accurate DPI information to begin with. This is also used for virtual
322     // displays and even primary displays with older hwcomposers, so be
323     // careful about orientation.
324 
325     uint32_t h = width < height ? width : height;
326     if (h >= 1080) return ACONFIGURATION_DENSITY_XHIGH;
327     else           return ACONFIGURATION_DENSITY_TV;
328 }
329 
330 static const uint32_t DISPLAY_ATTRIBUTES[] = {
331     HWC_DISPLAY_VSYNC_PERIOD,
332     HWC_DISPLAY_WIDTH,
333     HWC_DISPLAY_HEIGHT,
334     HWC_DISPLAY_DPI_X,
335     HWC_DISPLAY_DPI_Y,
336     HWC_DISPLAY_NO_ATTRIBUTE,
337 };
338 #define NUM_DISPLAY_ATTRIBUTES (sizeof(DISPLAY_ATTRIBUTES) / sizeof(DISPLAY_ATTRIBUTES)[0])
339 
queryDisplayProperties(int disp)340 status_t HWComposer::queryDisplayProperties(int disp) {
341 
342     LOG_ALWAYS_FATAL_IF(!mHwc || !hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
343 
344     // use zero as default value for unspecified attributes
345     int32_t values[NUM_DISPLAY_ATTRIBUTES - 1];
346     memset(values, 0, sizeof(values));
347 
348     const size_t MAX_NUM_CONFIGS = 128;
349     uint32_t configs[MAX_NUM_CONFIGS] = {0};
350     size_t numConfigs = MAX_NUM_CONFIGS;
351     status_t err = mHwc->getDisplayConfigs(mHwc, disp, configs, &numConfigs);
352     if (err != NO_ERROR) {
353         // this can happen if an unpluggable display is not connected
354         mDisplayData[disp].connected = false;
355         return err;
356     }
357 
358     mDisplayData[disp].currentConfig = 0;
359     for (size_t c = 0; c < numConfigs; ++c) {
360         err = mHwc->getDisplayAttributes(mHwc, disp, configs[c],
361                 DISPLAY_ATTRIBUTES, values);
362         if (err != NO_ERROR) {
363             // we can't get this display's info. turn it off.
364             mDisplayData[disp].connected = false;
365             return err;
366         }
367 
368         DisplayConfig config = DisplayConfig();
369         for (size_t i = 0; i < NUM_DISPLAY_ATTRIBUTES - 1; i++) {
370             switch (DISPLAY_ATTRIBUTES[i]) {
371                 case HWC_DISPLAY_VSYNC_PERIOD:
372                     config.refresh = nsecs_t(values[i]);
373                     break;
374                 case HWC_DISPLAY_WIDTH:
375                     config.width = values[i];
376                     break;
377                 case HWC_DISPLAY_HEIGHT:
378                     config.height = values[i];
379                     break;
380                 case HWC_DISPLAY_DPI_X:
381                     config.xdpi = values[i] / 1000.0f;
382                     break;
383                 case HWC_DISPLAY_DPI_Y:
384                     config.ydpi = values[i] / 1000.0f;
385                     break;
386                 default:
387                     ALOG_ASSERT(false, "unknown display attribute[%zu] %#x",
388                             i, DISPLAY_ATTRIBUTES[i]);
389                     break;
390             }
391         }
392 
393         if (config.xdpi == 0.0f || config.ydpi == 0.0f) {
394             float dpi = getDefaultDensity(config.width, config.height);
395             config.xdpi = dpi;
396             config.ydpi = dpi;
397         }
398 
399         mDisplayData[disp].configs.push_back(config);
400     }
401 
402     // FIXME: what should we set the format to?
403     mDisplayData[disp].format = HAL_PIXEL_FORMAT_RGBA_8888;
404     mDisplayData[disp].connected = true;
405     return NO_ERROR;
406 }
407 
setVirtualDisplayProperties(int32_t id,uint32_t w,uint32_t h,uint32_t format)408 status_t HWComposer::setVirtualDisplayProperties(int32_t id,
409         uint32_t w, uint32_t h, uint32_t format) {
410     if (id < VIRTUAL_DISPLAY_ID_BASE || id >= int32_t(mNumDisplays) ||
411             !mAllocatedDisplayIDs.hasBit(id)) {
412         return BAD_INDEX;
413     }
414     size_t configId = mDisplayData[id].currentConfig;
415     mDisplayData[id].format = format;
416     DisplayConfig& config = mDisplayData[id].configs.editItemAt(configId);
417     config.width = w;
418     config.height = h;
419     config.xdpi = config.ydpi = getDefaultDensity(w, h);
420     return NO_ERROR;
421 }
422 
allocateDisplayId()423 int32_t HWComposer::allocateDisplayId() {
424     if (mAllocatedDisplayIDs.count() >= mNumDisplays) {
425         return NO_MEMORY;
426     }
427     int32_t id = mAllocatedDisplayIDs.firstUnmarkedBit();
428     mAllocatedDisplayIDs.markBit(id);
429     mDisplayData[id].connected = true;
430     mDisplayData[id].configs.resize(1);
431     mDisplayData[id].currentConfig = 0;
432     return id;
433 }
434 
freeDisplayId(int32_t id)435 status_t HWComposer::freeDisplayId(int32_t id) {
436     if (id < NUM_BUILTIN_DISPLAYS) {
437         // cannot free the reserved IDs
438         return BAD_VALUE;
439     }
440     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
441         return BAD_INDEX;
442     }
443     mAllocatedDisplayIDs.clearBit(id);
444     mDisplayData[id].connected = false;
445     return NO_ERROR;
446 }
447 
getRefreshTimestamp(int disp) const448 nsecs_t HWComposer::getRefreshTimestamp(int disp) const {
449     // this returns the last refresh timestamp.
450     // if the last one is not available, we estimate it based on
451     // the refresh period and whatever closest timestamp we have.
452     Mutex::Autolock _l(mLock);
453     nsecs_t now = systemTime(CLOCK_MONOTONIC);
454     size_t configId = mDisplayData[disp].currentConfig;
455     return now - ((now - mLastHwVSync[disp]) %
456             mDisplayData[disp].configs[configId].refresh);
457 }
458 
getDisplayFence(int disp) const459 sp<Fence> HWComposer::getDisplayFence(int disp) const {
460     return mDisplayData[disp].lastDisplayFence;
461 }
462 
getFormat(int disp) const463 uint32_t HWComposer::getFormat(int disp) const {
464     if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
465         return HAL_PIXEL_FORMAT_RGBA_8888;
466     } else {
467         return mDisplayData[disp].format;
468     }
469 }
470 
isConnected(int disp) const471 bool HWComposer::isConnected(int disp) const {
472     return mDisplayData[disp].connected;
473 }
474 
getWidth(int disp) const475 uint32_t HWComposer::getWidth(int disp) const {
476     size_t currentConfig = mDisplayData[disp].currentConfig;
477     return mDisplayData[disp].configs[currentConfig].width;
478 }
479 
getHeight(int disp) const480 uint32_t HWComposer::getHeight(int disp) const {
481     size_t currentConfig = mDisplayData[disp].currentConfig;
482     return mDisplayData[disp].configs[currentConfig].height;
483 }
484 
getDpiX(int disp) const485 float HWComposer::getDpiX(int disp) const {
486     size_t currentConfig = mDisplayData[disp].currentConfig;
487     return mDisplayData[disp].configs[currentConfig].xdpi;
488 }
489 
getDpiY(int disp) const490 float HWComposer::getDpiY(int disp) const {
491     size_t currentConfig = mDisplayData[disp].currentConfig;
492     return mDisplayData[disp].configs[currentConfig].ydpi;
493 }
494 
getRefreshPeriod(int disp) const495 nsecs_t HWComposer::getRefreshPeriod(int disp) const {
496     size_t currentConfig = mDisplayData[disp].currentConfig;
497     return mDisplayData[disp].configs[currentConfig].refresh;
498 }
499 
getConfigs(int disp) const500 const Vector<HWComposer::DisplayConfig>& HWComposer::getConfigs(int disp) const {
501     return mDisplayData[disp].configs;
502 }
503 
getCurrentConfig(int disp) const504 size_t HWComposer::getCurrentConfig(int disp) const {
505     return mDisplayData[disp].currentConfig;
506 }
507 
eventControl(int disp,int event,int enabled)508 void HWComposer::eventControl(int disp, int event, int enabled) {
509     if (uint32_t(disp)>31 || !mAllocatedDisplayIDs.hasBit(disp)) {
510         ALOGD("eventControl ignoring event %d on unallocated disp %d (en=%d)",
511               event, disp, enabled);
512         return;
513     }
514     if (event != EVENT_VSYNC) {
515         ALOGW("eventControl got unexpected event %d (disp=%d en=%d)",
516               event, disp, enabled);
517         return;
518     }
519     status_t err = NO_ERROR;
520     if (mHwc && !mDebugForceFakeVSync) {
521         // NOTE: we use our own internal lock here because we have to call
522         // into the HWC with the lock held, and we want to make sure
523         // that even if HWC blocks (which it shouldn't), it won't
524         // affect other threads.
525         Mutex::Autolock _l(mEventControlLock);
526         const int32_t eventBit = 1UL << event;
527         const int32_t newValue = enabled ? eventBit : 0;
528         const int32_t oldValue = mDisplayData[disp].events & eventBit;
529         if (newValue != oldValue) {
530             ATRACE_CALL();
531             err = mHwc->eventControl(mHwc, disp, event, enabled);
532             if (!err) {
533                 int32_t& events(mDisplayData[disp].events);
534                 events = (events & ~eventBit) | newValue;
535 
536                 char tag[16];
537                 snprintf(tag, sizeof(tag), "HW_VSYNC_ON_%1u", disp);
538                 ATRACE_INT(tag, enabled);
539             }
540         }
541         // error here should not happen -- not sure what we should
542         // do if it does.
543         ALOGE_IF(err, "eventControl(%d, %d) failed %s",
544                 event, enabled, strerror(-err));
545     }
546 
547     if (err == NO_ERROR && mVSyncThread != NULL) {
548         mVSyncThread->setEnabled(enabled);
549     }
550 }
551 
createWorkList(int32_t id,size_t numLayers)552 status_t HWComposer::createWorkList(int32_t id, size_t numLayers) {
553     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
554         return BAD_INDEX;
555     }
556 
557     if (mHwc) {
558         DisplayData& disp(mDisplayData[id]);
559         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
560             // we need space for the HWC_FRAMEBUFFER_TARGET
561             numLayers++;
562         }
563         if (disp.capacity < numLayers || disp.list == NULL) {
564             size_t size = sizeof(hwc_display_contents_1_t)
565                     + numLayers * sizeof(hwc_layer_1_t);
566             free(disp.list);
567             disp.list = (hwc_display_contents_1_t*)malloc(size);
568             disp.capacity = numLayers;
569         }
570         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
571             disp.framebufferTarget = &disp.list->hwLayers[numLayers - 1];
572             memset(disp.framebufferTarget, 0, sizeof(hwc_layer_1_t));
573             const DisplayConfig& currentConfig =
574                     disp.configs[disp.currentConfig];
575             const hwc_rect_t r = { 0, 0,
576                     (int) currentConfig.width, (int) currentConfig.height };
577             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
578             disp.framebufferTarget->hints = 0;
579             disp.framebufferTarget->flags = 0;
580             disp.framebufferTarget->handle = disp.fbTargetHandle;
581             disp.framebufferTarget->transform = 0;
582             disp.framebufferTarget->blending = HWC_BLENDING_PREMULT;
583             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
584                 disp.framebufferTarget->sourceCropf.left = 0;
585                 disp.framebufferTarget->sourceCropf.top = 0;
586                 disp.framebufferTarget->sourceCropf.right =
587                         currentConfig.width;
588                 disp.framebufferTarget->sourceCropf.bottom =
589                         currentConfig.height;
590             } else {
591                 disp.framebufferTarget->sourceCrop = r;
592             }
593             disp.framebufferTarget->displayFrame = r;
594             disp.framebufferTarget->visibleRegionScreen.numRects = 1;
595             disp.framebufferTarget->visibleRegionScreen.rects =
596                 &disp.framebufferTarget->displayFrame;
597             disp.framebufferTarget->acquireFenceFd = -1;
598             disp.framebufferTarget->releaseFenceFd = -1;
599             disp.framebufferTarget->planeAlpha = 0xFF;
600         }
601         disp.list->retireFenceFd = -1;
602         disp.list->flags = HWC_GEOMETRY_CHANGED;
603         disp.list->numHwLayers = numLayers;
604     }
605     return NO_ERROR;
606 }
607 
setFramebufferTarget(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buf)608 status_t HWComposer::setFramebufferTarget(int32_t id,
609         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buf) {
610     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
611         return BAD_INDEX;
612     }
613     DisplayData& disp(mDisplayData[id]);
614     if (!disp.framebufferTarget) {
615         // this should never happen, but apparently eglCreateWindowSurface()
616         // triggers a Surface::queueBuffer()  on some
617         // devices (!?) -- log and ignore.
618         ALOGE("HWComposer: framebufferTarget is null");
619         return NO_ERROR;
620     }
621 
622     int acquireFenceFd = -1;
623     if (acquireFence->isValid()) {
624         acquireFenceFd = acquireFence->dup();
625     }
626 
627     // ALOGD("fbPost: handle=%p, fence=%d", buf->handle, acquireFenceFd);
628     disp.fbTargetHandle = buf->handle;
629     disp.framebufferTarget->handle = disp.fbTargetHandle;
630     disp.framebufferTarget->acquireFenceFd = acquireFenceFd;
631     return NO_ERROR;
632 }
633 
prepare()634 status_t HWComposer::prepare() {
635     for (size_t i=0 ; i<mNumDisplays ; i++) {
636         DisplayData& disp(mDisplayData[i]);
637         if (disp.framebufferTarget) {
638             // make sure to reset the type to HWC_FRAMEBUFFER_TARGET
639             // DO NOT reset the handle field to NULL, because it's possible
640             // that we have nothing to redraw (eg: eglSwapBuffers() not called)
641             // in which case, we should continue to use the same buffer.
642             LOG_FATAL_IF(disp.list == NULL);
643             disp.framebufferTarget->compositionType = HWC_FRAMEBUFFER_TARGET;
644         }
645         if (!disp.connected && disp.list != NULL) {
646             ALOGW("WARNING: disp %zu: connected, non-null list, layers=%zu",
647                   i, disp.list->numHwLayers);
648         }
649         mLists[i] = disp.list;
650         if (mLists[i]) {
651             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
652                 mLists[i]->outbuf = disp.outbufHandle;
653                 mLists[i]->outbufAcquireFenceFd = -1;
654             } else if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
655                 // garbage data to catch improper use
656                 mLists[i]->dpy = (hwc_display_t)0xDEADBEEF;
657                 mLists[i]->sur = (hwc_surface_t)0xDEADBEEF;
658             } else {
659                 mLists[i]->dpy = EGL_NO_DISPLAY;
660                 mLists[i]->sur = EGL_NO_SURFACE;
661             }
662         }
663     }
664 
665     int err = mHwc->prepare(mHwc, mNumDisplays, mLists);
666     ALOGE_IF(err, "HWComposer: prepare failed (%s)", strerror(-err));
667 
668     if (err == NO_ERROR) {
669         // here we're just making sure that "skip" layers are set
670         // to HWC_FRAMEBUFFER and we're also counting how many layers
671         // we have of each type.
672         //
673         // If there are no window layers, we treat the display has having FB
674         // composition, because SurfaceFlinger will use GLES to draw the
675         // wormhole region.
676         for (size_t i=0 ; i<mNumDisplays ; i++) {
677             DisplayData& disp(mDisplayData[i]);
678             disp.hasFbComp = false;
679             disp.hasOvComp = false;
680             if (disp.list) {
681                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
682                     hwc_layer_1_t& l = disp.list->hwLayers[i];
683 
684                     //ALOGD("prepare: %d, type=%d, handle=%p",
685                     //        i, l.compositionType, l.handle);
686 
687                     if (l.flags & HWC_SKIP_LAYER) {
688                         l.compositionType = HWC_FRAMEBUFFER;
689                     }
690                     if (l.compositionType == HWC_FRAMEBUFFER) {
691                         disp.hasFbComp = true;
692                     }
693                     if (l.compositionType == HWC_OVERLAY) {
694                         disp.hasOvComp = true;
695                     }
696                     if (l.compositionType == HWC_CURSOR_OVERLAY) {
697                         disp.hasOvComp = true;
698                     }
699                 }
700                 if (disp.list->numHwLayers == (disp.framebufferTarget ? 1 : 0)) {
701                     disp.hasFbComp = true;
702                 }
703             } else {
704                 disp.hasFbComp = true;
705             }
706         }
707     }
708     return (status_t)err;
709 }
710 
hasHwcComposition(int32_t id) const711 bool HWComposer::hasHwcComposition(int32_t id) const {
712     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
713         return false;
714     return mDisplayData[id].hasOvComp;
715 }
716 
hasGlesComposition(int32_t id) const717 bool HWComposer::hasGlesComposition(int32_t id) const {
718     if (!mHwc || uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
719         return true;
720     return mDisplayData[id].hasFbComp;
721 }
722 
getAndResetReleaseFence(int32_t id)723 sp<Fence> HWComposer::getAndResetReleaseFence(int32_t id) {
724     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
725         return Fence::NO_FENCE;
726 
727     int fd = INVALID_OPERATION;
728     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
729         const DisplayData& disp(mDisplayData[id]);
730         if (disp.framebufferTarget) {
731             fd = disp.framebufferTarget->releaseFenceFd;
732             disp.framebufferTarget->acquireFenceFd = -1;
733             disp.framebufferTarget->releaseFenceFd = -1;
734         }
735     }
736     return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
737 }
738 
commit()739 status_t HWComposer::commit() {
740     int err = NO_ERROR;
741     if (mHwc) {
742         if (!hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
743             // On version 1.0, the OpenGL ES target surface is communicated
744             // by the (dpy, sur) fields and we are guaranteed to have only
745             // a single display.
746             mLists[0]->dpy = eglGetCurrentDisplay();
747             mLists[0]->sur = eglGetCurrentSurface(EGL_DRAW);
748         }
749 
750         for (size_t i=VIRTUAL_DISPLAY_ID_BASE; i<mNumDisplays; i++) {
751             DisplayData& disp(mDisplayData[i]);
752             if (disp.outbufHandle) {
753                 mLists[i]->outbuf = disp.outbufHandle;
754                 mLists[i]->outbufAcquireFenceFd =
755                         disp.outbufAcquireFence->dup();
756             }
757         }
758 
759         err = mHwc->set(mHwc, mNumDisplays, mLists);
760 
761         for (size_t i=0 ; i<mNumDisplays ; i++) {
762             DisplayData& disp(mDisplayData[i]);
763             disp.lastDisplayFence = disp.lastRetireFence;
764             disp.lastRetireFence = Fence::NO_FENCE;
765             if (disp.list) {
766                 if (disp.list->retireFenceFd != -1) {
767                     disp.lastRetireFence = new Fence(disp.list->retireFenceFd);
768                     disp.list->retireFenceFd = -1;
769                 }
770                 disp.list->flags &= ~HWC_GEOMETRY_CHANGED;
771             }
772         }
773     }
774     return (status_t)err;
775 }
776 
setPowerMode(int disp,int mode)777 status_t HWComposer::setPowerMode(int disp, int mode) {
778     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
779     if (mHwc) {
780         if (mode == HWC_POWER_MODE_OFF) {
781             eventControl(disp, HWC_EVENT_VSYNC, 0);
782         }
783         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
784             return (status_t)mHwc->setPowerMode(mHwc, disp, mode);
785         } else {
786             return (status_t)mHwc->blank(mHwc, disp,
787                     mode == HWC_POWER_MODE_OFF ? 1 : 0);
788         }
789     }
790     return NO_ERROR;
791 }
792 
setActiveConfig(int disp,int mode)793 status_t HWComposer::setActiveConfig(int disp, int mode) {
794     LOG_FATAL_IF(disp >= VIRTUAL_DISPLAY_ID_BASE);
795     DisplayData& dd(mDisplayData[disp]);
796     dd.currentConfig = mode;
797     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
798         return (status_t)mHwc->setActiveConfig(mHwc, disp, mode);
799     } else {
800         LOG_FATAL_IF(mode != 0);
801     }
802     return NO_ERROR;
803 }
804 
disconnectDisplay(int disp)805 void HWComposer::disconnectDisplay(int disp) {
806     LOG_ALWAYS_FATAL_IF(disp < 0 || disp == HWC_DISPLAY_PRIMARY);
807     DisplayData& dd(mDisplayData[disp]);
808     free(dd.list);
809     dd.list = NULL;
810     dd.framebufferTarget = NULL;    // points into dd.list
811     dd.fbTargetHandle = NULL;
812     dd.outbufHandle = NULL;
813     dd.lastRetireFence = Fence::NO_FENCE;
814     dd.lastDisplayFence = Fence::NO_FENCE;
815     dd.outbufAcquireFence = Fence::NO_FENCE;
816     // clear all the previous configs and repopulate when a new
817     // device is added
818     dd.configs.clear();
819 }
820 
getVisualID() const821 int HWComposer::getVisualID() const {
822     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
823         // FIXME: temporary hack until HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED
824         // is supported by the implementation. we can only be in this case
825         // if we have HWC 1.1
826         return HAL_PIXEL_FORMAT_RGBA_8888;
827         //return HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED;
828     } else {
829         return mFbDev->format;
830     }
831 }
832 
supportsFramebufferTarget() const833 bool HWComposer::supportsFramebufferTarget() const {
834     return (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1));
835 }
836 
fbPost(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buffer)837 int HWComposer::fbPost(int32_t id,
838         const sp<Fence>& acquireFence, const sp<GraphicBuffer>& buffer) {
839     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
840         return setFramebufferTarget(id, acquireFence, buffer);
841     } else {
842         acquireFence->waitForever("HWComposer::fbPost");
843         return mFbDev->post(mFbDev, buffer->handle);
844     }
845 }
846 
fbCompositionComplete()847 int HWComposer::fbCompositionComplete() {
848     if (mHwc && hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1))
849         return NO_ERROR;
850 
851     if (mFbDev->compositionComplete) {
852         return mFbDev->compositionComplete(mFbDev);
853     } else {
854         return INVALID_OPERATION;
855     }
856 }
857 
fbDump(String8 & result)858 void HWComposer::fbDump(String8& result) {
859     if (mFbDev && mFbDev->common.version >= 1 && mFbDev->dump) {
860         const size_t SIZE = 4096;
861         char buffer[SIZE];
862         mFbDev->dump(mFbDev, buffer, SIZE);
863         result.append(buffer);
864     }
865 }
866 
setOutputBuffer(int32_t id,const sp<Fence> & acquireFence,const sp<GraphicBuffer> & buf)867 status_t HWComposer::setOutputBuffer(int32_t id, const sp<Fence>& acquireFence,
868         const sp<GraphicBuffer>& buf) {
869     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
870         return BAD_INDEX;
871     if (id < VIRTUAL_DISPLAY_ID_BASE)
872         return INVALID_OPERATION;
873 
874     DisplayData& disp(mDisplayData[id]);
875     disp.outbufHandle = buf->handle;
876     disp.outbufAcquireFence = acquireFence;
877     return NO_ERROR;
878 }
879 
getLastRetireFence(int32_t id) const880 sp<Fence> HWComposer::getLastRetireFence(int32_t id) const {
881     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id))
882         return Fence::NO_FENCE;
883     return mDisplayData[id].lastRetireFence;
884 }
885 
setCursorPositionAsync(int32_t id,const Rect & pos)886 status_t HWComposer::setCursorPositionAsync(int32_t id, const Rect& pos)
887 {
888     if (mHwc->setCursorPositionAsync) {
889         return (status_t)mHwc->setCursorPositionAsync(mHwc, id, pos.left, pos.top);
890     }
891     else {
892         return NO_ERROR;
893     }
894 }
895 
896 /*
897  * Helper template to implement a concrete HWCLayer
898  * This holds the pointer to the concrete hwc layer type
899  * and implements the "iterable" side of HWCLayer.
900  */
901 template<typename CONCRETE, typename HWCTYPE>
902 class Iterable : public HWComposer::HWCLayer {
903 protected:
904     HWCTYPE* const mLayerList;
905     HWCTYPE* mCurrentLayer;
Iterable(HWCTYPE * layer)906     Iterable(HWCTYPE* layer) : mLayerList(layer), mCurrentLayer(layer) { }
getLayer() const907     inline HWCTYPE const * getLayer() const { return mCurrentLayer; }
getLayer()908     inline HWCTYPE* getLayer() { return mCurrentLayer; }
~Iterable()909     virtual ~Iterable() { }
910 private:
911     // returns a copy of ourselves
dup()912     virtual HWComposer::HWCLayer* dup() {
913         return new CONCRETE( static_cast<const CONCRETE&>(*this) );
914     }
setLayer(size_t index)915     virtual status_t setLayer(size_t index) {
916         mCurrentLayer = &mLayerList[index];
917         return NO_ERROR;
918     }
919 };
920 
921 /*
922  * Concrete implementation of HWCLayer for HWC_DEVICE_API_VERSION_1_0.
923  * This implements the HWCLayer side of HWCIterableLayer.
924  */
925 class HWCLayerVersion1 : public Iterable<HWCLayerVersion1, hwc_layer_1_t> {
926     struct hwc_composer_device_1* mHwc;
927 public:
HWCLayerVersion1(struct hwc_composer_device_1 * hwc,hwc_layer_1_t * layer)928     HWCLayerVersion1(struct hwc_composer_device_1* hwc, hwc_layer_1_t* layer)
929         : Iterable<HWCLayerVersion1, hwc_layer_1_t>(layer), mHwc(hwc) { }
930 
getCompositionType() const931     virtual int32_t getCompositionType() const {
932         return getLayer()->compositionType;
933     }
getHints() const934     virtual uint32_t getHints() const {
935         return getLayer()->hints;
936     }
getAndResetReleaseFence()937     virtual sp<Fence> getAndResetReleaseFence() {
938         int fd = getLayer()->releaseFenceFd;
939         getLayer()->releaseFenceFd = -1;
940         return fd >= 0 ? new Fence(fd) : Fence::NO_FENCE;
941     }
setAcquireFenceFd(int fenceFd)942     virtual void setAcquireFenceFd(int fenceFd) {
943         getLayer()->acquireFenceFd = fenceFd;
944     }
setPerFrameDefaultState()945     virtual void setPerFrameDefaultState() {
946         //getLayer()->compositionType = HWC_FRAMEBUFFER;
947     }
setPlaneAlpha(uint8_t alpha)948     virtual void setPlaneAlpha(uint8_t alpha) {
949         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_2)) {
950             getLayer()->planeAlpha = alpha;
951         } else {
952             if (alpha < 0xFF) {
953                 getLayer()->flags |= HWC_SKIP_LAYER;
954             }
955         }
956     }
setDefaultState()957     virtual void setDefaultState() {
958         hwc_layer_1_t* const l = getLayer();
959         l->compositionType = HWC_FRAMEBUFFER;
960         l->hints = 0;
961         l->flags = HWC_SKIP_LAYER;
962         l->handle = 0;
963         l->transform = 0;
964         l->blending = HWC_BLENDING_NONE;
965         l->visibleRegionScreen.numRects = 0;
966         l->visibleRegionScreen.rects = NULL;
967         l->acquireFenceFd = -1;
968         l->releaseFenceFd = -1;
969         l->planeAlpha = 0xFF;
970     }
setSkip(bool skip)971     virtual void setSkip(bool skip) {
972         if (skip) {
973             getLayer()->flags |= HWC_SKIP_LAYER;
974         } else {
975             getLayer()->flags &= ~HWC_SKIP_LAYER;
976         }
977     }
setIsCursorLayerHint(bool isCursor)978     virtual void setIsCursorLayerHint(bool isCursor) {
979         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_4)) {
980             if (isCursor) {
981                 getLayer()->flags |= HWC_IS_CURSOR_LAYER;
982             }
983             else {
984                 getLayer()->flags &= ~HWC_IS_CURSOR_LAYER;
985             }
986         }
987     }
setBlending(uint32_t blending)988     virtual void setBlending(uint32_t blending) {
989         getLayer()->blending = blending;
990     }
setTransform(uint32_t transform)991     virtual void setTransform(uint32_t transform) {
992         getLayer()->transform = transform;
993     }
setFrame(const Rect & frame)994     virtual void setFrame(const Rect& frame) {
995         getLayer()->displayFrame = reinterpret_cast<hwc_rect_t const&>(frame);
996     }
setCrop(const FloatRect & crop)997     virtual void setCrop(const FloatRect& crop) {
998         if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
999             getLayer()->sourceCropf = reinterpret_cast<hwc_frect_t const&>(crop);
1000         } else {
1001             /*
1002              * Since h/w composer didn't support a flot crop rect before version 1.3,
1003              * using integer coordinates instead produces a different output from the GL code in
1004              * Layer::drawWithOpenGL(). The difference can be large if the buffer crop to
1005              * window size ratio is large and a window crop is defined
1006              * (i.e.: if we scale the buffer a lot and we also crop it with a window crop).
1007              */
1008             hwc_rect_t& r = getLayer()->sourceCrop;
1009             r.left  = int(ceilf(crop.left));
1010             r.top   = int(ceilf(crop.top));
1011             r.right = int(floorf(crop.right));
1012             r.bottom= int(floorf(crop.bottom));
1013         }
1014     }
setVisibleRegionScreen(const Region & reg)1015     virtual void setVisibleRegionScreen(const Region& reg) {
1016         // Region::getSharedBuffer creates a reference to the underlying
1017         // SharedBuffer of this Region, this reference is freed
1018         // in onDisplayed()
1019         hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1020         SharedBuffer const* sb = reg.getSharedBuffer(&visibleRegion.numRects);
1021         visibleRegion.rects = reinterpret_cast<hwc_rect_t const *>(sb->data());
1022     }
setSidebandStream(const sp<NativeHandle> & stream)1023     virtual void setSidebandStream(const sp<NativeHandle>& stream) {
1024         ALOG_ASSERT(stream->handle() != NULL);
1025         getLayer()->compositionType = HWC_SIDEBAND;
1026         getLayer()->sidebandStream = stream->handle();
1027     }
setBuffer(const sp<GraphicBuffer> & buffer)1028     virtual void setBuffer(const sp<GraphicBuffer>& buffer) {
1029         if (buffer == 0 || buffer->handle == 0) {
1030             getLayer()->compositionType = HWC_FRAMEBUFFER;
1031             getLayer()->flags |= HWC_SKIP_LAYER;
1032             getLayer()->handle = 0;
1033         } else {
1034             if (getLayer()->compositionType == HWC_SIDEBAND) {
1035                 // If this was a sideband layer but the stream was removed, reset
1036                 // it to FRAMEBUFFER. The HWC can change it to OVERLAY in prepare.
1037                 getLayer()->compositionType = HWC_FRAMEBUFFER;
1038             }
1039             getLayer()->handle = buffer->handle;
1040         }
1041     }
onDisplayed()1042     virtual void onDisplayed() {
1043         hwc_region_t& visibleRegion = getLayer()->visibleRegionScreen;
1044         SharedBuffer const* sb = SharedBuffer::bufferFromData(visibleRegion.rects);
1045         if (sb) {
1046             sb->release();
1047             // not technically needed but safer
1048             visibleRegion.numRects = 0;
1049             visibleRegion.rects = NULL;
1050         }
1051 
1052         getLayer()->acquireFenceFd = -1;
1053     }
1054 };
1055 
1056 /*
1057  * returns an iterator initialized at a given index in the layer list
1058  */
getLayerIterator(int32_t id,size_t index)1059 HWComposer::LayerListIterator HWComposer::getLayerIterator(int32_t id, size_t index) {
1060     if (uint32_t(id)>31 || !mAllocatedDisplayIDs.hasBit(id)) {
1061         return LayerListIterator();
1062     }
1063     const DisplayData& disp(mDisplayData[id]);
1064     if (!mHwc || !disp.list || index > disp.list->numHwLayers) {
1065         return LayerListIterator();
1066     }
1067     return LayerListIterator(new HWCLayerVersion1(mHwc, disp.list->hwLayers), index);
1068 }
1069 
1070 /*
1071  * returns an iterator on the beginning of the layer list
1072  */
begin(int32_t id)1073 HWComposer::LayerListIterator HWComposer::begin(int32_t id) {
1074     return getLayerIterator(id, 0);
1075 }
1076 
1077 /*
1078  * returns an iterator on the end of the layer list
1079  */
end(int32_t id)1080 HWComposer::LayerListIterator HWComposer::end(int32_t id) {
1081     size_t numLayers = 0;
1082     if (uint32_t(id) <= 31 && mAllocatedDisplayIDs.hasBit(id)) {
1083         const DisplayData& disp(mDisplayData[id]);
1084         if (mHwc && disp.list) {
1085             numLayers = disp.list->numHwLayers;
1086             if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_1)) {
1087                 // with HWC 1.1, the last layer is always the HWC_FRAMEBUFFER_TARGET,
1088                 // which we ignore when iterating through the layer list.
1089                 ALOGE_IF(!numLayers, "mDisplayData[%d].list->numHwLayers is 0", id);
1090                 if (numLayers) {
1091                     numLayers--;
1092                 }
1093             }
1094         }
1095     }
1096     return getLayerIterator(id, numLayers);
1097 }
1098 
1099 // Converts a PixelFormat to a human-readable string.  Max 11 chars.
1100 // (Could use a table of prefab String8 objects.)
getFormatStr(PixelFormat format)1101 static String8 getFormatStr(PixelFormat format) {
1102     switch (format) {
1103     case PIXEL_FORMAT_RGBA_8888:    return String8("RGBA_8888");
1104     case PIXEL_FORMAT_RGBX_8888:    return String8("RGBx_8888");
1105     case PIXEL_FORMAT_RGB_888:      return String8("RGB_888");
1106     case PIXEL_FORMAT_RGB_565:      return String8("RGB_565");
1107     case PIXEL_FORMAT_BGRA_8888:    return String8("BGRA_8888");
1108     case PIXEL_FORMAT_sRGB_A_8888:  return String8("sRGB_A_8888");
1109     case PIXEL_FORMAT_sRGB_X_8888:  return String8("sRGB_x_8888");
1110     case HAL_PIXEL_FORMAT_IMPLEMENTATION_DEFINED:
1111                                     return String8("ImplDef");
1112     default:
1113         String8 result;
1114         result.appendFormat("? %08x", format);
1115         return result;
1116     }
1117 }
1118 
dump(String8 & result) const1119 void HWComposer::dump(String8& result) const {
1120     if (mHwc) {
1121         result.appendFormat("Hardware Composer state (version %08x):\n", hwcApiVersion(mHwc));
1122         result.appendFormat("  mDebugForceFakeVSync=%d\n", mDebugForceFakeVSync);
1123         for (size_t i=0 ; i<mNumDisplays ; i++) {
1124             const DisplayData& disp(mDisplayData[i]);
1125             if (!disp.connected)
1126                 continue;
1127 
1128             const Vector< sp<Layer> >& visibleLayersSortedByZ =
1129                     mFlinger->getLayerSortedByZForHwcDisplay(i);
1130 
1131 
1132             result.appendFormat("  Display[%zd] configurations (* current):\n", i);
1133             for (size_t c = 0; c < disp.configs.size(); ++c) {
1134                 const DisplayConfig& config(disp.configs[c]);
1135                 result.appendFormat("    %s%zd: %ux%u, xdpi=%f, ydpi=%f, refresh=%" PRId64 "\n",
1136                         c == disp.currentConfig ? "* " : "", c, config.width, config.height,
1137                         config.xdpi, config.ydpi, config.refresh);
1138             }
1139 
1140             if (disp.list) {
1141                 result.appendFormat(
1142                         "  numHwLayers=%zu, flags=%08x\n",
1143                         disp.list->numHwLayers, disp.list->flags);
1144 
1145                 result.append(
1146                         "    type   |  handle  | hint | flag | tr | blnd |   format    |     source crop (l,t,r,b)      |          frame         | name \n"
1147                         "-----------+----------+------+------+----+------+-------------+--------------------------------+------------------------+------\n");
1148                 //      " _________ | ________ | ____ | ____ | __ | ____ | ___________ |_____._,_____._,_____._,_____._ |_____,_____,_____,_____ | ___...
1149                 for (size_t i=0 ; i<disp.list->numHwLayers ; i++) {
1150                     const hwc_layer_1_t&l = disp.list->hwLayers[i];
1151                     int32_t format = -1;
1152                     String8 name("unknown");
1153 
1154                     if (i < visibleLayersSortedByZ.size()) {
1155                         const sp<Layer>& layer(visibleLayersSortedByZ[i]);
1156                         const sp<GraphicBuffer>& buffer(
1157                                 layer->getActiveBuffer());
1158                         if (buffer != NULL) {
1159                             format = buffer->getPixelFormat();
1160                         }
1161                         name = layer->getName();
1162                     }
1163 
1164                     int type = l.compositionType;
1165                     if (type == HWC_FRAMEBUFFER_TARGET) {
1166                         name = "HWC_FRAMEBUFFER_TARGET";
1167                         format = disp.format;
1168                     }
1169 
1170                     static char const* compositionTypeName[] = {
1171                             "GLES",
1172                             "HWC",
1173                             "BKGND",
1174                             "FB TARGET",
1175                             "SIDEBAND",
1176                             "HWC_CURSOR",
1177                             "UNKNOWN"};
1178                     if (type >= NELEM(compositionTypeName))
1179                         type = NELEM(compositionTypeName) - 1;
1180 
1181                     String8 formatStr = getFormatStr(format);
1182                     if (hwcHasApiVersion(mHwc, HWC_DEVICE_API_VERSION_1_3)) {
1183                         result.appendFormat(
1184                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7.1f,%7.1f,%7.1f,%7.1f |%5d,%5d,%5d,%5d | %s\n",
1185                                         compositionTypeName[type],
1186                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1187                                         l.sourceCropf.left, l.sourceCropf.top, l.sourceCropf.right, l.sourceCropf.bottom,
1188                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1189                                         name.string());
1190                     } else {
1191                         result.appendFormat(
1192                                 " %9s | %08" PRIxPTR " | %04x | %04x | %02x | %04x | %-11s |%7d,%7d,%7d,%7d |%5d,%5d,%5d,%5d | %s\n",
1193                                         compositionTypeName[type],
1194                                         intptr_t(l.handle), l.hints, l.flags, l.transform, l.blending, formatStr.string(),
1195                                         l.sourceCrop.left, l.sourceCrop.top, l.sourceCrop.right, l.sourceCrop.bottom,
1196                                         l.displayFrame.left, l.displayFrame.top, l.displayFrame.right, l.displayFrame.bottom,
1197                                         name.string());
1198                     }
1199                 }
1200             }
1201         }
1202     }
1203 
1204     if (mHwc && mHwc->dump) {
1205         const size_t SIZE = 4096;
1206         char buffer[SIZE];
1207         mHwc->dump(mHwc, buffer, SIZE);
1208         result.append(buffer);
1209     }
1210 }
1211 
1212 // ---------------------------------------------------------------------------
1213 
VSyncThread(HWComposer & hwc)1214 HWComposer::VSyncThread::VSyncThread(HWComposer& hwc)
1215     : mHwc(hwc), mEnabled(false),
1216       mNextFakeVSync(0),
1217       mRefreshPeriod(hwc.getRefreshPeriod(HWC_DISPLAY_PRIMARY))
1218 {
1219 }
1220 
setEnabled(bool enabled)1221 void HWComposer::VSyncThread::setEnabled(bool enabled) {
1222     Mutex::Autolock _l(mLock);
1223     if (mEnabled != enabled) {
1224         mEnabled = enabled;
1225         mCondition.signal();
1226     }
1227 }
1228 
onFirstRef()1229 void HWComposer::VSyncThread::onFirstRef() {
1230     run("VSyncThread", PRIORITY_URGENT_DISPLAY + PRIORITY_MORE_FAVORABLE);
1231 }
1232 
threadLoop()1233 bool HWComposer::VSyncThread::threadLoop() {
1234     { // scope for lock
1235         Mutex::Autolock _l(mLock);
1236         while (!mEnabled) {
1237             mCondition.wait(mLock);
1238         }
1239     }
1240 
1241     const nsecs_t period = mRefreshPeriod;
1242     const nsecs_t now = systemTime(CLOCK_MONOTONIC);
1243     nsecs_t next_vsync = mNextFakeVSync;
1244     nsecs_t sleep = next_vsync - now;
1245     if (sleep < 0) {
1246         // we missed, find where the next vsync should be
1247         sleep = (period - ((now - next_vsync) % period));
1248         next_vsync = now + sleep;
1249     }
1250     mNextFakeVSync = next_vsync + period;
1251 
1252     struct timespec spec;
1253     spec.tv_sec  = next_vsync / 1000000000;
1254     spec.tv_nsec = next_vsync % 1000000000;
1255 
1256     int err;
1257     do {
1258         err = clock_nanosleep(CLOCK_MONOTONIC, TIMER_ABSTIME, &spec, NULL);
1259     } while (err<0 && errno == EINTR);
1260 
1261     if (err == 0) {
1262         mHwc.mEventHandler.onVSyncReceived(0, next_vsync);
1263     }
1264 
1265     return true;
1266 }
1267 
DisplayData()1268 HWComposer::DisplayData::DisplayData()
1269 :   configs(),
1270     currentConfig(0),
1271     format(HAL_PIXEL_FORMAT_RGBA_8888),
1272     connected(false),
1273     hasFbComp(false), hasOvComp(false),
1274     capacity(0), list(NULL),
1275     framebufferTarget(NULL), fbTargetHandle(0),
1276     lastRetireFence(Fence::NO_FENCE), lastDisplayFence(Fence::NO_FENCE),
1277     outbufHandle(NULL), outbufAcquireFence(Fence::NO_FENCE),
1278     events(0)
1279 {}
1280 
~DisplayData()1281 HWComposer::DisplayData::~DisplayData() {
1282     free(list);
1283 }
1284 
1285 // ---------------------------------------------------------------------------
1286 }; // namespace android
1287