-
Notifications
You must be signed in to change notification settings - Fork 5
/
protocol.c
3891 lines (3363 loc) · 133 KB
/
protocol.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
/*-
* Copyright (c) 2019-2020 Xilinx, Inc.
* Copyright (c) 2014-2018 Solarflare Communications Inc.
* Copyright (c) 2013 Harlan Stenn,
* George N. Neville-Neil,
* Wojciech Owczarek
* Solarflare Communications Inc.
* Copyright (c) 2011-2012 George V. Neville-Neil,
* Steven Kreuzer,
* Martin Burnicki,
* Jan Breuer,
* Wojciech Owczarek,
* Gael Mace,
* Alexandre Van Kempen,
* Inaqui Delgado,
* Rick Ratzel,
* National Instruments.
* Solarflare Communications Inc.
* Copyright (c) 2009-2010 George V. Neville-Neil,
* Steven Kreuzer,
* Martin Burnicki,
* Jan Breuer,
* Gael Mace,
* Alexandre Van Kempen
*
* Copyright (c) 2005-2008 Kendall Correll, Aidan Williams
*
* All Rights Reserved
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
* 1. Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* @file protocol.c
* @date Wed Jun 23 09:40:39 2010
*
* @brief The code that handles the IEEE-1588 protocol and state machine
*
*
*/
#include "ptpd.h"
#include "ptpd_lib.h"
static void handleAnnounce(MsgHeader*, ssize_t, Boolean, RunTimeOpts*, PtpClock*);
static void handleSync(const MsgHeader*, ssize_t, TimeInternal*, Boolean, Boolean, RunTimeOpts*, PtpClock*);
static void handleFollowUp(const MsgHeader*, ssize_t, const MsgFollowUp*, Boolean, Boolean, RunTimeOpts*, PtpClock*);
static void handlePDelayReq(MsgHeader*, ssize_t, TimeInternal*, Boolean, Boolean, RunTimeOpts*, PtpClock*);
static void handleDelayReq(const MsgHeader*, ssize_t, TimeInternal*, Boolean, Boolean, RunTimeOpts*, PtpClock*);
static void handlePDelayResp(const MsgHeader*, ssize_t, TimeInternal*, Boolean, Boolean, RunTimeOpts*, PtpClock*);
static void handleDelayResp(const MsgHeader*, ssize_t, RunTimeOpts*, PtpClock*);
static void handlePDelayRespFollowUp(const MsgHeader*, ssize_t, Boolean, RunTimeOpts*, PtpClock*);
static void handleManagement(MsgHeader*, ssize_t, Boolean, RunTimeOpts*, PtpClock*);
static void handleSignaling(PtpClock*);
static void issueAnnounce(RunTimeOpts*, PtpClock*);
static void issueSync(RunTimeOpts*, PtpClock*);
static void issueFollowup(const TimeInternal*, RunTimeOpts*, PtpClock*, const UInteger16);
static void issuePDelayReq(RunTimeOpts*, PtpClock*);
static void issueDelayReq(RunTimeOpts*, PtpClock*);
static void issuePDelayResp(TimeInternal*, MsgHeader*, RunTimeOpts*, PtpClock*);
static void issueDelayResp(TimeInternal*, MsgHeader*, RunTimeOpts*, PtpClock*);
static void issuePDelayRespFollowUp(TimeInternal*, MsgHeader*, RunTimeOpts*, PtpClock*, const UInteger16);
static void issueManagementRespOrAck(MsgManagement*, RunTimeOpts*, PtpClock*, const struct sockaddr_storage *address, socklen_t addressLength);
static void issueManagementErrorStatus(MsgManagement*, RunTimeOpts*, PtpClock*, const struct sockaddr_storage *address, socklen_t addressLength);
static void processMessage(InterfaceOpts *ifOpts, PtpInterface *ptpInterface, TimeInternal *timestamp, Boolean timestampValid, ssize_t length);
static void processPortMessage(RunTimeOpts *rtOpts, PtpClock *ptpClock, TimeInternal *timestamp, Boolean timestampValid, ssize_t length, int offset, acl_bitmap_t acls_checked, acl_bitmap_t acls_passed);
static ssize_t unpackPortMessage(PtpClock *ptpClock, ssize_t safe_length);
static bool processTLVs(RunTimeOpts *rtOpts, PtpClock *ptpClock, int payload_offset,
ssize_t unpack_result, ssize_t safe_length, Boolean isFromSelf,
TimeInternal *timestamp, Boolean timestampValid,
acl_bitmap_t acls_checked, acl_bitmap_t acls_passed);
static void handleMessage(RunTimeOpts *rtOpts, PtpClock *ptpClock,
ssize_t safe_length, Boolean isFromSelf,
TimeInternal *timestamp, Boolean timestampValid);
static void processSyncFromSelf(const TimeInternal *tint, RunTimeOpts *rtOpts, PtpClock *ptpClock, const UInteger16 sequenceId);
static void processDelayReqFromSelf(const TimeInternal *tint, RunTimeOpts *rtOpts, PtpClock *ptpClock);
static void processPDelayReqFromSelf(const TimeInternal *tint, RunTimeOpts *rtOpts, PtpClock *ptpClock);
static void processPDelayRespFromSelf(const TimeInternal *tint, RunTimeOpts *rtOpts, PtpClock *ptpClock, const UInteger16 sequenceId);
static void issueDelayRespWithMonitoring(TimeInternal *time, MsgHeader *header, RunTimeOpts *rtOpts, PtpClock *ptpClock);
static void issueSyncForMonitoring(RunTimeOpts*, PtpClock*, UInteger16 sequenceId);
static void issueFollowupForMonitoring(const TimeInternal*, RunTimeOpts*, PtpClock*, const UInteger16);
static void processMonitoringSyncFromSelf(const TimeInternal *tint, RunTimeOpts *rtOpts, PtpClock *ptpClock, const UInteger16 sequenceId);
struct tlv_dispatch_info {
TLV tlv;
off_t tlv_offset;
const struct tlv_handling *handler;
};
#define MAX_TLVS 32
static enum ptpd_tlv_result
ptpmon_req_tlv_handler(const MsgHeader *header, ssize_t length,
TimeInternal *time, Boolean timestampValid, Boolean isFromSelf,
RunTimeOpts *rtOpts, PtpClock *ptpClock,
TLV *tlv, size_t tlv_offset);
static enum ptpd_tlv_result
mtie_req_tlv_handler(const MsgHeader *header, ssize_t length,
TimeInternal *time, Boolean timestampValid, Boolean isFromSelf,
RunTimeOpts *rtOpts, PtpClock *ptpClock,
TLV *tlv, size_t tlv_offset);
static enum ptpd_tlv_result
port_communication_capabilities_handler(const MsgHeader *header, ssize_t length,
TimeInternal *time, Boolean timestampValid, Boolean isFromSelf,
RunTimeOpts *rtOpts, PtpClock *ptpClock,
TLV *tlv, size_t tlv_offset);
static void statsAddNode(Octet *buf, MsgHeader *header, PtpInterface *ptpInterface);
static void applyUtcOffset(TimeInternal *time, RunTimeOpts *rtOpts, PtpClock *ptpClock);
static const struct tlv_handling tlv_handlers[] = {
{
.tlv_type = PTPD_TLV_PTPMON_REQ_OLD,
.name = "PTPMON_REQ_TLV",
.permitted_message_types_mask = 1 << PTPD_MSG_DELAY_REQ,
.required_acl_types_mask = PTPD_ACL_TIMING | PTPD_ACL_MONITORING,
.pass1_handler_fn = NULL,
.pass2_handler_fn = ptpmon_req_tlv_handler
},
{
.tlv_type = PTPD_TLV_MTIE_REQ_OLD,
.name = "MTIE_REQ_TLV",
.permitted_message_types_mask = 1 << PTPD_MSG_DELAY_REQ,
.required_acl_types_mask = PTPD_ACL_TIMING | PTPD_ACL_MONITORING,
.pass1_handler_fn = mtie_req_tlv_handler,
.pass2_handler_fn = NULL
},
{
.tlv_type = PTPD_TLV_PAD,
.name = "PAD",
.permitted_message_types_mask = ~0,
.required_acl_types_mask = 0,
.pass1_handler_fn = NULL,
.pass2_handler_fn = NULL
},
{
.tlv_type = PTPD_TLV_SLAVE_RX_SYNC_TIMING_DATA,
.name = "SLAVE_RX_SYNC_TIMING_DATA",
.permitted_message_types_mask = 1 << PTPD_MSG_SIGNALING,
.required_acl_types_mask = PTPD_ACL_MONITORING,
.pass1_handler_fn = NULL,
.pass2_handler_fn = slave_rx_sync_timing_data_handler
},
{
.tlv_type = PTPD_TLV_SLAVE_RX_SYNC_COMPUTED_DATA,
.name = "SLAVE_RX_SYNC_COMPUTED_DATA",
.permitted_message_types_mask = 1 << PTPD_MSG_SIGNALING,
.required_acl_types_mask = PTPD_ACL_MONITORING,
.pass1_handler_fn = NULL,
.pass2_handler_fn = slave_rx_sync_computed_data_handler
},
{
.tlv_type = PTPD_TLV_SLAVE_TX_EVENT_TIMESTAMPS,
.name = "SLAVE_TX_EVENT_TIMESTAMPS",
.permitted_message_types_mask = 1 << PTPD_MSG_SIGNALING,
.required_acl_types_mask = PTPD_ACL_MONITORING,
.pass1_handler_fn = NULL,
.pass2_handler_fn = slave_tx_event_timestamps_handler
},
{
.tlv_type = PTPD_TLV_ORGANIZATION_EXTENSION_NON_FORWARDING,
.organization_id = PTPD_SFC_TLV_ORGANISATION_ID,
.organization_sub_type = PTPD_TLV_SFC_SLAVE_STATUS,
.permitted_message_types_mask = 1 << PTPD_MSG_SIGNALING,
.required_acl_types_mask = PTPD_ACL_MONITORING,
.pass1_handler_fn = NULL,
.pass2_handler_fn = slave_status_handler
},
{
.tlv_type = PTPD_TLV_PORT_COMMUNICATION_CAPABILITIES,
.name = "PORT_COMMUNICATION_CAPABILITIES",
.permitted_message_types_mask = 1 << PTPD_MSG_ANNOUNCE,
.required_acl_types_mask = 0,
.pass1_handler_fn = port_communication_capabilities_handler,
.pass2_handler_fn = NULL,
},
};
/* perform actions required when leaving 'port_state' and entering 'state' */
void
toState(ptpd_state_e state, RunTimeOpts *rtOpts, PtpClock *ptpClock)
{
bool valid = true;
/* Stop all protocol timers */
timerStop(ANNOUNCE_INTERVAL_TIMER, ptpClock->itimer);
timerStop(ANNOUNCE_RECEIPT_TIMER, ptpClock->itimer);
timerStop(SYNC_INTERVAL_TIMER, ptpClock->itimer);
timerStop(SYNC_RECEIPT_TIMER, ptpClock->itimer);
timerStop(DELAYREQ_INTERVAL_TIMER, ptpClock->itimer);
timerStop(DELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
timerStop(MASTER_IGMP_REFRESH_TIMER, ptpClock->interface->itimer);
timerStop(FAULT_RESTART_TIMER, ptpClock->itimer);
timerStop(FOREIGN_MASTER_TIMER, ptpClock->itimer);
/* Reset the port alarms - these are generally only valid in the slave
* state. */
ptpClock->portAlarms = 0;
/* Note that we don't reset the servo when entering or leaving the slave
* state. Instead we assume let the servo continue to work. If the time
* on a the next master is significantly different, this will cause a
* servo reset and a time correction. Otherwise we will converge as
* normal.
*/
ptpClock->counters.stateTransitions++;
/* Default to our configured communication capabilities */
ptpClock->effective_comm_caps = rtOpts->comm_caps;
DBG("ptp %s: state %s\n", rtOpts->name, portState_getName(state));
switch (state) {
case PTPD_INITIALIZING:
timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer);
timerStop(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
break;
case PTPD_FAULTY:
timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer);
timerStop(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
timerStart(FAULT_RESTART_TIMER, PTPD_FAULT_RESTART_INTERVAL,
ptpClock->itimer);
break;
case PTPD_DISABLED:
timerStop(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer);
timerStop(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
break;
case PTPD_LISTENING:
/* in Listening mode, we don't send anything. Instead we just
* expect/wait for announces (started below) */
/* Count how many _unique_ timeouts happen to us. If we were
* already in Listen mode, then do not count this as a separate
* reset, but still do a new IGMP refresh */
if (ptpClock->portState != PTPD_LISTENING) {
ptpClock->resetCount++;
}
/* Revert to the original DelayReq, Announce and Sync intervals */
ptpClock->logMinDelayReqInterval = rtOpts->minDelayReqInterval;
ptpClock->logSyncInterval = rtOpts->syncInterval;
ptpd_update_announce_interval(ptpClock, rtOpts);
/* Update the expected interval in the servo */
servo_set_interval(&ptpClock->servo,
powl(2, ptpClock->logSyncInterval));
/* force a IGMP refresh per reset */
if (rtOpts->comm_caps.syncCapabilities & PTPD_COMM_MULTICAST_CAPABLE ||
rtOpts->comm_caps.delayRespCapabilities & PTPD_COMM_MULTICAST_CAPABLE) {
netRefreshIGMP(&ptpClock->interface->transport, rtOpts->ifOpts, ptpClock->interface);
}
timerStart(ANNOUNCE_RECEIPT_TIMER,
(ptpClock->announceReceiptTimeout *
powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
timerStart(FOREIGN_MASTER_TIMER,
(FOREIGN_MASTER_TIME_CHECK * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
/* Avoid restarting the peer-delay timer if it's already
* running. Unlike delay requests (end-to-end) there is no
* randomization in when peer-delay messages are sent so it is
* quite easy to end up with all slaves sending peer delay
* messages at the same time: note that this wouldn't be a
* problem in a network where the peer is a genuine transparent
* clock (switch), however we don't want code that clearly
* would ddos the GM in a misconfigured network. */
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
!timerRunning(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
break;
case PTPD_MASTER:
/* Revert to the original DelayReq, Announce and Sync intervals */
ptpClock->logMinDelayReqInterval = rtOpts->minDelayReqInterval;
ptpClock->logAnnounceInterval = rtOpts->announceInterval;
ptpClock->logSyncInterval = rtOpts->syncInterval;
/* Update the expected interval in the servo */
servo_set_interval(&ptpClock->servo,
powl(2, ptpClock->logSyncInterval));
timerStart(SYNC_INTERVAL_TIMER,
powl(2,ptpClock->logSyncInterval), ptpClock->itimer);
DBG("SYNC INTERVAL TIMER : %Lf \n",
powl(2,ptpClock->logSyncInterval));
timerStart(ANNOUNCE_INTERVAL_TIMER,
powl(2,ptpClock->logAnnounceInterval),
ptpClock->itimer);
timerStart(FOREIGN_MASTER_TIMER,
(FOREIGN_MASTER_TIME_CHECK * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
!timerRunning(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
/* If IGMP refresh is configured, start the refresh timer */
if (rtOpts->ifOpts->masterRefreshIgmp &&
(rtOpts->ifOpts->masterIgmpRefreshInterval > 0) &&
(rtOpts->comm_caps.syncCapabilities & PTPD_COMM_MULTICAST_CAPABLE ||
rtOpts->comm_caps.delayRespCapabilities & PTPD_COMM_MULTICAST_CAPABLE)) {
timerStart(MASTER_IGMP_REFRESH_TIMER,
rtOpts->ifOpts->masterIgmpRefreshInterval,
ptpClock->interface->itimer);
}
break;
case PTPD_PASSIVE:
timerStart(ANNOUNCE_RECEIPT_TIMER,
(ptpClock->announceReceiptTimeout *
powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
timerStart(FOREIGN_MASTER_TIMER,
(FOREIGN_MASTER_TIME_CHECK * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
!timerRunning(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
break;
case PTPD_UNCALIBRATED:
break;
case PTPD_SLAVE:
/* Don't reset the servo when entering or leaving the slave
* state. Instead we assume let the servo continue to work.
* If the time on a the next master is significantly different,
* this will cause a servo reset and a time correction.
* Otherwise we will converge as normal.
*/
ptpClock->waitingForFollow = FALSE;
ptpClock->waitingForDelayResp = FALSE;
/* Copy announced communication capabilities from foreign master record */
ptpClock->partner_comm_caps =
ptpClock->foreign.records[ptpClock->foreign.best_index].comm_caps;
/* Mask local and remote communication capability sets */
ptpClock->effective_comm_caps.syncCapabilities =
ptpClock->partner_comm_caps.syncCapabilities &
rtOpts->comm_caps.syncCapabilities;
ptpClock->effective_comm_caps.delayRespCapabilities =
ptpClock->partner_comm_caps.delayRespCapabilities &
rtOpts->comm_caps.delayRespCapabilities;
if (ptpClock->effective_comm_caps.syncCapabilities == 0) {
WARNING("ptp %s: no common sync message capabilities\n", rtOpts->name);
}
if (ptpClock->effective_comm_caps.delayRespCapabilities == 0) {
WARNING("ptp %s: no common delay resp capabilities\n", rtOpts->name);
}
ptpClock->unicast_delay_resp_failures = 0;
timerStart(OPERATOR_MESSAGES_TIMER,
OPERATOR_MESSAGES_INTERVAL,
ptpClock->itimer);
timerStart(ANNOUNCE_RECEIPT_TIMER,
(ptpClock->announceReceiptTimeout * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
timerStart(FOREIGN_MASTER_TIMER,
(FOREIGN_MASTER_TIME_CHECK * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
ptpClock->sync_missing_interval = 0.0;
ptpClock->sync_missing_next_warning =
ptpClock->syncReceiptTimeout * powl(2,ptpClock->logSyncInterval);
timerStart(SYNC_RECEIPT_TIMER,
ptpClock->sync_missing_next_warning,
ptpClock->itimer);
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
!timerRunning(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
/*
* Previously, this state transition would start the
* delayreq timer immediately. However, if this was
* faster than the first received sync, then the servo
* would drop the delayResp Now, we only start the
* timer after we receive the first sync (in
* handle_sync())
*/
ptpClock->waiting_for_first_sync = TRUE;
ptpClock->waiting_for_first_delayresp = TRUE;
break;
default:
DBG("to unrecognized state\n");
valid = false;
break;
}
if (valid && ptpClock->portState != state) {
ptpClock->portState = state;
displayStatus(ptpClock, "now in state: ");
}
}
void
toStateAllPorts(ptpd_state_e state, PtpInterface *ptpInterface)
{
PtpClock *port;
for (port = ptpInterface->ports; port; port = port->next) {
toState(state, &port->rtOpts, port);
}
}
void
handleSendFailure(RunTimeOpts *rtOpts, PtpClock *ptpClock, const char *message) {
ptpClock->counters.messageSendErrors++;
if (rtOpts->missingInterfaceTolerance) {
toState(PTPD_LISTENING, rtOpts, ptpClock);
DBGV("%s message can't be sent. In missing interface tolerance mode -> LISTENING state\n",
message);
} else {
toState(PTPD_FAULTY, rtOpts, ptpClock);
DBGV("%s message can't be sent -> FAULTY state\n",
message);
}
}
Boolean
doInitGlobal(void)
{
initTimer();
return TRUE;
}
Boolean
doInitPort(RunTimeOpts *rtOpts, PtpClock *ptpClock)
{
/* In case we are re-initializing, first shutdown components that
* require it before initializing.
*/
managementShutdown(ptpClock);
/* initialize networking */
if (!netInitPort(ptpClock, rtOpts)) {
ERROR("ptp %s: failed to initialize network\n", rtOpts->name);
return FALSE;
}
/* Initialize the PTP data sets */
initData(rtOpts, ptpClock);
/* initialize other stuff */
if (!servo_init(rtOpts, &ptpClock->servo, ptpClock->interface->clock)) {
ERROR("ptp %s: failed to initialize servo\n", rtOpts->name);
toState(PTPD_FAULTY, rtOpts, ptpClock);
return FALSE;
}
managementInit(rtOpts, ptpClock);
m1(rtOpts, ptpClock);
msgPackHeader(ptpClock->msgObuf, sizeof ptpClock->msgObuf,
ptpClock, PTPD_MSG_SYNC);
if (rtOpts->node_type == PTPD_NODE_CLOCK) {
toState(PTPD_LISTENING, rtOpts, ptpClock);
} else {
toState(PTPD_DISABLED, rtOpts, ptpClock);
}
return TRUE;
}
Boolean
doInitInterface(InterfaceOpts *ifOpts, PtpInterface *ptpInterface)
{
/* In case we are re-initializing, shutdown and then
* initialize networking.
*/
netShutdown(&ptpInterface->transport);
/* initialize networking */
/* Initialize networking */
if(ifOpts->physIface == NULL) {
WARNING("no physical interface currently available; not starting networking\n");
ptpInterface->clock = sfptpd_interface_get_clock(ptpInterface->interface);
return TRUE;
} else if (!netInit(&ptpInterface->transport, ifOpts, ptpInterface)) {
ERROR("failed to initialize network\n");
return FALSE;
}
return TRUE;
}
/* handle a timer tick */
void
doTimerTick(RunTimeOpts *rtOpts, PtpClock *ptpClock)
{
UInteger8 state;
/* Update the timers */
timerTick(ptpClock->itimer);
/* Process record_update (BMC algorithm) before everything else */
switch (ptpClock->portState) {
case PTPD_LISTENING:
case PTPD_PASSIVE:
case PTPD_SLAVE:
case PTPD_MASTER:
/*State decision Event*/
/* If we received a valid Announce message
* and can use it (record_update),
* or we received a SET management message that
* changed an attribute in ptpClock,
* then run the BMC algorithm
*/
if (ptpClock->record_update) {
DBG2("event STATE_DECISION_EVENT\n");
ptpClock->record_update = FALSE;
state = bmc(&ptpClock->foreign, rtOpts, ptpClock);
if (state != ptpClock->portState)
toState(state, rtOpts, ptpClock);
}
break;
default:
break;
}
switch(ptpClock->portState) {
case PTPD_FAULTY:
/* If the restart timer has expired, clear fault and attempt
* to re-initialise. Otherwise sleep until the next SIGALRM */
if (timerExpired(FAULT_RESTART_TIMER, ptpClock->itimer)) {
DBG("event FAULT_CLEARED\n");
timerStop(FAULT_RESTART_TIMER, ptpClock->itimer);
toState(PTPD_INITIALIZING, rtOpts, ptpClock);
}
break;
case PTPD_LISTENING:
case PTPD_UNCALIBRATED:
case PTPD_SLAVE:
/* passive mode behaves like the SLAVE state, in order to wait for the announce
* timeout of the current active master */
case PTPD_PASSIVE:
/*
* handle SLAVE timers:
* - No Announce message was received
* - No Sync message was received
* - No DelayResponse message was received
* - Time to send new delayReq (miss of delayResp is not monitored explicitelly)
*/
if (timerExpired(ANNOUNCE_RECEIPT_TIMER, ptpClock->itimer)) {
WARNING("ptp %s: failed to receive Announce within %0.3Lf seconds\n",
rtOpts->name,
(ptpClock->announceReceiptTimeout * powl(2,ptpClock->logAnnounceInterval)));
ptpClock->counters.announceTimeouts++;
if (!ptpClock->slaveOnly &&
ptpClock->clockQuality.clockClass != SLAVE_ONLY_CLOCK_CLASS) {
m1(rtOpts, ptpClock);
toState(PTPD_MASTER, rtOpts, ptpClock);
} else {
/*
* Force a reset when getting a timeout in state listening, that will lead to an IGMP reset
* previously this was not the case when we were already in LISTENING mode
*/
toState(PTPD_LISTENING, rtOpts, ptpClock);
}
}
if (timerExpired(FOREIGN_MASTER_TIMER, ptpClock->itimer)) {
DBGV("event FOREIGN_MASTER_TIME_CHECK expires\n");
timerStart(FOREIGN_MASTER_TIMER,
(FOREIGN_MASTER_TIME_CHECK * powl(2,ptpClock->logAnnounceInterval)),
ptpClock->itimer);
struct timespec threshold;
/* Expire old foreign master records */
getForeignMasterExpiryTime(ptpClock, &threshold);
expireForeignMasterRecords(&ptpClock->foreign, &threshold);
}
if (timerExpired(SYNC_RECEIPT_TIMER, ptpClock->itimer)) {
LongDouble interval =
ptpClock->syncReceiptTimeout * powl(2,ptpClock->logSyncInterval);
ptpClock->sync_missing_interval += interval;
if (ptpClock->sync_missing_interval >= ptpClock->sync_missing_next_warning) {
WARNING("ptp %s: failed to receive Sync for sequence number %d for %0.1Lf seconds\n",
rtOpts->name,
(ptpClock->recvSyncSequenceId + 1) & 0xffff,
ptpClock->sync_missing_interval);
ptpClock->sync_missing_next_warning *= 2.0;
}
/* Increment the timeout stat and set the alarm */
SYNC_MODULE_ALARM_SET(ptpClock->portAlarms, NO_SYNC_PKTS);
ptpClock->counters.syncTimeouts++;
/* Record the fact that the data is missing */
servo_missing_m2s_ts(&ptpClock->servo);
/* Restart the missing sync timer */
timerStart(SYNC_RECEIPT_TIMER, interval, ptpClock->itimer);
}
if (timerExpired(DELAYRESP_RECEIPT_TIMER, ptpClock->itimer)) {
WARNING("ptp %s: failed to receive DelayResp for DelayReq sequence number %d\n",
rtOpts->name,
(ptpClock->sentDelayReqSequenceId - 1) & 0xffff);
/* Record the fact that we didn't get a timely response
* and set the alarm if it's happened too many times. */
ptpClock->sequentialMissingDelayResps++;
if (ptpClock->sequentialMissingDelayResps >= DELAY_RESP_MISSING_ALARM_THRESHOLD) {
SYNC_MODULE_ALARM_SET(ptpClock->portAlarms, NO_DELAY_RESPS);
ptpClock->sequentialMissingDelayResps = DELAY_RESP_MISSING_ALARM_THRESHOLD;
}
ptpClock->counters.delayRespTimeouts++;
/* Record the data as missing */
servo_missing_s2m_ts(&ptpClock->servo);
/* Stop the response receipt timer and start the timer
* to issue the next Delay Request. */
timerStop(DELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
/* If in hybrid mode and it has never succeeded, increment the
* failure count unless not multicast capable */
if ((ptpClock->effective_comm_caps.delayRespCapabilities & PTPD_COMM_UNICAST_CAPABLE) &&
(ptpClock->effective_comm_caps.delayRespCapabilities & PTPD_COMM_MULTICAST_CAPABLE) &&
(ptpClock->unicast_delay_resp_failures >= 0)) {
ptpClock->unicast_delay_resp_failures++;
if (ptpClock->unicast_delay_resp_failures >= PTPD_HYBRID_MODE_DELAY_RESP_MAX_FAILURES) {
ptpClock->effective_comm_caps.delayRespCapabilities &= ~PTPD_COMM_UNICAST_CAPABLE;
WARNING("ptp %s: failed to receive DelayResp %d times in "
"hybrid mode. Reverting to multicast mode.\n",
rtOpts->name,
PTPD_HYBRID_MODE_DELAY_RESP_MAX_FAILURES);
}
}
timerStart_random(DELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinDelayReqInterval),
ptpClock->itimer);
}
if (timerExpired(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer)) {
/* We only make a fuss about failure to receive a
* response in the slave state. */
if (ptpClock->portState == PTPD_SLAVE) {
WARNING("ptp %s: failed to receive PDelayResp for "
"PDelayReq sequence number %d\n",
rtOpts->name,
(ptpClock->sentPDelayReqSequenceId - 1) & 0xffff);
/* Record the fact that we didn't get a timely response,
* and set the alarm if it's happened too many times. */
ptpClock->sequentialMissingDelayResps++;
if (ptpClock->sequentialMissingDelayResps >= DELAY_RESP_MISSING_ALARM_THRESHOLD) {
SYNC_MODULE_ALARM_SET(ptpClock->portAlarms, NO_DELAY_RESPS);
ptpClock->sequentialMissingDelayResps = DELAY_RESP_MISSING_ALARM_THRESHOLD;
}
ptpClock->counters.delayRespTimeouts++;
}
/* Record the data as missing */
servo_missing_p2p_ts(&ptpClock->servo);
/* Stop the response receipt timer and start the timer
* to issue the next peer delay request. */
timerStop(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
if (timerExpired(OPERATOR_MESSAGES_TIMER, ptpClock->itimer)) {
servo_reset_operator_messages(&ptpClock->servo);
}
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_E2E) &&
timerExpired(DELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
DBG2("event DELAYREQ_INTERVAL_TIMEOUT_EXPIRES\n");
issueDelayReq(rtOpts,ptpClock);
} else if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
timerExpired(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
DBGV("event PDELAYREQ_INTERVAL_TIMEOUT_EXPIRES\n");
issuePDelayReq(rtOpts,ptpClock);
}
break;
case PTPD_MASTER:
/*
* handle MASTER timers:
* - Time to send new Sync
* - Time to send new Announce
* - Time to send new PathDelay
* (DelayResp has no timer - as these are sent and retransmitted by the slaves)
*/
if (timerExpired(SYNC_INTERVAL_TIMER, ptpClock->itimer)) {
DBGV("event SYNC_INTERVAL_TIMEOUT_EXPIRES\n");
issueSync(rtOpts, ptpClock);
}
if (timerExpired(ANNOUNCE_INTERVAL_TIMER, ptpClock->itimer)) {
DBGV("event ANNOUNCE_INTERVAL_TIMEOUT_EXPIRES\n");
issueAnnounce(rtOpts, ptpClock);
}
if (timerExpired(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer)) {
/* Record the data as missing */
servo_missing_p2p_ts(&ptpClock->servo);
/* Stop the response receipt timer and start the timer
* to issue the next peer delay request. */
timerStop(PDELAYRESP_RECEIPT_TIMER, ptpClock->itimer);
timerStart(PDELAYREQ_INTERVAL_TIMER,
powl(2,ptpClock->logMinPdelayReqInterval),
ptpClock->itimer);
}
if ((ptpClock->delayMechanism == PTPD_DELAY_MECHANISM_P2P) &&
timerExpired(PDELAYREQ_INTERVAL_TIMER, ptpClock->itimer)) {
DBGV("event PDELAYREQ_INTERVAL_TIMEOUT_EXPIRES\n");
issuePDelayReq(rtOpts,ptpClock);
}
if (rtOpts->ifOpts->masterRefreshIgmp &&
(rtOpts->comm_caps.syncCapabilities & PTPD_COMM_MULTICAST_CAPABLE ||
rtOpts->comm_caps.delayRespCapabilities & PTPD_COMM_MULTICAST_CAPABLE) &&
timerExpired(MASTER_IGMP_REFRESH_TIMER, ptpClock->interface->itimer)) {
DBGV("Periodic IGMP refresh - next in %d seconds...\n",
rtOpts->ifOpts->masterIgmpRefreshInterval);
netRefreshIGMP(&ptpClock->interface->transport, rtOpts->ifOpts, ptpClock->interface);
}
if (ptpClock->slaveOnly ||
(ptpClock->clockQuality.clockClass == SLAVE_ONLY_CLOCK_CLASS))
toState(PTPD_LISTENING, rtOpts, ptpClock);
break;
case PTPD_DISABLED:
break;
default:
DBG("doTimerTick() unrecognized state\n");
break;
}
}
static Boolean
isFromCurrentParent(const PtpClock *ptpClock, const MsgHeader* header)
{
return(!memcmp(
ptpClock->parentPortIdentity.clockIdentity,
header->sourcePortIdentity.clockIdentity,
CLOCK_IDENTITY_LENGTH) &&
(ptpClock->parentPortIdentity.portNumber ==
header->sourcePortIdentity.portNumber));
}
static bool checkACL(enum ptpd_acl_type acl_type,
struct in_addr address,
const char *name,
PtpInterface *ptpInterface,
InterfaceOpts *ifOpts,
acl_bitmap_t *checked,
acl_bitmap_t *passed) {
Ipv4AccessList *acl = NULL;
bool pass = false;
if ((*checked & acl_type) != 0) {
return ((*passed & acl_type) ? true : false);
}
switch (acl_type) {
case PTPD_ACL_MANAGEMENT:
acl = ptpInterface->transport.managementAcl;
if (!ifOpts->managementAclEnabled) {
pass = true;
goto result;
}
break;
case PTPD_ACL_TIMING:
acl = ptpInterface->transport.timingAcl;
if (!ifOpts->timingAclEnabled) {
pass = true;
goto result;
}
break;
case PTPD_ACL_MONITORING:
acl = ptpInterface->transport.monitoringAcl;
if (!ifOpts->monitoringAclEnabled) {
pass = true;
goto result;
}
break;
}
if (acl == NULL) {
ERROR("unknown ACL type %d\n", acl_type);
/* Do not save the result because the input was nonsense */
return false;
}
if (!matchIpv4AccessList(acl, ntohl(address.s_addr))) {
if (name == NULL) {
DBG("ACL type %d denied message from %s\n", acl_type, inet_ntoa(address));
} else {
DBG("ACL dropped %s from %s\n", inet_ntoa(address));
}
} else {
if (name == NULL) {
DBG("ACL type %d accepted message from %s\n", acl_type, inet_ntoa(address));
} else {
DBG2("ACL accepted %s from %s\n", inet_ntoa(address));
}
pass = true;
}
result:
*checked |= acl_type;
if (pass) {
*passed |= acl_type;
}
return pass;
}
static bool checkACLmask(acl_bitmap_t mask,
struct in_addr address,
PtpInterface *ptpInterface,
InterfaceOpts *ifOpts,
acl_bitmap_t *checked,
acl_bitmap_t *passed) {
int i;
acl_bitmap_t bit;
for (i = 0; mask != 0; i++) {
bit = mask & (1 << i);
if (bit != 0) {
if (!checkACL(bit,
address,
NULL,
ptpInterface,
ifOpts,
checked,
passed)) {
return false;
}
mask &= ~bit;
}
}
return true;
}
static void
processMessage(InterfaceOpts *ifOpts, PtpInterface *ptpInterface, TimeInternal *timestamp,
Boolean timestampValid, ssize_t length)
{
PtpClock *port;
ssize_t unpack_result;
acl_bitmap_t acls_checked = 0;
acl_bitmap_t acls_passed = 0;
if (length < PTPD_HEADER_LENGTH) {
DBG("message shorter than header length (%zd, %d)\n",
length, PTPD_HEADER_LENGTH);
ptpInterface->counters.messageFormatErrors++;
return;
}
unpack_result = msgUnpackHeader(ptpInterface->msgIbuf, length, &ptpInterface->msgTmpHeader);
if (!UNPACK_OK(unpack_result)) {
ERROR("unpacking header\n");
ptpInterface->counters.messageFormatErrors++;
return;
}
/* If the packet is not from us and is from a non-zero source address
* check ACLs */
if (ptpInterface->transport.lastRecvAddrLen != 0 &&
!hostAddressesEqual(&ptpInterface->transport.lastRecvAddr,
ptpInterface->transport.lastRecvAddrLen,
&ptpInterface->transport.interfaceAddr,
ptpInterface->transport.interfaceAddrLen)) {
struct sockaddr_in *in = ((struct sockaddr_in *) &ptpInterface->transport.lastRecvAddr);
ptpInterface->transport.lastRecvHost[0] = '\0';
getnameinfo((struct sockaddr *) &ptpInterface->transport.lastRecvAddr,
ptpInterface->transport.lastRecvAddrLen,
ptpInterface->transport.lastRecvHost,
sizeof ptpInterface->transport.lastRecvHost,
NULL, 0, NI_NUMERICHOST);
if (ptpInterface->msgTmpHeader.messageType == PTPD_MSG_MANAGEMENT) {
if (!checkACL(PTPD_ACL_MANAGEMENT, in->sin_addr,
"management message",
ptpInterface, ifOpts, &acls_checked, &acls_passed)) {
ptpInterface->counters.aclManagementDiscardedMessages++;
return;
}
} else if (ifOpts->timingAclEnabled) {
if (!checkACL(PTPD_ACL_TIMING, in->sin_addr,
"timing message",
ptpInterface, ifOpts, &acls_checked, &acls_passed)) {
ptpInterface->counters.aclTimingDiscardedMessages++;
return;
}
}
}
if (ptpInterface->msgTmpHeader.versionPTP != PTPD_PROTOCOL_VERSION) {
DBG2("ignore version %d message\n",
ptpInterface->msgTmpHeader.versionPTP);
ptpInterface->counters.discardedMessages++;
ptpInterface->counters.versionMismatchErrors++;
return;
}
PtpClock *monitoringPort = NULL;
for (port = ptpInterface->ports; port; port = port->next) {
if (port->rtOpts.node_type == PTPD_NODE_MONITOR)
monitoringPort = port;
if (port->domainNumber == ptpInterface->msgTmpHeader.domainNumber)
break;
}
/* Divert any traffic for unhandled domains to the monitoring
port if one is defined. */
if (port == NULL && monitoringPort != NULL)
port = monitoringPort;
if (port != NULL) {
DBG2("delivering message from %s for domain %d to port %d (instance %s)\n",
ptpInterface->ifOpts.ifaceName,
ptpInterface->msgTmpHeader.domainNumber,
port->portIdentity.portNumber,
port->rtOpts.name);
processPortMessage(&port->rtOpts, port, timestamp,