vlib: map pci region by using vfio FD when vfio is used
[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
46 #include <sys/types.h>
47 #include <sys/stat.h>
48 #include <fcntl.h>
49 #include <dirent.h>
50 #include <sys/ioctl.h>
51 #include <net/if.h>
52 #include <linux/ethtool.h>
53 #include <linux/sockios.h>
54 #include <linux/vfio.h>
55 #include <sys/eventfd.h>
56
57 static const char *sysfs_pci_dev_path = "/sys/bus/pci/devices";
58 static const char *sysfs_pci_drv_path = "/sys/bus/pci/drivers";
59 static char *sysfs_mod_vfio_noiommu =
60   "/sys/module/vfio/parameters/enable_unsafe_noiommu_mode";
61
62 typedef struct
63 {
64   int fd;
65   void *addr;
66   size_t size;
67 } linux_pci_region_t;
68
69
70 typedef enum
71 {
72   LINUX_PCI_DEVICE_TYPE_UNKNOWN,
73   LINUX_PCI_DEVICE_TYPE_UIO,
74   LINUX_PCI_DEVICE_TYPE_VFIO,
75 } linux_pci_device_type_t;
76
77 typedef struct
78 {
79   linux_pci_device_type_t type;
80   vlib_pci_dev_handle_t handle;
81   vlib_pci_addr_t addr;
82
83   /* Resource file descriptors. */
84   linux_pci_region_t *regions;
85
86   /* File descriptor for config space read/write. */
87   int config_fd;
88   u64 config_offset;
89
90   /* Device File descriptor */
91   int fd;
92
93   /* Minor device for uio device. */
94   u32 uio_minor;
95
96   /* Index given by clib_file_add. */
97   u32 clib_file_index;
98
99   /* Interrupt handler */
100   void (*interrupt_handler) (vlib_pci_dev_handle_t h);
101
102   /* private data */
103   uword private_data;
104
105 } linux_pci_device_t;
106
107 typedef struct
108 {
109   int group;
110   int fd;
111   int refcnt;
112 } linux_pci_vfio_iommu_group_t;
113
114 /* Pool of PCI devices. */
115 typedef struct
116 {
117   vlib_main_t *vlib_main;
118   linux_pci_device_t *linux_pci_devices;
119
120   /* VFIO */
121   int vfio_container_fd;
122   int vfio_iommu_mode;
123
124   /* pool of IOMMU groups */
125   linux_pci_vfio_iommu_group_t *iommu_groups;
126
127   /* iommu group pool index by group id  hash */
128   uword *iommu_pool_index_by_group;
129
130 } linux_pci_main_t;
131
132 extern linux_pci_main_t linux_pci_main;
133
134 linux_pci_device_t *
135 linux_pci_get_device (vlib_pci_dev_handle_t h)
136 {
137   linux_pci_main_t *lpm = &linux_pci_main;
138   return pool_elt_at_index (lpm->linux_pci_devices, h);
139 }
140
141 uword
142 vlib_pci_get_private_data (vlib_pci_dev_handle_t h)
143 {
144   linux_pci_device_t *d = linux_pci_get_device (h);
145   return d->private_data;
146 }
147
148 void
149 vlib_pci_set_private_data (vlib_pci_dev_handle_t h, uword private_data)
150 {
151   linux_pci_device_t *d = linux_pci_get_device (h);
152   d->private_data = private_data;
153 }
154
155 vlib_pci_addr_t *
156 vlib_pci_get_addr (vlib_pci_dev_handle_t h)
157 {
158   linux_pci_device_t *lpm = linux_pci_get_device (h);
159   return &lpm->addr;
160 }
161
162 /* Call to allocate/initialize the pci subsystem.
163    This is not an init function so that users can explicitly enable
164    pci only when it's needed. */
165 clib_error_t *pci_bus_init (vlib_main_t * vm);
166
167 linux_pci_main_t linux_pci_main;
168
169 vlib_pci_device_info_t *
170 vlib_pci_get_device_info (vlib_pci_addr_t * addr, clib_error_t ** error)
171 {
172   linux_pci_main_t *lpm = &linux_pci_main;
173   clib_error_t *err;
174   vlib_pci_device_info_t *di;
175   u8 *f = 0;
176   u32 tmp;
177   int fd;
178
179   di = clib_mem_alloc (sizeof (vlib_pci_device_info_t));
180   memset (di, 0, sizeof (vlib_pci_device_info_t));
181   di->addr.as_u32 = addr->as_u32;
182
183   u8 *dev_dir_name = format (0, "%s/%U", sysfs_pci_dev_path,
184                              format_vlib_pci_addr, addr);
185
186   f = format (0, "%v/config%c", dev_dir_name, 0);
187   fd = open ((char *) f, O_RDWR);
188
189   /* Try read-only access if write fails. */
190   if (fd < 0)
191     fd = open ((char *) f, O_RDONLY);
192
193   if (fd < 0)
194     {
195       err = clib_error_return_unix (0, "open `%s'", f);
196       goto error;
197     }
198
199   /* You can only read more that 64 bytes of config space as root; so we try to
200      read the full space but fall back to just the first 64 bytes. */
201   if (read (fd, &di->config_data, sizeof (di->config_data)) <
202       sizeof (di->config0))
203     {
204       err = clib_error_return_unix (0, "read `%s'", f);
205       close (fd);
206       goto error;
207     }
208
209   {
210     static pci_config_header_t all_ones;
211     if (all_ones.vendor_id == 0)
212       memset (&all_ones, ~0, sizeof (all_ones));
213
214     if (!memcmp (&di->config0.header, &all_ones, sizeof (all_ones)))
215       {
216         err = clib_error_return (0, "invalid PCI config for `%s'", f);
217         close (fd);
218         goto error;
219       }
220   }
221
222   if (di->config0.header.header_type == 0)
223     pci_config_type0_little_to_host (&di->config0);
224   else
225     pci_config_type1_little_to_host (&di->config1);
226
227   di->numa_node = -1;
228   vec_reset_length (f);
229   f = format (f, "%v/numa_node%c", dev_dir_name, 0);
230   err = clib_sysfs_read ((char *) f, "%u", &di->numa_node);
231   if (err)
232     {
233       di->numa_node = -1;
234       clib_error_free (err);
235     }
236
237   vec_reset_length (f);
238   f = format (f, "%v/class%c", dev_dir_name, 0);
239   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
240   if (err)
241     goto error;
242   di->device_class = tmp >> 8;
243
244   vec_reset_length (f);
245   f = format (f, "%v/vendor%c", dev_dir_name, 0);
246   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
247   if (err)
248     goto error;
249   di->vendor_id = tmp;
250
251   vec_reset_length (f);
252   f = format (f, "%v/device%c", dev_dir_name, 0);
253   err = clib_sysfs_read ((char *) f, "0x%x", &tmp);
254   if (err)
255     goto error;
256   di->device_id = tmp;
257
258   vec_reset_length (f);
259   f = format (f, "%v/driver%c", dev_dir_name, 0);
260   di->driver_name = clib_sysfs_link_to_name ((char *) f);
261
262   di->iommu_group = -1;
263   if (lpm->vfio_container_fd != -1)
264     {
265       u8 *tmpstr;
266       vec_reset_length (f);
267       f = format (f, "%v/iommu_group%c", dev_dir_name, 0);
268       tmpstr = clib_sysfs_link_to_name ((char *) f);
269       if (tmpstr)
270         {
271           di->iommu_group = atoi ((char *) tmpstr);
272           vec_free (tmpstr);
273         }
274     }
275
276   close (fd);
277
278   vec_reset_length (f);
279   f = format (f, "%v/vpd%c", dev_dir_name, 0);
280   fd = open ((char *) f, O_RDONLY);
281   if (fd >= 0)
282     {
283       while (1)
284         {
285           u8 tag[3];
286           u8 *data = 0;
287           uword len;
288
289           if (read (fd, &tag, 3) != 3)
290             break;
291
292           if (tag[0] != 0x82 && tag[0] != 0x90 && tag[0] != 0x91)
293             break;
294
295           len = (tag[2] << 8) | tag[1];
296           vec_validate (data, len);
297
298           if (read (fd, data, len) != len)
299             {
300               vec_free (data);
301               break;
302             }
303           if (tag[0] == 0x82)
304             di->product_name = data;
305           else if (tag[0] == 0x90)
306             di->vpd_r = data;
307           else if (tag[0] == 0x91)
308             di->vpd_w = data;
309
310           data = 0;
311         }
312       close (fd);
313     }
314
315   goto done;
316
317 error:
318   vlib_pci_free_device_info (di);
319   di = 0;
320
321 done:
322   vec_free (f);
323   vec_free (dev_dir_name);
324   if (error)
325     *error = err;
326   else
327     clib_error_free (err);
328   return di;
329 }
330
331 static int
332 directory_exists (char *path)
333 {
334   struct stat s = { 0 };
335   if (stat (path, &s) == -1)
336     return 0;
337
338   return S_ISDIR (s.st_mode);
339 }
340
341 clib_error_t *
342 vlib_pci_bind_to_uio (vlib_pci_addr_t * addr, char *uio_drv_name)
343 {
344   clib_error_t *error = 0;
345   u8 *s = 0, *driver_name = 0;
346   DIR *dir = 0;
347   struct dirent *e;
348   vlib_pci_device_info_t *di;
349   int fd, clear_driver_override = 0;
350   u8 *dev_dir_name = format (0, "%s/%U", sysfs_pci_dev_path,
351                              format_vlib_pci_addr, addr);
352
353   di = vlib_pci_get_device_info (addr, &error);
354
355   if (error)
356     return error;
357
358   if (strncmp ("auto", uio_drv_name, 5) == 0)
359     {
360       int vfio_pci_loaded = 0;
361
362       if (directory_exists ("/sys/module/vfio_pci"))
363         vfio_pci_loaded = 1;
364
365       if (di->iommu_group != -1)
366         {
367           /* device is bound to IOMMU group */
368           if (!vfio_pci_loaded)
369             {
370               error = clib_error_return (0, "Skipping PCI device %U: device "
371                                          "is bound to IOMMU group and "
372                                          "vfio-pci driver is not loaded",
373                                          format_vlib_pci_addr, addr);
374               goto done;
375             }
376           else
377             uio_drv_name = "vfio-pci";
378         }
379       else
380         {
381           /* device is not bound to IOMMU group so we have multiple options */
382           if (vfio_pci_loaded &&
383               (error = clib_sysfs_write (sysfs_mod_vfio_noiommu, "Y")) == 0)
384             uio_drv_name = "vfio-pci";
385           else if (directory_exists ("/sys/module/uio_pci_generic"))
386             uio_drv_name = "uio_pci_generic";
387           else if (directory_exists ("/sys/module/igb_uio"))
388             uio_drv_name = "igb_uio";
389           else
390             {
391               clib_error_free (error);
392               error = clib_error_return (0, "Skipping PCI device %U: missing "
393                                          "kernel VFIO or UIO driver",
394                                          format_vlib_pci_addr, addr);
395               goto done;
396             }
397           clib_error_free (error);
398         }
399     }
400
401   s = format (s, "%v/driver%c", dev_dir_name, 0);
402   driver_name = clib_sysfs_link_to_name ((char *) s);
403   vec_reset_length (s);
404
405   if (driver_name &&
406       ((strcmp ("vfio-pci", (char *) driver_name) == 0) ||
407        (strcmp ("uio_pci_generic", (char *) driver_name) == 0) ||
408        (strcmp ("igb_uio", (char *) driver_name) == 0)))
409     goto done;
410
411   /* walk trough all linux interfaces and if interface belonging to
412      this device is founf check if interface is admin up  */
413   dir = opendir ("/sys/class/net");
414   s = format (s, "%U%c", format_vlib_pci_addr, addr, 0);
415
416   if (!dir)
417     {
418       error = clib_error_return (0, "Skipping PCI device %U: failed to "
419                                  "read /sys/class/net",
420                                  format_vlib_pci_addr, addr);
421       goto done;
422     }
423
424   fd = socket (PF_INET, SOCK_DGRAM, 0);
425   if (fd < 0)
426     {
427       error = clib_error_return_unix (0, "socket");
428       goto done;
429     }
430
431   while ((e = readdir (dir)))
432     {
433       struct ifreq ifr;
434       struct ethtool_drvinfo drvinfo;
435
436       if (e->d_name[0] == '.')  /* skip . and .. */
437         continue;
438
439       memset (&ifr, 0, sizeof ifr);
440       memset (&drvinfo, 0, sizeof drvinfo);
441       ifr.ifr_data = (char *) &drvinfo;
442       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
443       drvinfo.cmd = ETHTOOL_GDRVINFO;
444       if (ioctl (fd, SIOCETHTOOL, &ifr) < 0)
445         {
446           /* Some interfaces (eg "lo") don't support this ioctl */
447           if ((errno != ENOTSUP) && (errno != ENODEV))
448             clib_unix_warning ("ioctl fetch intf %s bus info error",
449                                e->d_name);
450           continue;
451         }
452
453       if (strcmp ((char *) s, drvinfo.bus_info))
454         continue;
455
456       memset (&ifr, 0, sizeof (ifr));
457       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
458       if (ioctl (fd, SIOCGIFFLAGS, &ifr) < 0)
459         {
460           error = clib_error_return_unix (0, "ioctl fetch intf %s flags",
461                                           e->d_name);
462           close (fd);
463           goto done;
464         }
465
466       if (ifr.ifr_flags & IFF_UP)
467         {
468           error = clib_error_return (0, "Skipping PCI device %U as host "
469                                      "interface %s is up",
470                                      format_vlib_pci_addr, addr, e->d_name);
471           close (fd);
472           goto done;
473         }
474     }
475
476   close (fd);
477   vec_reset_length (s);
478
479   s = format (s, "%v/driver/unbind%c", dev_dir_name, 0);
480   clib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, addr);
481   vec_reset_length (s);
482
483   s = format (s, "%v/driver_override%c", dev_dir_name, 0);
484   if (access ((char *) s, F_OK) == 0)
485     {
486       clib_sysfs_write ((char *) s, "%s", uio_drv_name);
487       clear_driver_override = 1;
488     }
489   else
490     {
491       vec_reset_length (s);
492       s = format (s, "%s/%s/new_id%c", sysfs_pci_drv_path, uio_drv_name, 0);
493       clib_sysfs_write ((char *) s, "0x%04x 0x%04x", di->vendor_id,
494                         di->device_id);
495     }
496   vec_reset_length (s);
497
498   s = format (s, "%s/%s/bind%c", sysfs_pci_drv_path, uio_drv_name, 0);
499   clib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, addr);
500   vec_reset_length (s);
501
502   if (clear_driver_override)
503     {
504       s = format (s, "%v/driver_override%c", dev_dir_name, 0);
505       clib_sysfs_write ((char *) s, "%c", 0);
506       vec_reset_length (s);
507     }
508
509 done:
510   closedir (dir);
511   vec_free (s);
512   vec_free (dev_dir_name);
513   vec_free (driver_name);
514   return error;
515 }
516
517
518 static clib_error_t *
519 scan_uio_dir (void *arg, u8 * path_name, u8 * file_name)
520 {
521   linux_pci_device_t *l = arg;
522   unformat_input_t input;
523
524   unformat_init_string (&input, (char *) file_name, vec_len (file_name));
525
526   if (!unformat (&input, "uio%d", &l->uio_minor))
527     abort ();
528
529   unformat_free (&input);
530   return 0;
531 }
532
533 static clib_error_t *
534 linux_pci_uio_read_ready (clib_file_t * uf)
535 {
536   int __attribute__ ((unused)) rv;
537   vlib_pci_dev_handle_t h = uf->private_data;
538   linux_pci_device_t *p = linux_pci_get_device (h);
539
540   u32 icount;
541   rv = read (uf->file_descriptor, &icount, 4);
542
543   if (p->interrupt_handler)
544     p->interrupt_handler (h);
545
546   vlib_pci_intr_enable (h);
547
548   return /* no error */ 0;
549 }
550
551 static clib_error_t *
552 linux_pci_vfio_unmask_intx (linux_pci_device_t * d)
553 {
554   clib_error_t *err = 0;
555   struct vfio_irq_set i = {
556     .argsz = sizeof (struct vfio_irq_set),
557     .start = 0,
558     .count = 1,
559     .index = VFIO_PCI_INTX_IRQ_INDEX,
560     .flags = VFIO_IRQ_SET_DATA_NONE | VFIO_IRQ_SET_ACTION_UNMASK,
561   };
562
563   if (ioctl (d->fd, VFIO_DEVICE_SET_IRQS, &i) < 0)
564     {
565       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_SET_IRQS) '%U'",
566                                     format_vlib_pci_addr, &d->addr);
567     }
568   return err;
569 }
570
571 static clib_error_t *
572 linux_pci_uio_error_ready (clib_file_t * uf)
573 {
574   u32 error_index = (u32) uf->private_data;
575
576   return clib_error_return (0, "pci device %d: error", error_index);
577 }
578
579 static clib_error_t *
580 linux_pci_vfio_read_ready (clib_file_t * uf)
581 {
582   int __attribute__ ((unused)) rv;
583   vlib_pci_dev_handle_t h = uf->private_data;
584   linux_pci_device_t *p = linux_pci_get_device (h);
585
586   u64 icount;
587   rv = read (uf->file_descriptor, &icount, sizeof (icount));
588
589   if (p->interrupt_handler)
590     p->interrupt_handler (h);
591
592   linux_pci_vfio_unmask_intx (p);
593
594   return /* no error */ 0;
595 }
596
597 static clib_error_t *
598 linux_pci_vfio_error_ready (clib_file_t * uf)
599 {
600   u32 error_index = (u32) uf->private_data;
601
602   return clib_error_return (0, "pci device %d: error", error_index);
603 }
604
605 static clib_error_t *
606 add_device_uio (vlib_main_t * vm, linux_pci_device_t * p,
607                 vlib_pci_device_info_t * di, pci_device_registration_t * r)
608 {
609   clib_error_t *err = 0;
610   clib_file_t t = { 0 };
611   u8 *s = 0;
612
613   p->addr.as_u32 = di->addr.as_u32;
614   p->fd = -1;
615   p->type = LINUX_PCI_DEVICE_TYPE_UIO;
616
617   s = format (s, "%s/%U/config%c", sysfs_pci_dev_path,
618               format_vlib_pci_addr, &di->addr, 0);
619
620   p->config_fd = open ((char *) s, O_RDWR);
621   p->config_offset = 0;
622   vec_reset_length (s);
623
624   if (p->config_fd == -1)
625     {
626       err = clib_error_return_unix (0, "open '%s'", s);
627       goto error;
628     }
629
630   s = format (0, "%s/%U/uio", sysfs_pci_dev_path,
631               format_vlib_pci_addr, &di->addr);
632   foreach_directory_file ((char *) s, scan_uio_dir, p,  /* scan_dirs */
633                           1);
634   vec_reset_length (s);
635
636   s = format (s, "/dev/uio%d%c", p->uio_minor, 0);
637   p->fd = open ((char *) s, O_RDWR);
638   if (p->fd < 0)
639     {
640       err = clib_error_return_unix (0, "open '%s'", s);
641       goto error;
642     }
643
644   t.read_function = linux_pci_uio_read_ready;
645   t.file_descriptor = p->fd;
646   t.error_function = linux_pci_uio_error_ready;
647   t.private_data = p->handle;
648
649   p->clib_file_index = clib_file_add (&file_main, &t);
650   p->interrupt_handler = r->interrupt_handler;
651   err = r->init_function (vm, p->handle);
652
653 error:
654   free (s);
655   if (err)
656     {
657       if (p->config_fd != -1)
658         close (p->config_fd);
659       if (p->fd != -1)
660         close (p->fd);
661     }
662   return err;
663 }
664
665 static linux_pci_vfio_iommu_group_t *
666 get_vfio_iommu_group (int group)
667 {
668   linux_pci_main_t *lpm = &linux_pci_main;
669   uword *p;
670
671   p = hash_get (lpm->iommu_pool_index_by_group, group);
672
673   return p ? pool_elt_at_index (lpm->iommu_groups, p[0]) : 0;
674 }
675
676 static clib_error_t *
677 open_vfio_iommu_group (int group)
678 {
679   linux_pci_main_t *lpm = &linux_pci_main;
680   linux_pci_vfio_iommu_group_t *g;
681   clib_error_t *err = 0;
682   struct vfio_group_status group_status;
683   u8 *s = 0;
684   int fd;
685
686   g = get_vfio_iommu_group (group);
687   if (g)
688     {
689       g->refcnt++;
690       return 0;
691     }
692   s = format (s, "/dev/vfio/%u%c", group, 0);
693   fd = open ((char *) s, O_RDWR);
694   if (fd < 0)
695     return clib_error_return_unix (0, "open '%s'", s);
696
697   group_status.argsz = sizeof (group_status);
698   if (ioctl (fd, VFIO_GROUP_GET_STATUS, &group_status) < 0)
699     {
700       err = clib_error_return_unix (0, "ioctl(VFIO_GROUP_GET_STATUS) '%s'",
701                                     s);
702       goto error;
703     }
704
705   if (!(group_status.flags & VFIO_GROUP_FLAGS_VIABLE))
706     {
707       err = clib_error_return (0, "iommu group %d is not viable (not all "
708                                "devices in this group bound to vfio-pci)",
709                                group);
710       goto error;
711     }
712
713   if (ioctl (fd, VFIO_GROUP_SET_CONTAINER, &lpm->vfio_container_fd) < 0)
714     {
715       err = clib_error_return_unix (0, "ioctl(VFIO_GROUP_SET_CONTAINER) '%s'",
716                                     s);
717       goto error;
718     }
719
720   if (lpm->vfio_iommu_mode == 0)
721     {
722       if (ioctl (lpm->vfio_container_fd, VFIO_SET_IOMMU, VFIO_TYPE1_IOMMU) <
723           0)
724         {
725           err = clib_error_return_unix (0, "ioctl(VFIO_SET_IOMMU) "
726                                         "'/dev/vfio/vfio'");
727           goto error;
728         }
729       lpm->vfio_iommu_mode = VFIO_TYPE1_IOMMU;
730     }
731
732
733   pool_get (lpm->iommu_groups, g);
734   g->fd = fd;
735   g->refcnt = 1;
736   hash_set (lpm->iommu_pool_index_by_group, group, g - lpm->iommu_groups);
737   vec_free (s);
738   return 0;
739 error:
740   close (fd);
741   return err;
742 }
743
744 static clib_error_t *
745 add_device_vfio (vlib_main_t * vm, linux_pci_device_t * p,
746                  vlib_pci_device_info_t * di, pci_device_registration_t * r)
747 {
748   linux_pci_vfio_iommu_group_t *g;
749   struct vfio_device_info device_info = { 0 };
750   struct vfio_region_info reg = { 0 };
751   struct vfio_irq_info irq_info = { 0 };
752   clib_error_t *err = 0;
753   u8 *s = 0;
754
755   p->addr.as_u32 = di->addr.as_u32;
756   p->type = LINUX_PCI_DEVICE_TYPE_VFIO;
757
758   if (di->driver_name == 0 ||
759       (strcmp ("vfio-pci", (char *) di->driver_name) != 0))
760     return clib_error_return (0, "Device '%U' (iommu group %d) not bound to "
761                               "vfio-pci", format_vlib_pci_addr, &di->addr,
762                               di->iommu_group);
763
764   if ((err = open_vfio_iommu_group (di->iommu_group)))
765     return err;
766
767   g = get_vfio_iommu_group (di->iommu_group);
768
769   s = format (s, "%U%c", format_vlib_pci_addr, &di->addr, 0);
770   if ((p->fd = ioctl (g->fd, VFIO_GROUP_GET_DEVICE_FD, (char *) s)) < 0)
771     {
772       err = clib_error_return_unix (0, "ioctl(VFIO_GROUP_GET_DEVICE_FD) '%U'",
773                                     format_vlib_pci_addr, &di->addr);
774       goto error;
775     }
776   vec_reset_length (s);
777
778   device_info.argsz = sizeof (device_info);
779   if (ioctl (p->fd, VFIO_DEVICE_GET_INFO, &device_info) < 0)
780     {
781       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_INFO) '%U'",
782                                     format_vlib_pci_addr, &di->addr);
783       goto error;
784     }
785
786   irq_info.argsz = sizeof (struct vfio_irq_info);
787   irq_info.index = VFIO_PCI_INTX_IRQ_INDEX;
788   if (ioctl (p->fd, VFIO_DEVICE_GET_IRQ_INFO, &irq_info) < 0)
789     {
790       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_IRQ_INFO) "
791                                     "'%U'", format_vlib_pci_addr, &di->addr);
792       goto error;
793     }
794
795   /* reset if device supports it */
796   if (device_info.flags & VFIO_DEVICE_FLAGS_RESET)
797     if (ioctl (p->fd, VFIO_DEVICE_RESET) < 0)
798       {
799         err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_RESET) '%U'",
800                                       format_vlib_pci_addr, &di->addr);
801         goto error;
802       }
803
804   if ((irq_info.flags & VFIO_IRQ_INFO_EVENTFD) && irq_info.count == 1)
805     {
806       u8 buf[sizeof (struct vfio_irq_set) + sizeof (int)] = { 0 };
807       struct vfio_irq_set *irq_set = (struct vfio_irq_set *) buf;
808       clib_file_t t = { 0 };
809       int efd = eventfd (0, EFD_NONBLOCK);
810
811       irq_set->argsz = sizeof (buf);
812       irq_set->count = 1;
813       irq_set->index = VFIO_PCI_INTX_IRQ_INDEX;
814       irq_set->flags =
815         VFIO_IRQ_SET_DATA_EVENTFD | VFIO_IRQ_SET_ACTION_TRIGGER;
816       clib_memcpy (&irq_set->data, &efd, sizeof (int));
817
818       if (ioctl (p->fd, VFIO_DEVICE_SET_IRQS, irq_set) < 0)
819         {
820           err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_SET_IRQS) '%U'",
821                                         format_vlib_pci_addr, &di->addr);
822           goto error;
823         }
824
825       t.read_function = linux_pci_vfio_read_ready;
826       t.file_descriptor = efd;
827       t.error_function = linux_pci_vfio_error_ready;
828       t.private_data = p->handle;
829       p->clib_file_index = clib_file_add (&file_main, &t);
830
831       /* unmask the interrupt */
832       linux_pci_vfio_unmask_intx (p);
833     }
834
835   p->interrupt_handler = r->interrupt_handler;
836
837   reg.argsz = sizeof (struct vfio_region_info);
838   reg.index = VFIO_PCI_CONFIG_REGION_INDEX;
839   if (ioctl (p->fd, VFIO_DEVICE_GET_REGION_INFO, &reg) < 0)
840     {
841       err = clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_REGION_INFO) "
842                                     "'%U'", format_vlib_pci_addr, &di->addr);
843       goto error;
844     }
845   p->config_offset = reg.offset;
846   p->config_fd = p->fd;
847
848   err = r->init_function (vm, p->handle);
849
850 error:
851   vec_free (s);
852   if (err)
853     {
854       if (p->fd != -1)
855         close (p->fd);
856       if (p->config_fd != -1)
857         close (p->config_fd);
858     }
859   return err;
860 }
861
862 /* Configuration space read/write. */
863 clib_error_t *
864 vlib_pci_read_write_config (vlib_pci_dev_handle_t h,
865                             vlib_read_or_write_t read_or_write,
866                             uword address, void *data, u32 n_bytes)
867 {
868   linux_pci_device_t *p = linux_pci_get_device (h);
869   int n;
870
871   if (read_or_write == VLIB_READ)
872     n = pread (p->config_fd, data, n_bytes, p->config_offset + address);
873   else
874     n = pwrite (p->config_fd, data, n_bytes, p->config_offset + address);
875
876   if (n != n_bytes)
877     return clib_error_return_unix (0, "%s",
878                                    read_or_write == VLIB_READ
879                                    ? "read" : "write");
880
881   return 0;
882 }
883
884 static clib_error_t *
885 vlib_pci_map_region_int (vlib_pci_dev_handle_t h,
886                          u32 bar, u8 * addr, void **result)
887 {
888   linux_pci_device_t *p = linux_pci_get_device (h);
889   int fd = -1;
890   clib_error_t *error;
891   int flags = MAP_SHARED;
892   u64 size = 0, offset = 0;
893
894   ASSERT (bar <= 5);
895
896   error = 0;
897
898   if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
899     {
900       u8 *file_name;
901       struct stat stat_buf;
902       file_name = format (0, "%s/%U/resource%d%c", sysfs_pci_dev_path,
903                           format_vlib_pci_addr, &p->addr, bar, 0);
904
905       fd = open ((char *) file_name, O_RDWR);
906       if (fd < 0)
907         {
908           error = clib_error_return_unix (0, "open `%s'", file_name);
909           vec_free (file_name);
910           return error;
911         }
912
913       if (fstat (fd, &stat_buf) < 0)
914         {
915           error = clib_error_return_unix (0, "fstat `%s'", file_name);
916           vec_free (file_name);
917           close (fd);
918           return error;
919         }
920
921       vec_free (file_name);
922       if (addr != 0)
923         flags |= MAP_FIXED;
924       size = stat_buf.st_size;
925       offset = 0;
926     }
927   else if (p->type == LINUX_PCI_DEVICE_TYPE_VFIO)
928     {
929       struct vfio_region_info reg = { 0 };
930       reg.argsz = sizeof (struct vfio_region_info);
931       reg.index = bar;
932       if (ioctl (p->fd, VFIO_DEVICE_GET_REGION_INFO, &reg) < 0)
933         return clib_error_return_unix (0, "ioctl(VFIO_DEVICE_GET_INFO) "
934                                        "'%U'", format_vlib_pci_addr,
935                                        &p->addr);
936       fd = p->fd;
937       size = reg.size;
938       offset = reg.offset;
939     }
940   else
941     ASSERT (0);
942
943   *result = mmap (addr, size, PROT_READ | PROT_WRITE, flags, fd, offset);
944   if (*result == (void *) -1)
945     {
946       error = clib_error_return_unix (0, "mmap `BAR%u'", bar);
947       if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
948         close (fd);
949       return error;
950     }
951
952   /* *INDENT-OFF* */
953   vec_validate_init_empty (p->regions, bar,
954                            (linux_pci_region_t) { .fd = -1});
955   /* *INDENT-ON* */
956   if (p->type == LINUX_PCI_DEVICE_TYPE_UIO)
957     p->regions[bar].fd = fd;
958   p->regions[bar].addr = *result;
959   p->regions[bar].size = size;
960   return 0;
961 }
962
963 clib_error_t *
964 vlib_pci_map_region (vlib_pci_dev_handle_t h, u32 resource, void **result)
965 {
966   return (vlib_pci_map_region_int (h, resource, 0 /* addr */ , result));
967 }
968
969 clib_error_t *
970 vlib_pci_map_region_fixed (vlib_pci_dev_handle_t h, u32 resource, u8 * addr,
971                            void **result)
972 {
973   return (vlib_pci_map_region_int (h, resource, addr, result));
974 }
975
976 void
977 init_device_from_registered (vlib_main_t * vm, vlib_pci_device_info_t * di)
978 {
979   vlib_pci_main_t *pm = &pci_main;
980   linux_pci_main_t *lpm = &linux_pci_main;
981   pci_device_registration_t *r;
982   pci_device_id_t *i;
983   clib_error_t *err = 0;
984   linux_pci_device_t *p;
985
986   pool_get (lpm->linux_pci_devices, p);
987   p->handle = p - lpm->linux_pci_devices;
988
989   r = pm->pci_device_registrations;
990
991   while (r)
992     {
993       for (i = r->supported_devices; i->vendor_id != 0; i++)
994         if (i->vendor_id == di->vendor_id && i->device_id == di->device_id)
995           {
996             if (di->iommu_group != -1)
997               err = add_device_vfio (vm, p, di, r);
998             else
999               err = add_device_uio (vm, p, di, r);
1000
1001             if (err)
1002               clib_error_report (err);
1003             else
1004               return;
1005           }
1006       r = r->next_registration;
1007     }
1008
1009   /* No driver, close the PCI config-space FD */
1010   memset (p, 0, sizeof (linux_pci_device_t));
1011   pool_put (lpm->linux_pci_devices, p);
1012 }
1013
1014 static clib_error_t *
1015 scan_pci_addr (void *arg, u8 * dev_dir_name, u8 * ignored)
1016 {
1017   vlib_pci_addr_t addr, **addrv = arg;
1018   unformat_input_t input;
1019   clib_error_t *err = 0;
1020
1021   unformat_init_string (&input, (char *) dev_dir_name,
1022                         vec_len (dev_dir_name));
1023
1024   if (!unformat (&input, "/sys/bus/pci/devices/%U",
1025                  unformat_vlib_pci_addr, &addr))
1026     err = clib_error_return (0, "unformat error `%v`", dev_dir_name);
1027
1028   unformat_free (&input);
1029
1030   if (err)
1031     return err;
1032
1033   vec_add1 (*addrv, addr);
1034   return 0;
1035 }
1036
1037 static int
1038 pci_addr_cmp (void *v1, void *v2)
1039 {
1040   vlib_pci_addr_t *a1 = v1;
1041   vlib_pci_addr_t *a2 = v2;
1042
1043   if (a1->domain > a2->domain)
1044     return 1;
1045   if (a1->domain < a2->domain)
1046     return -1;
1047   if (a1->bus > a2->bus)
1048     return 1;
1049   if (a1->bus < a2->bus)
1050     return -1;
1051   if (a1->slot > a2->slot)
1052     return 1;
1053   if (a1->slot < a2->slot)
1054     return -1;
1055   if (a1->function > a2->function)
1056     return 1;
1057   if (a1->function < a2->function)
1058     return -1;
1059   return 0;
1060 }
1061
1062 vlib_pci_addr_t *
1063 vlib_pci_get_all_dev_addrs ()
1064 {
1065   vlib_pci_addr_t *addrs = 0;
1066   clib_error_t *err;
1067   err = foreach_directory_file ((char *) sysfs_pci_dev_path, scan_pci_addr,
1068                                 &addrs, /* scan_dirs */ 0);
1069   if (err)
1070     {
1071       vec_free (addrs);
1072       return 0;
1073     }
1074
1075   vec_sort_with_function (addrs, pci_addr_cmp);
1076
1077   return addrs;
1078 }
1079
1080 clib_error_t *
1081 linux_pci_init (vlib_main_t * vm)
1082 {
1083   vlib_pci_main_t *pm = &pci_main;
1084   linux_pci_main_t *lpm = &linux_pci_main;
1085   vlib_pci_addr_t *addr = 0, *addrs;
1086   clib_error_t *error;
1087   int fd;
1088
1089   pm->vlib_main = vm;
1090
1091   if ((error = vlib_call_init_function (vm, unix_input_init)))
1092     return error;
1093
1094   ASSERT (sizeof (vlib_pci_addr_t) == sizeof (u32));
1095
1096   fd = open ("/dev/vfio/vfio", O_RDWR);
1097
1098   if ((fd != -1) && (ioctl (fd, VFIO_GET_API_VERSION) != VFIO_API_VERSION))
1099     {
1100       close (fd);
1101       fd = -1;
1102     }
1103
1104   if ((fd != -1) && (ioctl (fd, VFIO_CHECK_EXTENSION, VFIO_TYPE1_IOMMU) == 0))
1105     {
1106       close (fd);
1107       fd = -1;
1108     }
1109
1110   lpm->vfio_container_fd = fd;
1111   lpm->iommu_pool_index_by_group = hash_create (0, sizeof (uword));
1112
1113   addrs = vlib_pci_get_all_dev_addrs ();
1114   /* *INDENT-OFF* */
1115   vec_foreach (addr, addrs)
1116     {
1117       vlib_pci_device_info_t *d;
1118       if ((d = vlib_pci_get_device_info (addr, 0)))
1119         {
1120           init_device_from_registered (vm, d);
1121           vlib_pci_free_device_info (d);
1122         }
1123     }
1124   /* *INDENT-ON* */
1125
1126   return error;
1127 }
1128
1129 VLIB_INIT_FUNCTION (linux_pci_init);
1130
1131 /*
1132  * fd.io coding-style-patch-verification: ON
1133  *
1134  * Local Variables:
1135  * eval: (c-set-style "gnu")
1136  * End:
1137  */