forked from richardcochran/linuxptp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clock.c
2283 lines (2043 loc) · 58.8 KB
/
clock.c
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
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file clock.c
* @note Copyright (C) 2011 Richard Cochran <[email protected]>
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include <errno.h>
#include <time.h>
#include <linux/net_tstamp.h>
#include <poll.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/queue.h>
#include "address.h"
#include "bmc.h"
#include "clock.h"
#include "clockadj.h"
#include "clockcheck.h"
#include "foreign.h"
#include "filter.h"
#include "missing.h"
#include "msg.h"
#include "phc.h"
#include "port.h"
#include "servo.h"
#include "stats.h"
#include "print.h"
#include "rtnl.h"
#include "tlv.h"
#include "tsproc.h"
#include "tz.h"
#include "uds.h"
#include "util.h"
#define N_CLOCK_PFD (N_POLLFD + 1) /* one extra per port, for the fault timer */
#define POW2_41 ((double)(1ULL << 41))
struct interface {
STAILQ_ENTRY(interface) list;
};
struct port {
LIST_ENTRY(port) list;
};
struct freq_estimator {
tmv_t origin1;
tmv_t ingress1;
unsigned int max_count;
unsigned int count;
};
struct clock_stats {
struct stats *offset;
struct stats *freq;
struct stats *delay;
unsigned int max_count;
};
struct clock_subscriber {
LIST_ENTRY(clock_subscriber) list;
uint8_t events[EVENT_BITMASK_CNT];
struct PortIdentity targetPortIdentity;
struct address addr;
UInteger16 sequenceId;
time_t expiration;
};
struct time_zone {
bool enabled;
int32_t current_offset;
int32_t jump_seconds;
uint16_t next_jump_msb;
uint32_t next_jump_lsb;
struct static_ptp_text display_name;
};
struct clock {
enum clock_type type;
struct config *config;
clockid_t clkid;
struct servo *servo;
enum servo_type servo_type;
int (*dscmp)(struct dataset *a, struct dataset *b);
struct defaultDS dds;
struct dataset default_dataset;
struct currentDS cur;
struct parent_ds dad;
struct timePropertiesDS tds;
struct ClockIdentity ptl[PATH_TRACE_MAX];
struct foreign_clock *best;
struct ClockIdentity best_id;
LIST_HEAD(ports_head, port) ports;
struct port *uds_rw_port;
struct port *uds_ro_port;
struct pollfd *pollfd;
int pollfd_valid;
int nports; /* does not include the two UDS ports */
int last_port_number;
int sde;
int free_running;
int freq_est_interval;
int local_sync_uncertain;
int write_phase_mode;
int grand_master_capable; /* for 802.1AS only */
int utc_timescale;
int utc_offset_set;
int leap_set;
int kernel_leap;
int utc_offset;
int time_flags; /* grand master role */
int time_source; /* grand master role */
UInteger8 clock_class_threshold;
UInteger8 max_steps_removed;
enum servo_state servo_state;
enum timestamp_type timestamping;
tmv_t master_offset;
tmv_t path_delay;
tmv_t ingress_ts;
tmv_t initial_delay;
struct tsproc *tsproc;
struct freq_estimator fest;
struct time_status_np status;
double master_local_rr; /* maintained when free_running */
double nrr;
struct clock_description desc;
struct clock_stats stats;
int stats_interval;
struct clockcheck *sanity_check;
struct interface *uds_rw_if;
struct interface *uds_ro_if;
LIST_HEAD(clock_subscribers_head, clock_subscriber) subscribers;
struct monitor *slave_event_monitor;
int step_window_counter;
int step_window;
struct time_zone tz[MAX_TIME_ZONES];
};
struct clock the_clock;
static void handle_state_decision_event(struct clock *c);
static int clock_resize_pollfd(struct clock *c, int new_nports);
static void clock_remove_port(struct clock *c, struct port *p);
static void clock_stats_display(struct clock_stats *s);
static int clock_alttime_offset_append(struct clock *c, int key, struct ptp_message *m)
{
struct alternate_time_offset_indicator_tlv *atoi;
struct tlv_extra *extra;
int tlv_len;
tlv_len = sizeof(*atoi) + c->tz[key].display_name.length;
if (tlv_len % 2) {
tlv_len++;
}
extra = msg_tlv_append(m, tlv_len);
if (!extra) {
return -1;
}
atoi = (struct alternate_time_offset_indicator_tlv *) extra->tlv;
atoi->type = TLV_ALTERNATE_TIME_OFFSET_INDICATOR;
atoi->length = tlv_len - sizeof(atoi->type) - sizeof(atoi->length);
atoi->keyField = key;
/* Message alignment broken by design. */
memcpy(&atoi->currentOffset, &c->tz[key].current_offset,
sizeof(atoi->currentOffset));
memcpy(&atoi->jumpSeconds, &c->tz[key].jump_seconds,
sizeof(atoi->jumpSeconds));
memcpy(&atoi->timeOfNextJump.seconds_lsb, &c->tz[key].next_jump_lsb,
sizeof(atoi->timeOfNextJump.seconds_lsb));
memcpy(&atoi->timeOfNextJump.seconds_msb, &c->tz[key].next_jump_msb,
sizeof(atoi->timeOfNextJump.seconds_msb));
ptp_text_copy(&atoi->displayName, &c->tz[key].display_name);
return 0;
}
uint8_t clock_alttime_offset_get_key(struct ptp_message *req)
{
struct management_tlv_datum *mtd;
struct management_tlv *mgt =
(struct management_tlv *) req->management.suffix;
/*
* The data field of incoming management request messages is
* normally ignored. Indeed it can even be empty. However
* the ALTERNATE_TIME_OFFSET requests are exceptional because
* the key field selects one of the configured time zones.
*
* Provide the first time zone for an empty GET, and validate
* the length of the request when non-empty.
*/
if (mgt->length == sizeof(mgt->id)) {
return 0;
}
if (mgt->length < sizeof(mgt->id) + sizeof(*mtd)) {
return MAX_TIME_ZONES;
}
mtd = (struct management_tlv_datum *) mgt->data;
return mtd->val;
}
static void remove_subscriber(struct clock_subscriber *s)
{
LIST_REMOVE(s, list);
free(s);
}
static void clock_update_subscription(struct clock *c, struct ptp_message *req,
uint8_t *bitmask, uint16_t duration)
{
struct clock_subscriber *s, *tmp;
struct timespec now;
int i, remove = 1;
for (i = 0; i < EVENT_BITMASK_CNT; i++) {
if (bitmask[i]) {
remove = 0;
break;
}
}
LIST_FOREACH_SAFE(s, &c->subscribers, list, tmp) {
if (pid_eq(&s->targetPortIdentity,
&req->header.sourcePortIdentity)) {
if (!remove) {
/* Update transport address and event mask. */
s->addr = req->address;
memcpy(s->events, bitmask, EVENT_BITMASK_CNT);
clock_gettime(CLOCK_MONOTONIC, &now);
s->expiration = now.tv_sec + duration;
} else {
remove_subscriber(s);
}
return;
}
}
if (remove)
return;
/* Not present yet, add the subscriber. */
s = malloc(sizeof(*s));
if (!s) {
pr_err("failed to allocate memory for a subscriber");
return;
}
s->targetPortIdentity = req->header.sourcePortIdentity;
s->addr = req->address;
memcpy(s->events, bitmask, EVENT_BITMASK_CNT);
clock_gettime(CLOCK_MONOTONIC, &now);
s->expiration = now.tv_sec + duration;
s->sequenceId = 0;
LIST_INSERT_HEAD(&c->subscribers, s, list);
}
static void clock_get_subscription(struct clock *c, struct ptp_message *req,
uint8_t *bitmask, uint16_t *duration)
{
struct clock_subscriber *s;
struct timespec now;
LIST_FOREACH(s, &c->subscribers, list) {
if (pid_eq(&s->targetPortIdentity,
&req->header.sourcePortIdentity)) {
memcpy(bitmask, s->events, EVENT_BITMASK_CNT);
clock_gettime(CLOCK_MONOTONIC, &now);
if (s->expiration < now.tv_sec)
*duration = 0;
else
*duration = s->expiration - now.tv_sec;
return;
}
}
/* A client without entry means the client has no subscriptions. */
memset(bitmask, 0, EVENT_BITMASK_CNT);
*duration = 0;
}
static void clock_flush_subscriptions(struct clock *c)
{
struct clock_subscriber *s, *tmp;
LIST_FOREACH_SAFE(s, &c->subscribers, list, tmp) {
remove_subscriber(s);
}
}
static void clock_prune_subscriptions(struct clock *c)
{
struct clock_subscriber *s, *tmp;
struct timespec now;
clock_gettime(CLOCK_MONOTONIC, &now);
LIST_FOREACH_SAFE(s, &c->subscribers, list, tmp) {
if (s->expiration <= now.tv_sec) {
pr_info("subscriber %s timed out",
pid2str(&s->targetPortIdentity));
remove_subscriber(s);
}
}
}
void clock_send_notification(struct clock *c, struct ptp_message *msg,
enum notification event)
{
struct port *uds = c->uds_rw_port;
struct clock_subscriber *s;
LIST_FOREACH(s, &c->subscribers, list) {
if (!event_bitmask_get(s->events, event))
continue;
/* send event */
msg->header.sequenceId = htons(s->sequenceId);
s->sequenceId++;
msg->management.targetPortIdentity.clockIdentity =
s->targetPortIdentity.clockIdentity;
msg->management.targetPortIdentity.portNumber =
htons(s->targetPortIdentity.portNumber);
msg->address = s->addr;
port_forward_to(uds, msg);
}
}
void clock_destroy(struct clock *c)
{
struct port *p, *tmp;
interface_destroy(c->uds_rw_if);
interface_destroy(c->uds_ro_if);
clock_flush_subscriptions(c);
LIST_FOREACH_SAFE(p, &c->ports, list, tmp) {
clock_remove_port(c, p);
}
monitor_destroy(c->slave_event_monitor);
port_close(c->uds_rw_port);
port_close(c->uds_ro_port);
free(c->pollfd);
if (c->clkid != CLOCK_REALTIME) {
phc_close(c->clkid);
}
servo_destroy(c->servo);
tsproc_destroy(c->tsproc);
stats_destroy(c->stats.offset);
stats_destroy(c->stats.freq);
stats_destroy(c->stats.delay);
if (c->sanity_check) {
clockcheck_destroy(c->sanity_check);
}
memset(c, 0, sizeof(*c));
msg_cleanup();
tc_cleanup();
}
static int clock_fault_timeout(struct port *port, int set)
{
struct fault_interval i;
if (!set) {
pr_debug("clearing fault on %s", port_log_name(port));
return port_set_fault_timer_lin(port, 0);
}
fault_interval(port, last_fault_type(port), &i);
if (i.type == FTMO_LINEAR_SECONDS) {
pr_debug("waiting %d seconds to clear fault on %s",
i.val, port_log_name(port));
return port_set_fault_timer_lin(port, i.val);
} else if (i.type == FTMO_LOG2_SECONDS) {
pr_debug("waiting 2^{%d} seconds to clear fault on %s",
i.val, port_log_name(port));
return port_set_fault_timer_log(port, 1, i.val);
}
pr_err("Unsupported fault interval type %d", i.type);
return -1;
}
static void clock_freq_est_reset(struct clock *c)
{
c->fest.origin1 = tmv_zero();
c->fest.ingress1 = tmv_zero();
c->fest.count = 0;
}
static void clock_management_send_error(struct port *p,
struct ptp_message *msg, int error_id)
{
if (port_management_error(port_identity(p), p, msg, error_id))
pr_err("failed to send management error status");
}
/* The 'p' and 'req' paremeters are needed for the GET actions that operate
* on per-client datasets. If such actions do not apply to the caller, it is
* allowed to pass both of them as NULL.
*/
static int clock_management_fill_response(struct clock *c, struct port *p,
struct ptp_message *req,
struct ptp_message *rsp, int id)
{
struct alternate_time_offset_properties *atop;
struct alternate_time_offset_name *aton;
struct grandmaster_settings_np *gsn;
struct management_tlv_datum *mtd;
struct subscribe_events_np *sen;
struct management_tlv *tlv;
struct time_status_np *tsn;
struct tlv_extra *extra;
struct PTPText *text;
uint16_t duration;
int datalen = 0;
uint8_t key;
extra = tlv_extra_alloc();
if (!extra) {
pr_err("failed to allocate TLV descriptor");
return 0;
}
extra->tlv = (struct TLV *) rsp->management.suffix;
tlv = (struct management_tlv *) rsp->management.suffix;
tlv->type = TLV_MANAGEMENT;
tlv->id = id;
switch (id) {
case MID_USER_DESCRIPTION:
text = (struct PTPText *) tlv->data;
text->length = c->desc.userDescription.length;
memcpy(text->text, c->desc.userDescription.text, text->length);
datalen = 1 + text->length;
break;
case MID_DEFAULT_DATA_SET:
memcpy(tlv->data, &c->dds, sizeof(c->dds));
datalen = sizeof(c->dds);
break;
case MID_CURRENT_DATA_SET:
memcpy(tlv->data, &c->cur, sizeof(c->cur));
datalen = sizeof(c->cur);
break;
case MID_PARENT_DATA_SET:
memcpy(tlv->data, &c->dad.pds, sizeof(c->dad.pds));
datalen = sizeof(c->dad.pds);
break;
case MID_TIME_PROPERTIES_DATA_SET:
memcpy(tlv->data, &c->tds, sizeof(c->tds));
datalen = sizeof(c->tds);
break;
case MID_PRIORITY1:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->dds.priority1;
datalen = sizeof(*mtd);
break;
case MID_PRIORITY2:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->dds.priority2;
datalen = sizeof(*mtd);
break;
case MID_DOMAIN:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->dds.domainNumber;
datalen = sizeof(*mtd);
break;
case MID_SLAVE_ONLY:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->dds.flags & DDS_SLAVE_ONLY ? 1 : 0;
datalen = sizeof(*mtd);
break;
case MID_CLOCK_ACCURACY:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->dds.clockQuality.clockAccuracy;
datalen = sizeof(*mtd);
break;
case MID_TRACEABILITY_PROPERTIES:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->tds.flags & (TIME_TRACEABLE|FREQ_TRACEABLE);
datalen = sizeof(*mtd);
break;
case MID_TIMESCALE_PROPERTIES:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->tds.flags & PTP_TIMESCALE;
datalen = sizeof(*mtd);
break;
case MID_ALTERNATE_TIME_OFFSET_ENABLE:
key = clock_alttime_offset_get_key(req);
if (key >= MAX_TIME_ZONES) {
break;
}
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = key;
mtd->reserved = c->tz[key].enabled ? 1 : 0;
datalen = sizeof(*mtd);
break;
case MID_ALTERNATE_TIME_OFFSET_NAME:
key = clock_alttime_offset_get_key(req);
if (key >= MAX_TIME_ZONES) {
break;
}
aton = (struct alternate_time_offset_name *) tlv->data;
aton->keyField = key;
ptp_text_copy(&aton->displayName, &c->tz[key].display_name);
datalen = sizeof(*aton) + aton->displayName.length;
break;
case MID_ALTERNATE_TIME_OFFSET_PROPERTIES:
key = clock_alttime_offset_get_key(req);
if (key >= MAX_TIME_ZONES) {
break;
}
atop = (struct alternate_time_offset_properties *) tlv->data;
atop->keyField = key;
/* Message alignment broken by design. */
memcpy(&atop->currentOffset, &c->tz[key].current_offset,
sizeof(atop->currentOffset));
memcpy(&atop->jumpSeconds, &c->tz[key].jump_seconds,
sizeof(atop->jumpSeconds));
memcpy(&atop->timeOfNextJump.seconds_lsb, &c->tz[key].next_jump_lsb,
sizeof(atop->timeOfNextJump.seconds_lsb));
memcpy(&atop->timeOfNextJump.seconds_msb, &c->tz[key].next_jump_msb,
sizeof(atop->timeOfNextJump.seconds_msb));
datalen = sizeof(*atop);
break;
case MID_TIME_STATUS_NP:
tsn = (struct time_status_np *) tlv->data;
tsn->master_offset = tmv_to_nanoseconds(c->master_offset);
tsn->ingress_time = tmv_to_nanoseconds(c->ingress_ts);
tsn->cumulativeScaledRateOffset =
(Integer32) (c->status.cumulativeScaledRateOffset +
c->nrr * POW2_41 - POW2_41);
tsn->scaledLastGmPhaseChange = c->status.scaledLastGmPhaseChange;
tsn->gmTimeBaseIndicator = c->status.gmTimeBaseIndicator;
tsn->lastGmPhaseChange = c->status.lastGmPhaseChange;
if (cid_eq(&c->dad.pds.grandmasterIdentity, &c->dds.clockIdentity))
tsn->gmPresent = 0;
else
tsn->gmPresent = 1;
tsn->gmIdentity = c->dad.pds.grandmasterIdentity;
datalen = sizeof(*tsn);
break;
case MID_GRANDMASTER_SETTINGS_NP:
gsn = (struct grandmaster_settings_np *) tlv->data;
gsn->clockQuality = c->dds.clockQuality;
gsn->utc_offset = c->utc_offset;
gsn->time_flags = c->time_flags;
gsn->time_source = c->time_source;
datalen = sizeof(*gsn);
break;
case MID_SUBSCRIBE_EVENTS_NP:
if (p != c->uds_rw_port) {
/* Only the UDS-RW port allowed. */
break;
}
sen = (struct subscribe_events_np *)tlv->data;
clock_get_subscription(c, req, sen->bitmask, &duration);
memcpy(&sen->duration, &duration, sizeof(sen->duration));
datalen = sizeof(*sen);
break;
case MID_SYNCHRONIZATION_UNCERTAIN_NP:
mtd = (struct management_tlv_datum *) tlv->data;
mtd->val = c->local_sync_uncertain;
datalen = sizeof(*mtd);
break;
default:
/* The caller should *not* respond to this message. */
tlv_extra_recycle(extra);
return 0;
}
if (datalen % 2) {
tlv->data[datalen] = 0;
datalen++;
}
tlv->length = sizeof(tlv->id) + datalen;
rsp->header.messageLength += sizeof(*tlv) + datalen;
msg_tlv_attach(rsp, extra);
/* The caller can respond to this message. */
return 1;
}
static int clock_management_get_response(struct clock *c, struct port *p,
int id, struct ptp_message *req)
{
struct PortIdentity pid = port_identity(p);
struct ptp_message *rsp;
int respond;
rsp = port_management_reply(pid, p, req);
if (!rsp) {
return 0;
}
respond = clock_management_fill_response(c, p, req, rsp, id);
if (respond)
port_prepare_and_send(p, rsp, TRANS_GENERAL);
msg_put(rsp);
return respond;
}
static int clock_management_set(struct clock *c, struct port *p,
int id, struct ptp_message *req, int *changed)
{
struct alternate_time_offset_properties *atop;
struct alternate_time_offset_name *aton;
struct grandmaster_settings_np *gsn;
struct management_tlv_datum *mtd;
struct subscribe_events_np *sen;
struct management_tlv *tlv;
int k, key, respond = 0;
tlv = (struct management_tlv *) req->management.suffix;
switch (id) {
case MID_PRIORITY1:
mtd = (struct management_tlv_datum *) tlv->data;
c->dds.priority1 = mtd->val;
*changed = 1;
respond = 1;
break;
case MID_PRIORITY2:
mtd = (struct management_tlv_datum *) tlv->data;
c->dds.priority2 = mtd->val;
*changed = 1;
respond = 1;
break;
case MID_ALTERNATE_TIME_OFFSET_ENABLE:
mtd = (struct management_tlv_datum *) tlv->data;
key = mtd->val;
if (key == 0xff) {
for (k = 0; k < MAX_TIME_ZONES; k++) {
c->tz[k].enabled = mtd->reserved & 1 ? true : false;
}
respond = 1;
}
if (key < MAX_TIME_ZONES) {
c->tz[key].enabled = mtd->reserved & 1 ? true : false;
respond = 1;
}
break;
case MID_ALTERNATE_TIME_OFFSET_NAME:
aton = (struct alternate_time_offset_name *) tlv->data;
key = aton->keyField;
if (key < MAX_TIME_ZONES &&
!static_ptp_text_copy(&c->tz[key].display_name, &aton->displayName)) {
respond = 1;
}
break;
case MID_ALTERNATE_TIME_OFFSET_PROPERTIES:
atop = (struct alternate_time_offset_properties *) tlv->data;
key = atop->keyField;
if (key < MAX_TIME_ZONES) {
/* Message alignment broken by design. */
memcpy(&c->tz[key].current_offset, &atop->currentOffset,
sizeof(c->tz[key].current_offset));
memcpy(&c->tz[key].jump_seconds, &atop->jumpSeconds,
sizeof(c->tz[key].jump_seconds));
memcpy(&c->tz[key].next_jump_lsb, &atop->timeOfNextJump.seconds_lsb,
sizeof(c->tz[key].next_jump_lsb));
memcpy(&c->tz[key].next_jump_msb, &atop->timeOfNextJump.seconds_msb,
sizeof(c->tz[key].next_jump_msb));
respond = 1;
}
break;
case MID_GRANDMASTER_SETTINGS_NP:
gsn = (struct grandmaster_settings_np *) tlv->data;
c->dds.clockQuality = gsn->clockQuality;
c->utc_offset = gsn->utc_offset;
c->time_flags = gsn->time_flags;
c->time_source = gsn->time_source;
*changed = 1;
respond = 1;
break;
case MID_SUBSCRIBE_EVENTS_NP:
sen = (struct subscribe_events_np *)tlv->data;
clock_update_subscription(c, req, sen->bitmask, sen->duration);
respond = 1;
break;
case MID_SYNCHRONIZATION_UNCERTAIN_NP:
mtd = (struct management_tlv_datum *) tlv->data;
switch (mtd->val) {
case SYNC_UNCERTAIN_DONTCARE:
case SYNC_UNCERTAIN_FALSE:
case SYNC_UNCERTAIN_TRUE:
/* Display stats on change of local_sync_uncertain */
if (c->local_sync_uncertain != mtd->val
&& stats_get_num_values(c->stats.offset))
clock_stats_display(&c->stats);
c->local_sync_uncertain = mtd->val;
respond = 1;
break;
}
break;
}
if (respond && !clock_management_get_response(c, p, id, req))
pr_err("failed to send management set response");
return respond ? 1 : 0;
}
static void clock_stats_update(struct clock_stats *s,
double offset, double freq)
{
stats_add_value(s->offset, offset);
stats_add_value(s->freq, freq);
if (stats_get_num_values(s->offset) < s->max_count)
return;
clock_stats_display(s);
}
static void clock_stats_display(struct clock_stats *s)
{
struct stats_result offset_stats, freq_stats, delay_stats;
stats_get_result(s->offset, &offset_stats);
stats_get_result(s->freq, &freq_stats);
/* Path delay stats are updated separately, they may be empty. */
if (!stats_get_result(s->delay, &delay_stats)) {
pr_info("rms %4.0f max %4.0f "
"freq %+6.0f +/- %3.0f "
"delay %5.0f +/- %3.0f",
offset_stats.rms, offset_stats.max_abs,
freq_stats.mean, freq_stats.stddev,
delay_stats.mean, delay_stats.stddev);
} else {
pr_info("rms %4.0f max %4.0f "
"freq %+6.0f +/- %3.0f",
offset_stats.rms, offset_stats.max_abs,
freq_stats.mean, freq_stats.stddev);
}
stats_reset(s->offset);
stats_reset(s->freq);
stats_reset(s->delay);
}
static enum servo_state clock_no_adjust(struct clock *c, tmv_t ingress,
tmv_t origin)
{
struct freq_estimator *f = &c->fest;
double freq, fui, ratio;
enum servo_state state;
if (c->local_sync_uncertain == SYNC_UNCERTAIN_FALSE) {
state = SERVO_LOCKED;
} else {
state = SERVO_UNLOCKED;
}
/*
* The ratio of the local clock freqency to the master clock
* is estimated by:
*
* (ingress_2 - ingress_1) / (origin_2 - origin_1)
*
* Both of the origin time estimates include the path delay,
* but we assume that the path delay is in fact constant.
* By leaving out the path delay altogther, we can avoid the
* error caused by our imperfect path delay measurement.
*/
if (tmv_is_zero(f->ingress1)) {
f->ingress1 = ingress;
f->origin1 = origin;
return state;
}
f->count++;
if (f->count < f->max_count) {
return state;
}
if (tmv_cmp(ingress, f->ingress1) == 0) {
pr_warning("bad timestamps in rate ratio calculation");
return state;
}
ratio = tmv_dbl(tmv_sub(origin, f->origin1)) /
tmv_dbl(tmv_sub(ingress, f->ingress1));
freq = (1.0 - ratio) * 1e9;
if (c->stats.max_count > 1) {
clock_stats_update(&c->stats, tmv_dbl(c->master_offset), freq);
} else {
pr_info("master offset %10" PRId64 " s%d freq %+7.0f "
"path delay %9" PRId64,
tmv_to_nanoseconds(c->master_offset), state, freq,
tmv_to_nanoseconds(c->path_delay));
}
fui = 1.0 + (c->status.cumulativeScaledRateOffset + 0.0) / POW2_41;
pr_debug("peer/local %.9f", c->nrr);
pr_debug("fup_info %.9f", fui);
pr_debug("product %.9f", fui * c->nrr);
pr_debug("sum-1 %.9f", fui + c->nrr - 1.0);
pr_debug("master/local %.9f", ratio);
pr_debug("diff %+.9f", ratio - (fui + c->nrr - 1.0));
f->ingress1 = ingress;
f->origin1 = origin;
f->count = 0;
c->master_local_rr = ratio;
return state;
}
static void clock_update_grandmaster(struct clock *c)
{
struct parentDS *pds = &c->dad.pds;
memset(&c->cur, 0, sizeof(c->cur));
memset(c->ptl, 0, sizeof(c->ptl));
pds->parentPortIdentity.clockIdentity = c->dds.clockIdentity;
/* Follow IEEE 1588 Table 30: Updates for state decision code M1 and M2 */
pds->parentPortIdentity.portNumber = 0;
pds->grandmasterIdentity = c->dds.clockIdentity;
pds->grandmasterClockQuality = c->dds.clockQuality;
pds->grandmasterPriority1 = c->dds.priority1;
pds->grandmasterPriority2 = c->dds.priority2;
c->dad.path_length = 0;
c->tds.currentUtcOffset = c->utc_offset;
c->tds.flags = c->time_flags;
c->tds.timeSource = c->time_source;
}
static void clock_update_slave(struct clock *c)
{
struct parentDS *pds = &c->dad.pds;
struct timePropertiesDS tds;
struct ptp_message *msg;
if (!c->best)
return;
msg = TAILQ_FIRST(&c->best->messages);
c->cur.stepsRemoved = 1 + c->best->dataset.stepsRemoved;
pds->parentPortIdentity = c->best->dataset.sender;
pds->grandmasterIdentity = msg->announce.grandmasterIdentity;
pds->grandmasterClockQuality = msg->announce.grandmasterClockQuality;
pds->grandmasterPriority1 = msg->announce.grandmasterPriority1;
pds->grandmasterPriority2 = msg->announce.grandmasterPriority2;
tds.currentUtcOffset = msg->announce.currentUtcOffset;
tds.flags = msg->header.flagField[1];
tds.timeSource = msg->announce.timeSource;
if (!(tds.flags & PTP_TIMESCALE)) {
pr_warning("foreign master not using PTP timescale");
}
if (tds.currentUtcOffset < c->utc_offset) {
pr_warning("running in a temporal vortex");
}
clock_update_time_properties(c, tds);
}
static int clock_utc_correct(struct clock *c, tmv_t ingress)
{
struct timespec offset;
int utc_offset, leap, clock_leap;
uint64_t ts;
if (!c->utc_timescale && c->tds.flags & PTP_TIMESCALE)
return 0;
utc_offset = c->utc_offset;
if (c->tds.flags & LEAP_61) {
leap = 1;
} else if (c->tds.flags & LEAP_59) {
leap = -1;
} else {
leap = 0;
}
/* Handle leap seconds. */
if (leap || c->leap_set) {
/* If the clock will be stepped, the time stamp has to be the
target time. Ignore possible 1 second error in utc_offset. */
if (c->servo_state == SERVO_UNLOCKED) {
ts = tmv_to_nanoseconds(tmv_sub(ingress,
c->master_offset));
if (c->tds.flags & PTP_TIMESCALE)
ts -= utc_offset * NS_PER_SEC;
} else {
ts = tmv_to_nanoseconds(ingress);
}
/* Suspend clock updates in the last second before midnight. */
if (is_utc_ambiguous(ts)) {
pr_info("clock update suspended due to leap second");
return -1;
}
clock_leap = leap_second_status(ts, c->leap_set,
&leap, &utc_offset);
if (c->leap_set != clock_leap) {
if (c->kernel_leap && c->clkid == CLOCK_REALTIME)
sysclk_set_leap(clock_leap);
else
servo_leap(c->servo, clock_leap);
c->leap_set = clock_leap;
}
}
/* Update TAI-UTC offset of the system clock if valid and traceable. */
if (c->tds.flags & UTC_OFF_VALID && c->tds.flags & TIME_TRACEABLE &&
c->utc_offset_set != utc_offset && c->clkid == CLOCK_REALTIME) {
sysclk_set_tai_offset(utc_offset);
c->utc_offset_set = utc_offset;
}
if (!(c->tds.flags & PTP_TIMESCALE))
return 0;
offset.tv_sec = utc_offset;
offset.tv_nsec = 0;
/* Local clock is UTC, but master is TAI. */
c->master_offset = tmv_add(c->master_offset, timespec_to_tmv(offset));
return 0;
}
static int forwarding(struct clock *c, struct port *p)
{
enum port_state ps = port_state(p);
if (p == c->uds_ro_port)
return 0;
switch (ps) {
case PS_MASTER:
case PS_GRAND_MASTER:
case PS_SLAVE:
case PS_UNCALIBRATED:
case PS_PRE_MASTER:
return 1;
default:
break;
}
if (p == c->uds_rw_port && ps != PS_FAULTY) {
return 1;
}
return 0;
}
/* public methods */
int clock_append_timezones(struct clock *c, struct ptp_message *m)
{
int err = 0, i;
for (i = 0; i < MAX_TIME_ZONES; i++) {
if (!c->tz[i].enabled) {
continue;
}
err = clock_alttime_offset_append(c, i, m);
if (err) {
break;
}
}
return err;
}
UInteger8 clock_class(struct clock *c)
{
return c->dds.clockQuality.clockClass;
}
struct config *clock_config(struct clock *c)
{
return c->config;
}
int (*clock_dscmp(struct clock *c))(struct dataset *a, struct dataset *b)
{
return c->dscmp;
}
struct currentDS *clock_current_dataset(struct clock *c)
{
return &c->cur;
}
static int clock_add_port(struct clock *c, const char *phc_device,
int phc_index, enum timestamp_type timestamping,
struct interface *iface)
{
struct port *p, *piter, *lastp = NULL;