aboutsummaryrefslogtreecommitdiffstats
path: root/mpm/python/usrp_mpm/uio.py
blob: 18a894e9c5cfa8c3a7acd1ef74a01d677bc93b16 (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
#
# Copyright 2017 Ettus Research (National Instruments)
#
# 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 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
"""
Access to UIO mapped memory.
"""

import struct
import os
import mmap

class uio(object):
    """
    Provides peek/poke interfaces for uio-mapped memory.

    Arguments:
    path -- Path to UIO device, e.g. '/dev/uio0'
    length -- Number of bytes in the address space (is passed to mmap.mmap).
              Must be at least one page size
    read_only -- Boolean, True == ro, False == rw
    offset -- Passed to mmap.mmap
    """
    def __init__(self, path, length, read_only=True, offset=None):
        # Python can't tell the size of a uio device
        assert length >= mmap.PAGESIZE
        offset = offset or 0
        self._path = path
        self._read_only = read_only
        self._fd = os.open(path, os.O_RDONLY if read_only else os.O_RDWR)
        self._mm = mmap.mmap(
            self._fd,
            length,
            flags=mmap.MAP_SHARED,
            prot=mmap.PROT_READ | (0 if read_only else mmap.PROT_WRITE),
            offset=offset,
        )

    def peek32(self, addr):
        """
        Returns the 32-bit value starting at address addr as an integer
        """
        return struct.unpack('@I', self._mm[addr:addr+4])[0]

    def poke32(self, addr, val):
        """
        Writes the 32-bit value val to address starting at addr.
        Will throw if read_only was set to True.
        A value that exceeds 32 bits will be truncated to 32 bits.
        """
        assert not self._read_only
        self._mm[addr:addr+4] = struct.pack(
            '@I',
            (val & 0xFFFFFFFF),
        )