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