mousedrivers.tmpl
上传用户:jlfgdled
上传日期:2013-04-10
资源大小:33168k
文件大小:35k
源码类别:

Linux/Unix编程

开发平台:

Unix_Linux

  1. <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
  2. <book id="MouseGuide">
  3.  <bookinfo>
  4.   <title>Mouse Drivers</title>
  5.   
  6.   <authorgroup>
  7.    <author>
  8.     <firstname>Alan</firstname>
  9.     <surname>Cox</surname>
  10.     <affiliation>
  11.      <address>
  12.       <email>alan@redhat.com</email>
  13.      </address>
  14.     </affiliation>
  15.    </author>
  16.   </authorgroup>
  17.   <copyright>
  18.    <year>2000</year>
  19.    <holder>Alan Cox</holder>
  20.   </copyright>
  21.   <legalnotice>
  22.    <para>
  23.      This documentation is free software; you can redistribute
  24.      it and/or modify it under the terms of the GNU General Public
  25.      License as published by the Free Software Foundation; either
  26.      version 2 of the License, or (at your option) any later
  27.      version.
  28.    </para>
  29.       
  30.    <para>
  31.      This program is distributed in the hope that it will be
  32.      useful, but WITHOUT ANY WARRANTY; without even the implied
  33.      warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  34.      See the GNU General Public License for more details.
  35.    </para>
  36.       
  37.    <para>
  38.      You should have received a copy of the GNU General Public
  39.      License along with this program; if not, write to the Free
  40.      Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
  41.      MA 02111-1307 USA
  42.    </para>
  43.       
  44.    <para>
  45.      For more details see the file COPYING in the source
  46.      distribution of Linux.
  47.    </para>
  48.   </legalnotice>
  49.  </bookinfo>
  50.  <toc></toc>
  51.  <chapter id="intro">
  52.   <title>Introduction</title>
  53.   <note>
  54.    <title>Earlier publication</title>
  55.     <para>
  56.       Parts of this document first appeared in Linux Magazine under a
  57.       ninety day exclusivity.
  58.    </para>
  59.   </note> 
  60.   <para>
  61.     Mice are conceptually one of the simplest device interfaces in the 
  62.     Linux operating system. Not all mice are handled by the kernel. 
  63.     Instead there is a two layer abstraction.
  64.   </para>
  65.   <para>
  66.     The kernel mouse drivers and userspace drivers for the serial mice are
  67.     all managed by a system daemon called <application>gpm</application> 
  68.     - the general purpose mouse driver. <application>gpm</application> 
  69.     handles cutting and pasting on the text consoles. It provides a 
  70.     general library for mouse-aware applications and it handles the 
  71.     sharing of mouse services with the 
  72.     <application>X Window System</application> user interface.
  73.   </para>
  74.   <para>
  75.     Sometimes a mouse speaks a sufficiently convoluted protocol that the
  76.     protocol is handled by <application>Gpm</application> itself. Most 
  77.     of the mouse drivers follow a common interface called the bus mouse 
  78.     protocol.
  79.   </para>
  80.   <para>
  81.     Each read from a bus mouse interface device returns a block of data. 
  82.     The first three bytes of each read are defined as follows: 
  83.    <table frame=all>
  84.     <title>Mouse Data Encoding</title>
  85.     <tgroup cols=2 align=left>
  86.      <tbody>
  87.       <row>
  88.        <entry>Byte 0</entry>
  89.        <entry>0x80 + the buttons currently down.</entry>
  90.       </row>
  91.       <row>
  92.        <entry>Byte 1</entry>
  93.        <entry>A signed value for the shift in X position</entry>
  94.       </row>
  95.       <row>
  96.        <entry>Byte 2</entry>
  97.        <entry>A signed value for the shift in Y position</entry>
  98.       </row>
  99.      </tbody>
  100.     </tgroup>
  101.    </table>
  102.     An application can choose to read more than 3 bytes. The rest of the 
  103.     bytes will be zero, or may optionally return some additional 
  104.     device-specific information.
  105.   </para>
  106.   <para>
  107.     The position values are truncated if they exceed the 8bit range (that
  108.     is -127 &lt;= delta &lt;= 127). While the value -128 does fit into a 
  109.     byte is not allowed.
  110.   </para>
  111.   <para>
  112.     The <mousebutton>buttons</mousebutton> are numbered left to right as 
  113.     0, 1, 2, 3.. and each button sets the relevant bit. So a user pressing 
  114.     the left and right button of a three button mouse will set bits 0 and 2.
  115.   </para>
  116.   <para>
  117.     All mice are required to support the <function>poll</function> 
  118.     operation. Indeed pretty much every user of a mouse device uses 
  119.     <function>poll</function> to wait for mouse events to occur.
  120.   </para>
  121.   <para>
  122.     Finally the mice support asynchronous I/O. This is a topic we have not 
  123.     yet covered but which I will explain after looking at a simple mouse 
  124.     driver.
  125.   </para>
  126.  </chapter>
  127.  <chapter id="driver">
  128.   <title>A simple mouse driver</title>
  129.   <para>
  130.     First we will need the set up functions for our mouse device. To keep 
  131.     this simple our imaginary mouse device has three I/O ports fixed at I/O 
  132.     address 0x300 and always lives on interrupt 5.  The ports will be the X 
  133.     position, the Y position and the buttons in that order.
  134.   </para>
  135.   <programlisting>
  136. #define OURMOUSE_BASE        0x300
  137. static struct miscdevice our_mouse = {
  138.         OURMOUSE_MINOR, "ourmouse", &amp;our_mouse_fops
  139. };
  140. __init ourmouse_init(void)
  141. {
  142.         if(check_region(OURMOUSE_BASE, 3))
  143.                 return -ENODEV;
  144.         request_region(OURMOUSE_BASE, 3, "ourmouse");
  145.         misc_register(&amp;our_mouse);
  146.         return 0;
  147. }
  148.   </programlisting>
  149.   <para>
  150.     The <structname>miscdevice</structname> is new here. Linux normally 
  151.     parcels devices out by major number, and each device has 256 units. 
  152.     For things like mice this is extremely wasteful so a device exists 
  153.     which is used to accumulate all the odd individual devices that 
  154.     computers tend to have.
  155.   </para>
  156.   <para>
  157.     Minor numbers in this space are allocated by a central source, although 
  158.     you can look in the kernel <filename>Documentation/devices.txt</filename>
  159.     file and pick a free one for development use. This kernel file also 
  160.     carries instructions for registering a device. This may change over time 
  161.     so it is a good idea to obtain a current copy of this file first.
  162.   </para>
  163.   <para>
  164.     Our code then is fairly simple. We check nobody else has taken our 
  165.     address space. Having done so we reserve it to ensure nobody stamps 
  166.     on our device while probing for other ISA bus devices. Such a probe 
  167.     might confuse our device.
  168.   </para>
  169.   <para>
  170.     Then we tell the misc driver that we wish to own a minor number. We also
  171.     hand it our name (which is used in 
  172.     <filename class="directory">/proc/misc</filename>) and a set of file 
  173.     operations that are to be used. The file operations work exactly like the 
  174.     file operations you would register for a normal character device. The misc 
  175.     device itself is simply acting as a redirector for requests.
  176.   </para>
  177.   <para>
  178.     Next, in order to be able to use and test our code we need to add some 
  179.     module code to support it. This too is fairly simple:
  180.   </para>
  181.   <programlisting>
  182. #ifdef MODULE
  183. int init_module(void)
  184. {
  185.         if(ourmouse_init()&lt;0)
  186.                 return -ENODEV:
  187.         return 0;
  188. }
  189. void cleanup_module(void)
  190. {
  191.         misc_deregister(&amp;our_mouse);
  192.         free_region(OURMOUSE_BASE, 3);
  193. }
  194. #endif
  195.   </programlisting>
  196.   <para>
  197.     The module code provides the normal two functions. The 
  198.     <function>init_module</function> function is called when the module is 
  199.     loaded. In our case it simply calls the initialising function we wrote 
  200.     and returns an error if this fails. This ensures the module will only 
  201.     be loaded if it was successfully set up.
  202.   </para>
  203.   <para>
  204.     The <function>cleanup_module</function> function is called when the 
  205.     module is unloaded. We give the miscellaneous device entry back, and 
  206.     then free our I/O resources. If we didn't free the I/O resources then 
  207.     the next time the module loaded it would think someone else had its I/O 
  208.     space.
  209.   </para>
  210.   <para>
  211.     Once the <function>misc_deregister</function> has been called any 
  212.     attempts to open the mouse device will fail with the error  
  213.     <errorcode>ENODEV</errorcode> (<errorname>No such device</errorname>).
  214.   </para>
  215.   <para>
  216.     Next we need to fill in our file operations. A mouse doesn't need many 
  217.     of these. We need to provide open, release, read and poll. That makes 
  218.     for a nice simple structure:
  219.   </para>
  220.   <programlisting>
  221. struct file_operations our_mouse_fops = {
  222.         owner: THIS_MODULE,            /* Automatic usage management */
  223.         read:  read_mouse,             /* You can read a mouse */
  224.         write: write_mouse,            /* This won't do a lot */
  225.         poll:  poll_mouse,             /* Poll */
  226.         open:  open_mouse,             /* Called on open */
  227.         release: close_mouse,          /* Called on close */
  228. };
  229.   </programlisting>
  230.   <para>
  231.     There is nothing particularly special needed here. We provide functions 
  232.     for all the relevant or required operations and little else. There is 
  233.     nothing stopping us providing an ioctl function for this mouse. Indeed 
  234.     if you have a configurable mouse it may be very appropriate to provide 
  235.     configuration interfaces via ioctl calls.
  236.   </para>
  237.   <para>
  238.     The syntax we use is not standard C as such. GCC provides the ability
  239.     to initialise fields by name, and this generally makes the method table
  240.     much easier to read than counting through NULL pointers and remembering
  241.     the order by hand.
  242.   </para>
  243.   <para>
  244.     The owner field is used to manage the locking of module load an
  245.     unloading. It is obviously important that a module is not unloaded while
  246.     in use. When your device is opened the module specified by "owner" is 
  247.     locked. When it is finally released the module is unlocked.
  248.   </para>
  249.   <para>
  250.     The open and close routines need to manage enabling and disabling the 
  251.     interrupts for the mouse as well as stopping the mouse being unloaded
  252.     when it is no longer required. 
  253.   </para>
  254.   <programlisting>
  255. static int mouse_users = 0;                /* User count */
  256. static int mouse_dx = 0;                   /* Position changes */
  257. static int mouse_dy = 0;
  258. static int mouse_event = 0;                /* Mouse has moved */
  259. static int open_mouse(struct inode *inode, struct file *file)
  260. {
  261.         if(mouse_users++)
  262.                 return 0;
  263.         if(request_irq(mouse_intr, OURMOUSE_IRQ, 0, "ourmouse", NULL))
  264.         {
  265.                 mouse_users--;
  266.                 return -EBUSY;
  267.         }
  268.         mouse_dx = 0;
  269.         mouse_dy = 0;
  270.         mouse_event = 0;
  271.         mouse_buttons = 0;
  272. return 0;
  273. }
  274.   </programlisting>
  275.   <para>
  276.     The open function has to do a small amount of housework. We keep a count 
  277.     of the number of times the mouse is open. This is because we do not want 
  278.     to request the interrupt multiple times. If the mouse has at least one 
  279.     user then it is set up and we simply add to the user count and return
  280.     <returnvalue>0</returnvalue> for success.
  281.   </para>
  282.   <para>
  283.     We grab the interrupt and thus start mouse interrupts. If the interrupt 
  284.     has been borrowed by some other driver then <function>request_irq</function>
  285.     will fail and we will return an error. If we were capable of sharing an 
  286.     interrupt line we would specify <constant>SA_SHIRQ</constant> instead of 
  287.     <constant>zero</constant>. Provided that everyone claiming an interrupt 
  288.     sets this flag, they get to share the line. <hardware>PCI</hardware> can 
  289.     share interrupts, <hardware>ISA</hardware> normally however cannot. 
  290.   </para>
  291.   <para>
  292.     We do the housekeeping. We make the current mouse position the starting
  293.     point for accumulated changes and declare that nothing has happened
  294.     since the mouse driver was opened.
  295.   </para>
  296.   <para>
  297.     The release function needs to unwind all these:
  298.   </para>
  299.   <programlisting>
  300. static int close_mouse(struct inode *inode, struct file *file)
  301. {
  302.         if(--mouse_users)
  303.                 return 0;
  304.         free_irq(OURMOUSE_IRQ, NULL);
  305.         return 0;
  306. }
  307.   </programlisting>
  308.   <para>
  309.     We count off a user and provided that there are still other users need 
  310.     take no further action. The last person closing the mouse causes us to 
  311.     free up the interrupt. This stops interrupts from the mouse from using 
  312.     our CPU time, and ensures that the mouse can now be unloaded.
  313.   </para>
  314.   <para>
  315.     We can fill in the write handler at this point as the write function for 
  316.     our mouse simply declines to allow writes:
  317.   </para>
  318.   <programlisting>
  319. static ssize_t write_mouse(struct file *file, const char *buffer, size_t
  320.                                 count, loff_t *ppos)
  321. {
  322.         return -EINVAL;
  323. }
  324.   </programlisting>
  325.   <para>
  326.     This is pretty much self-explanatory. Whenever you write you get told 
  327.     it was an invalid function.
  328.   </para>
  329.   <para>
  330.     To make the poll and read functions work we have to consider how we 
  331.     handle the mouse interrupt. 
  332.   </para>
  333.   <programlisting>
  334. static struct wait_queue *mouse_wait;
  335. static spinlock_t mouse_lock = SPIN_LOCK_UNLOCKED;
  336. static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
  337. {
  338.         char delta_x;
  339.         char delta_y;
  340.         unsigned char new_buttons;
  341.         delta_x = inb(OURMOUSE_BASE);
  342.         delta_y = inb(OURMOUSE_BASE+1);
  343.         new_buttons = inb(OURMOUSE_BASE+2);
  344.         if(delta_x || delta_y || new_buttons != mouse_buttons)
  345.         {
  346.                 /* Something happened */
  347.                 spin_lock(&amp;mouse_lock);
  348.                 mouse_event = 1;
  349.                 mouse_dx += delta_x;
  350.                 mouse_dy += delta_y;
  351.                 mouse_buttons = new_buttons;
  352.                 spin_unlock(&amp;mouse_lock);
  353.                 
  354.                 wake_up_interruptible(&amp;mouse_wait);
  355.         }
  356. }
  357.   </programlisting>
  358.   <para>
  359.     The interrupt handler reads the mouse status. The next thing we do is 
  360.     to check whether something has changed. If the mouse was smart it would
  361.     only interrupt us if something had changed, but let's assume our mouse 
  362.     is stupid as most mice actually tend to be. 
  363.   </para>
  364.   <para>
  365.     If the mouse has changed we need to update the status variables. What we
  366.     don't want is the mouse functions reading these variables to read them
  367.     during a change. We add a spinlock that protects these variables while we
  368.     play with them.
  369.   </para>
  370.   <para>
  371.     If a change has occurred we also need to wake sleeping processes, so we 
  372.     add a wakeup call and a <structname>wait_queue</structname> to use when 
  373.     we wish to await a mouse event.
  374.   </para>
  375.   <para>
  376.     Now we have the wait queue we can implement the poll function for the 
  377.     mouse relatively easily:
  378.   </para>
  379.   <programlisting>
  380. static unsigned int mouse_poll(struct file *file, poll_table *wait)
  381. {
  382.         poll_wait(file, &amp;mouse_wait, wait);
  383.         if(mouse_event)
  384.                 return POLLIN | POLLRDNORM;
  385.         return 0;
  386. }
  387.   </programlisting>
  388.   <para>
  389.     This is fairly standard poll code. First we add the wait queue to the 
  390.     list of queues we want to monitor for an event. Secondly we check if an 
  391.     event has occurred. We only have one kind of event - the 
  392.     <varname>mouse_event</varname> flag tells us that something happened. 
  393.     We know that this something can only be mouse data. We return the flags 
  394.     indicating input and normal reading will succeed.
  395.   </para>
  396.   <para>
  397.     You may be wondering what happens if the function returns saying 'no 
  398.     event yet'. In this case the wake up from the wait queue we added to 
  399.     the poll table will cause the function to be called again. Eventually 
  400.     we will be woken up and have an event ready. At this point the 
  401.     <function>poll</function> call will exit back to the user.
  402.   </para>
  403.   <para>
  404.     After the poll completes the user will want to read the data. We now 
  405.     need to think about how our <function>mouse_read</function> function 
  406.     will work:
  407.   </para>
  408.   <programlisting>
  409. static ssize_t mouse_read(struct file *file, char *buffer, 
  410.                 size_t count, loff_t *pos)
  411. {
  412.         int dx, dy;
  413.         unsigned char button;
  414.         unsigned long flags;
  415.         int n;
  416.         if(count&lt;3)
  417.                 return -EINVAL;
  418.         /*
  419.           *        Wait for an event
  420.          */
  421.         while(!mouse_event)
  422.         {
  423.                 if(file-&gt;f_flags&amp;O_NDELAY)
  424.                         return -EAGAIN;
  425.                 interruptible_sleep_on(&amp;mouse_wait);
  426.                 if(signal_pending(current))
  427.                         return -ERESTARTSYS;
  428.         }
  429.   </programlisting>
  430.   <para>
  431.     We start by validating that the user is reading enough data. We could 
  432.     handle partial reads if we wanted but it isn't terribly useful and the 
  433.     mouse drivers don't bother to try.
  434.   </para>
  435.   <para>
  436.     Next we wait for an event to occur. The loop is fairly standard event
  437.     waiting in Linux. Having checked that the event has not yet occurred, we
  438.     then check if an event is pending and if not we need to sleep. 
  439.   </para>
  440.   <para>
  441.     A user process can set the <constant>O_NDELAY</constant> flag on a file 
  442.     to indicate that it wishes to be told immediately if no event is 
  443.     pending. We check this and give the appropriate error if so. 
  444.   </para>
  445.   <para>
  446.     Next we sleep until the mouse or a signal awakens us. A signal will 
  447.     awaken us as we have used <function>wakeup_interruptible</function>. 
  448.     This is important as it means a user can kill processes waiting for 
  449.     the mouse - clearly a desirable property. If we are interrupted we 
  450.     exit the call and the kernel will then process signals and maybe 
  451.     restart the call again - from the beginning.
  452.   </para>
  453.   <para>
  454.     This code contains a classic Linux bug. All will be revealed later in this
  455.     article as well as explanations for how to avoid it.
  456.   </para>
  457.   <programlisting>
  458.         /* Grab the event */
  459.         spinlock_irqsave(&amp;mouse_lock, flags);
  460.         dx = mouse_dx;
  461.         dy = mouse_dy;
  462.         button = mouse_buttons;
  463.         if(dx&lt;=-127)
  464.                 dx=-127;
  465.         if(dx&gt;=127)
  466.                 dx=127;
  467.         if(dy&lt;=-127)
  468.                 dy=-127;
  469.         if(dy&gt;=127)
  470.                 dy=127;
  471.         mouse_dx -= dx;
  472.         mouse_dy -= dy;
  473.         
  474.         if(mouse_dx == 0 &amp;&amp; mouse_dy == 0)
  475.                 mouse_event = 0;
  476.         spin_unlock_irqrestore(&amp;mouse_lock, flags);
  477.   </programlisting>
  478.   <para>
  479.     This is the next stage. Having established that there is an event 
  480.     going, we capture it. To be sure that the event is not being updated 
  481.     as we capture it we also take the spinlock and thus prevent parallel 
  482.     updates. Note here we use <function>spinlock_irqsave</function>. We 
  483.     need to disable interrupts on the local processor otherwise bad things 
  484.     will happen.
  485.   </para>
  486.   <para>
  487.     What will occur is that we take the spinlock. While we hold the lock 
  488.     an interrupt will occur. At this point our interrupt handler will try 
  489.     and take the spinlock. It will sit in a loop waiting for the read 
  490.     routine to release the lock. However because we are sitting in a loop 
  491.     in the interrupt handler we will never release the lock. The machine 
  492.     hangs and the user gets upset.
  493.   </para>
  494.   <para>
  495.     By blocking the interrupt on this processor we ensure that the lock 
  496.     holder will always give the lock back without deadlocking.
  497.   </para>
  498.   <para>
  499.     There is a little cleverness in the reporting mechanism too. We can 
  500.     only report a move of 127 per read. We don't however want to lose 
  501.     information by throwing away further movement. Instead we keep 
  502.     returning as much information as possible. Each time we return a 
  503.     report we remove the amount from the pending movement in 
  504.     <varname>mouse_dx</varname> and <varname>mouse_dy</varname>. Eventually 
  505.     when these counts hit zero we clear the <varname>mouse_event</varname>
  506.     flag as there is nothing else left to report.
  507.   </para>
  508.   <programlisting>
  509.         if(put_user(button|0x80, buffer))
  510.                 return -EFAULT;
  511.         if(put_user((char)dx, buffer+1))
  512.                 return -EFAULT;
  513.         if(put_user((char)dy, buffer+2))
  514.                 return -EFAULT;
  515.         for(n=3; n < count; n++)
  516.                 if(put_user(0x00, buffer+n))
  517.                         return -EFAULT;
  518.         return count;
  519. }
  520.   </programlisting>
  521.   <para>
  522.     Finally we must put the results in the user supplied buffer. We cannot 
  523.     do this while holding the lock as a write to user memory may sleep. 
  524.     For example the user memory may be residing on disk at this instant. 
  525.     Thus we did our computation beforehand and now copy the data. Each 
  526.     <function>put_user call</function> is filling in one byte of the buffer. 
  527.     If it returns an error we inform the program that it passed us an 
  528.     invalid buffer and abort.
  529.   </para>
  530.   <para>
  531.     Having written the data we blank the rest of the buffer that was read 
  532.     and report the read as being successful.
  533.   </para>
  534.  </chapter>
  535.  <chapter id="debugging">
  536.   <title>Debugging the mouse driver</title>
  537.   <para>
  538.     We now have an almost perfectly usable mouse driver. If you were to 
  539.     actually try and use it however you would eventually find a couple of 
  540.     problems with it. A few programs will also not work with as it does not 
  541.     yet support asynchronous I/O.
  542.   </para>
  543.   <para>
  544.     First let us look at the bugs. The most obvious one isn't really a driver
  545.     bug but a failure to consider the consequences. Imagine you bumped the 
  546.     mouse hard by accident and sent it skittering across the desk. The mouse 
  547.     interrupt routine will add up all that movement and report it in steps of 
  548.     127 until it has reported all of it. Clearly there is a point beyond 
  549.     which mouse movement isn't worth reporting. We need to add this as a 
  550.     limit to the interrupt handler:
  551.   </para>
  552.   <programlisting>
  553. static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
  554. {
  555.         char delta_x;
  556.         char delta_y;
  557.         unsigned char new_buttons;
  558.         delta_x = inb(OURMOUSE_BASE);
  559.         delta_y = inb(OURMOUSE_BASE+1);
  560.         new_buttons = inb(OURMOUSE_BASE+2);
  561.         if(delta_x || delta_y || new_buttons != mouse_buttons)
  562.         {
  563.                 /* Something happened */
  564.                 spin_lock(&amp;mouse_lock);
  565.                 mouse_event = 1;
  566.                 mouse_dx += delta_x;
  567.                 mouse_dy += delta_y;
  568.                 if(mouse_dx &lt; -4096)
  569.                         mouse_dx = -4096;
  570.                 if(mouse_dx &gt; 4096)
  571.                         mouse_dx = 4096;
  572.                 if(mouse_dy &lt; -4096)
  573.                         mouse_dy = -4096;
  574.                 if(mouse_dy &gt; 4096)
  575.                         mouse_dy = 4096;
  576.                 mouse_buttons = new_buttons;
  577.                 spin_unlock(&amp;mouse_lock);
  578.                 
  579.                 wake_up_interruptible(&amp;mouse_wait);
  580.         }
  581. }
  582.   </programlisting>
  583.   <para>
  584.     By adding these checks we limit the range of accumulated movement to
  585.     something sensible. 
  586.   </para>
  587.   <para>
  588.     The second bug is a bit more subtle, and that is perhaps why this is 
  589.     such a common mistake. Remember, I said the waiting loop for the read 
  590.     handler had a bug in it. Think about what happens when we execute:
  591.   </para>
  592.   <programlisting>
  593.         while(!mouse_event)
  594.         {
  595.   </programlisting>
  596.   <para>
  597.     and an interrupt occurs at this point here. This causes a mouse movement
  598.     and wakes up the queue. 
  599.   </para>
  600.   <programlisting>
  601.                 interruptible_sleep_on(&amp;mouse_wait);
  602.   </programlisting>
  603.   <para>
  604.     Now we sleep on the queue. We missed the wake up and the application 
  605.     will not see an event until the next mouse event occurs. This will 
  606.     lead to just the odd instance when a mouse button gets delayed. The 
  607.     consequences to the user will probably be almost undetectable with a 
  608.     mouse driver. With other drivers this bug could be a lot more severe.
  609.   </para>
  610.   <para>
  611.     There are two ways to solve this. The first is to disable interrupts 
  612.     during the testing and the sleep. This works because when a task sleeps 
  613.     it ceases to disable interrupts, and when it resumes it disables them 
  614.     again. Our code thus becomes:
  615.   </para>
  616.   <programlisting>
  617.         save_flags(flags);
  618.         cli();
  619.         while(!mouse_event)
  620.         {
  621.                 if(file-&gt;f_flags&amp;O_NDELAY)
  622.                 {
  623.                         restore_flags(flags);
  624.                         return -EAGAIN;
  625.                 }
  626.                 interruptible_sleep_on(&amp;mouse_wait);
  627.                 if(signal_pending(current))
  628.                 {
  629.                         restore_flags(flags);
  630.                         return -ERESTARTSYS;
  631.                 }
  632.         }
  633.         restore_flags(flags);
  634.   </programlisting>
  635.   <para>
  636.     This is the sledgehammer approach. It works but it means we spend a 
  637.     lot more time turning interrupts on and off. It also affects 
  638.     interrupts globally and has bad properties on multiprocessor machines 
  639.     where turning interrupts off globally is not a simple operation, but 
  640.     instead involves kicking each processor, waiting for them to disable 
  641.     interrupts and reply.
  642.   </para>
  643.   <para>
  644.     The real problem is the race between the event testing and the sleeping. 
  645.     We can avoid that by using the scheduling functions more directly. 
  646.     Indeed this is the way they generally should be used for an interrupt.
  647.   </para>
  648.   <programlisting>
  649.         struct wait_queue wait = { current, NULL };
  650.         add_wait_queue(&amp;mouse_wait, &amp;wait);
  651.         set_current_state(TASK_INTERRUPTIBLE);
  652.         
  653.         while(!mouse_event)
  654.         {
  655.                 if(file-&gt;f_flags&amp;O_NDELAY)
  656.                 {
  657.                         remove_wait_queue(&amp;mouse_wait, &amp;wait);
  658.                         set_current_state(TASK_RUNNING);
  659.                         return -EWOULDBLOCK;
  660.                 }
  661.                 if(signal_pending(current))
  662.                 {
  663.                         remove_wait_queue(&amp;mouse_wait, &amp;wait);
  664.                         current-&gt;state = TASK_RUNNING;
  665.                         return -ERESTARTSYS;
  666.                 }
  667.                 schedule();
  668.                 set_current_state(TASK_INTERRUPTIBLE);
  669.         }
  670.         
  671.         remove_wait_wait(&amp;mouse_wait, &amp;wait);
  672.         set_current_state(TASK_RUNNING);
  673.   </programlisting>
  674.   <para>
  675.     At first sight this probably looks like deep magic. To understand how 
  676.     this works you need to understand how scheduling and events work on 
  677.     Linux. Having a good grasp of this is one of the keys to writing clean 
  678.     efficient device drivers.
  679.   </para>
  680.   <para>
  681.     <function>add_wait_queue</function> does what its name suggests. It adds 
  682.     an entry to the <varname>mouse_wait</varname> list. The entry in this 
  683.     case is the entry for our current process (<varname>current</varname>
  684.     is the current task pointer). 
  685.   </para>
  686.   <para>
  687.     So we start by adding an entry for ourself onto the 
  688.     <varname>mouse_wait</varname> list. This does not put us to sleep 
  689.     however. We are merely tagged onto the list. 
  690.   </para>
  691.   <para>
  692.     Next we set our status to <constant>TASK_INTERRUPTIBLE</constant>. Again 
  693.     this does not mean we are now asleep. This flag says what should happen 
  694.     next time the process sleeps. <constant>TASK_INTERRUPTIBLE</constant> says 
  695.     that the process should not be rescheduled. It will run from now until it 
  696.     sleeps and then will need to be woken up.
  697.   </para>
  698.   <para>
  699.     The <function>wakeup_interruptible</function> call in the interrupt 
  700.     handler can now be explained in more detail. This function is also very 
  701.     simple. It goes along the list of processes on the queue it is given and 
  702.     any that are marked as <constant>TASK_INTERRUPTIBLE</constant> it changes 
  703.     to <constant>TASK_RUNNING</constant> and tells the kernel that new 
  704.     processes are runnable.
  705.   </para>
  706.   <para>
  707.     Behind all the wrappers in the original code what is happening is this
  708.   </para>
  709.   <procedure>
  710.    <step>
  711.     <para>
  712.       We add ourself to the mouse wait queue
  713.     </para>
  714.    </step>
  715.    <step>
  716.     <para>
  717.       We mark ourself as sleeping
  718.     </para>
  719.    </step>
  720.    <step>
  721.     <para>
  722.       We ask the kernel to schedule tasks again
  723.     </para>
  724.    </step>
  725.    <step>
  726.     <para>
  727.       The kernel sees we are asleep and schedules someone else.
  728.     </para>
  729.    </step>
  730.    <step>
  731.     <para>
  732.       The mouse interrupt sets our state to <constant>TASK_RUNNING</constant> 
  733.       and makes a note that the kernel should reschedule tasks
  734.     </para>
  735.    </step>
  736.    <step>
  737.     <para>
  738.       The kernel sees we are running again and continues our execution
  739.     </para>
  740.    </step>
  741.   </procedure>
  742.   <para>
  743.     This is why the apparent magic works. Because we mark ourself as
  744.     <constant>TASK_INTERRUPTIBLE</constant> and as we add ourselves 
  745.     to the queue before we check if there are events pending, the race 
  746.     condition is removed.
  747.   </para>
  748.   <para>
  749.     Now if an interrupt occurs after we check the queue status and before 
  750.     we call the <function>schedule</function> function in order to sleep, 
  751.     things work out. Instead of missing an event, we are set back to 
  752.     <constant>TASK_RUNNING</constant> by the mouse interrupt. We still call 
  753.     <function>schedule</function> but it will continue running our task. 
  754.     We go back around the loop and this time there may be an event.
  755.   </para>
  756.   <para>
  757.     There will not always be an event. Thus we set ourselves back to
  758.     <constant>TASK_INTERRUPTIBLE</constant> before resuming the loop. 
  759.     Another process doing a read may already have cleared the event flag, 
  760.     and if so we will need to go back to sleep again. Eventually we will 
  761.     get our event and escape.
  762.   </para>
  763.   <para>
  764.     Finally when we exit the loop we remove ourselves from the 
  765.     <varname>mouse_wait</varname> queue as we are no longer interested
  766.     in mouse events, and we set ourself back to 
  767.     <constant>TASK_RUNNABLE</constant> as we do not wish to go to sleep 
  768.     again just yet.
  769.   </para>
  770.   <note>
  771.    <title>Note</title> 
  772.    <para>
  773.      This isn't an easy topic. Don't be afraid to reread the description a 
  774.      few times and also look at other device drivers to see how it works. 
  775.      Finally if you can't grasp it just yet, you can use the code as 
  776.      boilerplate to write other drivers and trust me instead.
  777.    </para>
  778.   </note>
  779.  </chapter>
  780.  <chapter id="asyncio">
  781.   <title>Asynchronous I/O</title>
  782.   <para>
  783.     This leaves the missing feature - Asynchronous I/O. Normally UNIX 
  784.     programs use the <function>poll</function> call (or its variant form 
  785.     <function>select</function>) to wait for an event to occur on one of 
  786.     multiple input or output devices. This model works well for most tasks 
  787.     but because <function>poll</function> and <function>select</function> 
  788.     wait for an event isn't suitable for tasks that are also continually 
  789.     doing computation work. Such programs really want the kernel to kick 
  790.     them when something happens rather than watch for events.
  791.   </para>
  792.   <para>
  793.     Poll is akin to having a row of lights in front of you. You can see at a
  794.     glance which ones if any are lit. You cannot however get anything useful
  795.     done while watching them. Asynchronous I/O uses signals which work more 
  796.     like a door bell. Instead of you watching, it tells you that something 
  797.     is up.
  798.   </para>
  799.   <para>
  800.     Asynchronous I/O sends the signal SIGIO to a user process when the I/O 
  801.     events occur. In this case that means when people move the mouse. The 
  802.     SIGIO signal causes the user process to jump to its signal handler and 
  803.     execute code in that handler before returning to whatever was going on 
  804.     previously. It is the application equivalent of an interrupt handler.
  805.   </para>
  806.   <para>
  807.     Most of the code needed for this operation is common to all its users. 
  808.     The kernel provides a simple set of functions for managing asynchronous 
  809.     I/O.
  810.   </para>
  811.   <para>
  812.     Our first job is to allow users to set asynchronous I/O on file handles. 
  813.     To do that we need to add a new function to the file operations table for 
  814.     our mouse:
  815.   </para>
  816.   <programlisting>
  817. struct file_operations our_mouse_fops = {
  818.         owner: THIS_MODULE
  819.         read:  read_mouse,      /* You can read a mouse */
  820.         write: write_mouse,     /* This won't do a lot */
  821.         poll:  poll_mouse,      /* Poll */
  822.         open:  open_mouse,      /* Called on open */
  823.         release: close_mouse,   /* Called on close */
  824.         fasync: fasync_mouse,   /* Asynchronous I/O */
  825. };
  826.   </programlisting>
  827.   <para>
  828.     Once we have installed this entry the kernel knows we support 
  829.     asynchronous I/O and will allow all the relevant operations on the 
  830.     device. Whenever a user adds or removes asynchronous I/O notification 
  831.     on a file handle it calls our <function>fasync_mouse</function> routine 
  832.     we just added. This routine uses the helper functions to keep the queue 
  833.     of handles up to date:
  834.   </para>
  835.   <programlisting>
  836. static struct fasync_struct *mouse_fasync = NULL;
  837. static int fasync_mouse(int fd, struct file *filp, int on)
  838. {
  839.          int retval = fasync_helper(fd, filp, on, &amp;mouse_fasync);
  840.          if (retval &lt; 0)
  841.                  return retval;
  842.         return 0;
  843. }
  844.   </programlisting>
  845.   <para>
  846.     The fasync helper adds and deletes entries by managing the supplied 
  847.     list. We also need to remove entries from this list when the file is 
  848.     closed. This requires we add one line to our close function:
  849.   </para>
  850.   <programlisting>
  851. static int close_mouse(struct inode *inode, struct file *file)
  852. {
  853.         fasync_mouse(-1, file, 0)
  854.         if(--mouse_users)
  855.                 return 0;
  856.         free_irq(OURMOUSE_IRQ, NULL);
  857.         MOD_DEC_USE_COUNT;
  858.         return 0;
  859. }
  860.   </programlisting>
  861.   <para>
  862.     When we close the file we now call our own fasync handler as if the 
  863.     user had requested that this file cease to be used for asynchronous 
  864.     I/O. This rather neatly cleans up any loose ends. We certainly don't 
  865.     wait to deliver a signal for a file that no longer exists.
  866.   </para>
  867.   <para>
  868.     At this point the mouse driver supports all the asynchronous I/O 
  869.     operations, and applications using them will not error. They won't 
  870.     however work yet. We need to actually send the signals. Again the 
  871.     kernel provides a function for handling this.
  872.   </para>
  873.   <para>
  874.     We update our interrupt handler a little:
  875.   </para>
  876.   <programlisting>
  877. static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
  878. {
  879.         char delta_x;
  880.         char delta_y;
  881.         unsigned char new_buttons;
  882.         delta_x = inb(OURMOUSE_BASE);
  883.         delta_y = inb(OURMOUSE_BASE+1);
  884.         new_buttons = inb(OURMOUSE_BASE+2);
  885.         if(delta_x || delta_y || new_buttons != mouse_buttons)
  886.         {
  887.                 /* Something happened */
  888.                 spin_lock(&amp;mouse_lock);
  889.                 mouse_event = 1;
  890.                 mouse_dx += delta_x;
  891.                 mouse_dy += delta_y;
  892.                 if(mouse_dx &lt; -4096)
  893.                         mouse_dx = -4096;
  894.                 if(mouse_dx &gt; 4096)
  895.                         mouse_dx = 4096;
  896.                 if(mouse_dy &lt; -4096)
  897.                         mouse_dy = -4096;
  898.                 if(mouse_dy &gt; 4096)
  899.                         mouse_dy = 4096;
  900.                 mouse_buttons = new_buttons;
  901.                 spin_unlock(&amp;mouse_lock);
  902.                 /* Now we do asynchronous I/O */
  903.                 kill_fasync(&amp;mouse_fasync, SIGIO); 
  904.                 
  905.                 wake_up_interruptible(&amp;mouse_wait);
  906.         }
  907. }
  908.   </programlisting>
  909.   <para>
  910.     The new code simply calls the <function>kill_fasync</function> routine
  911.     provided by the kernel if the queue is non-empty. This sends the 
  912.     required signal (SIGIO in this case) to the process each file handle 
  913.     says should be informed about the exciting new mouse movement that 
  914.     just happened.
  915.   </para>
  916.   <para>
  917.     With this in place and the bugs in the original version fixed, you now 
  918.     have a fully functional mouse driver using the bus mouse protocol. It 
  919.     will work with the <application>X window system</application>, will work 
  920.     with <application>GPM</application> and should work with every other 
  921.     application you need. <application>Doom</application> is of course the 
  922.     ideal way to test your new mouse driver is functioning properly. Be sure 
  923.     to test it thoroughly.
  924.   </para>
  925.  </chapter>
  926. </book>