1
0
mirror of git://projects.qi-hardware.com/ben-blinkenlights.git synced 2024-07-02 23:24:12 +03:00
ben-blinkenlights/ubb-vga/physmem.c
Werner Almesberger 6cd21404cd physmem.c: added virtual to physical translation
- physmem.c (calloc_phys_vec): malloc the vector instead of sbrk'ing it
- ubb-vga.h (xlat_virt), physmem.c (xlat_one, xlat_virt): translate a
  vector of virtual addresses to physical addresses
2011-04-29 21:15:27 -03:00

123 lines
2.4 KiB
C

/*
* physmem.c - Physical memory allocator
*
* Written 2011 by Werner Almesberger
* Copyright 2011 Werner Almesberger
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
#include <stdint.h>
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#include <sys/types.h>
#define PAGEMAP_FILE "/proc/self/pagemap"
#define PAGE_SIZE 4096
#define PM_PSHIFT 55 /* page size */
#define PM_PSHIFT_MASK 63
#define PM_SWAPPED 62
#define PM_PRESENT 63
static void align_brk(int alignment)
{
unsigned long addr;
addr = (unsigned long) sbrk(0);
sbrk(alignment-(addr % alignment));
}
void **calloc_phys_vec(size_t n, size_t size)
{
void **vec;
int i;
vec = malloc(sizeof(void *)*n);
if (!vec) {
perror("malloc");
exit(1);
}
for (i = 0; i != n; i++) {
align_brk(512); /* crude page alignment */
vec[i] = sbrk(size);
memset(vec[i], 0, size);
}
return vec;
}
static unsigned long xlat_one(int fd, unsigned long vaddr)
{
unsigned long page, offset, paddr;
ssize_t got;
uint64_t map;
int pshift;
offset = vaddr & (PAGE_SIZE-1);
page = vaddr/PAGE_SIZE;
if (lseek(fd, page*8, SEEK_SET) < 0) {
perror("lseek");
exit(1);
}
got = read(fd, &map, 8);
if (got < 0) {
perror("read");
exit(1);
}
if (got != 8) {
fprintf(stderr, "bad read: got %d instead of 8\n", got);
exit(1);
}
if (!((map >> PM_PRESENT) & 1)) {
fprintf(stderr, "page %lu is not present\n", page);
abort();
}
if ((map >> PM_SWAPPED) & 1) {
fprintf(stderr, "page %lu is swapped\n", page);
abort();
}
pshift = (map >> PM_PSHIFT) & PM_PSHIFT_MASK;
if ((1 << pshift) != PAGE_SIZE) {
fprintf(stderr, "page claims to have size %u\n", 1 << pshift);
abort();
}
paddr = ((map & 0x7fffffffffffffULL) << pshift) | offset;
// fprintf(stderr, "0x%x -> 0x%x\n", vaddr, paddr);
return paddr;
}
unsigned long *xlat_virt(void *const *v, size_t n)
{
unsigned long *res;
int fd;
int i;
res = malloc(n*sizeof(unsigned long));
if (!res) {
perror("malloc");
exit(1);
}
fd = open(PAGEMAP_FILE, O_RDONLY);
if (fd < 0) {
perror(PAGEMAP_FILE);
exit(1);
}
for (i = 0; i != n; i++)
res[i] = xlat_one(fd, (unsigned long) v[i]);
close(fd);
return res;
}