sdev.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. // SPDX-License-Identifier: GPL-2.0
  2. /* Copyright (c) 2019 Mellanox Technologies. All rights reserved */
  3. #include <linux/debugfs.h>
  4. #include <linux/err.h>
  5. #include <linux/kernel.h>
  6. #include <linux/slab.h>
  7. #include "netdevsim.h"
  8. static struct dentry *nsim_sdev_ddir;
  9. static u32 nsim_sdev_id;
  10. struct netdevsim_shared_dev *nsim_sdev_get(struct netdevsim *joinns)
  11. {
  12. struct netdevsim_shared_dev *sdev;
  13. char sdev_ddir_name[10];
  14. int err;
  15. if (joinns) {
  16. if (WARN_ON(!joinns->sdev))
  17. return ERR_PTR(-EINVAL);
  18. sdev = joinns->sdev;
  19. sdev->refcnt++;
  20. return sdev;
  21. }
  22. sdev = kzalloc(sizeof(*sdev), GFP_KERNEL);
  23. if (!sdev)
  24. return ERR_PTR(-ENOMEM);
  25. sdev->refcnt = 1;
  26. sdev->switch_id = nsim_sdev_id++;
  27. sprintf(sdev_ddir_name, "%u", sdev->switch_id);
  28. sdev->ddir = debugfs_create_dir(sdev_ddir_name, nsim_sdev_ddir);
  29. if (IS_ERR_OR_NULL(sdev->ddir)) {
  30. err = PTR_ERR_OR_ZERO(sdev->ddir) ?: -EINVAL;
  31. goto err_sdev_free;
  32. }
  33. return sdev;
  34. err_sdev_free:
  35. nsim_sdev_id--;
  36. kfree(sdev);
  37. return ERR_PTR(err);
  38. }
  39. void nsim_sdev_put(struct netdevsim_shared_dev *sdev)
  40. {
  41. if (--sdev->refcnt)
  42. return;
  43. debugfs_remove_recursive(sdev->ddir);
  44. kfree(sdev);
  45. }
  46. int nsim_sdev_init(void)
  47. {
  48. nsim_sdev_ddir = debugfs_create_dir(DRV_NAME "_sdev", NULL);
  49. if (IS_ERR_OR_NULL(nsim_sdev_ddir))
  50. return -ENOMEM;
  51. return 0;
  52. }
  53. void nsim_sdev_exit(void)
  54. {
  55. debugfs_remove_recursive(nsim_sdev_ddir);
  56. }