HAL sndmonitor: Improve cleanup on error and deinit

Some resources were still leaked during sndmonitor deinit. That made
tests failed when the hal process had reach its 256 max fd open during
tests.
All file descriptor open during init should now be close during deinit.

Some memory is still leaked but as deinit of the hal is only used for
testing, it is not very important.

Test: vts-tradefed run vts --module VtsHalAudioV2_0Target
Test: call/play music/record/video...
Bug: 36311550
Change-Id: Id681a3d2dfac1692db168691ea33ef2b7d14ab2c
Signed-off-by: Kevin Rocard <krocard@google.com>
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 1f762e9..4c306d0 100644
--- a/hal/audio_hw.c
+++ b/hal/audio_hw.c
@@ -4054,10 +4054,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) {