Make Barrier robust against spurious wakeups

Fix Barrier implementation so that Wait cannot return prematurely
due to a spurious condition variable wakeup or interrupted futex call.

Document the resulting semantics of barrier.h, which are a bit surprising,
but appear to be exactly what current clients need.

Fix the test so that it actually passes with the fixed barrier.h,
and no longer tests for properties that can't be correctly satisfied.

Improve comment for InitTimeSpec, which we almost used.

Bug:18509123

Change-Id: I0b25f33bcd22322ba04e3951cd484843788c2bf5
diff --git a/runtime/barrier.cc b/runtime/barrier.cc
index 5a8fbb3..66ee870 100644
--- a/runtime/barrier.cc
+++ b/runtime/barrier.cc
@@ -52,7 +52,7 @@
   // Pass function is called by the last thread, the count will
   // be decremented to zero and a Broadcast will be made on the
   // condition variable, thus waking this up.
-  if (count_ != 0) {
+  while (count_ != 0) {
     condition_.Wait(self);
   }
 }
@@ -62,7 +62,18 @@
   SetCountLocked(self, count_ + delta);
   bool timed_out = false;
   if (count_ != 0) {
-    timed_out = condition_.TimedWait(self, timeout_ms, 0);
+    uint32_t timeout_ns = 0;
+    uint64_t abs_timeout = NanoTime() + MsToNs(timeout_ms);
+    for (;;) {
+      timed_out = condition_.TimedWait(self, timeout_ms, timeout_ns);
+      if (timed_out || count_ == 0) return timed_out;
+      // Compute time remaining on timeout.
+      uint64_t now = NanoTime();
+      int64_t time_left = abs_timeout - now;
+      if (time_left <= 0) return true;
+      timeout_ns = time_left % (1000*1000);
+      timeout_ms = time_left / (1000*1000);
+    }
   }
   return timed_out;
 }