lkml.org 
[lkml]   [2000]   [Oct]   [17]   [last100]   RSS Feed
Views: [wrap][no wrap]   [headers]  [forward] 
 
Messages in this thread
/
Date
From
SubjectRe: Is this a valid construct?
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/

\
 
 \ /
  Last update: 2005-03-22 12:45    [W:0.058 / U:7.956 seconds]
©2003-2018 Jasper Spaans|hosted at Digital Ocean and TransIP|Read the blog|Advertise on this site