Add --monotonic option

Setting this option configures the kernel to timestamp input events using
CLOCK_MONOTONIC instead of CLOCK_REALTIME.

Signed-off-by: Daniel Kurtz <djkurtz@chromium.org>

BUG=chromium-os:26493
TEST=mtplot => input events use wall clock timestamps
     mtplot --monotonic => input events use monotonic timestamps, iff
         supported by the kernel.
     mtplot --monotonic => if kernel dosen't support monotonic timestamps,
         a warning message is printed, and realtime timestamps are used.

Change-Id: I7a4e02989b733b8f569672cb4d0589b972777b14
diff --git a/mtplot.c b/mtplot.c
index edb6479..4f5ad06 100644
--- a/mtplot.c
+++ b/mtplot.c
@@ -19,6 +19,7 @@
 #include <stdlib.h>
 #include <string.h>
 #include <stdbool.h>
+#include <time.h>
 #include <X11/Xlib.h>
 
 #define BITS_PER_LONG (sizeof(long) * 8)
@@ -44,6 +45,11 @@
 #define ABS_MT_SLOT 47
 #endif
 
+/* Set clockid to be used for timestamps */
+#ifndef EVIOCSCLOCKID
+#define EVIOCSCLOCKID  _IOW('E', 0xa0, int)
+#endif
+
 #define NAME_ELEMENT(element) [element] = #element
 
 static const char * const events[EV_MAX + 1] = {
@@ -689,7 +695,8 @@
 // Print usage information.
 static int Usage(void) {
   printf("USAGE:\n");
-  printf("   %s /dev/input/eventX\n", program_invocation_short_name);
+  printf("   %s /dev/input/eventX [--display DISPLAY] [--monotonic]\n",
+         program_invocation_short_name);
 
   return EXIT_FAILURE;
 }
@@ -812,8 +819,17 @@
   return rc;
 }
 
+static void EnableMonotonicTimestamps(int fd)
+{
+  unsigned int clk = CLOCK_MONOTONIC;
+  int ret = ioctl(fd, EVIOCSCLOCKID, &clk);
+  if (ret < 0)
+    fprintf(stderr, "Monotonic timestamps not supported in this kernel.\n");
+}
+
 static const struct option long_options[] = {
   { "display", required_argument, NULL, 'd' },
+  { "monotonic", optional_argument, NULL, 'm' },
   { 0, },
 };
 
@@ -826,6 +842,7 @@
   struct mt_state mt_state;
   int fd, x11_fd, max_fd;
   fd_set rdfs;
+  bool monotonic_timestamps = false;
 
   while (1) {
     int option_index = 0;
@@ -836,6 +853,9 @@
       case 'd':
         displayname = optarg;
         break;
+      case 'm':
+        monotonic_timestamps = true;
+        break;
       default:
         return Usage();
     }
@@ -881,6 +901,9 @@
   if (IsSemiMtDevice(fd))
     semi_mt_device = true;
 
+  if (monotonic_timestamps)
+    EnableMonotonicTimestamps(fd);
+
   printf("Testing ... (interrupt to exit)\n");
 
   if (TestGrab(fd)) {