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