Revert "Package version up to 0.13.3"
[platform/upstream/libpciaccess.git] / src / linux_sysfs.c
1 /*
2  * (C) Copyright IBM Corporation 2006
3  * All Rights Reserved.
4  * Copyright 2012 Red Hat, Inc.
5  *
6  * Permission is hereby granted, free of charge, to any person obtaining a
7  * copy of this software and associated documentation files (the "Software"),
8  * to deal in the Software without restriction, including without limitation
9  * on the rights to use, copy, modify, merge, publish, distribute, sub
10  * license, and/or sell copies of the Software, and to permit persons to whom
11  * the Software is furnished to do so, subject to the following conditions:
12  *
13  * The above copyright notice and this permission notice (including the next
14  * paragraph) shall be included in all copies or substantial portions of the
15  * Software.
16  *
17  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19  * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
20  * IBM AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
22  * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
23  * DEALINGS IN THE SOFTWARE.
24  */
25
26 /**
27  * \file linux_sysfs.c
28  * Access PCI subsystem using Linux's sysfs interface.  This interface is
29  * available starting somewhere in the late 2.5.x kernel phase, and is the
30  * preferred method on all 2.6.x kernels.
31  *
32  * \author Ian Romanick <idr@us.ibm.com>
33  */
34
35 #define _GNU_SOURCE
36
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stdio.h>
40 #include <unistd.h>
41 #include <sys/types.h>
42 #include <sys/stat.h>
43 #include <fcntl.h>
44 #include <sys/mman.h>
45 #include <dirent.h>
46 #include <errno.h>
47
48 #if defined(__i386__) || defined(__x86_64__)
49 #include <sys/io.h>
50 #else
51 #define inb(x) -1
52 #define inw(x) -1
53 #define inl(x) -1
54 #define outb(x,y) do {} while (0)
55 #define outw(x,y) do {} while (0)
56 #define outl(x,y) do {} while (0)
57 #define iopl(x) -1
58 #endif
59
60 #include "config.h"
61
62 #ifdef HAVE_MTRR
63 #include <asm/mtrr.h>
64 #include <sys/ioctl.h>
65 #endif
66
67 #include "pciaccess.h"
68 #include "pciaccess_private.h"
69 #include "linux_devmem.h"
70
71 static const struct pci_system_methods linux_sysfs_methods;
72
73 #define SYS_BUS_PCI "/sys/bus/pci/devices"
74
75 static int
76 pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
77                              pciaddr_t offset, pciaddr_t size,
78                              pciaddr_t * bytes_read );
79
80 static int populate_entries(struct pci_system * pci_sys);
81
82 /**
83  * Attempt to access PCI subsystem using Linux's sysfs interface.
84  */
85 _pci_hidden int
86 pci_system_linux_sysfs_create( void )
87 {
88     int err = 0;
89     struct stat st;
90
91
92     /* If the directory "/sys/bus/pci/devices" exists, then the PCI subsystem
93      * can be accessed using this interface.
94      */
95
96     if ( stat( SYS_BUS_PCI, & st ) == 0 ) {
97         pci_sys = calloc( 1, sizeof( struct pci_system ) );
98         if ( pci_sys != NULL ) {
99             pci_sys->methods = & linux_sysfs_methods;
100 #ifdef HAVE_MTRR
101             pci_sys->mtrr_fd = open("/proc/mtrr", O_WRONLY | O_CLOEXEC);
102 #endif
103             err = populate_entries(pci_sys);
104         }
105         else {
106             err = ENOMEM;
107         }
108     }
109     else {
110         err = errno;
111     }
112
113     return err;
114 }
115
116
117 /**
118  * Filter out the names "." and ".." from the scanned sysfs entries.
119  *
120  * \param d  Directory entry being processed by \c scandir.
121  *
122  * \return
123  * Zero if the entry name matches either "." or "..", non-zero otherwise.
124  *
125  * \sa scandir, populate_entries
126  */
127 static int
128 scan_sys_pci_filter( const struct dirent * d )
129 {
130     return !((strcmp( d->d_name, "." ) == 0)
131              || (strcmp( d->d_name, ".." ) == 0));
132 }
133
134
135 int
136 populate_entries( struct pci_system * p )
137 {
138     struct dirent ** devices = NULL;
139     int n;
140     int i;
141     int err = 0;
142
143
144     n = scandir( SYS_BUS_PCI, & devices, scan_sys_pci_filter, alphasort );
145     if ( n > 0 ) {
146         p->num_devices = n;
147         p->devices = calloc( n, sizeof( struct pci_device_private ) );
148
149         if (p->devices != NULL) {
150             for (i = 0 ; i < n ; i++) {
151                 uint8_t config[48];
152                 pciaddr_t bytes;
153                 unsigned dom, bus, dev, func;
154                 struct pci_device_private *device =
155                         (struct pci_device_private *) &p->devices[i];
156
157
158                 sscanf(devices[i]->d_name, "%04x:%02x:%02x.%1u",
159                        & dom, & bus, & dev, & func);
160
161                 device->base.domain = dom;
162                 device->base.bus = bus;
163                 device->base.dev = dev;
164                 device->base.func = func;
165
166
167                 err = pci_device_linux_sysfs_read(& device->base, config, 0,
168                                                   48, & bytes);
169                 if ((bytes == 48) && !err) {
170                     device->base.vendor_id = (uint16_t)config[0]
171                         + ((uint16_t)config[1] << 8);
172                     device->base.device_id = (uint16_t)config[2]
173                         + ((uint16_t)config[3] << 8);
174                     device->base.device_class = (uint32_t)config[9]
175                         + ((uint32_t)config[10] << 8)
176                         + ((uint32_t)config[11] << 16);
177                     device->base.revision = config[8];
178                     device->base.subvendor_id = (uint16_t)config[44]
179                         + ((uint16_t)config[45] << 8);
180                     device->base.subdevice_id = (uint16_t)config[46]
181                         + ((uint16_t)config[47] << 8);
182                 }
183
184                 if (err) {
185                     break;
186                 }
187             }
188         }
189         else {
190             err = ENOMEM;
191         }
192     }
193
194     for (i = 0; i < n; i++)
195         free(devices[i]);
196     free(devices);
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 | O_CLOEXEC);
249         if ( fd != -1 ) {
250             int ret;
251             char * next;
252             pciaddr_t  low_addr;
253             pciaddr_t  high_addr;
254             pciaddr_t  flags;
255
256
257             ret = read( fd, resource, 512 );
258             resource[511] = '\0';
259
260             close( fd );
261
262             next = resource;
263             for ( i = 0 ; i < 6 ; i++ ) {
264
265                 dev->regions[i].base_addr = strtoull( next, & next, 16 );
266                 high_addr = strtoull( next, & next, 16 );
267                 flags = strtoull( next, & next, 16 );
268
269                 if ( dev->regions[i].base_addr != 0 ) {
270                     dev->regions[i].size = (high_addr
271                                             - dev->regions[i].base_addr) + 1;
272
273                     dev->regions[i].is_IO = (flags & 0x01);
274                     dev->regions[i].is_64 = (flags & 0x04);
275                     dev->regions[i].is_prefetchable = (flags & 0x08);
276                 }
277             }
278
279             low_addr = strtoull( next, & next, 16 );
280             high_addr = strtoull( next, & next, 16 );
281             flags = strtoull( next, & next, 16 );
282             if ( low_addr != 0 ) {
283                 priv->rom_base = low_addr;
284                 dev->rom_size = (high_addr - low_addr) + 1;
285             }
286         }
287     }
288
289     return err;
290 }
291
292
293 static int
294 pci_device_linux_sysfs_read_rom( struct pci_device * dev, void * buffer )
295 {
296     char name[256];
297     int fd;
298     struct stat  st;
299     int err = 0;
300     size_t rom_size;
301     size_t total_bytes;
302
303
304     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/rom",
305               SYS_BUS_PCI,
306               dev->domain,
307               dev->bus,
308               dev->dev,
309               dev->func );
310
311     fd = open( name, O_RDWR | O_CLOEXEC);
312     if ( fd == -1 ) {
313 #ifdef LINUX_ROM
314         /* If reading the ROM using sysfs fails, fall back to the old
315          * /dev/mem based interface.
316          * disable this for newer kernels using configure
317          */
318         return pci_device_linux_devmem_read_rom(dev, buffer);
319 #else
320         return errno;
321 #endif
322     }
323
324
325     if ( fstat( fd, & st ) == -1 ) {
326         close( fd );
327         return errno;
328     }
329
330     rom_size = st.st_size;
331     if ( rom_size == 0 )
332         rom_size = 0x10000;
333
334     /* This is a quirky thing on Linux.  Even though the ROM and the file
335      * for the ROM in sysfs are read-only, the string "1" must be written to
336      * the file to enable the ROM.  After the data has been read, "0" must be
337      * written to the file to disable the ROM.
338      */
339     write( fd, "1", 1 );
340     lseek( fd, 0, SEEK_SET );
341
342     for ( total_bytes = 0 ; total_bytes < rom_size ; /* empty */ ) {
343         const int bytes = read( fd, (char *) buffer + total_bytes,
344                                 rom_size - total_bytes );
345         if ( bytes == -1 ) {
346             err = errno;
347             break;
348         }
349         else if ( bytes == 0 ) {
350             break;
351         }
352
353         total_bytes += bytes;
354     }
355
356
357     lseek( fd, 0, SEEK_SET );
358     write( fd, "0", 1 );
359
360     close( fd );
361     return err;
362 }
363
364
365 static int
366 pci_device_linux_sysfs_read( struct pci_device * dev, void * data,
367                              pciaddr_t offset, pciaddr_t size,
368                              pciaddr_t * bytes_read )
369 {
370     char name[256];
371     pciaddr_t temp_size = size;
372     int err = 0;
373     int fd;
374     char *data_bytes = data;
375
376     if ( bytes_read != NULL ) {
377         *bytes_read = 0;
378     }
379
380     /* Each device has a directory under sysfs.  Within that directory there
381      * is a file named "config".  This file used to access the PCI config
382      * space.  It is used here to obtain most of the information about the
383      * device.
384      */
385     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
386               SYS_BUS_PCI,
387               dev->domain,
388               dev->bus,
389               dev->dev,
390               dev->func );
391
392     fd = open( name, O_RDONLY | O_CLOEXEC);
393     if ( fd == -1 ) {
394         return errno;
395     }
396
397
398     while ( temp_size > 0 ) {
399         const ssize_t bytes = pread64( fd, data_bytes, temp_size, offset );
400
401         /* If zero bytes were read, then we assume it's the end of the
402          * config file.
403          */
404         if (bytes == 0)
405             break;
406         if ( bytes < 0 ) {
407             err = errno;
408             break;
409         }
410
411         temp_size -= bytes;
412         offset += bytes;
413         data_bytes += bytes;
414     }
415
416     if ( bytes_read != NULL ) {
417         *bytes_read = size - temp_size;
418     }
419
420     close( fd );
421     return err;
422 }
423
424
425 static int
426 pci_device_linux_sysfs_write( struct pci_device * dev, const void * data,
427                              pciaddr_t offset, pciaddr_t size,
428                              pciaddr_t * bytes_written )
429 {
430     char name[256];
431     pciaddr_t temp_size = size;
432     int err = 0;
433     int fd;
434     const char *data_bytes = data;
435
436     if ( bytes_written != NULL ) {
437         *bytes_written = 0;
438     }
439
440     /* Each device has a directory under sysfs.  Within that directory there
441      * is a file named "config".  This file used to access the PCI config
442      * space.  It is used here to obtain most of the information about the
443      * device.
444      */
445     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/config",
446               SYS_BUS_PCI,
447               dev->domain,
448               dev->bus,
449               dev->dev,
450               dev->func );
451
452     fd = open( name, O_WRONLY | O_CLOEXEC);
453     if ( fd == -1 ) {
454         return errno;
455     }
456
457
458     while ( temp_size > 0 ) {
459         const ssize_t bytes = pwrite64( fd, data_bytes, temp_size, offset );
460
461         /* If zero bytes were written, then we assume it's the end of the
462          * config file.
463          */
464         if ( bytes == 0 )
465             break;
466         if ( bytes < 0 ) {
467             err = errno;
468             break;
469         }
470
471         temp_size -= bytes;
472         offset += bytes;
473         data_bytes += bytes;
474     }
475
476     if ( bytes_written != NULL ) {
477         *bytes_written = size - temp_size;
478     }
479
480     close( fd );
481     return err;
482 }
483
484 static int
485 pci_device_linux_sysfs_map_range_wc(struct pci_device *dev,
486                                     struct pci_device_mapping *map)
487 {
488     char name[256];
489     int fd;
490     const int prot = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0)
491         ? (PROT_READ | PROT_WRITE) : PROT_READ;
492     const int open_flags = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0)
493         ? O_RDWR : O_RDONLY;
494     const off_t offset = map->base - dev->regions[map->region].base_addr;
495
496     snprintf(name, 255, "%s/%04x:%02x:%02x.%1u/resource%u_wc",
497              SYS_BUS_PCI,
498              dev->domain,
499              dev->bus,
500              dev->dev,
501              dev->func,
502              map->region);
503     fd = open(name, open_flags | O_CLOEXEC);
504     if (fd == -1)
505             return errno;
506
507     map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
508     if (map->memory == MAP_FAILED) {
509         map->memory = NULL;
510         close(fd);
511         return errno;
512     }
513
514     close(fd);
515
516     return 0;
517 }
518
519 /**
520  * Map a memory region for a device using the Linux sysfs interface.
521  *
522  * \param dev   Device whose memory region is to be mapped.
523  * \param map   Parameters of the mapping that is to be created.
524  *
525  * \return
526  * Zero on success or an \c errno value on failure.
527  *
528  * \sa pci_device_map_rrange, pci_device_linux_sysfs_unmap_range
529  *
530  * \todo
531  * Some older 2.6.x kernels don't implement the resourceN files.  On those
532  * systems /dev/mem must be used.  On these systems it is also possible that
533  * \c mmap64 may need to be used.
534  */
535 static int
536 pci_device_linux_sysfs_map_range(struct pci_device *dev,
537                                  struct pci_device_mapping *map)
538 {
539     char name[256];
540     int fd;
541     int err = 0;
542     const int prot = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0)
543         ? (PROT_READ | PROT_WRITE) : PROT_READ;
544     const int open_flags = ((map->flags & PCI_DEV_MAP_FLAG_WRITABLE) != 0)
545         ? O_RDWR : O_RDONLY;
546     const off_t offset = map->base - dev->regions[map->region].base_addr;
547 #ifdef HAVE_MTRR
548     struct mtrr_sentry sentry = {
549         .base = map->base,
550         .size = map->size,
551         .type = MTRR_TYPE_UNCACHABLE
552     };
553 #endif
554
555     /* For WC mappings, try sysfs resourceN_wc file first */
556     if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) &&
557         !pci_device_linux_sysfs_map_range_wc(dev, map))
558             return 0;
559
560     snprintf(name, 255, "%s/%04x:%02x:%02x.%1u/resource%u",
561              SYS_BUS_PCI,
562              dev->domain,
563              dev->bus,
564              dev->dev,
565              dev->func,
566              map->region);
567
568     fd = open(name, open_flags | O_CLOEXEC);
569     if (fd == -1) {
570         return errno;
571     }
572
573
574     map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
575     if (map->memory == MAP_FAILED) {
576         map->memory = NULL;
577         close(fd);
578         return errno;
579     }
580
581 #ifdef HAVE_MTRR
582     if ((map->flags & PCI_DEV_MAP_FLAG_CACHABLE) != 0) {
583         sentry.type = MTRR_TYPE_WRBACK;
584     } else if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) != 0) {
585         sentry.type = MTRR_TYPE_WRCOMB;
586     }
587
588     if (pci_sys->mtrr_fd != -1 && sentry.type != MTRR_TYPE_UNCACHABLE) {
589         if (ioctl(pci_sys->mtrr_fd, MTRRIOC_ADD_ENTRY, &sentry) < 0) {
590             /* FIXME: Should we report an error in this case?
591              */
592             fprintf(stderr, "error setting MTRR "
593                     "(base = 0x%08lx, size = 0x%08x, type = %u) %s (%d)\n",
594                     sentry.base, sentry.size, sentry.type,
595                     strerror(errno), errno);
596 /*            err = errno;*/
597         }
598         /* KLUDGE ALERT -- rewrite the PTEs to turn off the CD and WT bits */
599         mprotect (map->memory, map->size, PROT_NONE);
600         err = mprotect (map->memory, map->size, PROT_READ|PROT_WRITE);
601
602         if (err != 0) {
603             fprintf(stderr, "mprotect(PROT_READ | PROT_WRITE) failed: %s\n",
604                     strerror(errno));
605             fprintf(stderr, "remapping without mprotect performance kludge.\n");
606
607             munmap(map->memory, map->size);
608             map->memory = mmap(NULL, map->size, prot, MAP_SHARED, fd, offset);
609             if (map->memory == MAP_FAILED) {
610                 map->memory = NULL;
611                 close(fd);
612                 return errno;
613             }
614         }
615     }
616 #endif
617
618     close(fd);
619
620     return 0;
621 }
622
623 /**
624  * Unmap a memory region for a device using the Linux sysfs interface.
625  *
626  * \param dev   Device whose memory region is to be unmapped.
627  * \param map   Parameters of the mapping that is to be destroyed.
628  *
629  * \return
630  * Zero on success or an \c errno value on failure.
631  *
632  * \sa pci_device_map_rrange, pci_device_linux_sysfs_map_range
633  *
634  * \todo
635  * Some older 2.6.x kernels don't implement the resourceN files.  On those
636  * systems /dev/mem must be used.  On these systems it is also possible that
637  * \c mmap64 may need to be used.
638  */
639 static int
640 pci_device_linux_sysfs_unmap_range(struct pci_device *dev,
641                                    struct pci_device_mapping *map)
642 {
643     int err = 0;
644 #ifdef HAVE_MTRR
645     struct mtrr_sentry sentry = {
646         .base = map->base,
647         .size = map->size,
648         .type = MTRR_TYPE_UNCACHABLE
649     };
650 #endif
651
652     err = pci_device_generic_unmap_range (dev, map);
653     if (err)
654         return err;
655
656 #ifdef HAVE_MTRR
657     if ((map->flags & PCI_DEV_MAP_FLAG_CACHABLE) != 0) {
658         sentry.type = MTRR_TYPE_WRBACK;
659     } else if ((map->flags & PCI_DEV_MAP_FLAG_WRITE_COMBINE) != 0) {
660         sentry.type = MTRR_TYPE_WRCOMB;
661     }
662
663     if (pci_sys->mtrr_fd != -1 && sentry.type != MTRR_TYPE_UNCACHABLE) {
664         if (ioctl(pci_sys->mtrr_fd, MTRRIOC_DEL_ENTRY, &sentry) < 0) {
665             /* FIXME: Should we report an error in this case?
666              */
667             fprintf(stderr, "error setting MTRR "
668                     "(base = 0x%08lx, size = 0x%08x, type = %u) %s (%d)\n",
669                     sentry.base, sentry.size, sentry.type,
670                     strerror(errno), errno);
671 /*            err = errno;*/
672         }
673     }
674 #endif
675
676     return err;
677 }
678
679 static void pci_device_linux_sysfs_enable(struct pci_device *dev)
680 {
681     char name[256];
682     int fd;
683
684     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/enable",
685               SYS_BUS_PCI,
686               dev->domain,
687               dev->bus,
688               dev->dev,
689               dev->func );
690
691     fd = open( name, O_RDWR | O_CLOEXEC);
692     if (fd == -1)
693        return;
694
695     write( fd, "1", 1 );
696     close(fd);
697 }
698
699 static int pci_device_linux_sysfs_boot_vga(struct pci_device *dev)
700 {
701     char name[256];
702     char reply[3];
703     int fd, bytes_read;
704     int ret = 0;
705
706     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/boot_vga",
707               SYS_BUS_PCI,
708               dev->domain,
709               dev->bus,
710               dev->dev,
711               dev->func );
712
713     fd = open( name, O_RDONLY | O_CLOEXEC);
714     if (fd == -1)
715        return 0;
716
717     bytes_read = read(fd, reply, 1);
718     if (bytes_read != 1)
719         goto out;
720     if (reply[0] == '1')
721         ret = 1;
722 out:
723     close(fd);
724     return ret;
725 }
726
727 static int pci_device_linux_sysfs_has_kernel_driver(struct pci_device *dev)
728 {
729     char name[256];
730     struct stat dummy;
731     int ret;
732
733     snprintf( name, 255, "%s/%04x:%02x:%02x.%1u/driver",
734               SYS_BUS_PCI,
735               dev->domain,
736               dev->bus,
737               dev->dev,
738               dev->func );
739
740     ret = stat(name, &dummy);
741     if (ret < 0)
742         return 0;
743     return 1;
744 }
745
746 static struct pci_io_handle *
747 pci_device_linux_sysfs_open_device_io(struct pci_io_handle *ret,
748                                       struct pci_device *dev, int bar,
749                                       pciaddr_t base, pciaddr_t size)
750 {
751     char name[PATH_MAX];
752
753     snprintf(name, PATH_MAX, "%s/%04x:%02x:%02x.%1u/resource%d",
754              SYS_BUS_PCI, dev->domain, dev->bus, dev->dev, dev->func, bar);
755
756     ret->fd = open(name, O_RDWR | O_CLOEXEC);
757
758     if (ret->fd < 0)
759         return NULL;
760
761     ret->base = base;
762     ret->size = size;
763
764     return ret;
765 }
766
767 static struct pci_io_handle *
768 pci_device_linux_sysfs_open_legacy_io(struct pci_io_handle *ret,
769                                       struct pci_device *dev, pciaddr_t base,
770                                       pciaddr_t size)
771 {
772     char name[PATH_MAX];
773
774     /* First check if there's a legacy io method for the device */
775     while (dev) {
776         snprintf(name, PATH_MAX, "/sys/class/pci_bus/%04x:%02x/legacy_io",
777                  dev->domain, dev->bus);
778
779         ret->fd = open(name, O_RDWR | O_CLOEXEC);
780         if (ret->fd >= 0)
781             break;
782
783         dev = pci_device_get_parent_bridge(dev);
784     }
785
786     /*
787      * You would think you'd want to use /dev/port here.  Don't make that
788      * mistake, /dev/port only does byte-wide i/o cycles which means it
789      * doesn't work.  If you think this is stupid, well, you're right.
790      */
791
792     /* If we've no other choice, iopl */
793     if (ret->fd < 0) {
794         if (iopl(3))
795             return NULL;
796     }
797
798     ret->base = base;
799     ret->size = size;
800
801     return ret;
802 }
803
804 static void
805 pci_device_linux_sysfs_close_io(struct pci_device *dev,
806                                 struct pci_io_handle *handle)
807 {
808     if (handle->fd > -1)
809         close(handle->fd);
810 }
811
812 static uint32_t
813 pci_device_linux_sysfs_read32(struct pci_io_handle *handle, uint32_t port)
814 {
815     uint32_t ret;
816
817     if (handle->fd > -1)
818         pread(handle->fd, &ret, 4, port + handle->base);
819     else
820         ret = inl(port + handle->base);
821         
822     return ret;
823 }
824
825 static uint16_t
826 pci_device_linux_sysfs_read16(struct pci_io_handle *handle, uint32_t port)
827 {
828     uint16_t ret;
829
830     if (handle->fd > -1)
831         pread(handle->fd, &ret, 2, port + handle->base);
832     else
833         ret = inw(port + handle->base);
834
835     return ret;
836 }
837
838 static uint8_t
839 pci_device_linux_sysfs_read8(struct pci_io_handle *handle, uint32_t port)
840 {
841     uint8_t ret;
842
843     if (handle->fd > -1)
844         pread(handle->fd, &ret, 1, port + handle->base);
845     else
846         ret = inb(port + handle->base);
847
848     return ret;
849 }
850
851 static void
852 pci_device_linux_sysfs_write32(struct pci_io_handle *handle, uint32_t port,
853                                uint32_t data)
854 {
855     if (handle->fd > -1)
856         pwrite(handle->fd, &data, 4, port + handle->base);
857     else
858         outl(data, port + handle->base);
859 }
860
861 static void
862 pci_device_linux_sysfs_write16(struct pci_io_handle *handle, uint32_t port,
863                                uint16_t data)
864 {
865     if (handle->fd > -1)
866         pwrite(handle->fd, &data, 2, port + handle->base);
867     else
868         outw(data, port + handle->base);
869 }
870
871 static void
872 pci_device_linux_sysfs_write8(struct pci_io_handle *handle, uint32_t port,
873                               uint8_t data)
874 {
875     if (handle->fd > -1)
876         pwrite(handle->fd, &data, 1, port + handle->base);
877     else
878         outb(data, port + handle->base);
879 }
880
881 static int
882 pci_device_linux_sysfs_map_legacy(struct pci_device *dev, pciaddr_t base,
883                                   pciaddr_t size, unsigned map_flags, void **addr)
884 {
885     char name[PATH_MAX];
886     int flags = O_RDONLY;
887     int prot = PROT_READ;
888     int fd;
889     int ret=0;
890
891     if (map_flags & PCI_DEV_MAP_FLAG_WRITABLE) {
892         flags = O_RDWR; /* O_RDWR != O_WRONLY | O_RDONLY */;
893         prot |= PROT_WRITE;
894     }
895
896     /* First check if there's a legacy memory method for the device */
897     while (dev) {
898         snprintf(name, PATH_MAX, "/sys/class/pci_bus/%04x:%02x/legacy_mem",
899                  dev->domain, dev->bus);
900
901         fd = open(name, flags | O_CLOEXEC);
902         if (fd >= 0)
903             break;
904
905         dev = pci_device_get_parent_bridge(dev);
906     }
907
908     /* If not, /dev/mem is the best we can do */
909     if (!dev)
910         fd = open("/dev/mem", flags | O_CLOEXEC);
911
912     if (fd < 0)
913         return errno;
914
915     *addr = mmap(NULL, size, prot, MAP_SHARED, fd, base);
916     if (*addr == MAP_FAILED) {
917         ret = errno;
918     }
919
920     close(fd);
921     return ret;
922 }
923
924 static int
925 pci_device_linux_sysfs_unmap_legacy(struct pci_device *dev, void *addr, pciaddr_t size)
926 {
927     return munmap(addr, size);
928 }
929
930
931 static void
932 pci_system_linux_destroy(void)
933 {
934 #ifdef HAVE_MTRR
935         if (pci_sys->mtrr_fd != -1)
936                 close(pci_sys->mtrr_fd);
937 #endif
938 }
939
940 static const struct pci_system_methods linux_sysfs_methods = {
941     .destroy = pci_system_linux_destroy,
942     .destroy_device = NULL,
943     .read_rom = pci_device_linux_sysfs_read_rom,
944     .probe = pci_device_linux_sysfs_probe,
945     .map_range = pci_device_linux_sysfs_map_range,
946     .unmap_range = pci_device_linux_sysfs_unmap_range,
947
948     .read = pci_device_linux_sysfs_read,
949     .write = pci_device_linux_sysfs_write,
950
951     .fill_capabilities = pci_fill_capabilities_generic,
952     .enable = pci_device_linux_sysfs_enable,
953     .boot_vga = pci_device_linux_sysfs_boot_vga,
954     .has_kernel_driver = pci_device_linux_sysfs_has_kernel_driver,
955
956     .open_device_io = pci_device_linux_sysfs_open_device_io,
957     .open_legacy_io = pci_device_linux_sysfs_open_legacy_io,
958     .close_io = pci_device_linux_sysfs_close_io,
959     .read32 = pci_device_linux_sysfs_read32,
960     .read16 = pci_device_linux_sysfs_read16,
961     .read8 = pci_device_linux_sysfs_read8,
962     .write32 = pci_device_linux_sysfs_write32,
963     .write16 = pci_device_linux_sysfs_write16,
964     .write8 = pci_device_linux_sysfs_write8,
965
966     .map_legacy = pci_device_linux_sysfs_map_legacy,
967     .unmap_legacy = pci_device_linux_sysfs_unmap_legacy,
968 };