]> www.infradead.org Git - users/hch/misc.git/commitdiff
list: add list_last_entry_or_null()
authorLuca Ceresoli <luca.ceresoli@bootlin.com>
Fri, 1 Aug 2025 17:05:23 +0000 (19:05 +0200)
committerLuca Ceresoli <luca.ceresoli@bootlin.com>
Tue, 2 Sep 2025 09:38:29 +0000 (11:38 +0200)
Add an equivalent of list_first_entry_or_null() to obtain the last element
of a list.

Acked-by: Andy Shevchenko <andriy.shevchenko@linux.intel.com>
Link: https://lore.kernel.org/r/20250801-drm-bridge-alloc-getput-drm_bridge_get_next_bridge-v2-1-888912b0be13@bootlin.com
Signed-off-by: Luca Ceresoli <luca.ceresoli@bootlin.com>
include/linux/list.h

index e7e28afd28f8eef94ab6baec77e69ea104ba0391..7f7657e416209a2941b3f292b1334e9e0f2a3ca5 100644 (file)
@@ -636,6 +636,20 @@ static inline void list_splice_tail_init(struct list_head *list,
        pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
 })
 
+/**
+ * list_last_entry_or_null - get the last element from a list
+ * @ptr:       the list head to take the element from.
+ * @type:      the type of the struct this is embedded in.
+ * @member:    the name of the list_head within the struct.
+ *
+ * Note that if the list is empty, it returns NULL.
+ */
+#define list_last_entry_or_null(ptr, type, member) ({ \
+       struct list_head *head__ = (ptr); \
+       struct list_head *pos__ = READ_ONCE(head__->prev); \
+       pos__ != head__ ? list_entry(pos__, type, member) : NULL; \
+})
+
 /**
  * list_next_entry - get the next element in list
  * @pos:       the type * to cursor