HAL sndmonitor: Improve cleanup on error and deinit am: a54534423a
am: 225076ff4d

Change-Id: Ida4b206598eae9eec3b498f4b0e53c6bd79cfd6d
diff --git a/hal/audio_extn/sndmonitor.c b/hal/audio_extn/sndmonitor.c
index 86a5b93..58ab43d 100644
--- a/hal/audio_extn/sndmonitor.c
+++ b/hal/audio_extn/sndmonitor.c
@@ -582,8 +582,12 @@
 
     write(sndmonitor.intpipe[1], "Q", 1);
     pthread_join(sndmonitor.monitor_thread, (void **) NULL);
-    free_sndcards();
     free_dev_events();
+    listeners_deinit();
+    free_sndcards();
+    close(sndmonitor.intpipe[0]);
+    close(sndmonitor.intpipe[1]);
+
     sndmonitor.initcheck = 0;
     return 0;
 }
@@ -597,13 +601,13 @@
     sndmonitor.initcheck = false;
 
     if (pipe(sndmonitor.intpipe) < 0)
-        return -ENODEV;
+        goto pipe_error;
 
     if (enum_sndcards() < 0)
-        return -ENODEV;
+        goto enum_sncards_error;
 
     if (listeners_init() < 0)
-        return -ENODEV;
+        goto listeners_error;
 
 #ifdef MONITOR_DEVICE_EVENTS
     enum_dev_events(); // failure here isn't fatal
@@ -614,14 +618,20 @@
                              monitor_thread_loop, NULL);
 
     if (ret) {
-        free_sndcards();
-        free_dev_events();
-        close(sndmonitor.intpipe[0]);
-        close(sndmonitor.intpipe[1]);
-        return -ENODEV;
+        goto monitor_thread_create_error;
     }
     sndmonitor.initcheck = true;
     return 0;
+
+monitor_thread_create_error:
+    listeners_deinit();
+listeners_error:
+    free_sndcards();
+enum_sncards_error:
+    close(sndmonitor.intpipe[0]);
+    close(sndmonitor.intpipe[1]);
+pipe_error:
+    return -ENODEV;
 }
 
 int audio_extn_snd_mon_register_listener(void *stream, snd_mon_cb cb)
diff --git a/hal/audio_hw.c b/hal/audio_hw.c
index 1d4cfd9..2b1d537 100644
--- a/hal/audio_hw.c
+++ b/hal/audio_hw.c
@@ -4069,10 +4069,11 @@
     if (!adev)
         return 0;
 
+    audio_extn_snd_mon_unregister_listener(adev);
     audio_extn_snd_mon_deinit();
+
     audio_extn_tfa_98xx_deinit();
 
-    audio_extn_snd_mon_unregister_listener(adev);
     pthread_mutex_lock(&adev_init_lock);
 
     if ((--audio_device_ref_count) == 0) {