v4l2-spi.c 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. // SPDX-License-Identifier: GPL-2.0-or-later
  2. /*
  3. * v4l2-spi - SPI helpers for Video4Linux2
  4. */
  5. #include <linux/module.h>
  6. #include <linux/spi/spi.h>
  7. #include <media/v4l2-common.h>
  8. #include <media/v4l2-device.h>
  9. void v4l2_spi_subdev_unregister(struct v4l2_subdev *sd)
  10. {
  11. struct spi_device *spi = v4l2_get_subdevdata(sd);
  12. if (spi && !spi->dev.of_node && !spi->dev.fwnode)
  13. spi_unregister_device(spi);
  14. }
  15. void v4l2_spi_subdev_init(struct v4l2_subdev *sd, struct spi_device *spi,
  16. const struct v4l2_subdev_ops *ops)
  17. {
  18. v4l2_subdev_init(sd, ops);
  19. sd->flags |= V4L2_SUBDEV_FL_IS_SPI;
  20. /* the owner is the same as the spi_device's driver owner */
  21. sd->owner = spi->dev.driver->owner;
  22. sd->dev = &spi->dev;
  23. /* spi_device and v4l2_subdev point to one another */
  24. v4l2_set_subdevdata(sd, spi);
  25. spi_set_drvdata(spi, sd);
  26. /* initialize name */
  27. snprintf(sd->name, sizeof(sd->name), "%s %s",
  28. spi->dev.driver->name, dev_name(&spi->dev));
  29. }
  30. EXPORT_SYMBOL_GPL(v4l2_spi_subdev_init);
  31. struct v4l2_subdev *v4l2_spi_new_subdev(struct v4l2_device *v4l2_dev,
  32. struct spi_controller *ctlr,
  33. struct spi_board_info *info)
  34. {
  35. struct v4l2_subdev *sd = NULL;
  36. struct spi_device *spi = NULL;
  37. if (!v4l2_dev)
  38. return NULL;
  39. if (info->modalias[0])
  40. request_module(info->modalias);
  41. spi = spi_new_device(ctlr, info);
  42. if (!spi || !spi->dev.driver)
  43. goto error;
  44. if (!try_module_get(spi->dev.driver->owner))
  45. goto error;
  46. sd = spi_get_drvdata(spi);
  47. /*
  48. * Register with the v4l2_device which increases the module's
  49. * use count as well.
  50. */
  51. if (__v4l2_device_register_subdev(v4l2_dev, sd, sd->owner))
  52. sd = NULL;
  53. /* Decrease the module use count to match the first try_module_get. */
  54. module_put(spi->dev.driver->owner);
  55. error:
  56. /*
  57. * If we have a client but no subdev, then something went wrong and
  58. * we must unregister the client.
  59. */
  60. if (!sd)
  61. spi_unregister_device(spi);
  62. return sd;
  63. }
  64. EXPORT_SYMBOL_GPL(v4l2_spi_new_subdev);