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