-
Notifications
You must be signed in to change notification settings - Fork 5
/
gopcie.go
269 lines (234 loc) · 7.69 KB
/
gopcie.go
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
//
// The MIT License
//
// Copyright (c) 2017-2018 by the author(s)
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
// Author(s):
// - Andreas Oeldemann <andreas.oeldemann@tum.de>
//
// Date Created: June 9th 2017
// Date Last Modified: July 4th 2017
//
// Description:
//
// Package gopcie implements data transfer to/from a PCIExpress hardware device
// on a Linux-based system. Data can be transferred via:
//
// 1) PCIExpress Direct Memory Access (DMA) transfers (requires kernel-space
// device driver) or
// 2) PCIExpress Base Address Register (BAR) accesses.
//
// The BAR resource file identification is based on Andre Richter's
// easy-pci-mmap:
// https://github.com/andre-richter/easy-pci-mmap
//
package gopcie
import (
"errors"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strconv"
"strings"
"syscall"
"unsafe"
)
const (
PCIE_ACCESS_READ = 1
PCIE_ACCESS_WRITE = 2
)
// PCIeDMA implements PCIExpress DMA reads and writes.
type PCIeDMA struct {
fd *os.File
accessMode int
}
// PCIeDMAOpen opens a PCIExpress DMA device. The function expects the
// device name (i.e. /dev/...) and an access mode flag (read/write).
func PCIeDMAOpen(devName string, accessMode int) (*PCIeDMA, error) {
// check if access mode is set
if (accessMode & (PCIE_ACCESS_READ | PCIE_ACCESS_WRITE)) == 0 {
return nil, errors.New("invalid access mode")
}
// open device
fd, err := os.OpenFile(devName, os.O_RDWR, 0600)
if err != nil {
return nil,
errors.New("could not open device")
}
// create device
dev := PCIeDMA{
fd: fd,
accessMode: accessMode,
}
return &dev, nil
}
// Close closes the PCIExpress DMA device.
func (dev *PCIeDMA) Close() {
dev.fd.Close()
}
// Write performs a DMA write transfer.
func (dev *PCIeDMA) Write(addr uint64, data []byte) error {
// check if access mode allows writing
if (dev.accessMode & PCIE_ACCESS_WRITE) == 0 {
return errors.New("access mode does not allow writing")
}
// perform write transfer
nBytesWritten, err := dev.fd.WriteAt(data, int64(addr))
if err != nil || nBytesWritten != len(data) {
return errors.New("could not write to device")
}
return nil
}
// Read performs a DMA read transfer.
func (dev *PCIeDMA) Read(addr uint64, data []byte) error {
// check if access mode allows reading
if (dev.accessMode & PCIE_ACCESS_READ) == 0 {
return errors.New("access mode does not allow reading")
}
// perform read transfer
nBytesRead, err := dev.fd.ReadAt(data, int64(addr))
if err != nil || nBytesRead != len(data) {
return errors.New("could not read from device")
}
return nil
}
// PCIeBAR implements reads and writes from/to a PCIExpress base address
// registers.
type PCIeBAR struct {
fd *os.File
bar []byte
}
// PCIeBAROpen opens the PCIExpress base address register. The function expects
// the function, vendor, device and bar ID of the bar to be opened.
func PCIeBAROpen(functionId, vendorId, deviceId, barId uint) (*PCIeBAR, error) {
barFilename := ""
// list system devices directory
devDirs, err := ioutil.ReadDir("/sys/bus/pci/devices")
if err != nil {
return nil, errors.New("could not read /sys/bus/pci/devices directory")
}
// iterate over all devices
for _, devDir := range devDirs {
// not the device we are looking for if directory name does not start
// with "0000:"
if devDir.Name()[0:5] != "0000:" {
continue
}
// get function id and see if it matches the one we are looking for
functionIdFound, err := strconv.ParseUint(
devDir.Name()[len(devDir.Name())-1:], 10, 32)
if err != nil || uint(functionIdFound) != functionId {
continue
}
// read device vendor file
vendorFilename := filepath.Join("/sys/bus/pci/devices", devDir.Name(),
"vendor")
vendorFile, err := ioutil.ReadFile(vendorFilename)
if err != nil {
return nil, errors.New("could not open pci vendor file")
}
vendorFileStr := string(vendorFile)
// device vendor file should have only one line and start with "0x"
if vendorFileStr[0:2] != "0x" ||
strings.Index(vendorFileStr, "\n") != len(vendorFileStr)-1 {
continue
}
vendorFileStr = vendorFileStr[0 : len(vendorFileStr)-1]
// get vendor id
vendorIdFound, err := strconv.ParseInt(vendorFileStr[2:], 16, 32)
if err != nil || uint(vendorIdFound) != vendorId {
continue
}
// read pci device file
deviceFilename := filepath.Join("/sys/bus/pci/devices", devDir.Name(),
"device")
deviceFile, err := ioutil.ReadFile(deviceFilename)
if err != nil {
return nil, errors.New("could not open pci device file")
}
deviceFileStr := string(deviceFile)
// device file should have only one line and start with "0x"
if deviceFileStr[0:2] != "0x" ||
strings.Index(deviceFileStr, "\n") != len(deviceFileStr)-1 {
continue
}
deviceFileStr = deviceFileStr[0 : len(deviceFileStr)-1]
// get device id
deviceIdFound, err := strconv.ParseInt(deviceFileStr[2:], 16, 32)
if err != nil || uint(deviceIdFound) != deviceId {
continue
}
// all ids matched. found it!
barFilename = filepath.Join("/sys/bus/pci/devices", devDir.Name(),
fmt.Sprintf("resource%d", barId))
break
}
// check if the BAR resource file was found
if len(barFilename) == 0 {
return nil, errors.New("could not find BAR")
}
// stat the BAR resource file to get its size
barFileInfo, err := os.Stat(barFilename)
if err != nil {
return nil, errors.New("could not stat BAR resource file")
}
// open BAR resource file
fd, err := os.OpenFile(barFilename, os.O_RDWR|os.O_SYNC, 0666)
if err != nil {
return nil, errors.New("could not open BAR resource file")
}
// memory-map the BAR
bar, err := syscall.Mmap(int(fd.Fd()), 0, int(barFileInfo.Size()),
syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_SHARED)
if err != nil {
return nil, errors.New("could not memory-map BAR")
}
return &PCIeBAR{fd, bar}, nil
}
// Close closes the PCIExpress base address register.
func (bar *PCIeBAR) Close() error {
// un-memory map the BAR
err := syscall.Munmap(bar.bar)
if err != nil {
return errors.New("could not un-memory-map BAR")
}
// close BAR resource file
bar.fd.Close()
return nil
}
// Write writes data to a PCIExpress base address register.
func (bar *PCIeBAR) Write(addr, data uint32) {
*(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&bar.bar[0])) +
uintptr(addr))) = data
}
// WriteMask writes data to a PCIExpress base address register. The specified
// mask determins which bits of the register shall be written.
func (bar *PCIeBAR) WriteMask(addr, data, mask uint32) {
rd_data := bar.Read(addr)
wr_data := (rd_data & ^mask) | (data & mask)
bar.Write(addr, wr_data)
}
// Read reads data from a PCIExpress base address register.
func (bar *PCIeBAR) Read(addr uint32) uint32 {
return *(*uint32)(unsafe.Pointer(uintptr(unsafe.Pointer(&bar.bar[0])) +
uintptr(addr)))
}