Re: Is this a valid construct?

From: Helge Hafting (helgehaf@idb.hist.no)
Date: Tue Oct 17 2000 - 02:43:25 EST


Matthew Dharm wrote:
>
> Does the following pseudocode do what I think it does?
>
> Assume the semaphore is properly initialized to locked.
>
> int flagvar = 0;
> struct semaphore blocking_sem;
>
> void function_called_from_kernel_thread(void)
> {
> chew_on_hardware();
> flagvar = 1;
> down(blocking_sem);
>
> if (flagvar)
> printk("something went wrong")
> else
> printk("everything okay")
> }
>
> void function_called_from_interrupt_context()
> {
> flagvar = 0;
> up(blocking_sem);
> }
>
> void function_to_call_from_timeout()
> {
> up(blocking_sem);
> }
>
> The idea is this -- I chew on the hardware, then sleep on the semaphore. I
> then either get woken up by an IRQ (which may never come), or the timeout.
> I then try to use the flagvar to determine which of the two happened.
>
> This _looks_ valid to me... but I'm seeing occurances where I get the IRQ
> (yes, I'm sure of it) but flagvar == 1, which confuses me.
>
What if the timeout happens, does the "up", *then* the irq happens
while still in the timeout routine?

Consider using two flags, as a debugging aid.
flag_irq_happened
flag_timeout_happened
You can then check 4 possible outcomes:
1. irq happened, no timeout (expected operation)
2. no irq, normal timeout (expected failure)
3. both irq and timeout happened. The window for this may be small,
   but small windows eventually happen - perhaps several times in a
minute.
4. neither happened, so something else went wrong with the semaphore.

> Is this one of those places where I need the "volatile" keyword?
Maybe. Take a look at the generated code, check if the memory read is
optimized away. (I.e. flagvar is "cached" in a register in
function_called_from_kernel_thread(). Or substituted for the
constant "1", as gcc notices that "flagvar" isn't changed between
the assignment and the test using a false assumption about no parallell
execution. "volatile" is supposed to help with that, telling the
compiler
that "this thing may change in mysterious ways, unknown to the generated
code,
i.e. other unknown code or hardware.

Helge Hafting
-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.kernel.org
Please read the FAQ at http://www.tux.org/lkml/



This archive was generated by hypermail 2b29 : Mon Oct 23 2000 - 21:00:10 EST