]> mj.ucw.cz Git - pciutils.git/blob - lib/sysfs.c
CXL3.0: Add DVSEC CXLCtrl3 and missing CXLCtl2
[pciutils.git] / lib / sysfs.c
1 /*
2  *      The PCI Library -- Configuration Access via /sys/bus/pci
3  *
4  *      Copyright (c) 2003 Matthew Wilcox <matthew@wil.cx>
5  *      Copyright (c) 1997--2008 Martin Mares <mj@ucw.cz>
6  *
7  *      Can be freely distributed and used under the terms of the GNU GPL.
8  */
9
10 #define _GNU_SOURCE
11
12 #include <stdio.h>
13 #include <stdlib.h>
14 #include <string.h>
15 #include <stdarg.h>
16 #include <unistd.h>
17 #include <errno.h>
18 #include <dirent.h>
19 #include <fcntl.h>
20 #include <sys/types.h>
21
22 #include "internal.h"
23 #include "pread.h"
24
25 static void
26 sysfs_config(struct pci_access *a)
27 {
28   pci_define_param(a, "sysfs.path", PCI_PATH_SYS_BUS_PCI, "Path to the sysfs device tree");
29 }
30
31 static inline char *
32 sysfs_name(struct pci_access *a)
33 {
34   return pci_get_param(a, "sysfs.path");
35 }
36
37 static int
38 sysfs_detect(struct pci_access *a)
39 {
40   if (access(sysfs_name(a), R_OK))
41     {
42       a->debug("...cannot open %s", sysfs_name(a));
43       return 0;
44     }
45   a->debug("...using %s", sysfs_name(a));
46   return 1;
47 }
48
49 static void
50 sysfs_init(struct pci_access *a)
51 {
52   a->fd = -1;
53   a->fd_vpd = -1;
54 }
55
56 static void
57 sysfs_flush_cache(struct pci_access *a)
58 {
59   if (a->fd >= 0)
60     {
61       close(a->fd);
62       a->fd = -1;
63     }
64   if (a->fd_vpd >= 0)
65     {
66       close(a->fd_vpd);
67       a->fd_vpd = -1;
68     }
69   a->cached_dev = NULL;
70 }
71
72 static void
73 sysfs_cleanup(struct pci_access *a)
74 {
75   sysfs_flush_cache(a);
76 }
77
78 #define OBJNAMELEN 1024
79 static void
80 sysfs_obj_name(struct pci_dev *d, char *object, char *buf)
81 {
82   int n = snprintf(buf, OBJNAMELEN, "%s/devices/%04x:%02x:%02x.%d/%s",
83                    sysfs_name(d->access), d->domain, d->bus, d->dev, d->func, object);
84   if (n < 0 || n >= OBJNAMELEN)
85     d->access->error("File name too long");
86 }
87
88 #define OBJBUFSIZE 1024
89
90 static int
91 sysfs_get_string(struct pci_dev *d, char *object, char *buf, int mandatory)
92 {
93   struct pci_access *a = d->access;
94   int fd, n;
95   char namebuf[OBJNAMELEN];
96   void (*warn)(char *msg, ...) = (mandatory ? a->error : a->warning);
97
98   sysfs_obj_name(d, object, namebuf);
99   fd = open(namebuf, O_RDONLY);
100   if (fd < 0)
101     {
102       if (mandatory || errno != ENOENT)
103         warn("Cannot open %s: %s", namebuf, strerror(errno));
104       return 0;
105     }
106   n = read(fd, buf, OBJBUFSIZE);
107   close(fd);
108   if (n < 0)
109     {
110       warn("Error reading %s: %s", namebuf, strerror(errno));
111       return 0;
112      }
113   if (n >= OBJBUFSIZE)
114     {
115       warn("Value in %s too long", namebuf);
116       return 0;
117     }
118   buf[n] = 0;
119   return 1;
120 }
121
122 static char *
123 sysfs_deref_link(struct pci_dev *d, char *link_name)
124 {
125   char path[2*OBJNAMELEN], rel_path[OBJNAMELEN];
126
127   sysfs_obj_name(d, link_name, path);
128   memset(rel_path, 0, sizeof(rel_path));
129
130   if (readlink(path, rel_path, sizeof(rel_path)) < 0)
131     return NULL;
132
133   sysfs_obj_name(d, "", path);
134   strcat(path, rel_path);
135
136   // Returns a pointer to malloc'ed memory
137   return realpath(path, NULL);
138 }
139
140 static int
141 sysfs_get_value(struct pci_dev *d, char *object, int mandatory)
142 {
143   char buf[OBJBUFSIZE];
144
145   if (sysfs_get_string(d, object, buf, mandatory))
146     return strtol(buf, NULL, 0);
147   else
148     return -1;
149 }
150
151 static void
152 sysfs_get_resources(struct pci_dev *d)
153 {
154   struct pci_access *a = d->access;
155   char namebuf[OBJNAMELEN], buf[256];
156   struct { pciaddr_t flags, base_addr, size; } lines[10];
157   int have_bar_bases, have_rom_base, have_bridge_bases;
158   FILE *file;
159   int i;
160
161   have_bar_bases = have_rom_base = have_bridge_bases = 0;
162   sysfs_obj_name(d, "resource", namebuf);
163   file = fopen(namebuf, "r");
164   if (!file)
165     a->error("Cannot open %s: %s", namebuf, strerror(errno));
166   for (i = 0; i < 7+6+4+1; i++)
167     {
168       unsigned long long start, end, size, flags;
169       if (!fgets(buf, sizeof(buf), file))
170         break;
171       if (sscanf(buf, "%llx %llx %llx", &start, &end, &flags) != 3)
172         a->error("Syntax error in %s", namebuf);
173       if (end > start)
174         size = end - start + 1;
175       else
176         size = 0;
177       if (i < 6)
178         {
179           d->flags[i] = flags;
180           flags &= PCI_ADDR_FLAG_MASK;
181           d->base_addr[i] = start | flags;
182           d->size[i] = size;
183           have_bar_bases = 1;
184         }
185       else if (i == 6)
186         {
187           d->rom_flags = flags;
188           flags &= PCI_ADDR_FLAG_MASK;
189           d->rom_base_addr = start | flags;
190           d->rom_size = size;
191           have_rom_base = 1;
192         }
193       else if (i < 7+6+4)
194         {
195           /*
196            * If kernel was compiled without CONFIG_PCI_IOV option then after
197            * the ROM line for configured bridge device (that which had set
198            * subordinary bus number to non-zero value) are four additional lines
199            * which describe resources behind bridge. For PCI-to-PCI bridges they
200            * are: IO, MEM, PREFMEM and empty. For CardBus bridges they are: IO0,
201            * IO1, MEM0 and MEM1. For unconfigured bridges and other devices
202            * there is no additional line after the ROM line. If kernel was
203            * compiled with CONFIG_PCI_IOV option then after the ROM line and
204            * before the first bridge resource line are six additional lines
205            * which describe IOV resources. Read all remaining lines in resource
206            * file and based on the number of remaining lines (0, 4, 6, 10) parse
207            * resources behind bridge.
208            */
209           lines[i-7].flags = flags;
210           lines[i-7].base_addr = start;
211           lines[i-7].size = size;
212         }
213     }
214   if (i == 7+4 || i == 7+6+4)
215     {
216       int offset = (i == 7+6+4) ? 6 : 0;
217       for (i = 0; i < 4; i++)
218         {
219           d->bridge_flags[i] = lines[offset+i].flags;
220           d->bridge_base_addr[i] = lines[offset+i].base_addr;
221           d->bridge_size[i] = lines[offset+i].size;
222         }
223       have_bridge_bases = 1;
224     }
225   fclose(file);
226   if (!have_bar_bases)
227     clear_fill(d, PCI_FILL_BASES | PCI_FILL_SIZES | PCI_FILL_IO_FLAGS);
228   if (!have_rom_base)
229     clear_fill(d, PCI_FILL_ROM_BASE);
230   if (!have_bridge_bases)
231     clear_fill(d, PCI_FILL_BRIDGE_BASES);
232 }
233
234 static void sysfs_scan(struct pci_access *a)
235 {
236   char dirname[1024];
237   DIR *dir;
238   struct dirent *entry;
239   int n;
240
241   n = snprintf(dirname, sizeof(dirname), "%s/devices", sysfs_name(a));
242   if (n < 0 || n >= (int) sizeof(dirname))
243     a->error("Directory name too long");
244   dir = opendir(dirname);
245   if (!dir)
246     a->error("Cannot open %s", dirname);
247   while ((entry = readdir(dir)))
248     {
249       struct pci_dev *d;
250       unsigned int dom, bus, dev, func;
251
252       /* ".", ".." or a special non-device perhaps */
253       if (entry->d_name[0] == '.')
254         continue;
255
256       d = pci_alloc_dev(a);
257       if (sscanf(entry->d_name, "%x:%x:%x.%d", &dom, &bus, &dev, &func) < 4)
258         a->error("sysfs_scan: Couldn't parse entry name %s", entry->d_name);
259
260       /* Ensure kernel provided domain that fits in a signed integer */
261       if (dom > 0x7fffffff)
262         a->error("sysfs_scan: Invalid domain %x", dom);
263
264       d->domain = dom;
265       d->bus = bus;
266       d->dev = dev;
267       d->func = func;
268       pci_link_dev(a, d);
269     }
270   closedir(dir);
271 }
272
273 static void
274 sysfs_fill_slots(struct pci_access *a)
275 {
276   char dirname[1024];
277   DIR *dir;
278   struct dirent *entry;
279   int n;
280
281   n = snprintf(dirname, sizeof(dirname), "%s/slots", sysfs_name(a));
282   if (n < 0 || n >= (int) sizeof(dirname))
283     a->error("Directory name too long");
284   dir = opendir(dirname);
285   if (!dir)
286     return;
287
288   while (entry = readdir(dir))
289     {
290       char namebuf[OBJNAMELEN], buf[16];
291       FILE *file;
292       unsigned int dom, bus, dev;
293       int res = 0;
294       struct pci_dev *d;
295
296       /* ".", ".." or a special non-device perhaps */
297       if (entry->d_name[0] == '.')
298         continue;
299
300       n = snprintf(namebuf, OBJNAMELEN, "%s/%s/%s", dirname, entry->d_name, "address");
301       if (n < 0 || n >= OBJNAMELEN)
302         a->error("File name too long");
303       file = fopen(namebuf, "r");
304       /*
305        * Old versions of Linux had a fakephp which didn't have an 'address'
306        * file.  There's no useful information to be gleaned from these
307        * devices, pretend they're not there.
308        */
309       if (!file)
310         continue;
311
312       if (!fgets(buf, sizeof(buf), file) || (res = sscanf(buf, "%x:%x:%x", &dom, &bus, &dev)) < 3)
313         {
314           /*
315            * In some cases, the slot is not tied to a specific device before
316            * a card gets inserted. This happens for example on IBM pSeries
317            * and we need not warn about it.
318            */
319           if (res != 2)
320             a->warning("sysfs_fill_slots: Couldn't parse entry address %s", buf);
321         }
322       else
323         {
324           for (d = a->devices; d; d = d->next)
325             if (dom == (unsigned)d->domain && bus == d->bus && dev == d->dev && !d->phy_slot)
326               d->phy_slot = pci_set_property(d, PCI_FILL_PHYS_SLOT, entry->d_name);
327         }
328       fclose(file);
329     }
330   closedir(dir);
331 }
332
333 static void
334 sysfs_fill_info(struct pci_dev *d, unsigned int flags)
335 {
336   int value, want_class, want_class_ext;
337
338   if (!d->access->buscentric)
339     {
340       /*
341        *  These fields can be read from the config registers, but we want to show
342        *  the kernel's view, which has regions and IRQs remapped and other fields
343        *  (most importantly classes) possibly fixed if the device is known broken.
344        */
345       if (want_fill(d, flags, PCI_FILL_IDENT))
346         {
347           d->vendor_id = sysfs_get_value(d, "vendor", 1);
348           d->device_id = sysfs_get_value(d, "device", 1);
349         }
350       want_class = want_fill(d, flags, PCI_FILL_CLASS);
351       want_class_ext = want_fill(d, flags, PCI_FILL_CLASS_EXT);
352       if (want_class || want_class_ext)
353         {
354           value = sysfs_get_value(d, "class", 1);
355           if (want_class)
356             d->device_class = value >> 8;
357           if (want_class_ext)
358             {
359               d->prog_if = value & 0xff;
360               value = sysfs_get_value(d, "revision", 0);
361               if (value < 0)
362                 value = pci_read_byte(d, PCI_REVISION_ID);
363               if (value >= 0)
364                 d->rev_id = value;
365             }
366         }
367       if (want_fill(d, flags, PCI_FILL_SUBSYS))
368         {
369           value = sysfs_get_value(d, "subsystem_vendor", 0);
370           if (value >= 0)
371             {
372               d->subsys_vendor_id = value;
373               value = sysfs_get_value(d, "subsystem_device", 0);
374               if (value >= 0)
375                 d->subsys_id = value;
376             }
377           else
378             clear_fill(d, PCI_FILL_SUBSYS);
379         }
380       if (want_fill(d, flags, PCI_FILL_IRQ))
381           d->irq = sysfs_get_value(d, "irq", 1);
382       if (want_fill(d, flags, PCI_FILL_BASES | PCI_FILL_ROM_BASE | PCI_FILL_SIZES | PCI_FILL_IO_FLAGS | PCI_FILL_BRIDGE_BASES))
383           sysfs_get_resources(d);
384       if (want_fill(d, flags, PCI_FILL_PARENT))
385         {
386           unsigned int domain, bus, dev, func;
387           char *path_abs, *path_canon, *name;
388           char path_rel[OBJNAMELEN];
389           struct pci_dev *parent;
390
391           /* Construct sysfs path for parent device */
392           sysfs_obj_name(d, "..", path_rel);
393           path_abs = realpath(path_rel, NULL);
394           name = path_abs ? strrchr(path_abs, '/') : NULL;
395           name = name ? name+1 : name;
396           parent = NULL;
397
398           if (name && sscanf(name, "%x:%x:%x.%d", &domain, &bus, &dev, &func) == 4 && domain <= 0x7fffffff)
399             for (parent = d->access->devices; parent; parent = parent->next)
400               if (parent->domain == (int)domain && parent->bus == bus && parent->dev == dev && parent->func == func)
401                 break;
402
403           if (parent)
404             {
405               /* Check if parsed BDF address from parent sysfs device is really expected PCI device */
406               sysfs_obj_name(parent, ".", path_rel);
407               path_canon = realpath(path_rel, NULL);
408               if (!path_canon || strcmp(path_canon, path_abs) != 0)
409                 parent = NULL;
410             }
411
412           if (parent)
413             d->parent = parent;
414           else
415             clear_fill(d, PCI_FILL_PARENT);
416         }
417     }
418
419   if (want_fill(d, flags, PCI_FILL_PHYS_SLOT))
420     {
421       struct pci_dev *pd;
422       sysfs_fill_slots(d->access);
423       for (pd = d->access->devices; pd; pd = pd->next)
424         pd->known_fields |= PCI_FILL_PHYS_SLOT;
425     }
426
427   if (want_fill(d, flags, PCI_FILL_MODULE_ALIAS))
428     {
429       char buf[OBJBUFSIZE];
430       if (sysfs_get_string(d, "modalias", buf, 0))
431         d->module_alias = pci_set_property(d, PCI_FILL_MODULE_ALIAS, buf);
432     }
433
434   if (want_fill(d, flags, PCI_FILL_LABEL))
435     {
436       char buf[OBJBUFSIZE];
437       if (sysfs_get_string(d, "label", buf, 0))
438         d->label = pci_set_property(d, PCI_FILL_LABEL, buf);
439     }
440
441   if (want_fill(d, flags, PCI_FILL_NUMA_NODE))
442     d->numa_node = sysfs_get_value(d, "numa_node", 0);
443
444   if (want_fill(d, flags, PCI_FILL_IOMMU_GROUP))
445     {
446       char *group_link = sysfs_deref_link(d, "iommu_group");
447       if (group_link)
448         {
449           pci_set_property(d, PCI_FILL_IOMMU_GROUP, basename(group_link));
450           free(group_link);
451         }
452     }
453
454   if (want_fill(d, flags, PCI_FILL_DT_NODE))
455     {
456       char *node = sysfs_deref_link(d, "of_node");
457       if (node)
458         {
459           pci_set_property(d, PCI_FILL_DT_NODE, node);
460           free(node);
461         }
462     }
463
464   if (want_fill(d, flags, PCI_FILL_DRIVER))
465     {
466       char *driver_path = sysfs_deref_link(d, "driver");
467       if (driver_path)
468         {
469           char *driver = strrchr(driver_path, '/');
470           driver = driver ? driver+1 : driver_path;
471           pci_set_property(d, PCI_FILL_DRIVER, driver);
472           free(driver_path);
473         }
474       else
475         clear_fill(d, PCI_FILL_DRIVER);
476     }
477
478   pci_generic_fill_info(d, flags);
479 }
480
481 /* Intent of the sysfs_setup() caller */
482 enum
483   {
484     SETUP_READ_CONFIG = 0,
485     SETUP_WRITE_CONFIG = 1,
486     SETUP_READ_VPD = 2
487   };
488
489 static int
490 sysfs_setup(struct pci_dev *d, int intent)
491 {
492   struct pci_access *a = d->access;
493   char namebuf[OBJNAMELEN];
494
495   if (a->cached_dev != d || (intent == SETUP_WRITE_CONFIG && !a->fd_rw))
496     {
497       sysfs_flush_cache(a);
498       a->cached_dev = d;
499     }
500
501   if (intent == SETUP_READ_VPD)
502     {
503       if (a->fd_vpd < 0)
504         {
505           sysfs_obj_name(d, "vpd", namebuf);
506           a->fd_vpd = open(namebuf, O_RDONLY);
507           /* No warning on error; vpd may be absent or accessible only to root */
508         }
509       return a->fd_vpd;
510     }
511
512   if (a->fd < 0)
513     {
514       sysfs_obj_name(d, "config", namebuf);
515       a->fd_rw = a->writeable || intent == SETUP_WRITE_CONFIG;
516       a->fd = open(namebuf, a->fd_rw ? O_RDWR : O_RDONLY);
517       if (a->fd < 0)
518         a->warning("Cannot open %s", namebuf);
519       a->fd_pos = 0;
520     }
521   return a->fd;
522 }
523
524 static int sysfs_read(struct pci_dev *d, int pos, byte *buf, int len)
525 {
526   int fd = sysfs_setup(d, SETUP_READ_CONFIG);
527   int res;
528
529   if (fd < 0)
530     return 0;
531   res = do_read(d, fd, buf, len, pos);
532   if (res < 0)
533     {
534       d->access->warning("sysfs_read: read failed: %s", strerror(errno));
535       return 0;
536     }
537   else if (res != len)
538     return 0;
539   return 1;
540 }
541
542 static int sysfs_write(struct pci_dev *d, int pos, byte *buf, int len)
543 {
544   int fd = sysfs_setup(d, SETUP_WRITE_CONFIG);
545   int res;
546
547   if (fd < 0)
548     return 0;
549   res = do_write(d, fd, buf, len, pos);
550   if (res < 0)
551     {
552       d->access->warning("sysfs_write: write failed: %s", strerror(errno));
553       return 0;
554     }
555   else if (res != len)
556     {
557       d->access->warning("sysfs_write: tried to write %d bytes at %d, but only %d succeeded", len, pos, res);
558       return 0;
559     }
560   return 1;
561 }
562
563 #ifdef PCI_HAVE_DO_READ
564
565 /* pread() is not available and do_read() only works for a single fd, so we
566  * cannot implement read_vpd properly. */
567 static int sysfs_read_vpd(struct pci_dev *d, int pos, byte *buf, int len)
568 {
569   return 0;
570 }
571
572 #else /* !PCI_HAVE_DO_READ */
573
574 static int sysfs_read_vpd(struct pci_dev *d, int pos, byte *buf, int len)
575 {
576   int fd = sysfs_setup(d, SETUP_READ_VPD);
577   int res;
578
579   if (fd < 0)
580     return 0;
581   res = pread(fd, buf, len, pos);
582   if (res < 0)
583     {
584       d->access->warning("sysfs_read_vpd: read failed: %s", strerror(errno));
585       return 0;
586     }
587   else if (res != len)
588     return 0;
589   return 1;
590 }
591
592 #endif /* PCI_HAVE_DO_READ */
593
594 static void sysfs_cleanup_dev(struct pci_dev *d)
595 {
596   struct pci_access *a = d->access;
597
598   if (a->cached_dev == d)
599     sysfs_flush_cache(a);
600 }
601
602 struct pci_methods pm_linux_sysfs = {
603   "linux-sysfs",
604   "The sys filesystem on Linux",
605   sysfs_config,
606   sysfs_detect,
607   sysfs_init,
608   sysfs_cleanup,
609   sysfs_scan,
610   sysfs_fill_info,
611   sysfs_read,
612   sysfs_write,
613   sysfs_read_vpd,
614   NULL,                                 /* init_dev */
615   sysfs_cleanup_dev
616 };