由init进程启动,从main函数开始
主要是初始化了Surflinger, 并启动了线程
79 int main(int, char**) {
80 signal(SIGPIPE, SIG_IGN);
81
82 hardware::configureRpcThreadpool(1 /* maxThreads */,
83 false /* callerWillJoin */);
// 启动图形服务
84
85 startGraphicsAllocatorService();
86
87 // When SF is launched in its own process, limit the number of
88 // binder threads to 4.
、、设置线程数
89 ProcessState::self()->setThreadPoolMaxThreadCount(4);
90
91 // Set uclamp.min setting on all threads, maybe an overkill but we want
92 // to cover important threads like RenderEngine.
93 if (SurfaceFlinger::setSchedAttr(true) != NO_ERROR) {
94 ALOGW("Failed to set uclamp.min during boot: %s", strerror(errno));
95 }
96
97 // The binder threadpool we start will inherit sched policy and priority
98 // of (this) creating thread. We want the binder thread pool to have
99 // SCHED_FIFO policy and priority 1 (lowest RT priority)
100 // Once the pool is created we reset this thread's priority back to
101 // original.
102 int newPriority = 0;
103 int origPolicy = sched_getscheduler(0);
104 struct sched_param origSchedParam;
105
106 int errorInPriorityModification = sched_getparam(0, &origSchedParam);
107 if (errorInPriorityModification == 0) {
108 int policy = SCHED_FIFO;
109 newPriority = sched_get_priority_min(policy);
110
111 struct sched_param param;
112 param.sched_priority = newPriority;
113
114 errorInPriorityModification = sched_setscheduler(0, policy, ¶m);
115 }
116
117 // start the thread pool
118 sp<ProcessState> ps(ProcessState::self());
// 启动线程池
119 ps->startThreadPool();
120
121 // Reset current thread's policy and priority
122 if (errorInPriorityModification == 0) {
123 errorInPriorityModification = sched_setscheduler(0, origPolicy, &origSchedParam);
124 } else {
125 ALOGE("Failed to set SurfaceFlinger binder threadpool priority to SCHED_FIFO");
126 }
127
128 // instantiate surfaceflinger
// 初始化SurfaceFlinger
129 sp<SurfaceFlinger> flinger = surfaceflinger::createSurfaceFlinger();
130
131 // Set the minimum policy of surfaceflinger node to be SCHED_FIFO.
132 // So any thread with policy/priority lower than {SCHED_FIFO, 1}, will run
133 // at least with SCHED_FIFO policy and priority 1.
134 if (errorInPriorityModification == 0) {
135 flinger->setMinSchedulerPolicy(SCHED_FIFO, newPriority);
136 }
137 //设置线程优先级
138 setpriority(PRIO_PROCESS, 0, PRIORITY_URGENT_DISPLAY);
139 //设置调度策略
140 set_sched_policy(0, SP_FOREGROUND);
141 //初始化flinger
142 // initialize before clients can connect
143 flinger->init();
144
145 // publish surface flinger
146 sp<IServiceManager> sm(defaultServiceManager());
147 sm->addService(String16(SurfaceFlinger::getServiceName()), flinger, false,
148 IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
149
150 // publish gui::ISurfaceComposer, the new AIDL interface
151 sp<SurfaceComposerAIDL> composerAIDL = sp<SurfaceComposerAIDL>::make(flinger);
// 添加到服务中
152 sm->addService(String16("SurfaceFlingerAIDL"), composerAIDL, false,
153 IServiceManager::DUMP_FLAG_PRIORITY_CRITICAL | IServiceManager::DUMP_FLAG_PROTO);
154 // 启动Display服务
155 startDisplayService(); // dependency on SF getting registered above
156
157 if (SurfaceFlinger::setSchedFifo(true) != NO_ERROR) {
158 ALOGW("Failed to set SCHED_FIFO during boot: %s", strerror(errno));
159 }
160
161 // run surface flinger in this thread 启动flinger
162 flinger->run();
163
164 return 0;
165 }
初始化SurfaceFlinger
frameworks/native/services/surfaceflinger/SurfaceFlinger.h
可见SurfaceFlinger继承于BnSurfaceComposer是服务端
HWC2::ComposerCallback类:面向底层硬件状态的监听回调接口,包括onHotplugReceived,显示屏热插拔事件回调onRefreshReceived,通知刷新的回调onVsyncReceived,VSYNC信号接收回调
192 class SurfaceFlinger : public BnSurfaceComposer,
193 public PriorityDumper,
194 private IBinder::DeathRecipient,
195 private HWC2::ComposerCallback,
196 private ICompositor,
197 private scheduler::ISchedulerCallback {
/frameworks/native/services/surfaceflinger/SurfaceFlingerFactory.cpp
26 sp<SurfaceFlinger> createSurfaceFlinger() {
27 static DefaultFactory factory;
28
29 return sp<SurfaceFlinger>::make(factory);
30 }
通过SurfaceFlingerFactory.cpp创建了一个SurfaceFlinger对象
1. 创建了CompositionEngine
2 . 添加了WindowInfosListenerInvoker回调
361 SurfaceFlinger::SurfaceFlinger(Factory& factory, SkipInitializationTag)
362 : mFactory(factory),
363 mPid(getpid()),
364 mTimeStats(std::make_shared<impl::TimeStats>()),
365 mFrameTracer(mFactory.createFrameTracer()),
366 mFrameTimeline(mFactory.createFrameTimeline(mTimeStats, mPid)),
367 mCompositionEngine(mFactory.createCompositionEngine()),
368 mHwcServiceName(base::GetProperty("debug.sf.hwc_service_name"s, "default"s)),
369 mTunnelModeEnabledReporter(sp<TunnelModeEnabledReporter>::make()),
370 mEmulatedDisplayDensity(getDensityFromProperty("qemu.sf.lcd_density", false)),
371 mInternalDisplayDensity(
372 getDensityFromProperty("ro.sf.lcd_density", !mEmulatedDisplayDensity)),
373 mPowerAdvisor(std::make_unique<Hwc2::impl::PowerAdvisor>(*this)),
374 mWindowInfosListenerInvoker(sp<WindowInfosListenerInvoker>::make()) {
375 ALOGI("Using HWComposer service: %s", mHwcServiceName.c_str());
376 }
378 SurfaceFlinger::SurfaceFlinger(Factory& factory) : SurfaceFlinger(factory, SkipInitialization) {
379 ALOGI("SurfaceFlinger is starting");
380
381 hasSyncFramework = running_without_sync_framework(true);
382
383 dispSyncPresentTimeOffset = present_time_offset_from_vsync_ns(0);
384
385 useHwcForRgbToYuv = force_hwc_copy_for_virtual_displays(false);
386
387 maxFrameBufferAcquiredBuffers = max_frame_buffer_acquired_buffers(2);
388
389 maxGraphicsWidth = std::max(max_graphics_width(0), 0);
390 maxGraphicsHeight = std::max(max_graphics_height(0), 0);
391
392 mSupportsWideColor = has_wide_color_display(false);
393 mDefaultCompositionDataspace =
394 static_cast<ui::Dataspace>(default_composition_dataspace(Dataspace::V0_SRGB));
395 mWideColorGamutCompositionDataspace = static_cast<ui::Dataspace>(wcg_composition_dataspace(
396 mSupportsWideColor ? Dataspace::DISPLAY_P3 : Dataspace::V0_SRGB));
397 defaultCompositionDataspace = mDefaultCompositionDataspace;
398 wideColorGamutCompositionDataspace = mWideColorGamutCompositionDataspace;
399 defaultCompositionPixelFormat = static_cast<ui::PixelFormat>(
400 default_composition_pixel_format(ui::PixelFormat::RGBA_8888));
401 wideColorGamutCompositionPixelFormat =
402 static_cast<ui::PixelFormat>(wcg_composition_pixel_format(ui::PixelFormat::RGBA_8888));
403
404 mColorSpaceAgnosticDataspace =
405 static_cast<ui::Dataspace>(color_space_agnostic_dataspace(Dataspace::UNKNOWN));
406
407 mLayerCachingEnabled = [] {
408 const bool enable =
409 android::sysprop::SurfaceFlingerProperties::enable_layer_caching().value_or(false);
410 return base::GetBoolProperty(std::string("debug.sf.enable_layer_caching"), enable);
411 }();
412
413 useContextPriority = use_context_priority(true);
414
415 mInternalDisplayPrimaries = sysprop::getDisplayNativePrimaries();
416
417 // debugging stuff...
418 char value[PROPERTY_VALUE_MAX];
419
420 property_get("ro.build.type", value, "user");
421 mIsUserBuild = strcmp(value, "user") == 0;
422
423 mDebugFlashDelay = base::GetUintProperty("debug.sf.showupdates"s, 0u);
424
425 mBackpressureGpuComposition = base::GetBoolProperty("debug.sf.enable_gl_backpressure"s, true);
426 ALOGI_IF(mBackpressureGpuComposition, "Enabling backpressure for GPU composition");
427
428 property_get("ro.surface_flinger.supports_background_blur", value, "0");
429 bool supportsBlurs = atoi(value);
430 mSupportsBlur = supportsBlurs;
431 ALOGI_IF(!mSupportsBlur, "Disabling blur effects, they are not supported.");
432
433 const size_t defaultListSize = MAX_LAYERS;
434 auto listSize = property_get_int32("debug.sf.max_igbp_list_size", int32_t(defaultListSize));
435 mMaxGraphicBufferProducerListSize = (listSize > 0) ? size_t(listSize) : defaultListSize;
436 mGraphicBufferProducerListSizeLogThreshold =
437 std::max(static_cast<int>(0.95 *
438 static_cast<double>(mMaxGraphicBufferProducerListSize)),
439 1);
440
441 property_get("debug.sf.luma_sampling", value, "1");
442 mLumaSampling = atoi(value);
443
444 property_get("debug.sf.disable_client_composition_cache", value, "0");
445 mDisableClientCompositionCache = atoi(value);
446
447 property_get("debug.sf.predict_hwc_composition_strategy", value, "1");
448 mPredictCompositionStrategy = atoi(value);
449
450 property_get("debug.sf.treat_170m_as_sRGB", value, "0");
451 mTreat170mAsSrgb = atoi(value);
452
453 mIgnoreHwcPhysicalDisplayOrientation =
454 base::GetBoolProperty("debug.sf.ignore_hwc_physical_display_orientation"s, false);
455
456 // We should be reading 'persist.sys.sf.color_saturation' here
457 // but since /data may be encrypted, we need to wait until after vold
458 // comes online to attempt to read the property. The property is
459 // instead read after the boot animation
460
461 if (base::GetBoolProperty("debug.sf.treble_testing_override"s, false)) {
462 // Without the override SurfaceFlinger cannot connect to HIDL
463 // services that are not listed in the manifests. Considered
464 // deriving the setting from the set service name, but it
465 // would be brittle if the name that's not 'default' is used
466 // for production purposes later on.
467 ALOGI("Enabling Treble testing override");
468 android::hardware::details::setTrebleTestingOverride(true);
469 }
470
471 // TODO (b/270966065) Update the HWC based refresh rate overlay to support spinner
472 mRefreshRateOverlaySpinner = property_get_bool("debug.sf.show_refresh_rate_overlay_spinner", 0);
473 mRefreshRateOverlayRenderRate =
474 property_get_bool("debug.sf.show_refresh_rate_overlay_render_rate", 0);
475 mRefreshRateOverlayShowInMiddle =
476 property_get_bool("debug.sf.show_refresh_rate_overlay_in_middle", 0);
477
478 if (!mIsUserBuild && base::GetBoolProperty("debug.sf.enable_transaction_tracing"s, true)) {
479 mTransactionTracing.emplace();
480 }
481
482 mIgnoreHdrCameraLayers = ignore_hdr_camera_layers(false);
483
484 mLayerLifecycleManagerEnabled =
485 base::GetBoolProperty("persist.debug.sf.enable_layer_lifecycle_manager"s, false);
486 mLegacyFrontEndEnabled = !mLayerLifecycleManagerEnabled ||
487 base::GetBoolProperty("persist.debug.sf.enable_legacy_frontend"s, false);
488 }
调用init
/frameworks/native/services/surfaceflinger/SurfaceFlinger.cpp
804 void SurfaceFlinger::init() FTL_FAKE_GUARD(kMainThreadContext) {
805 ALOGI( "SurfaceFlinger's main thread ready to run. "
806 "Initializing graphics H/W...");
807 addTransactionReadyFilters();
808 Mutex::Autolock lock(mStateLock);
809
810 // Get a RenderEngine for the given display / config (can't fail)
811 // TODO(b/77156734): We need to stop casting and use HAL types when possible.
812 // Sending maxFrameBufferAcquiredBuffers as the cache size is tightly tuned to single-display.
813 auto builder = renderengine::RenderEngineCreationArgs::Builder()
814 .setPixelFormat(static_cast<int32_t>(defaultCompositionPixelFormat))
815 .setImageCacheSize(maxFrameBufferAcquiredBuffers)
816 .setUseColorManagerment(useColorManagement)
817 .setEnableProtectedContext(enable_protected_contents(false))
818 .setPrecacheToneMapperShaderOnly(false)
819 .setSupportsBackgroundBlur(mSupportsBlur)
820 .setContextPriority(
821 useContextPriority
822 ? renderengine::RenderEngine::ContextPriority::REALTIME
823 : renderengine::RenderEngine::ContextPriority::MEDIUM);
824 if (auto type = chooseRenderEngineTypeViaSysProp()) {
825 builder.setRenderEngineType(type.value());
826 }
827 mRenderEngine = renderengine::RenderEngine::create(builder.build());
828 mCompositionEngine->setRenderEngine(mRenderEngine.get());
829 mMaxRenderTargetSize =
830 std::min(getRenderEngine().getMaxTextureSize(), getRenderEngine().getMaxViewportDims());
831
832 // Set SF main policy after initializing RenderEngine which has its own policy.
833 if (!SetTaskProfiles(0, {"SFMainPolicy"})) {
834 ALOGW("Failed to set main task profile");
835 }
836
837 mCompositionEngine->setTimeStats(mTimeStats);
838 mCompositionEngine->setHwComposer(getFactory().createHWComposer(mHwcServiceName));
839 mCompositionEngine->getHwComposer().setCallback(*this);
840 ClientCache::getInstance().setRenderEngine(&getRenderEngine());
841
842 enableLatchUnsignaledConfig = getLatchUnsignaledConfig();
843
844 if (base::GetBoolProperty("debug.sf.enable_hwc_vds"s, false)) {
845 enableHalVirtualDisplays(true);
846 }
847
848 // Process hotplug for displays connected at boot.
849 LOG_ALWAYS_FATAL_IF(!configureLocked(),
850 "Initial display configuration failed: HWC did not hotplug");
851
852 // Commit primary display.
853 sp<const DisplayDevice> display;
854 if (const auto indexOpt = mCurrentState.getDisplayIndex(getPrimaryDisplayIdLocked())) {
855 const auto& displays = mCurrentState.displays;
856
857 const auto& token = displays.keyAt(*indexOpt);
858 const auto& state = displays.valueAt(*indexOpt);
859
860 processDisplayAdded(token, state);
861 mDrawingState.displays.add(token, state);
862
863 display = getDefaultDisplayDeviceLocked();
864 }
865
866 LOG_ALWAYS_FATAL_IF(!display, "Failed to configure the primary display");
867 LOG_ALWAYS_FATAL_IF(!getHwComposer().isConnected(display->getPhysicalId()),
868 "Primary display is disconnected");
869
870 // TODO(b/241285876): The Scheduler needlessly depends on creating the CompositionEngine part of
871 // the DisplayDevice, hence the above commit of the primary display. Remove that special case by
872 // initializing the Scheduler after configureLocked, once decoupled from DisplayDevice.
873 initScheduler(display);
874 dispatchDisplayHotplugEvent(display->getPhysicalId(), true);
875
876 // Commit secondary display(s).
877 processDisplayChangesLocked();
878
879 // initialize our drawing state
880 mDrawingState = mCurrentState;
881
882 onActiveDisplayChangedLocked(nullptr, *display);
883
884 static_cast<void>(mScheduler->schedule(
885 [this]() FTL_FAKE_GUARD(kMainThreadContext) { initializeDisplays(); }));
886
887 mPowerAdvisor->init();
888
889 char primeShaderCache[PROPERTY_VALUE_MAX];
890 property_get("service.sf.prime_shader_cache", primeShaderCache, "1");
891 if (atoi(primeShaderCache)) {
892 if (setSchedFifo(false) != NO_ERROR) {
893 ALOGW("Can't set SCHED_OTHER for primeCache");
894 }
895
896 mRenderEnginePrimeCacheFuture = getRenderEngine().primeCache();
897
898 if (setSchedFifo(true) != NO_ERROR) {
899 ALOGW("Can't set SCHED_OTHER for primeCache");
900 }
901 }
902
903 // Inform native graphics APIs whether the present timestamp is supported:
904
905 const bool presentFenceReliable =
906 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE);
907 mStartPropertySetThread = getFactory().createStartPropertySetThread(presentFenceReliable);
908
909 if (mStartPropertySetThread->Start() != NO_ERROR) {
910 ALOGE("Run StartPropertySetThread failed!");
911 }
912
913 ALOGV("Done initializing");
914 }
调用initscheduler来初始化整个Vsync系统
3929 void SurfaceFlinger::initScheduler(const sp<const DisplayDevice>& display) {
3930 using namespace scheduler;
3931
3932 LOG_ALWAYS_FATAL_IF(mScheduler);
3933
3934 const auto activeMode = display->refreshRateSelector().getActiveMode();
3935 const Fps activeRefreshRate = activeMode.fps;
3936 mRefreshRateStats =
3937 std::make_unique<RefreshRateStats>(*mTimeStats, activeRefreshRate, hal::PowerMode::OFF);
3938
3939 mVsyncConfiguration = getFactory().createVsyncConfiguration(activeRefreshRate);
3940
3941 FeatureFlags features;
3942
3943 if (sysprop::use_content_detection_for_refresh_rate(false)) {
3944 features |= Feature::kContentDetection;
3945 }
3946 if (base::GetBoolProperty("debug.sf.show_predicted_vsync"s, false)) {
3947 features |= Feature::kTracePredictedVsync;
3948 }
3949 if (!base::GetBoolProperty("debug.sf.vsync_reactor_ignore_present_fences"s, false) &&
3950 !getHwComposer().hasCapability(Capability::PRESENT_FENCE_IS_NOT_RELIABLE)) {
3951 features |= Feature::kPresentFences;
3952 }
3953 if (display->refreshRateSelector().kernelIdleTimerController()) {
3954 features |= Feature::kKernelIdleTimer;
3955 }
3956
3957 auto modulatorPtr = sp<VsyncModulator>::make(mVsyncConfiguration->getCurrentConfigs());
3958
3959 mScheduler = std::make_unique<Scheduler>(static_cast<ICompositor&>(*this),
3960 static_cast<ISchedulerCallback&>(*this), features,
3961 std::move(modulatorPtr));
//创建mScheduler对象
3962 mScheduler->registerDisplay(display->getPhysicalId(), display->holdRefreshRateSelector());
3963
3964 setVsyncEnabled(display->getPhysicalId(), false);
3965 mScheduler->startTimers();
3966
3967 const auto configs = mVsyncConfiguration->getCurrentConfigs();
3968 //创建APP连接
3969 mAppConnectionHandle =
3970 mScheduler->createEventThread(Scheduler::Cycle::Render,
3971 mFrameTimeline->getTokenManager(),
3972 /* workDuration */ configs.late.appWorkDuration,
3973 /* readyDuration */ configs.late.sfWorkDuration);
// 创建SF连接
3974 mSfConnectionHandle =
3975 mScheduler->createEventThread(Scheduler::Cycle::LastComposite,
3976 mFrameTimeline->getTokenManager(),
3977 /* workDuration */ activeRefreshRate.getPeriod(),
3978 /* readyDuration */ configs.late.sfWorkDuration);
3979 //初始化Vsync
3980 mScheduler->initVsync(mScheduler->getVsyncSchedule()->getDispatch(),
3981 *mFrameTimeline->getTokenManager(), configs.late.sfWorkDuration);
3982
3983 mRegionSamplingThread =
3984 sp<RegionSamplingThread>::make(*this,
3985 RegionSamplingThread::EnvironmentTimingTunables());
3986 mFpsReporter = sp<FpsReporter>::make(*mFrameTimeline, *this);
3987 }
先来看连接的创建
createEventThread
/frameworks/native/services/surfaceflinger/Scheduler/Scheduler.cpp
225 ConnectionHandle Scheduler::createEventThread(Cycle cycle,
226 frametimeline::TokenManager* tokenManager,
227 std::chrono::nanoseconds workDuration,
228 std::chrono::nanoseconds readyDuration) {
229 auto eventThread = std::make_unique<impl::EventThread>(cycle == Cycle::Render ? "app" : "appSf",
230 getVsyncSchedule(), tokenManager,
231 makeThrottleVsyncCallback(),
232 makeGetVsyncPeriodFunction(),
233 workDuration, readyDuration);
234
235 auto& handle = cycle == Cycle::Render ? mAppConnectionHandle : mSfConnectionHandle;
236 handle = createConnection(std::move(eventThread));
237 return handle;
238 }
创建EventThread对象,对mVsyncTracer进行了赋值,systrace上我们看到的 VSYNC-app VSYNC-sf 标签就是它
/frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
242 EventThread::EventThread(const char* name, std::shared_ptr<scheduler::VsyncSchedule> vsyncSchedule,
243 android::frametimeline::TokenManager* tokenManager,
244 ThrottleVsyncCallback throttleVsyncCallback,
245 GetVsyncPeriodFunction getVsyncPeriodFunction,
246 std::chrono::nanoseconds workDuration,
247 std::chrono::nanoseconds readyDuration)
248 : mThreadName(name),
249 mVsyncTracer(base::StringPrintf("VSYNC-%s", name), 0),
250 mWorkDuration(base::StringPrintf("VsyncWorkDuration-%s", name), workDuration),
251 mReadyDuration(readyDuration),
252 mVsyncSchedule(std::move(vsyncSchedule)),
253 mVsyncRegistration(mVsyncSchedule->getDispatch(), createDispatchCallback(), name),
254 mTokenManager(tokenManager),
255 mThrottleVsyncCallback(std::move(throttleVsyncCallback)),
256 mGetVsyncPeriodFunction(std::move(getVsyncPeriodFunction)) {
257 LOG_ALWAYS_FATAL_IF(getVsyncPeriodFunction == nullptr,
258 "getVsyncPeriodFunction must not be null");
259
260 mThread = std::thread([this]() NO_THREAD_SAFETY_ANALYSIS {
261 std::unique_lock<std::mutex> lock(mMutex);
262 threadMain(lock);
263 });
264
265 pthread_setname_np(mThread.native_handle(), mThreadName);
266
267 pid_t tid = pthread_gettid_np(mThread.native_handle());
268
269 // Use SCHED_FIFO to minimize jitter
270 constexpr int EVENT_THREAD_PRIORITY = 2;
271 struct sched_param param = {0};
272 param.sched_priority = EVENT_THREAD_PRIORITY;
273 if (pthread_setschedparam(mThread.native_handle(), SCHED_FIFO, ¶m) != 0) {
274 ALOGE("Couldn't set SCHED_FIFO for EventThread");
275 }
276
277 set_sched_policy(tid, SP_FOREGROUND);
278 }
435 void EventThread::threadMain(std::unique_lock<std::mutex>& lock) {
436 DisplayEventConsumers consumers;
474 if (!consumers.empty()) {
475 dispatchEvent(*event, consumers);
476 consumers.clear();
477 }
654 void EventThread::dispatchEvent(const DisplayEventReceiver::Event& event,
655 const DisplayEventConsumers& consumers) {
656 for (const auto& consumer : consumers) {
657 DisplayEventReceiver::Event copy = event;
658 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_VSYNC) {
659 const int64_t frameInterval = mGetVsyncPeriodFunction(consumer->mOwnerUid);
660 copy.vsync.vsyncData.frameInterval = frameInterval;
661 generateFrameTimeline(copy.vsync.vsyncData, frameInterval, copy.header.timestamp,
662 event.vsync.vsyncData.preferredExpectedPresentationTime(),
663 event.vsync.vsyncData.preferredDeadlineTimestamp());
664 }
665 switch (consumer->postEvent(copy)) {
666 case NO_ERROR:
667 break;
668
669 case -EAGAIN:
670 // TODO: Try again if pipe is full.
671 ALOGW("Failed dispatching %s for %s", toString(event).c_str(),
672 toString(*consumer).c_str());
673 break;
674
675 default:
676 // Treat EPIPE and other errors as fatal.
677 removeDisplayEventConnectionLocked(consumer);
678 }
679 }
680 }
214 status_t EventThreadConnection::postEvent(const DisplayEventReceiver::Event& event) {
215 constexpr auto toStatus = [](ssize_t size) {
216 return size < 0 ? status_t(size) : status_t(NO_ERROR);
217 };
218
219 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE ||
220 event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE_FLUSH) {
221 mPendingEvents.emplace_back(event);
222 if (event.header.type == DisplayEventReceiver::DISPLAY_EVENT_FRAME_RATE_OVERRIDE) {
223 return status_t(NO_ERROR);
224 }
225
226 auto size = DisplayEventReceiver::sendEvents(&mChannel, mPendingEvents.data(),
227 mPendingEvents.size());
228 mPendingEvents.clear();
229 return toStatus(size);
230 }
231
232 auto size = DisplayEventReceiver::sendEvents(&mChannel, &event, 1);
233 return toStatus(size);
234 }
frameworks/native/libs/gui/DisplayEventReceiver.cpp
125 ssize_t DisplayEventReceiver::sendEvents(gui::BitTube* dataChannel,
126 Event const* events, size_t count)
127 {
128 return gui::BitTube::sendObjects(dataChannel, events, count);
129 }
/frameworks/native/libs/sensor/BitTube.cpp
143 ssize_t BitTube::sendObjects(const sp<BitTube>& tube,
144 void const* events, size_t count, size_t objSize)
145 {
146 const char* vaddr = reinterpret_cast<const char*>(events);
147 ssize_t size = tube->write(vaddr, count*objSize);
148
149 // should never happen because of SOCK_SEQPACKET
150 LOG_ALWAYS_FATAL_IF((size >= 0) && (size % static_cast<ssize_t>(objSize)),
151 "BitTube::sendObjects(count=%zu, size=%zu), res=%zd (partial events were sent!)",
152 count, objSize, size);
153
154 //ALOGE_IF(size<0, "error %d sending %d events", size, count);
155 return size < 0 ? size : size / static_cast<ssize_t>(objSize);
156 }
105 ssize_t BitTube::write(void const* vaddr, size_t size)
106 {
107 ssize_t err, len;
108 do {
109 len = ::send(mSendFd, vaddr, size, MSG_DONTWAIT | MSG_NOSIGNAL);
110 // cannot return less than size, since we're using SOCK_SEQPACKET
111 err = len < 0 ? errno : 0;
112 } while (err == EINTR);
113 return err == 0 ? len : -err;
114 }
通过调用系统函数send向与消费者关联的文件描述符FD发送信号,于是完成Vsync的分发
当pendingEvents为空的时候,就会调用mCondition.wait(lock);等待有新的Vsync或者新的Client进入
然后将EventThread 作为参数构建Connection
240 ConnectionHandle Scheduler::createConnection(std::unique_ptr<EventThread> eventThread) {
241 const ConnectionHandle handle = ConnectionHandle{mNextConnectionHandleId++};
242 ALOGV("Creating a connection handle with ID %" PRIuPTR, handle.id);
243
244 auto connection = createConnectionInternal(eventThread.get());
245
246 std::lock_guard<std::mutex> lock(mConnectionsLock);
247 mConnections.emplace(handle, Connection{connection, std::move(eventThread)});
248 return handle;
249 }
251 sp<EventThreadConnection> Scheduler::createConnectionInternal(
252 EventThread* eventThread, EventRegistrationFlags eventRegistration,
253 const sp<IBinder>& layerHandle) {
254 int32_t layerId = static_cast<int32_t>(LayerHandle::getLayerId(layerHandle));
255 auto connection = eventThread->createEventConnection([&] { resync(); }, eventRegistration);
256 mLayerHistory.attachChoreographer(layerId, connection);
257 return connection;
258 }
frameworks/native/services/surfaceflinger/Scheduler/EventThread.cpp
300 sp<EventThreadConnection> EventThread::createEventConnection(
301 ResyncCallback resyncCallback, EventRegistrationFlags eventRegistration) const {
302 return sp<EventThreadConnection>::make(const_cast<EventThread*>(this),
303 IPCThreadState::self()->getCallingUid(),
304 std::move(resyncCallback), eventRegistration);
305 }
构造函数中最重要的就是创建了mChannel,mChannel是gui::BitTube类型
接着看gui::BitTube的构造函数:这里传递的DefaultSize为4kb,
定义在BitTube.h中:
// creates a BitTube with a default (4KB) send buffer
struct DefaultSizeType {};
static constexpr DefaultSizeType DefaultSize{};
mChannel 相当于surfaceFlinger进程中创建的mReceiveFd传递到app进程中去,app进程有了mReceiveFd,surfaceFlinger进程有了mSendFd就能够实现通信了
178 void EventThreadConnection::onFirstRef() {
179 // NOTE: mEventThread doesn't hold a strong reference on us
180 mEventThread->registerDisplayEventConnection(sp<EventThreadConnection>::fromExisting(this));
181 }
initVsync
创建了ConnectionHandle后,后面调用了mEventQueue->initVsync。
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp
78 void MessageQueue::initVsync(std::shared_ptr<scheduler::VSyncDispatch> dispatch,
79 frametimeline::TokenManager& tokenManager,
80 std::chrono::nanoseconds workDuration) {
81 std::unique_ptr<scheduler::VSyncCallbackRegistration> oldRegistration;
82 {
83 std::lock_guard lock(mVsync.mutex);
84 mVsync.workDuration = workDuration;
85 mVsync.tokenManager = &tokenManager;
86 oldRegistration = onNewVsyncScheduleLocked(std::move(dispatch));
87 }
88
89 // See comments in onNewVsyncSchedule. Today, oldRegistration should be
90 // empty, but nothing prevents us from calling initVsync multiple times, so
91 // go ahead and destruct it outside the lock for safety.
92 oldRegistration.reset();
93 }
这里只是将MessageQueue::vsyncCallback这个方法与mVsync绑定,在后面mVsync.registration.schedule的时候,会触发MessageQueue::vsyncCallback方法。
flinger->run();
SurfaceFlinger线程run时,启动一个死循环,循环等待事件。
518 void SurfaceFlinger::run() {
519 mScheduler->run();
520 }
/frameworks/native/services/surfaceflinger/Scheduler/Scheduler.cpp
154 void Scheduler::run() {
155 while (true) {
156 waitMessage();
157 }
158 }
/frameworks/native/services/surfaceflinger/Scheduler/MessageQueue.cpp
149 void MessageQueue::waitMessage() {
150 do {
151 IPCThreadState::self()->flushCommands();
152 int32_t ret = mLooper->pollOnce(-1);
153 switch (ret) {
154 case Looper::POLL_WAKE:
155 case Looper::POLL_CALLBACK:
156 continue;
157 case Looper::POLL_ERROR:
158 ALOGE("Looper::POLL_ERROR");
159 continue;
160 case Looper::POLL_TIMEOUT:
161 // timeout (should not happen)
162 continue;
163 default:
164 // should not happen
165 ALOGE("Looper::pollOnce() returned unknown status %d", ret);
166 continue;
167 }
168 } while (true);
169 }
/frameworks/base/core/jni/android_os_MessageQueue.cpp
waitMessage,通过采用一个死循环,处理Looper的pollOnce。Looper内部的逻辑就不看了,主要是采用epoll_wait对fd进行监听,BitTube发送Event对象后,epoll_wait结束,调用callback,处理事件
122 void NativeMessageQueue::pollOnce(JNIEnv* env, jobject pollObj, int timeoutMillis) {
123 mPollEnv = env;
124 mPollObj = pollObj;
125 mLooper->pollOnce(timeoutMillis);
126 mPollObj = NULL;
127 mPollEnv = NULL;
128
129 if (mExceptionObj) {
130 env->Throw(mExceptionObj);
131 env->DeleteLocalRef(mExceptionObj);
132 mExceptionObj = NULL;
133 }
134 }