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