hpio icon indicating copy to clipboard operation
hpio copied to clipboard

linux sysfs pin export race

Open joeyh opened this issue 7 years ago • 3 comments

The linux sysfs gpio interface has a race:

root@honeybee:/sys/class/gpio>echo 84 > export ; echo out > gpio84/direction
bash: echo: write error: Device or resource busy

ghci> writeFile "export" "89" >> writeFile "gpio89/direction" "out"
*** Exception: gpio89/direction: hClose: failed (Unknown error 517)

It takes some short time for the export to complete, before that the directory for the pin may not yet exist, or the kernel may be unprepared to handle requests made there.

This seems like the kind of thing that users of hpio, at least the cross-platform part of it, should not need to worry about. I'm only just reading the documentaton for hpio, and have not checked it in the real world to see if it can crash in such a situation.

But, looking at the code of exportPin and System.GPIO.Linux.Sysfs.Monad, I don't see any indications that it tries to deal with this race. A good way to deal with it might be a brief busy-wait on exporting the pin for the pin directory to be created and the direction file to be readable.

joeyh avatar Apr 14 '18 12:04 joeyh

Thanks for the report. I don't think I've seen this is actual use, but I'll take a look at the code.

What is the platform you're using to produce this race in bash?

dhess avatar Apr 14 '18 14:04 dhess

I've seen the race on a cuietruck running debian testing with the stock debian kernel (4.15.11).

However, the bash example is wrong; I forgot that gpio pin 84 was actually already enabled, and the double-enable is what failed there, thus the "busy". Sorry for the bad example.

The haskell example does demonstrate the race. I've not seen it fail in hClose like that before; all the times I can remember before when I dealt with this race the gpioXX directory didn't exist yet immediately after exporting the pin.

-- see shy jo

joeyh avatar Apr 14 '18 18:04 joeyh

BTW, the linux sysfs gpio interface is deprecated; the character device interface probably does not suffer from these race conditions. https://git.kernel.org/pub/scm/libs/libgpiod/libgpiod.git/tree/

-- see shy jo

joeyh avatar Apr 14 '18 18:04 joeyh