VirtualRange.cpp 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Leon Albrecht <leon2002.la@gmail.com>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Vector.h>
  8. #include <Kernel/Memory/MemoryManager.h>
  9. #include <Kernel/Memory/VirtualRange.h>
  10. #include <LibC/limits.h>
  11. namespace Kernel::Memory {
  12. Vector<VirtualRange, 2> VirtualRange::carve(VirtualRange const& taken) const
  13. {
  14. VERIFY((taken.size() % PAGE_SIZE) == 0);
  15. Vector<VirtualRange, 2> parts;
  16. if (taken == *this)
  17. return {};
  18. if (taken.base() > base())
  19. parts.append({ base(), taken.base().get() - base().get() });
  20. if (taken.end() < end())
  21. parts.append({ taken.end(), end().get() - taken.end().get() });
  22. return parts;
  23. }
  24. bool VirtualRange::intersects(VirtualRange const& other) const
  25. {
  26. auto a = *this;
  27. auto b = other;
  28. if (a.base() > b.base())
  29. swap(a, b);
  30. return a.base() < b.end() && b.base() < a.end();
  31. }
  32. VirtualRange VirtualRange::intersect(VirtualRange const& other) const
  33. {
  34. if (*this == other) {
  35. return *this;
  36. }
  37. auto new_base = max(base(), other.base());
  38. auto new_end = min(end(), other.end());
  39. VERIFY(new_base < new_end);
  40. return VirtualRange(new_base, (new_end - new_base).get());
  41. }
  42. ErrorOr<VirtualRange> VirtualRange::expand_to_page_boundaries(FlatPtr address, size_t size)
  43. {
  44. if ((address + size) < address)
  45. return EINVAL;
  46. auto base = VirtualAddress { address }.page_base();
  47. auto end = TRY(page_round_up(address + size));
  48. return VirtualRange { base, end - base.get() };
  49. }
  50. }