Fix crashes after HDMI disconnect

The display was being removed from SurfaceFlinger's list before we
had a chance to reset HWComposer's layer list, so we were passing
stale data into the hardware composer (which has its own per-display
data).  This resulted in "invalid gralloc handle" complaints.
We now clear the layer list immediately after removing the display.

The display was being removed while its EGLSurface was still
"current", resulting in "cancelBuffer: BufferQueue has been
abandoned" complaints.  We now call makeCurrent on the primary
display before removing the external display.

Bug 7274254

Change-Id: Ia59e3a61d7ec46488b96bf93ec5e4ed3488b70e4
diff --git a/services/surfaceflinger/SurfaceFlinger.cpp b/services/surfaceflinger/SurfaceFlinger.cpp
index a8d20bb..ebec4cb 100644
--- a/services/surfaceflinger/SurfaceFlinger.cpp
+++ b/services/surfaceflinger/SurfaceFlinger.cpp
@@ -1123,7 +1123,13 @@
                 if (j < 0) {
                     // in drawing state but not in current state
                     if (!draw[i].isMainDisplay()) {
+                        // Call makeCurrent() on the primary display so we can
+                        // be sure that nothing associated with this display
+                        // is current.
+                        const sp<const DisplayDevice>& hw(getDefaultDisplayDevice());
+                        DisplayDevice::makeCurrent(mEGLDisplay, hw, mEGLContext);
                         mDisplays.removeItem(draw.keyAt(i));
+                        getHwComposer().disconnectDisplay(draw[i].type);
                     } else {
                         ALOGW("trying to remove the main display");
                     }