Re: [PATCH v4 2/7] kernel.h: Split out container_of() and typeof_member() macros

From: Joe Perches
Date: Thu Oct 07 2021 - 12:27:50 EST


On Thu, 2021-10-07 at 18:44 +0300, Andy Shevchenko wrote:
> kernel.h is being used as a dump for all kinds of stuff for a long time.
> Here is the attempt cleaning it up by splitting out container_of() and
> typeof_member() macros.
>
> For time being include new header back to kernel.h to avoid twisted
> indirected includes for existing users.

IMO: this new file is missing 2 #include directives.

> diff --git a/include/linux/container_of.h b/include/linux/container_of.h
[]
> @@ -0,0 +1,37 @@
> +/* SPDX-License-Identifier: GPL-2.0 */

And trivially: I'd prefer GPL-2.0-only

> +#ifndef _LINUX_CONTAINER_OF_H
> +#define _LINUX_CONTAINER_OF_H
> +
> +#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); \
> + BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) && \
> + !__same_type(*(ptr), void), \
> + "pointer type mismatch in container_of()"); \

This is not a self-contained header as it requires
#include <linux/build_bug.h>
which should be at the top of this file.

> + ((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); \
> + BUILD_BUG_ON_MSG(!__same_type(*(ptr), ((type *)0)->member) && \
> + !__same_type(*(ptr), void), \
> + "pointer type mismatch in container_of()"); \
> + IS_ERR_OR_NULL(__mptr) ? ERR_CAST(__mptr) : \
> + ((type *)(__mptr - offsetof(type, member))); })

And this requires

#include <linux/err.h>

> +
> +#endif /* _LINUX_CONTAINER_OF_H */