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