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