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