File: tlv.c

package info (click to toggle)
linuxptp 4.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,536 kB
  • sloc: ansic: 26,119; sh: 92; makefile: 87
file content (1249 lines) | stat: -rw-r--r-- 37,163 bytes parent folder | download | duplicates (2)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
/**
 * @file tlv.c
 * @note Copyright (C) 2012 Richard Cochran <richardcochran@gmail.com>
 *
 * 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 <arpa/inet.h>
#include <errno.h>
#include <stdbool.h>
#include <stdlib.h>
#include <string.h>

#include "port.h"
#include "tlv.h"
#include "msg.h"

#define HTONS(x) (x) = htons(x)
#define HTONL(x) (x) = htonl(x)
#define NTOHS(x) (x) = ntohs(x)
#define NTOHL(x) (x) = ntohl(x)

#define TLV_LENGTH_INVALID(tlv, type) \
	(tlv->length < sizeof(struct type) - sizeof(struct TLV))

uint8_t ieee8021_id[3] = { IEEE_802_1_COMMITTEE };
uint8_t ieeec37_238_id[3] = { IEEE_C37_238_PROFILE };
uint8_t itu_t_id[3] = { ITU_T_COMMITTEE };

static TAILQ_HEAD(tlv_pool, tlv_extra) tlv_pool =
	TAILQ_HEAD_INITIALIZER(tlv_pool);

static void scaled_ns_n2h(ScaledNs *sns)
{
	sns->nanoseconds_msb = ntohs(sns->nanoseconds_msb);
	sns->nanoseconds_lsb = net2host64(sns->nanoseconds_lsb);
	sns->fractional_nanoseconds = ntohs(sns->fractional_nanoseconds);
}

static void scaled_ns_h2n(ScaledNs *sns)
{
	sns->nanoseconds_msb = htons(sns->nanoseconds_msb);
	sns->nanoseconds_lsb = host2net64(sns->nanoseconds_lsb);
	sns->fractional_nanoseconds = htons(sns->fractional_nanoseconds);
}

static void timestamp_host2net(struct Timestamp *t)
{
	HTONL(t->seconds_lsb);
	HTONS(t->seconds_msb);
	HTONL(t->nanoseconds);
}

static void timestamp_net2host(struct Timestamp *t)
{
	NTOHL(t->seconds_lsb);
	NTOHS(t->seconds_msb);
	NTOHL(t->nanoseconds);
}

static uint16_t flip16(void *p)
{
	uint16_t v;
	memcpy(&v, p, sizeof(v));
	v = htons(v);
	memcpy(p, &v, sizeof(v));
	return v;
}

static void host2net32_unaligned(void *p)
{
	int32_t v;
	memcpy(&v, p, sizeof(v));
	v = htonl(v);
	memcpy(p, &v, sizeof(v));
}

static void net2host32_unaligned(void *p)
{
	int32_t v;
	memcpy(&v, p, sizeof(v));
	v = ntohl(v);
	memcpy(p, &v, sizeof(v));
}

static int64_t host2net64_unaligned(void *p)
{
	int64_t v;
	memcpy(&v, p, sizeof(v));
	v = host2net64(v);
	memcpy(p, &v, sizeof(v));
	return v;
}

static int64_t net2host64_unaligned(void *p)
{
	int64_t v;
	memcpy(&v, p, sizeof(v));
	v = net2host64(v);
	memcpy(p, &v, sizeof(v));
	return v;
}

static size_t tlv_array_count(struct TLV *tlv, size_t base_size, size_t item_size)
{
	return (tlv->length - base_size) / item_size;
}

static bool tlv_array_invalid(struct TLV *tlv, size_t base_size, size_t item_size)
{
	size_t expected_length, n_items;

	n_items = tlv_array_count(tlv, base_size, item_size);

	expected_length = base_size + n_items * item_size;

	return (tlv->length == expected_length) ? false : true;
}

static int alttime_offset_post_recv(struct tlv_extra *extra)
{
	struct TLV *tlv = extra->tlv;
	struct alternate_time_offset_indicator_tlv *atoi =
		(struct alternate_time_offset_indicator_tlv *) tlv;

	if (tlv->length < sizeof(struct alternate_time_offset_indicator_tlv) +
	    atoi->displayName.length - sizeof(struct TLV)) {
		return -EBADMSG;
	}

	/* Message alignment broken by design. */
	net2host32_unaligned(&atoi->currentOffset);
	net2host32_unaligned(&atoi->jumpSeconds);
	flip16(&atoi->timeOfNextJump.seconds_msb);
	net2host32_unaligned(&atoi->timeOfNextJump.seconds_lsb);

	return 0;
}

static void alttime_offset_pre_send(struct tlv_extra *extra)
{
	struct alternate_time_offset_indicator_tlv *atoi;

	atoi = (struct alternate_time_offset_indicator_tlv *) extra->tlv;

	/* Message alignment broken by design. */
	host2net32_unaligned(&atoi->currentOffset);
	host2net32_unaligned(&atoi->jumpSeconds);
	flip16(&atoi->timeOfNextJump.seconds_msb);
	host2net32_unaligned(&atoi->timeOfNextJump.seconds_lsb);
}

static int mgt_post_recv(struct management_tlv *m, uint16_t data_len,
			 struct tlv_extra *extra)
{
	struct alternate_time_offset_properties *atop;
	struct alternate_time_offset_name *aton;
	struct ieee_c37_238_settings_np *pwr;
	struct unicast_master_table_np *umtn;
	struct grandmaster_settings_np *gsn;
	struct port_service_stats_np *pssn;
	struct mgmt_clock_description *cd;
	struct unicast_master_entry *ume;
	struct subscribe_events_np *sen;
	struct port_properties_np *ppn;
	struct port_hwclock_np *phn;
	struct timePropertiesDS *tp;
	struct time_status_np *tsn;
	struct port_stats_np *psn;
	int extra_len = 0, i, len;
	struct port_ds_np *pdsnp;
	struct currentDS *cds;
	struct defaultDS *dds;
	struct parentDS *pds;
	struct portDS *p;
	uint8_t *buf;
	uint16_t u16;

	switch (m->id) {
	case MID_CLOCK_DESCRIPTION:
		cd = &extra->cd;
		buf = m->data;
		len = data_len;

		cd->clockType = (UInteger16 *) buf;
		buf += sizeof(*cd->clockType);
		len -= sizeof(*cd->clockType);
		if (len < 0)
			goto bad_length;
		flip16(cd->clockType);

		cd->physicalLayerProtocol = (struct PTPText *) buf;
		buf += sizeof(struct PTPText);
		len -= sizeof(struct PTPText);
		if (len < 0)
			goto bad_length;

		buf += cd->physicalLayerProtocol->length;
		len -= cd->physicalLayerProtocol->length;
		if (len < 0)
			goto bad_length;

		cd->physicalAddress = (struct PhysicalAddress *) buf;
		buf += sizeof(struct PhysicalAddress);
		len -= sizeof(struct PhysicalAddress);
		if (len < 0)
			goto bad_length;

		u16 = flip16(&cd->physicalAddress->length);
		if (u16 > TRANSPORT_ADDR_LEN)
			goto bad_length;
		buf += u16;
		len -= u16;
		if (len < 0)
			goto bad_length;

		cd->protocolAddress = (struct PortAddress *) buf;
		buf += sizeof(struct PortAddress);
		len -= sizeof(struct PortAddress);
		if (len < 0)
			goto bad_length;

		flip16(&cd->protocolAddress->networkProtocol);
		u16 = flip16(&cd->protocolAddress->addressLength);
		if (u16 > TRANSPORT_ADDR_LEN)
			goto bad_length;
		buf += u16;
		len -= u16;
		if (len < 0)
			goto bad_length;

		cd->manufacturerIdentity = buf;
		buf += OUI_LEN + 1;
		len -= OUI_LEN + 1;
		if (len < 0)
			goto bad_length;

		cd->productDescription = (struct PTPText *) buf;
		buf += sizeof(struct PTPText);
		len -= sizeof(struct PTPText);
		if (len < 0)
			goto bad_length;

		buf += cd->productDescription->length;
		len -= cd->productDescription->length;
		if (len < 0)
			goto bad_length;

		cd->revisionData = (struct PTPText *) buf;
		buf += sizeof(struct PTPText);
		len -= sizeof(struct PTPText);
		if (len < 0)
			goto bad_length;

		buf += cd->revisionData->length;
		len -= cd->revisionData->length;
		if (len < 0)
			goto bad_length;

		cd->userDescription = (struct PTPText *) buf;
		buf += sizeof(struct PTPText);
		len -= sizeof(struct PTPText);
		if (len < 0)
			goto bad_length;

		buf += cd->userDescription->length;
		len -= cd->userDescription->length;
		if (len < 0)
			goto bad_length;

		cd->profileIdentity = buf;
		buf += PROFILE_ID_LEN;
		len -= PROFILE_ID_LEN;
		if (len < 0)
			goto bad_length;

		extra_len = buf - m->data;
		break;
	case MID_USER_DESCRIPTION:
		if (data_len < sizeof(struct PTPText))
			goto bad_length;
		extra->cd.userDescription = (struct PTPText *) m->data;
		extra_len = sizeof(struct PTPText);
		extra_len += extra->cd.userDescription->length;
		break;
	case MID_DEFAULT_DATA_SET:
		if (data_len != sizeof(struct defaultDS))
			goto bad_length;
		dds = (struct defaultDS *) m->data;
		dds->numberPorts = ntohs(dds->numberPorts);
		dds->clockQuality.offsetScaledLogVariance =
			ntohs(dds->clockQuality.offsetScaledLogVariance);
		break;
	case MID_CURRENT_DATA_SET:
		if (data_len != sizeof(struct currentDS))
			goto bad_length;
		cds = (struct currentDS *) m->data;
		cds->stepsRemoved = ntohs(cds->stepsRemoved);
		cds->offsetFromMaster = net2host64(cds->offsetFromMaster);
		cds->meanPathDelay = net2host64(cds->meanPathDelay);
		break;
	case MID_PARENT_DATA_SET:
		if (data_len != sizeof(struct parentDS))
			goto bad_length;
		pds = (struct parentDS *) m->data;
		pds->parentPortIdentity.portNumber =
			ntohs(pds->parentPortIdentity.portNumber);
		pds->observedParentOffsetScaledLogVariance =
			ntohs(pds->observedParentOffsetScaledLogVariance);
		pds->observedParentClockPhaseChangeRate =
			ntohl(pds->observedParentClockPhaseChangeRate);
		pds->grandmasterClockQuality.offsetScaledLogVariance =
			ntohs(pds->grandmasterClockQuality.offsetScaledLogVariance);
		break;
	case MID_TIME_PROPERTIES_DATA_SET:
		if (data_len != sizeof(struct timePropertiesDS))
			goto bad_length;
		tp = (struct timePropertiesDS *) m->data;
		tp->currentUtcOffset = ntohs(tp->currentUtcOffset);
		break;
	case MID_PORT_DATA_SET:
		if (data_len != sizeof(struct portDS))
			goto bad_length;
		p = (struct portDS *) m->data;
		p->portIdentity.portNumber = ntohs(p->portIdentity.portNumber);
		p->peerMeanPathDelay = net2host64(p->peerMeanPathDelay);
		break;
	case MID_ALTERNATE_TIME_OFFSET_NAME:
		aton = (struct alternate_time_offset_name *) m->data;
		if (data_len < sizeof(*aton)) {
			goto bad_length;
		}
		extra_len = sizeof(*aton);
		extra_len += aton->displayName.length;
		break;
	case MID_ALTERNATE_TIME_OFFSET_PROPERTIES:
		atop = (struct alternate_time_offset_properties *) m->data;
		if (data_len != sizeof(*atop)) {
			goto bad_length;
		}
		/* Message alignment broken by design. */
		net2host32_unaligned(&atop->currentOffset);
		net2host32_unaligned(&atop->jumpSeconds);
		flip16(&atop->timeOfNextJump.seconds_msb);
		net2host32_unaligned(&atop->timeOfNextJump.seconds_lsb);
		break;
	case MID_TIME_STATUS_NP:
		if (data_len != sizeof(struct time_status_np))
			goto bad_length;
		tsn = (struct time_status_np *) m->data;
		tsn->master_offset = net2host64(tsn->master_offset);
		tsn->ingress_time = net2host64(tsn->ingress_time);
		tsn->cumulativeScaledRateOffset = ntohl(tsn->cumulativeScaledRateOffset);
		tsn->scaledLastGmPhaseChange = ntohl(tsn->scaledLastGmPhaseChange);
		tsn->gmTimeBaseIndicator = ntohs(tsn->gmTimeBaseIndicator);
		scaled_ns_n2h(&tsn->lastGmPhaseChange);
		tsn->gmPresent = ntohl(tsn->gmPresent);
		break;
	case MID_GRANDMASTER_SETTINGS_NP:
		if (data_len != sizeof(struct grandmaster_settings_np))
			goto bad_length;
		gsn = (struct grandmaster_settings_np *) m->data;
		gsn->clockQuality.offsetScaledLogVariance =
			ntohs(gsn->clockQuality.offsetScaledLogVariance);
		gsn->utc_offset = ntohs(gsn->utc_offset);
		break;
	case MID_PORT_DATA_SET_NP:
		if (data_len != sizeof(struct port_ds_np))
			goto bad_length;
		pdsnp = (struct port_ds_np *) m->data;
		pdsnp->neighborPropDelayThresh = ntohl(pdsnp->neighborPropDelayThresh);
		pdsnp->asCapable = ntohl(pdsnp->asCapable);
		break;
	case MID_SUBSCRIBE_EVENTS_NP:
		if (data_len != sizeof(struct subscribe_events_np))
			goto bad_length;
		sen = (struct subscribe_events_np *)m->data;
		sen->duration = ntohs(sen->duration);
		break;
	case MID_PORT_PROPERTIES_NP:
		if (data_len < sizeof(struct port_properties_np))
			goto bad_length;
		ppn = (struct port_properties_np *)m->data;
		ppn->portIdentity.portNumber = ntohs(ppn->portIdentity.portNumber);
		extra_len = sizeof(struct port_properties_np);
		extra_len += ppn->interface.length;
		break;
	case MID_PORT_STATS_NP:
		if (data_len < sizeof(struct port_stats_np))
			goto bad_length;
		psn = (struct port_stats_np *)m->data;
		psn->portIdentity.portNumber =
			ntohs(psn->portIdentity.portNumber);
		for (i = 0 ; i < MAX_MESSAGE_TYPES; i++) {
			psn->stats.rxMsgType[i] = __le64_to_cpu(psn->stats.rxMsgType[i]);
			psn->stats.txMsgType[i] = __le64_to_cpu(psn->stats.txMsgType[i]);
		}
		extra_len = sizeof(struct port_stats_np);
		break;
	case MID_PORT_SERVICE_STATS_NP:
		if (data_len < sizeof(struct port_service_stats_np))
			goto bad_length;
		pssn = (struct port_service_stats_np *)m->data;
		pssn->portIdentity.portNumber =
			htons(pssn->portIdentity.portNumber);
		pssn->stats.announce_timeout =
			__le64_to_cpu(pssn->stats.announce_timeout);
		pssn->stats.sync_timeout =
			__le64_to_cpu(pssn->stats.sync_timeout);
		pssn->stats.delay_timeout =
			__le64_to_cpu(pssn->stats.delay_timeout);
		pssn->stats.unicast_service_timeout =
			__le64_to_cpu(pssn->stats.unicast_service_timeout);
		pssn->stats.unicast_request_timeout =
			__le64_to_cpu(pssn->stats.unicast_request_timeout);
		pssn->stats.master_announce_timeout =
			__le64_to_cpu(pssn->stats.master_announce_timeout);
		pssn->stats.master_sync_timeout =
			__le64_to_cpu(pssn->stats.master_sync_timeout);
		pssn->stats.qualification_timeout =
			__le64_to_cpu(pssn->stats.qualification_timeout);
		pssn->stats.sync_mismatch =
			__le64_to_cpu(pssn->stats.sync_mismatch);
		pssn->stats.followup_mismatch =
			__le64_to_cpu(pssn->stats.followup_mismatch);
		extra_len = sizeof(struct port_service_stats_np);
		break;
	case MID_UNICAST_MASTER_TABLE_NP:
		if (data_len < sizeof(struct unicast_master_table_np))
			goto bad_length;
		len = sizeof(struct unicast_master_table_np);
		umtn = (struct unicast_master_table_np *)m->data;
		umtn->actual_table_size =
			ntohs(umtn->actual_table_size);
		buf = (uint8_t *) umtn->unicast_masters;
		for (i = 0; i < umtn->actual_table_size; i++) {
			len += sizeof(struct unicast_master_entry);
			if (data_len < len)
				goto bad_length;
			ume = (struct unicast_master_entry *) buf;
			ume->port_identity.portNumber =
				ntohs(ume->port_identity.portNumber);
			ume->clock_quality.offsetScaledLogVariance =
				ntohs(ume->clock_quality.offsetScaledLogVariance);
			ume->address.networkProtocol =
				ntohs(ume->address.networkProtocol);
			ume->address.addressLength =
				ntohs(ume->address.addressLength);
			len += ume->address.addressLength;
			if (data_len < len)
				goto bad_length;
			buf += sizeof(*ume) + ume->address.addressLength;
		}
		break;
	case MID_PORT_HWCLOCK_NP:
		if (data_len < sizeof(struct port_hwclock_np))
			goto bad_length;
		phn = (struct port_hwclock_np *)m->data;
		phn->portIdentity.portNumber = ntohs(phn->portIdentity.portNumber);
		phn->phc_index = ntohl(phn->phc_index);
		extra_len = sizeof(struct port_hwclock_np);
		break;
	case MID_POWER_PROFILE_SETTINGS_NP:
		if (data_len < sizeof(struct ieee_c37_238_settings_np))
			goto bad_length;
		pwr = (struct ieee_c37_238_settings_np *)m->data;
		NTOHS(pwr->version);
		NTOHS(pwr->grandmasterID);
		NTOHL(pwr->grandmasterTimeInaccuracy);
		NTOHL(pwr->networkTimeInaccuracy);
		NTOHL(pwr->totalTimeInaccuracy);
		break;
	case MID_SAVE_IN_NON_VOLATILE_STORAGE:
	case MID_RESET_NON_VOLATILE_STORAGE:
	case MID_INITIALIZE:
	case MID_FAULT_LOG_RESET:
	case MID_ENABLE_PORT:
	case MID_DISABLE_PORT:
		if (data_len != 0)
			goto bad_length;
		break;
	}
	if (extra_len) {
		if (extra_len % 2)
			extra_len++;
		if (extra_len + sizeof(m->id) != m->length)
			goto bad_length;
	}
	return 0;
bad_length:
	return -EBADMSG;
}

static void mgt_pre_send(struct management_tlv *m, struct tlv_extra *extra)
{
	struct alternate_time_offset_properties *atop;
	struct ieee_c37_238_settings_np *pwr;
	struct unicast_master_table_np *umtn;
	struct grandmaster_settings_np *gsn;
	struct port_service_stats_np *pssn;
	struct mgmt_clock_description *cd;
	struct unicast_master_entry *ume;
	struct subscribe_events_np *sen;
	struct port_properties_np *ppn;
	struct port_hwclock_np *phn;
	struct timePropertiesDS *tp;
	struct time_status_np *tsn;
	struct port_stats_np *psn;
	struct port_ds_np *pdsnp;
	struct defaultDS *dds;
	struct currentDS *cds;
	struct parentDS *pds;
	struct portDS *p;
	uint8_t *buf;
	int i;

	switch (m->id) {
	case MID_CLOCK_DESCRIPTION:
		if (extra) {
			cd = &extra->cd;
			flip16(cd->clockType);
			flip16(&cd->physicalAddress->length);
			flip16(&cd->protocolAddress->networkProtocol);
			flip16(&cd->protocolAddress->addressLength);
		}
		break;
	case MID_DEFAULT_DATA_SET:
		dds = (struct defaultDS *) m->data;
		dds->numberPorts = htons(dds->numberPorts);
		dds->clockQuality.offsetScaledLogVariance =
			htons(dds->clockQuality.offsetScaledLogVariance);
		break;
	case MID_CURRENT_DATA_SET:
		cds = (struct currentDS *) m->data;
		cds->stepsRemoved = htons(cds->stepsRemoved);
		cds->offsetFromMaster = host2net64(cds->offsetFromMaster);
		cds->meanPathDelay = host2net64(cds->meanPathDelay);
		break;
	case MID_PARENT_DATA_SET:
		pds = (struct parentDS *) m->data;
		pds->parentPortIdentity.portNumber =
			htons(pds->parentPortIdentity.portNumber);
		pds->observedParentOffsetScaledLogVariance =
			htons(pds->observedParentOffsetScaledLogVariance);
		pds->observedParentClockPhaseChangeRate =
			htonl(pds->observedParentClockPhaseChangeRate);
		pds->grandmasterClockQuality.offsetScaledLogVariance =
			htons(pds->grandmasterClockQuality.offsetScaledLogVariance);
		break;
	case MID_TIME_PROPERTIES_DATA_SET:
		tp = (struct timePropertiesDS *) m->data;
		tp->currentUtcOffset = htons(tp->currentUtcOffset);
		break;
	case MID_PORT_DATA_SET:
		p = (struct portDS *) m->data;
		p->portIdentity.portNumber = htons(p->portIdentity.portNumber);
		p->peerMeanPathDelay = host2net64(p->peerMeanPathDelay);
		break;
	case MID_ALTERNATE_TIME_OFFSET_NAME:
		break;
	case MID_ALTERNATE_TIME_OFFSET_PROPERTIES:
		atop = (struct alternate_time_offset_properties *) m->data;
		/* Message alignment broken by design. */
		host2net32_unaligned(&atop->currentOffset);
		host2net32_unaligned(&atop->jumpSeconds);
		flip16(&atop->timeOfNextJump.seconds_msb);
		host2net32_unaligned(&atop->timeOfNextJump.seconds_lsb);
		break;
	case MID_TIME_STATUS_NP:
		tsn = (struct time_status_np *) m->data;
		tsn->master_offset = host2net64(tsn->master_offset);
		tsn->ingress_time = host2net64(tsn->ingress_time);
		tsn->cumulativeScaledRateOffset = htonl(tsn->cumulativeScaledRateOffset);
		tsn->scaledLastGmPhaseChange = htonl(tsn->scaledLastGmPhaseChange);
		tsn->gmTimeBaseIndicator = htons(tsn->gmTimeBaseIndicator);
		scaled_ns_h2n(&tsn->lastGmPhaseChange);
		tsn->gmPresent = htonl(tsn->gmPresent);
		break;
	case MID_GRANDMASTER_SETTINGS_NP:
		gsn = (struct grandmaster_settings_np *) m->data;
		gsn->clockQuality.offsetScaledLogVariance =
			htons(gsn->clockQuality.offsetScaledLogVariance);
		gsn->utc_offset = htons(gsn->utc_offset);
		break;
	case MID_PORT_DATA_SET_NP:
		pdsnp = (struct port_ds_np *) m->data;
		pdsnp->neighborPropDelayThresh = htonl(pdsnp->neighborPropDelayThresh);
		pdsnp->asCapable = htonl(pdsnp->asCapable);
		break;
	case MID_SUBSCRIBE_EVENTS_NP:
		sen = (struct subscribe_events_np *)m->data;
		sen->duration = htons(sen->duration);
		break;
	case MID_PORT_PROPERTIES_NP:
		ppn = (struct port_properties_np *)m->data;
		ppn->portIdentity.portNumber = htons(ppn->portIdentity.portNumber);
		break;
	case MID_PORT_STATS_NP:
		psn = (struct port_stats_np *)m->data;
		psn->portIdentity.portNumber =
			htons(psn->portIdentity.portNumber);
		for (i = 0 ; i < MAX_MESSAGE_TYPES; i++) {
			psn->stats.rxMsgType[i] = __cpu_to_le64(psn->stats.rxMsgType[i]);
			psn->stats.txMsgType[i] = __cpu_to_le64(psn->stats.txMsgType[i]);
		}
		break;
	case MID_PORT_SERVICE_STATS_NP:
		pssn = (struct port_service_stats_np *)m->data;
		pssn->portIdentity.portNumber =
			htons(pssn->portIdentity.portNumber);
		pssn->stats.announce_timeout =
			__cpu_to_le64(pssn->stats.announce_timeout);
		pssn->stats.sync_timeout =
			__cpu_to_le64(pssn->stats.sync_timeout);
		pssn->stats.delay_timeout =
			__cpu_to_le64(pssn->stats.delay_timeout);
		pssn->stats.unicast_service_timeout =
			__cpu_to_le64(pssn->stats.unicast_service_timeout);
		pssn->stats.unicast_request_timeout =
			__cpu_to_le64(pssn->stats.unicast_request_timeout);
		pssn->stats.master_announce_timeout =
			__cpu_to_le64(pssn->stats.master_announce_timeout);
		pssn->stats.master_sync_timeout =
			__cpu_to_le64(pssn->stats.master_sync_timeout);
		pssn->stats.qualification_timeout =
			__cpu_to_le64(pssn->stats.qualification_timeout);
		pssn->stats.sync_mismatch =
			__cpu_to_le64(pssn->stats.sync_mismatch);
		pssn->stats.followup_mismatch =
			__cpu_to_le64(pssn->stats.followup_mismatch);
		break;
	case MID_UNICAST_MASTER_TABLE_NP:
		umtn = (struct unicast_master_table_np *)m->data;
		buf = (uint8_t *) umtn->unicast_masters;
		for (i = 0; i < umtn->actual_table_size; i++) {
			ume = (struct unicast_master_entry *) buf;
			// update pointer before the conversion
			buf += sizeof(*ume) + ume->address.addressLength;
			ume->port_identity.portNumber =
				htons(ume->port_identity.portNumber);
			ume->clock_quality.offsetScaledLogVariance =
				htons(ume->clock_quality.offsetScaledLogVariance);
			ume->address.networkProtocol =
				htons(ume->address.networkProtocol);
			ume->address.addressLength =
				htons(ume->address.addressLength);
		}
		umtn->actual_table_size =
			htons(umtn->actual_table_size);
		break;
	case MID_PORT_HWCLOCK_NP:
		phn = (struct port_hwclock_np *)m->data;
		phn->portIdentity.portNumber = htons(phn->portIdentity.portNumber);
		phn->phc_index = htonl(phn->phc_index);
		break;
	case MID_POWER_PROFILE_SETTINGS_NP:
		pwr = (struct ieee_c37_238_settings_np *)m->data;
		HTONS(pwr->version);
		HTONS(pwr->grandmasterID);
		HTONL(pwr->grandmasterTimeInaccuracy);
		HTONL(pwr->networkTimeInaccuracy);
		HTONL(pwr->totalTimeInaccuracy);
		break;
	}
}

static int nsm_resp_post_recv(struct tlv_extra *extra)
{
	struct nsm_resp_tlv_head *head;
	struct TLV *tlv = extra->tlv;
	struct timePropertiesDS *tp;
	struct PortAddress *paddr;
	struct currentDS *cds;
	struct parentDS *pds;
	unsigned char *ptr;
	uint16_t expected;

	if (tlv->length < sizeof(*head) + sizeof(*extra->foot)
	    - sizeof(head->type) - sizeof(head->length)) {
		return -EBADMSG;
	}
	head = (struct nsm_resp_tlv_head *) tlv;
	paddr = &head->parent_addr;
	NTOHS(paddr->networkProtocol);
	NTOHS(paddr->addressLength);

	switch (paddr->networkProtocol) {
	case TRANS_UDP_IPV4:
		expected = 4;
		break;
	case TRANS_UDP_IPV6:
		expected = 16;
		break;
	case TRANS_IEEE_802_3:
		expected = 6;
		break;
	default:
		return -EBADMSG;
	}
	if (paddr->addressLength != expected) {
		return -EBADMSG;
	}
	if (tlv->length != sizeof(*head) + sizeof(*extra->foot) +
	    paddr->addressLength - sizeof(head->type) - sizeof(head->length)) {
		return -EBADMSG;
	}

	ptr = (unsigned char *) tlv;
	ptr += sizeof(*head) + paddr->addressLength;
	extra->foot = (struct nsm_resp_tlv_foot *) ptr;

	pds = &extra->foot->parent;
	cds = &extra->foot->current;
	tp = &extra->foot->timeprop;

	/*
	 * At this point the alignment only 2 bytes worst case.
	 * So we need to be careful with the 64 bit words.
	 */
	NTOHS(pds->parentPortIdentity.portNumber);
	NTOHS(pds->observedParentOffsetScaledLogVariance);
	NTOHL(pds->observedParentClockPhaseChangeRate);
	NTOHS(pds->grandmasterClockQuality.offsetScaledLogVariance);

	NTOHS(cds->stepsRemoved);
	net2host64_unaligned(&cds->offsetFromMaster);
	net2host64_unaligned(&cds->meanPathDelay);

	NTOHS(tp->currentUtcOffset);

	NTOHL(extra->foot->lastsync.seconds_lsb);
	NTOHS(extra->foot->lastsync.seconds_msb);
	NTOHL(extra->foot->lastsync.nanoseconds);

	return 0;
}

static void nsm_resp_pre_send(struct tlv_extra *extra)
{
	struct nsm_resp_tlv_head *head;
	struct timePropertiesDS *tp;
	struct PortAddress *paddr;
	struct currentDS *cds;
	struct parentDS *pds;

	head = (struct nsm_resp_tlv_head *) extra->tlv;
	paddr = &head->parent_addr;

	pds = &extra->foot->parent;
	cds = &extra->foot->current;
	tp = &extra->foot->timeprop;

	NTOHS(paddr->networkProtocol);
	NTOHS(paddr->addressLength);

	HTONS(pds->parentPortIdentity.portNumber);
	HTONS(pds->observedParentOffsetScaledLogVariance);
	HTONL(pds->observedParentClockPhaseChangeRate);
	HTONS(pds->grandmasterClockQuality.offsetScaledLogVariance);

	HTONS(cds->stepsRemoved);
	host2net64_unaligned(&cds->offsetFromMaster);
	host2net64_unaligned(&cds->meanPathDelay);

	HTONS(tp->currentUtcOffset);

	HTONL(extra->foot->lastsync.seconds_lsb);
	HTONS(extra->foot->lastsync.seconds_msb);
	HTONL(extra->foot->lastsync.nanoseconds);
}

static int org_post_recv(struct organization_tlv *org)
{
	struct ieee_c37_238_2017_tlv *p;
	struct follow_up_info_tlv *f;
	struct msg_interface_rate_tlv *m;

	if (0 == memcmp(org->id, ieee8021_id, sizeof(ieee8021_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return 0;
		}
		switch (org->subtype[2]) {
		case 1:
			if (org->length + sizeof(struct TLV) != sizeof(struct follow_up_info_tlv))
				goto bad_length;
			f = (struct follow_up_info_tlv *) org;
			f->cumulativeScaledRateOffset = ntohl(f->cumulativeScaledRateOffset);
			f->gmTimeBaseIndicator = ntohs(f->gmTimeBaseIndicator);
			scaled_ns_n2h(&f->lastGmPhaseChange);
			f->scaledLastGmPhaseChange = ntohl(f->scaledLastGmPhaseChange);
			break;

		case 2:
			if (org->length + sizeof(struct TLV) != sizeof(struct msg_interval_req_tlv))
				goto bad_length;
		}
	} else if (0 == memcmp(org->id, itu_t_id, sizeof(itu_t_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return 0;
		}
		switch (org->subtype[2]) {
		case 2:
			if (org->length + sizeof(struct TLV) != sizeof(struct msg_interface_rate_tlv))
				goto bad_length;
			m = (struct msg_interface_rate_tlv *)org;
			m->interfaceBitPeriod = net2host64(m->interfaceBitPeriod);
			m->numberOfBitsBeforeTimestamp = ntohs(m->numberOfBitsBeforeTimestamp);
			m->numberOfBitsAfterTimestamp = ntohs(m->numberOfBitsAfterTimestamp);
			break;
		}

	}
	if (0 == memcmp(org->id, ieeec37_238_id, sizeof(ieeec37_238_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return 0;
		}
		switch (org->subtype[2]) {
		case 1:
		case 2:
			/* Layout of 2011 and 2017 messages is compatible. */
			if (org->length + sizeof(struct TLV) !=
			    sizeof(struct ieee_c37_238_2017_tlv))
				goto bad_length;
			p = (struct ieee_c37_238_2017_tlv *) org;
			NTOHS(p->grandmasterID);
			NTOHL(p->reserved1);
			NTOHL(p->totalTimeInaccuracy);
			break;
		}
	}
	return 0;
bad_length:
	return -EBADMSG;
}

static void org_pre_send(struct organization_tlv *org)
{
	struct ieee_c37_238_2017_tlv *p;
	struct follow_up_info_tlv *f;
	struct msg_interface_rate_tlv *m;

	if (0 == memcmp(org->id, ieee8021_id, sizeof(ieee8021_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return;
		}
		switch (org->subtype[2]) {
		case 1:
			f = (struct follow_up_info_tlv *) org;
			f->cumulativeScaledRateOffset = htonl(f->cumulativeScaledRateOffset);
			f->gmTimeBaseIndicator = htons(f->gmTimeBaseIndicator);
			scaled_ns_h2n(&f->lastGmPhaseChange);
			f->scaledLastGmPhaseChange = htonl(f->scaledLastGmPhaseChange);
			break;
		}
	} else if (0 == memcmp(org->id, itu_t_id, sizeof(itu_t_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return;
		}
		switch (org->subtype[2]) {
		case 2:
			m = (struct msg_interface_rate_tlv *)org;
			m->interfaceBitPeriod = host2net64(m->interfaceBitPeriod);
			m->numberOfBitsBeforeTimestamp = htons(m->numberOfBitsBeforeTimestamp);
			m->numberOfBitsAfterTimestamp = htons(m->numberOfBitsAfterTimestamp);
			break;
		}
	}
	if (0 == memcmp(org->id, ieeec37_238_id, sizeof(ieeec37_238_id))) {
		if (org->subtype[0] || org->subtype[1]) {
			return;
		}
		switch (org->subtype[2]) {
		case 1:
		case 2:
			/* Layout of 2011 and 2017 messages is compatible. */
			p = (struct ieee_c37_238_2017_tlv *) org;
			HTONS(p->grandmasterID);
			HTONL(p->reserved1);
			HTONL(p->totalTimeInaccuracy);
			break;
		}
	}
}

static int slave_delay_timing_data_post_revc(struct tlv_extra *extra)
{
	struct slave_delay_timing_data_tlv *slave_delay =
		(struct slave_delay_timing_data_tlv *) extra->tlv;
	size_t base_size = sizeof(slave_delay->sourcePortIdentity), n_items;
	struct slave_delay_timing_record *record;

	if (tlv_array_invalid(extra->tlv, base_size, sizeof(*record))) {
		return -EBADMSG;
	}
	n_items = tlv_array_count(extra->tlv, base_size, sizeof(*record));
	record = slave_delay->record;

	NTOHS(slave_delay->sourcePortIdentity.portNumber);

	while (n_items) {
		NTOHS(record->sequenceId);
		timestamp_net2host(&record->delayOriginTimestamp);
		net2host64_unaligned(&record->totalCorrectionField);
		timestamp_net2host(&record->delayResponseTimestamp);
		n_items--;
		record++;
	}

	return 0;
}

static void slave_delay_timing_data_pre_send(struct tlv_extra *extra)
{
	struct slave_delay_timing_data_tlv *slave_delay =
		(struct slave_delay_timing_data_tlv *) extra->tlv;
	size_t base_size = sizeof(slave_delay->sourcePortIdentity), n_items;
	struct slave_delay_timing_record *record;

	n_items = tlv_array_count(extra->tlv, base_size, sizeof(*record));
	record = slave_delay->record;

	HTONS(slave_delay->sourcePortIdentity.portNumber);

	while (n_items) {
		HTONS(record->sequenceId);
		timestamp_host2net(&record->delayOriginTimestamp);
		host2net64_unaligned(&record->totalCorrectionField);
		timestamp_host2net(&record->delayResponseTimestamp);
		n_items--;
		record++;
	}
}

static int slave_rx_sync_timing_data_post_revc(struct tlv_extra *extra)
{
	struct slave_rx_sync_timing_data_tlv *slave_data =
		(struct slave_rx_sync_timing_data_tlv *) extra->tlv;
	size_t base_size = sizeof(slave_data->sourcePortIdentity), n_items;
	struct slave_rx_sync_timing_record *record;

	if (tlv_array_invalid(extra->tlv, base_size, sizeof(*record))) {
		return -EBADMSG;
	}
	n_items = tlv_array_count(extra->tlv, base_size, sizeof(*record));
	record = slave_data->record;

	NTOHS(slave_data->sourcePortIdentity.portNumber);

	while (n_items) {
		NTOHS(record->sequenceId);
		timestamp_net2host(&record->syncOriginTimestamp);
		net2host64_unaligned(&record->totalCorrectionField);
		NTOHL(record->scaledCumulativeRateOffset);
		timestamp_net2host(&record->syncEventIngressTimestamp);
		n_items--;
		record++;
	}

	return 0;
}

static void slave_rx_sync_timing_data_pre_send(struct tlv_extra *extra)
{
	struct slave_rx_sync_timing_data_tlv *slave_data =
		(struct slave_rx_sync_timing_data_tlv *) extra->tlv;
	size_t base_size = sizeof(slave_data->sourcePortIdentity), n_items;
	struct slave_rx_sync_timing_record *record;

	n_items = tlv_array_count(extra->tlv, base_size, sizeof(*record));
	record = slave_data->record;

	HTONS(slave_data->sourcePortIdentity.portNumber);

	while (n_items) {
		HTONS(record->sequenceId);
		timestamp_host2net(&record->syncOriginTimestamp);
		host2net64_unaligned(&record->totalCorrectionField);
		HTONL(record->scaledCumulativeRateOffset);
		timestamp_host2net(&record->syncEventIngressTimestamp);
		n_items--;
		record++;
	}
}

static int unicast_message_type_valid(uint8_t message_type)
{
	message_type >>= 4;
	switch (message_type) {
	case ANNOUNCE:
	case SYNC:
	case DELAY_RESP:
	case PDELAY_RESP:
		return 1;
	default:
		return 0;
	}
}

static int unicast_negotiation_post_recv(struct tlv_extra *extra)
{
	struct request_unicast_xmit_tlv *request;
	struct ack_cancel_unicast_xmit_tlv *ack;
	struct cancel_unicast_xmit_tlv *cancel;
	struct grant_unicast_xmit_tlv *grant;
	struct TLV *tlv = extra->tlv;

	switch (tlv->type) {
	case TLV_REQUEST_UNICAST_TRANSMISSION:
		if (TLV_LENGTH_INVALID(tlv, request_unicast_xmit_tlv)) {
			return -EBADMSG;
		}
		request = (struct request_unicast_xmit_tlv *) tlv;
		if (!unicast_message_type_valid(request->message_type)) {
			return -EBADMSG;
		}
		NTOHL(request->durationField);
		break;
	case TLV_GRANT_UNICAST_TRANSMISSION:
		if (TLV_LENGTH_INVALID(tlv, grant_unicast_xmit_tlv)) {
			return -EBADMSG;
		}
		grant = (struct grant_unicast_xmit_tlv *) tlv;
		if (!unicast_message_type_valid(grant->message_type)) {
			return -EBADMSG;
		}
		NTOHL(grant->durationField);
		break;
	case TLV_CANCEL_UNICAST_TRANSMISSION:
		if (TLV_LENGTH_INVALID(tlv, cancel_unicast_xmit_tlv)) {
			return -EBADMSG;
		}
		cancel = (struct cancel_unicast_xmit_tlv *) tlv;
		if (!unicast_message_type_valid(cancel->message_type_flags)) {
			return -EBADMSG;
		}
		break;
	case TLV_ACKNOWLEDGE_CANCEL_UNICAST_TRANSMISSION:
		if (TLV_LENGTH_INVALID(tlv, ack_cancel_unicast_xmit_tlv)) {
			return -EBADMSG;
		}
		ack = (struct ack_cancel_unicast_xmit_tlv *) tlv;
		if (!unicast_message_type_valid(ack->message_type_flags)) {
			return -EBADMSG;
		}
		break;
	}
	return 0;
}

static void unicast_negotiation_pre_send(struct TLV *tlv)
{
	struct request_unicast_xmit_tlv *request;
	struct grant_unicast_xmit_tlv *grant;

	switch (tlv->type) {
	case TLV_REQUEST_UNICAST_TRANSMISSION:
		request = (struct request_unicast_xmit_tlv *) tlv;
		HTONL(request->durationField);
		break;
	case TLV_GRANT_UNICAST_TRANSMISSION:
		grant = (struct grant_unicast_xmit_tlv *) tlv;
		HTONL(grant->durationField);
		break;
	case TLV_CANCEL_UNICAST_TRANSMISSION:
	case TLV_ACKNOWLEDGE_CANCEL_UNICAST_TRANSMISSION:
		break;
	}
}

struct tlv_extra *tlv_extra_alloc(void)
{
	struct tlv_extra *extra = TAILQ_FIRST(&tlv_pool);

	if (extra) {
		TAILQ_REMOVE(&tlv_pool, extra, list);
	} else {
		extra = calloc(1, sizeof(*extra));
	}
	return extra;
}

void tlv_extra_cleanup(void)
{
	struct tlv_extra *extra;

	while ((extra = TAILQ_FIRST(&tlv_pool)) != NULL) {
		TAILQ_REMOVE(&tlv_pool, extra, list);
		free(extra);
	}
}

void tlv_extra_recycle(struct tlv_extra *extra)
{
	memset(extra, 0, sizeof(*extra));
	TAILQ_INSERT_HEAD(&tlv_pool, extra, list);
}

int tlv_post_recv(struct tlv_extra *extra)
{
	struct management_error_status *mes;
	struct TLV *tlv = extra->tlv;
	struct management_tlv *mgt;
	int result = 0;

	switch (tlv->type) {
	case TLV_MANAGEMENT:
		if (TLV_LENGTH_INVALID(tlv, management_tlv))
			goto bad_length;
		mgt = (struct management_tlv *) tlv;
		mgt->id = ntohs(mgt->id);
		if (tlv->length > sizeof(mgt->id))
			result = mgt_post_recv(mgt, tlv->length - sizeof(mgt->id), extra);
		break;
	case TLV_MANAGEMENT_ERROR_STATUS:
		if (TLV_LENGTH_INVALID(tlv, management_error_status))
			goto bad_length;
		mes = (struct management_error_status *) tlv;
		mes->error = ntohs(mes->error);
		mes->id = ntohs(mes->id);
		break;
	case TLV_ORGANIZATION_EXTENSION:
		if (TLV_LENGTH_INVALID(tlv, organization_tlv))
			goto bad_length;
		result = org_post_recv((struct organization_tlv *) tlv);
		break;
	case TLV_REQUEST_UNICAST_TRANSMISSION:
	case TLV_GRANT_UNICAST_TRANSMISSION:
	case TLV_CANCEL_UNICAST_TRANSMISSION:
	case TLV_ACKNOWLEDGE_CANCEL_UNICAST_TRANSMISSION:
		result = unicast_negotiation_post_recv(extra);
		break;
	case TLV_PATH_TRACE:
		if (tlv_array_invalid(tlv, 0, sizeof(struct ClockIdentity))) {
			goto bad_length;
		}
		break;
	case TLV_ALTERNATE_TIME_OFFSET_INDICATOR:
		result = alttime_offset_post_recv(extra);
		break;
	case TLV_AUTHENTICATION_2008:
	case TLV_AUTHENTICATION_CHALLENGE:
	case TLV_SECURITY_ASSOCIATION_UPDATE:
	case TLV_CUM_FREQ_SCALE_FACTOR_OFFSET:
	case TLV_PTPMON_REQ:
		break;
	case TLV_PTPMON_RESP:
		result = nsm_resp_post_recv(extra);
		break;
	case TLV_ORGANIZATION_EXTENSION_PROPAGATE:
	case TLV_ENHANCED_ACCURACY_METRICS:
	case TLV_ORGANIZATION_EXTENSION_DO_NOT_PROPAGATE:
	case TLV_L1_SYNC:
	case TLV_PORT_COMMUNICATION_AVAILABILITY:
	case TLV_PROTOCOL_ADDRESS:
		break;
	case TLV_SLAVE_RX_SYNC_TIMING_DATA:
		result = slave_rx_sync_timing_data_post_revc(extra);
		break;
	case TLV_SLAVE_RX_SYNC_COMPUTED_DATA:
	case TLV_SLAVE_TX_EVENT_TIMESTAMPS:
		break;
	case TLV_SLAVE_DELAY_TIMING_DATA_NP:
		result = slave_delay_timing_data_post_revc(extra);
		break;
	case TLV_CUMULATIVE_RATE_RATIO:
	case TLV_PAD:
	case TLV_AUTHENTICATION:
	default:
		break;
	}
	return result;
bad_length:
	return -EBADMSG;
}

void tlv_pre_send(struct TLV *tlv, struct tlv_extra *extra)
{
	struct management_tlv *mgt;
	struct management_error_status *mes;

	switch (tlv->type) {
	case TLV_MANAGEMENT:
		mgt = (struct management_tlv *) tlv;
		if (tlv->length > sizeof(mgt->id))
			mgt_pre_send(mgt, extra);
		mgt->id = htons(mgt->id);
		break;
	case TLV_MANAGEMENT_ERROR_STATUS:
		mes = (struct management_error_status *) tlv;
		mes->error = htons(mes->error);
		mes->id = htons(mes->id);
		break;
	case TLV_ORGANIZATION_EXTENSION:
		org_pre_send((struct organization_tlv *) tlv);
		break;
	case TLV_REQUEST_UNICAST_TRANSMISSION:
	case TLV_GRANT_UNICAST_TRANSMISSION:
	case TLV_CANCEL_UNICAST_TRANSMISSION:
	case TLV_ACKNOWLEDGE_CANCEL_UNICAST_TRANSMISSION:
		unicast_negotiation_pre_send(tlv);
		break;
	case TLV_PATH_TRACE:
		break;
	case TLV_ALTERNATE_TIME_OFFSET_INDICATOR:
		alttime_offset_pre_send(extra);
		break;
	case TLV_AUTHENTICATION_2008:
	case TLV_AUTHENTICATION_CHALLENGE:
	case TLV_SECURITY_ASSOCIATION_UPDATE:
	case TLV_CUM_FREQ_SCALE_FACTOR_OFFSET:
	case TLV_PTPMON_REQ:
		break;
	case TLV_PTPMON_RESP:
		nsm_resp_pre_send(extra);
		break;
	case TLV_ORGANIZATION_EXTENSION_PROPAGATE:
	case TLV_ENHANCED_ACCURACY_METRICS:
	case TLV_ORGANIZATION_EXTENSION_DO_NOT_PROPAGATE:
	case TLV_L1_SYNC:
	case TLV_PORT_COMMUNICATION_AVAILABILITY:
	case TLV_PROTOCOL_ADDRESS:
		break;
	case TLV_SLAVE_RX_SYNC_TIMING_DATA:
		slave_rx_sync_timing_data_pre_send(extra);
		break;
	case TLV_SLAVE_RX_SYNC_COMPUTED_DATA:
	case TLV_SLAVE_TX_EVENT_TIMESTAMPS:
		break;
	case TLV_SLAVE_DELAY_TIMING_DATA_NP:
		slave_delay_timing_data_pre_send(extra);
		break;
	case TLV_CUMULATIVE_RATE_RATIO:
	case TLV_PAD:
	case TLV_AUTHENTICATION:
	default:
		break;
	}
}