patch-2_6_7-vs1_9_1_12
[linux-2.6.git] / Documentation / sound / alsa / DocBook / writing-an-alsa-driver.tmpl
1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">
2
3 <book>
4 <?dbhtml filename="index.html">
5
6 <!-- ****************************************************** -->
7 <!-- Header  -->
8 <!-- ****************************************************** -->
9   <bookinfo>
10     <title>Writing an ALSA Driver</title>
11     <author>
12       <firstname>Takashi</firstname>
13       <surname>Iwai</surname>
14       <affiliation>
15         <address>
16           <email>tiwai@suse.de</email>
17         </address>
18       </affiliation>
19      </author>
20
21      <date>Mar. 6, 2004</date>
22      <edition>0.3.1</edition>
23
24     <abstract>
25       <para>
26         This document describes how to write an ALSA (Advanced Linux
27         Sound Architecture) driver.
28       </para>
29     </abstract>
30
31     <legalnotice>
32     <para>
33     Copyright (c) 2002-2004  Takashi Iwai <email>tiwai@suse.de</email>
34     </para>
35
36     <para>
37     This document is free; you can redistribute it and/or modify it
38     under the terms of the GNU General Public License as published by
39     the Free Software Foundation; either version 2 of the License, or
40     (at your option) any later version. 
41     </para>
42
43     <para>
44     This document is distributed in the hope that it will be useful,
45     but <emphasis>WITHOUT ANY WARRANTY</emphasis>; without even the
46     implied warranty of <emphasis>MERCHANTABILITY or FITNESS FOR A
47     PARTICULAR PURPOSE</emphasis>. See the GNU General Public License
48     for more details.
49     </para>
50
51     <para>
52     You should have received a copy of the GNU General Public
53     License along with this program; if not, write to the Free
54     Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
55     MA 02111-1307 USA
56     </para>
57     </legalnotice>
58
59   </bookinfo>
60
61 <!-- ****************************************************** -->
62 <!-- Preface  -->
63 <!-- ****************************************************** -->
64   <preface id="preface">
65     <title>Preface</title>
66     <para>
67       This document describes how to write an
68       <ulink url="http://www.alsa-project.org/"><citetitle>
69       ALSA (Advanced Linux Sound Architecture)</citetitle></ulink>
70       driver. The document focuses mainly on the PCI soundcard.
71       In the case of other device types, the API might
72       be different, too. However, at least the ALSA kernel API is
73       consistent, and therefore it would be still a bit help for
74       writing them.
75     </para>
76
77     <para>
78     The target of this document is ones who already have enough
79     skill of C language and have the basic knowledge of linux
80     kernel programming.  This document doesn't explain the general
81     topics of linux kernel codes and doesn't cover the detail of
82     implementation of each low-level driver.  It describes only how is
83     the standard way to write a PCI sound driver on ALSA.
84     </para>
85
86     <para>
87       If you are already familiar with the older ALSA ver.0.5.x, you
88     can check the drivers such as <filename>es1938.c</filename> or
89     <filename>maestro3.c</filename> which have also almost the same
90     code-base in the ALSA 0.5.x tree, so you can compare the differences.
91     </para>
92
93     <para>
94       This document is still a draft version. Any feedbacks and
95     corrections, please!!
96     </para>
97   </preface>
98
99
100 <!-- ****************************************************** -->
101 <!-- File Tree Structure  -->
102 <!-- ****************************************************** -->
103   <chapter id="file-tree">
104     <title>File Tree Structure</title>
105
106     <section id="file-tree-general">
107       <title>General</title>
108       <para>
109         The ALSA drivers are provided in the two ways.
110       </para>
111
112       <para>
113         One is the the trees provided as a tarball or via cvs from the
114       ALSA's ftp site, and another is the 2.6 (or later) Linux kernel
115       tree. To synchronize both, the ALSA driver tree is split to
116       two different trees: alsa-kernel and alsa-driver. The former
117       contains purely the source codes for the Linux 2.6 (or later)
118       tree. This tree is designed only for compilation on 2.6 or
119       later environment. The latter, alsa-driver, contains many subtle
120       files for compiling the ALSA driver on the outside of Linux
121       kernel like configure script, the wrapper functions for older,
122       2.2 and 2.4 kernels, to adapt the latest kernel API,
123       and additional drivers which are still in development or in
124       tests.  The drivers in alsa-driver tree will be moved to
125       alsa-kernel (eventually 2.6 kernel tree) once when they are
126       finished and confirmed to work fine.
127       </para>
128
129       <para>
130         The file tree structure of ALSA driver is depicted below. Both
131         alsa-kernel and alsa-driver have almost the same file
132         structure, except for <quote>core</quote> directory. It's
133         named as <quote>acore</quote> in alsa-driver tree. 
134
135         <example>
136           <title>ALSA File Tree Structure</title>
137           <literallayout>
138         sound
139                 /core
140                         /oss
141                         /seq
142                                 /oss
143                                 /instr
144                 /ioctl32
145                 /include
146                 /drivers
147                         /mpu401
148                         /opl3
149                 /i2c
150                         /l3
151                 /synth
152                         /emux
153                 /pci
154                         /(cards)
155                 /isa
156                         /(cards)
157                 /arm
158                 /ppc
159                 /sparc
160                 /usb
161                 /pcmcia /(cards)
162                 /oss
163           </literallayout>
164         </example>
165       </para>
166     </section>
167
168     <section id="file-tree-core-directory">
169       <title>core directory</title>
170       <para>
171         This directory contains the middle layer, that is, the heart
172       of ALSA drivers. In this directory, the native ALSA modules are
173       stored. The sub-directories contain different modules and are
174       dependent upon the kernel config. 
175       </para>
176
177       <section id="file-tree-core-directory-oss">
178         <title>core/oss</title>
179
180         <para>
181           The codes for PCM and mixer OSS emulation modules are stored
182         in this directory. The rawmidi OSS emulation is included in
183         the ALSA rawmidi code since it's quite small. The sequencer
184         code is stored in core/seq/oss directory (see
185         <link linkend="file-tree-core-directory-seq-oss"><citetitle>
186         below</citetitle></link>).
187         </para>
188       </section>
189
190       <section id="file-tree-core-directory-ioctl32">
191         <title>core/ioctl32</title>
192
193         <para>
194           This directory contains the 32bit-ioctl wrappers for 64bit
195         architectures such like x86-64, ppc64 and sparc64. For 32bit
196         and alpha architectures, these are not compiled. 
197         </para>
198       </section>
199
200       <section id="file-tree-core-directory-seq">
201         <title>core/seq</title>
202         <para>
203           This and its sub-directories are for the ALSA
204         sequencer. This directory contains the sequencer core and
205         primary sequencer modules such like snd-seq-midi,
206         snd-seq-virmidi, etc. They are compiled only when
207         <constant>CONFIG_SND_SEQUENCER</constant> is set in the kernel
208         config. 
209         </para>
210       </section>
211
212       <section id="file-tree-core-directory-seq-oss">
213         <title>core/seq/oss</title>
214         <para>
215           This contains the OSS sequencer emulation codes.
216         </para>
217       </section>
218
219       <section id="file-tree-core-directory-deq-instr">
220         <title>core/seq/instr</title>
221         <para>
222           This directory contains the modules for the sequencer
223         instrument layer. 
224         </para>
225       </section>
226     </section>
227
228     <section id="file-tree-include-directory">
229       <title>include directory</title>
230       <para>
231         This is the place for the public header files of ALSA drivers,
232       which are to be exported to the user-space, or included by
233       several files at different directories. Basically, the private
234       header files should not be placed in this directory, but you may
235       still find files there, due to historical reason :) 
236       </para>
237     </section>
238
239     <section id="file-tree-drivers-directory">
240       <title>drivers directory</title>
241       <para>
242         This directory contains the codes shared among different drivers
243       on the different architectures.  They are hence supposed not to be
244       architecture-specific.
245       For example, the dummy pcm driver and the serial MIDI
246       driver are found in this directory. In the sub-directories,
247       there are the codes for components which are independent from
248       bus and cpu architectures. 
249       </para>
250
251       <section id="file-tree-drivers-directory-mpu401">
252         <title>drivers/mpu401</title>
253         <para>
254           The MPU401 and MPU401-UART modules are stored here.
255         </para>
256       </section>
257
258       <section id="file-tree-drivers-directory-opl3">
259         <title>drivers/opl3 and opl4</title>
260         <para>
261           The OPL3 and OPL4 FM-synth stuff is found here.
262         </para>
263       </section>
264     </section>
265
266     <section id="file-tree-i2c-directory">
267       <title>i2c directory</title>
268       <para>
269         This contains the ALSA i2c components.
270       </para>
271
272       <para>
273         Although there is a standard i2c layer on Linux, ALSA has its
274       own i2c codes for some cards, because the soundcard needs only a
275       simple operation and the standard i2c API is too complicated for
276       such a purpose. 
277       </para>
278
279       <section id="file-tree-i2c-directory-l3">
280         <title>i2c/l3</title>
281         <para>
282           This is a sub-directory for ARM L3 i2c.
283         </para>
284       </section>
285     </section>
286
287     <section id="file-tree-synth-directory">
288         <title>synth directory</title>
289         <para>
290           This contains the synth middle-level modules.
291         </para>
292
293         <para>
294           So far, there is only Emu8000/Emu10k1 synth driver under
295         synth/emux sub-directory. 
296         </para>
297     </section>
298
299     <section id="file-tree-pci-directory">
300       <title>pci directory</title>
301       <para>
302         This and its sub-directories hold the top-level card modules
303       for PCI soundcards and the codes specific to the PCI BUS.
304       </para>
305
306       <para>
307         The drivers compiled from a single file is stored directly on
308       pci directory, while the drivers with several source files are
309       stored on its own sub-directory (e.g. emu10k1, ice1712). 
310       </para>
311     </section>
312
313     <section id="file-tree-isa-directory">
314       <title>isa directory</title>
315       <para>
316         This and its sub-directories hold the top-level card modules
317       for ISA soundcards. 
318       </para>
319     </section>
320
321     <section id="file-tree-arm-ppc-sparc-directories">
322       <title>arm, ppc, and sparc directories</title>
323       <para>
324         These are for the top-level card modules which are
325       specific to each given architecture. 
326       </para>
327     </section>
328
329     <section id="file-tree-usb-directory">
330       <title>usb directory</title>
331       <para>
332         This contains the USB-audio driver. On the latest version, the
333       USB MIDI driver is integrated together with usb-audio driver. 
334       </para>
335     </section>
336
337     <section id="file-tree-pcmcia-directory">
338       <title>pcmcia directory</title>
339       <para>
340         The PCMCIA, especially PCCard drivers will go here. CardBus
341       drivers will be on pci directory, because its API is identical
342       with the standard PCI cards. 
343       </para>
344     </section>
345
346     <section id="file-tree-oss-directory">
347       <title>oss directory</title>
348       <para>
349         The OSS/Lite source files are stored here on Linux 2.6 (or
350       later) tree. (In the ALSA driver tarball, it's empty, of course :) 
351       </para>
352     </section>
353   </chapter>
354
355
356 <!-- ****************************************************** -->
357 <!-- Basic Flow for PCI Drivers  -->
358 <!-- ****************************************************** -->
359   <chapter id="basic-flow">
360     <title>Basic Flow for PCI Drivers</title>
361
362     <section id="basic-flow-outline">
363       <title>Outline</title>
364       <para>
365         The minimum flow of PCI soundcard is like the following:
366
367         <itemizedlist>
368           <listitem><para>define the PCI ID table (see the section
369           <link linkend="pci-resource-entries"><citetitle>PCI Entries
370           </citetitle></link>).</para></listitem> 
371           <listitem><para>create <function>probe()</function> callback.</para></listitem>
372           <listitem><para>create <function>remove()</function> callback.</para></listitem>
373           <listitem><para>create pci_driver table which contains the three pointers above.</para></listitem>
374           <listitem><para>create <function>init()</function> function just calling <function>pci_module_init()</function> to register the pci_driver table defined above.</para></listitem>
375           <listitem><para>create <function>exit()</function> function to call <function>pci_unregister_driver()</function> function.</para></listitem>
376         </itemizedlist>
377       </para>
378     </section>
379
380     <section id="basic-flow-example">
381       <title>Full Code Example</title>
382       <para>
383         The code example is shown below. Some parts are kept
384       unimplemented at this moment but will be filled in the
385       succeeding sections. The numbers in comment lines of
386       <function>snd_mychip_probe()</function> function are the
387       markers. 
388
389         <example>
390           <title>Basic Flow for PCI Drivers Example</title>
391           <programlisting>
392 <![CDATA[
393   #include <sound/driver.h>
394   #include <linux/init.h>
395   #include <linux/pci.h>
396   #include <linux/slab.h>
397   #include <sound/core.h>
398   #define SNDRV_GET_ID
399   #include <sound/initval.h>
400
401   // module parameters (see "Module Parameters")
402   static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
403   static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
404   static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
405
406   // definition of the chip-specific record
407   typedef struct snd_mychip mychip_t;
408   struct snd_mychip {
409           snd_card_t *card;
410           // rest of implementation will be in the section
411           // "PCI Resource Managements"
412   };
413
414   // this should be go into <sound/sndmagic.h>
415   // (see "Management of Cards and Components")
416   #define mychip_t_magic        0xa15a4501
417
418   // chip-specific destructor
419   // (see "PCI Resource Managements")
420   static int snd_mychip_free(mychip_t *chip)
421   {
422           // will be implemented later...
423   }
424
425   // component-destructor
426   // (see "Management of Cards and Components")
427   static int snd_mychip_dev_free(snd_device_t *device)
428   {
429           mychip_t *chip = snd_magic_cast(mychip_t,
430                   device->device_data, return -ENXIO);
431           return snd_mychip_free(chip);
432   }
433
434   // chip-specific constructor
435   // (see "Management of Cards and Components")
436   static int __devinit snd_mychip_create(snd_card_t *card,
437                                          struct pci_dev *pci,
438                                          mychip_t **rchip)
439   {
440           mychip_t *chip;
441           int err;
442           static snd_device_ops_t ops = {
443                  .dev_free = snd_mychip_dev_free,
444           };
445
446           *rchip = NULL;
447
448           // check PCI availability here
449           // (see "PCI Resource Managements")
450
451           // allocate a chip-specific data with magic-alloc
452           chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
453           if (chip == NULL)
454                   return -ENOMEM;
455
456           chip->card = card;
457
458           // rest of initialization here; will be implemented
459           // later, see "PCI Resource Managements"
460
461           if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
462                                     chip, &ops)) < 0) {
463                   snd_mychip_free(chip);
464                   return err;
465           }
466           *rchip = chip;
467           return 0;
468   }
469
470   // constructor -- see "Constructor" sub-section
471   static int __devinit snd_mychip_probe(struct pci_dev *pci,
472                                const struct pci_device_id *pci_id)
473   {
474           static int dev;
475           snd_card_t *card;
476           mychip_t *chip;
477           int err;
478
479           // (1)
480           if (dev >= SNDRV_CARDS)
481                   return -ENODEV;
482           if (!enable[dev]) {
483                   dev++;
484                   return -ENOENT;
485           }
486
487           // (2)
488           card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
489           if (card == NULL)
490                   return -ENOMEM;
491
492           // (3)
493           if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
494                   snd_card_free(card);
495                   return err;
496           }
497
498           // (4)
499           strcpy(card->driver, "My Chip");
500           strcpy(card->shortname, "My Own Chip 123");
501           sprintf(card->longname, "%s at 0x%lx irq %i",
502                   card->shortname, chip->ioport, chip->irq);
503
504           // (5)
505           // implemented later
506
507           // (6)
508           if ((err = snd_card_register(card)) < 0) {
509                   snd_card_free(card);
510                   return err;
511           }
512
513           // (7)
514           pci_set_drvdata(pci, card);
515           dev++;
516           return 0;
517   }
518
519   // destructor -- see "Destructor" sub-section
520   static void __devexit snd_mychip_remove(struct pci_dev *pci)
521   {
522           snd_card_free(pci_get_drvdata(pci));
523           pci_set_drvdata(pci, NULL);
524   }
525 ]]>
526           </programlisting>
527         </example>
528       </para>
529     </section>
530
531     <section id="basic-flow-constructor">
532       <title>Constructor</title>
533       <para>
534         The real constructor of PCI drivers is probe callback. The
535       probe callback and other component-constructors which are called
536       from probe callback should be defined with
537       <parameter>__devinit</parameter> prefix. You 
538       cannot use <parameter>__init</parameter> prefix for them,
539       because any PCI device could be a hotplug device. 
540       </para>
541
542       <para>
543         In the probe callback, the following scheme is often used.
544       </para>
545
546       <section id="basic-flow-constructor-device-index">
547         <title>1) Check and increment the device index.</title>
548         <para>
549           <informalexample>
550             <programlisting>
551 <![CDATA[
552   static int dev;
553   ....
554   if (dev >= SNDRV_CARDS)
555           return -ENODEV;
556   if (!enable[dev]) {
557           dev++;
558           return -ENOENT;
559   }
560 ]]>
561             </programlisting>
562           </informalexample>
563
564         where enable[dev] is the module option.
565         </para>
566
567         <para>
568           At each time probe callback is called, check the
569         availability of the device. If not available, simply increment
570         the device index and returns. dev will be incremented also
571         later (<link
572         linkend="basic-flow-constructor-set-pci"><citetitle>step
573         7</citetitle></link>). 
574         </para>
575       </section>
576
577       <section id="basic-flow-constructor-create-card">
578         <title>2) Create a card instance</title>
579         <para>
580           <informalexample>
581             <programlisting>
582 <![CDATA[
583   snd_card_t *card;
584   ....
585   card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
586 ]]>
587             </programlisting>
588           </informalexample>
589         </para>
590
591         <para>
592           The detail will be explained in the section
593           <link linkend="card-management-card-instance"><citetitle>
594           Management of Cards and Components</citetitle></link>.
595         </para>
596       </section>
597
598       <section id="basic-flow-constructor-create-main">
599         <title>3) Create a main component</title>
600         <para>
601           In this part, the PCI resources are allocated.
602
603           <informalexample>
604             <programlisting>
605 <![CDATA[
606   mychip_t *chip;
607   ....
608   if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
609           snd_card_free(card);
610           return err;
611   }
612 ]]>
613             </programlisting>
614           </informalexample>
615
616           The detail will be explained in the section <link
617         linkend="pci-resource"><citetitle>PCI Resource
618         Managements</citetitle></link>.
619         </para>
620       </section>
621
622       <section id="basic-flow-constructor-main-component">
623         <title>4) Set the driver ID and name strings.</title>
624         <para>
625           <informalexample>
626             <programlisting>
627 <![CDATA[
628   strcpy(card->driver, "My Chip");
629   strcpy(card->shortname, "My Own Chip 123");
630   sprintf(card->longname, "%s at 0x%lx irq %i",
631           card->shortname, chip->ioport, chip->irq);
632 ]]>
633             </programlisting>
634           </informalexample>
635
636           The driver field holds the minimal ID string of the
637         chip. This is referred by alsa-lib's configurator, so keep it
638         simple but unique. 
639           Even the same driver can have different driver IDs to
640         distinguish the functionality of each chip type. 
641         </para>
642
643         <para>
644           The shortname field is a string shown as more verbose
645         name. The longname field contains the information which is
646         shown in <filename>/proc/asound/cards</filename>. 
647         </para>
648       </section>
649
650       <section id="basic-flow-constructor-create-other">
651         <title>5) Create other components, such as mixer, MIDI, etc.</title>
652         <para>
653           Here you define the basic components such as
654           <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
655           mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
656           MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
657           and other interfaces.
658           Also, if you want a <link linkend="proc-interface"><citetitle>proc
659         file</citetitle></link>, define it here, too.
660         </para>
661       </section>
662
663       <section id="basic-flow-constructor-register-card">
664         <title>6) Register the card instance.</title>
665         <para>
666           <informalexample>
667             <programlisting>
668 <![CDATA[
669   if ((err = snd_card_register(card)) < 0) {
670           snd_card_free(card);
671           return err;
672   }
673 ]]>
674             </programlisting>
675           </informalexample>
676         </para>
677
678         <para>
679           Will be explained in the section <link
680         linkend="card-management-registration"><citetitle>Management
681         of Cards and Components</citetitle></link>, too. 
682         </para>
683       </section>
684
685       <section id="basic-flow-constructor-set-pci">
686         <title>7) Set the PCI driver data and return zero.</title>
687         <para>
688           <informalexample>
689             <programlisting>
690 <![CDATA[
691         pci_set_drvdata(pci, card);
692         dev++;
693         return 0;
694 ]]>
695             </programlisting>
696           </informalexample>
697
698           In the above, the card record is stored. This pointer is
699         referred in the remove callback and power-management
700         callbacks, too. 
701         </para>
702       </section>
703     </section>
704
705     <section id="basic-flow-destructor">
706       <title>Destructor</title>
707       <para>
708         The destructor, remove callback, simply releases the card
709       instance. Then the ALSA middle layer will release all the
710       attached components automatically. 
711       </para>
712
713       <para>
714         It would be typically like the following:
715
716         <informalexample>
717           <programlisting>
718 <![CDATA[
719   static void __devexit snd_mychip_remove(struct pci_dev *pci)
720   {
721           snd_card_free(pci_get_drvdata(pci));
722           pci_set_drvdata(pci, NULL);
723   }
724 ]]>
725           </programlisting>
726         </informalexample>
727
728         The above code assumes that the card pointer is set to the PCI
729         driver data.
730       </para>
731     </section>
732
733     <section id="basic-flow-header-files">
734       <title>Header Files</title>
735       <para>
736         For the above example, at least the following include files
737       are necessary. 
738
739         <informalexample>
740           <programlisting>
741 <![CDATA[
742   #include <sound/driver.h>
743   #include <linux/init.h>
744   #include <linux/pci.h>
745   #include <linux/slab.h>
746   #include <sound/core.h>
747   #define SNDRV_GET_ID
748   #include <sound/initval.h>
749 ]]>
750           </programlisting>
751         </informalexample>
752
753         where the last twos are necessary only when module options are
754       defined in the source file.  If the codes are split to several
755       files, the file without module options don't need them.
756       </para>
757
758       <para>
759         In addition to them, you'll need
760       <filename>&lt;linux/interrupt.h&gt;</filename> for the interrupt
761       handling, and <filename>&lt;asm/io.h&gt;</filename> for the i/o
762       access. If you use <function>mdelay()</function> or
763       <function>udelay()</function> functions, you'll need to include
764       <filename>&lt;linux/delay.h&gt;</filename>, too. 
765       </para>
766
767       <para>
768       The ALSA interfaces like PCM or control API are define in other
769       header files as <filename>&lt;sound/xxx.h&gt;</filename>.
770       They have to be included after
771       <filename>&lt;sound/core.h&gt;</filename>.
772       </para>
773
774     </section>
775   </chapter>
776
777
778 <!-- ****************************************************** -->
779 <!-- Management of Cards and Components  -->
780 <!-- ****************************************************** -->
781   <chapter id="card-management">
782     <title>Management of Cards and Components</title>
783
784     <section id="card-management-card-instance">
785       <title>Card Instance</title>
786       <para>
787       For each soundcard, a <quote>card</quote> record must be allocated.
788       </para>
789
790       <para>
791       A card record is the headquarters of the soundcard.  It manages
792       the list of whole devices (components) on the soundcard, such as
793       PCM, mixers, MIDI, synthesizer, and so on.  Also, the card
794       record holds the ID and the name strings of the card, manages
795       the root of proc files, and controls the power-management states
796       and hotplug disconnections.  The component list on the card
797       record is used to manage the proper releases of resources at
798       destruction. 
799       </para>
800
801       <para>
802         As mentioned above, to create a card instance, call
803       <function>snd_card_new()</function>.
804
805         <informalexample>
806           <programlisting>
807 <![CDATA[
808   snd_card_t *card;
809   card = snd_card_new(index, id, module, extra_size);
810 ]]>
811           </programlisting>
812         </informalexample>
813       </para>
814
815       <para>
816         The function takes four arguments, the card-index number, the
817         id string, the module pointer (usually
818         <constant>THIS_MODULE</constant>),
819         and the size of extra-data space.  The last argument is used to
820         allocate card-&gt;private_data for the
821         chip-specific data.  Note that this data
822         <emphasis>is</emphasis> allocated by
823         <function>snd_card_new()</function>.
824       </para>
825     </section>
826
827     <section id="card-management-component">
828       <title>Components</title>
829       <para>
830         After the card is created, you can attach the components
831       (devices) to the card instance. On ALSA driver, a component is
832       represented as a <type>snd_device_t</type> object.
833       A component can be a PCM instance, a control interface, a raw
834       MIDI interface, etc.  Each of such instances has one component
835       entry.
836       </para>
837
838       <para>
839         A component can be created via
840         <function>snd_device_new()</function> function. 
841
842         <informalexample>
843           <programlisting>
844 <![CDATA[
845   snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
846 ]]>
847           </programlisting>
848         </informalexample>
849       </para>
850
851       <para>
852         This takes the card pointer, the device-level
853       (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
854       callback pointers (<parameter>&amp;ops</parameter>). The
855       device-level defines the type of components and the order of
856       registration and de-registration.  For most of components, the
857       device-level is already defined.  For a user-defined component,
858       you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
859       </para>
860
861       <para>
862       This function itself doesn't allocate the data space. The data
863       must be allocated manually beforehand, and its pointer is passed
864       as the argument. This pointer is used as the identifier
865       (<parameter>chip</parameter> in the above example) for the
866       instance. 
867       </para>
868
869       <para>
870         Each ALSA pre-defined component such as ac97 or pcm calls
871       <function>snd_device_new()</function> inside its
872       constructor. The destructor for each component is defined in the
873       callback pointers.  Hence, you don't need to take care of
874       calling a destructor for such a component.
875       </para>
876
877       <para>
878         If you would like to create your own component, you need to
879       set the destructor function to dev_free callback in
880       <parameter>ops</parameter>, so that it can be released
881       automatically via <function>snd_card_free()</function>. The
882       example will be shown later as an implementation of a
883       chip-specific data. 
884       </para>
885     </section>
886
887     <section id="card-management-chip-specific">
888       <title>Chip-Specific Data</title>
889       <para>
890       The chip-specific information, e.g. the i/o port address, its
891       resource pointer, or the irq number, is stored in the
892       chip-specific record.
893       Usually, the chip-specific record is typedef'ed as
894       <type>xxx_t</type> like the following:
895
896         <informalexample>
897           <programlisting>
898 <![CDATA[
899   typedef struct snd_mychip mychip_t;
900   struct snd_mychip {
901           ....
902   };
903 ]]>
904           </programlisting>
905         </informalexample>
906       </para>
907
908       <para>
909         You might have objections against such a typedef, but this
910       typedef is necessary if you use a <quote>magic-cast</quote>
911       (explained <link
912       linkend="card-management-chip-what-advantage"><citetitle>later</citetitle></link>). 
913       </para>
914
915       <para>
916         In general, there are two ways to allocate the chip record.
917       </para>
918
919       <section id="card-management-chip-specific-snd-card-new">
920         <title>1. Allocating via <function>snd_card_new()</function>.</title>
921         <para>
922           As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
923
924           <informalexample>
925             <programlisting>
926 <![CDATA[
927   card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
928 ]]>
929             </programlisting>
930           </informalexample>
931
932           whether <type>mychip_t</type> is the type of the chip record.
933         </para>
934
935         <para>
936           In return, the allocated record can be accessed as
937
938           <informalexample>
939             <programlisting>
940 <![CDATA[
941   mychip_t *chip = (mychip_t *)card->private_data;
942 ]]>
943             </programlisting>
944           </informalexample>
945
946           With this method, you don't have to allocate twice. But you
947         cannot use <quote>magic-cast</quote> for this record pointer,
948         instead. 
949         </para>
950       </section>
951
952       <section id="card-management-chip-specific-allocate-extra">
953         <title>2. Allocating an extra device.</title>
954
955         <para>
956           After allocating a card instance via
957           <function>snd_card_new()</function> (with
958           <constant>NULL</constant> on the 4th arg), call
959           <function>snd_magic_kcalloc()</function>. 
960
961           <informalexample>
962             <programlisting>
963 <![CDATA[
964   snd_card_t *card;
965   mychip_t *chip;
966   card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
967   .....
968   chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
969 ]]>
970             </programlisting>
971           </informalexample>
972
973           Once when the record is allocated via snd_magic stuff, you
974         can use <quote>magic-cast</quote> for the void pointer. 
975         </para>
976
977         <para>
978           The chip record should have the field to hold the card
979           pointer at least, 
980
981           <informalexample>
982             <programlisting>
983 <![CDATA[
984   struct snd_mychip {
985           snd_card_t *card;
986           ....
987   };
988 ]]>
989             </programlisting>
990           </informalexample>
991         </para>
992
993         <para>
994           Then, set the card pointer in the returned chip instance.
995
996           <informalexample>
997             <programlisting>
998 <![CDATA[
999   chip->card = card;
1000 ]]>
1001             </programlisting>
1002           </informalexample>
1003         </para>
1004
1005         <para>
1006           Also, you need to define a magic-value for <type>mychip_t</type>.
1007
1008           <informalexample>
1009             <programlisting>
1010 <![CDATA[
1011   #define mychip_t_magic        0xa15a4501
1012 ]]>
1013             </programlisting>
1014           </informalexample>
1015         (the detail will be described in the
1016         <link linkend="card-management-chip-what-advantage"><citetitle>
1017         next</citetitle></link> subsection).
1018         </para>
1019
1020         <para>
1021           Next, initialize the fields, and register this chip
1022           record as a low-level device with a specified
1023           <parameter>ops</parameter>, 
1024
1025           <informalexample>
1026             <programlisting>
1027 <![CDATA[
1028   static snd_device_ops_t ops = {
1029           .dev_free =        snd_mychip_dev_free,
1030   };
1031   ....
1032   snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1033 ]]>
1034             </programlisting>
1035           </informalexample>
1036
1037           <function>snd_mychip_dev_free()</function> is the
1038         device-destructor function, which will call the real
1039         destructor. 
1040         </para>
1041
1042         <para>
1043           <informalexample>
1044             <programlisting>
1045 <![CDATA[
1046   static int snd_mychip_dev_free(snd_device_t *device)
1047   {
1048           mychip_t *chip = snd_magic_cast(mychip_t, device->device_data,
1049                                           return -ENXIO);
1050           return snd_mychip_free(chip);
1051   }
1052 ]]>
1053             </programlisting>
1054           </informalexample>
1055
1056           where <function>snd_mychip_free()</function> is the real destructor.
1057         </para>
1058       </section>
1059
1060       <section id="card-management-chip-what-advantage">
1061         <title>Not a magic but a logic</title>
1062
1063         <para>Now, you might have a question: What is the advantage of the
1064         second method?  Obviously, it looks far more complicated.</para> 
1065         <para>
1066           As I wrote many times, the second method allows a
1067         <quote>magic-cast</quote> for <type>mychip_t</type>. If you
1068         have a void pointer (such as
1069         pcm-&gt;private_data), the pointer type
1070         is unknown at the compile time, and you cannot know even if a
1071         wrong pointer type is passed. The compiler would accept
1072         it. The magic-cast checks the pointer type at the runtime (and
1073         whether it's a null pointer, too). Hence, the cast will be
1074         much safer and good for debugging. 
1075         </para>
1076
1077         <para>
1078         As you have already seen, allocation with a magic-header can
1079         be done via <function>snd_magic_kmalloc()</function> or
1080         <function>snd_magic_kcalloc()</function>.
1081
1082           <informalexample>
1083             <programlisting>
1084 <![CDATA[
1085   mychip_t *chip;
1086   chip = snd_magic_kmalloc(mychip_t, 0, GFP_KERNEL);
1087   chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1088 ]]>
1089             </programlisting>
1090           </informalexample>
1091
1092         The difference of these two functions is whether the area is
1093         zero-cleared (<function>kcalloc</function>) or not
1094         (<function>kmalloc</function>).
1095         </para>
1096
1097         <para>
1098         The first argument of the allocator is the type of the
1099         record.  The magic-constant has to be defined for this type
1100         beforehand.  In this case, we'll need to define
1101         <constant>mychip_t_magic</constant>, for example, as already
1102         seen,
1103
1104           <informalexample>
1105             <programlisting>
1106 <![CDATA[
1107   #define mychip_t_magic        0xa15a4501
1108 ]]>
1109             </programlisting>
1110           </informalexample>
1111
1112         The value is arbitrary but should be unique.
1113         This is usually defined in
1114         <filename>&lt;include/sndmagic.h&gt;</filename> or
1115         <filename>&lt;include/amagic.h&gt;</filename> for alsa-driver tree,
1116         but you may define it locally in the code at the early
1117         development stage, since changing
1118         <filename>sndmagic.h</filename> will lead to the recompilation
1119         of the whole driver codes.
1120         </para>
1121
1122         <para>
1123         The second argument is the extra-data length.  It is usually
1124         zero.  The third argument is the flags to be passed to kernel
1125         memory allocator, <constant>GFP_XXX</constant>.  Normally,
1126         <constant>GFP_KERNEL</constant> is passed.
1127         </para>
1128
1129         <para>
1130           For casting a pointer, use
1131           <function>snd_magic_cast()</function> macro:
1132
1133           <informalexample>
1134             <programlisting>
1135 <![CDATA[
1136   mychip_t *chip = snd_magic_cast(mychip_t, source_pointer, action);
1137 ]]>
1138             </programlisting>
1139           </informalexample>
1140
1141         where <parameter>source_pointer</parameter> is the pointer to
1142         be casted (e.g. pcm-&gt;private_data), and
1143         <parameter>action</parameter> is the action to do if the cast
1144         fails (e.g. return <constant>-EINVAL</constant>). 
1145         </para>
1146
1147         <para>
1148         For releasing the magic-allocated data, you need to call
1149         <function>snd_magic_kfree()</function> function instead of
1150         <function>kfree()</function>.
1151
1152           <informalexample>
1153             <programlisting>
1154 <![CDATA[
1155   snd_magic_kfree(chip);
1156 ]]>
1157             </programlisting>
1158           </informalexample>
1159         </para>
1160
1161         <para>
1162         If you call <function>kfree()</function> for the
1163         magic-allocated value, it will lead to memory leaks.
1164         When the ALSA drivers are compiled with
1165         <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config (or
1166         configured with <option>--with-debug=full</option>), the
1167         non-matching free will be checked and you'll see warning
1168         messages.
1169         </para>
1170
1171         <para>
1172           If you are 100% sure that your code is bug-free, you can
1173           compile the driver without
1174           <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config,
1175           so that the magic-allocator and the magic-cast will be
1176           replaced to the normal kmalloc and cast.
1177         </para>
1178       </section>
1179     </section>
1180
1181     <section id="card-management-registration">
1182       <title>Registration and Release</title>
1183       <para>
1184         After all components are assigned, register the card instance
1185       by calling <function>snd_card_register()</function>. The access
1186       to the device files are enabled at this point. That is, before
1187       <function>snd_card_register()</function> is called, the
1188       components are safely inaccessible from external side. If this
1189       call fails, exit the probe function after releasing the card via
1190       <function>snd_card_free()</function>. 
1191       </para>
1192
1193       <para>
1194         For releasing the card instance, you can call simply
1195       <function>snd_card_free()</function>. As already mentioned, all
1196       components are released automatically by this call. 
1197       </para>
1198
1199       <para>
1200         As further notes, the destructors (both
1201       <function>snd_mychip_dev_free</function> and
1202       <function>snd_mychip_free</function>) cannot be defined with
1203       <parameter>__devexit</parameter> prefix, because they may be
1204       called from the constructor, too, at the false path. 
1205       </para>
1206
1207       <para>
1208       For a device which allows hotplugging, you can use
1209       <function>snd_card_free_in_thread</function>.  This one will
1210       postpone the destruction and wait in a kernel-thread until all
1211       devices are closed.
1212       </para>
1213
1214     </section>
1215
1216   </chapter>
1217
1218
1219 <!-- ****************************************************** -->
1220 <!-- PCI Resource Managements  -->
1221 <!-- ****************************************************** -->
1222   <chapter id="pci-resource">
1223     <title>PCI Resource Managements</title>
1224
1225     <section id="pci-resource-example">
1226       <title>Full Code Example</title>
1227       <para>
1228         In this section, we'll finish the chip-specific constructor,
1229       destructor and PCI entries. The example code is shown first,
1230       below. 
1231
1232         <example>
1233           <title>PCI Resource Managements Example</title>
1234           <programlisting>
1235 <![CDATA[
1236   struct snd_mychip {
1237           snd_card_t *card;
1238           struct pci_dev *pci;
1239
1240           unsigned long port;
1241           struct resource *res_port;
1242
1243           int irq;
1244   };
1245
1246   static int snd_mychip_free(mychip_t *chip)
1247   {
1248           // disable hardware here if any
1249           // (not implemented in this document)
1250
1251           // release the i/o port
1252           if (chip->res_port) {
1253                   release_resource(chip->res_port);
1254                   kfree_nocheck(chip->res_port);
1255           }
1256           // release the irq
1257           if (chip->irq >= 0)
1258                   free_irq(chip->irq, (void *)chip);
1259           // release the data
1260           snd_magic_kfree(chip);
1261           return 0;
1262   }
1263
1264   // chip-specific constructor
1265   static int __devinit snd_mychip_create(snd_card_t *card,
1266                                          struct pci_dev *pci,
1267                                          mychip_t **rchip)
1268   {
1269           mychip_t *chip;
1270           int err;
1271           static snd_device_ops_t ops = {
1272                  .dev_free = snd_mychip_dev_free,
1273           };
1274
1275           *rchip = NULL;
1276
1277           // check PCI availability (28bit DMA)
1278           if ((err = pci_enable_device(pci)) < 0)
1279                   return err;
1280           if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1281               pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1282                   printk(KERN_ERR "error to set 28bit mask DMA\n");
1283                   return -ENXIO;
1284           }
1285
1286           chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1287           if (chip == NULL)
1288                   return -ENOMEM;
1289
1290           // initialize the stuff
1291           chip->card = card;
1292           chip->pci = pci;
1293           chip->irq = -1;
1294
1295           // (1) PCI resource allocation
1296           chip->port = pci_resource_start(pci, 0);
1297           if ((chip->res_port = request_region(chip->port, 8,
1298                                                  "My Chip")) == NULL) { 
1299                   snd_mychip_free(chip);
1300                   printk(KERN_ERR "cannot allocate the port\n");
1301                   return -EBUSY;
1302           }
1303           if (request_irq(pci->irq, snd_mychip_interrupt,
1304                           SA_INTERRUPT|SA_SHIRQ, "My Chip",
1305                           (void *)chip)) {
1306                   snd_mychip_free(chip);
1307                   printk(KERN_ERR "cannot grab irq\n");
1308                   return -EBUSY;
1309           }
1310           chip->irq = pci->irq;
1311
1312           // (2) initialization of the chip hardware
1313           //     (not implemented in this document)
1314
1315           if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1316                                     chip, &ops)) < 0) {
1317                   snd_mychip_free(chip);
1318                   return err;
1319           }
1320           *rchip = chip;
1321           return 0;
1322   }        
1323
1324   // PCI IDs
1325   static struct pci_device_id snd_mychip_ids[] = {
1326           { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1327             PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1328           ....
1329           { 0, }
1330   };
1331   MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1332
1333   // pci_driver definition
1334   static struct pci_driver driver = {
1335           .name = "My Own Chip",
1336           .id_table = snd_mychip_ids,
1337           .probe = snd_mychip_probe,
1338           .remove = __devexit_p(snd_mychip_remove),
1339   };
1340
1341   // initialization of the module
1342   static int __init alsa_card_mychip_init(void)
1343   {
1344           return pci_module_init(&driver);
1345   }
1346
1347   // clean up the module
1348   static void __exit alsa_card_mychip_exit(void)
1349   {
1350           pci_unregister_driver(&driver);
1351   }
1352
1353   module_init(alsa_card_mychip_init)
1354   module_exit(alsa_card_mychip_exit)
1355
1356   EXPORT_NO_SYMBOLS; /* for old kernels only */
1357 ]]>
1358           </programlisting>
1359         </example>
1360       </para>
1361     </section>
1362
1363     <section id="pci-resource-some-haftas">
1364       <title>Some Hafta's</title>
1365       <para>
1366         The allocation of PCI resources is done in the
1367       <function>probe()</function> function, and usually an extra
1368       <function>xxx_create()</function> function is written for this
1369       purpose. 
1370       </para>
1371
1372       <para>
1373         In the case of PCI devices, you have to call at first
1374       <function>pci_enable_device()</function> function before
1375       allocating resources. Also, you need to set the proper PCI DMA
1376       mask to limit the accessed i/o range. In some cases, you might
1377       need to call <function>pci_set_master()</function> function,
1378       too. 
1379       </para>
1380
1381       <para>
1382         Suppose the 28bit mask, and the code to be added would be like:
1383
1384         <informalexample>
1385           <programlisting>
1386 <![CDATA[
1387   if ((err = pci_enable_device(pci)) < 0)
1388           return err;
1389   if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1390       pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1391           printk(KERN_ERR "error to set 28bit mask DMA\n");
1392           return -ENXIO;
1393   }
1394   
1395 ]]>
1396           </programlisting>
1397         </informalexample>
1398       </para>
1399     </section>
1400
1401     <section id="pci-resource-resource-allocation">
1402       <title>Resource Allocation</title>
1403       <para>
1404         The allocation of I/O ports and irqs are done via standard kernel
1405       functions. Unlike ALSA ver.0.5.x., there are no helpers for
1406       that. And these resources must be released in the destructor
1407       function (see below). Also, on ALSA 0.9.x, you don't need to
1408       allocate (pseudo-)DMA for PCI like ALSA 0.5.x. 
1409       </para>
1410
1411       <para>
1412         Now assume that this PCI device has an I/O port with 8 bytes
1413         and an interrupt. Then <type>mychip_t</type> will have the
1414         following fields: 
1415
1416         <informalexample>
1417           <programlisting>
1418 <![CDATA[
1419   struct snd_mychip {
1420           snd_card_t *card;
1421
1422           unsigned long port;
1423           struct resource *res_port;
1424
1425           int irq;
1426   };
1427 ]]>
1428           </programlisting>
1429         </informalexample>
1430       </para>
1431
1432       <para>
1433         For an i/o port (and also a memory region), you need to have
1434       the resource pointer for the standard resource management. For
1435       an irq, you have to keep only the irq number (integer). But you
1436       need to initialize this number as -1 before actual allocation,
1437       since irq 0 is valid. The port address and its resource pointer
1438       can be initialized as null by
1439       <function>snd_magic_kcalloc()</function> automatically, so you
1440       don't have to take care of resetting them. 
1441       </para>
1442
1443       <para>
1444         The allocation of an i/o port is done like this:
1445
1446         <informalexample>
1447           <programlisting>
1448 <![CDATA[
1449   chip->port = pci_resource_start(pci, 0);
1450   if ((chip->res_port = request_region(chip->port, 8,
1451                                        "My Chip")) == NULL) { 
1452           printk(KERN_ERR "cannot allocate the port 0x%lx\n",
1453                  chip->port);
1454           snd_mychip_free(chip);
1455           return -EBUSY;
1456   }
1457 ]]>
1458           </programlisting>
1459         </informalexample>
1460       </para>
1461
1462       <para>
1463         It will reserve the i/o port region of 8 bytes of the given
1464       PCI device. The returned value, chip-&gt;res_port, is allocated
1465       via <function>kmalloc()</function> by
1466       <function>request_region()</function>. The pointer must be
1467       released via <function>kfree()</function>, but there is some
1468       problem regarding this. This issue will be explained more below.
1469       </para>
1470
1471       <para>
1472         The allocation of an interrupt source is done like this:
1473
1474         <informalexample>
1475           <programlisting>
1476 <![CDATA[
1477   if (request_irq(pci->irq, snd_mychip_interrupt,
1478                   SA_INTERRUPT|SA_SHIRQ, "My Chip",
1479                   (void *)chip)) {
1480           snd_mychip_free(chip);
1481           printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1482           return -EBUSY;
1483   }
1484   chip->irq = pci->irq;
1485 ]]>
1486           </programlisting>
1487         </informalexample>
1488
1489         where <function>snd_mychip_interrupt()</function> is the
1490       interrupt handler defined <link
1491       linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1492       Note that chip-&gt;irq should be defined
1493       only when <function>request_irq()</function> succeeded.
1494       </para>
1495
1496       <para>
1497       On the PCI bus, the interrupts can be shared. Thus,
1498       <constant>SA_SHIRQ</constant> is given as the interrupt flag of
1499       <function>request_irq()</function>. 
1500       </para>
1501
1502       <para>
1503         The last argument of <function>request_irq()</function> is the
1504       data pointer passed to the interrupt handler. Usually, the
1505       chip-specific record is used for that, but you can use what you
1506       like, too. 
1507       </para>
1508
1509       <para>
1510         I won't define the detail of the interrupt handler at this
1511         point, but at least its appearance can be explained now. The
1512         interrupt handler looks usually like the following: 
1513
1514         <informalexample>
1515           <programlisting>
1516 <![CDATA[
1517   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1518                                           struct pt_regs *regs)
1519   {
1520           mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
1521           ....
1522           return IRQ_HANDLED;
1523   }
1524 ]]>
1525           </programlisting>
1526         </informalexample>
1527
1528         Again the magic-cast is used here to get the correct pointer
1529       from the second argument. 
1530       </para>
1531
1532       <para>
1533         Now let's write the corresponding destructor for the resources
1534       above. The role of destructor is simple: disable the hardware
1535       (if already activated) and release the resources. So far, we
1536       have no hardware part, so the disabling is not written here. 
1537       </para>
1538
1539       <para>
1540         For releasing the resources, <quote>check-and-release</quote>
1541         method is a safer way. For the i/o port, do like this: 
1542
1543         <informalexample>
1544           <programlisting>
1545 <![CDATA[
1546   if (chip->res_port) {
1547           release_resource(chip->res_port);
1548           kfree_nocheck(chip->res_port);
1549   }
1550 ]]>
1551           </programlisting>
1552         </informalexample>
1553       </para>
1554
1555       <para>
1556         As you can see, the i/o resource pointer is also to be freed
1557       via <function>kfree_nocheck()</function> after
1558       <function>release_resource()</function> is called. You
1559       cannot use <function>kfree()</function> here, because on ALSA,
1560       <function>kfree()</function> may be a wrapper to its own
1561       allocator with the memory debugging. Since the resource pointer
1562       is allocated externally outside the ALSA, it must be released
1563       via the native
1564       <function>kfree()</function>.
1565       <function>kfree_nocheck()</function> is used for that; it calls
1566       the native <function>kfree()</function> without wrapper. 
1567       </para>
1568
1569       <para>
1570         For releasing the interrupt, do like this:
1571
1572         <informalexample>
1573           <programlisting>
1574 <![CDATA[
1575   if (chip->irq >= 0)
1576           free_irq(chip->irq, (void *)chip);
1577 ]]>
1578           </programlisting>
1579         </informalexample>
1580
1581         And finally, release the chip-specific record.
1582
1583         <informalexample>
1584           <programlisting>
1585 <![CDATA[
1586   snd_magic_kfree(chip);
1587 ]]>
1588           </programlisting>
1589         </informalexample>
1590       </para>
1591
1592       <para>
1593         The chip instance is freed via
1594       <function>snd_magic_kfree()</function>. Please use this function
1595       for the object allocated by
1596       <function>snd_magic_kmalloc()</function>. If you free it with
1597       <function>kfree()</function>, it won't work properly and will
1598       result in the memory leak. Also, again, remember that you cannot
1599       set <parameter>__devexit</parameter> prefix for this destructor. 
1600       </para>
1601
1602       <para>
1603       We didn't implement the hardware-disabling part in the above.
1604       If you need to do this, please note that the destructor may be
1605       called even before the initialization of the chip is completed.
1606       It would be better to have a flag to skip the hardware-disabling
1607       if the hardware was not initialized yet.
1608       </para>
1609
1610       <para>
1611       When the chip-data is assigned to the card using
1612       <function>snd_device_new()</function> with
1613       <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is 
1614       called at the last.  that is, it is assured that all other
1615       components like PCMs and controls have been already released.
1616       You don't have to call stopping PCMs, etc. explicitly, but just
1617       stop the hardware in the low-level.
1618       </para>
1619
1620       <para>
1621         The management of a memory-mapped region is almost as same as
1622         the management of an i/o port. You'll need three fields like
1623         the following: 
1624
1625         <informalexample>
1626           <programlisting>
1627 <![CDATA[
1628   struct snd_mychip {
1629           ....
1630           unsigned long iobase_phys;
1631           unsigned long iobase_virt;
1632           struct resource *res_iobase;
1633   };
1634 ]]>
1635           </programlisting>
1636         </informalexample>
1637
1638         and the allocation would be (assuming its size is 512 bytes):
1639
1640         <informalexample>
1641           <programlisting>
1642 <![CDATA[
1643   chip->iobase_phys = pci_resource_start(pci, 0);
1644   chip->iobase_virt = (unsigned long)
1645                       ioremap_nocache(chip->iobase_phys, 512);
1646   if ((chip->res_port = request_mem_region(chip->iobase_phys, 512,
1647                                            "My Chip")) == NULL) {
1648           printk(KERN_ERR "cannot allocate the memory region\n");
1649           snd_mychip_free(chip);
1650           return -EBUSY;
1651   }
1652 ]]>
1653           </programlisting>
1654         </informalexample>
1655         
1656         and the corresponding destructor would be:
1657
1658         <informalexample>
1659           <programlisting>
1660 <![CDATA[
1661   static int snd_mychip_free(mychip_t *chip)
1662   {
1663           ....
1664           if (chip->iobase_virt)
1665                   iounmap((void *)chip->iobase_virt);
1666           if (chip->res_iobase) {
1667                   release_resource(chip->res_iobase);
1668                   kfree_nocheck(chip->res_iobase);
1669           }
1670           ....
1671   }
1672 ]]>
1673           </programlisting>
1674         </informalexample>
1675       </para>
1676
1677     </section>
1678
1679     <section id="pci-resource-entries">
1680       <title>PCI Entries</title>
1681       <para>
1682         So far, so good. Let's finish the rest of missing PCI
1683       stuffs. At first, we need a
1684       <structname>pci_device_id</structname> table for this
1685       chipset. It's a table of PCI vendor/device ID number, and some
1686       masks. 
1687       </para>
1688
1689       <para>
1690         For example,
1691
1692         <informalexample>
1693           <programlisting>
1694 <![CDATA[
1695   static struct pci_device_id snd_mychip_ids[] = {
1696           { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1697             PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1698           ....
1699           { 0, }
1700   };
1701   MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1702 ]]>
1703           </programlisting>
1704         </informalexample>
1705       </para>
1706
1707       <para>
1708         The first and second fields of
1709       <structname>pci_device_id</structname> struct are the vendor and
1710       device IDs. If you have nothing special to filter the matching
1711       devices, you can use the rest of fields like above. The last
1712       field of <structname>pci_device_id</structname> struct is a
1713       private data for this entry. You can specify any value here, for
1714       example, to tell the type of different operations per each
1715       device IDs. Such an example is found in intel8x0 driver. 
1716       </para>
1717
1718       <para>
1719         The last entry of this list is the terminator. You must
1720       specify this all-zero entry. 
1721       </para>
1722
1723       <para>
1724         Then, prepare the <structname>pci_driver</structname> record:
1725
1726         <informalexample>
1727           <programlisting>
1728 <![CDATA[
1729   static struct pci_driver driver = {
1730           .name = "My Own Chip",
1731           .id_table = snd_mychip_ids,
1732           .probe = snd_mychip_probe,
1733           .remove = __devexit_p(snd_mychip_remove),
1734   };
1735 ]]>
1736           </programlisting>
1737         </informalexample>
1738       </para>
1739
1740       <para>
1741         The <structfield>probe</structfield> and
1742       <structfield>remove</structfield> functions are what we already
1743       defined in 
1744       the previous sections. The <structfield>remove</structfield> should
1745       be defined with 
1746       <function>__devexit_p()</function> macro, so that it's not
1747       defined for built-in (and non-hot-pluggable) case. The
1748       <structfield>name</structfield> 
1749       field is the name string of this device. Note that you must not
1750       use a slash <quote>/</quote> in this string. 
1751       </para>
1752
1753       <para>
1754         And at last, the module entries:
1755
1756         <informalexample>
1757           <programlisting>
1758 <![CDATA[
1759   static int __init alsa_card_mychip_init(void)
1760   {
1761           return pci_module_init(&driver);
1762   }
1763
1764   static void __exit alsa_card_mychip_exit(void)
1765   {
1766           pci_unregister_driver(&driver);
1767   }
1768
1769   module_init(alsa_card_mychip_init)
1770   module_exit(alsa_card_mychip_exit)
1771 ]]>
1772           </programlisting>
1773         </informalexample>
1774       </para>
1775
1776       <para>
1777         Note that these module entries are tagged with
1778       <parameter>__init</parameter> and 
1779       <parameter>__exit</parameter> prefixes, not
1780       <parameter>__devinit</parameter> nor
1781       <parameter>__devexit</parameter>.
1782       </para>
1783
1784       <para>
1785         Oh, one thing was forgotten. If you have no exported symbols,
1786         you need to declare it on 2.2 or 2.4 kernels (on 2.6 kernels
1787         it's not necessary, though).
1788
1789         <informalexample>
1790           <programlisting>
1791 <![CDATA[
1792   EXPORT_NO_SYMBOLS;
1793 ]]>
1794           </programlisting>
1795         </informalexample>
1796
1797         That's all!
1798       </para>
1799     </section>
1800   </chapter>
1801
1802
1803 <!-- ****************************************************** -->
1804 <!-- PCM Interface  -->
1805 <!-- ****************************************************** -->
1806   <chapter id="pcm-interface">
1807     <title>PCM Interface</title>
1808
1809     <section id="pcm-interface-general">
1810       <title>General</title>
1811       <para>
1812         The PCM middle layer of ALSA is quite powerful and it is only
1813       necessary for each driver to implement the low-level functions
1814       to access its hardware.
1815       </para>
1816
1817       <para>
1818         For accessing to the PCM layer, you need to include
1819       <filename>&lt;sound/pcm.h&gt;</filename> above all. In addition,
1820       <filename>&lt;sound/pcm_params.h&gt;</filename> might be needed
1821       if you access to some functions related with hw_param. 
1822       </para>
1823
1824       <para>
1825         Each card device can have up to four pcm instances. A pcm
1826       instance corresponds to a pcm device file. The limitation of
1827       number of instances comes only from the available bit size of
1828       the linux's device number. Once when 64bit device number is
1829       used, we'll have more available pcm instances. 
1830       </para>
1831
1832       <para>
1833         A pcm instance consists of pcm playback and capture streams,
1834       and each pcm stream consists of one or more pcm substreams. Some
1835       soundcard supports the multiple-playback function. For example,
1836       emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1837       each open, a free substream is (usually) automatically chosen
1838       and opened. Meanwhile, when only one substream exists and it was
1839       already opened, the succeeding open will result in the blocking
1840       or the error with <constant>EAGAIN</constant> according to the
1841       file open mode. But you don't have to know the detail in your
1842       driver. The PCM middle layer will take all such jobs. 
1843       </para>
1844     </section>
1845
1846     <section id="pcm-interface-example">
1847       <title>Full Code Example</title>
1848       <para>
1849       The example code below does not include any hardware access
1850       routines but shows only the skeleton, how to build up the PCM
1851       interfaces.
1852
1853         <example>
1854           <title>PCM Example Code</title>
1855           <programlisting>
1856 <![CDATA[
1857   #include <sound/pcm.h>
1858   ....
1859
1860   #define chip_t mychip_t
1861   ....
1862
1863   /* hardware definition */
1864   static snd_pcm_hardware_t snd_mychip_playback_hw = {
1865           .info = (SNDRV_PCM_INFO_MMAP |
1866                    SNDRV_PCM_INFO_INTERLEAVED |
1867                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
1868                    SNDRV_PCM_INFO_MMAP_VALID),
1869           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
1870           .rates =            SNDRV_PCM_RATE_8000_48000,
1871           .rate_min =         8000,
1872           .rate_max =         48000,
1873           .channels_min =     2,
1874           .channels_max =     2,
1875           .buffer_bytes_max = 32768,
1876           .period_bytes_min = 4096,
1877           .period_bytes_max = 32768,
1878           .periods_min =      1,
1879           .periods_max =      1024,
1880   };
1881
1882   /* hardware definition */
1883   static snd_pcm_hardware_t snd_mychip_capture_hw = {
1884           .info = (SNDRV_PCM_INFO_MMAP |
1885                    SNDRV_PCM_INFO_INTERLEAVED |
1886                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
1887                    SNDRV_PCM_INFO_MMAP_VALID),
1888           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
1889           .rates =            SNDRV_PCM_RATE_8000_48000,
1890           .rate_min =         8000,
1891           .rate_max =         48000,
1892           .channels_min =     2,
1893           .channels_max =     2,
1894           .buffer_bytes_max = 32768,
1895           .period_bytes_min = 4096,
1896           .period_bytes_max = 32768,
1897           .periods_min =      1,
1898           .periods_max =      1024,
1899   };
1900
1901   /* open callback */
1902   static int snd_mychip_playback_open(snd_pcm_substream_t *substream)
1903   {
1904           mychip_t *chip = snd_pcm_substream_chip(substream);
1905           snd_pcm_runtime_t *runtime = substream->runtime;
1906
1907           runtime->hw = snd_mychip_playback_hw;
1908           // more hardware-initialization will be done here
1909           return 0;
1910   }
1911
1912   /* close callback */
1913   static int snd_mychip_playback_close(snd_pcm_substream_t *substream)
1914   {
1915           mychip_t *chip = snd_pcm_substream_chip(substream);
1916           // the hardware-specific codes will be here
1917           return 0;
1918
1919   }
1920
1921   /* open callback */
1922   static int snd_mychip_capture_open(snd_pcm_substream_t *substream)
1923   {
1924           mychip_t *chip = snd_pcm_substream_chip(substream);
1925           snd_pcm_runtime_t *runtime = substream->runtime;
1926
1927           runtime->hw = snd_mychip_capture_hw;
1928           // more hardware-initialization will be done here
1929           return 0;
1930   }
1931
1932   /* close callback */
1933   static int snd_mychip_capture_close(snd_pcm_substream_t *substream)
1934   {
1935           mychip_t *chip = snd_pcm_substream_chip(substream);
1936           // the hardware-specific codes will be here
1937           return 0;
1938
1939   }
1940
1941   /* hw_params callback */
1942   static int snd_mychip_pcm_hw_params(snd_pcm_substream_t *substream,
1943                                snd_pcm_hw_params_t * hw_params)
1944   {
1945           return snd_pcm_lib_malloc_pages(substream,
1946                                      params_buffer_bytes(hw_params));
1947   }
1948
1949   /* hw_free callback */
1950   static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1951   {
1952           return snd_pcm_lib_free_pages(substream);
1953   }
1954
1955   /* prepare callback */
1956   static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1957   {
1958           mychip_t *chip = snd_pcm_substream_chip(substream);
1959           snd_pcm_runtime_t *runtime = substream->runtime;
1960
1961           // set up the hardware with the current configuration
1962           // for example...
1963           mychip_set_sample_format(chip, runtime->format);
1964           mychip_set_sample_rate(chip, runtime->rate);
1965           mychip_set_channels(chip, runtime->channels);
1966           mychip_set_dma_setup(chip, runtime->dma_area,
1967                                chip->buffer_size,
1968                                chip->period_size);
1969           return 0;
1970   }
1971
1972   /* trigger callback */
1973   static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
1974                                     int cmd)
1975   {
1976           switch (cmd) {
1977           case SNDRV_PCM_TRIGGER_START:
1978                   // do something to start the PCM engine
1979                   break;
1980           case SNDRV_PCM_TRIGGER_STOP:
1981                   // do something to stop the PCM engine
1982                   break;
1983           default:
1984                   return -EINVAL;
1985           }
1986   }
1987
1988   /* pointer callback */
1989   static snd_pcm_uframes_t
1990   snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
1991   {
1992           mychip_t *chip = snd_pcm_substream_chip(substream);
1993           unsigned int current_ptr;
1994
1995           // get the current hardware pointer
1996           current_ptr = mychip_get_hw_pointer(chip);
1997           return current_ptr;
1998   }
1999
2000   /* operators */
2001   static snd_pcm_ops_t snd_mychip_playback_ops = {
2002           .open =        snd_mychip_playback_open,
2003           .close =       snd_mychip_playback_close,
2004           .ioctl =       snd_pcm_lib_ioctl,
2005           .hw_params =   snd_mychip_pcm_hw_params,
2006           .hw_free =     snd_mychip_pcm_hw_free,
2007           .prepare =     snd_mychip_pcm_prepare,
2008           .trigger =     snd_mychip_pcm_trigger,
2009           .pointer =     snd_mychip_pcm_pointer,
2010   };
2011
2012   /* operators */
2013   static snd_pcm_ops_t snd_mychip_capture_ops = {
2014           .open =        snd_mychip_capture_open,
2015           .close =       snd_mychip_capture_close,
2016           .ioctl =       snd_pcm_lib_ioctl,
2017           .hw_params =   snd_mychip_pcm_hw_params,
2018           .hw_free =     snd_mychip_pcm_hw_free,
2019           .prepare =     snd_mychip_pcm_prepare,
2020           .trigger =     snd_mychip_pcm_trigger,
2021           .pointer =     snd_mychip_pcm_pointer,
2022   };
2023
2024   /*
2025    *  definitions of capture are omitted here...
2026    */
2027
2028   /* create a pcm device */
2029   static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2030   {
2031           snd_pcm_t *pcm;
2032           int err;
2033
2034           if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2035                                  &pcm)) < 0) 
2036                   return err;
2037           pcm->private_data = chip;
2038           strcpy(pcm->name, "My Chip");
2039           chip->pcm = pcm;
2040           /* set operators */
2041           snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2042                           &snd_mychip_playback_ops);
2043           snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2044                           &snd_mychip_capture_ops);
2045           /* pre-allocation of buffers */
2046           snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2047                                                 snd_dma_pci_data(chip->pci),
2048                                                 64*1024, 64*1024);
2049           return 0;
2050   }
2051 ]]>
2052           </programlisting>
2053         </example>
2054       </para>
2055     </section>
2056
2057     <section id="pcm-interface-constructor">
2058       <title>Constructor</title>
2059       <para>
2060         A pcm instance is allocated <function>snd_pcm_new()</function>
2061       function. It would be better to create a constructor for pcm,
2062       namely, 
2063
2064         <informalexample>
2065           <programlisting>
2066 <![CDATA[
2067   static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2068   {
2069           snd_pcm_t *pcm;
2070           int err;
2071
2072           if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2073                                  &pcm)) < 0) 
2074                   return err;
2075           pcm->private_data = chip;
2076           strcpy(pcm->name, "My Chip");
2077           chip->pcm = pcm;
2078           ....
2079           return 0;
2080   }
2081 ]]>
2082           </programlisting>
2083         </informalexample>
2084       </para>
2085
2086       <para>
2087         The <function>snd_pcm_new()</function> function takes the four
2088       arguments. The first argument is the card pointer to which this
2089       pcm is assigned, and the second is the ID string. 
2090       </para>
2091
2092       <para>
2093         The third argument (<parameter>index</parameter>, 0 in the
2094       above) is the index of this new pcm. It begins from zero. When
2095       you will create more than one pcm instances, specify the
2096       different numbers in this argument. For example,
2097       <parameter>index</parameter> = 1 for the second PCM device.  
2098       </para>
2099
2100       <para>
2101         The fourth and fifth arguments are the number of substreams
2102       for playback and capture, respectively. Here both 1 are given in
2103       the above example.  When no playback or no capture is available,
2104       pass 0 to the corresponding argument.
2105       </para>
2106
2107       <para>
2108         If a chip supports multiple playbacks or captures, you can
2109       specify more numbers, but they must be handled properly in
2110       open/close, etc. callbacks.  When you need to know which
2111       substream you are referring to, then it can be obtained from
2112       <type>snd_pcm_substream_t</type> data passed to each callback
2113       as follows: 
2114
2115         <informalexample>
2116           <programlisting>
2117 <![CDATA[
2118   snd_pcm_substream_t *substream;
2119   int index = substream->number;
2120 ]]>
2121           </programlisting>
2122         </informalexample>
2123       </para>
2124
2125       <para>
2126         After the pcm is created, you need to set operators for each
2127         pcm stream. 
2128
2129         <informalexample>
2130           <programlisting>
2131 <![CDATA[
2132   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2133                   &snd_mychip_playback_ops);
2134   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2135                   &snd_mychip_capture_ops);
2136 ]]>
2137           </programlisting>
2138         </informalexample>
2139       </para>
2140
2141       <para>
2142         The operators are defined typically like this:
2143
2144         <informalexample>
2145           <programlisting>
2146 <![CDATA[
2147   static snd_pcm_ops_t snd_mychip_playback_ops = {
2148           .open =        snd_mychip_pcm_open,
2149           .close =       snd_mychip_pcm_close,
2150           .ioctl =       snd_pcm_lib_ioctl,
2151           .hw_params =   snd_mychip_pcm_hw_params,
2152           .hw_free =     snd_mychip_pcm_hw_free,
2153           .prepare =     snd_mychip_pcm_prepare,
2154           .trigger =     snd_mychip_pcm_trigger,
2155           .pointer =     snd_mychip_pcm_pointer,
2156   };
2157 ]]>
2158           </programlisting>
2159         </informalexample>
2160
2161         Each of callbacks is explained in the subsection 
2162         <link linkend="pcm-interface-operators"><citetitle>
2163         Operators</citetitle></link>.
2164       </para>
2165
2166       <para>
2167         After setting the operators, most likely you'd like to
2168         pre-allocate the buffer. For the pre-allocation, simply call
2169         the following: 
2170
2171         <informalexample>
2172           <programlisting>
2173 <![CDATA[
2174   snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2175                                         snd_dma_pci_data(chip->pci),
2176                                         64*1024, 64*1024);
2177 ]]>
2178           </programlisting>
2179         </informalexample>
2180
2181         It will allocate up to 64kB buffer as default. The details of
2182       buffer management will be described in the later section <link
2183       linkend="buffer-and-memory"><citetitle>Buffer and Memory
2184       Management</citetitle></link>. 
2185       </para>
2186
2187       <para>
2188         Additionally, you can set some extra information for this pcm
2189         in pcm-&gt;info_flags.
2190         The available values are defined as
2191         <constant>SNDRV_PCM_INFO_XXX</constant> in
2192         <filename>&lt;sound/asound.h&gt;</filename>, which is used for
2193         the hardware definition (described later). When your soundchip
2194         supports only half-duplex, specify like this: 
2195
2196         <informalexample>
2197           <programlisting>
2198 <![CDATA[
2199   pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2200 ]]>
2201           </programlisting>
2202         </informalexample>
2203       </para>
2204     </section>
2205
2206     <section id="pcm-interface-destructor">
2207       <title>... And the Destructor?</title>
2208       <para>
2209         The destructor for a pcm instance is not always
2210       necessary. Since the pcm device will be released by the middle
2211       layer code automatically, you don't have to call destructor
2212       explicitly.
2213       </para>
2214
2215       <para>
2216         The destructor would be necessary when you created some
2217         special records internally and need to release them. In such a
2218         case, set the destructor function to
2219         pcm-&gt;private_free: 
2220
2221         <example>
2222           <title>PCM Instance with a Destructor</title>
2223           <programlisting>
2224 <![CDATA[
2225   static void mychip_pcm_free(snd_pcm_t *pcm)
2226   {
2227           mychip_t *chip = snd_magic_cast(mychip_t,
2228                                     pcm->private_data, return);
2229           // free your own data
2230           kfree(chip->my_private_pcm_data);
2231           // do what you like else...
2232   }
2233
2234   static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2235   {
2236           snd_pcm_t *pcm;
2237           ....
2238           // allocate your own data
2239           chip->my_private_pcm_data = kmalloc(...);
2240           // set the destructor
2241           pcm->private_data = chip;
2242           pcm->private_free = mychip_pcm_free;
2243           ....
2244   }
2245 ]]>
2246           </programlisting>
2247         </example>
2248       </para>
2249     </section>
2250
2251     <section id="pcm-interface-runtime">
2252       <title>Runtime Pointer - The Chest of PCM Information</title>
2253         <para>
2254           When the PCM substream is opened, a PCM runtime instance is
2255         allocated and assigned to the substream. This pointer is
2256         accessible via <constant>substream-&gt;runtime</constant>.
2257         This runtime pointer holds the various information; it holds
2258         the copy of hw_params and sw_params configurations, the buffer
2259         pointers, mmap records, spinlocks, etc.  Almost everyhing you
2260         need for controlling the PCM can be found there.
2261         </para>
2262
2263         <para>
2264         The definition of runtime instance is found in
2265         <filename>&lt;sound/pcm.h&gt;</filename>.  Here is the
2266         copy from the file.
2267           <informalexample>
2268             <programlisting>
2269 <![CDATA[
2270 struct _snd_pcm_runtime {
2271         /* -- Status -- */
2272         snd_pcm_substream_t *trigger_master;
2273         snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2274         int overrange;
2275         snd_pcm_uframes_t avail_max;
2276         snd_pcm_uframes_t hw_ptr_base;  /* Position at buffer restart */
2277         snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2278
2279         /* -- HW params -- */
2280         snd_pcm_access_t access;        /* access mode */
2281         snd_pcm_format_t format;        /* SNDRV_PCM_FORMAT_* */
2282         snd_pcm_subformat_t subformat;  /* subformat */
2283         unsigned int rate;              /* rate in Hz */
2284         unsigned int channels;          /* channels */
2285         snd_pcm_uframes_t period_size;  /* period size */
2286         unsigned int periods;           /* periods */
2287         snd_pcm_uframes_t buffer_size;  /* buffer size */
2288         unsigned int tick_time;         /* tick time */
2289         snd_pcm_uframes_t min_align;    /* Min alignment for the format */
2290         size_t byte_align;
2291         unsigned int frame_bits;
2292         unsigned int sample_bits;
2293         unsigned int info;
2294         unsigned int rate_num;
2295         unsigned int rate_den;
2296
2297         /* -- SW params -- */
2298         int tstamp_timespec;            /* use timeval (0) or timespec (1) */
2299         snd_pcm_tstamp_t tstamp_mode;   /* mmap timestamp is updated */
2300         unsigned int period_step;
2301         unsigned int sleep_min;         /* min ticks to sleep */
2302         snd_pcm_uframes_t xfer_align;   /* xfer size need to be a multiple */
2303         snd_pcm_uframes_t start_threshold;
2304         snd_pcm_uframes_t stop_threshold;
2305         snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2306                                                 noise is nearest than this */
2307         snd_pcm_uframes_t silence_size; /* Silence filling size */
2308         snd_pcm_uframes_t boundary;     /* pointers wrap point */
2309
2310         snd_pcm_uframes_t silenced_start;
2311         snd_pcm_uframes_t silenced_size;
2312
2313         snd_pcm_sync_id_t sync;         /* hardware synchronization ID */
2314
2315         /* -- mmap -- */
2316         volatile snd_pcm_mmap_status_t *status;
2317         volatile snd_pcm_mmap_control_t *control;
2318         atomic_t mmap_count;
2319
2320         /* -- locking / scheduling -- */
2321         spinlock_t lock;
2322         wait_queue_head_t sleep;
2323         struct timer_list tick_timer;
2324         struct fasync_struct *fasync;
2325
2326         /* -- private section -- */
2327         void *private_data;
2328         void (*private_free)(snd_pcm_runtime_t *runtime);
2329
2330         /* -- hardware description -- */
2331         snd_pcm_hardware_t hw;
2332         snd_pcm_hw_constraints_t hw_constraints;
2333
2334         /* -- interrupt callbacks -- */
2335         void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2336         void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2337
2338         /* -- timer -- */
2339         unsigned int timer_resolution;  /* timer resolution */
2340
2341         /* -- DMA -- */           
2342         unsigned char *dma_area;        /* DMA area */
2343         dma_addr_t dma_addr;            /* physical bus address (not accessible from main CPU) */
2344         size_t dma_bytes;               /* size of DMA area */
2345         void *dma_private;              /* private DMA data for the memory allocator */
2346
2347 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2348         /* -- OSS things -- */
2349         snd_pcm_oss_runtime_t oss;
2350 #endif
2351 };
2352 ]]>
2353             </programlisting>
2354           </informalexample>
2355         </para>
2356
2357         <para>
2358           For the operators (callbacks) of each sound driver, most of
2359         these records are supposed to be read-only.  Only the PCM
2360         middle-layer changes / updates these info.  The excpetions are
2361         the hardware description (hw), interrupt callbacks
2362         (transfer_ack_xxx), DMA buffer information, and the private
2363         data.  Besides, if you use the standard buffer allocation
2364         method via <function>snd_pcm_lib_malloc_pages()</function>,
2365         you don't need to set the DMA buffer information by yourself.
2366         </para>
2367
2368         <para>
2369         In the sections below, important records are explained.
2370         </para>
2371
2372         <section id="pcm-interface-runtime-hw">
2373         <title>Hardware Description</title>
2374         <para>
2375           The hardware descriptor (<type>snd_pcm_hardware_t</type>)
2376         contains the definitions of the fundamental hardware
2377         configuration.  Above all, you'll need to define this in
2378         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2379         the open callback</citetitle></link>.
2380         Note that the runtime instance holds the copy of the
2381         descriptor, not the pointer to the existing descriptor.  That
2382         is, in the open callback, you can modify the copied descriptor
2383         (<constant>runtime-&gt;hw</constant>) as you need.  For example, if the maximum
2384         number of channels is 1 only on some chip models, you can
2385         still use the same hardware descriptor and change the
2386         channels_max later:
2387           <informalexample>
2388             <programlisting>
2389 <![CDATA[
2390           snd_pcm_runtime_t *runtime = substream->runtime;
2391           ...
2392           runtime->hw = snd_mychip_playback_hw; // common definition
2393           if (chip->model == VERY_OLD_ONE)
2394                   runtime->hw.channels_max = 1;
2395 ]]>
2396             </programlisting>
2397           </informalexample>
2398         </para>
2399
2400         <para>
2401           Typically, you'll have a hardware descriptor like below:
2402           <informalexample>
2403             <programlisting>
2404 <![CDATA[
2405   static snd_pcm_hardware_t snd_mychip_playback_hw = {
2406           .info = (SNDRV_PCM_INFO_MMAP |
2407                    SNDRV_PCM_INFO_INTERLEAVED |
2408                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
2409                    SNDRV_PCM_INFO_MMAP_VALID),
2410           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
2411           .rates =            SNDRV_PCM_RATE_8000_48000,
2412           .rate_min =         8000,
2413           .rate_max =         48000,
2414           .channels_min =     2,
2415           .channels_max =     2,
2416           .buffer_bytes_max = 32768,
2417           .period_bytes_min = 4096,
2418           .period_bytes_max = 32768,
2419           .periods_min =      1,
2420           .periods_max =      1024,
2421   };
2422 ]]>
2423             </programlisting>
2424           </informalexample>
2425         </para>
2426
2427         <para>
2428         <itemizedlist>
2429         <listitem><para>
2430           The <structfield>info</structfield> field contains the type and
2431         capabilities of this pcm. The bit flags are defined in
2432         <filename>&lt;sound/asound.h&gt;</filename> as
2433         <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2434         have to specify whether the mmap is supported and which
2435         interleaved format is supported.
2436         When the mmap is supported, add
2437         <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2438         hardware supports the interleaved or the non-interleaved
2439         format, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2440         <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2441         be set, respectively. If both are supported, you can set both,
2442         too. 
2443         </para>
2444
2445         <para>
2446           In the above example, <constant>MMAP_VALID</constant> and
2447         <constant>BLOCK_TRANSFER</constant> are specified for OSS mmap
2448         mode. Usually both are set. Of course,
2449         <constant>MMAP_VALID</constant> is set only if the mmap is
2450         really supported. 
2451         </para>
2452
2453         <para>
2454           The other possible flags are
2455         <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2456         <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2457         <constant>PAUSE</constant> bit means that the pcm supports the
2458         <quote>pause</quote> operation, while the
2459         <constant>RESUME</constant> bit means that the pcm supports
2460         the <quote>suspend/resume</quote> operation. If these flags
2461         are set, the <structfield>trigger</structfield> callback below
2462         must handle the corresponding commands. 
2463         </para>
2464
2465         <para>
2466           When the PCM substreams can be synchronized (typically,
2467         synchorinized start/stop of a playback and a capture streams),
2468         you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2469         too.  In this case, you'll need to check the linked-list of
2470         PCM substreams in the trigger callback.  This will be
2471         described in the later section.
2472         </para>
2473         </listitem>
2474
2475         <listitem>
2476         <para>
2477           <structfield>formats</structfield> field contains the bit-flags
2478         of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2479         If the hardware supports more than one format, give all or'ed
2480         bits.  In the example above, the signed 16bit little-endian
2481         format is specified.
2482         </para>
2483         </listitem>
2484
2485         <listitem>
2486         <para>
2487         <structfield>rates</structfield> field contains the bit-flags of
2488         supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2489         When the chip supports continuous rates, pass
2490         <constant>CONTINUOUS</constant> bit additionally.
2491         The pre-defined rate bits are provided only for typical
2492         rates. If your chip supports unconventional rates, you need to add
2493         <constant>KNOT</constant> bit and set up the hardware
2494         constraint manually (explained later).
2495         </para>
2496         </listitem>
2497
2498         <listitem>
2499         <para>
2500         <structfield>rate_min</structfield> and
2501         <structfield>rate_max</structfield> define the minimal and
2502         maximal sample rate.  This should correspond somehow to
2503         <structfield>rates</structfield> bits.
2504         </para>
2505         </listitem>
2506
2507         <listitem>
2508         <para>
2509         <structfield>channel_min</structfield> and
2510         <structfield>channel_max</structfield> 
2511         define, as you might already expected, the minimal and maximal
2512         number of channels.
2513         </para>
2514         </listitem>
2515
2516         <listitem>
2517         <para>
2518         <structfield>buffer_bytes_max</structfield> defines the
2519         maximal buffer size in bytes.  There is no
2520         <structfield>buffer_bytes_min</structfield> field, since
2521         it can be calculated from the minimal period size and the
2522         minimal number of periods.
2523         Meanwhile, <structfield>period_bytes_min</structfield> and
2524         define the minimal and maximal size of the period in bytes.
2525         <structfield>periods_max</structfield> and
2526         <structfield>periods_min</structfield> define the maximal and
2527         minimal number of periods in the buffer.
2528         </para>
2529
2530         <para>
2531         The <quote>period</quote> is a term, that corresponds to
2532         fragment in the OSS world.  The period defines the size at
2533         which the PCM interrupt is generated. This size strongly
2534         depends on the hardware. 
2535         Generally, the smaller period size will give you more
2536         interrupts, that is, more controls. 
2537         In the case of capture, this size defines the input latency.
2538         On the other hand, the whole buffer size defines the
2539         output latency for the playback direction.
2540         </para>
2541         </listitem>
2542
2543         <listitem>
2544         <para>
2545         There is also a field <structfield>fifo_size</structfield>.
2546         This specifies the size of the hardware FIFO, but it's not
2547         used currently in the driver nor in the alsa-lib.  So, you
2548         can ignore this field.
2549         </para>
2550         </listitem>
2551         </itemizedlist>
2552         </para>
2553         </section>
2554
2555         <section id="pcm-interface-runtime-config">
2556         <title>PCM Configurations</title>
2557         <para>
2558         Ok, let's go back again to the PCM runtime records.
2559         The most frequently referred records in the runtime instance are
2560         the PCM configurations.
2561         The PCM configurations are stored on runtime instance
2562         after the application sends <type>hw_params</type> data via
2563         alsa-lib.  There are many fields copied from hw_params and
2564         sw_params structs.  For example,
2565         <structfield>format</structfield> holds the format type
2566         chosen by the application.  This field contains the enum value
2567         <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2568         </para>
2569
2570         <para>
2571         One thing to be noted is that the configured buffer and period
2572         sizes are stored in <quote>frames</quote> in the runtime
2573         In the ALSA world, 1 frame = channels * samples-size.
2574         For conversion between frames and bytes, you can use the
2575         helper functions, <function>frames_to_bytes()</function> and
2576           <function>bytes_to_frames()</function>. 
2577           <informalexample>
2578             <programlisting>
2579 <![CDATA[
2580   period_bytes = frames_to_bytes(runtime, runtime->period_size);
2581 ]]>
2582             </programlisting>
2583           </informalexample>
2584         </para>
2585
2586         <para>
2587         Also, many software parameters (sw_params) are
2588         stored in frames, too.  Please check the type of the field.
2589         <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2590         integer while <type>snd_pcm_sframes_t</type> is for the frames
2591         as signed integer.
2592         </para>
2593         </section>
2594
2595         <section id="pcm-interface-runtime-dma">
2596         <title>DMA Buffer Information</title>
2597         <para>
2598         The DMA buffer is defined by the following four fields,
2599         <structfield>dma_area</structfield>,
2600         <structfield>dma_addr</structfield>,
2601         <structfield>dma_bytes</structfield> and
2602         <structfield>dma_private</structfield>.
2603         The <structfield>dma_area</structfield> holds the buffer
2604         pointer (the logical address).  You can call
2605         <function>memcpy</function> from/to 
2606         this pointer.  Meanwhile, <structfield>dma_addr</structfield>
2607         holds the physical address of the buffer.  This field is
2608         specified only when the buffer is a linear buffer.
2609         <structfield>dma_bytes</structfield> holds the size of buffer
2610         in bytes.  <structfield>dma_private</structfield> is used for
2611         the ALSA DMA allocator.
2612         </para>
2613
2614         <para>
2615         If you use a standard ALSA function,
2616         <function>snd_pcm_lib_malloc_pages()</function>, for
2617         allocating the buffer, these fields are set by the ALSA middle
2618         layer, and you should <emphasis>not</emphasis> change them by
2619         yourself.  You can read them but not write them.
2620         On the other hand, if you want to allocate the buffer by
2621         yourself, you'll need to manage it in hw_params callback.
2622         At least, <structfield>dma_bytes</structfield> is mandatory.
2623         <structfield>dma_area</structfield> is necessary when the
2624         buffer is mmapped.  If your driver doesn't support mmap, this
2625         field is not necessary.  <structfield>dma_addr</structfield>
2626         is also not mandatory.  You can use
2627         <structfield>dma_private</structfield> as you like, too.
2628         </para>
2629         </section>
2630
2631         <section id="pcm-interface-runtime-status">
2632         <title>Running Status</title>
2633         <para>
2634         The running status can be referred via <constant>runtime-&gt;status</constant>.
2635         This is the pointer to <type>snd_pcm_mmap_status_t</type>
2636         record.  For example, you can get the current DMA hardware
2637         pointer via <constant>runtime-&gt;status-&gt;hw_ptr</constant>.
2638         </para>
2639
2640         <para>
2641         The DMA application pointer can be referred via
2642         <constant>runtime-&gt;control</constant>, which points
2643         <type>snd_pcm_mmap_control_t</type> record.
2644         However, accessing directly to this value is not recommended.
2645         </para>
2646         </section>
2647
2648         <section id="pcm-interface-runtime-private">
2649         <title>Private Data</title> 
2650         <para>
2651         You can allocate a record for the substream and store it in
2652         <constant>runtime-&gt;private_data</constant>.  Usually, this
2653         done in
2654         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2655         the open callback</citetitle></link>.
2656         Since it's a void pointer, you should use magic-kmalloc and
2657         magic-cast for such an object. 
2658
2659           <informalexample>
2660             <programlisting>
2661 <![CDATA[
2662   static int snd_xxx_open(snd_pcm_substream_t *substream)
2663   {
2664           my_pcm_data_t *data;
2665           ....
2666           data = snd_magic_kmalloc(my_pcm_data_t, 0, GFP_KERNEL);
2667           substream->runtime->private_data = data;
2668           ....
2669   }
2670 ]]>
2671             </programlisting>
2672           </informalexample>
2673         </para>
2674
2675         <para>
2676           The allocated object must be released in
2677         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2678         the close callback</citetitle></link>.
2679         </para>
2680         </section>
2681
2682         <section id="pcm-interface-runtime-intr">
2683         <title>Interrupt Callbacks</title>
2684         <para>
2685         The field <structfield>transfer_ack_begin</structfield> and
2686         <structfield>transfer_ack_end</structfield> are called at
2687         the beginning and the end of
2688         <function>snd_pcm_period_elapsed()</function>, respectively. 
2689         </para>
2690         </section>
2691
2692     </section>
2693
2694     <section id="pcm-interface-operators">
2695       <title>Operators</title>
2696       <para>
2697         OK, now let me explain the detail of each pcm callback
2698       (<parameter>ops</parameter>). In general, every callback must
2699       return 0 if successful, or a negative number with the error
2700       number such as <constant>-EINVAL</constant> at any
2701       error. 
2702       </para>
2703
2704       <para>
2705         The callback function takes at least the argument with
2706         <type>snd_pcm_substream_t</type> pointer. For retrieving the
2707         chip record from the given substream instance, you can use the
2708         following macro. 
2709
2710         <informalexample>
2711           <programlisting>
2712 <![CDATA[
2713   #define chip_t mychip_t
2714
2715   int xxx() {
2716           mychip_t *chip = snd_pcm_substream_chip(substream);
2717           ....
2718   }
2719 ]]>
2720           </programlisting>
2721         </informalexample>
2722       </para>
2723
2724       <para>
2725         It's expanded with a magic-cast, so the cast-error is
2726       automatically checked. You should define <type>chip_t</type> at
2727       the beginning of the code, since this will be referred in many
2728       places of pcm and control interfaces. 
2729       </para>
2730
2731       <section id="pcm-interface-operators-open-callback">
2732         <title>open callback</title>
2733         <para>
2734           <informalexample>
2735             <programlisting>
2736 <![CDATA[
2737   static int snd_xxx_open(snd_pcm_substream_t *substream);
2738 ]]>
2739             </programlisting>
2740           </informalexample>
2741
2742           This is called when a pcm substream is opened.
2743         </para>
2744
2745         <para>
2746           At least, here you have to initialize the runtime-&gt;hw
2747           record. Typically, this is done by like this: 
2748
2749           <informalexample>
2750             <programlisting>
2751 <![CDATA[
2752   static int snd_xxx_open(snd_pcm_substream_t *substream)
2753   {
2754           mychip_t *chip = snd_pcm_substream_chip(substream);
2755           snd_pcm_runtime_t *runtime = substream->runtime;
2756
2757           runtime->hw = snd_mychip_playback_hw;
2758           return 0;
2759   }
2760 ]]>
2761             </programlisting>
2762           </informalexample>
2763
2764           where <parameter>snd_mychip_playback_hw</parameter> is the
2765           pre-defined hardware description.
2766         </para>
2767
2768         <para>
2769         You can allocate a private data in this callback, as described
2770         in <link linkend="pcm-interface-runtime-private"><citetitle>
2771         Private Data</citetitle></link> section.
2772         </para>
2773
2774         <para>
2775         If the hardware configuration needs more constraints, set the
2776         hardware constraints here, too.
2777         See <link linkend="pcm-interface-constraints"><citetitle>
2778         Constraints</citetitle></link> for more details.
2779         </para>
2780       </section>
2781
2782       <section id="pcm-interface-operators-close-callback">
2783         <title>close callback</title>
2784         <para>
2785           <informalexample>
2786             <programlisting>
2787 <![CDATA[
2788   static int snd_xxx_close(snd_pcm_substream_t *substream);
2789 ]]>
2790             </programlisting>
2791           </informalexample>
2792
2793           Obviously, this is called when a pcm substream is closed.
2794         </para>
2795
2796         <para>
2797           Any private instance for a pcm substream allocated in the
2798           open callback will be released here. 
2799
2800           <informalexample>
2801             <programlisting>
2802 <![CDATA[
2803   static int snd_xxx_close(snd_pcm_substream_t *substream)
2804   {
2805           ....
2806           snd_magic_kfree(substream->runtime->private_data);
2807           ....
2808   }
2809 ]]>
2810             </programlisting>
2811           </informalexample>
2812         </para>
2813       </section>
2814
2815       <section id="pcm-interface-operators-ioctl-callback">
2816         <title>ioctl callback</title>
2817         <para>
2818           This is used for any special action to pcm ioctls. But
2819         usually you can pass a generic ioctl callback, 
2820         <function>snd_pcm_lib_ioctl</function>.
2821         </para>
2822       </section>
2823
2824       <section id="pcm-interface-operators-hw-params-callback">
2825         <title>hw_params callback</title>
2826         <para>
2827           <informalexample>
2828             <programlisting>
2829 <![CDATA[
2830   static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2831                                snd_pcm_hw_params_t * hw_params);
2832 ]]>
2833             </programlisting>
2834           </informalexample>
2835
2836           This and <structfield>hw_free</structfield> callbacks exist
2837         only on ALSA 0.9.x. 
2838         </para>
2839
2840         <para>
2841           This is called when the hardware parameter
2842         (<structfield>hw_params</structfield>) is set
2843         up by the application, 
2844         that is, once when the buffer size, the period size, the
2845         format, etc. are defined for the pcm substream. 
2846         </para>
2847
2848         <para>
2849           Many hardware set-up should be done in this callback,
2850         including the allocation of buffers. 
2851         </para>
2852
2853         <para>
2854           Parameters to be initialized are retrieved by
2855           <function>params_xxx()</function> macros. For allocating a
2856           buffer, you can call a helper function, 
2857
2858           <informalexample>
2859             <programlisting>
2860 <![CDATA[
2861   snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2862 ]]>
2863             </programlisting>
2864           </informalexample>
2865
2866           <function>snd_pcm_lib_malloc_pages()</function> is available
2867           only when the DMA buffers have been pre-allocated.
2868           See the section <link
2869           linkend="buffer-and-memory-buffer-types"><citetitle>
2870           Buffer Types</citetitle></link> for more details.
2871         </para>
2872
2873         <para>
2874           Note that this and <structfield>prepare</structfield> callbacks
2875         may be called multiple times per initialization.
2876         For example, the OSS emulation may
2877         call these callbacks at each change via its ioctl. 
2878         </para>
2879
2880         <para>
2881           Thus, you need to take care not to allocate the same buffers
2882         many times, which will lead to memory leak!  Calling the
2883         helper function above many times is OK. It will release the
2884         previous buffer automatically when it was already allocated. 
2885         </para>
2886
2887         <para>
2888           Another note is that this callback is non-atomic
2889         (schedulable). This is important, because the
2890         <structfield>prepare</structfield> callback 
2891         is atomic (non-schedulable). That is, mutex or any
2892         schedule-related functions are available only in
2893         <structfield>hw_params</structfield> callback. 
2894         Please see the subsection
2895         <link linkend="pcm-interface-atomicity"><citetitle>
2896         Atomicity</citetitle></link> for details.
2897         </para>
2898       </section>
2899
2900       <section id="pcm-interface-operators-hw-free-callback">
2901         <title>hw_free callback</title>
2902         <para>
2903           <informalexample>
2904             <programlisting>
2905 <![CDATA[
2906   static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2907 ]]>
2908             </programlisting>
2909           </informalexample>
2910         </para>
2911
2912         <para>
2913           This is called to release the resources allocated via
2914           <structfield>hw_params</structfield>. For example, releasing the
2915           buffer via 
2916           <function>snd_pcm_lib_malloc_pages()</function> is done by
2917           calling the following: 
2918
2919           <informalexample>
2920             <programlisting>
2921 <![CDATA[
2922   snd_pcm_lib_free_pages(substream);
2923 ]]>
2924             </programlisting>
2925           </informalexample>
2926         </para>
2927
2928         <para>
2929           This function is always called before the close callback is called.
2930           Also, the callback may be called multiple times, too.
2931           Keep track whether the resource was already released. 
2932         </para>
2933       </section>
2934
2935       <section id="pcm-interface-operators-prepare-callback">
2936        <title>prepare callback</title>
2937         <para>
2938           <informalexample>
2939             <programlisting>
2940 <![CDATA[
2941   static int snd_xxx_prepare(snd_pcm_substream_t * substream);
2942 ]]>
2943             </programlisting>
2944           </informalexample>
2945         </para>
2946
2947         <para>
2948           This callback is called when the pcm is
2949         <quote>prepared</quote>. You can set the format type, sample
2950         rate, etc. here. The difference from
2951         <structfield>hw_params</structfield> is that the 
2952         <structfield>prepare</structfield> callback will be called at each
2953         time 
2954         <function>snd_pcm_prepare()</function> is called, i.e. when
2955         recovered after underruns, etc. 
2956         </para>
2957
2958         <para>
2959           As mentioned above, this callback is atomic.
2960         </para>
2961
2962         <para>
2963           In this and the following callbacks, you can refer to the
2964         values via the runtime record,
2965         substream-&gt;runtime.
2966         For example, to get the current
2967         rate, format or channels, access to
2968         runtime-&gt;rate,
2969         runtime-&gt;format or
2970         runtime-&gt;channels, respectively. 
2971         The physical address of the allocated buffer is set to
2972         runtime-&gt;dma_area.  The buffer and period sizes are
2973         in runtime-&gt;buffer_size and runtime-&gt;period_size,
2974         respectively.
2975         </para>
2976
2977         <para>
2978           Be careful that this callback will be called many times at
2979         each set up, too. 
2980         </para>
2981       </section>
2982
2983       <section id="pcm-interface-operators-trigger-callback">
2984         <title>trigger callback</title>
2985         <para>
2986           <informalexample>
2987             <programlisting>
2988 <![CDATA[
2989   static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
2990 ]]>
2991             </programlisting>
2992           </informalexample>
2993
2994           This is called when the pcm is started, stopped or paused.
2995         </para>
2996
2997         <para>
2998           Which action is specified in the second argument,
2999           <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
3000           <filename>&lt;sound/pcm.h&gt;</filename>. At least,
3001           <constant>START</constant> and <constant>STOP</constant>
3002           commands must be defined in this callback. 
3003
3004           <informalexample>
3005             <programlisting>
3006 <![CDATA[
3007   switch (cmd) {
3008   case SNDRV_PCM_TRIGGER_START:
3009           // do something to start the PCM engine
3010           break;
3011   case SNDRV_PCM_TRIGGER_STOP:
3012           // do something to stop the PCM engine
3013           break;
3014   default:
3015           return -EINVAL;
3016   }
3017 ]]>
3018             </programlisting>
3019           </informalexample>
3020         </para>
3021
3022         <para>
3023           When the pcm supports the pause operation (given in info
3024         field of the hardware table), <constant>PAUSE_PUSE</constant>
3025         and <constant>PAUSE_RELEASE</constant> commands must be
3026         handled here, too. The former is the command to pause the pcm,
3027         and the latter to restart the pcm again. 
3028         </para>
3029
3030         <para>
3031           When the pcm supports the suspend/resume operation
3032         (i.e. <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set),
3033         <constant>SUSPEND</constant> and <constant>RESUME</constant>
3034         commands must be handled, too.
3035         These commands are issued when the power-management status is
3036         changed.  Obviously, the <constant>SUSPEND</constant> and
3037         <constant>RESUME</constant>
3038         do suspend and resume of the pcm substream, and usually, they
3039         are identical with <constant>STOP</constant> and
3040         <constant>START</constant> commands, respectively.
3041         </para>
3042
3043         <para>
3044           This callback is also atomic.
3045         </para>
3046       </section>
3047
3048       <section id="pcm-interface-operators-pointer-callback">
3049         <title>pointer callback</title>
3050         <para>
3051           <informalexample>
3052             <programlisting>
3053 <![CDATA[
3054   static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
3055 ]]>
3056             </programlisting>
3057           </informalexample>
3058
3059           This callback is called when the PCM middle layer inquires
3060         the current hardware position on the buffer. The position must
3061         be returned in frames (which was in bytes on ALSA 0.5.x),
3062         ranged from 0 to buffer_size - 1.
3063         </para>
3064
3065         <para>
3066           This is called usually from the buffer-update routine in the
3067         pcm middle layer, which is invoked when
3068         <function>snd_pcm_period_elapsed()</function> is called in the
3069         interrupt routine. Then the pcm middle layer updates the
3070         position and calculates the available space, and wakes up the
3071         sleeping poll threads, etc. 
3072         </para>
3073
3074         <para>
3075           This callback is also atomic.
3076         </para>
3077       </section>
3078
3079       <section id="pcm-interface-operators-copy-silence">
3080         <title>copy and silence callbacks</title>
3081         <para>
3082           These callbacks are not mandatory, and can be omitted in
3083         most cases. These callbacks are used when the hardware buffer
3084         cannot be on the normal memory space. Some chips have their
3085         own buffer on the hardware which is not mappable. In such a
3086         case, you have to transfer the data manually from the memory
3087         buffer to the hardware buffer. Or, if the buffer is
3088         non-contiguous on both physical and virtual memory spaces,
3089         these callbacks must be defined, too. 
3090         </para>
3091
3092         <para>
3093           If these two callbacks are defined, copy and set-silence
3094         operations are done by them. The detailed will be described in
3095         the later section <link
3096         linkend="buffer-and-memory"><citetitle>Buffer and Memory
3097         Management</citetitle></link>. 
3098         </para>
3099       </section>
3100
3101       <section id="pcm-interface-operators-ack">
3102         <title>ack callback</title>
3103         <para>
3104           This callback is also not mandatory. This callback is called
3105         when the appl_ptr is updated in read or write operations.
3106         Some drivers like emu10k1-fx and cs46xx need to track the
3107         current appl_ptr for the internal buffer, and this callback
3108         is useful only for such a purpose.
3109         </para>
3110       </section>
3111
3112       <section id="pcm-interface-operators-page-callback">
3113         <title>page callback</title>
3114
3115         <para>
3116           This callback is also not mandatory. This callback is used
3117         mainly for the non-contiguous buffer. The mmap calls this
3118         callback to get the page address. Some examples will be
3119         explained in the later section <link
3120         linkend="buffer-and-memory"><citetitle>Buffer and Memory
3121         Management</citetitle></link>, too. 
3122         </para>
3123       </section>
3124     </section>
3125
3126     <section id="pcm-interface-interrupt-handler">
3127       <title>Interrupt Handler</title>
3128       <para>
3129         The rest of pcm stuff is the PCM interrupt handler. The
3130       role of PCM interrupt handler in the sound driver is to update
3131       the buffer position and to tell the PCM middle layer when the
3132       buffer position goes across the prescribed period size. To
3133       inform this, call <function>snd_pcm_period_elapsed()</function>
3134       function. 
3135       </para>
3136
3137       <para>
3138         There are several types of sound chips to generate the interrupts.
3139       </para>
3140
3141       <section id="pcm-interface-interrupt-handler-boundary">
3142         <title>Interrupts at the period (fragment) boundary</title>
3143         <para>
3144           This is the most frequently found type:  the hardware
3145         generates an interrupt at each period boundary.
3146         In this case, you can call
3147         <function>snd_pcm_period_elapsed()</function> at each 
3148         interrupt. 
3149         </para>
3150
3151         <para>
3152           <function>snd_pcm_period_elapsed()</function> takes the
3153         substream pointer as its argument. Thus, you need to keep the
3154         substream pointer accessible from the chip instance. For
3155         example, define substream field in the chip record to hold the
3156         current running substream pointer, and set the pointer value
3157         at open callback (and reset at close callback). 
3158         </para>
3159
3160         <para>
3161           If you aquire a spinlock in the interrupt handler, and the
3162         lock is used in other pcm callbacks, too, then you have to
3163         release the lock before calling
3164         <function>snd_pcm_period_elapsed()</function>, because
3165         <function>snd_pcm_period_elapsed()</function> calls other pcm
3166         callbacks inside. 
3167         </para>
3168
3169         <para>
3170           A typical coding would be like:
3171
3172           <example>
3173             <title>Interrupt Handler Case #1</title>
3174             <programlisting>
3175 <![CDATA[
3176   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3177                                           struct pt_regs *regs)
3178   {
3179           mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3180           spin_lock(&chip->lock);
3181           ....
3182           if (pcm_irq_invoked(chip)) {
3183                   // call updater, unlock before it
3184                   spin_unlock(&chip->lock);
3185                   snd_pcm_period_elapsed(chip->substream);
3186                   spin_lock(&chip->lock);
3187                   // acknowledge the interrupt if necessary
3188           }
3189           ....
3190           spin_unlock(&chip->lock);
3191           return IRQ_HANDLED;
3192   }
3193 ]]>
3194             </programlisting>
3195           </example>
3196         </para>
3197       </section>
3198
3199       <section id="pcm-interface-interrupt-handler-timer">
3200         <title>High-frequent timer interrupts</title>
3201         <para>
3202         This is the case when the hardware doesn't generate interrupts
3203         at the period boundary but do timer-interrupts at the fixed
3204         timer rate (e.g. es1968 or ymfpci drivers). 
3205         In this case, you need to check the current hardware
3206         position and accumulates the processed sample length at each
3207         interrupt.  When the accumulated size overcomes the period
3208         size, call 
3209         <function>snd_pcm_period_elapsed()</function> and reset the
3210         accumulator. 
3211         </para>
3212
3213         <para>
3214           A typical coding would be like the following.
3215
3216           <example>
3217             <title>Interrupt Handler Case #2</title>
3218             <programlisting>
3219 <![CDATA[
3220   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3221                                           struct pt_regs *regs)
3222   {
3223           mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3224           spin_lock(&chip->lock);
3225           ....
3226           if (pcm_irq_invoked(chip)) {
3227                   unsigned int last_ptr, size;
3228                   // get the current hardware pointer (in frames)
3229                   last_ptr = get_hw_ptr(chip);
3230                   // calculate the processed frames since the
3231                   // last update
3232                   if (last_ptr < chip->last_ptr)
3233                           size = runtime->buffer_size + last_ptr 
3234                                    - chip->last_ptr; 
3235                   else
3236                           size = last_ptr - chip->last_ptr;
3237                   // remember the last updated point
3238                   chip->last_ptr = last_ptr;
3239                   // accumulate the size
3240                   chip->size += size;
3241                   // over the period boundary?
3242                   if (chip->size >= runtime->period_size) {
3243                           // reset the accumulator
3244                           chip->size %= runtime->period_size;
3245                           // call updater
3246                           spin_unlock(&chip->lock);
3247                           snd_pcm_period_elapsed(substream);
3248                           spin_lock(&chip->lock);
3249                   }
3250                   // acknowledge the interrupt if necessary
3251           }
3252           ....
3253           spin_unlock(&chip->lock);
3254           return IRQ_HANDLED;
3255   }
3256 ]]>
3257             </programlisting>
3258           </example>
3259         </para>
3260       </section>
3261
3262       <section id="pcm-interface-interrupt-handler-both">
3263         <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3264         <para>
3265           In both cases, even if more than one period are elapsed, you
3266         don't have to call
3267         <function>snd_pcm_period_elapsed()</function> many times. Call
3268         only once. And the pcm layer will check the current hardware
3269         pointer and update to the latest status. 
3270         </para>
3271       </section>
3272     </section>
3273
3274     <section id="pcm-interface-atomicity">
3275       <title>Atomicity</title>
3276       <para>
3277       One of the most important (and thus difficult to debug) problem
3278       on the kernel programming is the race condition.
3279       On linux kernel, usually it's solved via spin-locks or
3280       semaphores.  In general, if the race condition may
3281       happen in the interrupt handler, it's handled as atomic, and you
3282       have to use spinlock for protecting the critical session.  If it
3283       never happens in the interrupt and it may take relatively long
3284       time, you should use semaphore.
3285       </para>
3286
3287       <para>
3288       As already seen, some pcm callbacks are atomic and some are
3289       not.  For example, <parameter>hw_params</parameter> callback is
3290       non-atomic, while <parameter>prepare</parameter> callback is
3291       atomic.  This means, the latter is called already in a spinlock
3292       held by the PCM middle layer. Please take this atomicity into
3293       account when you use a spinlock or a semaphore in the callbacks.
3294       </para>
3295
3296       <para>
3297       In the atomic callbacks, you cannot use functions which may call
3298       <function>schedule</function> or go to
3299       <function>sleep</function>.  The semaphore and mutex do sleep,
3300       and hence they cannot be used inside the atomic callbacks
3301       (e.g. <parameter>prepare</parameter> callback).
3302       For taking a certain delay in such a callback, please use
3303       <function>udelay()</function> or <function>mdelay()</function>.
3304       </para>
3305
3306     </section>
3307     <section id="pcm-interface-constraints">
3308       <title>Constraints</title>
3309       <para>
3310         If your chip supports unconventional sample rates, or only the
3311       limited samples, you need to set a constraint for the
3312       condition. 
3313       </para>
3314
3315       <para>
3316         For example, in order to restrict the sample rates in the some
3317         supported values, use
3318         <function>snd_pcm_hw_constraint_list()</function>.
3319         You need to call this function in the open callback.
3320
3321         <example>
3322           <title>Example of Hardware Constraints</title>
3323           <programlisting>
3324 <![CDATA[
3325   static unsigned int rates[] =
3326           {4000, 10000, 22050, 44100};
3327   static snd_pcm_hw_constraint_list_t constraints_rates = {
3328           .count = sizeof(rates) / sizeof(rates[0]),
3329           .list = rates,
3330           .mask = 0,
3331   };
3332
3333   static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3334   {
3335           int err;
3336           ....
3337           err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3338                                            SNDRV_PCM_HW_PARAM_RATE,
3339                                            &constraints_rates);
3340           if (err < 0)
3341                   return err;
3342           ....
3343   }
3344 ]]>
3345           </programlisting>
3346         </example>
3347       </para>
3348
3349       <para>
3350         There are many different constraints.
3351         Look in <filename>sound/asound.h</filename> for a complete list.
3352         You can even define your own constraint rules.
3353         For example, let's suppose my_chip can manage a substream of 1 channel
3354         if and only if the format is S16_LE, otherwise it supports any format
3355         specified in the <type>snd_pcm_hardware_t</type> stucture (or in any
3356         other constraint_list). You can build a rule like this:
3357
3358         <example>
3359           <title>Example of Hardware Constraints for Channels</title>
3360           <programlisting>
3361 <![CDATA[
3362   static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3363                                         snd_pcm_hw_rule_t *rule)
3364   {
3365           snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3366           snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3367           snd_mask_t fmt;
3368
3369           snd_mask_any(&fmt);    // Init the struct
3370           if (c->min < 2) {
3371                   fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3372                   return snd_mask_refine(f, &fmt);
3373           }
3374           return 0;
3375   }
3376 ]]>
3377           </programlisting>
3378         </example>
3379       </para>
3380  
3381       <para>
3382         Then you need to call this function to add your rule:
3383
3384        <informalexample>
3385          <programlisting>
3386 <![CDATA[
3387   snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3388                       hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3389                       -1);
3390 ]]>
3391           </programlisting>
3392         </informalexample>
3393       </para>
3394
3395       <para>
3396         The rule function is called when an application sets the number of
3397         channels. But an application can set the format before the number of
3398         channels. Thus you also need to define the inverse rule:
3399
3400        <example>
3401          <title>Example of Hardware Constraints for Channels</title>
3402          <programlisting>
3403 <![CDATA[
3404   static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3405                                         snd_pcm_hw_rule_t *rule)
3406   {
3407           snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3408           snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3409           snd_interval_t ch;
3410
3411           snd_interval_any(&ch);
3412           if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3413                   ch.min = ch.max = 1;
3414                   ch.integer = 1;
3415                   return snd_interval_refine(c, &ch);
3416           }
3417           return 0;
3418   }
3419 ]]>
3420           </programlisting>
3421         </example>
3422       </para>
3423
3424       <para>
3425       ...and in the open callback:
3426        <informalexample>
3427          <programlisting>
3428 <![CDATA[
3429   snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3430                       hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3431                       -1);
3432 ]]>
3433           </programlisting>
3434         </informalexample>
3435       </para>
3436
3437       <para>
3438         I won't explain more details here, rather I
3439         would like to say, <quote>Luke, use the source.</quote>
3440       </para>
3441     </section>
3442
3443   </chapter>
3444
3445
3446 <!-- ****************************************************** -->
3447 <!-- Control Interface  -->
3448 <!-- ****************************************************** -->
3449   <chapter id="control-interface">
3450     <title>Control Interface</title>
3451
3452     <section id="control-interface-general">
3453       <title>General</title>
3454       <para>
3455         The control interface is used widely for many switches,
3456       sliders, etc. which are accessed from the user-space. Its most
3457       important use is the mixer interface. In other words, on ALSA
3458       0.9.x, all the mixer stuff is implemented on the control kernel
3459       API (while there was an independent mixer kernel API on 0.5.x). 
3460       </para>
3461
3462       <para>
3463         ALSA has a well-defined AC97 control module. If your chip
3464       supports only the AC97 and nothing else, you can skip this
3465       section. 
3466       </para>
3467
3468       <para>
3469         The control API is defined in
3470       <filename>&lt;sound/control.h&gt;</filename>.
3471       Include this file if you add your own controls.
3472       </para>
3473     </section>
3474
3475     <section id="control-interface-definition">
3476       <title>Definition of Controls</title>
3477       <para>
3478         For creating a new control, you need to define the three
3479       callbacks: <structfield>info</structfield>,
3480       <structfield>get</structfield> and
3481       <structfield>put</structfield>. Then, define a
3482       <type>snd_kcontrol_new_t</type> record, such as: 
3483
3484         <example>
3485           <title>Definition of a Control</title>
3486           <programlisting>
3487 <![CDATA[
3488   static snd_kcontrol_new_t my_control __devinitdata = {
3489           .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3490           .name = "PCM Playback Switch",
3491           .index = 0,
3492           .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3493           .private_values = 0xffff,
3494           .info = my_control_info,
3495           .get = my_control_get,
3496           .put = my_control_put
3497   };
3498 ]]>
3499           </programlisting>
3500         </example>
3501       </para>
3502
3503       <para>
3504         Most likely the control is created via
3505       <function>snd_ctl_new1()</function>, and in such a case, you can
3506       add <parameter>__devinitdata</parameter> prefix to the
3507       definition like above. 
3508       </para>
3509
3510       <para>
3511         The <structfield>iface</structfield> field specifies the type of
3512       the control,
3513       <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3514       <constant>MIXER</constant>, <constant>PCM</constant>,
3515       <constant>CARD</constant>, etc.
3516       </para>
3517
3518       <para>
3519         The <structfield>name</structfield> is the name identifier
3520       string. On ALSA 0.9.x, the control name is very important,
3521       because its role is classified from its name. There are
3522       pre-defined standard control names. The details are described in
3523       the subsection
3524       <link linkend="control-interface-control-names"><citetitle>
3525       Control Names</citetitle></link>.
3526       </para>
3527
3528       <para>
3529         The <structfield>index</structfield> field holds the index number
3530       of this control. If there are several different controls with
3531       the same name, they can be distinguished by the index
3532       number. This is the case when 
3533       several codecs exist on the card. If the index is zero, you can
3534       omit the definition above. 
3535       </para>
3536
3537       <para>
3538         The <structfield>access</structfield> field contains the access
3539       type of this control. Give the combination of bit masks,
3540       <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.
3541       The detailed will be explained in the subsection
3542       <link linkend="control-interface-access-flags"><citetitle>
3543       Access Flags</citetitle></link>.
3544       </para>
3545
3546       <para>
3547         The <structfield>private_values</structfield> field contains
3548       an arbitrary long integer value for this record. When using
3549       generic <structfield>info</structfield>,
3550       <structfield>get</structfield> and
3551       <structfield>put</structfield> callbacks, you can pass a value 
3552       through this field. If several small numbers are necessary, you can
3553       combine them in bitwise. Or, it's possible to give a pointer
3554       (casted to unsigned long) of some record to this field, too. 
3555       </para>
3556
3557       <para>
3558         The other three are
3559         <link linkend="control-interface-callbacks"><citetitle>
3560         callback functions</citetitle></link>.
3561       </para>
3562     </section>
3563
3564     <section id="control-interface-control-names">
3565       <title>Control Names</title>
3566       <para>
3567         There are some standards for defining the control names. A
3568       control is usually defined from the three parts as
3569       <quote>SOURCE DIRECTION FUNCTION</quote>. 
3570       </para>
3571
3572       <para>
3573         The first, <constant>SOURCE</constant>, specifies the source
3574       of the control, and is a string such as <quote>Master</quote>,
3575       <quote>PCM</quote>, <quote>CD</quote> or
3576       <quote>Line</quote>. There are many pre-defined sources. 
3577       </para>
3578
3579       <para>
3580         The second, <constant>DIRECTION</constant>, is one of the
3581       following strings according to the direction of the control:
3582       <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass
3583       Playback</quote> and <quote>Bypass Capture</quote>. Or, it can
3584       be omitted, meaning both playback and capture directions. 
3585       </para>
3586
3587       <para>
3588         The third, <constant>FUNCTION</constant>, is one of the
3589       following strings according to the function of the control:
3590       <quote>Switch</quote>, <quote>Volume</quote> and
3591       <quote>Route</quote>. 
3592       </para>
3593
3594       <para>
3595         The example of control names are, thus, <quote>Master Capture
3596       Switch</quote> or <quote>PCM Playback Volume</quote>. 
3597       </para>
3598
3599       <para>
3600         There are some exceptions:
3601       </para>
3602
3603       <section id="control-interface-control-names-global">
3604         <title>Global capture and playback</title>
3605         <para>
3606           <quote>Capture Source</quote>, <quote>Capture Switch</quote>
3607         and <quote>Capture Volume</quote> are used for the global
3608         capture (input) source, switch and volume. Similarly,
3609         <quote>Playback Switch</quote> and <quote>Playback
3610         Volume</quote> are used for the global output gain switch and
3611         volume. 
3612         </para>
3613       </section>
3614
3615       <section id="control-interface-control-names-tone">
3616         <title>Tone-controls</title>
3617         <para>
3618           tone-control switch and volumes are specified like
3619         <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -
3620         Switch</quote>, <quote>Tone Control - Bass</quote>,
3621         <quote>Tone Control - Center</quote>.  
3622         </para>
3623       </section>
3624
3625       <section id="control-interface-control-names-3d">
3626         <title>3D controls</title>
3627         <para>
3628           3D-control switches and volumes are specified like <quote>3D
3629         Control - XXX</quote>, e.g. <quote>3D Control -
3630         Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D
3631         Control - Space</quote>. 
3632         </para>
3633       </section>
3634
3635       <section id="control-interface-control-names-mic">
3636         <title>Mic boost</title>
3637         <para>
3638           Mic-boost switch is set as <quote>Mic Boost</quote> or
3639         <quote>Mic Boost (6dB)</quote>. 
3640         </para>
3641
3642         <para>
3643           More precise information can be found in
3644         <filename>alsa-kernel/Documentation/sound/alsa/ControlNames.txt</filename>.
3645         </para>
3646       </section>
3647     </section>
3648
3649     <section id="control-interface-access-flags">
3650       <title>Access Flags</title>
3651
3652       <para>
3653       The access flag is the bit-flags which specifies the access type
3654       of the given control.  The default access type is
3655       <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>, 
3656       which means both read and write are allowed to this control.
3657       When the access flag is omitted (i.e. = 0), it is
3658       regarded as <constant>READWRITE</constant> access as default. 
3659       </para>
3660
3661       <para>
3662       When the control is read-only, pass
3663       <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.
3664       In this case, you don't have to define
3665       <structfield>put</structfield> callback.
3666       Similarly, when the control is write-only (although it's a rare
3667       case), you can use <constant>WRITE</constant> flag instead, and
3668       you don't need <structfield>get</structfield> callback.
3669       </para>
3670
3671       <para>
3672       If the control value changes frequently (e.g. the VU meter),
3673       <constant>VOLATILE</constant> flag should be given.  This means
3674       that the control may be changed without
3675       <link linkend="control-interface-change-notification"><citetitle>
3676       notification</citetitle></link>.  Applications should poll such
3677       a control constantly.
3678       </para>
3679
3680       <para>
3681       When the control is inactive, set
3682       <constant>INACTIVE</constant> flag, too.
3683       There are <constant>LOCK</constant> and
3684       <constant>OWNER</constant> flags for changing the write
3685       permissions.
3686       </para>
3687
3688     </section>
3689
3690     <section id="control-interface-callbacks">
3691       <title>Callbacks</title>
3692
3693       <section id="control-interface-callbacks-info">
3694         <title>info callback</title>
3695         <para>
3696           The <structfield>info</structfield> callback is used to get
3697         the detailed information of this control. This must store the
3698         values of the given <type>snd_ctl_elem_info_t</type>
3699         object. For example, for a boolean control with a single
3700         element will be: 
3701
3702           <example>
3703             <title>Example of info callback</title>
3704             <programlisting>
3705 <![CDATA[
3706   static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3707                           snd_ctl_elem_info_t *uinfo)
3708   {
3709           uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3710           uinfo->count = 1;
3711           uinfo->value.integer.min = 0;
3712           uinfo->value.integer.max = 1;
3713           return 0;
3714   }
3715 ]]>
3716             </programlisting>
3717           </example>
3718         </para>
3719
3720         <para>
3721           The <structfield>type</structfield> field specifies the type
3722         of the control. There are <constant>BOOLEAN</constant>,
3723         <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,
3724         <constant>BYTES</constant>, <constant>IEC958</constant> and
3725         <constant>INTEGER64</constant>. The
3726         <structfield>count</structfield> field specifies the 
3727         number of elements in this control. For example, a stereo
3728         volume would have count = 2. The
3729         <structfield>value</structfield> field is a union, and 
3730         the values stored are depending on the type. The boolean and
3731         integer are identical. 
3732         </para>
3733
3734         <para>
3735           The enumerated type is a bit different from others.  You'll
3736           need to set the string for the currently given item index. 
3737
3738           <informalexample>
3739             <programlisting>
3740 <![CDATA[
3741   static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3742                           snd_ctl_elem_info_t *uinfo)
3743   {
3744           static char *texts[4] = {
3745                   "First", "Second", "Third", "Fourth"
3746           };
3747           uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3748           uinfo->count = 1;
3749           uinfo->value.enumerated.items = 4;
3750           if (uinfo->value.enumerated.item > 3)
3751                   uinfo->value.enumerated.item = 3;
3752           strcpy(uinfo->value.enumerated.name,
3753                  texts[uinfo->value.enumerated.item]);
3754           return 0;
3755   }
3756 ]]>
3757             </programlisting>
3758           </informalexample>
3759         </para>
3760       </section>
3761
3762       <section id="control-interface-callbacks-get">
3763         <title>get callback</title>
3764
3765         <para>
3766           This callback is used to read the current value of the
3767         control and to return to the user-space. 
3768         </para>
3769
3770         <para>
3771           For example,
3772
3773           <example>
3774             <title>Example of get callback</title>
3775             <programlisting>
3776 <![CDATA[
3777   static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3778                            snd_ctl_elem_value_t *ucontrol)
3779   {
3780           mychip_t *chip = snd_kcontrol_chip(kcontrol);
3781           ucontrol->value.integer.value[0] = get_some_value(chip);
3782           return 0;
3783   }
3784 ]]>
3785             </programlisting>
3786           </example>
3787         </para>
3788
3789         <para>
3790           Here, the chip instance is retrieved via
3791         <function>snd_kcontrol_chip()</function> macro.  This macro
3792         converts from kcontrol-&gt;private_data to the type defined by
3793         <type>chip_t</type>. The
3794         kcontrol-&gt;private_data field is 
3795         given as the argument of <function>snd_ctl_new()</function>
3796         (see the later subsection
3797         <link linkend="control-interface-constructor"><citetitle>Constructor</citetitle></link>).
3798         </para>
3799
3800         <para>
3801         The <structfield>value</structfield> field is depending on
3802         the type of control as well as on info callback.  For example,
3803         the sb driver uses this field to store the register offset,
3804         the bit-shift and the bit-mask.  The
3805         <structfield>private_value</structfield> is set like
3806           <informalexample>
3807             <programlisting>
3808 <![CDATA[
3809   .private_value = reg | (shift << 16) | (mask << 24)
3810 ]]>
3811             </programlisting>
3812           </informalexample>
3813         and is retrieved in callbacks like
3814           <informalexample>
3815             <programlisting>
3816 <![CDATA[
3817   static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3818                                     snd_ctl_elem_value_t *ucontrol)
3819   {
3820           int reg = kcontrol->private_value & 0xff;
3821           int shift = (kcontrol->private_value >> 16) & 0xff;
3822           int mask = (kcontrol->private_value >> 24) & 0xff;
3823           ....
3824   }
3825 ]]>
3826             </programlisting>
3827           </informalexample>
3828         </para>
3829
3830         <para>
3831         In <structfield>get</structfield> callback, you have to fill all the elements if the
3832         control has more than one elements,
3833         i.e. <structfield>count</structfield> &gt; 1.
3834         In the example above, we filled only one element
3835         (<structfield>value.integer.value[0]</structfield>) since it's
3836         assumed as <structfield>count</structfield> = 1.
3837         </para>
3838       </section>
3839
3840       <section id="control-interface-callbacks-put">
3841         <title>put callback</title>
3842
3843         <para>
3844           This callback is used to write a value from the user-space.
3845         </para>
3846
3847         <para>
3848           For example,
3849
3850           <example>
3851             <title>Example of put callback</title>
3852             <programlisting>
3853 <![CDATA[
3854   static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3855                            snd_ctl_elem_value_t *ucontrol)
3856   {
3857           mychip_t *chip = snd_kcontrol_chip(kcontrol);
3858           int changed = 0;
3859           if (chip->current_value !=
3860                ucontrol->value.integer.value[0]) {
3861                   change_current_value(chip,
3862                               ucontrol->value.integer.value[0]);
3863                   changed = 1;
3864           }
3865           return changed;
3866   }
3867 ]]>
3868             </programlisting>
3869           </example>
3870
3871           As seen above, you have to return 1 if the value is
3872         changed. If the value is not changed, return 0 instead. 
3873         If any fatal error happens, return a negative error code as
3874         usual.
3875         </para>
3876
3877         <para>
3878         Like <structfield>get</structfield> callback,
3879         when the control has more than one elements,
3880         all elemehts must be evaluated in this callback, too.
3881         </para>
3882       </section>
3883
3884       <section id="control-interface-callbacks-all">
3885         <title>Callbacks are not atomic</title>
3886         <para>
3887           All these three callbacks are basically not atomic.
3888         </para>
3889       </section>
3890     </section>
3891
3892     <section id="control-interface-constructor">
3893       <title>Constructor</title>
3894       <para>
3895         When everything is ready, finally we can create a new
3896       control. For creating a control, there are two functions to be
3897       called, <function>snd_ctl_new1()</function> and
3898       <function>snd_ctl_add()</function>. 
3899       </para>
3900
3901       <para>
3902         In the simplest way, you can do like this:
3903
3904         <informalexample>
3905           <programlisting>
3906 <![CDATA[
3907   if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
3908           return err;
3909 ]]>
3910           </programlisting>
3911         </informalexample>
3912
3913         where <parameter>my_control</parameter> is the
3914       <type>snd_kcontrol_new_t</type> object defined above, and chip
3915       is the object pointer to be passed to
3916       kcontrol-&gt;private_data 
3917       which can be referred in callbacks. 
3918       </para>
3919
3920       <para>
3921         <function>snd_ctl_new1()</function> allocates a new
3922       <type>snd_kcontrol_t</type> instance (that's why the definition
3923       of <parameter>my_control</parameter> can be with
3924       <parameter>__devinitdata</parameter> 
3925       prefix), and <function>snd_ctl_add</function> assigns the given
3926       control component to the card. 
3927       </para>
3928     </section>
3929
3930     <section id="control-interface-change-notification">
3931       <title>Change Notification</title>
3932       <para>
3933         If you need to change and update a control in the interrupt
3934       routine, you can call <function>snd_ctl_notify()</function>. For
3935       example, 
3936
3937         <informalexample>
3938           <programlisting>
3939 <![CDATA[
3940   snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
3941 ]]>
3942           </programlisting>
3943         </informalexample>
3944
3945         This function takes the card pointer, the event-mask, and the
3946       control id pointer for the notification. The event-mask
3947       specifies the types of notification, for example, in the above
3948       example, the change of control values is notified.
3949       The id pointer is the pointer of <type>snd_ctl_elem_id_t</type>
3950       to be notified.
3951       You can find some examples in <filename>es1938.c</filename> or
3952       <filename>es1968.c</filename> for hardware volume interrupts. 
3953       </para>
3954     </section>
3955
3956   </chapter>
3957
3958
3959 <!-- ****************************************************** -->
3960 <!-- API for AC97 Codec  -->
3961 <!-- ****************************************************** -->
3962   <chapter id="api-ac97">
3963     <title>API for AC97 Codec</title>
3964
3965     <section>
3966       <title>General</title>
3967       <para>
3968         The ALSA AC97 codec layer is a well-defined one, and you don't
3969       have to write many codes to control it. Only low-level control
3970       routines are necessary. The AC97 codec API is defined in
3971       <filename>&lt;sound/ac97_codec.h&gt;</filename>. 
3972       </para>
3973     </section>
3974
3975     <section id="api-ac97-example">
3976       <title>Full Code Example</title>
3977       <para>
3978           <example>
3979             <title>Example of AC97 Interface</title>
3980             <programlisting>
3981 <![CDATA[
3982   struct snd_mychip {
3983           ....
3984           ac97_t *ac97;
3985           ....
3986   };
3987
3988   static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3989                                              unsigned short reg)
3990   {
3991           mychip_t *chip = snd_magic_cast(mychip_t,
3992                                    ac97->private_data, return 0);
3993           ....
3994           // read a register value here from the codec
3995           return the_register_value;
3996   }
3997
3998   static void snd_mychip_ac97_write(ac97_t *ac97,
3999                                    unsigned short reg, unsigned short val)
4000   {
4001           mychip_t *chip = snd_magic_cast(mychip_t,
4002                                    ac97->private_data, return 0);
4003           ....
4004           // write the given register value to the codec
4005   }
4006
4007   static int snd_mychip_ac97(mychip_t *chip)
4008   {
4009           ac97_bus_t bus, *pbus;
4010           ac97_t ac97;
4011           int err;
4012
4013           memset(&bus, 0, sizeof(bus));
4014           bus.write = snd_mychip_ac97_write;
4015           bus.read = snd_mychip_ac97_read;
4016           if ((err = snd_ac97_bus(chip->card, &bus, &pbus)) < 0)
4017                   return err;
4018           memset(&ac97, 0, sizeof(ac97));
4019           ac97.private_data = chip;
4020           return snd_ac97_mixer(pbus, &ac97, &chip->ac97);
4021   }
4022
4023 ]]>
4024           </programlisting>
4025         </example>
4026       </para>
4027     </section>
4028
4029     <section id="api-ac97-constructor">
4030       <title>Constructor</title>
4031       <para>
4032         For creating an ac97 instance, first call <function>snd_ac97_bus</function>
4033       with <type>ac97_bus_t</type> record including callback functions.
4034
4035         <informalexample>
4036           <programlisting>
4037 <![CDATA[
4038   ac97_bus_t bus, *pbus;
4039   int err;
4040
4041   memset(&bus, 0, sizeof(bus));
4042   bus.write = snd_mychip_ac97_write;
4043   bus.read = snd_mychip_ac97_read;
4044   snd_ac97_bus(card, &bus, &pbus);
4045 ]]>
4046           </programlisting>
4047         </informalexample>
4048
4049       The bus record is shared among all belonging ac97 instances.
4050       </para>
4051
4052       <para>
4053       And then call <function>snd_ac97_mixer()</function> with an <type>ac97_t</type>
4054       record together with the bus pointer created above.
4055
4056         <informalexample>
4057           <programlisting>
4058 <![CDATA[
4059   ac97_t ac97;
4060   int err;
4061
4062   memset(&ac97, 0, sizeof(ac97));
4063   ac97.private_data = chip;
4064   snd_ac97_mixer(bus, &ac97, &chip->ac97);
4065 ]]>
4066           </programlisting>
4067         </informalexample>
4068
4069         where chip-&gt;ac97 is the pointer of a newly created
4070         <type>ac97_t</type> instance.
4071         In this case, the chip pointer is set as the private data, so that
4072         the read/write callback functions can refer to this chip instance.
4073         This instance is not necessarily stored in the chip
4074         record.  When you need to change the register values from the
4075         driver, or need the suspend/resume of ac97 codecs, keep this
4076         pointer to pass to the corresponding functions.
4077       </para>
4078     </section>
4079
4080     <section id="api-ac97-callbacks">
4081       <title>Callbacks</title>
4082       <para>
4083         The standard callbacks are <structfield>read</structfield> and
4084       <structfield>write</structfield>. Obviously they 
4085       correspond to the functions for read and write accesses to the
4086       hardware low-level codes. 
4087       </para>
4088
4089       <para>
4090         The <structfield>read</structfield> callback returns the
4091         register value specified in the argument. 
4092
4093         <informalexample>
4094           <programlisting>
4095 <![CDATA[
4096   static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4097                                              unsigned short reg)
4098   {
4099           mychip_t *chip = snd_magic_cast(mychip_t,
4100                                    ac97->private_data, return 0);
4101           ....
4102           return the_register_value;
4103   }
4104 ]]>
4105           </programlisting>
4106         </informalexample>
4107
4108         Here, the chip can be cast from ac97-&gt;private_data.
4109       </para>
4110
4111       <para>
4112         Meanwhile, the <structfield>write</structfield> callback is
4113         used to set the register value. 
4114
4115         <informalexample>
4116           <programlisting>
4117 <![CDATA[
4118   static void snd_mychip_ac97_write(ac97_t *ac97,
4119                        unsigned short reg, unsigned short val)
4120 ]]>
4121           </programlisting>
4122         </informalexample>
4123       </para>
4124
4125       <para>
4126       These callbacks are non-atomic like the callbacks of control API.
4127       </para>
4128
4129       <para>
4130         There are also other callbacks:
4131       <structfield>reset</structfield>,
4132       <structfield>wait</structfield> and
4133       <structfield>init</structfield>. 
4134       </para>
4135
4136       <para>
4137         The <structfield>reset</structfield> callback is used to reset
4138       the codec. If the chip requires a special way of reset, you can
4139       define this callback. 
4140       </para>
4141
4142       <para>
4143         The <structfield>wait</structfield> callback is used for a
4144       certain wait at the standard initialization of the codec. If the
4145       chip requires the extra wait-time, define this callback. 
4146       </para>
4147
4148       <para>
4149         The <structfield>init</structfield> callback is used for
4150       additional initialization of the codec.
4151       </para>
4152     </section>
4153
4154     <section id="api-ac97-updating-registers">
4155       <title>Updating Registers in The Driver</title>
4156       <para>
4157         If you need to access to the codec from the driver, you can
4158       call the following functions:
4159       <function>snd_ac97_write()</function>,
4160       <function>snd_ac97_read()</function>,
4161       <function>snd_ac97_update()</function> and
4162       <function>snd_ac97_update_bits()</function>. 
4163       </para>
4164
4165       <para>
4166         Both <function>snd_ac97_write()</function> and
4167         <function>snd_ac97_update()</function> functions are used to
4168         set a value to the given register
4169         (<constant>AC97_XXX</constant>). The different between them is
4170         that <function>snd_ac97_update()</function> doesn't write a
4171         value if the given value has been already set, while
4172         <function>snd_ac97_write()</function> always rewrites the
4173         value. 
4174
4175         <informalexample>
4176           <programlisting>
4177 <![CDATA[
4178   snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4179   snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4180 ]]>
4181           </programlisting>
4182         </informalexample>
4183       </para>
4184
4185       <para>
4186         <function>snd_ac97_read()</function> is used to read the value
4187         of the given register. For example, 
4188
4189         <informalexample>
4190           <programlisting>
4191 <![CDATA[
4192   value = snd_ac97_read(ac97, AC97_MASTER);
4193 ]]>
4194           </programlisting>
4195         </informalexample>
4196       </para>
4197
4198       <para>
4199         <function>snd_ac97_update_bits()</function> is used to update
4200         some bits of the given register.  
4201
4202         <informalexample>
4203           <programlisting>
4204 <![CDATA[
4205   snd_ac97_update_bits(ac97, reg, mask, value);
4206 ]]>
4207           </programlisting>
4208         </informalexample>
4209       </para>
4210
4211       <para>
4212         Also, there is a function to change the sample rate (of a
4213         certain register such as
4214         <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA is
4215         supported by the codec:
4216         <function>snd_ac97_set_rate()</function>. 
4217
4218         <informalexample>
4219           <programlisting>
4220 <![CDATA[
4221   snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
4222 ]]>
4223           </programlisting>
4224         </informalexample>
4225       </para>
4226
4227       <para>
4228         The following registers are available for setting the rate:
4229       <constant>AC97_PCM_MIC_ADC_RATE</constant>,
4230       <constant>AC97_PCM_FRONT_DAC_RATE</constant>,
4231       <constant>AC97_PCM_LR_ADC_RATE</constant>,
4232       <constant>AC97_SPDIF</constant>. When the
4233       <constant>AC97_SPDIF</constant> is specified, the register is
4234       not really changed but the corresponding IEC958 status bits will
4235       be updated. 
4236       </para>
4237     </section>
4238
4239     <section id="api-ac97-clock-adjustment">
4240       <title>Clock Adjustment</title>
4241       <para>
4242         On some chip, the clock of the codec isn't 48000 but using a
4243       PCI clock (to save a quartz!). In this case, change the field
4244       ac97-&gt;clock to the corresponding
4245       value. For example, intel8x0 
4246       and es1968 drivers have the auto-measurement function of the
4247       clock. 
4248       </para>
4249     </section>
4250
4251     <section id="api-ac97-proc-files">
4252       <title>Proc Files</title>
4253       <para>
4254         The ALSA AC97 interface will create a proc file such as
4255       <filename>/proc/asound/card0/ac97#0</filename> and
4256       <filename>ac97#0regs</filename>. You can refer to these files to
4257       see the current status and registers of the codec. 
4258       </para>
4259     </section>
4260
4261     <section id="api-ac97-multiple-codecs">
4262       <title>Multiple Codecs</title>
4263       <para>
4264         When there are several codecs on the same card, you need to
4265       call <function>snd_ac97_new()</function> multiple times with
4266       ac97.num=1 or greater. The <structfield>num</structfield> field
4267       specifies the codec 
4268       number. 
4269       </para>
4270
4271       <para>
4272         If you have set up multiple codecs, you need to either write
4273       different callbacks for each codec or check
4274       ac97-&gt;num in the 
4275       callback routines. 
4276       </para>
4277     </section>
4278
4279   </chapter>
4280
4281
4282 <!-- ****************************************************** -->
4283 <!-- MIDI (MPU401-UART) Interface  -->
4284 <!-- ****************************************************** -->
4285   <chapter id="midi-interface">
4286     <title>MIDI (MPU401-UART) Interface</title>
4287
4288     <section id="midi-interface-general">
4289       <title>General</title>
4290       <para>
4291         Many soundcards have built-in MIDI (MPU401-UART)
4292       interfaces. When the soundcard supports the standard MPU401-UART
4293       interface, most likely you can use the ALSA MPU401-UART API. The
4294       MPU401-UART API is defined in
4295       <filename>&lt;sound/mpu401.h&gt;</filename>. 
4296       </para>
4297
4298       <para>
4299         Some soundchips have similar but a little bit different
4300       implementation of mpu401 stuff. For example, emu10k1 has its own
4301       mpu401 routines. 
4302       </para>
4303
4304       <para>
4305         In this document, I won't explain the rawmidi interface API,
4306       which is the basis of MPU401-UART implementation. 
4307       </para>
4308
4309       <para>
4310         For details, please check the source,
4311       <filename>core/rawmidi.c</filename>, and examples such as
4312       <filename>drivers/mpu401/mpu401_uart.c</filename> or
4313       <filename>usb/usbmidi.c</filename>. 
4314       </para>
4315     </section>
4316
4317     <section id="midi-interface-constructor">
4318       <title>Constructor</title>
4319       <para>
4320         For creating a rawmidi object, call
4321       <function>snd_mpu401_uart_new()</function>. 
4322
4323         <informalexample>
4324           <programlisting>
4325 <![CDATA[
4326   snd_rawmidi_t *rmidi;
4327   snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4328                       irq, irq_flags, &rmidi);
4329 ]]>
4330           </programlisting>
4331         </informalexample>
4332       </para>
4333
4334       <para>
4335         The first argument is the card pointer, and the second is the
4336       index of this component. You can create up to 8 rawmidi
4337       devices. 
4338       </para>
4339
4340       <para>
4341         The third argument is the type of the hardware,
4342       <constant>MPU401_HW_XXX</constant>. If it's not a special one,
4343       you can use <constant>MPU401_HW_MPU401</constant>. 
4344       </para>
4345
4346       <para>
4347         The 4th argument is the i/o port address. Many
4348       backward-compatible MPU401 has an i/o port such as 0x330. Or, it
4349       might be a part of its own PCI i/o region. It depends on the
4350       chip design. 
4351       </para>
4352
4353       <para>
4354         When the i/o port address above is a part of the PCI i/o
4355       region, the MPU401 i/o port might have been already allocated
4356       (reserved) by the driver itself. In such a case, pass non-zero
4357       to the 5th argument
4358       (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4359       and 
4360       the mpu401-uart layer will allocate the i/o ports by itself. 
4361       </para>
4362
4363       <para>
4364         Usually, the port address corresponds to the command port and
4365         port + 1 corresponds to the data port. If not, you may change
4366         the <structfield>cport</structfield> field of
4367         <type>mpu401_t</type> manually 
4368         afterward. However, <type>mpu401_t</type> pointer is not
4369         returned explicitly by
4370         <function>snd_mpu401_uart_new()</function>. You need to cast
4371         rmidi-&gt;private_data to
4372         <type>mpu401_t</type> explicitly, 
4373
4374         <informalexample>
4375           <programlisting>
4376 <![CDATA[
4377   mpu401_t *mpu;
4378   mpu = snd_magic_cast(mpu401_t, rmidi->private_data, );
4379 ]]>
4380           </programlisting>
4381         </informalexample>
4382
4383         and reset the cport as you like:
4384
4385         <informalexample>
4386           <programlisting>
4387 <![CDATA[
4388   mpu->cport = my_own_control_port;
4389 ]]>
4390           </programlisting>
4391         </informalexample>
4392       </para>
4393
4394       <para>
4395         The 6th argument specifies the irq number for UART. If the irq
4396       is already allocated, pass 0 to the 7th argument
4397       (<parameter>irq_flags</parameter>). Otherwise, pass the flags
4398       for irq allocation 
4399       (<constant>SA_XXX</constant> bits) to it, and the irq will be
4400       reserved by the mpu401-uart layer. If the card doesn't generates
4401       UART interrupts, pass -1 as the irq number. Then a timer
4402       interrupt will be invoked for polling. 
4403       </para>
4404     </section>
4405
4406     <section id="midi-interface-interrupt-handler">
4407       <title>Interrupt Handler</title>
4408       <para>
4409         When the interrupt is allocated in
4410       <function>snd_mpu401_uart_new()</function>, the private
4411       interrupt handler is used, hence you don't have to do nothing
4412       else than creating the mpu401 stuff. Otherwise, you have to call
4413       <function>snd_mpu401_uart_interrupt()</function> explicitly when
4414       a UART interrupt is invoked and checked in your own interrupt
4415       handler.  
4416       </para>
4417
4418       <para>
4419         In this case, you need to pass the private_data of the
4420         returned rawmidi object from
4421         <function>snd_mpu401_uart_new()</function> as the second
4422         argument of <function>snd_mpu401_uart_interrupt()</function>. 
4423
4424         <informalexample>
4425           <programlisting>
4426 <![CDATA[
4427   snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4428 ]]>
4429           </programlisting>
4430         </informalexample>
4431       </para>
4432     </section>
4433
4434   </chapter>
4435
4436
4437 <!-- ****************************************************** -->
4438 <!-- Miscellaneous Devices  -->
4439 <!-- ****************************************************** -->
4440   <chapter id="misc-devices">
4441     <title>Miscellaneous Devices</title>
4442
4443     <section id="misc-devices-opl3">
4444       <title>FM OPL3</title>
4445       <para>
4446         The FM OPL3 is still used on many chips (mainly for backward
4447       compatibility). ALSA has a nice OPL3 FM control layer, too. The
4448       OPL3 API is defined in
4449       <filename>&lt;sound/opl3.h&gt;</filename>. 
4450       </para>
4451
4452       <para>
4453         FM registers can be directly accessed through direct-FM API,
4454       defined in <filename>&lt;sound/asound_fm.h&gt;</filename>. In
4455       ALSA native mode, FM registers are accessed through
4456       Hardware-Dependant Device direct-FM extension API, whereas in
4457       OSS compatible mode, FM registers can be accessed with OSS
4458       direct-FM compatible API on <filename>/dev/dmfmX</filename> device. 
4459       </para>
4460
4461       <para>
4462         For creating the OPL3 component, you have two functions to
4463         call. The first one is a constructor for <type>opl3_t</type>
4464         instance. 
4465
4466         <informalexample>
4467           <programlisting>
4468 <![CDATA[
4469   opl3_t *opl3;
4470   snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
4471                   integrated, &opl3);
4472 ]]>
4473           </programlisting>
4474         </informalexample>
4475       </para>
4476
4477       <para>
4478         The first argument is the card pointer, the second one is the
4479       left port address, and the third is the right port address. In
4480       most cases, the right port is placed at the left port + 2. 
4481       </para>
4482
4483       <para>
4484         The fourth argument is the hardware type.
4485       </para>
4486
4487       <para>
4488         When the left and right ports have been already allocated by
4489       the card driver, pass non-zero to the fifth argument
4490       (<parameter>integrated</parameter>). Otherwise, opl3 module will
4491       allocate the specified ports by itself. 
4492       </para>
4493
4494       <para>
4495         If this function returns successfully with 0, then create a
4496         hwdep device for this opl3. 
4497
4498         <informalexample>
4499           <programlisting>
4500 <![CDATA[
4501   snd_hwdep_t *opl3hwdep;
4502   snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4503 ]]>
4504           </programlisting>
4505         </informalexample>
4506       </para>
4507
4508       <para>
4509         The first argument is the <type>opl3_t</type> instance you
4510       created, and the second is the index number, usually 0. 
4511       </para>
4512
4513       <para>
4514         The third argument is the index-offset for the sequencer
4515       client assigned to the OPL3 port. When there is an MPU401-UART,
4516       give 1 for here (UART always takes 0). 
4517       </para>
4518     </section>
4519
4520     <section id="misc-devices-hardware-dependent">
4521       <title>Hardware-Dependent Devices</title>
4522       <para>
4523         Some chips need the access from the user-space for special
4524       controls or for loading the micro code. In such a case, you can
4525       create a hwdep (hardware-dependent) device. The hwdep API is
4526       defined in <filename>&lt;sound/hwdep.h&gt;</filename>. You can
4527       find examples in opl3 driver or
4528       <filename>isa/sb/sb16_csp.c</filename>. 
4529       </para>
4530
4531       <para>
4532         Creation of the <type>hwdep</type> instance is done via
4533         <function>snd_hwdep_new()</function>. 
4534
4535         <informalexample>
4536           <programlisting>
4537 <![CDATA[
4538   snd_hwdep_t *hw;
4539   snd_hwdep_new(card, "My HWDEP", 0, &hw);
4540 ]]>
4541           </programlisting>
4542         </informalexample>
4543
4544         where the third argument is the index number.
4545       </para>
4546
4547       <para>
4548         You can then pass any pointer value to the
4549         <parameter>private_data</parameter>. Again, it should be a
4550         magic-allocated record, so that the cast can be checked more
4551         safely. If you assign a private data, you should define the
4552         destructor, too. The destructor function is set to
4553         <structfield>private_free</structfield> field.  
4554
4555         <informalexample>
4556           <programlisting>
4557 <![CDATA[
4558   mydata_t *p = snd_magic_kmalloc(mydata_t, 0, GFP_KERNEL);
4559   hw->private_data = p;
4560   hw->private_free = mydata_free;
4561 ]]>
4562           </programlisting>
4563         </informalexample>
4564
4565         and the implementation of destructor would be:
4566
4567         <informalexample>
4568           <programlisting>
4569 <![CDATA[
4570   static void mydata_free(snd_hwdep_t *hw)
4571   {
4572           mydata_t *p = snd_magic_cast(mydata_csp_t,
4573                                        hw->private_data, return);
4574           snd_magic_kfree(p);
4575   }
4576 ]]>
4577           </programlisting>
4578         </informalexample>
4579       </para>
4580
4581       <para>
4582         The arbitrary file operations can be defined for this
4583         instance. The file operators are defined in
4584         <parameter>ops</parameter> table. For example, assume that
4585         this chip needs an ioctl. 
4586
4587         <informalexample>
4588           <programlisting>
4589 <![CDATA[
4590   hw->ops.open = mydata_open;
4591   hw->ops.ioctl = mydata_ioctl;
4592   hw->ops.release = mydata_release;
4593 ]]>
4594           </programlisting>
4595         </informalexample>
4596
4597         And implement the callback functions as you like.
4598       </para>
4599     </section>
4600
4601     <section id="misc-devices-IEC958">
4602       <title>IEC958 (S/PDIF)</title>
4603       <para>
4604         Usually the controls for IEC958 devices are implemented via
4605       control interface. There is a macro to compose a name string for
4606       IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>
4607       defined in <filename>&lt;include/asound.h&gt;</filename>.  
4608       </para>
4609
4610       <para>
4611         There are some standard controls for IEC958 status bits. These
4612       controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,
4613       and the size of element is fixed as 4 bytes array
4614       (value.iec958.status[x]). For <structfield>info</structfield>
4615       callback, you don't specify 
4616       the value field for this type (the count field must be set,
4617       though). 
4618       </para>
4619
4620       <para>
4621         <quote>IEC958 Playback Con Mask</quote> is used to return the
4622       bit-mask for the IEC958 status bits of consumer mode. Similarly,
4623       <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for
4624       professional mode. They are read-only controls, and are defined
4625       as MIXER controls (iface =
4626       <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>).  
4627       </para>
4628
4629       <para>
4630         Meanwhile, <quote>IEC958 Playback Default</quote> control is
4631       defined for getting and setting the current default IEC958
4632       bits. Note that this one is usually defined as a PCM control
4633       (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),
4634       although in some places it's defined as a MIXER control. 
4635       </para>
4636
4637       <para>
4638         In addition, you can define the control switches to
4639       enable/disable or to set the raw bit mode. The implementation
4640       will depend on the chip, but the control should be named as
4641       <quote>IEC958 xxx</quote>, preferably using
4642       <function>SNDRV_CTL_NAME_IEC958()</function> macro. 
4643       </para>
4644
4645       <para>
4646         You can find several cases, for example,
4647       <filename>pci/emu10k1</filename>,
4648       <filename>pci/ice1712</filename>, or
4649       <filename>pci/cmipci.c</filename>.  
4650       </para>
4651     </section>
4652
4653   </chapter>
4654
4655
4656 <!-- ****************************************************** -->
4657 <!-- Buffer and Memory Management  -->
4658 <!-- ****************************************************** -->
4659   <chapter id="buffer-and-memory">
4660     <title>Buffer and Memory Management</title>
4661
4662     <section id="buffer-and-memory-buffer-types">
4663       <title>Buffer Types</title>
4664       <para>
4665         ALSA provides several different buffer allocation functions
4666       depending on the bus and the architecture. All these have a
4667       consistent API. The allocation of physically-contiguous pages is
4668       done via 
4669       <function>snd_malloc_xxx_pages()</function> function, where xxx
4670       is the bus type. 
4671       </para>
4672
4673       <para>
4674         The allocation of pages with fallback is
4675       <function>snd_malloc_xxx_pages_fallback()</function>. This
4676       function tries to allocate the specified pages but if the pages
4677       are not available, it tries to reduce the page sizes until the
4678       enough space is found.
4679       </para>
4680
4681       <para>
4682       For releasing the space, call
4683       <function>snd_free_xxx_pages()</function> function. 
4684       </para>
4685
4686       <para>
4687       Usually, ALSA drivers try to allocate and reserve
4688        a large contiguous physical space
4689        at the time the module is loaded for the later use.
4690        This is called <quote>pre-allocation</quote>.
4691        As already written, you can call the following function at the
4692        construction of pcm instance (in the case of PCI bus). 
4693
4694         <informalexample>
4695           <programlisting>
4696 <![CDATA[
4697   snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
4698                                         snd_dma_pci_data(pci), size, max);
4699 ]]>
4700           </programlisting>
4701         </informalexample>
4702
4703         where <parameter>size</parameter> is the byte size to be
4704       pre-allocated and the <parameter>max</parameter> is the maximal
4705       size to be changed via <filename>prealloc</filename> proc file.
4706       The allocator will try to get as the large area as possible
4707       within the given size. 
4708       </para>
4709
4710       <para>
4711       The second argument (type) and the third argument (device pointer)
4712       are dependent on the bus.
4713       In the case of ISA bus, pass <function>snd_dma_isa_data()</function>
4714       as the third argument with <constant>SNDRV_DMA_TYPE_DEV</constant> type.
4715       For the continuous buffer unrelated to the bus can be pre-allocated
4716       with <constant>SNDRV_DMA_TYPE_CONTINUOUS</constant> type and the
4717       <function>snd_dma_continuous_data(GFP_KERNEL)</function> device pointer,
4718       whereh <constant>GFP_KERNEL</constant> is the kernel allocation flag to
4719       use.  For the SBUS, <constant>SNDRV_DMA_TYPE_SBUS</constant> and
4720       <function>snd_dma_sbus_data(sbus_dev)</function> are used instead.
4721       For the PCI scatter-gather buffers, use
4722       <constant>SNDRV_DMA_TYPE_DEV_SG</constant> with
4723       <function>snd_dma_pci_data(pci)</function>
4724       (see the section
4725           <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers
4726           </citetitle></link>).
4727       </para>
4728
4729       <para>
4730         Once when the buffer is pre-allocated, you can use the
4731         allocator in the <structfield>hw_params</structfield> callback 
4732
4733         <informalexample>
4734           <programlisting>
4735 <![CDATA[
4736   snd_pcm_lib_malloc_pages(substream, size);
4737 ]]>
4738           </programlisting>
4739         </informalexample>
4740
4741         Note that you have to pre-allocate to use this function.
4742       </para>
4743     </section>
4744
4745     <section id="buffer-and-memory-external-hardware">
4746       <title>External Hardware Buffers</title>
4747       <para>
4748         Some chips have their own hardware buffers and the DMA
4749       transfer from the host memory is not available. In such a case,
4750       you need to either 1) copy/set the audio data directly to the
4751       external hardware buffer, or 2) make an intermediate buffer and
4752       copy/set the data from it to the external hardware buffer in
4753       interrupts (or in tasklets, preferably).
4754       </para>
4755
4756       <para>
4757         The first case works fine if the external hardware buffer is enough
4758       large.  This method doesn't need any extra buffers and thus is
4759       more effective. You need to define the
4760       <structfield>copy</structfield> and
4761       <structfield>silence</structfield> callbacks for 
4762       the data transfer. However, there is a drawback: it cannot
4763       be mmapped. The examples are GUS's GF1 PCM or emu8000's
4764       wavetable PCM. 
4765       </para>
4766
4767       <para>
4768         The second case allows the mmap of the buffer, although you have
4769       to handle an interrupt or a tasklet for transferring the data
4770       from the intermediate buffer to the hardware buffer. You can find an
4771       example in vxpocket driver. 
4772       </para>
4773
4774       <para>
4775         Another case is that the chip uses a PCI memory-map
4776       region for the buffer instead of the host memory. In this case,
4777       mmap is available only on certain architectures like intel. In
4778       non-mmap mode, the data cannot be transferred as the normal
4779       way. Thus you need to define <structfield>copy</structfield> and
4780       <structfield>silence</structfield> callbacks as well 
4781       as in the cases above. The examples are found in
4782       <filename>rme32.c</filename> and <filename>rme96.c</filename>. 
4783       </para>
4784
4785       <para>
4786         The implementation of <structfield>copy</structfield> and
4787         <structfield>silence</structfield> callbacks depends upon 
4788         whether the hardware supports interleaved or non-interleaved
4789         samples. The <structfield>copy</structfield> callback is
4790         defined like below, a bit 
4791         differently depending whether the direction is playback or
4792         capture: 
4793
4794         <informalexample>
4795           <programlisting>
4796 <![CDATA[
4797   static int playback_copy(snd_pcm_substream_t *substream, int channel,
4798                snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);
4799   static int capture_copy(snd_pcm_substream_t *substream, int channel,
4800                snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);
4801 ]]>
4802           </programlisting>
4803         </informalexample>
4804       </para>
4805
4806       <para>
4807         In the case of interleaved samples, the second argument
4808       (<parameter>channel</parameter>) is not used. The third argument
4809       (<parameter>pos</parameter>) points the 
4810       current position offset in frames. 
4811       </para>
4812
4813       <para>
4814         The meaning of the fourth argument is different between
4815       playback and capture. For playback, it holds the source data
4816       pointer, and for capture, it's the destination data pointer. 
4817       </para>
4818
4819       <para>
4820         The last argument is the number of frames to be copied.
4821       </para>
4822
4823       <para>
4824         What you have to do in this callback is again different
4825         between playback and capture directions. In the case of
4826         playback, you do: copy the given amount of data
4827         (<parameter>count</parameter>) at the specified pointer
4828         (<parameter>src</parameter>) to the specified offset
4829         (<parameter>pos</parameter>) on the hardware buffer. When
4830         coded like memcpy-like way, the copy would be like: 
4831
4832         <informalexample>
4833           <programlisting>
4834 <![CDATA[
4835   my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4836             frames_to_bytes(runtime, count));
4837 ]]>
4838           </programlisting>
4839         </informalexample>
4840       </para>
4841
4842       <para>
4843         For the capture direction, you do: copy the given amount of
4844         data (<parameter>count</parameter>) at the specified offset
4845         (<parameter>pos</parameter>) on the hardware buffer to the
4846         specified pointer (<parameter>dst</parameter>). 
4847
4848         <informalexample>
4849           <programlisting>
4850 <![CDATA[
4851   my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4852             frames_to_bytes(runtime, count));
4853 ]]>
4854           </programlisting>
4855         </informalexample>
4856
4857         Note that both of the position and the data amount are given
4858       in frames. 
4859       </para>
4860
4861       <para>
4862         In the case of non-interleaved samples, the implementation
4863       will be a bit more complicated. 
4864       </para>
4865
4866       <para>
4867         You need to check the channel argument, and if it's -1, copy
4868       the whole channels. Otherwise, you have to copy only the
4869       specified channel. Please check
4870       <filename>isa/gus/gus_pcm.c</filename> as an example. 
4871       </para>
4872
4873       <para>
4874         The <structfield>silence</structfield> callback is also
4875         implemented in a similar way. 
4876
4877         <informalexample>
4878           <programlisting>
4879 <![CDATA[
4880   static int silence(snd_pcm_substream_t *substream, int channel,
4881                      snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
4882 ]]>
4883           </programlisting>
4884         </informalexample>
4885       </para>
4886
4887       <para>
4888         The meanings of arguments are identical with the
4889       <structfield>copy</structfield> 
4890       callback, although there is no <parameter>src/dst</parameter>
4891       argument. In the case of interleaved samples, the channel
4892       argument has no meaning, as well as on
4893       <structfield>copy</structfield> callback.  
4894       </para>
4895
4896       <para>
4897         The role of <structfield>silence</structfield> callback is to
4898         set the given amount 
4899         (<parameter>count</parameter>) of silence data at the
4900         specified offset (<parameter>pos</parameter>) on the hardware
4901         buffer. Suppose that the data format is signed (that is, the
4902         silent-data is 0), and the implementation using a memset-like
4903         function would be like: 
4904
4905         <informalexample>
4906           <programlisting>
4907 <![CDATA[
4908   my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4909             frames_to_bytes(runtime, count));
4910 ]]>
4911           </programlisting>
4912         </informalexample>
4913       </para>
4914
4915       <para>
4916         In the case of non-interleaved samples, again, the
4917       implementation becomes a bit more complicated. See, for example,
4918       <filename>isa/gus/gus_pcm.c</filename>. 
4919       </para>
4920     </section>
4921
4922     <section id="buffer-and-memory-non-contiguous">
4923       <title>Non-Contiguous Buffers</title>
4924       <para>
4925         If your hardware supports the page table like emu10k1 or the
4926       buffer descriptors like via82xx, you can use the scatter-gather
4927       (SG) DMA. ALSA provides an interface for handling SG-buffers.
4928       The API is provided in <filename>&lt;sound/pcm_sgbuf.h&gt;</filename>. 
4929       </para>
4930
4931       <para>
4932         For creating the SG-buffer handler, call
4933         <function>snd_pcm_lib_preallocate_pages()</function> or
4934         <function>snd_pcm_lib_preallocate_pages_for_all()</function>
4935         with <constant>SNDRV_DMA_TYPE_DEV_SG</constant>
4936         in the PCM constructor like other PCI pre-allocator.
4937         You need to pass the <function>snd_dma_pci_data(pci)</function>,
4938         where pci is the struct <structname>pci_dev</structname> pointer
4939         of the chip as well.
4940         The <type>snd_sg_buf_t</type> instance is created as
4941         substream-&gt;dma_private. You can cast
4942         the pointer like: 
4943
4944         <informalexample>
4945           <programlisting>
4946 <![CDATA[
4947   snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
4948 ]]>
4949           </programlisting>
4950         </informalexample>
4951       </para>
4952
4953       <para>
4954         Then call <function>snd_pcm_lib_malloc_pages()</function>
4955       in <structfield>hw_params</structfield> callback
4956       as well as in the case of normal PCI buffer.
4957       The SG-buffer handler will allocate the non-contiguous kernel
4958       pages of the given size and map them onto the virtually contiguous
4959       memory.  The virtual pointer is addressed in runtime-&gt;dma_area.
4960       The physical address (runtime-&gt;dma_addr) is set to zero,
4961       because the buffer is physically non-contigous.
4962       The physical address table is set up in sgbuf-&gt;table.
4963       You can get the physical address at a certain offset via
4964       <function>snd_pcm_sgbuf_get_addr()</function>. 
4965       </para>
4966
4967       <para>
4968         When a SG-handler is used, you need to set
4969       <function>snd_pcm_sgbuf_ops_page</function> as
4970       the <structfield>page</structfield> callback.
4971       (See <link linkend="pcm-interface-operators-page-callback">
4972       <citetitle>page callback section</citetitle></link>.)
4973       </para>
4974
4975       <para>
4976         For releasing the data, call
4977       <function>snd_pcm_lib_free_pages()</function> in the
4978       <structfield>hw_free</structfield> callback as usual.
4979       </para>
4980     </section>
4981
4982     <section id="buffer-and-memory-vmalloced">
4983       <title>Vmalloc'ed Buffers</title>
4984       <para>
4985         It's possible to use a buffer allocated via
4986       <function>vmalloc</function>, for example, for an intermediate
4987       buffer. Since the allocated pages are not contiguous, you need
4988       to set the <structfield>page</structfield> callback to obtain
4989       the physical address at every offset. 
4990       </para>
4991
4992       <para>
4993         The implementation of <structfield>page</structfield> callback
4994         would be like this: 
4995
4996         <informalexample>
4997           <programlisting>
4998 <![CDATA[
4999   #include <linux/vmalloc.h>
5000
5001   /* get the physical page pointer on the given offset */
5002   static struct page *mychip_page(snd_pcm_substream_t *substream,
5003                                   unsigned long offset)
5004   {
5005           void *pageptr = substream->runtime->dma_area + offset;
5006           return vmalloc_to_page(pageptr);
5007   }
5008 ]]>
5009           </programlisting>
5010         </informalexample>
5011       </para>
5012     </section>
5013
5014   </chapter>
5015
5016
5017 <!-- ****************************************************** -->
5018 <!-- Proc Interface  -->
5019 <!-- ****************************************************** -->
5020   <chapter id="proc-interface">
5021     <title>Proc Interface</title>
5022     <para>
5023       ALSA provides an easy interface for procfs. The proc files are
5024       very useful for debugging. I recommend you set up proc files if
5025       you write a driver and want to get a running status or register
5026       dumps. The API is found in
5027       <filename>&lt;sound/info.h&gt;</filename>. 
5028     </para>
5029
5030     <para>
5031       For creating a proc file, call
5032       <function>snd_card_proc_new()</function>. 
5033
5034       <informalexample>
5035         <programlisting>
5036 <![CDATA[
5037   snd_info_entry_t *entry;
5038   int err = snd_card_proc_new(card, "my-file", &entry);
5039 ]]>
5040         </programlisting>
5041       </informalexample>
5042
5043       where the second argument specifies the proc-file name to be
5044     created. The above example will create a file
5045     <filename>my-file</filename> under the card directory,
5046     e.g. <filename>/proc/asound/card0/my-file</filename>. 
5047     </para>
5048
5049     <para>
5050     Like other components, the proc entry created via
5051     <function>snd_card_proc_new()</function> will be registered and
5052     released automatically in the card registration and release
5053     functions.
5054     </para>
5055
5056     <para>
5057       When the creation is successful, the function stores a new
5058     instance at the pointer given in the third argument.
5059     It is initialized as a text proc file for read only.  For using
5060     this proc file as a read-only text file as it is, set the read
5061     callback with a private data via 
5062      <function>snd_info_set_text_ops()</function>.
5063
5064       <informalexample>
5065         <programlisting>
5066 <![CDATA[
5067   snd_info_set_text_ops(entry, chip, read_size, my_proc_read);
5068 ]]>
5069         </programlisting>
5070       </informalexample>
5071     
5072     where the second argument (<parameter>chip</parameter>) is the
5073     private data to be used in the callbacks. The third parameter
5074     specifies the read buffer size and the fourth
5075     (<parameter>my_proc_read</parameter>) is the callback function, which
5076     is defined like
5077
5078       <informalexample>
5079         <programlisting>
5080 <![CDATA[
5081   static void my_proc_read(snd_info_entry_t *entry,
5082                            snd_info_buffer_t *buffer);
5083 ]]>
5084         </programlisting>
5085       </informalexample>
5086     
5087     </para>
5088
5089     <para>
5090     In the read callback, use <function>snd_iprintf()</function> for
5091     output strings, which works just like normal
5092     <function>printf()</function>.  For example,
5093
5094       <informalexample>
5095         <programlisting>
5096 <![CDATA[
5097   static void my_proc_read(snd_info_entry_t *entry,
5098                            snd_info_buffer_t *buffer)
5099   {
5100           chip_t *cm = snd_magic_cast(mychip_t,
5101                                   entry->private_data, return);
5102
5103           snd_iprintf(buffer, "This is my chip!\n");
5104           snd_iprintf(buffer, "Port = %ld\n", chip->port);
5105   }
5106 ]]>
5107         </programlisting>
5108       </informalexample>
5109     </para>
5110
5111     <para>
5112     The file permission can be changed afterwards.  As default, it's
5113     set as read only for all users.  If you want to add the write
5114     permission to the user (root as default), set like below:
5115
5116       <informalexample>
5117         <programlisting>
5118 <![CDATA[
5119  entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
5120 ]]>
5121         </programlisting>
5122       </informalexample>
5123
5124     and set the write buffer size and the callback
5125
5126       <informalexample>
5127         <programlisting>
5128 <![CDATA[
5129   entry->c.text.write_size = 256;
5130   entry->c.text.write = my_proc_write;
5131 ]]>
5132         </programlisting>
5133       </informalexample>
5134     </para>
5135
5136     <para>
5137     The buffer size for read is set to 1024 implicitly by
5138     <function>snd_info_set_text_ops()</function>.  It should suffice
5139     in most cases (the size will be aligned to
5140     <constant>PAGE_SIZE</constant> anyway), but if you need to handle
5141     very large text files, you can set it explicitly, too.
5142
5143       <informalexample>
5144         <programlisting>
5145 <![CDATA[
5146   entry->c.text.read_size = 65536;
5147 ]]>
5148         </programlisting>
5149       </informalexample>
5150     </para>
5151
5152     <para>
5153       For the write callback, you can use
5154     <function>snd_info_get_line()</function> to get a text line, and
5155     <function>snd_info_get_str()</function> to retrieve a string from
5156     the line. Some examples are found in
5157     <filename>core/oss/mixer_oss.c</filename>, core/oss/and
5158     <filename>pcm_oss.c</filename>. 
5159     </para>
5160
5161     <para>
5162       For a raw-data proc-file, set the attributes like the following:
5163
5164       <informalexample>
5165         <programlisting>
5166 <![CDATA[
5167   static struct snd_info_entry_ops my_file_io_ops = {
5168           .read = my_file_io_read,
5169   };
5170
5171   entry->content = SNDRV_INFO_CONTENT_DATA;
5172   entry->private_data = chip;
5173   entry->c.ops = &my_file_io_ops;
5174   entry->size = 4096;
5175   entry->mode = S_IFREG | S_IRUGO;
5176 ]]>
5177         </programlisting>
5178       </informalexample>
5179     </para>
5180
5181     <para>
5182       The callback is much more complicated than the text-file
5183       version. You need to use a low-level i/o functions such as
5184       <function>copy_from/to_user()</function> to transfer the
5185       data. Also, you have to keep tracking the file position, too. 
5186
5187       <informalexample>
5188         <programlisting>
5189 <![CDATA[
5190   static long my_file_io_read(snd_info_entry_t *entry,
5191                               void *file_private_data,
5192                               struct file *file,
5193                               char *buf, long count)
5194   {
5195           long size = count;
5196           if (file->f_pos + size > local_max_size)
5197                   size = local_max_size - file->f_pos;
5198           if (copy_to_user(buf, local_data + file->f_pos, size))
5199                   return -EFAULT;
5200           file->f_pos += size;
5201           return size;
5202   }
5203 ]]>
5204         </programlisting>
5205       </informalexample>
5206     </para>
5207
5208   </chapter>
5209
5210
5211 <!-- ****************************************************** -->
5212 <!-- Power Management  -->
5213 <!-- ****************************************************** -->
5214   <chapter id="power-management">
5215     <title>Power Management</title>
5216     <para>
5217       If the chip is supposed to work with with suspend/resume
5218       functions, you need to add the power-management codes to the
5219       driver. The additional codes for the power-management should be
5220       <function>ifdef</function>'ed with
5221       <constant>CONFIG_PM</constant>. 
5222     </para>
5223
5224     <para>
5225       ALSA provides the common power-management layer. Each card driver
5226       needs to have only low-level suspend and resume callbacks.
5227
5228       <informalexample>
5229         <programlisting>
5230 <![CDATA[
5231   #ifdef CONFIG_PM
5232   static int snd_my_suspend(snd_card_t *card, unsigned int state)
5233   {
5234           .... // do things for suspsend
5235           return 0;
5236   }
5237   static int snd_my_resume(snd_card_t *card, unsigned int state)
5238   {
5239           .... // do things for suspsend
5240           return 0;
5241   }
5242   #endif
5243 ]]>
5244         </programlisting>
5245       </informalexample>
5246     </para>
5247
5248     <para>
5249       The scheme of the real suspend job is as following.
5250
5251       <orderedlist>
5252         <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5253         <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>
5254         <listitem><para>Save the register values if necessary.</para></listitem>
5255         <listitem><para>Stop the hardware if necessary.</para></listitem>
5256         <listitem><para>Set the power-state as D3hot by calling <function>snd_power_change_state()</function>.</para></listitem>
5257       </orderedlist>
5258     </para>
5259
5260     <para>
5261       A typical code would be like:
5262
5263       <informalexample>
5264         <programlisting>
5265 <![CDATA[
5266   static int mychip_suspend(snd_card_t *card, unsigned int state)
5267   {
5268           // (1)
5269           mychip_t *chip = snd_magic_cast(mychip_t, card->pm_private_data,
5270                                           return -ENXIO);
5271           // (2)
5272           snd_pcm_suspend_all(chip->pcm);
5273           // (3)
5274           snd_mychip_save_registers(chip);
5275           // (4)
5276           snd_mychip_stop_hardware(chip);
5277           // (5)
5278           snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
5279           return 0;
5280   }
5281 ]]>
5282         </programlisting>
5283       </informalexample>
5284     </para>
5285
5286     <para>
5287     The scheme of the real resume job is as following.
5288
5289     <orderedlist>
5290     <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5291     <listitem><para>Enable the pci device again by calling
5292     <function>pci_enable_device()</function>.</para></listitem>
5293     <listitem><para>Re-initialize the chip.</para></listitem>
5294     <listitem><para>Restore the saved registers if necessary.</para></listitem>
5295     <listitem><para>Resume the mixer, e.g. calling
5296     <function>snd_ac97_resume()</function>.</para></listitem>
5297     <listitem><para>Restart the hardware (if any).</para></listitem>
5298     <listitem><para>Set the power-state as D0 by calling
5299     <function>snd_power_change_state()</function>.</para></listitem>
5300     </orderedlist>
5301     </para>
5302
5303     <para>
5304     A typical code would be like:
5305
5306       <informalexample>
5307         <programlisting>
5308 <![CDATA[
5309   static void mychip_resume(mychip_t *chip)
5310   {
5311           // (1)
5312           mychip_t *chip = snd_magic_cast(mychip_t, card->pm_private_data,
5313                                           return -ENXIO);
5314           // (2)
5315           pci_enable_device(chip->pci);
5316           // (3)
5317           snd_mychip_reinit_chip(chip);
5318           // (4)
5319           snd_mychip_restore_registers(chip);
5320           // (5)
5321           snd_ac97_resume(chip->ac97);
5322           // (6)
5323           snd_mychip_restart_chip(chip);
5324           // (7)
5325           snd_power_change_state(card, SNDRV_CTL_POWER_D0);
5326           return 0;
5327   }
5328 ]]>
5329         </programlisting>
5330       </informalexample>
5331     </para>
5332
5333     <para>
5334       OK, we have all callbacks now. Let's set up them now. In the
5335       initialization of the card, add the following: 
5336
5337       <informalexample>
5338         <programlisting>
5339 <![CDATA[
5340   static int __devinit snd_mychip_probe(struct pci_dev *pci,
5341                                const struct pci_device_id *pci_id)
5342   {
5343           ....
5344           snd_card_t *card;
5345           mychip_t *chip;
5346           ....
5347           snd_card_set_pm_callback(card, snd_my_suspend, snd_my_resume, chip);
5348           ....
5349   }
5350 ]]>
5351         </programlisting>
5352       </informalexample>
5353
5354     Here you don't have to put ifdef CONFIG_PM around, since it's already
5355     checked in the header and expanded to empty if not needed.
5356     </para>
5357
5358     <para>
5359       If you need a space for saving the registers, you'll need to
5360     allocate the buffer for it here, too, since it would be fatal
5361     if you cannot allocate a memory in the suspend phase.
5362     The allocated buffer should be released in the corresponding
5363     destructor.
5364     </para>
5365
5366     <para>
5367       And next, set suspend/resume callbacks to the pci_driver,
5368       This can be done by passing a macro SND_PCI_PM_CALLBACKS
5369       in the pci_driver struct.  This macro is expanded to the correct
5370       (global) callbacks if CONFIG_PM is set.
5371
5372       <informalexample>
5373         <programlisting>
5374 <![CDATA[
5375   static struct pci_driver driver = {
5376           .name = "My Chip",
5377           .id_table = snd_my_ids,
5378           .probe = snd_my_probe,
5379           .remove = __devexit_p(snd_my_remove),
5380           SND_PCI_PM_CALLBACKS
5381   };
5382 ]]>
5383         </programlisting>
5384       </informalexample>
5385     </para>
5386
5387   </chapter>
5388
5389
5390 <!-- ****************************************************** -->
5391 <!-- Module Parameters  -->
5392 <!-- ****************************************************** -->
5393   <chapter id="module-parameters">
5394     <title>Module Parameters</title>
5395     <para>
5396       There are standard module options for ALSA. At least, each
5397       module should have <parameter>index</parameter>,
5398       <parameter>id</parameter> and <parameter>enable</parameter>
5399       options. 
5400     </para>
5401
5402     <para>
5403       If the module supports multiple cards (usually up to
5404       8 = <constant>SNDRV_CARDS</constant> cards), they should be
5405       arrays.  The default initial values are defined already as
5406       constants for ease of programming:
5407
5408       <informalexample>
5409         <programlisting>
5410 <![CDATA[
5411   static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
5412   static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
5413   static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
5414 ]]>
5415         </programlisting>
5416       </informalexample>
5417     </para>
5418
5419     <para>
5420       If the module supports only a single card, they could be single
5421     variables, instead.  <parameter>enable</parameter> option is not
5422     always necessary in this case, but it wouldn't be so bad to have a
5423     dummy option for compatibility.
5424     </para>
5425
5426     <para>
5427       The module parameters must be declared with the standard
5428     <function>module_param()()</function>,
5429     <function>module_param_array()()</function> and
5430     <function>MODULE_PARM_DESC()</function> macros. The ALSA provides
5431     an additional macro, <function>MODULE_PARM_SYNTAX()</function>,
5432     for describing its syntax. The strings will be written to
5433     <filename>/lib/modules/XXX/modules.generic_string</filename>
5434     file. 
5435     </para>
5436
5437     <para>
5438       For convenience, the typical string arguments given to
5439     <function>MODULE_PARM_SYNTAX()</function> are defined in
5440     <filename>&lt;sound/initval.h&gt;</filename>, such as
5441     <constant>SNDRV_ID_DESC</constant> or
5442     <constant>SNDRV_ENABLED</constant>.
5443     </para>
5444
5445     <para>
5446       The typical coding would be like below:
5447
5448       <informalexample>
5449         <programlisting>
5450 <![CDATA[
5451   #define CARD_NAME "My Chip"
5452
5453   static int boot_devs;
5454   module_param_array(index, int, boot_devs, 0444);
5455   MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
5456   MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
5457   module_param_array(id, charp, boot_devs, 0444);
5458   MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
5459   MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
5460   module_param_array(enable, bool, boot_devs, 0444);
5461   MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
5462   MODULE_PARM_SYNTAX(enable, SNDRV_ENABLE_DESC);
5463 ]]>
5464         </programlisting>
5465       </informalexample>
5466
5467     Here boot_devs is passed but simply ignored since we don't care
5468     the number of parsed parameters.
5469     </para>
5470
5471     <para>
5472       Also, don't forget to define the module description, classes,
5473       license and devices. Especially, the recent modprobe requires to
5474       define the module license as GPL, etc., otherwise the system is
5475       shown as <quote>tainted</quote>. 
5476
5477       <informalexample>
5478         <programlisting>
5479 <![CDATA[
5480   MODULE_DESCRIPTION("My Chip");
5481   MODULE_CLASSES("{sound}");
5482   MODULE_LICENSE("GPL");
5483   MODULE_DEVICES("{{Vendor,My Chip Name}}");
5484 ]]>
5485         </programlisting>
5486       </informalexample>
5487     </para>
5488
5489   </chapter>
5490
5491
5492 <!-- ****************************************************** -->
5493 <!-- How To Put Your Driver  -->
5494 <!-- ****************************************************** -->
5495   <chapter id="how-to-put-your-driver">
5496     <title>How To Put Your Driver Into ALSA Tree</title>
5497         <section>
5498         <title>General</title>
5499         <para>
5500         So far, you've learned how to write the driver codes.
5501         And you might have a question now: how to put my own
5502         driver into the ALSA driver tree?
5503         Here (finally :) the standard procedure is described briefly.
5504         </para>
5505
5506         <para>
5507         Suppose that you'll create a new PCI driver for the card
5508         <quote>xyz</quote>.  The card module name would be
5509         snd-xyz.  The new driver is usually put into alsa-driver
5510         tree, <filename>alsa-driver/pci</filename> directory in
5511         the case of PCI cards.
5512         Then the driver is evaluated, audited and tested
5513         by developers and users.  After a certain time, the driver
5514         will go to alsa-kernel tree (to the corresponding directory,
5515         such as <filename>alsa-kernel/pci</filename>) and eventually
5516         integrated into Linux 2.6 tree (the directory would be
5517         <filename>linux/sound/pci</filename>).
5518         </para>
5519
5520         <para>
5521         In the following sections, the driver code is supposed
5522         to be put into alsa-driver tree.  The two cases are assumed:
5523         a driver consisting of a single source file and one consisting
5524         of several source files.
5525         </para>
5526         </section>
5527
5528         <section>
5529         <title>Driver with A Single Source File</title>
5530         <para>
5531         <orderedlist>
5532         <listitem>
5533         <para>
5534         Modify alsa-driver/pci/Makefile
5535         </para>
5536
5537         <para>
5538         Suppose you have a file xyz.c.  Add the following
5539         two lines
5540       <informalexample>
5541         <programlisting>
5542 <![CDATA[
5543   snd-xyz-objs := xyz.o
5544   obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5545 ]]>
5546         </programlisting>
5547       </informalexample>
5548         </para>
5549         </listitem>
5550
5551         <listitem>
5552         <para>
5553         Create the Kconfig entry
5554         </para>
5555
5556         <para>
5557         Add the new entry of Kconfig for your xyz driver.
5558       <informalexample>
5559         <programlisting>
5560 <![CDATA[
5561   config SND_XYZ
5562           tristate "Foobar XYZ"
5563           depends on SND
5564           select SND_PCM
5565           help
5566             Say 'Y' or 'M' to include support for Foobar XYZ soundcard.
5567 ]]>
5568         </programlisting>
5569       </informalexample>
5570
5571         the line, select SND_PCM, specifies that the driver xyz supports
5572         PCM.  In addition to SND_PCM, the following components are
5573         supported for select command:
5574         SND_RAWMIDI, SND_TIMER, SND_HWDEP, SND_MPU401_UART,
5575         SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB, SND_AC97_CODEC.
5576         Add the select command for each supported component.
5577         </para>
5578
5579         <para>
5580         Note that some selections imply the lowlevel selections.
5581         For example, PCM includes TIMER, MPU401_UART includes RAWMIDI,
5582         AC97_CODEC includes PCM, and OPL3_LIB includes HWDEP.
5583         You don't need to give the lowlevel selections again.
5584         </para>
5585
5586         <para>
5587         For the details of Kconfig script, refer to the kbuild
5588         documentation.
5589         </para>
5590
5591         </listitem>
5592
5593         <listitem>
5594         <para>
5595         Run cvscompile script to re-generate the configure script and
5596         build the whole stuff again.
5597         </para>
5598         </listitem>
5599         </orderedlist>
5600         </para>
5601         </section>
5602
5603         <section>
5604         <title>Drivers with Several Source Files</title>
5605         <para>
5606         Suppose that the driver snd-xyz have several source files.
5607         They are located in the new subdirectory,
5608         pci/xyz.
5609
5610         <orderedlist>
5611         <listitem>
5612         <para>
5613         Add a new directory (<filename>xyz</filename>) in
5614         <filename>alsa-driver/pci/Makefile</filename> like below
5615
5616       <informalexample>
5617         <programlisting>
5618 <![CDATA[
5619   obj-$(CONFIG_SND) += xyz/
5620 ]]>
5621         </programlisting>
5622       </informalexample>
5623         </para>
5624         </listitem>
5625
5626         <listitem>
5627         <para>
5628         Under the directory <filename>xyz</filename>, create a Makefile
5629
5630       <example>
5631         <title>Sample Makefile for a driver xyz</title>
5632         <programlisting>
5633 <![CDATA[
5634   ifndef SND_TOPDIR
5635   SND_TOPDIR=../..
5636   endif
5637
5638   include $(TOPDIR)/toplevel.config
5639   include $(TOPDIR)/Makefile.conf
5640
5641   snd-xyz-objs := xyz.o abc.o def.o
5642
5643   obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5644
5645   include $(TOPDIR)/Rules.make
5646 ]]>
5647         </programlisting>
5648       </example>
5649         </para>
5650         </listitem>
5651
5652         <listitem>
5653         <para>
5654         Create the Kconfig entry
5655         </para>
5656
5657         <para>
5658         This procedure is as same as in the last section.
5659         </para>
5660         </listitem>
5661
5662         <listitem>
5663         <para>
5664         Run cvscompile script to re-generate the configure script and
5665         build the whole stuff again.
5666         </para>
5667         </listitem>
5668         </orderedlist>
5669         </para>
5670         </section>
5671
5672   </chapter>
5673
5674 <!-- ****************************************************** -->
5675 <!-- Useful Functions  -->
5676 <!-- ****************************************************** -->
5677   <chapter id="useful-functions">
5678     <title>Useful Functions</title>
5679
5680     <section id="useful-functions-snd-printk">
5681       <title><function>snd_printk()</function> and friends</title>
5682       <para>
5683         ALSA provides a verbose version of
5684       <function>printk()</function> function. If a kernel config
5685       <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this
5686       function prints the given message together with the file name
5687       and the line of the caller. The <constant>KERN_XXX</constant>
5688       prefix is processed as 
5689       well as the original <function>printk()</function> does, so it's
5690       recommended to add this prefix, e.g. 
5691
5692         <informalexample>
5693           <programlisting>
5694 <![CDATA[
5695   snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
5696 ]]>
5697           </programlisting>
5698         </informalexample>
5699       </para>
5700
5701       <para>
5702         There are also <function>printk()</function>'s for
5703       debugging. <function>snd_printd()</function> can be used for
5704       general debugging purposes. If
5705       <constant>CONFIG_SND_DEBUG</constant> is set, this function is
5706       compiled, and works just like
5707       <function>snd_printk()</function>. If the ALSA is compiled
5708       without the debugging flag, it's ignored. 
5709       </para>
5710
5711       <para>
5712         <function>snd_printdd()</function> is compiled in only when
5713       <constant>CONFIG_SND_DEBUG_DETECT</constant> is set. Please note
5714       that <constant>DEBUG_DETECT</constant> is not set as default
5715       even if you configure the alsa-driver with
5716       <option>--with-debug=full</option> option. You need to give
5717       explicitly <option>--with-debug=detect</option> option instead. 
5718       </para>
5719     </section>
5720
5721     <section id="useful-functions-snd-assert">
5722       <title><function>snd_assert()</function></title>
5723       <para>
5724         <function>snd_assert()</function> macro is similar with the
5725       normal <function>assert()</function> macro. For example,  
5726
5727         <informalexample>
5728           <programlisting>
5729 <![CDATA[
5730   snd_assert(pointer != NULL, return -EINVAL);
5731 ]]>
5732           </programlisting>
5733         </informalexample>
5734       </para>
5735
5736       <para>
5737         The first argument is the expression to evaluate, and the
5738       second argument is the action if it fails. When
5739       <constant>CONFIG_SND_DEBUG</constant>, is set, it will show an
5740       error message such as <computeroutput>BUG? (xxx) (called from
5741       yyy)</computeroutput>. When no debug flag is set, this is
5742       ignored. 
5743       </para>
5744     </section>
5745
5746     <section id="useful-functions-snd-runtime-check">
5747       <title><function>snd_runtime_check()</function></title>
5748       <para>
5749         This macro is quite similar with
5750       <function>snd_assert()</function>. Unlike
5751       <function>snd_assert()</function>, the expression is always
5752       evaluated regardless of
5753       <constant>CONFIG_SND_DEBUG</constant>. When
5754       <constant>CONFIG_SND_DEBUG</constant> is set, the macro will
5755       show a message like <computeroutput>ERROR (xx) (called from
5756       yyy)</computeroutput>. 
5757       </para>
5758     </section>
5759
5760     <section id="useful-functions-snd-bug">
5761       <title><function>snd_BUG()</function></title>
5762       <para>
5763         It calls <function>snd_assert(0,)</function> -- that is, just
5764       prints the error message at the point. It's useful to show that
5765       a fatal error happens there. 
5766       </para>
5767     </section>
5768   </chapter>
5769
5770
5771 <!-- ****************************************************** -->
5772 <!-- Acknowledgments  -->
5773 <!-- ****************************************************** -->
5774   <chapter id="acknowledments">
5775     <title>Acknowledgments</title>
5776     <para>
5777       I would like to thank Phil Kerr for his help for improvement and
5778       corrections of this document. 
5779     </para>
5780     <para>
5781     Kevin Conder reformatted the original plain-text to the
5782     DocBook format.
5783     </para>
5784     <para>
5785     Giuliano Pochini corrected typos and contributed the example codes
5786     in the hardware constraints section.
5787     </para>
5788   </chapter>
5789
5790
5791 </book>