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