Sub-microsecond delays in Linux device drivers

Many pieces of hardware require short delays between setting registers or bus accesses. The linux delay routines mdelay, udelay and ndelay are defined in <linux/delay.h> but on some (most?) systems ndelay is just rounded to the nearest microsecond which can be too long when trying to optimise a driver function that will be called a lot.

In device drivers hardware access often takes place in interrupt context and so the following function could be used for very short delays. Based on the processor frequency you can calculate the approximate number of clock cycles needed for some time delay so this doesn’t have to be done at run time.


/*
* Assume interrupts are turned off.
* Length of each clock cycle = (1 / ProcessorFrequency)
*/
__inline__ void nop_sleep(unsigned long clk_cycs) {
      while (clk_cycs-- > 0)
            __asm__ volatile ("nop;");
}

I know this might be dirty way of doing it – unportable code. Correct me if you’ve got better ideas.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s