SurfaceFlinger.cpp revision a350ff98692b3a50cad5cc93f9f83221242ca86a
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#include "DisplayHardware/HWComposer.h" 56 57/* ideally AID_GRAPHICS would be in a semi-public header 58 * or there would be a way to map a user/group name to its id 59 */ 60#ifndef AID_GRAPHICS 61#define AID_GRAPHICS 1003 62#endif 63 64#define DISPLAY_COUNT 1 65 66namespace android { 67// --------------------------------------------------------------------------- 68 69SurfaceFlinger::SurfaceFlinger() 70 : BnSurfaceComposer(), Thread(false), 71 mTransactionFlags(0), 72 mTransactionCount(0), 73 mResizeTransationPending(false), 74 mLayersRemoved(false), 75 mBootTime(systemTime()), 76 mHardwareTest("android.permission.HARDWARE_TEST"), 77 mAccessSurfaceFlinger("android.permission.ACCESS_SURFACE_FLINGER"), 78 mDump("android.permission.DUMP"), 79 mVisibleRegionsDirty(false), 80 mHwWorkListDirty(false), 81 mDeferReleaseConsole(false), 82 mFreezeDisplay(false), 83 mFreezeCount(0), 84 mFreezeDisplayTime(0), 85 mDebugRegion(0), 86 mDebugBackground(0), 87 mDebugInSwapBuffers(0), 88 mLastSwapBufferTime(0), 89 mDebugInTransaction(0), 90 mLastTransactionTime(0), 91 mBootFinished(false), 92 mConsoleSignals(0), 93 mSecureFrameBuffer(0) 94{ 95 init(); 96} 97 98void SurfaceFlinger::init() 99{ 100 LOGI("SurfaceFlinger is starting"); 101 102 // debugging stuff... 103 char value[PROPERTY_VALUE_MAX]; 104 property_get("debug.sf.showupdates", value, "0"); 105 mDebugRegion = atoi(value); 106 property_get("debug.sf.showbackground", value, "0"); 107 mDebugBackground = atoi(value); 108 109 LOGI_IF(mDebugRegion, "showupdates enabled"); 110 LOGI_IF(mDebugBackground, "showbackground enabled"); 111} 112 113SurfaceFlinger::~SurfaceFlinger() 114{ 115 glDeleteTextures(1, &mWormholeTexName); 116} 117 118overlay_control_device_t* SurfaceFlinger::getOverlayEngine() const 119{ 120 return graphicPlane(0).displayHardware().getOverlayEngine(); 121} 122 123sp<IMemoryHeap> SurfaceFlinger::getCblk() const 124{ 125 return mServerHeap; 126} 127 128sp<ISurfaceComposerClient> SurfaceFlinger::createConnection() 129{ 130 sp<ISurfaceComposerClient> bclient; 131 sp<Client> client(new Client(this)); 132 status_t err = client->initCheck(); 133 if (err == NO_ERROR) { 134 bclient = client; 135 } 136 return bclient; 137} 138 139sp<ISurfaceComposerClient> SurfaceFlinger::createClientConnection() 140{ 141 sp<ISurfaceComposerClient> bclient; 142 sp<UserClient> client(new UserClient(this)); 143 status_t err = client->initCheck(); 144 if (err == NO_ERROR) { 145 bclient = client; 146 } 147 return bclient; 148} 149 150 151const GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) const 152{ 153 LOGE_IF(uint32_t(dpy) >= DISPLAY_COUNT, "Invalid DisplayID %d", dpy); 154 const GraphicPlane& plane(mGraphicPlanes[dpy]); 155 return plane; 156} 157 158GraphicPlane& SurfaceFlinger::graphicPlane(int dpy) 159{ 160 return const_cast<GraphicPlane&>( 161 const_cast<SurfaceFlinger const *>(this)->graphicPlane(dpy)); 162} 163 164void SurfaceFlinger::bootFinished() 165{ 166 const nsecs_t now = systemTime(); 167 const nsecs_t duration = now - mBootTime; 168 LOGI("Boot is finished (%ld ms)", long(ns2ms(duration)) ); 169 mBootFinished = true; 170 property_set("ctl.stop", "bootanim"); 171} 172 173void SurfaceFlinger::onFirstRef() 174{ 175 run("SurfaceFlinger", PRIORITY_URGENT_DISPLAY); 176 177 // Wait for the main thread to be done with its initialization 178 mReadyToRunBarrier.wait(); 179} 180 181static inline uint16_t pack565(int r, int g, int b) { 182 return (r<<11)|(g<<5)|b; 183} 184 185status_t SurfaceFlinger::readyToRun() 186{ 187 LOGI( "SurfaceFlinger's main thread ready to run. " 188 "Initializing graphics H/W..."); 189 190 // we only support one display currently 191 int dpy = 0; 192 193 { 194 // initialize the main display 195 GraphicPlane& plane(graphicPlane(dpy)); 196 DisplayHardware* const hw = new DisplayHardware(this, dpy); 197 plane.setDisplayHardware(hw); 198 } 199 200 // create the shared control-block 201 mServerHeap = new MemoryHeapBase(4096, 202 MemoryHeapBase::READ_ONLY, "SurfaceFlinger read-only heap"); 203 LOGE_IF(mServerHeap==0, "can't create shared memory dealer"); 204 205 mServerCblk = static_cast<surface_flinger_cblk_t*>(mServerHeap->getBase()); 206 LOGE_IF(mServerCblk==0, "can't get to shared control block's address"); 207 208 new(mServerCblk) surface_flinger_cblk_t; 209 210 // initialize primary screen 211 // (other display should be initialized in the same manner, but 212 // asynchronously, as they could come and go. None of this is supported 213 // yet). 214 const GraphicPlane& plane(graphicPlane(dpy)); 215 const DisplayHardware& hw = plane.displayHardware(); 216 const uint32_t w = hw.getWidth(); 217 const uint32_t h = hw.getHeight(); 218 const uint32_t f = hw.getFormat(); 219 hw.makeCurrent(); 220 221 // initialize the shared control block 222 mServerCblk->connected |= 1<<dpy; 223 display_cblk_t* dcblk = mServerCblk->displays + dpy; 224 memset(dcblk, 0, sizeof(display_cblk_t)); 225 dcblk->w = plane.getWidth(); 226 dcblk->h = plane.getHeight(); 227 dcblk->format = f; 228 dcblk->orientation = ISurfaceComposer::eOrientationDefault; 229 dcblk->xdpi = hw.getDpiX(); 230 dcblk->ydpi = hw.getDpiY(); 231 dcblk->fps = hw.getRefreshRate(); 232 dcblk->density = hw.getDensity(); 233 234 // Initialize OpenGL|ES 235 glPixelStorei(GL_UNPACK_ALIGNMENT, 4); 236 glPixelStorei(GL_PACK_ALIGNMENT, 4); 237 glEnableClientState(GL_VERTEX_ARRAY); 238 glEnable(GL_SCISSOR_TEST); 239 glShadeModel(GL_FLAT); 240 glDisable(GL_DITHER); 241 glDisable(GL_CULL_FACE); 242 243 const uint16_t g0 = pack565(0x0F,0x1F,0x0F); 244 const uint16_t g1 = pack565(0x17,0x2f,0x17); 245 const uint16_t textureData[4] = { g0, g1, g1, g0 }; 246 glGenTextures(1, &mWormholeTexName); 247 glBindTexture(GL_TEXTURE_2D, mWormholeTexName); 248 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST); 249 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST); 250 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_REPEAT); 251 glTexParameterx(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_REPEAT); 252 glTexImage2D(GL_TEXTURE_2D, 0, GL_RGB, 2, 2, 0, 253 GL_RGB, GL_UNSIGNED_SHORT_5_6_5, textureData); 254 255 glViewport(0, 0, w, h); 256 glMatrixMode(GL_PROJECTION); 257 glLoadIdentity(); 258 glOrthof(0, w, h, 0, 0, 1); 259 260 LayerDim::initDimmer(this, w, h); 261 262 mReadyToRunBarrier.open(); 263 264 /* 265 * We're now ready to accept clients... 266 */ 267 268 // start boot animation 269 property_set("ctl.start", "bootanim"); 270 271 return NO_ERROR; 272} 273 274// ---------------------------------------------------------------------------- 275#if 0 276#pragma mark - 277#pragma mark Events Handler 278#endif 279 280void SurfaceFlinger::waitForEvent() 281{ 282 while (true) { 283 nsecs_t timeout = -1; 284 const nsecs_t freezeDisplayTimeout = ms2ns(5000); 285 if (UNLIKELY(isFrozen())) { 286 // wait 5 seconds 287 const nsecs_t now = systemTime(); 288 if (mFreezeDisplayTime == 0) { 289 mFreezeDisplayTime = now; 290 } 291 nsecs_t waitTime = freezeDisplayTimeout - (now - mFreezeDisplayTime); 292 timeout = waitTime>0 ? waitTime : 0; 293 } 294 295 sp<MessageBase> msg = mEventQueue.waitMessage(timeout); 296 297 // see if we timed out 298 if (isFrozen()) { 299 const nsecs_t now = systemTime(); 300 nsecs_t frozenTime = (now - mFreezeDisplayTime); 301 if (frozenTime >= freezeDisplayTimeout) { 302 // we timed out and are still frozen 303 LOGW("timeout expired mFreezeDisplay=%d, mFreezeCount=%d", 304 mFreezeDisplay, mFreezeCount); 305 mFreezeDisplayTime = 0; 306 mFreezeCount = 0; 307 mFreezeDisplay = false; 308 } 309 } 310 311 if (msg != 0) { 312 switch (msg->what) { 313 case MessageQueue::INVALIDATE: 314 // invalidate message, just return to the main loop 315 return; 316 } 317 } 318 } 319} 320 321void SurfaceFlinger::signalEvent() { 322 mEventQueue.invalidate(); 323} 324 325void SurfaceFlinger::signal() const { 326 // this is the IPC call 327 const_cast<SurfaceFlinger*>(this)->signalEvent(); 328} 329 330status_t SurfaceFlinger::postMessageAsync(const sp<MessageBase>& msg, 331 nsecs_t reltime, uint32_t flags) 332{ 333 return mEventQueue.postMessage(msg, reltime, flags); 334} 335 336status_t SurfaceFlinger::postMessageSync(const sp<MessageBase>& msg, 337 nsecs_t reltime, uint32_t flags) 338{ 339 status_t res = mEventQueue.postMessage(msg, reltime, flags); 340 if (res == NO_ERROR) { 341 msg->wait(); 342 } 343 return res; 344} 345 346// ---------------------------------------------------------------------------- 347#if 0 348#pragma mark - 349#pragma mark Main loop 350#endif 351 352bool SurfaceFlinger::threadLoop() 353{ 354 waitForEvent(); 355 356 // check for transactions 357 if (UNLIKELY(mConsoleSignals)) { 358 handleConsoleEvents(); 359 } 360 361 if (LIKELY(mTransactionCount == 0)) { 362 // if we're in a global transaction, don't do anything. 363 const uint32_t mask = eTransactionNeeded | eTraversalNeeded; 364 uint32_t transactionFlags = getTransactionFlags(mask); 365 if (LIKELY(transactionFlags)) { 366 handleTransaction(transactionFlags); 367 } 368 } 369 370 // post surfaces (if needed) 371 handlePageFlip(); 372 373 if (UNLIKELY(mHwWorkListDirty)) { 374 // build the h/w work list 375 handleWorkList(); 376 } 377 378 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 379 if (LIKELY(hw.canDraw() && !isFrozen())) { 380 // repaint the framebuffer (if needed) 381 handleRepaint(); 382 383 // inform the h/w that we're done compositing 384 hw.compositionComplete(); 385 386 // release the clients before we flip ('cause flip might block) 387 unlockClients(); 388 389 postFramebuffer(); 390 } else { 391 // pretend we did the post 392 unlockClients(); 393 usleep(16667); // 60 fps period 394 } 395 return true; 396} 397 398void SurfaceFlinger::postFramebuffer() 399{ 400 if (!mInvalidRegion.isEmpty()) { 401 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 402 const nsecs_t now = systemTime(); 403 mDebugInSwapBuffers = now; 404 hw.flip(mInvalidRegion); 405 mLastSwapBufferTime = systemTime() - now; 406 mDebugInSwapBuffers = 0; 407 mInvalidRegion.clear(); 408 } 409} 410 411void SurfaceFlinger::handleConsoleEvents() 412{ 413 // something to do with the console 414 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 415 416 int what = android_atomic_and(0, &mConsoleSignals); 417 if (what & eConsoleAcquired) { 418 hw.acquireScreen(); 419 } 420 421 if (mDeferReleaseConsole && hw.canDraw()) { 422 // We got the release signal before the acquire signal 423 mDeferReleaseConsole = false; 424 hw.releaseScreen(); 425 } 426 427 if (what & eConsoleReleased) { 428 if (hw.canDraw()) { 429 hw.releaseScreen(); 430 } else { 431 mDeferReleaseConsole = true; 432 } 433 } 434 435 mDirtyRegion.set(hw.bounds()); 436} 437 438void SurfaceFlinger::handleTransaction(uint32_t transactionFlags) 439{ 440 Vector< sp<LayerBase> > ditchedLayers; 441 442 /* 443 * Perform and commit the transaction 444 */ 445 446 { // scope for the lock 447 Mutex::Autolock _l(mStateLock); 448 const nsecs_t now = systemTime(); 449 mDebugInTransaction = now; 450 handleTransactionLocked(transactionFlags, ditchedLayers); 451 mLastTransactionTime = systemTime() - now; 452 mDebugInTransaction = 0; 453 mHwWorkListDirty = true; 454 // here the transaction has been committed 455 } 456 457 /* 458 * Clean-up all layers that went away 459 * (do this without the lock held) 460 */ 461 462 const size_t count = ditchedLayers.size(); 463 for (size_t i=0 ; i<count ; i++) { 464 if (ditchedLayers[i] != 0) { 465 //LOGD("ditching layer %p", ditchedLayers[i].get()); 466 ditchedLayers[i]->ditch(); 467 } 468 } 469} 470 471void SurfaceFlinger::handleTransactionLocked( 472 uint32_t transactionFlags, Vector< sp<LayerBase> >& ditchedLayers) 473{ 474 const LayerVector& currentLayers(mCurrentState.layersSortedByZ); 475 const size_t count = currentLayers.size(); 476 477 /* 478 * Traversal of the children 479 * (perform the transaction for each of them if needed) 480 */ 481 482 const bool layersNeedTransaction = transactionFlags & eTraversalNeeded; 483 if (layersNeedTransaction) { 484 for (size_t i=0 ; i<count ; i++) { 485 const sp<LayerBase>& layer = currentLayers[i]; 486 uint32_t trFlags = layer->getTransactionFlags(eTransactionNeeded); 487 if (!trFlags) continue; 488 489 const uint32_t flags = layer->doTransaction(0); 490 if (flags & Layer::eVisibleRegion) 491 mVisibleRegionsDirty = true; 492 } 493 } 494 495 /* 496 * Perform our own transaction if needed 497 */ 498 499 if (transactionFlags & eTransactionNeeded) { 500 if (mCurrentState.orientation != mDrawingState.orientation) { 501 // the orientation has changed, recompute all visible regions 502 // and invalidate everything. 503 504 const int dpy = 0; 505 const int orientation = mCurrentState.orientation; 506 const uint32_t type = mCurrentState.orientationType; 507 GraphicPlane& plane(graphicPlane(dpy)); 508 plane.setOrientation(orientation); 509 510 // update the shared control block 511 const DisplayHardware& hw(plane.displayHardware()); 512 volatile display_cblk_t* dcblk = mServerCblk->displays + dpy; 513 dcblk->orientation = orientation; 514 dcblk->w = plane.getWidth(); 515 dcblk->h = plane.getHeight(); 516 517 mVisibleRegionsDirty = true; 518 mDirtyRegion.set(hw.bounds()); 519 } 520 521 if (mCurrentState.freezeDisplay != mDrawingState.freezeDisplay) { 522 // freezing or unfreezing the display -> trigger animation if needed 523 mFreezeDisplay = mCurrentState.freezeDisplay; 524 if (mFreezeDisplay) 525 mFreezeDisplayTime = 0; 526 } 527 528 if (currentLayers.size() > mDrawingState.layersSortedByZ.size()) { 529 // layers have been added 530 mVisibleRegionsDirty = true; 531 } 532 533 // some layers might have been removed, so 534 // we need to update the regions they're exposing. 535 if (mLayersRemoved) { 536 mLayersRemoved = false; 537 mVisibleRegionsDirty = true; 538 const LayerVector& previousLayers(mDrawingState.layersSortedByZ); 539 const size_t count = previousLayers.size(); 540 for (size_t i=0 ; i<count ; i++) { 541 const sp<LayerBase>& layer(previousLayers[i]); 542 if (currentLayers.indexOf( layer ) < 0) { 543 // this layer is not visible anymore 544 ditchedLayers.add(layer); 545 mDirtyRegionRemovedLayer.orSelf(layer->visibleRegionScreen); 546 } 547 } 548 } 549 } 550 551 commitTransaction(); 552} 553 554sp<FreezeLock> SurfaceFlinger::getFreezeLock() const 555{ 556 return new FreezeLock(const_cast<SurfaceFlinger *>(this)); 557} 558 559void SurfaceFlinger::computeVisibleRegions( 560 LayerVector& currentLayers, Region& dirtyRegion, Region& opaqueRegion) 561{ 562 const GraphicPlane& plane(graphicPlane(0)); 563 const Transform& planeTransform(plane.transform()); 564 const DisplayHardware& hw(plane.displayHardware()); 565 const Region screenRegion(hw.bounds()); 566 567 Region aboveOpaqueLayers; 568 Region aboveCoveredLayers; 569 Region dirty; 570 571 bool secureFrameBuffer = false; 572 573 size_t i = currentLayers.size(); 574 while (i--) { 575 const sp<LayerBase>& layer = currentLayers[i]; 576 layer->validateVisibility(planeTransform); 577 578 // start with the whole surface at its current location 579 const Layer::State& s(layer->drawingState()); 580 581 /* 582 * opaqueRegion: area of a surface that is fully opaque. 583 */ 584 Region opaqueRegion; 585 586 /* 587 * visibleRegion: area of a surface that is visible on screen 588 * and not fully transparent. This is essentially the layer's 589 * footprint minus the opaque regions above it. 590 * Areas covered by a translucent surface are considered visible. 591 */ 592 Region visibleRegion; 593 594 /* 595 * coveredRegion: area of a surface that is covered by all 596 * visible regions above it (which includes the translucent areas). 597 */ 598 Region coveredRegion; 599 600 601 // handle hidden surfaces by setting the visible region to empty 602 if (LIKELY(!(s.flags & ISurfaceComposer::eLayerHidden) && s.alpha)) { 603 const bool translucent = layer->needsBlending(); 604 const Rect bounds(layer->visibleBounds()); 605 visibleRegion.set(bounds); 606 visibleRegion.andSelf(screenRegion); 607 if (!visibleRegion.isEmpty()) { 608 // Remove the transparent area from the visible region 609 if (translucent) { 610 visibleRegion.subtractSelf(layer->transparentRegionScreen); 611 } 612 613 // compute the opaque region 614 const int32_t layerOrientation = layer->getOrientation(); 615 if (s.alpha==255 && !translucent && 616 ((layerOrientation & Transform::ROT_INVALID) == false)) { 617 // the opaque region is the layer's footprint 618 opaqueRegion = visibleRegion; 619 } 620 } 621 } 622 623 // Clip the covered region to the visible region 624 coveredRegion = aboveCoveredLayers.intersect(visibleRegion); 625 626 // Update aboveCoveredLayers for next (lower) layer 627 aboveCoveredLayers.orSelf(visibleRegion); 628 629 // subtract the opaque region covered by the layers above us 630 visibleRegion.subtractSelf(aboveOpaqueLayers); 631 632 // compute this layer's dirty region 633 if (layer->contentDirty) { 634 // we need to invalidate the whole region 635 dirty = visibleRegion; 636 // as well, as the old visible region 637 dirty.orSelf(layer->visibleRegionScreen); 638 layer->contentDirty = false; 639 } else { 640 /* compute the exposed region: 641 * the exposed region consists of two components: 642 * 1) what's VISIBLE now and was COVERED before 643 * 2) what's EXPOSED now less what was EXPOSED before 644 * 645 * note that (1) is conservative, we start with the whole 646 * visible region but only keep what used to be covered by 647 * something -- which mean it may have been exposed. 648 * 649 * (2) handles areas that were not covered by anything but got 650 * exposed because of a resize. 651 */ 652 const Region newExposed = visibleRegion - coveredRegion; 653 const Region oldVisibleRegion = layer->visibleRegionScreen; 654 const Region oldCoveredRegion = layer->coveredRegionScreen; 655 const Region oldExposed = oldVisibleRegion - oldCoveredRegion; 656 dirty = (visibleRegion&oldCoveredRegion) | (newExposed-oldExposed); 657 } 658 dirty.subtractSelf(aboveOpaqueLayers); 659 660 // accumulate to the screen dirty region 661 dirtyRegion.orSelf(dirty); 662 663 // Update aboveOpaqueLayers for next (lower) layer 664 aboveOpaqueLayers.orSelf(opaqueRegion); 665 666 // Store the visible region is screen space 667 layer->setVisibleRegion(visibleRegion); 668 layer->setCoveredRegion(coveredRegion); 669 670 // If a secure layer is partially visible, lock-down the screen! 671 if (layer->isSecure() && !visibleRegion.isEmpty()) { 672 secureFrameBuffer = true; 673 } 674 } 675 676 // invalidate the areas where a layer was removed 677 dirtyRegion.orSelf(mDirtyRegionRemovedLayer); 678 mDirtyRegionRemovedLayer.clear(); 679 680 mSecureFrameBuffer = secureFrameBuffer; 681 opaqueRegion = aboveOpaqueLayers; 682} 683 684 685void SurfaceFlinger::commitTransaction() 686{ 687 mDrawingState = mCurrentState; 688 mResizeTransationPending = false; 689 mTransactionCV.broadcast(); 690} 691 692void SurfaceFlinger::handlePageFlip() 693{ 694 bool visibleRegions = mVisibleRegionsDirty; 695 LayerVector& currentLayers( 696 const_cast<LayerVector&>(mDrawingState.layersSortedByZ)); 697 visibleRegions |= lockPageFlip(currentLayers); 698 699 const DisplayHardware& hw = graphicPlane(0).displayHardware(); 700 const Region screenRegion(hw.bounds()); 701 if (visibleRegions) { 702 Region opaqueRegion; 703 computeVisibleRegions(currentLayers, mDirtyRegion, opaqueRegion); 704 705 /* 706 * rebuild the visible layer list 707 */ 708 mVisibleLayersSortedByZ.clear(); 709 const LayerVector& currentLayers(mDrawingState.layersSortedByZ); 710 size_t count = currentLayers.size(); 711 mVisibleLayersSortedByZ.setCapacity(count); 712 for (size_t i=0 ; i<count ; i++) { 713 if (!currentLayers[i]->visibleRegionScreen.isEmpty()) 714 mVisibleLayersSortedByZ.add(currentLayers[i]); 715 } 716 717 mWormholeRegion = screenRegion.subtract(opaqueRegion); 718 mVisibleRegionsDirty = false; 719 mHwWorkListDirty = true; 720 } 721 722 unlockPageFlip(currentLayers); 723 mDirtyRegion.andSelf(screenRegion); 724} 725 726bool SurfaceFlinger::lockPageFlip(const LayerVector& currentLayers) 727{ 728 bool recomputeVisibleRegions = false; 729 size_t count = currentLayers.size(); 730 sp<LayerBase> const* layers = currentLayers.array(); 731 for (size_t i=0 ; i<count ; i++) { 732 const sp<LayerBase>& layer(layers[i]); 733 layer->lockPageFlip(recomputeVisibleRegions); 734 } 735 return recomputeVisibleRegions; 736} 737 738void SurfaceFlinger::unlockPageFlip(const LayerVector& currentLayers) 739{ 740 const GraphicPlane& plane(graphicPlane(0)); 741 const Transform& planeTransform(plane.transform()); 742 size_t count = currentLayers.size(); 743 sp<LayerBase> const* layers = currentLayers.array(); 744 for (size_t i=0 ; i<count ; i++) { 745 const sp<LayerBase>& layer(layers[i]); 746 layer->unlockPageFlip(planeTransform, mDirtyRegion); 747 } 748} 749 750void SurfaceFlinger::handleWorkList() 751{ 752 mHwWorkListDirty = false; 753 HWComposer& hwc(graphicPlane(0).displayHardware().getHwComposer()); 754 if (hwc.initCheck() == NO_ERROR) { 755 const Vector< sp<LayerBase> >& currentLayers(mVisibleLayersSortedByZ); 756 const size_t count = currentLayers.size(); 757 hwc.createWorkList(count); 758 HWComposer::iterator cur(hwc.begin()); 759 HWComposer::iterator last(hwc.end()); 760 for (size_t i=0 ; (i<count) && (cur!=last) ; ++i, ++cur) { 761 currentLayers[i]->setGeometry(cur); 762 } 763 } 764} 765 766void SurfaceFlinger::handleRepaint() 767{ 768 // compute the invalid region 769 mInvalidRegion.orSelf(mDirtyRegion); 770 if (mInvalidRegion.isEmpty()) { 771 // nothing to do 772 return; 773 } 774 775 if (UNLIKELY(mDebugRegion)) { 776 debugFlashRegions(); 777 } 778 779 // set the frame buffer 780 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 781 glMatrixMode(GL_MODELVIEW); 782 glLoadIdentity(); 783 784 uint32_t flags = hw.getFlags(); 785 if ((flags & DisplayHardware::SWAP_RECTANGLE) || 786 (flags & DisplayHardware::BUFFER_PRESERVED)) 787 { 788 // we can redraw only what's dirty, but since SWAP_RECTANGLE only 789 // takes a rectangle, we must make sure to update that whole 790 // rectangle in that case 791 if (flags & DisplayHardware::SWAP_RECTANGLE) { 792 // TODO: we really should be able to pass a region to 793 // SWAP_RECTANGLE so that we don't have to redraw all this. 794 mDirtyRegion.set(mInvalidRegion.bounds()); 795 } else { 796 // in the BUFFER_PRESERVED case, obviously, we can update only 797 // what's needed and nothing more. 798 // NOTE: this is NOT a common case, as preserving the backbuffer 799 // is costly and usually involves copying the whole update back. 800 } 801 } else { 802 if (flags & DisplayHardware::PARTIAL_UPDATES) { 803 // We need to redraw the rectangle that will be updated 804 // (pushed to the framebuffer). 805 // This is needed because PARTIAL_UPDATES only takes one 806 // rectangle instead of a region (see DisplayHardware::flip()) 807 mDirtyRegion.set(mInvalidRegion.bounds()); 808 } else { 809 // we need to redraw everything (the whole screen) 810 mDirtyRegion.set(hw.bounds()); 811 mInvalidRegion = mDirtyRegion; 812 } 813 } 814 815 // compose all surfaces 816 composeSurfaces(mDirtyRegion); 817 818 // clear the dirty regions 819 mDirtyRegion.clear(); 820} 821 822void SurfaceFlinger::composeSurfaces(const Region& dirty) 823{ 824 if (UNLIKELY(!mWormholeRegion.isEmpty())) { 825 // should never happen unless the window manager has a bug 826 // draw something... 827 drawWormhole(); 828 } 829 830 status_t err = NO_ERROR; 831 const Vector< sp<LayerBase> >& layers(mVisibleLayersSortedByZ); 832 const size_t count = layers.size(); 833 834 const DisplayHardware& hw(graphicPlane(0).displayHardware()); 835 HWComposer& hwc(hw.getHwComposer()); 836 HWComposer::iterator cur(hwc.begin()); 837 HWComposer::iterator last(hwc.end()); 838 839 // update the per-frame h/w composer data for each layer 840 if (cur != last) { 841 for (size_t i=0 ; i<count && cur!=last ; ++i, ++cur) { 842 layers[i]->setPerFrameData(cur); 843 } 844 err = hwc.prepare(); 845 LOGE_IF(err, "HWComposer::prepare failed (%s)", strerror(-err)); 846 } 847 848 // and then, render the layers targeted at the framebuffer 849 Region transparent(hw.bounds()); 850 for (size_t i=0 ; i<count ; ++i) { 851 852 // see if we need to skip this layer 853 if (!err && cur != last) { 854 if (!((cur->compositionType == HWC_FRAMEBUFFER) || 855 (cur->flags & HWC_SKIP_LAYER))) { 856 ++cur; 857 continue; 858 } 859 ++cur; 860 } 861 862 // draw the layer into the framebuffer 863 const sp<LayerBase>& layer(layers[i]); 864 transparent.subtractSelf(layer->visibleRegionScreen); 865 const Region clip(dirty.intersect(layer->visibleRegionScreen)); 866 if (!clip.isEmpty()) { 867 layer->draw(clip); 868 } 869 } 870 871 // finally clear everything we didn't draw as a result of calling 872 // prepare (this leaves the FB transparent). 873 transparent.andSelf(dirty); 874 if (!transparent.isEmpty()) { 875 glClearColor(0,0,0,0); 876 Region::const_iterator it = transparent.begin(); 877 Region::const_iterator const end = transparent.end(); 878 const int32_t height = hw.getHeight(); 879 while (it != end) { 880 const Rect& r(*it++); 881 const GLint sy = height - (r.top + r.height()); 882 glScissor(r.left, sy, r.width(), r.height()); 883 glClear(GL_COLOR_BUFFER_BIT); 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(layer); 1033 return (i < 0) ? status_t(i) : status_t(NO_ERROR); 1034} 1035 1036ssize_t SurfaceFlinger::addClientLayer(const sp<Client>& client, 1037 const sp<LayerBaseClient>& lbc) 1038{ 1039 Mutex::Autolock _l(mStateLock); 1040 1041 // attach this layer to the client 1042 ssize_t name = client->attachLayer(lbc); 1043 1044 // add this layer to the current state list 1045 addLayer_l(lbc); 1046 1047 return name; 1048} 1049 1050status_t SurfaceFlinger::removeLayer(const sp<LayerBase>& layer) 1051{ 1052 Mutex::Autolock _l(mStateLock); 1053 status_t err = purgatorizeLayer_l(layer); 1054 if (err == NO_ERROR) 1055 setTransactionFlags(eTransactionNeeded); 1056 return err; 1057} 1058 1059status_t SurfaceFlinger::removeLayer_l(const sp<LayerBase>& layerBase) 1060{ 1061 sp<LayerBaseClient> lbc(layerBase->getLayerBaseClient()); 1062 if (lbc != 0) { 1063 mLayerMap.removeItem( lbc->getSurface()->asBinder() ); 1064 } 1065 ssize_t index = mCurrentState.layersSortedByZ.remove(layerBase); 1066 if (index >= 0) { 1067 mLayersRemoved = true; 1068 return NO_ERROR; 1069 } 1070 return status_t(index); 1071} 1072 1073status_t SurfaceFlinger::purgatorizeLayer_l(const sp<LayerBase>& layerBase) 1074{ 1075 // remove the layer from the main list (through a transaction). 1076 ssize_t err = removeLayer_l(layerBase); 1077 1078 layerBase->onRemoved(); 1079 1080 // it's possible that we don't find a layer, because it might 1081 // have been destroyed already -- this is not technically an error 1082 // from the user because there is a race between Client::destroySurface(), 1083 // ~Client() and ~ISurface(). 1084 return (err == NAME_NOT_FOUND) ? status_t(NO_ERROR) : err; 1085} 1086 1087status_t SurfaceFlinger::invalidateLayerVisibility(const sp<LayerBase>& layer) 1088{ 1089 layer->forceVisibilityTransaction(); 1090 setTransactionFlags(eTraversalNeeded); 1091 return NO_ERROR; 1092} 1093 1094uint32_t SurfaceFlinger::getTransactionFlags(uint32_t flags) 1095{ 1096 return android_atomic_and(~flags, &mTransactionFlags) & flags; 1097} 1098 1099uint32_t SurfaceFlinger::setTransactionFlags(uint32_t flags) 1100{ 1101 uint32_t old = android_atomic_or(flags, &mTransactionFlags); 1102 if ((old & flags)==0) { // wake the server up 1103 signalEvent(); 1104 } 1105 return old; 1106} 1107 1108void SurfaceFlinger::openGlobalTransaction() 1109{ 1110 android_atomic_inc(&mTransactionCount); 1111} 1112 1113void SurfaceFlinger::closeGlobalTransaction() 1114{ 1115 if (android_atomic_dec(&mTransactionCount) == 1) { 1116 signalEvent(); 1117 1118 // if there is a transaction with a resize, wait for it to 1119 // take effect before returning. 1120 Mutex::Autolock _l(mStateLock); 1121 while (mResizeTransationPending) { 1122 status_t err = mTransactionCV.waitRelative(mStateLock, s2ns(5)); 1123 if (CC_UNLIKELY(err != NO_ERROR)) { 1124 // just in case something goes wrong in SF, return to the 1125 // called after a few seconds. 1126 LOGW_IF(err == TIMED_OUT, "closeGlobalTransaction timed out!"); 1127 mResizeTransationPending = false; 1128 break; 1129 } 1130 } 1131 } 1132} 1133 1134status_t SurfaceFlinger::freezeDisplay(DisplayID dpy, uint32_t flags) 1135{ 1136 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1137 return BAD_VALUE; 1138 1139 Mutex::Autolock _l(mStateLock); 1140 mCurrentState.freezeDisplay = 1; 1141 setTransactionFlags(eTransactionNeeded); 1142 1143 // flags is intended to communicate some sort of animation behavior 1144 // (for instance fading) 1145 return NO_ERROR; 1146} 1147 1148status_t SurfaceFlinger::unfreezeDisplay(DisplayID dpy, uint32_t flags) 1149{ 1150 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1151 return BAD_VALUE; 1152 1153 Mutex::Autolock _l(mStateLock); 1154 mCurrentState.freezeDisplay = 0; 1155 setTransactionFlags(eTransactionNeeded); 1156 1157 // flags is intended to communicate some sort of animation behavior 1158 // (for instance fading) 1159 return NO_ERROR; 1160} 1161 1162int SurfaceFlinger::setOrientation(DisplayID dpy, 1163 int orientation, uint32_t flags) 1164{ 1165 if (UNLIKELY(uint32_t(dpy) >= DISPLAY_COUNT)) 1166 return BAD_VALUE; 1167 1168 Mutex::Autolock _l(mStateLock); 1169 if (mCurrentState.orientation != orientation) { 1170 if (uint32_t(orientation)<=eOrientation270 || orientation==42) { 1171 mCurrentState.orientationType = flags; 1172 mCurrentState.orientation = orientation; 1173 setTransactionFlags(eTransactionNeeded); 1174 mTransactionCV.wait(mStateLock); 1175 } else { 1176 orientation = BAD_VALUE; 1177 } 1178 } 1179 return orientation; 1180} 1181 1182sp<ISurface> SurfaceFlinger::createSurface(const sp<Client>& client, int pid, 1183 const String8& name, ISurfaceComposerClient::surface_data_t* params, 1184 DisplayID d, uint32_t w, uint32_t h, PixelFormat format, 1185 uint32_t flags) 1186{ 1187 sp<LayerBaseClient> layer; 1188 sp<LayerBaseClient::Surface> surfaceHandle; 1189 1190 if (int32_t(w|h) < 0) { 1191 LOGE("createSurface() failed, w or h is negative (w=%d, h=%d)", 1192 int(w), int(h)); 1193 return surfaceHandle; 1194 } 1195 1196 //LOGD("createSurface for pid %d (%d x %d)", pid, w, h); 1197 sp<Layer> normalLayer; 1198 switch (flags & eFXSurfaceMask) { 1199 case eFXSurfaceNormal: 1200 if (UNLIKELY(flags & ePushBuffers)) { 1201 layer = createPushBuffersSurface(client, d, w, h, flags); 1202 } else { 1203 normalLayer = createNormalSurface(client, d, w, h, flags, format); 1204 layer = normalLayer; 1205 } 1206 break; 1207 case eFXSurfaceBlur: 1208 layer = createBlurSurface(client, d, w, h, flags); 1209 break; 1210 case eFXSurfaceDim: 1211 layer = createDimSurface(client, d, w, h, flags); 1212 break; 1213 } 1214 1215 if (layer != 0) { 1216 layer->initStates(w, h, flags); 1217 layer->setName(name); 1218 ssize_t token = addClientLayer(client, layer); 1219 1220 surfaceHandle = layer->getSurface(); 1221 if (surfaceHandle != 0) { 1222 params->token = token; 1223 params->identity = surfaceHandle->getIdentity(); 1224 params->width = w; 1225 params->height = h; 1226 params->format = format; 1227 if (normalLayer != 0) { 1228 Mutex::Autolock _l(mStateLock); 1229 mLayerMap.add(surfaceHandle->asBinder(), normalLayer); 1230 } 1231 } 1232 1233 setTransactionFlags(eTransactionNeeded); 1234 } 1235 1236 return surfaceHandle; 1237} 1238 1239sp<Layer> SurfaceFlinger::createNormalSurface( 1240 const sp<Client>& client, DisplayID display, 1241 uint32_t w, uint32_t h, uint32_t flags, 1242 PixelFormat& format) 1243{ 1244 // initialize the surfaces 1245 switch (format) { // TODO: take h/w into account 1246 case PIXEL_FORMAT_TRANSPARENT: 1247 case PIXEL_FORMAT_TRANSLUCENT: 1248 format = PIXEL_FORMAT_RGBA_8888; 1249 break; 1250 case PIXEL_FORMAT_OPAQUE: 1251#ifdef NO_RGBX_8888 1252 format = PIXEL_FORMAT_RGB_565; 1253#else 1254 format = PIXEL_FORMAT_RGBX_8888; 1255#endif 1256 break; 1257 } 1258 1259#ifdef NO_RGBX_8888 1260 if (format == PIXEL_FORMAT_RGBX_8888) 1261 format = PIXEL_FORMAT_RGBA_8888; 1262#endif 1263 1264 sp<Layer> layer = new Layer(this, display, client); 1265 status_t err = layer->setBuffers(w, h, format, flags); 1266 if (LIKELY(err != NO_ERROR)) { 1267 LOGE("createNormalSurfaceLocked() failed (%s)", strerror(-err)); 1268 layer.clear(); 1269 } 1270 return layer; 1271} 1272 1273sp<LayerBlur> SurfaceFlinger::createBlurSurface( 1274 const sp<Client>& client, DisplayID display, 1275 uint32_t w, uint32_t h, uint32_t flags) 1276{ 1277 sp<LayerBlur> layer = new LayerBlur(this, display, client); 1278 layer->initStates(w, h, flags); 1279 return layer; 1280} 1281 1282sp<LayerDim> SurfaceFlinger::createDimSurface( 1283 const sp<Client>& client, DisplayID display, 1284 uint32_t w, uint32_t h, uint32_t flags) 1285{ 1286 sp<LayerDim> layer = new LayerDim(this, display, client); 1287 layer->initStates(w, h, flags); 1288 return layer; 1289} 1290 1291sp<LayerBuffer> SurfaceFlinger::createPushBuffersSurface( 1292 const sp<Client>& client, DisplayID display, 1293 uint32_t w, uint32_t h, uint32_t flags) 1294{ 1295 sp<LayerBuffer> layer = new LayerBuffer(this, display, client); 1296 layer->initStates(w, h, flags); 1297 return layer; 1298} 1299 1300status_t SurfaceFlinger::removeSurface(const sp<Client>& client, SurfaceID sid) 1301{ 1302 /* 1303 * called by the window manager, when a surface should be marked for 1304 * destruction. 1305 * 1306 * The surface is removed from the current and drawing lists, but placed 1307 * in the purgatory queue, so it's not destroyed right-away (we need 1308 * to wait for all client's references to go away first). 1309 */ 1310 1311 status_t err = NAME_NOT_FOUND; 1312 Mutex::Autolock _l(mStateLock); 1313 sp<LayerBaseClient> layer = client->getLayerUser(sid); 1314 if (layer != 0) { 1315 err = purgatorizeLayer_l(layer); 1316 if (err == NO_ERROR) { 1317 setTransactionFlags(eTransactionNeeded); 1318 } 1319 } 1320 return err; 1321} 1322 1323status_t SurfaceFlinger::destroySurface(const sp<LayerBaseClient>& layer) 1324{ 1325 // called by ~ISurface() when all references are gone 1326 1327 class MessageDestroySurface : public MessageBase { 1328 SurfaceFlinger* flinger; 1329 sp<LayerBaseClient> layer; 1330 public: 1331 MessageDestroySurface( 1332 SurfaceFlinger* flinger, const sp<LayerBaseClient>& layer) 1333 : flinger(flinger), layer(layer) { } 1334 virtual bool handler() { 1335 sp<LayerBaseClient> l(layer); 1336 layer.clear(); // clear it outside of the lock; 1337 Mutex::Autolock _l(flinger->mStateLock); 1338 /* 1339 * remove the layer from the current list -- chances are that it's 1340 * not in the list anyway, because it should have been removed 1341 * already upon request of the client (eg: window manager). 1342 * However, a buggy client could have not done that. 1343 * Since we know we don't have any more clients, we don't need 1344 * to use the purgatory. 1345 */ 1346 status_t err = flinger->removeLayer_l(l); 1347 LOGE_IF(err<0 && err != NAME_NOT_FOUND, 1348 "error removing layer=%p (%s)", l.get(), strerror(-err)); 1349 return true; 1350 } 1351 }; 1352 1353 postMessageAsync( new MessageDestroySurface(this, layer) ); 1354 return NO_ERROR; 1355} 1356 1357status_t SurfaceFlinger::setClientState( 1358 const sp<Client>& client, 1359 int32_t count, 1360 const layer_state_t* states) 1361{ 1362 Mutex::Autolock _l(mStateLock); 1363 uint32_t flags = 0; 1364 for (int i=0 ; i<count ; i++) { 1365 const layer_state_t& s(states[i]); 1366 sp<LayerBaseClient> layer(client->getLayerUser(s.surface)); 1367 if (layer != 0) { 1368 const uint32_t what = s.what; 1369 if (what & ePositionChanged) { 1370 if (layer->setPosition(s.x, s.y)) 1371 flags |= eTraversalNeeded; 1372 } 1373 if (what & eLayerChanged) { 1374 ssize_t idx = mCurrentState.layersSortedByZ.indexOf(layer); 1375 if (layer->setLayer(s.z)) { 1376 mCurrentState.layersSortedByZ.removeAt(idx); 1377 mCurrentState.layersSortedByZ.add(layer); 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