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