summaryrefslogtreecommitdiff
path: root/kernel/include/containter_of.h
blob: 9cadd91ee7507b973f7fb970db1634896b6e4b36 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
/* SPDX-License-Identifier: GPL-2.0 */
#ifndef CONTAINER_OF
#define CONTAINER_OF

#define static_assert(expr, ...) __static_assert(expr, ##__VA_ARGS__, #expr)
#define __static_assert(expr, msg, ...) _Static_assert(expr, msg)
#define __same_type(a, b) __builtin_types_compatible_p(typeof(a), typeof(b))
#define typeof_member(T, m) typeof(((T *)0)->m)

/**
 * container_of - cast a member of a structure out to the containing structure
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 */
#define container_of(ptr, type, member)                                   \
	({                                                                \
		void *__mptr = (void *)(ptr);                             \
		static_assert(__same_type(*(ptr), ((type *)0)->member) || \
				      __same_type(*(ptr), void),          \
			      "pointer type mismatch in container_of()"); \
		((type *)(__mptr - offsetof(type, member)));              \
	})

/**
 * container_of_safe - cast a member of a structure out to the containing structure
 * @ptr:	the pointer to the member.
 * @type:	the type of the container struct this is embedded in.
 * @member:	the name of the member within the struct.
 *
 * If IS_ERR_OR_NULL(ptr), ptr is returned unchanged.
 */
#define container_of_safe(ptr, type, member)                                   \
	({                                                                     \
		void *__mptr = (void *)(ptr);                                  \
		static_assert(__same_type(*(ptr), ((type *)0)->member) ||      \
				      __same_type(*(ptr), void),               \
			      "pointer type mismatch in container_of_safe()"); \
		IS_ERR_OR_NULL(__mptr) ?                                       \
			ERR_CAST(__mptr) :                                     \
			((type *)(__mptr - offsetof(type, member)));           \
	})

#endif