xref: /openbmc/linux/include/linux/container_of.h (revision 2b8e3533)
1d2a8ebbfSAndy Shevchenko /* SPDX-License-Identifier: GPL-2.0 */
2d2a8ebbfSAndy Shevchenko #ifndef _LINUX_CONTAINER_OF_H
3d2a8ebbfSAndy Shevchenko #define _LINUX_CONTAINER_OF_H
4d2a8ebbfSAndy Shevchenko 
5d2a8ebbfSAndy Shevchenko #include <linux/build_bug.h>
6*2b8e3533SAndy Shevchenko #include <linux/stddef.h>
7d2a8ebbfSAndy Shevchenko 
8d2a8ebbfSAndy Shevchenko #define typeof_member(T, m)	typeof(((T*)0)->m)
9d2a8ebbfSAndy Shevchenko 
10d2a8ebbfSAndy Shevchenko /**
11d2a8ebbfSAndy Shevchenko  * container_of - cast a member of a structure out to the containing structure
12d2a8ebbfSAndy Shevchenko  * @ptr:	the pointer to the member.
13d2a8ebbfSAndy Shevchenko  * @type:	the type of the container struct this is embedded in.
14d2a8ebbfSAndy Shevchenko  * @member:	the name of the member within the struct.
15d2a8ebbfSAndy Shevchenko  *
167376e561SSakari Ailus  * WARNING: any const qualifier of @ptr is lost.
17d2a8ebbfSAndy Shevchenko  */
18d2a8ebbfSAndy Shevchenko #define container_of(ptr, type, member) ({				\
19d2a8ebbfSAndy Shevchenko 	void *__mptr = (void *)(ptr);					\
20e1edc277SRasmus Villemoes 	static_assert(__same_type(*(ptr), ((type *)0)->member) ||	\
21e1edc277SRasmus Villemoes 		      __same_type(*(ptr), void),			\
22d2a8ebbfSAndy Shevchenko 		      "pointer type mismatch in container_of()");	\
23d2a8ebbfSAndy Shevchenko 	((type *)(__mptr - offsetof(type, member))); })
24d2a8ebbfSAndy Shevchenko 
2564f6a5d1SGreg Kroah-Hartman /**
2664f6a5d1SGreg Kroah-Hartman  * container_of_const - cast a member of a structure out to the containing
2764f6a5d1SGreg Kroah-Hartman  *			structure and preserve the const-ness of the pointer
2864f6a5d1SGreg Kroah-Hartman  * @ptr:		the pointer to the member
2964f6a5d1SGreg Kroah-Hartman  * @type:		the type of the container struct this is embedded in.
3064f6a5d1SGreg Kroah-Hartman  * @member:		the name of the member within the struct.
3164f6a5d1SGreg Kroah-Hartman  */
3264f6a5d1SGreg Kroah-Hartman #define container_of_const(ptr, type, member)				\
3364f6a5d1SGreg Kroah-Hartman 	_Generic(ptr,							\
3464f6a5d1SGreg Kroah-Hartman 		const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
3564f6a5d1SGreg Kroah-Hartman 		default: ((type *)container_of(ptr, type, member))	\
3664f6a5d1SGreg Kroah-Hartman 	)
3764f6a5d1SGreg Kroah-Hartman 
38d2a8ebbfSAndy Shevchenko #endif	/* _LINUX_CONTAINER_OF_H */
39