summaryrefslogtreecommitdiff
path: root/libcpu/risc-v/common/mmu.c
blob: 8a15c24f2d869c79dd6d1229824ca6e78c96b2ba (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
/*
 * Copyright (c) 2006-2025 RT-Thread Development Team
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * Change Logs:
 * Date           Author       Notes
 * 2021-01-30     lizhirui     first version
 * 2022-12-13     WangXiaoyao  Port to new mm
 * 2023-10-12     Shell        Add permission control API
 * 2025-04-26     GuEe-GUI     Follow the specific and vendor
 */

#include <rthw.h>
#include <rtthread.h>

#define DBG_TAG "hw.mmu"
#define DBG_LVL DBG_INFO
#include <rtdbg.h>

#include <cpu.h>
#include <csr.h>
#include <mmu.h>
#include <tlb.h>
#include <cache.h>
#include <ioremap.h>
#include <isa_ext.h>
#include <mm_page.h>
#include <mm_aspace.h>
#include <board.h>
#ifdef RT_USING_SMART
#include <lwp_user_mm.h>
#endif

#ifndef ARCH_TEXT_OFFSET
#if __riscv_xlen == 64
#define ARCH_TEXT_OFFSET 0x200000
#elif __riscv_xlen == 32
#define ARCH_TEXT_OFFSET 0x400000
#else
#error "Unexpected __riscv_xlen"
#endif
#endif

#ifndef ARCH_RAM_OFFSET
#define ARCH_RAM_OFFSET 0
#endif

#ifndef KERNEL_VADDR_START
#ifdef KERNEL_ASPACE_START
#define KERNEL_VADDR_START KERNEL_ASPACE_START
#else
#define KERNEL_VADDR_START (ARCH_RAM_OFFSET + ARCH_TEXT_OFFSET)
#endif
#endif

#if defined(RT_USING_SMP) && RT_CPUS_NR > 1
#define MMU_PERCPU
#endif

#if __riscv_xlen == 32
#define VPN_BITS    10
#define VPN_MASK    0x3ffUL
#define PPN_MASK    0xfff00000UL
#define LEVEL_MAX   1
rt_weak rt_uint8_t rt_hw_arch_vaddr_width = 32;
#else
#define VPN_BITS    9
#define VPN_MASK    0x1ffUL
#define PPN_MASK    0x3ffffffffffc00UL
#define LEVEL_MAX   5
rt_weak rt_uint8_t rt_hw_arch_vaddr_width = 39;
#endif

struct mmu_level_info
{
    rt_ubase_t *pos;
    void *page;
};

#ifdef MMU_PERCPU
struct mmu_percpu_level_info
{
    rt_ubase_t offset;
    rt_ubase_t *page;
};

#define PERCPU_OFFSET rt_hw_cpu_id() * ARCH_PAGE_SIZE
static struct mmu_percpu_level_info percpu_level[RT_CPUS_NR][LEVEL_MAX + 1];
#else
#define PERCPU_OFFSET 0
#endif

rt_ubase_t MMUTable[(ARCH_PAGE_SIZE / sizeof(rt_ubase_t)) * RT_CPUS_NR]
        rt_align(ARCH_PAGE_SIZE);

static rt_uint8_t satp_level_4k, satp_level_2M;
static rt_ubase_t satp_mode;

struct page_table
{
    rt_ubase_t page[ARCH_PAGE_SIZE / sizeof(rt_ubase_t)];
};
static struct page_table *__init_page_array;

rt_inline rt_ubase_t mmu_attr_fixup(rt_ubase_t attr)
{
#if !defined(__HAS_MMU_VENDOR__) && __riscv_xlen != 32
    if (!riscv_isa_ext_test(SVPBMT))
    {
        attr &= ~PTE_VENDOR_MTMASK;
    }
#endif

    return attr;
}

void set_free_page(void *page_array)
{
    __init_page_array = page_array;
}

rt_ubase_t get_free_page(void)
{
    static rt_ubase_t page_off;

    if (page_off < ARCH_PAGE_SIZE / sizeof(rt_ubase_t))
    {
        return (rt_ubase_t)__init_page_array[page_off++].page;
    }

    return 0;
}

static int mmu_map_early(rt_ubase_t *tbl, rt_uint8_t max_level,
        rt_ubase_t va, rt_ubase_t pa, rt_ubase_t attr, rt_bool_t flush)
{
    rt_ubase_t page, *table, off, level_shift;

    attr = mmu_attr_fixup(attr);

    if (max_level == satp_level_2M)
    {
        if ((va & SUPPER_PAGE_MASK) || (pa & SUPPER_PAGE_MASK))
        {
            return MMU_MAP_ERROR_VANOTALIGN;
        }
    }
    else
    {
        if ((va & ARCH_PAGE_MASK) || (pa & ARCH_PAGE_MASK))
        {
            return MMU_MAP_ERROR_VANOTALIGN;
        }
    }

    table = tbl;
    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    for (int level = 0; level < max_level; ++level)
    {
        off = (va >> level_shift) & VPN_MASK;

        if (!(table[off] & PTE_V))
        {
            if (!(page = get_free_page()))
            {
                return MMU_MAP_ERROR_NOPAGE;
            }

            rt_memset((void *)page, 0, ARCH_PAGE_SIZE);
            table[off] = ((page >> ARCH_PAGE_SHIFT) << PTE_BITS) | PTE_V;

            if (flush)
            {
                rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));
            }
        }

        if ((table[off] & PTE_ATTR_RWX) != 0)
        {
            /* No a page! */
            return MMU_MAP_ERROR_CONFLICT;
        }

        /* Step into the next level page table */
        page = (table[off] >> PTE_BITS) << ARCH_PAGE_SHIFT;
        table = (rt_ubase_t *)page;

        level_shift -= VPN_BITS;
    }

    off = (va >> level_shift) & VPN_MASK;
    table[off] = ((pa >> ARCH_PAGE_SHIFT) << PTE_BITS) | attr;

    if (flush)
    {
        rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));
    }

    return 0;
}

#ifdef MMU_PERCPU
static int mmu_map_percpu_early(rt_ubase_t *tbl, rt_ubase_t *tbl_shadow,
                                rt_ubase_t va, rt_ubase_t pa)
{
    rt_ubase_t page, off, level_shift;

    if (tbl == tbl_shadow)
    {
        return mmu_map_early(tbl, satp_level_4k, va, pa, MMU_MAP_K_RWCB, RT_FALSE);
    }

    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    for (int level = 0; level < satp_level_4k; ++level)
    {
        off = (va >> level_shift) & VPN_MASK;

        if (!(tbl[off] & PTE_V) || (tbl[off] & PTE_ATTR_RWX))
        {
            return MMU_MAP_ERROR_CONFLICT;
        }

        /* Copy a shared branch before changing its leaf mapping. */
        if (tbl_shadow[off] == tbl[off])
        {
            if (!(page = get_free_page()))
            {
                return MMU_MAP_ERROR_NOPAGE;
            }

            rt_memcpy((void *)page,
                      (void *)((tbl[off] >> PTE_BITS) << ARCH_PAGE_SHIFT),
                      ARCH_PAGE_SIZE);
            tbl_shadow[off] = ((page >> ARCH_PAGE_SHIFT) << PTE_BITS) | PTE_V;
        }
        else if (!(tbl_shadow[off] & PTE_V) || (tbl_shadow[off] & PTE_ATTR_RWX))
        {
            return MMU_MAP_ERROR_CONFLICT;
        }

        /* Step into the next level page table */
        tbl = (rt_ubase_t *)((tbl[off] >> PTE_BITS) << ARCH_PAGE_SHIFT);
        tbl_shadow = (rt_ubase_t *)((tbl_shadow[off] >> PTE_BITS) << ARCH_PAGE_SHIFT);

        level_shift -= VPN_BITS;
    }

    off = (va >> level_shift) & VPN_MASK;
    tbl_shadow[off] = ((pa >> ARCH_PAGE_SHIFT) << PTE_BITS) | MMU_MAP_K_RWCB;

    return 0;
}
#endif /* MMU_PERCPU */

/**
 * @brief Switch the current address space to the specified one.
 *
 * This function is responsible for switching the address space by updating the page table
 * and related hardware state. The behavior depends on whether the architecture supports
 * Address Space Identifiers (ASIDs), devided by macro definition of ARCH_USING_ASID.
 *
 * @param aspace Pointer to the address space structure containing the new page table.
 *
 * @note If ASID is supported (`ARCH_USING_ASID` is defined), the ASID is encoded
 *       into `satp`. Otherwise, switching address spaces invalidates the local TLB.
 */
#ifdef ARCH_USING_ASID
/* Generation bits stay above the architectural ASID field. */
#define ASID_FIRST_GENERATION   (_ULL(1) << SATP_ASID_BITS)

rt_ubase_t riscv_asid_mask;

static rt_spinlock_t asid_lock = RT_SPINLOCK_INIT;

static void asid_init(void)
{
    rt_ubase_t old_satp = csr_read(CSR_SATP);

    /* Probe with the early page table active, preserving MODE and PPN. */
    csr_write(CSR_SATP, old_satp | (SATP_ASID_MASK << SATP_ASID_SHIFT));
    riscv_asid_mask = (csr_read(CSR_SATP) >> SATP_ASID_SHIFT) & SATP_ASID_MASK;
    csr_write(CSR_SATP, old_satp);

    /* The probe may have populated translations under the temporary ASID. */
    rt_hw_tlb_invalidate_all_local();
}

static rt_uint64_t _asid_acquire(rt_aspace_t aspace)
{
    static rt_uint32_t next_asid = 1;
    static rt_uint64_t global_asid_generation = ASID_FIRST_GENERATION;
    rt_ubase_t level;

    level = rt_spin_lock_irqsave(&asid_lock);

    if ((aspace->asid ^ global_asid_generation) >> SATP_ASID_BITS)
    {
        if (next_asid <= riscv_asid_mask)
        {
            aspace->asid = global_asid_generation | next_asid++;
        }
        else
        {
            global_asid_generation += ASID_FIRST_GENERATION;
            next_asid = 1;
            rt_hw_tlb_invalidate_all();

            aspace->asid = global_asid_generation | next_asid++;
        }
    }

    rt_spin_unlock_irqrestore(&asid_lock, level);

    return aspace->asid & riscv_asid_mask;
}

void rt_hw_aspace_switch(rt_aspace_t aspace)
{
    rt_ubase_t asid, page_table;

    page_table = (rt_ubase_t)rt_kmem_v2p(aspace->page_table + PERCPU_OFFSET);

    asid = riscv_asid_mask ? _asid_acquire(aspace) : 0;

    csr_write(CSR_SATP, satp_mode | (asid << SATP_ASID_SHIFT) |
            (page_table >> ARCH_PAGE_SHIFT));

#ifdef ARCH_RISCV_DISABLE_SFENCE_VMA_ASID
    rt_hw_tlb_invalidate_all_local();
#else
    if (riscv_asid_mask)
    {
        SFENCE_VMA_ASID(asid);
    }
    else
    {
        rt_hw_tlb_invalidate_all_local();
    }
#endif
}

#else /* !ARCH_USING_ASID */
void rt_hw_aspace_switch(rt_aspace_t aspace)
{
    rt_ubase_t page_table;

    page_table = (rt_ubase_t)rt_kmem_v2p(aspace->page_table + PERCPU_OFFSET);

    csr_write(CSR_SATP, satp_mode | ((rt_ubase_t)page_table >> ARCH_PAGE_SHIFT));

    rt_hw_tlb_invalidate_all_local();
}
#endif /* ARCH_USING_ASID */

void rt_hw_mmu_tbl_set(rt_ubase_t tbl)
{
    tbl += PERCPU_OFFSET;
    tbl += rt_kmem_pvoff();

    csr_write(CSR_SATP, satp_mode | (tbl >> ARCH_PAGE_SHIFT));

    rt_hw_tlb_invalidate_all_local();
}

void *rt_hw_mmu_tbl_get(void)
{
    rt_ubase_t satp = csr_read(CSR_SATP);

    return (void *)((satp & SATP_PPN) << ARCH_PAGE_SHIFT) - rt_kmem_pvoff();
}

void *rt_ioremap_early(void *paddr, size_t size)
{
    rt_ubase_t base;
    volatile size_t count;
    static void *tbl = RT_NULL;

    if (!size)
    {
        return RT_NULL;
    }

    if (!tbl)
    {
        tbl = rt_hw_mmu_tbl_get();
    }

    base = RT_ALIGN_DOWN((rt_size_t)paddr, SUPPER_PAGE_SIZE);
    count = RT_ALIGN((rt_ubase_t)paddr + size - base, SUPPER_PAGE_SIZE) / SUPPER_PAGE_SIZE;

    while (count --> 0)
    {
        if (mmu_map_early(tbl, satp_level_2M, base, base, MMU_MAP_K_DEVICE, RT_TRUE))
        {
            return RT_NULL;
        }

        base += SUPPER_PAGE_SIZE;
    }

    return paddr;
}

#ifdef MMU_PERCPU
static int _map_percpu_area(rt_ubase_t *table, void *va, void *pa, int cpu_id)
{
    rt_ubase_t page, off, level_shift;

    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    for (int level = 0; level < satp_level_4k; ++level)
    {
        off = ((rt_ubase_t)va >> level_shift) & VPN_MASK;

        if (!(table[off] & PTE_V))
        {
            if (!(page = (rt_ubase_t)rt_pages_alloc(0)))
            {
                return MMU_MAP_ERROR_NOPAGE;
            }

            rt_memset((void *)page, 0, ARCH_PAGE_SIZE);

            table[off] = (((page + rt_kmem_pvoff()) >> ARCH_PAGE_SHIFT) << PTE_BITS) | PTE_V;

            rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));
        }
        else if (table[off] & PTE_ATTR_RWX)
        {
            return MMU_MAP_ERROR_CONFLICT;
        }

        percpu_level[cpu_id][level].page = table;
        percpu_level[cpu_id][level].offset = off;

        /* Step into the next level page table */
        table = (rt_ubase_t *)(((table[off] >> PTE_BITS) << ARCH_PAGE_SHIFT) - rt_kmem_pvoff());

        level_shift -= VPN_BITS;
    }

    off = ((rt_ubase_t)va >> level_shift) & VPN_MASK;
    table[off] = (((rt_ubase_t)pa >> ARCH_PAGE_SHIFT) << PTE_BITS) | MMU_MAP_K_RWCB;

    rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));

    percpu_level[cpu_id][satp_level_4k].page = table;
    percpu_level[cpu_id][satp_level_4k].offset = off;

    return ARCH_PAGE_SIZE;
}

static void percpu_map_sync(struct rt_aspace *aspace, int level, rt_ubase_t *table, rt_ubase_t off)
{
    if (aspace == &rt_kernel_space &&
        percpu_level[0][level].page == table &&
        percpu_level[0][level].offset != off)
    {
        rt_ubase_t *table_shadow;

        for (int i = 1; i < RT_CPUS_NR; ++i)
        {
            table_shadow = percpu_level[i][level].page;
            table_shadow[off] = table[off];

            rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table_shadow + off, sizeof(void *));
        }
    }
}

static void user_root_sync(struct rt_aspace *aspace, int level,
                           rt_ubase_t *table, rt_ubase_t off)
{
    if (aspace != &rt_kernel_space && level == 0 && table == aspace->page_table)
    {
        for (int i = 1; i < RT_CPUS_NR; ++i)
        {
            rt_ubase_t *table_shadow = (void *)aspace->page_table + i * ARCH_PAGE_SIZE;

            table_shadow[off] = table[off];
            rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table_shadow + off,
                                 sizeof(*table_shadow));
        }
    }
}

static void pgtbl_entry_sync(struct rt_aspace *aspace, int level,
                             rt_ubase_t *table, rt_ubase_t off)
{
    percpu_map_sync(aspace, level, table, off);
    user_root_sync(aspace, level, table, off);
}

static void percpu_mmu_init_check(void)
{
    size_t mapped, size;
    void *page_table, *vaddr, *paddr;
    static rt_bool_t inited = RT_FALSE;

    if (inited)
    {
        return;
    }
    inited = RT_TRUE;

    page_table = rt_kernel_space.page_table;

    for (int cpu_id = 0; cpu_id < RT_CPUS_NR; ++cpu_id)
    {
        vaddr = &__percpu_start;
        paddr = vaddr + rt_kmem_pvoff();
        size = (size_t)(&__percpu_end - &__percpu_start);
        /* Offset to per-CPU partition for current CPU */
        paddr += size * cpu_id;

        while (size > 0)
        {
            MM_PGTBL_LOCK(&rt_kernel_space);
            mapped = _map_percpu_area(page_table, vaddr, paddr, cpu_id);
            MM_PGTBL_UNLOCK(&rt_kernel_space);

            RT_ASSERT(mapped > 0);

            size -= mapped;
            vaddr += mapped;
            paddr += mapped;
        }

        page_table += ARCH_PAGE_SIZE;
    }
}
#endif /* MMU_PERCPU */

static size_t _map_area(struct rt_aspace *aspace, void *va, void *pa,
                        size_t attr, size_t max_size)
{
    rt_uint8_t max_level;
    rt_ubase_t page, *table, off, level_shift;

    attr = mmu_attr_fixup(attr);

    if (max_size >= SUPPER_PAGE_SIZE &&
        !((rt_ubase_t)va & SUPPER_PAGE_MASK) &&
        !((rt_ubase_t)pa & SUPPER_PAGE_MASK))
    {
        max_level = satp_level_2M;
        max_size = SUPPER_PAGE_SIZE;
    }
    else
    {
        max_level = satp_level_4k;
        max_size = ARCH_PAGE_SIZE;
    }

    table = aspace->page_table;
    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    for (int level = 0; level < max_level; ++level)
    {
        off = ((rt_ubase_t)va >> level_shift) & VPN_MASK;

        if (!(table[off] & PTE_V))
        {
            if (!(page = (rt_ubase_t)rt_pages_alloc(0)))
            {
                return MMU_MAP_ERROR_NOPAGE;
            }

            rt_memset((void *)page, 0, ARCH_PAGE_SIZE);
            table[off] = (((page + rt_kmem_pvoff()) >> ARCH_PAGE_SHIFT) << PTE_BITS) | PTE_V;

            rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));
        }
        else
        {
            page = (table[off] >> PTE_BITS) << ARCH_PAGE_SHIFT;
            page -= rt_kmem_pvoff();

            rt_page_ref_inc((void *)page, 0);
        }

        if ((table[off] & PTE_ATTR_RWX) != 0)
        {
            /* No a page! */
            return MMU_MAP_ERROR_CONFLICT;
        }

    #ifdef MMU_PERCPU
        pgtbl_entry_sync(aspace, level, table, off);
    #endif

        /* Step into the next level page table */
        page = (table[off] >> PTE_BITS) << ARCH_PAGE_SHIFT;
        table = (rt_ubase_t *)(page - rt_kmem_pvoff());

        level_shift -= VPN_BITS;
    }

    off = ((rt_ubase_t)va >> level_shift) & VPN_MASK;
    table[off] = (((rt_ubase_t)pa >> ARCH_PAGE_SHIFT) << PTE_BITS) | attr;

    rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, table + off, sizeof(void *));

#ifdef MMU_PERCPU
    pgtbl_entry_sync(aspace, max_level, table, off);
#endif

    return max_size;
}

static size_t _unmap_area(struct rt_aspace *aspace, void *va, size_t max_size)
{
    int level, ref;
    size_t unmapped;
    rt_ubase_t entry, page, *table, *pos, off, level_shift;
    struct mmu_level_info level_info[LEVEL_MAX + 1];

    rt_memset(level_info, 0, sizeof(level_info));

    table = aspace->page_table;
    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    /* Max level is 4k */
    for (level = 0; level <= satp_level_4k; ++level)
    {
        off = ((rt_ubase_t)va >> level_shift) & VPN_MASK;
        pos = table + off;
        entry = *pos;
        unmapped = 1UL << (ARCH_PAGE_SHIFT +
                           VPN_BITS * (satp_level_4k - level));

        if (!(entry & PTE_V))
        {
            return max_size < unmapped ? max_size : unmapped;
        }

        level_info[level].pos = pos;

        if ((entry & PTE_ATTR_RWX) != 0)
        {
            break;
        }

        if (level == satp_level_4k)
        {
            return 0;
        }

        /* Step into the next level page table */
        page = (entry >> PTE_BITS) << ARCH_PAGE_SHIFT;
        table = (rt_ubase_t *)(page - rt_kmem_pvoff());

        level_info[level].page = table;

        level_shift -= VPN_BITS;
    }

    if (unmapped > max_size)
    {
        return 0;
    }

    pos = level_info[level].pos;
    *pos = 0;
    rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, pos, sizeof(void *));
#ifdef MMU_PERCPU
    pgtbl_entry_sync(aspace, level, pos - off, off);
#endif
    --level;

    while (level >= 0)
    {
        pos = level_info[level].pos;

        if (pos)
        {
            void *cur_page = level_info[level].page;

            ref = rt_page_ref_get(cur_page, 0);

            if (ref == 1)
            {
                *pos = 0;
                rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, pos, sizeof(void *));

            #ifdef MMU_PERCPU
                if (level == 0)
                {
                    table = aspace->page_table;
                }
                else
                {
                    table = percpu_level[0][level].page;
                }

                if (pos >= table && pos < table + (ARCH_PAGE_SIZE / sizeof(rt_ubase_t)))
                {
                    pgtbl_entry_sync(aspace, level, table, pos - table);
                }
            #endif /* MMU_PERCPU */
            }

            if (ref == 1)
            {
                /* Finish hardware page walks before recycling this table. */
                rt_hw_tlb_invalidate_all();
            }
            rt_pages_free(cur_page, 0);
        }
        else
        {
            break;
        }

        --level;
    }

    return unmapped;
}

/**
 * @brief Maps a virtual address space to a physical address space.
 *
 * This function maps a specified range of virtual addresses to a range of physical addresses
 * and sets the attributes of the page table entries (PTEs). If an error occurs during the
 * mapping process, the function will automatically roll back any partially completed mappings.
 *
 * @param aspace Pointer to the address space structure containing the page table information.
 * @param v_addr The starting virtual address to be mapped.
 * @param p_addr The starting physical address to be mapped.
 * @param size The size of the memory to be mapped (in bytes).
 * @param attr The attributes of the page table entries (e.g., read/write permissions, cache policies).
 *
 * @return On success, returns the starting virtual address `v_addr`;
 *         On failure, returns `NULL`.
 *
 * @note This function will not override existing page table entries.
 * @warning The caller must ensure that `v_addr` and `p_addr` are page-aligned,
 *          and `size` is a multiple of the page size.
 *
 */
void *rt_hw_mmu_map(struct rt_aspace *aspace, void *v_addr, void *p_addr,
                    size_t size, size_t attr)
{
    size_t mapped;
    void *unmap_va = v_addr;

#ifdef MMU_PERCPU
    percpu_mmu_init_check();
#endif

    while (size > 0)
    {
    #ifdef MMU_PERCPU
        if (v_addr < (void *)&__percpu_start ||
            v_addr >= (void *)&__percpu_real_end)
    #endif
        {
            MM_PGTBL_LOCK(aspace);
            mapped = _map_area(aspace, v_addr, p_addr, attr, size);
            MM_PGTBL_UNLOCK(aspace);
        }
    #ifdef MMU_PERCPU
        else
        {
            /* Make the kernel skip the per-CPU as soon as possible */
            mapped = size > SUPPER_PAGE_SIZE ? SUPPER_PAGE_SIZE : size;
        }
    #endif /* MMU_PERCPU */

        if (mapped && mapped <= size)
        {
            size -= mapped;
            v_addr += mapped;
            p_addr += mapped;

            continue;
        }

        /* Error, undo map */
        while (unmap_va != v_addr)
        {
            MM_PGTBL_LOCK(aspace);
            mapped = _unmap_area(aspace, unmap_va,
                    (rt_ubase_t)v_addr - (rt_ubase_t)unmap_va);
            MM_PGTBL_UNLOCK(aspace);

            if (!mapped)
            {
                RT_ASSERT(mapped != 0);
                break;
            }
            unmap_va += mapped;
        }

        rt_hw_tlb_invalidate_all();
        return RT_NULL;
    }

    return unmap_va;
}

/**
 * @brief Unmaps a range of virtual memory addresses from the specified address space.
 *
 * This function is responsible for unmapping a contiguous region of virtual memory
 * from the given address space. It handles multiple pages and ensures thread safety
 * by locking the page table during the unmapping operation.
 *
 * @param aspace Pointer to the address space structure from which the memory will be unmapped.
 * @param v_addr Starting virtual address to unmap. Must be page-aligned.
 * @param size Size of the memory region to unmap. Must be page-aligned.
 *
 * @note The caller must ensure that both `v_addr` and `size` are page-aligned.
 *
 * @details The function operates in a loop, unmapping memory in chunks. It uses the
 * `_unmap_area` function to perform the actual unmapping, which is called within a
 * locked section to ensure thread safety. The loop continues until the entire region
 * is unmapped.
 *
 * @see _unmap_area
 * @note unmap is different from map that it can handle multiple pages
 */
void rt_hw_mmu_unmap(struct rt_aspace *aspace, void *v_addr, size_t size)
{
    size_t unmapped;

    /* caller guarantee that v_addr & size are page aligned */
    if (!aspace->page_table)
    {
        return;
    }

    while (size > 0)
    {
        MM_PGTBL_LOCK(aspace);
        unmapped = _unmap_area(aspace, v_addr, size);
        MM_PGTBL_UNLOCK(aspace);

        if (unmapped && unmapped <= size)
        {
            size -= unmapped;
            v_addr += unmapped;

            continue;
        }

        /* Region not exist in pgtbl */
        break;
    }
}

rt_inline void _init_region(void *vaddr, size_t size)
{
    rt_ioremap_start = vaddr;
    rt_ioremap_size = size;
    rt_mpr_start = rt_ioremap_start - rt_mpr_size;
    LOG_D("rt_ioremap_start: %p, rt_mpr_start: %p", rt_ioremap_start,
          rt_mpr_start);
}

rt_inline rt_ubase_t get_top_vpn(rt_ubase_t va, rt_uint8_t satp_level)
{
    return (va >> (VPN_BITS * satp_level + 12)) & VPN_MASK;
}

/**
 * @brief Initialize the MMU (Memory Management Unit) mapping.
 *
 * This function initializes the MMU mapping, incluing these steps as follows:
 * 1. Check the validity of the input parameters,
 * 2. Calculate the start and end virtual addresses based on the input virtual address and size.
 * 3. Convert the virtual addresses to PPN2 indices.
 * 4. Check the initialization of the page table. If any entry in the page table within
 *    the specified range is non-zero, it returns -1.
 * 5. It initializes the kernel address space using rt_aspace_init() and initializes the specified region
 *    using _init_region.
 *
 * @param aspace Pointer to the address space. Must not be NULL.
 * @param v_address The starting virtual address.
 * @param size The size of the virtual address space.
 * @param vtable Pointer to the page table. Must not be NULL.
 * @param pv_off The page table offset.
 *
 * @return Returns 0 if the initialization is successful. Returns -1 if any input parameter is invalid
 *         or the page table initialization check fails.
 */
int rt_hw_mmu_map_init(rt_aspace_t aspace, void *v_address, rt_ubase_t size,
                       rt_ubase_t *vtable, rt_ubase_t pv_off)
{
    rt_size_t off, va_s, va_e;
    rt_ubase_t aspace_start = KERNEL_VADDR_START;

#if !defined(RT_USING_SMART) && ARCH_RAM_OFFSET
    aspace_start = ARCH_RAM_OFFSET;
#endif

    if ((!aspace) || (!vtable))
    {
        return -1;
    }

    va_s = (rt_ubase_t)v_address;
    va_e = (rt_ubase_t)v_address + size - 1;

    if (va_e < va_s)
    {
        return -1;
    }

    /* convert address to top-level index */
    va_s = get_top_vpn(va_s, satp_level_4k);
    va_e = get_top_vpn(va_e, satp_level_4k);

    if (va_s == 0)
    {
        return -1;
    }

    /* vtable initialization check */
    for (off = va_s; off <= va_e; off++)
    {
        rt_size_t v = vtable[off];

        if (v)
        {
            return -1;
        }
    }

#if __riscv_xlen == 32 && !defined(RT_USING_SMART)
    /* The RV32 ioremap and MPR regions are placed below the kernel image. */
    aspace_start = (rt_ubase_t)v_address - rt_mpr_size;
#endif

    rt_aspace_init(aspace, (void *)aspace_start, 0UL - aspace_start, vtable);

    _init_region(v_address, size);

    return 0;
}

static void *mmu_v2p(void *tbl, void *vaddr, int *out_level, rt_base_t **out_pte)
{
    rt_ubase_t page, entry, off, level_shift, pa;
    rt_ubase_t va = (rt_ubase_t)vaddr;
    rt_ubase_t *table = tbl;

#ifdef MMU_PERCPU
    if (tbl == rt_kernel_space.page_table)
    {
        table = (rt_ubase_t *)(tbl + PERCPU_OFFSET);
    }
#endif /* MMU_PERCPU */

    /* Calculate initial shift based on virtual address width */
    level_shift = rt_hw_arch_vaddr_width - VPN_BITS;

    /* 4k is the max level, translate to the last level */
    for (*out_level = 0; *out_level <= satp_level_4k; ++(*out_level))
    {
        /* Extract VPN (Virtual Page Number) for this level */
        off = (va >> level_shift) & VPN_MASK;
        /* Fetch the page table entry */
        entry = table[off];

        /* If entry is invalid (V bit not set), address translation fails */
        if (!(entry & PTE_V))
        {
            goto _translate_fail;
        }

        /* If entry has any RWX permission bits set, it is a leaf entry */
        if (entry & PTE_ATTR_RWX)
        {
            if (out_pte)
            {
                *out_pte = (rt_base_t *)table + off;
            }

            /* Extract physical page base address and add page offset */
            pa = ((entry & PTE_PPN_MASK) >> PTE_BITS) << ARCH_PAGE_SHIFT;

            if (*out_level >= satp_level_4k)
            {
                pa |= va & ARCH_PAGE_MASK;
            }
            else
            {
                pa |= va & ((1UL << level_shift) - 1);
            }

            return (void *)pa;
        }

        /* Otherwise, walk to the next level page table */
        page = (entry >> PTE_BITS) << ARCH_PAGE_SHIFT;
        table = (rt_ubase_t *)(page - rt_kmem_pvoff());

        level_shift -= VPN_BITS;
    }

_translate_fail:
    /* If reached here, it is not a valid mapped address */
    LOG_D("%s: failed at %p", __func__, vaddr);
    return ARCH_MAP_FAILED;
}

/**
 * @brief Translate a virtual address to a physical address.
 *
 * This function translates a given virtual address (`vaddr`) to its corresponding
 * physical address (`paddr`) using the page table in the specified address space (`aspace`).
 *
 * @param aspace Pointer to the address space structure containing the page table.
 * @param vaddr The virtual address to be translated.
 *
 * @return The translated physical address. If the translation fails, `ARCH_MAP_FAILED` is returned.
 *
 * @note The function queries the page table entry (PTE) for the virtual address using `mmu_v2p`.
 *       If a valid PTE is found, the physical address is extracted and combined with the offset
 *       from the virtual address. If no valid PTE is found, a debug log is recorded, and
 *       `ARCH_MAP_FAILED` is returned.
 */
void *rt_hw_mmu_v2p(struct rt_aspace *aspace, void *vaddr)
{
    int level;

    return mmu_v2p(aspace->page_table, vaddr, &level, RT_NULL);
}

static int _noncache(rt_base_t *pte)
{
    rt_ubase_t entry;

    if (!riscv_isa_ext_test(SVPBMT))
    {
        return -RT_ENOSYS;
    }

    entry = *pte;
    *pte = (entry & ~PTE_VENDOR_MTMASK) | PTE_VENDOR_NOCACHE;

    return 0;
}

static int _cache(rt_base_t *pte)
{
    rt_ubase_t entry;

    if (!riscv_isa_ext_test(SVPBMT))
    {
        return -RT_ENOSYS;
    }

    entry = *pte;
    *pte = (entry & ~PTE_VENDOR_MTMASK) | PTE_VENDOR_PMA;

    return 0;
}

static int (*control_handler[MMU_CNTL_DUMMY_END])(rt_base_t *pte)=
{
    [MMU_CNTL_CACHE] = _cache,
    [MMU_CNTL_NONCACHE] = _noncache,
};

/**
 * @brief Control the page table entries (PTEs) for a specified virtual address range.
 *
 * This function applies a control command (e.g., cache control) to the page table entries
 * (PTEs) corresponding to the specified virtual address range (`vaddr` to `vaddr + size`).
 *
 * @param aspace Pointer to the address space structure containing the page table.
 * @param vaddr The starting virtual address of the range.
 * @param size The size of the virtual address range.
 * @param cmd The control command to apply (e.g., `MMU_CNTL_CACHE`, `MMU_CNTL_NONCACHE`.etc.).
 *
 * @return `RT_EOK` on success, or an error code (`-RT_EINVAL` or `-RT_ENOSYS`) on failure.
 *
 * @note The function uses the `control_handler` array to map the command to a handler function.
 *       It iterates over the virtual address range, queries the PTEs, and applies the handler
 *       to each valid PTE. If the command is invalid, `-RT_ENOSYS` is returned.
 */
int rt_hw_mmu_control(struct rt_aspace *aspace, void *vaddr, size_t size,
                      enum rt_mmu_cntl cmd)
{
    int level;
    int err = -RT_EINVAL;
    void *vend = vaddr + size;

    int (*handler)(rt_base_t *pte);
    if (cmd >= 0 && cmd < MMU_CNTL_DUMMY_END)
    {
        handler = control_handler[cmd];

        while (vaddr < vend)
        {
            void *range_end;
            rt_base_t *pte = RT_NULL;

            mmu_v2p(aspace->page_table, vaddr, &level, &pte);

            if (level == satp_level_4k)
            {
                range_end = vaddr + ARCH_PAGE_SIZE;
            }
            else if (level == satp_level_2M)
            {
                range_end = vaddr + SUPPER_PAGE_SIZE;
            }
            else
            {
                /* 1G or larger is not supported. */
                RT_ASSERT(0);
            }

            if (pte)
            {
                err = handler(pte);
                RT_ASSERT(err == RT_EOK);
            }
            vaddr = range_end;
        }
    }
    else
    {
        err = -RT_ENOSYS;
    }

    return err;
}

/**
 * @brief setup Page Table for kernel space. It's a fixed map
 * and all mappings cannot be changed after initialization.
 *
 * Memory region in struct mem_desc must be page aligned,
 * otherwise is a failure and no report will be
 * returned.
 *
 * @param aspace Pointer to the address space structure.
 * @param mdesc Pointer to the array of memory descriptors.
 * @param desc_nr Number of memory descriptors in the array.
 */
void rt_hw_mmu_setup(rt_aspace_t aspace, struct mem_desc *mdesc, int desc_nr)
{
    void *err;

    for (size_t i = 0; i < desc_nr; ++i)
    {
        size_t attr;
        struct rt_mm_va_hint hint =
        {
            .flags = MMF_MAP_FIXED,
            .limit_start = aspace->start,
            .limit_range_size = aspace->size,
            .map_size = mdesc->vaddr_end - mdesc->vaddr_start + 1,
            .prefer = (void *)mdesc->vaddr_start
        };

        switch (mdesc->attr)
        {
        case NORMAL_MEM:
            attr = MMU_MAP_K_RWCB;
            break;
        case NORMAL_NOCACHE_MEM:
            attr = MMU_MAP_K_RWCB;
            break;
        case DEVICE_MEM:
            attr = MMU_MAP_K_DEVICE;
            break;
        default:
            attr = MMU_MAP_K_DEVICE;
        }

        if (mdesc->paddr_start == (rt_uintptr_t)ARCH_MAP_FAILED)
        {
            mdesc->paddr_start = mdesc->vaddr_start + rt_kmem_pvoff();
        }

        rt_aspace_map_phy_static(aspace, &mdesc->varea, &hint, attr,
                                 mdesc->paddr_start >> MM_PAGE_SHIFT, &err);
        mdesc++;
    }

#ifdef ARCH_USING_ASID
    asid_init();
#endif
    rt_hw_mmu_tbl_set((rt_ubase_t)rt_kernel_space.page_table);
    rt_page_cleanup();
}

/**
 * @brief Early memory setup function for hardware initialization.
 *
 * This function performs early memory setup tasks, including:
 * - Calculating the physical-to-virtual (PV) offset.
 * - Setting up initial page tables for identity mapping and text region relocation.
 * - Applying new memory mappings by updating the SATP register.
 *
 * @note This function is typically called during the early stages of system initialization (startup_gcc.S),
 *       before the memory management system is fully operational.
 */
void rt_hw_mem_setup_early(rt_ubase_t vaddr_start, rt_ubase_t paddr_start, void *pgtbl)
{
    extern char __text_start, __text_end;

    rt_size_t size = ARCH_EARLY_MAP_SIZE;
    rt_size_t map_pages;
    rt_ubase_t *early_pgtbl = pgtbl, paddr_end;
    rt_ubase_t kernel_paddr;

    rt_kmem_pvoff_set(paddr_start - vaddr_start);

    switch (rt_hw_arch_vaddr_width)
    {
    case 0:
        satp_mode = SATP_MODE_BARE;
        satp_level_4k = 0;
        satp_level_2M = 0;
    #ifdef RT_USING_SMART
        RT_ASSERT(0);
    #else
        RT_ASSERT(paddr_start == vaddr_start);
    #endif
        /* Do nothing */
        return;
#if __riscv_xlen != 32
    case 64:
        satp_mode = SATP_MODE_64;
        satp_level_4k = 5;
        satp_level_2M = 4;
        break;
    case 57:
        satp_mode = SATP_MODE_57;
        satp_level_4k = 4;
        satp_level_2M = 3;
        break;
    case 48:
        satp_mode = SATP_MODE_48;
        satp_level_4k = 3;
        satp_level_2M = 2;
        break;
    case 39:
    default:
        satp_mode = SATP_MODE_39;
        satp_level_4k = 2;
        satp_level_2M = 1;
        rt_hw_arch_vaddr_width = 39;
#else
    case 32:
    default:
        satp_mode = SATP_MODE_32;
        satp_level_4k = 1;
        satp_level_2M = 0;
        rt_hw_arch_vaddr_width = 32;
#endif /* __riscv_xlen != 32 */
        break;
    }

    map_pages = (size + (paddr_start & SUPPER_PAGE_MASK) + SUPPER_PAGE_MASK) /
            SUPPER_PAGE_SIZE;
    vaddr_start = RT_ALIGN_DOWN(vaddr_start, SUPPER_PAGE_SIZE);
    paddr_start = RT_ALIGN_DOWN(paddr_start, SUPPER_PAGE_SIZE);
    kernel_paddr = paddr_start;

    rt_memset(early_pgtbl, 0, RT_CPUS_NR * ARCH_PAGE_SIZE);

    if (!rt_kmem_pvoff())
    {
        goto _map_vaddress;
    }

    /* Identical mapping, only map for 'text' */
    size = RT_ALIGN((rt_ubase_t)(&__text_end - &__text_start), SUPPER_PAGE_SIZE);

    /* Check whether the virtual address area and identical area overlap */
    RT_ASSERT(size < rt_kmem_pvoff());

    for (rt_ssize_t pages = size / SUPPER_PAGE_SIZE; pages > 0; --pages)
    {
        mmu_map_early(early_pgtbl, satp_level_2M, paddr_start, paddr_start, MMU_MAP_K_RWCB, RT_FALSE);

        paddr_start += SUPPER_PAGE_SIZE;
    }

    /* Page array for map early */
    paddr_start = RT_ALIGN_DOWN((rt_ubase_t)early_pgtbl, SUPPER_PAGE_SIZE);
    mmu_map_early(early_pgtbl, satp_level_2M, paddr_start, paddr_start, MMU_MAP_K_RWCB, RT_FALSE);

    if ((rt_ubase_t)__init_page_array - paddr_start >= SUPPER_PAGE_SIZE)
    {
        paddr_start = RT_ALIGN_DOWN((rt_ubase_t)__init_page_array, SUPPER_PAGE_SIZE);
        mmu_map_early(early_pgtbl, satp_level_2M, paddr_start, paddr_start, MMU_MAP_K_RWCB, RT_FALSE);
    }

_map_vaddress:
    /* Virtual mapping */
    paddr_start = kernel_paddr;
    while (map_pages--)
    {
    #ifdef MMU_PERCPU
        if (paddr_start < (rt_ubase_t)&__percpu_start ||
            paddr_start >= (rt_ubase_t)&__percpu_real_end)
    #endif
        {
            mmu_map_early(early_pgtbl, satp_level_2M, vaddr_start, paddr_start, MMU_MAP_K_RWCB, RT_FALSE);
        }

        rt_ubase_t next_paddr = paddr_start + SUPPER_PAGE_SIZE;
        rt_ubase_t next_vaddr = vaddr_start + SUPPER_PAGE_SIZE;

        /* RV32 cannot represent an exclusive end address at 4 GiB. */
        if (next_paddr < paddr_start || next_vaddr < vaddr_start)
        {
            break;
        }

        paddr_start = next_paddr;
        vaddr_start = next_vaddr;
    }

#ifdef MMU_PERCPU
    for (int cpu_id = 0; cpu_id < RT_CPUS_NR; ++cpu_id)
    {
        rt_ubase_t *tbl_shadow = early_pgtbl +
            cpu_id * (ARCH_PAGE_SIZE / sizeof(*early_pgtbl));

        if (cpu_id)
        {
            rt_memcpy(tbl_shadow, early_pgtbl, ARCH_PAGE_SIZE);
        }

        paddr_start = (rt_ubase_t)&__percpu_start;
        vaddr_start = paddr_start - rt_kmem_pvoff();
        size = (rt_size_t)(&__percpu_end - &__percpu_start);
        /* Offset to per-CPU partition for current CPU */
        paddr_start += cpu_id * size;
        paddr_end = paddr_start + size;

        while (paddr_start < paddr_end)
        {
            /* Map physical address per-CPU partition */
            RT_ASSERT(mmu_map_percpu_early(early_pgtbl, tbl_shadow,
                                            vaddr_start, paddr_start) == 0);

            paddr_start += ARCH_PAGE_SIZE;
            vaddr_start += ARCH_PAGE_SIZE;
        }
    }
#endif /* MMU_PERCPU */
}

rt_ubase_t mmu_satp_load(void *pgtbl, rt_ubase_t hartid)
{
#ifdef MMU_PERCPU
    pgtbl += riscv_hartid_to_cpu_id(hartid) * ARCH_PAGE_SIZE;
#endif

    return satp_mode | ((rt_ubase_t)pgtbl >> ARCH_PAGE_SHIFT);
}

/**
 * @brief Creates and initializes a new MMU page table.
 *
 * This function allocates a new MMU page table, copies the kernel space
 * page table into it, and flushes the data cache to ensure consistency.
 *
 * @return
 * - A pointer to the newly allocated MMU page table on success.
 * - RT_NULL if the allocation fails.
 */
void *rt_hw_mmu_pgtbl_create(void)
{
    rt_size_t alloc_bits = 0;
    rt_ubase_t *mmu_table;

#ifdef MMU_PERCPU
    alloc_bits = rt_page_bits(RT_CPUS_NR * ARCH_PAGE_SIZE);
#endif
    mmu_table = (rt_ubase_t *)rt_pages_alloc_ext(alloc_bits, PAGE_ANY_AVAILABLE);
    if (!mmu_table)
    {
        return RT_NULL;
    }

#ifdef MMU_PERCPU
    for (int i = 0; i < RT_CPUS_NR; ++i)
    {
        rt_memcpy((void *)mmu_table + i * ARCH_PAGE_SIZE,
                  (void *)rt_kernel_space.page_table + i * ARCH_PAGE_SIZE,
                  ARCH_PAGE_SIZE);
    }
    rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, mmu_table,
                         RT_CPUS_NR * ARCH_PAGE_SIZE);
#else
    rt_memcpy(mmu_table, rt_kernel_space.page_table, ARCH_PAGE_SIZE);
    rt_hw_cpu_dcache_ops(RT_HW_CACHE_FLUSH, mmu_table, ARCH_PAGE_SIZE);
#endif

    return mmu_table;
}

/**
 * @brief Deletes an MMU page table.
 *
 * This function frees the memory allocated for the given MMU page table.
 *
 * @param pgtbl Pointer to the MMU page table to be deleted.
 */
void rt_hw_mmu_pgtbl_delete(void *pgtbl)
{
    rt_size_t alloc_bits = 0;

#ifdef MMU_PERCPU
    alloc_bits = rt_page_bits(RT_CPUS_NR * ARCH_PAGE_SIZE);
#endif
    rt_pages_free(pgtbl, alloc_bits);
}