SurfaceFlinger.cpp revision 4da751999358fffa4cefc4c8046dab72045925f6
1/*
2 * Copyright (C) 2007 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#include <stdlib.h>
18#include <stdio.h>
19#include <stdint.h>
20#include <unistd.h>
21#include <fcntl.h>
22#include <errno.h>
23#include <math.h>
24#include <limits.h>
25#include <sys/types.h>
26#include <sys/stat.h>
27#include <sys/ioctl.h>
28
29#include <cutils/log.h>
30#include <cutils/properties.h>
31
32#include <binder/IPCThreadState.h>
33#include <binder/IServiceManager.h>
34#include <binder/MemoryHeapBase.h>
35
36#include <utils/String8.h>
37#include <utils/String16.h>
38#include <utils/StopWatch.h>
39
40#include <ui/GraphicBufferAllocator.h>
41#include <ui/PixelFormat.h>
42
43#include <pixelflinger/pixelflinger.h>
44#include <GLES/gl.h>
45
46#include "clz.h"
47#include "GLExtensions.h"
48#include "Layer.h"
49#include "LayerBlur.h"
50#include "LayerBuffer.h"
51#include "LayerDim.h"
52#include "SurfaceFlinger.h"
53
54#include "DisplayHardware/DisplayHardware.h"
55
56/* ideally AID_GRAPHICS would be in a semi-public header
57 * or there would be a way to map a user/group name to its id
58 */
59#ifndef AID_GRAPHICS
60#define AID_GRAPHICS 1003
61#endif
62
63#define DISPLAY_COUNT       1
64
65namespace android {
66// ---------------------------------------------------------------------------
67
68SurfaceFlinger::LayerVector::LayerVector(const SurfaceFlinger::LayerVector& rhs)
69    : lookup(rhs.lookup), layers(rhs.layers)
70{
71}
72
73ssize_t SurfaceFlinger::LayerVector::indexOf(
74        const sp<LayerBase>& key, size_t guess) const
75{
76    if (guess<size() && lookup.keyAt(guess) == key)
77        return guess;
78    const ssize_t i = lookup.indexOfKey(key);
79    if (i>=0) {
80        const size_t idx = lookup.valueAt(i);
81        LOGE_IF(layers[idx]!=key,
82            "LayerVector[%p]: layers[%d]=%p, key=%p",
83            this, int(idx), layers[idx].get(), key.get());
84        return idx;
85    }
86    return i;
87}
88
89ssize_t SurfaceFlinger::LayerVector::add(
90        const sp<LayerBase>& layer,
91        Vector< sp<LayerBase> >::compar_t cmp)
92{
93    size_t count = layers.size();
94    ssize_t l = 0;
95    ssize_t h = count-1;
96    ssize_t mid;
97    sp<LayerBase> const* a = layers.array();
98    while (l <= h) {
99        mid = l + (h - l)/2;
100        const int c = cmp(a+mid, &layer);
101        if (c == 0)     { l = mid; break; }
102        else if (c<0)   { l = mid+1; }
103        else            { h = mid-1; }
104    }
105    size_t order = l;
106    while (order<count && !cmp(&layer, a+order)) {
107        order++;
108    }
109    count = lookup.size();
110    for (size_t i=0 ; i<count ; i++) {
111        if (lookup.valueAt(i) >= order) {
112            lookup.editValueAt(i)++;
113        }
114    }
115    layers.insertAt(layer, order);
116    lookup.add(layer, order);
117    return order;
118}
119
120ssize_t SurfaceFlinger::LayerVector::remove(const sp<LayerBase>& layer)
121{
122    const ssize_t keyIndex = lookup.indexOfKey(layer);
123    if (keyIndex >= 0) {
124        const size_t index = lookup.valueAt(keyIndex);
125        LOGE_IF(layers[index]!=layer,
126                "LayerVector[%p]: layers[%u]=%p, layer=%p",
127                this, int(index), layers[index].get(), layer.get());
128        layers.removeItemsAt(index);
129        lookup.removeItemsAt(keyIndex);
130        const size_t count = lookup.size();
131        for (size_t i=0 ; i<count ; i++) {
132            if (lookup.valueAt(i) >= size_t(index)) {
133                lookup.editValueAt(i)--;
134            }
135        }
136        return index;
137    }
138    return NAME_NOT_FOUND;
139}
140
141ssize_t SurfaceFlinger::LayerVector::reorder(
142        const sp<LayerBase>& layer,
143        Vector< sp<LayerBase> >::compar_t cmp)
144{
145    // XXX: it's a little lame. but oh well...
146    ssize_t err = remove(layer);
147    if (err >=0)
148        err = add(layer, cmp);
149    return err;
150}
151
152// ---------------------------------------------------------------------------
153#if 0
154#pragma mark -
155#endif
156
157SurfaceFlinger::SurfaceFlinger()
158    :   BnSurfaceComposer(), Thread(false),
159        mTransactionFlags(0),
160        mTransactionCount(0),
161        mResizeTransationPending(false),
162        mLayersRemoved(false),
163        mBootTime(systemTime()),
164        mHardwareTest("android.permission.HARDWARE_TEST"),
165        mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"),
166        mDump("android.permission.DUMP"),
167        mVisibleRegionsDirty(false),
168        mDeferReleaseConsole(false),
169        mFreezeDisplay(false),
170        mFreezeCount(0),
171        mFreezeDisplayTime(0),
172        mDebugRegion(0),
173        mDebugBackground(0),
174        mDebugInSwapBuffers(0),
175        mLastSwapBufferTime(0),
176        mDebugInTransaction(0),
177        mLastTransactionTime(0),
178        mBootFinished(false),
179        mConsoleSignals(0),
180        mSecureFrameBuffer(0)
181{
182    init();
183}
184
185void SurfaceFlinger::init()
186{
187    LOGI("SurfaceFlinger is starting");
188
189    // debugging stuff...
190    char value[PROPERTY_VALUE_MAX];
191    property_get("debug.sf.showupdates", value, "0");
192    mDebugRegion = atoi(value);
193    property_get("debug.sf.showbackground", value, "0");
194    mDebugBackground = atoi(value);
195
196    LOGI_IF(mDebugRegion,       "showupdates enabled");
197    LOGI_IF(mDebugBackground,   "showbackground enabled");
198}
199
200SurfaceFlinger::~SurfaceFlinger()
201{
202    glDeleteTextures(1, &mWormholeTexName);
203}
204
205overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const
206{
207    return graphicPlane(0).displayHardware().getOverlayEngine();
208}
209
210sp<IMemoryHeap> SurfaceFlinger::getCblk() const
211{
212    return mServerHeap;
213}
214
215sp<ISurfaceComposerClient> SurfaceFlinger::createConnection()
216{
217    sp<ISurfaceComposerClient> bclient;
218    sp<Client> client(new Client(this));
219    status_t err = client->initCheck();
220    if (err == NO_ERROR) {
221        bclient = client;
222    }
223    return bclient;
224}
225
226sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection()
227{
228    sp<ISurfaceComposerClient> bclient;
229    sp<UserClient> client(new UserClient(this));
230    status_t err = client->initCheck();
231    if (err == NO_ERROR) {
232        bclient = client;
233    }
234    return bclient;
235}
236
237
238const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const
239{
240    LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy);
241    const GraphicPlane& plane(mGraphicPlanes[dpy]);
242    return plane;
243}
244
245GraphicPlane& SurfaceFlinger::graphicPlane(int dpy)
246{
247    return const_cast<GraphicPlane&>(
248        const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy));
249}
250
251void SurfaceFlinger::bootFinished()
252{
253    const nsecs_t now = systemTime();
254    const nsecs_t duration = now - mBootTime;
255    LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) );
256    mBootFinished = true;
257    property_set("ctl.stop", "bootanim");
258}
259
260void SurfaceFlinger::onFirstRef()
261{
262    run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY);
263
264    // Wait for the main thread to be done with its initialization
265    mReadyToRunBarrier.wait();
266}
267
268static inline uint16_t pack565(int r, int g, int b) {
269    return (r<<11)|(g<<5)|b;
270}
271
272status_t SurfaceFlinger::readyToRun()
273{
274    LOGI(   "SurfaceFlinger's main thread ready to run. "
275            "Initializing graphics H/W...");
276
277    // we only support one display currently
278    int dpy = 0;
279
280    {
281        // initialize the main display
282        GraphicPlane& plane(graphicPlane(dpy));
283        DisplayHardware* const hw = new DisplayHardware(this, dpy);
284        plane.setDisplayHardware(hw);
285    }
286
287    // create the shared control-block
288    mServerHeap = new MemoryHeapBase(4096,
289            MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap");
290    LOGE_IF(mServerHeap==0, "can't create shared memory dealer");
291
292    mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase());
293    LOGE_IF(mServerCblk==0, "can't get to shared control block's address");
294
295    new(mServerCblk) surface_flinger_cblk_t;
296
297    // initialize primary screen
298    // (other display should be initialized in the same manner, but
299    // asynchronously, as they could come and go. None of this is supported
300    // yet).
301    const GraphicPlane& plane(graphicPlane(dpy));
302    const DisplayHardware& hw = plane.displayHardware();
303    const uint32_t w = hw.getWidth();
304    const uint32_t h = hw.getHeight();
305    const uint32_t f = hw.getFormat();
306    hw.makeCurrent();
307
308    // initialize the shared control block
309    mServerCblk->connected |= 1<<dpy;
310    display_cblk_t* dcblk = mServerCblk->displays + dpy;
311    memset(dcblk, 0, sizeof(display_cblk_t));
312    dcblk->w            = plane.getWidth();
313    dcblk->h            = plane.getHeight();
314    dcblk->format       = f;
315    dcblk->orientation  = ISurfaceComposer::eOrientationDefault;
316    dcblk->xdpi         = hw.getDpiX();
317    dcblk->ydpi         = hw.getDpiY();
318    dcblk->fps          = hw.getRefreshRate();
319    dcblk->density      = hw.getDensity();
320
321    // Initialize OpenGL|ES
322    glPixelStorei(GL_UNPACK_ALIGNMENT, 4);
323    glPixelStorei(GL_PACK_ALIGNMENT, 4);
324    glEnableClientState(GL_VERTEX_ARRAY);
325    glEnable(GL_SCISSOR_TEST);
326    glShadeModel(GL_FLAT);
327    glDisable(GL_DITHER);
328    glDisable(GL_CULL_FACE);
329
330    const uint16_t g0 = pack565(0x0F,0x1F,0x0F);
331    const uint16_t g1 = pack565(0x17,0x2f,0x17);
332    const uint16_t textureData[4] = { g0, g1, g1, g0 };
333    glGenTextures(1, &mWormholeTexName);
334    glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
335    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
336    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
337    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT);
338    glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT);
339    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0,
340            GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData);
341
342    glViewport(0, 0, w, h);
343    glMatrixMode(GL_PROJECTION);
344    glLoadIdentity();
345    glOrthof(0, w, h, 0, 0, 1);
346
347   LayerDim::initDimmer(this, w, h);
348
349    mReadyToRunBarrier.open();
350
351    /*
352     *  We're now ready to accept clients...
353     */
354
355    // start boot animation
356    property_set("ctl.start", "bootanim");
357
358    return NO_ERROR;
359}
360
361// ----------------------------------------------------------------------------
362#if 0
363#pragma mark -
364#pragma mark Events Handler
365#endif
366
367void SurfaceFlinger::waitForEvent()
368{
369    while (true) {
370        nsecs_t timeout = -1;
371        const nsecs_t freezeDisplayTimeout = ms2ns(5000);
372        if (UNLIKELY(isFrozen())) {
373            // wait 5 seconds
374            const nsecs_t now = systemTime();
375            if (mFreezeDisplayTime == 0) {
376                mFreezeDisplayTime = now;
377            }
378            nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime);
379            timeout = waitTime>0 ? waitTime : 0;
380        }
381
382        sp<MessageBase> msg = mEventQueue.waitMessage(timeout);
383
384        // see if we timed out
385        if (isFrozen()) {
386            const nsecs_t now = systemTime();
387            nsecs_t frozenTime = (now - mFreezeDisplayTime);
388            if (frozenTime >= freezeDisplayTimeout) {
389                // we timed out and are still frozen
390                LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d",
391                        mFreezeDisplay, mFreezeCount);
392                mFreezeDisplayTime = 0;
393                mFreezeCount = 0;
394                mFreezeDisplay = false;
395            }
396        }
397
398        if (msg != 0) {
399            switch (msg->what) {
400                case MessageQueue::INVALIDATE:
401                    // invalidate message, just return to the main loop
402                    return;
403            }
404        }
405    }
406}
407
408void SurfaceFlinger::signalEvent() {
409    mEventQueue.invalidate();
410}
411
412void SurfaceFlinger::signal() const {
413    // this is the IPC call
414    const_cast<SurfaceFlinger*>(this)->signalEvent();
415}
416
417status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg,
418        nsecs_t reltime, uint32_t flags)
419{
420    return mEventQueue.postMessage(msg, reltime, flags);
421}
422
423status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg,
424        nsecs_t reltime, uint32_t flags)
425{
426    status_t res = mEventQueue.postMessage(msg, reltime, flags);
427    if (res == NO_ERROR) {
428        msg->wait();
429    }
430    return res;
431}
432
433// ----------------------------------------------------------------------------
434#if 0
435#pragma mark -
436#pragma mark Main loop
437#endif
438
439bool SurfaceFlinger::threadLoop()
440{
441    waitForEvent();
442
443    // check for transactions
444    if (UNLIKELY(mConsoleSignals)) {
445        handleConsoleEvents();
446    }
447
448    if (LIKELY(mTransactionCount == 0)) {
449        // if we're in a global transaction, don't do anything.
450        const uint32_t mask = eTransactionNeeded | eTraversalNeeded;
451        uint32_t transactionFlags = getTransactionFlags(mask);
452        if (LIKELY(transactionFlags)) {
453            handleTransaction(transactionFlags);
454        }
455    }
456
457    // post surfaces (if needed)
458    handlePageFlip();
459
460    const DisplayHardware& hw(graphicPlane(0).displayHardware());
461    if (LIKELY(hw.canDraw() && !isFrozen())) {
462        // repaint the framebuffer (if needed)
463        handleRepaint();
464
465        // inform the h/w that we're done compositing
466        hw.compositionComplete();
467
468        // release the clients before we flip ('cause flip might block)
469        unlockClients();
470
471        postFramebuffer();
472    } else {
473        // pretend we did the post
474        unlockClients();
475        usleep(16667); // 60 fps period
476    }
477    return true;
478}
479
480void SurfaceFlinger::postFramebuffer()
481{
482    if (!mInvalidRegion.isEmpty()) {
483        const DisplayHardware& hw(graphicPlane(0).displayHardware());
484        const nsecs_t now = systemTime();
485        mDebugInSwapBuffers = now;
486        hw.flip(mInvalidRegion);
487        mLastSwapBufferTime = systemTime() - now;
488        mDebugInSwapBuffers = 0;
489        mInvalidRegion.clear();
490    }
491}
492
493void SurfaceFlinger::handleConsoleEvents()
494{
495    // something to do with the console
496    const DisplayHardware& hw = graphicPlane(0).displayHardware();
497
498    int what = android_atomic_and(0, &mConsoleSignals);
499    if (what & eConsoleAcquired) {
500        hw.acquireScreen();
501    }
502
503    if (mDeferReleaseConsole && hw.canDraw()) {
504        // We got the release signal before the acquire signal
505        mDeferReleaseConsole = false;
506        hw.releaseScreen();
507    }
508
509    if (what & eConsoleReleased) {
510        if (hw.canDraw()) {
511            hw.releaseScreen();
512        } else {
513            mDeferReleaseConsole = true;
514        }
515    }
516
517    mDirtyRegion.set(hw.bounds());
518}
519
520void SurfaceFlinger::handleTransaction(uint32_t transactionFlags)
521{
522    Vector< sp<LayerBase> > ditchedLayers;
523
524    /*
525     * Perform and commit the transaction
526     */
527
528    { // scope for the lock
529        Mutex::Autolock _l(mStateLock);
530        const nsecs_t now = systemTime();
531        mDebugInTransaction = now;
532        handleTransactionLocked(transactionFlags, ditchedLayers);
533        mLastTransactionTime = systemTime() - now;
534        mDebugInTransaction = 0;
535        // here the transaction has been committed
536    }
537
538    /*
539     * Clean-up all layers that went away
540     * (do this without the lock held)
541     */
542    const size_t count = ditchedLayers.size();
543    for (size_t i=0 ; i<count ; i++) {
544        if (ditchedLayers[i] != 0) {
545            //LOGD("ditching layer %p", ditchedLayers[i].get());
546            ditchedLayers[i]->ditch();
547        }
548    }
549}
550
551void SurfaceFlinger::handleTransactionLocked(
552        uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
553{
554    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
555    const size_t count = currentLayers.size();
556
557    /*
558     * Traversal of the children
559     * (perform the transaction for each of them if needed)
560     */
561
562    const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
563    if (layersNeedTransaction) {
564        for (size_t i=0 ; i<count ; i++) {
565            const sp<LayerBase>& layer = currentLayers[i];
566            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
567            if (!trFlags) continue;
568
569            const uint32_t flags = layer->doTransaction(0);
570            if (flags & Layer::eVisibleRegion)
571                mVisibleRegionsDirty = true;
572        }
573    }
574
575    /*
576     * Perform our own transaction if needed
577     */
578
579    if (transactionFlags & eTransactionNeeded) {
580        if (mCurrentState.orientation != mDrawingState.orientation) {
581            // the orientation has changed, recompute all visible regions
582            // and invalidate everything.
583
584            const int dpy = 0;
585            const int orientation = mCurrentState.orientation;
586            const uint32_t type = mCurrentState.orientationType;
587            GraphicPlane& plane(graphicPlane(dpy));
588            plane.setOrientation(orientation);
589
590            // update the shared control block
591            const DisplayHardware& hw(plane.displayHardware());
592            volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
593            dcblk->orientation = orientation;
594            dcblk->w = plane.getWidth();
595            dcblk->h = plane.getHeight();
596
597            mVisibleRegionsDirty = true;
598            mDirtyRegion.set(hw.bounds());
599        }
600
601        if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
602            // freezing or unfreezing the display -> trigger animation if needed
603            mFreezeDisplay = mCurrentState.freezeDisplay;
604            if (mFreezeDisplay)
605                 mFreezeDisplayTime = 0;
606        }
607
608        if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
609            // layers have been added
610            mVisibleRegionsDirty = true;
611        }
612
613        // some layers might have been removed, so
614        // we need to update the regions they're exposing.
615        if (mLayersRemoved) {
616            mLayersRemoved = false;
617            mVisibleRegionsDirty = true;
618            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
619            const size_t count = previousLayers.size();
620            for (size_t i=0 ; i<count ; i++) {
621                const sp<LayerBase>& layer(previousLayers[i]);
622                if (currentLayers.indexOf( layer ) < 0) {
623                    // this layer is not visible anymore
624                    ditchedLayers.add(layer);
625                    mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
626                }
627            }
628        }
629    }
630
631    commitTransaction();
632}
633
634sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
635{
636    return new FreezeLock(const_cast<SurfaceFlinger *>(this));
637}
638
639void SurfaceFlinger::computeVisibleRegions(
640    LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
641{
642    const GraphicPlane& plane(graphicPlane(0));
643    const Transform& planeTransform(plane.transform());
644    const DisplayHardware& hw(plane.displayHardware());
645    const Region screenRegion(hw.bounds());
646
647    Region aboveOpaqueLayers;
648    Region aboveCoveredLayers;
649    Region dirty;
650
651    bool secureFrameBuffer = false;
652
653    size_t i = currentLayers.size();
654    while (i--) {
655        const sp<LayerBase>& layer = currentLayers[i];
656        layer->validateVisibility(planeTransform);
657
658        // start with the whole surface at its current location
659        const Layer::State& s(layer->drawingState());
660
661        /*
662         * opaqueRegion: area of a surface that is fully opaque.
663         */
664        Region opaqueRegion;
665
666        /*
667         * visibleRegion: area of a surface that is visible on screen
668         * and not fully transparent. This is essentially the layer's
669         * footprint minus the opaque regions above it.
670         * Areas covered by a translucent surface are considered visible.
671         */
672        Region visibleRegion;
673
674        /*
675         * coveredRegion: area of a surface that is covered by all
676         * visible regions above it (which includes the translucent areas).
677         */
678        Region coveredRegion;
679
680
681        // handle hidden surfaces by setting the visible region to empty
682        if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
683            const bool translucent = layer->needsBlending();
684            const Rect bounds(layer->visibleBounds());
685            visibleRegion.set(bounds);
686            visibleRegion.andSelf(screenRegion);
687            if (!visibleRegion.isEmpty()) {
688                // Remove the transparent area from the visible region
689                if (translucent) {
690                    visibleRegion.subtractSelf(layer->transparentRegionScreen);
691                }
692
693                // compute the opaque region
694                const int32_t layerOrientation = layer->getOrientation();
695                if (s.alpha==255 && !translucent &&
696                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
697                    // the opaque region is the layer's footprint
698                    opaqueRegion = visibleRegion;
699                }
700            }
701        }
702
703        // Clip the covered region to the visible region
704        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
705
706        // Update aboveCoveredLayers for next (lower) layer
707        aboveCoveredLayers.orSelf(visibleRegion);
708
709        // subtract the opaque region covered by the layers above us
710        visibleRegion.subtractSelf(aboveOpaqueLayers);
711
712        // compute this layer's dirty region
713        if (layer->contentDirty) {
714            // we need to invalidate the whole region
715            dirty = visibleRegion;
716            // as well, as the old visible region
717            dirty.orSelf(layer->visibleRegionScreen);
718            layer->contentDirty = false;
719        } else {
720            /* compute the exposed region:
721             *   the exposed region consists of two components:
722             *   1) what's VISIBLE now and was COVERED before
723             *   2) what's EXPOSED now less what was EXPOSED before
724             *
725             * note that (1) is conservative, we start with the whole
726             * visible region but only keep what used to be covered by
727             * something -- which mean it may have been exposed.
728             *
729             * (2) handles areas that were not covered by anything but got
730             * exposed because of a resize.
731             */
732            const Region newExposed = visibleRegion - coveredRegion;
733            const Region oldVisibleRegion = layer->visibleRegionScreen;
734            const Region oldCoveredRegion = layer->coveredRegionScreen;
735            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
736            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
737        }
738        dirty.subtractSelf(aboveOpaqueLayers);
739
740        // accumulate to the screen dirty region
741        dirtyRegion.orSelf(dirty);
742
743        // Update aboveOpaqueLayers for next (lower) layer
744        aboveOpaqueLayers.orSelf(opaqueRegion);
745
746        // Store the visible region is screen space
747        layer->setVisibleRegion(visibleRegion);
748        layer->setCoveredRegion(coveredRegion);
749
750        // If a secure layer is partially visible, lock-down the screen!
751        if (layer->isSecure() && !visibleRegion.isEmpty()) {
752            secureFrameBuffer = true;
753        }
754    }
755
756    // invalidate the areas where a layer was removed
757    dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
758    mDirtyRegionRemovedLayer.clear();
759
760    mSecureFrameBuffer = secureFrameBuffer;
761    opaqueRegion = aboveOpaqueLayers;
762}
763
764
765void SurfaceFlinger::commitTransaction()
766{
767    mDrawingState = mCurrentState;
768    mResizeTransationPending = false;
769    mTransactionCV.broadcast();
770}
771
772void SurfaceFlinger::handlePageFlip()
773{
774    bool visibleRegions = mVisibleRegionsDirty;
775    LayerVector& currentLayers = const_cast<LayerVector&>(
776            mDrawingState.layersSortedByZ);
777    visibleRegions |= lockPageFlip(currentLayers);
778
779        const DisplayHardware& hw = graphicPlane(0).displayHardware();
780        const Region screenRegion(hw.bounds());
781        if (visibleRegions) {
782            Region opaqueRegion;
783            computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
784
785            /*
786             *  rebuild the visible layer list
787             */
788            mVisibleLayersSortedByZ.clear();
789            const LayerVector& currentLayers(mDrawingState.layersSortedByZ);
790            size_t count = currentLayers.size();
791            mVisibleLayersSortedByZ.setCapacity(count);
792            for (size_t i=0 ; i<count ; i++) {
793                if (!currentLayers[i]->visibleRegionScreen.isEmpty())
794                    mVisibleLayersSortedByZ.add(currentLayers[i]);
795            }
796
797            mWormholeRegion = screenRegion.subtract(opaqueRegion);
798            mVisibleRegionsDirty = false;
799        }
800
801    unlockPageFlip(currentLayers);
802    mDirtyRegion.andSelf(screenRegion);
803}
804
805bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
806{
807    bool recomputeVisibleRegions = false;
808    size_t count = currentLayers.size();
809    sp<LayerBase> const* layers = currentLayers.array();
810    for (size_t i=0 ; i<count ; i++) {
811        const sp<LayerBase>& layer(layers[i]);
812        layer->lockPageFlip(recomputeVisibleRegions);
813    }
814    return recomputeVisibleRegions;
815}
816
817void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
818{
819    const GraphicPlane& plane(graphicPlane(0));
820    const Transform& planeTransform(plane.transform());
821    size_t count = currentLayers.size();
822    sp<LayerBase> const* layers = currentLayers.array();
823    for (size_t i=0 ; i<count ; i++) {
824        const sp<LayerBase>& layer(layers[i]);
825        layer->unlockPageFlip(planeTransform, mDirtyRegion);
826    }
827}
828
829
830void SurfaceFlinger::handleRepaint()
831{
832    // compute the invalid region
833    mInvalidRegion.orSelf(mDirtyRegion);
834    if (mInvalidRegion.isEmpty()) {
835        // nothing to do
836        return;
837    }
838
839    if (UNLIKELY(mDebugRegion)) {
840        debugFlashRegions();
841    }
842
843    // set the frame buffer
844    const DisplayHardware& hw(graphicPlane(0).displayHardware());
845    glMatrixMode(GL_MODELVIEW);
846    glLoadIdentity();
847
848    uint32_t flags = hw.getFlags();
849    if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
850        (flags & DisplayHardware::BUFFER_PRESERVED))
851    {
852        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
853        // takes a rectangle, we must make sure to update that whole
854        // rectangle in that case
855        if (flags & DisplayHardware::SWAP_RECTANGLE) {
856            // TODO: we really should be able to pass a region to
857            // SWAP_RECTANGLE so that we don't have to redraw all this.
858            mDirtyRegion.set(mInvalidRegion.bounds());
859        } else {
860            // in the BUFFER_PRESERVED case, obviously, we can update only
861            // what's needed and nothing more.
862            // NOTE: this is NOT a common case, as preserving the backbuffer
863            // is costly and usually involves copying the whole update back.
864        }
865    } else {
866        if (flags & DisplayHardware::PARTIAL_UPDATES) {
867            // We need to redraw the rectangle that will be updated
868            // (pushed to the framebuffer).
869            // This is needed because PARTIAL_UPDATES only takes one
870            // rectangle instead of a region (see DisplayHardware::flip())
871            mDirtyRegion.set(mInvalidRegion.bounds());
872        } else {
873            // we need to redraw everything (the whole screen)
874            mDirtyRegion.set(hw.bounds());
875            mInvalidRegion = mDirtyRegion;
876        }
877    }
878
879    // compose all surfaces
880    composeSurfaces(mDirtyRegion);
881
882    // clear the dirty regions
883    mDirtyRegion.clear();
884}
885
886void SurfaceFlinger::composeSurfaces(const Region& dirty)
887{
888    if (UNLIKELY(!mWormholeRegion.isEmpty())) {
889        // should never happen unless the window manager has a bug
890        // draw something...
891        drawWormhole();
892    }
893    const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ);
894    const size_t count = layers.size();
895    for (size_t i=0 ; i<count ; ++i) {
896        const sp<LayerBase>& layer(layers[i]);
897        const Region clip(dirty.intersect(layer->visibleRegionScreen));
898        if (!clip.isEmpty()) {
899            layer->draw(clip);
900        }
901    }
902}
903
904void SurfaceFlinger::unlockClients()
905{
906    const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
907    const size_t count = drawingLayers.size();
908    sp<LayerBase> const* const layers = drawingLayers.array();
909    for (size_t i=0 ; i<count ; ++i) {
910        const sp<LayerBase>& layer = layers[i];
911        layer->finishPageFlip();
912    }
913}
914
915void SurfaceFlinger::debugFlashRegions()
916{
917    const DisplayHardware& hw(graphicPlane(0).displayHardware());
918    const uint32_t flags = hw.getFlags();
919
920    if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
921            (flags & DisplayHardware::BUFFER_PRESERVED))) {
922        const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
923                mDirtyRegion.bounds() : hw.bounds());
924        composeSurfaces(repaint);
925    }
926
927    TextureManager::deactivateTextures();
928
929    glDisable(GL_BLEND);
930    glDisable(GL_DITHER);
931    glDisable(GL_SCISSOR_TEST);
932
933    static int toggle = 0;
934    toggle = 1 - toggle;
935    if (toggle) {
936        glColor4f(1, 0, 1, 1);
937    } else {
938        glColor4f(1, 1, 0, 1);
939    }
940
941    Region::const_iterator it = mDirtyRegion.begin();
942    Region::const_iterator const end = mDirtyRegion.end();
943    while (it != end) {
944        const Rect& r = *it++;
945        GLfloat vertices[][2] = {
946                { r.left,  r.top },
947                { r.left,  r.bottom },
948                { r.right, r.bottom },
949                { r.right, r.top }
950        };
951        glVertexPointer(2, GL_FLOAT, 0, vertices);
952        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
953    }
954
955    if (mInvalidRegion.isEmpty()) {
956        mDirtyRegion.dump("mDirtyRegion");
957        mInvalidRegion.dump("mInvalidRegion");
958    }
959    hw.flip(mInvalidRegion);
960
961    if (mDebugRegion > 1)
962        usleep(mDebugRegion * 1000);
963
964    glEnable(GL_SCISSOR_TEST);
965    //mDirtyRegion.dump("mDirtyRegion");
966}
967
968void SurfaceFlinger::drawWormhole() const
969{
970    const Region region(mWormholeRegion.intersect(mDirtyRegion));
971    if (region.isEmpty())
972        return;
973
974    const DisplayHardware& hw(graphicPlane(0).displayHardware());
975    const int32_t width = hw.getWidth();
976    const int32_t height = hw.getHeight();
977
978    glDisable(GL_BLEND);
979    glDisable(GL_DITHER);
980
981    if (LIKELY(!mDebugBackground)) {
982        glClearColor(0,0,0,0);
983        Region::const_iterator it = region.begin();
984        Region::const_iterator const end = region.end();
985        while (it != end) {
986            const Rect& r = *it++;
987            const GLint sy = height - (r.top + r.height());
988            glScissor(r.left, sy, r.width(), r.height());
989            glClear(GL_COLOR_BUFFER_BIT);
990        }
991    } else {
992        const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
993                { width, height }, { 0, height }  };
994        const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 },  { 1, 1 }, { 0, 1 } };
995        glVertexPointer(2, GL_SHORT, 0, vertices);
996        glTexCoordPointer(2, GL_SHORT, 0, tcoords);
997        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
998#if defined(GL_OES_texture_external)
999        if (GLExtensions::getInstance().haveTextureExternal()) {
1000            glDisable(GL_TEXTURE_EXTERNAL_OES);
1001        }
1002#endif
1003        glEnable(GL_TEXTURE_2D);
1004        glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
1005        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
1006        glMatrixMode(GL_TEXTURE);
1007        glLoadIdentity();
1008        glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
1009        Region::const_iterator it = region.begin();
1010        Region::const_iterator const end = region.end();
1011        while (it != end) {
1012            const Rect& r = *it++;
1013            const GLint sy = height - (r.top + r.height());
1014            glScissor(r.left, sy, r.width(), r.height());
1015            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1016        }
1017        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1018    }
1019}
1020
1021void SurfaceFlinger::debugShowFPS() const
1022{
1023    static int mFrameCount;
1024    static int mLastFrameCount = 0;
1025    static nsecs_t mLastFpsTime = 0;
1026    static float mFps = 0;
1027    mFrameCount++;
1028    nsecs_t now = systemTime();
1029    nsecs_t diff = now - mLastFpsTime;
1030    if (diff > ms2ns(250)) {
1031        mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1032        mLastFpsTime = now;
1033        mLastFrameCount = mFrameCount;
1034    }
1035    // XXX: mFPS has the value we want
1036 }
1037
1038status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1039{
1040    Mutex::Autolock _l(mStateLock);
1041    addLayer_l(layer);
1042    setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1043    return NO_ERROR;
1044}
1045
1046status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1047{
1048    ssize_t i = mCurrentState.layersSortedByZ.add(
1049                layer, &LayerBase::compareCurrentStateZ);
1050    return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1051}
1052
1053ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1054        const sp<LayerBaseClient>& lbc)
1055{
1056    Mutex::Autolock _l(mStateLock);
1057
1058    // attach this layer to the client
1059    ssize_t name = client->attachLayer(lbc);
1060
1061    // add this layer to the current state list
1062    addLayer_l(lbc);
1063
1064    return name;
1065}
1066
1067status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1068{
1069    Mutex::Autolock _l(mStateLock);
1070    status_t err = purgatorizeLayer_l(layer);
1071    if (err == NO_ERROR)
1072        setTransactionFlags(eTransactionNeeded);
1073    return err;
1074}
1075
1076status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1077{
1078    sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1079    if (lbc != 0) {
1080        mLayerMap.removeItem( lbc->getSurface()->asBinder() );
1081    }
1082    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1083    if (index >= 0) {
1084        mLayersRemoved = true;
1085        return NO_ERROR;
1086    }
1087    return status_t(index);
1088}
1089
1090status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1091{
1092    // remove the layer from the main list (through a transaction).
1093    ssize_t err = removeLayer_l(layerBase);
1094
1095    layerBase->onRemoved();
1096
1097    // it's possible that we don't find a layer, because it might
1098    // have been destroyed already -- this is not technically an error
1099    // from the user because there is a race between Client::destroySurface(),
1100    // ~Client() and ~ISurface().
1101    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1102}
1103
1104status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1105{
1106    layer->forceVisibilityTransaction();
1107    setTransactionFlags(eTraversalNeeded);
1108    return NO_ERROR;
1109}
1110
1111uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1112{
1113    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1114}
1115
1116uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1117{
1118    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1119    if ((old & flags)==0) { // wake the server up
1120        signalEvent();
1121    }
1122    return old;
1123}
1124
1125void SurfaceFlinger::openGlobalTransaction()
1126{
1127    android_atomic_inc(&mTransactionCount);
1128}
1129
1130void SurfaceFlinger::closeGlobalTransaction()
1131{
1132    if (android_atomic_dec(&mTransactionCount) == 1) {
1133        signalEvent();
1134
1135        // if there is a transaction with a resize, wait for it to
1136        // take effect before returning.
1137        Mutex::Autolock _l(mStateLock);
1138        while (mResizeTransationPending) {
1139            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1140            if (CC_UNLIKELY(err != NO_ERROR)) {
1141                // just in case something goes wrong in SF, return to the
1142                // called after a few seconds.
1143                LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1144                mResizeTransationPending = false;
1145                break;
1146            }
1147        }
1148    }
1149}
1150
1151status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1152{
1153    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1154        return BAD_VALUE;
1155
1156    Mutex::Autolock _l(mStateLock);
1157    mCurrentState.freezeDisplay = 1;
1158    setTransactionFlags(eTransactionNeeded);
1159
1160    // flags is intended to communicate some sort of animation behavior
1161    // (for instance fading)
1162    return NO_ERROR;
1163}
1164
1165status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1166{
1167    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1168        return BAD_VALUE;
1169
1170    Mutex::Autolock _l(mStateLock);
1171    mCurrentState.freezeDisplay = 0;
1172    setTransactionFlags(eTransactionNeeded);
1173
1174    // flags is intended to communicate some sort of animation behavior
1175    // (for instance fading)
1176    return NO_ERROR;
1177}
1178
1179int SurfaceFlinger::setOrientation(DisplayID dpy,
1180        int orientation, uint32_t flags)
1181{
1182    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1183        return BAD_VALUE;
1184
1185    Mutex::Autolock _l(mStateLock);
1186    if (mCurrentState.orientation != orientation) {
1187        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1188            mCurrentState.orientationType = flags;
1189            mCurrentState.orientation = orientation;
1190            setTransactionFlags(eTransactionNeeded);
1191            mTransactionCV.wait(mStateLock);
1192        } else {
1193            orientation = BAD_VALUE;
1194        }
1195    }
1196    return orientation;
1197}
1198
1199sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid,
1200        const String8& name, ISurfaceComposerClient::surface_data_t* params,
1201        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1202        uint32_t flags)
1203{
1204    sp<LayerBaseClient> layer;
1205    sp<LayerBaseClient::Surface> surfaceHandle;
1206
1207    if (int32_t(w|h) < 0) {
1208        LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1209                int(w), int(h));
1210        return surfaceHandle;
1211    }
1212
1213    //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1214    sp<Layer> normalLayer;
1215    switch (flags & eFXSurfaceMask) {
1216        case eFXSurfaceNormal:
1217            if (UNLIKELY(flags & ePushBuffers)) {
1218                layer = createPushBuffersSurface(client, d, w, h, flags);
1219            } else {
1220                normalLayer = createNormalSurface(client, d, w, h, flags, format);
1221                layer = normalLayer;
1222            }
1223            break;
1224        case eFXSurfaceBlur:
1225            layer = createBlurSurface(client, d, w, h, flags);
1226            break;
1227        case eFXSurfaceDim:
1228            layer = createDimSurface(client, d, w, h, flags);
1229            break;
1230    }
1231
1232    if (layer != 0) {
1233        layer->initStates(w, h, flags);
1234        layer->setName(name);
1235        ssize_t token = addClientLayer(client, layer);
1236
1237        surfaceHandle = layer->getSurface();
1238        if (surfaceHandle != 0) {
1239            params->token = token;
1240            params->identity = surfaceHandle->getIdentity();
1241            params->width = w;
1242            params->height = h;
1243            params->format = format;
1244            if (normalLayer != 0) {
1245                Mutex::Autolock _l(mStateLock);
1246                mLayerMap.add(surfaceHandle->asBinder(), normalLayer);
1247            }
1248        }
1249
1250        setTransactionFlags(eTransactionNeeded);
1251    }
1252
1253    return surfaceHandle;
1254}
1255
1256sp<Layer> SurfaceFlinger::createNormalSurface(
1257        const sp<Client>& client, DisplayID display,
1258        uint32_t w, uint32_t h, uint32_t flags,
1259        PixelFormat& format)
1260{
1261    // initialize the surfaces
1262    switch (format) { // TODO: take h/w into account
1263    case PIXEL_FORMAT_TRANSPARENT:
1264    case PIXEL_FORMAT_TRANSLUCENT:
1265        format = PIXEL_FORMAT_RGBA_8888;
1266        break;
1267    case PIXEL_FORMAT_OPAQUE:
1268#ifdef NO_RGBX_8888
1269        format = PIXEL_FORMAT_RGB_565;
1270#else
1271        format = PIXEL_FORMAT_RGBX_8888;
1272#endif
1273        break;
1274    }
1275
1276#ifdef NO_RGBX_8888
1277    if (format == PIXEL_FORMAT_RGBX_8888)
1278        format = PIXEL_FORMAT_RGBA_8888;
1279#endif
1280
1281    sp<Layer> layer = new Layer(this, display, client);
1282    status_t err = layer->setBuffers(w, h, format, flags);
1283    if (LIKELY(err != NO_ERROR)) {
1284        LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1285        layer.clear();
1286    }
1287    return layer;
1288}
1289
1290sp<LayerBlur> SurfaceFlinger::createBlurSurface(
1291        const sp<Client>& client, DisplayID display,
1292        uint32_t w, uint32_t h, uint32_t flags)
1293{
1294    sp<LayerBlur> layer = new LayerBlur(this, display, client);
1295    layer->initStates(w, h, flags);
1296    return layer;
1297}
1298
1299sp<LayerDim> SurfaceFlinger::createDimSurface(
1300        const sp<Client>& client, DisplayID display,
1301        uint32_t w, uint32_t h, uint32_t flags)
1302{
1303    sp<LayerDim> layer = new LayerDim(this, display, client);
1304    layer->initStates(w, h, flags);
1305    return layer;
1306}
1307
1308sp<LayerBuffer> SurfaceFlinger::createPushBuffersSurface(
1309        const sp<Client>& client, DisplayID display,
1310        uint32_t w, uint32_t h, uint32_t flags)
1311{
1312    sp<LayerBuffer> layer = new LayerBuffer(this, display, client);
1313    layer->initStates(w, h, flags);
1314    return layer;
1315}
1316
1317status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1318{
1319    /*
1320     * called by the window manager, when a surface should be marked for
1321     * destruction.
1322     *
1323     * The surface is removed from the current and drawing lists, but placed
1324     * in the purgatory queue, so it's not destroyed right-away (we need
1325     * to wait for all client's references to go away first).
1326     */
1327
1328    status_t err = NAME_NOT_FOUND;
1329    Mutex::Autolock _l(mStateLock);
1330    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1331    if (layer != 0) {
1332        err = purgatorizeLayer_l(layer);
1333        if (err == NO_ERROR) {
1334            setTransactionFlags(eTransactionNeeded);
1335        }
1336    }
1337    return err;
1338}
1339
1340status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1341{
1342    // called by ~ISurface() when all references are gone
1343
1344    class MessageDestroySurface : public MessageBase {
1345        SurfaceFlinger* flinger;
1346        sp<LayerBaseClient> layer;
1347    public:
1348        MessageDestroySurface(
1349                SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1350            : flinger(flinger), layer(layer) { }
1351        virtual bool handler() {
1352            sp<LayerBaseClient> l(layer);
1353            layer.clear(); // clear it outside of the lock;
1354            Mutex::Autolock _l(flinger->mStateLock);
1355            /*
1356             * remove the layer from the current list -- chances are that it's
1357             * not in the list anyway, because it should have been removed
1358             * already upon request of the client (eg: window manager).
1359             * However, a buggy client could have not done that.
1360             * Since we know we don't have any more clients, we don't need
1361             * to use the purgatory.
1362             */
1363            status_t err = flinger->removeLayer_l(l);
1364            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1365                    "error removing layer=%p (%s)", l.get(), strerror(-err));
1366            return true;
1367        }
1368    };
1369
1370    postMessageAsync( new MessageDestroySurface(this, layer) );
1371    return NO_ERROR;
1372}
1373
1374status_t SurfaceFlinger::setClientState(
1375        const sp<Client>& client,
1376        int32_t count,
1377        const layer_state_t* states)
1378{
1379    Mutex::Autolock _l(mStateLock);
1380    uint32_t flags = 0;
1381    for (int i=0 ; i<count ; i++) {
1382        const layer_state_t& s(states[i]);
1383        sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1384        if (layer != 0) {
1385            const uint32_t what = s.what;
1386            if (what & ePositionChanged) {
1387                if (layer->setPosition(s.x, s.y))
1388                    flags |= eTraversalNeeded;
1389            }
1390            if (what & eLayerChanged) {
1391                if (layer->setLayer(s.z)) {
1392                    mCurrentState.layersSortedByZ.reorder(
1393                            layer, &Layer::compareCurrentStateZ);
1394                    // we need traversal (state changed)
1395                    // AND transaction (list changed)
1396                    flags |= eTransactionNeeded|eTraversalNeeded;
1397                }
1398            }
1399            if (what & eSizeChanged) {
1400                if (layer->setSize(s.w, s.h)) {
1401                    flags |= eTraversalNeeded;
1402                    mResizeTransationPending = true;
1403                }
1404            }
1405            if (what & eAlphaChanged) {
1406                if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1407                    flags |= eTraversalNeeded;
1408            }
1409            if (what & eMatrixChanged) {
1410                if (layer->setMatrix(s.matrix))
1411                    flags |= eTraversalNeeded;
1412            }
1413            if (what & eTransparentRegionChanged) {
1414                if (layer->setTransparentRegionHint(s.transparentRegion))
1415                    flags |= eTraversalNeeded;
1416            }
1417            if (what & eVisibilityChanged) {
1418                if (layer->setFlags(s.flags, s.mask))
1419                    flags |= eTraversalNeeded;
1420            }
1421        }
1422    }
1423    if (flags) {
1424        setTransactionFlags(flags);
1425    }
1426    return NO_ERROR;
1427}
1428
1429void SurfaceFlinger::screenReleased(int dpy)
1430{
1431    // this may be called by a signal handler, we can't do too much in here
1432    android_atomic_or(eConsoleReleased, &mConsoleSignals);
1433    signalEvent();
1434}
1435
1436void SurfaceFlinger::screenAcquired(int dpy)
1437{
1438    // this may be called by a signal handler, we can't do too much in here
1439    android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1440    signalEvent();
1441}
1442
1443status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1444{
1445    const size_t SIZE = 1024;
1446    char buffer[SIZE];
1447    String8 result;
1448    if (!mDump.checkCalling()) {
1449        snprintf(buffer, SIZE, "Permission Denial: "
1450                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1451                IPCThreadState::self()->getCallingPid(),
1452                IPCThreadState::self()->getCallingUid());
1453        result.append(buffer);
1454    } else {
1455
1456        // figure out if we're stuck somewhere
1457        const nsecs_t now = systemTime();
1458        const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1459        const nsecs_t inTransaction(mDebugInTransaction);
1460        nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1461        nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1462
1463        // Try to get the main lock, but don't insist if we can't
1464        // (this would indicate SF is stuck, but we want to be able to
1465        // print something in dumpsys).
1466        int retry = 3;
1467        while (mStateLock.tryLock()<0 && --retry>=0) {
1468            usleep(1000000);
1469        }
1470        const bool locked(retry >= 0);
1471        if (!locked) {
1472            snprintf(buffer, SIZE,
1473                    "SurfaceFlinger appears to be unresponsive, "
1474                    "dumping anyways (no locks held)\n");
1475            result.append(buffer);
1476        }
1477
1478        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1479        const size_t count = currentLayers.size();
1480        for (size_t i=0 ; i<count ; i++) {
1481            const sp<LayerBase>& layer(currentLayers[i]);
1482            layer->dump(result, buffer, SIZE);
1483            const Layer::State& s(layer->drawingState());
1484            s.transparentRegion.dump(result, "transparentRegion");
1485            layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1486            layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1487        }
1488
1489        mWormholeRegion.dump(result, "WormholeRegion");
1490        const DisplayHardware& hw(graphicPlane(0).displayHardware());
1491        snprintf(buffer, SIZE,
1492                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1493                mFreezeDisplay?"yes":"no", mFreezeCount,
1494                mCurrentState.orientation, hw.canDraw());
1495        result.append(buffer);
1496        snprintf(buffer, SIZE,
1497                "  last eglSwapBuffers() time: %f us\n"
1498                "  last transaction time     : %f us\n",
1499                mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1500        result.append(buffer);
1501
1502        if (inSwapBuffersDuration || !locked) {
1503            snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1504                    inSwapBuffersDuration/1000.0);
1505            result.append(buffer);
1506        }
1507
1508        if (inTransactionDuration || !locked) {
1509            snprintf(buffer, SIZE, "  transaction time: %f us\n",
1510                    inTransactionDuration/1000.0);
1511            result.append(buffer);
1512        }
1513
1514        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1515        alloc.dump(result);
1516
1517        if (locked) {
1518            mStateLock.unlock();
1519        }
1520    }
1521    write(fd, result.string(), result.size());
1522    return NO_ERROR;
1523}
1524
1525status_t SurfaceFlinger::onTransact(
1526    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1527{
1528    switch (code) {
1529        case CREATE_CONNECTION:
1530        case OPEN_GLOBAL_TRANSACTION:
1531        case CLOSE_GLOBAL_TRANSACTION:
1532        case SET_ORIENTATION:
1533        case FREEZE_DISPLAY:
1534        case UNFREEZE_DISPLAY:
1535        case BOOT_FINISHED:
1536        {
1537            // codes that require permission check
1538            IPCThreadState* ipc = IPCThreadState::self();
1539            const int pid = ipc->getCallingPid();
1540            const int uid = ipc->getCallingUid();
1541            if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1542                LOGE("Permission Denial: "
1543                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1544                return PERMISSION_DENIED;
1545            }
1546        }
1547    }
1548    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1549    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1550        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1551        if (UNLIKELY(!mHardwareTest.checkCalling())) {
1552            IPCThreadState* ipc = IPCThreadState::self();
1553            const int pid = ipc->getCallingPid();
1554            const int uid = ipc->getCallingUid();
1555            LOGE("Permission Denial: "
1556                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1557            return PERMISSION_DENIED;
1558        }
1559        int n;
1560        switch (code) {
1561            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1562                return NO_ERROR;
1563            case 1001:  // SHOW_FPS, NOT SUPPORTED ANYMORE
1564                return NO_ERROR;
1565            case 1002:  // SHOW_UPDATES
1566                n = data.readInt32();
1567                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1568                return NO_ERROR;
1569            case 1003:  // SHOW_BACKGROUND
1570                n = data.readInt32();
1571                mDebugBackground = n ? 1 : 0;
1572                return NO_ERROR;
1573            case 1004:{ // repaint everything
1574                Mutex::Autolock _l(mStateLock);
1575                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1576                mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1577                signalEvent();
1578                return NO_ERROR;
1579            }
1580            case 1005:{ // force transaction
1581                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1582                return NO_ERROR;
1583            }
1584            case 1007: // set mFreezeCount
1585                mFreezeCount = data.readInt32();
1586                mFreezeDisplayTime = 0;
1587                return NO_ERROR;
1588            case 1010:  // interrogate.
1589                reply->writeInt32(0);
1590                reply->writeInt32(0);
1591                reply->writeInt32(mDebugRegion);
1592                reply->writeInt32(mDebugBackground);
1593                return NO_ERROR;
1594            case 1013: {
1595                Mutex::Autolock _l(mStateLock);
1596                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1597                reply->writeInt32(hw.getPageFlipCount());
1598            }
1599            return NO_ERROR;
1600        }
1601    }
1602    return err;
1603}
1604
1605// ---------------------------------------------------------------------------
1606
1607sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
1608{
1609    sp<Layer> result;
1610    Mutex::Autolock _l(mStateLock);
1611    result = mLayerMap.valueFor( sur->asBinder() ).promote();
1612    return result;
1613}
1614
1615// ---------------------------------------------------------------------------
1616
1617Client::Client(const sp<SurfaceFlinger>& flinger)
1618    : mFlinger(flinger), mNameGenerator(1)
1619{
1620}
1621
1622Client::~Client()
1623{
1624    const size_t count = mLayers.size();
1625    for (size_t i=0 ; i<count ; i++) {
1626        sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
1627        if (layer != 0) {
1628            mFlinger->removeLayer(layer);
1629        }
1630    }
1631}
1632
1633status_t Client::initCheck() const {
1634    return NO_ERROR;
1635}
1636
1637ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
1638{
1639    int32_t name = android_atomic_inc(&mNameGenerator);
1640    mLayers.add(name, layer);
1641    return name;
1642}
1643
1644void Client::detachLayer(const LayerBaseClient* layer)
1645{
1646    // we do a linear search here, because this doesn't happen often
1647    const size_t count = mLayers.size();
1648    for (size_t i=0 ; i<count ; i++) {
1649        if (mLayers.valueAt(i) == layer) {
1650            mLayers.removeItemsAt(i, 1);
1651            break;
1652        }
1653    }
1654}
1655sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1656    sp<LayerBaseClient> lbc;
1657    const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
1658    if (layer != 0) {
1659        lbc = layer.promote();
1660        LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
1661    }
1662    return lbc;
1663}
1664
1665sp<IMemoryHeap> Client::getControlBlock() const {
1666    return 0;
1667}
1668ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const {
1669    return -1;
1670}
1671sp<ISurface> Client::createSurface(
1672        ISurfaceComposerClient::surface_data_t* params, int pid,
1673        const String8& name,
1674        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1675        uint32_t flags)
1676{
1677    return mFlinger->createSurface(this, pid, name, params,
1678            display, w, h, format, flags);
1679}
1680status_t Client::destroySurface(SurfaceID sid) {
1681    return mFlinger->removeSurface(this, sid);
1682}
1683status_t Client::setState(int32_t count, const layer_state_t* states) {
1684    return mFlinger->setClientState(this, count, states);
1685}
1686
1687// ---------------------------------------------------------------------------
1688
1689UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
1690    : ctrlblk(0), mBitmap(0), mFlinger(flinger)
1691{
1692    const int pgsize = getpagesize();
1693    const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
1694
1695    mCblkHeap = new MemoryHeapBase(cblksize, 0,
1696            "SurfaceFlinger Client control-block");
1697
1698    ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
1699    if (ctrlblk) { // construct the shared structure in-place.
1700        new(ctrlblk) SharedClient;
1701    }
1702}
1703
1704UserClient::~UserClient()
1705{
1706    if (ctrlblk) {
1707        ctrlblk->~SharedClient();  // destroy our shared-structure.
1708    }
1709
1710    /*
1711     * When a UserClient dies, it's unclear what to do exactly.
1712     * We could go ahead and destroy all surfaces linked to that client
1713     * however, it wouldn't be fair to the main Client
1714     * (usually the the window-manager), which might want to re-target
1715     * the layer to another UserClient.
1716     * I think the best is to do nothing, or not much; in most cases the
1717     * WM itself will go ahead and clean things up when it detects a client of
1718     * his has died.
1719     * The remaining question is what to display? currently we keep
1720     * just keep the current buffer.
1721     */
1722}
1723
1724status_t UserClient::initCheck() const {
1725    return ctrlblk == 0 ? NO_INIT : NO_ERROR;
1726}
1727
1728void UserClient::detachLayer(const Layer* layer)
1729{
1730    int32_t name = layer->getToken();
1731    if (name >= 0) {
1732        int32_t mask = 1LU<<name;
1733        if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) {
1734            LOGW("token %d wasn't marked as used %08x", name, int(mBitmap));
1735        }
1736    }
1737}
1738
1739sp<IMemoryHeap> UserClient::getControlBlock() const {
1740    return mCblkHeap;
1741}
1742
1743ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
1744{
1745    int32_t name = NAME_NOT_FOUND;
1746    sp<Layer> layer(mFlinger->getLayer(sur));
1747    if (layer == 0) return name;
1748
1749    // if this layer already has a token, just return it
1750    name = layer->getToken();
1751    if ((name >= 0) && (layer->getClient() == this))
1752        return name;
1753
1754    name = 0;
1755    do {
1756        int32_t mask = 1LU<<name;
1757        if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
1758            // we found and locked that name
1759            status_t err = layer->setToken(
1760                    const_cast<UserClient*>(this), ctrlblk, name);
1761            if (err != NO_ERROR) {
1762                // free the name
1763                android_atomic_and(~mask, &mBitmap);
1764                name = err;
1765            }
1766            break;
1767        }
1768        if (++name > 31)
1769            name = NO_MEMORY;
1770    } while(name >= 0);
1771
1772    //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
1773    //        sur->asBinder().get(), name, this, mBitmap);
1774    return name;
1775}
1776
1777sp<ISurface> UserClient::createSurface(
1778        ISurfaceComposerClient::surface_data_t* params, int pid,
1779        const String8& name,
1780        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1781        uint32_t flags) {
1782    return 0;
1783}
1784status_t UserClient::destroySurface(SurfaceID sid) {
1785    return INVALID_OPERATION;
1786}
1787status_t UserClient::setState(int32_t count, const layer_state_t* states) {
1788    return INVALID_OPERATION;
1789}
1790
1791// ---------------------------------------------------------------------------
1792
1793GraphicPlane::GraphicPlane()
1794    : mHw(0)
1795{
1796}
1797
1798GraphicPlane::~GraphicPlane() {
1799    delete mHw;
1800}
1801
1802bool GraphicPlane::initialized() const {
1803    return mHw ? true : false;
1804}
1805
1806int GraphicPlane::getWidth() const {
1807    return mWidth;
1808}
1809
1810int GraphicPlane::getHeight() const {
1811    return mHeight;
1812}
1813
1814void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
1815{
1816    mHw = hw;
1817
1818    // initialize the display orientation transform.
1819    // it's a constant that should come from the display driver.
1820    int displayOrientation = ISurfaceComposer::eOrientationDefault;
1821    char property[PROPERTY_VALUE_MAX];
1822    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
1823        //displayOrientation
1824        switch (atoi(property)) {
1825        case 90:
1826            displayOrientation = ISurfaceComposer::eOrientation90;
1827            break;
1828        case 270:
1829            displayOrientation = ISurfaceComposer::eOrientation270;
1830            break;
1831        }
1832    }
1833
1834    const float w = hw->getWidth();
1835    const float h = hw->getHeight();
1836    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
1837            &mDisplayTransform);
1838    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
1839        mDisplayWidth = h;
1840        mDisplayHeight = w;
1841    } else {
1842        mDisplayWidth = w;
1843        mDisplayHeight = h;
1844    }
1845
1846    setOrientation(ISurfaceComposer::eOrientationDefault);
1847}
1848
1849status_t GraphicPlane::orientationToTransfrom(
1850        int orientation, int w, int h, Transform* tr)
1851{
1852    uint32_t flags = 0;
1853    switch (orientation) {
1854    case ISurfaceComposer::eOrientationDefault:
1855        flags = Transform::ROT_0;
1856        break;
1857    case ISurfaceComposer::eOrientation90:
1858        flags = Transform::ROT_90;
1859        break;
1860    case ISurfaceComposer::eOrientation180:
1861        flags = Transform::ROT_180;
1862        break;
1863    case ISurfaceComposer::eOrientation270:
1864        flags = Transform::ROT_270;
1865        break;
1866    default:
1867        return BAD_VALUE;
1868    }
1869    tr->set(flags, w, h);
1870    return NO_ERROR;
1871}
1872
1873status_t GraphicPlane::setOrientation(int orientation)
1874{
1875    // If the rotation can be handled in hardware, this is where
1876    // the magic should happen.
1877
1878    const DisplayHardware& hw(displayHardware());
1879    const float w = mDisplayWidth;
1880    const float h = mDisplayHeight;
1881    mWidth = int(w);
1882    mHeight = int(h);
1883
1884    Transform orientationTransform;
1885    GraphicPlane::orientationToTransfrom(orientation, w, h,
1886            &orientationTransform);
1887    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
1888        mWidth = int(h);
1889        mHeight = int(w);
1890    }
1891
1892    mOrientation = orientation;
1893    mGlobalTransform = mDisplayTransform * orientationTransform;
1894    return NO_ERROR;
1895}
1896
1897const DisplayHardware& GraphicPlane::displayHardware() const {
1898    return *mHw;
1899}
1900
1901const Transform& GraphicPlane::transform() const {
1902    return mGlobalTransform;
1903}
1904
1905EGLDisplay GraphicPlane::getEGLDisplay() const {
1906    return mHw->getEGLDisplay();
1907}
1908
1909// ---------------------------------------------------------------------------
1910
1911}; // namespace android
1912