-
Notifications
You must be signed in to change notification settings - Fork 89
Expand file tree
/
Copy pathfbclock.c
More file actions
859 lines (772 loc) · 27.3 KB
/
Copy pathfbclock.c
File metadata and controls
859 lines (772 loc) · 27.3 KB
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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
/*
Copyright (c) Facebook, Inc. and its affiliates.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
#include "fbclock.h"
#include <fcntl.h> // For O_* constants
#include <linux/ptp_clock.h>
#include <stdint.h>
#include <stdio.h> // for printf and perror
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <time.h>
#include <unistd.h> // close
#ifdef __aarch64__
#include <arm_acle.h>
#endif
#if defined(__GNUC__) && !defined(__OPTIMIZE__)
#define fbclock_debug_print(fmt, ...) \
do { \
fprintf(stderr, fmt, __VA_ARGS__); \
} while (0)
#else
#define fbclock_debug_print(fmt, ...)
#endif
#define FBCLOCK_CLOCKDATA_SIZE sizeof(fbclock_clockdata)
#define FBCLOCK_CLOCKDATA_V2_SIZE sizeof(fbclock_clockdata_v2)
#define FBCLOCK_MAX_READ_TRIES 1000
#define NANOSECONDS_IN_SECONDS 1000000000ULL
// Smear window in seconds. v2 shared memory carries only the start, so the
// client rebuilds the end from this; keep it equal to leapDurationS in
// fbclock/daemon/daemon.go, which is what v1 publishes directly.
#define SMEAR_DURATION 62500
#ifdef __x86_64__
#define fbclock_crc64 __builtin_ia32_crc32di
#endif
#ifdef __aarch64__
#define fbclock_crc64 __crc32cd
#if defined(__GNUC__) && !defined(__clang__)
#pragma GCC target("+crc")
#endif
#endif
// dumb replacement for platforms we don't fully support
#ifndef fbclock_crc64
#define fbclock_crc64(a, b) ({ a ^ b; })
#endif
struct phc_time_res {
int64_t ts; // last ts got from PHC
int64_t delay; // mean delay of several requests
};
static inline uint64_t fbclock_clockdata_crc(fbclock_clockdata* value) {
uint64_t counter = fbclock_crc64(0xFFFFFFFF, value->ingress_time_ns);
counter = fbclock_crc64(counter, value->error_bound_ns);
counter = fbclock_crc64(counter, value->holdover_multiplier_ns);
return counter ^ 0xFFFFFFFF;
}
int ends_with(const char* str, const char* suffix) {
if (!str || !suffix) {
return 0;
}
size_t lenstr = strlen(str);
size_t lensuffix = strlen(suffix);
if (lensuffix > lenstr) {
return 0;
}
return strncmp(str + lenstr - lensuffix, suffix, lensuffix) == 0;
}
int fbclock_clockdata_store_data(uint32_t fd, fbclock_clockdata* data) {
fbclock_shmdata* shmp = mmap(
NULL, FBCLOCK_SHMDATA_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shmp == MAP_FAILED) {
return FBCLOCK_E_SHMEM_MAP_FAILED;
}
uint64_t crc = fbclock_clockdata_crc(data);
memcpy(&shmp->data, data, FBCLOCK_CLOCKDATA_SIZE);
atomic_store(&shmp->crc, crc);
munmap(shmp, FBCLOCK_SHMDATA_SIZE);
return FBCLOCK_E_NO_ERROR;
}
// fbclock_seq_write_begin marks the seqlock at seqp as "writing" (odd value)
// and returns the even value to publish once the write completes. A single
// writer is assumed; concurrent readers detect a torn read via the counter.
static uint64_t fbclock_seq_write_begin(atomic_uint64* _Nonnull seqp) {
uint64_t seq = 0;
for (int i = 0; i < FBCLOCK_MAX_READ_TRIES && (seq = atomic_load(seqp)) & 1;
i++) {
// LSB set means another writer is mid-write, but there should be only one
// writer so we just wait for it to finish (make seq even)
usleep(1);
}
seq = (seq & ~1) + 1;
atomic_store(seqp, seq);
return seq + 1;
}
// fbclock_seq_write_end publishes the post-write (even) seqlock value.
static void fbclock_seq_write_end(atomic_uint64* _Nonnull seqp, uint64_t seq) {
if (!seq) {
seq += 2; // avoid 0 value on wraparound
}
atomic_store(seqp, seq);
}
// fbclock_section_store writes one section's data under its seqlock. A single
// writer is assumed; concurrent readers detect a torn read via the counter.
// Each section has its own seqlock on its own cache line, so writing one never
// bumps the other's counter or disturbs the other reader's cache line.
static void fbclock_section_store(
fbclock_shmsection* _Nonnull section,
const fbclock_clockdata_v2* _Nonnull data) {
uint64_t seq = fbclock_seq_write_begin(§ion->seq);
__sync_synchronize();
section->data = *data;
__sync_synchronize();
fbclock_seq_write_end(§ion->seq, seq);
__sync_synchronize();
}
int fbclock_clockdata_store_data_v2(uint32_t fd, fbclock_clockdata_v2* data) {
if (data == NULL) {
return FBCLOCK_E_NO_DATA;
}
fbclock_shmdata_v2* shmp = mmap(
NULL, FBCLOCK_SHMDATA_V2_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shmp == MAP_FAILED || shmp == NULL) {
return FBCLOCK_E_SHMEM_MAP_FAILED;
}
fbclock_section_store(&shmp->primary, data);
munmap(shmp, FBCLOCK_SHMDATA_V2_SIZE);
return FBCLOCK_E_NO_ERROR;
}
// Writes the realtime section. The daemon calls this separately from (and
// after) the primary store so the primary anchor is published without waiting
// on the slower REALTIME PHC read. Only called on hosts whose primary is
// MONOTONIC_RAW.
int fbclock_clockdata_store_data_realtime(
uint32_t fd,
fbclock_clockdata_v2* data) {
if (data == NULL) {
return FBCLOCK_E_NO_DATA;
}
fbclock_shmdata_v2* shmp = mmap(
NULL, FBCLOCK_SHMDATA_V2_SIZE, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
if (shmp == MAP_FAILED || shmp == NULL) {
return FBCLOCK_E_SHMEM_MAP_FAILED;
}
fbclock_section_store(&shmp->realtime, data);
munmap(shmp, FBCLOCK_SHMDATA_V2_SIZE);
return FBCLOCK_E_NO_ERROR;
}
int fbclock_clockdata_load_data(
fbclock_shmdata* shmp,
fbclock_clockdata* data) {
for (int i = 0; i < FBCLOCK_MAX_READ_TRIES; i++) {
memcpy(data, &shmp->data, FBCLOCK_CLOCKDATA_SIZE);
uint64_t crc = atomic_load(&shmp->crc);
uint64_t our_crc = fbclock_clockdata_crc(data);
if (our_crc == crc) {
fbclock_debug_print("reading clock data took %d tries\n", i + 1);
return FBCLOCK_E_NO_ERROR;
}
}
fbclock_debug_print(
"failed to read clock data after %d tries\n", FBCLOCK_MAX_READ_TRIES);
// TODO: Enable mismatch error.
// return FBCLOCK_E_CRC_MISMATCH;
return FBCLOCK_E_NO_ERROR;
}
// Reads one anchor section under its seqlock, retrying on torn reads. Primary
// reads also retry uninitialized data for cold-start compatibility.
static int fbclock_section_load(
fbclock_shmsection* section,
fbclock_clockdata_v2* data,
int fail_fast_if_uninitialized) {
if (section == NULL || data == NULL) {
return FBCLOCK_E_NO_DATA;
}
for (int i = 0; i < FBCLOCK_MAX_READ_TRIES; i++) {
uint64_t seq = atomic_load(§ion->seq);
if (!seq) { // 0 value means uninitialized
if (fail_fast_if_uninitialized) {
return FBCLOCK_E_NO_DATA;
}
usleep(10);
__sync_synchronize();
continue;
}
if (seq & 1) {
__sync_synchronize();
continue;
}
__sync_synchronize();
*data = section->data;
__sync_synchronize();
if (seq == atomic_load(§ion->seq)) {
fbclock_debug_print("reading clock data took %d tries\n", i + 1);
return FBCLOCK_E_NO_ERROR;
}
}
fbclock_debug_print(
"failed to read clock data after %d tries\n", FBCLOCK_MAX_READ_TRIES);
return FBCLOCK_E_CRC_MISMATCH;
}
int fbclock_clockdata_load_data_v2(
fbclock_shmdata_v2* shmp,
fbclock_clockdata_v2* data) {
if (shmp == NULL) {
return FBCLOCK_E_NO_DATA;
}
return fbclock_section_load(&shmp->primary, data, 0);
}
int fbclock_clockdata_load_data_realtime(
fbclock_shmdata_v2* shmp,
fbclock_clockdata_v2* data) {
if (shmp == NULL) {
return FBCLOCK_E_NO_DATA;
}
return fbclock_section_load(&shmp->realtime, data, 1);
}
static inline int64_t fbclock_pct2ns(const struct ptp_clock_time* ptc) {
return (int64_t)(ptc->sec * NANOSECONDS_IN_SECONDS) + (int64_t)ptc->nsec;
}
static int fbclock_read_ptp_offset(int fd, struct phc_time_res* res) {
struct ptp_sys_offset pso = {.n_samples = 1};
int64_t min_delay = INT64_MAX, last_ts;
int r = ioctl(fd, PTP_SYS_OFFSET, &pso);
if (r) {
perror("PTP_SYS_OFFSET");
return -1;
}
for (unsigned i = 0; i < pso.n_samples; ++i) {
int64_t delay =
fbclock_pct2ns(&pso.ts[2 * i + 2]) - fbclock_pct2ns(&pso.ts[2 * i]);
min_delay = (delay < min_delay) ? delay : min_delay;
last_ts = fbclock_pct2ns(&pso.ts[2 * i + 1]);
}
res->ts = last_ts;
res->delay = min_delay;
if (min_delay < 0) {
perror("Negative request delay");
return -2;
}
return 0;
}
static int fbclock_read_ptp_offset_extended(int fd, struct phc_time_res* res) {
struct ptp_sys_offset_extended psoe = {.n_samples = 1};
int64_t min_delay = INT64_MAX;
int r = ioctl(fd, PTP_SYS_OFFSET_EXTENDED, &psoe);
if (r) {
perror("PTP_SYS_OFFSET_EXTENDED");
return -1;
}
for (unsigned i = 0; i < psoe.n_samples; ++i) {
int64_t delay =
fbclock_pct2ns(&psoe.ts[i][2]) - fbclock_pct2ns(&psoe.ts[i][0]);
min_delay = (delay < min_delay) ? delay : min_delay;
}
res->ts = fbclock_pct2ns(&psoe.ts[psoe.n_samples - 1][1]);
res->delay = min_delay;
if (min_delay < 0) {
perror("Negative request delay");
return -2;
}
return 0;
}
static void fbclock_close_fds(fbclock_lib* lib) {
if (lib == NULL) {
return;
}
if (lib->dev_fd >= 0) {
close(lib->dev_fd);
lib->dev_fd = -1;
}
if (lib->shm_fd >= 0) {
close(lib->shm_fd);
lib->shm_fd = -1;
}
}
int fbclock_init_with_options(
fbclock_lib* lib,
const char* shm_path,
const fbclock_options* options) {
lib->dev_fd = -1;
lib->shm_fd = -1;
lib->shmp = NULL;
lib->shmp_v2 = NULL;
lib->ptp_path = FBCLOCK_PTPPATH;
lib->max_wou_ns =
(options != NULL) ? options->max_wou_ns : FBCLOCK_MAX_WOU_NS_UNSET;
// No PTP device on this host -> fbclock unsupported here.
if (access(lib->ptp_path, F_OK) != 0) {
return FBCLOCK_E_NOTSUP;
}
int ffd = open(lib->ptp_path, O_RDONLY);
if (ffd == -1) {
perror("open PTP device");
return FBCLOCK_E_PTP_OPEN;
}
int sfd = open(shm_path, O_RDONLY, 0);
if (sfd == -1) {
perror("open shmem device");
close(ffd);
return FBCLOCK_E_SHMEM_OPEN;
}
lib->dev_fd = ffd;
lib->shm_fd = sfd;
lib->min_phc_delay = INT64_MAX;
struct ptp_sys_offset_extended psoe = {.n_samples = 1};
int r = ioctl(ffd, PTP_SYS_OFFSET_EXTENDED, &psoe);
if (!r) {
lib->gettime = fbclock_read_ptp_offset_extended;
} else {
lib->gettime = fbclock_read_ptp_offset;
}
if (ends_with(shm_path, "_v2")) {
fbclock_debug_print("Using v2 shared memory with path %s\n", shm_path);
fbclock_shmdata_v2* shmp = mmap(
NULL, FBCLOCK_SHMDATA_V2_SIZE, PROT_READ, MAP_SHARED, lib->shm_fd, 0);
if (shmp == MAP_FAILED) {
fbclock_close_fds(lib);
return FBCLOCK_E_SHMEM_MAP_FAILED;
}
lib->shmp_v2 = shmp;
lib->shmp = NULL;
} else {
fbclock_shmdata* shmp =
mmap(NULL, FBCLOCK_SHMDATA_SIZE, PROT_READ, MAP_SHARED, lib->shm_fd, 0);
if (shmp == MAP_FAILED) {
fbclock_close_fds(lib);
return FBCLOCK_E_SHMEM_MAP_FAILED;
}
lib->shmp = shmp;
lib->shmp_v2 = NULL;
}
return FBCLOCK_E_NO_ERROR;
}
int fbclock_init(fbclock_lib* lib, const char* shm_path) {
return fbclock_init_with_options(lib, shm_path, NULL);
}
int fbclock_is_ptp_host(void) {
return access(FBCLOCK_PTPPATH, F_OK) == 0 ? 1 : 0;
}
int fbclock_destroy(fbclock_lib* lib) {
munmap(lib->shmp, FBCLOCK_SHMDATA_SIZE);
munmap(lib->shmp_v2, FBCLOCK_SHMDATA_V2_SIZE);
fbclock_close_fds(lib);
return FBCLOCK_E_NO_ERROR;
// we don't want to unlink it, others might still use it
}
uint64_t fbclock_window_of_uncertainty(
double seconds,
uint64_t error_bound_ns,
double holdover_multiplier_ns) {
uint64_t h = (uint64_t)(holdover_multiplier_ns * seconds);
uint64_t w = error_bound_ns + h;
fbclock_debug_print("error_bound=%lu\n", error_bound_ns);
fbclock_debug_print("holdover_multiplier=%f\n", holdover_multiplier_ns);
fbclock_debug_print("%.3f seconds holdover, h=%lu\n", seconds, h);
fbclock_debug_print("w = %lu ns\n", w);
fbclock_debug_print("w = %lu ms\n", w / 1000000);
return w;
}
uint64_t fbclock_truetime_midpoint_ns(
const fbclock_truetime* _Nonnull truetime) {
return truetime->earliest_ns +
(truetime->latest_ns - truetime->earliest_ns) / 2;
}
int fbclock_check_max_wou(
uint64_t max_wou_ns,
const fbclock_truetime* truetime) {
if (max_wou_ns != FBCLOCK_MAX_WOU_NS_UNSET &&
(truetime->latest_ns - truetime->earliest_ns) > max_wou_ns) {
return FBCLOCK_E_WOU_TOO_BIG;
}
return FBCLOCK_E_NO_ERROR;
}
int fbclock_calculate_time(
uint64_t error_bound_ns,
double h_value_ns,
fbclock_clockdata* state,
int64_t phctime_ns,
fbclock_truetime* truetime,
int time_standard) {
if (state->ingress_time_ns > phctime_ns) {
return FBCLOCK_E_PHC_IN_THE_PAST;
}
// check how far back since last SYNC message from GM (in seconds)
double seconds =
(double)(phctime_ns - state->ingress_time_ns) / NANOSECONDS_IN_SECONDS;
// UTC offset applied if time standard used is UTC (and not TAI)
if (time_standard == FBCLOCK_UTC) {
phctime_ns = fbclock_apply_utc_offset(state, phctime_ns);
}
// calculate the Window of Uncertainty (WOU) (in nanoseconds)
uint64_t wou_ns =
fbclock_window_of_uncertainty(seconds, error_bound_ns, h_value_ns);
truetime->earliest_ns = phctime_ns - wou_ns;
truetime->latest_ns = phctime_ns + wou_ns;
return FBCLOCK_E_NO_ERROR;
}
int fbclock_calculate_time_v2(
uint64_t error_bound_ns,
double h_value_ns,
fbclock_clockdata_v2* state,
int64_t sysclock_time_now_ns,
fbclock_truetime* truetime,
int time_standard) {
int64_t phc_time_ns = state->phc_time_ns;
if (state->ingress_time_ns > phc_time_ns) {
return FBCLOCK_E_PHC_IN_THE_PAST;
}
int64_t diff_ns = sysclock_time_now_ns - state->sysclock_time_ns;
// Refuse to extrapolate past a sane bound, or backwards in time. Either case
// means the daemon stopped updating shared memory or there's a clock-source
// mismatch, so the extrapolated PHC time would have unbounded error.
if (diff_ns < 0 || diff_ns > FBCLOCK_MAX_EXTRAPOLATION_NS) {
return FBCLOCK_E_DATA_STALE;
}
// NANOSECONDS_IN_SECONDS is uint64_t, which would otherwise convert the
// signed dividend to unsigned. When coef_ppb is negative the product is
// negative, and that conversion turns it into a value near 2^64, making
// the quotient ~2^64/1e9 ≈ 18.45 s instead of the intended small ns count.
phc_time_ns +=
diff_ns + diff_ns * state->coef_ppb / (int64_t)NANOSECONDS_IN_SECONDS;
// Time since the last SYNC from the GM, at the PHC instant this call
// reports. Clamped like the past_v2 path below: a coef_ppb under -1e9
// extrapolates back past ingress, and fbclock_window_of_uncertainty casts
// the holdover product to uint64_t.
int64_t holdover_ns = phc_time_ns - state->ingress_time_ns;
double seconds =
holdover_ns > 0 ? (double)holdover_ns / NANOSECONDS_IN_SECONDS : 0.0;
// UTC offset applied if time standard used is UTC (and not TAI)
if (time_standard == FBCLOCK_UTC) {
phc_time_ns = fbclock_apply_utc_offset_v2(state, phc_time_ns);
}
// calculate the Window of Uncertainty (WOU) (in nanoseconds)
uint64_t wou_ns =
fbclock_window_of_uncertainty(seconds, error_bound_ns, h_value_ns);
truetime->earliest_ns = phc_time_ns - wou_ns;
truetime->latest_ns = phc_time_ns + wou_ns;
return FBCLOCK_E_NO_ERROR;
}
// Like fbclock_calculate_time_v2 but for the REALTIME-domain anchor section,
// with a caller-provided ts (CLOCK_REALTIME ns). The caller's ts is typically
// in the past (e.g. a kernel SW TX timestamp captured before sendmsg), so
// diff_ns may be negative and the bound is symmetric. If the ts predates the
// last GM sync, the holdover term is dropped (seconds clamped to 0).
int fbclock_calculate_time_past_v2(
uint64_t error_bound_ns,
double h_value_ns,
fbclock_clockdata_v2* _Nonnull state,
int64_t ts_realtime_ns,
fbclock_truetime* _Nonnull truetime,
int time_standard) {
int64_t phc_anchor_ns = state->phc_time_ns;
int64_t diff_ns = ts_realtime_ns - state->sysclock_time_ns;
if (diff_ns > FBCLOCK_MAX_EXTRAPOLATION_NS ||
diff_ns < -FBCLOCK_MAX_EXTRAPOLATION_NS) {
return FBCLOCK_E_DATA_STALE;
}
// Same signed-arithmetic care as v2: keep the divisor signed so a negative
// (coef_ppb * diff_ns) product divides correctly.
int64_t phc_at_ts_ns = phc_anchor_ns + diff_ns +
diff_ns * state->coef_ppb / (int64_t)NANOSECONDS_IN_SECONDS;
// Holdover term grows with time since last GM sync. For a past ts, measure
// from the past PHC moment, not from "now". If the past moment predates the
// last sync (ts older than ingress), clamp seconds to 0 so the WOU collapses
// to error_bound_ns alone.
double seconds = 0.0;
if (phc_at_ts_ns > state->ingress_time_ns) {
seconds = (double)(phc_at_ts_ns - state->ingress_time_ns) /
NANOSECONDS_IN_SECONDS;
}
if (time_standard == FBCLOCK_UTC) {
phc_at_ts_ns = fbclock_apply_utc_offset_v2(state, phc_at_ts_ns);
}
uint64_t wou_ns =
fbclock_window_of_uncertainty(seconds, error_bound_ns, h_value_ns);
truetime->earliest_ns = phc_at_ts_ns - wou_ns;
truetime->latest_ns = phc_at_ts_ns + wou_ns;
return FBCLOCK_E_NO_ERROR;
}
int fbclock_gettime_tz(
fbclock_lib* lib,
fbclock_truetime* truetime,
int time_standard) {
struct phc_time_res res;
fbclock_clockdata state = {};
int rcode = fbclock_clockdata_load_data(lib->shmp, &state);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
// cannot determine Truetime without these values
if (state.error_bound_ns == 0 || state.ingress_time_ns == 0) {
return FBCLOCK_E_NO_DATA;
}
// if the value is stored as UINT32_MAX then it's too big
if (state.error_bound_ns == UINT32_MAX ||
state.holdover_multiplier_ns == UINT32_MAX) {
return FBCLOCK_E_WOU_TOO_BIG;
}
if (lib->gettime(lib->dev_fd, &res)) {
return FBCLOCK_E_PTP_READ_OFFSET;
}
// store the minimal PHC request delay
if (res.delay < lib->min_phc_delay) {
lib->min_phc_delay = res.delay;
}
uint64_t error_bound = state.error_bound_ns + lib->min_phc_delay;
double h_value = (double)state.holdover_multiplier_ns / FBCLOCK_POW2_16;
// Compute the window, then enforce the caller's optional max-WOU policy.
rcode = fbclock_calculate_time(
error_bound, h_value, &state, res.ts, truetime, time_standard);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
return fbclock_check_max_wou(lib->max_wou_ns, truetime);
}
int fbclock_gettime_tz_v2(
fbclock_lib* lib,
fbclock_truetime* truetime,
int time_standard) {
fbclock_clockdata_v2 state = {};
int rcode = fbclock_clockdata_load_data_v2(lib->shmp_v2, &state);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
// cannot determine Truetime without these values
if (state.error_bound_ns == 0 || state.ingress_time_ns == 0) {
return FBCLOCK_E_NO_DATA;
}
if (state.phc_time_ns == 0 || state.sysclock_time_ns == 0) {
return FBCLOCK_E_NO_DATA;
}
// if the value is stored as UINT32_MAX then it's too big
if (state.error_bound_ns == UINT32_MAX ||
state.holdover_multiplier_ns == UINT32_MAX) {
return FBCLOCK_E_WOU_TOO_BIG;
}
uint64_t error_bound =
state.error_bound_ns; // FIXME add sys clock error bound here
double h_value = (double)state.holdover_multiplier_ns / FBCLOCK_POW2_16;
struct timespec ts;
if (clock_gettime(state.clockId, &ts) == -1) {
return FBCLOCK_E_PTP_READ_OFFSET;
}
int64_t sysclock_time_now_ns =
ts.tv_sec * NANOSECONDS_IN_SECONDS + ts.tv_nsec;
// Compute the window, then enforce the caller's optional max-WOU policy.
rcode = fbclock_calculate_time_v2(
error_bound,
h_value,
&state,
sysclock_time_now_ns,
truetime,
time_standard);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
return fbclock_check_max_wou(lib->max_wou_ns, truetime);
}
int fbclock_gettime(fbclock_lib* lib, fbclock_truetime* truetime) {
if (lib->shmp_v2) {
return fbclock_gettime_tz_v2(lib, truetime, FBCLOCK_TAI);
}
return fbclock_gettime_tz(lib, truetime, FBCLOCK_TAI);
}
int fbclock_gettime_utc(fbclock_lib* lib, fbclock_truetime* truetime) {
if (lib->shmp_v2) {
return fbclock_gettime_tz_v2(lib, truetime, FBCLOCK_UTC);
}
return fbclock_gettime_tz(lib, truetime, FBCLOCK_UTC);
}
static int fbclock_gettime_past_tz_v2(
fbclock_lib* _Nonnull lib,
int64_t ts_realtime_ns,
fbclock_truetime* _Nonnull truetime,
int time_standard) {
// Select the REALTIME-domain section. If the primary is already REALTIME
// (older hosts) we use it directly; otherwise the primary is MONOTONIC_RAW
// and the daemon publishes a dedicated REALTIME section we read instead.
fbclock_clockdata_v2 state = {};
if (lib->shmp_v2 == NULL) {
return FBCLOCK_E_NO_DATA;
}
int rcode = fbclock_section_load(&lib->shmp_v2->primary, &state, 1);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
if (state.clockId != CLOCK_REALTIME) {
rcode = fbclock_clockdata_load_data_realtime(lib->shmp_v2, &state);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
}
// The selected section is self-contained; make sure it actually has data.
if (state.error_bound_ns == 0 || state.ingress_time_ns == 0 ||
state.phc_time_ns == 0 || state.sysclock_time_ns == 0) {
return FBCLOCK_E_NO_DATA;
}
if (state.error_bound_ns == UINT32_MAX ||
state.holdover_multiplier_ns == UINT32_MAX) {
return FBCLOCK_E_WOU_TOO_BIG;
}
uint64_t error_bound = state.error_bound_ns;
double h_value = (double)state.holdover_multiplier_ns / FBCLOCK_POW2_16;
// Compute the window, then enforce the caller's optional max-WOU policy.
rcode = fbclock_calculate_time_past_v2(
error_bound, h_value, &state, ts_realtime_ns, truetime, time_standard);
if (rcode != FBCLOCK_E_NO_ERROR) {
return rcode;
}
return fbclock_check_max_wou(lib->max_wou_ns, truetime);
}
int fbclock_gettime_past(
fbclock_lib* _Nonnull lib,
int64_t ts_realtime_ns,
fbclock_truetime* _Nonnull truetime) {
if (!lib->shmp_v2) {
// gettime_past is v2-only: v1 has no sysclock anchor to extrapolate from.
return FBCLOCK_E_NO_DATA;
}
return fbclock_gettime_past_tz_v2(lib, ts_realtime_ns, truetime, FBCLOCK_TAI);
}
int fbclock_gettime_past_utc(
fbclock_lib* _Nonnull lib,
int64_t ts_realtime_ns,
fbclock_truetime* _Nonnull truetime) {
if (!lib->shmp_v2) {
return FBCLOCK_E_NO_DATA;
}
return fbclock_gettime_past_tz_v2(lib, ts_realtime_ns, truetime, FBCLOCK_UTC);
}
uint64_t fbclock_apply_smear(
uint64_t time,
uint64_t offset_pre_ns,
uint64_t offset_post_ns,
uint64_t smear_start_ns,
uint64_t smear_end_ns,
int multiplier) {
if (time > smear_end_ns) {
time -= offset_post_ns;
} else if (time < smear_start_ns) {
time -= offset_pre_ns;
} else {
// Spread the whole leap second across the window the daemon published, so
// the ramp reaches offset_post_ns exactly at smear_end_ns. A window of N
// seconds smears 1ns every N ns.
uint64_t window_ns = smear_end_ns - smear_start_ns;
uint64_t elapsed_ns = time - smear_start_ns;
uint64_t ramp_ns = window_ns
? (uint64_t)(((__uint128_t)elapsed_ns * NANOSECONDS_IN_SECONDS) /
window_ns)
: NANOSECONDS_IN_SECONDS;
time -= (uint64_t)((int64_t)offset_pre_ns +
(int64_t)multiplier * (int64_t)ramp_ns);
}
return time;
}
uint64_t fbclock_apply_utc_offset(
fbclock_clockdata* state,
int64_t phctime_ns) {
// Fixed offset is applied if tzdata information not in shared memory
if (state->utc_offset_pre_s == 0 && state->utc_offset_post_s == 0) {
phctime_ns += UTC_TAI_OFFSET_NS;
return (uint64_t)phctime_ns;
}
fbclock_debug_print(
"UTC-TAI Offset Before Leap Second Event: %d\n", state->utc_offset_pre_s);
fbclock_debug_print(
"UTC-TAI Offset After Leap Second Event: %d\n", state->utc_offset_post_s);
fbclock_debug_print(
"Clock Smearing Start Time (TAI): %lu\n", state->clock_smearing_start_s);
fbclock_debug_print(
"Clock Smearing End Time (TAI): %lu\n", state->clock_smearing_end_s);
// Multipler may be negative (if a negative leap second is applied)
int multiplier = state->utc_offset_post_s - state->utc_offset_pre_s;
// Switch to nanoseconds
uint64_t smear_end_ns = state->clock_smearing_end_s * NANOSECONDS_IN_SECONDS;
uint64_t smear_start_ns =
state->clock_smearing_start_s * NANOSECONDS_IN_SECONDS;
uint64_t offset_post_ns = state->utc_offset_post_s * NANOSECONDS_IN_SECONDS;
uint64_t offset_pre_ns = state->utc_offset_pre_s * NANOSECONDS_IN_SECONDS;
return fbclock_apply_smear(
phctime_ns,
offset_pre_ns,
offset_post_ns,
smear_start_ns,
smear_end_ns,
multiplier);
}
uint64_t fbclock_apply_utc_offset_v2(
fbclock_clockdata_v2* state,
int64_t phctime_ns) {
// Fixed offset is applied if tzdata information not in shared memory
if (state->utc_offset_pre_s == 0 && state->utc_offset_post_s == 0) {
phctime_ns += UTC_TAI_OFFSET_NS;
return (uint64_t)phctime_ns;
}
fbclock_debug_print(
"UTC-TAI Offset Before Leap Second Event: %d\n", state->utc_offset_pre_s);
fbclock_debug_print(
"UTC-TAI Offset After Leap Second Event: %d\n", state->utc_offset_post_s);
fbclock_debug_print(
"Clock Smearing Start Time (TAI): %lu\n", state->clock_smearing_start_s);
fbclock_debug_print(
"Clock Smearing End Time (TAI): %lu\n",
state->clock_smearing_start_s + SMEAR_DURATION);
// Multipler may be negative (if a negative leap second is applied)
int multiplier = state->utc_offset_post_s - state->utc_offset_pre_s;
// Switch to nanoseconds
uint64_t smear_end_ns =
(state->clock_smearing_start_s + SMEAR_DURATION) * NANOSECONDS_IN_SECONDS;
uint64_t smear_start_ns =
state->clock_smearing_start_s * NANOSECONDS_IN_SECONDS;
uint64_t offset_post_ns = state->utc_offset_post_s * NANOSECONDS_IN_SECONDS;
uint64_t offset_pre_ns = state->utc_offset_pre_s * NANOSECONDS_IN_SECONDS;
return fbclock_apply_smear(
phctime_ns,
offset_pre_ns,
offset_post_ns,
smear_start_ns,
smear_end_ns,
multiplier);
}
const char* fbclock_strerror(int err_code) {
const char* err_info;
switch (err_code) {
case FBCLOCK_E_SHMEM_MAP_FAILED:
err_info = "shmem map error";
break;
case FBCLOCK_E_SHMEM_OPEN:
err_info = "shmem open error";
break;
case FBCLOCK_E_PTP_READ_OFFSET:
err_info = "PTP PTP_SYS_OFFSET_EXTENDED ioctl error";
break;
case FBCLOCK_E_PTP_OPEN:
err_info = "PTP device open error";
break;
case FBCLOCK_E_NO_DATA:
err_info = "no data from daemon error";
break;
case FBCLOCK_E_WOU_TOO_BIG:
err_info = "WOU is too big";
break;
case FBCLOCK_E_PHC_IN_THE_PAST:
err_info = "PHC jumped back in time";
break;
case FBCLOCK_E_CRC_MISMATCH:
err_info = "CRC check failed all tries";
break;
case FBCLOCK_E_DATA_STALE:
err_info = "shared memory data too old to extrapolate";
break;
case FBCLOCK_E_NOTSUP:
err_info = "PTP not supported on this host (no PTP device)";
break;
case FBCLOCK_E_NO_ERROR:
err_info = "no error";
break;
default:
err_info = "unknown error";
break;
}
return err_info;
}