1/* SPDX-License-Identifier: GPL-2.0 */
2#ifndef _LINUX_CONTAINER_OF_H
3#define _LINUX_CONTAINER_OF_H
4
5#include <linux/build_bug.h>
6#include <linux/stddef.h>
7
8#define typeof_member(T, m) typeof(((T*)0)->m)
9
10/**
11 * container_of - cast a member of a structure out to the containing structure
12 * @ptr: the pointer to the member.
13 * @type: the type of the container struct this is embedded in.
14 * @member: the name of the member within the struct.
15 *
16 * WARNING: any const qualifier of @ptr is lost.
17 * Do not use container_of() in new code.
18 */
19#define container_of(ptr, type, member) ({ \
20 void *__mptr = (void *)(ptr); \
21 static_assert(__same_type(*(ptr), ((type *)0)->member) || \
22 __same_type(*(ptr), void), \
23 "pointer type mismatch in container_of()"); \
24 ((type *)(__mptr - offsetof(type, member))); })
25
26/**
27 * container_of_const - cast a member of a structure out to the containing
28 * structure and preserve the const-ness of the pointer
29 * @ptr: the pointer to the member
30 * @type: the type of the container struct this is embedded in.
31 * @member: the name of the member within the struct.
32 *
33 * Always prefer container_of_const() instead of container_of() in new code.
34 */
35#define container_of_const(ptr, type, member) \
36 _Generic(ptr, \
37 const typeof(*(ptr)) *: ((const type *)container_of(ptr, type, member)),\
38 default: ((type *)container_of(ptr, type, member)) \
39 )
40
41#endif /* _LINUX_CONTAINER_OF_H */
42