title: How to divide two 64-bit numbers in Linux Kernel?
body: <p>Some code that rounds up the division to demonstrate (C-syntax):</p>
  
  <pre><code>#define SINT64 long long int
  #define SINT32 long int
  
  SINT64 divRound(SINT64 dividend, SINT64 divisor)
  {
    SINT32 quotient1 = dividend / divisor;
  
    SINT32 modResult = dividend % divisor;
    SINT32 multResult = modResult * 2;
    SINT32 quotient2 = multResult / divisor;
  
    SINT64 result = quotient1 + quotient2;
  
    return ( result );
  }
  </code></pre>
  
  <p>Now, if this were User-space we probably wouldn't even notice that our compiler is generating code for those operators (e.g. <code>divdi3()</code> for division). Chances are we link with <code>libgcc</code> without even knowing it. The problem is that Kernel-space is different (e.g. no <code>libgcc</code>). What to do?</p>
  
  <p>Crawl Google for a while, notice that pretty much everyone addresses the unsigned variant:</p>
  
  <pre><code>#define UINT64 long long int
  #define UINT32 long int
  
  UINT64 divRound(UINT64 dividend, UINT64 divisor)
  {
    UINT32 quotient1 = dividend / divisor;
  
    UINT32 modResult = dividend % divisor;
    UINT32 multResult = modResult * 2;
    UINT32 quotient2 = multResult / divisor;
  
    UINT64 result = quotient1 + quotient2;
  
    return ( result );
  }
  </code></pre>
  
  <p>I know how to fix this one: Override <code>udivdi3()</code> and <code>umoddi3()</code> with <code>do_div()</code> from <em>asm/div64.h</em>. Done right? Wrong. Signed is not the same as unsigned, <code>sdivdi3()</code> does not simply call <code>udivdi3()</code>, they are separate functions for a reason.</p>
  
  <p>Have you solved this problem? Do you know of a library that will help me do this? I'm really stuck so whatever you might see here that I just don't right now would be really helpful.</p>
  
  <p>Thanks,
  Chad</p>