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