aboutsummaryrefslogtreecommitdiffstats
path: root/lib/physmem-posix.c
blob: 664ec48c96fd87b4079cc62932e7aea69ec4d68e (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/*
 *      The PCI Library -- Physical memory mapping for POSIX systems
 *
 *      Copyright (c) 2023 Pali Rohár <pali@kernel.org>
 *
 *      Can be freely distributed and used under the terms of the GNU GPL v2+
 *
 *      SPDX-License-Identifier: GPL-2.0-or-later
 */

/*
 * Tell 32-bit platforms that we are interested in 64-bit variant of off_t type
 * as 32-bit variant of off_t type is signed and so it cannot represent all
 * possible 32-bit offsets. It is required because off_t type is used by mmap().
 */
#define _FILE_OFFSET_BITS 64

#include "internal.h"
#include "physmem.h"

#include <limits.h>
#include <errno.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <fcntl.h>
#include <unistd.h>

#ifndef OFF_MAX
#define OFF_MAX (off_t)((1ULL << (sizeof(off_t) * CHAR_BIT - 1)) - 1)
#endif

struct physmem {
  int fd;
};

void
physmem_init_config(struct pci_access *a)
{
  pci_define_param(a, "devmem.path", PCI_PATH_DEVMEM_DEVICE, "Path to the /dev/mem device");
}

int
physmem_access(struct pci_access *a, int w)
{
  const char *devmem = pci_get_param(a, "devmem.path");
  a->debug("checking access permission of physical memory device %s for %s mode...", devmem, w ? "read/write" : "read-only");
  return access(devmem, R_OK | (w ? W_OK : 0));
}

struct physmem *
physmem_open(struct pci_access *a, int w)
{
  const char *devmem = pci_get_param(a, "devmem.path");
  struct physmem *physmem = pci_malloc(a, sizeof(struct physmem));

  a->debug("trying to open physical memory device %s in %s mode...", devmem, w ? "read/write" : "read-only");
  physmem->fd = open(devmem, (w ? O_RDWR : O_RDONLY) | O_DSYNC); /* O_DSYNC bypass CPU cache for mmap() on Linux */
  if (physmem->fd < 0)
    {
      pci_mfree(physmem);
      return NULL;
    }

  return physmem;
}

void
physmem_close(struct physmem *physmem)
{
  close(physmem->fd);
  pci_mfree(physmem);
}

long
physmem_get_pagesize(struct physmem *physmem UNUSED)
{
  return sysconf(_SC_PAGESIZE);
}

void *
physmem_map(struct physmem *physmem, u64 addr, size_t length, int w)
{
  if (addr > OFF_MAX)
    {
      errno = EOVERFLOW;
      return (void *)-1;
    }
  return mmap(NULL, length, PROT_READ | (w ? PROT_WRITE : 0), MAP_SHARED, physmem->fd, addr);
}

int
physmem_unmap(struct physmem *physmem UNUSED, void *ptr, size_t length)
{
  return munmap(ptr, length);
}