New interfaces to map memory with MTRR (or similar) support.
[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 "config.h"
48
49 #ifdef HAVE_MTRR
50 #include <asm/mtrr.h>
51 #include <sys/ioctl.h>
52 #endif
53
54 #include "pciaccess.h"
55 #include "pciaccess_private.h"
56 #include "linux_devmem.h"
57
58 static int pci_device_linux_sysfs_read_rom( struct pci_device * dev,
59     void * buffer );
60
61 static int pci_device_linux_sysfs_probe( struct pci_device * dev );
62
63 static int pci_device_linux_sysfs_map_range(struct pci_device *dev,
64     struct pci_device_mapping *map);
65
66 static int pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
67     pciaddr_t offset, pciaddr_t size, pciaddr_t * bytes_read );
68
69 static int pci_device_linux_sysfs_write( struct pci_device * dev,
70     const void * data, pciaddr_t offset, pciaddr_t size,
71     pciaddr_t * bytes_wrtten );
72
73 static const struct pci_system_methods linux_sysfs_methods = {
74     .destroy = NULL,
75     .destroy_device = NULL,
76     .read_rom = pci_device_linux_sysfs_read_rom,
77     .probe = pci_device_linux_sysfs_probe,
78     .map_range = pci_device_linux_sysfs_map_range,
79     .unmap_range = pci_device_generic_unmap_range,
80
81     .read = pci_device_linux_sysfs_read,
82     .write = pci_device_linux_sysfs_write,
83
84     .fill_capabilities = pci_fill_capabilities_generic
85 };
86
87 #define SYS_BUS_PCI "/sys/bus/pci/devices"
88
89
90 static int populate_entries(struct pci_system * pci_sys);
91
92
93 /**
94  * Attempt to access PCI subsystem using Linux's sysfs interface.
95  */
96 int
97 pci_system_linux_sysfs_create( void )
98 {
99     int err = 0;
100     struct stat st;
101
102
103     /* If the directory "/sys/bus/pci/devices" exists, then the PCI subsystem
104      * can be accessed using this interface.
105      */
106     
107     if ( stat( SYS_BUS_PCI, & st ) == 0 ) {
108         pci_sys = calloc( 1, sizeof( struct pci_system ) );
109         if ( pci_sys != NULL ) {
110             pci_sys->methods = & linux_sysfs_methods;
111             err = populate_entries(pci_sys);
112         }
113         else {
114             err = ENOMEM;
115         }
116     }
117     else {
118         err = errno;
119     }
120
121 #ifdef HAVE_MTRR
122     pci_sys->mtrr_fd = open("/proc/mtrr", O_WRONLY);
123 #endif
124
125     return err;
126 }
127
128
129 /**
130  * Filter out the names "." and ".." from the scanned sysfs entries.
131  *
132  * \param d  Directory entry being processed by \c scandir.
133  *
134  * \return
135  * Zero if the entry name matches either "." or "..", non-zero otherwise.
136  *
137  * \sa scandir, populate_entries
138  */
139 static int
140 scan_sys_pci_filter( const struct dirent * d )
141 {
142     return !((strcmp( d->d_name, "." ) == 0) 
143              || (strcmp( d->d_name, ".." ) == 0));
144 }
145
146
147 int
148 populate_entries( struct pci_system * p )
149 {
150     struct dirent ** devices;
151     int n;
152     int i;
153     int err = 0;
154
155
156     n = scandir( SYS_BUS_PCI, & devices, scan_sys_pci_filter, alphasort );
157     if ( n > 0 ) {
158         p->num_devices = n;
159         p->devices = calloc( n, sizeof( struct pci_device_private ) );
160
161         if (p->devices != NULL) {
162             for (i = 0 ; i < n ; i++) {
163                 uint8_t config[48];
164                 pciaddr_t bytes;
165                 unsigned dom, bus, dev, func;
166                 struct pci_device_private *device =
167                         (struct pci_device_private *) &p->devices[i];
168
169
170                 sscanf(devices[i]->d_name, "%04x:%02x:%02x.%1u",
171                        & dom, & bus, & dev, & func);
172
173                 device->base.domain = dom;
174                 device->base.bus = bus;
175                 device->base.dev = dev;
176                 device->base.func = func;
177
178
179                 err = pci_device_linux_sysfs_read(& device->base, config, 0,
180                                                   48, & bytes);
181                 if ((bytes == 48) && !err) {
182                     device->base.vendor_id = (uint16_t)config[0]
183                         + ((uint16_t)config[1] << 8);
184                     device->base.device_id = (uint16_t)config[2]
185                         + ((uint16_t)config[3] << 8);
186                     device->base.device_class = (uint32_t)config[9]
187                         + ((uint32_t)config[10] << 8)
188                         + ((uint32_t)config[11] << 16);
189                     device->base.revision = config[8];
190                     device->base.subvendor_id = (uint16_t)config[44]
191                         + ((uint16_t)config[45] << 8);
192                     device->base.subdevice_id = (uint16_t)config[46]
193                         + ((uint16_t)config[47] << 8);
194                 }
195
196                 if (err) {
197                     break;
198                 }
199             }
200         }
201         else {
202             err = ENOMEM;
203         }
204     }
205
206     if (err) {
207         free(p->devices);
208         p->devices = NULL;
209     }
210
211     return err;
212 }
213
214
215 static int
216 pci_device_linux_sysfs_probe( struct pci_device * dev )
217 {
218     char     name[256];
219     uint8_t  config[256];
220     char     resource[512];
221     int fd;
222     pciaddr_t bytes;
223     unsigned i;
224     int err;
225
226
227     err = pci_device_linux_sysfs_read( dev, config, 0, 256, & bytes );
228     if ( bytes >= 64 ) {
229         struct pci_device_private *priv = (struct pci_device_private *) dev;
230
231         dev->irq = config[60];
232         priv->header_type = config[14];
233
234
235         /* The PCI config registers can be used to obtain information
236          * about the memory and I/O regions for the device.  However,
237          * doing so requires some tricky parsing (to correctly handle
238          * 64-bit memory regions) and requires writing to the config
239          * registers.  Since we'd like to avoid having to deal with the
240          * parsing issues and non-root users can write to PCI config
241          * registers, we use a different file in the device's sysfs
242          * directory called "resource".
243          * 
244          * The resource file contains all of the needed information in
245          * a format that is consistent across all platforms.  Each BAR
246          * and the expansion ROM have a single line of data containing
247          * 3, 64-bit hex values:  the first address in the region,
248          * the last address in the region, and the region's flags.
249          */
250         snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/resource",
251                   SYS_BUS_PCI,
252                   dev->domain,
253                   dev->bus,
254                   dev->dev,
255                   dev->func );
256         fd = open( name, O_RDONLY );
257         if ( fd != -1 ) {
258             char * next;
259             pciaddr_t  low_addr;
260             pciaddr_t  high_addr;
261             pciaddr_t  flags;
262
263
264             bytes = read( fd, resource, 512 );
265             resource[511] = '\0';
266
267             close( fd );
268
269             next = resource;
270             for ( i = 0 ; i < 6 ; i++ ) {
271
272                 dev->regions[i].base_addr = strtoull( next, & next, 16 );
273                 high_addr = strtoull( next, & next, 16 );
274                 flags = strtoull( next, & next, 16 );
275                     
276                 if ( dev->regions[i].base_addr != 0 ) {
277                     dev->regions[i].size = (high_addr 
278                                             - dev->regions[i].base_addr) + 1;
279
280                     dev->regions[i].is_IO = (flags & 0x01);
281                     dev->regions[i].is_64 = (flags & 0x04);
282                     dev->regions[i].is_prefetchable = (flags & 0x08);
283                 }
284             }
285
286             low_addr = strtoull( next, & next, 16 );
287             high_addr = strtoull( next, & next, 16 );
288             flags = strtoull( next, & next, 16 );
289             if ( low_addr != 0 ) {
290                 priv->rom_base = low_addr;
291                 dev->rom_size = (high_addr - low_addr) + 1;
292             }
293         }
294     }
295
296     return err;
297 }
298
299
300 static int
301 pci_device_linux_sysfs_read_rom( struct pci_device * dev, void * buffer )
302 {
303     char name[256];
304     int fd;
305     struct stat  st;
306     int err = 0;
307     size_t total_bytes;
308
309
310     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/rom",
311               SYS_BUS_PCI,
312               dev->domain,
313               dev->bus,
314               dev->dev,
315               dev->func );
316     
317     fd = open( name, O_RDWR );
318     if ( fd == -1 ) {
319         /* If reading the ROM using sysfs fails, fall back to the old
320          * /dev/mem based interface.
321          */
322         return pci_device_linux_devmem_read_rom(dev, buffer);
323     }
324
325
326     if ( fstat( fd, & st ) == -1 ) {
327         close( fd );
328         return errno;
329     }
330
331
332     /* This is a quirky thing on Linux.  Even though the ROM and the file
333      * for the ROM in sysfs are read-only, the string "1" must be written to
334      * the file to enable the ROM.  After the data has been read, "0" must be
335      * written to the file to disable the ROM.
336      */
337     write( fd, "1", 1 );
338     lseek( fd, 0, SEEK_SET );
339
340     for ( total_bytes = 0 ; total_bytes < st.st_size ; /* empty */ ) {
341         const int bytes = read( fd, (char *) buffer + total_bytes,
342                                 st.st_size - total_bytes );
343         if ( bytes == -1 ) {
344             err = errno;
345             break;
346         }
347         else if ( bytes == 0 ) {
348             break;
349         }
350
351         total_bytes += bytes;
352     }
353         
354
355     lseek( fd, 0, SEEK_SET );
356     write( fd, "0", 1 );
357
358     close( fd );
359     return err;
360 }
361
362
363 static int
364 pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
365                              pciaddr_t offset, pciaddr_t size,
366                              pciaddr_t * bytes_read )
367 {
368     char name[256];
369     pciaddr_t temp_size = size;
370     int err = 0;
371     int fd;
372
373
374     if ( bytes_read != NULL ) {
375         *bytes_read = 0;
376     }
377
378     /* Each device has a directory under sysfs.  Within that directory there
379      * is a file named "config".  This file used to access the PCI config
380      * space.  It is used here to obtain most of the information about the
381      * device.
382      */
383     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
384               SYS_BUS_PCI,
385               dev->domain,
386               dev->bus,
387               dev->dev,
388               dev->func );
389
390     fd = open( name, O_RDONLY );
391     if ( fd == -1 ) {
392         return errno;
393     }
394
395
396     while ( temp_size > 0 ) {
397         const ssize_t bytes = pread64( fd, data, temp_size, offset );
398
399         /* If zero bytes were read, then we assume it's the end of the
400          * config file.
401          */
402         if ( bytes <= 0 ) {
403             err = errno;
404             break;
405         }
406
407         temp_size -= bytes;
408         offset += bytes;
409         data += bytes;
410     }
411     
412     if ( bytes_read != NULL ) {
413         *bytes_read = size - temp_size;
414     }
415
416     close( fd );
417     return err;
418 }
419
420
421 static int
422 pci_device_linux_sysfs_write( struct pci_device * dev, const void * data,
423                              pciaddr_t offset, pciaddr_t size,
424                              pciaddr_t * bytes_written )
425 {
426     char name[256];
427     pciaddr_t temp_size = size;
428     int err = 0;
429     int fd;
430
431
432     if ( bytes_written != NULL ) {
433         *bytes_written = 0;
434     }
435
436     /* Each device has a directory under sysfs.  Within that directory there
437      * is a file named "config".  This file used to access the PCI config
438      * space.  It is used here to obtain most of the information about the
439      * device.
440      */
441     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
442               SYS_BUS_PCI,
443               dev->domain,
444               dev->bus,
445               dev->dev,
446               dev->func );
447
448     fd = open( name, O_WRONLY );
449     if ( fd == -1 ) {
450         return errno;
451     }
452
453
454     while ( temp_size > 0 ) {
455         const ssize_t bytes = pwrite64( fd, data, temp_size, offset );
456
457         /* If zero bytes were written, then we assume it's the end of the
458          * config file.
459          */
460         if ( bytes <= 0 ) {
461             err = errno;
462             break;
463         }
464
465         temp_size -= bytes;
466         offset += bytes;
467         data += bytes;
468     }
469     
470     if ( bytes_written != NULL ) {
471         *bytes_written = size - temp_size;
472     }
473
474     close( fd );
475     return err;
476 }
477
478
479 /**
480  * Map a memory region for a device using the Linux sysfs interface.
481  * 
482  * \param dev   Device whose memory region is to be mapped.
483  * \param map   Parameters of the mapping that is to be created.
484  * 
485  * \return
486  * Zero on success or an \c errno value on failure.
487  *
488  * \sa pci_device_map_rrange, pci_device_linux_sysfs_unmap_range
489  *
490  * \todo
491  * Some older 2.6.x kernels don't implement the resourceN files.  On those
492  * systems /dev/mem must be used.  On these systems it is also possible that
493  * \c mmap64 may need to be used.
494  */
495 static int
496 pci_device_linux_sysfs_map_range(struct pci_device *dev,
497                                  struct pci_device_mapping *map)
498 {
499     char name[256];
500     int fd;
501     int err = 0;
502     const int prot = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
503         ? (PROT_READ | PROT_WRITE) : PROT_READ;
504     const int open_flags = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
505         ? O_RDWR : O_RDONLY;
506     const off_t offset = map->base - dev->regions[map->region].base_addr;
507 #ifdef HAVE_MTRR
508     struct mtrr_sentry sentry = {
509         .base = map->base,
510         .size = map->size,
511         .type = MTRR_TYPE_UNCACHABLE
512     };
513 #endif
514
515     snprintf(name, 255, "%s/%04x:%02x:%02x.%1u/resource%u",
516              SYS_BUS_PCI,
517              dev->domain,
518              dev->bus,
519              dev->dev,
520              dev->func,
521              map->region);
522
523     fd = open(name, open_flags);
524     if (fd == -1) {
525         return errno;
526     }
527
528
529     map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
530     if (map->memory == MAP_FAILED) {
531         err = errno;
532         map->memory = NULL;
533     }
534
535     close(fd);
536
537 #ifdef HAVE_MTRR
538     if ((map->flags & PCI_DEV_MAP_FLAG_CACHABLE) != 0) {
539         sentry.type = MTRR_TYPE_WRBACK;
540     } else if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) != 0) {
541         sentry.type = MTRR_TYPE_WRCOMB;
542     }
543
544     if (pci_sys->mtrr_fd != -1) {
545         if (ioctl(pci_sys->mtrr_fd, MTRRIOC_ADD_ENTRY, &sentry) < 0) {
546             /* FIXME: Should we report an error in this case?
547              */
548             fprintf(stderr, "error setting MTRR "
549                     "(base = 0x%08lx, size = 0x%08x, type = %u) %s (%d)\n",
550                     sentry.base, sentry.size, sentry.type,
551                     strerror(errno), errno);
552 /*            err = errno;*/
553         }
554     }
555 #endif
556
557     return err;
558 }