Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I read data from bar 0, from userspace, on a pci-e card in linux?

Tags:

linux

driver

pci

On windows there is this program called pcitree that allows you to set and read memory without writing a device driver. Is there a linux alternative to pcitree that will allow me read memory on block 0 of my pcie card?

A simple use case would be that I use driver code to write a 32bit integer on the first memory address in block zero of my pci-e card. I then use pcitree alternative to read the value at the first memory address of block zero and see my integer.

Thank you

like image 646
user514156 Avatar asked Oct 20 '22 01:10

user514156


1 Answers

I found some code online that does what I want here github.com/billfarrow/pcimem. As I understand it this link offers code that maps kernel memory to user memory via the system call "mmap"

This was mostly stolen from the readme of the program, and the man pages of mmap. mmap takes

  • a start address
  • a size
  • memory protection flags
  • file descriptor that that is linked to bar0 of your pci-card.
  • and an offset

mmap returns a userspace pointer to the memory defined by the start address and size parameters.

This code shows an example of mmaps usage.

//The file handle can be found by typing "lspci -v "
//    and looking for your device.
fd = open("/sys/devices/pci0001\:00/0001\:00\:07.0/resource0", O_RDWR | O_SYNC);
//mmap returns a userspace address
//0, 4096 tells it to pull one page 
ptr = mmap(0, 4096, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0); 
printf("PCI BAR0 0x0000 = 0x%4x\n", *((unsigned short *) ptr);
like image 110
user514156 Avatar answered Oct 24 '22 09:10

user514156