pci: support multiple PCI regions per device
[dpdk.git] / lib / librte_eal / linuxapp / eal / eal_pci.c
1 /*-
2  *   BSD LICENSE
3  * 
4  *   Copyright(c) 2010-2013 Intel Corporation. All rights reserved.
5  *   All rights reserved.
6  * 
7  *   Redistribution and use in source and binary forms, with or without 
8  *   modification, are permitted provided that the following conditions 
9  *   are met:
10  * 
11  *     * Redistributions of source code must retain the above copyright 
12  *       notice, this list of conditions and the following disclaimer.
13  *     * Redistributions in binary form must reproduce the above copyright 
14  *       notice, this list of conditions and the following disclaimer in 
15  *       the documentation and/or other materials provided with the 
16  *       distribution.
17  *     * Neither the name of Intel Corporation nor the names of its 
18  *       contributors may be used to endorse or promote products derived 
19  *       from this software without specific prior written permission.
20  * 
21  *   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
22  *   "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
23  *   LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR 
24  *   A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT 
25  *   OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, 
26  *   SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT 
27  *   LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, 
28  *   DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY 
29  *   THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT 
30  *   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 
31  *   OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
32  * 
33  */
34
35 #include <ctype.h>
36 #include <stdio.h>
37 #include <stdlib.h>
38 #include <string.h>
39 #include <stdarg.h>
40 #include <unistd.h>
41 #include <inttypes.h>
42 #include <sys/types.h>
43 #include <sys/stat.h>
44 #include <fcntl.h>
45 #include <stdarg.h>
46 #include <errno.h>
47 #include <dirent.h>
48 #include <limits.h>
49 #include <sys/queue.h>
50 #include <sys/mman.h>
51 #include <sys/ioctl.h>
52
53 #include <rte_interrupts.h>
54 #include <rte_log.h>
55 #include <rte_pci.h>
56 #include <rte_common.h>
57 #include <rte_launch.h>
58 #include <rte_memory.h>
59 #include <rte_memzone.h>
60 #include <rte_tailq.h>
61 #include <rte_eal.h>
62 #include <rte_eal_memconfig.h>
63 #include <rte_per_lcore.h>
64 #include <rte_lcore.h>
65 #include <rte_malloc.h>
66 #include <rte_string_fns.h>
67 #include <rte_debug.h>
68
69 #include "eal_filesystem.h"
70 #include "eal_private.h"
71
72 /**
73  * @file
74  * PCI probing under linux
75  *
76  * This code is used to simulate a PCI probe by parsing information in
77  * sysfs. Moreover, when a registered driver matches a device, the
78  * kernel driver currently using it is unloaded and replaced by
79  * igb_uio module, which is a very minimal userland driver for Intel
80  * network card, only providing access to PCI BAR to applications, and
81  * enabling bus master.
82  */
83
84 struct uio_map {
85         void *addr;
86         uint64_t offset;
87         uint64_t size;
88         uint64_t phaddr;
89 };
90
91 #define PROC_MODULES "/proc/modules"
92
93 #define IGB_UIO_NAME "igb_uio"
94
95 #define UIO_DRV_PATH  "/sys/bus/pci/drivers/%s"
96
97 /* maximum time to wait that /dev/uioX appears */
98 #define UIO_DEV_WAIT_TIMEOUT 3 /* seconds */
99
100 /*
101  * For multi-process we need to reproduce all PCI mappings in secondary
102  * processes, so save them in a tailq.
103  */
104 struct uio_resource {
105         TAILQ_ENTRY(uio_resource) next;
106
107         struct rte_pci_addr pci_addr;
108         char path[PATH_MAX];
109         size_t nb_maps;
110         struct uio_map maps[PCI_MAX_RESOURCE];
111 };
112
113 TAILQ_HEAD(uio_res_list, uio_resource);
114
115 static struct uio_res_list *uio_res_list = NULL;
116 static int pci_parse_sysfs_value(const char *filename, uint64_t *val);
117
118 /*
119  * Check that a kernel module is loaded. Returns 0 on success, or if the
120  * parameter is NULL, or -1 if the module is not loaded.
121  */
122 static int
123 pci_uio_check_module(const char *module_name)
124 {
125         FILE *f;
126         unsigned i;
127         char buf[BUFSIZ];
128
129         if (module_name == NULL)
130                 return 0;
131
132         f = fopen(PROC_MODULES, "r");
133         if (f == NULL) {
134                 RTE_LOG(ERR, EAL, "Cannot open "PROC_MODULES": %s\n", 
135                                 strerror(errno));
136                 return -1;
137         }
138
139         while(fgets(buf, sizeof(buf), f) != NULL) {
140
141                 for (i = 0; i < sizeof(buf) && buf[i] != '\0'; i++) {
142                         if (isspace(buf[i]))
143                             buf[i] = '\0';
144                 }
145
146                 if (strncmp(buf, module_name, sizeof(buf)) == 0) {
147                         fclose(f);
148                         return 0;
149                 }
150         }
151         fclose(f);
152         return -1;
153 }
154
155 /* bind a PCI to the kernel module driver */
156 static int
157 pci_bind_device(struct rte_pci_device *dev, char dr_path[])
158 {
159         FILE *f;
160         int n;
161         char buf[BUFSIZ];
162         char dev_bind[PATH_MAX];
163         struct rte_pci_addr *loc = &dev->addr;
164
165         RTE_LOG(DEBUG, EAL, "bind PCI device "PCI_PRI_FMT"\n",
166                         loc->domain, loc->bus, loc->devid, loc->function);
167
168         n = rte_snprintf(dev_bind, sizeof(dev_bind), "%s/bind", dr_path);
169         if ((n < 0) || (n >= (int)sizeof(buf))) {
170                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf device bind path\n");
171                 return -1;
172         }
173
174         f = fopen(dev_bind, "w");
175         if (f == NULL) {
176                 RTE_LOG(ERR, EAL, "Cannot open %s\n", dev->previous_dr);
177                 return -1;
178         }
179         n = rte_snprintf(buf, sizeof(buf), PCI_PRI_FMT "\n",
180                          loc->domain, loc->bus, loc->devid, loc->function);
181         if ((n < 0) || (n >= (int)sizeof(buf))) {
182                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf PCI infos\n");
183                 fclose(f);
184                 return -1;
185         }
186         if (fwrite(buf, n, 1, f) == 0) {
187                 fclose(f);
188                 return -1;
189         }
190
191         RTE_LOG(DEBUG, EAL, "Device bound\n");
192
193         fclose(f);
194         return 0;
195 }
196
197 static int
198 pci_uio_bind_device(struct rte_pci_device *dev, const char *module_name)
199 {
200         FILE *f;
201         int n;
202         char buf[BUFSIZ];
203         char uio_newid[PATH_MAX];
204         char uio_bind[PATH_MAX];
205
206         n = rte_snprintf(uio_newid, sizeof(uio_newid), UIO_DRV_PATH "/new_id", module_name);
207         if ((n < 0) || (n >= (int)sizeof(uio_newid))) {
208                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf uio_newid name\n");
209                 return -1;
210         }
211
212         n = rte_snprintf(uio_bind, sizeof(uio_bind), UIO_DRV_PATH, module_name);
213         if ((n < 0) || (n >= (int)sizeof(uio_bind))) {
214                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf uio_bind name\n");
215                 return -1;
216         }
217
218         n = rte_snprintf(buf, sizeof(buf), "%x %x\n",
219                         dev->id.vendor_id, dev->id.device_id);
220         if ((n < 0) || (n >= (int)sizeof(buf))) {
221                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf vendor_id/device_id\n");
222                 return -1;
223         }
224
225         f = fopen(uio_newid, "w");
226         if (f == NULL) {
227                 RTE_LOG(ERR, EAL, "Cannot open %s\n", uio_newid);
228                 return -1;
229         }
230         if (fwrite(buf, n, 1, f) == 0) {
231                 fclose(f);
232                 return -1;
233         }
234         fclose(f);
235
236         pci_bind_device(dev, uio_bind);
237         return 0;
238 }
239
240
241 /*
242  * open devname: it can take some time to
243  * appear, so we wait some time before returning an error
244  */
245 static int uio_open(const char *devname)
246 {
247         int n, fd;
248
249         for (n=0; n < UIO_DEV_WAIT_TIMEOUT*10; n++) {
250                 fd = open(devname, O_RDWR);
251                 if (fd >= 0)
252                         return fd;
253
254                 if (errno != ENOENT)
255                         break;
256                 usleep(100000);
257         }
258         return -1;
259 }
260
261 /* map a particular resource from a file */
262 static void *
263 pci_mmap(int fd, void *addr, off_t offset, size_t size)
264 {
265         void *mapaddr;
266
267         /* Map the PCI memory resource of device */
268         mapaddr = mmap(addr, size, PROT_READ | PROT_WRITE, MAP_SHARED,
269                        fd, offset);
270         if (mapaddr == MAP_FAILED || (addr != NULL && mapaddr != addr)) {
271                 RTE_LOG(ERR, EAL, "%s(): cannot mmap %zd@0x%lx: %s\n",
272                         __func__, size, offset, strerror(errno));
273                 return NULL;
274         }
275
276         RTE_LOG(DEBUG, EAL, "PCI memory mapped at %p\n", mapaddr);
277         return mapaddr;
278
279 fail:
280         dev->intr_handle.fd = -1;
281         dev->intr_handle.type = RTE_INTR_HANDLE_UNKNOWN;
282
283         return NULL;
284 }
285
286 #define OFF_MAX              ((uint64_t)(off_t)-1)
287 static ssize_t
288 pci_uio_get_mappings(const char *devname, struct uio_map maps[], size_t nb_maps)
289 {
290         size_t i;
291         char dirname[PATH_MAX];
292         char filename[PATH_MAX];
293         uint64_t offset, size;
294
295         for (i = 0; i != nb_maps; i++) {
296  
297                 /* check if map directory exists */
298                 rte_snprintf(dirname, sizeof(dirname), 
299                         "%s/maps/map%u", devname, i);
300  
301                 if (access(dirname, F_OK) != 0)
302                         break;
303  
304                 /* get mapping offset */
305                 rte_snprintf(filename, sizeof(filename),
306                         "%s/offset", dirname);
307                 if (pci_parse_sysfs_value(filename, &offset) < 0) {
308                         RTE_LOG(ERR, EAL,
309                                 "%s(): cannot parse offset of %s\n",
310                                 __func__, dirname);
311                         return (-1);
312                 }
313  
314                 /* get mapping size */
315                 rte_snprintf(filename, sizeof(filename),
316                         "%s/size", dirname);
317                 if (pci_parse_sysfs_value(filename, &size) < 0) {
318                         RTE_LOG(ERR, EAL,
319                                 "%s(): cannot parse size of %s\n",
320                                 __func__, dirname);
321                         return (-1);
322                 }
323  
324                 /* get mapping physical address */
325                 rte_snprintf(filename, sizeof(filename),
326                         "%s/addr", dirname);
327                 if (pci_parse_sysfs_value(filename, &maps[i].phaddr) < 0) {
328                         RTE_LOG(ERR, EAL,
329                                 "%s(): cannot parse addr of %s\n",
330                                 __func__, dirname);
331                         return (-1);
332                 }
333
334                 if ((offset > OFF_MAX) || (size > SIZE_MAX)) {
335                         RTE_LOG(ERR, EAL,
336                                 "%s(): offset/size exceed system max value\n",
337                                 __func__); 
338                         return (-1);
339                 }
340
341                 maps[i].offset = offset;
342                 maps[i].size = size;
343         }
344         return (i);
345 }
346
347 static int
348 pci_uio_map_secondary(struct rte_pci_device *dev)
349 {
350         size_t i;
351         struct uio_resource *uio_res;
352  
353         TAILQ_FOREACH(uio_res, uio_res_list, next) {
354  
355                 /* skip this element if it doesn't match our PCI address */
356                 if (memcmp(&uio_res->pci_addr, &dev->addr, sizeof(dev->addr)))
357                         continue;
358                 
359                 for (i = 0; i != uio_res->nb_maps; i++) {
360                         if (pci_map_resource(dev, uio_res->maps[i].addr,
361                                         uio_res->path,
362                                         (off_t)uio_res->maps[i].offset,
363                                         (size_t)uio_res->maps[i].size) != 
364                                         uio_res->maps[i].addr) {
365                                 RTE_LOG(ERR, EAL,
366                                         "Cannot mmap device resource\n");
367                                 return (-1);
368                         }
369                 }
370                 return (0);
371         }
372
373         RTE_LOG(ERR, EAL, "Cannot find resource for device\n");
374         return -1;
375 }
376
377 /* map the PCI resource of a PCI device in virtual memory */
378 static int
379 pci_uio_map_resource(struct rte_pci_device *dev)
380 {
381         int i, j;
382         struct dirent *e;
383         DIR *dir;
384         char dirname[PATH_MAX];
385         char dirname2[PATH_MAX];
386         char devname[PATH_MAX]; /* contains the /dev/uioX */
387         void *mapaddr;
388         unsigned uio_num;
389         uint64_t phaddr;
390         uint64_t offset;
391         uint64_t pagesz;
392         ssize_t nb_maps;
393         struct rte_pci_addr *loc = &dev->addr;
394         struct uio_resource *uio_res;
395         struct uio_map *maps;
396
397         RTE_LOG(DEBUG, EAL, "map PCI resource for device "PCI_PRI_FMT"\n",
398                 loc->domain, loc->bus, loc->devid, loc->function);
399
400         /* secondary processes - use already recorded details */
401         if (rte_eal_process_type() != RTE_PROC_PRIMARY)
402                 return pci_uio_map_restore(dev);
403
404         /* depending on kernel version, uio can be located in uio/uioX
405          * or uio:uioX */
406
407         rte_snprintf(dirname, sizeof(dirname),
408                  "/sys/bus/pci/devices/" PCI_PRI_FMT "/uio",
409                  loc->domain, loc->bus, loc->devid, loc->function);
410
411         dir = opendir(dirname);
412         if (dir == NULL) {
413                 /* retry with the parent directory */
414                 rte_snprintf(dirname, sizeof(dirname),
415                          "/sys/bus/pci/devices/" PCI_PRI_FMT,
416                          loc->domain, loc->bus, loc->devid, loc->function);
417                 dir = opendir(dirname);
418
419                 if (dir == NULL) {
420                         RTE_LOG(ERR, EAL, "Cannot opendir %s\n", dirname);
421                         return -1;
422                 }
423         }
424
425         /* take the first file starting with "uio" */
426         while ((e = readdir(dir)) != NULL) {
427                 int shortprefix_len = sizeof("uio") - 1; /* format could be uio%d ...*/
428                 int longprefix_len = sizeof("uio:uio") - 1; /* ... or uio:uio%d */
429                 char *endptr;
430
431                 if (strncmp(e->d_name, "uio", 3) != 0)
432                         continue;
433
434                 /* first try uio%d */
435                 errno = 0;
436                 uio_num = strtoull(e->d_name + shortprefix_len, &endptr, 10);
437                 if (errno == 0 && endptr != e->d_name) {
438                         rte_snprintf(dirname2, sizeof(dirname2),
439                                  "%s/uio%u", dirname, uio_num);
440                         break;
441                 }
442
443                 /* then try uio:uio%d */
444                 errno = 0;
445                 uio_num = strtoull(e->d_name + longprefix_len, &endptr, 10);
446                 if (errno == 0 && endptr != e->d_name) {
447                         rte_snprintf(dirname2, sizeof(dirname2),
448                                  "%s/uio:uio%u", dirname, uio_num);
449                         break;
450                 }
451         }
452         closedir(dir);
453
454         /* No uio resource found */
455         if (e == NULL) {
456                 RTE_LOG(WARNING, EAL, "  "PCI_PRI_FMT" not managed by UIO driver, "
457                                 "skipping\n", loc->domain, loc->bus, loc->devid, loc->function);
458                 return -1;
459         }
460
461         /* allocate the mapping details for secondary processes*/
462         if ((uio_res = rte_zmalloc("UIO_RES", sizeof (*uio_res), 0)) == NULL) {
463                 RTE_LOG(ERR, EAL,
464                         "%s(): cannot store uio mmap details\n", __func__);
465                 return (-1);
466         }
467  
468         rte_snprintf(devname, sizeof(devname), "/dev/uio%u", uio_num);
469         rte_snprintf(uio_res->path, sizeof(uio_res->path), "%s", devname);
470         memcpy(&uio_res->pci_addr, &dev->addr, sizeof(uio_res->pci_addr));
471  
472         /* collect info about device mappings */
473         if ((nb_maps = pci_uio_get_mappings(dirname2, uio_res->maps,
474                         sizeof (uio_res->maps) / sizeof (uio_res->maps[0])))
475                         < 0)
476                 return (nb_maps);
477  
478         uio_res->nb_maps = nb_maps;
479
480         /* Map all BARs */
481         pagesz = sysconf(_SC_PAGESIZE);
482  
483         maps = uio_res->maps;
484         for (i = 0; i != PCI_MAX_RESOURCE; i++) {
485     
486                 /* skip empty BAR */
487                 if ((phaddr = dev->mem_resource[i].phys_addr) == 0)
488                         continue;
489  
490                 for (j = 0; j != nb_maps && (phaddr != maps[j].phaddr ||
491                                 dev->mem_resource[i].len != maps[j].size);
492                                 j++)
493                         ;
494  
495                 /* if matching map is found, then use it */
496                 if (j != nb_maps) {
497                         offset = j * pagesz;
498                         if (maps[j].addr != NULL ||
499                                         (mapaddr = pci_map_resource(dev,
500                                         NULL, devname, (off_t)offset,
501                                         (size_t)maps[j].size)) == NULL) {
502                                 return (-1);
503                         }
504  
505                         maps[j].addr = mapaddr;
506                         maps[j].offset = offset;
507                         dev->mem_resource[i].addr = mapaddr;
508                 }
509         }
510
511         TAILQ_INSERT_TAIL(uio_res_list, uio_res, next);
512
513         return (0);
514 }
515
516 /* parse the "resource" sysfs file */
517 #define IORESOURCE_MEM  0x00000200
518
519 static int
520 pci_parse_sysfs_resource(const char *filename, struct rte_pci_device *dev)
521 {
522         FILE *f;
523         char buf[BUFSIZ];
524         union pci_resource_info {
525                 struct {
526                         char *phys_addr;
527                         char *end_addr;
528                         char *flags;
529                 };
530                 char *ptrs[PCI_RESOURCE_FMT_NVAL];
531         } res_info;
532         int i;
533         uint64_t phys_addr, end_addr, flags;
534
535         f = fopen(filename, "r");
536         if (f == NULL) {
537                 RTE_LOG(ERR, EAL, "Cannot open sysfs resource\n");
538                 return -1;
539         }
540
541         for (i = 0; i<PCI_MAX_RESOURCE; i++) {
542
543                 if (fgets(buf, sizeof(buf), f) == NULL) {
544                         RTE_LOG(ERR, EAL, "%s(): cannot read resource\n", __func__);
545                         goto error;
546                 }
547
548                 if (rte_strsplit(buf, sizeof(buf), res_info.ptrs, 3, ' ') != 3) {
549                         RTE_LOG(ERR, EAL, "%s(): bad resource format\n", __func__);
550                         goto error;
551                 }
552                 errno = 0;
553                 phys_addr = strtoull(res_info.phys_addr, NULL, 16);
554                 end_addr = strtoull(res_info.end_addr, NULL, 16);
555                 flags = strtoull(res_info.flags, NULL, 16);
556                 if (errno != 0) {
557                         RTE_LOG(ERR, EAL, "%s(): bad resource format\n", __func__);
558                         goto error;
559                 }
560
561                 if (flags & IORESOURCE_MEM) {
562                         dev->mem_resource[i].phys_addr = phys_addr;
563                         dev->mem_resource[i].len = end_addr - phys_addr + 1;
564                         /* not mapped for now */
565                         dev->mem_resource[i].addr = NULL; 
566                 }
567         }
568         fclose(f);
569         return 0;
570
571 error:
572         fclose(f);
573         return -1;
574 }
575
576 /* 
577  * parse a sysfs file containing one integer value 
578  * different to the eal version, as it needs to work with 64-bit values
579  */ 
580 static int 
581 pci_parse_sysfs_value(const char *filename, uint64_t *val) 
582 {
583         FILE *f;
584         char buf[BUFSIZ];
585         char *end = NULL;
586  
587         f = fopen(filename, "r");
588         if (f == NULL) {
589                 RTE_LOG(ERR, EAL, "%s(): cannot open sysfs value %s\n",
590                         __func__, filename);
591                 return -1;
592         }
593  
594         if (fgets(buf, sizeof(buf), f) == NULL) {
595                 RTE_LOG(ERR, EAL, "%s(): cannot read sysfs value %s\n",
596                         __func__, filename);
597                 fclose(f);
598                 return -1;
599         }
600         *val = strtoull(buf, &end, 0);
601         if ((buf[0] == '\0') || (end == NULL) || (*end != '\n')) {
602                 RTE_LOG(ERR, EAL, "%s(): cannot parse sysfs value %s\n",
603                                 __func__, filename);
604                 fclose(f);
605                 return -1;
606         }
607         fclose(f);
608         return 0;
609 }
610
611 /* Compare two PCI device addresses. */
612 static int
613 pci_addr_comparison(struct rte_pci_addr *addr, struct rte_pci_addr *addr2)
614 {
615         uint64_t dev_addr = (addr->domain << 24) + (addr->bus << 16) + (addr->devid << 8) + addr->function;
616         uint64_t dev_addr2 = (addr2->domain << 24) + (addr2->bus << 16) + (addr2->devid << 8) + addr2->function;
617
618         if (dev_addr > dev_addr2) 
619                 return 1;       
620         else 
621                 return 0;
622 }
623
624
625 /* Scan one pci sysfs entry, and fill the devices list from it. */
626 static int
627 pci_scan_one(const char *dirname, uint16_t domain, uint8_t bus,
628              uint8_t devid, uint8_t function)
629 {
630         char filename[PATH_MAX];
631         unsigned long tmp;
632         struct rte_pci_device *dev;
633
634         dev = malloc(sizeof(*dev));
635         if (dev == NULL) {
636                 return -1;
637         }
638
639         memset(dev, 0, sizeof(*dev));
640         dev->addr.domain = domain;
641         dev->addr.bus = bus;
642         dev->addr.devid = devid;
643         dev->addr.function = function;
644
645         /* get vendor id */
646         rte_snprintf(filename, sizeof(filename), "%s/vendor", dirname);
647         if (eal_parse_sysfs_value(filename, &tmp) < 0) {
648                 free(dev);
649                 return -1;
650         }
651         dev->id.vendor_id = (uint16_t)tmp;
652
653         /* get device id */
654         rte_snprintf(filename, sizeof(filename), "%s/device", dirname);
655         if (eal_parse_sysfs_value(filename, &tmp) < 0) {
656                 free(dev);
657                 return -1;
658         }
659         dev->id.device_id = (uint16_t)tmp;
660
661         /* get subsystem_vendor id */
662         rte_snprintf(filename, sizeof(filename), "%s/subsystem_vendor",
663                  dirname);
664         if (eal_parse_sysfs_value(filename, &tmp) < 0) {
665                 free(dev);
666                 return -1;
667         }
668         dev->id.subsystem_vendor_id = (uint16_t)tmp;
669
670         /* get subsystem_device id */
671         rte_snprintf(filename, sizeof(filename), "%s/subsystem_device",
672                  dirname);
673         if (eal_parse_sysfs_value(filename, &tmp) < 0) {
674                 free(dev);
675                 return -1;
676         }
677         dev->id.subsystem_device_id = (uint16_t)tmp;
678
679         /* parse resources */
680         rte_snprintf(filename, sizeof(filename), "%s/resource", dirname);
681         if (pci_parse_sysfs_resource(filename, dev) < 0) {
682                 RTE_LOG(ERR, EAL, "%s(): cannot parse resource\n", __func__);
683                 free(dev);
684                 return -1;
685         }
686
687         /* device is valid, add in list (sorted) */
688         if (TAILQ_EMPTY(&device_list)) {
689                 TAILQ_INSERT_TAIL(&device_list, dev, next);
690         }       
691         else {
692                 struct rte_pci_device *dev2 = NULL;
693
694                 TAILQ_FOREACH(dev2, &device_list, next) {
695                         if (pci_addr_comparison(&dev->addr, &dev2->addr))
696                                 continue;
697                         else {
698                                 TAILQ_INSERT_BEFORE(dev2, dev, next);
699                                 return 0;
700                         }
701                 }
702                 TAILQ_INSERT_TAIL(&device_list, dev, next);
703         }
704                                 
705         return 0;
706 }
707
708 /*
709  * split up a pci address into its constituent parts.
710  */
711 static int
712 parse_pci_addr_format(const char *buf, int bufsize, uint16_t *domain,
713                 uint8_t *bus, uint8_t *devid, uint8_t *function)
714 {
715         /* first split on ':' */
716         union splitaddr {
717                 struct {
718                         char *domain;
719                         char *bus;
720                         char *devid;
721                         char *function;
722                 };
723                 char *str[PCI_FMT_NVAL]; /* last element-separator is "." not ":" */
724         } splitaddr;
725
726         char *buf_copy = strndup(buf, bufsize);
727         if (buf_copy == NULL)
728                 return -1;
729
730         if (rte_strsplit(buf_copy, bufsize, splitaddr.str, PCI_FMT_NVAL, ':')
731                         != PCI_FMT_NVAL - 1)
732                 goto error;
733         /* final split is on '.' between devid and function */
734         splitaddr.function = strchr(splitaddr.devid,'.');
735         if (splitaddr.function == NULL)
736                 goto error;
737         *splitaddr.function++ = '\0';
738
739         /* now convert to int values */
740         errno = 0;
741         *domain = (uint16_t)strtoul(splitaddr.domain, NULL, 16);
742         *bus = (uint8_t)strtoul(splitaddr.bus, NULL, 16);
743         *devid = (uint8_t)strtoul(splitaddr.devid, NULL, 16);
744         *function = (uint8_t)strtoul(splitaddr.function, NULL, 10);
745         if (errno != 0)
746                 goto error;
747
748         free(buf_copy); /* free the copy made with strdup */
749         return 0;
750 error:
751         free(buf_copy);
752         return -1;
753 }
754
755 /*
756  * Scan the content of the PCI bus, and the devices in the devices
757  * list
758  */
759 static int
760 pci_scan(void)
761 {
762         struct dirent *e;
763         DIR *dir;
764         char dirname[PATH_MAX];
765         uint16_t domain;
766         uint8_t bus, devid, function;
767
768         dir = opendir(SYSFS_PCI_DEVICES);
769         if (dir == NULL) {
770                 RTE_LOG(ERR, EAL, "%s(): opendir failed: %s\n",
771                         __func__, strerror(errno));
772                 return -1;
773         }
774
775         while ((e = readdir(dir)) != NULL) {
776                 if (e->d_name[0] == '.')
777                         continue;
778
779                 if (parse_pci_addr_format(e->d_name, sizeof(e->d_name), &domain,
780                                 &bus, &devid, &function) != 0)
781                         continue;
782
783                 rte_snprintf(dirname, sizeof(dirname), "%s/%s", SYSFS_PCI_DEVICES,
784                          e->d_name);
785                 if (pci_scan_one(dirname, domain, bus, devid, function) < 0)
786                         goto error;
787         }
788         closedir(dir);
789         return 0;
790
791 error:
792         closedir(dir);
793         return -1;
794 }
795
796 /* unbind kernel driver for this device */
797 static int
798 pci_unbind_kernel_driver(struct rte_pci_device *dev)
799 {
800         int n;
801         FILE *f;
802         char filename[PATH_MAX];
803         char buf[BUFSIZ];
804         struct rte_pci_addr *loc = &dev->addr;
805
806         /* open /sys/bus/pci/devices/AAAA:BB:CC.D/driver */
807         rte_snprintf(filename, sizeof(filename),
808                  SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/driver/unbind",
809                  loc->domain, loc->bus, loc->devid, loc->function);
810
811         RTE_LOG(DEBUG, EAL, "unbind kernel driver %s\n", filename);
812
813         f = fopen(filename, "w");
814         if (f == NULL) /* device was not bound */
815                 return 0;
816
817         n = rte_snprintf(buf, sizeof(buf), PCI_PRI_FMT "\n",
818                      loc->domain, loc->bus, loc->devid, loc->function);
819         if ((n < 0) || (n >= (int)sizeof(buf))) {
820                 RTE_LOG(ERR, EAL, "%s(): rte_snprintf failed\n", __func__);
821                 goto error;
822         }
823         if (fwrite(buf, n, 1, f) == 0) {
824                 RTE_LOG(ERR, EAL, "%s(): could not write to %s\n", __func__,
825                                 filename);
826                 goto error;
827         }
828
829         fclose(f);
830         return 0;
831
832 error:
833         fclose(f);
834         return -1;
835 }
836
837 static int
838 pci_exit_process(struct rte_pci_device *dev)
839 {
840         if (munmap(dev->mem_resource.addr, dev->mem_resource.len) == -1){
841                 RTE_LOG(ERR, EAL, "Error with munmap\n");
842                 return -1;
843         }
844         if (close(dev->intr_handle.fd) == -1){
845                 RTE_LOG(ERR, EAL, "Error closing interrupt handle\n");
846                 return -1;
847         }
848         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
849                 if (pci_unbind_kernel_driver(dev) < 0){
850                         RTE_LOG(ERR, EAL, "Error unbinding\n");
851                         return -1;
852                 }
853                 if (pci_bind_device(dev, dev->previous_dr) < 0){
854                         RTE_LOG(ERR, EAL, "Error binding\n");
855                         return -1;
856                 }
857         }
858
859         return 0;
860 }
861
862 static void
863 pci_get_previous_driver_path(struct rte_pci_device *dev)
864 {
865         int n;
866         char dev_path[PATH_MAX];
867         char dr_path[PATH_MAX];
868         struct rte_pci_addr *loc = &dev->addr;
869
870         n = rte_snprintf(dev_path, sizeof(dev_path), SYSFS_PCI_DEVICES "/"
871                         PCI_PRI_FMT "/driver", loc->domain, loc->bus, loc->devid, loc->function );
872         if ((n < 0) || (n >= (int)sizeof(dev_path)))
873                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf device filepath\n");
874
875         n = readlink(dev_path, dr_path, sizeof(dr_path));
876         if ((n < 0) || (n >= (int)sizeof(dr_path))){
877                 RTE_LOG(ERR, EAL, "Cannot readlink driver filepath\n");
878                 dev->previous_dr[0] = '\0';
879                 return;
880         }
881         dr_path[n] = '\0';
882
883         if (dr_path[0] != '/')
884                 n = rte_snprintf(dev->previous_dr, sizeof(dev->previous_dr),
885                                 SYSFS_PCI_DEVICES "/" PCI_PRI_FMT "/%s",
886                                 loc->domain, loc->bus, loc->devid, loc->function, dr_path);
887         else
888                 n = rte_snprintf(dev->previous_dr, sizeof(dev->previous_dr),
889                                 "%s", dr_path);
890         if ((n < 0) || (n >= (int)sizeof(dev_path)))
891                 RTE_LOG(ERR, EAL, "Cannot rte_snprintf driver filepath\n");
892 }
893
894 /*
895  * If vendor/device ID match, call the devinit() function of the
896  * driver.
897  */
898 int
899 rte_eal_pci_probe_one_driver(struct rte_pci_driver *dr, struct rte_pci_device *dev)
900 {
901         struct rte_pci_id *id_table;
902         const char *module_name = NULL;
903         int uio_status = -1;
904
905         if (dr->drv_flags & RTE_PCI_DRV_NEED_IGB_UIO)
906                 module_name = IGB_UIO_NAME;
907
908         for (id_table = dr->id_table ; id_table->vendor_id != 0; id_table++) {
909
910                 /* check if device's identifiers match the driver's ones */
911                 if (id_table->vendor_id != dev->id.vendor_id &&
912                                 id_table->vendor_id != PCI_ANY_ID)
913                         continue;
914                 if (id_table->device_id != dev->id.device_id &&
915                                 id_table->device_id != PCI_ANY_ID)
916                         continue;
917                 if (id_table->subsystem_vendor_id != dev->id.subsystem_vendor_id &&
918                                 id_table->subsystem_vendor_id != PCI_ANY_ID)
919                         continue;
920                 if (id_table->subsystem_device_id != dev->id.subsystem_device_id &&
921                                 id_table->subsystem_device_id != PCI_ANY_ID)
922                         continue;
923
924                 RTE_LOG(DEBUG, EAL, "probe driver: %x:%x %s\n", dev->id.vendor_id,
925                                 dev->id.device_id, dr->name);
926
927                 /* reference driver structure */
928                 dev->driver = dr;
929
930                 /* no initialization when blacklisted, return without error */
931                 if (dev->blacklisted)
932                         return 0;
933
934                 /* Unbind PCI devices if needed */
935                 if (module_name != NULL) {
936
937                         if (rte_eal_process_type() == RTE_PROC_PRIMARY) {
938                                 /* check that our driver is loaded */
939                                 if (uio_status != 0 &&
940                                                 (uio_status = pci_uio_check_module(module_name)) != 0)
941                                         rte_exit(EXIT_FAILURE, "The %s module is required by the "
942                                                         "%s driver\n", module_name, dr->name);
943
944                                 /* unbind current driver, bind ours */
945                                 pci_get_previous_driver_path(dev);
946                                 if (pci_unbind_kernel_driver(dev) < 0)
947                                         return -1;
948                                 if (pci_uio_bind_device(dev, module_name) < 0)
949                                         return -1;
950                         }
951                         /* map the NIC resources */
952                         if (pci_uio_map_resource(dev) < 0)
953                                 return -1;
954 #else
955                 /* just map the NIC resources */
956                 if (pci_uio_map_resource(dev) < 0)
957                         return -1;
958 #endif
959
960                 /* We always should have BAR0 mapped */
961                 if (rte_eal_process_type() == RTE_PROC_PRIMARY && 
962                         dev->mem_resource[0].addr == NULL) {
963                         RTE_LOG(ERR, EAL,
964                                 "%s(): BAR0 is not mapped\n",
965                                 __func__);
966                         return (-1);
967                 }
968  
969                 /* reference driver structure */
970                 dev->driver = dr;
971
972                 /* call the driver devinit() function */
973                 return dr->devinit(dr, dev);
974         }
975         return -1;
976 }
977
978 /*Start the exit process for each dev in use*/
979 void
980 rte_eal_pci_exit(void)
981 {
982         struct rte_pci_device *dev = NULL;
983
984         TAILQ_FOREACH(dev, &device_list, next){
985                 if (dev->previous_dr[0] == '\0')
986                         continue;
987                 if(pci_exit_process(dev) == 1)
988                         RTE_LOG(ERR, EAL, "Exit process failure\n");
989         }
990 }
991
992 /* Init the PCI EAL subsystem */
993 int
994 rte_eal_pci_init(void)
995 {
996         TAILQ_INIT(&driver_list);
997         TAILQ_INIT(&device_list);
998         uio_res_list = RTE_TAILQ_RESERVE_BY_IDX(RTE_TAILQ_PCI, uio_res_list);
999
1000         /* for debug purposes, PCI can be disabled */
1001         if (internal_config.no_pci)
1002                 return 0;
1003
1004         if (pci_scan() < 0) {
1005                 RTE_LOG(ERR, EAL, "%s(): Cannot scan PCI bus\n", __func__);
1006                 return -1;
1007         }
1008         return 0;
1009 }