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