debugfs.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /* https://cirosantilli.com/linux-kernel-module-cheat#debugfs */
  2. #include <linux/debugfs.h>
  3. #include <linux/kernel.h>
  4. #include <linux/module.h>
  5. #include <uapi/linux/stat.h> /* S_IRUSR */
  6. static struct dentry *dir, *toplevel_file;
  7. static u32 value = 42;
  8. /* This basically re-implents the write operation of debugfs_create_u32,
  9. * it is just an excuse to illustrate a fop. */
  10. static ssize_t write(struct file *filp, const char __user *buf, size_t len, loff_t *off)
  11. {
  12. int ret;
  13. unsigned long long res;
  14. /* https://stackoverflow.com/questions/6139493/how-convert-char-to-int-in-linux-kernel */
  15. ret = kstrtoull_from_user(buf, len, 10, &res);
  16. if (ret) {
  17. /* Negative error code. */
  18. return ret;
  19. } else {
  20. value = res;
  21. *off= len;
  22. return len;
  23. }
  24. }
  25. static const struct file_operations fops = {
  26. .owner = THIS_MODULE,
  27. .write = write,
  28. };
  29. static int myinit(void)
  30. {
  31. struct dentry *file;
  32. dir = debugfs_create_dir("lkmc_debugfs", 0);
  33. if (!dir) {
  34. pr_alert("debugfs_create_dir failed");
  35. return -1;
  36. }
  37. file = debugfs_create_u32("myfile", S_IRUSR | S_IWUSR, dir, &value);
  38. if (!file) {
  39. pr_alert("debugfs_create_u32 failed");
  40. return -1;
  41. }
  42. /* Created on the toplevel of the debugfs mount,
  43. * and with explicit fops instead of a fixed integer value.
  44. */
  45. toplevel_file = debugfs_create_file(
  46. "lkmc_debugfs_file", S_IWUSR, NULL, NULL, &fops);
  47. if (!toplevel_file) {
  48. return -1;
  49. }
  50. return 0;
  51. }
  52. static void myexit(void)
  53. {
  54. debugfs_remove_recursive(dir);
  55. debugfs_remove(toplevel_file);
  56. }
  57. module_init(myinit)
  58. module_exit(myexit)
  59. MODULE_LICENSE("GPL");