summaryrefslogtreecommitdiff
path: root/bsp/phytium/libraries/drivers/drv_xmac.c
blob: bf7bc70cc271d988a97e80f5dbfb8f7e483ebec2 (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
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
/*
 * Copyright (c) 2006-2023, RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Email: [email protected]
 *
 * Change Logs:
 * Date        Author       Notes
 * 2022-07-07  liuzhihong   first commit
 * 2023-07-14  liuzhihong   support RT-Smart
 * 2023-12-01  liuzhihong   support initialisation of multiple mac
 */

#include"rtconfig.h"

#ifdef BSP_USING_ETH

#include "board.h"
#define LOG_TAG      "xmac_drv"
#include "drv_log.h"
#include "mm_aspace.h"
#ifdef RT_USING_SMART
    #include "ioremap.h"
#endif


#include "eth_board.h"
#include "drv_xmac.h"

#define FXMAC_BD_TO_INDEX(ringptr, bdptr) \
    (((uintptr)bdptr - (uintptr)(ringptr)->base_bd_addr) / (ringptr)->separation)


static void FXmacInitOnError(FXmacOs *instance_p);
static void FXmacSetupIsr(FXmacOs *instance_p);

static FXmacOs fxmac_os_instace[FXMAC_NUM] =
{
    [FXMAC0_ID] =
    {
        .config = (0),
        .hwaddr = {0x98, 0x0e, 0x24, 0x00, 0x11, 0x0},

    },
    [FXMAC1_ID] =
    {
        .config = (0),
        .hwaddr = {0x98, 0x0e, 0x24, 0x00, 0x11, 0x1},

    },
    [FXMAC2_ID] =
    {
        .config = (0),
        .hwaddr = {0x98, 0x0e, 0x24, 0x00, 0x11, 0x2},
    },
    [FXMAC3_ID] =
    {
        .config = (0),
        .hwaddr = {0x98, 0x0e, 0x24, 0x00, 0x11, 0x3},
    },
};

int isr_calling_flg = 0;

/* queue */

void FXmacQueueInit(PqQueue *q)
{
    FASSERT(q != NULL);
    q->head = q->tail = q->len = 0;
}

int FXmacPqEnqueue(PqQueue *q, void *p)
{
    if (q->len == PQ_QUEUE_SIZE)
    {
        return -1;
    }

    q->data[q->head] = (uintptr)p;
    q->head = (q->head + 1) % PQ_QUEUE_SIZE;
    q->len++;

    return 0;
}

void *FXmacPqDequeue(PqQueue *q)
{
    int ptail;

    if (q->len == 0)
    {
        return NULL;
    }

    ptail = q->tail;
    q->tail = (q->tail + 1) % PQ_QUEUE_SIZE;
    q->len--;

    return (void *)q->data[ptail];
}

int FXmacPqQlength(PqQueue *q)
{
    return q->len;
}

/* dma */

/**
 * @name:  IsTxSpaceAvailable
 * @msg:   Get the number of free BDs in the Bdrings
 * @param {ethernetif} *ethernetif_p
 * @return {*}
 */
static u32 IsTxSpaceAvailable(FXmacOs *instance_p)
{
    FXmacBdRing *txring;
    u32 freecnt;
    FASSERT(instance_p != NULL);

    txring = &(FXMAC_GET_TXRING(instance_p->instance));

    /* tx space is available as long as there are valid BD's */
    freecnt = FXMAC_BD_RING_GET_FREE_CNT(txring);
    return freecnt;
}

/**
 * @name: FXmacProcessSentBds
 * @msg:   Free up memory space of pbuf on the send queue
 * @return {*}
 * @param {ethernetif} *ethernetif_p
 * @param {FXmacBdRing} *txring
 */
void FXmacProcessSentBds(FXmacOs *instance_p, FXmacBdRing *txring)
{
    FXmacBd *txbdset;
    FXmacBd *curbdpntr;
    u32 n_bds;
    FError status;
    u32 n_pbufs_freed;
    u32 bdindex;
    struct pbuf *p;
    u32 *temp;

    while (1)
    {
        /* obtain processed BD's */
        n_bds = FXmacBdRingFromHwTx(txring, FXMAX_TX_PBUFS_LENGTH, &txbdset);
        if (n_bds == 0)
        {
            return;
        }
        /* free the processed BD's */
        n_pbufs_freed = n_bds;
        curbdpntr = txbdset;
        while (n_pbufs_freed > 0)
        {
            bdindex = FXMAC_BD_TO_INDEX(txring, curbdpntr);
            temp = (u32 *)curbdpntr;
            *temp = 0; /* Word 0 */
            temp++;
            if (bdindex == (FXMAX_TX_PBUFS_LENGTH - 1))
            {
                *temp = 0xC0000000; /* Word 1 ,used/Wrap – marks last descriptor in transmit buffer descriptor list.*/
            }
            else
            {
                *temp = 0x80000000; /* Word 1 , Used – must be zero for GEM to read data to the transmit buffer.*/
            }


            p = (struct pbuf *)instance_p->buffer.tx_pbufs_storage[bdindex];

            if (p != NULL)
            {
                pbuf_free(p);
            }
            instance_p->buffer.tx_pbufs_storage[bdindex] = (uintptr)NULL;
            curbdpntr = FXMAC_BD_RING_NEXT(txring, curbdpntr);
            n_pbufs_freed--;

        }

        status = FXmacBdRingFree(txring, n_bds, txbdset);
        if (status != FT_SUCCESS)
        {
            LOG_I("Failure while freeing in Tx Done ISR.");
        }
    }
    return;
}

FError FXmacSgsend(FXmacOs *instance_p, struct pbuf *p)
{
    struct pbuf *q;
    u32 n_pbufs;
    FXmacBd *txbdset, *txbd, *last_txbd = NULL;
    FXmacBd *temp_txbd;
    FError status;
    FXmacBdRing *txring;
    u32 bdindex;
    uintptr tx_payload ;
    u32 max_fr_size;


    txring = &(FXMAC_GET_TXRING(instance_p->instance));

    /* first count the number of pbufs */
    for (q = p, n_pbufs = 0; q != NULL; q = q->next)
    {
        n_pbufs++;
    }

    /* obtain as many BD's */
    status = FXmacBdRingAlloc(txring, n_pbufs, &txbdset);
    if (status != FT_SUCCESS)
    {
        LOG_I("sgsend: Error allocating TxBD.");
        return ERR_GENERAL;
    }

    for (q = p, txbd = txbdset; q != NULL; q = q->next)
    {
        bdindex = FXMAC_BD_TO_INDEX(txring, txbd);

        if (instance_p->buffer.tx_pbufs_storage[bdindex])
        {
            LOG_I("txbd %p, txring->base_bd_addr %p", txbd, txring->base_bd_addr);
            LOG_I("PBUFS not available bdindex is %d ", bdindex);
            LOG_I("instance_p->buffer.tx_pbufs_storage[bdindex] %p ", instance_p->buffer.tx_pbufs_storage[bdindex]);
            return ERR_GENERAL;
        }

        /* Send the data from the pbuf to the interface, one pbuf at a
           time. The size of the data in each pbuf is kept in the ->len
           variable. */
        tx_payload = (uintptr)q->payload;
#ifdef RT_USING_SMART
        tx_payload += PV_OFFSET;
#endif
        FXMAC_BD_SET_ADDRESS_TX(txbd, (uintptr)tx_payload);
        if (instance_p->config & FXMAC_OS_CONFIG_JUMBO)
        {
            max_fr_size = FXMAC_MAX_FRAME_SIZE_JUMBO;
        }
        else
        {
            max_fr_size = FXMAC_MAX_FRAME_SIZE;
        }

        if (q->len > max_fr_size)
        {
            FXMAC_BD_SET_LENGTH(txbd, max_fr_size & 0x3FFF);
        }
        else
        {
            FXMAC_BD_SET_LENGTH(txbd, q->len & 0x3FFF);
        }

        instance_p->buffer.tx_pbufs_storage[bdindex] = (uintptr)q;

        pbuf_ref(q);
        last_txbd = txbd;
        FXMAC_BD_CLEAR_LAST(txbd);
        txbd = FXMAC_BD_RING_NEXT(txring, txbd);
    }
    FXMAC_BD_SET_LAST(last_txbd);
    /* For fragmented packets, remember the 1st BD allocated for the 1st
       packet fragment. The used bit for this BD should be cleared at the end
       after clearing out used bits for other fragments. For packets without
       just remember the allocated BD. */
    temp_txbd = txbdset;
    txbd = txbdset;
    txbd = FXMAC_BD_RING_NEXT(txring, txbd);
    q = p->next;
    for (; q != NULL; q = q->next)
    {
        FXMAC_BD_CLEAR_TX_USED(txbd);

        txbd = FXMAC_BD_RING_NEXT(txring, txbd);
    }
    FXMAC_BD_CLEAR_TX_USED(temp_txbd);


    status = FXmacBdRingToHw(txring, n_pbufs, txbdset);
    if (status != FT_SUCCESS)
    {
        LOG_I("sgsend: Error submitting TxBD.");
        return ERR_GENERAL;
    }
    /* Start transmit */
    FXMAC_WRITEREG32((instance_p->instance).config.base_address,
                     FXMAC_NWCTRL_OFFSET,
                     (FXMAC_READREG32(instance_p->instance.config.base_address,
                                      FXMAC_NWCTRL_OFFSET) |
                      FXMAC_NWCTRL_STARTTX_MASK));

    return status;
}

void SetupRxBds(FXmacOs *instance_p, FXmacBdRing *rxring)
{
    FXmacBd *rxbd;
    FError status;
    struct pbuf *p;
    u32 freebds;
    u32 bdindex;
    u32 *temp;
    uintptr_t pl_paddr;
    freebds = FXMAC_BD_RING_GET_FREE_CNT(rxring);
    while (freebds > 0)
    {
        freebds--;

        if (instance_p->config & FXMAC_OS_CONFIG_JUMBO)
        {
            p = pbuf_alloc(PBUF_RAW, FXMAC_MAX_FRAME_SIZE_JUMBO, PBUF_RAM);
        }
        else
        {
            p = pbuf_alloc(PBUF_RAW, FXMAC_MAX_FRAME_SIZE, PBUF_RAM);
        }

        if (!p)
        {
#if LINK_STATS
            lwip_stats.link.memerr++;
            lwip_stats.link.drop++;
#endif
            LOG_I("Unable to alloc pbuf in recv_handler.");
            return;
        }
        status = FXmacBdRingAlloc(rxring, 1, &rxbd);
        if (status != FT_SUCCESS)
        {
            LOG_I("SetupRxBds: Error allocating RxBD.");
            pbuf_free(p);
            return;
        }
        status = FXmacBdRingToHw(rxring, 1, rxbd);
        if (status != FT_SUCCESS)
        {
            LOG_I("Error committing RxBD to hardware: ");
            if (status == FXMAC_ERR_SG_LIST)
            {
                LOG_I("XST_DMA_SG_LIST_ERROR: this function was called out of sequence with FXmacBdRingAlloc().");
            }
            else
            {
                LOG_I("Set of BDs was rejected because the first BD did not have its start-of-packet bit set, or the last BD did not have its end-of-packet bit set, or any one of the BD set has 0 as length value.");
            }

            pbuf_free(p);
            FXmacBdRingUnAlloc(rxring, 1, rxbd);
            return;
        }

        bdindex = FXMAC_BD_TO_INDEX(rxring, rxbd);
        temp = (u32 *)rxbd;
        if (bdindex == (FXMAX_RX_PBUFS_LENGTH - 1))
        {
            *temp = 0x00000002;
        }
        else
        {
            *temp = 0;
        }
        temp++;
        *temp = 0;
        pl_paddr = (uintptr)p->payload;
#ifdef RT_USING_SMART
        pl_paddr += PV_OFFSET;
#endif
        FXMAC_BD_SET_ADDRESS_RX(rxbd, (uintptr)pl_paddr);
        instance_p->buffer.rx_pbufs_storage[bdindex] = (uintptr)p;
    }
}
void FXmacRecvSemaphoreHandler(void *arg)
{
    FXmacOs *instance_p;
    rt_err_t result;

    if (RT_NULL == arg)
    {
        LOG_E("Args is NULL");
        return;
    }

    instance_p = (FXmacOs *)arg;

    result = eth_device_ready(&(instance_p->parent));
    if (result != RT_EOK)
    {
        LOG_I("RxCpltCallback err = %d", result);
    }

}
void FXmacRecvHandler(void *arg)
{
    struct pbuf *p;
    FXmacBd *rxbdset, *curbdptr;
    FXmacBdRing *rxring;
    volatile u32 bd_processed;
    u32 rx_bytes, k;
    u32 bdindex;
    u32 regval;
    FXmacOs *instance_p;
    FASSERT(arg != NULL);

    instance_p = (FXmacOs *)arg;
    rxring = &FXMAC_GET_RXRING(instance_p->instance);

    /* If Reception done interrupt is asserted, call RX call back function
     to handle the processed BDs and then raise the according flag.*/
    regval = FXMAC_READREG32(instance_p->instance.config.base_address, FXMAC_RXSR_OFFSET);
    FXMAC_WRITEREG32(instance_p->instance.config.base_address, FXMAC_RXSR_OFFSET, regval);

    while (1)
    {
        bd_processed = FXmacBdRingFromHwRx(rxring, FXMAX_RX_PBUFS_LENGTH, &rxbdset);
        if (bd_processed <= 0)
        {
            break;
        }

        for (k = 0, curbdptr = rxbdset; k < bd_processed; k++)
        {

            bdindex = FXMAC_BD_TO_INDEX(rxring, curbdptr);
            p = (struct pbuf *)instance_p->buffer.rx_pbufs_storage[bdindex];
            /*
             * Adjust the buffer size to the actual number of bytes received.
             */
            if (instance_p->config & FXMAC_OS_CONFIG_JUMBO)
            {
                rx_bytes = FXMAC_GET_RX_FRAME_SIZE(curbdptr);
            }
            else
            {
                rx_bytes = FXMAC_BD_GET_LENGTH(curbdptr);
            }

            pbuf_realloc(p, rx_bytes);

            /* Invalidate RX frame before queuing to handle
             * L1 cache prefetch conditions on any architecture.
             */
            // FCacheDCacheInvalidateRange((uintptr)p->payload, rx_bytes);

            /* store it in the receive queue,
             * where it'll be processed by a different handler
             */
            if (FXmacPqEnqueue(&instance_p->recv_q, (void *)p) < 0)
            {
#if LINK_STATS
                lwip_stats.link.memerr++;
                lwip_stats.link.drop++;
#endif
                pbuf_free(p);
            }
            instance_p->buffer.rx_pbufs_storage[bdindex] = (uintptr)NULL;
            curbdptr = FXMAC_BD_RING_NEXT(rxring, curbdptr);
        }

        /* free up the BD's */
        FXmacBdRingFree(rxring, bd_processed, rxbdset);
        SetupRxBds(instance_p, rxring);

    }

    return;
}


void CleanDmaTxdescs(FXmacOs *instance_p)
{
    FXmacBd bdtemplate;
    FXmacBdRing *txringptr;

    txringptr = &FXMAC_GET_TXRING((instance_p->instance));
    FXMAC_BD_CLEAR(&bdtemplate);
    FXMAC_BD_SET_STATUS(&bdtemplate, FXMAC_TXBUF_USED_MASK);

    FXmacBdRingCreate(txringptr, (uintptr)instance_p->buffer.tx_bdspace,
                      (uintptr)instance_p->buffer.tx_bdspace, BD_ALIGNMENT,
                      sizeof(instance_p->buffer.tx_bdspace));

    FXmacBdRingClone(txringptr, &bdtemplate, FXMAC_SEND);
}

FError FXmacInitDma(FXmacOs *instance_p)
{
    FXmacBd bdtemplate;
    FXmacBdRing *rxringptr, *txringptr;
    FXmacBd *rxbd;
    struct pbuf *p;
    FError status;
    int i;
    u32 bdindex;
    u32 *temp;
    uintptr rx_paddr;
    uintptr tx_paddr;
    uintptr pl_paddr;

    /*
     * The BDs need to be allocated in uncached memory. Hence the 1 MB
     * address range allocated for Bd_Space is made uncached
     * by setting appropriate attributes in the translation table.
     * The Bd_Space is aligned to 1MB and has a size of 1 MB. This ensures
     * a reserved uncached area used only for BDs.
     */

    rxringptr = &FXMAC_GET_RXRING(instance_p->instance);
    txringptr = &FXMAC_GET_TXRING(instance_p->instance);
    LOG_I("rxringptr: 0x%08x", rxringptr);
    LOG_I("txringptr: 0x%08x", txringptr);

    LOG_I("rx_bdspace: %p ", instance_p->buffer.rx_bdspace);
    LOG_I("tx_bdspace: %p ", instance_p->buffer.tx_bdspace);

    /* Setup RxBD space. */
    FXMAC_BD_CLEAR(&bdtemplate);
    rx_paddr = (uintptr)instance_p->buffer.rx_bdspace;
#ifdef RT_USING_SMART
    rx_paddr += PV_OFFSET;
#endif

    /* Create the RxBD ring */
    status = FXmacBdRingCreate(rxringptr, (uintptr)rx_paddr,
                               (uintptr)instance_p->buffer.rx_bdspace, BD_ALIGNMENT,
                               FXMAX_RX_PBUFS_LENGTH);

    if (status != FT_SUCCESS)
    {
        LOG_I("Error setting up RxBD space.");
        return ERR_IF;
    }

    status = FXmacBdRingClone(rxringptr, &bdtemplate, FXMAC_RECV);
    if (status != FT_SUCCESS)
    {
        LOG_I("Error initializing RxBD space.");
        return ERR_IF;
    }

    FXMAC_BD_CLEAR(&bdtemplate);
    FXMAC_BD_SET_STATUS(&bdtemplate, FXMAC_TXBUF_USED_MASK);

    tx_paddr = (uintptr)instance_p->buffer.tx_bdspace;
#ifdef RT_USING_SMART
    tx_paddr += PV_OFFSET;
#endif
    /* Create the TxBD ring */
    status = FXmacBdRingCreate(txringptr, (uintptr)tx_paddr,
                               (uintptr)instance_p->buffer.tx_bdspace, BD_ALIGNMENT,
                               FXMAX_TX_PBUFS_LENGTH);

    if (status != FT_SUCCESS)
    {
        return ERR_IF;
    }

    /* We reuse the bd template, as the same one will work for both rx and tx. */
    status = FXmacBdRingClone(txringptr, &bdtemplate, FXMAC_SEND);
    if (status != FT_SUCCESS)
    {
        return ERR_IF;
    }

    /*
     * Allocate RX descriptors, 1 RxBD at a time.
     */
    for (i = 0; i < FXMAX_RX_PBUFS_LENGTH; i++)
    {
        if (instance_p->config & FXMAC_OS_CONFIG_JUMBO)
        {
            p = pbuf_alloc(PBUF_RAW, FXMAC_MAX_FRAME_SIZE_JUMBO, PBUF_RAM);
        }
        else
        {
            p = pbuf_alloc(PBUF_RAW, FXMAC_MAX_FRAME_SIZE, PBUF_RAM);
        }

        if (!p)
        {
#if LINK_STATS
            lwip_stats.link.memerr++;
            lwip_stats.link.drop++;
#endif
            LOG_E("Unable to alloc pbuf in InitDma.");
            return ERR_IF;
        }
        status = FXmacBdRingAlloc(rxringptr, 1, &rxbd);
        if (status != FT_SUCCESS)
        {
            LOG_E("InitDma: Error allocating RxBD.");
            pbuf_free(p);
            return ERR_IF;
        }
        /* Enqueue to HW */
        status = FXmacBdRingToHw(rxringptr, 1, rxbd);
        if (status != FT_SUCCESS)
        {
            LOG_E("Error: committing RxBD to HW.");
            pbuf_free(p);
            FXmacBdRingUnAlloc(rxringptr, 1, rxbd);
            return ERR_IF;
        }

        bdindex = FXMAC_BD_TO_INDEX(rxringptr, rxbd);
        temp = (u32 *)rxbd;
        *temp = 0;
        if (bdindex == (FXMAX_RX_PBUFS_LENGTH - 1))
        {
            *temp = 0x00000002;
        }
        temp++;
        *temp = 0;

        pl_paddr = (uintptr)p->payload;
#ifdef RT_USING_SMART
        pl_paddr += PV_OFFSET;
#endif
        FXMAC_BD_SET_ADDRESS_RX(rxbd, (uintptr)pl_paddr);

        instance_p->buffer.rx_pbufs_storage[bdindex] = (uintptr)p;
    }

    FXmacSetQueuePtr(&(instance_p->instance), instance_p->instance.tx_bd_queue.bdring.phys_base_addr, 0, (u16)FXMAC_SEND);
    FXmacSetQueuePtr(&(instance_p->instance), instance_p->instance.rx_bd_queue.bdring.phys_base_addr, 0, (u16)FXMAC_RECV);

    return 0;
}

static void FreeOnlyTxPbufs(FXmacOs *instance_p)
{
    u32 index;
    struct pbuf *p;

    for (index = 0; index < (FXMAX_TX_PBUFS_LENGTH); index++)
    {
        if (instance_p->buffer.tx_pbufs_storage[index] != 0)
        {
            p = (struct pbuf *)instance_p->buffer.tx_pbufs_storage[index];
            pbuf_free(p);
            instance_p->buffer.tx_pbufs_storage[index] = (uintptr)NULL;
        }
        instance_p->buffer.tx_pbufs_storage[index] = (uintptr)0;
    }
}


static void FreeOnlyRxPbufs(FXmacOs *instance_p)
{
    u32 index;
    struct pbuf *p;

    for (index = 0; index < (FXMAX_RX_PBUFS_LENGTH); index++)
    {
        if (instance_p->buffer.rx_pbufs_storage[index] != 0)
        {
            p = (struct pbuf *)instance_p->buffer.rx_pbufs_storage[index];
            pbuf_free(p);
            instance_p->buffer.rx_pbufs_storage[index] = (uintptr)0;
        }
    }
}


static void FreeTxRxPbufs(FXmacOs *instance_p)
{
    u32 rx_queue_len;
    struct pbuf *p;
    /* first :free PqQueue data */
    rx_queue_len = FXmacPqQlength(&instance_p->recv_q);

    while (rx_queue_len)
    {
        /* return one packet from receive q */
        p = (struct pbuf *)FXmacPqDequeue(&instance_p->recv_q);
        pbuf_free(p);
        LOG_E("Delete queue %p", p);
        rx_queue_len--;
    }
    FreeOnlyTxPbufs(instance_p);
    FreeOnlyRxPbufs(instance_p);

}

/* interrupt */
static void FXmacHandleDmaTxError(FXmacOs *instance_p)
{
    s32_t status = FT_SUCCESS;
    u32 dmacrreg;

    FreeTxRxPbufs(instance_p);
    status = FXmacCfgInitialize(&instance_p->instance, &instance_p->instance.config);

    if (status != FT_SUCCESS)
    {
        LOG_E("In %s:EmacPs Configuration Failed....", __func__);
    }

    /* initialize the mac */
    FXmacInitOnError(instance_p); /* need to set mac filter address */
    dmacrreg = FXMAC_READREG32(instance_p->instance.config.base_address, FXMAC_DMACR_OFFSET);
    dmacrreg = dmacrreg | (FXMAC_DMACR_ORCE_DISCARD_ON_ERR_MASK); /* force_discard_on_err */
    FXMAC_WRITEREG32(instance_p->instance.config.base_address, FXMAC_DMACR_OFFSET, dmacrreg);
    FXmacSetupIsr(instance_p);
    FXmacInitDma(instance_p);

    FXmacStart(&instance_p->instance);

}

void FXmacHandleTxErrors(FXmacOs *instance_p)
{
    u32 netctrlreg;

    netctrlreg = FXMAC_READREG32(instance_p->instance.config.base_address,
                                 FXMAC_NWCTRL_OFFSET);
    netctrlreg = netctrlreg & (~FXMAC_NWCTRL_TXEN_MASK);
    FXMAC_WRITEREG32(instance_p->instance.config.base_address,
                     FXMAC_NWCTRL_OFFSET, netctrlreg);
    FreeOnlyTxPbufs(instance_p);

    CleanDmaTxdescs(instance_p);
    netctrlreg = FXMAC_READREG32(instance_p->instance.config.base_address, FXMAC_NWCTRL_OFFSET);
    netctrlreg = netctrlreg | (FXMAC_NWCTRL_TXEN_MASK);
    FXMAC_WRITEREG32(instance_p->instance.config.base_address, FXMAC_NWCTRL_OFFSET, netctrlreg);
}

void FXmacErrorHandler(void *arg, u8 direction, u32 error_word)
{
    FXmacBdRing *rxring;
    FXmacBdRing *txring;
    FXmacOs *instance_p;

    instance_p = (FXmacOs *)arg;
    rxring = &FXMAC_GET_RXRING(instance_p->instance);
    txring = &FXMAC_GET_TXRING(instance_p->instance);

    if (error_word != 0)
    {
        switch (direction)
        {
            case FXMAC_RECV:
                if (error_word & FXMAC_RXSR_HRESPNOK_MASK)
                {
                    LOG_I("Receive DMA error.");
                    FXmacHandleDmaTxError(instance_p);
                }
                if (error_word & FXMAC_RXSR_RXOVR_MASK)
                {
                    LOG_I("Receive over run.");
                    FXmacRecvHandler(arg);
                }
                if (error_word & FXMAC_RXSR_BUFFNA_MASK)
                {
                    LOG_I("Receive buffer not available.");
                    FXmacRecvHandler(arg);
                }
                break;
            case FXMAC_SEND:
                if (error_word & FXMAC_TXSR_HRESPNOK_MASK)
                {
                    LOG_I("Transmit DMA error.");
                    FXmacHandleDmaTxError(instance_p);
                }
                if (error_word & FXMAC_TXSR_URUN_MASK)
                {
                    LOG_I("Transmit under run.");
                    FXmacHandleTxErrors(instance_p);
                }
                if (error_word & FXMAC_TXSR_BUFEXH_MASK)
                {
                    LOG_I("Transmit buffer exhausted.");
                    FXmacHandleTxErrors(instance_p);
                }
                if (error_word & FXMAC_TXSR_RXOVR_MASK)
                {
                    LOG_I("Transmit retry excessed limits.");
                    FXmacHandleTxErrors(instance_p);
                }
                if (error_word & FXMAC_TXSR_FRAMERX_MASK)
                {
                    LOG_I("Transmit collision.");
                    FXmacProcessSentBds(instance_p, txring);
                }
                break;
        }
    }
}

void FXmacLinkChange(void *arg)
{
    u32 ctrl;
    u32 link, link_status;
    FXmac *xmac_p;
    FXmacOs *instance_p;

    instance_p = (FXmacOs *)arg;
    xmac_p = &instance_p->instance;

    if (xmac_p->config.interface == FXMAC_PHY_INTERFACE_MODE_SGMII)
    {
        LOG_I("xmac_p->config.base_address is %p", xmac_p->config.base_address);
        ctrl = FXMAC_READREG32(xmac_p->config.base_address, FXMAC_PCS_AN_LP_OFFSET);
        link = (ctrl & FXMAC_PCS_LINK_PARTNER_NEXT_PAGE_STATUS) >> 15;


        switch (link)
        {
            case 0:
                LOG_I("Link status is down");
                link_status = FXMAC_LINKDOWN;
                break;
            case 1:
                LOG_I("Link status is up");
                link_status = FXMAC_LINKUP;
                break;
            default:
                LOG_E("Link status is error 0x%x ", link);
                return;
        }

        if (link_status == FXMAC_LINKUP)
        {
            if (link_status != xmac_p->link_status)
            {
                xmac_p->link_status = FXMAC_NEGOTIATING;
                LOG_I("Need NEGOTIATING.");
            }
        }
        else
        {
            xmac_p->link_status = FXMAC_LINKDOWN;
        }
    }
}

/* phy */

/**
 * @name: FXmacPhyLinkDetect
 * @msg:  Get current link status
 * @note:
 * @param {FXmac} *fxmac_p
 * @param {u32} phy_addr
 * @return {*} 1 is link up , 0 is link down
 */
static u32 FXmacPhyLinkDetect(FXmac *xmac_p, u32 phy_addr)
{
    u16 status;

    /* Read Phy Status register twice to get the confirmation of the current
     * link status.
     */

    FXmacPhyRead(xmac_p, phy_addr, PHY_STATUS_REG_OFFSET, &status);

    if (status & PHY_STAT_LINK_STATUS)
    {
        return 1;
    }
    return 0;
}

static u32 FXmacPhyAutonegStatus(FXmac *xmac_p, u32 phy_addr)
{
    u16 status;

    /* Read Phy Status register twice to get the confirmation of the current
     * link status.
     */
    FXmacPhyRead(xmac_p, phy_addr, PHY_STATUS_REG_OFFSET, &status);

    if (status & PHY_STATUS_AUTONEGOTIATE_COMPLETE)
    {
        return 1;
    }
    return 0;
}

enum lwip_port_link_status FXmacLwipPortLinkDetect(FXmacOs *instance_p)
{
    u32 phy_link_status;
    FXmac *xmac_p = &instance_p->instance;

    if (xmac_p->is_ready != (u32)FT_COMPONENT_IS_READY)
    {
        return ETH_LINK_UNDEFINED;
    }

    phy_link_status = FXmacPhyLinkDetect(xmac_p, xmac_p->phy_address);

    if ((xmac_p->link_status == FXMAC_LINKUP) && (!phy_link_status))
    {
        xmac_p->link_status = FXMAC_LINKDOWN;
    }

    switch (xmac_p->link_status)
    {
        case FXMAC_LINKUP:
            return ETH_LINK_UP;
        case FXMAC_LINKDOWN:
            xmac_p->link_status = FXMAC_NEGOTIATING;
            LOG_D("Ethernet Link down.");
            return ETH_LINK_DOWN;
        case FXMAC_NEGOTIATING:
            if ((phy_link_status == FXMAC_LINKUP) && FXmacPhyAutonegStatus(xmac_p, xmac_p->phy_address))
            {
                err_t phy_ret;
                phy_ret = FXmacPhyInit(xmac_p, xmac_p->config.speed, xmac_p->config.duplex, xmac_p->config.auto_neg, XMAC_PHY_RESET_DISABLE);

                if (phy_ret != FT_SUCCESS)
                {
                    LOG_E("FXmacPhyInit is error.");
                    return ETH_LINK_DOWN;
                }
                FXmacSelectClk(xmac_p);
                FXmacInitInterface(xmac_p);

                /* Initiate Phy setup to get link speed */
                xmac_p->link_status = FXMAC_LINKUP;
                LOG_D("Ethernet Link up.");
                return ETH_LINK_UP;
            }
            return ETH_LINK_DOWN;
        default:
            return ETH_LINK_DOWN;
    }
}

enum lwip_port_link_status FXmacPhyReconnect(FXmacOs *instance_p)
{
    FXmac *xmac_p;

    xmac_p = &instance_p->instance;

    if (xmac_p->config.interface == FXMAC_PHY_INTERFACE_MODE_SGMII)
    {
        rt_hw_interrupt_mask(xmac_p->config.queue_irq_num[0]);
        if (xmac_p->link_status == FXMAC_NEGOTIATING)
        {
            /* auto negotiation again*/
            err_t phy_ret;
            phy_ret = FXmacPhyInit(xmac_p, xmac_p->config.speed, xmac_p->config.duplex, xmac_p->config.auto_neg, XMAC_PHY_RESET_DISABLE);
            if (phy_ret != FT_SUCCESS)
            {
                LOG_I("FXmacPhyInit is error.");
                rt_hw_interrupt_umask(xmac_p->config.queue_irq_num[0]);
                return ETH_LINK_DOWN;
            }
            FXmacSelectClk(xmac_p);
            FXmacInitInterface(xmac_p);
            xmac_p->link_status = FXMAC_LINKUP;
        }

        rt_hw_interrupt_umask(xmac_p->config.queue_irq_num[0]);

        switch (xmac_p->link_status)
        {
            case FXMAC_LINKDOWN:
                return ETH_LINK_DOWN;
            case FXMAC_LINKUP:
                return ETH_LINK_UP;
            default:
                return ETH_LINK_DOWN;
        }
    }
    else if ((xmac_p->config.interface == FXMAC_PHY_INTERFACE_MODE_RMII) || (xmac_p->config.interface == FXMAC_PHY_INTERFACE_MODE_RGMII))
    {
        return FXmacLwipPortLinkDetect(instance_p);
    }
    else
    {
        switch (xmac_p->link_status)
        {
            case FXMAC_LINKDOWN:
                return ETH_LINK_DOWN;
            case FXMAC_LINKUP:
                return ETH_LINK_UP;
            default:
                return ETH_LINK_DOWN;
        }
    }
}

static void FxmacOsIntrHandler(s32 vector, void *args)
{
    isr_calling_flg++;
    FXmacIntrHandler(vector, args);
    isr_calling_flg--;
}

static void FXmacSetupIsr(FXmacOs *instance_p)
{

    /* Setup callbacks */
    FXmacSetHandler(&instance_p->instance, FXMAC_HANDLER_DMARECV, FXmacRecvSemaphoreHandler, instance_p);
    FXmacSetHandler(&instance_p->instance, FXMAC_HANDLER_ERROR, FXmacErrorHandler, instance_p);
    FXmacSetHandler(&instance_p->instance, FXMAC_HANDLER_LINKCHANGE, FXmacLinkChange, instance_p);

    rt_hw_interrupt_install(instance_p->instance.config.queue_irq_num[0], FxmacOsIntrHandler, &instance_p->instance, "fxmac");
    rt_hw_interrupt_umask(instance_p->instance.config.queue_irq_num[0]);
}

/*  init fxmac instance */

static void FXmacInitOnError(FXmacOs *instance_p)
{
    FXmac *xmac_p;
    u32 status = FT_SUCCESS;
    xmac_p = &instance_p->instance;

    /* set mac address */
    status = FXmacSetMacAddress(xmac_p, (void *)(instance_p->hwaddr), 1);
    if (status != FT_SUCCESS)
    {
        LOG_E("In %s:Emac Mac Address set failed...", __func__);
    }
}

/* step 1: initialize instance */
/* step 2: depend on config set some options : JUMBO / IGMP */
/* step 3: FXmacSelectClk */
/* step 4: FXmacInitInterface */
/* step 5: initialize phy */
/* step 6: initialize dma */
/* step 7: initialize interrupt */
/* step 8: start mac */

FError FXmacOsInit(FXmacOs *instance_p)
{
    FXmacConfig mac_config;
    FXmacConfig *mac_config_p;
    FXmacPhyInterface interface = FXMAC_PHY_INTERFACE_MODE_SGMII;
    FXmac *xmac_p;
    u32 dmacrreg;
    FError status;
    FASSERT(instance_p != NULL);
    FASSERT(instance_p->mac_config.instance_id < FXMAC_NUM);

    xmac_p = &instance_p->instance;
    LOG_I("instance_id IS %d", instance_p->mac_config.instance_id);
    mac_config_p = FXmacLookupConfig(instance_p->mac_config.instance_id);
    if (mac_config_p == NULL)
    {
        LOG_E("FXmacLookupConfig is error , instance_id is %d", instance_p->mac_config.instance_id);
        return FREERTOS_XMAC_INIT_ERROR;
    }
#ifdef RT_USING_SMART
    mac_config_p->base_address = (uintptr)rt_ioremap((void *)mac_config_p->base_address, 0x2000);
#endif
    mac_config = *mac_config_p;
    switch (instance_p->mac_config.interface)
    {
        case FXMAC_OS_INTERFACE_SGMII:
            interface = FXMAC_PHY_INTERFACE_MODE_SGMII;
            LOG_I("SGMII select.");
            break;
        case FXMAC_OS_INTERFACE_RMII:
            interface = FXMAC_PHY_INTERFACE_MODE_RMII;
            LOG_I("RMII select.");
            break;
        case FXMAC_OS_INTERFACE_RGMII:
            LOG_I("RGMII select.");
            interface = FXMAC_PHY_INTERFACE_MODE_RGMII;
            break;
        default:
            LOG_E("Update interface is error , interface is %d", instance_p->mac_config.instance_id);
            return FREERTOS_XMAC_INIT_ERROR;
    }
    mac_config.interface = interface;

    if (instance_p->mac_config.autonegotiation)
    {
        mac_config.auto_neg = 1;
    }
    else
    {
        mac_config.auto_neg = 0;
    }

    switch (instance_p->mac_config.phy_speed)
    {
        case FXMAC_PHY_SPEED_10M:
            mac_config.speed = FXMAC_SPEED_10;
            break;
        case FXMAC_PHY_SPEED_100M:
            mac_config.speed = FXMAC_SPEED_100;
            break;
        case FXMAC_PHY_SPEED_1000M:
            mac_config.speed = FXMAC_SPEED_1000;
            break;
        default:
            LOG_E("Setting speed is not valid , speed is %d", instance_p->mac_config.phy_speed);
            return FREERTOS_XMAC_INIT_ERROR;
    }

    switch (instance_p->mac_config.phy_duplex)
    {
        case FXMAC_PHY_HALF_DUPLEX:
            mac_config.duplex = 0;
            break;
        case FXMAC_PHY_FULL_DUPLEX:
            mac_config.duplex = 1;
            break;
    }

    status = FXmacCfgInitialize(xmac_p, &mac_config);
    if (status != FT_SUCCESS)
    {
        LOG_E("In %s:EmacPs Configuration Failed....", __func__);
    }

    if (instance_p->config & FXMAC_OS_CONFIG_JUMBO)
    {
        FXmacSetOptions(xmac_p, FXMAC_JUMBO_ENABLE_OPTION, 0);
    }

    if (instance_p->config & FXMAC_OS_CONFIG_MULTICAST_ADDRESS_FILITER)
    {
        FXmacSetOptions(xmac_p, FXMAC_MULTICAST_OPTION, 0);
    }

    /* enable copy all frames */
    if (instance_p->config & FXMAC_OS_CONFIG_COPY_ALL_FRAMES)
    {
        FXmacSetOptions(xmac_p, FXMAC_PROMISC_OPTION, 0);
    }

    status = FXmacSetMacAddress(xmac_p, (void *)(instance_p->hwaddr), 0);
    if (status != FT_SUCCESS)
    {
        LOG_E("In %s:Emac Mac Address set failed...", __func__);
    }

    /* close fcs check */
    if (instance_p->config & FXMAC_OS_CONFIG_CLOSE_FCS_CHECK)
    {
        FXmacSetOptions(xmac_p, FXMAC_FCS_STRIP_OPTION, 0);
    }

    /* initialize phy */
    status = FXmacPhyInit(xmac_p, xmac_p->config.speed, xmac_p->config.duplex, xmac_p->config.auto_neg, XMAC_PHY_RESET_ENABLE);
    if (status != FT_SUCCESS)
    {
        LOG_W("FXmacPhyInit is error.");
    }

    FXmacSelectClk(xmac_p);
    FXmacInitInterface(xmac_p);

    /* initialize dma */
    dmacrreg = FXMAC_READREG32(xmac_p->config.base_address, FXMAC_DMACR_OFFSET);
    dmacrreg &= (~(FXMAC_DMACR_BLENGTH_MASK));
    dmacrreg |= (FXMAC_DMACR_INCR16_AHB_AXI_BURST); /* Attempt to use bursts of up to 16. */
    FXMAC_WRITEREG32(xmac_p->config.base_address, FXMAC_DMACR_OFFSET, dmacrreg);
    FXmacInitDma(instance_p);


    /* initialize interrupt */
    FXmacSetupIsr(instance_p);

    return FT_SUCCESS;
}




/**
 * @name: FXmacOsRx
 * @msg: struct pbuf *FXmacOsRx(FXmacOs *instance_p)
 * @return {*}
 * @note:
 * @param {FXmacOs} *instance_p
 */
struct pbuf *FXmacOsRx(FXmacOs *instance_p)
{
    FASSERT(instance_p != NULL);
    struct pbuf *p;

    /* see if there is data to process */
    if (FXmacPqQlength(&instance_p->recv_q) == 0)
    {
        return NULL;
    }
    /* return one packet from receive q */
    p = (struct pbuf *)FXmacPqDequeue(&instance_p->recv_q);

    return p;
}

static FError FXmacOsOutput(FXmacOs *instance_p, struct pbuf *p)
{
    FError status;

    status = FXmacSgsend(instance_p, p);
    if (status != FT_SUCCESS)
    {
#if LINK_STATS
        lwip_stats.link.drop++;
#endif
    }

#if LINK_STATS
    lwip_stats.link.xmit++;
#endif /* LINK_STATS */

    return status;
}

FError FXmacOsTx(FXmacOs *instance_p, void *tx_buf)
{
    FXmacBdRing *txring;
    FError ret;
    struct pbuf *p;
    FASSERT(instance_p != NULL);
    FASSERT(tx_buf != NULL);

    p = tx_buf;
    txring = &(FXMAC_GET_TXRING(instance_p->instance));
    FXmacProcessSentBds(instance_p, txring);

    /* check if space is available to send */
    if (IsTxSpaceAvailable(instance_p))
    {
        ret = FXmacOsOutput(instance_p, p);
    }
    else
    {
#if LINK_STATS
        lwip_stats.link.drop++;
#endif
        LOG_E("Pack dropped, no space.");
        ret = FREERTOS_XMAC_NO_VALID_SPACE;
    }

    return ret;
}

FXmacOs *FXmacOsGetInstancePointer(FXmacOsControl *config_p)
{
    FXmacOs *instance_p;
    FASSERT(config_p != NULL);
    FASSERT(config_p->instance_id < FXMAC_NUM);
    FASSERT_MSG(config_p->interface < FXMAC_OS_INTERFACE_LENGTH, "config_p->interface %d is over %d", config_p->interface, FXMAC_OS_INTERFACE_LENGTH);
    FASSERT_MSG(config_p->autonegotiation <= 1, "config_p->autonegotiation %d is over 1", config_p->autonegotiation);
    FASSERT_MSG(config_p->phy_speed <= FXMAC_PHY_SPEED_1000M, "config_p->phy_speed %d is over 1000", config_p->phy_speed);
    FASSERT_MSG(config_p->phy_duplex <= FXMAC_PHY_FULL_DUPLEX, "config_p->phy_duplex %d is over FXMAC_PHY_FULL_DUPLEX", config_p->phy_duplex);

    instance_p = &fxmac_os_instace[config_p->instance_id];
    memcpy(&instance_p->mac_config, config_p, sizeof(FXmacOsControl));
    return instance_p;
}

void FXmacOsStart(FXmacOs *instance_p)
{
    FASSERT(instance_p != NULL);

    /* start mac */
    instance_p->instance.mask &= (~FXMAC_IXR_TXCOMPL_MASK);
    FXmacStart(&instance_p->instance);
}

static rt_err_t rt_xmac_init(rt_device_t dev)
{

    struct eth_device *pXmacParent;
    FXmacOs *pOsMac;

    FError ret;

    pXmacParent = rt_container_of(dev, struct eth_device, parent);
    if (NULL == pXmacParent)
    {
        return -RT_ENOMEM;
    }

    pOsMac = rt_container_of(pXmacParent, FXmacOs, parent);
    if (NULL == pOsMac)
    {
        return -RT_ENOMEM;
    }


    ret = FXmacOsInit(pOsMac);

    if (ret != FT_SUCCESS)
    {
        LOG_E("FXmacOsInit is error\r\n");
        return -RT_ERROR;
    }
    rt_kprintf("FXMAC OS Init Success!\n");


    return RT_EOK;
}

static rt_err_t rt_xmac_open(rt_device_t dev, rt_uint16_t oflag)
{
    LOG_D("xmac open");
    return RT_EOK;
}

static rt_err_t rt_xmac_close(rt_device_t dev)
{
    LOG_D("xmac close");
    return RT_EOK;
}

static rt_ssize_t rt_xmac_read(rt_device_t dev, rt_off_t pos, void *buffer, rt_size_t size)
{
    LOG_D("xmac read");
    rt_set_errno(-RT_ENOSYS);
    return 0;
}

static rt_ssize_t rt_xmac_write(rt_device_t dev, rt_off_t pos, const void *buffer, rt_size_t size)
{
    LOG_D("xmac write");
    rt_set_errno(-RT_ENOSYS);
    return 0;
}

static rt_err_t rt_xmac_control(rt_device_t dev, int cmd, void *args)
{

    FXmacOs *pOsMac;
    struct eth_device *pXmacParent;


    pXmacParent = rt_container_of(dev, struct eth_device, parent);

    if (NULL == pXmacParent)
    {
        return -RT_ENOMEM;
    }

    pOsMac = rt_container_of(pXmacParent, FXmacOs, parent);
    if (NULL == pOsMac)
    {
        return -RT_ENOMEM;
    }
    switch (cmd)
    {
        case NIOCTL_GADDR:
            /* get mac address */
            if (args)
            {
                rt_memcpy(args, pOsMac->hwaddr, 6);
            }

            else
            {
                return -RT_ERROR;
            }
            break;

        default:
            break;
    }

    return RT_EOK;
}

rt_err_t rt_xmac_tx(rt_device_t dev, struct pbuf *p)
{
    FXmacOs *pOsMac;
    struct eth_device *pXmacParent;
    FError  ret;

    pXmacParent = rt_container_of(dev, struct eth_device, parent);
    if (NULL == pXmacParent)
    {
        return -RT_ENOMEM;
    }

    pOsMac = rt_container_of(pXmacParent, FXmacOs, parent);
    if (NULL == pOsMac)
    {
        return -RT_ENOMEM;
    }

#if RT_LWIP_ETH_PAD_SIZE
    pbuf_header(p, -RT_LWIP_ETH_PAD_SIZE); /* reclaim the padding word */
#endif
    ret = FXmacOsTx(pOsMac, p);
#if RT_LWIP_ETH_PAD_SIZE
    pbuf_header(p, ETH_PAD_SIZE); /* reclaim the padding word */
#endif


    if (ret != FT_SUCCESS)
    {
        return ERR_MEM;
    }

    return RT_EOK;

}

struct pbuf *rt_xmac_rx(rt_device_t dev)
{
    FXmacOs *pOsMac;
    struct eth_device *pXmacParent;
    struct pbuf *p;

    pXmacParent = rt_container_of(dev, struct eth_device, parent);
    if (NULL == pXmacParent)
    {
        return RT_NULL;
    }

    pOsMac = rt_container_of(pXmacParent, FXmacOs, parent);
    if (NULL == pOsMac)
    {
        return RT_NULL;
    }

    FXmacRecvHandler(pOsMac);
    p = FXmacOsRx(pOsMac);
    return p;
}


enum lwip_port_link_status eth_link_detect(FXmacOs *instance_p)
{
    if (instance_p->instance.is_ready != FT_COMPONENT_IS_READY)
    {
        return ETH_LINK_UNDEFINED;
    }

    return  FXmacPhyReconnect(instance_p);
}


static void ethernet_link_thread(void *Args)
{

    if (RT_NULL == Args)
    {
        return;
    }

    FXmacOs *pOsMac;
    pOsMac = (FXmacOs *)Args;

    while (1)
    {
        /* Call eth_link_detect() every 500ms to detect Ethernet link
         * change.
         */

        switch (eth_link_detect(pOsMac))
        {
            case ETH_LINK_UP:
                if (pOsMac->is_link_up == 0)
                {
                    LOG_I("netif flag is link_up\n");
                    pOsMac->is_link_up = 1;
                    eth_device_linkchange(&pOsMac->parent, RT_TRUE);
                }
                break;
            case ETH_LINK_DOWN:
            default:
                if (pOsMac->is_link_up == 1)
                {
                    LOG_I("netif flag is link_down\n");
                    pOsMac->is_link_up = 0;
                    eth_device_linkchange(&pOsMac->parent, RT_FALSE);
                }
                break;
        }
        rt_thread_mdelay(500);
    }
}

#ifdef RT_USING_DEVICE_OPS
const struct rt_device_ops net_ops=
{
    rt_xmac_init,
    rt_xmac_open,
    rt_xmac_close,
    rt_xmac_read,
    rt_xmac_write,
    rt_xmac_control
};
#endif

static int rt_hw_xmac_init(FXmacOs *pOsMac, const char *name, const char *link_thread_name)
{
    rt_err_t state = RT_EOK;

    #ifdef RT_USING_DEVICE_OPS
    pOsMac->parent.parent.ops= &net_ops;
    #else
    pOsMac->parent.parent.init = rt_xmac_init;
    pOsMac->parent.parent.open = rt_xmac_open;
    pOsMac->parent.parent.close = rt_xmac_close;
    pOsMac->parent.parent.read = rt_xmac_read;
    pOsMac->parent.parent.write = rt_xmac_write;
    pOsMac->parent.parent.control = rt_xmac_control;
    #endif
    pOsMac->parent.parent.user_data = RT_NULL;

    pOsMac->parent.eth_rx = rt_xmac_rx;
    pOsMac->parent.eth_tx = rt_xmac_tx;

    /* register eth device */
    state = eth_device_init(&(pOsMac->parent), name);

    if (RT_EOK != state)
    {
        LOG_E("xmac device init faild: %d", state);
        return -RT_ERROR;
    }
    rt_kprintf("Xmac %s Initiailized!\n", name);



    state = rt_thread_init(&pOsMac->_link_thread,
                           link_thread_name,
                           ethernet_link_thread,
                           pOsMac,
                           &pOsMac->_link_thread_stack[0],
                           sizeof(pOsMac->_link_thread_stack),
                           12, 2);
    if (RT_EOK == state)
    {
        rt_thread_startup(&pOsMac->_link_thread);
    }
    else
    {
        LOG_E("rt_thread_init is error");
        return -RT_ERROR;
    }

    return RT_EOK;
}
static int rt_hw_xmac_eth_init(void)
{
    rt_err_t state = RT_EOK;
    FXmacOsControl os_config;
    FXmacOs *pOsMac;

#if defined(MAC_NUM0)
    /* os_config initialize,need to be set manually here */
    os_config.instance_id = MAC_NUM0_CONTROLLER;
    os_config.interface = MAC_NUM0_MII_INTERFACE;
    os_config.autonegotiation = 1; /* 1 is autonegotiation ,0 is manually set */
    os_config.phy_speed = FXMAC_PHY_SPEED_1000M;  /* FXMAC_PHY_SPEED_XXX */
    os_config.phy_duplex = FXMAC_PHY_FULL_DUPLEX; /* FXMAC_PHY_XXX_DUPLEX */

    pOsMac = FXmacOsGetInstancePointer(&os_config);
    if (pOsMac == NULL)
    {
        LOG_E("FXmacOsGetInstancePointer is error\r\n");
        return -RT_ERROR;
    }

    const char *os_drv_xmac0_name = "e0";
    const char *e0_thread_name = "e0_link_detect";

    state = rt_hw_xmac_init(pOsMac, os_drv_xmac0_name, e0_thread_name);
    extern void set_if(const char *netif_name, const char *ip_addr, const char *gw_addr, const char *nm_addr);

    rt_kprintf("Set netif %s ip addr!\n", os_drv_xmac0_name);
    set_if(os_drv_xmac0_name, "192.168.4.10", "192.168.4.1", "255.255.255.0");
    if (RT_EOK != state)
    {
        goto __exit;
    }
#endif
#if defined(MAC_NUM1)
    os_config.instance_id = MAC_NUM1_CONTROLLER;
    os_config.interface = MAC_NUM1_MII_INTERFACE;
    os_config.autonegotiation = 1; /* 1 is autonegotiation ,0 is manually set */
    os_config.phy_speed = FXMAC_PHY_SPEED_1000M;  /* FXMAC_PHY_SPEED_XXX */
    os_config.phy_duplex = FXMAC_PHY_FULL_DUPLEX; /* FXMAC_PHY_XXX_DUPLEX */

    pOsMac = FXmacOsGetInstancePointer(&os_config);
    if (pOsMac == NULL)
    {
        LOG_E("FXmacOsGetInstancePointer is error\r\n");
        return -RT_ERROR;
    }

    const char *os_drv_xmac1_name = "e1";
    const char *e1_thread_name = "e1_link_detect";

    state = rt_hw_xmac_init(pOsMac, os_drv_xmac1_name, e1_thread_name);
    rt_kprintf("Set Xmac %s ip addr!\n", os_drv_xmac1_name);
    set_if(os_drv_xmac1_name, "192.168.4.11", "192.168.4.1", "255.255.255.0");
    if (RT_EOK != state)
    {
        goto __exit;
    }
#endif

#if defined(MAC_NUM0)
        rt_kprintf("Start Xmac NUM0 \n");
        FXmacOsStart(&fxmac_os_instace[MAC_NUM0_CONTROLLER]);
#endif
#if defined(MAC_NUM1)
        rt_kprintf("Start Xmac NUM1 \n");
        FXmacOsStart(&fxmac_os_instace[MAC_NUM1_CONTROLLER]);
#endif

__exit:
    return state;
}
INIT_DEVICE_EXPORT(rt_hw_xmac_eth_init);
#endif