2 * Copyright (c) 1985, 1993
3 * The Regents of the University of California. All rights reserved.
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 * notice, this list of conditions and the following disclaimer in the
12 * documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 * must display the following acknowledgement:
15 * This product includes software developed by the University of
16 * California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 * may be used to endorse or promote products derived from this software
19 * without specific prior written permission.
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
33 * @(#)master.c 8.1 (Berkeley) 6/6/93
34 * $FreeBSD: src/usr.sbin/timed/timed/master.c,v 1.6 1999/08/28 01:20:17 peter Exp $
35 * $DragonFly: src/usr.sbin/timed/timed/master.c,v 1.2 2003/06/17 04:30:03 dillon Exp $
40 #include <sys/types.h>
41 #include <sys/times.h>
44 #include <sys/schedctl.h>
47 #include "pathnames.h"
49 extern int measure_delta;
50 extern jmp_buf jmpenv;
55 static int slvcount; /* slaves listening to our clock */
57 static void mchgdate __P((struct tsp *));
60 extern void logwtmp __P((struct timeval *, struct timeval *));
62 extern void logwtmp __P((char *, char *, char *));
66 * The main function of `master' is to periodically compute the differences
67 * (deltas) between its clock and the clocks of the slaves, to compute the
68 * network average delta, and to send to the slaves the differences between
69 * their individual deltas and the network delta.
70 * While waiting, it receives messages from the slaves (i.e. requests for
71 * master's name, remote requests to set the network time, ...), and
72 * takes the appropriate action.
81 struct timeval wait, ntime;
83 struct tsp *msg, *answer, to;
85 struct sockaddr_in taddr;
86 char tname[MAXHOSTNAMELEN];
90 syslog(LOG_NOTICE, "This machine is master");
92 fprintf(fd, "This machine is master\n");
93 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
94 if (ntp->status == MASTER)
97 (void)gettimeofday(&ntime, 0);
98 pollingtime = ntime.tv_sec+3;
104 /* Process all outstanding messages before spending the long time necessary
105 * to update all timers.
108 (void)gettimeofday(&ntime, 0);
109 wait.tv_sec = pollingtime - ntime.tv_sec;
113 msg = readmsg(TSP_ANY, ANYADDR, &wait, 0);
115 (void)gettimeofday(&ntime, 0);
116 if (ntime.tv_sec >= pollingtime) {
117 pollingtime = ntime.tv_sec + SAMPLEINTVL;
120 /* If a bogus master told us to quit, we can have decided to ignore a
121 * network. Therefore, periodically try to take over everything.
123 polls = (polls + 1) % POLLRATE;
124 if (0 == polls && nignorednets > 0) {
125 trace_msg("Looking for nets to re-master\n");
126 for (ntp = nettab; ntp; ntp = ntp->next) {
127 if (ntp->status == IGNORE
128 || ntp->status == NOMASTER) {
130 if (ntp->status == MASTER) {
135 if (ntp->status == MASTER
136 && --ntp->quit_count < 0)
145 for (ntp = nettab; ntp != NULL; ntp = ntp->next) {
146 to.tsp_type = TSP_LOOP;
147 to.tsp_vers = TSPVERSION;
148 to.tsp_seq = sequence++;
149 to.tsp_hopcnt = MAX_HOPCNT;
150 (void)strcpy(to.tsp_name, hostname);
152 if (sendto(sock, (char *)&to,
153 sizeof(struct tsp), 0,
154 (struct sockaddr*)&ntp->dest_addr,
155 sizeof(ntp->dest_addr)) < 0) {
156 trace_sendto_err(ntp->dest_addr.sin_addr);
163 switch (msg->tsp_type) {
174 * XXX check to see it is from ourself
177 (void)cftime(newdate, "%D %T", &msg->tsp_time.tv_sec);
179 tsp_time_sec = msg->tsp_time.tv_sec;
180 (void)strcpy(newdate, ctime(&tsp_time_sec));
182 if (!good_host_name(msg->tsp_name)) {
184 "attempted date change by %s to %s",
185 msg->tsp_name, newdate);
191 (void)gettimeofday(&ntime, 0);
192 pollingtime = ntime.tv_sec + SAMPLEINTVL;
196 if (!fromnet || fromnet->status != MASTER)
199 (void)cftime(newdate, "%D %T", &msg->tsp_time.tv_sec);
201 tsp_time_sec = msg->tsp_time.tv_sec;
202 (void)strcpy(newdate, ctime(&tsp_time_sec));
204 htp = findhost(msg->tsp_name);
207 "attempted SET DATEREQ by uncontrolled %s to %s",
208 msg->tsp_name, newdate);
211 if (htp->seq == msg->tsp_seq)
213 htp->seq = msg->tsp_seq;
216 "attempted SET DATEREQ by untrusted %s to %s",
217 msg->tsp_name, newdate);
223 (void)gettimeofday(&ntime, 0);
224 pollingtime = ntime.tv_sec + SAMPLEINTVL;
228 xmit(TSP_ACK, msg->tsp_seq, &from);
239 traceoff("Tracing ended at %s\n");
245 if (fromnet->status == MASTER) {
247 (void)addmach(msg->tsp_name, &from,fromnet);
250 (void)strcpy(tname, msg->tsp_name);
251 to.tsp_type = TSP_QUIT;
252 (void)strcpy(to.tsp_name, hostname);
253 answer = acksend(&to, &taddr, tname,
255 if (answer == NULL) {
256 syslog(LOG_ERR, "election error by %s",
263 * After a network partition, there can be
264 * more than one master: the first slave to
265 * come up will notify here the situation.
267 if (!fromnet || fromnet->status != MASTER)
269 (void)strcpy(to.tsp_name, hostname);
271 /* The other master often gets into the same state,
272 * with boring results if we stay at it forever.
274 ntp = fromnet; /* (acksend() can leave fromnet=0 */
275 for (i = 0; i < 3; i++) {
276 to.tsp_type = TSP_RESOLVE;
277 (void)strcpy(to.tsp_name, hostname);
278 answer = acksend(&to, &ntp->dest_addr,
279 ANYADDR, TSP_MASTERACK,
283 htp = addmach(answer->tsp_name,&from,ntp);
284 to.tsp_type = TSP_QUIT;
285 msg = acksend(&to, &htp->addr, htp->name,
286 TSP_ACK, 0, htp->noanswer);
289 "no response from %s to CONFLICT-QUIT",
298 if (!fromnet || fromnet->status != MASTER)
301 * do not want to call synch() while waiting
304 (void)gettimeofday(&ntime, (struct timezone *)0);
305 pollingtime = ntime.tv_sec + SAMPLEINTVL;
309 doquit(msg); /* become a slave */
313 if (!fromnet || fromnet->status != MASTER
314 || !strcmp(msg->tsp_name, hostname))
317 * We should not have received this from a net
318 * we are master on. There must be two masters.
320 htp = addmach(msg->tsp_name, &from,fromnet);
321 to.tsp_type = TSP_QUIT;
322 (void)strcpy(to.tsp_name, hostname);
323 answer = acksend(&to, &htp->addr, htp->name,
327 "loop breakage: no reply from %s=%s to QUIT",
328 htp->name, inet_ntoa(htp->addr.sin_addr));
335 "\tnets = %d, masters = %d, slaves = %d, ignored = %d\n",
336 nnets, nmasternets, nslavenets, nignorednets);
345 fprintf(fd, "garbage message: ");
356 * change the system date on the master
362 char tname[MAXHOSTNAMELEN];
364 struct timeval otime, ntime;
366 (void)strcpy(tname, msg->tsp_name);
368 xmit(TSP_DATEACK, msg->tsp_seq, &from);
370 (void)strcpy(olddate, date());
372 /* adjust time for residence on the queue */
373 (void)gettimeofday(&otime, 0);
374 adj_msg_time(msg,&otime);
376 timevalsub(&ntime, &msg->tsp_time, &otime);
377 if (ntime.tv_sec < MAXADJ && ntime.tv_sec > -MAXADJ) {
379 * do not change the clock if we can adjust it
382 synch(tvtomsround(ntime));
385 if (0 > settimeofday(&msg->tsp_time, 0)) {
386 syslog(LOG_ERR, "settimeofday(): %m");
388 logwtmp(&otime, &msg->tsp_time);
390 logwtmp("|", "date", "");
391 (void)settimeofday(&msg->tsp_time, 0);
392 logwtmp("{", "date", "");
397 syslog(LOG_NOTICE, "date changed by %s from %s",
403 * synchronize all of the slaves
411 struct timeval check, stop, wait;
418 fprintf(fd, "measurements starting at %s\n", date());
419 (void)gettimeofday(&check, 0);
421 /* run fast to get good time */
422 pri = schedctl(NDPRI,0,NDPHIMIN);
424 syslog(LOG_ERR, "schedctl(): %m");
426 for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
427 if (htp->noanswer != 0) {
428 measure_status = measure(500, 100,
432 measure_status = measure(3000, 100,
436 if (measure_status != GOOD) {
437 /* The slave did not respond. We have
438 * just wasted lots of time on it.
440 htp->delta = HOSTDOWN;
441 if (++htp->noanswer >= LOSTHOST) {
444 "purging %s for not answering ICMP\n",
451 htp->delta = measure_delta;
453 (void)gettimeofday(&stop, 0);
454 timevalsub(&stop, &stop, &check);
455 if (stop.tv_sec >= 1) {
459 * ack messages periodically
463 if (0 != readmsg(TSP_TRACEON,ANYADDR,
466 (void)gettimeofday(&check, 0);
471 (void)schedctl(NDPRI,0,pri);
474 fprintf(fd, "measurements finished at %s\n", date());
476 if (!(status & SLAVE)) {
478 mydelta = networkdelta();
483 if (trace && (mydelta != 0 || (status & SLAVE)))
484 fprintf(fd,"local correction of %ld ms.\n", mydelta);
489 * sends the time to each slave after the master
490 * has received the command to set the network time
499 /* Do not listen to the consensus after forcing the time. This is because
500 * the consensus takes a while to reach the time we are dictating.
503 for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
504 to.tsp_type = TSP_SETTIME;
505 (void)strcpy(to.tsp_name, hostname);
506 (void)gettimeofday(&to.tsp_time, 0);
507 answer = acksend(&to, &htp->addr, htp->name,
508 TSP_ACK, 0, htp->noanswer);
510 /* We client does not respond, then we have
511 * just wasted lots of time on it.
514 "no reply to SETTIME from %s", htp->name);
515 if (++htp->noanswer >= LOSTHOST) {
518 "purging %s for not answering",
532 static time_t next_time;
539 if (!fd) /* quit if tracing already off */
542 this_time = times(&tm);
543 if (this_time + delta < next_time)
545 next_time = this_time + CLK_TCK;
547 fprintf(fd, "host table: %d entries at %s\n", slvcount, date());
550 for (i = 1; i <= slvcount; i++, htp = htp->l_fwd) {
551 l = strlen(htp->name) + 1;
552 if (length+l >= 80) {
557 fprintf(fd, " %s", htp->name);
563 static struct hosttbl *newhost_hash;
564 static struct hosttbl *lasthfree = &hosttbl[0];
567 struct hosttbl * /* answer or 0 */
576 for (p = name, i = 0; i < 8 && *p != '\0'; i++, p++)
578 newhost_hash = &hosttbl[j % NHOSTS];
581 if (htp->name[0] == '\0')
584 if (!strcmp(name, htp->name))
587 } while (htp != newhost_hash);
592 * add a host to the list of controlled machines if not already there
595 addmach(name, addr, ntp)
597 struct sockaddr_in *addr;
600 struct hosttbl *ret, *p, *b, *f;
602 ret = findhost(name);
604 if (slvcount >= NHOSTS) {
606 fprintf(fd, "no more slots in host table\n");
609 syslog(LOG_ERR, "no more slots in host table");
611 longjmp(jmpenv, 2); /* give up and be a slave */
614 /* if our home hash slot is occupied, find a free entry
617 if (newhost_hash->name[0] != '\0') {
620 if (++lasthfree > &hosttbl[NHOSTS])
621 lasthfree = &hosttbl[1];
622 } while (ret->name[0] != '\0');
624 if (!newhost_hash->head) {
625 /* Move an interloper using our home. Use
626 * scratch pointers in case the new head is
627 * pointing to itself.
629 f = newhost_hash->h_fwd;
630 b = newhost_hash->h_bak;
633 f = newhost_hash->l_fwd;
634 b = newhost_hash->l_bak;
637 bcopy(newhost_hash,ret,sizeof(*ret));
643 /* link to an existing chain in our home
646 p = newhost_hash->h_bak;
647 ret->h_fwd = newhost_hash;
650 newhost_hash->h_bak = ret;
660 (void)strncpy(ret->name, name, sizeof(ret->name));
661 ret->good = good_host_name(name);
663 ret->l_bak = self.l_bak;
664 self.l_bak->l_fwd = ret;
672 ret->noanswer = (ret->noanswer != 0);
675 /* need to clear sequence number anyhow */
681 * remove the machine with the given index in the host table.
687 struct hosttbl *lprv, *hnxt, *f, *b;
690 fprintf(fd, "remove %s\n", htp->name);
692 /* get out of the lists */
693 htp->l_fwd->l_bak = lprv = htp->l_bak;
694 htp->l_bak->l_fwd = htp->l_fwd;
695 htp->h_fwd->h_bak = htp->h_bak;
696 htp->h_bak->h_fwd = hnxt = htp->h_fwd;
698 /* If we are in the home slot, pull up the chain */
699 if (htp->head && hnxt != htp) {
703 /* Use scratch pointers in case the new head is pointing to
715 bcopy(hnxt, htp, sizeof(*htp));
721 lasthfree->name[0] = '\0';
722 lasthfree->h_fwd = 0;
723 lasthfree->l_fwd = 0;
731 * Remove all the machines from the host table that exist on the given
732 * network. This is called when a master transitions to a slave on a
743 for (htp = self.l_fwd; htp != &self; htp = htp->l_fwd) {
755 xmit(TSP_MASTERUP, 0, &net->dest_addr);
758 * Do not tell new slaves our time for a while. This ensures
759 * we do not tell them to start using our time, before we have
760 * found a good master.
762 (void)gettimeofday(&net->slvwait, 0);
770 struct tsp *answer, to;
773 if (!fromnet || fromnet->status != MASTER)
776 htp = addmach(msg->tsp_name, &from,fromnet);
777 htp->seq = msg->tsp_seq;
782 * If we are stable, send our time to the slave.
783 * Do not go crazy if the date has been changed.
785 (void)gettimeofday(&now, 0);
786 if (now.tv_sec >= fromnet->slvwait.tv_sec+3
787 || now.tv_sec < fromnet->slvwait.tv_sec) {
788 to.tsp_type = TSP_SETTIME;
789 (void)strcpy(to.tsp_name, hostname);
790 (void)gettimeofday(&to.tsp_time, 0);
791 answer = acksend(&to, &htp->addr,
798 "no reply to initial SETTIME from %s",
800 htp->noanswer = LOSTHOST;
807 * react to a TSP_QUIT:
813 if (fromnet->status == MASTER) {
814 if (!good_host_name(msg->tsp_name)) {
815 if (fromnet->quit_count <= 0) {
816 syslog(LOG_NOTICE,"untrusted %s told us QUIT",
818 suppress(&from, msg->tsp_name, fromnet);
819 fromnet->quit_count = 1;
822 syslog(LOG_NOTICE, "untrusted %s told us QUIT twice",
824 fromnet->quit_count = 2;
825 fromnet->status = NOMASTER;
827 fromnet->status = SLAVE;
830 longjmp(jmpenv, 2); /* give up and be a slave */
833 if (!good_host_name(msg->tsp_name)) {
834 syslog(LOG_NOTICE, "untrusted %s told us QUIT",
836 fromnet->quit_count = 2;
845 fd = fopen(_PATH_TIMEDLOG, "w");
850 fprintf(fd,"Tracing started at %s\n", date());
867 fprintf(fd, msg, date());
882 logwtmp(otime, ntime)
883 struct timeval *otime, *ntime;
885 static struct utmp wtmp[2] = {
886 {"","",OTIME_MSG,0,OLD_TIME,0,0,0},
887 {"","",NTIME_MSG,0,NEW_TIME,0,0,0}
889 static char *wtmpfile = WTMP_FILE;
892 wtmp[0].ut_time = otime->tv_sec + (otime->tv_usec + 500000) / 1000000;
893 wtmp[1].ut_time = ntime->tv_sec + (ntime->tv_usec + 500000) / 1000000;
894 if (wtmp[0].ut_time == wtmp[1].ut_time)
898 (void)pututline(&wtmp[0]);
899 (void)pututline(&wtmp[1]);
901 if ((f = open(wtmpfile, O_WRONLY|O_APPEND)) >= 0) {
902 (void) write(f, (char *)wtmp, sizeof(wtmp));