container_of.h 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /* SPDX-License-Identifier: GPL-2.0 */
  2. #ifndef _LINUX_CONTAINER_OF_H
  3. #define _LINUX_CONTAINER_OF_H
  4. #include <linux/build_bug.h>
  5. #include <linux/err.h>
  6. #define typeof_member(T, m) typeof(((T*)0)->m)
  7. /**
  8. * container_of - cast a member of a structure out to the containing structure
  9. * @ptr: the pointer to the member.
  10. * @type: the type of the container struct this is embedded in.
  11. * @member: the name of the member within the struct.
  12. *
  13. */
  14. #define container_of(ptr, type, member) ({ \
  15. void *__mptr = (void *)(ptr); \
  16. static_assert(__same_type(*(ptr), ((type *)0)->member) || \
  17. __same_type(*(ptr), void), \
  18. "pointer type mismatch in container_of()"); \
  19. ((type *)(__mptr - offsetof(type, member))); })
  20. /**
  21. * container_of_safe - cast a member of a structure out to the containing structure
  22. * @ptr: the pointer to the member.
  23. * @type: the type of the container struct this is embedded in.
  24. * @member: the name of the member within the struct.
  25. *
  26. * If IS_ERR_OR_NULL(ptr), ptr is returned unchanged.
  27. */
  28. #define container_of_safe(ptr, type, member) ({ \
  29. void *__mptr = (void *)(ptr); \
  30. static_assert(__same_type(*(ptr), ((type *)0)->member) || \
  31. __same_type(*(ptr), void), \
  32. "pointer type mismatch in container_of_safe()"); \
  33. IS_ERR_OR_NULL(__mptr) ? ERR_CAST(__mptr) : \
  34. ((type *)(__mptr - offsetof(type, member))); })
  35. #endif /* _LINUX_CONTAINER_OF_H */