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