summaryrefslogtreecommitdiff
path: root/cesar/bsu/src/bsu.c
blob: cfea17ce50ad5e05ebbb3c7ff72945a0c5f01730 (plain)
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
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
/* Cesar project {{{
 *
 * Copyright (C) 2010 Spidcom
 *
 * <<<Licence>>>
 *
 * }}} */
/**
 * \file    bsu/src/bsu.c
 * \brief   BSU core functions.
 * \ingroup bsu
 *
 * Explanation of how bsu handles schedules programmation:
 *   - On timer event, BSU copy the first two CA schedules and just modify the
 *   start date. It creates the last and third one using data present in the
 *   beacon i.e. bsu->sta_avln->beacon.
 *   - On beacon reception, BSU write all the schedules for the CA, it allows
 *   the CA to have non persistent schedules programmed for the current
 *   beacon period.
 */
#include "common/std.h"
#include "lib/bitstream.h"
#include "lib/fixed.h"
#include "bsu/bsu.h"
#include "bsu/ntb/ntb.h"
#include "bsu/aclf/aclf.h"
#include "mac/ca/ca.h"
#include "mac/common/timings.h"
#include "bsu/inc/context.h"
#include "bsu/inc/interface.h"
#include <string.h>
#include "hal/arch/arch.h"
#include "mac/pbproc/pbproc.h"
#include "cp/sta/core/core.h"


/* Define the process invalid value. */
#define BSU_MERGE_PROCESS_INVALID 0xff

/* Define the number of beacon periods to provide to the CA. */
#define BSU_BEACON_PERIOD_NB 4

/* Define the delay to program the timer. */
#define BSU_WAKEUP_DELAY_MS 15

/** Static declaration. */
static bsu_t bsu_global;

/**
 * EoC scheduler. Should be called in each beacon period.
 * \param  user_data  cp context.
 */
void
cp_eoc_scheduler_prepare (void * user_data) __attribute__ ((weak));

void
cp_eoc_scheduler_prepare (void * user_data)
{
}
/**
 * Store the values computed into the stats.
 * \param  ctx  the module context.
 *
 * Stats registered are dependent on the AVLN the station is tracking/using
 * it can change at any time.
 */
PRIVATE void
bsu_stats_store (bsu_t *ctx)
{
#if CONFIG_STATS
    ctx->stats.ntb_offset_tck = ctx->sta_avln->sync.ntb_offset_tck;
    if (ctx->sta_avln->sync.second_shoot)
        ctx->stats.frequency_error_q30 =
            FIXED (ctx->sta_avln->sync.fe, BSU_NTB_FIXED_POINT);
    else
        ctx->stats.frequency_error_q30 = 0;
#endif
}

/**
 * Remove the MFS beacon.
 * \param  ctx  the module context.
 * \param  index  the MFS index.
 */
PRIVATE inline void
bsu_mfs_remove (bsu_t *ctx, uint index)
{
    if (ctx->mfs_beacons[index])
    {
        ca_mfs_remove (ctx->ca, ctx->mfs_beacons[index]);
        pbproc_mfs_remove_all (ctx->mfs_beacons[index]);
        mac_store_mfs_remove (ctx->mac_store,
                              PARENT_OF (mfs_t, tx, ctx->mfs_beacons[index]));
        blk_release (ctx->mfs_beacons[index]);
        ctx->mfs_beacons[index] = NULL;
    }
}

/**
 * Clear BSU beacons MFS.
 * \param  ctx  the module context.
 */
PRIVATE void
bsu_clear_mfs_beacons (bsu_t *ctx)
{
    uint i;
    for (i = 0; i < COUNT (ctx->mfs_beacons); i++)
        bsu_mfs_remove (ctx, i);
}

/**
 * Reprogram bsu timer.
 * \param  ctx  the module context.
 * \param  date  the date to wake up.
 */
PRIVATE inline void
bsu_reprogram_timer (bsu_t *ctx, u32 date)
{
    /* Reprogram the timer. */
    hal_timer_instance_program (
        ctx->hal_timer, &ctx->timer,
        date - MAC_MS_TO_TCK (BSU_WAKEUP_DELAY_MS));
}

/**
 * Set tracking data.
 * \param  ctx  the module context.
 * \param  avln  the new AVLN to track.
 *
 * \warn providing a NULL AVLN will be considered as untracked.
 */
PRIVATE void
bsu_track_avln_identify (bsu_t *ctx, bsu_avln_t *avln)
{
    bsu_clear_mfs_beacons (ctx);
    if (avln)
    {
        ctx->nid_track = avln->beacon.vf.nid;
        ctx->snid_track = avln->snid;
        ctx->tei_track = avln->beacon.vf.stei;
        ctx->cco_mac_address_track = avln->cco_mac_address;
        ctx->sta_avln = avln;
        bsu_aclf_beacon_skew (ctx->aclf, false);
        ctx->track_new = true;
        ctx->avln_tracked = false;
    }
    else
    {
        ctx->nid_track = 0;
        ctx->snid_track = 0;
        ctx->tei_track = MAC_TEI_UNASSOCIATED;
        ctx->cco_mac_address_track = MAC_ZERO;
        bsu_avln_t *old_avln = ctx->sta_avln;
        ctx->sta_avln = &ctx->poweron;
        dbg_assert (!ctx->poweron.sync.init);
        dbg_assert (ctx->poweron.sync.fe == 0.0);
        /* When the CCo starts it must keep the ntb offset tck of the network.
         */
        ctx->poweron.sync.ntb_offset_tck = old_avln->sync.ntb_offset_tck;
        bsu_aclf_beacon_skew (ctx->aclf, true);
    }
}

/**
 * Get the associated AVLN.
 * \param  ctx  the module context.
 * \param  nid  the NID of the AVLN.
 * \param  snid  the SNID of the AVLN.
 * \param  mac  the CCo's mac address.
 * \return  the AVLN object.
 *
 * The AVLNs are static object do not release it.
 */
bsu_avln_t*
bsu_avln_get (bsu_t *ctx, u64 nid, u8 snid, mac_t mac)
{
    uint i;
    for (i = 0; i < ctx->avlns_nb; i++)
        if (ctx->avlns[i].beacon.vf.nid == nid
            && ctx->avlns[i].snid == snid
            && ctx->avlns[i].cco_mac_address == mac)
            return &ctx->avlns[i];
    return NULL;
}

/**
 * Initialise the AVLN data.
 * \param  avln  the avln structure to initialise.
 * \param  nid  the network identifier.
 * \param  snid  the short network identifier.
 * \param  mac  the CCo mac address.
 */
PRIVATE void
bsu_avln_init (bsu_avln_t *avln, u64 nid, u8 snid, mac_t mac)
{
    bsu_ntb_init (&avln->sync);
    avln->beacon.vf.nid = nid;
    avln->snid = snid;
    avln->cco_mac_address = mac;
    /* Simulate an activity by setting the date to the current one, this is
     * only used by BSU to
     *  - not remove it if adding a new AVLN
     *  - not process two beacons of the same AVLN on the beacon period.
     */
    avln->beacon.beacon_period_start_date = phy_date ();
}

/**
 * Add an AVLN.
 * \param  ctx  the module context.
 * \param  nid  the NID of the AVLN.
 * \param  snid  the SNID of the AVLN.
 * \param  mac  the CCo's mac address.
 * \param  added  set true if newly added.
 * \return  the AVLN object.
 *
 * The AVLNs are static object do not release it.
 * \warn  When calling this function, if no more room are available the oldest
 * AVLN will be used.
 */
inline bsu_avln_t*
bsu_avln_add (bsu_t *ctx, u64 nid, u8 snid, mac_t mac, bool *added)
{
    *added = false;
    bsu_avln_t* avln = bsu_avln_get (ctx, nid, snid, mac);
    if (!avln)
    {
        if(ctx->avlns_nb < BSU_FOREIGN_AVLNS_NB)
        {
            avln = &ctx->avlns[ctx->avlns_nb];
            ctx->avlns_nb++;
        }
        /* No more space available. */
        else
        {
            uint i;
            for (i = 1, avln = &ctx->avlns[0];
                 i < BSU_FOREIGN_AVLNS_NB - 1;
                 i++)
            {
                if (less_mod2p32 (
                        ctx->avlns[i].beacon.beacon_period_start_date,
                        avln->beacon.beacon_period_start_date))
                    /* found the oldest AVLN. */
                    avln = &ctx->avlns[i];
            }
            dbg_assert (ctx->sta_avln != avln);
        }
        bsu_avln_init (avln, nid, snid, mac);
        *added = true;
    }
    return avln;
}

void
bsu_avln_remove (bsu_t *ctx, u64 nid, u8 snid, mac_t mac)
{
    dbg_assert (ctx);
    bsu_avln_t *to_remove = NULL;
    uint i, pos;
    arch_dsr_lock ();
    for (i = 0; i < ctx->avlns_nb; i++)
    {
        if (ctx->avlns[i].beacon.vf.nid == nid
            && ctx->avlns[i].snid == snid
            && ctx->avlns[i].cco_mac_address == mac)
        {
            to_remove = &ctx->avlns[i];
            pos = i;
            break;
        }
    }
    if (to_remove)
    {
        /* Station's AVLN is the removed one. */
        if (to_remove == ctx->sta_avln)
            bsu_track_avln_identify (ctx, NULL);
        for (i = pos; i < ctx->avlns_nb - 1; i++)
        {
            if (ctx->sta_avln == &ctx->avlns[i+1])
                ctx->sta_avln = &ctx->avlns[i];
            ctx->avlns[i] = ctx->avlns[i+1];
        }
        ctx->avlns_nb--;
    }
    arch_dsr_unlock ();
}

/**
 * Initialise the process position index object.
 * \param  ctx  the module context.
 * \param  beacon  the beacon to use to read schedules.
 * \param  proc  the process object.
 * \param  beacon_period_index  the beacon period for the one the schedule is
 * being computed.
 */
PRIVATE inline void
bsu_schedules_merge_process_init (bsu_t *ctx, bsu_beacon_t *beacon,
                                  bsu_avln_schedules_process_t *proc,
                                  uint beacon_period_index)
{
    uint i;
    proc->ps_alloc_index = BSU_MERGE_PROCESS_INVALID;
    proc->ps = NULL;
    proc->nps_alloc_index = BSU_MERGE_PROCESS_INVALID;
    /* Persistent schedules position index. */
    for (i = 0; i < beacon->bmis.ps.nb; i++)
    {
        if ((beacon->bmis.ps.ps[i].pscd <= beacon_period_index
             && (u32) (beacon->bmis.ps.ps[i].pscd + beacon->bmis.ps.ps[i].cscd)
             >= beacon_period_index)
            || BSU_BEACON_PERSISTENT_ALLOC_IS_PERMANENT(beacon->bmis.ps.ps[i]))
        {
            proc->ps = &beacon->bmis.ps.ps[i];
            proc->ps_alloc_index = 0;
            break;
        }
    }
    /* Non persistent schedule index. */
    if (beacon->bmis.nps.ns)
        proc->nps_alloc_index = 0;
    dbg_assert (proc->nps_alloc_index != BSU_MERGE_PROCESS_INVALID
                || proc->ps_alloc_index != BSU_MERGE_PROCESS_INVALID);
}

/**
 * Take the first allocation available from the persistent schedules.
 * \param  proc_schedule  the process schedule structure to take the first
 * allocation.
 * \return  the first SAI of the persistent schedule.
 */
PRIVATE inline bsu_beacon_sai_t*
bsu_schedules_process__ps_first_allocation (
    bsu_t *ctx, bsu_avln_schedules_process_t *proc)
{
    bsu_beacon_sai_t *sai = &proc->ps->sais[proc->ps_alloc_index++];
    if (proc->ps_alloc_index == proc->ps->ns)
    {
        proc->ps_alloc_index = BSU_MERGE_PROCESS_INVALID;
        proc->ps = NULL;
    }
    return sai;
}

/**
 * Take the first allocation available from the non persistent schedules.
 * \param  ctx  the module context.
 * \param  proc_schedule  the process schedule structure to take the first
 * allocation.
 * \param  beacon  the beacon to get the schedules from.
 * \return  the first SAI of the non persistent schedule.
 */
PRIVATE inline bsu_beacon_sai_t*
bsu_schedules_process__nps_first_allocation (
    bsu_t *ctx, bsu_avln_schedules_process_t *proc,
    bsu_beacon_t *beacon)
{
    bsu_beacon_sai_t *sai = &beacon->bmis.nps.sais[proc->nps_alloc_index++];
    if (proc->nps_alloc_index == beacon->bmis.nps.ns)
        proc->nps_alloc_index = BSU_MERGE_PROCESS_INVALID;
    return sai;
}

/**
 * Get the lesser schedule.
 * \param  ctx  the module context.
 * \param  beacon  the beacon to read schedules.
 * \param  proc  the process object.
 * \return  the schedule to insert in the CA allocation.
 */
inline bsu_beacon_sai_t*
bsu_schedules_merge_get_lesser (bsu_t *ctx, bsu_beacon_t *beacon,
                                bsu_avln_schedules_process_t *proc)
{
    bsu_beacon_sai_t *sai = NULL;
    /* Persistent schedules lonely. */
    if (proc->ps
        && proc->nps_alloc_index == BSU_MERGE_PROCESS_INVALID
        && proc->ps_alloc_index != BSU_MERGE_PROCESS_INVALID)
        sai = bsu_schedules_process__ps_first_allocation (ctx, proc);
    /* Non persistent schedule alone. */
    else if (!proc->ps
             && proc->nps_alloc_index != BSU_MERGE_PROCESS_INVALID)
        sai = bsu_schedules_process__nps_first_allocation (
            ctx, proc, beacon);
    /* Non persistent and persistent schedules are available. */
    else if (proc->nps_alloc_index != BSU_MERGE_PROCESS_INVALID
             && proc->ps_alloc_index != BSU_MERGE_PROCESS_INVALID)
    {
        /* Persistent schedules is before the non persistent one. */
        if (proc->ps->sais[proc->ps_alloc_index].end_time_atu <
            beacon->bmis.nps.sais[proc->nps_alloc_index].end_time_atu)
            sai = bsu_schedules_process__ps_first_allocation (ctx, proc);
        /* Non persistent schedules is before the persistent one. */
        else
            sai = bsu_schedules_process__nps_first_allocation (
                ctx, proc, beacon);
    }
    return sai;
}

/**
 * Add an allocation into CA schedules.
 * \param  ctx  the module context.
 * \param  schedules  the CA schedules.
 * \param  pos  the position in the schedules allocations array.
 * \param  end_time_atu  the end of the allocation.
 * \param  glid  the GLID of the allocation
 */
PRIVATE inline void
bsu_schedules_merge__allocation_add (bsu_t *ctx, ca_schedule_t *schedules,
                                     uint pos, u32 end_time_atu, u8 glid)
{
    schedules->allocations[pos].end_offset_tck =
        MAC_ATU_TO_TCK (end_time_atu);
    schedules->allocations[pos].glid = glid;
}

/**
 * Merge schedules read from the central beacon into the ca schedules.
 * \param  ctx  the module context.
 * \param  beacon  the beacon containing the schedules.
 * \param  schedules  the CA schedules objects to fill.
 * \param  bp_index  the beacon period for the one the schedule is being
 * computed.
 */
inline void
bsu_schedules_merge (bsu_t *ctx, bsu_beacon_t *beacon,
                     ca_schedule_t *schedule, uint bp_index)
{
    uint alloc = 0;
    bsu_beacon_sai_t *sai;
    bsu_avln_schedules_process_t process;
    bsu_schedules_merge_process_init (ctx, beacon, &process, bp_index);
    while ((sai = bsu_schedules_merge_get_lesser (ctx, beacon, &process)))
    {
        /* A hole is present for the first allocation. It is a beacon region,
         * BSU should inform the CA with the correct glid (a reserved one).
         *  - When acting as CCo glid is MAC_LID_SPC_CENTRAL.
         *  - When acting as STA glid is MAC_LID_SPC_BEACON_LISTEN. */
        if (alloc == 0 && sai->stpf && sai->start_time_atu != 0)
        {
            u8 glid;
            if (ctx->is_sta == BSU_UPDATE_STA_TYPE_CCO)
                glid = MAC_LID_SPC_CENTRAL;
            else
                glid = MAC_LID_SPC_BEACON_LISTEN;
            bsu_schedules_merge__allocation_add (
                ctx, schedule, alloc, sai->start_time_atu, glid);
            alloc++;
        }
        /* Add a hole between the previous allocation end this one. */
        else if (sai->stpf
                 && MAC_ATU_TO_TCK(sai->start_time_atu)
                 != schedule->allocations[alloc-1].end_offset_tck)
        {
            bsu_schedules_merge__allocation_add (
                ctx, schedule, alloc, sai->start_time_atu, MAC_LID_SPC_HOLE);
            alloc++;
        }
        /* Add this allocation. */
        bsu_schedules_merge__allocation_add (
            ctx, schedule, alloc, sai->end_time_atu, sai->glid | 0x80);
        alloc++;
    }
    /* Special behavior for CSMA only mode. */
    if (beacon->vf.nm == BSU_BEACON_NM_CSMA_ONLY)
        schedule->allocations[alloc-1].end_offset_tck = BITS_ONES (24);
    /* store the number of allocations. */
    schedule->allocations_nb = alloc;
}

/**
 * Fill the Hybrid mode, SNID and NEK value for CA schedule.
 * \param  ctx  the module context.
 * \param  avln  the AVLN schedule structure containing the necessary data.
 * \param  casched  the Channel access schedule to fill.
 * \param  bpn  the beacon period number, 0 for the current one, 1 for the
 * next one and so on.
 */
inline void
bsu_ca_schedules_settings (bsu_t *ctx, bsu_avln_t *avln,
                           ca_schedule_t *casched, uint bpn)
{
    /* SNID. */
    if (avln->beacon.bmis.change_snid.present
        && ((ctx->is_sta == BSU_UPDATE_STA_TYPE_STA
             && avln->beacon.bmis.change_snid.snidccd <= bpn)
            || (ctx->is_sta == BSU_UPDATE_STA_TYPE_CCO
                && (uint) 1 + avln->beacon.bmis.change_snid.snidccd <= bpn)))
        casched->snid = avln->beacon.bmis.change_snid.new_snid;
    else
        casched->snid = avln->snid;
    /* NEK switch. */
    if (avln->beacon.bmis.eks.present
        && avln->beacon.bmis.eks.kbc == BSU_BEACON_EKS_KBC_NEK
        && ((ctx->is_sta == BSU_UPDATE_STA_TYPE_STA
             && avln->beacon.bmis.eks.kccd <= bpn)
            ||(ctx->is_sta == BSU_UPDATE_STA_TYPE_CCO
               && ((uint) 1 + avln->beacon.bmis.eks.kccd) <= bpn)))
        casched->nek_switch = !ctx->nek_switch;
    else
        casched->nek_switch = ctx->nek_switch;
    /* Hybrid mode. */
    if (avln->beacon.bmis.change_hm.present
        && ((ctx->is_sta == BSU_UPDATE_STA_TYPE_STA
             && avln->beacon.bmis.change_hm.hmccd <= bpn)
            || (ctx->is_sta == BSU_UPDATE_STA_TYPE_CCO
                && (uint) 1 + avln->beacon.bmis.change_hm.hmccd <= bpn)))
        casched->coexistence_mode = avln->beacon.bmis.change_hm.newhm;
    else
        casched->coexistence_mode = avln->beacon.vf.hm;
}

/**
 * If the network is in CSMA only mode, check the current schedule is
 * permanent and with a full CSMA period.
 * \param  ctx  the module context.
 * \param  beacon  the beacon to modify.
 *
 * If the schedules are not compatible with the network mode, the default will
 * be applied.
 */
inline void
bsu_ca_schedules_nm_csma_only (bsu_t *ctx, bsu_beacon_t *beacon)
{
    if (beacon->vf.nm == BSU_BEACON_NM_CSMA_ONLY)
    {
        if (beacon->bmis.ps.nb == 0
            || !(beacon->bmis.ps.nb == 1
                 && BSU_BEACON_PERSISTENT_ALLOC_IS_PERMANENT(
                     beacon->bmis.ps.ps[0])))
        {
            beacon->bmis.nps.ns = 0;
            beacon->bmis.ps.nb = 1;
            beacon->bmis.ps.ps[0].ns = 1;
            beacon->bmis.ps.ps[0].pscd = 0;
            beacon->bmis.ps.ps[0].cscd =
                BSU_BEACON_PERSISTENT_SCHEDULES_PERMANENT_COUNTDOWN;
            beacon->bmis.ps.ps[0].sais[0].stpf = false;
            beacon->bmis.ps.ps[0].sais[0].glid = MAC_LID_SHARED_CSMA & 0x7f;
        }
    }
}

/**
 * Get available slot of schedules for the CA.
 * \param  ctx  the module context.
 * \param  indexes  the array to fill with available slots.
 */
PRIVATE void
bsu_ca_schedules_available (bsu_t *ctx, uint *indexes)
{
    uint i, j;
    uint nb = 0;
    bool in_use;
    for (i = 0; i < CA_SCHEDULE_NB && nb < BSU_BEACON_SCHEDULES_NB; i++)
    {
        in_use = false;
        for (j = 0; j < COUNT (ctx->ca_schedules_in_use) && !in_use; j++)
        {
            if (ctx->ca_schedules_in_use[j] == i)
                in_use = true;
        }
        if (!in_use)
            indexes[nb++] = i;
    }
}

/**
 * Fill the missing schedule for the CA.
 * \param  ctx  the module context.
 * \param  avln  the avln containing the data to fill the missing schedules.
 * \param  bp  the array of data to provide to the CA.
 * \param  bpsd  the array of beacon period start date to fill the
 * allocations.
 * \param  start_index  start filling the array at this index.
 *
 * This function takes an array with bp_nb - start_index elements filled
 * corresponding to the current schedules in use in the CA. This should only
 * fill the last ones.
 *
 * It is not this function responsibility to provide the computed schedules
 * to the CA, the caller must handle it.
 */
PRIVATE void
bsu_ca_schedule_prepare_missing (
    bsu_t *ctx, bsu_avln_t *avln, ca_beacon_period_t *bp,
    u32 *bpsd, uint start_index)
{
    ca_schedule_t *schedule;
    uint i, j;
    uint ca_index[BSU_BEACON_SCHEDULES_NB];
    bsu_ca_schedules_available (ctx, ca_index);
    /* Get non used schedules from the CA. */
    for (i = start_index, j = 0; i < BSU_BEACON_SCHEDULES_NB; i++, j++)
    {
        /* Get the next channel access index not in use. */
        schedule = ca_alloc_get_schedule (ctx->ca, ca_index[j]);
        bsu_schedules_merge (ctx, &avln->beacon, schedule, i);
        bsu_ca_schedules_settings (ctx, avln, schedule, i);
        bp[i].start_date = bpsd[i];
        bp[i].schedule_index = ca_index[j];
    }
    /* Store the current schedules in use. */
    for (i = 0; i < BSU_BEACON_SCHEDULES_NB; i++)
        ctx->ca_schedules_in_use[i] = bp[i].schedule_index;
}

/**
 * End to fill the schedules and provide it to the CA.
 * \param  ctx  the module context.
 * \param  avln  the station avln data containing the schedules read from the
 * beacon.
 * \param  copy_nb  copy the first nb schedules.
 */
void
bsu_ca_schedules (bsu_t *ctx, bsu_avln_t *avln, uint copy_nb)
{
    uint start_nb;
    u32 bpsd[BSU_BEACON_SCHEDULES_NB];
    ca_beacon_period_t beacon_period[BSU_BEACON_SCHEDULES_NB];
    bsu_aclf_beacon_period_start_date (ctx->aclf, bpsd, COUNT (bpsd));
    for (start_nb = 0; start_nb < copy_nb; start_nb++)
    {
        beacon_period[start_nb].start_date = bpsd[start_nb];
        beacon_period[start_nb].schedule_index =
            ctx->ca_schedules_in_use[start_nb];
    }
    bsu_ca_schedule_prepare_missing (
        ctx, avln, beacon_period, bpsd, start_nb);
    /* Provide the schedules to the CA. */
    BSU_TRACE (SCHEDULES, bpsd[0], bpsd[1], bpsd[2]);
    ca_alloc_update_beacon_periods (
        ctx->ca, beacon_period, BSU_BEACON_SCHEDULES_NB);
}

/**
 * Decrease countdown EKS, SNID and HM.
 * \param  ctx  the module context.
 * \param  avln  the AVLN schedules data.
 * This should be done after programming the CA with the current schedules to
 * have data ready for next awake.
 */
PRIVATE inline void
bsu_avln_countdown_beacon_entries (bsu_t *ctx, bsu_avln_t *avln)
{
    if (avln->beacon.bmis.change_snid.present)
        avln->beacon.bmis.change_snid.snidccd--;
    if (avln->beacon.bmis.change_hm.present)
        avln->beacon.bmis.change_hm.hmccd--;
    if (avln->beacon.bmis.eks.present)
        avln->beacon.bmis.eks.kccd--;
}

/**
 * Apply EKS, SNID and HM.
 * \param  ctx  the module context.
 * \param  avln  the AVLN schedules data.
 * This should be done after programming the CA with the current schedules to
 * have data ready for next awake.
 */
PRIVATE inline void
bsu_avln_countdown_beacon_entries_apply_changes (bsu_t *ctx, bsu_avln_t *avln)
{
    if (avln->beacon.bmis.change_snid.present
        && avln->beacon.bmis.change_snid.snidccd == 1)
    {
        avln->beacon.bmis.change_snid.present = false;
        avln->snid = avln->beacon.bmis.change_snid.new_snid;
        if (avln == ctx->sta_avln)
            ctx->snid_track = avln->snid;
    }
    if (avln->beacon.bmis.change_hm.present
        && avln->beacon.bmis.change_hm.hmccd == 1)
    {
        avln->beacon.bmis.change_hm.present = false;
        avln->beacon.vf.hm = avln->beacon.bmis.change_hm.newhm;
    }
    if (avln->beacon.bmis.eks.present
        && avln->beacon.bmis.eks.kccd == 1)
    {
        avln->beacon.bmis.eks.present = false;
        if (avln->beacon.bmis.eks.kbc == BSU_BEACON_EKS_KBC_NEK)
            ctx->nek_switch = !ctx->nek_switch;
    }
}

/**
 * Decrease schedules countdown.
 * \param  ctx  the module context.
 * \param  avln  the AVLN object.
 */
inline void
bsu_avln_schedules_decrease_countdown (bsu_t *ctx, bsu_avln_t *avln)
{
    uint i;
    for (i = 0; i < avln->beacon.bmis.ps.nb; i++)
    {
        /* If one of the persistent schedules has the CSCD == 0, it should be
         * removed from the schedules. */
        if (avln->beacon.bmis.ps.ps[i].pscd == 0
            && avln->beacon.bmis.ps.ps[i].cscd == 0)
        {
            uint j;
            for (j = i; j < avln->beacon.bmis.ps.nb - 1; j++)
                avln->beacon.bmis.ps.ps[j] = avln->beacon.bmis.ps.ps[j+1];
            avln->beacon.bmis.ps.nb--;
        }
        if (avln->beacon.bmis.ps.nb)
        {
            if (avln->beacon.bmis.ps.ps[i].pscd)
                avln->beacon.bmis.ps.ps[i].pscd--;
            else if (avln->beacon.bmis.ps.ps[i].cscd
                     && (avln->beacon.vf.nm != BSU_BEACON_NM_CSMA_ONLY
                         || (avln->beacon.vf.nm == BSU_BEACON_NM_CSMA_ONLY
                             && avln->beacon.bmis.ps.ps[i].cscd !=
                             HPAV_SCHEDULE_PERMAMENT_VALUE)))
                avln->beacon.bmis.ps.ps[i].cscd--;
        }
    }
}

/**
 * Create the beacon to be send over the PLC.
 * \param  ctx  the module context.
 * \param  type  the beacon type.
 * \param  bsu_beacon  the beacon to use to write the PB.
 */
PRIVATE void
bsu_beacon_send_prepare (bsu_t *ctx, bsu_beacon_type_t type,
                         bsu_beacon_t *bsu_beacon)
{
    pb_beacon_t *beacon;
    pbproc_tx_beacon_params_t params;
    /* Make a copy of the beacon for upper layers. */
    bsu_beacon_t *ulbeacon = blk_alloc ();
    memcpy (ulbeacon, bsu_beacon, sizeof (bsu_beacon_t));
    ulbeacon->vf.stei = ctx->mac_config->tei;
    bsu_aclf_bto (ctx->aclf, (s16*) params.bto, COUNT (params.bto));
    /* Reset the updated flag in the discover info beacon entry. */
    if (type == BSU_BEACON_TYPE_DISCOVER)
    {
        ulbeacon->bmis.mac_address.present = true;
        ulbeacon->bmis.mac_address.mac_address =
            ctx->mac_config->sta_mac_address;
        ulbeacon->bmis.discover_info = ctx->discover_info;
        ulbeacon->bmis.discover_info.present = true;
        bitstream_direct_write (&ctx->discover_info.info_data, 0, 0, 1);
    }
    beacon = bsu_beacon_write (ulbeacon, type, ctx->mac_config, &params);
    /* Send the beacon. */
    bsu_beacon_send (ctx, type, beacon, &params);
    bsu_beacon_send_upper_layer (
        ctx, ulbeacon, BSU_BEACON_DIRECTION_TO_PLC);
}

/**
 * BSU timer expires.
 * \param  ud  the module context.
 *
 * Reprogram schedules using previous data, when acting as CCo sends the
 * central beacon.
 */
void
bsu_timer_event_process (void *ud)
{
    bsu_t *ctx = (bsu_t *) ud;
    if (ctx->activate)
    {
        dbg_assert (ctx);
        u32 bpsd0;
        cp_sta_core_refresh_watch_dog (ctx->ul_data);
        bsu_aclf_beacon_period_start_date (ctx->aclf, &bpsd0, 1);
        dbg_assert (
            less_mod2p32 (phy_date (),
                          bsu_aclf_beacon_period_start_date_next(ctx->aclf)));
        if (ctx->is_sta == BSU_UPDATE_STA_TYPE_STA)
        {
            if (ctx->track_new && ctx->avln_tracked)
            {
                u32 bpsd[BSU_BEACON_SCHEDULES_NB];
                uint bp = bsu_aclf_beacon_period_tck (ctx->aclf);
                /* Reset STA clock correction. */
                bsu_ntb_clock_configure (
                    &ctx->sta_avln->sync, ctx->mac_config, ctx->phy);
                /* Compute the new BPSD with the data of the new AVLN. */
                bsu_aclf_compute_beacon_period_start_date (
                    ctx->aclf,
                    ctx->sta_avln->sync.bts
                        - ctx->sta_avln->sync.ntb_offset_tck,
                    ctx->sta_avln->bto,
                    ctx->sta_avln->beacon.bmis.bpsto.present ?
                    ctx->sta_avln->beacon.bmis.bpsto.bpsto : 0);
                bsu_aclf_beacon_period_start_date (
                    ctx->aclf, bpsd, COUNT (bpsd));
                /* Decrease countdown, the first schedule will not be
                 * programmed. */
                bsu_avln_schedules_decrease_countdown (ctx, ctx->sta_avln);
                /* The current beacon period ends after the next beacon period
                 * in the new AVLN starts. */
                if (less_mod2p32 (bpsd[1], bpsd0 + bp))
                {
                    bsu_aclf_bpsd_avoid_overlap (ctx->aclf);
                    bsu_avln_schedules_decrease_countdown (ctx, ctx->sta_avln);
                    ctx->sta_avln->beacon.beacon_period_start_date = bpsd[2];
                }
                else
                    ctx->sta_avln->beacon.beacon_period_start_date = bpsd[1];
                ctx->track_new = false;
            }
            else if (less_mod2p32 (
                    ctx->sta_avln->beacon.beacon_period_start_date, bpsd0))
            {
                bsu_avln_schedules_decrease_countdown (ctx, ctx->sta_avln);
                ctx->sta_avln->beacon.beacon_period_start_date = bpsd0;
            }
        }
        else
        {
            /* Are update data late ?. */
            if (less_mod2p32 (
                    ctx->sta_avln->beacon.beacon_period_start_date, bpsd0))
                /* Create and send the beacon. */
                bsu_beacon_countdown (&ctx->sta_avln->beacon);
            if (ctx->track_new)
            {
                /* Reset STA clock correction. */
                bsu_ntb_clock_configure (
                    &ctx->sta_avln->sync, ctx->mac_config, ctx->phy);
                ctx->track_new = false;
            }
            cp_eoc_scheduler_prepare (ctx->ul_data);
            /* Inform PBProc we send a central beacon. */
            pbproc_beacon_detected (
                ctx->pbproc,
                bsu_aclf_beacon_period_start_date_next (ctx->aclf)
                + bsu_aclf_beacon_period_tck (ctx->aclf));
            bsu_beacon_send_prepare (ctx, BSU_BEACON_TYPE_CENTRAL,
                                     &ctx->sta_avln->beacon);
            if (ctx->sta_avln->beacon.bmis.discover.present
                && ctx->sta_avln->beacon.bmis.discover.tei
                == ctx->mac_config->tei)
            {
                bsu_beacon_send_prepare (ctx, BSU_BEACON_TYPE_DISCOVER,
                                         &ctx->sta_avln->beacon);
                ctx->sta_avln->beacon.bmis.discover.present = false;
            }
        }
        bsu_ca_schedules (ctx, ctx->sta_avln, 2);
        bsu_avln_countdown_beacon_entries_apply_changes (ctx, ctx->sta_avln);
        bsu_avln_countdown_beacon_entries (ctx, ctx->sta_avln);
        bsu_aclf_track_powerline (ctx->aclf);
        if (ctx->is_sta == BSU_UPDATE_STA_TYPE_STA)
            bsu_aclf_shift_beacon_period_start_date (ctx->aclf);
        else
            bsu_aclf_ac_compute_beacon_period_start_date (ctx->aclf);
        /* Shift schedules in use for next beacon period. */
        uint i;
        uint index_0 = ctx->ca_schedules_in_use[0];
        for (i = 0; i < COUNT (ctx->ca_schedules_in_use) - 1; i++)
            ctx->ca_schedules_in_use[i] = ctx->ca_schedules_in_use[i+1];
        /* To avoid the schedule of index_0 to be requested it is put at
         * the end of the array. This schedule will not be used for the next
         * program. */
        ctx->ca_schedules_in_use[i] = index_0;
        bsu_reprogram_timer (
            ctx, bsu_aclf_beacon_period_start_date_next (ctx->aclf));
        bsu_stats_store (ctx);
    }
}

/**
 * Initialise stats for bsu.
 * \param  ctx  the module context.
 */
PRIVATE void
bsu_stats_init (bsu_t *ctx)
{
#if CONFIG_STATS
    dbg_assert (ctx);
    /* Register our statistics. */
    lib_stats_set_stat_value_notype ("ntb_offset_tck",
                                     &ctx->stats.ntb_offset_tck,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_USER);
    lib_stats_set_stat_value_notype ("frequency_error_q30",
                                     &ctx->stats.frequency_error_q30,
                                     LIB_STATS_ACCESS_READ_ONLY,
                                     LIB_STATS_USER);
    lib_stats_set_stat_value_notype ("CLK_SYNC_WEIGHT_K",
                                     &ctx->bsu_ntb_clk_sync_weight_k,
                                     LIB_STATS_ACCESS_WRITE_ONLY,
                                     LIB_STATS_USER);
#endif
}

bsu_t *
bsu_init (bsu_aclf_t *aclf, mac_config_t *mac_config, phy_t *phy,
          mac_store_t *mac_store, ca_t *ca, sar_t *sar, hal_timer_t *timer,
          pbproc_t *pbproc)
{
    bsu_t *ctx = &bsu_global;
    dbg_assert (aclf);
    dbg_assert (mac_config);
    dbg_assert (phy);
    dbg_assert (mac_store);
    dbg_assert (ca);
    dbg_assert (sar);
    dbg_assert (timer);
    memset (&bsu_global, 0x0, sizeof (bsu_t));
    /* Initialise the context. */
    ctx->aclf = aclf;
    ctx->mac_config = mac_config;
    ctx->phy = phy;
    ctx->mac_store = mac_store;
    ctx->ca = ca;
    ctx->sar = sar;
    ctx->hal_timer = timer;
    ctx->pbproc = pbproc;
    /* Initialise the NTB. */
    uint i;
    for (i = 0; i < HPAV_AVLNS_NB_MAX; i++)
    {
        memset (&ctx->avlns[i], 0, sizeof (bsu_avln_t));
        ctx->avlns[i].beacon.vf.nm = BSU_BEACON_NM_CSMA_ONLY;
        bsu_ntb_init (&ctx->avlns[i].sync);
    }
    ctx->sta_avln = &ctx->poweron;
    memset (&ctx->poweron, 0, sizeof (bsu_avln_t));
    ctx->poweron.beacon.vf.nm = BSU_BEACON_NM_CSMA_ONLY;
    bsu_ntb_init (&ctx->poweron.sync);
    /* Initialise the SAR callback. */
    sar_init_beacon_cb (sar, ctx, (sar_beacon_cb_t)  bsu_beacon_recv);
    /* Initialise timer events. */
    hal_timer_instance_init (timer, &ctx->timer, ctx,
                             bsu_timer_event_process);
    ctx->activate = false;
    ctx->is_sta = BSU_UPDATE_STA_TYPE_STA;
    for (i = 0; i < COUNT (ctx->mfs_beacons); i++)
        ctx->mfs_beacons[i] = NULL;
    for (i = 0; i < COUNT (ctx->beacon_nb_recv); i++)
        ctx->beacon_nb_recv[i] = 0;
    for (i = 0; i < COUNT (ctx->beacon_nb_sent); i++)
        ctx->beacon_nb_sent[i] = 0;
    for (i = 0; i < COUNT (ctx->ca_schedules_in_use); i++)
        ctx->ca_schedules_in_use[i] = CA_SCHEDULE_NB;
    ctx->bsu_ntb_clk_sync_weight_k = BSU_NTB_CLK_SYNC_WEIGHT_K_DEFAULT;
    /* Trace. */
    bsu_trace_init (ctx);
    bsu_stats_init (ctx);
    return ctx;
}

void
bsu_init_beacon_cb (bsu_beacon_processed_t cb, void *cb_ud)
{
    bsu_global.ul_cb = cb;
    bsu_global.ul_data = cb_ud;
}

void
bsu_uninit (bsu_t *ctx)
{
    dbg_assert (ctx);
    hal_timer_instance_cancel (ctx->hal_timer, &ctx->timer);
    bsu_ntb_uninit (&ctx->sta_avln->sync);
    uint i;
    for (i = 0; i < BSU_FOREIGN_AVLNS_NB; i++)
        bsu_ntb_uninit (&ctx->avlns[i].sync);
    hal_timer_instance_cancel (ctx->hal_timer, &ctx->timer);
    bsu_clear_mfs_beacons (ctx);
    bsu_trace_uninit (ctx);
}

/**
 * Get the information from the beacon of the tracked AVLN.
 * \param  ctx  the module context.
 * \param  beacon  the beacon unpacked.
 * \param  params  the RX parameters.
 */
PRIVATE inline bsu_avln_t*
bsu_beacon_process__avln_tracked (bsu_t *ctx, bsu_beacon_t *beacon,
                                  pbproc_rx_beacon_params_t *params)
{
    u32 i, bts_date, bpsd0;
    /* Inform PBProc we received the central beacon. */
    pbproc_beacon_detected (
        ctx->pbproc, params->preamble_date
        + bsu_aclf_beacon_period_tck (ctx->aclf));
    memcpy (&ctx->sta_avln->beacon, beacon, sizeof (bsu_beacon_t));
    /* NTB synchronisation. */
    bsu_ntb_clk_sync (&ctx->sta_avln->sync, ctx->phy,
                      params->bts, params->preamble_sysdate,
                      params->preamble_date,
                      ctx->bsu_ntb_clk_sync_weight_k);
    /* Configure the clock frequency. */
    bsu_ntb_clock_configure (
        &ctx->sta_avln->sync, ctx->mac_config, ctx->phy);
    for (i = 0; i < HPAV_BEACON_BTO_NB; i++)
        ctx->sta_avln->bto[i] = params->bto[i];
    bts_date = params->bts - ctx->sta_avln->sync.ntb_offset_tck;
    bsu_aclf_beacon_period_start_date (ctx->aclf, &bpsd0, 1);
    if (ctx->track_new == false)
    {
        bsu_aclf_compute_beacon_period_start_date (
            ctx->aclf, bts_date, (s16*) params->bto,
            ctx->sta_avln->beacon.bmis.bpsto.present ?
            ctx->sta_avln->beacon.bmis.bpsto.bpsto : 0);
        /* Create the CA schedules. */
        bsu_ca_schedules (ctx, ctx->sta_avln, 0);
    }
    BSU_TRACE (
        BEACON_PROCESS, phy_date (), params->snid, beacon->vf.stei,
        ctx->sta_avln->sync.ntb_offset_tck,
        FIXED (ctx->sta_avln->sync.fe, BSU_NTB_FIXED_POINT));
    BSU_TRACE (BEACON_DATA, params->bts, params->bto[0],
               params->bto[1], params->bto[2]);
    /* A discover beacon had been requested ? */
    if (ctx->sta_avln->beacon.bmis.discover.present
        && ctx->sta_avln->beacon.bmis.discover.tei
        == ctx->mac_config->tei)
        bsu_beacon_send_prepare (ctx, BSU_BEACON_TYPE_DISCOVER, beacon);
    ctx->sta_avln->beacon.beacon_period_start_date = bts_date;
    bsu_stats_store (ctx);
    ctx->avln_tracked = true;
    return ctx->sta_avln;
}

/**
 * Get the information from the beacon of another AVLN.
 * \param  ctx  the module context.
 * \param  beacon  the beacon unpacked.
 * \param  params  the RX parameters.
 */
PRIVATE inline bsu_avln_t*
bsu_beacon_process__avln_not_tracked (bsu_t *ctx, bsu_beacon_t *beacon,
                                      pbproc_rx_beacon_params_t *params)
{
    bool added;
    bsu_avln_t *avln = bsu_avln_add (
        ctx, beacon->vf.nid, params->snid,
        beacon->bmis.mac_address.present ?
        beacon->bmis.mac_address.mac_address : MAC_ZERO,
        &added);
    u32 bpsd, i;
    bsu_aclf_beacon_period_start_date (ctx->aclf, &bpsd, 1);
    /* Other AVLN. */
    if ((!added
         && avln != ctx->sta_avln
         && less_mod2p32 (avln->beacon.beacon_period_start_date, bpsd))
        || added)
    {
        for (i = 0; i < HPAV_BEACON_BTO_NB; i++)
            avln->bto[i] = params->bto[i];
        memcpy (&avln->beacon, beacon, sizeof (bsu_beacon_t));
        /* NTB synchronisation. */
        bsu_ntb_clk_sync (&avln->sync, ctx->phy,
                          params->bts, params->preamble_sysdate,
                          params->preamble_date,
                          ctx->bsu_ntb_clk_sync_weight_k);
        avln->beacon.beacon_period_start_date = params->bts -
            avln->sync.ntb_offset_tck;
        BSU_TRACE (BEACON_PROCESS, phy_date (), params->snid, beacon->vf.stei,
                   avln ? avln->sync.ntb_offset_tck : 0,
                   avln ?  FIXED (avln->sync.fe, BSU_NTB_FIXED_POINT): 0);
        BSU_TRACE (BEACON_DATA, params->bts, params->bto[0],
                   params->bto[1], params->bto[2]);
    }
    return avln;
}

bsu_beacon_t*
bsu_beacon_process (bsu_t *ctx, pb_beacon_t *beacon,
                    pbproc_rx_beacon_params_t *params)
{
    bsu_avln_t *avln = NULL;
    bsu_beacon_t *bsu_beacon = blk_alloc ();
    dbg_assert (ctx);
    dbg_assert (beacon);
    dbg_assert (params);
    /* Check the CRC. */
    if (bsu_beacon_read (beacon, bsu_beacon))
    {
        memcpy (&bsu_beacon->params.rx_parameters, params,
                sizeof (pbproc_rx_beacon_params_t));
        ctx->beacon_nb_recv[bsu_beacon->vf.bt]++;
        bsu_ca_schedules_nm_csma_only (ctx, bsu_beacon);
        if (bsu_beacon->vf.bt == BSU_BEACON_TYPE_CENTRAL)
        {
            mac_t cco_mac = bsu_beacon->bmis.mac_address.present ?
                bsu_beacon->bmis.mac_address.mac_address: MAC_ZERO;
            /* It the beacon from our AVLN ? */
            if (ctx->is_sta == BSU_UPDATE_STA_TYPE_STA
                && ctx->nid_track == bsu_beacon->vf.nid
                && ctx->snid_track == params->snid
                && ctx->tei_track == bsu_beacon->vf.stei
                && ctx->cco_mac_address_track == cco_mac)
                avln = bsu_beacon_process__avln_tracked (
                    ctx, bsu_beacon, params);
            /* Other AVLN. */
            else
                avln = bsu_beacon_process__avln_not_tracked (
                    ctx, bsu_beacon, params);
            bsu_beacon->params.frequency_error =
                FIXED (avln->sync.fe, BSU_NTB_FIXED_POINT);
            bsu_beacon->params.ntb_offset_tck = avln->sync.ntb_offset_tck;
            bsu_beacon->params.frequency_error_valid =
                avln->sync.second_shoot;
        }
    }
    else
    {
        BSU_TRACE (BEACON_ERROR, phy_date ());
        blk_release (bsu_beacon);
        return NULL;
    }
    return bsu_beacon;
}

/**
 * Check if new persistent schedules is scheduled from the CP and copy it into
 * the BSU context.
 * \param  ctx  the module context.
 * \param  beacon  the beacon data to be used in the future.
 */
inline void
bsu_update__persistent_schedules (bsu_t *ctx, bsu_beacon_t *beacon)
{
    uint index;
    dbg_assert ((beacon->bmis.ps.nb == BSU_BEACON_BMI_PERSISTENT_SCHEDULE_MAX
                 && beacon->bmis.ps.ps[0].pscd + beacon->bmis.ps.ps[0].cscd
                 < beacon->bmis.ps.ps[1].pscd)
                || beacon->bmis.ps.nb
                != BSU_BEACON_BMI_PERSISTENT_SCHEDULE_MAX);
    /* If the persistent schedules number are at the maximum
     * ignore the data from the CP. */
    for (index = ctx->sta_avln->beacon.bmis.ps.nb;
         ctx->sta_avln->beacon.bmis.ps.nb < beacon->bmis.ps.nb;
         index ++)
    {
        ctx->sta_avln->beacon.bmis.ps.nb++;
        ctx->sta_avln->beacon.bmis.ps.ps[index] = beacon->bmis.ps.ps[index];
        uint beacon_delta =
            (bsu_aclf_beacon_period_start_date_next (ctx->aclf)
             - beacon->beacon_period_start_date)
            / bsu_aclf_beacon_period_tck (ctx->aclf);
        if (ctx->sta_avln->beacon.bmis.ps.ps[index].pscd <= beacon_delta)
        {
            beacon_delta -= ctx->sta_avln->beacon.bmis.ps.ps[index].pscd;
            ctx->sta_avln->beacon.bmis.ps.ps[index].pscd = 0;
            if (ctx->sta_avln->beacon.vf.nm != BSU_BEACON_NM_CSMA_ONLY
                || (ctx->sta_avln->beacon.vf.nm == BSU_BEACON_NM_CSMA_ONLY
                    && ctx->sta_avln->beacon.bmis.ps.ps[index].cscd
                    != HPAV_SCHEDULE_PERMAMENT_VALUE))
                ctx->sta_avln->beacon.bmis.ps.ps[index].cscd -= beacon_delta;
        }
        else
            ctx->sta_avln->beacon.bmis.ps.ps[index].pscd -= beacon_delta;
    }
}

void
bsu_update (bsu_t *ctx, bsu_beacon_t *beacon, bsu_update_sta_type_t is_sta)
{
    dbg_assert (ctx);
    dbg_assert (beacon);
    dbg_assert (ctx->is_sta == is_sta
                || (ctx->is_sta == BSU_UPDATE_STA_TYPE_STA
                    && is_sta == BSU_UPDATE_STA_TYPE_CCO
                    && ctx->tei_track == MAC_TEI_UNASSOCIATED
                    && ctx->nid_track == 0
                    && ctx->snid_track == 0)
                || (ctx->is_sta == BSU_UPDATE_STA_TYPE_CCO
                    && is_sta == BSU_UPDATE_STA_TYPE_STA));
    arch_dsr_lock ();
    ctx->is_sta = is_sta;
    dbg_assert ((beacon->bmis.ps.nb
                 && beacon->bmis.ps.ps[0].ns > 0)
                || beacon->bmis.nps.ns);
    /* If persistent schedules are present and there is more than one. The
     * second can only be present if the first one has its PSCD equal to 0.
     * See specification section 5.1.2 Beacon Period Structure Figure 5-3. */
    dbg_assert (beacon->bmis.ps.nb < BSU_BEACON_BMI_PERSISTENT_SCHEDULE_MAX
                || (beacon->bmis.ps.nb
                    == BSU_BEACON_BMI_PERSISTENT_SCHEDULE_MAX
                    && beacon->bmis.ps.ps[0].pscd == 0
                    && beacon->bmis.ps.ps[0].pscd
                    < beacon->bmis.ps.ps[1].pscd));
    dbg_assert (beacon->vf.hm < MAC_COEXISTENCE_NB);
    /* If the data provided are for the next beacon period. */
    if (lesseq_mod2p32 (bsu_aclf_beacon_period_start_date_next (ctx->aclf),
                        beacon->beacon_period_start_date)
        || !ctx->activate)
    {
        bsu_update_discover_info (ctx, &beacon->bmis.discover_info);
        ctx->sta_avln->beacon = *beacon;
    }
    /* Data in the beacon had already expired. */
    else
    {
        /* Copy some payload variant fields. */
        ctx->sta_avln->beacon.vf.ncnr = beacon->vf.ncnr;
        ctx->sta_avln->beacon.vf.npsm = beacon->vf.npsm;
        ctx->sta_avln->beacon.vf.rtsbf = beacon->vf.rtsbf;
        ctx->sta_avln->beacon.vf.ccocap = beacon->vf.ccocap;
        ctx->sta_avln->beacon.vf.hoip = beacon->vf.hoip;
        /* Copy data in non countdown beacon entry. */
        ctx->sta_avln->beacon.bmis.mac_address =
            beacon->bmis.mac_address;
        ctx->sta_avln->beacon.bmis.discover = beacon->bmis.discover;
        ctx->sta_avln->beacon.bmis.discover_info = beacon->bmis.discover_info;
        ctx->sta_avln->beacon.bmis.bpsto = beacon->bmis.bpsto;
        ctx->sta_avln->beacon.bmis.nps = beacon->bmis.nps;
        ctx->sta_avln->beacon.bmis.region = beacon->bmis.region;
        /* Process the beacon entry with countdowns. */
        bsu_update__persistent_schedules (ctx, beacon);
        if (beacon->bmis.eks.present
            && !ctx->sta_avln->beacon.bmis.eks.present)
            ctx->sta_avln->beacon.bmis.eks = beacon->bmis.eks;
        if (beacon->bmis.handover.present
            && !ctx->sta_avln->beacon.bmis.handover.present)
            ctx->sta_avln->beacon.bmis.handover = beacon->bmis.handover;
        if (beacon->bmis.relocation.present
            && !ctx->sta_avln->beacon.bmis.relocation.present)
            ctx->sta_avln->beacon.bmis.relocation = beacon->bmis.relocation;
        if (beacon->bmis.aclsc.present
            && !ctx->sta_avln->beacon.bmis.aclsc.present)
            ctx->sta_avln->beacon.bmis.aclsc = beacon->bmis.aclsc;
        if (beacon->bmis.cns.present
            && !ctx->sta_avln->beacon.bmis.cns.present)
            ctx->sta_avln->beacon.bmis.cns = beacon->bmis.cns;
        if (beacon->bmis.change_hm.present
            && !ctx->sta_avln->beacon.bmis.change_hm.present)
            ctx->sta_avln->beacon.bmis.change_hm = beacon->bmis.change_hm;
        if (beacon->bmis.change_snid.present
            && !ctx->sta_avln->beacon.bmis.change_snid.present)
            ctx->sta_avln->beacon.bmis.change_snid = beacon->bmis.change_snid;
        if (beacon->bmis.mac_address.present
            && !ctx->sta_avln->beacon.bmis.mac_address.present)
            ctx->sta_avln->beacon.bmis.mac_address =
                beacon->bmis.mac_address;
        if (beacon->bmis.discover_info.present)
            ctx->sta_avln->beacon.bmis.discover_info =
                beacon->bmis.discover_info;
    }
    arch_dsr_unlock ();
}

void
bsu_track_avln (bsu_t *ctx, u64 nid, u16 snid, u8 tei, mac_t mac)
{
    bool added;
    bsu_avln_t *avln;
    dbg_assert (ctx);
    arch_dsr_lock ();
    /* Station acts as STA now. */
    ctx->is_sta = BSU_UPDATE_STA_TYPE_STA;
    avln = bsu_avln_add (ctx, nid, snid, mac, &added);
    dbg_check (avln);
    bsu_track_avln_identify (ctx, avln);
    arch_dsr_unlock ();
}

void
bsu_untrack_avln (bsu_t *ctx)
{
    dbg_assert (ctx);
    arch_dsr_lock ();
    /* Reset tracking data. */
    bsu_track_avln_identify (ctx, NULL);
    arch_dsr_unlock ();
}


void
bsu_power_on (bsu_t *ctx, u8 snid)
{
    dbg_assert (ctx);
    arch_dsr_lock ();
    ctx->sta_avln = &ctx->poweron;
    ctx->sta_avln->snid = snid;
    ctx->nek_switch = 0;
    dbg_assert (ctx->sta_avln->beacon.bmis.ps.nb != 0
                || ctx->sta_avln->beacon.bmis.nps.ns != 0);
    arch_dsr_unlock ();
}

void
bsu_activate (bsu_t *ctx, bool status)
{
    dbg_assert (ctx);
    dbg_assert (status != ctx->activate);
    ctx->activate = status;
    arch_dsr_lock ();
    if (status)
    {
        /* Program the first schedules in the CA. */
        bsu_aclf_acl_frequency_detection (ctx->aclf);
        bsu_aclf_ac_compute_beacon_period_start_date (ctx->aclf);
        /* Prepare firsts schedules to the CA.*/
        bsu_ca_schedules (ctx, ctx->sta_avln, 0);
        /* Program the next wake up of the BSU. */
        bsu_reprogram_timer (
            ctx, bsu_aclf_beacon_period_start_date_next (ctx->aclf));
    }
    /* Stops BSU. */
    else
    {
        uint i;
        hal_timer_instance_cancel (ctx->hal_timer, &ctx->timer);
        for (i = 0; i < HPAV_AVLNS_NB_MAX; i++)
            bsu_ntb_init (&ctx->avlns[i].sync);
        ctx->sta_avln = &ctx->poweron;
        ctx->avlns_nb = 0;
        bsu_aclf_clear (ctx->aclf);
    }
    arch_dsr_unlock ();
}

void
bsu_nek_index_adjust (uint nek_index)
{
    bsu_t *ctx = &bsu_global;
    ctx->nek_switch = nek_index;
}

uint
bsu_nek_index_current (bsu_t *ctx)
{
    dbg_assert (ctx);
    return ctx->nek_switch;
}

uint
bsu_nek_index_next (bsu_t *ctx)
{
    dbg_assert (ctx);
    return !ctx->nek_switch;
}

void
bsu_update_discover_info (
    bsu_t *ctx, bsu_beacon_bmi_discover_info_t *discover)
{
    dbg_assert (ctx);
    dbg_assert (discover);
    arch_dsr_lock ();
    bool discover_updated = bitstream_direct_read
        (&discover->info_data, 0, 1);
    bool current_discover_updated =
        bitstream_direct_read (&ctx->discover_info.info_data, 0, 1);
    ctx->discover_info = *discover;
    /* BSU is responsible for reseting the updated flag in this entry. */
    if (current_discover_updated || discover_updated)
        bitstream_direct_write (&ctx->discover_info.info_data, 0, 1, 1);
    arch_dsr_unlock ();
}

void
bsu_update_nid (bsu_t *ctx, u64 nid)
{
    dbg_assert (ctx);
    arch_dsr_lock ();
    ctx->sta_avln->beacon.vf.nid = nid;
    arch_dsr_unlock ();
}