Add RT scheduler tracking

This interacts with event loops nicely, both in simulation and in the
real system.  This gives us tools to enforce that certain pieces of code
are run in a RT world, and others are not.

Future work will be to enforce that Malloc is not called while realtime.

Change-Id: I3ce3dc287e25390095bac34aed4888434a82f06e
diff --git a/aos/realtime.h b/aos/realtime.h
index 6e0a472..52db4a8 100644
--- a/aos/realtime.h
+++ b/aos/realtime.h
@@ -4,6 +4,8 @@
 #include <sched.h>
 #include <string_view>
 
+#include "glog/logging.h"
+
 namespace aos {
 
 // Locks everything into memory and sets the limits.  This plus InitNRT are
@@ -34,6 +36,55 @@
 
 void ExpandStackSize();
 
+// CHECKs that we are (or are not) running on the RT scheduler.  Useful for
+// enforcing that operations which are or are not bounded shouldn't be run. This
+// works both in simulation and when running against the real target.
+void CheckRealtime();
+void CheckNotRealtime();
+
+// Marks that we are or are not running on the realtime scheduler.  Returns the
+// previous state.
+//
+// Note: this shouldn't be used directly.  The event loop primitives should be
+// used instead.
+bool MarkRealtime(bool realtime);
+
+// Class which restores the current RT state when destructed.
+class ScopedRealtimeRestorer {
+ public:
+  ScopedRealtimeRestorer();
+  ~ScopedRealtimeRestorer() { MarkRealtime(prior_); }
+
+ private:
+  const bool prior_;
+};
+
+// Class which marks us as on the RT scheduler until it goes out of scope.
+// Note: this shouldn't be needed for most applications.
+class ScopedRealtime {
+ public:
+  ScopedRealtime() : prior_(MarkRealtime(true)) {}
+  ~ScopedRealtime() {
+    CHECK(MarkRealtime(prior_)) << ": Priority was modified";
+  }
+
+ private:
+  const bool prior_;
+};
+
+// Class which marks us as not on the RT scheduler until it goes out of scope.
+// Note: this shouldn't be needed for most applications.
+class ScopedNotRealtime {
+ public:
+  ScopedNotRealtime() : prior_(MarkRealtime(false)) {}
+  ~ScopedNotRealtime() {
+    CHECK(!MarkRealtime(prior_)) << ": Priority was modified";
+  }
+
+ private:
+  const bool prior_;
+};
+
 }  // namespace aos
 
 #endif  // AOS_REALTIME_H_