Merge "Eliminate potential reentrance from unregisterInputChannel." into jb-mr1-dev
diff --git a/services/input/InputDispatcher.cpp b/services/input/InputDispatcher.cpp
index 7862e17..0465215 100644
--- a/services/input/InputDispatcher.cpp
+++ b/services/input/InputDispatcher.cpp
@@ -224,10 +224,16 @@
         AutoMutex _l(mLock);
         mDispatcherIsAliveCondition.broadcast();
 
-        dispatchOnceInnerLocked(&nextWakeupTime);
+        // Run a dispatch loop if there are no pending commands.
+        // The dispatch loop might enqueue commands to run afterwards.
+        if (!haveCommandsLocked()) {
+            dispatchOnceInnerLocked(&nextWakeupTime);
+        }
 
+        // Run all pending commands if there are any.
+        // If any commands were run then force the next poll to wake up immediately.
         if (runCommandsLockedInterruptible()) {
-            nextWakeupTime = LONG_LONG_MIN;  // force next poll to wake up immediately
+            nextWakeupTime = LONG_LONG_MIN;
         }
     } // release lock
 
@@ -562,6 +568,10 @@
     return currentTime - entry->eventTime >= STALE_EVENT_TIMEOUT;
 }
 
+bool InputDispatcher::haveCommandsLocked() const {
+    return !mCommandQueue.isEmpty();
+}
+
 bool InputDispatcher::runCommandsLockedInterruptible() {
     if (mCommandQueue.isEmpty()) {
         return false;
@@ -3247,9 +3257,10 @@
         }
 
         mLooper->addFd(fd, 0, ALOOPER_EVENT_INPUT, handleReceiveCallback, this);
-
-        runCommandsLockedInterruptible();
     } // release lock
+
+    // Wake the looper because some connections have changed.
+    mLooper->wake();
     return OK;
 }
 
@@ -3294,8 +3305,6 @@
     nsecs_t currentTime = now();
     abortBrokenDispatchCycleLocked(currentTime, connection, notify);
 
-    runCommandsLockedInterruptible();
-
     connection->status = Connection::STATUS_ZOMBIE;
     return OK;
 }
diff --git a/services/input/InputDispatcher.h b/services/input/InputDispatcher.h
index 6099c43..d4f932e 100644
--- a/services/input/InputDispatcher.h
+++ b/services/input/InputDispatcher.h
@@ -899,6 +899,7 @@
     KeyEntry* synthesizeKeyRepeatLocked(nsecs_t currentTime);
 
     // Deferred command processing.
+    bool haveCommandsLocked() const;
     bool runCommandsLockedInterruptible();
     CommandEntry* postCommandLocked(Command command);