module.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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 = snprintf(str, len, "C%s", compat);
  34. tsize += csize;
  35. if (csize >= len)
  36. continue;
  37. for (c = str; c; ) {
  38. c = strchr(c, ' ');
  39. if (c)
  40. *c++ = '_';
  41. }
  42. len -= csize;
  43. str += csize;
  44. }
  45. return tsize;
  46. }
  47. int of_request_module(const struct device_node *np)
  48. {
  49. char *str;
  50. ssize_t size;
  51. int ret;
  52. if (!np)
  53. return -ENODEV;
  54. size = of_modalias(np, NULL, 0);
  55. if (size < 0)
  56. return size;
  57. /* Reserve an additional byte for the trailing '\0' */
  58. size++;
  59. str = kmalloc(size, GFP_KERNEL);
  60. if (!str)
  61. return -ENOMEM;
  62. of_modalias(np, str, size);
  63. str[size - 1] = '\0';
  64. ret = request_module(str);
  65. kfree(str);
  66. return ret;
  67. }
  68. EXPORT_SYMBOL_GPL(of_request_module);