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