SF: Creating a basic Scheduler class.

Added a flag that can be turned on at runtime, and turns on the new path.
Added a basic Scheduler that encapsulates SF and App thread.

This is part of the go/surfce-flinger-scheduler move.

Test: All SF tests pass. Adding a Scheduler test in the next CL.

Change-Id: Ic45b662f82d60da1172bf64485c838344082b306
diff --git a/services/surfaceflinger/Android.bp b/services/surfaceflinger/Android.bp
index 05535a5..da57511 100644
--- a/services/surfaceflinger/Android.bp
+++ b/services/surfaceflinger/Android.bp
@@ -125,6 +125,7 @@
         "Scheduler/EventControlThread.cpp",
         "Scheduler/EventThread.cpp",
         "Scheduler/MessageQueue.cpp",
+        "Scheduler/Scheduler.cpp",
         "StartPropertySetThread.cpp",
         "SurfaceFlinger.cpp",
         "SurfaceInterceptor.cpp",
diff --git a/services/surfaceflinger/Scheduler/EventThread.cpp b/services/surfaceflinger/Scheduler/EventThread.cpp
index b84177c..fa2b0a6 100644
--- a/services/surfaceflinger/Scheduler/EventThread.cpp
+++ b/services/surfaceflinger/Scheduler/EventThread.cpp
@@ -45,11 +45,27 @@
 
 namespace impl {
 
+EventThread::EventThread(std::unique_ptr<VSyncSource> src,
+                         ResyncWithRateLimitCallback resyncWithRateLimitCallback,
+                         InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
+      : EventThread(nullptr, std::move(src), resyncWithRateLimitCallback, interceptVSyncsCallback,
+                    threadName) {}
+
 EventThread::EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
                          InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
+      : EventThread(src, nullptr, resyncWithRateLimitCallback, interceptVSyncsCallback,
+                    threadName) {}
+
+EventThread::EventThread(VSyncSource* src, std::unique_ptr<VSyncSource> uniqueSrc,
+                         ResyncWithRateLimitCallback resyncWithRateLimitCallback,
+                         InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName)
       : mVSyncSource(src),
+        mVSyncSourceUnique(std::move(uniqueSrc)),
         mResyncWithRateLimitCallback(resyncWithRateLimitCallback),
         mInterceptVSyncsCallback(interceptVSyncsCallback) {
+    if (src == nullptr) {
+        mVSyncSource = mVSyncSourceUnique.get();
+    }
     for (auto& event : mVSyncEvent) {
         event.header.type = DisplayEventReceiver::DISPLAY_EVENT_VSYNC;
         event.header.id = 0;
diff --git a/services/surfaceflinger/Scheduler/EventThread.h b/services/surfaceflinger/Scheduler/EventThread.h
index a0262b2..127891e 100644
--- a/services/surfaceflinger/Scheduler/EventThread.h
+++ b/services/surfaceflinger/Scheduler/EventThread.h
@@ -108,8 +108,12 @@
     using ResyncWithRateLimitCallback = std::function<void()>;
     using InterceptVSyncsCallback = std::function<void(nsecs_t)>;
 
+    // TODO(b/113612090): Once the Scheduler is complete this constructor will become obsolete.
     EventThread(VSyncSource* src, ResyncWithRateLimitCallback resyncWithRateLimitCallback,
                 InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
+    EventThread(std::unique_ptr<VSyncSource> src,
+                ResyncWithRateLimitCallback resyncWithRateLimitCallback,
+                InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
     ~EventThread();
 
     sp<BnDisplayEventConnection> createEventConnection() const override;
@@ -134,6 +138,11 @@
 private:
     friend EventThreadTest;
 
+    // TODO(b/113612090): Once the Scheduler is complete this constructor will become obsolete.
+    EventThread(VSyncSource* src, std::unique_ptr<VSyncSource> uniqueSrc,
+                ResyncWithRateLimitCallback resyncWithRateLimitCallback,
+                InterceptVSyncsCallback interceptVSyncsCallback, const char* threadName);
+
     void threadMain();
     Vector<sp<EventThread::Connection>> waitForEventLocked(std::unique_lock<std::mutex>* lock,
                                                            DisplayEventReceiver::Event* event)
@@ -146,8 +155,10 @@
     // Implements VSyncSource::Callback
     void onVSyncEvent(nsecs_t timestamp) override;
 
+    // TODO(b/113612090): Once the Scheduler is complete this pointer will become obsolete.
+    VSyncSource* mVSyncSource GUARDED_BY(mMutex) = nullptr;
+    std::unique_ptr<VSyncSource> mVSyncSourceUnique GUARDED_BY(mMutex) = nullptr;
     // constants
-    VSyncSource* const mVSyncSource GUARDED_BY(mMutex) = nullptr;
     const ResyncWithRateLimitCallback mResyncWithRateLimitCallback;
     const InterceptVSyncsCallback mInterceptVSyncsCallback;
 
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.cpp b/services/surfaceflinger/Scheduler/MessageQueue.cpp
index 056d381..58355ae 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.cpp
+++ b/services/surfaceflinger/Scheduler/MessageQueue.cpp
@@ -101,6 +101,17 @@
                    this);
 }
 
+void MessageQueue::setEventConnection(const sp<BnDisplayEventConnection>& connection) {
+    if (mEventTube.getFd() >= 0) {
+        mLooper->removeFd(mEventTube.getFd());
+    }
+
+    mEvents = connection;
+    mEvents->stealReceiveChannel(&mEventTube);
+    mLooper->addFd(mEventTube.getFd(), 0, Looper::EVENT_INPUT, MessageQueue::cb_eventReceiver,
+                   this);
+}
+
 void MessageQueue::waitMessage() {
     do {
         IPCThreadState::self()->flushCommands();
diff --git a/services/surfaceflinger/Scheduler/MessageQueue.h b/services/surfaceflinger/Scheduler/MessageQueue.h
index 90d1c72..2ec697e 100644
--- a/services/surfaceflinger/Scheduler/MessageQueue.h
+++ b/services/surfaceflinger/Scheduler/MessageQueue.h
@@ -85,7 +85,9 @@
     virtual ~MessageQueue();
 
     virtual void init(const sp<SurfaceFlinger>& flinger) = 0;
+    // TODO(akrulec): Remove this function once everything is migrated to Scheduler.
     virtual void setEventThread(EventThread* events) = 0;
+    virtual void setEventConnection(const sp<BnDisplayEventConnection>& connection) = 0;
     virtual void waitMessage() = 0;
     virtual status_t postMessage(const sp<MessageBase>& message, nsecs_t reltime = 0) = 0;
     virtual void invalidate() = 0;
@@ -125,6 +127,7 @@
     ~MessageQueue() override = default;
     void init(const sp<SurfaceFlinger>& flinger) override;
     void setEventThread(android::EventThread* events) override;
+    void setEventConnection(const sp<BnDisplayEventConnection>& connection) override;
 
     void waitMessage() override;
     status_t postMessage(const sp<MessageBase>& message, nsecs_t reltime = 0) override;
diff --git a/services/surfaceflinger/Scheduler/Scheduler.cpp b/services/surfaceflinger/Scheduler/Scheduler.cpp
new file mode 100644
index 0000000..a7c08cf
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/Scheduler.cpp
@@ -0,0 +1,105 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#include "Scheduler.h"
+
+#include <cinttypes>
+#include <cstdint>
+#include <memory>
+
+#include <gui/ISurfaceComposer.h>
+
+#include "DispSync.h"
+#include "DispSyncSource.h"
+#include "EventThread.h"
+#include "InjectVSyncSource.h"
+
+namespace android {
+
+std::atomic<int64_t> Scheduler::sNextId = 0;
+
+sp<Scheduler::ConnectionHandle> Scheduler::createConnection(
+        const char* connectionName, DispSync* dispSync, int64_t phaseOffsetNs,
+        impl::EventThread::ResyncWithRateLimitCallback resyncCallback,
+        impl::EventThread::InterceptVSyncsCallback interceptCallback) {
+    const int64_t id = sNextId++;
+    ALOGV("Creating a connection handle with ID: %" PRId64 "\n", id);
+
+    std::unique_ptr<VSyncSource> eventThreadSource =
+            std::make_unique<DispSyncSource>(dispSync, phaseOffsetNs, true, connectionName);
+    std::unique_ptr<EventThread> eventThread =
+            std::make_unique<impl::EventThread>(std::move(eventThreadSource), resyncCallback,
+                                                interceptCallback, connectionName);
+    auto connection = std::make_unique<Connection>(new ConnectionHandle(id),
+                                                   eventThread->createEventConnection(),
+                                                   std::move(eventThread));
+    mConnections.insert(std::make_pair(id, std::move(connection)));
+    return mConnections[id]->handle;
+}
+
+sp<IDisplayEventConnection> Scheduler::createDisplayEventConnection(
+        const sp<Scheduler::ConnectionHandle>& handle) {
+    if (mConnections.count(handle->id) != 0) {
+        return mConnections[handle->id]->thread->createEventConnection();
+    }
+    return nullptr;
+}
+
+EventThread* Scheduler::getEventThread(const sp<Scheduler::ConnectionHandle>& handle) {
+    if (mConnections.count(handle->id) != 0) {
+        return mConnections[handle->id]->thread.get();
+    }
+    return nullptr;
+}
+
+sp<BnDisplayEventConnection> Scheduler::getEventConnection(const sp<ConnectionHandle>& handle) {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        return mConnections[handle->id]->eventConnection;
+    }
+    return nullptr;
+}
+
+void Scheduler::hotplugReceived(const sp<Scheduler::ConnectionHandle>& handle,
+                                EventThread::DisplayType displayType, bool connected) {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        mConnections[handle->id]->thread->onHotplugReceived(displayType, connected);
+    }
+}
+
+void Scheduler::onScreenAcquired(const sp<Scheduler::ConnectionHandle>& handle) {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        mConnections[handle->id]->thread->onScreenAcquired();
+    }
+}
+
+void Scheduler::onScreenReleased(const sp<Scheduler::ConnectionHandle>& handle) {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        mConnections[handle->id]->thread->onScreenReleased();
+    }
+}
+
+void Scheduler::dump(const sp<Scheduler::ConnectionHandle>& handle, String8& result) const {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        mConnections.at(handle->id)->thread->dump(result);
+    }
+}
+
+void Scheduler::setPhaseOffset(const sp<Scheduler::ConnectionHandle>& handle, nsecs_t phaseOffset) {
+    if (mConnections.find(handle->id) != mConnections.end()) {
+        mConnections[handle->id]->thread->setPhaseOffset(phaseOffset);
+    }
+}
+} // namespace android
diff --git a/services/surfaceflinger/Scheduler/Scheduler.h b/services/surfaceflinger/Scheduler/Scheduler.h
new file mode 100644
index 0000000..caccd6f
--- /dev/null
+++ b/services/surfaceflinger/Scheduler/Scheduler.h
@@ -0,0 +1,85 @@
+/*
+ * Copyright 2018 The Android Open Source Project
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ *      http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+#pragma once
+
+#include <cstdint>
+#include <memory>
+
+#include <gui/ISurfaceComposer.h>
+
+#include "DispSync.h"
+#include "EventThread.h"
+#include "InjectVSyncSource.h"
+
+namespace android {
+
+class Scheduler {
+public:
+    /* The scheduler handle is a BBinder object passed to the client from which we can extract
+     * an ID for subsequent operations.
+     */
+    class ConnectionHandle : public BBinder {
+    public:
+        ConnectionHandle(int64_t id) : id(id) {}
+        ~ConnectionHandle() = default;
+        const int64_t id;
+    };
+
+    class Connection {
+    public:
+        Connection(sp<ConnectionHandle> handle, sp<BnDisplayEventConnection> eventConnection,
+                   std::unique_ptr<EventThread> eventThread)
+              : handle(handle), eventConnection(eventConnection), thread(std::move(eventThread)) {}
+        ~Connection() = default;
+
+        sp<ConnectionHandle> handle;
+        sp<BnDisplayEventConnection> eventConnection;
+        const std::unique_ptr<EventThread> thread;
+    };
+
+    Scheduler() = default;
+    ~Scheduler() = default;
+
+    /** Creates an EventThread connection. */
+    sp<ConnectionHandle> createConnection(
+            const char* connectionName, DispSync* dispSync, int64_t phaseOffsetNs,
+            impl::EventThread::ResyncWithRateLimitCallback resyncCallback,
+            impl::EventThread::InterceptVSyncsCallback interceptCallback);
+    sp<IDisplayEventConnection> createDisplayEventConnection(const sp<ConnectionHandle>& handle);
+
+    // Getter methods.
+    EventThread* getEventThread(const sp<ConnectionHandle>& handle);
+    sp<BnDisplayEventConnection> getEventConnection(const sp<ConnectionHandle>& handle);
+
+    // Should be called when receiving a hotplug event.
+    void hotplugReceived(const sp<ConnectionHandle>& handle, EventThread::DisplayType displayType,
+                         bool connected);
+    // Should be called after the screen is turned on.
+    void onScreenAcquired(const sp<ConnectionHandle>& handle);
+    // Should be called before the screen is turned off.
+    void onScreenReleased(const sp<ConnectionHandle>& handle);
+    // Should be called when dumpsys command is received.
+    void dump(const sp<ConnectionHandle>& handle, String8& result) const;
+    // Offers ability to modify phase offset in the event thread.
+    void setPhaseOffset(const sp<ConnectionHandle>& handle, nsecs_t phaseOffset);
+
+private:
+    static std::atomic<int64_t> sNextId;
+    std::unordered_map<int64_t, std::unique_ptr<Connection>> mConnections;
+};
+
+} // namespace android
\ No newline at end of file
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index 124b773..8c46e8a 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -87,6 +87,7 @@
 #include "Scheduler/EventControlThread.h"
 #include "Scheduler/EventThread.h"
 #include "Scheduler/InjectVSyncSource.h"
+#include "Scheduler/Scheduler.h"
 
 #include <cutils/compiler.h>
 
@@ -399,6 +400,9 @@
     property_get("debug.sf.early_gl_app_phase_offset_ns", value, "-1");
     const int earlyGlAppOffsetNs = atoi(value);
 
+    property_get("debug.sf.use_scheduler", value, "0");
+    mUseScheduler = atoi(value);
+
     const VSyncModulator::Offsets earlyOffsets =
             {earlySfOffsetNs != -1 ? earlySfOffsetNs : sfVsyncPhaseOffsetNs,
             earlyAppOffsetNs != -1 ? earlyAppOffsetNs : vsyncPhaseOffsetNs};
@@ -595,26 +599,47 @@
     Mutex::Autolock _l(mStateLock);
 
     // start the EventThread
-    mEventThreadSource =
-            std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
-                                             SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
-    mEventThread = std::make_unique<impl::EventThread>(mEventThreadSource.get(),
-                                                       [this] { resyncWithRateLimit(); },
-                                                       impl::EventThread::InterceptVSyncsCallback(),
-                                                       "appEventThread");
-    mSfEventThreadSource =
-            std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
-                                             SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
+    if (mUseScheduler) {
+        mScheduler = std::make_unique<Scheduler>();
+        mAppConnectionHandle =
+                mScheduler->createConnection("appConnection", mPrimaryDispSync.get(),
+                                             SurfaceFlinger::vsyncPhaseOffsetNs,
+                                             [this] { resyncWithRateLimit(); },
+                                             impl::EventThread::InterceptVSyncsCallback());
+        mSfConnectionHandle =
+                mScheduler->createConnection("sfConnection", mPrimaryDispSync.get(),
+                                             SurfaceFlinger::sfVsyncPhaseOffsetNs,
+                                             [this] { resyncWithRateLimit(); },
+                                             [this](nsecs_t timestamp) {
+                                                 mInterceptor->saveVSyncEvent(timestamp);
+                                             });
 
-    mSFEventThread =
-            std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
-                                                [this] { resyncWithRateLimit(); },
-                                                [this](nsecs_t timestamp) {
-                                                    mInterceptor->saveVSyncEvent(timestamp);
-                                                },
-                                                "sfEventThread");
-    mEventQueue->setEventThread(mSFEventThread.get());
-    mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
+        mEventQueue->setEventConnection(mScheduler->getEventConnection(mSfConnectionHandle));
+        mVsyncModulator.setEventThreads(mScheduler->getEventThread(mSfConnectionHandle),
+                                        mScheduler->getEventThread(mAppConnectionHandle));
+    } else {
+        mEventThreadSource =
+                std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
+                                                 SurfaceFlinger::vsyncPhaseOffsetNs, true, "app");
+        mEventThread =
+                std::make_unique<impl::EventThread>(mEventThreadSource.get(),
+                                                    [this] { resyncWithRateLimit(); },
+                                                    impl::EventThread::InterceptVSyncsCallback(),
+                                                    "appEventThread");
+        mSfEventThreadSource =
+                std::make_unique<DispSyncSource>(mPrimaryDispSync.get(),
+                                                 SurfaceFlinger::sfVsyncPhaseOffsetNs, true, "sf");
+
+        mSFEventThread =
+                std::make_unique<impl::EventThread>(mSfEventThreadSource.get(),
+                                                    [this] { resyncWithRateLimit(); },
+                                                    [this](nsecs_t timestamp) {
+                                                        mInterceptor->saveVSyncEvent(timestamp);
+                                                    },
+                                                    "sfEventThread");
+        mEventQueue->setEventThread(mSFEventThread.get());
+        mVsyncModulator.setEventThreads(mSFEventThread.get(), mEventThread.get());
+    }
 
     // Get a RenderEngine for the given display / config (can't fail)
     int32_t renderEngineFeature = 0;
@@ -1083,6 +1108,8 @@
             return;
         }
 
+        // TODO(akrulec): Part of the Injector should be refactored, so that it
+        // can be passed to Scheduler.
         if (enable) {
             ALOGV("VSync Injections enabled");
             if (mVSyncInjector.get() == nullptr) {
@@ -1141,10 +1168,18 @@
 
 sp<IDisplayEventConnection> SurfaceFlinger::createDisplayEventConnection(
         ISurfaceComposer::VsyncSource vsyncSource) {
-    if (vsyncSource == eVsyncSourceSurfaceFlinger) {
-        return mSFEventThread->createEventConnection();
+    if (mUseScheduler) {
+        if (vsyncSource == eVsyncSourceSurfaceFlinger) {
+            return mScheduler->createDisplayEventConnection(mSfConnectionHandle);
+        } else {
+            return mScheduler->createDisplayEventConnection(mAppConnectionHandle);
+        }
     } else {
-        return mEventThread->createEventConnection();
+        if (vsyncSource == eVsyncSourceSurfaceFlinger) {
+            return mSFEventThread->createEventConnection();
+        } else {
+            return mEventThread->createEventConnection();
+        }
     }
 }
 
@@ -2508,9 +2543,19 @@
                     display->disconnect(getHwComposer());
                 }
                 if (draw[i].type == DisplayDevice::DISPLAY_PRIMARY) {
-                    mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
+                    if (mUseScheduler) {
+                        mScheduler->hotplugReceived(mAppConnectionHandle,
+                                                    EventThread::DisplayType::Primary, false);
+                    } else {
+                        mEventThread->onHotplugReceived(EventThread::DisplayType::Primary, false);
+                    }
                 } else if (draw[i].type == DisplayDevice::DISPLAY_EXTERNAL) {
-                    mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
+                    if (mUseScheduler) {
+                        mScheduler->hotplugReceived(mAppConnectionHandle,
+                                                    EventThread::DisplayType::External, false);
+                    } else {
+                        mEventThread->onHotplugReceived(EventThread::DisplayType::External, false);
+                    }
                 }
                 mDisplays.erase(draw.keyAt(i));
             } else {
@@ -2613,11 +2658,23 @@
                                                                     dispSurface, producer));
                     if (!state.isVirtual()) {
                         if (state.type == DisplayDevice::DISPLAY_PRIMARY) {
-                            mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
+                            if (mUseScheduler) {
+                                mScheduler->hotplugReceived(mAppConnectionHandle,
+                                                            EventThread::DisplayType::Primary,
                                                             true);
+                            } else {
+                                mEventThread->onHotplugReceived(EventThread::DisplayType::Primary,
+                                                                true);
+                            }
                         } else if (state.type == DisplayDevice::DISPLAY_EXTERNAL) {
-                            mEventThread->onHotplugReceived(EventThread::DisplayType::External,
+                            if (mUseScheduler) {
+                                mScheduler->hotplugReceived(mAppConnectionHandle,
+                                                            EventThread::DisplayType::External,
                                                             true);
+                            } else {
+                                mEventThread->onHotplugReceived(EventThread::DisplayType::External,
+                                                                true);
+                            }
                         }
                     }
                 }
@@ -3942,7 +3999,11 @@
         getHwComposer().setPowerMode(type, mode);
         if (display->isPrimary() && mode != HWC_POWER_MODE_DOZE_SUSPEND) {
             // FIXME: eventthread only knows about the main display right now
-            mEventThread->onScreenAcquired();
+            if (mUseScheduler) {
+                mScheduler->onScreenAcquired(mAppConnectionHandle);
+            } else {
+                mEventThread->onScreenAcquired();
+            }
             resyncToHardwareVsync(true);
         }
 
@@ -3966,7 +4027,11 @@
             disableHardwareVsync(true); // also cancels any in-progress resync
 
             // FIXME: eventthread only knows about the main display right now
-            mEventThread->onScreenReleased();
+            if (mUseScheduler) {
+                mScheduler->onScreenReleased(mAppConnectionHandle);
+            } else {
+                mEventThread->onScreenReleased();
+            }
         }
 
         getHwComposer().setPowerMode(type, mode);
@@ -3978,7 +4043,11 @@
         getHwComposer().setPowerMode(type, mode);
         if (display->isPrimary() && currentMode == HWC_POWER_MODE_DOZE_SUSPEND) {
             // FIXME: eventthread only knows about the main display right now
-            mEventThread->onScreenAcquired();
+            if (mUseScheduler) {
+                mScheduler->onScreenAcquired(mAppConnectionHandle);
+            } else {
+                mEventThread->onScreenAcquired();
+            }
             resyncToHardwareVsync(true);
         }
     } else if (mode == HWC_POWER_MODE_DOZE_SUSPEND) {
@@ -3986,7 +4055,11 @@
         if (display->isPrimary()) {
             disableHardwareVsync(true); // also cancels any in-progress resync
             // FIXME: eventthread only knows about the main display right now
-            mEventThread->onScreenReleased();
+            if (mUseScheduler) {
+                mScheduler->onScreenReleased(mAppConnectionHandle);
+            } else {
+                mEventThread->onScreenReleased();
+            }
         }
         getHwComposer().setPowerMode(type, mode);
     } else {
@@ -4584,10 +4657,15 @@
     result.appendFormat("  transaction time: %f us\n",
             inTransactionDuration/1000.0);
 
+    result.appendFormat("  use Scheduler: %s\n", mUseScheduler ? "true" : "false");
     /*
      * VSYNC state
      */
-    mEventThread->dump(result);
+    if (mUseScheduler) {
+        mScheduler->dump(mAppConnectionHandle, result);
+    } else {
+        mEventThread->dump(result);
+    }
     result.append("\n");
 
     /*
@@ -4923,12 +5001,20 @@
             }
             case 1018: { // Modify Choreographer's phase offset
                 n = data.readInt32();
-                mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
+                if (mUseScheduler) {
+                    mScheduler->setPhaseOffset(mAppConnectionHandle, static_cast<nsecs_t>(n));
+                } else {
+                    mEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
+                }
                 return NO_ERROR;
             }
             case 1019: { // Modify SurfaceFlinger's phase offset
                 n = data.readInt32();
-                mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
+                if (mUseScheduler) {
+                    mScheduler->setPhaseOffset(mSfConnectionHandle, static_cast<nsecs_t>(n));
+                } else {
+                    mSFEventThread->setPhaseOffset(static_cast<nsecs_t>(n));
+                }
                 return NO_ERROR;
             }
             case 1020: { // Layer updates interceptor
diff --git a/services/surfaceflinger/SurfaceFlinger.h b/services/surfaceflinger/SurfaceFlinger.h
index c000ea2..3e76904 100644
--- a/services/surfaceflinger/SurfaceFlinger.h
+++ b/services/surfaceflinger/SurfaceFlinger.h
@@ -69,6 +69,7 @@
 #include "Scheduler/DispSync.h"
 #include "Scheduler/EventThread.h"
 #include "Scheduler/MessageQueue.h"
+#include "Scheduler/Scheduler.h"
 #include "Scheduler/VSyncModulator.h"
 #include "TimeStats/TimeStats.h"
 
@@ -935,6 +936,11 @@
     CreateNativeWindowSurfaceFunction mCreateNativeWindowSurface;
 
     SurfaceFlingerBE mBE;
+
+    bool mUseScheduler = false;
+    std::unique_ptr<Scheduler> mScheduler;
+    sp<Scheduler::ConnectionHandle> mAppConnectionHandle;
+    sp<Scheduler::ConnectionHandle> mSfConnectionHandle;
 };
 }; // namespace android
 
diff --git a/services/surfaceflinger/tests/unittests/mock/MockMessageQueue.h b/services/surfaceflinger/tests/unittests/mock/MockMessageQueue.h
index 8d503f4..f2f3675 100644
--- a/services/surfaceflinger/tests/unittests/mock/MockMessageQueue.h
+++ b/services/surfaceflinger/tests/unittests/mock/MockMessageQueue.h
@@ -30,6 +30,7 @@
 
     MOCK_METHOD1(init, void(const sp<SurfaceFlinger>&));
     MOCK_METHOD1(setEventThread, void(android::EventThread*));
+    MOCK_METHOD1(setEventConnection, void(const sp<BnDisplayEventConnection>& connection));
     MOCK_METHOD0(waitMessage, void());
     MOCK_METHOD2(postMessage, status_t(const sp<MessageBase>&, nsecs_t));
     MOCK_METHOD0(invalidate, void());