Send TERMINATE to framework after a full deinit

Bug: 5102386
Change-Id: I41fc00ae469cf2752fe831db56db22c9ace73f52
diff --git a/wpa_supplicant/wpa_supplicant.c b/wpa_supplicant/wpa_supplicant.c
index 74a2286..b97912b 100644
--- a/wpa_supplicant/wpa_supplicant.c
+++ b/wpa_supplicant/wpa_supplicant.c
@@ -382,6 +382,8 @@
 		wpa_s->l2_br = NULL;
 	}
 
+/* This has been moved to wpa_supplicant_deinit_iface to avoid a race with hostapd */
+#ifndef ANDROID
 	if (wpa_s->ctrl_iface) {
 		wpa_supplicant_ctrl_iface_deinit(wpa_s->ctrl_iface);
 		wpa_s->ctrl_iface = NULL;
@@ -393,6 +395,7 @@
 		wpa_config_free(wpa_s->conf);
 		wpa_s->conf = NULL;
 	}
+#endif
 
 	os_free(wpa_s->confname);
 	wpa_s->confname = NULL;
@@ -2313,6 +2316,29 @@
 
 	if (wpa_s->drv_priv)
 		wpa_drv_deinit(wpa_s);
+
+/**
+ * The wpa_drv_deinit call after sending TERMINATING to the framework causes
+ * race condition with the start of hostapd.
+ * This has been moved out of wpa_supplicant_cleanup(). Send the control
+ * message and free config after the deinit.
+ */
+#ifdef ANDROID
+	wpa_msg(wpa_s, MSG_INFO, WPA_EVENT_TERMINATING);
+
+	if (wpa_s->ctrl_iface) {
+		wpa_supplicant_ctrl_iface_deinit(wpa_s->ctrl_iface);
+		wpa_s->ctrl_iface = NULL;
+	}
+
+	if (wpa_s->conf != NULL) {
+		struct wpa_ssid *ssid;
+		for (ssid = wpa_s->conf->ssid; ssid; ssid = ssid->next)
+			wpas_notify_network_removed(wpa_s, ssid);
+		wpa_config_free(wpa_s->conf);
+		wpa_s->conf = NULL;
+	}
+#endif
 }
 
 
@@ -2632,9 +2658,6 @@
 
 	if (global == NULL)
 		return;
-#ifdef ANDROID
-	wpa_supplicant_terminate(0, global);
-#endif
 #ifdef CONFIG_P2P
 	wpas_p2p_deinit_global(global);
 #endif /* CONFIG_P2P */