Volatile: Dark Corners of C

Volatile keyword is an interesting quirk. Used to fight back compiler optimization in order to access memory, which could be modified concurrently and unexpectedly. This includes:

  • communication with hardware via memory mapped I/O
  • access to system structures
  • access to program variables modified by multiple threads

I have described general purpose of volatile keyword in Adventures in Parallel Universe. Today we will dive more deeply into concept and we will see some confusing and counter-intuitive cases which can arise during volatile usage.

Volatile Pointers
Assume you have lock-free list with pointer to it’s tail. First thread atomically exchanges tail with pointer to new node, second waits until tail is not NULL.

struct Node {
  struct Node* prev;
  int elem;
}*tail;

void thread1() {
  while(!__sync_bool_compare_and_swap(&tail, oldtail, newtail))
    cpu_relax();
}

void thread2() {
  while(!tail) cpu_relax();
}

Because we are spinning at tail in thread2, tail has to be volatile to prevent compiler optimizations. We have 3 variants of volatile single pointer:
1. volatile Node* tail;
2. Node* volatile tail;
3. volatile Node* volatile tail;
Which should we choose?

After translating it to English we have:
1. pointer to volatile memory which means that dereferences of pointer will not be optimized by compiler. Example: while(tail->prev) will stay but while(tail) could be wiped out.
2. volatile pointer to memory which means that accessing pointer value will not be optimized. Example: while(tail) will stay but while(tail->prev) could be optimized.
3. volatile pointer to volatile memory which is combination of two previous. Example: both while(tail) and while(tail->prev) will not be optimized.

So in our case we can choose option 2 and 3. Option 3 is less desirable because in presented code we are not dereferencing memory on which tail points, but additional volatile prevents compiler from optimizations.
Of course there exists also multiple volatile pointers – rules are the same as with single volatile pointers.

Const Volatile
We can declare variable as const and volatile in the same time. This could be confusing because const tells us that variable is constant (so cannot be changed) and volatile tells us that variable could be changed. As an example let’s take code that communicates with external device via memory:

volatile int* p = (volatile int*)0xC0000000;
while(*p) cpu_relax();

In code we are only reading memory at address 0xC0000000 but we do not perform writes. And as we know, variables that are read-only should be marked as const to prevent accidental modification.

const volatile int* p = (volatile int*)0xC0000000;
while(*p) cpu_relax();

const volatile int* p means that memory pointed by p could be changed by “outside world” (like hardware) but cannot be changed by dereference of p (such attempt will result in compilation error).

Volatile Casts 1
In Windows there is a function for atomic increments of variable:

LONG __cdecl InterlockedIncrement(
  _Inout_  LONG volatile *Addend
);
...
long var;
InterlockedIncrement(&var);

Can we pass non-volatile variable to InterlockedIncrement function?
The answer is yes – in this situation we are performing implicit cast from non-volatile memory to volatile memory. It simply means that InterlockedIncrement will make less assumptions about passed argument and will expect that argument can be changed by outside world.

What with opposite situation: can we pass volatile memory to function that does not expect volatile argument (e.g. to memcpy)?

void * memcpy ( void * destination, const void * source, size_t num );
...
volatile char *dst = (volatile char*)0xC0000000;
char src[40];
memcpy((void*)dst, src, sizeof(src));

In this situation what we’ve got is undefined behavior. The C standard says:

If an attempt is made to refer to an object defined with a volatile-qualified type through use of an lvalue with non-volatile-qualified type, the behavior is undefined.

We have to use memcpy implementation that handles volatile memory or write our own implementation.

Volatile Casts 2
Assume we have legacy code which declares variable as non-volatile but we have to use it in multithreaded context:

#include <pthread.h>
#include <unistd.h>

int flag = 0;

void* thread_func(void* arg) {
    while(!(volatile int)flag);
    return 0;
}

int main(void) {
    pthread_t t;
    pthread_create(&t, 0, thread_func, 0);
    sleep(1);
    *(volatile int*)&flag = 1;
    pthread_join(t, 0);
    return 0;
}

We have casted flag to volatile so everything should be fine and program should exit. Instead of this, program goes into infinite loop. On disasembly listing you can see that while loop was transformed into infinite loop:

thread_func()
thread_func+38: jmp    0x400776 <thread_func+38>

C standard says:

The properties associated with qualified types [in our case volatile] are meaningful only for expressions that are lvalues

And expression (volatile int)flag is not lvalue (if you will try assign value to such expression you will get compilation error). This means expressions
while(flag)
and
while((volatile int)flag)
are exactly the same and your volatile cast was flushed down to a toilet. Nobody expects the Spanish Inquisition.
To fix it we have transform expression to lvalue:

while(!*(volatile int*)&flag);

Or even better – use volatile alias on non-volatile variable.

Volatile Ordering
Consider following scenario: one thread copies data to buffer and sets flag when it’s done, second thread spins on flag and then reads data from buffer:

char buffer[50];
volatile int done = 0;
void thread1() {
  for(int i = 0; i < _countof(buffer); ++i) 
    buffer[i] = next();
  done = 1;
}
void thread2() {
  while(!done) cpu_relax();
  for(int i = 0; i < _countof(buffer); ++i)
    process(buffer[i]);
}

Because flag is volatile, compiler will not cache it in registers so while loop will exit. But code is still incorrect: done=1 can be executed by compiler before for-loop. This is because buffer is not volatile. And two consecutive accesses: first to volatile variable and second to non-volatile variable (or vice versa) could be reordered by compiler. If such optimization is performed, it will result in accessing uninitialized buffer. This can be fixed by declaring buffer as volatile or by placing Compiler Memory Barrier:

void thread1() {
  for(int i = 0; i < _countof(buffer); ++i) 
    buffer[i] = next();
  KeMemoryBarrierWithoutFence();
  done = 1;
}

void thread2() {
  while(!done) cpu_relax();
  KeMemoryBarrierWithoutFence();
  for(int i = 0; i < _countof(buffer); ++i)
    process(buffer[i]);
}

KeMemoryBarrierWithoutFence will prevent reordering performed by compiler but access to memory could be still reordered by processor. Processor’s reordering, in turn, can be suppressed by Hardware Memory Barrier (but this is topic for another article… or several articles).

Volatile and Atomicity
Accessing volatile variable does not guarantee that access will be atomic. Let’s see what requirements must be met for InterlockedIncrement function to be atomic:

The variable pointed to by the Addend parameter must be aligned on a 32-bit boundary; otherwise, this function will behave unpredictably on multiprocessor x86 systems and any non-x86 systems

So we will prove that volatile does not guarantee alignment and therefore does not guarantee atomicity. We will place volatile variable into not aligned memory:

    #pragma pack(1)
    struct {
        char c;
        volatile long int v;
    } a ;
    #pragma pack()

    printf("%p", &a.v);

Output:

0x7fff2ba07971

It means that volatile variable is not aligned to 32-bit boundary which will result in non-atomic accesses on x86 processors. Even without requesting special alignment we can cause that volatile variable will be placed in not aligned memory – e.g. by putting it in memory returned from malloc (malloc does not guarantee that allocated memory will be aligned).

Volatile C++
When classes was added to C (i.e. when C++ was created) some new rules about volatile had to be established. Volatile objects, volatile methods, function overloads with volatile parameters, volatile copy constructors, volatile partial template specialization… It’s really funny to observe how C++ amplifies complexity of C features. But in case of volatile, which is hard to use correctly even in plane C, level of complication in C++ becomes insane. It is tempting to just ignore topic and do not use volatile in conjunction with C++ stuff. Unfortunately new C++ standard comes with bunch of generic classes that uses volatile for multithreading. This means if you want to understand and use correctly C++11 threading library you will have dig into gory details of C++’s volatile. Stay tuned…

Advertisements

Thread Stood Still

Thread suspension is a technique commonly used by Application Monitors such as:

  • debuggers
  • stop-the-world garbage collectors
  • security tools

Besides it is useful from technical point of view, having possibility to stop and resume nothing suspecting threads brings me joy. Maybe I’m becoming control freak. Or just spending too much time in front of my computer.

Anyway, let’s cut the crap out and see what possibilities of thread suspension do we have on different operating systems:

  • Windows: WinApi functions SuspendThread / ResumeThread
  • Unix: pthread_suspend / pthread_resume (name depends on particular system)
  • Linux: ptrhread_suspend_np / ptrhread_resume_np

_np postfix in Linux functions doesn’t look good – it means that they are non-portable and according to documentation – available only on RtLinux systems. If we want to have possibility of suspending threads on other Linuxes we have to do it by ourselves. And we want to have this possibility.

General idea
To implement thread suspension from user-mode we will have to break somehow into thread’s execution context. Fortunately this is exactly what signal mechanism provides us. General schema looks like this:

  1. Send signal to victim thread
  2. In signal handler place blocking operation
  3. During resume, notify blocking mechanism and exit signal handler which will resume thread’s execution

To make this mechanism safe we will have to carefully choose what operation we are performing during signal handler and what signal we are blocking:

  • Signal used to resume and suspend will be SIGUSR1 which is left free to programmer
  • Before signal handler is executed, signal mask of victim thread has to be changed to block SIGUSR1. If we won’t do this then multiple concurrent requests to suspend/resume can cause deadlocks and races. It can be done by specifying mask in sigaction function.
  • suspend function has to wait on signal delivery to victim thread. If it will exit asynchronously before signal is delivered it will be worthless as synchronization mechanism and could trick user to think that thread is already blocked (but in fact can still executes). Signal delivery synchronization can be done by spinlock shared between signal handler and issuing thread.
  • blocking operation in signal handler has to be reentrant (it means it has to be on the list of async-safe functions provided in man 7 signal). It also has to atomically change signal mask when entering (to not block SIGUSR1 anymore) and restore it when exiting. Fortunately such function exists and it is sigsuspend. It will block until specified signal is delivered and will temporarily replace current signal mask.

Implmentation
Code is available on github: https://github.com/bit-envoy/threadmgmt

#pragma once
#include <pthread.h>

#define USED_SIG SIGUSR1

int thread_mgmt_init(void);

int thread_mgmt_release(void);

int thread_mgmt_suspend(pthread_t t);

int thread_mgmt_resume(pthread_t t);
#include "threadmgmt.h"
#include <signal.h>
#include <string.h>
#include <pthread.h>

#define CPU_RELAX() asm("pause")
#define SMP_WB()
#define SMP_RB()

typedef struct thread_mgmt_op
{
    int op;
    volatile int done;
    volatile int res;
}thread_mgmt_op_t;

struct sigaction old_sigusr1;
static __thread volatile int thread_state = 1;

static void thread_mgmt_handler(int, siginfo_t*, void*);
static int thread_mgmt_send_op(pthread_t, int);


int thread_mgmt_init(void)
{
  struct sigaction sa;
  memset(&sa, 0, sizeof(sa));
  sa.sa_sigaction = (void*)thread_mgmt_handler;
  sa.sa_flags = SA_SIGINFO;      
  sigfillset(&sa.sa_mask);
  //register signal handler which will full signal mask
  return sigaction(USED_SIG, &sa, NULL);
}

int thread_mgmt_release()
{
    //restore previous signal handler
    return sigaction(USED_SIG, &old_sigusr1, NULL);
}

int thread_mgmt_suspend(pthread_t t)
{
    return thread_mgmt_send_op(t, 0);
}

int thread_mgmt_resume(pthread_t t)
{    
    return thread_mgmt_send_op(t, 1);
}

static int thread_mgmt_send_op(pthread_t t, int opnum)
{
    thread_mgmt_op_t op = {.op = opnum, .done = 0, .res = 0};
    sigval_t val = {.sival_ptr = &op};
    if(pthread_sigqueue(t, USED_SIG, val))
        return -1;
    
    //spin wait till signal is delivered
    while(!op.done) 
        CPU_RELAX();

    SMP_RB();
    return op.res;
}

static void thread_mgmt_handler(int signum, siginfo_t* info, void* ctx)
{
    thread_mgmt_op_t *op = (thread_mgmt_op_t*)(info->si_value.sival_ptr);
    if(op->op == 0 && thread_state == 1)
    {
        //suspend
        thread_state = 0;
        op->res = 0;
        SMP_WB();
        op->done = 1;
        
        sigset_t mask;
        sigfillset(&mask);
        sigdelset(&mask, USED_SIG);

        //wait till SIGUSR1
        sigsuspend(&mask);
    }
    else if(op->op == 1 && thread_state == 0)
    {
        //resume
        thread_state = 1;
        op->res = 0;
        SMP_WB();
        op->done = 1;
    }
    else
    {
        //resume resumed thread or
        //suspend suspended thread
        op->res = -1;
        SMP_WB();
        op->done = 1;
    }
}
#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

#include "threadmgmt.h"

void*  function(void*  arg)
{
    int i = 0;
    while(1) printf("thread(%d) %p\n", arg, i++);
    return 0;
}

int main( void )
{
    if(thread_mgmt_init())
        return -1;
    
   pthread_t t1, t2;
   pthread_create(&amp;t1, NULL, function, (void*)1);
   pthread_create(&amp;t2, NULL, function, (void*)2);

   
   sleep(1);
   if(thread_mgmt_suspend(t1))
       return -2;

   if(thread_mgmt_suspend(t2))
       return -2;
   
   sleep(2);
   if(thread_mgmt_resume(t1))
       return -3;

   if(thread_mgmt_resume(t2))
       return -3;
   
   sleep(4);
   thread_mgmt_release();
   
   return 0;
}

Additional notes

  • On processors that can reorder writes and reads to different addresses (e.g. some ARMs) macro SMP_WB and SMP_RB should be defined with proper memory barrier instructions. On x86 and x64 macros are empty because those processor does not perform reordering in described case.
  • Disadvantage of using signals to implement suspending is that signals will interrupt blocking operations like sleep(). So threads that will be suspended should be prepared for it. If you know better way how to implement thread suspension on Linux feel free to let me know. Sad true about thread suspension is it should be implemented in kernel (like in Windows and some Unixes) not hacked in user mode.

Final word
Suspending threads is handy mechanism in many situations but it also can be dangerous. If thread is suspended during holding some lock, and then issuing thread will try acquire the same lock it will deadlock. This effect can be observed on test application – when thread is suspended during printf (which acquire locks) and other thread tries to printf something it will hang on the same lock. You have know what you are doing – use it in monitoring / instrumentation scenarios – where you don’t have full control over monitored thread code.