vlib: add functions to dynamically open/close PCI device
[vpp.git] / src / vlib / linux / pci.c
1 /*
2  * Copyright (c) 2016 Cisco and/or its affiliates.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at:
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 /*
16  * pci.c: Linux user space PCI bus management.
17  *
18  * Copyright (c) 2008 Eliot Dresselhaus
19  *
20  * Permission is hereby granted, free of charge, to any person obtaining
21  * a copy of this software and associated documentation files (the
22  * "Software"), to deal in the Software without restriction, including
23  * without limitation the rights to use, copy, modify, merge, publish,
24  * distribute, sublicense, and/or sell copies of the Software, and to
25  * permit persons to whom the Software is furnished to do so, subject to
26  * the following conditions:
27  *
28  * The above copyright notice and this permission notice shall be
29  * included in all copies or substantial portions of the Software.
30  *
31  *  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
32  *  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33  *  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
34  *  NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
35  *  LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
36  *  OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
37  *  WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
38  */
39
40 #include <vppinfra/linux/sysfs.h>
41
42 #include <vlib/vlib.h>
43 #include <vlib/pci/pci.h>
44 #include <vlib/unix/unix.h>
45 #include <vlib/linux/vfio.h>
46
47 #include <sys/types.h>
48 #include <sys/stat.h>
49 #include <fcntl.h>
50 #include <dirent.h>
51 #include <sys/ioctl.h>
52 #include <net/if.h>
53 #include <linux/ethtool.h>
54 #include <linux/sockios.h>
55 #include <linux/vfio.h>
56 #include <sys/eventfd.h>
57
58 static const char *sysfs_pci_dev_path = "/sys/bus/pci/devices";
59 static const char *sysfs_pci_drv_path = "/sys/bus/pci/drivers";
60 static char *sysfs_mod_vfio_noiommu =
61   "/sys/module/vfio/parameters/enable_unsafe_noiommu_mode";
62
63 typedef struct
64 {
65   int fd;
66   void *addr;
67   size_t size;
68 } linux_pci_region_t;
69
70 typedef struct
71 {
72   int fd;
73   u32 clib_file_index;
74   union
75   {
76     pci_intx_handler_function_t *intx_handler;
77     pci_msix_handler_function_t *msix_handler;
78   };
79 } linux_pci_irq_t;
80
81 typedef enum
82 {
83   LINUX_PCI_DEVICE_TYPE_UNKNOWN,
84   LINUX_PCI_DEVICE_TYPE_UIO,
85   LINUX_PCI_DEVICE_TYPE_VFIO,
86 } linux_pci_device_type_t;
87
88 typedef struct
89 {
90   linux_pci_device_type_t type;
91   vlib_pci_dev_handle_t handle;
92   vlib_pci_addr_t addr;
93
94   /* Resource file descriptors. */
95   linux_pci_region_t *regions;
96
97   /* File descriptor for config space read/write. */
98   int config_fd;
99   u64 config_offset;
100
101   /* Device File descriptor */
102   int fd;
103
104   /* Minor device for uio device. */
105   u32 uio_minor;
106
107   /* Interrupt handlers */
108   linux_pci_irq_t intx_irq;
109   linux_pci_irq_t *msix_irqs;
110
111   /* private data */
112   uword private_data;
113
114 } linux_pci_device_t;
115
116 /* Pool of PCI devices. */
117 typedef struct
118 {
119   vlib_main_t *vlib_main;
120   linux_pci_device_t *linux_pci_devices;
121
122 } linux_pci_main_t;
123
124 extern linux_pci_main_t linux_pci_main;
125
126 static linux_pci_device_t *
127 linux_pci_get_device (vlib_pci_dev_handle_t h)
128 {
129   linux_pci_main_t *lpm = &linux_pci_main;
130   return pool_elt_at_index (lpm->linux_pci_devices, h);
131 }
132
133 uword
134 vlib_pci_get_private_data (vlib_pci_dev_handle_t h)
135 {
136   linux_pci_device_t *d = linux_pci_get_device (h);
137   return d->private_data;
138 }
139
140 void
141 vlib_pci_set_private_data (vlib_pci_dev_handle_t h, uword private_data)
142 {
143   linux_pci_device_t *d = linux_pci_get_device (h);
144   d->private_data = private_data;
145 }
146
147 vlib_pci_addr_t *
148 vlib_pci_get_addr (vlib_pci_dev_handle_t h)
149 {
150   linux_pci_device_t *d = linux_pci_get_device (h);
151   return &d->addr;
152 }
153
154 /* Call to allocate/initialize the pci subsystem.
155    This is not an init function so that users can explicitly enable
156    pci only when it's needed. */
157 clib_error_t *pci_bus_init (vlib_main_t * vm);
158
159 linux_pci_main_t linux_pci_main;
160
161 vlib_pci_device_info_t *
162 vlib_pci_get_device_info (vlib_pci_addr_t * addr, clib_error_t ** error)
163 {
164   linux_vfio_main_t *lvm = &vfio_main;
165   clib_error_t *err;
166   vlib_pci_device_info_t *di;
167   u8 *f = 0;
168   u32 tmp;
169   int fd;
170
171   di = clib_mem_alloc (sizeof (vlib_pci_device_info_t));
172   memset (di, 0, sizeof (vlib_pci_device_info_t));
173   di->addr.as_u32 = addr->as_u32;
174
175   u8 *dev_dir_name = format (0, "%s/%U", sysfs_pci_dev_path,
176                              format_vlib_pci_addr, addr);
177
178   f = format (0, "%v/config%c", dev_dir_name, 0);
179   fd = open ((char *) f, O_RDWR);
180
181   /* Try read-only access if write fails. */
182   if (fd < 0)
183     fd = open ((char *) f, O_RDONLY);
184
185   if (fd < 0)
186     {
187       err = clib_error_return_unix (0, "open `%s'", f);
188       goto error;
189     }
190
191   /* You can only read more that 64 bytes of config space as root; so we try to
192      read the full space but fall back to just the first 64 bytes. */
193   if (read (fd, &di->config_data, sizeof (di->config_data)) <
194       sizeof (di->config0))
195     {
196       err = clib_error_return_unix (0, "read `%s'", f);
197       close (fd);
198       goto error;
199     }
200
201   {
202     static pci_config_header_t all_ones;
203     if (all_ones.vendor_id == 0)
204       memset (&all_ones, ~0, sizeof (all_ones));
205
206     if (!memcmp (&di->config0.header, &all_ones, sizeof (all_ones)))
207       {
208         err = clib_error_return (0, "invalid PCI config for `%s'", f);
209         close (fd);
210         goto error;
211       }
212   }
213
214   if (di->config0.header.header_type == 0)
215     pci_config_type0_little_to_host (&di->config0);
216   else
217     pci_config_type1_little_to_host (&di->config1);
218
219   di->numa_node = -1;
220   vec_reset_length (f);
221   f = format (f, "%v/numa_node%c", dev_dir_name, 0);
222   err = clib_sysfs_read ((char *) f, "%u", &di->numa_node);
223   if (err)
224     {
225       di->numa_node = -1;
226       clib_error_free (err);
227     }
228
229   vec_reset_length (f);
230   f = format (f, "%v/class%c", dev_dir_name, 0);
231   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
232   if (err)
233     goto error;
234   di->device_class = tmp >> 8;
235
236   vec_reset_length (f);
237   f = format (f, "%v/vendor%c", dev_dir_name, 0);
238   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
239   if (err)
240     goto error;
241   di->vendor_id = tmp;
242
243   vec_reset_length (f);
244   f = format (f, "%v/device%c", dev_dir_name, 0);
245   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
246   if (err)
247     goto error;
248   di->device_id = tmp;
249
250   vec_reset_length (f);
251   f = format (f, "%v/driver%c", dev_dir_name, 0);
252   di->driver_name = clib_sysfs_link_to_name ((char *) f);
253
254   di->iommu_group = -1;
255   if (lvm->container_fd != -1)
256     {
257       u8 *tmpstr;
258       vec_reset_length (f);
259       f = format (f, "%v/iommu_group%c", dev_dir_name, 0);
260       tmpstr = clib_sysfs_link_to_name ((char *) f);
261       if (tmpstr)
262         {
263           di->iommu_group = atoi ((char *) tmpstr);
264           vec_free (tmpstr);
265         }
266     }
267
268   close (fd);
269
270   vec_reset_length (f);
271   f = format (f, "%v/vpd%c", dev_dir_name, 0);
272   fd = open ((char *) f, O_RDONLY);
273   if (fd >= 0)
274     {
275       while (1)
276         {
277           u8 tag[3];
278           u8 *data = 0;
279           uword len;
280
281           if (read (fd, &tag, 3) != 3)
282             break;
283
284           if (tag[0] != 0x82 && tag[0] != 0x90 && tag[0] != 0x91)
285             break;
286
287           len = (tag[2] << 8) | tag[1];
288           vec_validate (data, len);
289
290           if (read (fd, data, len) != len)
291             {
292               vec_free (data);
293               break;
294             }
295           if (tag[0] == 0x82)
296             di->product_name = data;
297           else if (tag[0] == 0x90)
298             di->vpd_r = data;
299           else if (tag[0] == 0x91)
300             di->vpd_w = data;
301
302           data = 0;
303         }
304       close (fd);
305     }
306
307   goto done;
308
309 error:
310   vlib_pci_free_device_info (di);
311   di = 0;
312
313 done:
314   vec_free (f);
315   vec_free (dev_dir_name);
316   if (error)
317     *error = err;
318   else
319     clib_error_free (err);
320   return di;
321 }
322
323 static int
324 directory_exists (char *path)
325 {
326   struct stat s = { 0 };
327   if (stat (path, &s) == -1)
328     return 0;
329
330   return S_ISDIR (s.st_mode);
331 }
332
333 clib_error_t *
334 vlib_pci_bind_to_uio (vlib_pci_addr_t * addr, char *uio_drv_name)
335 {
336   clib_error_t *error = 0;
337   u8 *s = 0, *driver_name = 0;
338   DIR *dir = 0;
339   struct dirent *e;
340   vlib_pci_device_info_t *di;
341   int fd, clear_driver_override = 0;
342   u8 *dev_dir_name = format (0, "%s/%U", sysfs_pci_dev_path,
343                              format_vlib_pci_addr, addr);
344
345   di = vlib_pci_get_device_info (addr, &error);
346
347   if (error)
348     return error;
349
350   if (strncmp ("auto", uio_drv_name, 5) == 0)
351     {
352       int vfio_pci_loaded = 0;
353
354       if (directory_exists ("/sys/module/vfio_pci"))
355         vfio_pci_loaded = 1;
356
357       if (di->iommu_group != -1)
358         {
359           /* device is bound to IOMMU group */
360           if (!vfio_pci_loaded)
361             {
362               error = clib_error_return (0, "Skipping PCI device %U: device "
363                                          "is bound to IOMMU group and "
364                                          "vfio-pci driver is not loaded",
365                                          format_vlib_pci_addr, addr);
366               goto done;
367             }
368           else
369             uio_drv_name = "vfio-pci";
370         }
371       else
372         {
373           /* device is not bound to IOMMU group so we have multiple options */
374           if (vfio_pci_loaded &&
375               (error = clib_sysfs_write (sysfs_mod_vfio_noiommu, "Y")) == 0)
376             uio_drv_name = "vfio-pci";
377           else if (directory_exists ("/sys/module/uio_pci_generic"))
378             uio_drv_name = "uio_pci_generic";
379           else if (directory_exists ("/sys/module/igb_uio"))
380             uio_drv_name = "igb_uio";
381           else
382             {
383               clib_error_free (error);
384               error = clib_error_return (0, "Skipping PCI device %U: missing "
385                                          "kernel VFIO or UIO driver",
386                                          format_vlib_pci_addr, addr);
387               goto done;
388             }
389           clib_error_free (error);
390         }
391     }
392
393   s = format (s, "%v/driver%c", dev_dir_name, 0);
394   driver_name = clib_sysfs_link_to_name ((char *) s);
395   vec_reset_length (s);
396
397   if (driver_name &&
398       ((strcmp ("vfio-pci", (char *) driver_name) == 0) ||
399        (strcmp ("uio_pci_generic", (char *) driver_name) == 0) ||
400        (strcmp ("igb_uio", (char *) driver_name) == 0)))
401     goto done;
402
403   /* walk trough all linux interfaces and if interface belonging to
404      this device is founf check if interface is admin up  */
405   dir = opendir ("/sys/class/net");
406   s = format (s, "%U%c", format_vlib_pci_addr, addr, 0);
407
408   if (!dir)
409     {
410       error = clib_error_return (0, "Skipping PCI device %U: failed to "
411                                  "read /sys/class/net",
412                                  format_vlib_pci_addr, addr);
413       goto done;
414     }
415
416   fd = socket (PF_INET, SOCK_DGRAM, 0);
417   if (fd < 0)
418     {
419       error = clib_error_return_unix (0, "socket");
420       goto done;
421     }
422
423   while ((e = readdir (dir)))
424     {
425       struct ifreq ifr;
426       struct ethtool_drvinfo drvinfo;
427
428       if (e->d_name[0] == '.')  /* skip . and .. */
429         continue;
430
431       memset (&ifr, 0, sizeof ifr);
432       memset (&drvinfo, 0, sizeof drvinfo);
433       ifr.ifr_data = (char *) &drvinfo;
434       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
435       drvinfo.cmd = ETHTOOL_GDRVINFO;
436       if (ioctl (fd, SIOCETHTOOL, &ifr) < 0)
437         {
438           /* Some interfaces (eg "lo") don't support this ioctl */
439           if ((errno != ENOTSUP) && (errno != ENODEV))
440             clib_unix_warning ("ioctl fetch intf %s bus info error",
441                                e->d_name);
442           continue;
443         }
444
445       if (strcmp ((char *) s, drvinfo.bus_info))
446         continue;
447
448       memset (&ifr, 0, sizeof (ifr));
449       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
450       if (ioctl (fd, SIOCGIFFLAGS, &ifr) < 0)
451         {
452           error = clib_error_return_unix (0, "ioctl fetch intf %s flags",
453                                           e->d_name);
454           close (fd);
455           goto done;
456         }
457
458       if (ifr.ifr_flags & IFF_UP)
459         {
460           error = clib_error_return (0, "Skipping PCI device %U as host "
461                                      "interface %s is up",
462                                      format_vlib_pci_addr, addr, e->d_name);
463           close (fd);
464           goto done;
465         }
466     }
467
468   close (fd);
469   vec_reset_length (s);
470
471   s = format (s, "%v/driver/unbind%c", dev_dir_name, 0);
472   clib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, addr);
473   vec_reset_length (s);
474
475   s = format (s, "%v/driver_override%c", dev_dir_name, 0);
476   if (access ((char *) s, F_OK) == 0)
477     {
478       clib_sysfs_write ((char *) s, "%s", uio_drv_name);
479       clear_driver_override = 1;
480     }
481   else
482     {
483       vec_reset_length (s);
484       s = format (s, "%s/%s/new_id%c", sysfs_pci_drv_path, uio_drv_name, 0);
485       clib_sysfs_write ((char *) s, "0x%04x 0x%04x", di->vendor_id,
486                         di->device_id);
487     }
488   vec_reset_length (s);
489
490   s = format (s, "%s/%s/bind%c", sysfs_pci_drv_path, uio_drv_name, 0);
491   clib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, addr);
492   vec_reset_length (s);
493
494   if (clear_driver_override)
495     {
496       s = format (s, "%v/driver_override%c", dev_dir_name, 0);
497       clib_sysfs_write ((char *) s, "%c", 0);
498       vec_reset_length (s);
499     }
500
501 done:
502   closedir (dir);
503   vec_free (s);
504   vec_free (dev_dir_name);
505   vec_free (driver_name);
506   return error;
507 }
508
509
510 static clib_error_t *
511 scan_uio_dir (void *arg, u8 * path_name, u8 * file_name)
512 {
513   linux_pci_device_t *l = arg;
514   unformat_input_t input;
515
516   unformat_init_string (&input, (char *) file_name, vec_len (file_name));
517
518   if (!unformat (&input, "uio%d", &l->uio_minor))
519     abort ();
520
521   unformat_free (&input);
522   return 0;
523 }
524
525 static clib_error_t *
526 vfio_set_irqs (linux_pci_device_t * p, u32 index, u32 start, u32 count,
527                u32 flags, int *efds)
528 {
529   int data_len = efds ? count * sizeof (int) : 0;
530   u8 buf[sizeof (struct vfio_irq_set) + data_len];
531   struct vfio_irq_info irq_info = { 0 };
532   struct vfio_irq_set *irq_set = (struct vfio_irq_set *) buf;
533
534
535   irq_info.argsz = sizeof (struct vfio_irq_info);
536   irq_info.index = index;
537
538   if (ioctl (p->fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0)
539     return clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_IRQ_INFO) "
540                                    "'%U'", format_vlib_pci_addr, &p->addr);
541
542   if (irq_info.count < start + count)
543     return clib_error_return_unix (0, "vfio_set_irq: unexistng interrupt on "
544                                    "'%U'", format_vlib_pci_addr, &p->addr);
545
546
547   if (efds)
548     {
549       flags |= VFIO_IRQ_SET_DATA_EVENTFD;
550       clib_memcpy (&irq_set->data, efds, data_len);
551     }
552   else
553     flags |= VFIO_IRQ_SET_DATA_NONE;
554
555   ASSERT ((flags & (VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_DATA_EVENTFD)) !=
556           (VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_DATA_EVENTFD));
557
558   irq_set->argsz = sizeof (struct vfio_irq_set) + data_len;
559   irq_set->index = index;
560   irq_set->start = start;
561   irq_set->count = count;
562   irq_set->flags = flags;
563
564   if (ioctl (p->fd, VFIO_DEVICE_SET_IRQS, irq_set) < 0)
565     return clib_error_return_unix (0, "%U:ioctl(VFIO_DEVICE_SET_IRQS) "
566                                    "[index = %u, start = %u, count = %u, "
567                                    "flags = 0x%x]",
568                                    format_vlib_pci_addr, &p->addr,
569                                    index, start, count, flags);
570   return 0;
571 }
572
573 static clib_error_t *
574 linux_pci_uio_read_ready (clib_file_t * uf)
575 {
576   int __attribute__ ((unused)) rv;
577   vlib_pci_dev_handle_t h = uf->private_data;
578   linux_pci_device_t *p = linux_pci_get_device (h);
579   linux_pci_irq_t *irq = &p->intx_irq;
580
581   u32 icount;
582   rv = read (uf->file_descriptor, &icount, 4);
583
584   if (irq->intx_handler)
585     irq->intx_handler (h);
586
587   vlib_pci_intr_enable (h);
588
589   return /* no error */ 0;
590 }
591
592 static clib_error_t *
593 linux_pci_vfio_unmask_intx (linux_pci_device_t * d)
594 {
595   return vfio_set_irqs (d, VFIO_PCI_INTX_IRQ_INDEX, 0, 1,
596                         VFIO_IRQ_SET_ACTION_UNMASK, 0);
597 }
598
599 static clib_error_t *
600 linux_pci_uio_error_ready (clib_file_t * uf)
601 {
602   u32 error_index = (u32) uf->private_data;
603
604   return clib_error_return (0, "pci device %d: error", error_index);
605 }
606
607 static clib_error_t *
608 linux_pci_vfio_msix_read_ready (clib_file_t * uf)
609 {
610   int __attribute__ ((unused)) rv;
611   vlib_pci_dev_handle_t h = uf->private_data >> 16;
612   u16 line = uf->private_data & 0xffff;
613   linux_pci_device_t *p = linux_pci_get_device (h);
614   linux_pci_irq_t *irq = vec_elt_at_index (p->msix_irqs, line);
615
616   u64 icount;
617   rv = read (uf->file_descriptor, &icount, sizeof (icount));
618
619   if (irq->msix_handler)
620     irq->msix_handler (h, line);
621
622   return /* no error */ 0;
623 }
624
625 static clib_error_t *
626 linux_pci_vfio_intx_read_ready (clib_file_t * uf)
627 {
628   int __attribute__ ((unused)) rv;
629   vlib_pci_dev_handle_t h = uf->private_data;
630   linux_pci_device_t *p = linux_pci_get_device (h);
631   linux_pci_irq_t *irq = &p->intx_irq;
632
633   u64 icount;
634   rv = read (uf->file_descriptor, &icount, sizeof (icount));
635
636   if (irq->intx_handler)
637     irq->intx_handler (h);
638
639   linux_pci_vfio_unmask_intx (p);
640
641   return /* no error */ 0;
642 }
643
644 static clib_error_t *
645 linux_pci_vfio_error_ready (clib_file_t * uf)
646 {
647   u32 error_index = (u32) uf->private_data;
648
649   return clib_error_return (0, "pci device %d: error", error_index);
650 }
651
652 static clib_error_t *
653 add_device_uio (linux_pci_device_t * p, vlib_pci_device_info_t * di,
654                 pci_device_registration_t * r)
655 {
656   linux_pci_main_t *lpm = &linux_pci_main;
657   clib_error_t *err = 0;
658   u8 *s = 0;
659
660   p->addr.as_u32 = di->addr.as_u32;
661   p->fd = -1;
662   p->type = LINUX_PCI_DEVICE_TYPE_UIO;
663
664   s = format (s, "%s/%U/config%c", sysfs_pci_dev_path,
665               format_vlib_pci_addr, &di->addr, 0);
666
667   p->config_fd = open ((char *) s, O_RDWR);
668   p->config_offset = 0;
669   vec_reset_length (s);
670
671   if (p->config_fd == -1)
672     {
673       err = clib_error_return_unix (0, "open '%s'", s);
674       goto error;
675     }
676
677   s = format (0, "%s/%U/uio", sysfs_pci_dev_path,
678               format_vlib_pci_addr, &di->addr);
679   foreach_directory_file ((char *) s, scan_uio_dir, p,  /* scan_dirs */
680                           1);
681   vec_reset_length (s);
682
683   s = format (s, "/dev/uio%d%c", p->uio_minor, 0);
684   p->fd = open ((char *) s, O_RDWR);
685   if (p->fd < 0)
686     {
687       err = clib_error_return_unix (0, "open '%s'", s);
688       goto error;
689     }
690
691   if (r && r->interrupt_handler)
692     vlib_pci_register_intx_handler (p->handle, r->interrupt_handler);
693
694   if (r && r->init_function)
695     err = r->init_function (lpm->vlib_main, p->handle);
696
697 error:
698   free (s);
699   if (err)
700     {
701       if (p->config_fd != -1)
702         close (p->config_fd);
703       if (p->fd != -1)
704         close (p->fd);
705     }
706   return err;
707 }
708
709 clib_error_t *
710 vlib_pci_register_intx_handler (vlib_pci_dev_handle_t h,
711                                 pci_intx_handler_function_t * intx_handler)
712 {
713   linux_pci_device_t *p = linux_pci_get_device (h);
714   clib_file_t t = { 0 };
715   linux_pci_irq_t *irq = &p->intx_irq;
716   ASSERT (irq->fd == -1);
717
718   if (p->type == LINUX_PCI_DEVICE_TYPE_VFIO)
719     {
720       struct vfio_irq_info irq_info = { 0 };
721       irq_info.argsz = sizeof (struct vfio_irq_info);
722       irq_info.index = VFIO_PCI_INTX_IRQ_INDEX;
723       if (ioctl (p->fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0)
724         return clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_IRQ_INFO) '"
725                                        "%U'", format_vlib_pci_addr, &p->addr);
726       if (irq_info.count != 1)
727         return clib_error_return (0, "INTx interrupt does not exist on device"
728                                   "'%U'", format_vlib_pci_addr, &p->addr);
729
730       irq->fd = eventfd (0, EFD_NONBLOCK);
731       if (irq->fd == -1)
732         return clib_error_return_unix (0, "eventfd");
733       t.file_descriptor = irq->fd;
734       t.read_function = linux_pci_vfio_intx_read_ready;
735     }
736   else if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
737     {
738       t.file_descriptor = p->fd;
739       t.read_function = linux_pci_uio_read_ready;
740     }
741   else
742     return 0;
743
744   t.error_function = linux_pci_uio_error_ready;
745   t.private_data = p->handle;
746   t.description = format (0, "PCI %U INTx", format_vlib_pci_addr, &p->addr);
747   irq->clib_file_index = clib_file_add (&file_main, &t);
748   irq->intx_handler = intx_handler;
749   return 0;
750 }
751
752 clib_error_t *
753 vlib_pci_register_msix_handler (vlib_pci_dev_handle_t h, u32 start, u32 count,
754                                 pci_msix_handler_function_t * msix_handler)
755 {
756   clib_error_t *err = 0;
757   linux_pci_device_t *p = linux_pci_get_device (h);
758   u32 i;
759
760   if (p->type != LINUX_PCI_DEVICE_TYPE_VFIO)
761     return clib_error_return (0, "vfio driver is needed for MSI-X interrupt "
762                               "support");
763
764   /* *INDENT-OFF* */
765   vec_validate_init_empty (p->msix_irqs, start + count - 1, (linux_pci_irq_t)
766                            { .fd = -1});
767   /* *INDENT-ON* */
768
769   for (i = start; i < start + count; i++)
770     {
771       clib_file_t t = { 0 };
772       linux_pci_irq_t *irq = vec_elt_at_index (p->msix_irqs, i);
773       ASSERT (irq->fd == -1);
774
775       irq->fd = eventfd (0, EFD_NONBLOCK);
776       if (irq->fd == -1)
777         {
778           err = clib_error_return_unix (0, "eventfd");
779           goto error;
780         }
781
782       t.read_function = linux_pci_vfio_msix_read_ready;
783       t.file_descriptor = irq->fd;
784       t.error_function = linux_pci_vfio_error_ready;
785       t.private_data = p->handle << 16 | i;
786       t.description = format (0, "PCI %U MSI-X #%u", format_vlib_pci_addr,
787                               &p->addr, i);
788       irq->clib_file_index = clib_file_add (&file_main, &t);
789       irq->msix_handler = msix_handler;
790     }
791
792   return 0;
793
794 error:
795   while (i-- > start)
796     {
797       linux_pci_irq_t *irq = vec_elt_at_index (p->msix_irqs, i);
798       if (irq->fd != -1)
799         {
800           clib_file_del_by_index (&file_main, irq->clib_file_index);
801           close (irq->fd);
802           irq->fd = -1;
803         }
804     }
805   return err;
806 }
807
808 clib_error_t *
809 vlib_pci_enable_msix_irq (vlib_pci_dev_handle_t h, u16 start, u16 count)
810 {
811   linux_pci_device_t *p = linux_pci_get_device (h);
812   int fds[count];
813   int i;
814
815   if (p->type != LINUX_PCI_DEVICE_TYPE_VFIO)
816     return clib_error_return (0, "vfio driver is needed for MSI-X interrupt "
817                               "support");
818
819   for (i = start; i < start + count; i++)
820     {
821       linux_pci_irq_t *irq = vec_elt_at_index (p->msix_irqs, i);
822       fds[i] = irq->fd;
823     }
824
825   return vfio_set_irqs (p, VFIO_PCI_MSIX_IRQ_INDEX, start, count,
826                         VFIO_IRQ_SET_ACTION_TRIGGER, fds);
827 }
828
829 clib_error_t *
830 vlib_pci_disable_msix_irq (vlib_pci_dev_handle_t h, u16 start, u16 count)
831 {
832   linux_pci_device_t *p = linux_pci_get_device (h);
833   int i, fds[count];
834
835   if (p->type != LINUX_PCI_DEVICE_TYPE_VFIO)
836     return clib_error_return (0, "vfio driver is needed for MSI-X interrupt "
837                               "support");
838
839   for (i = start; i < start + count; i++)
840     fds[i] = -1;
841
842   return vfio_set_irqs (p, VFIO_PCI_MSIX_IRQ_INDEX, start, count,
843                         VFIO_IRQ_SET_ACTION_TRIGGER, fds);
844 }
845
846 static clib_error_t *
847 add_device_vfio (linux_pci_device_t * p, vlib_pci_device_info_t * di,
848                  pci_device_registration_t * r)
849 {
850   linux_pci_main_t *lpm = &linux_pci_main;
851   struct vfio_device_info device_info = { 0 };
852   struct vfio_region_info reg = { 0 };
853   clib_error_t *err = 0;
854   u8 *s = 0;
855
856   p->addr.as_u32 = di->addr.as_u32;
857   p->type = LINUX_PCI_DEVICE_TYPE_VFIO;
858
859   if (di->driver_name == 0 ||
860       (strcmp ("vfio-pci", (char *) di->driver_name) != 0))
861     return clib_error_return (0, "Device '%U' (iommu group %d) not bound to "
862                               "vfio-pci", format_vlib_pci_addr, &di->addr,
863                               di->iommu_group);
864
865   if ((err = linux_vfio_group_get_device_fd (&p->addr, &p->fd)))
866     return err;
867
868   device_info.argsz = sizeof (device_info);
869   if (ioctl (p->fd, VFIO_DEVICE_GET_INFO, &device_info) < 0)
870     {
871       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_INFO) '%U'",
872                                     format_vlib_pci_addr, &di->addr);
873       goto error;
874     }
875
876   reg.argsz = sizeof (struct vfio_region_info);
877   reg.index = VFIO_PCI_CONFIG_REGION_INDEX;
878   if (ioctl (p->fd, VFIO_DEVICE_GET_REGION_INFO, &reg) < 0)
879     {
880       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_INFO) '%U'",
881                                     format_vlib_pci_addr, &di->addr);
882       goto error;
883     }
884   p->config_offset = reg.offset;
885   p->config_fd = p->fd;
886
887   /* reset if device supports it */
888   if (device_info.flags & VFIO_DEVICE_FLAGS_RESET)
889     if (ioctl (p->fd, VFIO_DEVICE_RESET) < 0)
890       {
891         err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_RESET) '%U'",
892                                       format_vlib_pci_addr, &di->addr);
893         goto error;
894       }
895
896   if (r && r->interrupt_handler)
897     {
898       vlib_pci_register_intx_handler (p->handle, r->interrupt_handler);
899       linux_pci_vfio_unmask_intx (p);
900     }
901
902   if (r && r->init_function)
903     err = r->init_function (lpm->vlib_main, p->handle);
904
905 error:
906   vec_free (s);
907   if (err)
908     {
909       if (p->fd != -1)
910         close (p->fd);
911       if (p->config_fd != -1)
912         close (p->config_fd);
913     }
914   return err;
915 }
916
917 /* Configuration space read/write. */
918 clib_error_t *
919 vlib_pci_read_write_config (vlib_pci_dev_handle_t h,
920                             vlib_read_or_write_t read_or_write,
921                             uword address, void *data, u32 n_bytes)
922 {
923   linux_pci_device_t *p = linux_pci_get_device (h);
924   int n;
925
926   if (read_or_write == VLIB_READ)
927     n = pread (p->config_fd, data, n_bytes, p->config_offset + address);
928   else
929     n = pwrite (p->config_fd, data, n_bytes, p->config_offset + address);
930
931   if (n != n_bytes)
932     return clib_error_return_unix (0, "%s",
933                                    read_or_write == VLIB_READ
934                                    ? "read" : "write");
935
936   return 0;
937 }
938
939 static clib_error_t *
940 vlib_pci_map_region_int (vlib_pci_dev_handle_t h,
941                          u32 bar, u8 * addr, void **result)
942 {
943   linux_pci_device_t *p = linux_pci_get_device (h);
944   int fd = -1;
945   clib_error_t *error;
946   int flags = MAP_SHARED;
947   u64 size = 0, offset = 0;
948
949   ASSERT (bar <= 5);
950
951   error = 0;
952
953   if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
954     {
955       u8 *file_name;
956       struct stat stat_buf;
957       file_name = format (0, "%s/%U/resource%d%c", sysfs_pci_dev_path,
958                           format_vlib_pci_addr, &p->addr, bar, 0);
959
960       fd = open ((char *) file_name, O_RDWR);
961       if (fd < 0)
962         {
963           error = clib_error_return_unix (0, "open `%s'", file_name);
964           vec_free (file_name);
965           return error;
966         }
967
968       if (fstat (fd, &stat_buf) < 0)
969         {
970           error = clib_error_return_unix (0, "fstat `%s'", file_name);
971           vec_free (file_name);
972           close (fd);
973           return error;
974         }
975
976       vec_free (file_name);
977       if (addr != 0)
978         flags |= MAP_FIXED;
979       size = stat_buf.st_size;
980       offset = 0;
981     }
982   else if (p->type == LINUX_PCI_DEVICE_TYPE_VFIO)
983     {
984       struct vfio_region_info reg = { 0 };
985       reg.argsz = sizeof (struct vfio_region_info);
986       reg.index = bar;
987       if (ioctl (p->fd, VFIO_DEVICE_GET_REGION_INFO, &reg) < 0)
988         return clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_INFO) "
989                                        "'%U'", format_vlib_pci_addr,
990                                        &p->addr);
991       fd = p->fd;
992       size = reg.size;
993       offset = reg.offset;
994     }
995   else
996     ASSERT (0);
997
998   *result = mmap (addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
999   if (*result == (void *) -1)
1000     {
1001       error = clib_error_return_unix (0, "mmap `BAR%u'", bar);
1002       if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
1003         close (fd);
1004       return error;
1005     }
1006
1007   /* *INDENT-OFF* */
1008   vec_validate_init_empty (p->regions, bar,
1009                            (linux_pci_region_t) { .fd = -1});
1010   /* *INDENT-ON* */
1011   if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
1012     p->regions[bar].fd = fd;
1013   p->regions[bar].addr = *result;
1014   p->regions[bar].size = size;
1015   return 0;
1016 }
1017
1018 clib_error_t *
1019 vlib_pci_map_region (vlib_pci_dev_handle_t h, u32 resource, void **result)
1020 {
1021   return (vlib_pci_map_region_int (h, resource, 0 /* addr */ , result));
1022 }
1023
1024 clib_error_t *
1025 vlib_pci_map_region_fixed (vlib_pci_dev_handle_t h, u32 resource, u8 * addr,
1026                            void **result)
1027 {
1028   return (vlib_pci_map_region_int (h, resource, addr, result));
1029 }
1030
1031 clib_error_t *
1032 vlib_pci_device_open (vlib_pci_addr_t * addr,
1033                       pci_device_id_t ids[], vlib_pci_dev_handle_t * handle)
1034 {
1035   linux_pci_main_t *lpm = &linux_pci_main;
1036   vlib_pci_device_info_t *di;
1037   linux_pci_device_t *p;
1038   clib_error_t *err = 0;
1039   pci_device_id_t *i;
1040
1041   di = vlib_pci_get_device_info (addr, &err);
1042
1043   if (err)
1044     return err;
1045   for (i = ids; i->vendor_id != 0; i++)
1046     if (i->vendor_id == di->vendor_id && i->device_id == di->device_id)
1047       break;
1048
1049   if (i->vendor_id == 0)
1050     return clib_error_return (0, "Wrong vendor or device id");
1051
1052   pool_get (lpm->linux_pci_devices, p);
1053   p->handle = p - lpm->linux_pci_devices;
1054   p->intx_irq.fd = -1;
1055
1056   if (di->iommu_group != -1)
1057     err = add_device_vfio (p, di, 0);
1058   else
1059     err = add_device_uio (p, di, 0);
1060   if (err)
1061     goto error;
1062
1063   *handle = p->handle;
1064
1065 error:
1066   vlib_pci_free_device_info (di);
1067   if (err)
1068     {
1069       memset (p, 0, sizeof (linux_pci_device_t));
1070       pool_put (lpm->linux_pci_devices, p);
1071     }
1072
1073   return err;
1074 }
1075
1076 void
1077 vlib_pci_device_close (vlib_pci_dev_handle_t h)
1078 {
1079   linux_pci_main_t *lpm = &linux_pci_main;
1080   linux_pci_device_t *p = linux_pci_get_device (h);
1081   linux_pci_irq_t *irq;
1082   linux_pci_region_t *res;
1083   clib_error_t *err = 0;
1084
1085   if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
1086     {
1087       irq = &p->intx_irq;
1088       clib_file_del_by_index (&file_main, irq->clib_file_index);
1089       close (p->config_fd);
1090     }
1091   else if (p->type == LINUX_PCI_DEVICE_TYPE_VFIO)
1092     {
1093       irq = &p->intx_irq;
1094       /* close INTx irqs */
1095       if (irq->fd != -1)
1096         {
1097           err = vfio_set_irqs (p, VFIO_PCI_INTX_IRQ_INDEX, 0, 0,
1098                                VFIO_IRQ_SET_ACTION_TRIGGER, 0);
1099           clib_error_free (err);
1100           clib_file_del_by_index (&file_main, irq->clib_file_index);
1101           close (irq->fd);
1102         }
1103
1104       /* close MSI-X irqs */
1105       if (vec_len (p->msix_irqs))
1106         {
1107           err = vfio_set_irqs (p, VFIO_PCI_MSIX_IRQ_INDEX, 0, 0,
1108                                VFIO_IRQ_SET_ACTION_TRIGGER, 0);
1109           clib_error_free (err);
1110           /* *INDENT-OFF* */
1111           vec_foreach (irq, p->msix_irqs)
1112             {
1113               if (irq->fd == -1)
1114                 continue;
1115               clib_file_del_by_index (&file_main, irq->clib_file_index);
1116               close (irq->fd);
1117             }
1118           /* *INDENT-ON* */
1119           vec_free (p->msix_irqs);
1120         }
1121     }
1122
1123   /* *INDENT-OFF* */
1124   vec_foreach (res, p->regions)
1125     {
1126       if (res->size == 0)
1127         continue;
1128       munmap (res->addr, res->size);
1129       if (res->fd != -1)
1130         close (res->fd);
1131     }
1132   /* *INDENT-ON* */
1133   vec_free (p->regions);
1134
1135   close (p->fd);
1136   memset (p, 0, sizeof (linux_pci_device_t));
1137   pool_put (lpm->linux_pci_devices, p);
1138 }
1139
1140 void
1141 init_device_from_registered (vlib_pci_device_info_t * di)
1142 {
1143   vlib_pci_main_t *pm = &pci_main;
1144   linux_pci_main_t *lpm = &linux_pci_main;
1145   pci_device_registration_t *r;
1146   pci_device_id_t *i;
1147   clib_error_t *err = 0;
1148   linux_pci_device_t *p;
1149
1150   pool_get (lpm->linux_pci_devices, p);
1151   p->handle = p - lpm->linux_pci_devices;
1152   p->intx_irq.fd = -1;
1153
1154   r = pm->pci_device_registrations;
1155
1156   while (r)
1157     {
1158       for (i = r->supported_devices; i->vendor_id != 0; i++)
1159         if (i->vendor_id == di->vendor_id && i->device_id == di->device_id)
1160           {
1161             if (di->iommu_group != -1)
1162               err = add_device_vfio (p, di, r);
1163             else
1164               err = add_device_uio (p, di, r);
1165
1166             if (err)
1167               clib_error_report (err);
1168             else
1169               return;
1170           }
1171       r = r->next_registration;
1172     }
1173
1174   /* No driver, close the PCI config-space FD */
1175   memset (p, 0, sizeof (linux_pci_device_t));
1176   pool_put (lpm->linux_pci_devices, p);
1177 }
1178
1179 static clib_error_t *
1180 scan_pci_addr (void *arg, u8 * dev_dir_name, u8 * ignored)
1181 {
1182   vlib_pci_addr_t addr, **addrv = arg;
1183   unformat_input_t input;
1184   clib_error_t *err = 0;
1185
1186   unformat_init_string (&input, (char *) dev_dir_name,
1187                         vec_len (dev_dir_name));
1188
1189   if (!unformat (&input, "/sys/bus/pci/devices/%U",
1190                  unformat_vlib_pci_addr, &addr))
1191     err = clib_error_return (0, "unformat error `%v`", dev_dir_name);
1192
1193   unformat_free (&input);
1194
1195   if (err)
1196     return err;
1197
1198   vec_add1 (*addrv, addr);
1199   return 0;
1200 }
1201
1202 static int
1203 pci_addr_cmp (void *v1, void *v2)
1204 {
1205   vlib_pci_addr_t *a1 = v1;
1206   vlib_pci_addr_t *a2 = v2;
1207
1208   if (a1->domain > a2->domain)
1209     return 1;
1210   if (a1->domain < a2->domain)
1211     return -1;
1212   if (a1->bus > a2->bus)
1213     return 1;
1214   if (a1->bus < a2->bus)
1215     return -1;
1216   if (a1->slot > a2->slot)
1217     return 1;
1218   if (a1->slot < a2->slot)
1219     return -1;
1220   if (a1->function > a2->function)
1221     return 1;
1222   if (a1->function < a2->function)
1223     return -1;
1224   return 0;
1225 }
1226
1227 vlib_pci_addr_t *
1228 vlib_pci_get_all_dev_addrs ()
1229 {
1230   vlib_pci_addr_t *addrs = 0;
1231   clib_error_t *err;
1232   err = foreach_directory_file ((char *) sysfs_pci_dev_path, scan_pci_addr,
1233                                 &addrs, /* scan_dirs */ 0);
1234   if (err)
1235     {
1236       vec_free (addrs);
1237       return 0;
1238     }
1239
1240   vec_sort_with_function (addrs, pci_addr_cmp);
1241
1242   return addrs;
1243 }
1244
1245 clib_error_t *
1246 linux_pci_init (vlib_main_t * vm)
1247 {
1248   vlib_pci_main_t *pm = &pci_main;
1249   vlib_pci_addr_t *addr = 0, *addrs;
1250   clib_error_t *error;
1251
1252   pm->vlib_main = vm;
1253
1254   if ((error = vlib_call_init_function (vm, unix_input_init)))
1255     return error;
1256
1257   ASSERT (sizeof (vlib_pci_addr_t) == sizeof (u32));
1258
1259   addrs = vlib_pci_get_all_dev_addrs ();
1260   /* *INDENT-OFF* */
1261   vec_foreach (addr, addrs)
1262     {
1263       vlib_pci_device_info_t *d;
1264       if ((d = vlib_pci_get_device_info (addr, 0)))
1265         {
1266           init_device_from_registered (d);
1267           vlib_pci_free_device_info (d);
1268         }
1269     }
1270   /* *INDENT-ON* */
1271
1272   return error;
1273 }
1274
1275 VLIB_INIT_FUNCTION (linux_pci_init);
1276
1277 /*
1278  * fd.io coding-style-patch-verification: ON
1279  *
1280  * Local Variables:
1281  * eval: (c-set-style "gnu")
1282  * End:
1283  */