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