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