1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
// Copyright 2020 The Fuchsia Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

use fuchsia_zircon as zx;

/// One million for PPM calculations
const MILLION: u64 = 1_000_000;

/// A transformation from monotonic time to synthetic time, including an error bound on this
/// synthetic time.
#[derive(Clone, Default, Debug, Eq, PartialEq)]
pub struct Transform<Output> {
    /// An offset on the monotonic timeline in nanoseconds.
    pub monotonic_offset: zx::MonotonicTime,
    /// An offset on the synthetic timeline in nanoseconds.
    pub synthetic_offset: zx::Time<Output>,
    /// An adjustment to the standard 1 monotonic tick:1 synthetic tick rate in parts per million.
    /// Positive values indicate the synthetic clock is moving faster than the monotonic clock.
    pub rate_adjust_ppm: i32,
    /// The error bound on synthetic clock at monotonic = monotonic_offset.
    pub error_bound_at_offset: u64,
    /// The growth in error bound per monotonic tick in parts per million.
    pub error_bound_growth_ppm: u32,
}

impl<Output: zx::Timeline + Copy> Transform<Output> {
    /// Returns the synthetic time at the supplied monotonic time.
    pub fn synthetic(&self, monotonic: zx::MonotonicTime) -> zx::Time<Output> {
        // Cast to i128 to avoid overflows in multiplication.
        let monotonic_difference = (monotonic - self.monotonic_offset).into_nanos() as i128;
        let synthetic_offset = self.synthetic_offset.into_nanos() as i128;
        let synthetic_ticks = self.rate_adjust_ppm as i128 + MILLION as i128;
        let reference_ticks = MILLION as i128;

        let time_nanos =
            (monotonic_difference * synthetic_ticks / reference_ticks) + synthetic_offset;
        zx::Time::from_nanos(time_nanos as i64)
    }

    /// Returns the error bound at the supplied monotonic time.
    pub fn error_bound(&self, monotonic: zx::MonotonicTime) -> u64 {
        // Cast to i128 to avoid overflows in multiplication.
        let monotonic_difference = (monotonic - self.monotonic_offset).into_nanos() as i128;
        if monotonic_difference <= 0 {
            // Assume the error bound was fixed at the supplied value before the reference time.
            self.error_bound_at_offset
        } else {
            // Error bound increases linearly after the reference time.
            let error_increase =
                (monotonic_difference * self.error_bound_growth_ppm as i128) / MILLION as i128;
            self.error_bound_at_offset + error_increase as u64
        }
    }

    /// Returns the synthetic time on this `Transform` minus the synthetic time on `other`,
    /// calculated at the supplied monotonic time.
    pub fn difference(&self, other: &Self, monotonic: zx::MonotonicTime) -> zx::Duration {
        self.synthetic(monotonic) - other.synthetic(monotonic)
    }

    /// Returns a `ClockUpdate` that will set a `Clock` onto this `Transform` using data
    /// from the supplied monotonic time.
    pub fn jump_to(&self, monotonic: zx::MonotonicTime) -> zx::ClockUpdate<Output> {
        zx::ClockUpdate::<Output>::builder()
            .absolute_value(monotonic, self.synthetic(monotonic))
            .rate_adjust(self.rate_adjust_ppm)
            .error_bounds(self.error_bound(monotonic))
            .build()
    }
}

impl<Output: zx::Timeline> From<&zx::Clock<Output>> for Transform<Output> {
    fn from(clock: &zx::Clock<Output>) -> Self {
        // Clock read failures should only be caused by an invalid clock object.
        let details = clock.get_details().expect("failed to get clock details");
        // Cast to i64 to avoid overflows in multiplication.
        let reference_ticks = details.mono_to_synthetic.rate.reference_ticks as i64;
        let synthetic_ticks = details.mono_to_synthetic.rate.synthetic_ticks as i64;
        let rate_adjust_ppm =
            ((synthetic_ticks * MILLION as i64) / reference_ticks) - MILLION as i64;

        Transform {
            monotonic_offset: details.mono_to_synthetic.reference_offset,
            synthetic_offset: details.mono_to_synthetic.synthetic_offset,
            rate_adjust_ppm: rate_adjust_ppm as i32,
            // Zircon clocks don't document the change in error over time. Assume a fixed error.
            error_bound_at_offset: details.error_bounds,
            error_bound_growth_ppm: 0,
        }
    }
}

/// Returns the time on the clock at a given monotonic reference time. This calculates the time
/// based on the clock transform definition, which only contains the most recent segment. This
/// is only useful for calculating the time for monotonic times close to the current time.
pub fn time_at_monotonic<T: zx::Timeline>(
    clock: &zx::Clock<T>,
    monotonic: zx::MonotonicTime,
) -> zx::Time<T> {
    let monotonic_reference = monotonic.into_nanos() as i128;
    // Clock read failures should only be caused by an invalid clock object.
    let details = clock.get_details().expect("failed to get clock details");
    // Calculate using the transform definition underlying a zircon clock.
    // Cast to i128 to avoid overflows in multiplication.
    let reference_offset = details.mono_to_synthetic.reference_offset.into_nanos() as i128;
    let synthetic_offset = details.mono_to_synthetic.synthetic_offset.into_nanos() as i128;
    let reference_ticks = details.mono_to_synthetic.rate.reference_ticks as i128;
    let synthetic_ticks = details.mono_to_synthetic.rate.synthetic_ticks as i128;

    let time_nanos = ((monotonic_reference - reference_offset) * synthetic_ticks / reference_ticks)
        + synthetic_offset;
    zx::Time::from_nanos(time_nanos as i64)
}

#[cfg(test)]
mod test {
    use super::*;
    use test_util::{assert_geq, assert_leq};
    use zx::DurationNum;

    const BACKSTOP: zx::SyntheticTime = zx::SyntheticTime::from_nanos(1234567890);
    const TIME_DIFF: zx::Duration = zx::Duration::from_seconds(5);
    const SLEW_RATE_PPM: i32 = 750;
    const ONE_MILLION: i32 = 1_000_000;

    const TEST_REFERENCE: zx::MonotonicTime = zx::MonotonicTime::from_nanos(70_000_000_000);
    const TEST_OFFSET: zx::Duration = zx::Duration::from_nanos(5_000_000_000);
    const TEST_ERROR_BOUND: u64 = 1234_000;
    const TEST_ERROR_BOUND_GROWTH: u32 = 100;

    const TOLERANCE: zx::Duration = zx::Duration::from_nanos(500_000_000);

    #[fuchsia::test]
    fn transform_properties_zero_rate_adjust() {
        let transform = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(
                (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
            ),
            rate_adjust_ppm: 0,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: TEST_ERROR_BOUND_GROWTH,
        };

        assert_eq!(
            transform.synthetic(TEST_REFERENCE).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET).into_nanos()
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE + 200.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET + 200.millis()).into_nanos(),
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE - 100.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET - 100.millis()).into_nanos(),
        );

        assert_eq!(transform.error_bound(TEST_REFERENCE), TEST_ERROR_BOUND);
        assert_eq!(
            transform.error_bound(TEST_REFERENCE + 1.milli()),
            TEST_ERROR_BOUND + TEST_ERROR_BOUND_GROWTH as u64
        );
        assert_eq!(transform.error_bound(TEST_REFERENCE - 1.milli()), TEST_ERROR_BOUND as u64);
    }

    #[fuchsia::test]
    fn transform_properties_positive_rate_adjust() {
        let transform = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(
                (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
            ),
            rate_adjust_ppm: 25,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: 0,
        };

        assert_eq!(
            transform.synthetic(TEST_REFERENCE).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE + 200.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET + 200.millis() + (25 * 200).nanos()).into_nanos(),
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE - 100.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET - 100.millis() - (25 * 100).nanos()).into_nanos(),
        );

        assert_eq!(transform.error_bound(TEST_REFERENCE), TEST_ERROR_BOUND);
        assert_eq!(transform.error_bound(TEST_REFERENCE + 1.milli()), TEST_ERROR_BOUND as u64);
        assert_eq!(transform.error_bound(TEST_REFERENCE - 1.milli()), TEST_ERROR_BOUND as u64);
    }

    #[fuchsia::test]
    fn transform_properties_negative_rate_adjust() {
        let transform = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(
                (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
            ),
            rate_adjust_ppm: -50,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: TEST_ERROR_BOUND_GROWTH,
        };

        assert_eq!(
            transform.synthetic(TEST_REFERENCE).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE + 200.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET + 200.millis() - (50 * 200).nanos()).into_nanos(),
        );
        assert_eq!(
            transform.synthetic(TEST_REFERENCE - 100.millis()).into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET - 100.millis() + (50 * 100).nanos()).into_nanos(),
        );

        assert_eq!(transform.error_bound(TEST_REFERENCE), TEST_ERROR_BOUND);
        assert_eq!(
            transform.error_bound(TEST_REFERENCE + 1.second()),
            TEST_ERROR_BOUND + (TEST_ERROR_BOUND_GROWTH * 1000) as u64
        );
        assert_eq!(transform.error_bound(TEST_REFERENCE - 1.second()), TEST_ERROR_BOUND as u64);
    }

    #[fuchsia::test]
    fn transform_difference() {
        let transform_1 = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(
                (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
            ),
            rate_adjust_ppm: 25,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: TEST_ERROR_BOUND_GROWTH,
        };

        let transform_2 = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(TEST_REFERENCE.into_nanos()),
            rate_adjust_ppm: -50,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: 0,
        };

        assert_eq!(transform_1.difference(&transform_1, TEST_REFERENCE), 0.nanos());
        assert_eq!(transform_1.difference(&transform_2, TEST_REFERENCE), TEST_OFFSET);
        assert_eq!(
            transform_2.difference(&transform_1, TEST_REFERENCE),
            zx::Duration::from_nanos(-TEST_OFFSET.into_nanos())
        );
        assert_eq!(
            transform_1.difference(&transform_2, TEST_REFERENCE + 500.millis()),
            TEST_OFFSET + (75 * 500).nanos()
        );
        assert_eq!(
            transform_1.difference(&transform_2, TEST_REFERENCE - 300.millis()),
            TEST_OFFSET - (75 * 300).nanos()
        );
    }

    #[fuchsia::test]
    fn transform_conversion() {
        let transform = Transform {
            monotonic_offset: TEST_REFERENCE,
            synthetic_offset: zx::SyntheticTime::from_nanos(
                (TEST_REFERENCE + TEST_OFFSET).into_nanos(),
            ),
            rate_adjust_ppm: -15,
            error_bound_at_offset: TEST_ERROR_BOUND,
            error_bound_growth_ppm: 0,
        };

        let monotonic = zx::MonotonicTime::get();
        let clock_update = transform.jump_to(monotonic);
        assert_eq!(
            clock_update,
            zx::ClockUpdate::builder()
                .absolute_value(monotonic, transform.synthetic(monotonic))
                .rate_adjust(-15)
                .error_bounds(transform.error_bound(monotonic))
                .build()
        );

        let clock = zx::Clock::create(zx::ClockOpts::empty(), None).unwrap();
        clock.update(clock_update).unwrap();

        let double_converted = Transform::from(&clock);
        assert_eq!(double_converted.rate_adjust_ppm, transform.rate_adjust_ppm);
        assert_eq!(double_converted.error_bound_at_offset, transform.error_bound_at_offset);
        assert_eq!(double_converted.error_bound_growth_ppm, 0);
        assert_eq!(double_converted.rate_adjust_ppm, transform.rate_adjust_ppm);
        // Before RFC-0077 we accumulate some error in setting a clock, perform a coarse comparison.
        let synthetic_from_double_converted = double_converted.synthetic(TEST_REFERENCE);
        assert_geq!(
            synthetic_from_double_converted.into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET - TOLERANCE).into_nanos()
        );
        assert_leq!(
            synthetic_from_double_converted.into_nanos(),
            (TEST_REFERENCE + TEST_OFFSET + TOLERANCE).into_nanos()
        );
    }

    #[fuchsia::test]
    fn time_at_monotonic_clock_not_started() {
        let clock = zx::Clock::create(zx::ClockOpts::empty(), Some(BACKSTOP)).unwrap();
        assert_eq!(time_at_monotonic(&clock, zx::MonotonicTime::get() + TIME_DIFF), BACKSTOP);
    }

    #[fuchsia::test]
    fn time_at_monotonic_clock_started() {
        let clock = zx::Clock::create(zx::ClockOpts::empty(), Some(BACKSTOP)).unwrap();

        let mono = zx::MonotonicTime::get();
        clock.update(zx::ClockUpdate::builder().absolute_value(mono, BACKSTOP)).unwrap();

        let clock_time = time_at_monotonic(&clock, mono + TIME_DIFF);
        assert_eq!(clock_time, BACKSTOP + TIME_DIFF);
    }

    #[fuchsia::test]
    fn time_at_monotonic_clock_slew_fast() {
        let clock = zx::Clock::create(zx::ClockOpts::empty(), Some(BACKSTOP)).unwrap();

        let mono = zx::MonotonicTime::get();
        clock
            .update(
                zx::ClockUpdate::builder()
                    .absolute_value(mono, BACKSTOP)
                    .rate_adjust(SLEW_RATE_PPM),
            )
            .unwrap();

        let clock_time = time_at_monotonic(&clock, mono + TIME_DIFF);
        assert_eq!(clock_time, BACKSTOP + TIME_DIFF * (ONE_MILLION + SLEW_RATE_PPM) / ONE_MILLION);
    }

    #[fuchsia::test]
    fn time_at_monotonic_clock_slew_slow() {
        let clock = zx::Clock::create(zx::ClockOpts::empty(), Some(BACKSTOP)).unwrap();

        let mono = zx::MonotonicTime::get();
        clock
            .update(
                zx::ClockUpdate::builder()
                    .absolute_value(mono, BACKSTOP)
                    .rate_adjust(-SLEW_RATE_PPM),
            )
            .unwrap();

        let clock_time = time_at_monotonic(&clock, mono + TIME_DIFF);
        assert_eq!(clock_time, BACKSTOP + TIME_DIFF * (ONE_MILLION - SLEW_RATE_PPM) / ONE_MILLION);
    }
}