How do I write to registers in hardware using Pyth

2019-07-20 19:50发布

问题:

I have a C function which can read/write perfectly into the hardware register by opening the device descriptor (nf10). I am trying to do the same using Python. I am able to read the registers, but I am not able to write registers. Why am I unable to write? Is there a better way to do read/write for registers in hardware?

Relevant Python code:

#! /usr/bin/env python
import os
from fcntl import *
from struct import *

SIOCDEVPRIVATE = 35312
NF10_IOCTL_CMD_READ_STAT = SIOCDEVPRIVATE + 0
NF10_IOCTL_CMD_WRITE_REG = SIOCDEVPRIVATE + 1
NF10_IOCTL_CMD_READ_REG = SIOCDEVPRIVATE + 2

def rdaxi(addr):

    f = open("/dev/nf10", "r+")
    arg = pack("q", int(addr, 16))
    value = ioctl(f, NF10_IOCTL_CMD_READ_REG, arg)
    value = unpack("q", value)
    value = value[0]
    value = hex(value & int("0xffffffff", 16))
    f.close()
    return value

def wraxi(addr, value):

    f = open("/dev/nf10", "r+")
    arg = (int(addr, 16) << 32) + int(value, 16)
    arg = pack("q", arg)
    ioctl(f, NF10_IOCTL_CMD_WRITE_REG, arg)
    f.close()

relevant C code

#include <fcntl.h>
#include <sys/ioctl.h> 
#include <stdio.h>
#include <stdint.h>
#include <string.h>

#define NF10_IOCTL_CMD_READ_STAT (SIOCDEVPRIVATE+0)
#define NF10_IOCTL_CMD_WRITE_REG (SIOCDEVPRIVATE+1)
#define NF10_IOCTL_CMD_READ_REG (SIOCDEVPRIVATE+2)

int main(int argc, char* argv[]){
   int f;
   uint64_t v;
   uint64_t addr;
   uint64_t val;

   if(argc < 3){
       printf("usage: rdaxi reg_addr(in hex) reg_val(in_hex)\n\n");
       return 0;
   }
   else{
    sscanf(argv[1], "%llx", &addr);
    sscanf(argv[2], "%llx", &val);
  }

//----------------------------------------------------
//-- open nf10 file descriptor for all the fun stuff
//----------------------------------------------------
f = open("/dev/nf10", O_RDWR);
if(f < 0){
    perror("/dev/nf10");
    return 0;
}

printf("\n");

// High 32 bits are the AXI address,
// low 32 bits are the value written to that address
v = (addr << 32) + val;
if(ioctl(f, NF10_IOCTL_CMD_WRITE_REG, v) < 0){
    perror("nf10 ioctl failed");
    return 0;
}
printf("\n");

close(f);

return 0;

}

回答1:

I think it's best to implement lower-level operations on registers in C, and compile C to .so. Then load the .so in python.



回答2:

I suspect "endianness" may be your issue. It's hard to tell without knowing the hardware you're writing to, though. I noticed you've left off the byte order specifier from your pack function call. Most hardware registers are big-endian, meaning they expect bit 0 at the lowest memory address and the most significant bit at the highest address.

Without the byte order specifier, Python will pack with your native endianness, which is little-endian on an Intel system. Try packing it with the big-endian specifier so that everything stays in the same order as it started:

arg = pack(">q", arg)