What's a mutex?

Mutex refers to mutual exclusion. While programming, sometimes you need to access same resource from different threads and if you carelessly try to use that resource a race condition may occur. After that point your code becomes unstable and in some cases security vulnerabilities can born. Mutexes are one group of solutions to race condition problems. Of course, there are many other solutions.

Race conditions are harder to detect bugs. Sometimes they may occur only under heavy load and they undergo undetected for years. Test engineers have to write test cases for shared resources with race conditions in mind.

There are many solutions to handle race conditions; hardware based, software based supported by OS, and even simple application logic.

A kernel level race condition example (and a security vulnerability)

CVE-2014-0196 is a simple and nice example for a kernel level race condition bug.

Check the code below.

            if (tty->ops->flush_chars)
                tty->ops->flush_chars(tty);
        } else {
            while (nr > 0) {
                c = tty->ops->write(tty, b, nr);    /*This is the critical resource. Should've been protected...*/
                if (c < 0) {
                    retval = c;
                    goto break_out;

As you can see, tty object is being written. But what happens when two processes try to write to same tty object? Well, race condition.

The fix is easy with the "mutex_lock" / "mutex_unlock" functions.

            if (tty->ops->flush_chars)
                tty->ops->flush_chars(tty);
        } else {
+           struct n_tty_data *ldata = tty->disc_data;
+
            while (nr > 0) {
+               mutex_lock(&ldata->output_lock);    /*Will wait until the resource is available to our process.*/
                c = tty->ops->write(tty, b, nr);    /*Fragile is now protected.*/
+               mutex_unlock(&ldata->output_lock);  /*Dont forget to release the mutex...*/
                if (c < 0) {
                    retval = c;
                    goto break_out;

That was a brief summary of mutexes and race conditions.

Cheers!