Merge changes I92cac83b,Ie897c40b

* changes:
  logd: wakeup wrap timeout if realtime changes drastically
  logd: cap how far back in-place sort will go to 5 seconds
diff --git a/logd/FlushCommand.cpp b/logd/FlushCommand.cpp
index ff6bff8..c67d2bf 100644
--- a/logd/FlushCommand.cpp
+++ b/logd/FlushCommand.cpp
@@ -57,8 +57,18 @@
         entry = (*it);
         if (entry->mClient == client) {
             if (entry->mTimeout.tv_sec || entry->mTimeout.tv_nsec) {
-                LogTimeEntry::unlock();
-                return;
+                if (mReader.logbuf().isMonotonic()) {
+                    LogTimeEntry::unlock();
+                    return;
+                }
+                // If the user changes the time in a gross manner that
+                // invalidates the timeout, fall through and trigger.
+                log_time now(CLOCK_REALTIME);
+                if (((entry->mEnd + entry->mTimeout) > now) &&
+                    (now > entry->mEnd)) {
+                    LogTimeEntry::unlock();
+                    return;
+                }
             }
             entry->triggerReader_Locked();
             if (entry->runningReader_Locked()) {
diff --git a/logd/LogBuffer.cpp b/logd/LogBuffer.cpp
index 1b79e89..352fc18 100644
--- a/logd/LogBuffer.cpp
+++ b/logd/LogBuffer.cpp
@@ -370,13 +370,19 @@
 
 // assumes mLogElementsLock held, owns elem, will look after garbage collection
 void LogBuffer::log(LogBufferElement* elem) {
+    // cap on how far back we will sort in-place, otherwise append
+    static uint32_t too_far_back = 5;  // five seconds
     // Insert elements in time sorted order if possible
     //  NB: if end is region locked, place element at end of list
     LogBufferElementCollection::iterator it = mLogElements.end();
     LogBufferElementCollection::iterator last = it;
     if (__predict_true(it != mLogElements.begin())) --it;
     if (__predict_false(it == mLogElements.begin()) ||
-        __predict_true((*it)->getRealTime() <= elem->getRealTime())) {
+        __predict_true((*it)->getRealTime() <= elem->getRealTime()) ||
+        __predict_false((((*it)->getRealTime().tv_sec - too_far_back) >
+                         elem->getRealTime().tv_sec) &&
+                        (elem->getLogId() != LOG_ID_KERNEL) &&
+                        ((*it)->getLogId() != LOG_ID_KERNEL))) {
         mLogElements.push_back(elem);
     } else {
         log_time end = log_time::EPOCH;