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