blob: 73cb9ea668d9157f8509d345b1be6bba00c12927 [file]
// Copyright 2026 The Fuchsia Authors
//
// Use of this source code is governed by a MIT-style
// license that can be found in the LICENSE file or at
// https://opensource.org/licenses/MIT
#include "identity-map.h"
#include <inttypes.h>
#include <lib/memalloc/pool.h>
#include <lib/memalloc/range.h>
#include <lib/uart/uart.h>
#include <zircon/assert.h>
#include <ktl/optional.h>
#include <phys/address-space/address-space.h>
#include <phys/allocation/allocation.h>
#include <phys/output/uart.h>
#include <ktl/enforce.h>
void IdentityMapRam(AddressSpace& aspace) {
memalloc::Pool& pool = Allocation::GetPool();
const size_t page_size = AddressSpace::PageSize();
// To account for the case of non-page-aligned RAM, we extend the mapped
// region to page-aligned boundaries, tracking the end of the last aligned
// range in the process. There should not be cases where both RAM and MMIO
// appear within the same page.
ktl::optional<uint64_t> last_aligned_end;
memalloc::NormalizeRam(pool, [&](const memalloc::Range& range) {
// If the end of the last page-aligned range overlaps with the current,
// take that to be the start of the current range.
uint64_t addr, size;
if (last_aligned_end && *last_aligned_end > range.addr) {
if (*last_aligned_end >= range.end()) {
return true;
}
addr = *last_aligned_end;
size = range.end() - *last_aligned_end;
} else {
addr = range.addr & -uint64_t{page_size};
size = (range.addr - addr) + range.size;
}
// Now page-align up the size.
size = (size + page_size - 1) & -uint64_t{page_size};
auto result = aspace.IdentityMap(addr, size,
AddressSpace::NormalMapSettings({
.readable = true,
.writable = true,
.executable = true,
}));
if (result.is_error()) {
ZX_PANIC("Failed to identity-map range [%#" PRIx64 ", %#" PRIx64
") (page-aligned from [%#" PRIx64 ", %#" PRIx64 "))",
addr, addr + size, range.addr, range.end());
}
last_aligned_end = addr + size;
return true;
});
}
void IdentityMapUart(AddressSpace& aspace) {
if (const ktl::optional uart_range = GetUartDriver().maybe_mmio_range()) {
const auto [start, size] = uart_range->AlignedTo(AddressSpace::PageSize());
auto result = aspace.IdentityMap(start, size, AddressSpace::MmioMapSettings());
ZX_ASSERT_MSG(result.is_ok(), "Failed to map in UART range: [%#" PRIx64 ", %#" PRIx64 ")",
start, size);
}
}