Ok, there's a test13-pre6 out there now, which does a partial sync with
[davej-history.git] / Documentation / DocBook / mousedrivers.tmpl
blob5d7be51e15bd05f2b4a40fd867818bcb18cd4554
1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V3.1//EN"[]>
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>
19   <copyright>
20    <year>2000</year>
21    <holder>Alan Cox</holder>
22   </copyright>
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>
54  <toc></toc>
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> 
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>
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: 
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>
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>
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>
146   <programlisting>
147 #define OURMOUSE_BASE        0x300
149 static struct miscdevice our_mouse = {
150         OURMOUSE_MINOR, "ourmouse", &amp;our_mouse_fops
153 __init ourmouse_init(void)
156         if(check_region(OURMOUSE_BASE, 3))
157                 return -ENODEV;
158         request_region(OURMOUSE_BASE, 3, "ourmouse");
160         misc_register(&amp;our_mouse);
161         return 0;
163   </programlisting>
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
200 int init_module(void)
202         if(ourmouse_init()&lt;0)
203                 return -ENODEV:
204         return 0;
207 void cleanup_module(void)
209         misc_deregister(&amp;our_mouse);
210         free_region(OURMOUSE_BASE, 3);
214 #endif
215   </programlisting>
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>
242   <programlisting>
243 struct file_operations our_mouse_fops = {
244         NULL,                   /* Mice don't seek */
245         read_mouse,             /* You can read a mouse */
246         write_mouse,            /* This won't do a lot */
247         NULL,                   /* No readdir - not a directory */
248         poll_mouse,             /* Poll */
249         NULL,                   /* No ioctl calls */
250         NULL,                   /* No mmap */
251         open_mouse,             /* Called on open */
252         NULL,                   /* Flush - 2.2+ only */
253         close_mouse,            /* Called on close */
255   </programlisting>
257   <para>
258     There is nothing particularly special needed here. We provide functions 
259     for all the relevant or required operations and little else. There is 
260     nothing stopping us providing an ioctl function for this mouse. Indeed 
261     if you have a configurable mouse it may be very appropriate to provide 
262     configuration interfaces via ioctl calls.
263   </para>
264   <para>
265     The open and close routines need to manage enabling and disabling the 
266     interrupts for the mouse as well as stopping the mouse being unloaded
267     when it is no longer required. 
268   </para>
270   <programlisting>
271 static int mouse_users = 0;                /* User count */
272 static int mouse_dx = 0;                   /* Position changes */
273 static int mouse_dy = 0;
274 static int mouse_event = 0;                /* Mouse has moved */
276 static int open_mouse(struct inode *inode, struct file *file)
278         if(mouse_users++)
279                 return 0;
281         MOD_INC_USE_COUNT;
283         if(request_irq(mouse_intr, OURMOUSE_IRQ, 0, "ourmouse", NULL))
284         {
285                 mouse_users--;
286                 MOD_DEC_USE_COUNT;
287                 return -EBUSY;
288         }
289         mouse_dx = 0;
290         mouse_dy = 0;
291         mouse_event = 0;
292         mouse_buttons = 0;
293         return 0;
295   </programlisting>
296   <para>
297     The open function has to do a small amount of housework. We keep a count 
298     of the number of times the mouse is open. This is because we do not want 
299     to request the interrupt multiple times. If the mouse has at least one 
300     user then it is set up and we simply add to the user count and return
301     <returnvalue>0</returnvalue> for success.
302   </para>
303   <para>
304     Firstly we use <function>MOD_INC_USE_COUNT</function> to ensure that 
305     while the mouse is open nobody will unload it and cause a nasty crash.
306     We must do this before we sleep - and grabbing the interrupt might sleep.
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>
326 static int close_mouse(struct inode *inode, struct file *file)
328         if(--mouse_users)
329                 return 0;
330         free_irq(OURMOUSE_IRQ, NULL);
331         MOD_DEC_USE_COUNT;
332         return 0;
334   </programlisting>
335   <para>
336     We count off a user and provided that there are still other users need 
337     take no further action. The last person closing the mouse causes us to 
338     free up the interrupt. This stopps interrupts from the mouse from using 
339     our CPU time, and lets us use <function>MOD_DEC_USE_COUNT</function> so 
340     that the mouse can now be unloaded.
341   </para>
342   <para>
343     We can fill in the write handler at this point as the write function for 
344     our mouse simply declines to allow writes:
345   </para>
347   <programlisting>
348 static ssize_t write_mouse(struct file *file, const char *buffer, size_t
349                                 count, loff_t *ppos)
351         return -EINVAL;
353   </programlisting>
355   <para>
356     This is pretty much self-explanatory. Whenever you write you get told 
357     it was an invalid function.
358   </para>
359   <para>
360     To make the poll and read functions work we have to consider how we 
361     handle the mouse interrupt. 
362   </para>
364   <programlisting>
365 static struct wait_queue *mouse_wait;
366 static spinlock_t mouse_lock = SPIN_LOCK_UNLOCKED;
368 static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
370         char delta_x;
371         char delta_y;
372         unsigned char new_buttons;
374         delta_x = inb(OURMOUSE_BASE);
375         delta_y = inb(OURMOUSE_BASE+1);
376         new_buttons = inb(OURMOUSE_BASE+2);
378         if(delta_x || delta_y || new_buttons != mouse_buttons)
379         {
380                 /* Something happened */
382                 spin_lock(&amp;mouse_lock);
383                 mouse_event = 1;
384                 mouse_dx += delta_x;
385                 mouse_dy += delta_y;
386                 mouse_buttons = new_buttons;
387                 spin_unlock(&amp;mouse_lock);
388                 
389                 wake_up_interruptible(&amp;mouse_wait);
390         }
392   </programlisting>
394   <para>
395     The interrupt handler reads the mouse status. The next thing we do is 
396     to check whether something has changed. If the mouse was smart it would
397     only interrupt us if something had changed, but let's assume our mouse 
398     is stupid as most mice actually tend to be. 
399   </para>
400   <para>
401     If the mouse has changed we need to update the status variables. What we
402     don't want is the mouse functions reading these variables to read them
403     during a change. We add a spinlock that protects these variables while we
404     play with them.
405   </para>
406   <para>
407     If a change has occured we also need to wake sleeping processes, so we 
408     add a wakeup call and a <structname>wait_queue</structname> to use when 
409     we wish to await a mouse event.
410   </para>
411   <para>
412     Now we have the wait queue we can implement the poll function for the 
413     mouse relatively easily:
414   </para>
416   <programlisting>
417 static unsigned int mouse_poll(struct file *file, poll_table *wait)
419         poll_wait(file, &amp;mouse_wait, wait);
420         if(mouse_event)
421                 return POLLIN | POLLRDNORM;
422         return 0;
424   </programlisting>
426   <para>
427     This is fairly standard poll code. First we add the wait queue to the 
428     list of queues we want to monitor for an event. Secondly we check if an 
429     event has occured. We only have one kind of event - the 
430     <varname>mouse_event</varname> flag tells us that something happened. 
431     We know that this something can only be mouse data. We return the flags 
432     indicating input and normal reading will succeed.
433   </para>
434   <para>
435     You may be wondering what happens if the function returns saying 'no 
436     event yet'. In this case the wake up from the wait queue we added to 
437     the poll table will cause the function to be called again. Eventually 
438     we will be woken up and have an event ready. At this point the 
439     <function>poll</function> call will exit back to the user.
440   </para>
441   <para>
442     After the poll completes the user will want to read the data. We now 
443     need to think about how our <function>mouse_read</function> function 
444     will work:
445   </para>
446   <programlisting>
447 static ssize_t mouse_read(struct file *file, char *buffer, 
448                 size_t count, loff_t *pos)
450         int dx, dy;
451         unsigned char button;
452         unsigned long flags;
453         int n;
455         if(count&lt;3)
456                 return -EINVAL;
458         /*
459           *        Wait for an event
460          */
462         while(!mouse_event)
463         {
464                 if(file-&gt;f_flags&amp;O_NDELAY)
465                         return -EAGAIN;
466                 interruptible_sleep_on(&amp;mouse_wait);
467                 if(signal_pending(current))
468                         return -ERESTARTSYS;
469         }
470   </programlisting>
472   <para>
473     We start by validating that the user is reading enough data. We could 
474     handle partial reads if we wanted but it isn't terribly useful and the 
475     mouse drivers don't bother to try.
476   </para>
477   <para>
478     Next we wait for an event to occur. The loop is fairly standard event
479     waiting in Linux. Having checked that the event has not yet occured, we
480     then check if an event is pending and if not we need to sleep. 
481   </para>
482   <para>
483     A user process can set the <constant>O_NDELAY</constant> flag on a file 
484     to indicate that it wishes to be told immediately if no event is 
485     pending. We check this and give the appropriate error if so. 
486   </para>
487   <para>
488     Next we sleep until the mouse or a signal awakens us. A signal will 
489     awaken us as we have used <function>wakeup_interruptible</function>. 
490     This is important as it means a user can kill processes waiting for 
491     the mouse - clearly a desireable property. If we are interrupted we 
492     exit the call and the kernel will then process signals and maybe 
493     restart the call again - from the beginning.
494   </para>
495   <para>
496     This code contains a classic Linux bug. All will be revealed later in this
497     article as well as explanations for how to avoid it.
498   </para>
499   <programlisting>
500         /* Grab the event */
502         spinlock_irqsave(&amp;mouse_lock, flags);
504         dx = mouse_dx;
505         dy = mouse_dy;
506         button = mouse_buttons;
508         if(dx&lt;=-127)
509                 dx=-127;
510         if(dx&gt;=127)
511                 dx=127;
512         if(dy&lt;=-127)
513                 dy=-127;
514         if(dy&gt;=127)
515                 dy=127;
517         mouse_dx -= dx;
518         mouse_dy -= dy;
519         
520         if(mouse_dx == 0 &amp;&amp; mouse_dy == 0)
521                 mouse_event = 0;
523         spin_unlock_irqrestore(&amp;mouse_lock, flags);
524   </programlisting>
525   <para>
526     This is the next stage. Having established that there is an event 
527     going, we capture it. To be sure that the event is not being updated 
528     as we capture it we also take the spinlock and thus prevent parallel 
529     updates. Note here we use <function>spinlock_irqsave</function>. We 
530     need to disable interrupts on the local processor otherwise bad things 
531     will happen.
532   </para>
533   <para>
534     What will occur is that we take the spinlock. While we hold the lock 
535     an interrupt will occur. At this point our interrupt handler will try 
536     and take the spinlock. It will sit in a loop waiting for the read 
537     routine to release the lock. However because we are sitting in a loop 
538     in the interrupt handler we will never release the lock. The machine 
539     hangs and the user gets upset.
540   </para>
541   <para>
542     By blocking the interrupt on this processor we ensure that the lock 
543     holder will always give the lock back without deadlocking.
544   </para>
545   <para>
546     There is a little cleverness in the reporting mechanism too. We can 
547     only report a move of 127 per read. We don't however want to lose 
548     information by throwing away further movement. Instead we keep 
549     returning as much information as possible. Each time we return a 
550     report we remove the amount from the pending movement in 
551     <varname>mouse_dx</varname> and <varname>mouse_dy</varname>. Eventually 
552     when these counts hit zero we clear the <varname>mouse_event</varname>
553     flag as there is nothing else left to report.
554   </para>
556   <programlisting>
557         if(put_user(button|0x80, buffer))
558                 return -EFAULT;
559         if(put_user((char)dx, buffer+1))
560                 return -EFAULT;
561         if(put_user((char)dy, buffer+2))
562                 return -EFAULT;
564         for(n=3; n < count; n++)
565                 if(put_user(0x00, buffer+n))
566                         return -EFAULT;
568         return count;
570   </programlisting>
572   <para>
573     Finally we must put the results in the user supplied buffer. We cannot 
574     do this while holding the lock as a write to user memory may sleep. 
575     For example the user memory may be residing on disk at this instant. 
576     Thus we did our computation beforehand and now copy the data. Each 
577     <function>put_user call</function> is filling in one byte of the buffer. 
578     If it returns an error we inform the program that it passed us an 
579     invalid buffer and abort.
580   </para>
581   <para>
582     Having written the data we blank the rest of the buffer that was read 
583     and report the read as being successful.
584   </para>
585  </chapter>
587  <chapter id="debugging">
588   <title>Debugging the mouse driver</title>
590   <para>
591     We now have an almost perfectly usable mouse driver. If you were to 
592     actually try and use it however you would eventually find a couple of 
593     problems with it. A few programs will also not work with as it does not 
594     yet support asynchronous I/O.
595   </para>
596   <para>
597     First let us look at the bugs. The most obvious one isn't really a driver
598     bug but a failure to consider the consequences. Imagine you bumped the 
599     mouse hard by accident and sent it skittering across the desk. The mouse 
600     interrupt routine will add up all that movement and report it in steps of 
601     127 until it has reported all of it. Clearly there is a point beyond 
602     which mouse movement isn't worth reporting. We need to add this as a 
603     limit to the interrupt handler:
604   </para>
606   <programlisting>
607 static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
609         char delta_x;
610         char delta_y;
611         unsigned char new_buttons;
613         delta_x = inb(OURMOUSE_BASE);
614         delta_y = inb(OURMOUSE_BASE+1);
615         new_buttons = inb(OURMOUSE_BASE+2);
617         if(delta_x || delta_y || new_buttons != mouse_buttons)
618         {
619                 /* Something happened */
621                 spin_lock(&amp;mouse_lock);
622                 mouse_event = 1;
623                 mouse_dx += delta_x;
624                 mouse_dy += delta_y;
626                 if(mouse_dx &lt; -4096)
627                         mouse_dx = -4096;
628                 if(mouse_dx &gt; 4096)
629                         mouse_dx = 4096;
631                 if(mouse_dy &lt; -4096)
632                         mouse_dy = -4096;
633                 if(mouse_dy &gt; 4096)
634                         mouse_dy = 4096;
636                 mouse_buttons = new_buttons;
637                 spin_unlock(&amp;mouse_lock);
638                 
639                 wake_up_interruptible(&amp;mouse_wait);
640         }
642   </programlisting>
644   <para>
645     By adding these checks we limit the range of accumulated movement to
646     something sensible. 
647   </para>
648   <para>
649     The second bug is a bit more subtle, and that is perhaps why this is 
650     such a common mistake. Remember, I said the waiting loop for the read 
651     handler had a bug in it. Think about what happens when we execute:
652   </para>
654   <programlisting>
655         while(!mouse_event)
656         {
657   </programlisting>
659   <para>
660     and an interrupt occurs at this point here. This causes a mouse movement
661     and wakes up the queue. 
662   </para>
664   <programlisting>
665                 interruptible_sleep_on(&amp;mouse_wait);
666   </programlisting>
668   <para>
669     Now we sleep on the queue. We missed the wake up and the application 
670     will not see an event until the next mouse event occurs. This will 
671     lead to just the odd instance when a mouse button gets delayed. The 
672     consequences to the user will probably be almost undetectable with a 
673     mouse driver. With other drivers this bug could be a lot more severe.
674   </para>
675   <para>
676     There are two ways to solve this. The first is to disable interrupts 
677     during the testing and the sleep. This works because when a task sleeps 
678     it ceases to disable interrupts, and when it resumes it disables them 
679     again. Our code thus becomes:
680   </para>
682   <programlisting>
683         save_flags(flags);
684         cli();
686         while(!mouse_event)
687         {
688                 if(file-&gt;f_flags&amp;O_NDELAY)
689                 {
690                         restore_flags(flags);
691                         return -EAGAIN;
692                 }
693                 interruptible_sleep_on(&amp;mouse_wait);
694                 if(signal_pending(current))
695                 {
696                         restore_flags(flags);
697                         return -ERESTARTSYS;
698                 }
699         }
700         restore_flags(flags);
701   </programlisting>
703   <para>
704     This is the sledgehammer approach. It works but it means we spend a 
705     lot more time turning interrupts on and off. It also affects 
706     interrupts globally and has bad properties on multiprocessor machines 
707     where turning interrupts off globally is not a simple operation, but 
708     instead involves kicking each processor, waiting for them to disable 
709     interrupts and reply.
710   </para>
711   <para>
712     The real problem is the race between the event testing and the sleeping. 
713     We can avoid that by using the scheduling functions more directly. 
714     Indeed this is the way they generally should be used for an interrupt.
715   </para>
717   <programlisting>
718         struct wait_queue wait = { current, NULL };
720         add_wait_queue(&amp;mouse_wait, &amp;wait);
721         current-&gt;state = TASK_INTERRUPTIBLE;
722         
723         while(!mouse_event)
724         {
725                 if(file-&gt;f_flags&amp;O_NDELAY)
726                 {
727                         remove_wait_queue(&amp;mouse_wait, &amp;wait);
728                         current-&gt;state = TASK_RUNNING;
729                         return -EWOULDBLOCK;
730                 }
731                 if(signal_pending(current))
732                 {
733                         remove_wait_queue(&amp;mouse_wait, &amp;wait);
734                         current-&gt;state = TASK_RUNNING;
735                         return -ERESTARTSYS;
736                 }
737                 schedule();
738                 current-&gt;state = TASK_INTERRUPTIBLE;
739         }
740         
741         remove_wait_wait(&amp;mouse_wait, &amp;wait);
742         current-&gt;state = TASK_RUNNING;
743   </programlisting>
745   <para>
746     At first sight this probably looks like deep magic. To understand how 
747     this works you need to understand how scheduling and events work on 
748     Linux. Having a good grasp of this is one of the keys to writing clean 
749     efficient device drivers.
750   </para>
751   <para>
752     <function>add_wait_queue</function> does what its name suggests. It adds 
753     an entry to the <varname>mouse_wait</varname> list. The entry in this 
754     case is the entry for our current process (<varname>current</varname>
755     is the current task pointer). 
756   </para>
757   <para>
758     So we start by adding an entry for ourself onto the 
759     <varname>mouse_wait</varname> list. This does not put us to sleep 
760     however. We are merely tagged onto the list. 
761   </para>
762   <para>
763     Next we set our status to <constant>TASK_INTERRUPTIBLE</constant>. Again 
764     this does not mean we are now asleep. This flag says what should happen 
765     next time the process sleeps. <constant>TASK_INTERRUPTIBLE</constant> says 
766     that the process should not be rescheduled. It will run from now until it 
767     sleeps and then will need to be woken up.
768   </para>
769   <para>
770     The <function>wakeup_interruptible</function> call in the interrupt 
771     handler can now be explained in more detail. This function is also very 
772     simple. It goes along the list of processes on the queue it is given and 
773     any that are marked as <constant>TASK_INTERRUPTIBLE</constant> it changes 
774     to <constant>TASK_RUNNING</constant> and tells the kernel that new 
775     processes are runnable.
776   </para>
777   <para>
778     Behind all the wrappers in the original code what is happening is this
779   </para>
781   <procedure>
782    <step>
783     <para>
784       We add ourself to the mouse wait queue
785     </para>
786    </step>
787    <step>
788     <para>
789       We mark ourself as sleeping
790     </para>
791    </step>
792    <step>
793     <para>
794       We ask the kernel to schedule tasks again
795     </para>
796    </step>
797    <step>
798     <para>
799       The kernel sees we are asleep and schedules someone else.
800     </para>
801    </step>
802    <step>
803     <para>
804       The mouse interrupt sets our state to <constant>TASK_RUNNING</constant> 
805       and makes a note that the kernel should reschedule tasks
806     </para>
807    </step>
808    <step>
809     <para>
810       The kernel sees we are running again and continues our execution
811     </para>
812    </step>
813   </procedure>
814   <para>
815     This is why the apparent magic works. Because we mark ourself as
816     <constant>TASK_INTERRUPTIBLE</constant> and as we add ourselves 
817     to the queue before we check if there are events pending, the race 
818     condition is removed.
819   </para>
820   <para>
821     Now if an interrupt occurs after we check the queue status and before 
822     we call the <function>schedule</function> function in order to sleep, 
823     things work out. Instead of missing an event, we are set back to 
824     <constant>TASK_RUNNING</constant> by the mouse interrupt. We still call 
825     <function>schedule</function> but it will continue running our task. 
826     We go back around the loop and this time there may be an event.
827   </para>
828   <para>
829     There will not always be an event. Thus we set ourselves back to
830     <constant>TASK_INTERRUPTIBLE</constant> before resuming the loop. 
831     Another process doing a read may already have cleared the event flag, 
832     and if so we will need to go back to sleep again. Eventually we will 
833     get our event and escape.
834   </para>
835   <para>
836     Finally when we exit the loop we remove ourselves from the 
837     <varname>mouse_wait</varname> queue as we are no longer interested
838     in mouse events, and we set ourself back to 
839     <constant>TASK_RUNNABLE</constant> as we do not wish to go to sleep 
840     again just yet.
841   </para>
842   <note>
843    <title>Note</title> 
844    <para>
845      This isn't an easy topic. Don't be afraid to reread the description a 
846      few times and also look at other device drivers to see how it works. 
847      Finally if you can't grasp it just yet, you can use the code as 
848      boilerplate to write other drivers and trust me instead.
849    </para>
850   </note>
851  </chapter>
853  <chapter id="asyncio">
854   <title>Asynchronous I/O</title>
855   <para>
856     This leaves the missing feature - Asynchronous I/O. Normally UNIX 
857     programs use the <function>poll</function> call (or its variant form 
858     <function>select</function>) to wait for an event to occur on one of 
859     multiple input or output devices. This model works well for most tasks 
860     but because <function>poll</function> and <function>select</function> 
861     wait for an event isn't suitable for tasks that are also continually 
862     doing computation work. Such programs really want the kernel to kick 
863     them when something happens rather than watch for events.
864   </para>
865   <para>
866     Poll is akin to having a row of lights in front of you. You can see at a
867     glance which ones if any are lit. You cannot however get anything useful
868     done while watching them. Asynchronous I/O uses signals which work more 
869     like a door bell. Instead of you watching, it tells you that something 
870     is up.
871   </para>
872   <para>
873     Asynchronous I/O sends the signal SIGIO to a user process when the I/O 
874     events occur. In this case that means when people move the mouse. The 
875     SIGIO signal causes the user process to jump to its signal handler and 
876     execute code in that handler before returning to whatever was going on 
877     previously. It is the application equivalent of an interrupt handler.
878   </para>
879   <para>
880     Most of the code needed for this operation is common to all its users. 
881     The kernel provides a simple set of functions for managing asynchronous 
882     I/O.
883   </para>
884   <para>
885     Our first job is to allow users to set asynchronous I/O on file handles. 
886     To do that we need to add a new function to the file operations table for 
887     our mouse:
888   </para>
890   <programlisting>
891 struct file_operations our_mouse_fops = {
892         NULL,                   /* Mice don't seek */
893         read_mouse,             /* You can read a mouse */
894         write_mouse,            /* This won't do a lot */
895         NULL,                   /* No readdir - not a directory */
896         poll_mouse,             /* Poll */
897         NULL,                   /* No ioctl calls */
898         NULL,                   /* No mmap */
899         open_mouse,             /* Called on open */
900         NULL,                   /* Flush */
901         close_mouse,            /* Called on close */
902         NULL,                   /* No fsync on a mouse */
903         fasync_mouse,           /* Asynchronous I/O */
905   </programlisting>
907   <para>
908     Once we have installed this entry the kernel knows we support 
909     asynchronous I/O and will allow all the relevant operations on the 
910     device. Whenever a user adds or removes asynchronous I/O notification 
911     on a file handle it calls our <function>fasync_mouse</function> routine 
912     we just added. This routine uses the helper functions to keep the queue 
913     of handles up to date:
914   </para>
916   <programlisting>
917 static struct fasync_struct *mouse_fasync = NULL;
919 static int fasync_mouse(int fd, struct file *filp, int on)
921          int retval = fasync_helper(fd, filp, on, &amp;mouse_fasync);
923          if (retval &lt; 0)
924                  return retval;
925         return 0;
927   </programlisting>
929   <para>
930     The fasync helper adds and deletes entries by managing the supplied 
931     list. We also need to remove entries from this list when the file is 
932     closed. This requires we add one line to our close function:
933   </para>
935   <programlisting>
936 static int close_mouse(struct inode *inode, struct file *file)
938         fasync_mouse(-1, file, 0)
939         if(--mouse_users)
940                 return 0;
941         free_irq(OURMOUSE_IRQ, NULL);
942         MOD_DEC_USE_COUNT;
943         return 0;
945   </programlisting>
947   <para>
948     When we close the file we now call our own fasync handler as if the 
949     user had requested that this file cease to be used for asynchronous 
950     I/O. This rather neatly cleans up any loose ends. We certainly don't 
951     wait to deliver a signal for a file that no longer exists.
952   </para>
953   <para>
954     At this point the mouse driver supports all the asynchronous I/O 
955     operations, and applications using them will not error. They won't 
956     however work yet. We need to actually send the signals. Again the 
957     kernel provides a function for handling this.
958   </para>
959   <para>
960     We update our interrupt handler a little:
961   </para>
963   <programlisting>
964 static void ourmouse_interrupt(int irq, void *dev_id, struct pt_regs *regs)
966         char delta_x;
967         char delta_y;
968         unsigned char new_buttons;
970         delta_x = inb(OURMOUSE_BASE);
971         delta_y = inb(OURMOUSE_BASE+1);
972         new_buttons = inb(OURMOUSE_BASE+2);
974         if(delta_x || delta_y || new_buttons != mouse_buttons)
975         {
976                 /* Something happened */
978                 spin_lock(&amp;mouse_lock);
979                 mouse_event = 1;
980                 mouse_dx += delta_x;
981                 mouse_dy += delta_y;
983                 if(mouse_dx &lt; -4096)
984                         mouse_dx = -4096;
985                 if(mouse_dx &gt; 4096)
986                         mouse_dx = 4096;
988                 if(mouse_dy &lt; -4096)
989                         mouse_dy = -4096;
990                 if(mouse_dy &gt; 4096)
991                         mouse_dy = 4096;
993                 mouse_buttons = new_buttons;
994                 spin_unlock(&amp;mouse_lock);
996                 /* Now we do asynchronous I/O */
997                 kill_fasync(&amp;mouse_fasync, SIGIO); 
998                 
999                 wake_up_interruptible(&amp;mouse_wait);
1000         }
1002   </programlisting>
1004   <para>
1005     The new code simply calls the <function>kill_fasync</function> routine
1006     provided by the kernel if the queue is non-empty. This sends the 
1007     required signal (SIGIO in this case) to the process each file handle 
1008     says should be informed about the exciting new mouse movement that 
1009     just happened.
1010   </para>
1011   <para>
1012     With this in place and the bugs in the original version fixed, you now 
1013     have a fully functional mouse driver using the bus mouse protocol. It 
1014     will work with the <application>X window system</application>, will work 
1015     with <application>GPM</application> and should work with every other 
1016     application you need. <application>Doom</application> is of course the 
1017     ideal way to test your new mouse driver is functioning properly. Be sure 
1018     to test it thoroughly.
1019   </para>
1020  </chapter>
1021 </book>