debugfs.c 2.1 KB

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