debugfs.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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. dir = debugfs_create_dir("lkmc_debugfs", 0);
  32. if (!dir) {
  33. pr_alert("debugfs_create_dir failed");
  34. return -1;
  35. }
  36. debugfs_create_u32("myfile", S_IRUSR | S_IWUSR, dir, &value);
  37. /* Created on the toplevel of the debugfs mount,
  38. * and with explicit fops instead of a fixed integer value.
  39. */
  40. toplevel_file = debugfs_create_file(
  41. "lkmc_debugfs_file", S_IWUSR, NULL, NULL, &fops);
  42. if (!toplevel_file) {
  43. return -1;
  44. }
  45. return 0;
  46. }
  47. static void myexit(void)
  48. {
  49. debugfs_remove_recursive(dir);
  50. debugfs_remove(toplevel_file);
  51. }
  52. module_init(myinit)
  53. module_exit(myexit)
  54. MODULE_LICENSE("GPL");