Hi Ying, Very interesting question. On Thu, Mar 21, 2024 at 7:40 PM Huang, Ying <ying.huang@xxxxxxxxx> wrote: > > 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. I am trying to see if your program can convert into a litmus test so the linux memory model tools can answer it for you. Because you allow reader() to read written value a little later, there is nothing the test can verify against. The reader can see both before or after the writer's update, both are valid observations. To make your test example more complete, you need the reader/writer to do more actions to expose the race. For example, " if (READ_ONCE(x[n]) y = 1;" Then you can ask the question whether it is possible to observe x[n] == 0 and y== 1. That might not be the test condition you have in mind, you can get the idea. We want to have a test example that shows the result observable state to indicate the bad things did happen(or not possible). > 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? We need to define what is the expected behavior outcome to be "correct", possibly including the before and after barrier actions. Chris > > 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 >