module.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Linux kernel module helpers.
  4. */
  5. #include <linux/of.h>
  6. #include <linux/module.h>
  7. #include <linux/slab.h>
  8. #include <linux/string.h>
  9. ssize_t of_modalias(const struct device_node *np, char *str, ssize_t len)
  10. {
  11. const char *compat;
  12. char *c;
  13. struct property *p;
  14. ssize_t csize;
  15. ssize_t tsize;
  16. /*
  17. * Prevent a kernel oops in vsnprintf() -- it only allows passing a
  18. * NULL ptr when the length is also 0. Also filter out the negative
  19. * lengths...
  20. */
  21. if ((len > 0 && !str) || len < 0)
  22. return -EINVAL;
  23. /* Name & Type */
  24. /* %p eats all alphanum characters, so %c must be used here */
  25. csize = snprintf(str, len, "of:N%pOFn%c%s", np, 'T',
  26. of_node_get_device_type(np));
  27. tsize = csize;
  28. if (csize >= len)
  29. csize = len > 0 ? len - 1 : 0;
  30. len -= csize;
  31. str += csize;
  32. of_property_for_each_string(np, "compatible", p, compat) {
  33. csize = strlen(compat) + 1;
  34. tsize += csize;
  35. if (csize >= len)
  36. continue;
  37. csize = snprintf(str, len, "C%s", compat);
  38. for (c = str; c; ) {
  39. c = strchr(c, ' ');
  40. if (c)
  41. *c++ = '_';
  42. }
  43. len -= csize;
  44. str += csize;
  45. }
  46. return tsize;
  47. }
  48. int of_request_module(const struct device_node *np)
  49. {
  50. char *str;
  51. ssize_t size;
  52. int ret;
  53. if (!np)
  54. return -ENODEV;
  55. size = of_modalias(np, NULL, 0);
  56. if (size < 0)
  57. return size;
  58. /* Reserve an additional byte for the trailing '\0' */
  59. size++;
  60. str = kmalloc(size, GFP_KERNEL);
  61. if (!str)
  62. return -ENOMEM;
  63. of_modalias(np, str, size);
  64. str[size - 1] = '\0';
  65. ret = request_module(str);
  66. kfree(str);
  67. return ret;
  68. }
  69. EXPORT_SYMBOL_GPL(of_request_module);