asid.c 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. /*
  2. * Copyright (c) 2006-2024, RT-Thread Development Team
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. *
  6. * Change Logs:
  7. * Date Author Notes
  8. * 2024-07-12 RT-Thread first version.
  9. */
  10. #define DBG_TAG "hw.asid"
  11. #define DBG_LVL DBG_INFO
  12. #include <rtdbg.h>
  13. #include <rtthread.h>
  14. #include <board.h>
  15. #include <cache.h>
  16. #include <mm_aspace.h>
  17. #include <mm_page.h>
  18. #include <mmu.h>
  19. #include <riscv_mmu.h>
  20. #include <tlb.h>
  21. static rt_uint8_t ASID_BITS = 0;
  22. static rt_uint32_t next_asid;
  23. static rt_uint64_t global_asid_generation;
  24. #define ASID_MASK ((1 << ASID_BITS) - 1)
  25. #define ASID_FIRST_GENERATION (1 << ASID_BITS)
  26. #define MAX_ASID ASID_FIRST_GENERATION
  27. void rt_hw_asid_init(void)
  28. {
  29. unsigned int satp_reg = read_csr(satp);
  30. satp_reg |= (((rt_uint64_t)0xffff) << PPN_BITS);
  31. write_csr(satp, satp_reg);
  32. unsigned short valid_asid_bit = ((read_csr(satp) >> PPN_BITS) & 0xffff);
  33. // The maximal value of ASIDLEN, is 9 for Sv32 or 16 for Sv39, Sv48, and Sv57
  34. for (unsigned i = 0; i < 16; i++)
  35. {
  36. if (!(valid_asid_bit & 0x1))
  37. {
  38. break;
  39. }
  40. valid_asid_bit >>= 1;
  41. ASID_BITS++;
  42. }
  43. global_asid_generation = ASID_FIRST_GENERATION;
  44. next_asid = 1;
  45. }
  46. static rt_uint64_t _asid_acquire(rt_aspace_t aspace)
  47. {
  48. if ((aspace->asid ^ global_asid_generation) >> ASID_BITS) // not same generation
  49. {
  50. if (next_asid != MAX_ASID)
  51. {
  52. aspace->asid = global_asid_generation | next_asid;
  53. next_asid++;
  54. }
  55. else
  56. {
  57. // scroll to next generation
  58. global_asid_generation += ASID_FIRST_GENERATION;
  59. next_asid = 1;
  60. rt_hw_tlb_invalidate_all_local();
  61. aspace->asid = global_asid_generation | next_asid;
  62. next_asid++;
  63. }
  64. }
  65. return aspace->asid & ASID_MASK;
  66. }
  67. void rt_hw_asid_switch_pgtbl(struct rt_aspace *aspace, rt_ubase_t pgtbl)
  68. {
  69. rt_uint64_t asid = _asid_acquire(aspace);
  70. write_csr(satp, (((size_t)SATP_MODE) << SATP_MODE_OFFSET) |
  71. (asid << PPN_BITS) |
  72. ((rt_ubase_t)pgtbl >> PAGE_OFFSET_BIT));
  73. asm volatile("sfence.vma x0,%0"::"r"(asid):"memory");
  74. }