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