d0d307a
--- cyrus-imapd-2.1.3/lib/lock_flock.c	Tue Oct  2 16:08:13 2001
d0d307a
+++ cyrus-imapd-2.1.3-patched/lib/lock_flock.c	Tue Apr 16 09:44:58 2002
d0d307a
@@ -51,6 +51,10 @@
d0d307a
 #endif
d0d307a
 
d0d307a
 #include "lock.h"
d0d307a
+#include <syslog.h>
d0d307a
+
d0d307a
+/* Locking timeout parameter */
d0d307a
+#define MAXTIME 99
d0d307a
 
d0d307a
 const char *lock_method_desc = "flock";
d0d307a
 
d0d307a
@@ -69,6 +73,18 @@
d0d307a
  * 'failaction' is provided, it is filled in with a pointer to a fixed
d0d307a
  * string naming the action that failed.
d0d307a
  *
d0d307a
+ *  Modified by jwade 4/16/2002 to work around seen file locking problem
d0d307a
+ *  Added locking timeout parameter to allow processes that are  
d0d307a
+ *  waiting for a lock to eventually time out
d0d307a
+ *
d0d307a
+ *  Calls flock() in non-blocking fashion and then retries until a 
d0d307a
+ *  maximum delay is reached or the lock succeeds.
d0d307a
+ *  
d0d307a
+ *  As written, uses a quadratic backoff on retries with MAXTIME being
d0d307a
+ *  the longest interval delay.   Total delay time is the sum of the squares
d0d307a
+ *  of all integers whose square is less than MAXTIME.  In the case of 
d0d307a
+ *  MAXTIME = 99 this is 0+1+4+9+16+25+36+49+64+81= 285 Seconds   
d0d307a
+ *  This time is arbitrary and can be adjusted
d0d307a
  */
d0d307a
 int lock_reopen(fd, filename, sbuf, failaction)
d0d307a
 int fd;
d0d307a
@@ -79,17 +95,29 @@
d0d307a
     int r;
d0d307a
     struct stat sbuffile, sbufspare;
d0d307a
     int newfd;
d0d307a
+    int delay=0, i=0;
d0d307a
 
d0d307a
     if (!sbuf) sbuf = &sbufspare;
d0d307a
 
d0d307a
-    for (;;) {
d0d307a
-	r = flock(fd, LOCK_EX);
d0d307a
+    for(i=0,delay=0;;) {
d0d307a
+	r = flock(fd, LOCK_EX|LOCK_NB);
d0d307a
 	if (r == -1) {
d0d307a
-	    if (errno == EINTR) continue;
d0d307a
-	    if (failaction) *failaction = "locking";
d0d307a
+	    if (errno == EINTR) {
d0d307a
+                 continue;
d0d307a
+            }
d0d307a
+            else if ((errno == EWOULDBLOCK) && (delay < MAXTIME)) {
d0d307a
+                syslog(LOG_DEBUG, "lock: reopen-blocked sleeping for %d on interval %d (%d, %s)" , delay, i, fd, filename);
d0d307a
+                sleep(delay);
d0d307a
+                i++;
d0d307a
+                delay = i*i;
d0d307a
+                continue;
d0d307a
+            }
d0d307a
+	    if (failaction) {
d0d307a
+                if (delay >= MAXTIME) *failaction = "locking_timeout";
d0d307a
+                else *failaction = "locking";
d0d307a
+            }
d0d307a
 	    return -1;
d0d307a
 	}
d0d307a
-
d0d307a
 	fstat(fd, sbuf);
d0d307a
 	r = stat(filename, &sbuffile);
d0d307a
 	if (r == -1) {
d0d307a
@@ -97,9 +125,7 @@
d0d307a
 	    flock(fd, LOCK_UN);
d0d307a
 	    return -1;
d0d307a
 	}
d0d307a
-
d0d307a
 	if (sbuf->st_ino == sbuffile.st_ino) return 0;
d0d307a
-
d0d307a
 	newfd = open(filename, O_RDWR);
d0d307a
 	if (newfd == -1) {
d0d307a
 	    if (failaction) *failaction = "opening";