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