Can you help us on memory barrier usage? (was Re: [PATCH v4 4/6] mm: swap: Allow storage of all mTHP orders)

From: Huang, Ying
Date: Thu Mar 21 2024 - 22:40:30 EST


Hi, Paul,

Can you help us on WRITE_ONCE()/READ_ONCE()/barrier() usage as follows?
For some example kernel code as follows,

"
unsigned char x[16];

void writer(void)
{
memset(x, 1, sizeof(x));
/* To make memset() take effect ASAP */
barrier();
}

unsigned char reader(int n)
{
return READ_ONCE(x[n]);
}
"

where, writer() and reader() may be called on 2 CPUs without any lock.
It's acceptable for reader() to read the written value a little later.
Our questions are,

1. because it's impossible for accessing "unsigned char" to cause
tearing. So, WRITE_ONCE()/READ_ONCE()/barrier() isn't necessary for
correctness, right?

2. we use barrier() and READ_ONCE() in writer() and reader(), because we
want to make writing take effect ASAP. Is it a good practice? Or it's
a micro-optimization that should be avoided?

--
Best Regards,
Huang, Ying