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