title: Timekeeping in Linux kernel 2.6
body: <p>I've read chapter 7 in the 'Linux Device Drivers' <a href="http://lwn.net/Kernel/LDD3/" rel="noreferrer">(which can be found here)</a> that time can be measured in 'jiffies'. The problem with the stock jiffies variable is that it wraps around quite frequently (especially if you have your CONFIG_HZ set to 1000).</p>
  
  <p>In my kernel module I'm saving a jiffies value that is set to some time in the future and comparing it at a later time with the current 'jiffies' value. I've learned already that there are functions that take the 32bit jiffy wrap into consideration so to compare two values I'm using this:</p>
  
  <pre><code>if (time_after(jiffies, some_future_jiffies_value))
  {
     // we've already passed the saved value
  }
  </code></pre>
  
  <p>Here comes my question: So now I want to set the 'some_future_jiffies_value' to "now + 10ms". This can easily be accomplished by doing this:</p>
  
  <pre><code>some_future_jiffies_value = jiffies + msecs_to_jiffies(10);
  </code></pre>
  
  <p>Is this correct? What happens if the current jiffies is near MAX_JIFFY_OFFSET and the resulting value of msecs_to_jiffies(10) puts some_future_jiffies_value past that offset? Does it wrap around automatically or should I add some code to check for this? Are there functions that save me from having to deal with this?</p>
  
  <p><strong>Update:</strong></p>
  
  <p>To avoid stuff with wraparound I've rewritten my sleep loop:</p>
  
  <pre><code>   // Sleep for the appropriate time
     while (time_after(some_future_jiffies_value, jiffies))
     {
        set_current_state(TASK_INTERRUPTIBLE);
        schedule_timeout(1);
     }
  </code></pre>
  
  <p>I assume this is more portable right?</p>
  
  <p><strong>Update 2:</strong></p>
  
  <p>Thank you very much 'ctuffli' for taking the time to come back to this question and providing some feedback on my comments as well. My kernel driver is working fine now and it is a lot less ugly compared to the situation before you provided me with all these tips. Thanks!</p>