SurfaceFlinger.cpp revision a1e6bc864fb821c1b470b7aad9b75c441f54eeb4
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    { // scope for the lock
525        Mutex::Autolock _l(mStateLock);
526        const nsecs_t now = systemTime();
527        mDebugInTransaction = now;
528        handleTransactionLocked(transactionFlags, ditchedLayers);
529        mLastTransactionTime = systemTime() - now;
530        mDebugInTransaction = 0;
531    }
532
533    // do this without lock held
534    const size_t count = ditchedLayers.size();
535    for (size_t i=0 ; i<count ; i++) {
536        if (ditchedLayers[i] != 0) {
537            //LOGD("ditching layer %p", ditchedLayers[i].get());
538            ditchedLayers[i]->ditch();
539        }
540    }
541}
542
543void SurfaceFlinger::handleTransactionLocked(
544        uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers)
545{
546    const LayerVector& currentLayers(mCurrentState.layersSortedByZ);
547    const size_t count = currentLayers.size();
548
549    /*
550     * Traversal of the children
551     * (perform the transaction for each of them if needed)
552     */
553
554    const bool layersNeedTransaction = transactionFlags & eTraversalNeeded;
555    if (layersNeedTransaction) {
556        for (size_t i=0 ; i<count ; i++) {
557            const sp<LayerBase>& layer = currentLayers[i];
558            uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded);
559            if (!trFlags) continue;
560
561            const uint32_t flags = layer->doTransaction(0);
562            if (flags & Layer::eVisibleRegion)
563                mVisibleRegionsDirty = true;
564        }
565    }
566
567    /*
568     * Perform our own transaction if needed
569     */
570
571    if (transactionFlags & eTransactionNeeded) {
572        if (mCurrentState.orientation != mDrawingState.orientation) {
573            // the orientation has changed, recompute all visible regions
574            // and invalidate everything.
575
576            const int dpy = 0;
577            const int orientation = mCurrentState.orientation;
578            const uint32_t type = mCurrentState.orientationType;
579            GraphicPlane& plane(graphicPlane(dpy));
580            plane.setOrientation(orientation);
581
582            // update the shared control block
583            const DisplayHardware& hw(plane.displayHardware());
584            volatile display_cblk_t* dcblk = mServerCblk->displays + dpy;
585            dcblk->orientation = orientation;
586            dcblk->w = plane.getWidth();
587            dcblk->h = plane.getHeight();
588
589            mVisibleRegionsDirty = true;
590            mDirtyRegion.set(hw.bounds());
591        }
592
593        if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) {
594            // freezing or unfreezing the display -> trigger animation if needed
595            mFreezeDisplay = mCurrentState.freezeDisplay;
596            if (mFreezeDisplay)
597                 mFreezeDisplayTime = 0;
598        }
599
600        if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) {
601            // layers have been added
602            mVisibleRegionsDirty = true;
603        }
604
605        // some layers might have been removed, so
606        // we need to update the regions they're exposing.
607        if (mLayersRemoved) {
608            mLayersRemoved = false;
609            mVisibleRegionsDirty = true;
610            const LayerVector& previousLayers(mDrawingState.layersSortedByZ);
611            const size_t count = previousLayers.size();
612            for (size_t i=0 ; i<count ; i++) {
613                const sp<LayerBase>& layer(previousLayers[i]);
614                if (currentLayers.indexOf( layer ) < 0) {
615                    // this layer is not visible anymore
616                    ditchedLayers.add(layer);
617                    mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen);
618                }
619            }
620        }
621    }
622
623    commitTransaction();
624}
625
626sp<FreezeLock> SurfaceFlinger::getFreezeLock() const
627{
628    return new FreezeLock(const_cast<SurfaceFlinger *>(this));
629}
630
631void SurfaceFlinger::computeVisibleRegions(
632    LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion)
633{
634    const GraphicPlane& plane(graphicPlane(0));
635    const Transform& planeTransform(plane.transform());
636    const DisplayHardware& hw(plane.displayHardware());
637    const Region screenRegion(hw.bounds());
638
639    Region aboveOpaqueLayers;
640    Region aboveCoveredLayers;
641    Region dirty;
642
643    bool secureFrameBuffer = false;
644
645    size_t i = currentLayers.size();
646    while (i--) {
647        const sp<LayerBase>& layer = currentLayers[i];
648        layer->validateVisibility(planeTransform);
649
650        // start with the whole surface at its current location
651        const Layer::State& s(layer->drawingState());
652
653        /*
654         * opaqueRegion: area of a surface that is fully opaque.
655         */
656        Region opaqueRegion;
657
658        /*
659         * visibleRegion: area of a surface that is visible on screen
660         * and not fully transparent. This is essentially the layer's
661         * footprint minus the opaque regions above it.
662         * Areas covered by a translucent surface are considered visible.
663         */
664        Region visibleRegion;
665
666        /*
667         * coveredRegion: area of a surface that is covered by all
668         * visible regions above it (which includes the translucent areas).
669         */
670        Region coveredRegion;
671
672
673        // handle hidden surfaces by setting the visible region to empty
674        if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) {
675            const bool translucent = layer->needsBlending();
676            const Rect bounds(layer->visibleBounds());
677            visibleRegion.set(bounds);
678            visibleRegion.andSelf(screenRegion);
679            if (!visibleRegion.isEmpty()) {
680                // Remove the transparent area from the visible region
681                if (translucent) {
682                    visibleRegion.subtractSelf(layer->transparentRegionScreen);
683                }
684
685                // compute the opaque region
686                const int32_t layerOrientation = layer->getOrientation();
687                if (s.alpha==255 && !translucent &&
688                        ((layerOrientation & Transform::ROT_INVALID) == false)) {
689                    // the opaque region is the layer's footprint
690                    opaqueRegion = visibleRegion;
691                }
692            }
693        }
694
695        // Clip the covered region to the visible region
696        coveredRegion = aboveCoveredLayers.intersect(visibleRegion);
697
698        // Update aboveCoveredLayers for next (lower) layer
699        aboveCoveredLayers.orSelf(visibleRegion);
700
701        // subtract the opaque region covered by the layers above us
702        visibleRegion.subtractSelf(aboveOpaqueLayers);
703
704        // compute this layer's dirty region
705        if (layer->contentDirty) {
706            // we need to invalidate the whole region
707            dirty = visibleRegion;
708            // as well, as the old visible region
709            dirty.orSelf(layer->visibleRegionScreen);
710            layer->contentDirty = false;
711        } else {
712            /* compute the exposed region:
713             *   the exposed region consists of two components:
714             *   1) what's VISIBLE now and was COVERED before
715             *   2) what's EXPOSED now less what was EXPOSED before
716             *
717             * note that (1) is conservative, we start with the whole
718             * visible region but only keep what used to be covered by
719             * something -- which mean it may have been exposed.
720             *
721             * (2) handles areas that were not covered by anything but got
722             * exposed because of a resize.
723             */
724            const Region newExposed = visibleRegion - coveredRegion;
725            const Region oldVisibleRegion = layer->visibleRegionScreen;
726            const Region oldCoveredRegion = layer->coveredRegionScreen;
727            const Region oldExposed = oldVisibleRegion - oldCoveredRegion;
728            dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed);
729        }
730        dirty.subtractSelf(aboveOpaqueLayers);
731
732        // accumulate to the screen dirty region
733        dirtyRegion.orSelf(dirty);
734
735        // Update aboveOpaqueLayers for next (lower) layer
736        aboveOpaqueLayers.orSelf(opaqueRegion);
737
738        // Store the visible region is screen space
739        layer->setVisibleRegion(visibleRegion);
740        layer->setCoveredRegion(coveredRegion);
741
742        // If a secure layer is partially visible, lock-down the screen!
743        if (layer->isSecure() && !visibleRegion.isEmpty()) {
744            secureFrameBuffer = true;
745        }
746    }
747
748    // invalidate the areas where a layer was removed
749    dirtyRegion.orSelf(mDirtyRegionRemovedLayer);
750    mDirtyRegionRemovedLayer.clear();
751
752    mSecureFrameBuffer = secureFrameBuffer;
753    opaqueRegion = aboveOpaqueLayers;
754}
755
756
757void SurfaceFlinger::commitTransaction()
758{
759    mDrawingState = mCurrentState;
760    mResizeTransationPending = false;
761    mTransactionCV.broadcast();
762}
763
764void SurfaceFlinger::handlePageFlip()
765{
766    bool visibleRegions = mVisibleRegionsDirty;
767    LayerVector& currentLayers = const_cast<LayerVector&>(
768            mDrawingState.layersSortedByZ);
769    visibleRegions |= lockPageFlip(currentLayers);
770
771        const DisplayHardware& hw = graphicPlane(0).displayHardware();
772        const Region screenRegion(hw.bounds());
773        if (visibleRegions) {
774            Region opaqueRegion;
775            computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion);
776            mWormholeRegion = screenRegion.subtract(opaqueRegion);
777            mVisibleRegionsDirty = false;
778        }
779
780    unlockPageFlip(currentLayers);
781    mDirtyRegion.andSelf(screenRegion);
782}
783
784bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers)
785{
786    bool recomputeVisibleRegions = false;
787    size_t count = currentLayers.size();
788    sp<LayerBase> const* layers = currentLayers.array();
789    for (size_t i=0 ; i<count ; i++) {
790        const sp<LayerBase>& layer(layers[i]);
791        layer->lockPageFlip(recomputeVisibleRegions);
792    }
793    return recomputeVisibleRegions;
794}
795
796void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers)
797{
798    const GraphicPlane& plane(graphicPlane(0));
799    const Transform& planeTransform(plane.transform());
800    size_t count = currentLayers.size();
801    sp<LayerBase> const* layers = currentLayers.array();
802    for (size_t i=0 ; i<count ; i++) {
803        const sp<LayerBase>& layer(layers[i]);
804        layer->unlockPageFlip(planeTransform, mDirtyRegion);
805    }
806}
807
808
809void SurfaceFlinger::handleRepaint()
810{
811    // compute the invalid region
812    mInvalidRegion.orSelf(mDirtyRegion);
813    if (mInvalidRegion.isEmpty()) {
814        // nothing to do
815        return;
816    }
817
818    if (UNLIKELY(mDebugRegion)) {
819        debugFlashRegions();
820    }
821
822    // set the frame buffer
823    const DisplayHardware& hw(graphicPlane(0).displayHardware());
824    glMatrixMode(GL_MODELVIEW);
825    glLoadIdentity();
826
827    uint32_t flags = hw.getFlags();
828    if ((flags & DisplayHardware::SWAP_RECTANGLE) ||
829        (flags & DisplayHardware::BUFFER_PRESERVED))
830    {
831        // we can redraw only what's dirty, but since SWAP_RECTANGLE only
832        // takes a rectangle, we must make sure to update that whole
833        // rectangle in that case
834        if (flags & DisplayHardware::SWAP_RECTANGLE) {
835            // TODO: we really should be able to pass a region to
836            // SWAP_RECTANGLE so that we don't have to redraw all this.
837            mDirtyRegion.set(mInvalidRegion.bounds());
838        } else {
839            // in the BUFFER_PRESERVED case, obviously, we can update only
840            // what's needed and nothing more.
841            // NOTE: this is NOT a common case, as preserving the backbuffer
842            // is costly and usually involves copying the whole update back.
843        }
844    } else {
845        if (flags & DisplayHardware::PARTIAL_UPDATES) {
846            // We need to redraw the rectangle that will be updated
847            // (pushed to the framebuffer).
848            // This is needed because PARTIAL_UPDATES only takes one
849            // rectangle instead of a region (see DisplayHardware::flip())
850            mDirtyRegion.set(mInvalidRegion.bounds());
851        } else {
852            // we need to redraw everything (the whole screen)
853            mDirtyRegion.set(hw.bounds());
854            mInvalidRegion = mDirtyRegion;
855        }
856    }
857
858    // compose all surfaces
859    composeSurfaces(mDirtyRegion);
860
861    // clear the dirty regions
862    mDirtyRegion.clear();
863}
864
865void SurfaceFlinger::composeSurfaces(const Region& dirty)
866{
867    if (UNLIKELY(!mWormholeRegion.isEmpty())) {
868        // should never happen unless the window manager has a bug
869        // draw something...
870        drawWormhole();
871    }
872    const SurfaceFlinger& flinger(*this);
873    const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
874    const size_t count = drawingLayers.size();
875    sp<LayerBase> const* const layers = drawingLayers.array();
876    for (size_t i=0 ; i<count ; ++i) {
877        const sp<LayerBase>& layer = layers[i];
878        const Region& visibleRegion(layer->visibleRegionScreen);
879        if (!visibleRegion.isEmpty())  {
880            const Region clip(dirty.intersect(visibleRegion));
881            if (!clip.isEmpty()) {
882                layer->draw(clip);
883            }
884        }
885    }
886}
887
888void SurfaceFlinger::unlockClients()
889{
890    const LayerVector& drawingLayers(mDrawingState.layersSortedByZ);
891    const size_t count = drawingLayers.size();
892    sp<LayerBase> const* const layers = drawingLayers.array();
893    for (size_t i=0 ; i<count ; ++i) {
894        const sp<LayerBase>& layer = layers[i];
895        layer->finishPageFlip();
896    }
897}
898
899void SurfaceFlinger::debugFlashRegions()
900{
901    const DisplayHardware& hw(graphicPlane(0).displayHardware());
902    const uint32_t flags = hw.getFlags();
903
904    if (!((flags & DisplayHardware::SWAP_RECTANGLE) ||
905            (flags & DisplayHardware::BUFFER_PRESERVED))) {
906        const Region repaint((flags & DisplayHardware::PARTIAL_UPDATES) ?
907                mDirtyRegion.bounds() : hw.bounds());
908        composeSurfaces(repaint);
909    }
910
911    TextureManager::deactivateTextures();
912
913    glDisable(GL_BLEND);
914    glDisable(GL_DITHER);
915    glDisable(GL_SCISSOR_TEST);
916
917    static int toggle = 0;
918    toggle = 1 - toggle;
919    if (toggle) {
920        glColor4f(1, 0, 1, 1);
921    } else {
922        glColor4f(1, 1, 0, 1);
923    }
924
925    Region::const_iterator it = mDirtyRegion.begin();
926    Region::const_iterator const end = mDirtyRegion.end();
927    while (it != end) {
928        const Rect& r = *it++;
929        GLfloat vertices[][2] = {
930                { r.left,  r.top },
931                { r.left,  r.bottom },
932                { r.right, r.bottom },
933                { r.right, r.top }
934        };
935        glVertexPointer(2, GL_FLOAT, 0, vertices);
936        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
937    }
938
939    if (mInvalidRegion.isEmpty()) {
940        mDirtyRegion.dump("mDirtyRegion");
941        mInvalidRegion.dump("mInvalidRegion");
942    }
943    hw.flip(mInvalidRegion);
944
945    if (mDebugRegion > 1)
946        usleep(mDebugRegion * 1000);
947
948    glEnable(GL_SCISSOR_TEST);
949    //mDirtyRegion.dump("mDirtyRegion");
950}
951
952void SurfaceFlinger::drawWormhole() const
953{
954    const Region region(mWormholeRegion.intersect(mDirtyRegion));
955    if (region.isEmpty())
956        return;
957
958    const DisplayHardware& hw(graphicPlane(0).displayHardware());
959    const int32_t width = hw.getWidth();
960    const int32_t height = hw.getHeight();
961
962    glDisable(GL_BLEND);
963    glDisable(GL_DITHER);
964
965    if (LIKELY(!mDebugBackground)) {
966        glClearColor(0,0,0,0);
967        Region::const_iterator it = region.begin();
968        Region::const_iterator const end = region.end();
969        while (it != end) {
970            const Rect& r = *it++;
971            const GLint sy = height - (r.top + r.height());
972            glScissor(r.left, sy, r.width(), r.height());
973            glClear(GL_COLOR_BUFFER_BIT);
974        }
975    } else {
976        const GLshort vertices[][2] = { { 0, 0 }, { width, 0 },
977                { width, height }, { 0, height }  };
978        const GLshort tcoords[][2] = { { 0, 0 }, { 1, 0 },  { 1, 1 }, { 0, 1 } };
979        glVertexPointer(2, GL_SHORT, 0, vertices);
980        glTexCoordPointer(2, GL_SHORT, 0, tcoords);
981        glEnableClientState(GL_TEXTURE_COORD_ARRAY);
982#if defined(GL_OES_texture_external)
983        if (GLExtensions::getInstance().haveTextureExternal()) {
984            glDisable(GL_TEXTURE_EXTERNAL_OES);
985        }
986#endif
987        glEnable(GL_TEXTURE_2D);
988        glBindTexture(GL_TEXTURE_2D, mWormholeTexName);
989        glTexEnvx(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);
990        glMatrixMode(GL_TEXTURE);
991        glLoadIdentity();
992        glScalef(width*(1.0f/32.0f), height*(1.0f/32.0f), 1);
993        Region::const_iterator it = region.begin();
994        Region::const_iterator const end = region.end();
995        while (it != end) {
996            const Rect& r = *it++;
997            const GLint sy = height - (r.top + r.height());
998            glScissor(r.left, sy, r.width(), r.height());
999            glDrawArrays(GL_TRIANGLE_FAN, 0, 4);
1000        }
1001        glDisableClientState(GL_TEXTURE_COORD_ARRAY);
1002    }
1003}
1004
1005void SurfaceFlinger::debugShowFPS() const
1006{
1007    static int mFrameCount;
1008    static int mLastFrameCount = 0;
1009    static nsecs_t mLastFpsTime = 0;
1010    static float mFps = 0;
1011    mFrameCount++;
1012    nsecs_t now = systemTime();
1013    nsecs_t diff = now - mLastFpsTime;
1014    if (diff > ms2ns(250)) {
1015        mFps =  ((mFrameCount - mLastFrameCount) * float(s2ns(1))) / diff;
1016        mLastFpsTime = now;
1017        mLastFrameCount = mFrameCount;
1018    }
1019    // XXX: mFPS has the value we want
1020 }
1021
1022status_t SurfaceFlinger::addLayer(const sp<LayerBase>& layer)
1023{
1024    Mutex::Autolock _l(mStateLock);
1025    addLayer_l(layer);
1026    setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1027    return NO_ERROR;
1028}
1029
1030status_t SurfaceFlinger::addLayer_l(const sp<LayerBase>& layer)
1031{
1032    ssize_t i = mCurrentState.layersSortedByZ.add(
1033                layer, &LayerBase::compareCurrentStateZ);
1034    return (i < 0) ? status_t(i) : status_t(NO_ERROR);
1035}
1036
1037ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client,
1038        const sp<LayerBaseClient>& lbc)
1039{
1040    Mutex::Autolock _l(mStateLock);
1041
1042    // attach this layer to the client
1043    ssize_t name = client->attachLayer(lbc);
1044
1045    // add this layer to the current state list
1046    addLayer_l(lbc);
1047
1048    return name;
1049}
1050
1051status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer)
1052{
1053    Mutex::Autolock _l(mStateLock);
1054    status_t err = purgatorizeLayer_l(layer);
1055    if (err == NO_ERROR)
1056        setTransactionFlags(eTransactionNeeded);
1057    return err;
1058}
1059
1060status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase)
1061{
1062    sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient());
1063    if (lbc != 0) {
1064        mLayerMap.removeItem( lbc->getSurface()->asBinder() );
1065    }
1066    ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase);
1067    if (index >= 0) {
1068        mLayersRemoved = true;
1069        return NO_ERROR;
1070    }
1071    return status_t(index);
1072}
1073
1074status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase)
1075{
1076    // remove the layer from the main list (through a transaction).
1077    ssize_t err = removeLayer_l(layerBase);
1078
1079    layerBase->onRemoved();
1080
1081    // it's possible that we don't find a layer, because it might
1082    // have been destroyed already -- this is not technically an error
1083    // from the user because there is a race between Client::destroySurface(),
1084    // ~Client() and ~ISurface().
1085    return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err;
1086}
1087
1088status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer)
1089{
1090    layer->forceVisibilityTransaction();
1091    setTransactionFlags(eTraversalNeeded);
1092    return NO_ERROR;
1093}
1094
1095uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags)
1096{
1097    return android_atomic_and(~flags, &mTransactionFlags) & flags;
1098}
1099
1100uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags)
1101{
1102    uint32_t old = android_atomic_or(flags, &mTransactionFlags);
1103    if ((old & flags)==0) { // wake the server up
1104        signalEvent();
1105    }
1106    return old;
1107}
1108
1109void SurfaceFlinger::openGlobalTransaction()
1110{
1111    android_atomic_inc(&mTransactionCount);
1112}
1113
1114void SurfaceFlinger::closeGlobalTransaction()
1115{
1116    if (android_atomic_dec(&mTransactionCount) == 1) {
1117        signalEvent();
1118
1119        // if there is a transaction with a resize, wait for it to
1120        // take effect before returning.
1121        Mutex::Autolock _l(mStateLock);
1122        while (mResizeTransationPending) {
1123            status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5));
1124            if (CC_UNLIKELY(err != NO_ERROR)) {
1125                // just in case something goes wrong in SF, return to the
1126                // called after a few seconds.
1127                LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!");
1128                mResizeTransationPending = false;
1129                break;
1130            }
1131        }
1132    }
1133}
1134
1135status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags)
1136{
1137    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1138        return BAD_VALUE;
1139
1140    Mutex::Autolock _l(mStateLock);
1141    mCurrentState.freezeDisplay = 1;
1142    setTransactionFlags(eTransactionNeeded);
1143
1144    // flags is intended to communicate some sort of animation behavior
1145    // (for instance fading)
1146    return NO_ERROR;
1147}
1148
1149status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags)
1150{
1151    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1152        return BAD_VALUE;
1153
1154    Mutex::Autolock _l(mStateLock);
1155    mCurrentState.freezeDisplay = 0;
1156    setTransactionFlags(eTransactionNeeded);
1157
1158    // flags is intended to communicate some sort of animation behavior
1159    // (for instance fading)
1160    return NO_ERROR;
1161}
1162
1163int SurfaceFlinger::setOrientation(DisplayID dpy,
1164        int orientation, uint32_t flags)
1165{
1166    if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT))
1167        return BAD_VALUE;
1168
1169    Mutex::Autolock _l(mStateLock);
1170    if (mCurrentState.orientation != orientation) {
1171        if (uint32_t(orientation)<=eOrientation270 || orientation==42) {
1172            mCurrentState.orientationType = flags;
1173            mCurrentState.orientation = orientation;
1174            setTransactionFlags(eTransactionNeeded);
1175            mTransactionCV.wait(mStateLock);
1176        } else {
1177            orientation = BAD_VALUE;
1178        }
1179    }
1180    return orientation;
1181}
1182
1183sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid,
1184        const String8& name, ISurfaceComposerClient::surface_data_t* params,
1185        DisplayID d, uint32_t w, uint32_t h, PixelFormat format,
1186        uint32_t flags)
1187{
1188    sp<LayerBaseClient> layer;
1189    sp<LayerBaseClient::Surface> surfaceHandle;
1190
1191    if (int32_t(w|h) < 0) {
1192        LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)",
1193                int(w), int(h));
1194        return surfaceHandle;
1195    }
1196
1197    //LOGD("createSurface for pid %d (%d x %d)", pid, w, h);
1198    sp<Layer> normalLayer;
1199    switch (flags & eFXSurfaceMask) {
1200        case eFXSurfaceNormal:
1201            if (UNLIKELY(flags & ePushBuffers)) {
1202                layer = createPushBuffersSurface(client, d, w, h, flags);
1203            } else {
1204                normalLayer = createNormalSurface(client, d, w, h, flags, format);
1205                layer = normalLayer;
1206            }
1207            break;
1208        case eFXSurfaceBlur:
1209            layer = createBlurSurface(client, d, w, h, flags);
1210            break;
1211        case eFXSurfaceDim:
1212            layer = createDimSurface(client, d, w, h, flags);
1213            break;
1214    }
1215
1216    if (layer != 0) {
1217        layer->initStates(w, h, flags);
1218        layer->setName(name);
1219        ssize_t token = addClientLayer(client, layer);
1220
1221        surfaceHandle = layer->getSurface();
1222        if (surfaceHandle != 0) {
1223            params->token = token;
1224            params->identity = surfaceHandle->getIdentity();
1225            params->width = w;
1226            params->height = h;
1227            params->format = format;
1228            if (normalLayer != 0) {
1229                Mutex::Autolock _l(mStateLock);
1230                mLayerMap.add(surfaceHandle->asBinder(), normalLayer);
1231            }
1232        }
1233
1234        setTransactionFlags(eTransactionNeeded);
1235    }
1236
1237    return surfaceHandle;
1238}
1239
1240sp<Layer> SurfaceFlinger::createNormalSurface(
1241        const sp<Client>& client, DisplayID display,
1242        uint32_t w, uint32_t h, uint32_t flags,
1243        PixelFormat& format)
1244{
1245    // initialize the surfaces
1246    switch (format) { // TODO: take h/w into account
1247    case PIXEL_FORMAT_TRANSPARENT:
1248    case PIXEL_FORMAT_TRANSLUCENT:
1249        format = PIXEL_FORMAT_RGBA_8888;
1250        break;
1251    case PIXEL_FORMAT_OPAQUE:
1252#ifdef NO_RGBX_8888
1253        format = PIXEL_FORMAT_RGB_565;
1254#else
1255        format = PIXEL_FORMAT_RGBX_8888;
1256#endif
1257        break;
1258    }
1259
1260#ifdef NO_RGBX_8888
1261    if (format == PIXEL_FORMAT_RGBX_8888)
1262        format = PIXEL_FORMAT_RGBA_8888;
1263#endif
1264
1265    sp<Layer> layer = new Layer(this, display, client);
1266    status_t err = layer->setBuffers(w, h, format, flags);
1267    if (LIKELY(err != NO_ERROR)) {
1268        LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err));
1269        layer.clear();
1270    }
1271    return layer;
1272}
1273
1274sp<LayerBlur> SurfaceFlinger::createBlurSurface(
1275        const sp<Client>& client, DisplayID display,
1276        uint32_t w, uint32_t h, uint32_t flags)
1277{
1278    sp<LayerBlur> layer = new LayerBlur(this, display, client);
1279    layer->initStates(w, h, flags);
1280    return layer;
1281}
1282
1283sp<LayerDim> SurfaceFlinger::createDimSurface(
1284        const sp<Client>& client, DisplayID display,
1285        uint32_t w, uint32_t h, uint32_t flags)
1286{
1287    sp<LayerDim> layer = new LayerDim(this, display, client);
1288    layer->initStates(w, h, flags);
1289    return layer;
1290}
1291
1292sp<LayerBuffer> SurfaceFlinger::createPushBuffersSurface(
1293        const sp<Client>& client, DisplayID display,
1294        uint32_t w, uint32_t h, uint32_t flags)
1295{
1296    sp<LayerBuffer> layer = new LayerBuffer(this, display, client);
1297    layer->initStates(w, h, flags);
1298    return layer;
1299}
1300
1301status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid)
1302{
1303    /*
1304     * called by the window manager, when a surface should be marked for
1305     * destruction.
1306     *
1307     * The surface is removed from the current and drawing lists, but placed
1308     * in the purgatory queue, so it's not destroyed right-away (we need
1309     * to wait for all client's references to go away first).
1310     */
1311
1312    status_t err = NAME_NOT_FOUND;
1313    Mutex::Autolock _l(mStateLock);
1314    sp<LayerBaseClient> layer = client->getLayerUser(sid);
1315    if (layer != 0) {
1316        err = purgatorizeLayer_l(layer);
1317        if (err == NO_ERROR) {
1318            setTransactionFlags(eTransactionNeeded);
1319        }
1320    }
1321    return err;
1322}
1323
1324status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer)
1325{
1326    // called by ~ISurface() when all references are gone
1327
1328    class MessageDestroySurface : public MessageBase {
1329        SurfaceFlinger* flinger;
1330        sp<LayerBaseClient> layer;
1331    public:
1332        MessageDestroySurface(
1333                SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer)
1334            : flinger(flinger), layer(layer) { }
1335        virtual bool handler() {
1336            sp<LayerBaseClient> l(layer);
1337            layer.clear(); // clear it outside of the lock;
1338            Mutex::Autolock _l(flinger->mStateLock);
1339            /*
1340             * remove the layer from the current list -- chances are that it's
1341             * not in the list anyway, because it should have been removed
1342             * already upon request of the client (eg: window manager).
1343             * However, a buggy client could have not done that.
1344             * Since we know we don't have any more clients, we don't need
1345             * to use the purgatory.
1346             */
1347            status_t err = flinger->removeLayer_l(l);
1348            LOGE_IF(err<0 && err != NAME_NOT_FOUND,
1349                    "error removing layer=%p (%s)", l.get(), strerror(-err));
1350            return true;
1351        }
1352    };
1353
1354    postMessageAsync( new MessageDestroySurface(this, layer) );
1355    return NO_ERROR;
1356}
1357
1358status_t SurfaceFlinger::setClientState(
1359        const sp<Client>& client,
1360        int32_t count,
1361        const layer_state_t* states)
1362{
1363    Mutex::Autolock _l(mStateLock);
1364    uint32_t flags = 0;
1365    for (int i=0 ; i<count ; i++) {
1366        const layer_state_t& s(states[i]);
1367        sp<LayerBaseClient> layer(client->getLayerUser(s.surface));
1368        if (layer != 0) {
1369            const uint32_t what = s.what;
1370            if (what & ePositionChanged) {
1371                if (layer->setPosition(s.x, s.y))
1372                    flags |= eTraversalNeeded;
1373            }
1374            if (what & eLayerChanged) {
1375                if (layer->setLayer(s.z)) {
1376                    mCurrentState.layersSortedByZ.reorder(
1377                            layer, &Layer::compareCurrentStateZ);
1378                    // we need traversal (state changed)
1379                    // AND transaction (list changed)
1380                    flags |= eTransactionNeeded|eTraversalNeeded;
1381                }
1382            }
1383            if (what & eSizeChanged) {
1384                if (layer->setSize(s.w, s.h)) {
1385                    flags |= eTraversalNeeded;
1386                    mResizeTransationPending = true;
1387                }
1388            }
1389            if (what & eAlphaChanged) {
1390                if (layer->setAlpha(uint8_t(255.0f*s.alpha+0.5f)))
1391                    flags |= eTraversalNeeded;
1392            }
1393            if (what & eMatrixChanged) {
1394                if (layer->setMatrix(s.matrix))
1395                    flags |= eTraversalNeeded;
1396            }
1397            if (what & eTransparentRegionChanged) {
1398                if (layer->setTransparentRegionHint(s.transparentRegion))
1399                    flags |= eTraversalNeeded;
1400            }
1401            if (what & eVisibilityChanged) {
1402                if (layer->setFlags(s.flags, s.mask))
1403                    flags |= eTraversalNeeded;
1404            }
1405        }
1406    }
1407    if (flags) {
1408        setTransactionFlags(flags);
1409    }
1410    return NO_ERROR;
1411}
1412
1413void SurfaceFlinger::screenReleased(int dpy)
1414{
1415    // this may be called by a signal handler, we can't do too much in here
1416    android_atomic_or(eConsoleReleased, &mConsoleSignals);
1417    signalEvent();
1418}
1419
1420void SurfaceFlinger::screenAcquired(int dpy)
1421{
1422    // this may be called by a signal handler, we can't do too much in here
1423    android_atomic_or(eConsoleAcquired, &mConsoleSignals);
1424    signalEvent();
1425}
1426
1427status_t SurfaceFlinger::dump(int fd, const Vector<String16>& args)
1428{
1429    const size_t SIZE = 1024;
1430    char buffer[SIZE];
1431    String8 result;
1432    if (!mDump.checkCalling()) {
1433        snprintf(buffer, SIZE, "Permission Denial: "
1434                "can't dump SurfaceFlinger from pid=%d, uid=%d\n",
1435                IPCThreadState::self()->getCallingPid(),
1436                IPCThreadState::self()->getCallingUid());
1437        result.append(buffer);
1438    } else {
1439
1440        // figure out if we're stuck somewhere
1441        const nsecs_t now = systemTime();
1442        const nsecs_t inSwapBuffers(mDebugInSwapBuffers);
1443        const nsecs_t inTransaction(mDebugInTransaction);
1444        nsecs_t inSwapBuffersDuration = (inSwapBuffers) ? now-inSwapBuffers : 0;
1445        nsecs_t inTransactionDuration = (inTransaction) ? now-inTransaction : 0;
1446
1447        // Try to get the main lock, but don't insist if we can't
1448        // (this would indicate SF is stuck, but we want to be able to
1449        // print something in dumpsys).
1450        int retry = 3;
1451        while (mStateLock.tryLock()<0 && --retry>=0) {
1452            usleep(1000000);
1453        }
1454        const bool locked(retry >= 0);
1455        if (!locked) {
1456            snprintf(buffer, SIZE,
1457                    "SurfaceFlinger appears to be unresponsive, "
1458                    "dumping anyways (no locks held)\n");
1459            result.append(buffer);
1460        }
1461
1462        const LayerVector& currentLayers = mCurrentState.layersSortedByZ;
1463        const size_t count = currentLayers.size();
1464        for (size_t i=0 ; i<count ; i++) {
1465            const sp<LayerBase>& layer(currentLayers[i]);
1466            layer->dump(result, buffer, SIZE);
1467            const Layer::State& s(layer->drawingState());
1468            s.transparentRegion.dump(result, "transparentRegion");
1469            layer->transparentRegionScreen.dump(result, "transparentRegionScreen");
1470            layer->visibleRegionScreen.dump(result, "visibleRegionScreen");
1471        }
1472
1473        mWormholeRegion.dump(result, "WormholeRegion");
1474        const DisplayHardware& hw(graphicPlane(0).displayHardware());
1475        snprintf(buffer, SIZE,
1476                "  display frozen: %s, freezeCount=%d, orientation=%d, canDraw=%d\n",
1477                mFreezeDisplay?"yes":"no", mFreezeCount,
1478                mCurrentState.orientation, hw.canDraw());
1479        result.append(buffer);
1480        snprintf(buffer, SIZE,
1481                "  last eglSwapBuffers() time: %f us\n"
1482                "  last transaction time     : %f us\n",
1483                mLastSwapBufferTime/1000.0, mLastTransactionTime/1000.0);
1484        result.append(buffer);
1485
1486        if (inSwapBuffersDuration || !locked) {
1487            snprintf(buffer, SIZE, "  eglSwapBuffers time: %f us\n",
1488                    inSwapBuffersDuration/1000.0);
1489            result.append(buffer);
1490        }
1491
1492        if (inTransactionDuration || !locked) {
1493            snprintf(buffer, SIZE, "  transaction time: %f us\n",
1494                    inTransactionDuration/1000.0);
1495            result.append(buffer);
1496        }
1497
1498        const GraphicBufferAllocator& alloc(GraphicBufferAllocator::get());
1499        alloc.dump(result);
1500
1501        if (locked) {
1502            mStateLock.unlock();
1503        }
1504    }
1505    write(fd, result.string(), result.size());
1506    return NO_ERROR;
1507}
1508
1509status_t SurfaceFlinger::onTransact(
1510    uint32_t code, const Parcel& data, Parcel* reply, uint32_t flags)
1511{
1512    switch (code) {
1513        case CREATE_CONNECTION:
1514        case OPEN_GLOBAL_TRANSACTION:
1515        case CLOSE_GLOBAL_TRANSACTION:
1516        case SET_ORIENTATION:
1517        case FREEZE_DISPLAY:
1518        case UNFREEZE_DISPLAY:
1519        case BOOT_FINISHED:
1520        {
1521            // codes that require permission check
1522            IPCThreadState* ipc = IPCThreadState::self();
1523            const int pid = ipc->getCallingPid();
1524            const int uid = ipc->getCallingUid();
1525            if ((uid != AID_GRAPHICS) && !mAccessSurfaceFlinger.check(pid, uid)) {
1526                LOGE("Permission Denial: "
1527                        "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1528                return PERMISSION_DENIED;
1529            }
1530        }
1531    }
1532    status_t err = BnSurfaceComposer::onTransact(code, data, reply, flags);
1533    if (err == UNKNOWN_TRANSACTION || err == PERMISSION_DENIED) {
1534        CHECK_INTERFACE(ISurfaceComposer, data, reply);
1535        if (UNLIKELY(!mHardwareTest.checkCalling())) {
1536            IPCThreadState* ipc = IPCThreadState::self();
1537            const int pid = ipc->getCallingPid();
1538            const int uid = ipc->getCallingUid();
1539            LOGE("Permission Denial: "
1540                    "can't access SurfaceFlinger pid=%d, uid=%d", pid, uid);
1541            return PERMISSION_DENIED;
1542        }
1543        int n;
1544        switch (code) {
1545            case 1000: // SHOW_CPU, NOT SUPPORTED ANYMORE
1546                return NO_ERROR;
1547            case 1001:  // SHOW_FPS, NOT SUPPORTED ANYMORE
1548                return NO_ERROR;
1549            case 1002:  // SHOW_UPDATES
1550                n = data.readInt32();
1551                mDebugRegion = n ? n : (mDebugRegion ? 0 : 1);
1552                return NO_ERROR;
1553            case 1003:  // SHOW_BACKGROUND
1554                n = data.readInt32();
1555                mDebugBackground = n ? 1 : 0;
1556                return NO_ERROR;
1557            case 1004:{ // repaint everything
1558                Mutex::Autolock _l(mStateLock);
1559                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1560                mDirtyRegion.set(hw.bounds()); // careful that's not thread-safe
1561                signalEvent();
1562                return NO_ERROR;
1563            }
1564            case 1005:{ // force transaction
1565                setTransactionFlags(eTransactionNeeded|eTraversalNeeded);
1566                return NO_ERROR;
1567            }
1568            case 1007: // set mFreezeCount
1569                mFreezeCount = data.readInt32();
1570                mFreezeDisplayTime = 0;
1571                return NO_ERROR;
1572            case 1010:  // interrogate.
1573                reply->writeInt32(0);
1574                reply->writeInt32(0);
1575                reply->writeInt32(mDebugRegion);
1576                reply->writeInt32(mDebugBackground);
1577                return NO_ERROR;
1578            case 1013: {
1579                Mutex::Autolock _l(mStateLock);
1580                const DisplayHardware& hw(graphicPlane(0).displayHardware());
1581                reply->writeInt32(hw.getPageFlipCount());
1582            }
1583            return NO_ERROR;
1584        }
1585    }
1586    return err;
1587}
1588
1589// ---------------------------------------------------------------------------
1590
1591sp<Layer> SurfaceFlinger::getLayer(const sp<ISurface>& sur) const
1592{
1593    sp<Layer> result;
1594    Mutex::Autolock _l(mStateLock);
1595    result = mLayerMap.valueFor( sur->asBinder() ).promote();
1596    return result;
1597}
1598
1599// ---------------------------------------------------------------------------
1600
1601Client::Client(const sp<SurfaceFlinger>& flinger)
1602    : mFlinger(flinger), mNameGenerator(1)
1603{
1604}
1605
1606Client::~Client()
1607{
1608    const size_t count = mLayers.size();
1609    for (size_t i=0 ; i<count ; i++) {
1610        sp<LayerBaseClient> layer(mLayers.valueAt(i).promote());
1611        if (layer != 0) {
1612            mFlinger->removeLayer(layer);
1613        }
1614    }
1615}
1616
1617status_t Client::initCheck() const {
1618    return NO_ERROR;
1619}
1620
1621ssize_t Client::attachLayer(const sp<LayerBaseClient>& layer)
1622{
1623    int32_t name = android_atomic_inc(&mNameGenerator);
1624    mLayers.add(name, layer);
1625    return name;
1626}
1627
1628void Client::detachLayer(const LayerBaseClient* layer)
1629{
1630    // we do a linear search here, because this doesn't happen often
1631    const size_t count = mLayers.size();
1632    for (size_t i=0 ; i<count ; i++) {
1633        if (mLayers.valueAt(i) == layer) {
1634            mLayers.removeItemsAt(i, 1);
1635            break;
1636        }
1637    }
1638}
1639sp<LayerBaseClient> Client::getLayerUser(int32_t i) const {
1640    sp<LayerBaseClient> lbc;
1641    const wp<LayerBaseClient>& layer(mLayers.valueFor(i));
1642    if (layer != 0) {
1643        lbc = layer.promote();
1644        LOGE_IF(lbc==0, "getLayerUser(name=%d) is dead", int(i));
1645    }
1646    return lbc;
1647}
1648
1649sp<IMemoryHeap> Client::getControlBlock() const {
1650    return 0;
1651}
1652ssize_t Client::getTokenForSurface(const sp<ISurface>& sur) const {
1653    return -1;
1654}
1655sp<ISurface> Client::createSurface(
1656        ISurfaceComposerClient::surface_data_t* params, int pid,
1657        const String8& name,
1658        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1659        uint32_t flags)
1660{
1661    return mFlinger->createSurface(this, pid, name, params,
1662            display, w, h, format, flags);
1663}
1664status_t Client::destroySurface(SurfaceID sid) {
1665    return mFlinger->removeSurface(this, sid);
1666}
1667status_t Client::setState(int32_t count, const layer_state_t* states) {
1668    return mFlinger->setClientState(this, count, states);
1669}
1670
1671// ---------------------------------------------------------------------------
1672
1673UserClient::UserClient(const sp<SurfaceFlinger>& flinger)
1674    : ctrlblk(0), mBitmap(0), mFlinger(flinger)
1675{
1676    const int pgsize = getpagesize();
1677    const int cblksize = ((sizeof(SharedClient)+(pgsize-1))&~(pgsize-1));
1678
1679    mCblkHeap = new MemoryHeapBase(cblksize, 0,
1680            "SurfaceFlinger Client control-block");
1681
1682    ctrlblk = static_cast<SharedClient *>(mCblkHeap->getBase());
1683    if (ctrlblk) { // construct the shared structure in-place.
1684        new(ctrlblk) SharedClient;
1685    }
1686}
1687
1688UserClient::~UserClient()
1689{
1690    if (ctrlblk) {
1691        ctrlblk->~SharedClient();  // destroy our shared-structure.
1692    }
1693
1694    /*
1695     * When a UserClient dies, it's unclear what to do exactly.
1696     * We could go ahead and destroy all surfaces linked to that client
1697     * however, it wouldn't be fair to the main Client
1698     * (usually the the window-manager), which might want to re-target
1699     * the layer to another UserClient.
1700     * I think the best is to do nothing, or not much; in most cases the
1701     * WM itself will go ahead and clean things up when it detects a client of
1702     * his has died.
1703     * The remaining question is what to display? currently we keep
1704     * just keep the current buffer.
1705     */
1706}
1707
1708status_t UserClient::initCheck() const {
1709    return ctrlblk == 0 ? NO_INIT : NO_ERROR;
1710}
1711
1712void UserClient::detachLayer(const Layer* layer)
1713{
1714    int32_t name = layer->getToken();
1715    if (name >= 0) {
1716        int32_t mask = 1LU<<name;
1717        if ((android_atomic_and(~mask, &mBitmap) & mask) == 0) {
1718            LOGW("token %d wasn't marked as used %08x", name, int(mBitmap));
1719        }
1720    }
1721}
1722
1723sp<IMemoryHeap> UserClient::getControlBlock() const {
1724    return mCblkHeap;
1725}
1726
1727ssize_t UserClient::getTokenForSurface(const sp<ISurface>& sur) const
1728{
1729    int32_t name = NAME_NOT_FOUND;
1730    sp<Layer> layer(mFlinger->getLayer(sur));
1731    if (layer == 0) return name;
1732
1733    // if this layer already has a token, just return it
1734    name = layer->getToken();
1735    if ((name >= 0) && (layer->getClient() == this))
1736        return name;
1737
1738    name = 0;
1739    do {
1740        int32_t mask = 1LU<<name;
1741        if ((android_atomic_or(mask, &mBitmap) & mask) == 0) {
1742            // we found and locked that name
1743            status_t err = layer->setToken(
1744                    const_cast<UserClient*>(this), ctrlblk, name);
1745            if (err != NO_ERROR) {
1746                // free the name
1747                android_atomic_and(~mask, &mBitmap);
1748                name = err;
1749            }
1750            break;
1751        }
1752        if (++name > 31)
1753            name = NO_MEMORY;
1754    } while(name >= 0);
1755
1756    //LOGD("getTokenForSurface(%p) => %d (client=%p, bitmap=%08lx)",
1757    //        sur->asBinder().get(), name, this, mBitmap);
1758    return name;
1759}
1760
1761sp<ISurface> UserClient::createSurface(
1762        ISurfaceComposerClient::surface_data_t* params, int pid,
1763        const String8& name,
1764        DisplayID display, uint32_t w, uint32_t h, PixelFormat format,
1765        uint32_t flags) {
1766    return 0;
1767}
1768status_t UserClient::destroySurface(SurfaceID sid) {
1769    return INVALID_OPERATION;
1770}
1771status_t UserClient::setState(int32_t count, const layer_state_t* states) {
1772    return INVALID_OPERATION;
1773}
1774
1775// ---------------------------------------------------------------------------
1776
1777GraphicPlane::GraphicPlane()
1778    : mHw(0)
1779{
1780}
1781
1782GraphicPlane::~GraphicPlane() {
1783    delete mHw;
1784}
1785
1786bool GraphicPlane::initialized() const {
1787    return mHw ? true : false;
1788}
1789
1790int GraphicPlane::getWidth() const {
1791    return mWidth;
1792}
1793
1794int GraphicPlane::getHeight() const {
1795    return mHeight;
1796}
1797
1798void GraphicPlane::setDisplayHardware(DisplayHardware *hw)
1799{
1800    mHw = hw;
1801
1802    // initialize the display orientation transform.
1803    // it's a constant that should come from the display driver.
1804    int displayOrientation = ISurfaceComposer::eOrientationDefault;
1805    char property[PROPERTY_VALUE_MAX];
1806    if (property_get("ro.sf.hwrotation", property, NULL) > 0) {
1807        //displayOrientation
1808        switch (atoi(property)) {
1809        case 90:
1810            displayOrientation = ISurfaceComposer::eOrientation90;
1811            break;
1812        case 270:
1813            displayOrientation = ISurfaceComposer::eOrientation270;
1814            break;
1815        }
1816    }
1817
1818    const float w = hw->getWidth();
1819    const float h = hw->getHeight();
1820    GraphicPlane::orientationToTransfrom(displayOrientation, w, h,
1821            &mDisplayTransform);
1822    if (displayOrientation & ISurfaceComposer::eOrientationSwapMask) {
1823        mDisplayWidth = h;
1824        mDisplayHeight = w;
1825    } else {
1826        mDisplayWidth = w;
1827        mDisplayHeight = h;
1828    }
1829
1830    setOrientation(ISurfaceComposer::eOrientationDefault);
1831}
1832
1833status_t GraphicPlane::orientationToTransfrom(
1834        int orientation, int w, int h, Transform* tr)
1835{
1836    uint32_t flags = 0;
1837    switch (orientation) {
1838    case ISurfaceComposer::eOrientationDefault:
1839        flags = Transform::ROT_0;
1840        break;
1841    case ISurfaceComposer::eOrientation90:
1842        flags = Transform::ROT_90;
1843        break;
1844    case ISurfaceComposer::eOrientation180:
1845        flags = Transform::ROT_180;
1846        break;
1847    case ISurfaceComposer::eOrientation270:
1848        flags = Transform::ROT_270;
1849        break;
1850    default:
1851        return BAD_VALUE;
1852    }
1853    tr->set(flags, w, h);
1854    return NO_ERROR;
1855}
1856
1857status_t GraphicPlane::setOrientation(int orientation)
1858{
1859    // If the rotation can be handled in hardware, this is where
1860    // the magic should happen.
1861
1862    const DisplayHardware& hw(displayHardware());
1863    const float w = mDisplayWidth;
1864    const float h = mDisplayHeight;
1865    mWidth = int(w);
1866    mHeight = int(h);
1867
1868    Transform orientationTransform;
1869    GraphicPlane::orientationToTransfrom(orientation, w, h,
1870            &orientationTransform);
1871    if (orientation & ISurfaceComposer::eOrientationSwapMask) {
1872        mWidth = int(h);
1873        mHeight = int(w);
1874    }
1875
1876    mOrientation = orientation;
1877    mGlobalTransform = mDisplayTransform * orientationTransform;
1878    return NO_ERROR;
1879}
1880
1881const DisplayHardware& GraphicPlane::displayHardware() const {
1882    return *mHw;
1883}
1884
1885const Transform& GraphicPlane::transform() const {
1886    return mGlobalTransform;
1887}
1888
1889EGLDisplay GraphicPlane::getEGLDisplay() const {
1890    return mHw->getEGLDisplay();
1891}
1892
1893// ---------------------------------------------------------------------------
1894
1895}; // namespace android
1896