From: Yaroslav Halchenko <debian@onerussian.com>
Subject:  Retry up to 5 times setting the mode for loop device

  Needed for newer kernels.
  See https://github.com/hpcng/singularity/pull/4449/files
  for original patch in the later Go version

Origin: NeuroDebian
Applied-Upstream:  yes in go, not in older C 2.6.x
Last-Update: 2020-09-25

--- a/src/lib/image/bind.c
+++ b/src/lib/image/bind.c
@@ -131,10 +131,19 @@ char *singularity_image_bind(struct imag
 
     singularity_priv_escalate();
     singularity_message(DEBUG, "Setting loop device flags\n");
-    if ( ioctl(loop_fd, LOOP_SET_STATUS64, &lo64) < 0 ) {
-        singularity_message(ERROR, "Failed to set loop flags on loop device: %s\n", strerror(errno));
-        (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
-        ABORT(255);
+    /* C version of https://github.com/hpcng/singularity/pull/4449/files */
+    for( i=0; i < 5; i++ ) {
+        if ( ioctl(loop_fd, LOOP_SET_STATUS64, &lo64) < 0 ) {
+            if ( (errno == EAGAIN) && (i < 4) ) {
+                singularity_message(DEBUG, "Failed to set loop flags on loop device: %s. Sleeping and retrying\n", strerror(errno));
+                usleep(250000);
+                continue;
+            }
+            singularity_message(ERROR, "Failed to set loop flags on loop device: %s\n", strerror(errno));
+            (void)ioctl(loop_fd, LOOP_CLR_FD, 0);
+            ABORT(255);
+        }
+        break;
     }
     singularity_priv_drop();
 
