debugfs.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. Adapted from: https://github.com/chadversary/debugfs-tutorial/blob/47b3cf7ca47208c61ccb51b27aac6f9f932bfe0b/example1/debugfs_example1.c
  3. Usage:
  4. /debugfs.sh
  5. Requires `CONFIG_DEBUG_FS=y`.
  6. Only the more basic fops can be implemented in debugfs, e.g. mmap is never called:
  7. - https://patchwork.kernel.org/patch/9252557/
  8. - https://github.com/torvalds/linux/blob/v4.9/fs/debugfs/file.c#L212
  9. */
  10. #include <linux/debugfs.h>
  11. #include <linux/kernel.h>
  12. #include <linux/module.h>
  13. #include <uapi/linux/stat.h> /* S_IRUSR */
  14. static struct dentry *dir, *toplevel_file;
  15. static u32 value = 42;
  16. /* This basically re-implents the write operation of debugfs_create_u32,
  17. * it is just an excuse to illustrate a fop. */
  18. static ssize_t write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
  19. {
  20. int ret;
  21. unsigned long long res;
  22. /* https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel */
  23. ret = kstrtoull_from_user(buf, len, 10, &res);
  24. if (ret) {
  25. /* Negative error code. */
  26. return ret;
  27. } else {
  28. value = res;
  29. *off= len;
  30. return len;
  31. }
  32. }
  33. static const struct file_operations fops = {
  34. .owner = THIS_MODULE,
  35. .write = write,
  36. };
  37. static int myinit(void)
  38. {
  39. struct dentry *file;
  40. dir = debugfs_create_dir("lkmc_debugfs", 0);
  41. if (!dir) {
  42. pr_alert("debugfs_create_dir failed");
  43. return -1;
  44. }
  45. file = debugfs_create_u32("myfile", S_IRUSR | S_IWUSR, dir, &value);
  46. if (!file) {
  47. pr_alert("debugfs_create_u32 failed");
  48. return -1;
  49. }
  50. /* Created on the toplevel of the debugfs mount,
  51. * and with explicit fops instead of a fixed integer value. */
  52. toplevel_file = debugfs_create_file(
  53. "lkmc_debugfs_file", S_IWUSR, NULL, NULL, &fops);
  54. if (!toplevel_file) {
  55. return -1;
  56. }
  57. return 0;
  58. }
  59. static void myexit(void)
  60. {
  61. debugfs_remove_recursive(dir);
  62. debugfs_remove(toplevel_file);
  63. }
  64. module_init(myinit)
  65. module_exit(myexit)
  66. MODULE_LICENSE("GPL");