vlib: move linux-specific code to vlib/linux
[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 <vlib/vlib.h>
41 #include <vlib/pci/pci.h>
42 #include <vlib/unix/unix.h>
43 #include <vlib/linux/sysfs.h>
44
45 #include <sys/types.h>
46 #include <sys/stat.h>
47 #include <fcntl.h>
48 #include <dirent.h>
49 #include <sys/ioctl.h>
50 #include <net/if.h>
51 #include <linux/ethtool.h>
52 #include <linux/sockios.h>
53
54 typedef struct
55 {
56   /* /sys/bus/pci/devices/... directory name for this device. */
57   u8 *dev_dir_name;
58
59   /* Resource file descriptors. */
60   int *resource_fds;
61
62   /* File descriptor for config space read/write. */
63   int config_fd;
64
65   /* File descriptor for /dev/uio%d */
66   int uio_fd;
67
68   /* Minor device for uio device. */
69   u32 uio_minor;
70
71   /* Index given by unix_file_add. */
72   u32 unix_file_index;
73
74 } linux_pci_device_t;
75
76 /* Pool of PCI devices. */
77 typedef struct
78 {
79   vlib_main_t *vlib_main;
80   linux_pci_device_t *linux_pci_devices;
81 } linux_pci_main_t;
82
83 extern linux_pci_main_t linux_pci_main;
84
85 /* Call to allocate/initialize the pci subsystem.
86    This is not an init function so that users can explicitly enable
87    pci only when it's needed. */
88 clib_error_t *pci_bus_init (vlib_main_t * vm);
89
90 clib_error_t *vlib_pci_bind_to_uio (vlib_pci_device_t * d,
91                                     char *uio_driver_name);
92
93 linux_pci_main_t linux_pci_main;
94
95 clib_error_t *
96 vlib_pci_bind_to_uio (vlib_pci_device_t * d, char *uio_driver_name)
97 {
98   clib_error_t *error = 0;
99   u8 *s = 0, *driver_name = 0;
100   DIR *dir = 0;
101   struct dirent *e;
102   int fd, clear_driver_override = 0;
103   u8 *dev_dir_name = format (0, "/sys/bus/pci/devices/%U",
104                              format_vlib_pci_addr, &d->bus_address);
105
106   s = format (s, "%v/driver%c", dev_dir_name, 0);
107   driver_name = vlib_sysfs_link_to_name ((char *) s);
108   vec_reset_length (s);
109
110   if (driver_name &&
111       ((strcmp ("vfio-pci", (char *) driver_name) == 0) ||
112        (strcmp ("uio_pci_generic", (char *) driver_name) == 0) ||
113        (strcmp ("igb_uio", (char *) driver_name) == 0)))
114     goto done;
115
116   /* walk trough all linux interfaces and if interface belonging to
117      this device is founf check if interface is admin up  */
118   dir = opendir ("/sys/class/net");
119   s = format (s, "%U%c", format_vlib_pci_addr, &d->bus_address, 0);
120
121   if (!dir)
122     {
123       error = clib_error_return (0, "Skipping PCI device %U: failed to "
124                                  "read /sys/class/net",
125                                  format_vlib_pci_addr, &d->bus_address);
126       goto done;
127     }
128
129   fd = socket (PF_INET, SOCK_DGRAM, 0);
130   if (fd < 0)
131     {
132       error = clib_error_return_unix (0, "socket");
133       goto done;
134     }
135
136   while ((e = readdir (dir)))
137     {
138       struct ifreq ifr;
139       struct ethtool_drvinfo drvinfo;
140
141       if (e->d_name[0] == '.')  /* skip . and .. */
142         continue;
143
144       memset (&ifr, 0, sizeof ifr);
145       memset (&drvinfo, 0, sizeof drvinfo);
146       ifr.ifr_data = (char *) &drvinfo;
147       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
148       drvinfo.cmd = ETHTOOL_GDRVINFO;
149       if (ioctl (fd, SIOCETHTOOL, &ifr) < 0)
150         {
151           /* Some interfaces (eg "lo") don't support this ioctl */
152           if ((errno != ENOTSUP) && (errno != ENODEV))
153             clib_unix_warning ("ioctl fetch intf %s bus info error",
154                                e->d_name);
155           continue;
156         }
157
158       if (strcmp ((char *) s, drvinfo.bus_info))
159         continue;
160
161       memset (&ifr, 0, sizeof (ifr));
162       strncpy (ifr.ifr_name, e->d_name, IFNAMSIZ - 1);
163       if (ioctl (fd, SIOCGIFFLAGS, &ifr) < 0)
164         {
165           error = clib_error_return_unix (0, "ioctl fetch intf %s flags",
166                                           e->d_name);
167           close (fd);
168           goto done;
169         }
170
171       if (ifr.ifr_flags & IFF_UP)
172         {
173           error = clib_error_return (0, "Skipping PCI device %U as host "
174                                      "interface %s is up",
175                                      format_vlib_pci_addr, &d->bus_address,
176                                      e->d_name);
177           close (fd);
178           goto done;
179         }
180     }
181
182   close (fd);
183   vec_reset_length (s);
184
185   s = format (s, "%v/driver/unbind%c", dev_dir_name, 0);
186   vlib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, &d->bus_address);
187   vec_reset_length (s);
188
189   s = format (s, "%v/driver_override%c", dev_dir_name, 0);
190   if (access ((char *) s, F_OK) == 0)
191     {
192       vlib_sysfs_write ((char *) s, "%s", uio_driver_name);
193       clear_driver_override = 1;
194     }
195   else
196     {
197       vec_reset_length (s);
198       s = format (s, "/sys/bus/pci/drivers/%s/new_id%c", uio_driver_name, 0);
199       vlib_sysfs_write ((char *) s, "0x%04x 0x%04x", d->vendor_id,
200                         d->device_id);
201     }
202   vec_reset_length (s);
203
204   s = format (s, "/sys/bus/pci/drivers/%s/bind%c", uio_driver_name, 0);
205   vlib_sysfs_write ((char *) s, "%U", format_vlib_pci_addr, &d->bus_address);
206   vec_reset_length (s);
207
208   if (clear_driver_override)
209     {
210       s = format (s, "%v/driver_override%c", dev_dir_name, 0);
211       vlib_sysfs_write ((char *) s, "%c", 0);
212       vec_reset_length (s);
213     }
214
215 done:
216   closedir (dir);
217   vec_free (s);
218   vec_free (dev_dir_name);
219   vec_free (driver_name);
220   return error;
221 }
222
223
224 static clib_error_t *
225 scan_uio_dir (void *arg, u8 * path_name, u8 * file_name)
226 {
227   linux_pci_device_t *l = arg;
228   unformat_input_t input;
229
230   unformat_init_string (&input, (char *) file_name, vec_len (file_name));
231
232   if (!unformat (&input, "uio%d", &l->uio_minor))
233     abort ();
234
235   unformat_free (&input);
236   return 0;
237 }
238
239 static clib_error_t *
240 linux_pci_uio_read_ready (unix_file_t * uf)
241 {
242   vlib_pci_main_t *pm = &pci_main;
243   vlib_pci_device_t *d;
244   int __attribute__ ((unused)) rv;
245
246   u32 icount;
247   rv = read (uf->file_descriptor, &icount, 4);
248
249   d = pool_elt_at_index (pm->pci_devs, uf->private_data);
250
251   if (d->interrupt_handler)
252     d->interrupt_handler (d);
253
254   vlib_pci_intr_enable (d);
255
256   return /* no error */ 0;
257 }
258
259 static clib_error_t *
260 linux_pci_uio_error_ready (unix_file_t * uf)
261 {
262   u32 error_index = (u32) uf->private_data;
263
264   return clib_error_return (0, "pci device %d: error", error_index);
265 }
266
267 static void
268 add_device (vlib_pci_device_t * dev, linux_pci_device_t * pdev)
269 {
270   vlib_pci_main_t *pm = &pci_main;
271   linux_pci_main_t *lpm = &linux_pci_main;
272   linux_pci_device_t *l;
273
274   pool_get (lpm->linux_pci_devices, l);
275   l[0] = pdev[0];
276
277   l->dev_dir_name = vec_dup (l->dev_dir_name);
278
279   dev->os_handle = l - lpm->linux_pci_devices;
280
281   {
282     u8 *uio_dir = format (0, "%s/uio", l->dev_dir_name);
283     foreach_directory_file ((char *) uio_dir, scan_uio_dir, l,  /* scan_dirs */
284                             1);
285     vec_free (uio_dir);
286   }
287
288   {
289     char *uio_name = (char *) format (0, "/dev/uio%d%c", l->uio_minor, 0);
290     l->uio_fd = open (uio_name, O_RDWR);
291     if (l->uio_fd < 0)
292       clib_unix_error ("open `%s'", uio_name);
293     vec_free (uio_name);
294   }
295
296   {
297     unix_file_t template = { 0 };
298     unix_main_t *um = &unix_main;
299
300     template.read_function = linux_pci_uio_read_ready;
301     template.file_descriptor = l->uio_fd;
302     template.error_function = linux_pci_uio_error_ready;
303     template.private_data = dev - pm->pci_devs;
304
305     l->unix_file_index = unix_file_add (um, &template);
306   }
307 }
308
309 static void
310 linux_pci_device_free (linux_pci_device_t * l)
311 {
312   int i;
313   for (i = 0; i < vec_len (l->resource_fds); i++)
314     if (l->resource_fds[i] > 0)
315       close (l->resource_fds[i]);
316   if (l->config_fd > 0)
317     close (l->config_fd);
318   if (l->uio_fd > 0)
319     close (l->uio_fd);
320   vec_free (l->resource_fds);
321   vec_free (l->dev_dir_name);
322 }
323
324 /* Configuration space read/write. */
325 clib_error_t *
326 vlib_pci_read_write_config (vlib_pci_device_t * dev,
327                             vlib_read_or_write_t read_or_write,
328                             uword address, void *data, u32 n_bytes)
329 {
330   linux_pci_main_t *lpm = &linux_pci_main;
331   linux_pci_device_t *p;
332   int n;
333
334   p = pool_elt_at_index (lpm->linux_pci_devices, dev->os_handle);
335
336   if (read_or_write == VLIB_READ)
337     n = pread (p->config_fd, data, n_bytes, address);
338   else
339     n = pwrite (p->config_fd, data, n_bytes, address);
340
341   if (n != n_bytes)
342     return clib_error_return_unix (0, "%s",
343                                    read_or_write == VLIB_READ
344                                    ? "read" : "write");
345
346   return 0;
347 }
348
349 static clib_error_t *
350 os_map_pci_resource_internal (uword os_handle,
351                               u32 resource, u8 * addr, void **result)
352 {
353   linux_pci_main_t *pm = &linux_pci_main;
354   linux_pci_device_t *p;
355   struct stat stat_buf;
356   u8 *file_name;
357   int fd;
358   clib_error_t *error;
359   int flags = MAP_SHARED;
360
361   error = 0;
362   p = pool_elt_at_index (pm->linux_pci_devices, os_handle);
363
364   file_name = format (0, "%v/resource%d%c", p->dev_dir_name, resource, 0);
365   fd = open ((char *) file_name, O_RDWR);
366   if (fd < 0)
367     {
368       error = clib_error_return_unix (0, "open `%s'", file_name);
369       goto done;
370     }
371
372   if (fstat (fd, &stat_buf) < 0)
373     {
374       error = clib_error_return_unix (0, "fstat `%s'", file_name);
375       goto done;
376     }
377
378   vec_validate (p->resource_fds, resource);
379   p->resource_fds[resource] = fd;
380   if (addr != 0)
381     flags |= MAP_FIXED;
382
383   *result = mmap (addr,
384                   /* size */ stat_buf.st_size,
385                   PROT_READ | PROT_WRITE, flags,
386                   /* file */ fd,
387                   /* offset */ 0);
388   if (*result == (void *) -1)
389     {
390       error = clib_error_return_unix (0, "mmap `%s'", file_name);
391       goto done;
392     }
393
394 done:
395   if (error)
396     {
397       if (fd >= 0)
398         close (fd);
399     }
400   vec_free (file_name);
401   return error;
402 }
403
404 clib_error_t *
405 vlib_pci_map_resource (vlib_pci_device_t * dev, u32 resource, void **result)
406 {
407   return (os_map_pci_resource_internal
408           (dev->os_handle, resource, 0 /* addr */ ,
409            result));
410 }
411
412 clib_error_t *
413 vlib_pci_map_resource_fixed (vlib_pci_device_t * dev,
414                              u32 resource, u8 * addr, void **result)
415 {
416   return (os_map_pci_resource_internal
417           (dev->os_handle, resource, addr, result));
418 }
419
420 void
421 vlib_pci_free_device (vlib_pci_device_t * dev)
422 {
423   linux_pci_main_t *pm = &linux_pci_main;
424   linux_pci_device_t *l;
425
426   l = pool_elt_at_index (pm->linux_pci_devices, dev->os_handle);
427   linux_pci_device_free (l);
428   pool_put (pm->linux_pci_devices, l);
429 }
430
431 pci_device_registration_t * __attribute__ ((unused))
432 pci_device_next_registered (pci_device_registration_t * r)
433 {
434   uword i;
435
436   /* Null vendor id marks end of initialized list. */
437   for (i = 0; r->supported_devices[i].vendor_id != 0; i++)
438     ;
439
440   return clib_elf_section_data_next (r, i * sizeof (r->supported_devices[0]));
441 }
442
443 static clib_error_t *
444 init_device_from_registered (vlib_main_t * vm,
445                              vlib_pci_device_t * dev,
446                              linux_pci_device_t * pdev)
447 {
448   vlib_pci_main_t *pm = &pci_main;
449   pci_device_registration_t *r;
450   pci_device_id_t *i;
451   clib_error_t *error;
452
453   r = pm->pci_device_registrations;
454
455   while (r)
456     {
457       for (i = r->supported_devices; i->vendor_id != 0; i++)
458         if (i->vendor_id == dev->vendor_id && i->device_id == dev->device_id)
459           {
460             error = vlib_pci_bind_to_uio (dev, "uio_pci_generic");
461             if (error)
462               {
463                 clib_error_report (error);
464                 continue;
465               }
466
467             add_device (dev, pdev);
468             dev->interrupt_handler = r->interrupt_handler;
469             return r->init_function (vm, dev);
470           }
471       r = r->next_registration;
472     }
473   /* No driver, close the PCI config-space FD */
474   close (pdev->config_fd);
475   return 0;
476 }
477
478 static clib_error_t *
479 init_device (vlib_main_t * vm,
480              vlib_pci_device_t * dev, linux_pci_device_t * pdev)
481 {
482   return init_device_from_registered (vm, dev, pdev);
483 }
484
485 static clib_error_t *
486 scan_device (void *arg, u8 * dev_dir_name, u8 * ignored)
487 {
488   vlib_main_t *vm = arg;
489   vlib_pci_main_t *pm = &pci_main;
490   int fd;
491   u8 *f;
492   clib_error_t *error = 0;
493   vlib_pci_device_t *dev;
494   linux_pci_device_t pdev = { 0 };
495   u32 tmp;
496
497   f = format (0, "%v/config%c", dev_dir_name, 0);
498   fd = open ((char *) f, O_RDWR);
499
500   /* Try read-only access if write fails. */
501   if (fd < 0)
502     fd = open ((char *) f, O_RDONLY);
503
504   if (fd < 0)
505     {
506       error = clib_error_return_unix (0, "open `%s'", f);
507       goto done;
508     }
509
510   pool_get (pm->pci_devs, dev);
511
512   /* You can only read more that 64 bytes of config space as root; so we try to
513      read the full space but fall back to just the first 64 bytes. */
514   if (read (fd, &dev->config_data, sizeof (dev->config_data)) !=
515       sizeof (dev->config_data)
516       && read (fd, &dev->config0,
517                sizeof (dev->config0)) != sizeof (dev->config0))
518     {
519       pool_put (pm->pci_devs, dev);
520       error = clib_error_return_unix (0, "read `%s'", f);
521       close (fd);
522       goto done;
523     }
524
525   {
526     static pci_config_header_t all_ones;
527     if (all_ones.vendor_id == 0)
528       memset (&all_ones, ~0, sizeof (all_ones));
529
530     if (!memcmp (&dev->config0.header, &all_ones, sizeof (all_ones)))
531       {
532         pool_put (pm->pci_devs, dev);
533         error = clib_error_return (0, "invalid PCI config for `%s'", f);
534         close (fd);
535         goto done;
536       }
537   }
538
539   if (dev->config0.header.header_type == 0)
540     pci_config_type0_little_to_host (&dev->config0);
541   else
542     pci_config_type1_little_to_host (&dev->config1);
543
544   /* Parse bus, dev, function from directory name. */
545   {
546     unformat_input_t input;
547
548     unformat_init_string (&input, (char *) dev_dir_name,
549                           vec_len (dev_dir_name));
550
551     if (!unformat (&input, "/sys/bus/pci/devices/%U",
552                    unformat_vlib_pci_addr, &dev->bus_address))
553       abort ();
554
555     unformat_free (&input);
556
557   }
558
559
560   pdev.config_fd = fd;
561   pdev.dev_dir_name = dev_dir_name;
562
563   hash_set (pm->pci_dev_index_by_pci_addr, dev->bus_address.as_u32,
564             dev - pm->pci_devs);
565
566   vec_reset_length (f);
567   f = format (f, "%v/vpd%c", dev_dir_name, 0);
568   fd = open ((char *) f, O_RDONLY);
569   if (fd >= 0)
570     {
571       while (1)
572         {
573           u8 tag[3];
574           u8 *data = 0;
575           int len;
576
577           if (read (fd, &tag, 3) != 3)
578             break;
579
580           if (tag[0] != 0x82 && tag[0] != 0x90 && tag[0] != 0x91)
581             break;
582
583           len = (tag[2] << 8) | tag[1];
584           vec_validate (data, len);
585
586           if (read (fd, data, len) != len)
587             {
588               vec_free (data);
589               break;
590             }
591           if (tag[0] == 0x82)
592             dev->product_name = data;
593           else if (tag[0] == 0x90)
594             dev->vpd_r = data;
595           else if (tag[0] == 0x91)
596             dev->vpd_w = data;
597
598           data = 0;
599         }
600       close (fd);
601     }
602
603   dev->numa_node = -1;
604   vec_reset_length (f);
605   f = format (f, "%v/numa_node%c", dev_dir_name, 0);
606   vlib_sysfs_read ((char *) f, "%u", &dev->numa_node);
607
608   vec_reset_length (f);
609   f = format (f, "%v/class%c", dev_dir_name, 0);
610   vlib_sysfs_read ((char *) f, "0x%x", &tmp);
611   dev->device_class = tmp >> 8;
612
613   vec_reset_length (f);
614   f = format (f, "%v/vendor%c", dev_dir_name, 0);
615   vlib_sysfs_read ((char *) f, "0x%x", &tmp);
616   dev->vendor_id = tmp;
617
618   vec_reset_length (f);
619   f = format (f, "%v/device%c", dev_dir_name, 0);
620   vlib_sysfs_read ((char *) f, "0x%x", &tmp);
621   dev->device_id = tmp;
622
623   error = init_device (vm, dev, &pdev);
624
625   vec_reset_length (f);
626   f = format (f, "%v/driver%c", dev_dir_name, 0);
627   dev->driver_name = vlib_sysfs_link_to_name ((char *) f);
628
629 done:
630   vec_free (f);
631   return error;
632 }
633
634 clib_error_t *
635 linux_pci_init (vlib_main_t * vm)
636 {
637   vlib_pci_main_t *pm = &pci_main;
638   clib_error_t *error;
639
640   pm->vlib_main = vm;
641
642   if ((error = vlib_call_init_function (vm, unix_input_init)))
643     return error;
644
645   ASSERT (sizeof (vlib_pci_addr_t) == sizeof (u32));
646   pm->pci_dev_index_by_pci_addr = hash_create (0, sizeof (uword));
647
648   error = foreach_directory_file ("/sys/bus/pci/devices", scan_device, vm,
649                                   /* scan_dirs */ 0);
650
651   /* Complain and continue. might not be root, etc. */
652   if (error)
653     clib_error_report (error);
654
655   return error;
656 }
657
658 VLIB_INIT_FUNCTION (linux_pci_init);
659
660 /*
661  * fd.io coding-style-patch-verification: ON
662  *
663  * Local Variables:
664  * eval: (c-set-style "gnu")
665  * End:
666  */