Home | History | Annotate | Download | only in common_time
      1 /*
      2  * Copyright (C) 2012 The Android Open Source Project
      3  *
      4  * Licensed under the Apache License, Version 2.0 (the "License");
      5  * you may not use this file except in compliance with the License.
      6  * You may obtain a copy of the License at
      7  *
      8  *      http://www.apache.org/licenses/LICENSE-2.0
      9  *
     10  * Unless required by applicable law or agreed to in writing, software
     11  * distributed under the License is distributed on an "AS IS" BASIS,
     12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
     13  * See the License for the specific language governing permissions and
     14  * limitations under the License.
     15  */
     16 
     17 /*
     18  * A service that exchanges time synchronization information between
     19  * a master that defines a timeline and clients that follow the timeline.
     20  */
     21 
     22 #define LOG_TAG "common_time"
     23 #include <utils/Log.h>
     24 
     25 #include <arpa/inet.h>
     26 #include <assert.h>
     27 #include <fcntl.h>
     28 #include <linux/if_ether.h>
     29 #include <net/if.h>
     30 #include <net/if_arp.h>
     31 #include <netinet/ip.h>
     32 #include <poll.h>
     33 #include <stdio.h>
     34 #include <sys/eventfd.h>
     35 #include <sys/ioctl.h>
     36 #include <sys/stat.h>
     37 #include <sys/types.h>
     38 #include <sys/socket.h>
     39 
     40 #include <common_time/local_clock.h>
     41 #include <binder/IPCThreadState.h>
     42 #include <binder/ProcessState.h>
     43 #include <utils/Timers.h>
     44 
     45 #include "common_clock_service.h"
     46 #include "common_time_config_service.h"
     47 #include "common_time_server.h"
     48 #include "common_time_server_packets.h"
     49 #include "clock_recovery.h"
     50 #include "common_clock.h"
     51 
     52 #define MAX_INT ((int)0x7FFFFFFF)
     53 
     54 namespace android {
     55 
     56 const char*    CommonTimeServer::kDefaultMasterElectionAddr = "239.195.128.88";
     57 const uint16_t CommonTimeServer::kDefaultMasterElectionPort = 8887;
     58 const uint64_t CommonTimeServer::kDefaultSyncGroupID = 0;
     59 const uint8_t  CommonTimeServer::kDefaultMasterPriority = 1;
     60 const uint32_t CommonTimeServer::kDefaultMasterAnnounceIntervalMs = 10000;
     61 const uint32_t CommonTimeServer::kDefaultSyncRequestIntervalMs = 1000;
     62 const uint32_t CommonTimeServer::kDefaultPanicThresholdUsec = 50000;
     63 const bool     CommonTimeServer::kDefaultAutoDisable = true;
     64 const int      CommonTimeServer::kSetupRetryTimeoutMs = 30000;
     65 const int64_t  CommonTimeServer::kNoGoodDataPanicThresholdUsec = 600000000ll;
     66 const uint32_t CommonTimeServer::kRTTDiscardPanicThreshMultiplier = 5;
     67 
     68 // timeout value representing an infinite timeout
     69 const int CommonTimeServer::kInfiniteTimeout = -1;
     70 
     71 /*** Initial state constants ***/
     72 
     73 // number of WhoIsMaster attempts sent before giving up
     74 const int CommonTimeServer::kInitial_NumWhoIsMasterRetries = 6;
     75 
     76 // timeout used when waiting for a response to a WhoIsMaster request
     77 const int CommonTimeServer::kInitial_WhoIsMasterTimeoutMs = 500;
     78 
     79 /*** Client state constants ***/
     80 
     81 // number of sync requests that can fail before a client assumes its master
     82 // is dead
     83 const int CommonTimeServer::kClient_NumSyncRequestRetries = 10;
     84 
     85 /*** Master state constants ***/
     86 
     87 /*** Ronin state constants ***/
     88 
     89 // number of WhoIsMaster attempts sent before declaring ourselves master
     90 const int CommonTimeServer::kRonin_NumWhoIsMasterRetries = 20;
     91 
     92 // timeout used when waiting for a response to a WhoIsMaster request
     93 const int CommonTimeServer::kRonin_WhoIsMasterTimeoutMs = 500;
     94 
     95 /*** WaitForElection state constants ***/
     96 
     97 // how long do we wait for an announcement from a master before
     98 // trying another election?
     99 const int CommonTimeServer::kWaitForElection_TimeoutMs = 12500;
    100 
    101 CommonTimeServer::CommonTimeServer()
    102     : Thread(false)
    103     , mState(ICommonClock::STATE_INITIAL)
    104     , mClockRecovery(&mLocalClock, &mCommonClock)
    105     , mSocket(-1)
    106     , mLastPacketRxLocalTime(0)
    107     , mTimelineID(ICommonClock::kInvalidTimelineID)
    108     , mClockSynced(false)
    109     , mCommonClockHasClients(false)
    110     , mInitial_WhoIsMasterRequestTimeouts(0)
    111     , mClient_MasterDeviceID(0)
    112     , mClient_MasterDevicePriority(0)
    113     , mRonin_WhoIsMasterRequestTimeouts(0) {
    114     // zero out sync stats
    115     resetSyncStats();
    116 
    117     // Setup the master election endpoint to use the default.
    118     struct sockaddr_in* meep =
    119         reinterpret_cast<struct sockaddr_in*>(&mMasterElectionEP);
    120     memset(&mMasterElectionEP, 0, sizeof(mMasterElectionEP));
    121     inet_aton(kDefaultMasterElectionAddr, &meep->sin_addr);
    122     meep->sin_family = AF_INET;
    123     meep->sin_port   = htons(kDefaultMasterElectionPort);
    124 
    125     // Zero out the master endpoint.
    126     memset(&mMasterEP, 0, sizeof(mMasterEP));
    127     mMasterEPValid    = false;
    128     mBindIfaceValid   = false;
    129     setForceLowPriority(false);
    130 
    131     // Set all remaining configuration parameters to their defaults.
    132     mDeviceID                 = 0;
    133     mSyncGroupID              = kDefaultSyncGroupID;
    134     mMasterPriority           = kDefaultMasterPriority;
    135     mMasterAnnounceIntervalMs = kDefaultMasterAnnounceIntervalMs;
    136     mSyncRequestIntervalMs    = kDefaultSyncRequestIntervalMs;
    137     mPanicThresholdUsec       = kDefaultPanicThresholdUsec;
    138     mAutoDisable              = kDefaultAutoDisable;
    139 
    140     // Create the eventfd we will use to signal our thread to wake up when
    141     // needed.
    142     mWakeupThreadFD = eventfd(0, EFD_NONBLOCK);
    143 
    144     // seed the random number generator (used to generated timeline IDs)
    145     srand48(static_cast<unsigned int>(systemTime()));
    146 }
    147 
    148 CommonTimeServer::~CommonTimeServer() {
    149     shutdownThread();
    150 
    151     // No need to grab the lock here.  We are in the destructor; if the the user
    152     // has a thread in any of the APIs while the destructor is being called,
    153     // there is a threading problem a the application level we cannot reasonably
    154     // do anything about.
    155     cleanupSocket_l();
    156 
    157     if (mWakeupThreadFD >= 0) {
    158         close(mWakeupThreadFD);
    159         mWakeupThreadFD = -1;
    160     }
    161 }
    162 
    163 bool CommonTimeServer::startServices() {
    164     // start the ICommonClock service
    165     mICommonClock = CommonClockService::instantiate(*this);
    166     if (mICommonClock == NULL)
    167         return false;
    168 
    169     // start the ICommonTimeConfig service
    170     mICommonTimeConfig = CommonTimeConfigService::instantiate(*this);
    171     if (mICommonTimeConfig == NULL)
    172         return false;
    173 
    174     return true;
    175 }
    176 
    177 bool CommonTimeServer::threadLoop() {
    178     // Register our service interfaces.
    179     if (!startServices())
    180         return false;
    181 
    182     // Hold the lock while we are in the main thread loop.  It will release the
    183     // lock when it blocks, and hold the lock at all other times.
    184     mLock.lock();
    185     runStateMachine_l();
    186     mLock.unlock();
    187 
    188     IPCThreadState::self()->stopProcess();
    189     return false;
    190 }
    191 
    192 bool CommonTimeServer::runStateMachine_l() {
    193     if (!mLocalClock.initCheck())
    194         return false;
    195 
    196     if (!mCommonClock.init(mLocalClock.getLocalFreq()))
    197         return false;
    198 
    199     // Enter the initial state.
    200     becomeInitial("startup");
    201 
    202     // run the state machine
    203     while (!exitPending()) {
    204         struct pollfd pfds[2];
    205         int rc;
    206         int eventCnt = 0;
    207         int64_t wakeupTime;
    208 
    209         // We are always interested in our wakeup FD.
    210         pfds[eventCnt].fd      = mWakeupThreadFD;
    211         pfds[eventCnt].events  = POLLIN;
    212         pfds[eventCnt].revents = 0;
    213         eventCnt++;
    214 
    215         // If we have a valid socket, then we are interested in what it has to
    216         // say as well.
    217         if (mSocket >= 0) {
    218             pfds[eventCnt].fd      = mSocket;
    219             pfds[eventCnt].events  = POLLIN;
    220             pfds[eventCnt].revents = 0;
    221             eventCnt++;
    222         }
    223 
    224         // Note, we were holding mLock when this function was called.  We
    225         // release it only while we are blocking and hold it at all other times.
    226         mLock.unlock();
    227         rc          = poll(pfds, eventCnt, mCurTimeout.msecTillTimeout());
    228         wakeupTime  = mLocalClock.getLocalTime();
    229         mLock.lock();
    230 
    231         // Is it time to shutdown?  If so, don't hesitate... just do it.
    232         if (exitPending())
    233             break;
    234 
    235         // Did the poll fail?  This should never happen and is fatal if it does.
    236         if (rc < 0) {
    237             ALOGE("%s:%d poll failed", __PRETTY_FUNCTION__, __LINE__);
    238             return false;
    239         }
    240 
    241         if (rc == 0)
    242             mCurTimeout.setTimeout(kInfiniteTimeout);
    243 
    244         // Were we woken up on purpose?  If so, clear the eventfd with a read.
    245         if (pfds[0].revents)
    246             clearPendingWakeupEvents_l();
    247 
    248         // Is out bind address dirty?  If so, clean up our socket (if any).
    249         // Alternatively, do we have an active socket but should be auto
    250         // disabled?  If so, release the socket and enter the proper sync state.
    251         bool droppedSocket = false;
    252         if (mBindIfaceDirty || ((mSocket >= 0) && shouldAutoDisable())) {
    253             cleanupSocket_l();
    254             mBindIfaceDirty = false;
    255             droppedSocket = true;
    256         }
    257 
    258         // Do we not have a socket but should have one?  If so, try to set one
    259         // up.
    260         if ((mSocket < 0) && mBindIfaceValid && !shouldAutoDisable()) {
    261             if (setupSocket_l()) {
    262                 // Success!  We are now joining a new network (either coming
    263                 // from no network, or coming from a potentially different
    264                 // network).  Force our priority to be lower so that we defer to
    265                 // any other masters which may already be on the network we are
    266                 // joining.  Later, when we enter either the client or the
    267                 // master state, we will clear this flag and go back to our
    268                 // normal election priority.
    269                 setForceLowPriority(true);
    270                 switch (mState) {
    271                     // If we were in initial (whether we had a immediately
    272                     // before this network or not) we want to simply reset the
    273                     // system and start again.  Forcing a transition from
    274                     // INITIAL to INITIAL should do the job.
    275                     case CommonClockService::STATE_INITIAL:
    276                         becomeInitial("bound interface");
    277                         break;
    278 
    279                     // If we were in the master state, then either we were the
    280                     // master in a no-network situation, or we were the master
    281                     // of a different network and have moved to a new interface.
    282                     // In either case, immediately transition to Ronin at low
    283                     // priority.  If there is no one in the network we just
    284                     // joined, we will become master soon enough.  If there is,
    285                     // we want to be certain to defer master status to the
    286                     // existing timeline currently running on the network.
    287                     //
    288                     case CommonClockService::STATE_MASTER:
    289                         becomeRonin("leaving networkless mode");
    290                         break;
    291 
    292                     // If we were in any other state (CLIENT, RONIN, or
    293                     // WAIT_FOR_ELECTION) then we must be moving from one
    294                     // network to another.  We have lost our old master;
    295                     // transition to RONIN in an attempt to find a new master.
    296                     // If there are none out there, we will just assume
    297                     // responsibility for the timeline we used to be a client
    298                     // of.
    299                     default:
    300                         becomeRonin("bound interface");
    301                         break;
    302                 }
    303             } else {
    304                 // That's odd... we failed to set up our socket.  This could be
    305                 // due to some transient network change which will work itself
    306                 // out shortly; schedule a retry attempt in the near future.
    307                 mCurTimeout.setTimeout(kSetupRetryTimeoutMs);
    308             }
    309 
    310             // One way or the other, we don't have any data to process at this
    311             // point (since we just tried to bulid a new socket).  Loop back
    312             // around and wait for the next thing to do.
    313             continue;
    314         } else if (droppedSocket) {
    315             // We just lost our socket, and for whatever reason (either no
    316             // config, or auto disable engaged) we are not supposed to rebuild
    317             // one at this time.  We are not going to rebuild our socket until
    318             // something about our config/auto-disabled status changes, so we
    319             // are basically in network-less mode.  If we are already in either
    320             // INITIAL or MASTER, just stay there until something changes.  If
    321             // we are in any other state (CLIENT, RONIN or WAIT_FOR_ELECTION),
    322             // then transition to either INITIAL or MASTER depending on whether
    323             // or not our timeline is valid.
    324             ALOGI("Entering networkless mode interface is %s, "
    325                  "shouldAutoDisable = %s",
    326                  mBindIfaceValid ? "valid" : "invalid",
    327                  shouldAutoDisable() ? "true" : "false");
    328             if ((mState != ICommonClock::STATE_INITIAL) &&
    329                 (mState != ICommonClock::STATE_MASTER)) {
    330                 if (mTimelineID == ICommonClock::kInvalidTimelineID)
    331                     becomeInitial("network-less mode");
    332                 else
    333                     becomeMaster("network-less mode");
    334             }
    335 
    336             continue;
    337         }
    338 
    339         // Did we wakeup with no signalled events across all of our FDs?  If so,
    340         // we must have hit our timeout.
    341         if (rc == 0) {
    342             if (!handleTimeout())
    343                 ALOGE("handleTimeout failed");
    344             continue;
    345         }
    346 
    347         // Does our socket have data for us (assuming we still have one, we
    348         // may have RXed a packet at the same time as a config change telling us
    349         // to shut our socket down)?  If so, process its data.
    350         if ((mSocket >= 0) && (eventCnt > 1) && (pfds[1].revents)) {
    351             mLastPacketRxLocalTime = wakeupTime;
    352             if (!handlePacket())
    353                 ALOGE("handlePacket failed");
    354         }
    355     }
    356 
    357     cleanupSocket_l();
    358     return true;
    359 }
    360 
    361 void CommonTimeServer::clearPendingWakeupEvents_l() {
    362     int64_t tmp;
    363     read(mWakeupThreadFD, &tmp, sizeof(tmp));
    364 }
    365 
    366 void CommonTimeServer::wakeupThread_l() {
    367     int64_t tmp = 1;
    368     write(mWakeupThreadFD, &tmp, sizeof(tmp));
    369 }
    370 
    371 void CommonTimeServer::cleanupSocket_l() {
    372     if (mSocket >= 0) {
    373         close(mSocket);
    374         mSocket = -1;
    375     }
    376 }
    377 
    378 void CommonTimeServer::shutdownThread() {
    379     // Flag the work thread for shutdown.
    380     this->requestExit();
    381 
    382     // Signal the thread in case its sleeping.
    383     mLock.lock();
    384     wakeupThread_l();
    385     mLock.unlock();
    386 
    387     // Wait for the thread to exit.
    388     this->join();
    389 }
    390 
    391 bool CommonTimeServer::setupSocket_l() {
    392     int rc;
    393     bool ret_val = false;
    394     struct sockaddr_in* ipv4_addr = NULL;
    395     char masterElectionEPStr[64];
    396     const int one = 1;
    397 
    398     // This should never be needed, but if we happened to have an old socket
    399     // lying around, be sure to not leak it before proceeding.
    400     cleanupSocket_l();
    401 
    402     // If we don't have a valid endpoint to bind to, then how did we get here in
    403     // the first place?  Regardless, we know that we are going to fail to bind,
    404     // so don't even try.
    405     if (!mBindIfaceValid)
    406         return false;
    407 
    408     sockaddrToString(mMasterElectionEP, true, masterElectionEPStr,
    409                      sizeof(masterElectionEPStr));
    410     ALOGI("Building socket :: bind = %s master election = %s",
    411          mBindIface.string(), masterElectionEPStr);
    412 
    413     // TODO: add proper support for IPv6.  Right now, we block IPv6 addresses at
    414     // the configuration interface level.
    415     if (AF_INET != mMasterElectionEP.ss_family) {
    416         ALOGW("TODO: add proper IPv6 support");
    417         goto bailout;
    418     }
    419 
    420     // open a UDP socket for the timeline serivce
    421     mSocket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
    422     if (mSocket < 0) {
    423         ALOGE("Failed to create socket (errno = %d)", errno);
    424         goto bailout;
    425     }
    426 
    427     // Bind to the selected interface using Linux's spiffy SO_BINDTODEVICE.
    428     struct ifreq ifr;
    429     memset(&ifr, 0, sizeof(ifr));
    430     snprintf(ifr.ifr_name, sizeof(ifr.ifr_name), "%s", mBindIface.string());
    431     ifr.ifr_name[sizeof(ifr.ifr_name) - 1] = 0;
    432     rc = setsockopt(mSocket, SOL_SOCKET, SO_BINDTODEVICE,
    433                     (void *)&ifr, sizeof(ifr));
    434     if (rc) {
    435         ALOGE("Failed to bind socket at to interface %s (errno = %d)",
    436               ifr.ifr_name, errno);
    437         goto bailout;
    438     }
    439 
    440     // Bind our socket to INADDR_ANY and the master election port.  The
    441     // interface binding we made using SO_BINDTODEVICE should limit us to
    442     // traffic only on the interface we are interested in.  We need to bind to
    443     // INADDR_ANY and the specific master election port in order to be able to
    444     // receive both unicast traffic and master election multicast traffic with
    445     // just a single socket.
    446     struct sockaddr_in bindAddr;
    447     ipv4_addr = reinterpret_cast<struct sockaddr_in*>(&mMasterElectionEP);
    448     memcpy(&bindAddr, ipv4_addr, sizeof(bindAddr));
    449     bindAddr.sin_addr.s_addr = INADDR_ANY;
    450     rc = bind(mSocket,
    451               reinterpret_cast<const sockaddr *>(&bindAddr),
    452               sizeof(bindAddr));
    453     if (rc) {
    454         ALOGE("Failed to bind socket to port %hu (errno = %d)",
    455               ntohs(bindAddr.sin_port), errno);
    456         goto bailout;
    457     }
    458 
    459     if (0xE0000000 == (ntohl(ipv4_addr->sin_addr.s_addr) & 0xF0000000)) {
    460         // If our master election endpoint is a multicast address, be sure to join
    461         // the multicast group.
    462         struct ip_mreq mreq;
    463         mreq.imr_multiaddr = ipv4_addr->sin_addr;
    464         mreq.imr_interface.s_addr = htonl(INADDR_ANY);
    465         rc = setsockopt(mSocket, IPPROTO_IP, IP_ADD_MEMBERSHIP,
    466                         &mreq, sizeof(mreq));
    467         if (rc == -1) {
    468             ALOGE("Failed to join multicast group at %s.  (errno = %d)",
    469                  masterElectionEPStr, errno);
    470             goto bailout;
    471         }
    472 
    473         // disable loopback of multicast packets
    474         const int zero = 0;
    475         rc = setsockopt(mSocket, IPPROTO_IP, IP_MULTICAST_LOOP,
    476                         &zero, sizeof(zero));
    477         if (rc == -1) {
    478             ALOGE("Failed to disable multicast loopback (errno = %d)", errno);
    479             goto bailout;
    480         }
    481     } else
    482     if (ntohl(ipv4_addr->sin_addr.s_addr) != 0xFFFFFFFF) {
    483         // If the master election address is neither broadcast, nor multicast,
    484         // then we are misconfigured.  The config API layer should prevent this
    485         // from ever happening.
    486         goto bailout;
    487     }
    488 
    489     // Set the TTL of sent packets to 1.  (Time protocol sync should never leave
    490     // the local subnet)
    491     rc = setsockopt(mSocket, IPPROTO_IP, IP_TTL, &one, sizeof(one));
    492     if (rc == -1) {
    493         ALOGE("Failed to set TTL to %d (errno = %d)", one, errno);
    494         goto bailout;
    495     }
    496 
    497     // get the device's unique ID
    498     if (!assignDeviceID())
    499         goto bailout;
    500 
    501     ret_val = true;
    502 
    503 bailout:
    504     if (!ret_val)
    505         cleanupSocket_l();
    506     return ret_val;
    507 }
    508 
    509 // generate a unique device ID that can be used for arbitration
    510 bool CommonTimeServer::assignDeviceID() {
    511     if (!mBindIfaceValid)
    512         return false;
    513 
    514     struct ifreq ifr;
    515     memset(&ifr, 0, sizeof(ifr));
    516     ifr.ifr_addr.sa_family = AF_INET;
    517     strlcpy(ifr.ifr_name, mBindIface.string(), IFNAMSIZ);
    518 
    519     int rc = ioctl(mSocket, SIOCGIFHWADDR, &ifr);
    520     if (rc) {
    521         ALOGE("%s:%d ioctl failed", __PRETTY_FUNCTION__, __LINE__);
    522         return false;
    523     }
    524 
    525     if (ifr.ifr_addr.sa_family != ARPHRD_ETHER) {
    526         ALOGE("%s:%d got non-Ethernet address", __PRETTY_FUNCTION__, __LINE__);
    527         return false;
    528     }
    529 
    530     mDeviceID = 0;
    531     for (int i = 0; i < ETH_ALEN; i++) {
    532         mDeviceID = (mDeviceID << 8) | ifr.ifr_hwaddr.sa_data[i];
    533     }
    534 
    535     return true;
    536 }
    537 
    538 // generate a new timeline ID
    539 void CommonTimeServer::assignTimelineID() {
    540     do {
    541         mTimelineID = (static_cast<uint64_t>(lrand48()) << 32)
    542                     |  static_cast<uint64_t>(lrand48());
    543     } while (mTimelineID == ICommonClock::kInvalidTimelineID);
    544 }
    545 
    546 // Select a preference between the device IDs of two potential masters.
    547 // Returns true if the first ID wins, or false if the second ID wins.
    548 bool CommonTimeServer::arbitrateMaster(
    549         uint64_t deviceID1, uint8_t devicePrio1,
    550         uint64_t deviceID2, uint8_t devicePrio2) {
    551     return ((devicePrio1 >  devicePrio2) ||
    552            ((devicePrio1 == devicePrio2) && (deviceID1 > deviceID2)));
    553 }
    554 
    555 bool CommonTimeServer::handlePacket() {
    556     uint8_t buf[256];
    557     struct sockaddr_storage srcAddr;
    558     socklen_t srcAddrLen = sizeof(srcAddr);
    559 
    560     ssize_t recvBytes = recvfrom(
    561             mSocket, buf, sizeof(buf), 0,
    562             reinterpret_cast<const sockaddr *>(&srcAddr), &srcAddrLen);
    563 
    564     if (recvBytes < 0) {
    565         ALOGE("%s:%d recvfrom failed", __PRETTY_FUNCTION__, __LINE__);
    566         return false;
    567     }
    568 
    569     UniversalTimeServicePacket pkt;
    570     recvBytes = pkt.deserializePacket(buf, recvBytes, mSyncGroupID);
    571     if (recvBytes < 0)
    572         return false;
    573 
    574     bool result;
    575     switch (pkt.packetType) {
    576         case TIME_PACKET_WHO_IS_MASTER_REQUEST:
    577             result = handleWhoIsMasterRequest(&pkt.p.who_is_master_request,
    578                                               srcAddr);
    579             break;
    580 
    581         case TIME_PACKET_WHO_IS_MASTER_RESPONSE:
    582             result = handleWhoIsMasterResponse(&pkt.p.who_is_master_response,
    583                                                srcAddr);
    584             break;
    585 
    586         case TIME_PACKET_SYNC_REQUEST:
    587             result = handleSyncRequest(&pkt.p.sync_request, srcAddr);
    588             break;
    589 
    590         case TIME_PACKET_SYNC_RESPONSE:
    591             result = handleSyncResponse(&pkt.p.sync_response, srcAddr);
    592             break;
    593 
    594         case TIME_PACKET_MASTER_ANNOUNCEMENT:
    595             result = handleMasterAnnouncement(&pkt.p.master_announcement,
    596                                               srcAddr);
    597             break;
    598 
    599         default: {
    600             ALOGD("%s:%d unknown packet type(%d)",
    601                     __PRETTY_FUNCTION__, __LINE__, pkt.packetType);
    602             result = false;
    603         } break;
    604     }
    605 
    606     return result;
    607 }
    608 
    609 bool CommonTimeServer::handleTimeout() {
    610     // If we have no socket, then this must be a timeout to retry socket setup.
    611     if (mSocket < 0)
    612         return true;
    613 
    614     switch (mState) {
    615         case ICommonClock::STATE_INITIAL:
    616             return handleTimeoutInitial();
    617         case ICommonClock::STATE_CLIENT:
    618             return handleTimeoutClient();
    619         case ICommonClock::STATE_MASTER:
    620             return handleTimeoutMaster();
    621         case ICommonClock::STATE_RONIN:
    622             return handleTimeoutRonin();
    623         case ICommonClock::STATE_WAIT_FOR_ELECTION:
    624             return handleTimeoutWaitForElection();
    625     }
    626 
    627     return false;
    628 }
    629 
    630 bool CommonTimeServer::handleTimeoutInitial() {
    631     if (++mInitial_WhoIsMasterRequestTimeouts ==
    632             kInitial_NumWhoIsMasterRetries) {
    633         // none of our attempts to discover a master succeeded, so make
    634         // this device the master
    635         return becomeMaster("initial timeout");
    636     } else {
    637         // retry the WhoIsMaster request
    638         return sendWhoIsMasterRequest();
    639     }
    640 }
    641 
    642 bool CommonTimeServer::handleTimeoutClient() {
    643     if (shouldPanicNotGettingGoodData())
    644         return becomeInitial("timeout panic, no good data");
    645 
    646     if (mClient_SyncRequestPending) {
    647         mClient_SyncRequestPending = false;
    648 
    649         if (++mClient_SyncRequestTimeouts < kClient_NumSyncRequestRetries) {
    650             // a sync request has timed out, so retry
    651             return sendSyncRequest();
    652         } else {
    653             // The master has failed to respond to a sync request for too many
    654             // times in a row.  Assume the master is dead and start electing
    655             // a new master.
    656             return becomeRonin("master not responding");
    657         }
    658     } else {
    659         // initiate the next sync request
    660         return sendSyncRequest();
    661     }
    662 }
    663 
    664 bool CommonTimeServer::handleTimeoutMaster() {
    665     // send another announcement from the master
    666     return sendMasterAnnouncement();
    667 }
    668 
    669 bool CommonTimeServer::handleTimeoutRonin() {
    670     if (++mRonin_WhoIsMasterRequestTimeouts == kRonin_NumWhoIsMasterRetries) {
    671         // no other master is out there, so we won the election
    672         return becomeMaster("no better masters detected");
    673     } else {
    674         return sendWhoIsMasterRequest();
    675     }
    676 }
    677 
    678 bool CommonTimeServer::handleTimeoutWaitForElection() {
    679     return becomeRonin("timeout waiting for election conclusion");
    680 }
    681 
    682 bool CommonTimeServer::handleWhoIsMasterRequest(
    683         const WhoIsMasterRequestPacket* request,
    684         const sockaddr_storage& srcAddr) {
    685     if (mState == ICommonClock::STATE_MASTER) {
    686         // is this request related to this master's timeline?
    687         if (request->timelineID != ICommonClock::kInvalidTimelineID &&
    688             request->timelineID != mTimelineID)
    689             return true;
    690 
    691         WhoIsMasterResponsePacket pkt;
    692         pkt.initHeader(mTimelineID, mSyncGroupID);
    693         pkt.deviceID = mDeviceID;
    694         pkt.devicePriority = effectivePriority();
    695 
    696         uint8_t buf[256];
    697         ssize_t bufSz = pkt.serializePacket(buf, sizeof(buf));
    698         if (bufSz < 0)
    699             return false;
    700 
    701         ssize_t sendBytes = sendto(
    702                 mSocket, buf, bufSz, 0,
    703                 reinterpret_cast<const sockaddr *>(&srcAddr),
    704                 sizeof(srcAddr));
    705         if (sendBytes == -1) {
    706             ALOGE("%s:%d sendto failed", __PRETTY_FUNCTION__, __LINE__);
    707             return false;
    708         }
    709     } else if (mState == ICommonClock::STATE_RONIN) {
    710         // if we hear a WhoIsMaster request from another device following
    711         // the same timeline and that device wins arbitration, then we will stop
    712         // trying to elect ourselves master and will instead wait for an
    713         // announcement from the election winner
    714         if (request->timelineID != mTimelineID)
    715             return true;
    716 
    717         if (arbitrateMaster(request->senderDeviceID,
    718                             request->senderDevicePriority,
    719                             mDeviceID,
    720                             effectivePriority()))
    721             return becomeWaitForElection("would lose election");
    722 
    723         return true;
    724     } else if (mState == ICommonClock::STATE_INITIAL) {
    725         // If a group of devices booted simultaneously (e.g. after a power
    726         // outage) and all of them are in the initial state and there is no
    727         // master, then each device may time out and declare itself master at
    728         // the same time.  To avoid this, listen for
    729         // WhoIsMaster(InvalidTimeline) requests from peers.  If we would lose
    730         // arbitration against that peer, reset our timeout count so that the
    731         // peer has a chance to become master before we time out.
    732         if (request->timelineID == ICommonClock::kInvalidTimelineID &&
    733                 arbitrateMaster(request->senderDeviceID,
    734                                 request->senderDevicePriority,
    735                                 mDeviceID,
    736                                 effectivePriority())) {
    737             mInitial_WhoIsMasterRequestTimeouts = 0;
    738         }
    739     }
    740 
    741     return true;
    742 }
    743 
    744 bool CommonTimeServer::handleWhoIsMasterResponse(
    745         const WhoIsMasterResponsePacket* response,
    746         const sockaddr_storage& srcAddr) {
    747     if (mState == ICommonClock::STATE_INITIAL || mState == ICommonClock::STATE_RONIN) {
    748         return becomeClient(srcAddr,
    749                             response->deviceID,
    750                             response->devicePriority,
    751                             response->timelineID,
    752                             "heard whois response");
    753     } else if (mState == ICommonClock::STATE_CLIENT) {
    754         // if we get multiple responses because there are multiple devices
    755         // who believe that they are master, then follow the master that
    756         // wins arbitration
    757         if (arbitrateMaster(response->deviceID,
    758                             response->devicePriority,
    759                             mClient_MasterDeviceID,
    760                             mClient_MasterDevicePriority)) {
    761             return becomeClient(srcAddr,
    762                                 response->deviceID,
    763                                 response->devicePriority,
    764                                 response->timelineID,
    765                                 "heard whois response");
    766         }
    767     }
    768 
    769     return true;
    770 }
    771 
    772 bool CommonTimeServer::handleSyncRequest(const SyncRequestPacket* request,
    773                                          const sockaddr_storage& srcAddr) {
    774     SyncResponsePacket pkt;
    775     pkt.initHeader(mTimelineID, mSyncGroupID);
    776 
    777     if ((mState == ICommonClock::STATE_MASTER) &&
    778         (mTimelineID == request->timelineID)) {
    779         int64_t rxLocalTime = mLastPacketRxLocalTime;
    780         int64_t rxCommonTime;
    781 
    782         // If we are master on an actual network and have actual clients, then
    783         // we are no longer low priority.
    784         setForceLowPriority(false);
    785 
    786         if (OK != mCommonClock.localToCommon(rxLocalTime, &rxCommonTime)) {
    787             return false;
    788         }
    789 
    790         int64_t txLocalTime = mLocalClock.getLocalTime();;
    791         int64_t txCommonTime;
    792         if (OK != mCommonClock.localToCommon(txLocalTime, &txCommonTime)) {
    793             return false;
    794         }
    795 
    796         pkt.nak = 0;
    797         pkt.clientTxLocalTime  = request->clientTxLocalTime;
    798         pkt.masterRxCommonTime = rxCommonTime;
    799         pkt.masterTxCommonTime = txCommonTime;
    800     } else {
    801         pkt.nak = 1;
    802         pkt.clientTxLocalTime  = 0;
    803         pkt.masterRxCommonTime = 0;
    804         pkt.masterTxCommonTime = 0;
    805     }
    806 
    807     uint8_t buf[256];
    808     ssize_t bufSz = pkt.serializePacket(buf, sizeof(buf));
    809     if (bufSz < 0)
    810         return false;
    811 
    812     ssize_t sendBytes = sendto(
    813             mSocket, &buf, bufSz, 0,
    814             reinterpret_cast<const sockaddr *>(&srcAddr),
    815             sizeof(srcAddr));
    816     if (sendBytes == -1) {
    817         ALOGE("%s:%d sendto failed", __PRETTY_FUNCTION__, __LINE__);
    818         return false;
    819     }
    820 
    821     return true;
    822 }
    823 
    824 bool CommonTimeServer::handleSyncResponse(
    825         const SyncResponsePacket* response,
    826         const sockaddr_storage& srcAddr) {
    827     if (mState != ICommonClock::STATE_CLIENT)
    828         return true;
    829 
    830     assert(mMasterEPValid);
    831     if (!sockaddrMatch(srcAddr, mMasterEP, true)) {
    832         char srcEP[64], expectedEP[64];
    833         sockaddrToString(srcAddr, true, srcEP, sizeof(srcEP));
    834         sockaddrToString(mMasterEP, true, expectedEP, sizeof(expectedEP));
    835         ALOGI("Dropping sync response from unexpected address."
    836              " Expected %s Got %s", expectedEP, srcEP);
    837         return true;
    838     }
    839 
    840     if (response->nak) {
    841         // if our master is no longer accepting requests, then we need to find
    842         // a new master
    843         return becomeRonin("master NAK'ed");
    844     }
    845 
    846     mClient_SyncRequestPending = 0;
    847     mClient_SyncRequestTimeouts = 0;
    848     mClient_PacketRTTLog.logRX(response->clientTxLocalTime,
    849                                mLastPacketRxLocalTime);
    850 
    851     bool result;
    852     if (!(mClient_SyncRespsRXedFromCurMaster++)) {
    853         // the first request/response exchange between a client and a master
    854         // may take unusually long due to ARP, so discard it.
    855         result = true;
    856     } else {
    857         int64_t clientTxLocalTime  = response->clientTxLocalTime;
    858         int64_t clientRxLocalTime  = mLastPacketRxLocalTime;
    859         int64_t masterTxCommonTime = response->masterTxCommonTime;
    860         int64_t masterRxCommonTime = response->masterRxCommonTime;
    861 
    862         int64_t rtt       = (clientRxLocalTime - clientTxLocalTime);
    863         int64_t avgLocal  = (clientTxLocalTime + clientRxLocalTime) >> 1;
    864         int64_t avgCommon = (masterTxCommonTime + masterRxCommonTime) >> 1;
    865 
    866         // if the RTT of the packet is significantly larger than the panic
    867         // threshold, we should simply discard it.  Its better to do nothing
    868         // than to take cues from a packet like that.
    869         int rttCommon = mCommonClock.localDurationToCommonDuration(rtt);
    870         if (rttCommon > (static_cast<int64_t>(mPanicThresholdUsec) *
    871                          kRTTDiscardPanicThreshMultiplier)) {
    872             ALOGV("Dropping sync response with RTT of %lld uSec", rttCommon);
    873             mClient_ExpiredSyncRespsRXedFromCurMaster++;
    874             if (shouldPanicNotGettingGoodData())
    875                 return becomeInitial("RX panic, no good data");
    876         } else {
    877             result = mClockRecovery.pushDisciplineEvent(avgLocal, avgCommon, rttCommon);
    878             mClient_LastGoodSyncRX = clientRxLocalTime;
    879 
    880             if (result) {
    881                 // indicate to listeners that we've synced to the common timeline
    882                 notifyClockSync();
    883             } else {
    884                 ALOGE("Panic!  Observed clock sync error is too high to tolerate,"
    885                         " resetting state machine and starting over.");
    886                 notifyClockSyncLoss();
    887                 return becomeInitial("panic");
    888             }
    889         }
    890     }
    891 
    892     mCurTimeout.setTimeout(mSyncRequestIntervalMs);
    893     return result;
    894 }
    895 
    896 bool CommonTimeServer::handleMasterAnnouncement(
    897         const MasterAnnouncementPacket* packet,
    898         const sockaddr_storage& srcAddr) {
    899     uint64_t newDeviceID   = packet->deviceID;
    900     uint8_t  newDevicePrio = packet->devicePriority;
    901     uint64_t newTimelineID = packet->timelineID;
    902 
    903     if (mState == ICommonClock::STATE_INITIAL ||
    904         mState == ICommonClock::STATE_RONIN ||
    905         mState == ICommonClock::STATE_WAIT_FOR_ELECTION) {
    906         // if we aren't currently following a master, then start following
    907         // this new master
    908         return becomeClient(srcAddr,
    909                             newDeviceID,
    910                             newDevicePrio,
    911                             newTimelineID,
    912                             "heard master announcement");
    913     } else if (mState == ICommonClock::STATE_CLIENT) {
    914         // if the new master wins arbitration against our current master,
    915         // then become a client of the new master
    916         if (arbitrateMaster(newDeviceID,
    917                             newDevicePrio,
    918                             mClient_MasterDeviceID,
    919                             mClient_MasterDevicePriority))
    920             return becomeClient(srcAddr,
    921                                 newDeviceID,
    922                                 newDevicePrio,
    923                                 newTimelineID,
    924                                 "heard master announcement");
    925     } else if (mState == ICommonClock::STATE_MASTER) {
    926         // two masters are competing - if the new one wins arbitration, then
    927         // cease acting as master
    928         if (arbitrateMaster(newDeviceID, newDevicePrio,
    929                             mDeviceID, effectivePriority()))
    930             return becomeClient(srcAddr, newDeviceID,
    931                                 newDevicePrio, newTimelineID,
    932                                 "heard master announcement");
    933     }
    934 
    935     return true;
    936 }
    937 
    938 bool CommonTimeServer::sendWhoIsMasterRequest() {
    939     assert(mState == ICommonClock::STATE_INITIAL || mState == ICommonClock::STATE_RONIN);
    940 
    941     // If we have no socket, then we must be in the unconfigured initial state.
    942     // Don't report any errors, just don't try to send the initial who-is-master
    943     // query.  Eventually, our network will either become configured, or we will
    944     // be forced into network-less master mode by higher level code.
    945     if (mSocket < 0) {
    946         assert(mState == ICommonClock::STATE_INITIAL);
    947         return true;
    948     }
    949 
    950     bool ret = false;
    951     WhoIsMasterRequestPacket pkt;
    952     pkt.initHeader(mSyncGroupID);
    953     pkt.senderDeviceID = mDeviceID;
    954     pkt.senderDevicePriority = effectivePriority();
    955 
    956     uint8_t buf[256];
    957     ssize_t bufSz = pkt.serializePacket(buf, sizeof(buf));
    958     if (bufSz >= 0) {
    959         ssize_t sendBytes = sendto(
    960                 mSocket, buf, bufSz, 0,
    961                 reinterpret_cast<const sockaddr *>(&mMasterElectionEP),
    962                 sizeof(mMasterElectionEP));
    963         if (sendBytes < 0)
    964             ALOGE("WhoIsMaster sendto failed (errno %d)", errno);
    965         ret = true;
    966     }
    967 
    968     if (mState == ICommonClock::STATE_INITIAL) {
    969         mCurTimeout.setTimeout(kInitial_WhoIsMasterTimeoutMs);
    970     } else {
    971         mCurTimeout.setTimeout(kRonin_WhoIsMasterTimeoutMs);
    972     }
    973 
    974     return ret;
    975 }
    976 
    977 bool CommonTimeServer::sendSyncRequest() {
    978     // If we are sending sync requests, then we must be in the client state and
    979     // we must have a socket (when we have no network, we are only supposed to
    980     // be in INITIAL or MASTER)
    981     assert(mState == ICommonClock::STATE_CLIENT);
    982     assert(mSocket >= 0);
    983 
    984     bool ret = false;
    985     SyncRequestPacket pkt;
    986     pkt.initHeader(mTimelineID, mSyncGroupID);
    987     pkt.clientTxLocalTime = mLocalClock.getLocalTime();
    988 
    989     if (!mClient_FirstSyncTX)
    990         mClient_FirstSyncTX = pkt.clientTxLocalTime;
    991 
    992     mClient_PacketRTTLog.logTX(pkt.clientTxLocalTime);
    993 
    994     uint8_t buf[256];
    995     ssize_t bufSz = pkt.serializePacket(buf, sizeof(buf));
    996     if (bufSz >= 0) {
    997         ssize_t sendBytes = sendto(
    998                 mSocket, buf, bufSz, 0,
    999                 reinterpret_cast<const sockaddr *>(&mMasterEP),
   1000                 sizeof(mMasterEP));
   1001         if (sendBytes < 0)
   1002             ALOGE("SyncRequest sendto failed (errno %d)", errno);
   1003         ret = true;
   1004     }
   1005 
   1006     mClient_SyncsSentToCurMaster++;
   1007     mCurTimeout.setTimeout(mSyncRequestIntervalMs);
   1008     mClient_SyncRequestPending = true;
   1009 
   1010     return ret;
   1011 }
   1012 
   1013 bool CommonTimeServer::sendMasterAnnouncement() {
   1014     bool ret = false;
   1015     assert(mState == ICommonClock::STATE_MASTER);
   1016 
   1017     // If we are being asked to send a master announcement, but we have no
   1018     // socket, we must be in network-less master mode.  Don't bother to send the
   1019     // announcement, and don't bother to schedule a timeout.  When the network
   1020     // comes up, the work thread will get poked and start the process of
   1021     // figuring out who the current master should be.
   1022     if (mSocket < 0) {
   1023         mCurTimeout.setTimeout(kInfiniteTimeout);
   1024         return true;
   1025     }
   1026 
   1027     MasterAnnouncementPacket pkt;
   1028     pkt.initHeader(mTimelineID, mSyncGroupID);
   1029     pkt.deviceID = mDeviceID;
   1030     pkt.devicePriority = effectivePriority();
   1031 
   1032     uint8_t buf[256];
   1033     ssize_t bufSz = pkt.serializePacket(buf, sizeof(buf));
   1034     if (bufSz >= 0) {
   1035         ssize_t sendBytes = sendto(
   1036                 mSocket, buf, bufSz, 0,
   1037                 reinterpret_cast<const sockaddr *>(&mMasterElectionEP),
   1038                 sizeof(mMasterElectionEP));
   1039         if (sendBytes < 0)
   1040             ALOGE("MasterAnnouncement sendto failed (errno %d)", errno);
   1041         ret = true;
   1042     }
   1043 
   1044     mCurTimeout.setTimeout(mMasterAnnounceIntervalMs);
   1045     return ret;
   1046 }
   1047 
   1048 bool CommonTimeServer::becomeClient(const sockaddr_storage& masterEP,
   1049                                     uint64_t masterDeviceID,
   1050                                     uint8_t  masterDevicePriority,
   1051                                     uint64_t timelineID,
   1052                                     const char* cause) {
   1053     char newEPStr[64], oldEPStr[64];
   1054     sockaddrToString(masterEP, true, newEPStr, sizeof(newEPStr));
   1055     sockaddrToString(mMasterEP, mMasterEPValid, oldEPStr, sizeof(oldEPStr));
   1056 
   1057     ALOGI("%s --> CLIENT (%s) :%s"
   1058          " OldMaster: %02x-%014llx::%016llx::%s"
   1059          " NewMaster: %02x-%014llx::%016llx::%s",
   1060          stateToString(mState), cause,
   1061          (mTimelineID != timelineID) ? " (new timeline)" : "",
   1062          mClient_MasterDevicePriority, mClient_MasterDeviceID,
   1063          mTimelineID, oldEPStr,
   1064          masterDevicePriority, masterDeviceID,
   1065          timelineID, newEPStr);
   1066 
   1067     if (mTimelineID != timelineID) {
   1068         // start following a new timeline
   1069         mTimelineID = timelineID;
   1070         mClockRecovery.reset(true, true);
   1071         notifyClockSyncLoss();
   1072     } else {
   1073         // start following a new master on the existing timeline
   1074         mClockRecovery.reset(false, true);
   1075     }
   1076 
   1077     mMasterEP = masterEP;
   1078     mMasterEPValid = true;
   1079 
   1080     // If we are on a real network as a client of a real master, then we should
   1081     // no longer force low priority.  If our master disappears, we should have
   1082     // the high priority bit set during the election to replace the master
   1083     // because this group was a real group and not a singleton created in
   1084     // networkless mode.
   1085     setForceLowPriority(false);
   1086 
   1087     mClient_MasterDeviceID = masterDeviceID;
   1088     mClient_MasterDevicePriority = masterDevicePriority;
   1089     resetSyncStats();
   1090 
   1091     setState(ICommonClock::STATE_CLIENT);
   1092 
   1093     // add some jitter to when the various clients send their requests
   1094     // in order to reduce the likelihood that a group of clients overload
   1095     // the master after receiving a master announcement
   1096     usleep((lrand48() % 100) * 1000);
   1097 
   1098     return sendSyncRequest();
   1099 }
   1100 
   1101 bool CommonTimeServer::becomeMaster(const char* cause) {
   1102     uint64_t oldTimelineID = mTimelineID;
   1103     if (mTimelineID == ICommonClock::kInvalidTimelineID) {
   1104         // this device has not been following any existing timeline,
   1105         // so it will create a new timeline and declare itself master
   1106         assert(!mCommonClock.isValid());
   1107 
   1108         // set the common time basis
   1109         mCommonClock.setBasis(mLocalClock.getLocalTime(), 0);
   1110 
   1111         // assign an arbitrary timeline iD
   1112         assignTimelineID();
   1113 
   1114         // notify listeners that we've created a common timeline
   1115         notifyClockSync();
   1116     }
   1117 
   1118     ALOGI("%s --> MASTER (%s) : %s timeline %016llx",
   1119          stateToString(mState), cause,
   1120          (oldTimelineID == mTimelineID) ? "taking ownership of"
   1121                                         : "creating new",
   1122          mTimelineID);
   1123 
   1124     memset(&mMasterEP, 0, sizeof(mMasterEP));
   1125     mMasterEPValid = false;
   1126     mClient_MasterDevicePriority = effectivePriority();
   1127     mClient_MasterDeviceID = mDeviceID;
   1128     mClockRecovery.reset(false, true);
   1129     resetSyncStats();
   1130 
   1131     setState(ICommonClock::STATE_MASTER);
   1132     return sendMasterAnnouncement();
   1133 }
   1134 
   1135 bool CommonTimeServer::becomeRonin(const char* cause) {
   1136     // If we were the client of a given timeline, but had never received even a
   1137     // single time sync packet, then we transition back to Initial instead of
   1138     // Ronin.  If we transition to Ronin and end up becoming the new Master, we
   1139     // will be unable to service requests for other clients because we never
   1140     // actually knew what time it was.  By going to initial, we ensure that
   1141     // other clients who know what time it is, but would lose master arbitration
   1142     // in the Ronin case, will step up and become the proper new master of the
   1143     // old timeline.
   1144 
   1145     char oldEPStr[64];
   1146     sockaddrToString(mMasterEP, mMasterEPValid, oldEPStr, sizeof(oldEPStr));
   1147     memset(&mMasterEP, 0, sizeof(mMasterEP));
   1148     mMasterEPValid = false;
   1149 
   1150     if (mCommonClock.isValid()) {
   1151         ALOGI("%s --> RONIN (%s) : lost track of previously valid timeline "
   1152              "%02x-%014llx::%016llx::%s (%d TXed %d RXed %d RXExpired)",
   1153              stateToString(mState), cause,
   1154              mClient_MasterDevicePriority, mClient_MasterDeviceID,
   1155              mTimelineID, oldEPStr,
   1156              mClient_SyncsSentToCurMaster,
   1157              mClient_SyncRespsRXedFromCurMaster,
   1158              mClient_ExpiredSyncRespsRXedFromCurMaster);
   1159 
   1160         mRonin_WhoIsMasterRequestTimeouts = 0;
   1161         setState(ICommonClock::STATE_RONIN);
   1162         return sendWhoIsMasterRequest();
   1163     } else {
   1164         ALOGI("%s --> INITIAL (%s) : never synced timeline "
   1165              "%02x-%014llx::%016llx::%s (%d TXed %d RXed %d RXExpired)",
   1166              stateToString(mState), cause,
   1167              mClient_MasterDevicePriority, mClient_MasterDeviceID,
   1168              mTimelineID, oldEPStr,
   1169              mClient_SyncsSentToCurMaster,
   1170              mClient_SyncRespsRXedFromCurMaster,
   1171              mClient_ExpiredSyncRespsRXedFromCurMaster);
   1172 
   1173         return becomeInitial("ronin, no timeline");
   1174     }
   1175 }
   1176 
   1177 bool CommonTimeServer::becomeWaitForElection(const char* cause) {
   1178     ALOGI("%s --> WAIT_FOR_ELECTION (%s) : dropping out of election,"
   1179          " waiting %d mSec for completion.",
   1180          stateToString(mState), cause, kWaitForElection_TimeoutMs);
   1181 
   1182     setState(ICommonClock::STATE_WAIT_FOR_ELECTION);
   1183     mCurTimeout.setTimeout(kWaitForElection_TimeoutMs);
   1184     return true;
   1185 }
   1186 
   1187 bool CommonTimeServer::becomeInitial(const char* cause) {
   1188     ALOGI("Entering INITIAL (%s), total reset.", cause);
   1189 
   1190     setState(ICommonClock::STATE_INITIAL);
   1191 
   1192     // reset clock recovery
   1193     mClockRecovery.reset(true, true);
   1194 
   1195     // reset internal state bookkeeping.
   1196     mCurTimeout.setTimeout(kInfiniteTimeout);
   1197     memset(&mMasterEP, 0, sizeof(mMasterEP));
   1198     mMasterEPValid = false;
   1199     mLastPacketRxLocalTime = 0;
   1200     mTimelineID = ICommonClock::kInvalidTimelineID;
   1201     mClockSynced = false;
   1202     mInitial_WhoIsMasterRequestTimeouts = 0;
   1203     mClient_MasterDeviceID = 0;
   1204     mClient_MasterDevicePriority = 0;
   1205     mRonin_WhoIsMasterRequestTimeouts = 0;
   1206     resetSyncStats();
   1207 
   1208     // send the first request to discover the master
   1209     return sendWhoIsMasterRequest();
   1210 }
   1211 
   1212 void CommonTimeServer::notifyClockSync() {
   1213     if (!mClockSynced) {
   1214         mClockSynced = true;
   1215         mICommonClock->notifyOnTimelineChanged(mTimelineID);
   1216     }
   1217 }
   1218 
   1219 void CommonTimeServer::notifyClockSyncLoss() {
   1220     if (mClockSynced) {
   1221         mClockSynced = false;
   1222         mICommonClock->notifyOnTimelineChanged(
   1223                 ICommonClock::kInvalidTimelineID);
   1224     }
   1225 }
   1226 
   1227 void CommonTimeServer::setState(ICommonClock::State s) {
   1228     mState = s;
   1229 }
   1230 
   1231 const char* CommonTimeServer::stateToString(ICommonClock::State s) {
   1232     switch(s) {
   1233         case ICommonClock::STATE_INITIAL:
   1234             return "INITIAL";
   1235         case ICommonClock::STATE_CLIENT:
   1236             return "CLIENT";
   1237         case ICommonClock::STATE_MASTER:
   1238             return "MASTER";
   1239         case ICommonClock::STATE_RONIN:
   1240             return "RONIN";
   1241         case ICommonClock::STATE_WAIT_FOR_ELECTION:
   1242             return "WAIT_FOR_ELECTION";
   1243         default:
   1244             return "unknown";
   1245     }
   1246 }
   1247 
   1248 void CommonTimeServer::sockaddrToString(const sockaddr_storage& addr,
   1249                                         bool addrValid,
   1250                                         char* buf, size_t bufLen) {
   1251     if (!bufLen || !buf)
   1252         return;
   1253 
   1254     if (addrValid) {
   1255         switch (addr.ss_family) {
   1256             case AF_INET: {
   1257                 const struct sockaddr_in* sa =
   1258                     reinterpret_cast<const struct sockaddr_in*>(&addr);
   1259                 unsigned long a = ntohl(sa->sin_addr.s_addr);
   1260                 uint16_t      p = ntohs(sa->sin_port);
   1261                 snprintf(buf, bufLen, "%lu.%lu.%lu.%lu:%hu",
   1262                         ((a >> 24) & 0xFF), ((a >> 16) & 0xFF),
   1263                         ((a >>  8) & 0xFF),  (a        & 0xFF), p);
   1264             } break;
   1265 
   1266             case AF_INET6: {
   1267                 const struct sockaddr_in6* sa =
   1268                     reinterpret_cast<const struct sockaddr_in6*>(&addr);
   1269                 const uint8_t* a = sa->sin6_addr.s6_addr;
   1270                 uint16_t       p = ntohs(sa->sin6_port);
   1271                 snprintf(buf, bufLen,
   1272                         "%02X%02X:%02X%02X:%02X%02X:%02X%02X:"
   1273                         "%02X%02X:%02X%02X:%02X%02X:%02X%02X port %hd",
   1274                         a[0], a[1], a[ 2], a[ 3], a[ 4], a[ 5], a[ 6], a[ 7],
   1275                         a[8], a[9], a[10], a[11], a[12], a[13], a[14], a[15],
   1276                         p);
   1277             } break;
   1278 
   1279             default:
   1280                 snprintf(buf, bufLen,
   1281                          "<unknown sockaddr family %d>", addr.ss_family);
   1282                 break;
   1283         }
   1284     } else {
   1285         snprintf(buf, bufLen, "<none>");
   1286     }
   1287 
   1288     buf[bufLen - 1] = 0;
   1289 }
   1290 
   1291 bool CommonTimeServer::sockaddrMatch(const sockaddr_storage& a1,
   1292                                      const sockaddr_storage& a2,
   1293                                      bool matchAddressOnly) {
   1294     if (a1.ss_family != a2.ss_family)
   1295         return false;
   1296 
   1297     switch (a1.ss_family) {
   1298         case AF_INET: {
   1299             const struct sockaddr_in* sa1 =
   1300                 reinterpret_cast<const struct sockaddr_in*>(&a1);
   1301             const struct sockaddr_in* sa2 =
   1302                 reinterpret_cast<const struct sockaddr_in*>(&a2);
   1303 
   1304             if (sa1->sin_addr.s_addr != sa2->sin_addr.s_addr)
   1305                 return false;
   1306 
   1307             return (matchAddressOnly || (sa1->sin_port == sa2->sin_port));
   1308         } break;
   1309 
   1310         case AF_INET6: {
   1311             const struct sockaddr_in6* sa1 =
   1312                 reinterpret_cast<const struct sockaddr_in6*>(&a1);
   1313             const struct sockaddr_in6* sa2 =
   1314                 reinterpret_cast<const struct sockaddr_in6*>(&a2);
   1315 
   1316             if (memcmp(&sa1->sin6_addr, &sa2->sin6_addr, sizeof(sa2->sin6_addr)))
   1317                 return false;
   1318 
   1319             return (matchAddressOnly || (sa1->sin6_port == sa2->sin6_port));
   1320         } break;
   1321 
   1322         // Huh?  We don't deal in non-IPv[46] addresses.  Not sure how we got
   1323         // here, but we don't know how to comapre these addresses and simply
   1324         // default to a no-match decision.
   1325         default: return false;
   1326     }
   1327 }
   1328 
   1329 void CommonTimeServer::TimeoutHelper::setTimeout(int msec) {
   1330     mTimeoutValid = (msec >= 0);
   1331     if (mTimeoutValid)
   1332         mEndTime = systemTime() +
   1333                    (static_cast<nsecs_t>(msec) * 1000000);
   1334 }
   1335 
   1336 int CommonTimeServer::TimeoutHelper::msecTillTimeout() {
   1337     if (!mTimeoutValid)
   1338         return kInfiniteTimeout;
   1339 
   1340     nsecs_t now = systemTime();
   1341     if (now >= mEndTime)
   1342         return 0;
   1343 
   1344     uint64_t deltaMsec = (((mEndTime - now) + 999999) / 1000000);
   1345 
   1346     if (deltaMsec > static_cast<uint64_t>(MAX_INT))
   1347         return MAX_INT;
   1348 
   1349     return static_cast<int>(deltaMsec);
   1350 }
   1351 
   1352 bool CommonTimeServer::shouldPanicNotGettingGoodData() {
   1353     if (mClient_FirstSyncTX) {
   1354         int64_t now = mLocalClock.getLocalTime();
   1355         int64_t delta = now - (mClient_LastGoodSyncRX
   1356                              ? mClient_LastGoodSyncRX
   1357                              : mClient_FirstSyncTX);
   1358         int64_t deltaUsec = mCommonClock.localDurationToCommonDuration(delta);
   1359 
   1360         if (deltaUsec >= kNoGoodDataPanicThresholdUsec)
   1361             return true;
   1362     }
   1363 
   1364     return false;
   1365 }
   1366 
   1367 void CommonTimeServer::PacketRTTLog::logTX(int64_t txTime) {
   1368     txTimes[wrPtr] = txTime;
   1369     rxTimes[wrPtr] = 0;
   1370     wrPtr = (wrPtr + 1) % RTT_LOG_SIZE;
   1371     if (!wrPtr)
   1372         logFull = true;
   1373 }
   1374 
   1375 void CommonTimeServer::PacketRTTLog::logRX(int64_t txTime, int64_t rxTime) {
   1376     if (!logFull && !wrPtr)
   1377         return;
   1378 
   1379     uint32_t i = logFull ? wrPtr : 0;
   1380     do {
   1381         if (txTimes[i] == txTime) {
   1382             rxTimes[i] = rxTime;
   1383             break;
   1384         }
   1385         i = (i + 1) % RTT_LOG_SIZE;
   1386     } while (i != wrPtr);
   1387 }
   1388 
   1389 }  // namespace android
   1390