Back to home page

OSCL-LXR

 
 

    


0001 /* SPDX-License-Identifier: GPL-2.0 */
0002 #ifndef _LINUX_CONTAINER_OF_H
0003 #define _LINUX_CONTAINER_OF_H
0004 
0005 #include <linux/build_bug.h>
0006 #include <linux/err.h>
0007 
0008 #define typeof_member(T, m) typeof(((T*)0)->m)
0009 
0010 /**
0011  * container_of - cast a member of a structure out to the containing structure
0012  * @ptr:    the pointer to the member.
0013  * @type:   the type of the container struct this is embedded in.
0014  * @member: the name of the member within the struct.
0015  *
0016  */
0017 #define container_of(ptr, type, member) ({              \
0018     void *__mptr = (void *)(ptr);                   \
0019     static_assert(__same_type(*(ptr), ((type *)0)->member) ||   \
0020               __same_type(*(ptr), void),            \
0021               "pointer type mismatch in container_of()");   \
0022     ((type *)(__mptr - offsetof(type, member))); })
0023 
0024 /**
0025  * container_of_safe - cast a member of a structure out to the containing structure
0026  * @ptr:    the pointer to the member.
0027  * @type:   the type of the container struct this is embedded in.
0028  * @member: the name of the member within the struct.
0029  *
0030  * If IS_ERR_OR_NULL(ptr), ptr is returned unchanged.
0031  */
0032 #define container_of_safe(ptr, type, member) ({             \
0033     void *__mptr = (void *)(ptr);                   \
0034     static_assert(__same_type(*(ptr), ((type *)0)->member) ||   \
0035               __same_type(*(ptr), void),            \
0036               "pointer type mismatch in container_of_safe()");  \
0037     IS_ERR_OR_NULL(__mptr) ? ERR_CAST(__mptr) :         \
0038         ((type *)(__mptr - offsetof(type, member))); })
0039 
0040 #endif  /* _LINUX_CONTAINER_OF_H */