]> nv-tegra.nvidia Code Review - linux-2.6.git/blob - Documentation/sound/alsa/DocBook/writing-an-alsa-driver.tmpl
320384c1791bc1885bdf9940055a4af0694065f4
[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>Oct 15, 2007</date>
22      <edition>0.3.7</edition>
23
24     <abstract>
25       <para>
26         This document describes how to write an ALSA (Advanced Linux
27         Sound Architecture) driver.
28       </para>
29     </abstract>
30
31     <legalnotice>
32     <para>
33     Copyright (c) 2002-2005  Takashi Iwai <email>tiwai@suse.de</email>
34     </para>
35
36     <para>
37     This document is free; you can redistribute it and/or modify it
38     under the terms of the GNU General Public License as published by
39     the Free Software Foundation; either version 2 of the License, or
40     (at your option) any later version. 
41     </para>
42
43     <para>
44     This document is distributed in the hope that it will be useful,
45     but <emphasis>WITHOUT ANY WARRANTY</emphasis>; without even the
46     implied warranty of <emphasis>MERCHANTABILITY or FITNESS FOR A
47     PARTICULAR PURPOSE</emphasis>. See the GNU General Public License
48     for more details.
49     </para>
50
51     <para>
52     You should have received a copy of the GNU General Public
53     License along with this program; if not, write to the Free
54     Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
55     MA 02111-1307 USA
56     </para>
57     </legalnotice>
58
59   </bookinfo>
60
61 <!-- ****************************************************** -->
62 <!-- Preface  -->
63 <!-- ****************************************************** -->
64   <preface id="preface">
65     <title>Preface</title>
66     <para>
67       This document describes how to write an
68       <ulink url="http://www.alsa-project.org/"><citetitle>
69       ALSA (Advanced Linux Sound Architecture)</citetitle></ulink>
70       driver. The document focuses mainly on PCI soundcards.
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     This document targets people who already have enough
79     C language skills and have basic linux kernel programming
80     knowledge.  This document doesn't explain the general
81     topic of linux kernel coding and doesn't cover low-level
82     driver implementation details. It only describes
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 API, you
88     can check the drivers such as <filename>sound/pci/es1938.c</filename> or
89     <filename>sound/pci/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 feedback 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 two ways.
110       </para>
111
112       <para>
113         One is the trees provided as a tarball or via cvs from the
114       ALSA's ftp site, and another is the 2.6 (or later) Linux kernel
115       tree. To synchronize both, the ALSA driver tree is split into
116       two different trees: alsa-kernel and alsa-driver. The former
117       contains purely the source code 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 ALSA drivers outside of the Linux kernel tree,
121       wrapper functions for older 2.2 and 2.4 kernels, to adapt the latest kernel API,
122       and additional drivers which are still in development or in
123       tests.  The drivers in alsa-driver tree will be moved to
124       alsa-kernel (and eventually to the 2.6 kernel tree) when they are
125       finished and confirmed to work fine.
126       </para>
127
128       <para>
129         The file tree structure of ALSA driver is depicted below. Both
130         alsa-kernel and alsa-driver have almost the same file
131         structure, except for <quote>core</quote> directory. It's
132         named as <quote>acore</quote> in alsa-driver tree. 
133
134         <example>
135           <title>ALSA File Tree Structure</title>
136           <literallayout>
137         sound
138                 /core
139                         /oss
140                         /seq
141                                 /oss
142                                 /instr
143                 /ioctl32
144                 /include
145                 /drivers
146                         /mpu401
147                         /opl3
148                 /i2c
149                         /l3
150                 /synth
151                         /emux
152                 /pci
153                         /(cards)
154                 /isa
155                         /(cards)
156                 /arm
157                 /ppc
158                 /sparc
159                 /usb
160                 /pcmcia /(cards)
161                 /oss
162           </literallayout>
163         </example>
164       </para>
165     </section>
166
167     <section id="file-tree-core-directory">
168       <title>core directory</title>
169       <para>
170         This directory contains the middle layer which is the heart
171       of ALSA drivers. In this directory, the native ALSA modules are
172       stored. The sub-directories contain different modules and are
173       dependent upon the kernel config. 
174       </para>
175
176       <section id="file-tree-core-directory-oss">
177         <title>core/oss</title>
178
179         <para>
180           The codes for PCM and mixer OSS emulation modules are stored
181         in this directory. The rawmidi OSS emulation is included in
182         the ALSA rawmidi code since it's quite small. The sequencer
183         code is stored in <filename>core/seq/oss</filename> directory (see
184         <link linkend="file-tree-core-directory-seq-oss"><citetitle>
185         below</citetitle></link>).
186         </para>
187       </section>
188
189       <section id="file-tree-core-directory-ioctl32">
190         <title>core/ioctl32</title>
191
192         <para>
193           This directory contains the 32bit-ioctl wrappers for 64bit
194         architectures such like x86-64, ppc64 and sparc64. For 32bit
195         and alpha architectures, these are not compiled. 
196         </para>
197       </section>
198
199       <section id="file-tree-core-directory-seq">
200         <title>core/seq</title>
201         <para>
202           This directory and its sub-directories are for the ALSA
203         sequencer. This directory contains the sequencer core and
204         primary sequencer modules such like snd-seq-midi,
205         snd-seq-virmidi, etc. They are compiled only when
206         <constant>CONFIG_SND_SEQUENCER</constant> is set in the kernel
207         config. 
208         </para>
209       </section>
210
211       <section id="file-tree-core-directory-seq-oss">
212         <title>core/seq/oss</title>
213         <para>
214           This contains the OSS sequencer emulation codes.
215         </para>
216       </section>
217
218       <section id="file-tree-core-directory-deq-instr">
219         <title>core/seq/instr</title>
220         <para>
221           This directory contains the modules for the sequencer
222         instrument layer. 
223         </para>
224       </section>
225     </section>
226
227     <section id="file-tree-include-directory">
228       <title>include directory</title>
229       <para>
230         This is the place for the public header files of ALSA drivers,
231       which are to be exported to user-space, or included by
232       several files at different directories. Basically, the private
233       header files should not be placed in this directory, but you may
234       still find files there, due to historical reasons :) 
235       </para>
236     </section>
237
238     <section id="file-tree-drivers-directory">
239       <title>drivers directory</title>
240       <para>
241         This directory contains code shared among different drivers
242       on different architectures.  They are hence supposed not to be
243       architecture-specific.
244       For example, the dummy pcm driver and the serial MIDI
245       driver are found in this directory. In the sub-directories,
246       there is code for components which are independent from
247       bus and cpu architectures. 
248       </para>
249
250       <section id="file-tree-drivers-directory-mpu401">
251         <title>drivers/mpu401</title>
252         <para>
253           The MPU401 and MPU401-UART modules are stored here.
254         </para>
255       </section>
256
257       <section id="file-tree-drivers-directory-opl3">
258         <title>drivers/opl3 and opl4</title>
259         <para>
260           The OPL3 and OPL4 FM-synth stuff is found here.
261         </para>
262       </section>
263     </section>
264
265     <section id="file-tree-i2c-directory">
266       <title>i2c directory</title>
267       <para>
268         This contains the ALSA i2c components.
269       </para>
270
271       <para>
272         Although there is a standard i2c layer on Linux, ALSA has its
273       own i2c code for some cards, because the soundcard needs only a
274       simple operation and the standard i2c API is too complicated for
275       such a purpose. 
276       </para>
277
278       <section id="file-tree-i2c-directory-l3">
279         <title>i2c/l3</title>
280         <para>
281           This is a sub-directory for ARM L3 i2c.
282         </para>
283       </section>
284     </section>
285
286     <section id="file-tree-synth-directory">
287         <title>synth directory</title>
288         <para>
289           This contains the synth middle-level modules.
290         </para>
291
292         <para>
293           So far, there is only Emu8000/Emu10k1 synth driver under
294         the <filename>synth/emux</filename> sub-directory. 
295         </para>
296     </section>
297
298     <section id="file-tree-pci-directory">
299       <title>pci directory</title>
300       <para>
301         This directory and its sub-directories hold the top-level card modules
302       for PCI soundcards and the code specific to the PCI BUS.
303       </para>
304
305       <para>
306         The drivers compiled from a single file are stored directly
307       in the pci directory, while the drivers with several source files are
308       stored on their own sub-directory (e.g. emu10k1, ice1712). 
309       </para>
310     </section>
311
312     <section id="file-tree-isa-directory">
313       <title>isa directory</title>
314       <para>
315         This directory and its sub-directories hold the top-level card modules
316       for ISA soundcards. 
317       </para>
318     </section>
319
320     <section id="file-tree-arm-ppc-sparc-directories">
321       <title>arm, ppc, and sparc directories</title>
322       <para>
323         They are used for top-level card modules which are
324       specific to one of these architectures. 
325       </para>
326     </section>
327
328     <section id="file-tree-usb-directory">
329       <title>usb directory</title>
330       <para>
331         This directory contains the USB-audio driver. In the latest version, the
332       USB MIDI driver is integrated in the usb-audio driver. 
333       </para>
334     </section>
335
336     <section id="file-tree-pcmcia-directory">
337       <title>pcmcia directory</title>
338       <para>
339         The PCMCIA, especially PCCard drivers will go here. CardBus
340       drivers will be in the pci directory, because their API is identical
341       to that of standard PCI cards. 
342       </para>
343     </section>
344
345     <section id="file-tree-oss-directory">
346       <title>oss directory</title>
347       <para>
348         The OSS/Lite source files are stored here in Linux 2.6 (or
349       later) tree. In the ALSA driver tarball, this directory is empty,
350       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 for PCI soundcards is as follows:
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 a <structname>pci_driver</structname> structure
374           containing the three pointers above.</para></listitem>
375           <listitem><para>create an <function>init()</function> function just calling
376           the <function>pci_register_driver()</function> to register the pci_driver table
377           defined above.</para></listitem>
378           <listitem><para>create an <function>exit()</function> function to call
379           the <function>pci_unregister_driver()</function> function.</para></listitem>
380         </itemizedlist>
381       </para>
382     </section>
383
384     <section id="basic-flow-example">
385       <title>Full Code Example</title>
386       <para>
387         The code example is shown below. Some parts are kept
388       unimplemented at this moment but will be filled in the
389       next sections. The numbers in the comment lines of the
390       <function>snd_mychip_probe()</function> function
391       refer to details explained in the following section. 
392
393         <example>
394           <title>Basic Flow for PCI Drivers - Example</title>
395           <programlisting>
396 <![CDATA[
397   #include <linux/init.h>
398   #include <linux/pci.h>
399   #include <linux/slab.h>
400   #include <sound/core.h>
401   #include <sound/initval.h>
402
403   /* module parameters (see "Module Parameters") */
404   /* SNDRV_CARDS: maximum number of cards supported by this module */
405   static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
406   static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
407   static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
408
409   /* definition of the chip-specific record */
410   struct mychip {
411           struct snd_card *card;
412           /* the rest of the implementation will be in section
413            * "PCI Resource Management"
414            */
415   };
416
417   /* chip-specific destructor
418    * (see "PCI Resource Management")
419    */
420   static int snd_mychip_free(struct mychip *chip)
421   {
422           .... /* will be implemented later... */
423   }
424
425   /* component-destructor
426    * (see "Management of Cards and Components")
427    */
428   static int snd_mychip_dev_free(struct snd_device *device)
429   {
430           return snd_mychip_free(device->device_data);
431   }
432
433   /* chip-specific constructor
434    * (see "Management of Cards and Components")
435    */
436   static int __devinit snd_mychip_create(struct snd_card *card,
437                                          struct pci_dev *pci,
438                                          struct mychip **rchip)
439   {
440           struct mychip *chip;
441           int err;
442           static struct snd_device_ops ops = {
443                  .dev_free = snd_mychip_dev_free,
444           };
445
446           *rchip = NULL;
447
448           /* check PCI availability here
449            * (see "PCI Resource Management")
450            */
451           ....
452
453           /* allocate a chip-specific data with zero filled */
454           chip = kzalloc(sizeof(*chip), GFP_KERNEL);
455           if (chip == NULL)
456                   return -ENOMEM;
457
458           chip->card = card;
459
460           /* rest of initialization here; will be implemented
461            * later, see "PCI Resource Management"
462            */
463           ....
464
465           err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
466           if (err < 0) {
467                   snd_mychip_free(chip);
468                   return err;
469           }
470
471           snd_card_set_dev(card, &pci->dev);
472
473           *rchip = chip;
474           return 0;
475   }
476
477   /* constructor -- see "Constructor" sub-section */
478   static int __devinit snd_mychip_probe(struct pci_dev *pci,
479                                const struct pci_device_id *pci_id)
480   {
481           static int dev;
482           struct snd_card *card;
483           struct mychip *chip;
484           int err;
485
486           /* (1) */
487           if (dev >= SNDRV_CARDS)
488                   return -ENODEV;
489           if (!enable[dev]) {
490                   dev++;
491                   return -ENOENT;
492           }
493
494           /* (2) */
495           err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
496           if (err < 0)
497                   return err;
498
499           /* (3) */
500           err = snd_mychip_create(card, pci, &chip);
501           if (err < 0) {
502                   snd_card_free(card);
503                   return err;
504           }
505
506           /* (4) */
507           strcpy(card->driver, "My Chip");
508           strcpy(card->shortname, "My Own Chip 123");
509           sprintf(card->longname, "%s at 0x%lx irq %i",
510                   card->shortname, chip->ioport, chip->irq);
511
512           /* (5) */
513           .... /* implemented later */
514
515           /* (6) */
516           err = snd_card_register(card);
517           if (err < 0) {
518                   snd_card_free(card);
519                   return err;
520           }
521
522           /* (7) */
523           pci_set_drvdata(pci, card);
524           dev++;
525           return 0;
526   }
527
528   /* destructor -- see the "Destructor" sub-section */
529   static void __devexit snd_mychip_remove(struct pci_dev *pci)
530   {
531           snd_card_free(pci_get_drvdata(pci));
532           pci_set_drvdata(pci, NULL);
533   }
534 ]]>
535           </programlisting>
536         </example>
537       </para>
538     </section>
539
540     <section id="basic-flow-constructor">
541       <title>Constructor</title>
542       <para>
543         The real constructor of PCI drivers is the <function>probe</function> callback.
544       The <function>probe</function> callback and other component-constructors which are called
545       from the <function>probe</function> callback should be defined with
546       the <parameter>__devinit</parameter> prefix. You 
547       cannot use the <parameter>__init</parameter> prefix for them,
548       because any PCI device could be a hotplug device. 
549       </para>
550
551       <para>
552         In the <function>probe</function> callback, the following scheme is often used.
553       </para>
554
555       <section id="basic-flow-constructor-device-index">
556         <title>1) Check and increment the device index.</title>
557         <para>
558           <informalexample>
559             <programlisting>
560 <![CDATA[
561   static int dev;
562   ....
563   if (dev >= SNDRV_CARDS)
564           return -ENODEV;
565   if (!enable[dev]) {
566           dev++;
567           return -ENOENT;
568   }
569 ]]>
570             </programlisting>
571           </informalexample>
572
573         where enable[dev] is the module option.
574         </para>
575
576         <para>
577           Each time the <function>probe</function> callback is called, check the
578         availability of the device. If not available, simply increment
579         the device index and returns. dev will be incremented also
580         later (<link
581         linkend="basic-flow-constructor-set-pci"><citetitle>step
582         7</citetitle></link>). 
583         </para>
584       </section>
585
586       <section id="basic-flow-constructor-create-card">
587         <title>2) Create a card instance</title>
588         <para>
589           <informalexample>
590             <programlisting>
591 <![CDATA[
592   struct snd_card *card;
593   int err;
594   ....
595   err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
596 ]]>
597             </programlisting>
598           </informalexample>
599         </para>
600
601         <para>
602           The details will be explained in the section
603           <link linkend="card-management-card-instance"><citetitle>
604           Management of Cards and Components</citetitle></link>.
605         </para>
606       </section>
607
608       <section id="basic-flow-constructor-create-main">
609         <title>3) Create a main component</title>
610         <para>
611           In this part, the PCI resources are allocated.
612
613           <informalexample>
614             <programlisting>
615 <![CDATA[
616   struct mychip *chip;
617   ....
618   err = snd_mychip_create(card, pci, &chip);
619   if (err < 0) {
620           snd_card_free(card);
621           return err;
622   }
623 ]]>
624             </programlisting>
625           </informalexample>
626
627           The details will be explained in the section <link
628         linkend="pci-resource"><citetitle>PCI Resource
629         Management</citetitle></link>.
630         </para>
631       </section>
632
633       <section id="basic-flow-constructor-main-component">
634         <title>4) Set the driver ID and name strings.</title>
635         <para>
636           <informalexample>
637             <programlisting>
638 <![CDATA[
639   strcpy(card->driver, "My Chip");
640   strcpy(card->shortname, "My Own Chip 123");
641   sprintf(card->longname, "%s at 0x%lx irq %i",
642           card->shortname, chip->ioport, chip->irq);
643 ]]>
644             </programlisting>
645           </informalexample>
646
647           The driver field holds the minimal ID string of the
648         chip. This is used by alsa-lib's configurator, so keep it
649         simple but unique. 
650           Even the same driver can have different driver IDs to
651         distinguish the functionality of each chip type. 
652         </para>
653
654         <para>
655           The shortname field is a string shown as more verbose
656         name. The longname field contains the information
657         shown in <filename>/proc/asound/cards</filename>. 
658         </para>
659       </section>
660
661       <section id="basic-flow-constructor-create-other">
662         <title>5) Create other components, such as mixer, MIDI, etc.</title>
663         <para>
664           Here you define the basic components such as
665           <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
666           mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
667           MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
668           and other interfaces.
669           Also, if you want a <link linkend="proc-interface"><citetitle>proc
670         file</citetitle></link>, define it here, too.
671         </para>
672       </section>
673
674       <section id="basic-flow-constructor-register-card">
675         <title>6) Register the card instance.</title>
676         <para>
677           <informalexample>
678             <programlisting>
679 <![CDATA[
680   err = snd_card_register(card);
681   if (err < 0) {
682           snd_card_free(card);
683           return err;
684   }
685 ]]>
686             </programlisting>
687           </informalexample>
688         </para>
689
690         <para>
691           Will be explained in the section <link
692         linkend="card-management-registration"><citetitle>Management
693         of Cards and Components</citetitle></link>, too. 
694         </para>
695       </section>
696
697       <section id="basic-flow-constructor-set-pci">
698         <title>7) Set the PCI driver data and return zero.</title>
699         <para>
700           <informalexample>
701             <programlisting>
702 <![CDATA[
703         pci_set_drvdata(pci, card);
704         dev++;
705         return 0;
706 ]]>
707             </programlisting>
708           </informalexample>
709
710           In the above, the card record is stored. This pointer is
711         used in the remove callback and power-management
712         callbacks, too. 
713         </para>
714       </section>
715     </section>
716
717     <section id="basic-flow-destructor">
718       <title>Destructor</title>
719       <para>
720         The destructor, remove callback, simply releases the card
721       instance. Then the ALSA middle layer will release all the
722       attached components automatically. 
723       </para>
724
725       <para>
726         It would be typically like the following:
727
728         <informalexample>
729           <programlisting>
730 <![CDATA[
731   static void __devexit snd_mychip_remove(struct pci_dev *pci)
732   {
733           snd_card_free(pci_get_drvdata(pci));
734           pci_set_drvdata(pci, NULL);
735   }
736 ]]>
737           </programlisting>
738         </informalexample>
739
740         The above code assumes that the card pointer is set to the PCI
741         driver data.
742       </para>
743     </section>
744
745     <section id="basic-flow-header-files">
746       <title>Header Files</title>
747       <para>
748         For the above example, at least the following include files
749       are necessary. 
750
751         <informalexample>
752           <programlisting>
753 <![CDATA[
754   #include <linux/init.h>
755   #include <linux/pci.h>
756   #include <linux/slab.h>
757   #include <sound/core.h>
758   #include <sound/initval.h>
759 ]]>
760           </programlisting>
761         </informalexample>
762
763         where the last one is necessary only when module options are
764       defined in the source file.  If the code is split into several
765       files, the files without module options don't need them.
766       </para>
767
768       <para>
769         In addition to these headers, you'll need
770       <filename>&lt;linux/interrupt.h&gt;</filename> for interrupt
771       handling, and <filename>&lt;asm/io.h&gt;</filename> for I/O
772       access. If you use the <function>mdelay()</function> or
773       <function>udelay()</function> functions, you'll need to include
774       <filename>&lt;linux/delay.h&gt;</filename> too. 
775       </para>
776
777       <para>
778       The ALSA interfaces like the PCM and control APIs are defined in other
779       <filename>&lt;sound/xxx.h&gt;</filename> header files.
780       They have to be included after
781       <filename>&lt;sound/core.h&gt;</filename>.
782       </para>
783
784     </section>
785   </chapter>
786
787
788 <!-- ****************************************************** -->
789 <!-- Management of Cards and Components  -->
790 <!-- ****************************************************** -->
791   <chapter id="card-management">
792     <title>Management of Cards and Components</title>
793
794     <section id="card-management-card-instance">
795       <title>Card Instance</title>
796       <para>
797       For each soundcard, a <quote>card</quote> record must be allocated.
798       </para>
799
800       <para>
801       A card record is the headquarters of the soundcard.  It manages
802       the whole list of devices (components) on the soundcard, such as
803       PCM, mixers, MIDI, synthesizer, and so on.  Also, the card
804       record holds the ID and the name strings of the card, manages
805       the root of proc files, and controls the power-management states
806       and hotplug disconnections.  The component list on the card
807       record is used to manage the correct release of resources at
808       destruction. 
809       </para>
810
811       <para>
812         As mentioned above, to create a card instance, call
813       <function>snd_card_create()</function>.
814
815         <informalexample>
816           <programlisting>
817 <![CDATA[
818   struct snd_card *card;
819   int err;
820   err = snd_card_create(index, id, module, extra_size, &card);
821 ]]>
822           </programlisting>
823         </informalexample>
824       </para>
825
826       <para>
827         The function takes five arguments, the card-index number, the
828         id string, the module pointer (usually
829         <constant>THIS_MODULE</constant>),
830         the size of extra-data space, and the pointer to return the
831         card instance.  The extra_size argument is used to
832         allocate card-&gt;private_data for the
833         chip-specific data.  Note that these data
834         are allocated by <function>snd_card_create()</function>.
835       </para>
836     </section>
837
838     <section id="card-management-component">
839       <title>Components</title>
840       <para>
841         After the card is created, you can attach the components
842       (devices) to the card instance. In an ALSA driver, a component is
843       represented as a struct <structname>snd_device</structname> object.
844       A component can be a PCM instance, a control interface, a raw
845       MIDI interface, etc.  Each such instance has one component
846       entry.
847       </para>
848
849       <para>
850         A component can be created via
851         <function>snd_device_new()</function> function. 
852
853         <informalexample>
854           <programlisting>
855 <![CDATA[
856   snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
857 ]]>
858           </programlisting>
859         </informalexample>
860       </para>
861
862       <para>
863         This takes the card pointer, the device-level
864       (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
865       callback pointers (<parameter>&amp;ops</parameter>). The
866       device-level defines the type of components and the order of
867       registration and de-registration.  For most components, the
868       device-level is already defined.  For a user-defined component,
869       you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
870       </para>
871
872       <para>
873       This function itself doesn't allocate the data space. The data
874       must be allocated manually beforehand, and its pointer is passed
875       as the argument. This pointer is used as the
876       (<parameter>chip</parameter> identifier in the above example)
877       for the instance. 
878       </para>
879
880       <para>
881         Each pre-defined ALSA component such as ac97 and pcm calls
882       <function>snd_device_new()</function> inside its
883       constructor. The destructor for each component is defined in the
884       callback pointers.  Hence, you don't need to take care of
885       calling a destructor for such a component.
886       </para>
887
888       <para>
889         If you wish to create your own component, you need to
890       set the destructor function to the dev_free callback in
891       the <parameter>ops</parameter>, so that it can be released
892       automatically via <function>snd_card_free()</function>.
893       The next example will show an implementation of chip-specific
894       data.
895       </para>
896     </section>
897
898     <section id="card-management-chip-specific">
899       <title>Chip-Specific Data</title>
900       <para>
901       Chip-specific information, e.g. the I/O port address, its
902       resource pointer, or the irq number, is stored in the
903       chip-specific record.
904
905         <informalexample>
906           <programlisting>
907 <![CDATA[
908   struct mychip {
909           ....
910   };
911 ]]>
912           </programlisting>
913         </informalexample>
914       </para>
915
916       <para>
917         In general, there are two ways of allocating the chip record.
918       </para>
919
920       <section id="card-management-chip-specific-snd-card-new">
921         <title>1. Allocating via <function>snd_card_create()</function>.</title>
922         <para>
923           As mentioned above, you can pass the extra-data-length
924           to the 4th argument of <function>snd_card_create()</function>, i.e.
925
926           <informalexample>
927             <programlisting>
928 <![CDATA[
929   err = snd_card_create(index[dev], id[dev], THIS_MODULE,
930                         sizeof(struct mychip), &card);
931 ]]>
932             </programlisting>
933           </informalexample>
934
935           struct <structname>mychip</structname> is the type of the chip record.
936         </para>
937
938         <para>
939           In return, the allocated record can be accessed as
940
941           <informalexample>
942             <programlisting>
943 <![CDATA[
944   struct mychip *chip = card->private_data;
945 ]]>
946             </programlisting>
947           </informalexample>
948
949           With this method, you don't have to allocate twice.
950           The record is released together with the card instance.
951         </para>
952       </section>
953
954       <section id="card-management-chip-specific-allocate-extra">
955         <title>2. Allocating an extra device.</title>
956
957         <para>
958           After allocating a card instance via
959           <function>snd_card_create()</function> (with
960           <constant>0</constant> on the 4th arg), call
961           <function>kzalloc()</function>. 
962
963           <informalexample>
964             <programlisting>
965 <![CDATA[
966   struct snd_card *card;
967   struct mychip *chip;
968   err = snd_card_create(index[dev], id[dev], THIS_MODULE, 0, &card);
969   .....
970   chip = kzalloc(sizeof(*chip), GFP_KERNEL);
971 ]]>
972             </programlisting>
973           </informalexample>
974         </para>
975
976         <para>
977           The chip record should have the field to hold the card
978           pointer at least, 
979
980           <informalexample>
981             <programlisting>
982 <![CDATA[
983   struct mychip {
984           struct snd_card *card;
985           ....
986   };
987 ]]>
988             </programlisting>
989           </informalexample>
990         </para>
991
992         <para>
993           Then, set the card pointer in the returned chip instance.
994
995           <informalexample>
996             <programlisting>
997 <![CDATA[
998   chip->card = card;
999 ]]>
1000             </programlisting>
1001           </informalexample>
1002         </para>
1003
1004         <para>
1005           Next, initialize the fields, and register this chip
1006           record as a low-level device with a specified
1007           <parameter>ops</parameter>, 
1008
1009           <informalexample>
1010             <programlisting>
1011 <![CDATA[
1012   static struct snd_device_ops ops = {
1013           .dev_free =        snd_mychip_dev_free,
1014   };
1015   ....
1016   snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1017 ]]>
1018             </programlisting>
1019           </informalexample>
1020
1021           <function>snd_mychip_dev_free()</function> is the
1022         device-destructor function, which will call the real
1023         destructor. 
1024         </para>
1025
1026         <para>
1027           <informalexample>
1028             <programlisting>
1029 <![CDATA[
1030   static int snd_mychip_dev_free(struct snd_device *device)
1031   {
1032           return snd_mychip_free(device->device_data);
1033   }
1034 ]]>
1035             </programlisting>
1036           </informalexample>
1037
1038           where <function>snd_mychip_free()</function> is the real destructor.
1039         </para>
1040       </section>
1041     </section>
1042
1043     <section id="card-management-registration">
1044       <title>Registration and Release</title>
1045       <para>
1046         After all components are assigned, register the card instance
1047       by calling <function>snd_card_register()</function>. Access
1048       to the device files is enabled at this point. That is, before
1049       <function>snd_card_register()</function> is called, the
1050       components are safely inaccessible from external side. If this
1051       call fails, exit the probe function after releasing the card via
1052       <function>snd_card_free()</function>. 
1053       </para>
1054
1055       <para>
1056         For releasing the card instance, you can call simply
1057       <function>snd_card_free()</function>. As mentioned earlier, all
1058       components are released automatically by this call. 
1059       </para>
1060
1061       <para>
1062         As further notes, the destructors (both
1063       <function>snd_mychip_dev_free</function> and
1064       <function>snd_mychip_free</function>) cannot be defined with
1065       the <parameter>__devexit</parameter> prefix, because they may be
1066       called from the constructor, too, at the false path. 
1067       </para>
1068
1069       <para>
1070       For a device which allows hotplugging, you can use
1071       <function>snd_card_free_when_closed</function>.  This one will
1072       postpone the destruction until all devices are closed.
1073       </para>
1074
1075     </section>
1076
1077   </chapter>
1078
1079
1080 <!-- ****************************************************** -->
1081 <!-- PCI Resource Management  -->
1082 <!-- ****************************************************** -->
1083   <chapter id="pci-resource">
1084     <title>PCI Resource Management</title>
1085
1086     <section id="pci-resource-example">
1087       <title>Full Code Example</title>
1088       <para>
1089         In this section, we'll complete the chip-specific constructor,
1090       destructor and PCI entries. Example code is shown first,
1091       below. 
1092
1093         <example>
1094           <title>PCI Resource Management Example</title>
1095           <programlisting>
1096 <![CDATA[
1097   struct mychip {
1098           struct snd_card *card;
1099           struct pci_dev *pci;
1100
1101           unsigned long port;
1102           int irq;
1103   };
1104
1105   static int snd_mychip_free(struct mychip *chip)
1106   {
1107           /* disable hardware here if any */
1108           .... /* (not implemented in this document) */
1109
1110           /* release the irq */
1111           if (chip->irq >= 0)
1112                   free_irq(chip->irq, chip);
1113           /* release the I/O ports & memory */
1114           pci_release_regions(chip->pci);
1115           /* disable the PCI entry */
1116           pci_disable_device(chip->pci);
1117           /* release the data */
1118           kfree(chip);
1119           return 0;
1120   }
1121
1122   /* chip-specific constructor */
1123   static int __devinit snd_mychip_create(struct snd_card *card,
1124                                          struct pci_dev *pci,
1125                                          struct mychip **rchip)
1126   {
1127           struct mychip *chip;
1128           int err;
1129           static struct snd_device_ops ops = {
1130                  .dev_free = snd_mychip_dev_free,
1131           };
1132
1133           *rchip = NULL;
1134
1135           /* initialize the PCI entry */
1136           err = pci_enable_device(pci);
1137           if (err < 0)
1138                   return err;
1139           /* check PCI availability (28bit DMA) */
1140           if (pci_set_dma_mask(pci, DMA_28BIT_MASK) < 0 ||
1141               pci_set_consistent_dma_mask(pci, DMA_28BIT_MASK) < 0) {
1142                   printk(KERN_ERR "error to set 28bit mask DMA\n");
1143                   pci_disable_device(pci);
1144                   return -ENXIO;
1145           }
1146
1147           chip = kzalloc(sizeof(*chip), GFP_KERNEL);
1148           if (chip == NULL) {
1149                   pci_disable_device(pci);
1150                   return -ENOMEM;
1151           }
1152
1153           /* initialize the stuff */
1154           chip->card = card;
1155           chip->pci = pci;
1156           chip->irq = -1;
1157
1158           /* (1) PCI resource allocation */
1159           err = pci_request_regions(pci, "My Chip");
1160           if (err < 0) {
1161                   kfree(chip);
1162                   pci_disable_device(pci);
1163                   return err;
1164           }
1165           chip->port = pci_resource_start(pci, 0);
1166           if (request_irq(pci->irq, snd_mychip_interrupt,
1167                           IRQF_SHARED, "My Chip", chip)) {
1168                   printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1169                   snd_mychip_free(chip);
1170                   return -EBUSY;
1171           }
1172           chip->irq = pci->irq;
1173
1174           /* (2) initialization of the chip hardware */
1175           .... /*   (not implemented in this document) */
1176
1177           err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1178           if (err < 0) {
1179                   snd_mychip_free(chip);
1180                   return err;
1181           }
1182
1183           snd_card_set_dev(card, &pci->dev);
1184
1185           *rchip = chip;
1186           return 0;
1187   }        
1188
1189   /* PCI IDs */
1190   static struct pci_device_id snd_mychip_ids[] = {
1191           { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1192             PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1193           ....
1194           { 0, }
1195   };
1196   MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1197
1198   /* pci_driver definition */
1199   static struct pci_driver driver = {
1200           .name = "My Own Chip",
1201           .id_table = snd_mychip_ids,
1202           .probe = snd_mychip_probe,
1203           .remove = __devexit_p(snd_mychip_remove),
1204   };
1205
1206   /* module initialization */
1207   static int __init alsa_card_mychip_init(void)
1208   {
1209           return pci_register_driver(&driver);
1210   }
1211
1212   /* module clean up */
1213   static void __exit alsa_card_mychip_exit(void)
1214   {
1215           pci_unregister_driver(&driver);
1216   }
1217
1218   module_init(alsa_card_mychip_init)
1219   module_exit(alsa_card_mychip_exit)
1220
1221   EXPORT_NO_SYMBOLS; /* for old kernels only */
1222 ]]>
1223           </programlisting>
1224         </example>
1225       </para>
1226     </section>
1227
1228     <section id="pci-resource-some-haftas">
1229       <title>Some Hafta's</title>
1230       <para>
1231         The allocation of PCI resources is done in the
1232       <function>probe()</function> function, and usually an extra
1233       <function>xxx_create()</function> function is written for this
1234       purpose.
1235       </para>
1236
1237       <para>
1238         In the case of PCI devices, you first have to call
1239       the <function>pci_enable_device()</function> function before
1240       allocating resources. Also, you need to set the proper PCI DMA
1241       mask to limit the accessed I/O range. In some cases, you might
1242       need to call <function>pci_set_master()</function> function,
1243       too.
1244       </para>
1245
1246       <para>
1247         Suppose the 28bit mask, and the code to be added would be like:
1248
1249         <informalexample>
1250           <programlisting>
1251 <![CDATA[
1252   err = pci_enable_device(pci);
1253   if (err < 0)
1254           return err;
1255   if (pci_set_dma_mask(pci, DMA_28BIT_MASK) < 0 ||
1256       pci_set_consistent_dma_mask(pci, DMA_28BIT_MASK) < 0) {
1257           printk(KERN_ERR "error to set 28bit mask DMA\n");
1258           pci_disable_device(pci);
1259           return -ENXIO;
1260   }
1261   
1262 ]]>
1263           </programlisting>
1264         </informalexample>
1265       </para>
1266     </section>
1267
1268     <section id="pci-resource-resource-allocation">
1269       <title>Resource Allocation</title>
1270       <para>
1271         The allocation of I/O ports and irqs is done via standard kernel
1272       functions. Unlike ALSA ver.0.5.x., there are no helpers for
1273       that. And these resources must be released in the destructor
1274       function (see below). Also, on ALSA 0.9.x, you don't need to
1275       allocate (pseudo-)DMA for PCI like in ALSA 0.5.x.
1276       </para>
1277
1278       <para>
1279         Now assume that the PCI device has an I/O port with 8 bytes
1280         and an interrupt. Then struct <structname>mychip</structname> will have the
1281         following fields:
1282
1283         <informalexample>
1284           <programlisting>
1285 <![CDATA[
1286   struct mychip {
1287           struct snd_card *card;
1288
1289           unsigned long port;
1290           int irq;
1291   };
1292 ]]>
1293           </programlisting>
1294         </informalexample>
1295       </para>
1296
1297       <para>
1298         For an I/O port (and also a memory region), you need to have
1299       the resource pointer for the standard resource management. For
1300       an irq, you have to keep only the irq number (integer). But you
1301       need to initialize this number as -1 before actual allocation,
1302       since irq 0 is valid. The port address and its resource pointer
1303       can be initialized as null by
1304       <function>kzalloc()</function> automatically, so you
1305       don't have to take care of resetting them. 
1306       </para>
1307
1308       <para>
1309         The allocation of an I/O port is done like this:
1310
1311         <informalexample>
1312           <programlisting>
1313 <![CDATA[
1314   err = pci_request_regions(pci, "My Chip");
1315   if (err < 0) { 
1316           kfree(chip);
1317           pci_disable_device(pci);
1318           return err;
1319   }
1320   chip->port = pci_resource_start(pci, 0);
1321 ]]>
1322           </programlisting>
1323         </informalexample>
1324       </para>
1325
1326       <para>
1327         <!-- obsolete -->
1328         It will reserve the I/O port region of 8 bytes of the given
1329       PCI device. The returned value, chip-&gt;res_port, is allocated
1330       via <function>kmalloc()</function> by
1331       <function>request_region()</function>. The pointer must be
1332       released via <function>kfree()</function>, but there is a
1333       problem with this. This issue will be explained later.
1334       </para>
1335
1336       <para>
1337         The allocation of an interrupt source is done like this:
1338
1339         <informalexample>
1340           <programlisting>
1341 <![CDATA[
1342   if (request_irq(pci->irq, snd_mychip_interrupt,
1343                   IRQF_SHARED, "My Chip", chip)) {
1344           printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1345           snd_mychip_free(chip);
1346           return -EBUSY;
1347   }
1348   chip->irq = pci->irq;
1349 ]]>
1350           </programlisting>
1351         </informalexample>
1352
1353         where <function>snd_mychip_interrupt()</function> is the
1354       interrupt handler defined <link
1355       linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1356       Note that chip-&gt;irq should be defined
1357       only when <function>request_irq()</function> succeeded.
1358       </para>
1359
1360       <para>
1361       On the PCI bus, interrupts can be shared. Thus,
1362       <constant>IRQF_SHARED</constant> is used as the interrupt flag of
1363       <function>request_irq()</function>. 
1364       </para>
1365
1366       <para>
1367         The last argument of <function>request_irq()</function> is the
1368       data pointer passed to the interrupt handler. Usually, the
1369       chip-specific record is used for that, but you can use what you
1370       like, too. 
1371       </para>
1372
1373       <para>
1374         I won't give details about the interrupt handler at this
1375         point, but at least its appearance can be explained now. The
1376         interrupt handler looks usually like the following: 
1377
1378         <informalexample>
1379           <programlisting>
1380 <![CDATA[
1381   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
1382   {
1383           struct mychip *chip = dev_id;
1384           ....
1385           return IRQ_HANDLED;
1386   }
1387 ]]>
1388           </programlisting>
1389         </informalexample>
1390       </para>
1391
1392       <para>
1393         Now let's write the corresponding destructor for the resources
1394       above. The role of destructor is simple: disable the hardware
1395       (if already activated) and release the resources. So far, we
1396       have no hardware part, so the disabling code is not written here. 
1397       </para>
1398
1399       <para>
1400         To release the resources, the <quote>check-and-release</quote>
1401         method is a safer way. For the interrupt, do like this: 
1402
1403         <informalexample>
1404           <programlisting>
1405 <![CDATA[
1406   if (chip->irq >= 0)
1407           free_irq(chip->irq, chip);
1408 ]]>
1409           </programlisting>
1410         </informalexample>
1411
1412         Since the irq number can start from 0, you should initialize
1413         chip-&gt;irq with a negative value (e.g. -1), so that you can
1414         check the validity of the irq number as above.
1415       </para>
1416
1417       <para>
1418         When you requested I/O ports or memory regions via
1419         <function>pci_request_region()</function> or
1420         <function>pci_request_regions()</function> like in this example,
1421         release the resource(s) using the corresponding function,
1422         <function>pci_release_region()</function> or
1423         <function>pci_release_regions()</function>.
1424
1425         <informalexample>
1426           <programlisting>
1427 <![CDATA[
1428   pci_release_regions(chip->pci);
1429 ]]>
1430           </programlisting>
1431         </informalexample>
1432       </para>
1433
1434       <para>
1435         When you requested manually via <function>request_region()</function>
1436         or <function>request_mem_region</function>, you can release it via
1437         <function>release_resource()</function>.  Suppose that you keep
1438         the resource pointer returned from <function>request_region()</function>
1439         in chip-&gt;res_port, the release procedure looks like:
1440
1441         <informalexample>
1442           <programlisting>
1443 <![CDATA[
1444   release_and_free_resource(chip->res_port);
1445 ]]>
1446           </programlisting>
1447         </informalexample>
1448       </para>
1449
1450       <para>
1451       Don't forget to call <function>pci_disable_device()</function>
1452       before the end.
1453       </para>
1454
1455       <para>
1456         And finally, release the chip-specific record.
1457
1458         <informalexample>
1459           <programlisting>
1460 <![CDATA[
1461   kfree(chip);
1462 ]]>
1463           </programlisting>
1464         </informalexample>
1465       </para>
1466
1467       <para>
1468       Again, remember that you cannot
1469       use the <parameter>__devexit</parameter> prefix for this destructor. 
1470       </para>
1471
1472       <para>
1473       We didn't implement the hardware disabling part in the above.
1474       If you need to do this, please note that the destructor may be
1475       called even before the initialization of the chip is completed.
1476       It would be better to have a flag to skip hardware disabling
1477       if the hardware was not initialized yet.
1478       </para>
1479
1480       <para>
1481       When the chip-data is assigned to the card using
1482       <function>snd_device_new()</function> with
1483       <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is 
1484       called at the last.  That is, it is assured that all other
1485       components like PCMs and controls have already been released.
1486       You don't have to stop PCMs, etc. explicitly, but just
1487       call low-level hardware stopping.
1488       </para>
1489
1490       <para>
1491         The management of a memory-mapped region is almost as same as
1492         the management of an I/O port. You'll need three fields like
1493         the following: 
1494
1495         <informalexample>
1496           <programlisting>
1497 <![CDATA[
1498   struct mychip {
1499           ....
1500           unsigned long iobase_phys;
1501           void __iomem *iobase_virt;
1502   };
1503 ]]>
1504           </programlisting>
1505         </informalexample>
1506
1507         and the allocation would be like below:
1508
1509         <informalexample>
1510           <programlisting>
1511 <![CDATA[
1512   if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1513           kfree(chip);
1514           return err;
1515   }
1516   chip->iobase_phys = pci_resource_start(pci, 0);
1517   chip->iobase_virt = ioremap_nocache(chip->iobase_phys,
1518                                       pci_resource_len(pci, 0));
1519 ]]>
1520           </programlisting>
1521         </informalexample>
1522         
1523         and the corresponding destructor would be:
1524
1525         <informalexample>
1526           <programlisting>
1527 <![CDATA[
1528   static int snd_mychip_free(struct mychip *chip)
1529   {
1530           ....
1531           if (chip->iobase_virt)
1532                   iounmap(chip->iobase_virt);
1533           ....
1534           pci_release_regions(chip->pci);
1535           ....
1536   }
1537 ]]>
1538           </programlisting>
1539         </informalexample>
1540       </para>
1541
1542     </section>
1543
1544     <section id="pci-resource-device-struct">
1545       <title>Registration of Device Struct</title>
1546       <para>
1547         At some point, typically after calling <function>snd_device_new()</function>,
1548         you need to register the struct <structname>device</structname> of the chip
1549         you're handling for udev and co.  ALSA provides a macro for compatibility with
1550         older kernels.  Simply call like the following:
1551         <informalexample>
1552           <programlisting>
1553 <![CDATA[
1554   snd_card_set_dev(card, &pci->dev);
1555 ]]>
1556           </programlisting>
1557         </informalexample>
1558         so that it stores the PCI's device pointer to the card.  This will be
1559         referred by ALSA core functions later when the devices are registered.
1560       </para>
1561       <para>
1562         In the case of non-PCI, pass the proper device struct pointer of the BUS
1563         instead.  (In the case of legacy ISA without PnP, you don't have to do
1564         anything.)
1565       </para>
1566     </section>
1567
1568     <section id="pci-resource-entries">
1569       <title>PCI Entries</title>
1570       <para>
1571         So far, so good. Let's finish the missing PCI
1572       stuff. At first, we need a
1573       <structname>pci_device_id</structname> table for this
1574       chipset. It's a table of PCI vendor/device ID number, and some
1575       masks. 
1576       </para>
1577
1578       <para>
1579         For example,
1580
1581         <informalexample>
1582           <programlisting>
1583 <![CDATA[
1584   static struct pci_device_id snd_mychip_ids[] = {
1585           { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1586             PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1587           ....
1588           { 0, }
1589   };
1590   MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1591 ]]>
1592           </programlisting>
1593         </informalexample>
1594       </para>
1595
1596       <para>
1597         The first and second fields of
1598       the <structname>pci_device_id</structname> structure are the vendor and
1599       device IDs. If you have no reason to filter the matching
1600       devices, you can leave the remaining fields as above. The last
1601       field of the <structname>pci_device_id</structname> struct contains
1602       private data for this entry. You can specify any value here, for
1603       example, to define specific operations for supported device IDs.
1604       Such an example is found in the intel8x0 driver. 
1605       </para>
1606
1607       <para>
1608         The last entry of this list is the terminator. You must
1609       specify this all-zero entry. 
1610       </para>
1611
1612       <para>
1613         Then, prepare the <structname>pci_driver</structname> record:
1614
1615         <informalexample>
1616           <programlisting>
1617 <![CDATA[
1618   static struct pci_driver driver = {
1619           .name = "My Own Chip",
1620           .id_table = snd_mychip_ids,
1621           .probe = snd_mychip_probe,
1622           .remove = __devexit_p(snd_mychip_remove),
1623   };
1624 ]]>
1625           </programlisting>
1626         </informalexample>
1627       </para>
1628
1629       <para>
1630         The <structfield>probe</structfield> and
1631       <structfield>remove</structfield> functions have already
1632       been defined in the previous sections.
1633       The <structfield>remove</structfield> function should
1634       be defined with the 
1635       <function>__devexit_p()</function> macro, so that it's not
1636       defined for built-in (and non-hot-pluggable) case. The
1637       <structfield>name</structfield> 
1638       field is the name string of this device. Note that you must not
1639       use a slash <quote>/</quote> in this string. 
1640       </para>
1641
1642       <para>
1643         And at last, the module entries:
1644
1645         <informalexample>
1646           <programlisting>
1647 <![CDATA[
1648   static int __init alsa_card_mychip_init(void)
1649   {
1650           return pci_register_driver(&driver);
1651   }
1652
1653   static void __exit alsa_card_mychip_exit(void)
1654   {
1655           pci_unregister_driver(&driver);
1656   }
1657
1658   module_init(alsa_card_mychip_init)
1659   module_exit(alsa_card_mychip_exit)
1660 ]]>
1661           </programlisting>
1662         </informalexample>
1663       </para>
1664
1665       <para>
1666         Note that these module entries are tagged with
1667       <parameter>__init</parameter> and 
1668       <parameter>__exit</parameter> prefixes, not
1669       <parameter>__devinit</parameter> nor
1670       <parameter>__devexit</parameter>.
1671       </para>
1672
1673       <para>
1674         Oh, one thing was forgotten. If you have no exported symbols,
1675         you need to declare it in 2.2 or 2.4 kernels (it's not necessary in 2.6 kernels).
1676
1677         <informalexample>
1678           <programlisting>
1679 <![CDATA[
1680   EXPORT_NO_SYMBOLS;
1681 ]]>
1682           </programlisting>
1683         </informalexample>
1684
1685         That's all!
1686       </para>
1687     </section>
1688   </chapter>
1689
1690
1691 <!-- ****************************************************** -->
1692 <!-- PCM Interface  -->
1693 <!-- ****************************************************** -->
1694   <chapter id="pcm-interface">
1695     <title>PCM Interface</title>
1696
1697     <section id="pcm-interface-general">
1698       <title>General</title>
1699       <para>
1700         The PCM middle layer of ALSA is quite powerful and it is only
1701       necessary for each driver to implement the low-level functions
1702       to access its hardware.
1703       </para>
1704
1705       <para>
1706         For accessing to the PCM layer, you need to include
1707       <filename>&lt;sound/pcm.h&gt;</filename> first. In addition,
1708       <filename>&lt;sound/pcm_params.h&gt;</filename> might be needed
1709       if you access to some functions related with hw_param. 
1710       </para>
1711
1712       <para>
1713         Each card device can have up to four pcm instances. A pcm
1714       instance corresponds to a pcm device file. The limitation of
1715       number of instances comes only from the available bit size of
1716       the Linux's device numbers. Once when 64bit device number is
1717       used, we'll have more pcm instances available. 
1718       </para>
1719
1720       <para>
1721         A pcm instance consists of pcm playback and capture streams,
1722       and each pcm stream consists of one or more pcm substreams. Some
1723       soundcards support multiple playback functions. For example,
1724       emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1725       each open, a free substream is (usually) automatically chosen
1726       and opened. Meanwhile, when only one substream exists and it was
1727       already opened, the successful open will either block
1728       or error with <constant>EAGAIN</constant> according to the
1729       file open mode. But you don't have to care about such details in your
1730       driver. The PCM middle layer will take care of such work.
1731       </para>
1732     </section>
1733
1734     <section id="pcm-interface-example">
1735       <title>Full Code Example</title>
1736       <para>
1737       The example code below does not include any hardware access
1738       routines but shows only the skeleton, how to build up the PCM
1739       interfaces.
1740
1741         <example>
1742           <title>PCM Example Code</title>
1743           <programlisting>
1744 <![CDATA[
1745   #include <sound/pcm.h>
1746   ....
1747
1748   /* hardware definition */
1749   static struct snd_pcm_hardware snd_mychip_playback_hw = {
1750           .info = (SNDRV_PCM_INFO_MMAP |
1751                    SNDRV_PCM_INFO_INTERLEAVED |
1752                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
1753                    SNDRV_PCM_INFO_MMAP_VALID),
1754           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
1755           .rates =            SNDRV_PCM_RATE_8000_48000,
1756           .rate_min =         8000,
1757           .rate_max =         48000,
1758           .channels_min =     2,
1759           .channels_max =     2,
1760           .buffer_bytes_max = 32768,
1761           .period_bytes_min = 4096,
1762           .period_bytes_max = 32768,
1763           .periods_min =      1,
1764           .periods_max =      1024,
1765   };
1766
1767   /* hardware definition */
1768   static struct snd_pcm_hardware snd_mychip_capture_hw = {
1769           .info = (SNDRV_PCM_INFO_MMAP |
1770                    SNDRV_PCM_INFO_INTERLEAVED |
1771                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
1772                    SNDRV_PCM_INFO_MMAP_VALID),
1773           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
1774           .rates =            SNDRV_PCM_RATE_8000_48000,
1775           .rate_min =         8000,
1776           .rate_max =         48000,
1777           .channels_min =     2,
1778           .channels_max =     2,
1779           .buffer_bytes_max = 32768,
1780           .period_bytes_min = 4096,
1781           .period_bytes_max = 32768,
1782           .periods_min =      1,
1783           .periods_max =      1024,
1784   };
1785
1786   /* open callback */
1787   static int snd_mychip_playback_open(struct snd_pcm_substream *substream)
1788   {
1789           struct mychip *chip = snd_pcm_substream_chip(substream);
1790           struct snd_pcm_runtime *runtime = substream->runtime;
1791
1792           runtime->hw = snd_mychip_playback_hw;
1793           /* more hardware-initialization will be done here */
1794           ....
1795           return 0;
1796   }
1797
1798   /* close callback */
1799   static int snd_mychip_playback_close(struct snd_pcm_substream *substream)
1800   {
1801           struct mychip *chip = snd_pcm_substream_chip(substream);
1802           /* the hardware-specific codes will be here */
1803           ....
1804           return 0;
1805
1806   }
1807
1808   /* open callback */
1809   static int snd_mychip_capture_open(struct snd_pcm_substream *substream)
1810   {
1811           struct mychip *chip = snd_pcm_substream_chip(substream);
1812           struct snd_pcm_runtime *runtime = substream->runtime;
1813
1814           runtime->hw = snd_mychip_capture_hw;
1815           /* more hardware-initialization will be done here */
1816           ....
1817           return 0;
1818   }
1819
1820   /* close callback */
1821   static int snd_mychip_capture_close(struct snd_pcm_substream *substream)
1822   {
1823           struct mychip *chip = snd_pcm_substream_chip(substream);
1824           /* the hardware-specific codes will be here */
1825           ....
1826           return 0;
1827
1828   }
1829
1830   /* hw_params callback */
1831   static int snd_mychip_pcm_hw_params(struct snd_pcm_substream *substream,
1832                                struct snd_pcm_hw_params *hw_params)
1833   {
1834           return snd_pcm_lib_malloc_pages(substream,
1835                                      params_buffer_bytes(hw_params));
1836   }
1837
1838   /* hw_free callback */
1839   static int snd_mychip_pcm_hw_free(struct snd_pcm_substream *substream)
1840   {
1841           return snd_pcm_lib_free_pages(substream);
1842   }
1843
1844   /* prepare callback */
1845   static int snd_mychip_pcm_prepare(struct snd_pcm_substream *substream)
1846   {
1847           struct mychip *chip = snd_pcm_substream_chip(substream);
1848           struct snd_pcm_runtime *runtime = substream->runtime;
1849
1850           /* set up the hardware with the current configuration
1851            * for example...
1852            */
1853           mychip_set_sample_format(chip, runtime->format);
1854           mychip_set_sample_rate(chip, runtime->rate);
1855           mychip_set_channels(chip, runtime->channels);
1856           mychip_set_dma_setup(chip, runtime->dma_addr,
1857                                chip->buffer_size,
1858                                chip->period_size);
1859           return 0;
1860   }
1861
1862   /* trigger callback */
1863   static int snd_mychip_pcm_trigger(struct snd_pcm_substream *substream,
1864                                     int cmd)
1865   {
1866           switch (cmd) {
1867           case SNDRV_PCM_TRIGGER_START:
1868                   /* do something to start the PCM engine */
1869                   ....
1870                   break;
1871           case SNDRV_PCM_TRIGGER_STOP:
1872                   /* do something to stop the PCM engine */
1873                   ....
1874                   break;
1875           default:
1876                   return -EINVAL;
1877           }
1878   }
1879
1880   /* pointer callback */
1881   static snd_pcm_uframes_t
1882   snd_mychip_pcm_pointer(struct snd_pcm_substream *substream)
1883   {
1884           struct mychip *chip = snd_pcm_substream_chip(substream);
1885           unsigned int current_ptr;
1886
1887           /* get the current hardware pointer */
1888           current_ptr = mychip_get_hw_pointer(chip);
1889           return current_ptr;
1890   }
1891
1892   /* operators */
1893   static struct snd_pcm_ops snd_mychip_playback_ops = {
1894           .open =        snd_mychip_playback_open,
1895           .close =       snd_mychip_playback_close,
1896           .ioctl =       snd_pcm_lib_ioctl,
1897           .hw_params =   snd_mychip_pcm_hw_params,
1898           .hw_free =     snd_mychip_pcm_hw_free,
1899           .prepare =     snd_mychip_pcm_prepare,
1900           .trigger =     snd_mychip_pcm_trigger,
1901           .pointer =     snd_mychip_pcm_pointer,
1902   };
1903
1904   /* operators */
1905   static struct snd_pcm_ops snd_mychip_capture_ops = {
1906           .open =        snd_mychip_capture_open,
1907           .close =       snd_mychip_capture_close,
1908           .ioctl =       snd_pcm_lib_ioctl,
1909           .hw_params =   snd_mychip_pcm_hw_params,
1910           .hw_free =     snd_mychip_pcm_hw_free,
1911           .prepare =     snd_mychip_pcm_prepare,
1912           .trigger =     snd_mychip_pcm_trigger,
1913           .pointer =     snd_mychip_pcm_pointer,
1914   };
1915
1916   /*
1917    *  definitions of capture are omitted here...
1918    */
1919
1920   /* create a pcm device */
1921   static int __devinit snd_mychip_new_pcm(struct mychip *chip)
1922   {
1923           struct snd_pcm *pcm;
1924           int err;
1925
1926           err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);
1927           if (err < 0) 
1928                   return err;
1929           pcm->private_data = chip;
1930           strcpy(pcm->name, "My Chip");
1931           chip->pcm = pcm;
1932           /* set operators */
1933           snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1934                           &snd_mychip_playback_ops);
1935           snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
1936                           &snd_mychip_capture_ops);
1937           /* pre-allocation of buffers */
1938           /* NOTE: this may fail */
1939           snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
1940                                                 snd_dma_pci_data(chip->pci),
1941                                                 64*1024, 64*1024);
1942           return 0;
1943   }
1944 ]]>
1945           </programlisting>
1946         </example>
1947       </para>
1948     </section>
1949
1950     <section id="pcm-interface-constructor">
1951       <title>Constructor</title>
1952       <para>
1953         A pcm instance is allocated by the <function>snd_pcm_new()</function>
1954       function. It would be better to create a constructor for pcm,
1955       namely, 
1956
1957         <informalexample>
1958           <programlisting>
1959 <![CDATA[
1960   static int __devinit snd_mychip_new_pcm(struct mychip *chip)
1961   {
1962           struct snd_pcm *pcm;
1963           int err;
1964
1965           err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);
1966           if (err < 0) 
1967                   return err;
1968           pcm->private_data = chip;
1969           strcpy(pcm->name, "My Chip");
1970           chip->pcm = pcm;
1971           ....
1972           return 0;
1973   }
1974 ]]>
1975           </programlisting>
1976         </informalexample>
1977       </para>
1978
1979       <para>
1980         The <function>snd_pcm_new()</function> function takes four
1981       arguments. The first argument is the card pointer to which this
1982       pcm is assigned, and the second is the ID string. 
1983       </para>
1984
1985       <para>
1986         The third argument (<parameter>index</parameter>, 0 in the
1987       above) is the index of this new pcm. It begins from zero. If
1988       you create more than one pcm instances, specify the
1989       different numbers in this argument. For example,
1990       <parameter>index</parameter> = 1 for the second PCM device.  
1991       </para>
1992
1993       <para>
1994         The fourth and fifth arguments are the number of substreams
1995       for playback and capture, respectively. Here 1 is used for
1996       both arguments. When no playback or capture substreams are available,
1997       pass 0 to the corresponding argument.
1998       </para>
1999
2000       <para>
2001         If a chip supports multiple playbacks or captures, you can
2002       specify more numbers, but they must be handled properly in
2003       open/close, etc. callbacks.  When you need to know which
2004       substream you are referring to, then it can be obtained from
2005       struct <structname>snd_pcm_substream</structname> data passed to each callback
2006       as follows: 
2007
2008         <informalexample>
2009           <programlisting>
2010 <![CDATA[
2011   struct snd_pcm_substream *substream;
2012   int index = substream->number;
2013 ]]>
2014           </programlisting>
2015         </informalexample>
2016       </para>
2017
2018       <para>
2019         After the pcm is created, you need to set operators for each
2020         pcm stream. 
2021
2022         <informalexample>
2023           <programlisting>
2024 <![CDATA[
2025   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2026                   &snd_mychip_playback_ops);
2027   snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2028                   &snd_mychip_capture_ops);
2029 ]]>
2030           </programlisting>
2031         </informalexample>
2032       </para>
2033
2034       <para>
2035         The operators are defined typically like this:
2036
2037         <informalexample>
2038           <programlisting>
2039 <![CDATA[
2040   static struct snd_pcm_ops snd_mychip_playback_ops = {
2041           .open =        snd_mychip_pcm_open,
2042           .close =       snd_mychip_pcm_close,
2043           .ioctl =       snd_pcm_lib_ioctl,
2044           .hw_params =   snd_mychip_pcm_hw_params,
2045           .hw_free =     snd_mychip_pcm_hw_free,
2046           .prepare =     snd_mychip_pcm_prepare,
2047           .trigger =     snd_mychip_pcm_trigger,
2048           .pointer =     snd_mychip_pcm_pointer,
2049   };
2050 ]]>
2051           </programlisting>
2052         </informalexample>
2053
2054         All the callbacks are described in the
2055         <link linkend="pcm-interface-operators"><citetitle>
2056         Operators</citetitle></link> subsection.
2057       </para>
2058
2059       <para>
2060         After setting the operators, you probably will want to
2061         pre-allocate the buffer. For the pre-allocation, simply call
2062         the following: 
2063
2064         <informalexample>
2065           <programlisting>
2066 <![CDATA[
2067   snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2068                                         snd_dma_pci_data(chip->pci),
2069                                         64*1024, 64*1024);
2070 ]]>
2071           </programlisting>
2072         </informalexample>
2073
2074         It will allocate a buffer up to 64kB as default.
2075       Buffer management details will be described in the later section <link
2076       linkend="buffer-and-memory"><citetitle>Buffer and Memory
2077       Management</citetitle></link>. 
2078       </para>
2079
2080       <para>
2081         Additionally, you can set some extra information for this pcm
2082         in pcm-&gt;info_flags.
2083         The available values are defined as
2084         <constant>SNDRV_PCM_INFO_XXX</constant> in
2085         <filename>&lt;sound/asound.h&gt;</filename>, which is used for
2086         the hardware definition (described later). When your soundchip
2087         supports only half-duplex, specify like this: 
2088
2089         <informalexample>
2090           <programlisting>
2091 <![CDATA[
2092   pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2093 ]]>
2094           </programlisting>
2095         </informalexample>
2096       </para>
2097     </section>
2098
2099     <section id="pcm-interface-destructor">
2100       <title>... And the Destructor?</title>
2101       <para>
2102         The destructor for a pcm instance is not always
2103       necessary. Since the pcm device will be released by the middle
2104       layer code automatically, you don't have to call the destructor
2105       explicitly.
2106       </para>
2107
2108       <para>
2109         The destructor would be necessary if you created
2110         special records internally and needed to release them. In such a
2111         case, set the destructor function to
2112         pcm-&gt;private_free: 
2113
2114         <example>
2115           <title>PCM Instance with a Destructor</title>
2116           <programlisting>
2117 <![CDATA[
2118   static void mychip_pcm_free(struct snd_pcm *pcm)
2119   {
2120           struct mychip *chip = snd_pcm_chip(pcm);
2121           /* free your own data */
2122           kfree(chip->my_private_pcm_data);
2123           /* do what you like else */
2124           ....
2125   }
2126
2127   static int __devinit snd_mychip_new_pcm(struct mychip *chip)
2128   {
2129           struct snd_pcm *pcm;
2130           ....
2131           /* allocate your own data */
2132           chip->my_private_pcm_data = kmalloc(...);
2133           /* set the destructor */
2134           pcm->private_data = chip;
2135           pcm->private_free = mychip_pcm_free;
2136           ....
2137   }
2138 ]]>
2139           </programlisting>
2140         </example>
2141       </para>
2142     </section>
2143
2144     <section id="pcm-interface-runtime">
2145       <title>Runtime Pointer - The Chest of PCM Information</title>
2146         <para>
2147           When the PCM substream is opened, a PCM runtime instance is
2148         allocated and assigned to the substream. This pointer is
2149         accessible via <constant>substream-&gt;runtime</constant>.
2150         This runtime pointer holds most information you need
2151         to control the PCM: the copy of hw_params and sw_params configurations, the buffer
2152         pointers, mmap records, spinlocks, etc.
2153         </para>
2154
2155         <para>
2156         The definition of runtime instance is found in
2157         <filename>&lt;sound/pcm.h&gt;</filename>.  Here are
2158        the contents of this file:
2159           <informalexample>
2160             <programlisting>
2161 <![CDATA[
2162 struct _snd_pcm_runtime {
2163         /* -- Status -- */
2164         struct snd_pcm_substream *trigger_master;
2165         snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2166         int overrange;
2167         snd_pcm_uframes_t avail_max;
2168         snd_pcm_uframes_t hw_ptr_base;  /* Position at buffer restart */
2169         snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2170
2171         /* -- HW params -- */
2172         snd_pcm_access_t access;        /* access mode */
2173         snd_pcm_format_t format;        /* SNDRV_PCM_FORMAT_* */
2174         snd_pcm_subformat_t subformat;  /* subformat */
2175         unsigned int rate;              /* rate in Hz */
2176         unsigned int channels;          /* channels */
2177         snd_pcm_uframes_t period_size;  /* period size */
2178         unsigned int periods;           /* periods */
2179         snd_pcm_uframes_t buffer_size;  /* buffer size */
2180         unsigned int tick_time;         /* tick time */
2181         snd_pcm_uframes_t min_align;    /* Min alignment for the format */
2182         size_t byte_align;
2183         unsigned int frame_bits;
2184         unsigned int sample_bits;
2185         unsigned int info;
2186         unsigned int rate_num;
2187         unsigned int rate_den;
2188
2189         /* -- SW params -- */
2190         struct timespec tstamp_mode;    /* mmap timestamp is updated */
2191         unsigned int period_step;
2192         unsigned int sleep_min;         /* min ticks to sleep */
2193         snd_pcm_uframes_t start_threshold;
2194         snd_pcm_uframes_t stop_threshold;
2195         snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2196                                                 noise is nearest than this */
2197         snd_pcm_uframes_t silence_size; /* Silence filling size */
2198         snd_pcm_uframes_t boundary;     /* pointers wrap point */
2199
2200         snd_pcm_uframes_t silenced_start;
2201         snd_pcm_uframes_t silenced_size;
2202
2203         snd_pcm_sync_id_t sync;         /* hardware synchronization ID */
2204
2205         /* -- mmap -- */
2206         volatile struct snd_pcm_mmap_status *status;
2207         volatile struct snd_pcm_mmap_control *control;
2208         atomic_t mmap_count;
2209
2210         /* -- locking / scheduling -- */
2211         spinlock_t lock;
2212         wait_queue_head_t sleep;
2213         struct timer_list tick_timer;
2214         struct fasync_struct *fasync;
2215
2216         /* -- private section -- */
2217         void *private_data;
2218         void (*private_free)(struct snd_pcm_runtime *runtime);
2219
2220         /* -- hardware description -- */
2221         struct snd_pcm_hardware hw;
2222         struct snd_pcm_hw_constraints hw_constraints;
2223
2224         /* -- interrupt callbacks -- */
2225         void (*transfer_ack_begin)(struct snd_pcm_substream *substream);
2226         void (*transfer_ack_end)(struct snd_pcm_substream *substream);
2227
2228         /* -- timer -- */
2229         unsigned int timer_resolution;  /* timer resolution */
2230
2231         /* -- DMA -- */           
2232         unsigned char *dma_area;        /* DMA area */
2233         dma_addr_t dma_addr;            /* physical bus address (not accessible from main CPU) */
2234         size_t dma_bytes;               /* size of DMA area */
2235
2236         struct snd_dma_buffer *dma_buffer_p;    /* allocated buffer */
2237
2238 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2239         /* -- OSS things -- */
2240         struct snd_pcm_oss_runtime oss;
2241 #endif
2242 };
2243 ]]>
2244             </programlisting>
2245           </informalexample>
2246         </para>
2247
2248         <para>
2249           For the operators (callbacks) of each sound driver, most of
2250         these records are supposed to be read-only.  Only the PCM
2251         middle-layer changes / updates them.  The exceptions are
2252         the hardware description (hw), interrupt callbacks
2253         (transfer_ack_xxx), DMA buffer information, and the private
2254         data.  Besides, if you use the standard buffer allocation
2255         method via <function>snd_pcm_lib_malloc_pages()</function>,
2256         you don't need to set the DMA buffer information by yourself.
2257         </para>
2258
2259         <para>
2260         In the sections below, important records are explained.
2261         </para>
2262
2263         <section id="pcm-interface-runtime-hw">
2264         <title>Hardware Description</title>
2265         <para>
2266           The hardware descriptor (struct <structname>snd_pcm_hardware</structname>)
2267         contains the definitions of the fundamental hardware
2268         configuration.  Above all, you'll need to define this in
2269         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2270         the open callback</citetitle></link>.
2271         Note that the runtime instance holds the copy of the
2272         descriptor, not the pointer to the existing descriptor.  That
2273         is, in the open callback, you can modify the copied descriptor
2274         (<constant>runtime-&gt;hw</constant>) as you need.  For example, if the maximum
2275         number of channels is 1 only on some chip models, you can
2276         still use the same hardware descriptor and change the
2277         channels_max later:
2278           <informalexample>
2279             <programlisting>
2280 <![CDATA[
2281           struct snd_pcm_runtime *runtime = substream->runtime;
2282           ...
2283           runtime->hw = snd_mychip_playback_hw; /* common definition */
2284           if (chip->model == VERY_OLD_ONE)
2285                   runtime->hw.channels_max = 1;
2286 ]]>
2287             </programlisting>
2288           </informalexample>
2289         </para>
2290
2291         <para>
2292           Typically, you'll have a hardware descriptor as below:
2293           <informalexample>
2294             <programlisting>
2295 <![CDATA[
2296   static struct snd_pcm_hardware snd_mychip_playback_hw = {
2297           .info = (SNDRV_PCM_INFO_MMAP |
2298                    SNDRV_PCM_INFO_INTERLEAVED |
2299                    SNDRV_PCM_INFO_BLOCK_TRANSFER |
2300                    SNDRV_PCM_INFO_MMAP_VALID),
2301           .formats =          SNDRV_PCM_FMTBIT_S16_LE,
2302           .rates =            SNDRV_PCM_RATE_8000_48000,
2303           .rate_min =         8000,
2304           .rate_max =         48000,
2305           .channels_min =     2,
2306           .channels_max =     2,
2307           .buffer_bytes_max = 32768,
2308           .period_bytes_min = 4096,
2309           .period_bytes_max = 32768,
2310           .periods_min =      1,
2311           .periods_max =      1024,
2312   };
2313 ]]>
2314             </programlisting>
2315           </informalexample>
2316         </para>
2317
2318         <para>
2319         <itemizedlist>
2320         <listitem><para>
2321           The <structfield>info</structfield> field contains the type and
2322         capabilities of this pcm. The bit flags are defined in
2323         <filename>&lt;sound/asound.h&gt;</filename> as
2324         <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2325         have to specify whether the mmap is supported and which
2326         interleaved format is supported.
2327         When the is supported, add the
2328         <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2329         hardware supports the interleaved or the non-interleaved
2330         formats, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2331         <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2332         be set, respectively. If both are supported, you can set both,
2333         too. 
2334         </para>
2335
2336         <para>
2337           In the above example, <constant>MMAP_VALID</constant> and
2338         <constant>BLOCK_TRANSFER</constant> are specified for the OSS mmap
2339         mode. Usually both are set. Of course,
2340         <constant>MMAP_VALID</constant> is set only if the mmap is
2341         really supported. 
2342         </para>
2343
2344         <para>
2345           The other possible flags are
2346         <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2347         <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2348         <constant>PAUSE</constant> bit means that the pcm supports the
2349         <quote>pause</quote> operation, while the
2350         <constant>RESUME</constant> bit means that the pcm supports
2351         the full <quote>suspend/resume</quote> operation.
2352         If the <constant>PAUSE</constant> flag is set,
2353         the <structfield>trigger</structfield> callback below
2354         must handle the corresponding (pause push/release) commands.
2355         The suspend/resume trigger commands can be defined even without
2356         the <constant>RESUME</constant> flag.  See <link
2357         linkend="power-management"><citetitle>
2358         Power Management</citetitle></link> section for details.
2359         </para>
2360
2361         <para>
2362           When the PCM substreams can be synchronized (typically,
2363         synchronized start/stop of a playback and a capture streams),
2364         you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2365         too.  In this case, you'll need to check the linked-list of
2366         PCM substreams in the trigger callback.  This will be
2367         described in the later section.
2368         </para>
2369         </listitem>
2370
2371         <listitem>
2372         <para>
2373           <structfield>formats</structfield> field contains the bit-flags
2374         of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2375         If the hardware supports more than one format, give all or'ed
2376         bits.  In the example above, the signed 16bit little-endian
2377         format is specified.
2378         </para>
2379         </listitem>
2380
2381         <listitem>
2382         <para>
2383         <structfield>rates</structfield> field contains the bit-flags of
2384         supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2385         When the chip supports continuous rates, pass
2386         <constant>CONTINUOUS</constant> bit additionally.
2387         The pre-defined rate bits are provided only for typical
2388         rates. If your chip supports unconventional rates, you need to add
2389         the <constant>KNOT</constant> bit and set up the hardware
2390         constraint manually (explained later).
2391         </para>
2392         </listitem>
2393
2394         <listitem>
2395         <para>
2396         <structfield>rate_min</structfield> and
2397         <structfield>rate_max</structfield> define the minimum and
2398         maximum sample rate.  This should correspond somehow to
2399         <structfield>rates</structfield> bits.
2400         </para>
2401         </listitem>
2402
2403         <listitem>
2404         <para>
2405         <structfield>channel_min</structfield> and
2406         <structfield>channel_max</structfield> 
2407         define, as you might already expected, the minimum and maximum
2408         number of channels.
2409         </para>
2410         </listitem>
2411
2412         <listitem>
2413         <para>
2414         <structfield>buffer_bytes_max</structfield> defines the
2415         maximum buffer size in bytes.  There is no
2416         <structfield>buffer_bytes_min</structfield> field, since
2417         it can be calculated from the minimum period size and the
2418         minimum number of periods.
2419         Meanwhile, <structfield>period_bytes_min</structfield> and
2420         define the minimum and maximum size of the period in bytes.
2421         <structfield>periods_max</structfield> and
2422         <structfield>periods_min</structfield> define the maximum and
2423         minimum number of periods in the buffer.
2424         </para>
2425
2426         <para>
2427         The <quote>period</quote> is a term that corresponds to
2428         a fragment in the OSS world. The period defines the size at
2429         which a PCM interrupt is generated. This size strongly
2430         depends on the hardware. 
2431         Generally, the smaller period size will give you more
2432         interrupts, that is, more controls. 
2433         In the case of capture, this size defines the input latency.
2434         On the other hand, the whole buffer size defines the
2435         output latency for the playback direction.
2436         </para>
2437         </listitem>
2438
2439         <listitem>
2440         <para>
2441         There is also a field <structfield>fifo_size</structfield>.
2442         This specifies the size of the hardware FIFO, but currently it
2443         is neither used in the driver nor in the alsa-lib.  So, you
2444         can ignore this field.
2445         </para>
2446         </listitem>
2447         </itemizedlist>
2448         </para>
2449         </section>
2450
2451         <section id="pcm-interface-runtime-config">
2452         <title>PCM Configurations</title>
2453         <para>
2454         Ok, let's go back again to the PCM runtime records.
2455         The most frequently referred records in the runtime instance are
2456         the PCM configurations.
2457         The PCM configurations are stored in the runtime instance
2458         after the application sends <type>hw_params</type> data via
2459         alsa-lib.  There are many fields copied from hw_params and
2460         sw_params structs.  For example,
2461         <structfield>format</structfield> holds the format type
2462         chosen by the application.  This field contains the enum value
2463         <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2464         </para>
2465
2466         <para>
2467         One thing to be noted is that the configured buffer and period
2468         sizes are stored in <quote>frames</quote> in the runtime.
2469         In the ALSA world, 1 frame = channels * samples-size.
2470         For conversion between frames and bytes, you can use the
2471         <function>frames_to_bytes()</function> and
2472           <function>bytes_to_frames()</function> helper functions. 
2473           <informalexample>
2474             <programlisting>
2475 <![CDATA[
2476   period_bytes = frames_to_bytes(runtime, runtime->period_size);
2477 ]]>
2478             </programlisting>
2479           </informalexample>
2480         </para>
2481
2482         <para>
2483         Also, many software parameters (sw_params) are
2484         stored in frames, too.  Please check the type of the field.
2485         <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2486         integer while <type>snd_pcm_sframes_t</type> is for the frames
2487         as signed integer.
2488         </para>
2489         </section>
2490
2491         <section id="pcm-interface-runtime-dma">
2492         <title>DMA Buffer Information</title>
2493         <para>
2494         The DMA buffer is defined by the following four fields,
2495         <structfield>dma_area</structfield>,
2496         <structfield>dma_addr</structfield>,
2497         <structfield>dma_bytes</structfield> and
2498         <structfield>dma_private</structfield>.
2499         The <structfield>dma_area</structfield> holds the buffer
2500         pointer (the logical address).  You can call
2501         <function>memcpy</function> from/to 
2502         this pointer.  Meanwhile, <structfield>dma_addr</structfield>
2503         holds the physical address of the buffer.  This field is
2504         specified only when the buffer is a linear buffer.
2505         <structfield>dma_bytes</structfield> holds the size of buffer
2506         in bytes.  <structfield>dma_private</structfield> is used for
2507         the ALSA DMA allocator.
2508         </para>
2509
2510         <para>
2511         If you use a standard ALSA function,
2512         <function>snd_pcm_lib_malloc_pages()</function>, for
2513         allocating the buffer, these fields are set by the ALSA middle
2514         layer, and you should <emphasis>not</emphasis> change them by
2515         yourself.  You can read them but not write them.
2516         On the other hand, if you want to allocate the buffer by
2517         yourself, you'll need to manage it in hw_params callback.
2518         At least, <structfield>dma_bytes</structfield> is mandatory.
2519         <structfield>dma_area</structfield> is necessary when the
2520         buffer is mmapped.  If your driver doesn't support mmap, this
2521         field is not necessary.  <structfield>dma_addr</structfield>
2522         is also optional.  You can use
2523         <structfield>dma_private</structfield> as you like, too.
2524         </para>
2525         </section>
2526
2527         <section id="pcm-interface-runtime-status">
2528         <title>Running Status</title>
2529         <para>
2530         The running status can be referred via <constant>runtime-&gt;status</constant>.
2531         This is the pointer to the struct <structname>snd_pcm_mmap_status</structname>
2532         record.  For example, you can get the current DMA hardware
2533         pointer via <constant>runtime-&gt;status-&gt;hw_ptr</constant>.
2534         </para>
2535
2536         <para>
2537         The DMA application pointer can be referred via
2538         <constant>runtime-&gt;control</constant>, which points to the
2539         struct <structname>snd_pcm_mmap_control</structname> record.
2540         However, accessing directly to this value is not recommended.
2541         </para>
2542         </section>
2543
2544         <section id="pcm-interface-runtime-private">
2545         <title>Private Data</title> 
2546         <para>
2547         You can allocate a record for the substream and store it in
2548         <constant>runtime-&gt;private_data</constant>.  Usually, this
2549         is done in
2550         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2551         the open callback</citetitle></link>.
2552         Don't mix this with <constant>pcm-&gt;private_data</constant>.
2553         The <constant>pcm-&gt;private_data</constant> usually points to the
2554         chip instance assigned statically at the creation of PCM, while the 
2555         <constant>runtime-&gt;private_data</constant> points to a dynamic
2556         data structure created at the PCM open callback.
2557
2558           <informalexample>
2559             <programlisting>
2560 <![CDATA[
2561   static int snd_xxx_open(struct snd_pcm_substream *substream)
2562   {
2563           struct my_pcm_data *data;
2564           ....
2565           data = kmalloc(sizeof(*data), GFP_KERNEL);
2566           substream->runtime->private_data = data;
2567           ....
2568   }
2569 ]]>
2570             </programlisting>
2571           </informalexample>
2572         </para>
2573
2574         <para>
2575           The allocated object must be released in
2576         <link linkend="pcm-interface-operators-open-callback"><citetitle>
2577         the close callback</citetitle></link>.
2578         </para>
2579         </section>
2580
2581         <section id="pcm-interface-runtime-intr">
2582         <title>Interrupt Callbacks</title>
2583         <para>
2584         The field <structfield>transfer_ack_begin</structfield> and
2585         <structfield>transfer_ack_end</structfield> are called at
2586         the beginning and at the end of
2587         <function>snd_pcm_period_elapsed()</function>, respectively. 
2588         </para>
2589         </section>
2590
2591     </section>
2592
2593     <section id="pcm-interface-operators">
2594       <title>Operators</title>
2595       <para>
2596         OK, now let me give details about each pcm callback
2597       (<parameter>ops</parameter>). In general, every callback must
2598       return 0 if successful, or a negative error number
2599       such as <constant>-EINVAL</constant>. To choose an appropriate
2600       error number, it is advised to check what value other parts of
2601       the kernel return when the same kind of request fails.
2602       </para>
2603
2604       <para>
2605         The callback function takes at least the argument with
2606         <structname>snd_pcm_substream</structname> pointer. To retrieve
2607         the chip record from the given substream instance, you can use the
2608         following macro. 
2609
2610         <informalexample>
2611           <programlisting>
2612 <![CDATA[
2613   int xxx() {
2614           struct mychip *chip = snd_pcm_substream_chip(substream);
2615           ....
2616   }
2617 ]]>
2618           </programlisting>
2619         </informalexample>
2620
2621         The macro reads <constant>substream-&gt;private_data</constant>,
2622         which is a copy of <constant>pcm-&gt;private_data</constant>.
2623         You can override the former if you need to assign different data
2624         records per PCM substream.  For example, the cmi8330 driver assigns
2625         different private_data for playback and capture directions,
2626         because it uses two different codecs (SB- and AD-compatible) for
2627         different directions.
2628       </para>
2629
2630       <section id="pcm-interface-operators-open-callback">
2631         <title>open callback</title>
2632         <para>
2633           <informalexample>
2634             <programlisting>
2635 <![CDATA[
2636   static int snd_xxx_open(struct snd_pcm_substream *substream);
2637 ]]>
2638             </programlisting>
2639           </informalexample>
2640
2641           This is called when a pcm substream is opened.
2642         </para>
2643
2644         <para>
2645           At least, here you have to initialize the runtime-&gt;hw
2646           record. Typically, this is done by like this: 
2647
2648           <informalexample>
2649             <programlisting>
2650 <![CDATA[
2651   static int snd_xxx_open(struct snd_pcm_substream *substream)
2652   {
2653           struct mychip *chip = snd_pcm_substream_chip(substream);
2654           struct snd_pcm_runtime *runtime = substream->runtime;
2655
2656           runtime->hw = snd_mychip_playback_hw;
2657           return 0;
2658   }
2659 ]]>
2660             </programlisting>
2661           </informalexample>
2662
2663           where <parameter>snd_mychip_playback_hw</parameter> is the
2664           pre-defined hardware description.
2665         </para>
2666
2667         <para>
2668         You can allocate a private data in this callback, as described
2669         in <link linkend="pcm-interface-runtime-private"><citetitle>
2670         Private Data</citetitle></link> section.
2671         </para>
2672
2673         <para>
2674         If the hardware configuration needs more constraints, set the
2675         hardware constraints here, too.
2676         See <link linkend="pcm-interface-constraints"><citetitle>
2677         Constraints</citetitle></link> for more details.
2678         </para>
2679       </section>
2680
2681       <section id="pcm-interface-operators-close-callback">
2682         <title>close callback</title>
2683         <para>
2684           <informalexample>
2685             <programlisting>
2686 <![CDATA[
2687   static int snd_xxx_close(struct snd_pcm_substream *substream);
2688 ]]>
2689             </programlisting>
2690           </informalexample>
2691
2692           Obviously, this is called when a pcm substream is closed.
2693         </para>
2694
2695         <para>
2696           Any private instance for a pcm substream allocated in the
2697           open callback will be released here. 
2698
2699           <informalexample>
2700             <programlisting>
2701 <![CDATA[
2702   static int snd_xxx_close(struct snd_pcm_substream *substream)
2703   {
2704           ....
2705           kfree(substream->runtime->private_data);
2706           ....
2707   }
2708 ]]>
2709             </programlisting>
2710           </informalexample>
2711         </para>
2712       </section>
2713
2714       <section id="pcm-interface-operators-ioctl-callback">
2715         <title>ioctl callback</title>
2716         <para>
2717           This is used for any special call to pcm ioctls. But
2718         usually you can pass a generic ioctl callback, 
2719         <function>snd_pcm_lib_ioctl</function>.
2720         </para>
2721       </section>
2722
2723       <section id="pcm-interface-operators-hw-params-callback">
2724         <title>hw_params callback</title>
2725         <para>
2726           <informalexample>
2727             <programlisting>
2728 <![CDATA[
2729   static int snd_xxx_hw_params(struct snd_pcm_substream *substream,
2730                                struct snd_pcm_hw_params *hw_params);
2731 ]]>
2732             </programlisting>
2733           </informalexample>
2734         </para>
2735
2736         <para>
2737           This is called when the hardware parameter
2738         (<structfield>hw_params</structfield>) is set
2739         up by the application, 
2740         that is, once when the buffer size, the period size, the
2741         format, etc. are defined for the pcm substream. 
2742         </para>
2743
2744         <para>
2745           Many hardware setups should be done in this callback,
2746         including the allocation of buffers. 
2747         </para>
2748
2749         <para>
2750           Parameters to be initialized are retrieved by
2751           <function>params_xxx()</function> macros. To allocate
2752           buffer, you can call a helper function, 
2753
2754           <informalexample>
2755             <programlisting>
2756 <![CDATA[
2757   snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2758 ]]>
2759             </programlisting>
2760           </informalexample>
2761
2762           <function>snd_pcm_lib_malloc_pages()</function> is available
2763           only when the DMA buffers have been pre-allocated.
2764           See the section <link
2765           linkend="buffer-and-memory-buffer-types"><citetitle>
2766           Buffer Types</citetitle></link> for more details.
2767         </para>
2768
2769         <para>
2770           Note that this and <structfield>prepare</structfield> callbacks
2771         may be called multiple times per initialization.
2772         For example, the OSS emulation may
2773         call these callbacks at each change via its ioctl. 
2774         </para>
2775
2776         <para>
2777           Thus, you need to be careful not to allocate the same buffers
2778         many times, which will lead to memory leaks!  Calling the
2779         helper function above many times is OK. It will release the
2780         previous buffer automatically when it was already allocated. 
2781         </para>
2782
2783         <para>
2784           Another note is that this callback is non-atomic
2785         (schedulable). This is important, because the
2786         <structfield>trigger</structfield> callback 
2787         is atomic (non-schedulable). That is, mutexes or any
2788         schedule-related functions are not available in
2789         <structfield>trigger</structfield> callback.
2790         Please see the subsection
2791         <link linkend="pcm-interface-atomicity"><citetitle>
2792         Atomicity</citetitle></link> for details.
2793         </para>
2794       </section>
2795
2796       <section id="pcm-interface-operators-hw-free-callback">
2797         <title>hw_free callback</title>
2798         <para>
2799           <informalexample>
2800             <programlisting>
2801 <![CDATA[
2802   static int snd_xxx_hw_free(struct snd_pcm_substream *substream);
2803 ]]>
2804             </programlisting>
2805           </informalexample>
2806         </para>
2807
2808         <para>
2809           This is called to release the resources allocated via
2810           <structfield>hw_params</structfield>. For example, releasing the
2811           buffer via 
2812           <function>snd_pcm_lib_malloc_pages()</function> is done by
2813           calling the following: 
2814
2815           <informalexample>
2816             <programlisting>
2817 <![CDATA[
2818   snd_pcm_lib_free_pages(substream);
2819 ]]>
2820             </programlisting>
2821           </informalexample>
2822         </para>
2823
2824         <para>
2825           This function is always called before the close callback is called.
2826           Also, the callback may be called multiple times, too.
2827           Keep track whether the resource was already released. 
2828         </para>
2829       </section>
2830
2831       <section id="pcm-interface-operators-prepare-callback">
2832        <title>prepare callback</title>
2833         <para>
2834           <informalexample>
2835             <programlisting>
2836 <![CDATA[
2837   static int snd_xxx_prepare(struct snd_pcm_substream *substream);
2838 ]]>
2839             </programlisting>
2840           </informalexample>
2841         </para>
2842
2843         <para>
2844           This callback is called when the pcm is
2845         <quote>prepared</quote>. You can set the format type, sample
2846         rate, etc. here. The difference from
2847         <structfield>hw_params</structfield> is that the 
2848         <structfield>prepare</structfield> callback will be called each
2849         time 
2850         <function>snd_pcm_prepare()</function> is called, i.e. when
2851         recovering after underruns, etc. 
2852         </para>
2853
2854         <para>
2855         Note that this callback is now non-atomic.
2856         You can use schedule-related functions safely in this callback.
2857         </para>
2858
2859         <para>
2860           In this and the following callbacks, you can refer to the
2861         values via the runtime record,
2862         substream-&gt;runtime.
2863         For example, to get the current
2864         rate, format or channels, access to
2865         runtime-&gt;rate,
2866         runtime-&gt;format or
2867         runtime-&gt;channels, respectively. 
2868         The physical address of the allocated buffer is set to
2869         runtime-&gt;dma_area.  The buffer and period sizes are
2870         in runtime-&gt;buffer_size and runtime-&gt;period_size,
2871         respectively.
2872         </para>
2873
2874         <para>
2875           Be careful that this callback will be called many times at
2876         each setup, too. 
2877         </para>
2878       </section>
2879
2880       <section id="pcm-interface-operators-trigger-callback">
2881         <title>trigger callback</title>
2882         <para>
2883           <informalexample>
2884             <programlisting>
2885 <![CDATA[
2886   static int snd_xxx_trigger(struct snd_pcm_substream *substream, int cmd);
2887 ]]>
2888             </programlisting>
2889           </informalexample>
2890
2891           This is called when the pcm is started, stopped or paused.
2892         </para>
2893
2894         <para>
2895           Which action is specified in the second argument,
2896           <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
2897           <filename>&lt;sound/pcm.h&gt;</filename>. At least,
2898           the <constant>START</constant> and <constant>STOP</constant>
2899           commands must be defined in this callback. 
2900
2901           <informalexample>
2902             <programlisting>
2903 <![CDATA[
2904   switch (cmd) {
2905   case SNDRV_PCM_TRIGGER_START:
2906           /* do something to start the PCM engine */
2907           break;
2908   case SNDRV_PCM_TRIGGER_STOP:
2909           /* do something to stop the PCM engine */
2910           break;
2911   default:
2912           return -EINVAL;
2913   }
2914 ]]>
2915             </programlisting>
2916           </informalexample>
2917         </para>
2918
2919         <para>
2920           When the pcm supports the pause operation (given in the info
2921         field of the hardware table), the <constant>PAUSE_PUSE</constant>
2922         and <constant>PAUSE_RELEASE</constant> commands must be
2923         handled here, too. The former is the command to pause the pcm,
2924         and the latter to restart the pcm again. 
2925         </para>
2926
2927         <para>
2928           When the pcm supports the suspend/resume operation,
2929         regardless of full or partial suspend/resume support,
2930         the <constant>SUSPEND</constant> and <constant>RESUME</constant>
2931         commands must be handled, too.
2932         These commands are issued when the power-management status is
2933         changed.  Obviously, the <constant>SUSPEND</constant> and
2934         <constant>RESUME</constant> commands
2935         suspend and resume the pcm substream, and usually, they
2936         are identical to the <constant>STOP</constant> and
2937         <constant>START</constant> commands, respectively.
2938           See the <link linkend="power-management"><citetitle>
2939         Power Management</citetitle></link> section for details.
2940         </para>
2941
2942         <para>
2943           As mentioned, this callback is atomic.  You cannot call
2944           functions which may sleep.
2945           The trigger callback should be as minimal as possible,
2946           just really triggering the DMA.  The other stuff should be
2947           initialized hw_params and prepare callbacks properly
2948           beforehand.
2949         </para>
2950       </section>
2951
2952       <section id="pcm-interface-operators-pointer-callback">
2953         <title>pointer callback</title>
2954         <para>
2955           <informalexample>
2956             <programlisting>
2957 <![CDATA[
2958   static snd_pcm_uframes_t snd_xxx_pointer(struct snd_pcm_substream *substream)
2959 ]]>
2960             </programlisting>
2961           </informalexample>
2962
2963           This callback is called when the PCM middle layer inquires
2964         the current hardware position on the buffer. The position must
2965         be returned in frames,
2966         ranging from 0 to buffer_size - 1.
2967         </para>
2968
2969         <para>
2970           This is called usually from the buffer-update routine in the
2971         pcm middle layer, which is invoked when
2972         <function>snd_pcm_period_elapsed()</function> is called in the
2973         interrupt routine. Then the pcm middle layer updates the
2974         position and calculates the available space, and wakes up the
2975         sleeping poll threads, etc. 
2976         </para>
2977
2978         <para>
2979           This callback is also atomic.
2980         </para>
2981       </section>
2982
2983       <section id="pcm-interface-operators-copy-silence">
2984         <title>copy and silence callbacks</title>
2985         <para>
2986           These callbacks are not mandatory, and can be omitted in
2987         most cases. These callbacks are used when the hardware buffer
2988         cannot be in the normal memory space. Some chips have their
2989         own buffer on the hardware which is not mappable. In such a
2990         case, you have to transfer the data manually from the memory
2991         buffer to the hardware buffer. Or, if the buffer is
2992         non-contiguous on both physical and virtual memory spaces,
2993         these callbacks must be defined, too. 
2994         </para>
2995
2996         <para>
2997           If these two callbacks are defined, copy and set-silence
2998         operations are done by them. The detailed will be described in
2999         the later section <link
3000         linkend="buffer-and-memory"><citetitle>Buffer and Memory
3001         Management</citetitle></link>. 
3002         </para>
3003       </section>
3004
3005       <section id="pcm-interface-operators-ack">
3006         <title>ack callback</title>
3007         <para>
3008           This callback is also not mandatory. This callback is called
3009         when the appl_ptr is updated in read or write operations.
3010         Some drivers like emu10k1-fx and cs46xx need to track the
3011         current appl_ptr for the internal buffer, and this callback
3012         is useful only for such a purpose.
3013         </para>
3014         <para>
3015           This callback is atomic.
3016         </para>
3017       </section>
3018
3019       <section id="pcm-interface-operators-page-callback">
3020         <title>page callback</title>
3021
3022         <para>
3023           This callback is optional too. This callback is used
3024         mainly for non-contiguous buffers. The mmap calls this
3025         callback to get the page address. Some examples will be
3026         explained in the later section <link
3027         linkend="buffer-and-memory"><citetitle>Buffer and Memory
3028         Management</citetitle></link>, too. 
3029         </para>
3030       </section>
3031     </section>
3032
3033     <section id="pcm-interface-interrupt-handler">
3034       <title>Interrupt Handler</title>
3035       <para>
3036         The rest of pcm stuff is the PCM interrupt handler. The
3037       role of PCM interrupt handler in the sound driver is to update
3038       the buffer position and to tell the PCM middle layer when the
3039       buffer position goes across the prescribed period size. To
3040       inform this, call the <function>snd_pcm_period_elapsed()</function>
3041       function. 
3042       </para>
3043
3044       <para>
3045         There are several types of sound chips to generate the interrupts.
3046       </para>
3047
3048       <section id="pcm-interface-interrupt-handler-boundary">
3049         <title>Interrupts at the period (fragment) boundary</title>
3050         <para>
3051           This is the most frequently found type:  the hardware
3052         generates an interrupt at each period boundary.
3053         In this case, you can call
3054         <function>snd_pcm_period_elapsed()</function> at each 
3055         interrupt. 
3056         </para>
3057
3058         <para>
3059           <function>snd_pcm_period_elapsed()</function> takes the
3060         substream pointer as its argument. Thus, you need to keep the
3061         substream pointer accessible from the chip instance. For
3062         example, define substream field in the chip record to hold the
3063         current running substream pointer, and set the pointer value
3064         at open callback (and reset at close callback). 
3065         </para>
3066
3067         <para>
3068           If you acquire a spinlock in the interrupt handler, and the
3069         lock is used in other pcm callbacks, too, then you have to
3070         release the lock before calling
3071         <function>snd_pcm_period_elapsed()</function>, because
3072         <function>snd_pcm_period_elapsed()</function> calls other pcm
3073         callbacks inside. 
3074         </para>
3075
3076         <para>
3077           Typical code would be like:
3078
3079           <example>
3080             <title>Interrupt Handler Case #1</title>
3081             <programlisting>
3082 <![CDATA[
3083   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
3084   {
3085           struct mychip *chip = dev_id;
3086           spin_lock(&chip->lock);
3087           ....
3088           if (pcm_irq_invoked(chip)) {
3089                   /* call updater, unlock before it */
3090                   spin_unlock(&chip->lock);
3091                   snd_pcm_period_elapsed(chip->substream);
3092                   spin_lock(&chip->lock);
3093                   /* acknowledge the interrupt if necessary */
3094           }
3095           ....
3096           spin_unlock(&chip->lock);
3097           return IRQ_HANDLED;
3098   }
3099 ]]>
3100             </programlisting>
3101           </example>
3102         </para>
3103       </section>
3104
3105       <section id="pcm-interface-interrupt-handler-timer">
3106         <title>High frequency timer interrupts</title>
3107         <para>
3108         This happense when the hardware doesn't generate interrupts
3109         at the period boundary but issues timer interrupts at a fixed
3110         timer rate (e.g. es1968 or ymfpci drivers). 
3111         In this case, you need to check the current hardware
3112         position and accumulate the processed sample length at each
3113         interrupt.  When the accumulated size exceeds the period
3114         size, call 
3115         <function>snd_pcm_period_elapsed()</function> and reset the
3116         accumulator. 
3117         </para>
3118
3119         <para>
3120           Typical code would be like the following.
3121
3122           <example>
3123             <title>Interrupt Handler Case #2</title>
3124             <programlisting>
3125 <![CDATA[
3126   static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
3127   {
3128           struct mychip *chip = dev_id;
3129           spin_lock(&chip->lock);
3130           ....
3131           if (pcm_irq_invoked(chip)) {
3132                   unsigned int last_ptr, size;
3133                   /* get the current hardware pointer (in frames) */
3134                   last_ptr = get_hw_ptr(chip);
3135                   /* calculate the processed frames since the
3136                    * last update
3137                    */
3138                   if (last_ptr < chip->last_ptr)
3139                           size = runtime->buffer_size + last_ptr 
3140                                    - chip->last_ptr; 
3141                   else
3142                           size = last_ptr - chip->last_ptr;
3143                   /* remember the last updated point */
3144                   chip->last_ptr = last_ptr;
3145                   /* accumulate the size */
3146                   chip->size += size;
3147                   /* over the period boundary? */
3148                   if (chip->size >= runtime->period_size) {
3149                           /* reset the accumulator */
3150                           chip->size %= runtime->period_size;
3151                           /* call updater */
3152                           spin_unlock(&chip->lock);
3153                           snd_pcm_period_elapsed(substream);
3154                           spin_lock(&chip->lock);
3155                   }
3156                   /* acknowledge the interrupt if necessary */
3157           }
3158           ....
3159           spin_unlock(&chip->lock);
3160           return IRQ_HANDLED;
3161   }
3162 ]]>
3163             </programlisting>
3164           </example>
3165         </para>
3166       </section>
3167
3168       <section id="pcm-interface-interrupt-handler-both">
3169         <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3170         <para>
3171           In both cases, even if more than one period are elapsed, you
3172         don't have to call
3173         <function>snd_pcm_period_elapsed()</function> many times. Call
3174         only once. And the pcm layer will check the current hardware
3175         pointer and update to the latest status. 
3176         </para>
3177       </section>
3178     </section>
3179
3180     <section id="pcm-interface-atomicity">
3181       <title>Atomicity</title>
3182       <para>
3183       One of the most important (and thus difficult to debug) problems
3184       in kernel programming are race conditions.
3185       In the Linux kernel, they are usually avoided via spin-locks, mutexes
3186       or semaphores.  In general, if a race condition can happen
3187       in an interrupt handler, it has to be managed atomically, and you
3188       have to use a spinlock to protect the critical session. If the
3189       critical section is not in interrupt handler code and
3190       if taking a relatively long time to execute is acceptable, you
3191       should use mutexes or semaphores instead.
3192       </para>
3193
3194       <para>
3195       As already seen, some pcm callbacks are atomic and some are
3196       not.  For example, the <parameter>hw_params</parameter> callback is
3197       non-atomic, while <parameter>trigger</parameter> callback is
3198       atomic.  This means, the latter is called already in a spinlock
3199       held by the PCM middle layer. Please take this atomicity into
3200       account when you choose a locking scheme in the callbacks.
3201       </para>
3202
3203       <para>
3204       In the atomic callbacks, you cannot use functions which may call
3205       <function>schedule</function> or go to
3206       <function>sleep</function>.  Semaphores and mutexes can sleep,
3207       and hence they cannot be used inside the atomic callbacks
3208       (e.g. <parameter>trigger</parameter> callback).
3209       To implement some delay in such a callback, please use
3210       <function>udelay()</function> or <function>mdelay()</function>.
3211       </para>
3212
3213       <para>
3214       All three atomic callbacks (trigger, pointer, and ack) are
3215       called with local interrupts disabled.
3216       </para>
3217
3218     </section>
3219     <section id="pcm-interface-constraints">
3220       <title>Constraints</title>
3221       <para>
3222         If your chip supports unconventional sample rates, or only the
3223       limited samples, you need to set a constraint for the
3224       condition. 
3225       </para>
3226
3227       <para>
3228         For example, in order to restrict the sample rates in the some
3229         supported values, use
3230         <function>snd_pcm_hw_constraint_list()</function>.
3231         You need to call this function in the open callback.
3232
3233         <example>
3234           <title>Example of Hardware Constraints</title>
3235           <programlisting>
3236 <![CDATA[
3237   static unsigned int rates[] =
3238           {4000, 10000, 22050, 44100};
3239   static struct snd_pcm_hw_constraint_list constraints_rates = {
3240           .count = ARRAY_SIZE(rates),
3241           .list = rates,
3242           .mask = 0,
3243   };
3244
3245   static int snd_mychip_pcm_open(struct snd_pcm_substream *substream)
3246   {
3247           int err;
3248           ....
3249           err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3250                                            SNDRV_PCM_HW_PARAM_RATE,
3251                                            &constraints_rates);
3252           if (err < 0)
3253                   return err;
3254           ....
3255   }
3256 ]]>
3257           </programlisting>
3258         </example>
3259       </para>
3260
3261       <para>
3262         There are many different constraints.
3263         Look at <filename>sound/pcm.h</filename> for a complete list.
3264         You can even define your own constraint rules.
3265         For example, let's suppose my_chip can manage a substream of 1 channel
3266         if and only if the format is S16_LE, otherwise it supports any format
3267         specified in the <structname>snd_pcm_hardware</structname> structure (or in any
3268         other constraint_list). You can build a rule like this:
3269
3270         <example>
3271           <title>Example of Hardware Constraints for Channels</title>
3272           <programlisting>
3273 <![CDATA[
3274   static int hw_rule_format_by_channels(struct snd_pcm_hw_params *params,
3275                                         struct snd_pcm_hw_rule *rule)
3276   {
3277           struct snd_interval *c = hw_param_interval(params,
3278                 SNDRV_PCM_HW_PARAM_CHANNELS);
3279           struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3280           struct snd_mask fmt;
3281
3282           snd_mask_any(&fmt);    /* Init the struct */
3283           if (c->min < 2) {
3284                   fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3285                   return snd_mask_refine(f, &fmt);
3286           }
3287           return 0;
3288   }
3289 ]]>
3290           </programlisting>
3291         </example>
3292       </para>
3293  
3294       <para>
3295         Then you need to call this function to add your rule:
3296
3297        <informalexample>
3298          <programlisting>
3299 <![CDATA[
3300   snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3301                       hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3302                       -1);
3303 ]]>
3304           </programlisting>
3305         </informalexample>
3306       </para>
3307
3308       <para>
3309         The rule function is called when an application sets the number of
3310         channels. But an application can set the format before the number of
3311         channels. Thus you also need to define the inverse rule:
3312
3313        <example>
3314          <title>Example of Hardware Constraints for Channels</title>
3315          <programlisting>
3316 <![CDATA[
3317   static int hw_rule_channels_by_format(struct snd_pcm_hw_params *params,
3318                                         struct snd_pcm_hw_rule *rule)
3319   {
3320           struct snd_interval *c = hw_param_interval(params,
3321                         SNDRV_PCM_HW_PARAM_CHANNELS);
3322           struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3323           struct snd_interval ch;
3324
3325           snd_interval_any(&ch);
3326           if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3327                   ch.min = ch.max = 1;
3328                   ch.integer = 1;
3329                   return snd_interval_refine(c, &ch);
3330           }
3331           return 0;
3332   }
3333 ]]>
3334           </programlisting>
3335         </example>
3336       </para>
3337
3338       <para>
3339       ...and in the open callback:
3340        <informalexample>
3341          <programlisting>
3342 <![CDATA[
3343   snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3344                       hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3345                       -1);
3346 ]]>
3347           </programlisting>
3348         </informalexample>
3349       </para>
3350
3351       <para>
3352         I won't give more details here, rather I
3353         would like to say, <quote>Luke, use the source.</quote>
3354       </para>
3355     </section>
3356
3357   </chapter>
3358
3359
3360 <!-- ****************************************************** -->
3361 <!-- Control Interface  -->
3362 <!-- ****************************************************** -->
3363   <chapter id="control-interface">
3364     <title>Control Interface</title>
3365
3366     <section id="control-interface-general">
3367       <title>General</title>
3368       <para>
3369         The control interface is used widely for many switches,
3370       sliders, etc. which are accessed from user-space. Its most
3371       important use is the mixer interface. In other words, since ALSA
3372       0.9.x, all the mixer stuff is implemented on the control kernel API.
3373       </para>
3374
3375       <para>
3376         ALSA has a well-defined AC97 control module. If your chip
3377       supports only the AC97 and nothing else, you can skip this
3378       section. 
3379       </para>
3380
3381       <para>
3382         The control API is defined in
3383       <filename>&lt;sound/control.h&gt;</filename>.
3384       Include this file if you want to add your own controls.
3385       </para>
3386     </section>
3387
3388     <section id="control-interface-definition">
3389       <title>Definition of Controls</title>
3390       <para>
3391         To create a new control, you need to define the
3392         following three
3393       callbacks: <structfield>info</structfield>,
3394       <structfield>get</structfield> and
3395       <structfield>put</structfield>. Then, define a
3396       struct <structname>snd_kcontrol_new</structname> record, such as: 
3397
3398         <example>
3399           <title>Definition of a Control</title>
3400           <programlisting>
3401 <![CDATA[
3402   static struct snd_kcontrol_new my_control __devinitdata = {
3403           .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3404           .name = "PCM Playback Switch",
3405           .index = 0,
3406           .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3407           .private_value = 0xffff,
3408           .info = my_control_info,
3409           .get = my_control_get,
3410           .put = my_control_put
3411   };
3412 ]]>
3413           </programlisting>
3414         </example>
3415       </para>
3416
3417       <para>
3418         Most likely the control is created via
3419       <function>snd_ctl_new1()</function>, and in such a case, you can
3420       add the <parameter>__devinitdata</parameter> prefix to the
3421       definition as above. 
3422       </para>
3423
3424       <para>
3425         The <structfield>iface</structfield> field specifies the control
3426       type, <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>, which
3427       is usually <constant>MIXER</constant>.
3428       Use <constant>CARD</constant> for global controls that are not
3429       logically part of the mixer.
3430       If the control is closely associated with some specific device on
3431       the sound card, use <constant>HWDEP</constant>,
3432       <constant>PCM</constant>, <constant>RAWMIDI</constant>,
3433       <constant>TIMER</constant>, or <constant>SEQUENCER</constant>, and
3434       specify the device number with the
3435       <structfield>device</structfield> and
3436       <structfield>subdevice</structfield> fields.
3437       </para>
3438
3439       <para>
3440         The <structfield>name</structfield> is the name identifier
3441       string. Since ALSA 0.9.x, the control name is very important,
3442       because its role is classified from its name. There are
3443       pre-defined standard control names. The details are described in
3444       the <link linkend="control-interface-control-names"><citetitle>
3445       Control Names</citetitle></link> subsection.
3446       </para>
3447
3448       <para>
3449         The <structfield>index</structfield> field holds the index number
3450       of this control. If there are several different controls with
3451       the same name, they can be distinguished by the index
3452       number. This is the case when 
3453       several codecs exist on the card. If the index is zero, you can
3454       omit the definition above. 
3455       </para>
3456
3457       <para>
3458