PhysicalAddress.h 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/Format.h>
  8. #include <AK/Types.h>
  9. typedef u64 PhysicalPtr;
  10. typedef u64 PhysicalSize;
  11. class PhysicalAddress {
  12. public:
  13. ALWAYS_INLINE static PhysicalPtr physical_page_base(PhysicalPtr page_address) { return page_address & ~(PhysicalPtr)0xfff; }
  14. ALWAYS_INLINE static size_t physical_page_index(PhysicalPtr page_address)
  15. {
  16. auto page_index = page_address >> 12;
  17. if constexpr (sizeof(size_t) < sizeof(PhysicalPtr))
  18. VERIFY(!(page_index & ~(PhysicalPtr)((size_t)-1)));
  19. return (size_t)(page_index);
  20. }
  21. PhysicalAddress() = default;
  22. explicit PhysicalAddress(PhysicalPtr address)
  23. : m_address(address)
  24. {
  25. }
  26. [[nodiscard]] PhysicalAddress offset(PhysicalPtr o) const { return PhysicalAddress(m_address + o); }
  27. [[nodiscard]] PhysicalPtr get() const { return m_address; }
  28. void set(PhysicalPtr address) { m_address = address; }
  29. void mask(PhysicalPtr m) { m_address &= m; }
  30. [[nodiscard]] bool is_null() const { return m_address == 0; }
  31. [[nodiscard]] u8* as_ptr() { return reinterpret_cast<u8*>(m_address); }
  32. [[nodiscard]] const u8* as_ptr() const { return reinterpret_cast<const u8*>(m_address); }
  33. [[nodiscard]] PhysicalAddress page_base() const { return PhysicalAddress(physical_page_base(m_address)); }
  34. [[nodiscard]] PhysicalPtr offset_in_page() const { return PhysicalAddress(m_address & 0xfff).get(); }
  35. bool operator==(const PhysicalAddress& other) const { return m_address == other.m_address; }
  36. bool operator!=(const PhysicalAddress& other) const { return m_address != other.m_address; }
  37. bool operator>(const PhysicalAddress& other) const { return m_address > other.m_address; }
  38. bool operator>=(const PhysicalAddress& other) const { return m_address >= other.m_address; }
  39. bool operator<(const PhysicalAddress& other) const { return m_address < other.m_address; }
  40. bool operator<=(const PhysicalAddress& other) const { return m_address <= other.m_address; }
  41. private:
  42. PhysicalPtr m_address { 0 };
  43. };
  44. template<>
  45. struct AK::Formatter<PhysicalAddress> : AK::Formatter<FormatString> {
  46. void format(FormatBuilder& builder, PhysicalAddress value)
  47. {
  48. if constexpr (sizeof(PhysicalPtr) == sizeof(u64))
  49. return AK::Formatter<FormatString>::format(builder, "P{:016x}", value.get());
  50. else
  51. return AK::Formatter<FormatString>::format(builder, "P{}", value.as_ptr());
  52. }
  53. };