home *** CD-ROM | disk | FTP | other *** search
/ OS/2 Shareware BBS: 35 Internet / 35-Internet.zip / daytime.zip / rfc1305 < prev    next >
Text File  |  1997-04-26  |  307KB  |  6,392 lines

  1. Network Working Group                           David L. Mills
  2. Request for Comments: 1305                      University of Delaware
  3. Obsoletes RFC-1119, RFC-1059, RFC-958           March 1992
  4.  
  5.  
  6.  
  7.                    Network Time Protocol (Version 3)
  8.                Specification, Implementation and Analysis
  9.  
  10.  
  11.  
  12. Note: This document consists of an approximate rendering in ASCII of the
  13. PostScript document of the same name. It is provided for convenience and
  14. for use in searches, etc. However, most tables, figures, equations and
  15. captions have not been rendered and the pagination and section headings
  16. are not available.
  17.  
  18. Abstract
  19.  
  20. This document describes the Network Time Protocol (NTP), specifies its
  21. formal structure and summarizes information useful for its
  22. implementation. NTP provides the mechanisms to synchronize time and
  23. coordinate time distribution in a large, diverse internet operating at
  24. rates from mundane to lightwave. It uses a returnable-time design in
  25. which a distributed subnet of time servers operating in a self-
  26. organizing, hierarchical-master-slave configuration synchronizes local
  27. clocks within the subnet and to national time standards via wire or
  28. radio. The servers can also redistribute reference time via local
  29. routing algorithms and time daemons.
  30.  
  31. Status of this Memo
  32.  
  33. This RFC specifies an IAB standards track protocol for the Internet
  34. community and requests discussion and suggestions for improvements.
  35. Please refer to the current edition of the <169>IAB Official Protocol
  36. Standards<170> for the standardization state and status of this
  37. protocol. Distribution of this memo is unlimited.
  38.  
  39. Keywords: network clock synchronization, standard time distribution,
  40. fault-tolerant architecture, maximum-likelihood estimation, disciplined
  41. oscillator, internet protocol, high-speed networks, formal
  42. specification.
  43.  
  44. Preface
  45.  
  46. This document describes Version 3 of the Network Time Protocol (NTP). It
  47. supersedes Version 2 of the protocol described in RFC-1119 dated
  48. September 1989. However, it neither changes the protocol in any
  49. significant way nor obsoletes previous versions or existing
  50. implementations. The main motivation for the new version is to refine
  51. the analysis and implementation models for new applications at much
  52. higher network speeds to the gigabit-per-second regime and to provide
  53. for the enhanced stability, accuracy and precision required at such
  54. speeds. In particular, the sources of time and frequency errors have
  55. been rigorously examined and error bounds established in order to
  56. improve performance, provide a model for correctness assertions and
  57. indicate timekeeping quality to the user. The revision also incorporates
  58. two new optional features, (1) an algorithm to combine the offsets of a
  59. number of peer time servers in order to enhance accuracy and (2)
  60. improved local-clock algorithms which allow the poll intervals on all
  61. synchronization paths to be substantially increased in order to reduce
  62. network overhead. An overview of the changes, which are described in
  63. detail in Appendix D, follows:
  64.  
  65. 1.
  66. In Version 3 The local-clock algorithm has been overhauled to improve
  67. stability and accuracy. Appendix G presents a detailed mathematical
  68. model and design example which has been refined with the aid of
  69. feedback-control analysis and extensive simulation using data collected
  70. over ordinary Internet paths. Section 5 of RFC-1119 on the NTP local
  71. clock has been completely rewritten to describe the new algorithm. Since
  72. the new algorithm can result in message rates far below the old ones, it
  73. is highly recommended that they be used in new implementations. Note
  74. that use of the new algorithm does not affect interoperability with
  75. previous versions or existing implementations.
  76.  
  77. 2.
  78.  
  79. In Version 3 a new algorithm to combine the offsets of a number of peer
  80. time servers is presented in Appendix F. This algorithm is modelled on
  81. those used by national standards laboratories to combine the weighted
  82. offsets from a number of standard clocks to construct a synthetic
  83. laboratory timescale more accurate than that of any clock separately. It
  84. can be used in an NTP implementation to improve accuracy and stability
  85. and reduce errors due to asymmetric paths in the Internet. The new
  86. algorithm has been simulated using data collected over ordinary Internet
  87. paths and, along with the new local-clock algorithm, implemented and
  88. tested in the Fuzzball time servers now running in the Internet. Note
  89. that use of the new algorithm does not affect interoperability with
  90. previous versions or existing implementations.
  91.  
  92. 3.
  93.  
  94. Several inconsistencies and minor errors in previous versions have been
  95. corrected in Version 3. The description of the procedures has been
  96. rewritten in pseudo-code augmented by English commentary for clarity and
  97. to avoid ambiguity. Appendix I has been added to illustrate C-language
  98. implementations of the various filtering and selection algorithms
  99. suggested for NTP. Additional information is included in Section 5 and
  100. in Appendix E, which includes the tutorial material formerly included in
  101. Section 2 of RFC-1119, as well as much new material clarifying the
  102. interpretation of timescales and leap seconds.
  103.  
  104. 4.
  105.  
  106. Minor changes have been made in the Version-3 local-clock algorithms to
  107. avoid problems observed when leap seconds are introduced in the UTC
  108. timescale and also to support an auxiliary precision oscillator, such as
  109. a cesium clock or timing receiver, as a precision timebase. In addition,
  110. changes were made to some procedures described in Section 3 and in the
  111. clock-filter and clock-selection procedures described in Section 4.
  112. While these changes were made to correct minor bugs found as the result
  113. of experience and are recommended for new implementations, they do not
  114. affect interoperability with previous versions or existing
  115. implementations in other than minor ways (at least until the next leap
  116. second).
  117.  
  118. 5.
  119.  
  120. In Version 3 changes were made to the way delay, offset and dispersion
  121. are defined, calculated and processed in order to reliably bound the
  122. errors inherent in the time-transfer procedures. In particular, the
  123. error accumulations were moved from the delay computation to the
  124. dispersion computation and both included in the clock filter and
  125. selection procedures. The clock-selection procedure was modified to
  126. remove the first of the two sorting/discarding steps and replace with an
  127. algorithm first proposed by Marzullo and later incorporated in the
  128. Digital Time Service. These changes do not significantly affect the
  129. ordinary operation of or compatibility with various versions of NTP, but
  130. they do provide the basis for formal statements of correctness as
  131. described in Appendix H.
  132. Table of Contents
  133.  
  134. 1.       Introduction   1
  135.  
  136. 1.1.     Related Technology     2
  137.  
  138. 2.       System Architecture    4
  139.  
  140. 2.1.     Implementation Model   6
  141.  
  142. 2.2.     Network Configurations 7
  143.  
  144. 3.       Network Time Protocol  8
  145.  
  146. 3.1.     Data Formats   8
  147.  
  148. 3.2.     State Variables and Parameters 9
  149.  
  150. 3.2.1.   Common Variables       9
  151.  
  152. 3.2.2.   System Variables       12
  153.  
  154. 3.2.3.   Peer Variables 12
  155.  
  156. 3.2.4.   Packet Variables       14
  157.  
  158. 3.2.5.   Clock-Filter Variables 14
  159.  
  160. 3.2.6.   Authentication Variables       15
  161.  
  162. 3.2.7.   Parameters     15
  163.  
  164. 3.3.     Modes of Operation     17
  165.  
  166. 3.4.     Event Processing       19
  167.  
  168. 3.4.1.   Notation Conventions   19
  169.  
  170. 3.4.2.   Transmit Procedure     20
  171.  
  172. 3.4.3.   Receive Procedure      22
  173.  
  174. 3.4.4.   Packet Procedure       24
  175.  
  176. 3.4.5.   Clock-Update Procedure 27
  177.  
  178. 3.4.6.   Primary-Clock Procedure        28
  179.  
  180. 3.4.7.   Initialization Procedures      28
  181.  
  182. 3.4.7.1.         Initialization Procedure       29
  183.  
  184. 3.4.7.2.         Initialization-Instantiation Procedure 29
  185.  
  186. 3.4.7.3.         Receive-Instantiation Procedure        30
  187.  
  188. 3.4.7.4.         Primary Clock-Instantiation Procedure  31
  189.  
  190. 3.4.8.   Clear Procedure        31
  191.  
  192. 3.4.9.   Poll-Update Procedure  32
  193.  
  194. 3.5.     Synchronization Distance Procedure     32
  195.  
  196. 3.6.     Access Control Issues  33
  197.  
  198. 4.       Filtering and Selection Algorithms     34
  199.  
  200. 4.1.     Clock-Filter Procedure 35
  201.  
  202. 4.2.     Clock-Selection Procedure      36
  203.  
  204. 4.2.1.   Intersection Algorithm 36
  205.  
  206. 5.       Local Clocks   40
  207.  
  208. 5.1.     Fuzzball Implementation        41
  209.  
  210. 5.2.     Gradual Phase Adjustments      42
  211.  
  212. 5.3.     Step Phase Adjustments 43
  213.  
  214. 5.4.     Implementation Issues  44
  215.  
  216. 6.       Acknowledgments        45
  217.  
  218. 7.       References     46
  219.  
  220. A.       Appendix A. NTP Data Format - Version 3        50
  221.  
  222. B.       Appendix B. NTP Control Messages       53
  223.  
  224. B.1.     NTP Control Message Format     54
  225.  
  226. B.2.     Status Words   56
  227.  
  228. B.2.1.   System Status Word     56
  229.  
  230. B.2.2.   Peer Status Word       57
  231.  
  232. B.2.3.   Clock Status Word      58
  233.  
  234. B.2.4.   Error Status Word      58
  235.  
  236. B.3.     Commands       59
  237.  
  238. C.       Appendix C. Authentication Issues      61
  239.  
  240. C.1.     NTP Authentication Mechanism   62
  241.  
  242. C.2.     NTP Authentication Procedures  63
  243.  
  244. C.2.1.   Encrypt Procedure      63
  245.  
  246. 4.2.2.   Clustering Algorithm   38
  247.  
  248. C.2.2.   Decrypt Procedure      64
  249.  
  250. C.2.3.   Control-Message Procedures     65
  251.  
  252. D.       Appendix D. Differences from Previous Versions.        66
  253.  
  254. E.       Appendix E. The NTP Timescale and its Chronometry      70
  255.  
  256. E.1.     Introduction   70
  257.  
  258. E.2.     Primary Frequency and Time Standards   70
  259.  
  260. E.3.     Time and Frequency Dissemination       72
  261.  
  262. E.4.     Calendar Systems       74
  263.  
  264. E.5.     The Modified Julian Day System 75
  265.  
  266. E.6.     Determination of Frequency     76
  267.  
  268. E.7.     Determination of Time and Leap Seconds 76
  269.  
  270. E.8.     The NTP Timescale and Reckoning with UTC       78
  271.  
  272. F.       Appendix F. The NTP Clock-Combining Algorithm  80
  273.  
  274. F.1.     Introduction   80
  275.  
  276. F.2.     Determining Time and Frequency 80
  277.  
  278. F.3.     Clock Modelling        81
  279.  
  280. F.4.     Development of a Composite Timescale   81
  281.  
  282. F.5.     Application to NTP     84
  283.  
  284. F.6.     Clock-Combining Procedure      84
  285.  
  286. G.       Appendix G. Computer Clock Modelling and Analysis      86
  287.  
  288. G.1.     Computer Clock Models  86
  289.  
  290. G.1.1.   The Fuzzball Clock Model       88
  291.  
  292. G.1.2.   The Unix Clock Model   89
  293.  
  294. G.2.     Mathematical Model of the NTP Logical Clock    91
  295.  
  296. G.3.     Parameter Management   93
  297.  
  298. G.4.     Adjusting VCO Gain (<$Ebold alpha>)    94
  299.  
  300. G.5.     Adjusting PLL Bandwidth (<$Ebold tau>) 94
  301.  
  302. G.6.     The NTP Clock Model    95
  303.  
  304. H.       Appendix H. Analysis of Errors and Correctness Principles
  305.  
  306. 98
  307.  
  308. H.1.     Introduction   98
  309.  
  310. H.2.     Timestamp Errors       98
  311.  
  312. H.3.     Measurement Errors     100
  313.  
  314. H.4.     Network Errors 101
  315.  
  316. H.5.     Inherited Errors       102
  317.  
  318. H.6.     Correctness Principles 104
  319.  
  320. I.       Appendix I. Selected C-Language Program Listings       107
  321.  
  322. I.1.     Common Definitions and Variables       107
  323.  
  324. I.2.     Clock<196>Filter Algorithm     108
  325.  
  326. I.3.     Interval Intersection Algorithm        109
  327.  
  328. I.4.     Clock<196>Selection Algorithm  110
  329.  
  330. I.5.     Clock<196>Combining Procedure  111
  331.  
  332. I.6.     Subroutine to Compute Synchronization Distance 112
  333.  
  334. List of Figures
  335.  
  336. Figure 1. Implementation Model  6
  337.  
  338. Figure 2. Calculating Delay and Offset  25
  339.  
  340. Figure 3. Clock Registers       39
  341.  
  342. Figure 4. NTP Message Header    50
  343.  
  344. Figure 5. NTP Control Message Header    54
  345.  
  346. Figure 6. Status Word Formats   55
  347.  
  348. Figure 7. Authenticator Format  63
  349.  
  350. Figure 8. Comparison of UTC and NTP Timescales at Leap  79
  351.  
  352. Figure 9. Network Time Protocol 80
  353.  
  354. Figure 10. Hardware Clock Models        86
  355.  
  356. Figure 11. Clock Adjustment Process     90
  357.  
  358. Figure 12. NTP Phase-Lock Loop (PLL) Model      91
  359.  
  360. Figure 13. Timing Intervals     96
  361.  
  362. Figure 14. Measuring Delay and Offset   100
  363.  
  364. Figure 15. Error Accumulations  103
  365.  
  366. Figure 16. Confidence Intervals and Intersections       105
  367.  
  368. List of Tables
  369.  
  370. Table 1. System Variables       12
  371.  
  372. Table 2. Peer Variables 13
  373.  
  374. Table 3. Packet Variables       14
  375.  
  376. Table 4. Parameters     16
  377.  
  378. Table 5. Modes and Actions      22
  379.  
  380. Table 6. Clock Parameters       40
  381.  
  382. Table 7. Characteristics of Standard Oscillators        71
  383.  
  384. Table 8. Table of Leap-Second Insertions        77
  385.  
  386. Table 9. Notation Used in PLL Analysis  91
  387.  
  388. Table 10. PLL Parameters        91
  389.  
  390. Table 11. Notation Used in PLL Analysis 95
  391.  
  392. Table 12. Notation Used in Error Analysis       98
  393.  
  394. Introduction
  395. This document constitutes a formal specification of the Network Time
  396. Protocol (NTP) Version 3, which is used to synchronize timekeeping among
  397. a set of distributed time servers and clients. It defines the
  398. architectures, algorithms, entities and protocols used by NTP and is
  399. intended primarily for implementors. A companion document [MIL91a]
  400. summarizes the requirements, analytical models, algorithmic analysis and
  401. performance under typical Internet conditions. Another document [MIL91b]
  402. describes the NTP timescale and its relationship to other standard
  403. timescales now in use. NTP was first described in RFC-958 [MIL85c], but
  404. has since evolved in significant ways, culminating in the most recent
  405. NTP Version 2 described in RFC-1119 [MIL89]. It is built on the Internet
  406. Protocol (IP) [DAR81a] and User Datagram Protocol (UDP) [POS80], which
  407. provide a connectionless transport mechanism; however, it is readily
  408. adaptable to other protocol suites. NTP is evolved from the Time
  409. Protocol [POS83b] and the ICMP Timestamp message [DAR81b], but is
  410. specifically designed to maintain accuracy and robustness, even when
  411. used over typical Internet paths involving multiple gateways, highly
  412. dispersive delays and unreliable nets.
  413.  
  414. The service environment consists of the implementation model and service
  415. model described in Section 2. The implementation model is based on a
  416. multiple-process operating system architecture, although other
  417. architectures could be used as well. The service model is based on a
  418. returnable-time design which depends only on measured clock offsets, but
  419. does not require reliable message delivery. The synchronization subnet
  420. uses a self-organizing, hierarchical-master-slave configuration, with
  421. synchronization paths determined by a minimum-weight spanning tree.
  422. While multiple masters (primary servers) may exist, there is no
  423. requirement for an election protocol.
  424.  
  425. NTP itself is described in Section 3. It provides the protocol
  426. mechanisms to synchronize time in principle to precisions in the order
  427. of nanoseconds while preserving a non-ambiguous date well into the next
  428. century. The protocol includes provisions to specify the characteristics
  429. and estimate the error of the local clock and the time server to which
  430. it may be synchronized. It also includes provisions for operation with a
  431. number of mutually suspicious, hierarchically distributed primary
  432. reference sources such as radio-synchronized clocks.
  433.  
  434. Section 4 describes algorithms useful for deglitching and smoothing
  435. clock-offset samples collected on a continuous basis. These algorithms
  436. evolved from those suggested in [MIL85a], were refined as the results of
  437. experiments described in [MIL85b] and further evolved under typical
  438. operating conditions over the last three years. In addition, as the
  439. result of experience in operating multiple-server subnets including
  440. radio clocks at several sites in the U.S. and with clients in the U.S.
  441. and Europe, reliable algorithms for selecting good clocks from a
  442. population possibly including broken ones have been developed [DEC89],
  443. [MIL91a] and are described in Section 4.
  444.  
  445. The accuracies achievable by NTP depend strongly on the precision of the
  446. local-clock hardware and stringent control of device and process
  447. latencies. Provisions must be included to adjust the software logical-
  448. clock time and frequency in response to corrections produced by NTP.
  449. Section 5 describes a local-clock design evolved from the Fuzzball
  450. implementation described in [MIL83b] and [MIL88b]. This design includes
  451. offset-slewing, frequency compensation and deglitching mechanisms
  452. capable of accuracies in the order of a millisecond, even after extended
  453. periods when synchronization to primary reference sources has been lost.
  454.  
  455. Details specific to NTP packet formats used with the Internet Protocol
  456. (IP) and User Datagram Protocol (UDP) are presented in Appendix A, while
  457. details of a suggested auxiliary NTP Control Message, which may be used
  458. when comprehensive network-monitoring facilities are not available, are
  459. presented in Appendix B. Appendix C contains specification and
  460. implementation details of an optional authentication mechanism which can
  461. be used to control access and prevent unauthorized data modification,
  462. while Appendix D contains a listing of differences between Version 3 of
  463. NTP and previous versions. Appendix E expands on issues involved with
  464. precision timescales and calendar dating peculiar to computer networks
  465. and NTP. Appendix F describes an optional algorithm to improve accuracy
  466. by combining the time offsets of a number of clocks. Appendix G presents
  467. a detailed mathematical model and analysis of the NTP local-clock
  468. algorithms. Appendix H analyzes the sources and propagation of errors
  469. and presents correctness principles relating to the time-transfer
  470. service. Appendix I illustrates C-language code segments for the clock-
  471. filter, clock-selection and related algorithms described in Section 4.
  472.  
  473. Related Technology
  474.  
  475. Other mechanisms have been specified in the Internet protocol suite to
  476. record and transmit the time at which an event takes place, including
  477. the Daytime protocol [POS83a], Time Protocol [POS83b], ICMP Timestamp
  478. message [DAR81b] and IP Timestamp option [SU81]. Experimental results on
  479. measured clock offsets and roundtrip delays in the Internet are
  480. discussed in [MIL83a], [MIL85b], [COL88] and [MIL88a]. Other
  481. synchronization algorithms are discussed in [LAM78], [GUS84], [HAL84],
  482. [LUN84], [LAM85], [MAR85], [MIL85a], [MIL85b], [MIL85c], [GUS85b],
  483. [SCH86], [TRI86], [RIC88], [MIL88a], [DEC89] and [MIL91a], while
  484. protocols based on them are described in [MIL81a], [MIL81b], [MIL83b],
  485. [GUS85a], [MIL85c], [TRI86], [MIL88a], [DEC89] and [MIL91a]. NTP uses
  486. techniques evolved from them and both linear-systems and agreement
  487. methodologies. Linear methods for digital telephone network
  488. synchronization are summarized in [LIN80], while agreement methods for
  489. clock synchronization are summarized in [LAM85].
  490.  
  491. The Digital Time Service (DTS) [DEC89] has many of the same service
  492. objectives as NTP. The DTS design places heavy emphasis on configuration
  493. management and correctness principles when operated in a managed LAN or
  494. LAN-cluster environment, while NTP places heavy emphasis on the accuracy
  495. and stability of the service operated in an unmanaged, global-internet
  496. environment. In DTS a synchronization subnet consists of clerks,
  497. servers, couriers and time providers. With respect to the NTP
  498. nomenclature, a time provider is a primary reference source, a courier
  499. is a secondary server intended to import time from one or more distant
  500. primary servers for local redistribution and a server is intended to
  501. provide time for possibly many end nodes or clerks. Unlike NTP, DTS does
  502. not need or use mode or stratum information in clock selection and does
  503. not include provisions to filter timing noise, select the most accurate
  504. from a set of presumed correct clocks or compensate for inherent
  505. frequency errors.
  506.  
  507. In fact, the latest revisions in NTP have adopted certain features of
  508. DTS in order to support correctness principles. These include mechanisms
  509. to bound the maximum errors inherent in the time-transfer procedures and
  510. the use of a provably correct (subject to stated assumptions) mechanism
  511. to reject inappropriate peers in the clock-selection procedures. These
  512. features are described in Section 4 and Appendix H of this document.
  513.  
  514. The Fuzzball routing protocol [MIL83b], sometimes called Hellospeak,
  515. incorporates time synchronization directly into the routing-protocol
  516. design. One or more processes synchronize to an external reference
  517. source, such as a radio clock or NTP daemon, and the routing algorithm
  518. constructs a minimum-weight spanning tree rooted on these processes. The
  519. clock offsets are then distributed along the arcs of the spanning tree
  520. to all processes in the system and the various process clocks corrected
  521. using the procedure described in Section 5 of this document. While it
  522. can be seen that the design of Hellospeak strongly influenced the design
  523. of NTP, Hellospeak itself is not an Internet protocol and is unsuited
  524. for use outside its local-net environment.
  525.  
  526. The Unix 4.3bsd time daemon timed [GUS85a] uses a single master-time
  527. daemon to measure offsets of a number of slave hosts and send periodic
  528. corrections to them. In this model the master is determined using an
  529. election algorithm [GUS85b] designed to avoid situations where either no
  530. master is elected or more than one master is elected. The election
  531. process requires a broadcast capability, which is not a ubiquitous
  532. feature of the Internet. While this model has been extended to support
  533. hierarchical configurations in which a slave on one network serves as a
  534. master on the other [TRI86], the model requires handcrafted
  535. configuration tables in order to establish the hierarchy and avoid
  536. loops. In addition to the burdensome, but presumably infrequent,
  537. overheads of the election process, the offset measurement/correction
  538. process requires twice as many messages as NTP per update.
  539.  
  540. A scheme with features similar to NTP is described in [KOP87]. This
  541. scheme is intended for multi-server LANs where each of a set of possibly
  542. many time servers determines its local-time offset relative to each of
  543. the other servers in the set using periodic timestamped messages, then
  544. determines the local-clock correction using the Fault-Tolerant Average
  545. (FTA) algorithm of [LUN84]. The FTA algorithm, which is useful where up
  546. to k servers may be faulty, sorts the offsets, discards the k highest
  547. and lowest ones and averages the rest. The scheme, as described in
  548. [SCH86], is most suitable to LAN environments which support broadcast
  549. and would result in unacceptable overhead in an internet environment. In
  550. addition, for reasons given in Section 4 of this paper, the statistical
  551. properties of the FTA algorithm are not likely to be optimal in an
  552. internet environment with highly dispersive delays.
  553.  
  554. A good deal of research has gone into the issue of maintaining accurate
  555. time in a community where some clocks cannot be trusted. A truechimer is
  556. a clock that maintains timekeeping accuracy to a previously published
  557. (and trusted) standard, while a falseticker is a clock that does not.
  558. Determining whether a particular clock is a truechimer or falseticker is
  559. an interesting abstract problem which can be attacked using agreement
  560. methods summarized in [LAM85] and [SRI87].
  561.  
  562. A convergence function operates upon the offsets between the clocks in a
  563. system to increase the accuracy by reducing or eliminating errors caused
  564. by falsetickers. There are two classes of convergence functions, those
  565. involving interactive-convergence algorithms and those involving
  566. interactive-consistency algorithms. Interactive-convergence algorithms
  567. use statistical clustering techniques such as the fault-tolerant average
  568. algorithm of [HAL84], the CNV algorithm of [LUN84], the majority-subset
  569. algorithm of [MIL85a], the non-Byzantine algorithm of [RIC88], the
  570. egocentric algorithm of [SCH86], the intersection algorithm of [MAR85]
  571. and [DEC89] and the algorithms in Section 4 of this document.
  572.  
  573. Interactive-consistency algorithms are designed to detect faulty clock
  574. processes which might indicate grossly inconsistent offsets in
  575. successive readings or to different readers. These algorithms use an
  576. agreement protocol involving successive rounds of readings, possibly
  577. relayed and possibly augmented by digital signatures. Examples include
  578. the fireworks algorithm of [HAL84] and the optimum algorithm of [SRI87].
  579. However, these algorithms require large numbers of messages, especially
  580. when large numbers of clocks are involved, and are designed to detect
  581. faults that have rarely been found in the Internet experience. For these
  582. reasons they are not considered further in this document.
  583.  
  584. In practice it is not possible to determine the truechimers from the
  585. falsetickers on other than a statistical basis, especially with
  586. hierarchical configurations and a statistically noisy Internet. While it
  587. is possible to bound the maximum errors in the time-transfer procedures,
  588. assuming sufficiently generous tolerances are adopted for the hardware
  589. components, this generally results in rather poor accuracies and
  590. stabilities. The approach taken in the NTP design and its predecessors
  591. involves mutually coupled oscillators and maximum-likelihood estimation
  592. and clock-selection procedures, together with a design that allows
  593. provable assertions on error bounds to be made relative to stated
  594. assumptions on the correctness of the primary reference sources. From
  595. the analytical point of view, the system of distributed NTP peers
  596. operates as a set of coupled phase-locked oscillators, with the update
  597. algorithm functioning as a phase detector and the local clock as a
  598. disciplined oscillator, but with deterministic error bounds calculated
  599. at each step in the time-transfer process.
  600.  
  601. The particular choice of offset measurement and computation procedure
  602. described in Section 3 is a variant of the returnable-time system used
  603. in some digital telephone networks [LIN80]. The clock filter and
  604. selection algorithms are designed so that the clock synchronization
  605. subnet self-organizes into a hierarchical-master-slave configuration
  606. [MIT80]. With respect to timekeeping accuracy and stability, the
  607. similarity of NTP to digital telephone systems is not accidental, since
  608. systems like this have been studied extensively [LIN80], [BRA80]. What
  609. makes the NTP model unique is the adaptive configuration, polling,
  610. filtering, selection and correctness mechanisms which tailor the
  611. dynamics of the system to fit the ubiquitous Internet environment.
  612.  
  613. System Architecture
  614.  
  615. In the NTP model a number of primary reference sources, synchronized by
  616. wire or radio to national standards, are connected to widely accessible
  617. resources, such as backbone gateways, and operated as primary time
  618. servers. The purpose of NTP is to convey timekeeping information from
  619. these servers to other time servers via the Internet and also to cross-
  620. check clocks and mitigate errors due to equipment or propagation
  621. failures. Some number of local-net hosts or gateways, acting as
  622. secondary time servers, run NTP with one or more of the primary servers.
  623. In order to reduce the protocol overhead, the secondary servers
  624. distribute time via NTP to the remaining local-net hosts. In the
  625. interest of reliability, selected hosts can be equipped with less
  626. accurate but less expensive radio clocks and used for backup in case of
  627. failure of the primary and/or secondary servers or communication paths
  628. between them.
  629.  
  630. Throughout this document a standard nomenclature has been adopted: the
  631. stability of a clock is how well it can maintain a constant frequency,
  632. the accuracy is how well its frequency and time compare with national
  633. standards and the precision is how precisely these quantities can be
  634. maintained within a particular timekeeping system. Unless indicated
  635. otherwise, the offset of two clocks is the time difference between them,
  636. while the skew is the frequency difference (first derivative of offset
  637. with time) between them. Real clocks exhibit some variation in skew
  638. (second derivative of offset with time), which is called drift; however,
  639. in this version of the specification the drift is assumed zero.
  640.  
  641. NTP is designed to produce three products: clock offset, roundtrip delay
  642. and dispersion, all of which are relative to a selected reference clock.
  643. Clock offset represents the amount to adjust the local clock to bring it
  644. into correspondence with the reference clock. Roundtrip delay provides
  645. the capability to launch a message to arrive at the reference clock at a
  646. specified time. Dispersion represents the maximum error of the local
  647. clock relative to the reference clock. Since most host time servers will
  648. synchronize via another peer time server, there are two components in
  649. each of these three products, those determined by the peer relative to
  650. the primary reference source of standard time and those measured by the
  651. host relative to the peer. Each of these components are maintained
  652. separately in the protocol in order to facilitate error control and
  653. management of the subnet itself. They provide not only precision
  654. measurements of offset and delay, but also definitive maximum error
  655. bounds, so that the user interface can determine not only the time, but
  656. the quality of the time as well.
  657.  
  658. There is no provision for peer discovery or virtual-circuit management
  659. in NTP. Data integrity is provided by the IP and UDP checksums. No flow-
  660. control or retransmission facilities are provided or necessary.
  661. Duplicate detection is inherent in the processing algorithms. The
  662. service can operate in a symmetric mode, in which servers and clients
  663. are indistinguishable, yet maintain a small amount of state information,
  664. or in client/server mode, in which servers need maintain no state other
  665. than that contained in the client request. A lightweight association-
  666. management capability, including dynamic reachability and variable poll-
  667. rate mechanisms, is included only to manage the state information and
  668. reduce resource requirements. Since only a single NTP message format is
  669. used, the protocol is easily implemented and can be used in a variety of
  670. solicited or unsolicited polling mechanisms.
  671.  
  672. It should be recognized that clock synchronization requires by its
  673. nature long periods and multiple comparisons in order to maintain
  674. accurate timekeeping. While only a few measurements are usually adequate
  675. to reliably determine local time to within a second or so, periods of
  676. many hours and dozens of measurements are required to resolve oscillator
  677. skew and maintain local time to the order of a millisecond. Thus, the
  678. accuracy achieved is directly dependent on the time taken to achieve it.
  679. Fortunately, the frequency of measurements can be quite low and almost
  680. always non-intrusive to normal net operations.
  681.  
  682. Implementation Model
  683.  
  684. In what may be the most common client/server model a client sends an NTP
  685. message to one or more servers and processes the replies as received.
  686. The server interchanges addresses and ports, overwrites certain fields
  687. in the message, recalculates the checksum and returns the message
  688. immediately. Information included in the NTP message allows the client
  689. to determine the server time with respect to local time and adjust the
  690. local clock accordingly. In addition, the message includes information
  691. to calculate the expected timekeeping accuracy and reliability, as well
  692. as select the best from possibly several servers.
  693.  
  694. While the client/server model may suffice for use on local nets
  695. involving a public server and perhaps many workstation clients, the full
  696. generality of NTP requires distributed participation of a number of
  697. client/servers or peers arranged in a dynamically reconfigurable,
  698. hierarchically distributed configuration. It also requires sophisticated
  699. algorithms for association management, data manipulation and local-clock
  700. control. Throughout the remainder of this document the term host refers
  701. to an instantiation of the protocol on a local processor, while the term
  702. peer refers to the instantiation of the protocol on a remote processor
  703. connected by a network path.
  704.  
  705. Figure 1<$&fig1> shows an implementation model for a host including
  706. three processes sharing a partitioned data base, with a partition
  707. dedicated to each peer, and interconnected by a message-passing system.
  708. The transmit process, driven by independent timers for each peer,
  709. collects information in the data base and sends NTP messages to the
  710. peers. Each message contains the local timestamp when the message is
  711. sent, together with previously received timestamps and other information
  712. necessary to determine the hierarchy and manage the association. The
  713. message transmission rate is determined by the accuracy required of the
  714. local clock, as well as the accuracies of its peers.
  715.  
  716. The receive process receives NTP messages and perhaps messages in other
  717. protocols, as well as information from directly connected radio clocks.
  718. When an NTP message is received, the offset between the peer clock and
  719. the local clock is computed and incorporated into the data base along
  720. with other information useful for error determination and peer
  721. selection. A filtering algorithm described in Section 4 improves the
  722. accuracy by discarding inferior data.
  723.  
  724. The update procedure is initiated upon receipt of a message and at other
  725. times. It processes the offset data from each peer and selects the best
  726. one using the algorithms of Section 4. This may involve many
  727. observations of a few peers or a few observations of many peers,
  728. depending on the accuracies required.
  729.  
  730. The local-clock process operates upon the offset data produced by the
  731. update procedure and adjusts the phase and frequency of the local clock
  732. using the mechanisms described in Section 5. This may result in either a
  733. step-change or a gradual phase adjustment of the local clock to reduce
  734. the offset to zero. The local clock provides a stable source of time
  735. information to other users of the system and for subsequent reference by
  736. NTP itself.
  737.  
  738. Network Configurations
  739.  
  740. The synchronization subnet is a connected network of primary and
  741. secondary time servers, clients and interconnecting transmission paths.
  742. A primary time server is directly synchronized to a primary reference
  743. source, usually a radio clock. A secondary time server derives
  744. synchronization, possibly via other secondary servers, from a primary
  745. server over network paths possibly shared with other services. Under
  746. normal circumstances it is intended that the synchronization subnet of
  747. primary and secondary servers assumes a hierarchical-master-slave
  748. configuration with the primary servers at the root and secondary servers
  749. of decreasing accuracy at successive levels toward the leaves.
  750.  
  751. Following conventions established by the telephone industry [BEL86], the
  752. accuracy of each server is defined by a number called the stratum, with
  753. the topmost level (primary servers) assigned as one and each level
  754. downwards (secondary servers) in the hierarchy assigned as one greater
  755. than the preceding level. With current technology and available radio
  756. clocks, single-sample accuracies in the order of a millisecond can be
  757. achieved at the network interface of a primary server. Accuracies of
  758. this order require special care in the design and implementation of the
  759. operating system and the local-clock mechanism, such as described in
  760. Section 5.
  761.  
  762. As the stratum increases from one, the single-sample accuracies
  763. achievable will degrade depending on the network paths and local-clock
  764. stabilities. In order to avoid the tedious calculations [BRA80]
  765. necessary to estimate errors in each specific configuration, it is
  766. useful to assume the mean measurement errors accumulate approximately in
  767. proportion to the measured delay and dispersion relative to the root of
  768. the synchronization subnet. Appendix H contains an analysis of errors,
  769. including a derivation of maximum error as a function of delay and
  770. dispersion, where the latter quantity depends on the precision of the
  771. timekeeping system, frequency tolerance of the local clock and various
  772. residuals. Assuming the primary servers are synchronized to standard
  773. time within known accuracies, this provides a reliable, determistic
  774. specification on timekeeping accuracies throughout the synchronization
  775. subnet.
  776.  
  777. Again drawing from the experience of the telephone industry, which
  778. learned such lessons at considerable cost [ABA89], the synchronization
  779. subnet topology should be organized to produce the highest accuracy, but
  780. must never be allowed to form a loop. An additional factor is that each
  781. increment in stratum involves a potentially unreliable time server which
  782. introduces additional measurement errors. The selection algorithm used
  783. in NTP uses a variant of the Bellman-Ford distributed routing algorithm
  784. [37] to compute the minimum-weight spanning trees rooted on the primary
  785. servers. The distance metric used by the algorithm consists of the
  786. (scaled) stratum plus the synchronization distance, which itself
  787. consists of the dispersion plus one-half the absolute delay. Thus, the
  788. synchronization path will always take the minimum number of servers to
  789. the root, with ties resolved on the basis of maximum error.
  790.  
  791. As a result of this design, the subnet reconfigures automatically in a
  792. hierarchical-master-slave configuration to produce the most accurate and
  793. reliable time, even when one or more primary or secondary servers or the
  794. network paths between them fail. This includes the case where all normal
  795. primary servers (e.g., highly accurate WWVB radio clock operating at the
  796. lowest synchronization distances) on a possibly partitioned subnet fail,
  797. but one or more backup primary servers (e.g., less accurate WWV radio
  798. clock operating at higher synchronization distances) continue operation.
  799. However, should all primary servers throughout the subnet fail, the
  800. remaining secondary servers will synchronize among themselves while
  801. distances ratchet upwards to a preselected maximum <169>infinity<170>
  802. due to the well-known properties of the Bellman-Ford algorithm. Upon
  803. reaching the maximum on all paths, a server will drop off the subnet and
  804. free-run using its last determined time and frequency. Since these
  805. computations are expected to be very precise, especially in frequency,
  806. even extended outage periods can result in timekeeping errors not
  807. greater than a few milliseconds per day with appropriately stabilized
  808. oscillators (see Section 5).
  809.  
  810. In the case of multiple primary servers, the spanning-tree computation
  811. will usually select the server at minimum synchronization distance.
  812. However, when these servers are at approximately the same distance, the
  813. computation may result in random selections among them as the result of
  814. normal dispersive delays. Ordinarily, this does not degrade accuracy as
  815. long as any discrepancy between the primary servers is small compared to
  816. the synchronization distance. If not, the filter and selection
  817. algorithms will select the best of the available servers and cast out
  818. outlyers as intended.
  819.  
  820. Network Time Protocol
  821.  
  822. This section consists of a formal definition of the Network Time
  823. Protocol, including its data formats, entities, state variables, events
  824. and event-processing procedures. The specification is based on the
  825. implementation model illustrated in Figure 1, but it is not intended
  826. that this model is the only one upon which a specification can be based.
  827. In particular, the specification is intended to illustrate and clarify
  828. the intrinsic operations of NTP, as well as to serve as a foundation for
  829. a more rigorous, comprehensive and verifiable specification.
  830.  
  831. Data Formats
  832.  
  833. All mathematical operations expressed or implied herein are in two's-
  834. complement, fixed-point arithmetic. Data are specified as integer or
  835. fixed-point quantities, with bits numbered in big-endian fashion from
  836. zero starting at the left, or high-order, position. Since various
  837. implementations may scale externally derived quantities for internal
  838. use, neither the precision nor decimal-point placement for fixed-point
  839. quantities is specified. Unless specified otherwise, all quantities are
  840. unsigned and may occupy the full field width with an implied zero
  841. preceding bit zero. Hardware and software packages designed to work with
  842. signed quantities will thus yield surprising results when the most
  843. significant (sign) bit is set. It is suggested that externally derived,
  844. unsigned fixed-point quantities such as timestamps be shifted right one
  845. bit for internal use, since the precision represented by the full field
  846. width is seldom justified.
  847.  
  848. Since NTP timestamps are cherished data and, in fact, represent the main
  849. product of the protocol, a special timestamp format has been
  850. established. NTP timestamps are represented as a 64-bit unsigned fixed-
  851. point number, in seconds relative to 0h on 1 January 1900. The integer
  852. part is in the first 32 bits and the fraction part in the last 32 bits.
  853. This format allows convenient multiple-precision arithmetic and
  854. conversion to Time Protocol representation (seconds), but does
  855. complicate the conversion to ICMP Timestamp message representation
  856. (milliseconds). The precision of this representation is about 200
  857. picoseconds, which should be adequate for even the most exotic
  858. requirements.
  859.  
  860. Timestamps are determined by copying the current value of the local
  861. clock to a timestamp when some significant event, such as the arrival of
  862. a message, occurs. In order to maintain the highest accuracy, it is
  863. important that this be done as close to the hardware or software driver
  864. associated with the event as possible. In particular, departure
  865. timestamps should be redetermined for each link-level retransmission. In
  866. some cases a particular timestamp may not be available, such as when the
  867. host is rebooted or the protocol first starts up. In these cases the 64-
  868. bit field is set to zero, indicating the value is invalid or undefined.
  869.  
  870. Note that since some time in 1968 the most significant bit (bit 0 of the
  871. integer part) has been set and that the 64-bit field will overflow some
  872. time in 2036. Should NTP be in use in 2036, some external means will be
  873. necessary to qualify time relative to 1900 and time relative to 2036
  874. (and other multiples of 136 years). Timestamped data requiring such
  875. qualification will be so precious that appropriate means should be
  876. readily available. There will exist an 200-picosecond interval,
  877. henceforth ignored, every 136 years when the 64-bit field will be zero
  878. and thus considered invalid.
  879.  
  880. State Variables and Parameters
  881.  
  882. Following is a summary of the various state variables and parameters
  883. used by the protocol. They are separated into classes of system
  884. variables, which relate to the operating system environment and local-
  885. clock mechanism; peer variables, which represent the state of the
  886. protocol machine specific to each peer; packet variables, which
  887. represent the contents of the NTP message; and parameters, which
  888. represent fixed configuration constants for all implementations of the
  889. current version. For each class the description of the variable is
  890. followed by its name and the procedure or value which controls it. Note
  891. that variables are in lower case, while parameters are in upper case.
  892. Additional details on formats and use are presented in later sections
  893. and Appendices.
  894.  
  895. Common Variables
  896.  
  897. The following variables are common to two or more of the system, peer
  898. and packet classes. Additional variables are specific to the optional
  899. authentication mechanism as described in Appendix C. When necessary to
  900. distinguish between common variables of the same name, the variable
  901. identifier will be used.
  902.  
  903. Peer Address (peer.peeraddr, pkt.peeraddr), Peer Port (peer.peerport,
  904. pkt.peerport): These are the 32-bit Internet address and 16-bit port
  905. number of the peer.
  906.  
  907. Host Address (peer.hostaddr, pkt.hostaddr), Host Port (peer.hostport,
  908. pkt.hostport): These are the 32-bit Internet address and 16-bit port
  909. number of the host. They are included among the state variables to
  910. support multi-homing.
  911.  
  912. Leap Indicator (sys.leap, peer.leap, pkt.leap): This is a two-bit code
  913. warning of an impending leap second to be inserted in the NTP timescale.
  914. The bits are set before 23:59 on the day of insertion and reset after
  915. 00:00 on the following day. This causes the number of seconds (rollover
  916. interval) in the day of insertion to be increased or decreased by one.
  917. In the case of primary servers the bits are set by operator
  918. intervention, while in the case of secondary servers the bits are set by
  919. the protocol. The two bits, bit 0 and bit 1, respectively, are coded as
  920. follows:
  921. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  922. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  923.  
  924. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  925.  
  926. 00, no warning
  927.  
  928. 01, last minute has 61 seconds
  929.  
  930. 10, last minute has 59 seconds
  931.  
  932. 11, alarm condition (clock not synchronized)
  933.  
  934. @Z_TBL_END =
  935.  
  936. In all except the alarm condition (112), NTP itself does nothing with
  937. these bits, except pass them on to the time-conversion routines that are
  938. not part of NTP. The alarm condition occurs when, for whatever reason,
  939. the local clock is not synchronized, such as when first coming up or
  940. after an extended period when no primary reference source is available.
  941.  
  942. Mode (peer.mode, pkt.mode): This is an integer indicating the
  943. association mode, with values coded as follows:
  944.  
  945. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  946. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  947.  
  948. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  949.  
  950. 0, unspecified
  951.  
  952. 1, symmetric active
  953.  
  954. 2, symmetric passive
  955.  
  956. 3, client
  957.  
  958. 4, server
  959.  
  960. 5, broadcast
  961.  
  962. 6, reserved for NTP control messages
  963.  
  964. 7, reserved for private use
  965.  
  966. @Z_TBL_END =
  967.  
  968. Stratum (sys.stratum, peer.stratum, pkt.stratum): This is an integer
  969. indicating the stratum of the local clock, with values defined as
  970. follows:
  971.  
  972. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  973. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  974.  
  975. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  976.  
  977. 0, unspecified
  978.  
  979. 1, primary reference (e.g.,, calibrated atomic clock,, radio clock)
  980.  
  981. 2-255, secondary reference (via NTP)
  982.  
  983. @Z_TBL_END =
  984.  
  985. For comparison purposes a value of zero is considered greater than any
  986. other value. Note that the maximum value of the integer encoded as a
  987. packet variable is limited by the parameter NTP.MAXSTRATUM.
  988.  
  989. Poll Interval (sys.poll, peer.hostpoll, peer.peerpoll, pkt.poll): This
  990. is a signed integer indicating the minimum interval between transmitted
  991. messages, in seconds as a power of two. For instance, a value of six
  992. indicates a minimum interval of 64 seconds.
  993.  
  994. Precision (sys.precision, peer.precision, pkt.precision): This is a
  995. signed integer indicating the precision of the various clocks, in
  996. seconds to the nearest power of two. The value must be rounded to the
  997. next larger power of two; for instance, a 50-Hz (20 ms) or 60-Hz (16.67
  998. ms) power-frequency clock would be assigned the value -5 (31.25 ms),
  999. while a 1000-Hz (1 ms) crystal-controlled clock would be assigned the
  1000. value -9 (1.95 ms).
  1001.  
  1002. Root Delay (sys.rootdelay, peer.rootdelay, pkt.rootdelay): This is a
  1003. signed fixed-point number indicating the total roundtrip delay to the
  1004. primary reference source at the root of the synchronization subnet, in
  1005. seconds. Note that this variable can take on both positive and negative
  1006. values, depending on clock precision and skew.
  1007.  
  1008. Root Dispersion (sys.rootdispersion, peer.rootdispersion,
  1009. pkt.rootdispersion): This is a signed fixed-point number indicating the
  1010. maximum error relative to the primary reference source at the root of
  1011. the synchronization subnet, in seconds. Only positive values greater
  1012. than zero are possible.
  1013.  
  1014. Reference Clock Identifier (sys.refid, peer.refid, pkt.refid): This is a
  1015. 32-bit code identifying the particular reference clock. In the case of
  1016. stratum 0 (unspecified) or stratum 1 (primary reference source), this is
  1017. a four-octet, left-justified, zero-padded ASCII string, for example (see
  1018. Appendix A for comprehensive list):
  1019.  
  1020. @Z_TBL_BEG = COLUMNS(3), DIMENSION(IN), COLWIDTHS(E2,E2,E5),
  1021. WIDTH(4.1700), ABOVE(.1670), BELOW(.0830), HGUTTER(.3330),
  1022. BOX(Z_SINGLE), KEEP(ON), ALIGN(CT), L1(R1C0..R1C3)
  1023.  
  1024. @Z_TBL_BODY = TABLE CENTER, TABLE HEADER, TABLE HEADER
  1025.  
  1026. Stratum, Code, Meaning
  1027.  
  1028. @Z_TBL_BODY = TABLE CENTER, TABLE TEXT, TABLE TEXT
  1029.  
  1030. 0, DCN, DCN routing protocol
  1031.  
  1032. 0, TSP, TSP time protocol
  1033.  
  1034. 1, ATOM, Atomic clock (calibrated)
  1035.  
  1036. 1, WWVB, WWVB LF (band 5) radio
  1037.  
  1038. 1, GOES, GOES UHF (band 9) satellite
  1039.  
  1040. @Z_TBL_BODY = TABLE CENTER, TABLE HEADER, TABLE HEADER
  1041.  
  1042. 1, WWV, WWV HF (band 7) radio
  1043.  
  1044. @Z_TBL_END =
  1045.  
  1046. In the case of stratum 2 and greater (secondary reference) this is the
  1047. four-octet Internet address of the peer selected for synchronization.
  1048.  
  1049. Reference Timestamp (sys.reftime, peer.reftime, pkt.reftime): This is
  1050. the local time, in timestamp format, when the local clock was last
  1051. updated. If the local clock has never been synchronized, the value is
  1052. zero.
  1053.  
  1054. Originate Timestamp (peer.org, pkt.org): This is the local time, in
  1055. timestamp format, at the peer when its latest NTP message was sent. If
  1056. the peer becomes unreachable the value is set to zero.
  1057.  
  1058. Receive Timestamp (peer.rec, pkt.rec): This is the local time, in
  1059. timestamp format, when the latest NTP message from the peer arrived. If
  1060. the peer becomes unreachable the value is set to zero.
  1061.  
  1062. Transmit Timestamp (peer.xmt, pkt.xmt): This is the local time, in
  1063. timestamp format, at which the NTP message departed the sender.
  1064.  
  1065. System Variables
  1066.  
  1067. Table 1<$&tab1> shows the complete set of system variables. In addition
  1068. to the common variables described previously, the following variables
  1069. are used by the operating system in order to synchronize the local
  1070. clock.
  1071.  
  1072. Local Clock (sys.clock): This is the current local time, in timestamp
  1073. format. Local time is derived from the hardware clock of the particular
  1074. machine and increments at intervals depending on the design used. An
  1075. appropriate design, including slewing and skew-Compensation mechanisms,
  1076. is described in Section 5.
  1077.  
  1078. Clock Source (sys.peer): This is a selector identifying the current
  1079. synchronization source. Usually this will be a pointer to a structure
  1080. containing the peer variables. The special value NULL indicates there is
  1081. no currently valid synchronization source.
  1082.  
  1083. Peer Variables
  1084.  
  1085. Table 2 shows the complete set of peer variables. In addition to the
  1086. common variables described previously, the following variables are used
  1087. by the peer management and measurement functions.
  1088.  
  1089. Configured Bit (peer.config): This is a bit indicating that the
  1090. association was created from configuration information and should not be
  1091. demobilized if the peer becomes unreachable.
  1092.  
  1093. Update Timestamp (peer.update): This is the local time, in timestamp
  1094. format, when the most recent NTP message was received. It is used in
  1095. calculating the skew dispersion.
  1096.  
  1097. Reachability Register (peer.reach): This is a shift register of
  1098. NTP.WINDOW bits used to determine the reachability status of the peer,
  1099. with bits entering from the least significant (rightmost) end. A peer is
  1100. considered reachable if at least one bit in this register is set to one.
  1101.  
  1102. Peer Timer (peer.timer): This is an integer counter used to control the
  1103. interval between transmitted NTP messages. Once set to a nonzero value,
  1104. the counter decrements at one-second intervals until reaching zero, at
  1105. which time the transmit procedure is called. Note that the operation of
  1106. this timer is independent of local-clock updates, which implies that the
  1107. timekeeping system and interval-timer system architecture must be
  1108. independent of each other.<$&tab2>
  1109.  
  1110. Packet Variables
  1111.  
  1112. Table 3<$&tab3> shows the complete set of packet variables. In addition
  1113. to the common variables described previously, the following variables
  1114. are defined.
  1115.  
  1116. Version Number (pkt.version): This is an integer indicating the version
  1117. number of the sender. NTP messages will always be sent with the current
  1118. version number NTP.VERSION and will always be accepted if the version
  1119. number matches NTP.VERSION. Exceptions may be advised on a case-by-case
  1120. basis at times when the version number is changed. Specific guidelines
  1121. for interoperation between this version and previous versions of NTP are
  1122. summarized in Appendix D.
  1123.  
  1124. Clock-Filter Variables
  1125.  
  1126. When the filter and selection algorithms suggested in Section 4 are
  1127. used, the following state variables are defined in addition to the
  1128. variables described previously.
  1129.  
  1130. Filter Register (peer.filter): This is a shift register of NTP.SHIFT
  1131. stages, where each stage stores a 3-tuple consisting of the measured
  1132. delay, measured offset and calculated dispersion associated with a
  1133. single observation. These 3-tuples enter from the most significant
  1134. (leftmost) right and are shifted towards the least significant
  1135. (rightmost) end and eventually discarded as new observations arrive.
  1136.  
  1137. Valid Data Counter (peer.valid): This is an integer counter indicating
  1138. the valid samples remaining in the filter register. It is used to
  1139. determine the reachability state and when the poll interval should be
  1140. increased or decreased.
  1141.  
  1142. Offset (peer.offset): This is a signed, fixed-point number indicating
  1143. the offset of the peer clock relative to the local clock, in seconds.
  1144.  
  1145. Delay (peer.delay): This is a signed fixed-point number indicating the
  1146. roundtrip delay of the peer clock relative to the local clock over the
  1147. network path between them, in seconds. Note that this variable can take
  1148. on both positive and negative values, depending on clock precision and
  1149. skew-error accumulation.
  1150.  
  1151. Dispersion (peer.dispersion): This is a signed fixed-point number
  1152. indicating the maximum error of the peer clock relative to the local
  1153. clock over the network path between them, in seconds. Only positive
  1154. values greater than zero are possible.
  1155.  
  1156. Authentication Variables
  1157.  
  1158. When the authentication mechanism suggested in Appendix C is used, the
  1159. following state variables are defined in addition to the variables
  1160. described previously. These variables are used only if the optional
  1161. authentication mechanism described in Appendix C is implemented.
  1162.  
  1163. Authentication Enabled Bit (peer.authenable): This is a bit indicating
  1164. that the association is to operate in the authenticated mode.
  1165.  
  1166. Authenticated Bit (peer.authentic): This is a bit indicating that the
  1167. last message received from the peer has been correctly authenticated.
  1168.  
  1169. Key Identifier (peer.hostkeyid, peer.peerkeyid, pkt.keyid): This is an
  1170. integer identifying the cryptographic key used to generate the message-
  1171. authentication code.
  1172.  
  1173. Cryptographic Keys (sys.key): This is a set of 64-bit DES keys. Each key
  1174. is constructed as in the Berkeley Unix distributions, which consists of
  1175. eight octets, where the seven low-order bits of each octet correspond to
  1176. the DES bits 1-7 and the high-order bit corresponds to the DES odd-
  1177. parity bit 8.
  1178.  
  1179. Crypto-Checksum (pkt.check): This is a crypto-checksum computed by the
  1180. encryption procedure.
  1181.  
  1182. Parameters
  1183.  
  1184. Table 4<$&tab4> shows the parameters assumed for all implementations
  1185. operating in the Internet system. It is necessary to agree on the values
  1186. for these parameters in order to avoid unnecessary network overheads and
  1187. stable peer associations. The following parameters are assumed fixed and
  1188. applicable to all associations.
  1189.  
  1190. Version Number (NTP.VERSION): This is the current NTP version number
  1191. (3).
  1192.  
  1193. NTP Port (NTP.PORT): This is the port number (123) assigned by the
  1194. Internet Assigned Numbers Authority to NTP.
  1195.  
  1196. Maximum Stratum (NTP.MAXSTRATUM): This is the maximum stratum value that
  1197. can be encoded as a packet variable, also interpreted as
  1198. <169>infinity<170> or unreachable by the subnet routing algorithm.
  1199.  
  1200. Maximum Clock Age (NTP.MAXAGE): This is the maximum interval a reference
  1201. clock will be considered valid after its last update, in seconds.
  1202.  
  1203. Maximum Skew (NTP.MAXSKEW): This is the maximum offset error due to skew
  1204. of the local clock over the interval determined by NTP.MAXAGE, in
  1205. seconds. The ratio <$Ephi~=~roman {NTP.MAXSKEW over NTP.MAXAGE}> is
  1206. interpreted as the maximum possible skew rate due to all causes.
  1207.  
  1208. Maximum Distance (NTP.MAXDISTANCE): When the selection algorithm
  1209. suggested in Section 4 is used, this is the maximum synchronization
  1210. distance for peers acceptable for synchronization.
  1211.  
  1212. Minimum Poll Interval (NTP.MINPOLL): This is the minimum poll interval
  1213. allowed by any peer of the Internet system, in seconds to a power of
  1214. two.
  1215.  
  1216. Maximum Poll Interval (NTP.MAXPOLL): This is the maximum poll interval
  1217. allowed by any peer of the Internet system, in seconds to a power of
  1218. two.
  1219.  
  1220. Minimum Select Clocks (NTP.MINCLOCK): When the selection algorithm
  1221. suggested in Section 4 is used, this is the minimum number of peers
  1222. acceptable for synchronization.
  1223.  
  1224. Maximum Select Clocks (NTP.MAXCLOCK): When the selection algorithm
  1225. suggested in Section 4 is used, this is the maximum number of peers
  1226. considered for selection.
  1227.  
  1228. Minimum Dispersion (NTP.MINDISPERSE): When the filter algorithm
  1229. suggested in Section 4 is used, this is the minimum dispersion increment
  1230. for each stratum level, in seconds.
  1231.  
  1232. Maximum Dispersion (NTP.MAXDISPERSE): When the filter algorithm
  1233. suggested in Section 4 is used, this is the maximum peer dispersion and
  1234. the dispersion assumed for missing data, in seconds.
  1235.  
  1236. Reachability Register Size (NTP.WINDOW): This is the size of the
  1237. reachability register (peer.reach), in bits.
  1238.  
  1239. Filter Size (NTP.SHIFT): When the filter algorithm suggested in Section
  1240. 4 is used, this is the size of the clock filter (peer.filter) shift
  1241. register, in stages.
  1242. Filter Weight (NTP.FILTER): When the filter algorithm suggested in
  1243. Section 4 is used, this is the weight used to compute the filter
  1244. dispersion.
  1245.  
  1246. Select Weight (NTP.SELECT): When the selection algorithm suggested in
  1247. Section 4 is used, this is the weight used to compute the select
  1248. dispersion.
  1249.  
  1250. Modes of Operation
  1251.  
  1252. Except in broadcast mode, an NTP association is formed when two peers
  1253. exchange messages and one or both of them create and maintain an
  1254. instantiation of the protocol machine, called an association. The
  1255. association can operate in one of five modes as indicated by the host-
  1256. mode variable (peer.mode): symmetric active, symmetric passive, client,
  1257. server and broadcast, which are defined as follows:
  1258.  
  1259. Symmetric Active (1): A host operating in this mode sends periodic
  1260. messages regardless of the reachability state or stratum of its peer. By
  1261. operating in this mode the host announces its willingness to synchronize
  1262. and be synchronized by the peer.
  1263.  
  1264. Symmetric Passive (2): This type of association is ordinarily created
  1265. upon arrival of a message from a peer operating in the symmetric active
  1266. mode and persists only as long as the peer is reachable and operating at
  1267. a stratum level less than or equal to the host; otherwise, the
  1268. association is dissolved. However, the association will always persist
  1269. until at least one message has been sent in reply. By operating in this
  1270. mode the host announces its willingness to synchronize and be
  1271. synchronized by the peer.
  1272.  
  1273. Client (3): A host operating in this mode sends periodic messages
  1274. regardless of the reachability state or stratum of its peer. By
  1275. operating in this mode the host, usually a LAN workstation, announces
  1276. its willingness to be synchronized by, but not to synchronize the peer.
  1277.  
  1278. Server (4): This type of association is ordinarily created upon arrival
  1279. of a client request message and exists only in order to reply to that
  1280. request, after which the association is dissolved. By operating in this
  1281. mode the host, usually a LAN time server, announces its willingness to
  1282. synchronize, but not to be synchronized by the peer.
  1283.  
  1284. Broadcast (5): A host operating in this mode sends periodic messages
  1285. regardless of the reachability state or stratum of the peers. By
  1286. operating in this mode the host, usually a LAN time server operating on
  1287. a high-speed broadcast medium, announces its willingness to synchronize
  1288. all of the peers, but not to be synchronized by any of them.
  1289.  
  1290. A host operating in client mode occasionally sends an NTP message to a
  1291. host operating in server mode, perhaps right after rebooting and at
  1292. periodic intervals thereafter. The server responds by simply
  1293. interchanging addresses and ports, filling in the required information
  1294. and returning the message to the client. Servers need retain no state
  1295. information between client requests, while clients are free to manage
  1296. the intervals between sending NTP messages to suit local conditions. In
  1297. these modes the protocol machine described in this document can be
  1298. considerably simplified to a simple remote-procedure-call mechanism
  1299. without significant loss of accuracy or robustness, especially when
  1300. operating over high-speed LANs.
  1301.  
  1302. In the symmetric modes the client/server distinction (almost)
  1303. disappears. Symmetric passive mode is intended for use by time servers
  1304. operating near the root nodes (lowest stratum) of the synchronization
  1305. subnet and with a relatively large number of peers on an intermittent
  1306. basis. In this mode the identity of the peer need not be known in
  1307. advance, since the association with its state variables is created only
  1308. when an NTP message arrives. Furthermore, the state storage can be
  1309. reused when the peer becomes unreachable or is operating at a higher
  1310. stratum level and thus ineligible as a synchronization source.
  1311.  
  1312. Symmetric active mode is intended for use by time servers operating near
  1313. the end nodes (highest stratum) of the synchronization subnet. Reliable
  1314. time service can usually be maintained with two peers at the next lower
  1315. stratum level and one peer at the same stratum level, so the rate of
  1316. ongoing polls is usually not significant, even when connectivity is lost
  1317. and error messages are being returned for every poll.
  1318.  
  1319. Normally, one peer operates in an active mode (symmetric active, client
  1320. or broadcast modes) as configured by a startup file, while the other
  1321. operates in a passive mode (symmetric passive or server modes), often
  1322. without prior configuration. However, both peers can be configured to
  1323. operate in the symmetric active mode. An error condition results when
  1324. both peers operate in the same mode, but not symmetric active mode. In
  1325. such cases each peer will ignore messages from the other, so that prior
  1326. associations, if any, will be demobilized due to reachability failure.
  1327.  
  1328. Broadcast mode is intended for operation on high-speed LANs with
  1329. numerous workstations and where the highest accuracies are not required.
  1330. In the typical scenario one or more time servers on the LAN send
  1331. periodic broadcasts to the workstations, which then determine the time
  1332. on the basis of a preconfigured latency in the order of a few
  1333. milliseconds. As in the client/server modes the protocol machine can be
  1334. considerably simplified in this mode; however, a modified form of the
  1335. clock selection algorithm may prove useful in cases where multiple time
  1336. servers are used for enhanced reliability.
  1337.  
  1338. Event Processing
  1339.  
  1340. The significant events of interest in NTP occur upon expiration of a
  1341. peer timer (peer.timer), one of which is dedicated to each peer with an
  1342. active association, and upon arrival of an NTP message from the various
  1343. peers. An event can also occur as the result of an operator command or
  1344. detected system fault, such as a primary reference source failure. This
  1345. section describes the procedures invoked when these events occur.
  1346.  
  1347. Notation Conventions
  1348.  
  1349. The NTP filtering and selection algorithms act upon a set of variables
  1350. for clock offset (<$Etheta ,~THETA>), roundtrip delay (<$Edelta
  1351. ,~DELTA>) and dispersion (<$Eepsilon ,~EPSILON>). When necessary to
  1352. distinguish between them, lower-case Greek letters are used for
  1353. variables relative to a peer, while upper-case Greek letters are used
  1354. for variables relative to the primary reference source(s), i.e., via the
  1355. peer to the root of the synchronization subnet. Subscripts will be used
  1356. to identify the particular peer when this is not clear from context. The
  1357. algorithms are based on a quantity called the synchronization distance
  1358. (<$Elambda ,~LAMBDA>), which is computed from the roundtrip delay and
  1359. dispersion as described below.
  1360.  
  1361. As described in Appendix H, the peer dispersion <$Eepsilon> includes
  1362. contributions due to measurement error <$Erho~=~1~<< <<~roman
  1363. sys.precision>, skew-error accumulation <$Ephi tau>, where
  1364. <$Ephi~=~roman {NTP.MAXSKEW over NTP.MAXAGE}> is the maximum skew rate
  1365. and <$Etau~=~roman {sys.clock~-~peer.update}> is the interval since the
  1366. last update, and filter (sample) dispersion <$Eepsilon sub sigma>
  1367. computed by the clock-filter algorithm. The root dispersion <$EEPSILON>
  1368. includes contributions due to the selected peer dispersion <$Eepsilon>
  1369. and skew-error accumulation <$Ephi tau>, together with the root
  1370. dispersion for the peer itself. The system dispersion includes the
  1371. select (sample) dispersion <$Eepsilon sub xi> computed by the clock-
  1372. select algorithm and the absolute initial clock offset <$E| THETA |>
  1373. provided to the local-clock algorithm. Both <$Eepsilon> and <$EEPSILON>
  1374. are dynamic quantities, since they depend on the elapsed time <$Etau>
  1375. since the last update, as well as the sample dispersions calculated by
  1376. the algorithms.
  1377.  
  1378. Each time the relevant peer variables are updated, all dispersions
  1379. associated with that peer are updated to reflect the skew-error
  1380. accumulation. The computations can be summarized as follows:
  1381.  
  1382. <$Etheta~==~roman peer.offset> ,
  1383. <$Edelta~==~roman peer.delay> ,
  1384. <$Eepsilon~==~roman peer.dispersion~=~rho~+~phi tau~+~epsilon sub sigma>
  1385. ,
  1386. <$Elambda~==~epsilon~+~{| delta |} over 2> ,
  1387.  
  1388. where <$Etau> is the interval since the original timestamp (from which
  1389. <$Etheta> and <$Edelta> were determined) was transmitted to the present
  1390. time and <$Eepsilon sub sigma> is the filter dispersion (see clock-
  1391. filter procedure below). The variables relative to the root of the
  1392. synchronization subnet via peer i are determined as follows:
  1393.  
  1394. <$ETHETA sub i~==~theta sub i> ,
  1395. <$EDELTA sub i~==~roman peer.rootdelay~+~delta sub i> ,
  1396. <$EEPSILON sub i~==~roman peer.rootdispersion~+~epsilon sub i~+~phi tau
  1397. sub i> ,
  1398. <$ELAMBDA sub i~==~EPSILON sub i~+~{| DELTA sub i |} over 2> ,
  1399.  
  1400. where all variables are understood to pertain to the ith peer. Finally,
  1401. assuming the ith peer is selected for synchronization, the system
  1402. variables are determined as follows:
  1403.  
  1404. <$ETHETA~=~>combined final offset ,
  1405. <$EDELTA~=~DELTA sub i> ,
  1406. <$EEPSILON~=~EPSILON sub i~+~epsilon sub xi~+~| THETA |> ,
  1407. <$ELAMBDA~=~LAMBDA sub i> ,
  1408.  
  1409. where <$Eepsilon sub xi> is the select dispersion (see clock-selection
  1410. procedure below).
  1411.  
  1412. Informal pseudo-code which accomplishes these computations is presented
  1413. below. Note that the pseudo-code is represented in no particular
  1414. language, although it has many similarities to the C language. Specific
  1415. details on the important algorithms are further illustrated in the C-
  1416. language routines in Appendix I.
  1417.  
  1418. Transmit Procedure
  1419.  
  1420. The transmit procedure is executed when the peer timer decrements to
  1421. zero for all modes except client mode with a broadcast server and server
  1422. mode in all cases. In client mode with a broadcast server messages are
  1423. never sent. In server mode messages are sent only in response to
  1424. received messages. This procedure is also called by the receive
  1425. procedure when an NTP message arrives that does not result in a
  1426. persistent association.
  1427.  
  1428. begin transmit procedure
  1429.  
  1430. The following initializes the packet buffer and copies the packet
  1431. variables. The value skew is necessary to account for the skew-error
  1432. accumulated over the interval since the local clock was last set.
  1433.  
  1434.         <$Eroman pkt.peeraddr~<<-~roman peer.hostaddr>;         /* copy
  1435. system and peer variables */
  1436.         <$Eroman pkt.peerport~<<-~roman peer.hostport>;
  1437.         <$Eroman pkt.hostaddr~<<-~roman peer.peeraddr>;
  1438.         <$Eroman pkt.hostport~<<-~roman peer.peerport>;
  1439.         <$Eroman pkt.leap~<<-~roman sys.leap>;
  1440.         <$Eroman pkt.version~<<-~roman NTP.VERSION>;
  1441.         <$Eroman pkt.mode~<<-~roman peer.mode>;
  1442.         <$Eroman pkt.stratum~<<-~roman sys.stratum>;
  1443.         <$Eroman pkt.poll~<<-~roman peer.hostpoll>;
  1444.         <$Eroman pkt.precision~<<-~roman sys.precision>;
  1445.         <$Eroman pkt.rootdelay~<<-~roman sys.rootdelay>;
  1446.         if (sys.leap = 112 or (sys.clock <196> sys.reftime) >>
  1447. NTP.MAXAGE)
  1448.                 <$Eskew~<<-~roman NTP.MAXSKEW>;
  1449.         else
  1450.                 <$Eskew~<<-~phi roman {(sys.clock~-~sys.reftime)}>;
  1451.         <$Eroman {pkt.rootdispersion~<<-~roman
  1452. sys.rootdispersion~+~(1~<< <<~sys.precision)}~+~skew>;
  1453.         <$Eroman pkt.refid~<<-~roman sys.refid>;
  1454.         <$Eroman pkt.reftime~<<-~roman sys.reftime>;
  1455.  
  1456. The transmit timestamp pkt.xmt will be used later in order to validate
  1457. the reply; thus, implementations must save the exact value transmitted.
  1458. In addition, the order of copying the timestamps should be designed so
  1459. that the time to format and copy the data does not degrade accuracy.
  1460.  
  1461.         <$Eroman pkt.org~<<-~roman peer.org>;                           
  1462. /* copy timestamps */
  1463.         <$Eroman pkt.rec~<<-~roman peer.rec>;
  1464.         <$Eroman pkt.xmt~<<-~roman sys.clock>;
  1465.         <$Eroman peer.xmt~<<-~roman pkt.xmt>;
  1466.  
  1467. The call to encrypt is implemented only if authentication is
  1468. implemented. If authentication is enabled, the delay to encrypt the
  1469. authenticator may degrade accuracy. Therefore, implementations should
  1470. include a system state variable (not mentioned elsewhere in this
  1471. specification) which contains an offset calculated to match the expected
  1472. encryption delay and correct the transmit timestamp as obtained from the
  1473. local clock.
  1474.  
  1475.         #ifdef (authentication implemented)     /* see Appendix C */
  1476.                 call encrypt;
  1477.                 #endef
  1478.         send packet;
  1479.  
  1480. The reachability register is shifted one position to the left, with zero
  1481. replacing the vacated bit. If all bits of this register are zero, the
  1482. clear procedure is called to purge the clock filter and reselect the
  1483. synchronization source, if necessary. If the association was not
  1484. configured by the initialization procedure, the association is
  1485. demobilized.
  1486.  
  1487.         <$Eroman peer.reach~<<-~roman peer.reach~<< <<~1>;              
  1488. /* update reachability */
  1489.         if (<$Eroman peer.reach~=~0> and <$Eroman peer.config~=~0>)
  1490. begin
  1491.                 demobilize association;
  1492.                 exit;
  1493.                 endif
  1494.  
  1495. If valid data have been shifted into the filter register at least once
  1496. during the preceding two poll intervals (low-order bit of peer.reach set
  1497. to one), the valid data counter is incremented. After eight such valid
  1498. intervals the poll interval is incremented. Otherwise, the valid data
  1499. counter and poll interval are both decremented and the clock-filter
  1500. procedure called with zero values for offset and delay and
  1501. NTP.MAXDISPERSE for dispersion. The clock-select procedure is called to
  1502. reselect the synchronization source, if necessary.
  1503.  
  1504.         if (<$Eroman peer.reach~&~6~!=~0>)                      /* test
  1505. two low-order bits (shifted) */ 
  1506.                 if (<$Eroman peer.valid~<<~roman NTP.SHIFT>)    /* valid
  1507. data received */
  1508.                         <$Eroman peer.valid~<<-~roman peer.valid~+~1>;
  1509.                         else <$Eroman peer.hostpoll~<<-~roman
  1510. peer.hostpoll~+~1>;
  1511.         else begin
  1512.                 <$Eroman peer.valid~<<-~roman peer.valid~-~1>;  /*
  1513. nothing heard */
  1514.                 <$Eroman peer.hostpoll~<<-~roman peer.hostpoll~-~1>);
  1515.                 call clock-filter(0, 0, NTP.MAXDISPERSE);
  1516.                 call clock-select;                      /* select clock
  1517. source */
  1518.                 endif
  1519.         call poll-update;
  1520.         end transmit procedure;
  1521.  
  1522. Receive Procedure
  1523.  
  1524. The receive procedure is executed upon arrival of an NTP message. It
  1525. validates the message, interprets the various modes and calls other
  1526. procedures to filter the data and select the synchronization source. If
  1527. the version number in the packet does not match the current version, the
  1528. message may be discarded; however, exceptions may be advised on a case-
  1529. by-case basis at times when the version is changed. If the NTP control
  1530. messages described in Appendix B are implemented and the packet mode is
  1531. 6 (control), the control-message procedure is called. The source and
  1532. destination Internet addresses and ports in the IP and UDP headers are
  1533. matched to the correct peer. If there is no match a new instantiation of
  1534. the protocol machine is created and the association mobilized.
  1535.  
  1536. begin receive procedure
  1537.         if (<$Eroman pkt.version~!=~roman NTP.VERSION>) exit;
  1538.         #ifdef (control messages implemented)
  1539.                 if (<$Eroman pkt.mode~=~6>) call control-message;
  1540.                 #endef
  1541.         for (all associations)                  /* access control goes
  1542. here */
  1543.                 match addresses and ports to associations;
  1544.         if (no matching association)
  1545.                 call receive-instantiation procedure;   /* create
  1546. association */
  1547.  
  1548. The call to decrypt is implemented only if authentication is
  1549. implemented.
  1550.  
  1551.         #ifdef (authentication implemented)     /* see Appendix C */
  1552.                 call decrypt;
  1553.                 #endef
  1554.  
  1555. If the packet mode is nonzero, this becomes the value of mode used in
  1556. the following step; otherwise, the peer is an old NTP version and mode
  1557. is determined from the port numbers as described in Section 3.3.
  1558.  
  1559.         if (pkt.mode = 0)                               /* for
  1560. compatibility with old versions */
  1561.                 <$Emode~<<-~>(see Section 3.3);
  1562.         else
  1563.                 <$Emode~<<-~roman pkt.mode>;
  1564.  
  1565. Table 5<$&tab5> shows for each combination of peer.mode and mode the
  1566. resulting case labels.
  1567.  
  1568.         case (mode, peer.hostmode)              /* see Table 5 */
  1569.  
  1570. If error the packet is simply ignored and the association demobilized,
  1571. if not previously configured.
  1572. error:          if (<$Eroman peer.config~=~0>) demobilize association;  
  1573. /* see no evil */
  1574.                 break;
  1575.  
  1576. If recv the packet is processed and the association marked reachable if
  1577. tests five through eight (valid header) enumerated in the packet
  1578. procedure succeed. If, in addition, tests one through four succeed
  1579. (valid data), the clock-update procedure is called to update the local
  1580. clock. Otherwise, if the association was not previously configured, it
  1581. is demobilized.
  1582.  
  1583. recv:           call packet;                            /* process
  1584. packet */
  1585.                 if (valid header) begin         /* if valid header,
  1586. update local clock */
  1587.                         <$Eroman peer.reach~<<-~roman peer.reach~|~1>;
  1588.                         if (valid data) call clock-update;
  1589.                         endif
  1590.                 else
  1591.                         if (<$Eroman peer.config~=~0>) demobilize
  1592. association;
  1593.                 break;
  1594.  
  1595. If xmit the packet is processed and an immediate reply is sent. The
  1596. association is then demobilized if not previously configured.
  1597.  
  1598. xmit:           call packet;                            /* process
  1599. packet */
  1600.                 <$Eroman peer.hostpoll~<<-~roman peer.peerpoll>;        
  1601. /* send immediate reply */
  1602.                 call poll-update;
  1603.                 call transmit;
  1604.                 if (<$Eroman peer.config~=~0>) demobilize association;
  1605.                 break;
  1606.  
  1607. If pkt the packet is processed and the association marked reachable if
  1608. tests five through eight (valid header) enumerated in the packet
  1609. procedure succeed. If, in addition, tests one through four succeed
  1610. (valid data), the clock-update procedure is called to update the local
  1611. clock. Otherwise, if the association was not previously configured, an
  1612. immediate reply is sent and the association demobilized.
  1613.  
  1614. pkt:            call packet;                            /* process
  1615. packet */
  1616.                 if (valid header) begin         /* if valid header,
  1617. update local clock */
  1618.                         <$Eroman peer.reach~<<-~roman peer.reach~|~1>;
  1619.                         if (valid data) call clock-update;
  1620.                         endif
  1621.                 else if (<$Eroman peer.config~=~0>) begin
  1622.                         <$Eroman peer.hostpoll~<<-~roman
  1623. peer.peerpoll>; /* send immediate reply */
  1624.                         call poll-update;
  1625.                         call transmit;
  1626.                         demobilize association;
  1627.                         endif
  1628.                 endcase
  1629.         end receive procedure;
  1630.  
  1631. Packet Procedure
  1632.  
  1633. The packet procedure checks the message validity, computes delay/offset
  1634. samples and calls other procedures to filter the data and select the
  1635. synchronization source. Test 1 requires the transmit timestamp not match
  1636. the last one received from the same peer; otherwise, the message might
  1637. be an old duplicate. Test 2 requires the originate timestamp match the
  1638. last one sent to the same peer; otherwise, the message might be out of
  1639. order, bogus or worse. In case of broadcast mode (5) the apparent
  1640. roundtrip delay will be zero and the full accuracy of the time-transfer
  1641. operation may not be achievable. However, the accuracy achieved may be
  1642. adequate for most purposes. The poll-update procedure is called with
  1643. argument peer.hostpoll (peer.peerpoll may have changed).
  1644.  
  1645. begin packet procedure
  1646.         <$Eroman peer.rec~<<-~roman sys.clock>;                 /*
  1647. capture receive timestamp */
  1648.         if (<$Eroman pkt.mode ~!=~5>) begin
  1649.                 <$Etest1~<<-~( roman {pkt.xmt~!=~peer.org})>;   /* test
  1650. 1 */
  1651.                 <$Etest2~<<-~( roman {pkt.org~=~peer.xmt})>;    /* test
  1652. 2 */
  1653.                 endif
  1654.         else begin
  1655.                 <$Eroman pkt.org~<<-~roman peer.rec>;                   
  1656. /* fudge missing timestamps */
  1657.                 <$Eroman pkt.rec~<<-~roman pkt.xmt>;
  1658.                 <$Etest1~<<-~bold roman true>;                          
  1659. /* fake tests */
  1660.                 <$Etest2~<<-~bold roman true>;
  1661.                 endif
  1662.         <$Eroman peer.org~<<-~roman pkt.xmt>;                           
  1663. /* update originate timestamp */
  1664.         <$Eroman peer.peerpoll~<<-~roman pkt.poll>;                     
  1665. /* adjust poll interval */
  1666.         call poll-update(peer.hostpoll);
  1667.  
  1668. Test 3 requires that both the originate and receive timestamps are
  1669. nonzero. If either of the timestamps are zero, the association has not
  1670. synchronized or has lost reachability in one or both directions.
  1671.  
  1672.         <$Etest3~<<-~( roman pkt.org~!=~0> and <$Eroman pkt.rec~!=~0)>; 
  1673. /* test 3 */
  1674.  
  1675. The roundtrip delay and clock offset relative to the peer are calculated
  1676. as follows. Number the times of sending and receiving NTP messages as
  1677. shown in Figure 2<$&fig2> and let i be an even integer. Then Ti-3, Ti-2,
  1678. Ti-1 and Ti are the contents of the pkt.org, pkt.rec, pkt.xmt and
  1679. peer.rec variables, respectively. The clock offset <$Etheta>, roundtrip
  1680. delay <$Edelta> and dispersion <$Eepsilon> of the host relative to the
  1681. peer is:
  1682.  
  1683. <$Edelta~=~(T sub i~-~T sub {i - 3} )~-~(T sub {i - 1}~-~T sub {i - 2}
  1684. )> ,
  1685. <$Etheta~=~{(T sub {i - 2}~-~T sub {i-3})~+~(T sub {i-1}~-~T sub i ) }
  1686. over 2> ,
  1687. <$Eepsilon~=~roman {(1~<< <<~sys.precision})~+~phi (T sub i ~-~T sub {i-
  1688. 3} )> ,
  1689.  
  1690. where, as before, <$Ephi~=~roman{ NTP.MAXSKEW over NTP.MAXAGE}>. The
  1691. quantity <$Eepsilon> represents the maximum error or dispersion due to
  1692. measurement error at the host and local-clock skew accumulation over the
  1693. interval since the last message was transmitted to the peer.
  1694. Subsequently, the dispersion will be updated by the clock-filter
  1695. procedure.
  1696.  
  1697. The above method amounts to a continuously sampled, returnable-time
  1698. system, which is used in some digital telephone networks [BEL86]. Among
  1699. the advantages are that the order and timing of the messages are
  1700. unimportant and that reliable delivery is not required. Obviously, the
  1701. accuracies achievable depend upon the statistical properties of the
  1702. outbound and inbound data paths. Further analysis and experimental
  1703. results bearing on this issue can be found in [MIL90] and in Appendix H.
  1704. Test 4 requires that the calculated delay be within <169>reasonable<170>
  1705. bounds:
  1706.  
  1707.         <$Etest4~<<-~(| delta |~<<~roman NTP.MAXDISPERSE~bold
  1708. and~epsilon~<<~roman NTP.MAXDISPERSE)>;  /* test 4 */
  1709.  
  1710. Test 5 is implemented only if the authentication mechanism described in
  1711. Appendix C is implemented. It requires either that authentication be
  1712. explicitly disabled or that the authenticator be present and correct as
  1713. determined by the decrypt procedure.
  1714.  
  1715.         #ifdef (authentication implemented)     /* test 5 */
  1716.                 <$Etest5~<<-~( roman {(peer.config~=~1~bold
  1717. and~peer.authenable~=~0)~bold or~ peer.authentic~=~1})>;
  1718.                 #endef
  1719.  
  1720. Test 6 requires the peer clock be synchronized and the interval since
  1721. the peer clock was last updated be positive and less than NTP.MAXAGE.
  1722. Test 7 insures that the host will not synchronize on a peer with greater
  1723. stratum. Test 8 requires that the header contains <169>reasonable<170>
  1724. values for the pkt.rootdelay and pkt.rootdispersion fields.
  1725.  
  1726.         <$Etest6~<<-~( roman pkt.leap~!=~11 sub 2> and          /* test
  1727. 6 */
  1728.                 <$Eroman
  1729. {pkt.reftime~<<=~pkt.xmt~<<~pkt.reftime~+~NTP.MAXAGE}>)
  1730.         <$Etest7~<<-~roman {pkt.stratum ~<<=~sys.stratum}> and  /* test
  1731. 7 */
  1732.                  <$Eroman {pkt.stratum ~<<~NTP.MAXSTRATUM}>;
  1733.         <$Etest8~<<-~( roman {| pkt.rootdelay |~<<~NTP.MAXDISPERSE}>
  1734. and     /* test 8 */
  1735.                 <$Eroman {pkt.rootdispersion~<<~NTP.MAXDISPERSE})>;
  1736.  
  1737. With respect to further processing, the packet includes valid
  1738. (synchronized) data if tests one through four succeed
  1739. <$E(test1~&~test2~&~test3~&~test4~=~1)>, regardless of the remaining
  1740. tests. Only packets with valid data can be used to calculate offset,
  1741. delay and dispersion values. The packet includes a valid header if tests
  1742. five through eight succeed <$E(test5~&~test6~&~test7~&~test8~=~1)>,
  1743. regardless of the remaining tests. Only packets with valid headers can
  1744. be used to determine whether a peer can be selected for synchronization.
  1745. Note that <$Etest1> and <$Etest2> are not used in broadcast mode (forced
  1746. to true), since the originate and receive timestamps are undefined.
  1747.  
  1748. The clock-filter procedure is called to produce the delay (peer.delay),
  1749. offset (peer.offset) and dispersion (peer.dispersion) for the peer.
  1750. Specification of the clock-filter algorithm is not an integral part of
  1751. the NTP specification, since there may be other algorithms that work
  1752. well in practice. However, one found to work well in the Internet
  1753. environment is described in Section 4 and its use is recommended.
  1754.  
  1755.         if (not valid header) exit;
  1756.         <$Eroman peer.leap~<<-~roman pkt.leap>;                 /* copy
  1757. packet variables */
  1758.         <$Eroman peer.stratum~<<-~roman pkt.stratum>;
  1759.         <$Eroman peer.precision~<<-~roman pkt.precision>;
  1760.         <$Eroman peer.rootdelay~<<-~roman pkt.rootdelay>;
  1761.         <$Eroman peer.rootdispersion~<<-~roman pkt.rootdispersion>;
  1762.         <$Eroman peer.refid~<<-~roman pkt.refid>;
  1763.         <$Eroman peer.reftime~<<-~roman pkt.reftime>;
  1764.         if (valid data) call clock-filter(<$Etheta ,~delta ,~epsilon>); 
  1765. /* process sample */
  1766.         end packet procedure;
  1767.  
  1768. Clock-Update Procedure
  1769. The clock-update procedure is called from the receive procedure when
  1770. valid clock offset, delay and dispersion data have been determined by
  1771. the clock-filter procedure for the current peer. The result of the
  1772. clock-selection and clock-combining procedures is the final clock
  1773. correction <$ETHETA>, which is used by the local-clock procedure to
  1774. update the local clock. If no candidates survive these procedures, the
  1775. clock-update procedure exits without doing anything further.
  1776.  
  1777. begin clock-update procedure
  1778.         call clock-select;                              /* select clock
  1779. source */
  1780.         if (<$Eroman sys.peer~!=~peer>) exit;
  1781.  
  1782. It may happen that the local clock may be reset, rather than slewed to
  1783. its final value. In this case the clear procedure is called for every
  1784. peer to purge the clock filter, reset the poll interval and reselect the
  1785. synchronization source, if necessary. Note that the local-clock
  1786. procedure sets the leap bits sys.leap to <169>unsynchronized<170> 112 in
  1787. this case, so that no other peer will attempt to synchronize to the host
  1788. until the host once again selects a peer for synchronization.
  1789.  
  1790. The distance procedure calculates the root delay <$EDELTA>, root
  1791. dispersion <$EEPSILON> and root synchronization distance <$ELAMBDA> via
  1792. the peer to the root of the synchronization subnet. The host will not
  1793. synchronize to the selected peer if the distance is greater than
  1794. NTP.MAXDISTANCE. The reason for the minimum clamp at NTP.MINDISPERSE is
  1795. to discourage subnet route flaps that can happen with Bellman-Ford
  1796. algorithms and small roundtrip delays.
  1797.  
  1798.         <$ELAMBDA~<M=O>
  1799. <~>an distance (peer)>;                         /* update system
  1800. variables */
  1801.  <B>    if (<$ELAMBDA~>>=~roman NTP.MAXDISTANCE>) exit;
  1802.         <$Eroman sys.leap~<<-~roman peer.leap>;
  1803.         <$Eroman sys.stratum~<<-~roman peer.stratum~+~1>;
  1804.         <$Eroman sys.refid~<<-~roman peer.peeraddr>;
  1805.         call local-clock;
  1806.         if (local clock reset) begin                    /* if reset,
  1807. clear state variables */
  1808.                 <$Eroman sys.leap~<<-~11 sub 2>;
  1809.                 for (all peers) call clear;
  1810.                 endif
  1811.         else begin
  1812.                 <$Eroman sys.peer~<<-~peer>;                    /* if
  1813. not, adjust local clock */
  1814.                 <$Eroman sys.rootdelay~<<-~DELTA>;
  1815.                 <$Eroman sys.rootdispersion~<<-~EPSILON~+~max ( epsilon
  1816. sub xi~+~| THETA |,~roman NTP.MINDISPERSE)>;
  1817.                 endif
  1818.         <$Eroman sys.reftime~<<-~roman sys.clock>;
  1819.         end clock-update procedure;
  1820.  
  1821. In some system configurations a precise source of timing information is
  1822. available in the form of a train of timing pulses spaced at one-second
  1823. intervals. Usually, this is in addition to a source of timecode
  1824. information, such as a radio clock or even NTP itself, to number the
  1825. seconds, minutes, hours and days. In these configurations the system
  1826. variables are set to refer to the source from which the pulses are
  1827. derived. For those configurations which support a primary reference
  1828. source, such as a radio clock or calibrated atomic clock, the stratum is
  1829. set at one as long as this is the actual synchronization source and
  1830. whether or not the primary-clock procedure is used.
  1831.  
  1832. Specification of the clock-selection and local-clock algorithms is not
  1833. an integral part of the NTP specification, since there may be other
  1834. algorithms which provide equivalent performance. However, a clock-
  1835. selection algorithm found to work well in the Internet environment is
  1836. described in Section 4, while a local-clock algorithm is described in
  1837. Section 5 and their use is recommended. The clock-selection algorithm
  1838. described in Section 4 usually picks the peer at the lowest stratum and
  1839. minimum synchronization distance among all those available, unless that
  1840. peer appears to be a falseticker. The result is that the algorithms all
  1841. work to build a minimum-weight spanning tree relative to the primary
  1842. reference time servers and thus a hierarchical-master-slave
  1843. synchronization subnet.
  1844.  
  1845. Primary-Clock Procedure
  1846.  
  1847. When a primary reference source such as a radio clock is connected to
  1848. the host, it is convenient to incorporate its information into the data
  1849. base as if the clock were represented as an ordinary peer. In the
  1850. primary-clock procedure the clock is polled once a minute or so and the
  1851. returned timecode used to produce a new update for the local clock. When
  1852. peer.timer decrements to zero for a primary clock peer, the transmit
  1853. procedure is not called; rather, the radio clock is polled, usually
  1854. using an ASCII string specified for this purpose. When a valid timecode
  1855. is received from the radio clock, it is converted to NTP timestamp
  1856. format and the peer variables updated. The value of peer.leap is set
  1857. depending on the status of the leap-warning bit in the timecode, if
  1858. available, or manually by the operator. The value for peer.peeraddr,
  1859. which will become the value of sys.refid when the clock-update procedure
  1860. is called, is set to an ASCII string describing the clock type (see
  1861. Appendix A).
  1862.  
  1863. begin primary-clock-update procedure
  1864.         <$Eroman peer.leap~<<-~"from"~radio~or~operator>;       /* copy
  1865. variables */
  1866.         <$Eroman peer.peeraddr~<<-~ASCII~identifier>;
  1867.         <$Eroman peer.rec~<<-~radio~timestamp>;
  1868.         <$Eroman peer.reach~<<-~1>;
  1869.         call clock-filter(<$Eroman {sys.clock~-~peer.rec,~0,~1~<<
  1870. <<~peer.precision}>);   /* process sample */
  1871.         call clock-update;                              /* update local
  1872. clock */
  1873.         end primary-clock-update procedure;
  1874.  
  1875. Initialization Procedures
  1876.  
  1877. The initialization procedures are used to set up and initialize the
  1878. system, its peers and associations.
  1879.  
  1880.  Initialization Procedure
  1881.  
  1882. The initialization procedure is called upon reboot or restart of the NTP
  1883. daemon. The local clock is presumably undefined at reboot; however, in
  1884. some equipment an estimate is available from the reboot environment,
  1885. such as a battery-backed clock/calendar. The precision variable is
  1886. determined by the intrinsic architecture of the local hardware clock.
  1887. The authentication variables are used only if the authentication
  1888. mechanism described in Appendix C is implemented. The values of these
  1889. variables are determined using procedures beyond the scope of NTP
  1890. itself.
  1891.  
  1892. begin initialization procedure
  1893.         #ifdef (authentication implemented)     / * see Appendix C */
  1894.                 <$Eroman sys.keys~<<-~as~required>;
  1895.                 #endef;
  1896.         <$Eroman sys.leap~<<-~11 sub 2>;                                
  1897. /* copy variables */
  1898.         <$Eroman sys.stratum~<<-~0~(undefined)>;
  1899.         <$Eroman sys.precision~<<-~host~precision>;
  1900.         <$Eroman sys.rootdelay~<<-~0~(undefined)>;
  1901.         <$Eroman sys.rootdispersion~<<-~0~(undefined)>;
  1902.         <$Eroman sys.refid~<<-~0~(undefined)>;
  1903.         <$Eroman sys.reftime~<<-~0~(undefined)>;
  1904.         <$Eroman sys.clock~<<-~external~reference>;
  1905.         <$Eroman sys.peer~<<-~roman NULL>;
  1906.         <$Eroman sys.poll~<<-~roman NTP.MINPOLL>;
  1907.         for (all configured peers)                      /* create
  1908. configured associations */
  1909.                 call initialization-instantiation procedure;
  1910.         end initialization procedure;
  1911.  
  1912.  Initialization-Instantiation Procedure
  1913.  
  1914. This implementation-specific procedure is called from the initialization
  1915. procedure to define an association. The addresses and modes of the peers
  1916. are determined using information read during the reboot procedure or as
  1917. the result of operator commands. The authentication variables are used
  1918. only if the authentication mechanism described in Appendix C is
  1919. implemented. The values of these variables are determined using
  1920. procedures beyond the scope of NTP itself. With the authentication bits
  1921. set as suggested, only properly authenticated peers can become the
  1922. synchronization source.
  1923.  
  1924. begin initialization-instantiation procedure
  1925.         <$Eroman peer.config~<<-~1>;
  1926.         #ifdef (authentication implemented)     /* see Appendix C */
  1927.                 <$Eroman peer.authenable~<<-~1~(suggested)>;
  1928.                 <$Eroman peer.authentic~<<-~0>;
  1929.                 <$Eroman peer.hostkeyid~<<-~as~required>;
  1930.                 <$Eroman peer.peerkeyid~<<-~0>;
  1931.                 #endef;
  1932.         <$Eroman peer.peeraddr~<<-~peer~IP~address>;    /* copy
  1933. variables */
  1934.         <$Eroman peer.peerport~<<-~roman NTP.PORT>;
  1935.         <$Eroman peer.hostaddr~<<-~host~IP~address>;
  1936.         <$Eroman peer.hostport~<<-~roman NTP.PORT>;
  1937.         <$Eroman peer.mode~<<-~host~mode>;
  1938.         <$Eroman peer.peerpoll~<<-~0~(undefined)>;
  1939.         <$Eroman peer.timer~<<-~0>;
  1940.         <$Eroman peer.delay~<<-~0~(undefined)>;
  1941.         <$Eroman peer.offset~<<-~0~(undefined)>;
  1942.         call clear;                                     /* initialize
  1943. association */
  1944.         end initialization-instantiation procedure;
  1945.  
  1946.  Receive-Instantiation Procedure
  1947.  
  1948. The receive-instantiation procedure is called from the receive procedure
  1949. when a new peer is discovered. It initializes the peer variables and
  1950. mobilizes the association. If the message is from a peer operating in
  1951. client mode (3), the host mode is set to server mode (4); otherwise, it
  1952. is set to symmetric passive mode (2). The authentication variables are
  1953. used only if the authentication mechanism described in Appendix C is
  1954. implemented. If implemented, only properly authenticated non-configured
  1955. peers can become the synchronization source.
  1956.  
  1957. begin receive-instantiation procedure
  1958.         #ifdef (authentication implemented)     /* see Appendix C */
  1959.                 <$Eroman peer.authenable~<<-~0>;
  1960.                 <$Eroman peer.authentic~<<-~0>;
  1961.                 <$Eroman peer.hostkeyid~<<-~as~required>;
  1962.                 <$Eroman peer.peerkeyid~<<-~0>;
  1963.                 #endef
  1964.         <$Eroman peer.config~<<-~0>;                            /* copy
  1965. variables */
  1966.         <$Eroman peer.peeraddr~<<-~roman pkt.peeraddr>;
  1967.         <$Eroman peer.peerport~<<-~roman pkt.peerport>;
  1968.         <$Eroman peer.hostaddr~<<-~roman pkt.hostaddr>;
  1969.         <$Eroman peer.hostport~<<-~roman pkt.hostport>;
  1970.         if (pkt.mode = 3)                               /* determine
  1971. mode */
  1972.                 <$Eroman peer.mode~<<-~4>;
  1973.                 else
  1974.                 <$Eroman peer.mode~<<-~2>;
  1975.         <$Eroman peer.peerpoll~<<-~0~(undefined)>;
  1976.         <$Eroman peer.timer~<<-~0>;
  1977.         <$Eroman peer.delay~<<-~0~(undefined)>;
  1978.         <$Eroman peer.offset~<<-~0~(undefined)>;
  1979.         call clear;                                     /* initialize
  1980. association */
  1981.         end receive-instantiation procedure;
  1982.  
  1983.  Primary Clock-Instantiation Procedure
  1984.  
  1985. This procedure is called from the initialization procedure in order to
  1986. set up the state variables for the primary clock. The value for
  1987. peer.precision is determined from the radio clock specification and
  1988. hardware interface. The value for peer.rootdispersion is nominally ten
  1989. times the inherent maximum error of the radio clock; for instance,
  1990. <$E10~mu s> for a calibrated atomic clock, 10 ms for a WWVB or GOES
  1991. radio clock and 100 ms for a less accurate WWV radio clock.
  1992.  
  1993. begin clock-instantiation procedure
  1994.         <$Eroman peer.config~<<-~1>;                            /* copy
  1995. variables */
  1996.         <$Eroman peer.peeraddr~<<-~0~undefined>;
  1997.         <$Eroman peer.peerport~<<-~0~(not~used)>;
  1998.         <$Eroman peer.hostaddr~<<-~0~(not~used)>;
  1999.         <$Eroman peer.hostport~<<-~0~(not~used)>;
  2000.         <$Eroman peer.leap~<<-~11 sub 2>;
  2001.         <$Eroman peer.mode~<<-~0~(not~used)>;
  2002.         <$Eroman peer.stratum~<<-~0>;
  2003.         <$Eroman peer.peerpoll~<<-~0~(undefined)>;
  2004.         <$Eroman peer.precision~<<-~clock~precision>;
  2005.         <$Eroman peer.rootdelay~<<-~0>;
  2006.         <$Eroman peer.rootdispersion~<<-~clock~dispersion>;
  2007.         <$Eroman peer.refid~<<-~0~(not~used)>;
  2008.         <$Eroman peer.reftime~<<-~0~(undefined)>;
  2009.         <$Eroman peer.timer~<<-~0>;
  2010.         <$Eroman peer.delay~<<-~0~(undefined)>;
  2011.         <$Eroman peer.offset~<<-~0~(undefined)>;
  2012.         call clear;                                     /* initialize
  2013. association */
  2014.         end clock-instantiation procedure;
  2015.  
  2016. In some configurations involving a calibrated atomic clock or LORAN-C
  2017. receiver, the primary reference source may provide only a seconds pulse,
  2018. but lack a complete timecode from which the numbering of the seconds,
  2019. etc., can be derived. In these configurations seconds numbering can be
  2020. derived from other sources, such as a radio clock or even other NTP
  2021. peers. In these configurations the primary clock variables should
  2022. reflect the primary reference source, not the seconds-numbering source;
  2023. however, if the seconds-numbering source fails or is known to be
  2024. operating incorrectly, updates from the primary reference source should
  2025. be suppressed as if it had failed.
  2026.  
  2027. Clear Procedure
  2028.  
  2029. The clear procedure is called when some event occurs that results in a
  2030. significant change in reachability state or potential disruption of the
  2031. local clock.
  2032. begin clear procedure
  2033.         <$Eroman peer.org~<<-~0~(undefined)>;                   /* mark
  2034. timestamps undefined */
  2035.         <$Eroman peer.rec~<<-~0~(undefined)>;
  2036.         <$Eroman peer.xmt~<<-~0~(undefined)>;
  2037.         <$Eroman peer.reach~<<-~0>;                             /* reset
  2038. state variables */
  2039.         <$Eroman peer.filter~<<-~[0,~,0,~roman NTP.MAXDISPERSE]>;   /*
  2040. all stages */
  2041.         <$Eroman peer.valid~<<-~0>;
  2042.         <$Eroman peer.dispersion~<<-~roman NTP.MAXDISPERSE>;
  2043.         <$Eroman {peer.hostpoll~<<-~NTP.MINPOLL}>;              /* reset
  2044. poll interval */
  2045.         call poll-update;
  2046.         call clock-select;                              /* select clock
  2047. source */
  2048.         end clear procedure;
  2049.  
  2050. Poll-Update Procedure
  2051.  
  2052. The poll-update procedure is called when a significant event occurs that
  2053. may result in a change of the poll interval or peer timer. It checks the
  2054. values of the host poll interval (peer.hostpoll) and peer poll interval
  2055. (peer.peerpoll) and clamps each within the valid range. If the peer is
  2056. selected for synchronization, the value is further clamped as a function
  2057. of the computed compliance (see Section 5).
  2058.  
  2059. begin poll-update procedure
  2060.         <$Etemp~<<-~roman peer.hostpoll>;                       /*
  2061. determine host poll interval */
  2062.         if (<$Epeer~=~roman sys.peer>)
  2063.                 <$Etemp~<<-~min (temp,~roman {sys.poll,~NTP.MAXPOLL)}>;
  2064.         else
  2065.                 <$Etemp~<<-~min (temp,~roman NTP.MAXPOLL)>;
  2066.         <$Eroman peer.hostpoll~<<-~max (temp,~roman NTP.MINPOLL)>;
  2067.         <$Etemp~<<-~1~<< << ~min ( roman {peer.hostpoll,~max
  2068. (peer.peerpoll,~NTP.MINPOLL)})>;
  2069.  
  2070. If the poll interval is unchanged and the peer timer is zero, the timer
  2071. is simply reset. If the poll interval is changed and the new timer value
  2072. is greater than the present value, no additional action is necessary;
  2073. otherwise, the peer timer must be reduced. When the peer timer must be
  2074. reduced it is important to discourage tendencies to synchronize
  2075. transmissions between the peers. A prudent precaution is to randomize
  2076. the first transmission after the timer is reduced, for instance by the
  2077. sneaky technique illustrated.
  2078.  
  2079.         if (peer.timer = 0)                             /* reset peer
  2080. timer */
  2081.                 <$Eroman peer.timer~<<-~temp>;
  2082.         else if (<$Eroman peer.timer~>>~temp>)
  2083.                 <$Eroman peer.timer~<<-~( roman sys.clock~&~(temp~-
  2084. ~1))~+~1>;
  2085.         end poll-update procedure;
  2086.  
  2087. Synchronization Distance Procedure
  2088.  
  2089. The distance procedure calculates the synchronization distance from the
  2090. peer variables for the peer peer.
  2091.  
  2092. begin distance(peer) procedure;
  2093.         <$EDELTA~<<-~roman {peer.rootdelay~+~|peer.delay|}>;
  2094.         <$EEPSILON~<<-~roman
  2095. {peer.rootdispersion~+~peer.dispersion~+~phi (sys.clock~-~peer.update)
  2096. }>;
  2097.         <$ELAMBDA~<<-~EPSILON~+~{| DELTA |} over 2> ;
  2098.         end distance procedure;
  2099.  
  2100. Note that, while <$EDELTA> may be negative in some cases, both
  2101. <$EEPSILON> and <$ELAMBDA> are always positive.
  2102.  
  2103. Access Control Issues
  2104.  
  2105. The NTP design is such that accidental or malicious data modification
  2106. (tampering) or destruction (jamming) at a time server should not in
  2107. general result in timekeeping errors elsewhere in the synchronization
  2108. subnet. However, the success of this approach depends on redundant time
  2109. servers and diverse network paths, together with the assumption that
  2110. tampering or jamming will not occur at many time servers throughout the
  2111. synchronization subnet at the same time. In principle, the subnet
  2112. vulnerability can be engineered through the selection of time servers
  2113. known to be trusted and allowing only those time servers to become the
  2114. synchronization source. The authentication procedures described in
  2115. Appendix C represent one mechanism to enforce this; however, the
  2116. encryption algorithms can be quite CPU-intensive and can seriously
  2117. degrade accuracy, unless precautions such as mentioned in the
  2118. description of the transmit procedure are taken.
  2119.  
  2120. While not a required feature of NTP itself, some implementations may
  2121. include an access-control feature that prevents unauthorized access and
  2122. controls which peers are allowed to update the local clock. For this
  2123. purpose it is useful to distinguish between three categories of access:
  2124. those that are preauthorized as trusted, preauthorized as friendly and
  2125. all other (non-preauthorized) accesses. Presumably, preauthorization is
  2126. accomplished by entries in the configuration file or some kind of
  2127. ticket-management system such as Kerberos [STE88]. In this model only
  2128. trusted accesses can result in the peer becoming the synchronization
  2129. source. While friendly accesses cannot result in the peer becoming the
  2130. synchronization source, NTP messages and timestamps are returned as
  2131. specified.
  2132.  
  2133. It does not seem useful to maintain a secret clock, as would result from
  2134. restricting non-preauthorized accesses, unless the intent is to hide the
  2135. existence of the time server itself. Well-behaved Internet hosts are
  2136. expected to return an ICMP service-unavailable error message if a
  2137. service is not implemented or resources are not available; however, in
  2138. the case of NTP the resources required are minimal, so there is little
  2139. need to restrict requests intended only to read the clock. A simple but
  2140. effective access-control mechanism is then to consider all associations
  2141. preconfigured in a symmetric mode or client mode (modes 1, 2 and 3) as
  2142. trusted and all other associations, preconfigured or not, as friendly.
  2143.  
  2144. If a more comprehensive trust model is required, the design can be based
  2145. on an access-control list with each entry consisting of a 32-bit
  2146. Internet address, 32-bit mask and three-bit mode. If the logical AND of
  2147. the source address (pkt.peeraddr) and the mask in an entry matches the
  2148. corresponding address in the entry and the mode (pkt.mode) matches the
  2149. mode in the entry, the access is allowed; otherwise an ICMP error
  2150. message is returned to the requestor. Through appropriate choice of
  2151. mask, it is possible to restrict requests by mode to individual
  2152. addresses, a particular subnet or net addresses, or have no restriction
  2153. at all. The access-control list would then serve as a filter controlling
  2154. which peers could create associations.
  2155.  
  2156. Filtering and Selection Algorithms
  2157.  
  2158. A most important factor affecting the accuracy and reliability of time
  2159. distribution is the complex of algorithms used to reduce the effect of
  2160. statistical errors and falsetickers due to failure of various subnet
  2161. components, reference sources or propagation media. The algorithms
  2162. suggested in this section were developed and refined over several years
  2163. of operation in the Internet under widely varying topologies, speeds and
  2164. traffic regimes. While these algorithms are believed the best available
  2165. at the present time, they are not an integral part of the NTP
  2166. specification, since other algorithms with similar or superior
  2167. performance may be devised in future.
  2168.  
  2169. However, it is important to observe that not all time servers or clients
  2170. in an NTP synchronization subnet must implement these algorithms. For
  2171. instance, simple workstations may dispense with one or both of them in
  2172. the interests of simplicity if accuracy and reliability requirements
  2173. justify. Nevertheless, it would be expected that an NTP server providing
  2174. synchronization to a sizable community, such as a university campus or
  2175. research laboratory, would be expected to implement these algorithms or
  2176. others proved to have equivalent functionality. A comprehensive
  2177. discussion of the design principles and performance is given in
  2178. [MIL91a].
  2179.  
  2180. In order for the NTP filter and selection algorithms to operate
  2181. effectively, it is useful to have a measure of recent sample variance
  2182. recorded for each peer. The measure adopted is based on first-order
  2183. differences, which are easy to compute and effective for the purposes
  2184. intended. There are two measures, one called the filter dispersion
  2185. <$Eepsilon sub sigma> and the other the select dispersion <$Eepsilon sub
  2186. xi>. Both are computed as the weighted sum of the clock offsets in a
  2187. temporary list sorted by synchronization distance. If <$Etheta sub i
  2188. ~(0~<<=~i~<<~n)> is the offset of the ith entry, then the sample
  2189. difference <$Eepsilon sub ij> of the ith entry relative to the jth entry
  2190. is defined <$Eepsilon sub ij~<~>=~| theta sub i~-~theta sub j |> . The
  2191. dispersion relative to the jth entry is defined <$Eepsilon sub j> and
  2192. computed as the weighted sum
  2193.  
  2194. <$Eepsilon sub j~=~sum from {i~=~0} to {n~-~1}~epsilon sub ij~w~sup
  2195. {i+1}> ,
  2196.  
  2197. where w is a weighting factor chosen to control the influence of
  2198. synchronization distance in the dispersion budget. In the NTP algorithms
  2199. w is chosen less than <$E1 / 2>: <$Ew~=~roman NTP.FILTER> for filter
  2200. dispersion and <$Ew~=~roman NTP.SELECT> for select dispersion. The
  2201. (absolute) dispersion <$Eepsilon sub sigma> and <$Eepsilon sub xi> as
  2202. used in the NTP algorithms are defined relative to the 0th entry
  2203. <$Eepsilon sub 0>.
  2204.  
  2205. There are two procedures described in the following, the clock-filter
  2206. procedure, which is used to select the best offset samples from a given
  2207. clock, and the clock-selection procedure, which is used to select the
  2208. best clock among a hierarchical set of clocks.
  2209.  
  2210. Clock-Filter Procedure
  2211.  
  2212. The clock-filter procedure is executed upon arrival of an NTP message or
  2213. other event that results in new data samples. It takes arguments of the
  2214. form (<$Etheta ,~delta ,~epsilon>), where <$Etheta> is a sample clock
  2215. offset measurement and <$Edelta> and <$Eepsilon> are the associated
  2216. roundtrip delay and dispersion. It determines the filtered clock offset
  2217. (peer.offset), roundtrip delay (peer.delay) and dispersion
  2218. (peer.dispersion). It also updates the dispersion of samples already
  2219. recorded and saves the current time (peer.update).
  2220.  
  2221. The basis of the clock-filter procedure is the filter shift register
  2222. (peer.filter), which consists of NTP.SHIFT stages, each stage containing
  2223. a 3-tuple <$E[ theta sub i ,~delta sub i ,~epsilon sub i ]>, with
  2224. indices numbered from zero on the left. The filter is initialized with
  2225. the value <$E[0,~0,~roman NTP.MAXDISPERSE]> in all stages by the clear
  2226. procedure. New data samples are shifted into the filter at the left end,
  2227. causing first NULLs then old samples to fall off the right end. The
  2228. packet procedure provides samples of the form (<$Etheta ,~delta
  2229. ,~epsilon>) as new updates arrive, while the transmit procedure provides
  2230. samples of the form <$E[0,~0,~roman NTP.MAXDISPERSE]> when two poll
  2231. intervals elapse without a fresh update. While the same symbols
  2232. (<$Etheta ,~delta ,~epsilon>) are used here for the arguments, clock-
  2233. filter contents and peer variables, the meaning will be clear from
  2234. context. The following pseudo-code describes this procedure.
  2235.  
  2236. begin clock-filter procedure (<$Etheta ,~delta ,~epsilon>)
  2237.  
  2238. The dispersion <$Eepsilon sub i> for all valid samples in the filter
  2239. register must be updated to account for the skew-error accumulation
  2240. since the last update. These samples are also inserted on a temporary
  2241. list with entry format <$E[distance,index]>. The samples in the register
  2242. are shifted right one stage, with the overflow sample discarded and the
  2243. new sample inserted at the leftmost stage. The temporary list is then
  2244. sorted by increasing distance. If no samples remain in the list, the
  2245. procedure exits without updating the peer variables.
  2246.  
  2247.         for (i from NTP.SIZE <196> 1 to 1) begin        /* update
  2248. dispersion */
  2249.                 <$E[ theta sub i ,~delta sub i ,~epsilon sub i ]~<<-~[
  2250. theta sub {i-1} ,~delta sub {i-1} ,~epsilon sub {i-1} ]>;               
  2251. /* shift stage right */
  2252.                 <$Eepsilon sub i~=~epsilon sub i~+~phi tau>;
  2253.                 add <$E[ lambda sub i~==~epsilon sub i~+~{| delta  sub i
  2254. |} over 2 ,~i]> to temporary list;
  2255.                 endfor;
  2256.         <$E[ theta sub 0 ,~delta sub 0 ,~epsilon sub 0 ]~<<-~[ theta
  2257. ,~delta ,~epsilon ]>;                   /* insert new sample */
  2258.         add <$E[ lambda~==~epsilon~+~{| delta |} over 2 ,~0]> to
  2259. temporary list;
  2260.         <$Eroman peer.update~<<-~roman sys.clock>;                      
  2261. /* reset base time */
  2262.         sort temporary list by increasing <$E[distance~||index]>;
  2263.  
  2264. where <$E[distance~||index]> represents the concatenation of the
  2265. distance and index fields and distance is the high-order field. The
  2266. filter dispersion <$Eepsilon sub sigma> is computed and included in the
  2267. peer dispersion. Note that for this purpose the temporary list is
  2268. already sorted.
  2269.  
  2270.         <$Eepsilon sub sigma~<<-~0>;
  2271.         for (i from NTP.SHIFT<196>1 to 0)               /* compute
  2272. filter dispersion */
  2273.                 if (<$Eroman peer.dispersion sub index[i]~>>=~roman
  2274. NTP.MAXDISPERSE> or
  2275.                         <$E| theta sub i~-~theta sub 0 |~>>~roman
  2276. NTP.MAXDISPERSE>)
  2277.                         <$Eepsilon sub sigma~<~><<-~( epsilon sub
  2278. sigma~+~roman NTP.MAXDISPERSE)~times~roman NTP.FILTER>;
  2279.                 else
  2280.                         <$Eepsilon sub sigma~<~><<-~( epsilon sub
  2281. sigma~+~| theta sub i~-~theta sub 0 |)~times~roman NTP.FILTER>;
  2282.  
  2283. The peer offset <$Etheta sub 0>, delay <$Edelta sub 0> and dispersion
  2284. <$Eepsilon sub 0> are chosen as the values corresponding to the minimum-
  2285. distance sample; in other words, the sample corresponding to the first
  2286. entry on the temporary list, here represented as the 0th subscript.
  2287.  
  2288.         <$Eroman peer.offset~<<-~theta sub 0>;                          
  2289. /* update peer variables */
  2290.         <$Eroman peer.delay~<<-~delta sub 0>;
  2291.         <$Eroman peer.dispersion~<<-~min ( epsilon sub 0~+~epsilon sub
  2292. sigma ,~roman NTP.MAXDISPERSE)>;
  2293.         end clock-filter procedure
  2294.  
  2295. The peer.offset and peer.delay variables represent the clock offset and
  2296. roundtrip delay of the local clock relative to the peer clock. Both of
  2297. these are precision quantities and can usually be averaged over long
  2298. intervals in order to improve accuracy and stability without bias
  2299. accumulation (see Appendix H). The peer.dispersion variable represents
  2300. the maximum error due to measurement error, skew-error accumulation and
  2301. sample variance. All three variables are used in the clock-selection and
  2302. clock-combining procedures to select the peer clock(s) used for
  2303. synchronization and to maximize the accuracy and stability of the
  2304. indications.
  2305.  
  2306. Clock-Selection Procedure
  2307.  
  2308. The clock-selection procedure uses the peer variables <$ETHETA>,
  2309. <$EDELTA>, <$EEPSILON> and <$Etau> and is called when these variables
  2310. change or when the reachability status changes. It consists of two
  2311. algorithms, the intersection algorithm and the clustering algorithm. The
  2312. intersection algorithm constructs a list of candidate peers eligible to
  2313. become the synchronization source, computes a confidence interval for
  2314. each and casts out falsetickers using a technique adapted from Marzullo
  2315. and Owicki [MAR85]. The clustering algorithm sorts the list of surviving
  2316. candidates in order of stratum and synchronization distance and
  2317. repeatedly casts out outlyers on the basis of select dispersion until
  2318. only the most accurate, precise and stable survivors are left. A bit is
  2319. set for each survivor to indicate the outcome of the selection process.
  2320. The system variable sys.peer is set as a pointer to the most likely
  2321. survivor, if there is one, or to the NULL value if not.
  2322.  
  2323. Intersection Algorithm
  2324.  
  2325.         begin clock-selection procedure
  2326.  
  2327. Each peer is examined in turn and added to an endpoint list only if it
  2328. passes several sanity checks designed to avoid loops and use of
  2329. exceptionally noisy data. If no peers survive the sanity checks, the
  2330. procedure exits without finding a synchronization source. For each of m
  2331. survivors three entries of the form <$E[endpoint,~type]> are added to
  2332. the endpoint list: <$E[ THETA~-~LAMBDA ,~-~1]>, <$E[ THETA ,~0]> and
  2333. <$E[ THETA~+~LAMBDA ,~1]>. There will be <$E3 m> entries on the list,
  2334. which is then sorted by increasing endpoint.
  2335.  
  2336.         <$Em~<<-~0>;
  2337.         for (each peer)                         /* calling all peers */
  2338.                 if (<$Eroman {peer.reach~!=~0~bold
  2339. and~peer.dispersion~<<~NTP.MAXDISPERSE}> and
  2340.                         not (peer.stratum >> 1 and peer.refid =
  2341. peer.hostaddr)) begin
  2342.                         <$ELAMBDA~<MO>
  2343. <~>an distance (peer)>;                 /* make list entry */
  2344.                         add <$E[ THETA~-~LAMBDA ,~-1]> to endpoint list;
  2345.                         add <$E[ THETA ,~0]> to endpoint list;
  2346.                         add <$E[ THETA~+~LAMBDA ,~1]> to endpoint list;
  2347.                         <$Em~<<-~m~+~1>;
  2348.                         <B>endif
  2349.                 endfor
  2350.         if (<$Em~=~0>) begin                            /* skedaddle if
  2351. no candidates */
  2352.                 <$Eroman sys.peer~<<-~roman NULL>;
  2353.                 <$Eroman sys.stratum~<<-~0~(undefined)>;
  2354.                 exit;
  2355.                 endif
  2356.         sort endpoint list by increasing endpoint||type;
  2357.  
  2358. The following algorithm is adapted from DTS [DEC89] and is designed to
  2359. produce the largest single intersection containing only truechimers. The
  2360. algorithm begins by initializing a value f and counters i and c to zero.
  2361. Then, starting from the lowest endpoint of the sorted endpoint list, for
  2362. each entry <$E[endpoint,~type]> the value of type is subtracted from the
  2363. counter i, which is the number of intersections. If type is zero,
  2364. increment the value of c, which is the number of falsetickers (see
  2365. Appendix H). If <$Ei~>>=~m~-~f> for some entry, endpoint of that entry
  2366. becomes the lower endpoint of the intersection; otherwise, f is
  2367. increased by one and the above procedure is repeated. Without resetting
  2368. f or c, a similar procedure is used to find the upper endpoint, except
  2369. that the value of type is added to the counter.. If after both endpoints
  2370. have been determined <$Ec~<<=~f>, the procedure continues having found
  2371. <$Em~-~f> truechimers; otherwise, f is increased by one and the entire
  2372. procedure is repeated.
  2373.  
  2374.         for (f from 0 to <$Ef~>>=~m over 2>) begin              /*
  2375. calling all truechimers */
  2376.                 <$Ec~<<-~0>;
  2377.                 <$Ei~<<-~0>;
  2378.                 for (each [endpoint, type] from lowest) begin   /* find
  2379. low endpoint */
  2380.                         <$Ei~<<-~i~-~type>;
  2381.                         <$Elow~<<-~endpoint>;
  2382.                         if (<$Ei~>>=~m~-~f>) break;
  2383.                         if (<$Etype~=~0>) <$Ec~<<-~c~+~1>;
  2384.                         endfor;
  2385.                 <$Ei~<<-~0>;
  2386.  
  2387.                 for (each [endpoint, type] from highest) begin  /* find
  2388. high endpoint */
  2389.                         <$Ei~<<-~i~+~type>;
  2390.                         <$Ehigh~<<-~endpoint>;
  2391.                         if (<$Ei~>>=~m~-~f>) break;
  2392.                         if (<$Etype~=~0>) <$Ec~<<-~c~+~1>;
  2393.                         endfor;
  2394.                 if (<$Ec~<<=~f>) break;                 /* continue
  2395. until all falsetickers found */
  2396.                 endfor;
  2397.         if (<$Elow~>>~high>) begin                              /* quit
  2398. if no intersection found */
  2399.                 <$Eroman sys.peer~<<-~roman NULL>;
  2400.                 exit;
  2401.                 endif;
  2402.  
  2403. Note that processing continues past this point only if there are more
  2404. than <$Em over 2> intersections. However, it is possible, but not highly
  2405. likely, that there may be fewer than <$Em over 2> truechimers remaining
  2406. in the intersection.
  2407.  
  2408. Clustering Algorithm
  2409.  
  2410. In the original DTS algorithm the clock-selection procedure exits at
  2411. this point with the presumed correct time set midway in the computed
  2412. intersection <$E[low,~high]>. However, this can lead to a considerable
  2413. loss in accuracy and stability, since the individual peer statistics are
  2414. lost. Therefore, in NTP the candidates that survived the preceding steps
  2415. are processed further. The candidate list is rebuilt with entries of the
  2416. form <$E[distance,~index]>, where distance is computed from the (scaled)
  2417. peer stratum and synchronization distance <$ELAMBDA>. The scaling factor
  2418. provides a mechanism to weight the combination of stratum and distance.
  2419. Ordinarily, the stratum will dominate, unless one or more of the
  2420. survivors has an exceptionally high distance. The list is then sorted by
  2421. increasing distance.
  2422.  
  2423.         <$Em~<<-~0>;
  2424.         for (each peer) begin                   /* calling all peers */
  2425.                 if (<$Elow~<<=~theta~<<=~high>) begin
  2426.                         <$ELAMBDA~<<-~roman distance (peer)>;           
  2427. /* make list entry */
  2428.                         <$Edist~<<-~roman
  2429. {peer.stratum~times~NTP.MAXDISPERSE~+~LAMBDA }>
  2430.                         add <$E[ dist ,~peer]> to candidate list;
  2431.                         <$Em~<<-~m~+~1>;
  2432.                         endif;
  2433.                 endfor;
  2434.         sort candidate list by increasing dist;
  2435.  
  2436. The next steps are designed to cast out outlyers which exhibit
  2437. significant dispersions relative to the other members of the candidate
  2438. list while minimizing wander, especially on high-speed LANs with many
  2439. time servers. Wander causes needless network overhead, since the poll
  2440. interval is clamped at sys.poll as each new peer is selected for
  2441. synchronization and only slowly increases when the peer is no longer
  2442. selected. It has been the practical experience that the number of
  2443. candidates surviving to this point can become quite large and can result
  2444. in significant processor cycles without materially enhancing stability
  2445. and accuracy. Accordingly, the candidate list is truncated at
  2446. NTP.MAXCLOCK entries.
  2447.  
  2448. Note <$Eepsilon sub {xi i}> is the select (sample) dispersion relative
  2449. to the ith peer represented on the candidate list, which can be
  2450. calculated in a manner similar to the filter dispersion described
  2451. previously. The <$EEPSILON sub j> is the dispersion of the jth peer
  2452. represented on the list and includes components due to measurement
  2453. error, skew-error accumulation and filter dispersion. If the maximum
  2454. <$Eepsilon sub {xi i}> is greater than the minimum <$EEPSILON sub j> and
  2455. the number of survivors is greater than NTP.MINCLOCK, the ith peer is
  2456. discarded from the list and the procedure is repeated. If the current
  2457. synchronization source is one of the survivors and there is no other
  2458. survivor of lower stratum, then the procedure exits without doing
  2459. anything further. Otherwise, the synchronization source is set to the
  2460. first survivor on the candidate list. In the following i, j, k, l are
  2461. peer indices, with k the index of the current synchronization source
  2462. (NULL if none) and l the index of the first survivor on the candidate
  2463. list.
  2464.  
  2465.         while begin
  2466.                 for (each survivor <$E[distance,~index]>) begin /*
  2467. compute dispersions */
  2468.                         find index i for max <$Eepsilon sub {xi i}>;
  2469.                         find index j for min <$EEPSILON sub j>;
  2470.                         endfor
  2471.                 if (<$Eepsilon sub {xi i}~<<=~EPSILON sub j> or
  2472. <$Em~<<=~roman NTP.MINCLOCK>) break;
  2473.                 <$Eroman peer.survivor [i]~<<-~0> ;             /*
  2474. discard ith peer */
  2475.                 if (<$Ei~=~k>) <$Eroman sys.peer~<<-~roman NULL>;
  2476.                 delete the ith peer from the candidate list;
  2477.                 <$Em~<<-~m~-~1>;
  2478.                 endwhile
  2479.         if (<$Eroman peer.survivor [k]~=~0> or <$Eroman peer.stratum
  2480. [k]~>>~roman peer.stratum [l]>) begin
  2481.                 <$Eroman sys.peer~<<-~l>;                               
  2482. /* new clock source */
  2483.                 call poll-update;
  2484.                 endif
  2485.         end clock-select procedure;
  2486.  
  2487. The algorithm is designed to favor those peers near the head of the
  2488. candidate list, which are at the lowest stratum and distance and
  2489. presumably can provide the most accurate and stable time. With proper
  2490. selection of weight factor v (also called NTP.SELECT), entries will be
  2491. trimmed from the tail of the list, unless a few outlyers disagree
  2492. significantly with respect to the remaining entries, in which case the
  2493. outlyers are discarded first. The termination condition is designed to
  2494. avoid needless switching between synchronization sources when not
  2495. statistically justified, yet maintain a bias toward the low-stratum,
  2496. low-distance peers.
  2497.  
  2498. Local Clocks
  2499.  
  2500. In order to implement a precise and accurate local clock, the host must
  2501. be equipped with a hardware clock consisting of an oscillator and
  2502. interface and capable of the required precision and stability. A logical
  2503. clock is then constructed using these components plus software
  2504. components that adjust the apparent time and frequency in response to
  2505. periodic updates computed by NTP or some other time-synchronization
  2506. protocol such as Hellospeak [MIL83b] or the Unix 4.3bsd TSP [GUS85a].
  2507. This section describes the Fuzzball local-clock model and
  2508. implementation, which includes provisions for precise time and frequency
  2509. adjustment and can maintain time to within 15 ns and frequency to within
  2510. 0.3 ms per day. The model is suitable for use with both compensated and
  2511. uncompensated quartz oscillators and can be adapted to power-frequency
  2512. oscillators. A summary of the characteristics of these and other types
  2513. of oscillators can be found in Appendix E, while a comprehensive
  2514. mathematical analysis of the NTP local-clock model can be found in
  2515. Appendix G.
  2516.  
  2517. It is important to note that the particular implementation described is
  2518. only one of possibly many implementations that provide equivalent
  2519. functionality. However, it is equally important to note that the clock
  2520. model described in Appendix G and which is the basis of the
  2521. implementation involves a particular kind of control-feedback loop that
  2522. is potentially unstable if the design rules are broken. The model and
  2523. parameter described in Appendix G are designed to provide accurate and
  2524. stable time under typical operating conditions using conventional
  2525. hardware and in the face of disruptions in hardware or network
  2526. connectivity. The parameters have been engineered for reliable operation
  2527. in a multi-level hierarchical subnet where unstable operation at one
  2528. level can disrupt possibly many other levels.
  2529.  
  2530. Fuzzball Implementation
  2531.  
  2532. The Fuzzball local clock consists of a collection of hardware and
  2533. software registers, together with a set of algorithms, which implement a
  2534. logical clock that functions as a disciplined oscillator and
  2535. synchronizes to an external source. Following is a description of its
  2536. components and manner of operation. Note that all arithmetic is two's
  2537. complement integer and all shifts <169><<<<<170> and <169>>>>><170> are
  2538. arithmetic (sign-fill for right shifts and zero-fill for left shifts).
  2539. Also note that <$Ex~<< <<~n> is equivalent to <$Ex~>> >>~-~n>.
  2540.  
  2541. The principal components of the local clock are shown in Figure
  2542. 3,<$&fig3> in which the fraction points shown are relative to whole
  2543. milliseconds. The 48-bit Clock register and 32-bit Prescaler function as
  2544. a disciplined oscillator which increments in milliseconds relative to
  2545. midnight at the fraction point. The 32-bit Clock-Adjust register is used
  2546. to adjust the oscillator phase in gradual steps to avoid discontinuities
  2547. in the indicated timescale. Its contents are designated x in the
  2548. following. The 32-bit Skew-Compensation register is used to trim the
  2549. oscillator frequency by adding small phase increments at periodic
  2550. adjustment intervals and can compensate for frequency errors as much as
  2551. .01% or <F128M>µ<F255D>100 ppm. Its contents are designated y in the
  2552. following. The 16-bit Watchdog counter and 32-bit Compliance register
  2553. are used to determine validity, as well as establish the PLL bandwidth
  2554. and poll interval (see Appendix G). The contents of the Compliance
  2555. register are designated z in the following. The 32-bit PPS-Adjust
  2556. register is used to hold a precision time adjustment when a source of 1-
  2557. pps pulses is available, while the 8-bit PPS counter is used to verify
  2558. presence of these pulses. The two-bit Flags register contains the two
  2559. leap bits described elsewhere (leap).
  2560.  
  2561. All registers except the Prescaler register are ordinarily implemented
  2562. in memory. In typical clock interface designs such as the DEC KWV11-C,
  2563. the Prescaler register is implemented as a 16-bit buffered counter
  2564. driven by a quartz-controlled oscillator at some multiple of 1000 Hz. A
  2565. counter overflow is signalled by an interrupt, which results in an
  2566. increment of the Clock register at the bit corresponding to the
  2567. overflow. The time of day is determined by reading the Prescaler
  2568. register, which does not disturb the counting process, and adding its
  2569. value to that of the Clock register with fraction points aligned as
  2570. shown and with unimplemented low-order bits set to zero. In other
  2571. interface designs, such as the LSI-11 event-line mechanism, each tick of
  2572. the clock is signalled by an interrupt at intervals of 16-2/3 ms or 20
  2573. ms, depending on interface and mains frequency. When this occurs the
  2574. appropriate increment in fractional milliseconds is added to the Clock
  2575. register.
  2576.  
  2577. The various parameters used are summarized in Table 6, in which certain
  2578. parameters have been rescaled from those given in Appendix G due to the
  2579. units here being in milliseconds.<$&tab6> When the system is
  2580. initialized, all registers and counters are cleared and the leap bits
  2581. set to 112 (unsynchronized). At adjustment intervals of CLOCK.ADJ
  2582. seconds CLOCK.ADJ is subtracted from the PPS counter, but only if the
  2583. previous contents of the PPS counter are greater than zero. Also,
  2584. CLOCK.ADJ is added to the Watchdog counter, but the latter is clamped
  2585. not to exceed NTP.MAXAGE divided by CLOCK.ADJ (one full day). In
  2586. addition, if the Watchdog counter reaches this value, the leap bits are
  2587. set to 112 (unsynchronized).
  2588.  
  2589. In some system configurations a precise source of timing information is
  2590. available in the form of a train of timing pulses spaced at one-second
  2591. intervals. Usually, this is in addition to a source of timecode
  2592. information, such as a radio clock or even NTP itself, to number the
  2593. seconds, minutes, hours and days. In typical clock interface designs
  2594. such as the DEC KWV11-C, a special input is provided which can trigger
  2595. an interrupt as each pulse is received. When this happens the PPS
  2596. counter is set to CLOCK.PPS and the current time offset is determined in
  2597. the usual way. Then, the PPS-Adjust register is set to the time offset
  2598. scaled to milliseconds. Finally, if the PPS-Adjust register is greater
  2599. than or equal to 500, 1000 is subtracted from its contents. As described
  2600. below, the PPS-Adjust register and PPS counters can be used in
  2601. conjunction with an ordinary timecode to produce an extremely accurate
  2602. local clock.
  2603.  
  2604. Gradual Phase Adjustments
  2605.  
  2606. Left uncorrected, the local clock runs at the offset and frequency
  2607. resulting from its last update. An update is produced by an event that
  2608. results in a valid clock selection. It consists of a signed 48-bit
  2609. integer in whole milliseconds and fraction, with fraction point to the
  2610. left of bit 32. If the magnitude is greater than the maximum aperture
  2611. CLOCK.MAX, a step adjustment is required, in which case proceed as
  2612. described later. Otherwise, a gradual phase adjustment is performed.
  2613. Normally, the update is computed by the NTP algorithms described
  2614. previously; however, if the PPS counter is greater than zero, the value
  2615. of the PPS-Adjust register is used instead. Let u be a 32-bit quantity
  2616. with bits 0-31 set as bits 16-47 of the update. If some of the low-order
  2617. bits of the update are unimplemented, they are set as the value of the
  2618. sign bit. These operations move the fraction point of u to the left of
  2619. bit 16 and minimize the effects of truncation and roundoff errors. Let b
  2620. be the number of leading zeros of the absolute value of the Compliance
  2621. register and let c be the number of leading zeros of the Watchdog
  2622. counter, both of which are easily computed by compact loops. Then, set b
  2623. to
  2624. <$Eb~=~b~-~16~+~roman CLOCK.COMP>
  2625.  
  2626. and clamp it to be not less than zero. This represents the logarithm of
  2627. the loop time constant. Then, set c to
  2628.  
  2629. <$Ec~=~10~-~c>
  2630.  
  2631. and clamp it to be not greater than NTP.MAXPOLL <196> NTP.MINPOLL. This
  2632. represents the logarithm of the integration interval since the last
  2633. update. The clamps insure stable operation under typical conditions
  2634. encountered in the Internet. Then, compute new values for the Clock-
  2635. Adjust and Skew-Compensation registers
  2636.  
  2637. <$Ex~=~u~>> >>~b> ,
  2638. <$Ey~=~y~+~(u~>> >>~(b~+~b~-~c))> .
  2639.  
  2640. Finally, compute the exponential average
  2641.  
  2642. <$Ez~=~z~+~(u~<< <<~(b~+~ roman CLOCK.MULT)~-~z)~>> >>~ roman
  2643. CLOCK.WEIGHT> ,
  2644.  
  2645. where the left shift realigns the fraction point for greater precision
  2646. and ease of computation.
  2647.  
  2648. At each adjustment interval the final clock correction consisting of two
  2649. components is determined. The first (phase) component consists of the
  2650. quantity
  2651.  
  2652. <$Ex~>> >>~ roman CLOCK.PHASE> ,
  2653.  
  2654. which is then subtracted from the previous contents of the Clock-Adjust
  2655. register to form the new contents of that register. The second
  2656. (frequency) component consists of the quantity
  2657.  
  2658. <$Ey~>> >>~ roman CLOCK.FREQ> .
  2659.  
  2660. The sum of the phase and frequency components is the final clock
  2661. correction, which is then added to the Clock register. FInally, the
  2662. Watchdog counter is set to zero. Operation continues in this way until a
  2663. new correction is introduced.
  2664.  
  2665. The value of b computed above can be used to update the poll interval
  2666. system variable (sys.poll). This functions as an adaptive parameter that
  2667. provides a very valuable feature which reduces the polling overhead,
  2668. especially if the clock-combining algorithm described in Appendix F is
  2669. used:
  2670.  
  2671. <$Eroman sys.poll~<<-~b~+~roman NTP.MINPOLL> .
  2672.  
  2673. Under conditions when update noise is high or the hardware oscillator
  2674. frequency is changing relatively rapidly due to environmental
  2675. conditions, the magnitude of the compliance increases. With the
  2676. parameters specified, this causes the loop bandwidth (reciprocal of time
  2677. constant) to increase and the poll interval to decrease, eventually to
  2678. NTP.MINPOLL seconds. When noise is low and the hardware oscillator very
  2679. stable, the compliance decreases, which causes the loop bandwidth to
  2680. decrease and the poll interval to increase, eventually to NTP.MAXPOLL
  2681. seconds.
  2682.  
  2683. The parameters in Table 6 have been selected so that, under good
  2684. conditions with updates in the order of a few milliseconds, a precision
  2685. of a millisecond per day (about .01 ppm or 10-8), can be achieved. Care
  2686. is required in the implementation to insure monotonicity of the Clock
  2687. register and to preserve the highest precision while minimizing the
  2688. propagation of roundoff errors. Since all of the multiply/divide
  2689. operations (except those involved with the 1-pps pulses) computed in
  2690. real time can be approximated by bitwise-shift operations, it is not
  2691. necessary to implement a full multiply/divide capability in hardware or
  2692. software.
  2693.  
  2694. In the various implementations of NTP for many Unix-based systems it has
  2695. been the common experience that the single most important factor
  2696. affecting local-clock stability is the matching of the phase and
  2697. frequency coefficients to the particular kernel implementation. It is
  2698. vital that these coefficients be engineered according to the model
  2699. values, for otherwise the PLL can fail to track normal oscillator
  2700. variations and can even become unstable.
  2701.  
  2702. Step Phase Adjustments
  2703.  
  2704. When the magnitude of a correction exceeds the maximum aperture
  2705. CLOCK.MAX, the possibility exists that the clock is so far out of
  2706. synchronization with the reference source that the best action is an
  2707. immediate and wholesale replacement of Clock register contents, rather
  2708. than in gradual adjustments as described above. However, in cases where
  2709. the sample variance is extremely high, it is prudent to disbelieve a
  2710. step change, unless a significant interval has elapsed since the last
  2711. gradual adjustment. Therefore, if a step change is indicated and the
  2712. Watchdog counter is less than the preconfigured value CLOCK.MINSTEP, the
  2713. update is ignored and the local-clock procedure exits. These safeguards
  2714. are especially useful in those system configurations using a calibrated
  2715. atomic clock or LORAN-C receiver in conjunction with a separate source
  2716. of seconds-numbering information, such as a radio clock or NTP peer.
  2717.  
  2718. If a step change is indicated the update is added directly to the Clock
  2719. register and the Clock-Adjust register and Watchdog counter both set to
  2720. zero, but the other registers are left undisturbed. Since a step change
  2721. invalidates data currently in the clock filters, the leap bits are set
  2722. to 112 (unsynchronized) and, as described elsewhere, the clear procedure
  2723. is called to purge the clock filters and state variables for all peers.
  2724. In practice, the necessity to perform a step change is rare and usually
  2725. occurs when the local host or reference source is rebooted, for example.
  2726. This is fortunate, since step changes can result in the local clock
  2727. apparently running backward, as well as incorrect delay and offset
  2728. measurements of the synchronization mechanism itself.
  2729.  
  2730. Considerable experience with the Internet environment suggests the
  2731. values of CLOCK.MAX tabulated in Table 6 as appropriate. In practice,
  2732. these values are exceeded with a single time-server source only under
  2733. conditions of the most extreme congestion or when multiple failures of
  2734. nodes or links have occurred. The most common case when the maximum is
  2735. exceeded is when the time-server source is changed and the time
  2736. indicated by the new and old sources exceeds the maximum due to
  2737. systematic errors in the primary reference source or large differences
  2738. in path delays. It is recommended that implementations include
  2739. provisions to tailor CLOCK.MAX for specific situations. The amount that
  2740. CLOCK.MAX can be increased without violating the monotonicity
  2741. requirement depends on the Clock register increment. For an increment of
  2742. 10 ms, as used in many workstations, the value shown in Table 6 can be
  2743. increased by a factor of five.
  2744.  
  2745. Implementation Issues
  2746.  
  2747. The basic NTP robustness model is that a host has no other means to
  2748. verify time other than NTP itself. In some equipment a battery-backed
  2749. clock/calendar is available for a sanity check. If such a device is
  2750. available, it should be used only to confirm sanity of the timekeeping
  2751. system, not as the source of system time. In the common assumption (not
  2752. always justified) that the clock/calendar is more reliable, but less
  2753. accurate, than the NTP synchronization subnet, the recommended approach
  2754. at initialization is to set the Clock register as determined from the
  2755. clock/calendar and the other registers, counters and flags as described
  2756. above. On subsequent updates if the time offset is greater than a
  2757. configuration parameter (e.g., 1000 seconds), then the update should be
  2758. discarded and an error condition reported. Some implementations
  2759. periodically record the contents of the Skew-Compensation register in
  2760. stable storage such as a system file or NVRAM and retrieve this value at
  2761. initialization. This can significantly reduce the time to converge to
  2762. the nominal stability and accuracy regime.
  2763.  
  2764. Conversion from NTP format to the common date and time formats used by
  2765. application programs is simplified if the internal local-clock format
  2766. uses separate date and time variables. The time variable is designed to
  2767. roll over at 24 hours, give or take a leap second as determined by the
  2768. leap-indicator bits, with its overflows (underflows) incrementing
  2769. (decrementing) the date variable. The date and time variables then
  2770. indicate the number of days and seconds since some previous reference
  2771. time, but uncorrected for intervening leap seconds.
  2772.  
  2773. On the day prior to the insertion of a leap second the leap bits
  2774. (sys.leap) are set at the primary servers, presumably by manual means.
  2775. Subsequently, these bits show up at the local host and are passed to the
  2776. local-clock procedure. This causes the modulus of the time variable,
  2777. which is the length of the current day, to be increased or decreased by
  2778. one second as appropriate. Immediately following insertion the leap bits
  2779. are reset. Additional discussion on this issue can be found in Appendix
  2780. E.
  2781.  
  2782. Lack of a comprehensive mechanism to administer the leap bits in the
  2783. primary servers is presently an awkward problem better suited to a
  2784. comprehensive network-management mechanism yet to be developed. As a
  2785. practical matter and unless specific provisions have been made
  2786. otherwise, currently manufactured radio clocks have no provisions for
  2787. leap seconds, either automatic or manual. Thus, when a leap actually
  2788. occurs, the radio must resynchronize to the broadcast timecode, which
  2789. may take from a few minutes to some hours. Unless special provisions are
  2790. made, a primary server might leap to the new timescale, only to be
  2791. yanked back to the previous timescale when it next synchronizes to the
  2792. radio. Subsequently, the server will be yanked forward again when the
  2793. radio itself resynchronizes to the broadcast timecode.
  2794.  
  2795. This problem can not be reliably avoided using any selection algorithm,
  2796. since there will always exist an interval of at least a couple of
  2797. minutes and possibly as much as some hours when some or all radios will
  2798. be out of synchronization with the broadcast timecode and only after the
  2799. majority of them have resynchronized will the subnet settle down. The
  2800. CLOCK.MINSTEP delay is designed to cope with this problem by forcing a
  2801. minimum interval since the last gradual adjustment was made before
  2802. allowing a step change to occur. Therefore, until the radio
  2803. resynchronizes, it will continue on the old timescale, which is one
  2804. second off the local clock after the leap and outside the maximum
  2805. aperture CLOCK.MAX permitted for gradual phase adjustments. When the
  2806. radio eventually resynchronizes, it will almost certainly come up within
  2807. the aperture and again become the reference source. Thus, even in the
  2808. unlikely case when the local clock incorrectly leaps, the server will go
  2809. no longer than CLOCK.MINSTEP seconds before resynchronizing.
  2810.  
  2811. Acknowledgments
  2812.  
  2813. Many people contributed to the contents of this document, which was
  2814. thoroughly debated by electronic mail and debugged using two different
  2815. prototype implementations for the Unix 4.3bsd operating system, one
  2816. written by Louis Mamakos and Michael Petry of the University of Maryland
  2817. and the other by Dennis Ferguson of the University of Toronto. Another
  2818. implementation for the Fuzzball operating system [MIL88b] was written by
  2819. the author. Many individuals to numerous to mention meticulously tested
  2820. the several beta-test prototype versions and ruthlessly smoked out the
  2821. bugs, both in the code and the specification. Especially useful were
  2822. comments from Dennis Ferguson and Bill Sommerfeld, as well as
  2823. discussions with Joe Comuzzi and others at Digital Equipment
  2824. Corporation.
  2825.  
  2826. References
  2827.  
  2828. [ABA89]
  2829.  
  2830. Abate, et al. AT&T's new approach to the synchronization of
  2831. telecommunication networks. IEEE Communications Magazine (April 1989),
  2832. 35-45.
  2833.  
  2834. [ALL74a]
  2835.  
  2836. Allan, D.W., J.H. Shoaf and D. Halford. Statistics of time and frequency
  2837. data analysis. In: Blair, B.E. (Ed.). Time and Frequency Theory and
  2838. Fundamentals. National Bureau of Standards Monograph 140, U.S.
  2839. Department of Commerce, 1974, 151-204.
  2840.  
  2841. [ALL74b]
  2842.  
  2843. Allan, D.W., J.E. Gray and H.E. Machlan. The National Bureau of
  2844. Standards atomic time scale: generation, stability, accuracy and
  2845. accessibility. In: Blair, B.E. (Ed.). Time and Frequency Theory and
  2846. Fundamentals. National Bureau of Standards Monograph 140, U.S.
  2847. Department of Commerce, 1974, 205-231.
  2848.  
  2849. [BEL86]
  2850.  
  2851. Bell Communications Research. Digital Synchronization Network Plan.
  2852. Technical Advisory TA-NPL-000436, 1 November 1986.
  2853.  
  2854. [BER87]
  2855.  
  2856. Bertsekas, D., and R. Gallager. Data Networks. Prentice-Hall, Englewood
  2857. Cliffs, NJ, 1987.
  2858.  
  2859. [BLA74]
  2860.  
  2861. Blair, B.E. Time and frequency dissemination: an overview of principles
  2862. and techniques. In: Blair, B.E. (Ed.). Time and Frequency Theory and
  2863. Fundamentals. National Bureau of Standards Monograph 140, U.S.
  2864. Department of Commerce, 1974, 233-314.
  2865.  
  2866. [BRA80]
  2867.  
  2868. Braun, W.B. Short term frequency effects in networks of coupled
  2869. oscillators. IEEE Trans. Communications COM-28, 8 (August 1980), 1269-
  2870. 1275.
  2871.  
  2872. [COL88]
  2873.  
  2874. Cole, R., and C. Foxcroft. An experiment in clock synchronisation. The
  2875. Computer Journal 31, 6 (1988), 496-502.
  2876.  
  2877. [DAR81a]
  2878.  
  2879. Defense Advanced Research Projects Agency. Internet Protocol. DARPA
  2880. Network Working Group Report RFC-791, USC Information Sciences
  2881. Institute, September 1981.
  2882.  
  2883. [DAR81b]
  2884.  
  2885. Defense Advanced Research Projects Agency. Internet Control Message
  2886. Protocol. DARPA Network Working Group Report RFC-792, USC Information
  2887. Sciences Institute, September 1981.
  2888.  
  2889. [DEC89]
  2890.  
  2891. Digital Time Service Functional Specification Version T.1.0.5. Digital
  2892. Equipment Corporation, 1989.
  2893.  
  2894. [DER90]
  2895.  
  2896. Dershowitz, N., and E.M. Reingold. Calendrical Calculations. Software
  2897. Practice and Experience 20, 9 (September 1990), 899-928.
  2898.  
  2899. [FRA82]
  2900.  
  2901. Frank, R.L. History of LORAN-C. Navigation 29, 1 (Spring 1982).
  2902.  
  2903. [GUS84]
  2904.  
  2905. Gusella, R., and S. Zatti. TEMPO - A network time controller for a
  2906. distributed Berkeley UNIX system. IEEE Distributed Processing Technical
  2907. Committee Newsletter 6, NoSI-2 (June 1984), 7-15. Also in: Proc. Summer
  2908. USENIX Conference (June 1984, Salt Lake City).
  2909.  
  2910. [GUS85a]
  2911.  
  2912. Gusella, R., and S. Zatti. The Berkeley UNIX 4.3BSD time synchronization
  2913. protocol: protocol specification. Technical Report UCB/CSD 85/250,
  2914. University of California, Berkeley, June 1985.
  2915.  
  2916. [GUS85b]
  2917.  
  2918. Gusella, R., and S. Zatti. An election algorithm for a distributed clock
  2919. synchronization program. Technical Report UCB/CSD 86/275, University of
  2920. California, Berkeley, December 1985.
  2921.  
  2922. [HAL84]
  2923.  
  2924. Halpern, J.Y., B. Simons, R. Strong and D. Dolly. Fault-tolerant clock
  2925. synchronization. Proc. Third Annual ACM Symposium on Principles of
  2926. Distributed Computing (August 1984), 89-102.
  2927.  
  2928. [JOR85]
  2929.  
  2930. Jordan, E.C. (Ed). Reference Data for Engineers, Seventh Edition. H.W.
  2931. Sams & Co., New York, 1985.
  2932.  
  2933. [KOP87]
  2934.  
  2935. Kopetz, H., and W. Ochsenreiter. Clock synchronization in distributed
  2936. real-time systems. IEEE Trans. Computers C-36, 8 (August 1987), 933-939.
  2937.  
  2938. [LAM78]
  2939.  
  2940. Lamport, L., Time, clocks and the ordering of events in a distributed
  2941. system. Comm. ACM 21, 7 (July 1978), 558-565.
  2942.  
  2943. [LAM85]
  2944.  
  2945. Lamport, L., and P.M. Melliar-Smith. Synchronizing clocks in the
  2946. presence of faults. J. ACM 32, 1 (January 1985), 52-78.
  2947.  
  2948. [LIN80]
  2949.  
  2950. Lindsay, W.C., and A.V. Kantak. Network synchronization of random
  2951. signals. IEEE Trans. Communications COM-28, 8 (August 1980), 1260-1266.
  2952.  
  2953. [LUN84]
  2954.  
  2955. Lundelius, J., and N.A. Lynch. A new fault-tolerant algorithm for clock
  2956. synchronization. Proc. Third Annual ACM Symposium on Principles of
  2957. Distributed Computing (August 1984), 75-88.
  2958.  
  2959. [MAR85]
  2960.  
  2961. Marzullo, K., and S. Owicki. Maintaining the time in a distributed
  2962. system. ACM Operating Systems Review 19, 3 (July 1985), 44-54.
  2963.  
  2964. [MIL81a]
  2965.  
  2966. Mills, D.L. Time Synchronization in DCNET Hosts. DARPA Internet Project
  2967. Report IEN-173, COMSAT Laboratories, February 1981.
  2968.  
  2969. [MIL81b]
  2970.  
  2971. Mills, D.L. DCNET Internet Clock Service. DARPA Network Working Group
  2972. Report RFC-778, COMSAT Laboratories, April 1981.
  2973.  
  2974. [MIL83a]
  2975.  
  2976. Mills, D.L. Internet Delay Experiments. DARPA Network Working Group
  2977. Report RFC-889, M/A-COM Linkabit, December 1983.
  2978.  
  2979. [MIL83b]
  2980.  
  2981. Mills, D.L. DCN local-network protocols. DARPA Network Working Group
  2982. Report RFC-891, M/A-COM Linkabit, December 1983.
  2983.  
  2984. [MIL85a]
  2985.  
  2986. Mills, D.L. Algorithms for synchronizing network clocks. DARPA Network
  2987. Working Group Report RFC-956, M/A-COM Linkabit, September 1985.
  2988.  
  2989. [MIL85b]
  2990.  
  2991. Mills, D.L. Experiments in network clock synchronization. DARPA Network
  2992. Working Group Report RFC-957, M/A-COM Linkabit, September 1985.
  2993.  
  2994. [MIL85c]
  2995.  
  2996. Mills, D.L. Network Time Protocol (NTP). DARPA Network Working Group
  2997. Report RFC-958, M/A-COM Linkabit, September 1985.
  2998.  
  2999. [MIL88a]
  3000.  
  3001. Mills, D.L. Network Time Protocol (version 1) - specification and
  3002. implementation. DARPA Network Working Group Report RFC-1059, University
  3003. of Delaware, July 1988.
  3004.  
  3005. [MIL88b]
  3006.  
  3007. Mills, D.L. The Fuzzball. Proc. ACM SIGCOMM 88 Symposium (Palo Alto, CA,
  3008. August 1988), 115-122.
  3009.  
  3010. [MIL89]
  3011.  
  3012. Mills, D.L. Network Time Protocol (version 2) - specification and
  3013. implementation. DARPA Network Working Group Report RFC-1119, University
  3014. of Delaware, September 1989.
  3015.  
  3016. [MIL90]
  3017.  
  3018. Mills, D.L. Measured performance of the Network Time Protocol in the
  3019. Internet system. ACM Computer Communication Review 20, 1 (January 1990),
  3020. 65-75.
  3021.  
  3022. [MIL91a]
  3023.  
  3024. Mills, D.L. Internet time synchronization: the Network Time Protocol.
  3025. IEEE Trans. Communications 39, 10 (October 1991), 1482-1493.
  3026.  
  3027. [MIL91b]
  3028.  
  3029. Mills, D.L. On the chronology and metrology of computer network
  3030. timescales and their application to the Network Time Protocol. ACM
  3031. Computer Communications Review 21, 5 (October 1991), 8-17.
  3032.  
  3033. [MIT80]
  3034.  
  3035. Mitra, D. Network synchronization: analysis of a hybrid of master-slave
  3036. and mutual synchronization. IEEE Trans. Communications COM-28, 8 (August
  3037. 1980), 1245-1259.
  3038.  
  3039. [NBS77]
  3040.  
  3041. Data Encryption Standard. Federal Information Processing Standards
  3042. Publication 46. National Bureau of Standards, U.S. Department of
  3043. Commerce, 1977.
  3044.  
  3045. [NBS79]
  3046.  
  3047. Time and Frequency Dissemination Services. NBS Special Publication 432,
  3048. U.S. Department of Commerce, 1979.
  3049.  
  3050. [NBS80]
  3051.  
  3052. DES Modes of Operation. Federal Information Processing Standards
  3053. Publication 81. National Bureau of Standards, U.S. Department of
  3054. Commerce, December 1980.
  3055.  
  3056. [POS80]
  3057.  
  3058. Postel, J. User Datagram Protocol. DARPA Network Working Group Report
  3059. RFC-768, USC Information Sciences Institute, August 1980.
  3060.  
  3061. [POS83a]
  3062.  
  3063. Postel, J. Daytime protocol. DARPA Network Working Group Report RFC-867,
  3064. USC Information Sciences Institute, May 1983.
  3065.  
  3066. [POS83b]
  3067.  
  3068. Postel, J. Time protocol. DARPA Network Working Group Report RFC-868,
  3069. USC Information Sciences Institute, May 1983.
  3070.  
  3071. [RIC88]
  3072.  
  3073. Rickert, N.W. Non Byzantine clock synchronization - a programming
  3074. experiment. ACM Operating Systems Review 22, 1 (January 1988), 73-78.
  3075.  
  3076. [SCH86]
  3077.  
  3078. Schneider, F.B. A paradigm for reliable clock synchronization.
  3079. Department of Computer Science Technical Report TR 86-735, Cornell
  3080. University, February 1986.
  3081.  
  3082. [SMI86]
  3083.  
  3084. Smith, J. Modern Communications Circuits. McGraw-Hill, New York, NY,
  3085. 1986.
  3086.  
  3087. [SRI87]
  3088.  
  3089. Srikanth, T.K., and S. Toueg. Optimal clock synchronization. J. ACM 34,
  3090. 3 (July 1987), 626-645.
  3091.  
  3092. [STE88]
  3093.  
  3094. Steiner, J.G., C. Neuman, and J.I. Schiller. Kerberos: an authentication
  3095. service for open network systems. Proc. Winter USENIX Conference
  3096. (February 1988).
  3097.  
  3098. [SU81]
  3099.  
  3100. Su, Z. A specification of the Internet protocol (IP) timestamp option.
  3101. DARPA Network Working Group Report RFC-781. SRI International, May 1981.
  3102.  
  3103. [TRI86]
  3104.  
  3105. Tripathi, S.K., and S.H. Chang. ETempo: a clock synchronization
  3106. algorithm for hierarchical LANs - implementation and measurements.
  3107. Systems Research Center Technical Report TR-86-48, University of
  3108. Maryland, 1986.
  3109.  
  3110. [VAN84]
  3111.  
  3112. Van Dierendonck, A.J., and W.C. Melton. Applications of time transfer
  3113. using NAVSTAR GPS. In: Global Positioning System, Papers Published in
  3114. Navigation, Vol. II, Institute of Navigation, Washington, DC, 1984.
  3115.  
  3116. [VAS78]
  3117.  
  3118. Vass, E.R. OMEGA navigation system: present status and plans 1977-1980.
  3119. Navigation 25, 1 (Spring 1978).
  3120.  
  3121. Appendix A. NTP Data Format - Version 3
  3122.  
  3123. The format of the NTP Message data area, which immediately follows the
  3124. UDP header, is shown in Figure 4<$&fig4>. Following is a description of
  3125. its fields.
  3126.  
  3127. Leap Indicator (LI): This is a two-bit code warning of an impending leap
  3128. second to be inserted/deleted in the last minute of the current day,
  3129. with bit 0 and bit 1, respectively, coded as follows:
  3130.  
  3131. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3132. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3133.  
  3134. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3135.  
  3136. 00, no warning
  3137.  
  3138. 01, last minute has 61 seconds
  3139.  
  3140. 10, last minute has 59 seconds)
  3141.  
  3142. 11, alarm condition (clock not synchronized)
  3143.  
  3144. @Z_TBL_END =
  3145.  
  3146. Version Number (VN): This is a three-bit integer indicating the NTP
  3147. version number, currently three (3).
  3148.  
  3149. Mode: This is a three-bit integer indicating the mode, with values
  3150. defined as follows:
  3151.  
  3152. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3153. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3154. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3155.  
  3156. 0, reserved
  3157.  
  3158. 1, symmetric active
  3159.  
  3160. 2, symmetric passive
  3161.  
  3162. 3, client
  3163.  
  3164. 4, server
  3165.  
  3166. 5, broadcast
  3167.  
  3168. 6, reserved for NTP control message (see Appendix B)
  3169.  
  3170. 7, reserved for private use
  3171.  
  3172. @Z_TBL_END =
  3173.  
  3174. Stratum: This is a eight-bit integer indicating the stratum level of the
  3175. local clock, with values defined as follows:
  3176.  
  3177. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3178. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3179.  
  3180. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3181.  
  3182. 0, unspecified
  3183.  
  3184. 1, primary reference (e.g.,, radio clock)
  3185.  
  3186. 2-255, secondary reference (via NTP)
  3187.  
  3188. @Z_TBL_END =
  3189.  
  3190. The values that can appear in this field range from zero to NTP.INFIN
  3191. inclusive.
  3192.  
  3193. Poll Interval: This is an eight-bit signed integer indicating the
  3194. maximum interval between successive messages, in seconds to the nearest
  3195. power of two. The values that can appear in this field range from
  3196. NTP.MINPOLL to NTP.MAXPOLL inclusive.
  3197.  
  3198. Precision: This is an eight-bit signed integer indicating the precision
  3199. of the local clock, in seconds to the nearest power of two.
  3200.  
  3201. Root Delay: This is a 32-bit signed fixed-point number indicating the
  3202. total roundtrip delay to the primary reference source, in seconds with
  3203. fraction point between bits 15 and 16. Note that this variable can take
  3204. on both positive and negative values, depending on clock precision and
  3205. skew.
  3206.  
  3207. Root Dispersion: This is a 32-bit signed fixed-point number indicating
  3208. the maximum error relative to the primary reference source, in seconds
  3209. with fraction point between bits 15 and 16. Only positive values greater
  3210. than zero are possible.
  3211.  
  3212. Reference Clock Identifier: This is a 32-bit code identifying the
  3213. particular reference clock. In the case of stratum 0 (unspecified) or
  3214. stratum 1 (primary reference), this is a four-octet, left-justified,
  3215. zero-padded ASCII string. While not enumerated as part of the NTP
  3216. specification, the following are suggested ASCII identifiers:
  3217. @Z_TBL_BEG = COLUMNS(3), DIMENSION(IN), COLWIDTHS(E2,E2,E5),
  3218. WIDTH(4.6700), ABOVE(.1670), BELOW(.0830), HGUTTER(.3330),
  3219. BOX(Z_SINGLE), KEEP(ON), ALIGN(CT), L1(R1C0..R1C3)
  3220.  
  3221. @Z_TBL_BODY = TABLE HEADER, TABLE HEADER, TABLE HEADER
  3222.  
  3223. Stratum, Code, Meaning
  3224.  
  3225. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT, TABLE TEXT
  3226.  
  3227. 0, DCN, DCN routing protocol
  3228.  
  3229. 0, NIST, NIST public modem
  3230.  
  3231. 0, TSP, TSP time protocol
  3232.  
  3233. 0, DTS, Digital Time Service
  3234.  
  3235. 1, ATOM, Atomic clock (calibrated)
  3236.  
  3237. 1, VLF, VLF radio (OMEGA,, etc.)
  3238.  
  3239. 1, callsign, Generic radio
  3240.  
  3241. 1, LORC, LORAN-C radionavigation
  3242.  
  3243. 1, GOES, GOES UHF environment satellite
  3244.  
  3245. @Z_TBL_BODY = TABLE HEADER, TABLE HEADER, TABLE HEADER
  3246.  
  3247. 1, GPS, GPS UHF satellite positioning
  3248.  
  3249. @Z_TBL_END =
  3250.  
  3251. In the case of stratum 2 and greater (secondary reference) this is the
  3252. four-octet Internet address of the primary reference host.
  3253.  
  3254. Reference Timestamp: This is the local time at which the local clock was
  3255. last set or corrected, in 64-bit timestamp format.
  3256.  
  3257. Originate Timestamp: This is the local time at which the request
  3258. departed the client host for the service host, in 64-bit timestamp
  3259. format.
  3260.  
  3261. Receive Timestamp: This is the local time at which the request arrived
  3262. at the service host, in 64-bit timestamp format.
  3263.  
  3264. Transmit Timestamp: This is the local time at which the reply departed
  3265. the service host for the client host, in 64-bit timestamp format.
  3266.  
  3267. Authenticator (optional): When the NTP authentication mechanism is
  3268. implemented, this contains the authenticator information defined in
  3269. Appendix C.
  3270.  
  3271. Appendix B. NTP Control Messages
  3272.  
  3273. In a comprehensive network-management environment, facilities are
  3274. presumed available to perform routine NTP control and monitoring
  3275. functions, such as setting the leap-indicator bits at the primary
  3276. servers, adjusting the various system parameters and monitoring regular
  3277. operations. Ordinarily, these functions can be implemented using a
  3278. network-management protocol such as SNMP and suitable extensions to the
  3279. MIB database. However, in those cases where such facilities are not
  3280. available, these functions can be implemented using special NTP control
  3281. messages described herein. These messages are intended for use only in
  3282. systems where no other management facilities are available or
  3283. appropriate, such as in dedicated-function bus peripherals. Support for
  3284. these messages is not required in order to conform to this
  3285. specification.
  3286.  
  3287. The NTP Control Message has the value 6 specified in the mode field of
  3288. the first octet of the NTP header and is formatted as shown below. The
  3289. format of the data field is specific to each command or response;
  3290. however, in most cases the format is designed to be constructed and
  3291. viewed by humans and so is coded in free-form ASCII. This facilitates
  3292. the specification and implementation of simple management tools in the
  3293. absence of fully evolved network-management facilities. As in ordinary
  3294. NTP messages, the authenticator field follows the data field. If the
  3295. authenticator is used the data field is zero-padded to a 32-bit
  3296. boundary, but the padding bits are not considered part of the data field
  3297. and are not included in the field count.
  3298.  
  3299. IP hosts are not required to reassemble datagrams larger than 576
  3300. octets; however, some commands or responses may involve more data than
  3301. will fit into a single datagram. Accordingly, a simple reassembly
  3302. feature is included in which each octet of the message data is numbered
  3303. starting with zero. As each fragment is transmitted the number of its
  3304. first octet is inserted in the offset field and the number of octets is
  3305. inserted in the count field. The more-data (M) bit is set in all
  3306. fragments except the last.
  3307.  
  3308. Most control functions involve sending a command and receiving a
  3309. response, perhaps involving several fragments. The sender chooses a
  3310. distinct, nonzero sequence number and sets the status field and R and E
  3311. bits to zero. The responder interprets the opcode and additional
  3312. information in the data field, updates the status field, sets the R bit
  3313. to one and returns the three 32-bit words of the header along with
  3314. additional information in the data field. In case of invalid message
  3315. format or contents the responder inserts a code in the status field,
  3316. sets the R and E bits to one and, optionally, inserts a diagnostic
  3317. message in the data field.
  3318.  
  3319. Some commands read or write system variables and peer variables for an
  3320. association identified in the command. Others read or write variables
  3321. associated with a radio clock or other device directly connected to a
  3322. source of primary synchronization information. To identify which type of
  3323. variable and association a 16-bit association identifier is used. System
  3324. variables are indicated by the identifier zero. As each association is
  3325. mobilized a unique, nonzero identifier is created for it. These
  3326. identifiers are used in a cyclic fashion, so that the chance of using an
  3327. old identifier which matches a newly created association is remote. A
  3328. management entity can request a list of current identifiers and
  3329. subsequently use them to read and write variables for each association.
  3330. An attempt to use an expired identifier results in an exception
  3331. response, following which the list can be requested again.
  3332.  
  3333. Some exception events, such as when a peer becomes reachable or
  3334. unreachable, occur spontaneously and are not necessarily associated with
  3335. a command. An implementation may elect to save the event information for
  3336. later retrieval or to send an asynchronous response (called a trap) or
  3337. both. In case of a trap the IP address and port number is determined by
  3338. a previous command and the sequence field is set as described below.
  3339. Current status and summary information for the latest exception event is
  3340. returned in all normal responses. Bits in the status field indicate
  3341. whether an exception has occurred since the last response and whether
  3342. more than one exception has occurred.
  3343.  
  3344. Commands need not necessarily be sent by an NTP peer, so ordinary
  3345. access-control procedures may not apply; however, the optional
  3346. mask/match mechanism suggested elsewhere in this document provides the
  3347. capability to control access by mode number, so this could be used to
  3348. limit access for control messages (mode 6) to selected address ranges.
  3349.  
  3350. NTP Control Message Format
  3351.  
  3352. The format of the NTP Control Message header, which immediately follows
  3353. the UDP header, is shown in Figure 5<$&fig5>. Following is a description
  3354. of its fields. Bit positions marked as zero are reserved and should
  3355. always be transmitted as zero.
  3356.  
  3357. Version Number (VN): This is a three-bit integer indicating the NTP
  3358. version number, currently three (3).
  3359.  
  3360. Mode: This is a three-bit integer indicating the mode. It must have the
  3361. value 6, indicating an NTP control message.
  3362.  
  3363. Response Bit (R): Set to zero for commands, one for responses.
  3364.  
  3365. Error Bit (E): Set to zero for normal response, one for error response.
  3366.  
  3367. More Bit (M): Set to zero for last fragment, one for all others.
  3368.  
  3369. Operation Code (Op): This is a five-bit integer specifying the command
  3370. function. Values currently defined include the following:
  3371.  
  3372. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3373. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3374.  
  3375. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3376.  
  3377. 0, reserved
  3378.  
  3379. 1, read status command/response
  3380.  
  3381. 2, read variables command/response
  3382.  
  3383. 3, write variables command/response
  3384.  
  3385. 4, read clock variables command/response
  3386.  
  3387. 5, write clock variables command/response
  3388.  
  3389. 6, set trap address/port command/response
  3390.  
  3391. 7, trap response
  3392.  
  3393. 8-31, reserved
  3394.  
  3395. @Z_TBL_END =
  3396.  
  3397. Sequence: This is a 16-bit integer indicating the sequence number of the
  3398. command or response.
  3399.  
  3400. Status: This is a 16-bit code indicating the current status of the
  3401. system, peer or clock, with values coded as described in following
  3402. sections.
  3403.  
  3404. Association ID: This is a 16-bit integer identifying a valid
  3405. association.
  3406.  
  3407. Offset: This is a 16-bit integer indicating the offset, in octets, of
  3408. the first octet in the data area.
  3409.  
  3410. Count: This is a 16-bit integer indicating the length of the data field,
  3411. in octets.
  3412. Data: This contains the message data for the command or response. The
  3413. maximum number of data octets is 468.
  3414.  
  3415. Authenticator (optional): When the NTP authentication mechanism is
  3416. implemented, this contains the authenticator information defined in
  3417. Appendix C.
  3418.  
  3419. Status Words
  3420.  
  3421. Status words indicate the present status of the system, associations and
  3422. clock. They are designed to be interpreted by network-monitoring
  3423. programs and are in one of four 16-bit formats shown in Figure 6<$&fig6>
  3424. and described in this section. System and peer status words are
  3425. associated with responses for all commands except the read clock
  3426. variables, write clock variables and set trap address/port commands. The
  3427. association identifier zero specifies the system status word, while a
  3428. nonzero identifier specifies a particular peer association. The status
  3429. word returned in response to read clock variables and write clock
  3430. variables commands indicates the state of the clock hardware and
  3431. decoding software. A special error status word is used to report
  3432. malformed command fields or invalid values.
  3433.  
  3434. System Status Word
  3435.  
  3436. The system status word appears in the status field of the response to a
  3437. read status or read variables command with a zero association
  3438. identifier. The format of the system status word is as follows:
  3439.  
  3440. Leap Indicator (LI): This is a two-bit code warning of an impending leap
  3441. second to be inserted/deleted in the last minute of the current day,
  3442. with bit 0 and bit 1, respectively, coded as follows:
  3443.  
  3444. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3445. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3446.  
  3447. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3448.  
  3449. 00, no warning
  3450.  
  3451. 01, last minute has 61 seconds
  3452.  
  3453. 10, last minute has 59 seconds)
  3454.  
  3455. 11, alarm condition (clock not synchronized)
  3456.  
  3457. @Z_TBL_END =
  3458.  
  3459. Clock Source: This is a six-bit integer indicating the current
  3460. synchronization source, with values coded as follows:
  3461.  
  3462. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3463. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3464.  
  3465. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3466.  
  3467. 0, unspecified or unknown
  3468.  
  3469. 1, Calibrated atomic clock (e.g.,, HP 5061)
  3470.  
  3471. 2, VLF (band 4) or LF (band 5) radio (e.g.,, OMEGA,, WWVB)
  3472.  
  3473. 3, HF (band 7) radio (e.g.,, CHU,, MSF,, WWV/H)
  3474.  
  3475. 4, UHF (band 9) satellite (e.g.,, GOES,, GPS)
  3476.  
  3477. 5, local net (e.g.,, DCN,, TSP,, DTS)
  3478. 6, UDP/NTP
  3479.  
  3480. 7, UDP/TIME
  3481.  
  3482. 8, eyeball-and-wristwatch
  3483.  
  3484. 9, telephone modem (e.g.,, NIST)
  3485.  
  3486. 10-63, reserved
  3487.  
  3488. @Z_TBL_END =
  3489.  
  3490. System Event Counter: This is a four-bit integer indicating the number
  3491. of system exception events occurring since the last time the system
  3492. status word was returned in a response or included in a trap message.
  3493. The counter is cleared when returned in the status field of a response
  3494. and freezes when it reaches the value 15.
  3495.  
  3496. System Event Code: This is a four-bit integer identifying the latest
  3497. system exception event, with new values overwriting previous values, and
  3498. coded as follows:
  3499.  
  3500. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3501. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3502.  
  3503. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3504.  
  3505. 0, unspecified
  3506.  
  3507. 1, system restart
  3508.  
  3509. 2, system or hardware fault
  3510.  
  3511. 3, system new status word (leap bits or synchronization change)
  3512.  
  3513. 4, system new synchronization source or stratum (sys.peer or sys.stratum
  3514. change)
  3515.  
  3516. 5, system clock reset (offset correction exceeds CLOCK.MAX)
  3517.  
  3518. 6, system invalid time or date (see NTP specification)
  3519.  
  3520. 7, system clock exception (see system clock status word)
  3521.  
  3522. 8-15, reserved
  3523.  
  3524. @Z_TBL_END =
  3525.  
  3526. Peer Status Word
  3527.  
  3528. A peer status word is returned in the status field of a response to a
  3529. read status, read variables or write variables command and appears also
  3530. in the list of association identifiers and status words returned by a
  3531. read status command with a zero association identifier. The format of a
  3532. peer status word is as follows:
  3533.  
  3534. Peer Status: This is a five-bit code indicating the status of the peer
  3535. determined by the packet procedure, with bits assigned as follows:
  3536.  
  3537. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3538. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3539.  
  3540. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3541.  
  3542. 0, configured (peer.config)
  3543. 1, authentication enabled (peer.authenable)
  3544.  
  3545. 2, authentication okay (peer.authentic)
  3546.  
  3547. 3, reachability okay (peer.reach <F128M>╓<F255D> 0)
  3548.  
  3549. 4, reserved
  3550.  
  3551. @Z_TBL_END =
  3552.  
  3553. Peer Selection (Sel): This is a three-bit integer indicating the status
  3554. of the peer determined by the clock-selection procedure, with values
  3555. coded as follows:
  3556.  
  3557. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3558. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3559.  
  3560. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3561.  
  3562. 0, rejected
  3563.  
  3564. 1, passed sanity checks (tests 1 through 8 in Section 3.4.3)
  3565.  
  3566. 2, passed correctness checks (intersection algorithm in Section 4.2.1)
  3567.  
  3568. 3, passed candidate checks (if limit check implemented)
  3569.  
  3570. 4, passed outlyer checks (clustering algorithm in Section 4.2.2)
  3571.  
  3572. 5, current synchronization source; max distance exceeded (if limit check
  3573. implemented)
  3574.  
  3575. 6, current synchronization source; max distance okay
  3576.  
  3577. 7, reserved
  3578.  
  3579. @Z_TBL_END =
  3580.  
  3581. Peer Event Counter: This is a four-bit integer indicating the number of
  3582. peer exception events that occurred since the last time the peer status
  3583. word was returned in a response or included in a trap message. The
  3584. counter is cleared when returned in the status field of a response and
  3585. freezes when it reaches the value 15.
  3586.  
  3587. Peer Event Code: This is a four-bit integer identifying the latest peer
  3588. exception event, with new values overwriting previous values, and coded
  3589. as follows:
  3590.  
  3591. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3592. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3593.  
  3594. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3595.  
  3596. 0, unspecified
  3597.  
  3598. 1, peer IP error
  3599.  
  3600. 2, peer authentication failure (peer.authentic bit was one now zero)
  3601.  
  3602. 3, peer unreachable (peer.reach was nonzero now zero)
  3603.  
  3604. 4, peer reachable (peer.reach was zero now nonzero)
  3605.  
  3606. 5, peer clock exception (see peer clock status word)
  3607.  
  3608. 6-15, reserved
  3609. @Z_TBL_END =
  3610.  
  3611. Clock Status Word
  3612.  
  3613. There are two ways a reference clock can be attached to a NTP service
  3614. host, as an dedicated device managed by the operating system and as a
  3615. synthetic peer managed by NTP. As in the read status command, the
  3616. association identifier is used to identify which one, zero for the
  3617. system clock and nonzero for a peer clock. Only one system clock is
  3618. supported by the protocol, although many peer clocks can be supported. A
  3619. system or peer clock status word appears in the status field of the
  3620. response to a read clock variables or write clock variables command.
  3621. This word can be considered an extension of the system status word or
  3622. the peer status word as appropriate. The format of the clock status word
  3623. is as follows:
  3624.  
  3625. Clock Status: This is an eight-bit integer indicating the current clock
  3626. status, with values coded as follows:
  3627.  
  3628. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3629. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3630.  
  3631. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3632.  
  3633. 0, clock operating within nominals
  3634.  
  3635. 1, reply timeout
  3636.  
  3637. 2, bad reply format
  3638.  
  3639. 3, hardware or software fault
  3640.  
  3641. 4, propagation failure
  3642.  
  3643. 5, bad date format or value
  3644.  
  3645. 6, bad time format or value
  3646.  
  3647. 7-255, reserved
  3648.  
  3649. @Z_TBL_END =
  3650.  
  3651. Clock Event Code: This is an eight-bit integer identifying the latest
  3652. clock exception event, with new values overwriting previous values. When
  3653. a change to any nonzero value occurs in the radio status field, the
  3654. radio status field is copied to the clock event code field and a system
  3655. or peer clock exception event is declared as appropriate.
  3656.  
  3657. Error Status Word
  3658.  
  3659. An error status word is returned in the status field of an error
  3660. response as the result of invalid message format or contents. Its
  3661. presence is indicated when the E (error) bit is set along with the
  3662. response (R) bit in the response. It consists of an eight-bit integer
  3663. coded as follows:
  3664.  
  3665. @Z_TBL_BEG = COLUMNS(2), DIMENSION(IN), COLWIDTHS(E1,E8), WIDTH(5.0000),
  3666. ABOVE(.0830), BELOW(.0830), HGUTTER(.0560), KEEP(OFF), ALIGN(CT)
  3667.  
  3668. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT
  3669.  
  3670. 0, unspecified
  3671.  
  3672. 1, authentication failure
  3673.  
  3674. 2, invalid message length or format
  3675. 3, invalid opcode
  3676.  
  3677. 4, unknown association identifier
  3678.  
  3679. 5, unknown variable name
  3680.  
  3681. 6, invalid variable value
  3682.  
  3683. 7, administratively prohibited
  3684.  
  3685. 8-255, reserved
  3686.  
  3687. @Z_TBL_END =
  3688.  
  3689. Commands
  3690.  
  3691. Commands consist of the header and optional data field shown in Figure
  3692. 6. When present, the data field contains a list of identifiers or
  3693. assignments in the form
  3694.  
  3695. <<identifier>>[=<<value>>],<<identifier>>[=<<value>>],...
  3696.  
  3697. where <<identifier>> is the ASCII name of a system or peer variable
  3698. specified in Table 2 or Table 3 and <<value>> is expressed as a decimal,
  3699. hexadecimal or string constant in the syntax of the C programming
  3700. language. Where no ambiguity exists, the <169>sys.<170> or
  3701. <169>peer.<170> prefixes shown in Table 2 or Table 4 can be suppressed.
  3702. Whitespace (ASCII nonprinting format effectors) can be added to improve
  3703. readability for simple monitoring programs that do not reformat the data
  3704. field. Internet addresses are represented as four octets in the form
  3705. [n.n.n.n], where n is in decimal notation and the brackets are optional.
  3706. Timestamps, including reference, originate, receive and transmit values,
  3707. as well as the logical clock, are represented in units of seconds and
  3708. fractions, preferably in hexadecimal notation, while delay, offset,
  3709. dispersion and distance values are represented in units of milliseconds
  3710. and fractions, preferably in decimal notation. All other values are
  3711. represented as-is, preferably in decimal notation.
  3712.  
  3713. Implementations may define variables other than those listed in Table 2
  3714. or Table 3. Called extramural variables, these are distinguished by the
  3715. inclusion of some character type other than alphanumeric or <169>.<170>
  3716. in the name. For those commands that return a list of assignments in the
  3717. response data field, if the command data field is empty, it is expected
  3718. that all available variables defined in Table 3 or Table 4 of the NTP
  3719. specification will be included in the response. For the read commands,
  3720. if the command data field is nonempty, an implementation may choose to
  3721. process this field to individually select which variables are to be
  3722. returned.
  3723.  
  3724. Commands are interpreted as follows:
  3725.  
  3726. Read Status (1): The command data field is empty or contains a list of
  3727. identifiers separated by commas. The command operates in two ways
  3728. depending on the value of the association identifier. If this identifier
  3729. is nonzero, the response includes the peer identifier and status word.
  3730. Optionally, the response data field may contain other information, such
  3731. as described in the Read Variables command. If the association
  3732. identifier is zero, the response includes the system identifier (0) and
  3733. status word, while the data field contains a list of binary-coded pairs
  3734.  
  3735. <<association identifier>> <<status word>>,
  3736.  
  3737. one for each currently defined association.
  3738. Read Variables (2): The command data field is empty or contains a list
  3739. of identifiers separated by commas. If the association identifier is
  3740. nonzero, the response includes the requested peer identifier and status
  3741. word, while the data field contains a list of peer variables and values
  3742. as described above. If the association identifier is zero, the data
  3743. field contains a list of system variables and values. If a peer has been
  3744. selected as the synchronization source, the response includes the peer
  3745. identifier and status word; otherwise, the response includes the system
  3746. identifier (0) and status word.
  3747.  
  3748. Write Variables (3): The command data field contains a list of
  3749. assignments as described above. The variables are updated as indicated.
  3750. The response is as described for the Read Variables command.
  3751.  
  3752. Read Clock Variables (4): The command data field is empty or contains a
  3753. list of identifiers separated by commas. The association identifier
  3754. selects the system clock variables or peer clock variables in the same
  3755. way as in the Read Variables command. The response includes the
  3756. requested clock identifier and status word and the data field contains a
  3757. list of clock variables and values, including the last timecode message
  3758. received from the clock.
  3759.  
  3760. Write Clock Variables (5): The command data field contains a list of
  3761. assignments as described above. The clock variables are updated as
  3762. indicated. The response is as described for the Read Clock Variables
  3763. command.
  3764.  
  3765. Set Trap Address/Port (6): The command association identifier, status
  3766. and data fields are ignored. The address and port number for subsequent
  3767. trap messages are taken from the source address and port of the control
  3768. message itself. The initial trap counter for trap response messages is
  3769. taken from the sequence field of the command. The response association
  3770. identifier, status and data fields are not significant. Implementations
  3771. should include sanity timeouts which prevent trap transmissions if the
  3772. monitoring program does not renew this information after a lengthy
  3773. interval.
  3774.  
  3775. Trap Response (7): This message is sent when a system, peer or clock
  3776. exception event occurs. The opcode field is 7 and the R bit is set. The
  3777. trap counter is incremented by one for each trap sent and the sequence
  3778. field set to that value. The trap message is sent using the IP address
  3779. and port fields established by the set trap address/port command. If a
  3780. system trap the association identifier field is set to zero and the
  3781. status field contains the system status word. If a peer trap the
  3782. association identifier field is set to that peer and the status field
  3783. contains the peer status word. Optional ASCII-coded information can be
  3784. included in the data field.
  3785.  
  3786. Appendix C. Authentication Issues
  3787.  
  3788. NTP robustness requirements are similar to those of other multiple-peer
  3789. distributed protocols used for network routing, management and file
  3790. access. These include protection from faulty implementations, improper
  3791. operation and possibly malicious replay attacks with or without data
  3792. modification. These requirements are especially stringent with
  3793. distributed protocols, since damage due to failures can propagate
  3794. quickly throughout the network, devastating archives, routes and
  3795. monitoring systems and even bring down major portions of the network in
  3796. the fashion of the classic Internet Worm.
  3797.  
  3798. The access-control mechanism suggested in the NTP specification responds
  3799. to these requirements by limiting access to trusted peers. The various
  3800. sanity checks resist most replay and spoofing attacks by discarding old
  3801. duplicates and using the originate timestamp as a one-time pad, since it
  3802. is unlikely that even a synchronized peer can predict future timestamps
  3803. with the precision required on the basis of past observations alone. In
  3804. addition, the protocol environment resists jamming attacks by employing
  3805. redundant time servers and diverse network paths. Resistance to
  3806. stochastic disruptions, actual or manufactured, are minimized by careful
  3807. design of the filtering and selection algorithms.
  3808.  
  3809. However, it is possible that a determined intruder can disrupt
  3810. timekeeping operations between peers by subtle modifications of NTP
  3811. message data, such as falsifying header fields or certain timestamps. In
  3812. cases where protection from even these types of attacks is required, a
  3813. specifically engineered message-authentication mechanism based on
  3814. cryptographic techniques is necessary. Typical mechanisms involve the
  3815. use of cryptographic certificates, algorithms and key media, together
  3816. with secure media databases and key-management protocols. Ongoing
  3817. research efforts in this area are directed toward developing a standard
  3818. methodology that can be used with many protocols, including NTP.
  3819. However, while it may eventually be the case that ubiquitous, widely
  3820. applicable authentication methodology may be adopted by the Internet
  3821. community and effectively overtake the mechanism described here, it does
  3822. not appear that specific standards and implementations will happen
  3823. within the lifetime of this particular version of NTP.
  3824.  
  3825. The NTP authentication mechanism described here is intended for interim
  3826. use until specific standards and implementations operating at the
  3827. network level or transport level are available. Support for this
  3828. mechanism is not required in order to conform to the NTP specification
  3829. itself. The mechanism, which operates at the application level, is
  3830. designed to protect against unauthorized message-stream modification and
  3831. misrepresentation of source by insuring that unbroken, authenticated
  3832. paths exist between a trusted, stratum-one server in a particular
  3833. synchronization subnet and all other servers in that subnet. It employs
  3834. a crypto-checksum, computed by the sender and checked by the receiver,
  3835. together with a set of predistributed algorithms, certificates and
  3836. cryptographic keys indexed by a key identifier included in the message.
  3837. However, there are no provisions in NTP itself to distribute or maintain
  3838. the certificates, algorithms or keys. These quantities may occasionally
  3839. be changed, which may result in inconsistent key information while
  3840. rekeying is in progress. The nature of NTP itself is quite tolerant to
  3841. such disruptions, so no particular provisions are included to deal with
  3842. them.
  3843.  
  3844. The intent of the authentication mechanism is to provide a framework
  3845. that can be used in conjunction with selected mode combinations to build
  3846. specific plans to manage clockworking communities and implement policy
  3847. as necessary. It can be selectively enabled or disabled on a per-peer
  3848. basis. There is no specific plan proposed to manage the use of such
  3849. schemes; although several possibilities are immediately obvious. In one
  3850. scenario a group of time servers peers among themselves using symmetric
  3851. modes and shares one secret key, say key 1, while another group of
  3852. servers peers among themselves using symmetric modes and shares another
  3853. secret key, say key 2. Now, assume by policy it is decided that selected
  3854. servers in group 1 can provide synchronization to group 2, but not the
  3855. other way around. The selected servers in group 1 are given key 2, but
  3856. operated only in server mode, so cannot accept synchronization from
  3857. group 2; however, group 2 has authenticated access to group-1 servers.
  3858. Many other scenarios are possible with suitable combinations of modes
  3859. and keys.
  3860.  
  3861. A packet format and crypto-checksum procedure appropriate for NTP is
  3862. specified in the following sections. The cryptographic information is
  3863. carried in an authenticator which follows the (unmodified) NTP header
  3864. fields. The crypto-checksum procedure uses the Data Encryption Standard
  3865. (DES) [NBS77]; however, only the DES encryption algorithm is used and
  3866. the decryption algorithm is not necessary. This feature is specifically
  3867. targeted toward governmental sensitivities on the export of
  3868. cryptographic technology, since the DES decryption algorithm need not be
  3869. included in NTP software distributions and thus cannot be extracted and
  3870. used in other applications to avoid message data disclosure.
  3871.  
  3872. NTP Authentication Mechanism
  3873.  
  3874. When it is created and possibly at other times, each association is
  3875. allocated variables identifying the certificate authority, encryption
  3876. algorithm, cryptographic key and possibly other data. The specific
  3877. procedures to allocate and initialize these variables are beyond the
  3878. scope of this specification, as are the association of the identifiers
  3879. and keys and the management and distribution of the keys themselves. For
  3880. example and consistency with the conventions of the NTP specification, a
  3881. set of appropriate peer and packet variables might include the
  3882. following:
  3883.  
  3884. Authentication Enabled Bit (peer.authenable): This is a bit indicating
  3885. that the association is to operate in the authenticated mode. For
  3886. configured peers this bit is determined from the startup environment.
  3887. For non-configured peers, this bit is set to one if an arriving message
  3888. includes the authenticator and set to zero otherwise.
  3889.  
  3890. Authenticated Bit (peer.authentic): This is a bit indicating that the
  3891. last message received from the peer has been correctly authenticated.
  3892.  
  3893. Key Identifier (peer.hostkeyid, peer.peerkeyid, pkt.keyid): This is an
  3894. integer identifying the cryptographic key used to generate the message-
  3895. authentication code. The system variable peer.hostkeyid is used for
  3896. active associations. The peer.peerkeyid variable is initialized at zero
  3897. (unspecified) when the association is mobilized. For purposes of
  3898. authentication an unassigned value is interpreted as zero (unspecified).
  3899.  
  3900. Cryptographic Keys (sys.key): This is a set of 64-bit DES keys. Each key
  3901. is constructed as in the Berkeley Unix distributions, which consists of
  3902. eight octets, where the seven low-order bits of each octet correspond to
  3903. the DES bits 1-7 and the high-order bit corresponds to the DES odd-
  3904. parity bit 8. By convention, the unspecified key 0 (zero), consisting of
  3905. eight odd-parity zero octets, is used for testing and presumed known
  3906. throughout the NTP community. The remaining keys are distributed using
  3907. methods outside the scope of NTP.
  3908.  
  3909. Crypto-Checksum (pkt.check): This is a crypto-checksum computed by the
  3910. encryption procedure.
  3911.  
  3912. The authenticator field consists of two subfields, one consisting of the
  3913. pkt.keyid variable and the other the pkt.check variable computed by the
  3914. encrypt procedure, which is called by the transmit procedure described
  3915. in the NTP specification, and by the decrypt procedure, which is called
  3916. by the receive procedure described in the NTP specification. Its
  3917. presence is revealed by the fact the total datagram length according to
  3918. the UDP header is longer than the NTP message length, which includes the
  3919. header plus the data field, if present. For authentication purposes, the
  3920. NTP message is zero-padded if necessary to a 64-bit boundary, although
  3921. the padding bits are not considered part of the NTP message itself. The
  3922. authenticator format shown in Figure 7<$&fig7> has 96 bits, including a
  3923. 32-bit key identifier and 64-bit crypto-checksum, and is aligned on a
  3924. 32-bit boundary for efficient computation. Additional information
  3925. required in some implementations, such as certificate authority and
  3926. encryption algorithm, can be inserted between the (padded) NTP message
  3927. and the key identifier, as long as the alignment conditions are met.
  3928. Like the authenticator itself, this information is not included in the
  3929. crypto-checksum. Use of these data are beyond the scope of this
  3930. specification. These conventions may be changed in future as the result
  3931. of other standardization activities.
  3932.  
  3933. NTP Authentication Procedures
  3934. When authentication is implemented there are two additional procedures
  3935. added to those described in the NTP specification. One of these
  3936. (encrypt) constructs the crypto-checksum in transmitted messages, while
  3937. the other (decrypt) checks this quantity in received messages. The
  3938. procedures use a variant of the cipher-block chaining method described
  3939. in [NBS80] as applied to DES. In principal, the procedure is independent
  3940. of DES and requires only that the encryption algorithm operate on 64-bit
  3941. blocks. While the NTP authentication mechanism specifies the use of DES,
  3942. other algorithms could be used by prior arrangement.
  3943.  
  3944. Encrypt Procedure
  3945.  
  3946. For ordinary NTP messages the encryption procedure operates as follows.
  3947. If authentication is not enabled, the procedure simply exits. If the
  3948. association is active (modes 1, 3, 5), the key is determined from the
  3949. system key identifier. If the association is passive (modes 2, 4) the
  3950. key is determined from the peer key identifier, if the authentic bit is
  3951. set, or as the default key (zero) otherwise. These conventions allow
  3952. further protection against replay attacks and keying errors, as well as
  3953. facilitate testing and migration to new versions. The crypto-checksum is
  3954. calculated using the 64-bit NTP header and data words, but not the
  3955. authenticator or padding bits.
  3956.  
  3957. begin encrypt procedure
  3958.         if (<$Eroman peer.authenable~=~0>) exit;                /* do
  3959. nothing if not enabled */
  3960.         if (<$Eroman {peer.hostmode~=~1~bold or~peer.hostmode~=~3~bold
  3961. or~peer.hostmode ~=~5}>)
  3962.                 <$Ekeyid~<<-~roman peer.hostkeyid>;             /*
  3963. active modes use system key */
  3964.         else
  3965.                 if (<$Eroman peer.authentic~=~1>)               /*
  3966. passive modes use peer key */
  3967.                          <$Ekeyid~<<-~roman peer.peerkeyid>;
  3968.                 else
  3969.                          <$Ekeyid~<<-~0>;                       /*
  3970. unauthenticated use key 0 */
  3971.         <$Etemp~<<-~0>;                                 /* calculate
  3972. crypto-checksum */
  3973.         for (each 64-bit header and data word) begin
  3974.                 <$Etemp~<<-~temp~roman bold xor~word>;
  3975.                 <$Etemp~<<-~roman DES (temp,~keyid)>;
  3976.                 endfor;
  3977.         <$Eroman pkt.keyid~<<-~keyid>;                          /*
  3978. insert packet variables */
  3979.         <$Eroman pkt.check~<<-~temp>;
  3980.         end encrypt procedure;
  3981.  
  3982. Decrypt Procedure
  3983.  
  3984. For ordinary messages the decryption procedure operates as follows. If
  3985. the peer is not configured, the data portion of the message is inspected
  3986. to determine if the authenticator fields are present. If so,
  3987. authentication is enabled; otherwise, it is disabled. If authentication
  3988. is enabled and the authenticator fields are present and the crypto-
  3989. checksum succeeds, the authentication bit is set to one; otherwise, it
  3990. is set to zero.
  3991.  
  3992. begin decrypt procedure
  3993.         <$Eroman peer.authentic~<<-~0>;
  3994.         if (<$Eroman peer.config~=~0>)                          /* if
  3995. not configured, enable per packet */
  3996.                 if (authenticator present)
  3997.                         <$Eroman peer.authenable~<<-~1>;
  3998.                 else
  3999.                         <$Eroman peer.authenable~<<-~0>;
  4000.         if (<$Eroman peer.authenable~=~0> or authenticator not present))
  4001. exit;
  4002.         <$Eroman {peer.peerkeyid~<<-~pkt.keyid}>;               /* use
  4003. peer key */
  4004.         <$Etemp~<<-~0>;                                 /* calculate
  4005. crypto-checksum */
  4006.         for (each 64-bit header and data word) begin
  4007.                 <$Etemp~<<-~temp~roman bold xor~word>;
  4008.                 <$Etemp~<<-~roman DES (temp,~roman peer.peerkeyid)>;
  4009.                 endfor;
  4010.         if (temp == pkt.check) <$Eroman peer.authentic~<<-~1>;  /*
  4011. declare result */
  4012.         end decrypt procedure;
  4013.  
  4014. Control-Message Procedures
  4015.  
  4016. In anticipation that the functions provided by the NTP control messages
  4017. will eventually be subsumed by a comprehensive network-managment
  4018. function, the peer variables are not used for control message
  4019. authentication. If an NTP command message is received with an
  4020. authenticator field, the crypto-checksum is computed as in the decrypt
  4021. procedure and the response message includes the authenticator field as
  4022. computed by the encrypt procedure. If the received authenticator is
  4023. correct, the key for the response is the same as in the command;
  4024. otherwise, the default key (zero) is used. Commands causing a change to
  4025. the peer data base, such as the write variables and set trap
  4026. address/port commands, must be correctly authenticated; however, the
  4027. remaining commands are normally not authenticated in order to minimize
  4028. the encryption overhead.
  4029.  
  4030. Appendix D. Differences from Previous Versions.
  4031.  
  4032. The original NTP, later called NTP Version 0, was described in RFC-958
  4033. [MIL85c]. Subsequently, Version 0 was superseded by Version 1 (RFC-1059
  4034. [MIL88a]), and Version 2 (RFC-1119 [MIL89]. The Version-2 description
  4035. was split into two documents, RFC-1119 defining the architecture and
  4036. specifying the protocol and algorithms, and another [MIL90b] describing
  4037. the service model, algorithmic analysis and operating experience. In
  4038. previous versions these two objectives were combined in one document.
  4039. While the architecture assumed in Version 3 is identical to Version 2,
  4040. the protocols and algorithms differ in minor ways. Differences between
  4041. NTP Version 3 and previous versions are described in this Appendix. Due
  4042. to known bugs in very old implementations, continued support for
  4043. Version-0 implementations is not recommended. It is recommended that new
  4044. implementations follow the guidelines below when interoperating with
  4045. older implementations.
  4046.  
  4047. Version 3 neither changes the protocol in any significant way nor
  4048. obsoletes previous versions or existing implementations. The main
  4049. motivation for the new version is to refine the analysis and
  4050. implementation models for new applications at much higher network speeds
  4051. to the gigabit-per-second regime and to provide for the enhanced
  4052. stability, accuracy and precision required at such speeds. In
  4053. particular, the sources of time and frequency errors have been
  4054. rigorously examined and error bounds established in order to improve
  4055. performance, provide a model for correctness assertions and indicate
  4056. timekeeping quality to the user. Version 3 also incorporates two new
  4057. optional features, (1) an algorithm to combine the offsets of a number
  4058. of peer time servers in order to enhance accuracy and (2) improved
  4059. local-clock algorithms which allow the poll intervals on all
  4060. synchronization paths to be substantially increased in order to reduce
  4061. network overhead. Following is a summary of previous versions of the
  4062. protocol together with details of the Version 3 changes.
  4063.  
  4064. 1.
  4065. Version 1 supports no modes other than symmetric-active and symmetric-
  4066. passive, which are determined by inspecting the port-number fields of
  4067. the UDP packet header. The peer mode can be determined explicitly from
  4068. the packet-mode variable (pkt.mode) if it is nonzero and implicitly from
  4069. the source port (pkt.peerport) and destination port (pkt.hostport)
  4070. variables if it is zero. For the case where pkt.mode is zero the mode is
  4071. determined as follows:
  4072.  
  4073. @Z_TBL_BEG = COLUMNS(3), DIMENSION(IN), WIDTH(5.0000), ABOVE(.1670),
  4074. BELOW(.0830), HGUTTER(.3330), BOX(Z_SINGLE), KEEP(ON), ALIGN(CT),
  4075. L1(R1C0..R1C3)
  4076.  
  4077. @Z_TBL_BODY = TABLE HEADER, TABLE HEADER, TABLE HEADER
  4078.  
  4079. pkt.peerport, pkt.hostport, Mode
  4080.  
  4081. @Z_TBL_BODY = TABLE TEXT, TABLE TEXT, TABLE TEXT
  4082.  
  4083. NTP.PORT, NTP.PORT, symmetric active
  4084.  
  4085. NTP.PORT, not NTP.PORT, server
  4086.  
  4087. not NTP.PORT, NTP.PORT, client
  4088.  
  4089. @Z_TBL_BODY = TABLE HEADER, TABLE HEADER, TABLE HEADER
  4090.  
  4091. not NTP.PORT, not NTP.PORT, not possible
  4092.  
  4093. @Z_TBL_END =
  4094.  
  4095. Note that it is not possible in this case to distinguish between
  4096. symmetric active and symmetric passive modes. Use of the pkt.mode and
  4097. NTP.PORT variables in this way is not recommended and may not be
  4098. supported in future versions of the protocol. The low-order three bits
  4099. of the first octet, specified as zero in Version 1, are used for the
  4100. mode field in Version 2. Version-2 and Version-3 implementations
  4101. interoperating with Version-1 implementations should operate in a
  4102. passive mode only and use the value one in the version number
  4103. (pkt.version) field and zero in the mode (pkt.mode) field in transmitted
  4104. messages.
  4105.  
  4106. 2.
  4107.  
  4108. Version 1 does not support the NTP control message described in Appendix
  4109. B. Certain old versions of the Unix NTP daemon ntpd use the high-order
  4110. bits of the stratum field (pkt.stratum) for control and monitoring
  4111. purposes. While these bits are never set during normal Version-1,
  4112. Version-2 or Version-3 operations, new implementations may use the NTP
  4113. reserved mode 6 described in Appendix B and/or private reserved mode 7
  4114. for special purposes, such as remote control and monitoring, and in such
  4115. cases the format of the packet following the first octet can be
  4116. arbitrary. While there is no guarantee that different implementations
  4117. can interoperate using private reserved mode 7, it is recommended that
  4118. vanilla ASCII format be used whenever possible.
  4119.  
  4120. 3.
  4121.  
  4122. Version 1 does not support authentication. The key identifiers,
  4123. cryptographic keys and procedures described in Appendix C are new to
  4124. Version 2 and continued in Version 3, along with the corresponding
  4125. variables, procedures and authenticator fields. In the NTP message
  4126. described in Appendix A and NTP control message described in Appendix B
  4127. the format and contents of the header fields are independent of the
  4128. authentication mechanism and the authenticator itself follows the header
  4129. fields, so that previous versions will ignore the authenticator.
  4130.  
  4131. 4.
  4132.  
  4133. In Version 1 the total dispersion (pkt.rootdispersion) field of the NTP
  4134. header was called the estimated drift rate, but not used in the protocol
  4135. or timekeeping procedures. Implementations of the Version-1 protocol
  4136. typically set this field to the current value of the skew-compensation
  4137. register, which is a signed quantity. In a Version 2 implementation
  4138. apparent large values in this field may affect the order considered in
  4139. the clock-selection procedure. Version-2 and Version-3 implementations
  4140. interoperating with older implementations should assume this field is
  4141. zero, regardless of its actual contents.
  4142.  
  4143. 5.
  4144.  
  4145. Version 2 and Version 3 incorporate several sanity checks designed to
  4146. avoid disruptions due to unsynchronized, duplicate or bogus timestamp
  4147. information. The checks in Version 3 are specifically designed to detect
  4148. lost or duplicate packets and resist invalid timestamps. The leap-
  4149. indicator bits are set to show the unsynchronized state if updates are
  4150. not received from a reference source for a considerable time or if the
  4151. reference source has not received updates for a considerable time. Some
  4152. Version-1 implementations could claim valid synchronization indefinitely
  4153. following loss of the reference source.
  4154.  
  4155. 6.
  4156.  
  4157. The clock-selection procedure of Version 2 was considerably refined as
  4158. the result of accumulated experience with the Version-1 implementation.
  4159. Additional sanity checks are included for authentication, range bounds
  4160. and to avoid use of very old data. The candidate list is sorted twice,
  4161. once to select a relatively few robust candidates from a potentially
  4162. large population of unruly peers and again to order the resulting list
  4163. by measurement quality. As in Version 1, The final selection procedure
  4164. repeatedly casts out outlyers on the basis of weighted dispersion.
  4165.  
  4166. 7.
  4167.  
  4168. The local-clock procedure of Version 2 were considerably improved over
  4169. Version 1 as the result of analysis, simulation and experience. Checks
  4170. have been added to warn that the oscillator has gone too long without
  4171. update from a reference source. The compliance register has been added
  4172. to improve frequency stability to the order of a millisecond per day.
  4173. The various parameters were retuned for optimum loop stability using
  4174. measured data over typical Internet paths and with typical local-clock
  4175. hardware. In version 3 the phase-lock loop model was further refined to
  4176. provide an adaptive-bandwidth feature that automatically adjusts for the
  4177. inherent stabilities of the reference clock and local clock while
  4178. providing optimum loop stability in each case.
  4179.  
  4180. 8.
  4181.  
  4182. Problems in the timekeeping calculations of Version 1 with high-speed
  4183. LANs were found and corrected in Version 2. These were caused by jitter
  4184. due to small differences in clock rates and different precisions between
  4185. the peers. Subtle bugs in the Version-1 reachability and polling-rate
  4186. control were found and corrected. The peer.valid and sys.hold variables
  4187. were added to avoid instabilities when the reference source changes
  4188. rapidly due to large dispersive delays under conditions of severe
  4189. network congestion. The peer.config, peer.authenable and peer.authentic
  4190. bits were added to control special features and simplify configuration.
  4191.  
  4192. 9.
  4193.  
  4194. In Version 3 The local-clock algorithm has been overhauled to improve
  4195. stability and accuracy. Appendix G presents a detailed mathematical
  4196. model and design example which has been refined with the aid of
  4197. feedback-control analysis and extensive simulation using data collected
  4198. over ordinary Internet paths. Section 5 of RFC-1119 on the NTP local
  4199. clock has been completely rewritten to describe the new algorithm. Since
  4200. the new algorithm can result in message rates far below the old ones, it
  4201. is highly recommended that they be used in new implementations. Note
  4202. that this algorithm is not integral to the NTP protocol specification
  4203. itself and its use does not affect interoperability with previous
  4204. versions or existing implementations; however, in order to insure
  4205. overall NTP subnet stability in the Internet, it is essential that the
  4206. local-clock characteristics of all NTP time servers conform to the
  4207. analytical models presented previously and in this document.
  4208.  
  4209. 10.
  4210.  
  4211. In Version 3 a new algorithm to combine the offsets of a number of peer
  4212. time servers is presented in Appendix F. This algorithm is modelled on
  4213. those used by national standards laboratories to combine the weighted
  4214. offsets from a number of standard clocks to construct a synthetic
  4215. laboratory timescale more accurate than that of any clock separately. It
  4216. can be used in an NTP implementation to improve accuracy and stability
  4217. and reduce errors due to asymmetric paths in the Internet. The new
  4218. algorithm has been simulated using data collected over ordinary Internet
  4219. paths and, along with the new local-clock algorithm, implemented and
  4220. tested in the Fuzzball time servers now running in the Internet. Note
  4221. that this algorithm is not integral to the NTP protocol specification
  4222. itself and its use does not affect interoperability with previous
  4223. versions or existing implementations.
  4224.  
  4225. 11.
  4226.  
  4227. Several inconsistencies and minor errors in previous versions have been
  4228. corrected in Version 3. The description of the procedures has been
  4229. rewritten in pseudo-code augmented by English commentary for clarity and
  4230. to avoid ambiguity. Appendix I has been added to illustrate C-language
  4231. implementations of the various filtering and selection algorithms
  4232. suggested for NTP. Additional information is included in Section 5 and
  4233. in Appendix E, which includes the tutorial material formerly included in
  4234. Section 2 of RFC-1119, as well as much new material clarifying the
  4235. interpretation of timescales and leap seconds.
  4236.  
  4237. 12.
  4238.  
  4239. Minor changes have been made in the Version-3 local-clock algorithms to
  4240. avoid problems observed when leap seconds are introduced in the UTC
  4241. timescale and also to support an auxiliary precision oscillator, such as
  4242. a cesium clock or timing receiver, as a precision timebase. In addition,
  4243. changes were made to some procedures described in Section 3 and in the
  4244. clock-filter and clock-selection procedures described in Section 4.
  4245. While these changes were made to correct minor bugs found as the result
  4246. of experience and are recommended for new implementations, they do not
  4247. affect interoperability with previous versions or existing
  4248. implementations in other than minor ways (at least until the next leap
  4249. second).
  4250.  
  4251. 13.
  4252.  
  4253. In Version 3 changes were made to the way delay, offset and dispersion
  4254. are defined, calculated and processed in order to reliably bound the
  4255. errors inherent in the time-transfer procedures. In particular, the
  4256. error accumulations were moved from the delay computation to the
  4257. dispersion computation and both included in the clock filter and
  4258. selection procedures. The clock-selection procedure was modified to
  4259. remove the first of the two sorting/discarding steps and replace with an
  4260. algorithm first proposed by Marzullo and later incorporated in the
  4261. Digital Time Service. These changes do not significantly affect the
  4262. ordinary operation of or compatibility with various versions of NTP, but
  4263. they do provide the basis for formal statements of correctness as
  4264. described in Appendix H.
  4265.  
  4266. Appendix E. The NTP Timescale and its Chronometry
  4267.  
  4268. Introduction
  4269.  
  4270. Following is an extended discussion on computer network chronometry,
  4271. which is the precise determination of computer time and frequency
  4272. relative to international standards and the determination of
  4273. conventional civil time and date according to the modern calendar. It
  4274. describes the methods conventionally used to establish civil time and
  4275. date and the various timescales now in use. In particular, it
  4276. characterizes the Network Time Protocol (NTP) timescale relative to the
  4277. Coordinated Universal Time (UTC) timescale, and establishes the precise
  4278. interpretation of UTC leap seconds in NTP.
  4279.  
  4280. In the following discussion the terms time, oscillator, clock, epoch,
  4281. calendar, date and timescale are used in a technical sense. Strictly
  4282. speaking, the time of an event is an abstraction which determines the
  4283. ordering of events in some given frame of reference. An oscillator is a
  4284. generator capable of precise frequency (relative to the given frame of
  4285. reference) to a specified tolerance. A clock is an oscillator together
  4286. with a counter which records the (fractional) number of cycles since
  4287. being initialized with a given value at a given time. The value of the
  4288. counter at any given time is called its epoch at that time. In general,
  4289. epoches are not continuous and depend on the precision of the counter.
  4290.  
  4291. A calendar is a mapping from epoch in some frame of reference to the
  4292. times and dates used in everyday life. Since multiple calendars are in
  4293. use today and sometimes disagree on the dating of the same events in the
  4294. past, the chronometry of past and present events is an art practiced by
  4295. historians. One of the goals of this discussion is to provide a standard
  4296. chronometry for precision dating of present and future events in a
  4297. global networking community. To synchronize frequency means to adjust
  4298. the oscillators in the network to run at the same frequency, to
  4299. synchronize time means to set the clocks so that all agree at a
  4300. particular epoch with respect to UTC, as provided by international
  4301. standards, and to synchronize clocks means to synchronize them in both
  4302. frequency and time.
  4303.  
  4304. In order to synchronize clocks, there must be some way to directly or
  4305. indirectly compare them in time and frequency. The ultimate frame of
  4306. reference for our world consists of the cosmic oscillators: the Sun,
  4307. Moon and other galactic orbiters. Since the frequencies of these
  4308. oscillators are relatively unstable and not known exactly, the ultimate
  4309. reference standard oscillator has been chosen by international agreement
  4310. as a synthesis of many observations of an atomic transition of exquisite
  4311. stability. The epoches of each heavenly and Earthbound oscillator
  4312. defines a distinctive timescale, not necessarily always continuous,
  4313. relative to the standard oscillator. Another goal of this presentation
  4314. is to describe a standard chronometry to rationalize conventional
  4315. computer time and UTC; in particular, how to handle leap seconds.
  4316.  
  4317. Primary Frequency and Time Standards
  4318.  
  4319. A primary frequency standard is an oscillator that can maintain
  4320. extremely precise frequency relative to a physical phenomenon, such as a
  4321. transition in the orbital states of an electron. Presently available
  4322. atomic oscillators are based on the transitions of the hydrogen, cesium
  4323. and rubidium atoms. Table 7<$&tab7> shows the characteristics for
  4324. typical oscillators of these types compared with those for various types
  4325. of quartz-crystal oscillators found in electronic equipment. For reasons
  4326. of cost and robustness cesium oscillators are used worldwide for
  4327. national primary frequency standards. On the other hand, local clocks
  4328. used in computing equipment almost always are designed with
  4329. uncompensated crystal oscillators.
  4330.  
  4331. For the three atomic oscillators listed in Table 7 the drift/aging
  4332. column shows the maximum offset per day from nominal standard frequency
  4333. due to systematic mechanical and electrical characteristics. In the case
  4334. of crystal oscillators this offset is not constant, which results in a
  4335. gradual change in frequency with time, called aging. Even if a crystal
  4336. oscillator is temperature compensated by some means, it must be
  4337. periodically compared to a primary standard in order to maintain the
  4338. highest accuracy. For all types of oscillators the stability column
  4339. shows the maximum variation in frequency per day due to circuit noise
  4340. and environmental factors.
  4341.  
  4342. As the telephone networks of the world are evolving rapidly to digital
  4343. technology, consideration should be given to the methods used for
  4344. frequency synchronization in digital networks. A network of clocks in
  4345. which each oscillator is phase-locked to a single frequency standard is
  4346. called isochronous, while a network in which some oscillators are phase-
  4347. locked to different master oscillators, but with the master oscillators
  4348. closely synchronized in frequency (not necessarily phase locked), to a
  4349. single frequency standard is called plesiochronous. In plesiochronous
  4350. systems the phase of some oscillators can slip relative to others and
  4351. cause occasional data errors in synchronous transmission systems.
  4352.  
  4353. The industry has agreed on a classification of clock oscillators as a
  4354. function of minimum accuracy, minimum stability and other factors
  4355. [ALL74a]. There are three factors which determine the classification:
  4356. stability, jitter and wander. Stability refers to the systematic
  4357. variation of frequency with time and is synonymous with aging, drift,
  4358. trends, etc. Jitter (also called timing jitter) refers to short-term
  4359. variations in frequency with components greater than 10 Hz, while wander
  4360. refers to long-term variations in frequency with components less than 10
  4361. Hz. The classification determines the oscillator stratum (not to be
  4362. confused with the NTP stratum), with the more accurate oscillators
  4363. assigned the lower strata and less accurate oscillators the higher
  4364. strata:
  4365.  
  4366. @Z_TBL_BEG = COLUMNS(3), DIMENSION(IN), COLWIDTHS(E1,E2,E2),
  4367. WIDTH(5.0000), ABOVE(.1670), BELOW(.0830), HGUTTER(.3330),
  4368. BOX(Z_SINGLE), KEEP(ON), ALIGN(CT), L1(R1C0..R1C3)
  4369.  
  4370. @Z_TBL_BODY = TABLE CENTER, TABLE HEADER, TABLE HEADER
  4371.  
  4372. Stratum, Min Accuracy (per day), Min Stability (per day)
  4373.  
  4374. @Z_TBL_BODY = TABLE CENTER, TABLE TEXT, TABLE TEXT
  4375.  
  4376. 1, 1 x 10-11, not specified
  4377.  
  4378. 2, 1.6 x 10-8, 1 x 10-10
  4379.  
  4380. 3, 4.6 x 10-6, 3.7 x 10-7
  4381.  
  4382. @Z_TBL_BODY = TABLE CENTER, TABLE HEADER, TABLE HEADER
  4383.  
  4384. 4, 3.2 x 10-5, not specified
  4385.  
  4386. @Z_TBL_END =
  4387.  
  4388. The construction, operation and maintenance of stratum-one oscillators
  4389. is assumed to be consistent with national standards and often includes
  4390. cesium oscillators or precision crystal oscillators synchronized via
  4391. LORAN-C to national standards. Stratum-two oscillators represent the
  4392. stability required for interexchange toll switches such as the AT&T 4ESS
  4393. and interexchange digital cross-connect systems, while stratum-three
  4394. oscillators represent the stability required for exchange switches such
  4395. as the AT&T 5ESS and local cross-connect systems. Stratum-four
  4396. oscillators represent the stability required for digital channel-banks
  4397. and PBX systems.
  4398.  
  4399. Time and Frequency Dissemination
  4400.  
  4401. In order that atomic and civil time can be coordinated throughout the
  4402. world, national administrations operate primary time and frequency
  4403. standards and coordinate them cooperatively by observing various radio
  4404. broadcasts and through occasional use of portable atomic clocks. Most
  4405. seafaring nations of the world operate some sort of broadcast time
  4406. service for the purpose of calibrating chronographs, which are used in
  4407. conjunction with ephemeris data to determine navigational position. In
  4408. many countries the service is primitive and limited to seconds-pips
  4409. broadcast by marine communication stations at certain hours. For
  4410. instance, a chronograph error of one second represents a longitudinal
  4411. position error of about 0.23 nautical mile at the Equator.
  4412.  
  4413. The U.S. National Institute of Standards and Technology (NIST - formerly
  4414. National Bureau of Standards) operates three radio services for the
  4415. dissemination of primary time and frequency information. One of these
  4416. uses high-frequency (HF or CCIR band 7) transmissions on frequencies of
  4417. 2.5, 5, 10, 15 and 20 MHz from Fort Collins, CO (WWV), and Kauai, HI
  4418. (WWVH). Signal propagation is usually by reflection from the upper
  4419. ionospheric layers, which vary in height and composition throughout the
  4420. day and season and result in unpredictable delay variations at the
  4421. receiver. The timecode is transmitted over a 60-second interval at a
  4422. data rate of 1 bps using a 100-Hz subcarrier on the broadcast signal.
  4423. The timecode information includes UTC time-day information, but does not
  4424. currently include year or leap-second warning. While these transmissions
  4425. and those of Canada from Ottawa, Ontario (CHU), and other countries can
  4426. be received over large areas in the western hemisphere, reliable
  4427. frequency comparisons can be made only to the order of 10-7 and time
  4428. accuracies are limited to the order of a millisecond [BLA74]. Radio
  4429. clocks which operate with these transmissions include the Traconex 1020,
  4430. which provides accuracies to about ten milliseconds and is priced in the
  4431. $1,500 range.
  4432.  
  4433. A second service operated by NIST uses low-frequency (LF or CCIR band 5)
  4434. transmissions on 60 kHz from Boulder, CO (WWVB), and can be received
  4435. over the continental U.S. and adjacent coastal areas. Signal propagation
  4436. is via the lower ionospheric layers, which are relatively stable and
  4437. have predictable diurnal variations in height. The timecode is
  4438. transmitted over a 60-second interval at a rate of 1 pps using periodic
  4439. reductions in carrier power. With appropriate receiving and averaging
  4440. techniques and corrections for diurnal and seasonal propagation effects,
  4441. frequency comparisons to within 10-11 are possible and time accuracies
  4442. of from a few to 50 microseconds can be obtained [BLA74]. Some countries
  4443. in western Europe operate similar services which use transmissions on 60
  4444. kHz from Rugby, U.K. (MSF), and on 77.5 kHz from Mainflingen, West
  4445. Germany (DCF77). The timecode information includes UTC time-day-year
  4446. information and leap-second warning. Radio clocks which operate with
  4447. these transmissions include the Spectracom 8170 and Kinemetrics/TrueTime
  4448. 60-DC and LF-DC, which provide accuracies to a millisecond or less and
  4449. are priced in the $2,500 range. However, these receivers do not extract
  4450. the year information and leap-second warning.
  4451.  
  4452. The third service operated by NIST uses ultra-high frequency (UHF or
  4453. CCIR band 9) transmissions on about 468 MHz from the Geosynchronous
  4454. Orbit Environmental Satellites (GOES), three of which cover the western
  4455. hemisphere. The timecode is interleaved with messages used to
  4456. interrogate remote sensors and consists of 60 4-bit binary-coded decimal
  4457. words transmitted over an interval of 30 seconds. The timecode
  4458. information includes UTC time-day-year information and leap-second
  4459. warning. Radio clocks which operate with these transmissions include the
  4460. Kinemetrics/TrueTime 468-DC, which provides accuracies to 0.5 ms and is
  4461. priced in the $6,000 range. However, this receiver does not extract the
  4462. year information and leap-second warning.
  4463.  
  4464. The U.S. Department of Defense is developing the Global Positioning
  4465. System (GPS) for worldwide precision navigation. This system will
  4466. eventually provide 24-hour worldwide coverage using a constellation of
  4467. 24 satellites in 12-hour orbits. For time-transfer applications GPS has
  4468. a potential accuracy in the order of a few nanoseconds; however, various
  4469. considerations of defense policy may limit accuracy to hundreds of
  4470. nanoseconds [VAN84]. The timecode information includes GPS time and UTC
  4471. correction; however, there appears to be no leap-second warning. Radio
  4472. clocks which operate with these transmissions include the
  4473. Kinemetrics/TrueTime GPS-DC, which provides accuracies to 200 <$Emu>s
  4474. and is priced in the $12,000 range. However, since only about half the
  4475. satellites have been launched, expensive rubidium or quartz oscillators
  4476. are necessary to preserve accuracy during outages. Also, since this is a
  4477. single-channel receiver, it must be supplied with geographic coordinates
  4478. within a degree from an external source before operation begins.
  4479.  
  4480. The U.S. Coast Guard, along with agencies of other countries, has
  4481. operated the LORAN-C [FRA82] radionavigation system for many years. It
  4482. currently provides time-transfer accuracies of less than a microsecond
  4483. and eventually may achieve 100 ns within the ground-wave coverage area
  4484. of a few hundred kilometers from the transmitter. Beyond the ground wave
  4485. area signal propagation is via the lower ionospheric layers, which
  4486. decreases accuracies to the order of 50 us. With the recent addition of
  4487. the Mid-Continent Chain, the deployment of LORAN-C transmitters now
  4488. provides complete coverage of the U.S. LORAN-C timing receivers, such as
  4489. the Austron 2000, are specialized and extremely expensive (up to
  4490. $20,000). They are used primarily to monitor local cesium clocks and are
  4491. not suited for unattended, automatic operation. While the LORAN-C system
  4492. provides a highly accurate frequency and time reference within the
  4493. ground wave area, there is no timecode modulation, so the receiver must
  4494. be supplied with UTC time to within a few tens of seconds from an
  4495. external source before operation begins.
  4496.  
  4497. The OMEGA [VAS78] radionavigation system operated by the U.S. Navy and
  4498. other countries consists of eight very-low-frequency (VLF or CCIR band
  4499. 4) transmitters operating on frequencies from 10.2 to 13.1 kHz and
  4500. providing 24-hour worldwide coverage. With appropriate receiving and
  4501. averaging techniques and corrections for propagation effects, frequency
  4502. comparisons and time accuracies are comparable to the LF systems, but
  4503. with worldwide coverage [BLA74]. Radio clocks which operate with these
  4504. transmissions include the Kinemetrics/TrueTime OM-DC, which provides
  4505. accuracies to 1 ms and is priced in the $3,500 range. While the OMEGA
  4506. system provides a highly accurate frequency reference, there is no
  4507. timecode modulation, so the receiver must be supplied with geographic
  4508. coordinates within a degree and UTC time within five seconds from an
  4509. external source before operation begins. There are several other VLF
  4510. services intended primarily for worldwide data communications with
  4511. characteristics similar to OMEGA. These services can be used in a manner
  4512. similar to OMEGA, but this requires specialized techniques not suited
  4513. for unattended, automatic operation.
  4514.  
  4515. Note that not all transmission formats used by NIST radio broadcast
  4516. services [NBS79] and no currently available radio clocks include
  4517. provisions for year information and leap-second warning. This
  4518. information must be determined from other sources. NTP includes
  4519. provisions to distribute advance warnings of leap seconds using the
  4520. leap-indicator bits described in the NTP specification. The protocol is
  4521. designed so that these bits can be set manually or by the radio timecode
  4522. at the primary time servers and then automatically distributed
  4523. throughout the synchronization subnet to all other time servers.
  4524. Calendar Systems
  4525.  
  4526. The calendar systems used in the ancient world reflect the agricultural,
  4527. political and ritual needs characteristic of the societies in which they
  4528. flourished. Astronomical observations to establish the winter and summer
  4529. solstices were in use three to four millennia ago. By the 14th century
  4530. BC the Shang Chinese had established the solar year as 365.25 days and
  4531. the lunar month as 29.5 days. The lunisolar calendar, in which the
  4532. ritual month is based on the Moon and the agricultural year on the Sun,
  4533. was used throughout the ancient Near East (except Egypt) and Greece from
  4534. the third millennium BC. Early calendars used either thirteen lunar
  4535. months of 28 days or twelve alternating lunar months of 29 and 30 days
  4536. and haphazard means to reconcile the 354/364-day lunar year with the
  4537. 365-day vague solar year.
  4538.  
  4539. The ancient Egyptian lunisolar calendar had twelve 30-day lunar months,
  4540. but was guided by the seasonal appearance of the star Sirius (Sothis).
  4541. In order to reconcile this calendar with the solar year, a civil
  4542. calendar was invented by adding five intercalary days for a total of 365
  4543. days. However, in time it was observed that the civil year was about
  4544. one-fourth day shorter than the actual solar year and thus would precess
  4545. relative to it over a 1460-year cycle called the Sothic cycle. Along
  4546. with the Shang Chinese, the ancient Egyptians had thus established the
  4547. solar year at 365.25 days, or within about 11 minutes of the present
  4548. measured value. In 432 BC, about a century after the Chinese had done
  4549. so, the Greek astronomer Meton calculated there were 110 lunar months of
  4550. 29 days and 125 lunar months of 30 days for a total of 235 lunar months
  4551. in 6940 solar days, or just over 19 years. The 19-year cycle, called the
  4552. Metonic cycle, established the lunar month at 29.532 solar days, or
  4553. within about two minutes of the present measured value.
  4554.  
  4555. The Roman republican calendar was based on a lunar year and by 50 BC was
  4556. eight weeks out of step with the solar year. Julius Caesar invited the
  4557. Alexandrian astronomer Sosigenes to redesign the calendar, which led to
  4558. the adoption in 46 BC of the Julian calendar. This calendar is based on
  4559. a year of 365 days with an intercalary day inserted every four years.
  4560. However, for the first 36 years an intercalary day was mistakenly
  4561. inserted every three years instead of every four. The result was 12
  4562. intercalary days instead of nine, and a series of corrections that was
  4563. not complete until 8 AD.
  4564.  
  4565. The seven-day Sumerian week was introduced only in the fourth century AD
  4566. by Emperor Constantine I. During the Roman era a 15-year census cycle,
  4567. called the Indiction cycle, was instituted for taxation purposes. The
  4568. sequence of day-names for consecutive occurrences of a particular day of
  4569. the year does not recur for 28 years, called the solar cycle. Thus, the
  4570. least common multiple of the 28-year solar cycle, 19-year Metonic cycle
  4571. and 15-year Indiction cycle results in a grand 7980-year supercycle
  4572. called the Julian Era, which began in 4713 BC. A particular combination
  4573. of the day of the week, day of the year, phase of the Moon and round of
  4574. the census will recur beginning in 3268 AD.
  4575.  
  4576. By 1545 the discrepancy in the Julian year relative to the solar year
  4577. had accumulated to ten days. In 1582, following suggestions by the
  4578. astronomers Christopher Clavius and Luigi Lilio, Pope Gregory XIII
  4579. issued a papal bull which decreed, among other things, that the solar
  4580. year would consist of 365.2422 days. In order to more closely
  4581. approximate the new value, only those centennial years divisible by 400
  4582. would be leap years, while the remaining centennial years would not,
  4583. making the actual value 365.2425, or within about 26 seconds of the
  4584. current measured value. Since the beginning of the Common Era and prior
  4585. to 1990 there were 474 intercalary days inserted in the Julian calendar,
  4586. but 14 of these were removed in the Gregorian calendar. While the
  4587. Gregorian calendar is in use throughout most of the world today, some
  4588. countries did not adopt it until early in the twentieth century.
  4589. While it remains a fascinating field for time historians, the above
  4590. narrative provides conclusive evidence that conjugating calendar dates
  4591. of significant events and assigning NTP timestamps to them is
  4592. approximate at best. In principle, reliable dating of such events
  4593. requires only an accurate count of the days relative to some globally
  4594. alarming event, such as a comet passage or supernova explosion; however,
  4595. only historically persistent and politically stable societies, such as
  4596. the ancient Chinese and Egyptian, and especially the classic Maya,
  4597. possessed the means and will to do so.
  4598.  
  4599. The Modified Julian Day System
  4600.  
  4601. In order to measure the span of the universe or the decay of the proton,
  4602. it is necessary to have a standard day-numbering plan. Accordingly, the
  4603. International Astronomical Union has adopted the use of the standard
  4604. second and Julian Day Number (JDN) to date cosmological events and
  4605. related phenomena. The standard day consists of 86,400 standard seconds,
  4606. where time is expressed as a fraction of the whole day, and the standard
  4607. year consists of 365.25 standard days.
  4608.  
  4609. In the scheme devised in 1583 by the French scholar Joseph Julius
  4610. Scaliger and named after his father, Julius Caesar Scaliger, JDN 0.0
  4611. corresponds to 12h (noon) on the first day of the Julian Era, 1 January
  4612. 4713 BC. The years prior to the Common Era (BC) are reckoned according
  4613. to the Julian calendar, while the years of the Common Era (AD) are
  4614. reckoned according to the Gregorian calendar. Since 1 January 1 AD in
  4615. the Gregorian calendar corresponds to 3 January 1 in the Julian calendar
  4616. [DER90], JDN 1,721,426.0 corresponds to 12h on the first day of the
  4617. Common Era, 1 January 1 AD. The Modified Julian Date (MJD), which is
  4618. sometimes used to represent dates near our own era in conventional time
  4619. and with fewer digits, is defined as MJD = JD <196> 2,400,000.5.
  4620. Following the convention that our century began at 0h on 1 January 1900,
  4621. at which time the tropical year was already 12h old, that eclectic
  4622. instant corresponds to MJD 15,020.0. Thus, the Julian timescale ticks in
  4623. standard (atomic) 365.25-day centuries and was set to a given value at
  4624. the approximate epoch of a cosmic event which apparently synchronized
  4625. the entire human community, the origin of the Common Era.
  4626.  
  4627. Determination of Frequency
  4628.  
  4629. For many years the most important use of time and frequency information
  4630. was for worldwide navigation and space science, which depend on
  4631. astronomical observations of the Sun, Moon and stars [JOR85]. Sidereal
  4632. time is based on the transit of stars across the celestial meridian of
  4633. an observer. The mean sidereal day is 23 hours, 56 minutes and 4.09
  4634. seconds, but varies about <F128M>µ<F255D>30 ms throughout the year due
  4635. to polar wandering and orbit variations. Ephemeris time is based on
  4636. tables with which a standard time interval such as the tropical year -
  4637. one complete revolution of the Earth around the Sun - can be determined
  4638. through observations of the Sun, Moon and planets. In 1958 the standard
  4639. second was defined as 1/31,556,925.9747 of the tropical year that began
  4640. this century. On this scale the tropical year is 365.2421987 days and
  4641. the lunar month - one complete revolution of the Moon around the Earth -
  4642. is 29.53059 days; however, the actual tropical year can be determined
  4643. only to an accuracy of about 50 ms and has been increasing by about 5.3
  4644. ms per year.
  4645.  
  4646. Of the three heavenly oscillators readily apparent to ancient mariners
  4647. and astronomers - the Earth rotation about its axis, the Earth
  4648. revolution around the Sun and the Moon revolution around the Earth -
  4649. none of the three have the intrinsic stability, relative to modern
  4650. technology, to serve as a standard reference oscillator. In 1967 the
  4651. standard second was redefined as <169>9,192,631,770 periods of the
  4652. radiation corresponding to the transition between the two hyperfine
  4653. levels of the ground state of the cesium-133 atom.<170> Since 1972 the
  4654. time and frequency standards of the world have been based on
  4655. International Atomic Time (TAI), which is defined and maintained using
  4656. multiple cesium-beam oscillators to an accuracy of a few parts in 1013,
  4657. or better than a microsecond per day. Note that, while this provides an
  4658. extraordinarily precise timescale, it does not necessarily agree with
  4659. conventional solar time and may not in fact even be absolutely uniform,
  4660. unless subtle atomic conspiracies can be ruled out.
  4661.  
  4662. Determination of Time and Leap Seconds
  4663.  
  4664. The International Bureau of Weights and Measures (IBWM) uses
  4665. astronomical observations provided by the U.S. Naval Observatory and
  4666. other observatories to determine UTC. Starting from apparent mean solar
  4667. time as observed, the UT0 timescale is determined using corrections for
  4668. Earth orbit and inclination (the Equation of Time, as used by sundials),
  4669. the UT1 (navigator's) timescale by adding corrections for polar
  4670. migration and the UT2 timescale by adding corrections for known
  4671. periodicity variations. While standard frequencies are based on TAI,
  4672. conventional civil time is based on UT1, which is presently slowing
  4673. relative to TAI by a fraction of a second per year. When the magnitude
  4674. of correction approaches 0.7 second, a leap second is inserted or
  4675. deleted in the TAI timescale on the last day of June or December.
  4676.  
  4677. For the most precise coordination and timestamping of events since 1972,
  4678. it is necessary to know when leap seconds are implemented in UTC and how
  4679. the seconds are numbered. As specified in CCIR Report 517, which is
  4680. reproduced in [BLA74], a leap second is inserted following second
  4681. 23:59:59 on the last day of June or December and becomes second 23:59:60
  4682. of that day. A leap second would be deleted by omitting second 23:59:59
  4683. on one of these days, although this has never happened. Leap seconds
  4684. were inserted prior to 1 January 1991 on the occasions listed in Table
  4685. 8<$&tab8> (courtesy U.S. Naval Observatory). Published IBWM corrections
  4686. consist not only of leap seconds, which result in step discontinuities
  4687. relative to TAI, but 100-ms UT1 adjustments called DUT1, which provide
  4688. increased accuracy for navigation and space science.
  4689.  
  4690. Note that the NTP time column actually shows the epoch following the
  4691. last second of the day given in the UTC date and MJD columns (except for
  4692. the first line), which is the precise epoch of insertion. The offset
  4693. column shows the cumulative seconds offset between the uncoordinated
  4694. (Julian) timescale and the UTC timescale; that is, the number of seconds
  4695. to add to the Julian clock in order to maintain nominal agreement with
  4696. the UTC clock. Finally, note that the epoch of insertion is relative to
  4697. the timescale immediately prior to that epoch; e.g., the epoch of the 31
  4698. December 90 insertion is determined on the timescale in effect following
  4699. the 31 December 1990 insertion, which means the actual insertion
  4700. relative to the Julian clock is fourteen seconds later than the apparent
  4701. time on the UTC timescale.
  4702.  
  4703. The UTC timescale thus ticks in standard (atomic) seconds and was set to
  4704. the value 0h MJD 41,317.0 at the epoch determined by astronomical
  4705. observation to be 0h on 1 January 1972 according to the Gregorian
  4706. calendar; that is, the inaugural tick of the UTC Era. In fact, the
  4707. inaugural tick which synchronized the cosmic oscillators, Julian clock,
  4708. UTC clock and Gregorian calendar forevermore was displaced about ten
  4709. seconds from the civil clock then in use, while the GPS clock is ahead
  4710. of the UTC clock by six seconds in late 1990. Subsequently, the UTC
  4711. clock has marched backward relative to the Julian timescale exactly one
  4712. second on scheduled occasions at monumental epoches embedded in the
  4713. institutional memory of our civilization. Note in passing that leap-
  4714. second adjustments affect the number of seconds per day and thus the
  4715. number of seconds per year. Apparently, should we choose to worry about
  4716. it, the UTC clock, Julian clock and various cosmic clocks will
  4717. inexorably drift apart with time until rationalized by some future papal
  4718. bull.
  4719.  
  4720. The NTP Timescale and Reckoning with UTC
  4721. The NTP timescale is based on the UTC timescale, but not necessarily
  4722. always coincident with it. At 0h on 1 January 1972 (MJD 41,317.0), the
  4723. first tick of the UTC Era, the NTP clock was set to 2,272,060,800,
  4724. representing the number of standard seconds since 0h on 1 January 1900
  4725. (MJD 15,020.0). The insertion of leap seconds in UTC and subsequently
  4726. into NTP does not affect the UTC or NTP oscillator, only the conversion
  4727. to conventional civil UTC time. However, since the only institutional
  4728. memory available to NTP are the UTC timecode broadcast services, the NTP
  4729. timescale is in effect reset to UTC as each timecode is received. Thus,
  4730. when a leap second is inserted in UTC and subsequently in NTP, knowledge
  4731. of all previous leap seconds is lost.
  4732.  
  4733. Another way to describe this is to say there are as many NTP timescales
  4734. as historic leap seconds. In effect, a new timescale is established
  4735. after each new leap second. Thus, all previous leap seconds, not to
  4736. mention the apparent origin of the timescale itself, lurch backward one
  4737. second as each new timescale is established. If a clock synchronized to
  4738. NTP in 1990 was used to establish the UTC epoch of an event that
  4739. occurred in early 1972 without correction, the event would appear
  4740. fifteen seconds late relative to UTC. However, NTP primary time servers
  4741. resolve the epoch using the broadcast timecode, so that the NTP clock is
  4742. set to the broadcast value on the current timescale. As a result, for
  4743. the most precise determination of epoch relative to the historic UTC
  4744. clock, the user must subtract from the apparent NTP epoch the offsets
  4745. shown in Table 8 at the relative epoches shown. This is a feature of
  4746. almost all present day time-distribution mechanisms.
  4747.  
  4748. The chronometry involved can be illustrated with the help of Figure 8,
  4749. which shows the details of seconds numbering just before, during and
  4750. after the last scheduled leap insertion at 23:59:59 on 31 December 1989.
  4751. Notice the NTP leap bits are set on the day prior to insertion, as
  4752. indicated by the <169>+<170> symbols on the figure. Since this makes the
  4753. day one second longer than usual, the NTP day rollover will not occur
  4754. until the end of the first occurrence of second 800. The UTC time
  4755. conversion routines must notice the apparent time and the leap bits and
  4756. handle the timescale conversions accordingly. Immediately after the leap
  4757. insertion both timescales resume ticking the seconds as if the leap had
  4758. never happened. The chronometric correspondence between the UTC and NTP
  4759. timescales continues, but NTP has forgotten about all past leap
  4760. insertions. In NTP chronometric determination of UTC time intervals
  4761. spanning leap seconds will thus be in error, unless the exact times of
  4762. insertion are known.
  4763.  
  4764. It is possible that individual systems may use internal data formats
  4765. other than the NTP timestamp format, which is represented in seconds to
  4766. a precision of about 200 picoseconds; however, a persuasive argument
  4767. exists to use a two-part representation, one part for whole days (MJD or
  4768. some fixed offset from it) and the other for the seconds (or some scaled
  4769. value, such as milliseconds). This not only facilitates conversion
  4770. between NTP and conventional civil time, but makes the insertion of leap
  4771. seconds much easier. All that is required is to change the modulus of
  4772. the seconds counter, which on overflow increments the day counter. This
  4773. design insures that continuity of the timescale is assured, even if
  4774. outside synchronization is lost before, during or after leap-second
  4775. insertion. Since timestamp data are unaffected, synchronization is
  4776. assured, even if timestamp data are in flight at the instant and
  4777. originated before or at that instant.
  4778.  
  4779. Appendix F. The NTP Clock-Combining Algorithm
  4780.  
  4781. Introduction
  4782.  
  4783. A common problem in synchronization subnets is systematic time-offset
  4784. errors resulting from asymmetric transmission paths, where the networks
  4785. or transmission media in one direction are substantially different from
  4786. the other. The errors can range from microseconds on high-speed ring
  4787. networks to large fractions of a second on satellite/landline paths. It
  4788. has been found experimentally that these errors can be considerably
  4789. reduced by combining the apparent offsets of a number of time servers to
  4790. produce a more accurate working offset. Following is a description of
  4791. the combining method used in the NTP implementation for the Fuzzball
  4792. [MIL88b]. The method is similar to that used by national standards
  4793. laboratories to determine a synthetic laboratory timescale from an
  4794. ensemble of cesium clocks [ALL74b]. These procedures are optional and
  4795. not required in a conforming NTP implementation.
  4796.  
  4797. In the following description the stability of a clock is how well it can
  4798. maintain a constant frequency, the accuracy is how well its frequency
  4799. and time compare with national standards and the precision is how
  4800. precisely these quantities can be maintained within a particular
  4801. timekeeping system. Unless indicated otherwise, The offset of two clocks
  4802. is the time difference between them, while the skew is the frequency
  4803. difference (first derivative of offset with time) between them. Real
  4804. clocks exhibit some variation in skew (second derivative of offset with
  4805. time), which is called drift.
  4806.  
  4807. Determining Time and Frequency
  4808.  
  4809. Figure 9<$&fig9> shows the overall organization of the NTP time-server
  4810. model. Timestamps exchanged with possibly many other subnet peers are
  4811. used to determine individual roundtrip delays and clock offsets relative
  4812. to each peer as described in the NTP specification. As shown in the
  4813. figure, the computed delays and offsets are processed by the clock
  4814. filter to reduce incidental timing noise and the most accurate and
  4815. reliable subset determined by the clock-selection algorithm. The
  4816. resulting offsets of this subset are first combined as described below
  4817. and then processed by the phase-locked loop (PLL). In the PLL the
  4818. combined effects of the filtering, selection and combining operations is
  4819. to produce a phase-correction term. This is processed by the loop filter
  4820. to control the local clock, which functions as a voltage-controlled
  4821. oscillator (VCO). The VCO furnishes the timing (phase) reference to
  4822. produce the timestamps used in all calculations.
  4823.  
  4824. Clock Modelling
  4825.  
  4826. The International Standard (SI) definition of time interval is in terms
  4827. of the standard second: <169>the duration of 9,192,631,770 periods of
  4828. the radiation corresponding to the transition between the two hyperfine
  4829. levels of the ground state of the cesium-133 atom.<170> Let u represent
  4830. the standard unit of time interval so defined and <$Ev~=~1 over u> be
  4831. the standard unit of frequency. The epoch, denoted by t, is defined as
  4832. the reading of a counter that runs at frequency v and began counting at
  4833. some agreed initial epoch t0, which defines the standard or absolute
  4834. timescale. For the purposes of the following analysis, the epoch of the
  4835. standard timescale, as well as the time indicated by a clock will be
  4836. considered continuous. In practice, time is determined relative to a
  4837. clock constructed from an atomic oscillator and system of
  4838. counter/dividers, which defines a timescale associated with that
  4839. particular oscillator. Standard time and frequency are then determined
  4840. from an ensemble of such timescales and algorithms designed to combine
  4841. them to produce a composite timescale approximating the standard
  4842. timescale.
  4843.  
  4844. Let <$ET(t)> be the time displayed by a clock at epoch t relative to the
  4845. standard timescale:
  4846.  
  4847. <$ET(t)~=~1/2 D(t sub 0 )[t~-~t sub 0 ] sup 2~+~R(t sub 0 )[t~-~t sub 0
  4848. ]~ +~T(t sub 0 )~+~x(t)> ,
  4849.  
  4850. where <$ED(t sub 0 )> is the fractional frequency drift per unit time,
  4851. <$ER(t sub 0 )> the frequency and <$ET(t sub 0 )> the time at some
  4852. previous epoch t0. In the usual stationary model these quantities can be
  4853. assumed constant or changing slowly with epoch. The random nature of the
  4854. clock is characterized by <$Ex(t)>, which represents the random noise
  4855. (jitter) relative to the standard timescale. In the usual analysis the
  4856. second-order term <$ED(t sub 0 )> is ignored and the noise term <$Ex(t)>
  4857. modelled as a normal distribution with predictable spectral density or
  4858. autocorrelation function.
  4859.  
  4860. The probability density function of time offset <$Eroman p (t~-~T(t))>
  4861. usually appears as a bell-shaped curve centered somewhere near zero. The
  4862. width and general shape of the curve are determined by <$Ex(t)>, which
  4863. depends on the oscillator precision and jitter characteristics, as well
  4864. as the measurement system and its transmission paths. Beginning at epoch
  4865. t0 the offset is set to zero, following which the bell creeps either to
  4866. the left or right, depending on the value of <$ER(t sub 0 )> and
  4867. accelerates depending on the value of <$ED(t sub 0 )>.
  4868.  
  4869. Development of a Composite Timescale
  4870.  
  4871. Now consider the time offsets of a number of real clocks connected by
  4872. real networks. A display of the offsets of all clocks relative to the
  4873. standard timescale will appear as a system of bell-shaped curves slowly
  4874. precessing relative to each other, but with some further away from
  4875. nominal zero than others. The bells will normally be scattered over the
  4876. offset space, more or less close to each other, with some overlapping
  4877. and some not. The problem is to estimate the true offset relative to the
  4878. standard timescale from a system of offsets collected routinely between
  4879. the clocks.
  4880.  
  4881. A composite timescale can be determined from a sequence of offsets
  4882. measured between the n clocks of an ensemble at nominal intervals
  4883. <$Etau>. Let <$ER sub i (t sub 0 )> be the frequency and <$ET sub i (t
  4884. sub 0 )> the time of the ith clock at epoch t0 relative to the standard
  4885. timescale and let <169>^<170> designate the associated estimates. Then,
  4886. an estimator for Ti computed at t0 for epoch <$Et sub 0~+~tau> is
  4887.  
  4888. <$ET hat sub i ( t sub 0~+~ tau )~=~R hat sub i (t sub 0 ) tau ~+~T sub
  4889. i (t sub 0 )> ,
  4890.  
  4891. neglecting second-order terms. Consider a set of n independent time-
  4892. offset measurements made between the clocks at epoch <$Et sub 0 ~+~ tau>
  4893. and let the offset between clock i and clock j at that epoch be <$ET sub
  4894. ij (t sub 0~+~ tau )>, defined as
  4895.  
  4896. <$ET sub ij (t sub 0~+~ tau )~==~T sub i (t sub 0~+~ tau )~-~T sub j (t
  4897. sub 0~+~ tau )> .
  4898.  
  4899. Note that <$ET sub ij~=~- T sub ji> and <$ET sub ii~=~0>. Let <$Ew sub i
  4900. ( tau )> be a previously determined weight factor associated with the
  4901. ith clock for the nominal interval <$Etau>. The basis for new estimates
  4902. at epoch <$Et sub 0~+~ tau > is
  4903.  
  4904. <$ET sub j (t sub 0~+~tau )~=~sum from {i=1} to n w sub i ( tau )[ T hat
  4905. sub i (t sub 0~+~tau )~+~T sub ji (t sub 0~+~tau )].>
  4906.  
  4907. That is, the apparent time indicated by the jth clock is a weighted
  4908. average of the estimated time of each clock at epoch <$Et sub 0 ~+~ tau>
  4909. plus the time offset measured between the jth clock and that clock at
  4910. epoch <$Et sub 0 ~+~ tau>.
  4911.  
  4912. An intuitive grasp of the behavior of this algorithm can be gained with
  4913. the aid of a few examples. For instance, if <$Ew sub i ( tau )> is unity
  4914. for the ith clock and zero for all others, the apparent time for each of
  4915. the other clocks is simply the estimated time <$ET hat sub i (t sub
  4916. 0~+~tau )>. If <$Ew sub i ( tau )> is zero for the ith clock, that clock
  4917. can never affect any other clock and its apparent time is determined
  4918. entirely from the other clocks. If <$Ew sub i ( tau )~=~1 / n> for all
  4919. i, the apparent time of the ith clock is equal to the average of the
  4920. time estimates computed at t0 plus the average of the time offsets
  4921. measured to all other clocks. Finally, in a system with two clocks and
  4922. <$Ew sub i ( tau )~=~1 / 2> for each, and if the estimated time at epoch
  4923. <$Et sub 0~+~tau> is fast by 1 s for one clock and slow by 1 s for the
  4924. other, the apparent time for both clocks will coincide with the standard
  4925. timescale.
  4926.  
  4927. In order to establish a basis for the next interval <$Etau>, it is
  4928. necessary to update the frequency estimate <$ER hat sub i (t sub 0~+~tau
  4929. )> and weight factor <$Ew sub i ( tau )>. The average frequency assumed
  4930. for the ith clock during the previous interval <$Etau> is simply the
  4931. difference between the times at the beginning and end of the interval
  4932. divided by <$Etau>. A good estimator for <$ER sub i (t sub 0~+~tau )>
  4933. has been found to be the exponential average of these differences, which
  4934. is given by
  4935.  
  4936. <$ER hat sub i (t sub 0~+~tau )~=~R hat sub i (t sub 0 )~+~alpha sub i [
  4937. R hat sub i (t sub 0 )~-~{T sub i (t sub 0~+~tau )~-~T sub i (t sub 0 )}
  4938. over tau ]> ,
  4939.  
  4940. where <$Ealpha sub i> is an experimentally determined weight factor
  4941. which depends on the estimated frequency error of the ith clock. In
  4942. order to calculate the weight factor <$Ew sub i ( tau )>, it is
  4943. necessary to determine the expected error <$Eepsilon sub i ( tau )> for
  4944. each clock. In the following, braces <169>|<170> indicate absolute value
  4945. and brackets <169><<>><170> indicate the infinite time average. In
  4946. practice, the infinite averages are computed as exponential time
  4947. averages. An estimate of the magnitude of the unbiased error of the ith
  4948. clock accumulated over the nominal interval <$Etau> is
  4949.  
  4950. <$Eepsilon sub i ( tau )~=~| T hat sub i ( t sub 0~+~tau )~-~T sub i ( t
  4951. sub 0~+~tau ) |~+~{0.8~<<~epsilon sub e sup 2 ( tau )~>> } over sqrt {
  4952. <<~epsilon sub i sup 2 ( tau )~>> }> ,
  4953.  
  4954. where <$Eepsilon sub i ( tau )> and <$Eepsilon sub e ( tau )> are the
  4955. accumulated error of the ith clock and entire clock ensemble,
  4956. respectively. The accumulated error of the entire ensemble is
  4957.  
  4958. <$E<<~epsilon sub e sup 2 ( tau )~>>~=~left [ sum from i=1 to n~1 over {
  4959. <<~epsilon sub i sup 2 ( tau )~>> } right ] sup {~-1}>.
  4960.  
  4961. Finally, the weight factor for the ith clock is calculated as
  4962.  
  4963. <$Ew sub i ( tau )~=~ { <<~epsilon sub e sup 2 ( tau )~>> } over {
  4964. <<~epsilon sub i sup 2 ( tau )~>> }> .
  4965.  
  4966. When all estimators and weight factors have been updated, the origin of
  4967. the estimation interval is shifted and the new value of t0 becomes the
  4968. old value of <$Et sub 0 ~+~ tau>.
  4969.  
  4970. While not entering into the above calculations, it is useful to estimate
  4971. the frequency error, since the ensemble clocks can be located some
  4972. distance from each other and become isolated for some time due to
  4973. network failures. The frequency-offset error in Ri is equivalent to the
  4974. fractional frequency yi,
  4975.  
  4976. <$Ey sub i~=~{ nu sub i~-~nu sub I } over nu sub I>
  4977.  
  4978. measured between the ith timescale and the standard timescale I.
  4979. Temporarily dropping the subscript i for clarity, consider a sequence of
  4980. N independent frequency-offset samples <$Ey(j)~ (j~=~1,~2,~... ,~N)>
  4981. where the interval between samples is uniform and equal to T. Let
  4982. <$Etau> be the nominal interval over which these samples are averaged.
  4983. The Allan variance <$Esigma sub y sup 2 ( N,~T,~tau )> [ALL74a] is
  4984. defined as
  4985. <$E<< sigma sub y sup 2 ( N,~T,~tau )~>>~=~<< ~ 1 over { N~-~1 }~ left [
  4986. sum from j=1 to N~y (j) sup 2~-~1 over N~left ( sum from j=1 to N~y(j)
  4987. right ) sup 2 right ]~>>> ,
  4988.  
  4989. A particularly useful formulation is <$EN~=~2> and <$ET~=~tau>:
  4990.  
  4991. <$E<< sigma sub y sup 2 (N~=~2,~T~=~tau ,~tau )>>~==~sigma sub y sup 2 (
  4992. tau )~=~<< {[y(j~+~1)~-~y(j)] sup 2 } over 2 >>> ,
  4993.  
  4994. so that
  4995.  
  4996. <$Esigma sub y sup 2 ( tau )~=~1 over {2(N~-~1)}sum from { j = 1 } to
  4997. {n-1 }~[y(j~+~1)~-~y(j)] sup 2> .
  4998.  
  4999. While the Allan variance has found application when estimating errors in
  5000. ensembles of cesium clocks, its application to NTP is limited due to the
  5001. computation and storage burden. As described in the next section, it is
  5002. possible to estimate errors with some degree of confidence using normal
  5003. byproducts of NTP processing algorithms.
  5004.  
  5005. Application to NTP
  5006.  
  5007. The NTP clock model is somewhat less complex than the general model
  5008. described above. For instance, at the present level of development it is
  5009. not necessary to separately estimate the time and frequency of all peer
  5010. clocks, only the time and frequency of the local clock. If the
  5011. timekeeping reference is the local clock itself, then the offsets
  5012. available in the peer.offset peer variables can be used directly for the
  5013. <$ET sub ij> quantities above. In addition, the NTP local-clock model
  5014. incorporates a type-II phase-locked loop, which itself reliably
  5015. estimates frequency errors and corrects accordingly. Thus, the
  5016. requirement for estimating frequency is entirely eliminated.
  5017.  
  5018. There remains the problem of how to determine a robust and easily
  5019. computable error estimate <$Eepsilon sub i>. The method described above,
  5020. although analytically justified, is most difficult to implement.
  5021. Happily, as a byproduct of the NTP clock-filter algorithm, a useful
  5022. error estimate is available in the form of the dispersion. As described
  5023. in the NTP specification, the dispersion includes the absolute value of
  5024. the weighted average of the offsets between the chosen offset sample and
  5025. the <$En~-~1> other samples retained for selection. The effectiveness of
  5026. this estimator was compared with the above estimator by simulation using
  5027. observed timekeeping data and found to give quite acceptable results.
  5028.  
  5029. The NTP clock-combining algorithm can be implemented with only minor
  5030. modifications to the algorithms as described in the NTP specification.
  5031. Although elsewhere in the NTP specification the use of general-purpose
  5032. multiply/divide routines has been successfully avoided, there seems to
  5033. be no way to avoid them in the clock-combining algorithm. However, for
  5034. best performance the local-clock algorithm described elsewhere in this
  5035. document should be implemented as well, since the combining algorithms
  5036. result in a modest increase in phase noise which the revised local-clock
  5037. algorithm is designed to suppress.
  5038.  
  5039. Clock-Combining Procedure
  5040.  
  5041. The result of the NTP clock-selection procedure is a set of survivors
  5042. (there must be at least one) that represent truechimers, or correct
  5043. clocks. When clock combining is not implemented, one of these peers,
  5044. chosen as the most likely candidate, becomes the synchronization source
  5045. and its computed offset becomes the final clock correction.
  5046. Subsequently, the system variables are adjusted as described in the NTP
  5047. clock-update procedure. When clock combining is implemented, these
  5048. actions are unchanged, except that the final clock correction is
  5049. computed by the clock-combining procedure.
  5050.  
  5051. The clock-combining procedure is called from the clock-select procedure.
  5052. It constructs from the variables of all surviving peers the final clock
  5053. correction <$ETHETA>. The estimated error required by the algorithms
  5054. previously described is based on the synchronization distance <$ELAMBDA>
  5055. computed by the distance procedure, as defined in the NTP specification.
  5056. The reciprocal of <$ELAMBDA> is the weight of each clock-offset
  5057. contribution to the final clock correction. The following pseudo-code
  5058. describes the procedure.
  5059.  
  5060. begin clock-combining procedure
  5061.         <$Etemp1~<<-~0>;
  5062.         <$Etemp2~<<-~0>;
  5063.         for (each peer remaining on the candidate list)         /* scan
  5064. all survivors */
  5065.                 <$ELAMBDA~<<-~roman distance (peer)>;
  5066.                 <$Etemp~<<-~1 over roman
  5067. {peer.stratum~times~NTP.MAXDISPERSE~+~LAMBDA }>;
  5068.                 <$Etemp1~<<-~temp1~+~temp>;             /* update weight
  5069. and offset */
  5070.                 <$Etemp2~<<-~temp2~+~temp~times~roman peer.offset>;
  5071.                 endif;
  5072.         <$ETHETA~<<-~temp2 over temp1>;                                 
  5073. /* compute final correction */
  5074.         end clock-combining procedure;
  5075.  
  5076. The value <$ETHETA> is the final clock correction used by the local-
  5077. clock procedure to adjust the clock.
  5078.  
  5079. Appendix G. Computer Clock Modelling and Analysis
  5080.  
  5081. A computer clock includes some kind of reference oscillator, which is
  5082. stabilized by a quartz crystal or some other means, such as the power
  5083. grid. Usually, the clock includes a prescaler, which divides the
  5084. oscillator frequency to a standard value, such as 1 MHz or 100 Hz, and a
  5085. counter, implemented in hardware, software or some combination of the
  5086. two, which can be read by the processor. For systems intended to be
  5087. synchronized to an external source of standard time, there must be some
  5088. means to correct the phase and frequency by occasional vernier
  5089. adjustments produced by the timekeeping protocol. Special care is
  5090. necessary in all timekeeping system designs to insure that the clock
  5091. indications are always monotonically increasing; that is, system time
  5092. never <169>runs backwards.<170>
  5093.  
  5094. Computer Clock Models
  5095.  
  5096. The simplest computer clock consists of a hardware latch which is set by
  5097. overflow of a hardware counter or prescaler, and causes a processor
  5098. interrupt or tick. The latch is reset when acknowledged by the
  5099. processor, which then increments the value of a software clock counter.
  5100. The phase of the clock is adjusted by adding periodic corrections to the
  5101. counter as necessary. The frequency of the clock can be adjusted by
  5102. changing the value of the increment itself, in order to make the clock
  5103. run faster or slower. The precision of this simple clock model is
  5104. limited to the tick interval, usually in the order of 10 ms; although in
  5105. some systems the tick interval can be changed using a kernel variable.
  5106.  
  5107. This software clock model requires a processor interrupt on every tick,
  5108. which can cause significant overhead if the tick interval is small, say
  5109. in the order less 1 ms with the newer RISC processors. Thus, in order to
  5110. achieve timekeeping precisions less than 1 ms, some kind of hardware
  5111. assist is required. A straightforward design consists of a voltage-
  5112. controlled oscillator (VCO), in which the frequency is controlled by a
  5113. buffered, digital/analog converter (DAC). Under the assumption that the
  5114. VCO tolerance is 10-4 or 100 parts-per-million (ppm) (a reasonable value
  5115. for inexpensive crystals) and the precision required is 100 <$Emu roman
  5116. s> (a reasonable goal for a RISC processor), the DAC must include at
  5117. least ten bits.
  5118.  
  5119. A design sketch of a computer clock constructed entirely of hardware
  5120. logic components is shown in Figure 10a<$&fig10>. The clock is read by
  5121. first pulsing the read signal, which latches the current value of the
  5122. clock counter, then adding the contents of the clock-counter latch and a
  5123. 64-bit clock-offset variable, which is maintained in processor memory.
  5124. The clock phase is adjusted by adding a correction to the clock-offset
  5125. variable, while the clock frequency is adjusted by loading a correction
  5126. to the DAC latch. In principle, this clock model can be adapted to any
  5127. precision by changing the number of bits of the prescaler or clock
  5128. counter or changing the VCO frequency. However, it does not seem useful
  5129. to reduce precision much below the minimum interrupt latency, which is
  5130. in the low microseconds for a modern RISC processor.
  5131.  
  5132. If it is not possible to vary the oscillator frequency, which might be
  5133. the case if the oscillator is an external frequency standard, a design
  5134. such as shown in Figure 10b may be used. It includes a fixed-frequency
  5135. oscillator and prescaler which includes a dual-modulus swallow counter
  5136. that can be operated in either divide-by-10 or divide-by-11 modes as
  5137. controlled by a pulse produced by a programmable divider (PD). The PD is
  5138. loaded with a value representing the frequency offset. Each time the
  5139. divider overflows a pulse is produced which switches the swallow counter
  5140. from the divide-by-10 mode to the divide-by-11 mode and then back again,
  5141. which in effect <169>swallows<170> or deletes a single pulse of the
  5142. prescaler pulse train.
  5143.  
  5144. The pulse train produced by the prescaler is controlled precisely over a
  5145. small range by the contents of the PD. If programmed to emit pulses at a
  5146. low rate, relatively few pulses are swallowed per second and the
  5147. frequency counted is near the upper limit of its range; while, if
  5148. programmed to emit pulses at a high rate, relatively many pulses are
  5149. swallowed and the frequency counted is near the lower limit. Assuming
  5150. some degree of freedom in the choice of oscillator frequency and
  5151. prescaler ratios, this design can compensate for a wide range of
  5152. oscillator frequency tolerances.
  5153.  
  5154. In all of the above designs it is necessary to limit the amount of
  5155. adjustment incorporated in any step to insure that the system clock
  5156. indications are always monotonically increasing. With the software clock
  5157. model this is assured as long as the increment is never negative. When
  5158. the magnitude of a phase adjustment exceeds the tick interval (as
  5159. corrected for the frequency adjustment), it is necessary to spread the
  5160. adjustments over mulitple tick intervals. This strategy amounts to a
  5161. deliberate frequency offset sustained for an interval equal to the total
  5162. number of ticks required and, in fact, is a feature of the Unix clock
  5163. model discussed below.
  5164.  
  5165. In the hardware clock models the same considerations apply; however, in
  5166. these designs the tick interval amounts to a single pulse at the
  5167. prescaler output, which may be in the order of 1 ms. In order to avoid
  5168. decreasing the indicated time when a negative phase correction occurs,
  5169. it is necessary to avoid modifying the clock-offset variable in
  5170. processor memory and to confine all adjustments to the VCO or prescaler.
  5171. Thus, all phase adjustments must be performed by means of programmed
  5172. frequency adjustments in much the same way as with the software clock
  5173. model described previously.
  5174.  
  5175. It is interesting to conjecture on the design of a processor assist that
  5176. could provide all of the above functions in a compact, general-purpose
  5177. hardware interface. The interface might consist of a multifunction timer
  5178. chip such as the AMD 9513A, which includes five 16-bit counters, each
  5179. with programmable load and hold registers, plus an onboard crystal
  5180. oscillator, prescaler and control circuitry. A 48-bit hardware clock
  5181. counter would utilize three of the 16-bit counters, while the fourth
  5182. would be used as the swallow counter and the fifth as the programmable
  5183. divider. With the addition of a programmable-array logic device and
  5184. architecture-specific host interface, this compact design could provide
  5185. all the functions necessary for a comprehensive timekeeping system.
  5186.  
  5187. The Fuzzball Clock Model
  5188.  
  5189. The Fuzzball clock model uses a combination of hardware and software to
  5190. provide precision timing with a minimum of software and processor
  5191. overhead. The model includes an oscillator, prescaler and hardware
  5192. counter; however, the oscillator frequency remains constant and the
  5193. hardware counter produces only a fraction of the total number of bits
  5194. required by the clock counter. A typical design uses a 64-bit software
  5195. clock counter and a 16-bit hardware counter which counts the prescaler
  5196. output. A hardware-counter overflow causes the processor to increment
  5197. the software counter at the bit corresponding to the frequency <$E2 sup
  5198. N f sub p>, where N is the number of bits of the hardware counter and fp
  5199. is the counted frequency at the prescaler output. The processor reads
  5200. the clock counter by first generating a read pulse, which latches the
  5201. hardware counter, and then adding its contents, suitably aligned, to the
  5202. software counter.
  5203.  
  5204. The Fuzzball clock can be corrected in phase by adding a (signed)
  5205. adjustment to the software clock counter. In practice, this is done only
  5206. when the local time is substantially different from the time indicated
  5207. by the clock and may violate the monotonicity requirement. Vernier phase
  5208. adjustments determined in normal system operation must be limited to no
  5209. more than the period of the counted frequency, which is 1 kHz for LSI-11
  5210. Fuzzballs. In the Fuzzball model these adjustments are performed at
  5211. intervals of 4 s, called the adjustment interval, which provides a
  5212. maximum frequency adjustment range of 250 ppm. The adjustment
  5213. opportunities are created using the interval-timer facility, which is a
  5214. feature of most operating systems and independent of the time-of-day
  5215. clock. However,  if the counted frequency is increased from 1 kHz to 1
  5216. MHz for enhanced precision, the adjustment frequency must be increased
  5217. to 250 Hz, which substantially increases processor overhead. A modified
  5218. design suitable for high precision clocks is presented in the next
  5219. section.
  5220.  
  5221. In some applications involving the Fuzzball model, an external pulse-
  5222. per-second (pps) signal is available from a reference source such as a
  5223. cesium clock or GPS receiver. Such a signal generally provides much
  5224. higher accuracy than the serial character string produced by a radio
  5225. timecode receiver, typically in the low nanoseconds. In the Fuzzball
  5226. model this signal is processed by an interface which produces a hardware
  5227. interrupt coincident with the arrival of the pps pulse. The processor
  5228. then reads the clock counter and computes the residual modulo 1 s of the
  5229. clock counter. This represents the local-clock error relative to the pps
  5230. signal.
  5231.  
  5232. Assuming the seconds numbering of the clock counter has been determined
  5233. by a reliable source, such as a timecode receiver, the offset within the
  5234. second is determined by the residual computed above. In the NTP local-
  5235. clock model the timecode receiver or NTP establishes the time to within
  5236. <F128M>µ<F255D>128 ms, called the aperture, which guarantees the seconds
  5237. numbering to within the second. Then, the pps residual can be used
  5238. directly to correct the oscillator, since the offset must be less than
  5239. the aperture for a correctly operating timecode receiver and pps signal.
  5240.  
  5241. The above technique has an inherent error equal to the latency of the
  5242. interrupt system, which in modern RISC processors is in the low tens of
  5243. microseconds. It is possible to improve accuracy by latching the
  5244. hardware time-of-day counter directly by the pps pulse and then reading
  5245. the counter in the same way as usual. This requires additional circuitry
  5246. to prioritize the pps signal relative to the pulse generated by the
  5247. program to latch the counter.
  5248. The Unix Clock Model
  5249.  
  5250. The Unix 4.3bsd clock model is based on two system calls, settimeofday
  5251. and adjtime, together with two kernel variables tick and tickadj. The
  5252. settimeofday call unceremoniously resets the kernel clock to the value
  5253. given, while the adjtime call slews the kernel clock to a new value
  5254. numerically equal to the sum of the present time of day and the (signed)
  5255. argument given in the adjtime call. In order to understand the behavior
  5256. of the Unix clock as controlled by the Fuzzball clock model described
  5257. above, it is helpful to explore the operations of adjtime in more
  5258. detail.
  5259.  
  5260. The Unix clock model assumes an interrupt produced by an onboard
  5261. frequency source, such as the clock counter and prescaler described
  5262. previously, to deliver a pulse train in the 100-Hz range. In priniciple,
  5263. the power grid frequency can be used, although it is much less stable
  5264. than a crystal oscillator. Each interrupt causes an increment called
  5265. tick to be added to the clock counter. The value of the increment is
  5266. chosen so that the clock counter, plus an initial offset established by
  5267. the settimeofday call, is equal to the time of day in microseconds.
  5268.  
  5269. The Unix clock can actually run at three different rates, one
  5270. corresponding to tick, which is related to the intrinsic frequency of
  5271. the particular oscillator used as the clock source, one to
  5272. <$Etick~+~tickadj> and the third to <$Etick~-~tickadj>. Normally the
  5273. rate corresponding to tick is used; but, if adjtime is called, the
  5274. argument <$Edelta> given is used to calculate an interval <$EDELTA
  5275. t~=~delta~tick over tickadj> during which one or the other of the two
  5276. rates are used, depending on the sign of <$Edelta>. The effect is to
  5277. slew the clock to a new value at a small, constant rate, rather than
  5278. incorporate the adjustment all at once, which could cause the clock to
  5279. be set backward. With common values of <$Etick~=~10> ms and
  5280. <$Etickadj~=~5~mu roman s>, the maximum frequency adjustment range is
  5281. <$E+- tickadj over tick~=~+- {5~roman x~10 sup -6} over {10 sup -2}> or
  5282. <F128M>µ<F255D>500 ppm. Even larger ranges may be required in the case
  5283. of some workstations (e.g., SPARCstations) with extremely poor component
  5284. tolerances.
  5285.  
  5286. When precisions not less than about 1 ms are required, the Fuzzball
  5287. clock model can be adapted to the Unix model by software simulation, as
  5288. described in Section 5 of the NTP specification, and calling adjtime at
  5289. each adjustment interval. When precisions substantially better than this
  5290. are required, the hardware microsecond clock provided in some
  5291. workstations can be used together with certain refinements of the
  5292. Fuzzball and Unix clock models. The particular design described below is
  5293. appropriate for a maximum oscillator frequency tolerance of 100 ppm
  5294. (.01%), which can be obtained using a relatively inexpensive quartz
  5295. crystal oscillator, but is readily scalable for other assumed
  5296. tolerances.
  5297.  
  5298. The clock model requires the capability to slew the clock frequency over
  5299. the range <F128M>µ<F255D>100 ppm with an intrinsic oscillator frequency
  5300. error as great as <F128M>µ<F255D>100 ppm. Figure 11<$&fig11> shows the
  5301. timing relationships at the extremes of the requirements envelope.
  5302. Starting from an assumed offset of nominal zero and an assumed error of
  5303. +100 ppm at time 0 s, the line AC shows how the uncorrected offset grows
  5304. with time. Let <$Esigma> represent the adjustment interval and a the
  5305. interval AB, in seconds, and let r be the slew, or rate at which
  5306. corrections are introduced, in ppm. For an accuracy specification of 100
  5307. <$Emu roman s>, then
  5308.  
  5309. <$Esigma~<<=~{100~mu roman s} over {100~roman ppm}~+~{100~mu roman s}
  5310. over {(r~-~100)~roman ppm}~=~r over {r~-~100}> .
  5311. The line AE represents the extreme case where the clock is to be steered
  5312. <F128M>-<F255D>100 ppm. Since the slew must be complete at the end of
  5313. the adjustment interval,
  5314.  
  5315. <$Ea~<<=~{(r~-~200)~sigma} over r>.
  5316.  
  5317. These relationships are satisfied only if <$Er~>>~200~roman ppm> and
  5318. <$Esigma~<<~2~roman s>. Using <$Er~=~300~roman ppm> for convenience,
  5319. <$Esigma~=~1.5~roman s> and <$Ea~<<=~0.5~roman s>. For the Unix clock
  5320. model with <$Etick~=~10~roman ms>, this results in the value of
  5321. <$Etickadj~=~3~mu roman s>.
  5322.  
  5323. One of the assumptions made in the Unix clock model is that the period
  5324. of adjustment computed in the adjtime call must be completed before the
  5325. next call is made. If not, this results in an error message to the
  5326. system log. However, in order to correct for the intrinsic frequency
  5327. offset of the clock oscillator, the NTP clock model requires adjtime to
  5328. be called at regular adjustment intervals of <$Esigma> s. Using the
  5329. algorithms described here and the architecture constants in the NTP
  5330. specification, these adjustments will always complete.
  5331.  
  5332. Mathematical Model of the NTP Logical Clock
  5333.  
  5334. The NTP logical clock can be represented by the feedback-control model
  5335. shown in Figure 12<$&fig12>. The model consists of an adaptive-
  5336. parameter, phase-lock loop (PLL), which continuously adjusts the phase
  5337. and frequency of an oscillator to compensate for its intrinsic jitter,
  5338. wander and drift. A mathematical analysis of this model developed along
  5339. the lines of [SMI86] is presented in following sections, along with a
  5340. design example useful for implementation guidance in operating-systems
  5341. environments such as Unix and Fuzzball. Table 9<$&tab9> summarizes the
  5342. quantities ordinarily treated as variables in the model. By convention,
  5343. <$Ev> is used for internal loop variables, <$Etheta> for phase,
  5344. <$Eomega> for frequency and <$Etau> for time. Table 10<$&tab10>
  5345. summarizes those quantities ordinarily fixed as constants in the model.
  5346. Note that these are all expressed as a power of two in order to simplify
  5347. the implementation.
  5348.  
  5349. In Figure 12 the variable <$Etheta sub r> represents the phase of the
  5350. reference signal and <$Etheta sub o> the phase of the voltage-controlled
  5351. oscillator (VCO). The phase detector (PD) produces a voltage <$Ev sub d>
  5352. representing the phase difference <$Etheta sub r~-~theta sub o> . The
  5353. clock filter functions as a tapped delay line, with the output <$Ev sub
  5354. s> taken at the tap selected by the clock-filter algorithm described in
  5355. the NTP specification. The loop filter, represented by the equations
  5356. given below, produces a VCO correction voltage <$Ev sub c>, which
  5357. controls the oscillator frequency and thus the phase <$Etheta sub o>.
  5358.  
  5359. The PLL behavior is completely determined by its open-loop, Laplace
  5360. transfer function <$EG(s)> in the s domain. Since both frequency and
  5361. phase corrections are required, an appropriate design consists of a
  5362. type-II PLL, which is defined by the function
  5363.  
  5364. <$EG(s)~=~{omega sub c sup 2} over {tau sup 2 s sup 2}~( 1 ~+~{tau s}
  5365. over omega sub z )> ,
  5366.  
  5367. where <$Eomega sub c> is the crossover frequency (also called loop
  5368. gain), <$Eomega sub z> is the corner frequency (required for loop
  5369. stability) and <$Etau> determines the PLL time constant and thus the
  5370. bandwidth. While this is a first-order function and some improvement in
  5371. phase noise might be gained from a higher-order function, in practice
  5372. the improvement is lost due to the effects of the clock-filter delay, as
  5373. described below.
  5374.  
  5375. The open-loop transfer function <$EG(s)> is constructed by breaking the
  5376. loop at point a on Figure 12 and computing the ratio of the output phase
  5377. <$Etheta sub o (s)> to the reference phase <$Etheta sub r (s)>. This
  5378. function is the product of the individual transfer functions for the
  5379. phase detector, clock filter, loop filter and VCO. The phase detector
  5380. delivers a voltage <$Ev sub d (t)~=~ theta sub r (t)>, so its transfer
  5381. function is simply <$EF sub d (s)~=~1>, expressed in V/rad. The VCO
  5382. delivers a frequency change <$EDELTA omega ~=~{roman d~theta sub o (t)}
  5383. over {roman dt}~=~alpha {v sub c (t)}>, where <$Ealpha> is the VCO gain
  5384. in rad/V-sec and <$Etheta sub o (t)~=~alpha~int v sub c (t)~dt>. Its
  5385. transfer function is the Laplace transform of the integral, <$EF sub o
  5386. (s)~=~alpha over s>, expressed in rad/V. The clock filter contributes a
  5387. stochastic delay due to the clock-filter algorithm; but, for present
  5388. purposes, this delay will be assumed a constant T, so its transfer
  5389. function is the Laplace transform of the delay, <$EF sub s (s)~=~e sup
  5390. {- Ts}>. Let <$EF(s)> be the transfer function of the loop filter, which
  5391. has yet to be determined. The open-loop transfer function <$EG(s)> is
  5392. the product of these four individual transfer functions:
  5393.  
  5394. <$EG(s)~=~{omega sub c sup 2} over {tau sup 2 s sup 2}~( 1 ~+~{tau s}
  5395. over omega sub z )~=~F sub d (s) F sub s (s) F(s) F sub o (s)~=~1e sup
  5396. {-Ts}~F(s)~alpha over s> .
  5397.  
  5398. For the moment, assume that the product <$ETs> is small, so that <$Ee
  5399. sup {-Ts}~approx ~1>. Making the following substitutions,
  5400.  
  5401. <$Eomega sub c sup 2~=~alpha over { K sub f}~~~~> and <$E~~~~omega sub
  5402. z~=~K sub g over {K sub f}>
  5403.  
  5404. and rearranging yields
  5405.  
  5406. <$EF(s)~=~1 over {K sub g~tau}~+~1 over {K sub f~tau sup 2 s }> ,
  5407.  
  5408. which corresponds to a constant term plus an integrating term scaled by
  5409. the PLL time constant <$Etau>. This form is convenient for
  5410. implementation as a sampled-data system, as described later.
  5411.  
  5412. With the parameter values given in Table 10, the Bode plot of the open-
  5413. loop transfer function <$EG(s)> consists of a <196>12 dB/octave line
  5414. which intersects the 0-dB baseline at <$Eomega sub c~=~2 sup -12> rad/s,
  5415. together with a +6 dB/octave line at the corner frequency <$Eomega sub
  5416. z~=~2 sup -14> rad/s. The damping factor <$Ezeta~=~omega sub c over {2
  5417. omega sub z}~=~2> suggests the PLL will be stable and have a large phase
  5418. margin together with a low overshoot. However, if the clock-filter delay
  5419. T is not small compared to the loop delay, which is approximately equal
  5420. to <$E1 over omega sub c>, the above analysis becomes unreliable and the
  5421. loop can become unstable. With the values determined as above, T is
  5422. ordinarily small enough to be neglected.
  5423.  
  5424. Assuming the output is taken at <$Ev sub s>, the closed-loop transfer
  5425. function <$EH(s)> is
  5426.  
  5427. <$EH(s)~==~{v sub s (s)} over {theta sub r (s)}~=~{F sub d (s) e sup {-
  5428. Ts}} over {1~+~G(s)}> .
  5429.  
  5430. If only the relative response is needed and the clock-filter delay can
  5431. be neglected, <$EH(s)> can be written
  5432.  
  5433. <$EH(s)~=~1 over {1~+~G(s)}~=~s sup 2 over {s sup 2~+~omega sub c sup 2
  5434. over {omega sub z~tau} s~+~omega sub c sup 2 over tau sup 2}> .
  5435.  
  5436. For some input function <$EI(s)> the output function <$EI(s)H(s)> can be
  5437. inverted to find the time response. Using a unit-step input <$EI(s)~=~1
  5438. over s> and the values determined as above, This yields a PLL risetime
  5439. of about 52 minutes, a maximum overshoot of about 4.8 percent in about
  5440. 1.7 hours and a settling time to within one percent of the initial
  5441. offset in about 8.7 hours.
  5442. Parameter Management
  5443.  
  5444. A very important feature of the NTP PLL design is the ability to adapt
  5445. its behavior to match the prevailing stability of the local oscillator
  5446. and transmission conditions in the network. This is done using the
  5447. <$Ealpha> and <$Etau> parameters shown in Table 10. Mechanisms for doing
  5448. this are described in following sections.
  5449.  
  5450. Adjusting VCO Gain (<$Ebold alpha>)
  5451.  
  5452. The <$Ealpha> parameter is determined by the maximum frequency tolerance
  5453. of the local oscillator and the maximum jitter requirements of the
  5454. timekeeping system. This parameter is usually an architecture constant
  5455. and fixed during system operation. In the implementation model described
  5456. below, the reciprocal of <$Ealpha>, called the adjustment interval
  5457. <$Esigma>, determines the time between corrections of the local clock,
  5458. and thus the value of <$Ealpha>. The value of <$Esigma> can be
  5459. determined by the following procedure.
  5460.  
  5461. The maximum frequency tolerance for board-mounted, uncompensated quartz-
  5462. crystal oscillators is probably in the range of 10-4 (100 ppm). Many if
  5463. not most Internet timekeeping systems can tolerate jitter to at least
  5464. the order of the intrinsic local-clock resolution, called precision in
  5465. the NTP specification, which is commonly in the range from one to 20 ms.
  5466. Assuming 10-3 s peak-to-peak as the most demanding case, the interval
  5467. between clock corrections must be no more than <$Esigma~=~10 sup -3 over
  5468. {2 roman~x~10 sup -4}~=~5> sec. For the NTP reference model
  5469. <$Esigma~=~4> sec in order to allow for known features of the Unix
  5470. operating-system kernel. However, in order to support future anticipated
  5471. improvements in accuracy possible with faster workstations, it may be
  5472. useful to decrease <$Esigma> to as little as one-tenth the present
  5473. value.
  5474.  
  5475. Note that if <$Esigma> is changed, it is necessary to adjust the
  5476. parameters <$EK sub f> and <$EK sub g> in order to retain the same loop
  5477. bandwidth; in particular, the same <$Eomega sub c> and <$Eomega sub z>.
  5478. Since <$Ealpha> varies as the reciprocal of <$Esigma>, if <$Esigma> is
  5479. changed to something other than 22, as in Table 10, it is necessary to
  5480. divide both <$EK sub f> and <$EK sub g> by <$Esigma over 4> to obtain
  5481. the new values.
  5482.  
  5483. Adjusting PLL Bandwidth (<$Ebold tau>)
  5484.  
  5485. A key feature of the type-II PLL design is its capability to compensate
  5486. for the intrinsic frequency errors of the local oscillator. This
  5487. requires a initial period of adaptation in order to refine the frequency
  5488. estimate (see later sections of this appendix). The <$Etau> parameter
  5489. determines the PLL time constant and thus the loop bandwidth, which is
  5490. approximately equal to <$E{omega sub c} over tau>. When operated with a
  5491. relatively large bandwidth (small <$Etau>), as in the analysis above,
  5492. the PLL adapts quickly to changes in the input reference signal, but has
  5493. poor long term stability. Thus, it is possible to accumulate substantial
  5494. errors if the system is deprived of the reference signal for an extended
  5495. period. When operated with a relatively small bandwidth (large <$Etau>),
  5496. the PLL adapts slowly to changes in the input reference signal, and may
  5497. even fail to lock onto it. Assuming the frequency estimate has
  5498. stabilized, it is possible for the PLL to coast for an extended period
  5499. without external corrections and without accumulating significant error.
  5500.  
  5501. In order to achieve the best performance without requiring individual
  5502. tailoring of the loop bandwidth, it is necessary to compute each value
  5503. of <$Etau> based on the measured values of offset, delay and dispersion,
  5504. as produced by the NTP protocol itself. The traditional way of doing
  5505. this in precision timekeeping systems based on cesium clocks, is to
  5506. relate <$Etau> to the Allan variance, which is defined as the mean of
  5507. the first-order differences of sequential samples measured during a
  5508. specified interval <$Etau>,
  5509.  
  5510. <$Esigma sub y sup 2 ( tau )~=~1 over {2(N~-~1)}sum from { i = 1 } to
  5511. {N-1 }~[y(i~+~1)~-~y(i)] sup 2> ,
  5512.  
  5513. where y is the fractional frequency measured with respect to the local
  5514. timescale and N is the number of samples.
  5515.  
  5516. In the NTP local-clock model the Allan variance (called the compliance,
  5517. h in Table 11) is approximated on a continuous basis by exponentially
  5518. averaging the first-order differences of the offset samples using an
  5519. empirically determined averaging constant. Using somewhat ad-hoc mapping
  5520. functions determined from simulation and experience, the compliance is
  5521. manipulated to produce the loop time constant and update interval.
  5522.  
  5523. The NTP Clock Model
  5524.  
  5525. The PLL behavior can also be described by a set of recurrence equations,
  5526. which depend upon several variables and constants. The variables and
  5527. parameters used in these equations are shown in Tables 9, 10 and
  5528. 11<$&tab11>. Note the use of powers of two, which facilitates
  5529. implementation using arithmetic shifts and avoids the requirement for a
  5530. multiply/divide capability.
  5531.  
  5532. A capsule overview of the design may be helpful in understanding how it
  5533. operates. The logical clock is continuously adjusted in small increments
  5534. at fixed intervals of <$Esigma>. The increments are determined while
  5535. updating the variables shown in Tables 9 and 11, which are computed from
  5536. received NTP messages as described in the NTP specification. Updates
  5537. computed from these messages occur at discrete times as each is
  5538. received. The intervals <$Emu> between updates are variable and can
  5539. range up to about 17 minutes. As part of update processing the
  5540. compliance h is computed and used to adjust the PLL time constant
  5541. <$Etau>. Finally, the update interval <$Erho> for transmitted NTP
  5542. messages is determined as a fixed multiple of <$Etau>.
  5543.  
  5544. Updates are numbered from zero, with those in the neighborhood of the
  5545. ith update shown in Figure 13<$&fig13>. All variables are initialized at
  5546. <$Ei~=~0> to zero, except the time constant <$Etau (0)~=~tau>, poll
  5547. interval <$Emu (0)~=~tau> (from Table 10) and compliance <$Eh (0)~=~K
  5548. sub s>. After an interval <$Emu (i)> (<$Ei~>>~0>) from the previous
  5549. update the ith update arrives at time <$Et(i)> including the time
  5550. offset <$Ev sub s (i)>. Then, after an interval <$Emu (i~+~1)> the
  5551. <$Ei+1 roman th> update arrives at time <$Et(i~+~1)> including the time
  5552. offset <$Ev sub s (i~+~1)>. When the update <$Ev sub s (i)> is received,
  5553. the frequency error <$Ef(i~+~1)> and phase error <$Eg(i~+~1)> are
  5554. computed:
  5555.  
  5556. <$Ef(i~+~1)~=~f(i)~+~{mu (i) v sub s (i)} over {tau (i) sup 2 }>
  5557. ,<$E~~~~~g(i~+~1)~=~{v sub s (i)} over {tau (i)}> .
  5558.  
  5559. Note that these computations depend on the value of the time constant
  5560. <$Etau (i)> and poll interval <$Emu (i)> previously computed from the
  5561. <$Ei-1 roman th> update. Then, the time constant for the next interval
  5562. is computed from the current value of the compliance <$Eh(i)>
  5563.  
  5564. <$Etau (i~+~1)~=~roman max [K sub s~-~|~h(i)|,~1]> .
  5565.  
  5566. Next, using the new value of <$Etau>, called <$Etau prime> to avoid
  5567. confusion, the poll interval is computed
  5568.  
  5569. <$Erho (i~+~1)~=~K sub u~tau prime> .
  5570.  
  5571. Finally, the compliance <$Eh(i~+~1)> is recomputed for use in the <$Ei+1
  5572. roman th> update:
  5573. <$Eh(i~+~1)~=~h(i)~+~{K sub t~tau prime v sub s (i)~-~h(i) }over K sub
  5574. h> .
  5575.  
  5576. The factor <$Etau prime> in the above has the effect of adjusting the
  5577. bandwidth of the PLL as a function of compliance. When the compliance
  5578. has been low over some relatively long period, <$Etau prime> is
  5579. increased and the bandwidth is decreased. In this mode small timing
  5580. fluctuations due to jitter in the network are suppressed and the PLL
  5581. attains the most accurate frequency estimate. On the other hand, if the
  5582. compliance becomes high due to greatly increased jitter or a systematic
  5583. frequency offset, <$Etau prime> is decreased and the bandwidth is
  5584. increased. In this mode the PLL is most adaptive to transients which can
  5585. occur due to reboot of the system or a major timing error. In order to
  5586. maintain optimum stability, the poll interval <$Erho> is varied directly
  5587. with <$Etau>.
  5588.  
  5589. A model suitable for simulation and parameter refinement can be
  5590. constructed from the above recurrence relations. It is convenient to set
  5591. the temporary variable <$Ea~=~g(i~+~1)>. At each adjustment interval
  5592. <$Esigma> the quantity <$Ea over K sub g~+~{f(i~+~1)} over K sub f> is
  5593. added to the local-clock phase and the quantity <$Ea over K sub g> is
  5594. subtracted from a. For convenience, let n be the greatest integer in
  5595. <$E{mu (i)} over sigma>; that is, the number of adjustments that occur
  5596. in the ith interval. Thus, at the end of the ith interval just before
  5597. the <$Ei+1 roman th> update, the VCO control voltage is:
  5598.  
  5599. <$Ev sub c (i~+~1)~=~v sub c (i)~+~{[1~-~(1~-~1 over K sub g ) sup n
  5600. ]}~{g(i~+~1)} ~+~n over {K sub f }~{ f(i~+~1)}~.>
  5601.  
  5602. Detailed simulation of the NTP PLL with the values specified in Tables
  5603. 9, 10 and 11 and the clock filter described in the NTP specification
  5604. results in the following characteristics: For a 100-ms phase change the
  5605. loop reaches zero error in 39 minutes, overshoots 7 ms at 54 minutes and
  5606. settles to less than 1 ms in about six hours. For a 50-ppm frequency
  5607. change the loop reaches 1 ppm in about 16 hours and 0.1 ppm in about 26
  5608. hours. When the magnitude of correction exceeds a few milliseconds or a
  5609. few ppm for more than a few updates, the compliance begins to increase,
  5610. which causes the loop time constant and update interval to decrease.
  5611. When the magnitude of correction falls below about 0.1 ppm for a few
  5612. hours, the compliance begins to decrease, which causes the loop time
  5613. constant and update interval to increase. The effect is to provide a
  5614. broad capture range exceeding 4 s per day, yet the capability to resolve
  5615. oscillator skew well below 1 ms per day. These characteristics are
  5616. appropriate for typical crystal-controlled oscillators with or without
  5617. temperature compensation or oven control.
  5618.  
  5619. Appendix H. Analysis of Errors and Correctness Principles
  5620.  
  5621. Introduction
  5622.  
  5623. This appendix contains an analysis of errors arising in the generation
  5624. and processing of NTP timestamps and the determination of delays and
  5625. offsets. It establishes error bounds as a function of measured roundtrip
  5626. delay and dispersion to the root (primary reference source) of the
  5627. synchronization subnet. It also discusses correctness assertions about
  5628. these error bounds and the time-transfer, filtering and selection
  5629. algorithms used in NTP.
  5630.  
  5631. The notation <$Ew~=~[u,~v]> in the following describes the interval in
  5632. which u is the lower limit and v the upper limit, inclusive. Thus,
  5633. <$Eu~=~min (w)~<<=~v~=~max (w)>, and for scalar a,
  5634. <$Ew~+~a~=~[u~+~a,~v~+~a]>. Table 12<$&tab12> shows a summary of other
  5635. notation used in the analysis. The notation <$E<<~x~>>> designates the
  5636. (infinite) average of x, which is usually approximated by an exponential
  5637. average, while the notation <$Ex hat> designates an estimator for x. The
  5638. lower-case Greek letters <$Etheta>, <$Edelta> and <$Eepsilon> are used
  5639. to designate measurement data for the local clock to a peer clock, while
  5640. the upper-case Greek letters <$ETHETA>, <$EDELTA> and <$EEPSILON> are
  5641. used to designate measurement data for the local clock relative to the
  5642. primary reference source at the root of the synchronization subnet.
  5643. Exceptions will be noted as they arise.
  5644.  
  5645. Timestamp Errors
  5646.  
  5647. The standard second (1 s) is defined as <169>9,192,631,770 periods of
  5648. the radiation corresponding to the transition between the two hyperfine
  5649. levels of the ground state of the cesium-133 atom<170> [ALL74b], which
  5650. implies a granularity of about 1.1x10-10 s. Other intervals can be
  5651. determined as rational multiples of 1 s. While NTP time has an inherent
  5652. resolution of about 2.3x10-10 s, local clocks ordinarily have
  5653. resolutions much worse than this, so the inherent error in resolving NTP
  5654. time relative to the 1 s can be neglected.
  5655.  
  5656. In this analysis the local clock is represented by a counter/divider
  5657. which increments at intervals of s seconds and is driven by an
  5658. oscillator which operates at frequency <$Ef sub c~=~n over s> for some
  5659. integer n. A timestamp <$ET(t)> is determined by reading the clock at an
  5660. arbitrary time t (the argument t will be usually omitted for
  5661. conciseness). Strictly speaking, s is not known exactly, but can be
  5662. assumed bounded from above by the maximum reading error <$Erho>. The
  5663. reading error itself is represented by the random variable r bounded by
  5664. the interval <$E[-~rho ,~0]>, where <$Erho> depends on the particular
  5665. clock implementation. Since the intervals between reading the same clock
  5666. are almost always independent of and much larger than s, successive
  5667. readings can be considered independent and identically distributed. The
  5668. frequency error of the clock oscillator is represented by the random
  5669. variable f bounded by the interval <$E[-~phi ,~phi ]>, where <$Ephi>
  5670. represents the maximum frequency tolerance of the oscillator throughout
  5671. its service life. While f for a particular clock is a random variable
  5672. with respect to the population of all clocks, for any one clock it
  5673. ordinarily changes only slowly with time and can usually be assumed a
  5674. constant for that clock. Thus, an NTP timestamp can be represented by
  5675. the random variable T:
  5676.  
  5677. <$ET~=~t~+~r~+~f tau> ,
  5678.  
  5679. where t represents a clock reading, <$Etau> represents the time interval
  5680. since this reading and minor approximations inherent in the measurement
  5681. of <$Etau> are neglected.
  5682.  
  5683. In order to assess the nature and expected magnitude of timestamp errors
  5684. and the calculations based on them, it is useful to examine the
  5685. characteristics of the probability density functions (pdf) <$Ep sub r
  5686. (x)> and <$Ep sub f (x)> for r and f respectively. Assuming the clock
  5687. reading and counting processes are independent, the pdf for r is uniform
  5688. over the interval <$E[-~rho ,~0]>. With conventional manufacturing
  5689. processes and temperature variations the pdf for f can be approximated
  5690. by a truncated, zero-mean Gaussian distribution with standard deviation
  5691. <$Esigma>. In conventional manufacturing processes <$Esigma> is
  5692. maneuvered so that the fraction of samples rejected outside the interval
  5693. <$E[-~phi ,~phi ]> is acceptable. The pdf for the total timestamp error
  5694. <$Eepsilon (x)> is thus the sum of the r and f contributions, computed
  5695. as
  5696.  
  5697. <$Eepsilon (x)~ =~ int~from {- inf } to inf p sub r (t) p sub f (x~-~t)
  5698. d t> ,
  5699.  
  5700. which appears as a bell-shaped curve, symmetric about <$E-~rho over 2>
  5701. and bounded by the interval
  5702.  
  5703. <$E[ min (r)~+~min (f tau ),~max (r)~+~max (f tau )]~=~[-~rho ~-~phi tau
  5704. ,~phi tau ]> .
  5705. Since f changes only slowly over time for any single clock,
  5706.  
  5707. <$Eepsilon~==~[ min (r)~+~f tau ,~max (r)~+~f tau ]~=~ [-~ rho ,~0]~+~f
  5708. tau> ,
  5709.  
  5710. where <$Eepsilon> without argument designates the interval and
  5711. <$Eepsilon (x)> designates the pdf. In the following development
  5712. subscripts will be used on various quantities to indicate to which
  5713. entity or timestamp the quantity applies. Occasionally, <$Eepsilon> will
  5714. be used to designate an absolute maximum error, rather than the
  5715. interval, but the distinction will be clear from context.
  5716.  
  5717. Measurement Errors
  5718.  
  5719. In NTP the roundtrip delay and clock offset between two peers A and B
  5720. are determined by a procedure in which timestamps are exchanged via the
  5721. network paths between them. The procedure involves the four most recent
  5722. timestamps numbered as shown in Figure 14<$&fig14>, where the <$Etheta
  5723. sub 0> represents the true clock offset of peer B relative to peer A.
  5724. The <$ET sub 1> and <$ET sub 4> timestamps are determined relative to
  5725. the A clock, while the <$ET sub 2> and <$ET sub 3> timestamps are
  5726. determined relative to the B clock. The measured roundtrip delay
  5727. <$Edelta> and clock offset <$Etheta> of B relative to A are given by
  5728.  
  5729. <$Edelta~=~(T sub 4~-~T sub 1 )~-~(T sub 3~-~T sub 2
  5730. )~~~~and~~~~theta~=~{(T sub 2~-~T sub 1 )~+~(T sub 3~-~T sub 4 )} over
  5731. 2> .
  5732.  
  5733. The errors inherent in determining the timestamps T1, T2, T3 and T4 are,
  5734. respectively,
  5735.  
  5736. <$Eepsilon sub 1~=~[-~rho sub A ,~0]>, <$E~epsilon sub 2~=~[-~rho sub B
  5737. ,~0]>, <$E~epsilon sub 3~=~[-~rho sub B ,~0]~+~f sub B (T sub 3 ~-~T sub
  5738. 2 )>, <$E~epsilon sub 4~=~[-~rho sub A ,~0]~+~f sub A (T sub 4 ~-~T sub
  5739. 1 )> .
  5740.  
  5741. For specific peers A and B, where <$Ef sub A> and <$Ef sub B> can be
  5742. considered constants, the interval containing the maximum error inherent
  5743. in determining <$Edelta> is given by
  5744.  
  5745. <$E[ min ( epsilon sub 4 )~-~max ( epsilon sub 1 )~-~max ( epsilon sub 3
  5746. )~+~min ( epsilon sub 2 ),~ max ( epsilon sub 4 )~-~min ( epsilon sub 1
  5747. )~-~min ( epsilon sub 3 )~+~max ( epsilon sub 2 )]>
  5748. <$E=~[-~rho sub A~-~rho sub B ,~rho sub A ~+~rho sub B ]~+~f sub A (T
  5749. sub 4~-~T sub 1 )~-~f sub B (T sub 3~-~T sub 2 )> .
  5750.  
  5751. In the NTP local clock model the residual frequency errors <$Ef sub A>
  5752. and <$Ef sub B> are minimized through the use of a type-II phase-lock
  5753. loop (PLL). Under most conditions these errors will be small and can be
  5754. ignored. The pdf for the remaining errors is symmetric, so that <$Edelta
  5755. hat~=~<< delta >>> is an unbiased maximum-likelihood estimator for the
  5756. true roundtrip delay, independent of the particular values of <$Erho sub
  5757. A> and <$Erho sub B>.
  5758.  
  5759. However, in order to reliably bound the errors under all conditions of
  5760. component variation and operational regimes, the design of the PLL and
  5761. the tolerance of its intrinsic oscillator must be controlled so that it
  5762. is not possible under any circumstances for <$Ef sub A> or <$Ef sub B>
  5763. to exceed the bounds <$E[-~phi sub A ,~phi sub A ]> or <$E[-~phi sub B
  5764. ,~phi sub B ]>, respectively. Setting <$Erho~=~max ( rho sub A ,~rho sub
  5765. B )> for convenience, the absolute maximum error <$Eepsilon sub delta>
  5766. inherent in determining roundtrip delay <$Edelta> is given by
  5767.  
  5768. <$Eepsilon sub delta~==~rho~+~phi sub A (T sub 4~-~T sub 1 )~+~phi sub B
  5769. (T sub 3~-~T sub 2 )> ,
  5770. neglecting residuals.
  5771.  
  5772. As in the case for <$Edelta>, where <$Ef sub A> and <$Ef sub B> can be
  5773. considered constants, the interval containing the maximum error inherent
  5774. in determining <$Etheta> is given by
  5775.  
  5776. <$E{[ min ( epsilon sub 2 )~-~max ( epsilon sub 1 )~+~min ( epsilon sub
  5777. 3 )~-~max ( epsilon sub 4 ),~ max ( epsilon sub 2 )~-~min ( epsilon sub
  5778. 1 )~+~max ( epsilon sub 3 )~-~min ( epsilon sub 4 )]} over 2>
  5779. <$E=~[ -~rho sub B ,~rho sub A ]~+~{f sub B (T sub 3~-~T sub 2 )~-~f sub
  5780. A (T sub 4 ~-~T sub 1 )} over 2> .
  5781.  
  5782. Under most conditions the errors due to <$Ef sub A> and <$Ef sub B> will
  5783. be small and can be ignored. If <$Erho sub A~=~rho sub B~=~rho>; that
  5784. is, if both the A and B clocks have the same resolution, the pdf for the
  5785. remaining errors is symmetric, so that <$Etheta hat~=~<< theta >>> is an
  5786. unbiased maximum-likelihood estimator for the true clock offset <$Etheta
  5787. sub 0>, independent of the particular value of <$Erho>. If <$Erho sub
  5788. A~!=~rho sub B>, <$E<< theta >>> is not an unbiased estimator; however,
  5789. the bias error is in the order of
  5790.  
  5791. <$E{rho sub A~-~rho sub B } over 2> .
  5792.  
  5793. and can usually be neglected.
  5794.  
  5795. Again setting <$Erho~=~max ( rho sub A ,~rho sub B )> for convenience,
  5796. the absolute maximum error <$Eepsilon sub theta> inherent in determining
  5797. clock offset <$Etheta> is given by
  5798.  
  5799. <$Eepsilon sub theta~==~{rho~+~phi sub A (T sub 4~-~T sub 1 )~+~phi sub
  5800. B (T sub 3~-~T sub 2 )} over 2 > .
  5801.  
  5802. Network Errors
  5803.  
  5804. In practice, errors due to stochastic network delays usually dominate.
  5805. In general, it is not possible to characterize network delays as a
  5806. stationary random process, since network queues can grow and shrink in
  5807. chaotic fashion and arriving customer traffic is frequently bursty.
  5808. However, it is a simple exercise to calculate bounds on clock offset
  5809. errors as a function of measured delay. Let <$ET sub 2~-~T sub 1~=~a>
  5810. and <$ET sub 3~-~T sub 4~=~b>. Then,
  5811.  
  5812. <$Edelta~=~a~-~b~~~~ and ~~~~theta~=~{a~+~b} over 2> .
  5813.  
  5814. The true offset of B relative to A is called <$Etheta sub 0> in Figure
  5815. 14. Let x denote the actual delay between the departure of a message
  5816. from A and its arrival at B. Therefore, <$Ex~+~theta sub 0~=~T sub 2~-~T
  5817. sub 1~==~a>. Since x must be positive in our universe, <$Ex~=~a~-~theta
  5818. sub 0~>>=~0>, which requires <$Etheta sub 0~<<=~a>. A similar argument
  5819. requires that <$Eb~<<=~theta sub 0>, so surely <$Eb~<<=~theta sub
  5820. 0~<<=~a>. This inequality can also be expressed
  5821.  
  5822. <$Eb~=~{a~+~b} over 2~-~{a~-~b} over 2~<<=~theta sub 0~<<=~{a~+~b} over
  5823. 2~+~{a~-~b} over 2~=~a> ,
  5824.  
  5825. which is equivalent to
  5826.  
  5827. <$Etheta~-~delta over 2~<<=~theta sub 0~<<=~theta~+~delta over 2> .
  5828.  
  5829. In the previous section bounds on delay and offset errors were
  5830. determined. Thus, the inequality can be written
  5831.  
  5832. <$Etheta~-~epsilon sub theta~-~{delta~+~epsilon sub delta} over
  5833. 2~<<=~theta sub 0~<<=~theta~+~epsilon sub theta~+~{delta~+~ epsilon sub
  5834. delta } over 2> ,
  5835. where <$Eepsilon sub theta> is the maximum offset error and <$Eepsilon
  5836. sub delta> is the maximum delay error derived previously. The quantity
  5837.  
  5838. <$Eepsilon~=~epsilon sub theta~+~epsilon sub delta over 2~=~rho~+~phi
  5839. sub A (T sub 4~-~T sub 1 )~+~phi sub B (T sub 3~-~T sub 2 )> ,
  5840.  
  5841. called the peer dispersion, defines the maximum error in the inequality.
  5842. Thus, the correctness interval I can be defined as the interval
  5843.  
  5844. <$EI~=~[ theta~-~delta over 2~-~epsilon ,~theta~+~delta over 2~+~epsilon
  5845. ]> ,
  5846.  
  5847. in which the clock offset <$EC~=~theta> is the midpoint. By
  5848. construction, the true offset <$Etheta sub 0> must lie somewhere in this
  5849. interval.
  5850.  
  5851. Inherited Errors
  5852.  
  5853. As described in the NTP specification, the NTP time server maintains the
  5854. local clock <$ETHETA>, together with the root roundtrip delay <$EDELTA>
  5855. and root dispersion <$EEPSILON> relative to the primary reference source
  5856. at the root of the synchronization subnet. The values of these variables
  5857. are either included in each update message or can be derived as
  5858. described in the NTP specification. In addition, the protocol exchange
  5859. and clock-filter algorithm provide the clock offset <$Etheta> and
  5860. roundtrip delay <$Edelta> of the local clock relative to the peer clock,
  5861. as well as various error accumulations as described below. The following
  5862. discussion establishes how errors inherent in the time-transfer process
  5863. accumulate within the subnet and contribute to the overall error budget
  5864. at each server.
  5865.  
  5866. An NTP measurement update includes three parts: clock offset <$Etheta>,
  5867. roundtrip delay <$Edelta> and maximum error or dispersion <$Eepsilon> of
  5868. the local clock relative to a peer clock. In case of a primary clock
  5869. update, these values are usually all zero, although <$Eepsilon> can be
  5870. tailored to reflect the specified maximum error of the primary reference
  5871. source itself. In other cases <$Etheta> and <$Edelta> are calculated
  5872. directly from the four most recent timestamps, as described in the NTP
  5873. specification. The dispersion <$Eepsilon> includes the following
  5874. contributions:
  5875.  
  5876. 1.
  5877.  
  5878. Each time the local clock is read a reading error is incurred due to the
  5879. finite granularity or precision of the implementation. This is called
  5880. the measurement dispersion <$Erho>.
  5881.  
  5882. 2.
  5883.  
  5884. Once an offset is determined, an error due to frequency offset or skew
  5885. accumulates with time. This is called the skew dispersion <$Ephi tau>,
  5886. where <$Ephi> represents the skew-rate constant (<$Eroman NTP.MAXSKEW
  5887. over NTP.MAXAGE> in the NTP specification) and <$Etau> is the interval
  5888. since the dispersion was last updated.
  5889.  
  5890. 3
  5891.  
  5892. When a series of offsets are determined at regular intervals and
  5893. accumulated in a window of samples, as in the NTP clock-filter
  5894. algorithm, the (estimated) additional error due to offset sample
  5895. variance is called the filter dispersion <$Eepsilon sub sigma>.
  5896.  
  5897. 4.
  5898.  
  5899. When a number of peers are considered for synchronization and two or
  5900. more are determined to be correctly synchronized to a primary reference
  5901. source, as in the NTP clock-selection algorithm, the (estimated)
  5902. additional error due to offset sample variance is called the selection
  5903. dispersion <$Eepsilon sub xi>.
  5904.  
  5905. Figure 15<$&fig15> shows how these errors accumulate in the ordinary
  5906. course of NTP processing. Received messages from a single peer are
  5907. represented by the packet variables. From the four most recent
  5908. timestamps T1, T2, T3 and T4 the clock offset and roundtrip delay sample
  5909. for the local clock relative to the peer clock are calculated directly.
  5910. Included in the message are the root roundtrip delay <$EDELTA prime> and
  5911. root dispersion <$EEPSILON prime> of the peer itself; however, before
  5912. sending, the peer adds the measurement dispersion <$Erho> and skew
  5913. dispersion <$Ephi tau>, where these quantities are determined by the
  5914. peer and <$Etau> is the interval according to the peer clock since its
  5915. clock was last updated.
  5916.  
  5917. The NTP clock-filter procedure saves the most recent samples <$Etheta
  5918. sub i> and <$Edelta sub i> in the clock filter as described in the NTP
  5919. specification. The quantities <$Erho> and <$Ephi> characterize the local
  5920. clock maximum reading error and frequency error, respectively. Each
  5921. sample includes the dispersion <$Eepsilon sub i~=~rho~+~phi (T sub 4~-~T
  5922. sub 1 )>, which is set upon arrival. Each time a new sample arrives all
  5923. samples in the filter are updated with the skew dispersion <$Ephi tau
  5924. sub i>, where <$Etau sub i> is the interval since the last sample
  5925. arrived, as recorded in the variable peer.update. The clock-filter
  5926. algorithm determines the selected clock offset <$Etheta> (peer.offset),
  5927. together with the associated roundtrip delay <$Edelta> (peer.delay) and
  5928. filter dispersion <$Eepsilon sub sigma>, which is added to the
  5929. associated sample dispersion <$Eepsilon sub i> to form the peer
  5930. dispersion <$Eepsilon> (peer.dispersion).
  5931.  
  5932. The NTP clock-selection procedure selects a single peer to become the
  5933. synchronization source as described in the NTP specification. The
  5934. operation of the algorithm determines the final clock offset <$ETHETA>
  5935. (local clock), roundtrip delay <$EDELTA> (sys.rootdelay) and dispersion
  5936. <$EEPSILON> (sys.rootdispersion) relative to the root of the
  5937. synchronization subnet, as shown in Figure 15. Note the inclusion of the
  5938. selected peer dispersion and skew accumulation since the dispersion was
  5939. last updated, as well as the select dispersion <$Eepsilon sub xi>
  5940. computed by the clock-select algorithm itself. Also, note that, in order
  5941. to preserve overall synchronization subnet stability, the final clock
  5942. offset <$ETHETA> is in fact determined from the offset of the local
  5943. clock relative to the peer clock, rather than the root of the subnet.
  5944. Finally, note that the packet variables <$EDELTA prime> and <$EEPSILON
  5945. prime> are in fact determined from the latest message received, not at
  5946. the precise time the offset selected by the clock-filter algorithm was
  5947. determined. Minor errors arising due to these simplifications will be
  5948. ignored. Thus, the total dispersion accumulation relative to the root of
  5949. the synchronization subnet is
  5950.  
  5951. <$EEPSILON~=~epsilon~+~phi tau~+~epsilon sub xi~+~| THETA |~+~EPSILON
  5952. prime > ,
  5953.  
  5954. where <$Etau> is the time since the peer variables were last updated and
  5955. <$E| THETA |> is the initial absolute error in setting the local clock.
  5956.  
  5957. The three values of clock offset, roundtrip delay and dispersion are all
  5958. additive; that is, if <$ETHETA sub i>, <$EDELTA sub i> and <$EEPSILON
  5959. sub i> represent the values at peer i relative to the root of the
  5960. synchronization subnet, the values
  5961.  
  5962. <$ETHETA sub j (t)~==~THETA sub i~+~theta sub j (t)> ,   <$EDELTA sub j
  5963. (t)~==~DELTA sub i~+~delta sub j> ,   <$EEPSILON sub j (t)~==~EPSILON
  5964. sub i~+~epsilon sub i~+~epsilon sub j (t)> ,
  5965. represent the clock offset, roundtrip delay and dispersion of peer j at
  5966. time t. The time dependence of <$Etheta sub j (t)> and <$Eepsilon sub j
  5967. (t)> represents the local-clock correction and dispersion accumulated
  5968. since the last update was received from peer i, while the term
  5969. <$Eepsilon sub i> represents the dispersion accumulated by peer i from
  5970. the time its clock was last set until the latest update was sent to peer
  5971. j. Note that, while the offset of the local clock relative to the peer
  5972. clock can be determined directly, the offset relative to the root of the
  5973. synchronization subnet is not directly determinable, except on a
  5974. probabilistic basis and within the bounds established in this and the
  5975. previous section.
  5976.  
  5977. The NTP synchronization subnet topology is that of a tree rooted at the
  5978. primary server(s). Thus, there is an unbroken path from every time
  5979. server to the primary reference source. Accuracy and stability are
  5980. proportional to synchronization distance <$ELAMBDA>, defined as
  5981.  
  5982. <$ELAMBDA~==~EPSILON~+~DELTA over 2> .
  5983.  
  5984. The selection algorithm favors the minimum-distance paths and thus
  5985. maximizes accuracy and stability. Since <$ETHETA sub 0>, <$EDELTA sub 0>
  5986. and <$EEPSILON sub 0> are all zero, the sum of the clock offsets,
  5987. roundtrip delays and dispersions of each server along the minimum-
  5988. distance path from the root of the synchronization subnet to a given
  5989. server i are the clock offset <$ETHETA sub i>, roundtrip delay <$EDELTA
  5990. sub i> and dispersion <$EEPSILON sub i> inherited by and characteristic
  5991. of that server.
  5992.  
  5993. Correctness Principles
  5994.  
  5995. In order to minimize the occurrence of errors due to incorrect clocks
  5996. and maximize the reliability of the service, NTP relies on multiple
  5997. peers and disjoint peer paths whenever possible. In the previous
  5998. development it was shown that, if the primary reference source at the
  5999. root of the synchronization subnet is in fact a correct clock, then the
  6000. true offset <$Etheta sub 0> relative to that clock must be contained in
  6001. the interval
  6002.  
  6003. <$E[ THETA~-~LAMBDA ,~THETA~+~LAMBDA ]~==~[ THETA~-~EPSILON~-~DELTA over
  6004. 2 ,~THETA~+~EPSILON~+~DELTA over 2 ]> .
  6005.  
  6006. When a number of clocks are involved, it is not clear beforehand which
  6007. are correct and which are not; however, as cited previously, there are a
  6008. number of techniques based on clustering and filtering principles which
  6009. yield a high probability of detecting and discarding incorrect clocks.
  6010. Marzullo and Owicki [MAR85] devised an algorithm designed to find an
  6011. appropriate interval containing the correct time given the confidence
  6012. intervals of m clocks, of which no more than f are considered incorrect.
  6013. The algorithm finds the smallest single intersection containing all
  6014. points in at least <$Em~-~f> of the given confidence intervals.
  6015.  
  6016. Figure 16<$&fig16> illustrates the operation of this algorithm with a
  6017. scenario involving four clocks A, B, C and D, with the calculated time
  6018. (shown by the <F128>∞<F255> symbol) and confidence interval shown for
  6019. each. These intervals are computed as described in previous sections of
  6020. this appendix. For instance, any point in the A interval may possibly
  6021. represent the actual time associated with that clock. If all clocks are
  6022. correct, there must exist a nonempty intersection including all four
  6023. intervals; but, clearly this is not the case in this scenario. However,
  6024. if it is assumed that one of the clocks is incorrect (e.g., D), it might
  6025. be possible to find a nonempty intersection including all but one of the
  6026. intervals. If not, it might be possible to find a nonempty intersection
  6027. including all but two of the intervals and so on.
  6028.  
  6029. The algorithm proposed by DEC for use in the Digital Time Service
  6030. [DEC89] is based on these principles. For the scenario illustrated in
  6031. Figure 16, it computes the interval for <$Em~=~4> clocks, three of which
  6032. turn out to be correct and one not. The low endpoint of the intersection
  6033. is found as follows. A variable f is initialized with the number of
  6034. presumed incorrect clocks, in this case zero, and a counter i is
  6035. initialized at zero. Starting from the lowest endpoint, the algorithm
  6036. increments i at each low endpoint, decrements i at each high endpoint,
  6037. and stops when <$Ei~>>=~m~-~f>. The counter records the number of
  6038. intersections and thus the number of presumed correct clocks. In the
  6039. example the counter never reaches four, so f is increased by one and the
  6040. procedure is repeated. This time the counter reaches three and stops at
  6041. the low endpoint of the intersection marked DTS. The upper endpoint of
  6042. this intersection is found using a similar procedure.
  6043.  
  6044. This algorithm will always find the smallest single intersection
  6045. containing points in at least one of the original <$Em~-~f> confidence
  6046. intervals as long as the number of incorrect clocks is less than half
  6047. the total <$Ef~<<~m over 2>. However, some points in the intersection
  6048. may not be contained in all <$Em~-~f> of the original intervals;
  6049. moreover, some or all of the calculated times (such as for C in Figure
  6050. 16) may lie outside the intersection. In the NTP clock-selection
  6051. procedure the above algorithm is modified so as to include at least
  6052. <$Em~-~f> of the calculated times. In the modified algorithm a counter c
  6053. is initialized at zero. When starting from either endpoint, c is
  6054. incremented at each calculated time; however, neither f nor c are reset
  6055. between finding the low and high endpoints of the intersection. If after
  6056. both endpoints have been found <$Ec~>>~f>, f is increased by one and the
  6057. entire procedure is repeated. The revised algorithm finds the smallest
  6058. intersection of <$Em~-~f> intervals containing at least <$Em~-~f>
  6059. calculated times. As shown in Figure 16, the modified algorithm produces
  6060. the intersection marked NTP and including the calculated time for C.
  6061.  
  6062. In the NTP clock-selection procedure the peers represented by the clocks
  6063. in the final intersection, called the survivors, are placed on a
  6064. candidate list. In the remaining steps of the procedure one or more
  6065. survivors may be discarded from the list as outlyers. Finally, the
  6066. clock-combining algorithm described in Appendix F provides a weighted
  6067. average of the remaining survivors based on synchronization distance.
  6068. The resulting estimates represent a synthetic peer with offset between
  6069. the maximum and minimum offsets of the remaining survivors. This defines
  6070. the clock offset <$ETHETA>, total roundtrip total delay <$EDELTA> and
  6071. total dispersion <$EEPSILON> which the local clock inherits. In
  6072. principle, these values could be included in the time interface provided
  6073. by the operating system to the user, so that the user could evaluate the
  6074. quality of indications directly.
  6075.  
  6076. Appendix I. Selected C-Language Program Listings
  6077.  
  6078. Following are C-language program listings of selected algorithms
  6079. described in the NTP specification. While these have been tested as part
  6080. of a software simulator using data collected in regular operation, they
  6081. do not necessarily represent a standard implementation, since many other
  6082. implementations could in principle conform to the NTP specification.
  6083.  
  6084. Common Definitions and Variables
  6085.  
  6086. The following definitions are common to all procedures and peers.
  6087.  
  6088. #define NMAX 40                                 /* max clocks */
  6089. #define FMAX 8                                  /* max filter size */
  6090. #define HZ 1000                                 /* clock rate */
  6091. #define MAXSTRAT 15                             /* max stratum */
  6092. #define MAXSKEW 1                               /* max skew error per
  6093. MAXAGE */
  6094. #define MAXAGE 86400                            /* max clock age */
  6095. #define MAXDISP 16                              /* max dispersion */
  6096. #define MINCLOCK 3                              /* min survivor clocks
  6097. */
  6098. #define MAXCLOCK 10                             /* min candidate clocks
  6099. */
  6100. #define FILTER .5                                       /* filter weight
  6101. */
  6102. #define SELECT .75                              /* select weight */
  6103.  
  6104. The folowing are peer state variables (one set for each peer).
  6105.  
  6106. double filtp[NMAX][FMAX];                               /* offset
  6107. samples */
  6108. double fildp[NMAX][FMAX];                       /* delay samples */
  6109. double filep[NMAX][FMAX];                       /* dispersion samples */
  6110. double tp[NMAX];                                        /* offset */
  6111. double dp[NMAX];                                        /* delay */
  6112. double ep[NMAX];                                        /* dispersion */
  6113. double rp[NMAX];                                        /* last offset
  6114. */
  6115. double utc[NMAX];                                       /* update tstamp
  6116. */
  6117. int st[NMAX];                                           /* stratum */
  6118.  
  6119. The following are system state variables and constants.
  6120.  
  6121. double rho = 1./HZ;                                     /* max reading
  6122. error */
  6123. double phi = MAXSKEW/MAXAGE;            /* max skew rate */
  6124. double bot, top;                                        /* confidence
  6125. interval limits */
  6126. double theta;                                           /* clock offset
  6127. */
  6128. double delta;                                           /* roundtrip
  6129. delay */
  6130. double epsil;                                           /* dispersion */
  6131. double tstamp;                                  /* current time */
  6132. int source;                                             /* clock source
  6133. */
  6134. int n1, n2;                                             /* min/max clock
  6135. ids */
  6136.  
  6137. The folowing are temporary lists shared by all peers and procedures.
  6138.  
  6139. double list[3*NMAX];                            /* temporary list*/
  6140. int index[3*NMAX];                                      /* index list */
  6141.  
  6142. Clock<196>Filter Algorithm
  6143.  
  6144. /*
  6145.    clock filter algorithm
  6146.  
  6147.    n = peer id, offset = sample offset, delay = sample delay, disp =
  6148. sample dispersion;
  6149.    computes tp[n] = peer offset, dp[n] = peer delay, ep[n] = peer
  6150. dispersion
  6151.  */
  6152.  
  6153. void filter(int n, double offset, double delay, double disp) {
  6154.  
  6155.         int i, j, k, m;                                 /* int temps */
  6156.         double x;                                       /* double temps
  6157. */
  6158.  
  6159.         for (i = FMAX<196>1; i >> 0; i<196> <196>) {            /*
  6160. update/shift filter */
  6161.                 filtp[n][i] = filtp[n][i<196>1]; fildp[n][i] =
  6162. fildp[n][i<196>1];
  6163.                 filep[n][i] = filep[n][i<196>1]+phi*(tstamp<196>utc[n]);
  6164.                 }
  6165.         utc[n] = tstamp; filtp[n][0] = offset<196>tp[0]; fildp[n][0] =
  6166. delay; filep[n][0] = disp;
  6167.         m = 0;                                          /*
  6168. construct/sort temp list */
  6169.         for (i = 0; i << FMAX; i++) {
  6170.                 if (filep[n][i] >>= MAXDISP) continue;
  6171.                 list[m] = filep[n][i]+fildp[n][i]/2.; index[m] = i;
  6172.                 for (j = 0; j << m; j++) {
  6173.                         if (list[j] >> list[m]) {
  6174.                                 x = list[j]; k = index[j]; list[j] =
  6175. list[m]; index[j] = index[m];
  6176.                                 list[m] = x; index[m] = k;
  6177.                                 }
  6178.                         }
  6179.                 m = m+1;
  6180.                 }
  6181.  
  6182.         if (m <<= 0) ep[n] = MAXDISP;           /* compute filter
  6183. dispersion */           
  6184.         else {
  6185.                 ep[n] = 0;
  6186.                 for (i = FMAX<196>1; i >>= 0; i<196> <196>) {
  6187.                         if (i << m) x =
  6188. fabs(filtp[n][index[0]]<196>filtp[n][index[i]]);
  6189.                         else x = MAXDISP;
  6190.                         ep[n] = FILTER*(ep[n]+x);
  6191.                         }
  6192.                 i = index[0]; ep[n] = ep[n]+filep[n][i]; tp[n] =
  6193. filtp[n][i]; dp[n] = fildp[n][i];
  6194.                 }
  6195.         return;
  6196.         }
  6197.  
  6198. Interval Intersection Algorithm
  6199.  
  6200. /*
  6201.    compute interval intersection
  6202.  
  6203.    computes bot = lowpoint, top = highpoint (bot >> top if no
  6204. intersection)
  6205. */
  6206.  
  6207. void dts() {
  6208.  
  6209.         int f;                                          /* intersection
  6210. ceiling */
  6211.         int end;                                        /* endpoint
  6212. counter */
  6213.         int clk;                                                /*
  6214. falseticker counter */
  6215.         int i, j, k, m, n;                              /* int temps */
  6216.         double x, y;                                    /* double temps
  6217. */
  6218.  
  6219.         m = 0; i = 0;
  6220.         for (n = n1; n <<= n2; n++) {   /* construct endpoint list */
  6221.                 if (ep[n] >>= MAXDISP) continue;
  6222.                 m = m+1;
  6223.                 list[i] = tp[n]<196>dist(n); index[i] = <196>1; /*
  6224. lowpoint */
  6225.                 for (j = 0; j << i; j++) {
  6226.                         if ((list[j] >> list[i]) || ((list[j] ==
  6227. list[i]) && (index[j] >> index[i]))) {
  6228.                                 x = list[j]; k = index[j]; list[j] =
  6229. list[i]; index[j] = index[i];
  6230.                                 list[i] = x; index[i] = k;
  6231.                                 }
  6232.                         }
  6233.                 i = i+1;
  6234.  
  6235.                 list[i] = tp[n]; index[i] = 0;          /* midpoint */
  6236.                 for (j = 0; j << i; j++) {
  6237.                         if ((list[j] >> list[i]) || ((list[j] ==
  6238. list[i]) && (index[j] >> index[i]))) {
  6239.                                 x = list[j]; k = index[j]; list[j] =
  6240. list[i]; index[j] = index[i];
  6241.                                 list[i] = x; index[i] = k;
  6242.                                 }
  6243.                         }
  6244.                 i = i+1;
  6245.  
  6246.                 list[i] = tp[n]+dist(n); index[i] = 1;  /* highpoint */
  6247.                 for (j = 0; j << i; j++) {
  6248.                         if ((list[j] >> list[i]) || ((list[j] ==
  6249. list[i]) && (index[j] >> index[i]))) {
  6250.                                 x = list[j]; k = index[j]; list[j] =
  6251. list[i]; index[j] = index[i];
  6252.                                 list[i] = x; index[i] = k;
  6253.                                 }
  6254.                         }
  6255.                 i = i+1;
  6256.                 }
  6257.  
  6258.         if (m <<= 0) return;
  6259.         for (f = 0; f << m/2; f++) {                    /* find
  6260. intersection */
  6261.                 clk = 0; end = 0;                       /* lowpoint */
  6262.                 for (j = 0; j << i; j++) {
  6263.                         end = end<196>index[j]; bot = list[j];
  6264.                         if (end >>= (m<196>f)) break;
  6265.                         if (index[j] == 0) clk = clk+1;
  6266.                         }
  6267.                 end = 0;                                /* highpoint */
  6268.                 for (j = i<196>1; j >>= 0; j<196> <196>) {
  6269.                         end = end+index[j]; top = list[j];
  6270.                         if (end >>= (m<196>f)) break;
  6271.                         if (index[j] == 0) clk = clk+1;
  6272.                         }
  6273.                 if (clk <<= f) break;
  6274.                 }
  6275.         return;
  6276.         }
  6277.  
  6278. Clock<196>Selection Algorithm
  6279.  
  6280. /*
  6281.    select best subset of clocks in candidate list
  6282.  
  6283.    bot = lowpoint, top = highpoint; constructs index = candidate index
  6284. list,
  6285.    m = number of candidates, source = clock source,
  6286.    theta = clock offset, delta = roundtrip delay, epsil = dispersion
  6287. */
  6288.  
  6289. void select() {
  6290.  
  6291.         double xi;                                      /* max select
  6292. dispersion */
  6293.         double eps;                                     /* min peer
  6294. dispersion */
  6295.         int i, j, k, n;                                 /* int temps */
  6296.         double x, y, z;                         /* double temps */
  6297.  
  6298.         m = 0;
  6299.         for (n = n1; n <<= n2; n++) {   /* make/sort candidate list */
  6300.                 if ((st[n] >> 0) && (st[n] << MAXSTRAT) && (tp[n] >>=
  6301. bot) && (tp[n] <<= top)) {
  6302.                         list[m] = MAXDISP*st[n]+dist(n); index[m] = n;
  6303.                         for (j = 0; j << m; j++) {
  6304.                                 if (list[j] >> list[m]) {
  6305.                                         x = list[j]; k = index[j];
  6306. list[j] = list[m]; index[j] = index[m];
  6307.                                         list[m] = x; index[m] = k;
  6308.                                         }
  6309.                                 }
  6310.                         m = m+1;
  6311.                         }
  6312.                 }
  6313.         if (m <<= 0) {
  6314.                 source = 0; return;
  6315.                 }
  6316.         if (m >> MAXCLOCK) m = MAXCLOCK;
  6317.  
  6318.         while (1) {                                     /* cast out
  6319. falsetickers */
  6320.                 xi = 0.; eps = MAXDISP;
  6321.                 for (j = 0; j << m; j++) {
  6322.                         x = 0.;
  6323.                         for (k = m<196>1; k >>= 0; k<196> <196>)
  6324.                                 x =
  6325. SELECT*(x+fabs(tp[index[j]]<196>tp[index[k]]));
  6326.                         if (x >> xi) {
  6327.                                 xi = x; i = j;          /* max(xi) */
  6328.                                 }
  6329.                         x = ep[index[j]]+phi*(tstamp<196>utc[index[j]]);
  6330.                         if (x << eps) eps = x;          /* min(eps) */
  6331.                         }
  6332.                 if ((xi <<= eps) || (m <<= MINCLOCK)) break;
  6333.                 if (index[i] == source) source = 0;
  6334.                 for (j = i; j << m<196>1; j++) index[j] = index[j+1];
  6335.                 m = m<196>1;
  6336.                 }
  6337.  
  6338.         i = index[0];                                   /* declare
  6339. winner */
  6340.         if (source != i)
  6341.                 if (source == 0) source = i;
  6342.                 else if (st[i] << st[source]) source = i;
  6343.         theta = combine(); delta = dp[i]; epsil =
  6344. ep[i]+phi*(tstamp<196>utc[i])+xi;
  6345.         return;
  6346.         }
  6347.  
  6348. Clock<196>Combining Procedure
  6349.  
  6350. /*
  6351.    compute weighted ensemble average
  6352.  
  6353.    index = candidate index list, m = number of candidates; returns
  6354. combined clock offset
  6355. */
  6356.  
  6357. double combine() {
  6358.  
  6359.         int i;                                          /* int temps */
  6360.         double x, y, z;                         /* double temps */
  6361.         z = 0. ; y = 0.;
  6362.         for (i = 0; i << m; i++) {                      /* compute
  6363. weighted offset */
  6364.                 j = index[i]; x = dist(j)); z = z+tp[j]/x; y = y+1./x;
  6365.                 }
  6366.         return z/y;                                     /* normalize */
  6367.         }
  6368.  
  6369. Subroutine to Compute Synchronization Distance
  6370.  
  6371. /*
  6372.    compute synchronization distance
  6373.  
  6374.    n = peer id; returns synchronization distance
  6375.  */
  6376.  
  6377. double dist(int n) {
  6378.  
  6379.         return ep[n]+phi*(tstamp<196>utc[n])+fabs(dp[n])/2.;
  6380.         }
  6381.  
  6382. Security considerations
  6383. see Section 3.6 and Appendix C
  6384.  
  6385. Author's address
  6386. David L. Mills
  6387. Electrical Engineering Department
  6388. University of Delaware
  6389. Newark, DE 19716
  6390. Phone (302) 451<196>8247
  6391. EMail mills@udel.edu
  6392.