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