Merge "Properly recover vr_wm from surface vr_flinger crashes."
diff --git a/services/vr/vr_window_manager/application.cpp b/services/vr/vr_window_manager/application.cpp
index c7d7d50..b2f02e5 100644
--- a/services/vr/vr_window_manager/application.cpp
+++ b/services/vr/vr_window_manager/application.cpp
@@ -174,7 +174,12 @@
   // TODO(steventhomas): If we're not visible, block until we are. For now we
   // throttle by calling dvrGraphicsWaitNextFrame.
   DvrFrameSchedule schedule;
-  dvrGraphicsWaitNextFrame(graphics_context_, 0, &schedule);
+  int status = dvrGraphicsWaitNextFrame(graphics_context_, 0, &schedule);
+  if (status < 0) {
+    ALOGE("Context lost, deallocating graphics resources");
+    SetVisibility(false);
+    DeallocateResources();
+  }
 
   OnDrawFrame();
 
diff --git a/services/vr/vr_window_manager/shell_view.cpp b/services/vr/vr_window_manager/shell_view.cpp
index 67ef5d4..c270be2 100644
--- a/services/vr/vr_window_manager/shell_view.cpp
+++ b/services/vr/vr_window_manager/shell_view.cpp
@@ -126,10 +126,6 @@
   if (!surface_flinger_view_->Initialize(this))
     return 1;
 
-  // This is a temporary fix for now. These APIs will be changed when everything
-  // is moved into vrcore.
-  display_client_ = DisplayClient::Create();
-
   return 0;
 }
 
@@ -164,7 +160,14 @@
 }
 
 void ShellView::DeallocateResources() {
-  surface_flinger_view_.reset();
+  {
+    std::unique_lock<std::mutex> l(display_frame_mutex_);
+    removed_displays_.clear();
+    new_displays_.clear();
+    displays_.clear();
+  }
+
+  display_client_.reset();
   reticle_.reset();
   controller_mesh_.reset();
   program_.reset(new ShaderProgram);
@@ -283,6 +286,20 @@
 
   bool showing = false;
 
+  // This is a temporary fix for now. These APIs will be changed when everything
+  // is moved into vrcore.
+  // Do this on demand in case vr_flinger crashed and we are reconnecting.
+  if (!display_client_.get()) {
+    int error = 0;
+    display_client_ = DisplayClient::Create(&error);
+
+    if (error) {
+      ALOGE("Could not connect to display service : %s(%d)", strerror(error),
+            error);
+      return base::unique_fd();
+    }
+  }
+
   // TODO(achaulk): change when moved into vrcore.
   bool vr_running = display_client_->IsVrAppRunning();