pciaccess: make linux rom reading fallback optional
[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  * preferred 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 void pci_device_linux_sysfs_enable(struct pci_device *dev);
59
60 static int pci_device_linux_sysfs_read_rom( struct pci_device * dev,
61     void * buffer );
62
63 static int pci_device_linux_sysfs_probe( struct pci_device * dev );
64
65 static int pci_device_linux_sysfs_map_range(struct pci_device *dev,
66     struct pci_device_mapping *map);
67
68 static int pci_device_linux_sysfs_unmap_range(struct pci_device *dev,
69     struct pci_device_mapping *map);
70
71 static int pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
72     pciaddr_t offset, pciaddr_t size, pciaddr_t * bytes_read );
73
74 static int pci_device_linux_sysfs_write( struct pci_device * dev,
75     const void * data, pciaddr_t offset, pciaddr_t size,
76     pciaddr_t * bytes_written );
77
78 static int pci_device_linux_sysfs_boot_vga( struct pci_device * dev );
79
80 static const struct pci_system_methods linux_sysfs_methods = {
81     .destroy = NULL,
82     .destroy_device = NULL,
83     .read_rom = pci_device_linux_sysfs_read_rom,
84     .probe = pci_device_linux_sysfs_probe,
85     .map_range = pci_device_linux_sysfs_map_range,
86     .unmap_range = pci_device_linux_sysfs_unmap_range,
87
88     .read = pci_device_linux_sysfs_read,
89     .write = pci_device_linux_sysfs_write,
90
91     .fill_capabilities = pci_fill_capabilities_generic,
92     .enable = pci_device_linux_sysfs_enable,
93     .boot_vga = pci_device_linux_sysfs_boot_vga,
94 };
95
96 #define SYS_BUS_PCI "/sys/bus/pci/devices"
97
98
99 static int populate_entries(struct pci_system * pci_sys);
100
101
102 /**
103  * Attempt to access PCI subsystem using Linux's sysfs interface.
104  */
105 _pci_hidden int
106 pci_system_linux_sysfs_create( void )
107 {
108     int err = 0;
109     struct stat st;
110
111
112     /* If the directory "/sys/bus/pci/devices" exists, then the PCI subsystem
113      * can be accessed using this interface.
114      */
115     
116     if ( stat( SYS_BUS_PCI, & st ) == 0 ) {
117         pci_sys = calloc( 1, sizeof( struct pci_system ) );
118         if ( pci_sys != NULL ) {
119             pci_sys->methods = & linux_sysfs_methods;
120 #ifdef HAVE_MTRR
121             pci_sys->mtrr_fd = open("/proc/mtrr", O_WRONLY);
122 #endif
123             err = populate_entries(pci_sys);
124         }
125         else {
126             err = ENOMEM;
127         }
128     }
129     else {
130         err = errno;
131     }
132
133     return err;
134 }
135
136
137 /**
138  * Filter out the names "." and ".." from the scanned sysfs entries.
139  *
140  * \param d  Directory entry being processed by \c scandir.
141  *
142  * \return
143  * Zero if the entry name matches either "." or "..", non-zero otherwise.
144  *
145  * \sa scandir, populate_entries
146  */
147 static int
148 scan_sys_pci_filter( const struct dirent * d )
149 {
150     return !((strcmp( d->d_name, "." ) == 0) 
151              || (strcmp( d->d_name, ".." ) == 0));
152 }
153
154
155 int
156 populate_entries( struct pci_system * p )
157 {
158     struct dirent ** devices;
159     int n;
160     int i;
161     int err = 0;
162
163
164     n = scandir( SYS_BUS_PCI, & devices, scan_sys_pci_filter, alphasort );
165     if ( n > 0 ) {
166         p->num_devices = n;
167         p->devices = calloc( n, sizeof( struct pci_device_private ) );
168
169         if (p->devices != NULL) {
170             for (i = 0 ; i < n ; i++) {
171                 uint8_t config[48];
172                 pciaddr_t bytes;
173                 unsigned dom, bus, dev, func;
174                 struct pci_device_private *device =
175                         (struct pci_device_private *) &p->devices[i];
176
177
178                 sscanf(devices[i]->d_name, "%04x:%02x:%02x.%1u",
179                        & dom, & bus, & dev, & func);
180
181                 device->base.domain = dom;
182                 device->base.bus = bus;
183                 device->base.dev = dev;
184                 device->base.func = func;
185
186
187                 err = pci_device_linux_sysfs_read(& device->base, config, 0,
188                                                   48, & bytes);
189                 if ((bytes == 48) && !err) {
190                     device->base.vendor_id = (uint16_t)config[0]
191                         + ((uint16_t)config[1] << 8);
192                     device->base.device_id = (uint16_t)config[2]
193                         + ((uint16_t)config[3] << 8);
194                     device->base.device_class = (uint32_t)config[9]
195                         + ((uint32_t)config[10] << 8)
196                         + ((uint32_t)config[11] << 16);
197                     device->base.revision = config[8];
198                     device->base.subvendor_id = (uint16_t)config[44]
199                         + ((uint16_t)config[45] << 8);
200                     device->base.subdevice_id = (uint16_t)config[46]
201                         + ((uint16_t)config[47] << 8);
202                 }
203
204                 if (err) {
205                     break;
206                 }
207             }
208         }
209         else {
210             err = ENOMEM;
211         }
212     }
213
214     if (err) {
215         free(p->devices);
216         p->devices = NULL;
217     }
218
219     return err;
220 }
221
222
223 static int
224 pci_device_linux_sysfs_probe( struct pci_device * dev )
225 {
226     char     name[256];
227     uint8_t  config[256];
228     char     resource[512];
229     int fd;
230     pciaddr_t bytes;
231     unsigned i;
232     int err;
233
234
235     err = pci_device_linux_sysfs_read( dev, config, 0, 256, & bytes );
236     if ( bytes >= 64 ) {
237         struct pci_device_private *priv = (struct pci_device_private *) dev;
238
239         dev->irq = config[60];
240         priv->header_type = config[14];
241
242
243         /* The PCI config registers can be used to obtain information
244          * about the memory and I/O regions for the device.  However,
245          * doing so requires some tricky parsing (to correctly handle
246          * 64-bit memory regions) and requires writing to the config
247          * registers.  Since we'd like to avoid having to deal with the
248          * parsing issues and non-root users can write to PCI config
249          * registers, we use a different file in the device's sysfs
250          * directory called "resource".
251          * 
252          * The resource file contains all of the needed information in
253          * a format that is consistent across all platforms.  Each BAR
254          * and the expansion ROM have a single line of data containing
255          * 3, 64-bit hex values:  the first address in the region,
256          * the last address in the region, and the region's flags.
257          */
258         snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/resource",
259                   SYS_BUS_PCI,
260                   dev->domain,
261                   dev->bus,
262                   dev->dev,
263                   dev->func );
264         fd = open( name, O_RDONLY );
265         if ( fd != -1 ) {
266             char * next;
267             pciaddr_t  low_addr;
268             pciaddr_t  high_addr;
269             pciaddr_t  flags;
270
271
272             bytes = read( fd, resource, 512 );
273             resource[511] = '\0';
274
275             close( fd );
276
277             next = resource;
278             for ( i = 0 ; i < 6 ; i++ ) {
279
280                 dev->regions[i].base_addr = strtoull( next, & next, 16 );
281                 high_addr = strtoull( next, & next, 16 );
282                 flags = strtoull( next, & next, 16 );
283                     
284                 if ( dev->regions[i].base_addr != 0 ) {
285                     dev->regions[i].size = (high_addr 
286                                             - dev->regions[i].base_addr) + 1;
287
288                     dev->regions[i].is_IO = (flags & 0x01);
289                     dev->regions[i].is_64 = (flags & 0x04);
290                     dev->regions[i].is_prefetchable = (flags & 0x08);
291                 }
292             }
293
294             low_addr = strtoull( next, & next, 16 );
295             high_addr = strtoull( next, & next, 16 );
296             flags = strtoull( next, & next, 16 );
297             if ( low_addr != 0 ) {
298                 priv->rom_base = low_addr;
299                 dev->rom_size = (high_addr - low_addr) + 1;
300             }
301         }
302     }
303
304     return err;
305 }
306
307
308 static int
309 pci_device_linux_sysfs_read_rom( struct pci_device * dev, void * buffer )
310 {
311     char name[256];
312     int fd;
313     struct stat  st;
314     int err = 0;
315     size_t rom_size;
316     size_t total_bytes;
317
318
319     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/rom",
320               SYS_BUS_PCI,
321               dev->domain,
322               dev->bus,
323               dev->dev,
324               dev->func );
325     
326     fd = open( name, O_RDWR );
327     if ( fd == -1 ) {
328 #ifdef LINUX_ROM
329         /* If reading the ROM using sysfs fails, fall back to the old
330          * /dev/mem based interface.
331          * disable this for newer kernels using configure
332          */
333         return pci_device_linux_devmem_read_rom(dev, buffer);
334 #else
335         return errno;
336 #endif
337     }
338
339
340     if ( fstat( fd, & st ) == -1 ) {
341         close( fd );
342         return errno;
343     }
344
345     rom_size = st.st_size;
346     if ( rom_size == 0 )
347         rom_size = 0x10000;
348
349     /* This is a quirky thing on Linux.  Even though the ROM and the file
350      * for the ROM in sysfs are read-only, the string "1" must be written to
351      * the file to enable the ROM.  After the data has been read, "0" must be
352      * written to the file to disable the ROM.
353      */
354     write( fd, "1", 1 );
355     lseek( fd, 0, SEEK_SET );
356
357     for ( total_bytes = 0 ; total_bytes < rom_size ; /* empty */ ) {
358         const int bytes = read( fd, (char *) buffer + total_bytes,
359                                 rom_size - total_bytes );
360         if ( bytes == -1 ) {
361             err = errno;
362             break;
363         }
364         else if ( bytes == 0 ) {
365             break;
366         }
367
368         total_bytes += bytes;
369     }
370         
371
372     lseek( fd, 0, SEEK_SET );
373     write( fd, "0", 1 );
374
375     close( fd );
376     return err;
377 }
378
379
380 static int
381 pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
382                              pciaddr_t offset, pciaddr_t size,
383                              pciaddr_t * bytes_read )
384 {
385     char name[256];
386     pciaddr_t temp_size = size;
387     int err = 0;
388     int fd;
389     char *data_bytes = data;
390
391     if ( bytes_read != NULL ) {
392         *bytes_read = 0;
393     }
394
395     /* Each device has a directory under sysfs.  Within that directory there
396      * is a file named "config".  This file used to access the PCI config
397      * space.  It is used here to obtain most of the information about the
398      * device.
399      */
400     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
401               SYS_BUS_PCI,
402               dev->domain,
403               dev->bus,
404               dev->dev,
405               dev->func );
406
407     fd = open( name, O_RDONLY );
408     if ( fd == -1 ) {
409         return errno;
410     }
411
412
413     while ( temp_size > 0 ) {
414         const ssize_t bytes = pread64( fd, data_bytes, temp_size, offset );
415
416         /* If zero bytes were read, then we assume it's the end of the
417          * config file.
418          */
419         if ( bytes <= 0 ) {
420             err = errno;
421             break;
422         }
423
424         temp_size -= bytes;
425         offset += bytes;
426         data_bytes += bytes;
427     }
428     
429     if ( bytes_read != NULL ) {
430         *bytes_read = size - temp_size;
431     }
432
433     close( fd );
434     return err;
435 }
436
437
438 static int
439 pci_device_linux_sysfs_write( struct pci_device * dev, const void * data,
440                              pciaddr_t offset, pciaddr_t size,
441                              pciaddr_t * bytes_written )
442 {
443     char name[256];
444     pciaddr_t temp_size = size;
445     int err = 0;
446     int fd;
447     const char *data_bytes = data;
448
449     if ( bytes_written != NULL ) {
450         *bytes_written = 0;
451     }
452
453     /* Each device has a directory under sysfs.  Within that directory there
454      * is a file named "config".  This file used to access the PCI config
455      * space.  It is used here to obtain most of the information about the
456      * device.
457      */
458     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
459               SYS_BUS_PCI,
460               dev->domain,
461               dev->bus,
462               dev->dev,
463               dev->func );
464
465     fd = open( name, O_WRONLY );
466     if ( fd == -1 ) {
467         return errno;
468     }
469
470
471     while ( temp_size > 0 ) {
472         const ssize_t bytes = pwrite64( fd, data_bytes, temp_size, offset );
473
474         /* If zero bytes were written, then we assume it's the end of the
475          * config file.
476          */
477         if ( bytes <= 0 ) {
478             err = errno;
479             break;
480         }
481
482         temp_size -= bytes;
483         offset += bytes;
484         data_bytes += bytes;
485     }
486     
487     if ( bytes_written != NULL ) {
488         *bytes_written = size - temp_size;
489     }
490
491     close( fd );
492     return err;
493 }
494
495 static int
496 pci_device_linux_sysfs_map_range_wc(struct pci_device *dev,
497                                     struct pci_device_mapping *map)
498 {
499     char name[256];
500     int fd;
501     const int prot = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
502         ? (PROT_READ | PROT_WRITE) : PROT_READ;
503     const int open_flags = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
504         ? O_RDWR : O_RDONLY;
505     const off_t offset = map->base - dev->regions[map->region].base_addr;
506
507     snprintf(name, 255, "%s/%04x:%02x:%02x.%1u/resource%u_wc",
508              SYS_BUS_PCI,
509              dev->domain,
510              dev->bus,
511              dev->dev,
512              dev->func,
513              map->region);
514     fd = open(name, open_flags);
515     if (fd == -1)
516             return errno;
517
518     map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
519     if (map->memory == MAP_FAILED) {
520         map->memory = NULL;
521         close(fd);
522         return errno;
523     }
524
525     close(fd);
526
527     return 0;
528 }
529
530 /**
531  * Map a memory region for a device using the Linux sysfs interface.
532  * 
533  * \param dev   Device whose memory region is to be mapped.
534  * \param map   Parameters of the mapping that is to be created.
535  * 
536  * \return
537  * Zero on success or an \c errno value on failure.
538  *
539  * \sa pci_device_map_rrange, pci_device_linux_sysfs_unmap_range
540  *
541  * \todo
542  * Some older 2.6.x kernels don't implement the resourceN files.  On those
543  * systems /dev/mem must be used.  On these systems it is also possible that
544  * \c mmap64 may need to be used.
545  */
546 static int
547 pci_device_linux_sysfs_map_range(struct pci_device *dev,
548                                  struct pci_device_mapping *map)
549 {
550     char name[256];
551     int fd;
552     int err = 0;
553     const int prot = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
554         ? (PROT_READ | PROT_WRITE) : PROT_READ;
555     const int open_flags = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0) 
556         ? O_RDWR : O_RDONLY;
557     const off_t offset = map->base - dev->regions[map->region].base_addr;
558 #ifdef HAVE_MTRR
559     struct mtrr_sentry sentry = {
560         .base = map->base,
561         .size = map->size,
562         .type = MTRR_TYPE_UNCACHABLE
563     };
564 #endif
565
566     /* For WC mappings, try sysfs resourceN_wc file first */
567     if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) &&
568         !pci_device_linux_sysfs_map_range_wc(dev, map))
569             return 0;
570
571     snprintf(name, 255, "%s/%04x:%02x:%02x.%1u/resource%u",
572              SYS_BUS_PCI,
573              dev->domain,
574              dev->bus,
575              dev->dev,
576              dev->func,
577              map->region);
578
579     fd = open(name, open_flags);
580     if (fd == -1) {
581         return errno;
582     }
583
584
585     map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
586     if (map->memory == MAP_FAILED) {
587         map->memory = NULL;
588         close(fd);
589         return errno;
590     }
591
592 #ifdef HAVE_MTRR
593     if ((map->flags & PCI_DEV_MAP_FLAG_CACHABLE) != 0) {
594         sentry.type = MTRR_TYPE_WRBACK;
595     } else if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) != 0) {
596         sentry.type = MTRR_TYPE_WRCOMB;
597     }
598
599     if (pci_sys->mtrr_fd != -1 && sentry.type != MTRR_TYPE_UNCACHABLE) {
600         if (ioctl(pci_sys->mtrr_fd, MTRRIOC_ADD_ENTRY, &sentry) < 0) {
601             /* FIXME: Should we report an error in this case?
602              */
603             fprintf(stderr, "error setting MTRR "
604                     "(base = 0x%08lx, size = 0x%08x, type = %u) %s (%d)\n",
605                     sentry.base, sentry.size, sentry.type,
606                     strerror(errno), errno);
607 /*            err = errno;*/
608         }
609         /* KLUDGE ALERT -- rewrite the PTEs to turn off the CD and WT bits */
610         mprotect (map->memory, map->size, PROT_NONE);
611         err = mprotect (map->memory, map->size, PROT_READ|PROT_WRITE);
612
613         if (err != 0) {
614             fprintf(stderr, "mprotect(PROT_READ | PROT_WRITE) failed: %s\n",
615                     strerror(errno));
616             fprintf(stderr, "remapping without mprotect performance kludge.\n");
617
618             munmap(map->memory, map->size);
619             map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
620             if (map->memory == MAP_FAILED) {
621                 map->memory = NULL;
622                 close(fd);
623                 return errno;
624             }
625         }
626     }
627 #endif
628
629     close(fd);
630
631     return 0;
632 }
633
634 /**
635  * Unmap a memory region for a device using the Linux sysfs interface.
636  * 
637  * \param dev   Device whose memory region is to be unmapped.
638  * \param map   Parameters of the mapping that is to be destroyed.
639  * 
640  * \return
641  * Zero on success or an \c errno value on failure.
642  *
643  * \sa pci_device_map_rrange, pci_device_linux_sysfs_map_range
644  *
645  * \todo
646  * Some older 2.6.x kernels don't implement the resourceN files.  On those
647  * systems /dev/mem must be used.  On these systems it is also possible that
648  * \c mmap64 may need to be used.
649  */
650 static int
651 pci_device_linux_sysfs_unmap_range(struct pci_device *dev,
652                                    struct pci_device_mapping *map)
653 {
654     int err = 0;
655 #ifdef HAVE_MTRR
656     struct mtrr_sentry sentry = {
657         .base = map->base,
658         .size = map->size,
659         .type = MTRR_TYPE_UNCACHABLE
660     };
661 #endif
662
663     err = pci_device_generic_unmap_range (dev, map);
664     if (err)
665         return err;
666     
667 #ifdef HAVE_MTRR
668     if ((map->flags & PCI_DEV_MAP_FLAG_CACHABLE) != 0) {
669         sentry.type = MTRR_TYPE_WRBACK;
670     } else if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) != 0) {
671         sentry.type = MTRR_TYPE_WRCOMB;
672     }
673
674     if (pci_sys->mtrr_fd != -1 && sentry.type != MTRR_TYPE_UNCACHABLE) {
675         if (ioctl(pci_sys->mtrr_fd, MTRRIOC_DEL_ENTRY, &sentry) < 0) {
676             /* FIXME: Should we report an error in this case?
677              */
678             fprintf(stderr, "error setting MTRR "
679                     "(base = 0x%08lx, size = 0x%08x, type = %u) %s (%d)\n",
680                     sentry.base, sentry.size, sentry.type,
681                     strerror(errno), errno);
682 /*            err = errno;*/
683         }
684     }
685 #endif
686
687     return err;
688 }
689
690 static void pci_device_linux_sysfs_enable(struct pci_device *dev)
691 {
692     char name[256];
693     int fd;
694
695     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/enable",
696               SYS_BUS_PCI,
697               dev->domain,
698               dev->bus,
699               dev->dev,
700               dev->func );
701     
702     fd = open( name, O_RDWR );
703     if (fd == -1)
704        return;
705
706     write( fd, "1", 1 );
707     close(fd);
708 }
709
710 static int pci_device_linux_sysfs_boot_vga(struct pci_device *dev)
711 {
712     char name[256];
713     char reply[3];
714     int fd, bytes_read;
715     int ret = 0;
716
717     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/boot_vga",
718               SYS_BUS_PCI,
719               dev->domain,
720               dev->bus,
721               dev->dev,
722               dev->func );
723     
724     fd = open( name, O_RDONLY );
725     if (fd == -1)
726        return 0;
727
728     bytes_read = read(fd, reply, 1);
729     if (bytes_read != 1)
730         goto out;
731     if (reply[0] == '1')
732         ret = 1;
733 out:
734     close(fd);
735     return ret;
736 }