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