I am reading the linux kernel implementation of doubled linked list. I do not understand the use of the macro WRITE_ONCE(x, val)
. It is defined as follow in compiler.h:
#define WRITE_ONCE(x, val) x=(val)
It is used seven times in the file, such as
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
WRITE_ONCE(prev->next, new);
}
I have read that it is used for avoiding race conditions.
I have two questions:
1/ I thought macro was replace by code at compile time. So how this code differs to the following one ? How this macro can avoid race conditions ?
static inline void __list_add(struct list_head *new,
struct list_head *prev,
struct list_head *next)
{
next->prev = new;
new->next = next;
new->prev = prev;
prev->next = new;
}
2/ How to know when we should use it ? For instance, it is used for __lst_add()
but not for __lst_splice()
:
static inline void __list_splice(const struct list_head *list,
struct list_head *prev,
struct list_head *next)
{
struct list_head *first = list->next;
struct list_head *last = list->prev;
first->prev = prev;
prev->next = first;
last->next = next;
next->prev = last;
}
edit:
Here is a commit message concerning this file and WRITE_ONCE
, but it does not help me to understand anything...
list: Use WRITE_ONCE() when initializing list_head structures
Code that does lockless emptiness testing of non-RCU lists is relying on INIT_LIST_HEAD() to write the list head's ->next pointer atomically, particularly when INIT_LIST_HEAD() is invoked from list_del_init(). This commit therefore adds WRITE_ONCE() to this function's pointer stores that could affect the head's ->next pointer.
__write_once_size
...WRITE_ONCE
(it is defined in three headers), I do not known exactly which one is used...