Merge tag android-5.1.0_r1 into AOSP_5.1_MERGE

Change-Id: I3c99bf4440205917238a64d91d5ae07e558b9eac
diff --git a/ext4_utils/make_ext4fs.c b/ext4_utils/make_ext4fs.c
index 2f89ae8..62a3f1a 100644
--- a/ext4_utils/make_ext4fs.c
+++ b/ext4_utils/make_ext4fs.c
@@ -143,8 +143,18 @@
 	if (full_path) {
 		entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
 		if (entries < 0) {
-			error_errno("scandir");
-			return EXT4_ALLOCATE_FAILED;
+#ifdef __GLIBC__
+			/* The scandir function implemented in glibc has a bug that makes it
+			   erroneously fail with ENOMEM under certain circumstances.
+			   As a workaround we can retry the scandir call with the same arguments.
+			   GLIBC BZ: https://sourceware.org/bugzilla/show_bug.cgi?id=17804 */
+			if (errno == ENOMEM)
+				entries = scandir(full_path, &namelist, filter_dot, (void*)alphasort);
+#endif
+			if (entries < 0) {
+				error_errno("scandir");
+				return EXT4_ALLOCATE_FAILED;
+			}
 		}
 	}
 
diff --git a/ext4_utils/mkuserimg.sh b/ext4_utils/mkuserimg.sh
index 436e8f1..78936e0 100755
--- a/ext4_utils/mkuserimg.sh
+++ b/ext4_utils/mkuserimg.sh
@@ -91,7 +91,32 @@
 
 MAKE_EXT4FS_CMD="make_ext4fs $ENABLE_SPARSE_IMAGE -T $TIMESTAMP $OPT -l $SIZE $JOURNAL_FLAGS -a $MOUNT_POINT $OUTPUT_FILE $SRC_DIR"
 echo $MAKE_EXT4FS_CMD
+vmstat 1 &
+statpid=$!
 $MAKE_EXT4FS_CMD
 if [ $? -ne 0 ]; then
-  exit 4
+  echo "Ext image generation failed 1st time"
+  ps aux
+  lsof
+  ls -Rl $SRC_DIR
+  echo "Image generation retry. 2nd time"
+  sleep 1m
+  echo $MAKE_EXT4FS_CMD
+  $MAKE_EXT4FS_CMD
+
+  if [ $? -ne 0 ]; then
+    echo "Ext image generation failed 2nd time"
+    ps aux
+    echo "Image generation retry. 3rd time"
+    sleep 3m
+    echo $MAKE_EXT4FS_CMD
+    $MAKE_EXT4FS_CMD
+
+    if [ $? -ne 0 ]; then
+      kill $statpid
+      exit 4
+    fi
+  fi
 fi
+kill $statpid
+