devres.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * This file contains all networking devres helpers.
  4. */
  5. #include <linux/device.h>
  6. #include <linux/etherdevice.h>
  7. #include <linux/netdevice.h>
  8. struct net_device_devres {
  9. struct net_device *ndev;
  10. };
  11. static void devm_free_netdev(struct device *dev, void *this)
  12. {
  13. struct net_device_devres *res = this;
  14. free_netdev(res->ndev);
  15. }
  16. struct net_device *devm_alloc_etherdev_mqs(struct device *dev, int sizeof_priv,
  17. unsigned int txqs, unsigned int rxqs)
  18. {
  19. struct net_device_devres *dr;
  20. dr = devres_alloc(devm_free_netdev, sizeof(*dr), GFP_KERNEL);
  21. if (!dr)
  22. return NULL;
  23. dr->ndev = alloc_etherdev_mqs(sizeof_priv, txqs, rxqs);
  24. if (!dr->ndev) {
  25. devres_free(dr);
  26. return NULL;
  27. }
  28. devres_add(dev, dr);
  29. return dr->ndev;
  30. }
  31. EXPORT_SYMBOL(devm_alloc_etherdev_mqs);
  32. static void devm_unregister_netdev(struct device *dev, void *this)
  33. {
  34. struct net_device_devres *res = this;
  35. unregister_netdev(res->ndev);
  36. }
  37. static int netdev_devres_match(struct device *dev, void *this, void *match_data)
  38. {
  39. struct net_device_devres *res = this;
  40. struct net_device *ndev = match_data;
  41. return ndev == res->ndev;
  42. }
  43. /**
  44. * devm_register_netdev - resource managed variant of register_netdev()
  45. * @dev: managing device for this netdev - usually the parent device
  46. * @ndev: device to register
  47. *
  48. * This is a devres variant of register_netdev() for which the unregister
  49. * function will be call automatically when the managing device is
  50. * detached. Note: the net_device used must also be resource managed by
  51. * the same struct device.
  52. */
  53. int devm_register_netdev(struct device *dev, struct net_device *ndev)
  54. {
  55. struct net_device_devres *dr;
  56. int ret;
  57. /* struct net_device must itself be managed. For now a managed netdev
  58. * can only be allocated by devm_alloc_etherdev_mqs() so the check is
  59. * straightforward.
  60. */
  61. if (WARN_ON(!devres_find(dev, devm_free_netdev,
  62. netdev_devres_match, ndev)))
  63. return -EINVAL;
  64. dr = devres_alloc(devm_unregister_netdev, sizeof(*dr), GFP_KERNEL);
  65. if (!dr)
  66. return -ENOMEM;
  67. ret = register_netdev(ndev);
  68. if (ret) {
  69. devres_free(dr);
  70. return ret;
  71. }
  72. dr->ndev = ndev;
  73. devres_add(ndev->dev.parent, dr);
  74. return 0;
  75. }
  76. EXPORT_SYMBOL(devm_register_netdev);