Initial support for reading expansion ROM via VGA BIOS address.
[platform/upstream/libpciaccess.git] / src / linux_sysfs.c
1 /*
2  * (C) Copyright IBM Corporation 2006
3  * All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a
6  * copy of this software and associated documentation files (the "Software"),
7  * to deal in the Software without restriction, including without limitation
8  * on the rights to use, copy, modify, merge, publish, distribute, sub
9  * license, and/or sell copies of the Software, and to permit persons to whom
10  * the Software is furnished to do so, subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice (including the next
13  * paragraph) shall be included in all copies or substantial portions of the
14  * Software.
15  *
16  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
19  * IBM AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22  * DEALINGS IN THE SOFTWARE.
23  */
24
25 /**
26  * \file linux_sysfs.c
27  * Access PCI subsystem using Linux's sysfs interface.  This interface is
28  * available starting somewhere in the late 2.5.x kernel phase, and is the
29  * prefered method on all 2.6.x kernels.
30  *
31  * \author Ian Romanick <idr@us.ibm.com>
32  */
33
34 #define _GNU_SOURCE
35
36 #include <stdlib.h>
37 #include <string.h>
38 #include <stdio.h>
39 #include <unistd.h>
40 #include <sys/types.h>
41 #include <sys/stat.h>
42 #include <fcntl.h>
43 #include <sys/mman.h>
44 #include <dirent.h>
45 #include <errno.h>
46
47 #include "pciaccess.h"
48 #include "pciaccess_private.h"
49 #include "linux_devmem.h"
50
51 static int pci_device_linux_sysfs_read_rom( struct pci_device * dev,
52     void * buffer );
53
54 static int pci_device_linux_sysfs_probe( struct pci_device * dev );
55
56 static int pci_device_linux_sysfs_map_region( struct pci_device * dev,
57     unsigned region, int write_enable );
58
59 static int pci_device_linux_sysfs_unmap_region( struct pci_device * dev,
60     unsigned region );
61
62 static int pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
63     pciaddr_t offset, pciaddr_t size, pciaddr_t * bytes_read );
64
65 static int pci_device_linux_sysfs_write( struct pci_device * dev,
66     const void * data, pciaddr_t offset, pciaddr_t size,
67     pciaddr_t * bytes_wrtten );
68
69 static const struct pci_system_methods linux_sysfs_methods = {
70     .destroy = NULL,
71     .destroy_device = NULL,
72     .read_rom = pci_device_linux_sysfs_read_rom,
73     .probe = pci_device_linux_sysfs_probe,
74     .map = pci_device_linux_sysfs_map_region,
75     .unmap = pci_device_linux_sysfs_unmap_region,
76
77     .read = pci_device_linux_sysfs_read,
78     .write = pci_device_linux_sysfs_write,
79
80     .fill_capabilities = pci_fill_capabilities_generic
81 };
82
83 #define SYS_BUS_PCI "/sys/bus/pci/devices"
84
85
86 static int populate_entries(struct pci_system * pci_sys);
87
88
89 /**
90  * Attempt to access PCI subsystem using Linux's sysfs interface.
91  */
92 int
93 pci_system_linux_sysfs_create( void )
94 {
95     int err = 0;
96     struct stat st;
97
98
99     /* If the directory "/sys/bus/pci/devices" exists, then the PCI subsystem
100      * can be accessed using this interface.
101      */
102     
103     if ( stat( SYS_BUS_PCI, & st ) == 0 ) {
104         pci_sys = calloc( 1, sizeof( struct pci_system ) );
105         if ( pci_sys != NULL ) {
106             pci_sys->methods = & linux_sysfs_methods;
107             err = populate_entries(pci_sys);
108         }
109         else {
110             err = ENOMEM;
111         }
112     }
113     else {
114         err = errno;
115     }
116
117     return err;
118 }
119
120
121 /**
122  * Filter out the names "." and ".." from the scanned sysfs entries.
123  *
124  * \param d  Directory entry being processed by \c scandir.
125  *
126  * \return
127  * Zero if the entry name matches either "." or "..", non-zero otherwise.
128  *
129  * \sa scandir, populate_entries
130  */
131 static int
132 scan_sys_pci_filter( const struct dirent * d )
133 {
134     return !((strcmp( d->d_name, "." ) == 0) 
135              || (strcmp( d->d_name, ".." ) == 0));
136 }
137
138
139 int
140 populate_entries( struct pci_system * p )
141 {
142     struct dirent ** devices;
143     int n;
144     int i;
145     int err;
146
147
148     n = scandir( SYS_BUS_PCI, & devices, scan_sys_pci_filter, alphasort );
149     if ( n > 0 ) {
150         p->num_devices = n;
151         p->devices = calloc( n, sizeof( struct pci_device_private ) );
152
153         if (p->devices != NULL) {
154             for (i = 0 ; i < n ; i++) {
155                 uint8_t config[48];
156                 pciaddr_t bytes;
157                 unsigned dom, bus, dev, func;
158                 struct pci_device_private *device =
159                         (struct pci_device_private *) &p->devices[i];
160
161
162                 sscanf(devices[i]->d_name, "%04x:%02x:%02x.%1u",
163                        & dom, & bus, & dev, & func);
164
165                 device->base.domain = dom;
166                 device->base.bus = bus;
167                 device->base.dev = dev;
168                 device->base.func = func;
169
170
171                 err = pci_device_linux_sysfs_read(& device->base, config, 0,
172                                                   48, & bytes);
173                 if ((bytes == 48) && !err) {
174                     device->base.vendor_id = (uint16_t)config[0]
175                         + ((uint16_t)config[1] << 8);
176                     device->base.device_id = (uint16_t)config[2]
177                         + ((uint16_t)config[3] << 8);
178                     device->base.device_class = (uint32_t)config[9]
179                         + ((uint32_t)config[10] << 8)
180                         + ((uint32_t)config[11] << 16);
181                     device->base.revision = config[8];
182                     device->base.subvendor_id = (uint16_t)config[44]
183                         + ((uint16_t)config[45] << 8);
184                     device->base.subdevice_id = (uint16_t)config[46]
185                         + ((uint16_t)config[47] << 8);
186                 }
187
188                 if (err) {
189                     break;
190                 }
191             }
192         }
193         else {
194             err = ENOMEM;
195         }
196     }
197
198     if (err) {
199         free(p->devices);
200         p->devices = NULL;
201     }
202
203     return err;
204 }
205
206
207 static int
208 pci_device_linux_sysfs_probe( struct pci_device * dev )
209 {
210     char     name[256];
211     uint8_t  config[256];
212     char     resource[512];
213     int fd;
214     pciaddr_t bytes;
215     unsigned i;
216     int err;
217
218
219     err = pci_device_linux_sysfs_read( dev, config, 0, 256, & bytes );
220     if ( bytes >= 64 ) {
221         struct pci_device_private *priv = (struct pci_device_private *) dev;
222
223         dev->irq = config[60];
224         priv->header_type = config[14];
225
226
227         /* The PCI config registers can be used to obtain information
228          * about the memory and I/O regions for the device.  However,
229          * doing so requires some tricky parsing (to correctly handle
230          * 64-bit memory regions) and requires writing to the config
231          * registers.  Since we'd like to avoid having to deal with the
232          * parsing issues and non-root users can write to PCI config
233          * registers, we use a different file in the device's sysfs
234          * directory called "resource".
235          * 
236          * The resource file contains all of the needed information in
237          * a format that is consistent across all platforms.  Each BAR
238          * and the expansion ROM have a single line of data containing
239          * 3, 64-bit hex values:  the first address in the region,
240          * the last address in the region, and the region's flags.
241          */
242         snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/resource",
243                   SYS_BUS_PCI,
244                   dev->domain,
245                   dev->bus,
246                   dev->dev,
247                   dev->func );
248         fd = open( name, O_RDONLY );
249         if ( fd != -1 ) {
250             char * next;
251             pciaddr_t  low_addr;
252             pciaddr_t  high_addr;
253             pciaddr_t  flags;
254
255
256             bytes = read( fd, resource, 512 );
257             resource[511] = '\0';
258
259             close( fd );
260
261             next = resource;
262             for ( i = 0 ; i < 6 ; i++ ) {
263
264                 dev->regions[i].base_addr = strtoull( next, & next, 16 );
265                 high_addr = strtoull( next, & next, 16 );
266                 flags = strtoull( next, & next, 16 );
267                     
268                 if ( dev->regions[i].base_addr != 0 ) {
269                     dev->regions[i].size = (high_addr 
270                                             - dev->regions[i].base_addr) + 1;
271
272                     dev->regions[i].is_IO = (flags & 0x01);
273                     dev->regions[i].is_64 = (flags & 0x04);
274                     dev->regions[i].is_prefetchable = (flags & 0x08);
275                 }
276             }
277
278             low_addr = strtoull( next, & next, 16 );
279             high_addr = strtoull( next, & next, 16 );
280             flags = strtoull( next, & next, 16 );
281             if ( low_addr != 0 ) {
282                 priv->rom_base = low_addr;
283                 dev->rom_size = (high_addr - low_addr) + 1;
284             }
285         }
286     }
287
288     return err;
289 }
290
291
292 static int
293 pci_device_linux_sysfs_read_rom( struct pci_device * dev, void * buffer )
294 {
295     char name[256];
296     int fd;
297     struct stat  st;
298     int err = 0;
299     size_t total_bytes;
300
301
302     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/rom",
303               SYS_BUS_PCI,
304               dev->domain,
305               dev->bus,
306               dev->dev,
307               dev->func );
308     
309     fd = open( name, O_RDWR );
310     if ( fd == -1 ) {
311         /* If reading the ROM using sysfs fails, fall back to the old
312          * /dev/mem based interface.
313          */
314         return pci_device_linux_devmem_read_rom(dev, buffer);
315     }
316
317
318     if ( fstat( fd, & st ) == -1 ) {
319         close( fd );
320         return errno;
321     }
322
323
324     /* This is a quirky thing on Linux.  Even though the ROM and the file
325      * for the ROM in sysfs are read-only, the string "1" must be written to
326      * the file to enable the ROM.  After the data has been read, "0" must be
327      * written to the file to disable the ROM.
328      */
329     write( fd, "1", 1 );
330     lseek( fd, 0, SEEK_SET );
331
332     for ( total_bytes = 0 ; total_bytes < st.st_size ; /* empty */ ) {
333         const int bytes = read( fd, (char *) buffer + total_bytes,
334                                 st.st_size - total_bytes );
335         if ( bytes == -1 ) {
336             err = errno;
337             break;
338         }
339         else if ( bytes == 0 ) {
340             break;
341         }
342
343         total_bytes += bytes;
344     }
345         
346
347     lseek( fd, 0, SEEK_SET );
348     write( fd, "0", 1 );
349
350     close( fd );
351     return err;
352 }
353
354
355 static int
356 pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
357                              pciaddr_t offset, pciaddr_t size,
358                              pciaddr_t * bytes_read )
359 {
360     char name[256];
361     pciaddr_t temp_size = size;
362     int err = 0;
363     int fd;
364
365
366     if ( bytes_read != NULL ) {
367         *bytes_read = 0;
368     }
369
370     /* Each device has a directory under sysfs.  Within that directory there
371      * is a file named "config".  This file used to access the PCI config
372      * space.  It is used here to obtain most of the information about the
373      * device.
374      */
375     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
376               SYS_BUS_PCI,
377               dev->domain,
378               dev->bus,
379               dev->dev,
380               dev->func );
381
382     fd = open( name, O_RDONLY );
383     if ( fd == -1 ) {
384         return errno;
385     }
386
387
388     while ( temp_size > 0 ) {
389         const ssize_t bytes = pread64( fd, data, temp_size, offset );
390
391         /* If zero bytes were read, then we assume it's the end of the
392          * config file.
393          */
394         if ( bytes <= 0 ) {
395             err = errno;
396             break;
397         }
398
399         temp_size -= bytes;
400         offset += bytes;
401         data += bytes;
402     }
403     
404     if ( bytes_read != NULL ) {
405         *bytes_read = size - temp_size;
406     }
407
408     close( fd );
409     return err;
410 }
411
412
413 static int
414 pci_device_linux_sysfs_write( struct pci_device * dev, const void * data,
415                              pciaddr_t offset, pciaddr_t size,
416                              pciaddr_t * bytes_written )
417 {
418     char name[256];
419     pciaddr_t temp_size = size;
420     int err = 0;
421     int fd;
422
423
424     if ( bytes_written != NULL ) {
425         *bytes_written = 0;
426     }
427
428     /* Each device has a directory under sysfs.  Within that directory there
429      * is a file named "config".  This file used to access the PCI config
430      * space.  It is used here to obtain most of the information about the
431      * device.
432      */
433     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
434               SYS_BUS_PCI,
435               dev->domain,
436               dev->bus,
437               dev->dev,
438               dev->func );
439
440     fd = open( name, O_WRONLY );
441     if ( fd == -1 ) {
442         return errno;
443     }
444
445
446     while ( temp_size > 0 ) {
447         const ssize_t bytes = pwrite64( fd, data, temp_size, offset );
448
449         /* If zero bytes were written, then we assume it's the end of the
450          * config file.
451          */
452         if ( bytes <= 0 ) {
453             err = errno;
454             break;
455         }
456
457         temp_size -= bytes;
458         offset += bytes;
459         data += bytes;
460     }
461     
462     if ( bytes_written != NULL ) {
463         *bytes_written = size - temp_size;
464     }
465
466     close( fd );
467     return err;
468 }
469
470
471 /**
472  * Map a memory region for a device using the Linux sysfs interface.
473  * 
474  * \param dev          Device whose memory region is to be mapped.
475  * \param region       Region, on the range [0, 5], that is to be mapped.
476  * \param write_enable Map for writing (non-zero).
477  * 
478  * \return
479  * Zero on success or an \c errno value on failure.
480  *
481  * \sa pci_device_map_region, pci_device_linux_sysfs_unmap_region
482  *
483  * \todo
484  * Some older 2.6.x kernels don't implement the resourceN files.  On those
485  * systems /dev/mem must be used.  On these systems it is also possible that
486  * \c mmap64 may need to be used.
487  */
488 static int
489 pci_device_linux_sysfs_map_region( struct pci_device * dev, unsigned region,
490                                    int write_enable )
491 {
492     char name[256];
493     int fd;
494     int err = 0;
495     const int prot = (write_enable) ? (PROT_READ | PROT_WRITE) : PROT_READ;
496
497
498     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/resource%u",
499               SYS_BUS_PCI,
500               dev->domain,
501               dev->bus,
502               dev->dev,
503               dev->func,
504               region );
505
506     fd = open( name, (write_enable) ? O_RDWR : O_RDONLY );
507     if ( fd == -1 ) {
508         return errno;
509     }
510
511
512     dev->regions[ region ].memory = mmap( NULL, dev->regions[ region ].size,
513                                           prot, MAP_SHARED, fd, 0 );
514     if ( dev->regions[ region ].memory == MAP_FAILED ) {
515         err = errno;
516         dev->regions[ region ].memory = NULL;
517     }
518
519     close( fd );
520     return err;
521 }
522
523
524 /**
525  * Unmap the specified region using the Linux sysfs interface.
526  *
527  * \param dev          Device whose memory region is to be mapped.
528  * \param region       Region, on the range [0, 5], that is to be mapped.
529  *
530  * \return
531  * Zero on success or an \c errno value on failure.
532  *
533  * \sa pci_device_unmap_region, pci_device_linux_sysfs_map_region
534  *
535  * \todo
536  * Some older 2.6.x kernels don't implement the resourceN files.  On those
537  * systems /dev/mem must be used.  On these systems it is also possible that
538  * \c mmap64 may need to be used.
539  */
540 static int
541 pci_device_linux_sysfs_unmap_region( struct pci_device * dev, unsigned region )
542 {
543     int err = 0;
544
545     if ( munmap( dev->regions[ region ].memory, dev->regions[ region ].size )
546          == -1 ) {
547         err = errno;
548     }
549
550     dev->regions[ region ].memory = NULL;
551
552     return err;
553 }