title: Linux Kernel Modules: When to use try_module_get / module_put
body: <p>I was reading the LKMPG ( <a href="http://tldp.org/LDP/lkmpg/2.6/html/x569.html" rel="noreferrer">See Section 4.1.4. Unregistering A Device</a> ) and it wasn't clear to me when to use the <code>try_module_get / module_put</code> functions.  Some of the LKMPG examples use them, some don't.</p>
  
  <p>To add to the confusion, <code>try_module_get</code> appears 282 times in 193 files in the 2.6.24 source, yet in <a href="http://lwn.net/Kernel/LDD3/" rel="noreferrer">Linux Device Drivers ( LDD3 )</a> and <a href="http://www.elinuxdd.com/" rel="noreferrer">Essential Linux Device Drivers</a>, they appears in not even a single code example.</p>
  
  <p>I thought maybe they were tied to the old <code>register_chrdev</code> interface ( superseded in 2.6 by the cdev interface ), but they only appear together in the same files 8 times:</p>
  
  <pre><code>find -type f -name *.c | xargs grep -l try_module_get | sort -u | xargs grep -l register_chrdev | sort -u | grep -c .
  </code></pre>
  
  <p>So when is it appropriate to use these functions and are they tied to the use of a particular interface or set of circumstances?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>I loaded the <a href="http://tldp.org/LDP/lkmpg/2.6/html/x1211.html#AEN1250" rel="noreferrer">sched.c</a> example from the LKMPG and tried the following experiment:</p>
  
  <pre><code>anon@anon:~/kernel-source/lkmpg/2.6.24$ tail /proc/sched -f &amp;
  Timer called 5041 times so far
  [1] 14594
  
  anon@anon:~$ lsmod | grep sched
  sched                   2868  1 
  
  anon@anon:~$ sudo rmmod sched
  ERROR: Module sched is in use
  </code></pre>
  
  <p>This leads me to believe that the kernel now does it's own accounting and the gets / puts may be obsolete.  Can anyone verify this?</p>