Page 1 of 2

Fixing potential race condition

Posted: Mon Nov 03, 2008 1:06 pm
by cyr1x
Hi,
I'm currently on the way of implementing the kernel's object manager.
Now there's a problem, I came across.
Object's are reference counted (so they're deleted if not used anymore)
Now I tought of something like this:

Code: Select all

void Reference()
{
    refCount++;
}

void Release()
{
    refCount--;
    if(refCount == 0)
        delete this;
}
So far so good.
Well, now consider a context switch occurs after entering "Reference" and before "refCount++"
and the other context does a "Release". When the count then drops the zero the object is deleted, while there's someone waiting to reference it. -> race
On a uniprocessor system this wouldn't be a problem, just a matter of disabling interrupts while in the kernel.
On a multiprocessor system this is a really big problem as you probably found out.

Does anyone know a way around this?

Cheers.

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 1:29 pm
by Love4Boobies
You can use a lock, a semaphore or a monitor. There are also some other solutions around this but these are the best ways to go about it.

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 1:36 pm
by cyr1x
No this won't help because it could be preempted before it acquires the lock or on multiprocessor release can occur before reference. [-X
Anyway thanks. :)

Cheers.

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 2:33 pm
by Love4Boobies
You can aquire the lock outside of Reference().

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 3:37 pm
by Laksen
Couldn't you do it using locked primitives like
InterlockedExchangeAdd(refCount, 1);

and

if(InterlockedExchangeAdd(refCount, -1) == 0)
delete this;

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 5:35 pm
by Brendan
Hi,

First, let me point out that I've never used an OOP language and never used any sort of (software) garbage collection - AFAIK everything I'm about to say could be completely wrong...
cyr1x wrote:No this won't help because it could be preempted before it acquires the lock or on multiprocessor release can occur before reference.
It could be preempted before the "Reference()" function is even called.

However, how does the caller know that the object exists? Something must have told it the object exists. More importantly, something that has it's own reference must have told the caller that the object exists.

When an object is created the object creation code would increment the reference count and return a reference to the new object. Then, any time this reference is copied you'd increase the reference count *before* it's copied. For example, if threadA needs to tell threadB about the object, then it'd call the "Reference()" function and then give threadB a reference to the object.

Your problem seems to be that you're thinking about doing it the other way - e.g. give threadB a reference to the object and then call the "Reference()" function. AFAIK that will never work (unless you acquire a lock, then give threadB the reference, then let threadB call "Reference()" and then free the lock; but that's far too messy IMHO).

In this case, you don't need any locks. All you'd need is "lock inc [this->referenceCount]" in the "Reference()" function. In the "Release()" function you'd do "lock sub [this->referenceCount],1" followed by "je .delete" (or "jne .skipDelete").

The new problem is that all code must call "Reference()" before creating a copy of any reference; and if you can't trust programmers to call "free()" at the right time then you may not be able to trust them to call "Reference()" at the right time either... ;)


Cheers,

Brendan

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 5:40 pm
by CodeCat
Brendan, he's using C++. He can just use the object destructor to decrease the reference count. ;)

Re: Fixing potential race condition

Posted: Mon Nov 03, 2008 7:46 pm
by Walling
I might be slightly off-topic. Just wanted to tell you that ref counting is only safe if you can guarantee that no cycles occur. If you're in a situation where object A and object B knows each other (two drivers relying on each other services?) then you have a cycle and that can be a problem. The objects will never be freed. The simplest situation where a cycle occur is when an object have a reference to itself. One solution is to let no cycles occur: Build a dependency graph and check it for cycles whenever an object is loaded. Another solution is to build a full fledged garbage collector, but I guess that is more difficult. Just wanted to tell you. You probably know this and have a solution for it. :)

Re: Fixing potential race condition

Posted: Tue Nov 04, 2008 3:53 am
by Combuster
CodeCat wrote:Brendan, he's using C++. He can just use the object destructor to decrease the reference count. ;)
The idea of a destructor is that it destroys an object, while here we usually want to leave the object for other people to use.

Re: Fixing potential race condition

Posted: Tue Nov 04, 2008 6:01 am
by CodeCat
True. I think most C++ programs get around that by having a separate 'reference' class that lowers the reference count when it's destructed. Kind of like a smart pointer but with reference counting facilities. I think the Boost library has one that might actually be usable for OSDev.

Re: Fixing potential race condition

Posted: Tue Nov 04, 2008 9:35 am
by cyr1x
Hmm,
I think I have to clarify some points.
- The destructor does not decrease the reference count.
When the reference count drops to zero the destructor is called.
- There's no concept of thread's. Threads are object themselves.
In fact an object is bound to a context containing functions, variables, etc.
- The problem isn't the atomicity of the reference count itself! The problem is that the reference count may drop to zero, hence deleting the object, while there's someone who wants to acquire it.
-> When the context is preempted in the Reference() function before incrementing the count to an other context that decreases the count, probably deleting the object, then we have obviously have problems here as the object isn't valid anymore.
- Before Reference()ing an object, the kernel just checks if there's such an object, otherwise the request is just rejected.

Cheers.

Re: Fixing potential race condition

Posted: Tue Nov 04, 2008 11:52 am
by ezeaguerre
Couldn't something like this work?

Code: Select all

void MyClass::Reference () {
	EntreCriticalSection ();
	if ( refCount <= 0 )
		reload ();
	refCount++;
	LeaveCriticalSection ();
}

void MyClass::Release () {
	EnterCriticalSection ();
	refCount--;
	if ( refCount == 0 )
		delete this;
	LeaveCriticalSection ();
}
or like this?

Code: Select all

EnterCriticalSection ();
if ( !myObject )
	myObject = new MyClass;
myObject->Reference ();
LeaveCriticalSection ();

void MyClass::Release () {
	EnterCriticalSection ();
	refCount--;
	if ( refCount == 0 )
		delete this;
	LeaveCriticalSection ();
}
or maybe I just don't get it O.o

Re: Fixing potential race condition

Posted: Wed Nov 05, 2008 12:28 am
by Brendan
Hi,

Hmmm.

Here's an example of what I said last time. This is written in C because I don't know C++. AFAIK C++ uses almost identical concepts (except "MYOBJECT_DATA *myObjectData" becomes "this", and there's a few other differences with syntax/grammer).

Code: Select all

typedef struct {
	int referenceCount;
} MYOBJECT_DATA;


MYOBJECT_DATA *myObject_new(void) {
    MYOBJECT_DATA *myObjectData;

    myObjectData = malloc(sizeof(MYOBJECT_DATA));
    if(myObjectData != NULL) {
        myObjectData->referenceCount = 1;
        myObject_initialize(myObjectData);
    }
    return myObjectData;
}


void myObject_initialize(MYOBJECT_DATA *myObjectData) {
    /* ??? */
}

void myObject_destructor(MYOBJECT_DATA *myObjectData) {
    /* ??? */
}


void myObject_reference(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount++;      // Needs to be "lock inc dword [myObjectData->referenceCount]" for multi-CPU
}

void myObject_release(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount--;           // Needs to be "lock sub dword [myObjectData->referenceCount], 1" for multi-CPU
    if(myObjectData->referenceCount == 0) {   // Needs to be "jne .skip_the_next_2_lines" for multi-CPU
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}


void main(void) {
    MYOBJECT_DATA *myObjectData;

    myObjectData = myObject_new();

    myObject_reference(myObjectData);
    foo(myObjectData);

    myObject_reference(myObjectData);
    pthread_create(spareThread, myObjectData);

    myObject_release(myObjectData);
}


void foo(MYOBJECT_DATA *myObjectData) {
    / * ??? */
    myObject_release(myObjectData);
}


void spareThread(MYOBJECT_DATA *myObjectData) {
    if( rand() > RAND_MAX / 4) {
        myObject_reference(myObjectData);
        pthread_create(spareThread, myObjectData);
    }
    myObject_release(myObjectData);
}

Hopefully this makes sense...

There is no race condition (because the reference count is always increased *before* a reference is given to anything else).


Cheers,

Brendan

Re: Fixing potential race condition

Posted: Wed Nov 05, 2008 8:48 am
by cyr1x
Again,
the atomicity is not the problem!!
The problem is that an object can be deleted while there is somebody waiting to reference it.

Well I think I found a solution myself.

Code: Select all

bool Reference()
{
  lock;
  if(!ObjectIsAvailable(this))    // check if the object is available or it's deleted already
   return false;    
  refCount++;                  // <-- this was already atomic before!
  unlock;
  return true;
}

void Release()
{
  lock;
  refCount--;
  if(refCount == 0)           // check if the objects count is zero
  {
   removeFromObjectList(this); // remove from list ...
   delete this;                 // ... and delete it
  }
  unlock;
}

Why all this? I wanted the reference count to be 0. The point was not to trust the object creator that it removes the reference afterwards.
After thinking a while about Brendan's solution I think I change it to be 1 at initialisation.

@ezeaguerre: How to check if the reference count is zero as there isn't any object?

Re: Fixing potential race condition

Posted: Wed Nov 05, 2008 9:50 am
by Colonel Kernel
Brendan wrote:

Code: Select all

void myObject_release(MYOBJECT_DATA *myObjectData) {
    myObjectData->referenceCount--;           // Needs to be "lock sub dword [myObjectData->referenceCount], 1" for multi-CPU
    if(myObjectData->referenceCount == 0) {   // Needs to be "jne .skip_the_next_2_lines" for multi-CPU
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}
As written, this is incorrect due to a race condition. Imagine this scenario:
  • The object has refcount 2.
  • Thread A calls release(), which decrements the refcount to 1.
  • Thread B calls release(), which decrements the refcount to 0.
  • Thread A checks the refcount, sees that it is 0, and destroys the object.
  • Thread B checks the refcount, sees that it is 0, and destroys the object again -> BANG!
The solution is to store the decremented value of the refcount in a local variable. Here it is with a bit of pseudo-code for the atomic instructions:

Code: Select all

void myObject_release(MYOBJECT_DATA *myObjectData) {
    int finalCount = atomic_decrement( &(myObjectData->referenceCount) );
    if (finalCount == 0) {
        myObject_destructor(myObjectData);
        free(myObjectData);
    }
}
cyr1x wrote:the atomicity is not the problem!!
The problem is that an object can be deleted while there is somebody waiting to reference it.
There is no "waiting to reference" an object. Either it is referenced, or it is not. If a thread holds a pointer to an object with refcount 0 (other than during the final execution of release()), it is the result of a double-deletion bug somewhere else in the code.

Brendan's implementation (with my fix) has been used successfully for decades in multi-threaded OO applications and frameworks (most notably in COM on Windows and Objective-C/NeXTStep/Cocoa on NeXT & Mac OS X). It definitely works, as long as objects start with a refcount of 1 and as long as clients of an object match calls to retain/release (a.k.a. AddRef(), Release(), etc.)