debugfs.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. #include <errno.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <string.h>
  5. #include <stdbool.h>
  6. #include <sys/vfs.h>
  7. #include <sys/mount.h>
  8. #include <linux/kernel.h>
  9. #include "debugfs.h"
  10. char debugfs_mountpoint[PATH_MAX + 1] = "/sys/kernel/debug";
  11. static const char * const debugfs_known_mountpoints[] = {
  12. "/sys/kernel/debug/",
  13. "/debug/",
  14. 0,
  15. };
  16. static bool debugfs_found;
  17. /* find the path to the mounted debugfs */
  18. const char *debugfs_find_mountpoint(void)
  19. {
  20. const char * const *ptr;
  21. char type[100];
  22. FILE *fp;
  23. if (debugfs_found)
  24. return (const char *)debugfs_mountpoint;
  25. ptr = debugfs_known_mountpoints;
  26. while (*ptr) {
  27. if (debugfs_valid_mountpoint(*ptr) == 0) {
  28. debugfs_found = true;
  29. strcpy(debugfs_mountpoint, *ptr);
  30. return debugfs_mountpoint;
  31. }
  32. ptr++;
  33. }
  34. /* give up and parse /proc/mounts */
  35. fp = fopen("/proc/mounts", "r");
  36. if (fp == NULL)
  37. return NULL;
  38. while (fscanf(fp, "%*s %" STR(PATH_MAX) "s %99s %*s %*d %*d\n",
  39. debugfs_mountpoint, type) == 2) {
  40. if (strcmp(type, "debugfs") == 0)
  41. break;
  42. }
  43. fclose(fp);
  44. if (strcmp(type, "debugfs") != 0)
  45. return NULL;
  46. debugfs_found = true;
  47. return debugfs_mountpoint;
  48. }
  49. /* verify that a mountpoint is actually a debugfs instance */
  50. int debugfs_valid_mountpoint(const char *debugfs)
  51. {
  52. struct statfs st_fs;
  53. if (statfs(debugfs, &st_fs) < 0)
  54. return -ENOENT;
  55. else if (st_fs.f_type != (long) DEBUGFS_MAGIC)
  56. return -ENOENT;
  57. return 0;
  58. }
  59. /* mount the debugfs somewhere if it's not mounted */
  60. char *debugfs_mount(const char *mountpoint)
  61. {
  62. /* see if it's already mounted */
  63. if (debugfs_find_mountpoint())
  64. goto out;
  65. /* if not mounted and no argument */
  66. if (mountpoint == NULL) {
  67. /* see if environment variable set */
  68. mountpoint = getenv(PERF_DEBUGFS_ENVIRONMENT);
  69. /* if no environment variable, use default */
  70. if (mountpoint == NULL)
  71. mountpoint = "/sys/kernel/debug";
  72. }
  73. if (mount(NULL, mountpoint, "debugfs", 0, NULL) < 0)
  74. return NULL;
  75. /* save the mountpoint */
  76. debugfs_found = true;
  77. strncpy(debugfs_mountpoint, mountpoint, sizeof(debugfs_mountpoint));
  78. out:
  79. return debugfs_mountpoint;
  80. }