1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">
4 <?dbhtml filename="index.html">
6 <!-- ****************************************************** -->
8 <!-- ****************************************************** -->
10 <title>Writing an ALSA Driver</title>
12 <firstname>Takashi</firstname>
13 <surname>Iwai</surname>
16 <email>tiwai@suse.de</email>
21 <date>Mar. 6, 2004</date>
22 <edition>0.3.1</edition>
26 This document describes how to write an ALSA (Advanced Linux
27 Sound Architecture) driver.
33 Copyright (c) 2002-2004 Takashi Iwai <email>tiwai@suse.de</email>
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.
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
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,
61 <!-- ****************************************************** -->
63 <!-- ****************************************************** -->
64 <preface id="preface">
65 <title>Preface</title>
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
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.
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.
94 This document is still a draft version. Any feedbacks and
100 <!-- ****************************************************** -->
101 <!-- File Tree Structure -->
102 <!-- ****************************************************** -->
103 <chapter id="file-tree">
104 <title>File Tree Structure</title>
106 <section id="file-tree-general">
107 <title>General</title>
109 The ALSA drivers are provided in the two ways.
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.
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.
136 <title>ALSA File Tree Structure</title>
168 <section id="file-tree-core-directory">
169 <title>core directory</title>
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.
177 <section id="file-tree-core-directory-oss">
178 <title>core/oss</title>
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>).
190 <section id="file-tree-core-directory-ioctl32">
191 <title>core/ioctl32</title>
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.
200 <section id="file-tree-core-directory-seq">
201 <title>core/seq</title>
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
212 <section id="file-tree-core-directory-seq-oss">
213 <title>core/seq/oss</title>
215 This contains the OSS sequencer emulation codes.
219 <section id="file-tree-core-directory-deq-instr">
220 <title>core/seq/instr</title>
222 This directory contains the modules for the sequencer
228 <section id="file-tree-include-directory">
229 <title>include directory</title>
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 :)
239 <section id="file-tree-drivers-directory">
240 <title>drivers directory</title>
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.
251 <section id="file-tree-drivers-directory-mpu401">
252 <title>drivers/mpu401</title>
254 The MPU401 and MPU401-UART modules are stored here.
258 <section id="file-tree-drivers-directory-opl3">
259 <title>drivers/opl3 and opl4</title>
261 The OPL3 and OPL4 FM-synth stuff is found here.
266 <section id="file-tree-i2c-directory">
267 <title>i2c directory</title>
269 This contains the ALSA i2c components.
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
279 <section id="file-tree-i2c-directory-l3">
280 <title>i2c/l3</title>
282 This is a sub-directory for ARM L3 i2c.
287 <section id="file-tree-synth-directory">
288 <title>synth directory</title>
290 This contains the synth middle-level modules.
294 So far, there is only Emu8000/Emu10k1 synth driver under
295 synth/emux sub-directory.
299 <section id="file-tree-pci-directory">
300 <title>pci directory</title>
302 This and its sub-directories hold the top-level card modules
303 for PCI soundcards and the codes specific to the PCI BUS.
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).
313 <section id="file-tree-isa-directory">
314 <title>isa directory</title>
316 This and its sub-directories hold the top-level card modules
321 <section id="file-tree-arm-ppc-sparc-directories">
322 <title>arm, ppc, and sparc directories</title>
324 These are for the top-level card modules which are
325 specific to each given architecture.
329 <section id="file-tree-usb-directory">
330 <title>usb directory</title>
332 This contains the USB-audio driver. On the latest version, the
333 USB MIDI driver is integrated together with usb-audio driver.
337 <section id="file-tree-pcmcia-directory">
338 <title>pcmcia directory</title>
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.
346 <section id="file-tree-oss-directory">
347 <title>oss directory</title>
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 :)
356 <!-- ****************************************************** -->
357 <!-- Basic Flow for PCI Drivers -->
358 <!-- ****************************************************** -->
359 <chapter id="basic-flow">
360 <title>Basic Flow for PCI Drivers</title>
362 <section id="basic-flow-outline">
363 <title>Outline</title>
365 The minimum flow of PCI soundcard is like the following:
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>
380 <section id="basic-flow-example">
381 <title>Full Code Example</title>
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
390 <title>Basic Flow for PCI Drivers Example</title>
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>
399 #include <sound/initval.h>
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;
406 // definition of the chip-specific record
407 typedef struct snd_mychip mychip_t;
410 // rest of implementation will be in the section
411 // "PCI Resource Managements"
414 // this should be go into <sound/sndmagic.h>
415 // (see "Management of Cards and Components")
416 #define mychip_t_magic 0xa15a4501
418 // chip-specific destructor
419 // (see "PCI Resource Managements")
420 static int snd_mychip_free(mychip_t *chip)
422 // will be implemented later...
425 // component-destructor
426 // (see "Management of Cards and Components")
427 static int snd_mychip_dev_free(snd_device_t *device)
429 mychip_t *chip = snd_magic_cast(mychip_t,
430 device->device_data, return -ENXIO);
431 return snd_mychip_free(chip);
434 // chip-specific constructor
435 // (see "Management of Cards and Components")
436 static int __devinit snd_mychip_create(snd_card_t *card,
442 static snd_device_ops_t ops = {
443 .dev_free = snd_mychip_dev_free,
448 // check PCI availability here
449 // (see "PCI Resource Managements")
451 // allocate a chip-specific data with magic-alloc
452 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
458 // rest of initialization here; will be implemented
459 // later, see "PCI Resource Managements"
461 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
463 snd_mychip_free(chip);
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)
480 if (dev >= SNDRV_CARDS)
488 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
493 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
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);
508 if ((err = snd_card_register(card)) < 0) {
514 pci_set_drvdata(pci, chip);
519 // destructor -- see "Destructor" sub-section
520 static void __devexit snd_mychip_remove(struct pci_dev *pci)
522 mychip_t *chip = snd_magic_cast(mychip_t,
523 pci_get_drvdata(pci), return);
525 snd_card_free(chip->card);
526 pci_set_drvdata(pci, NULL);
534 <section id="basic-flow-constructor">
535 <title>Constructor</title>
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.
546 In the probe callback, the following scheme is often used.
549 <section id="basic-flow-constructor-device-index">
550 <title>1) Check and increment the device index.</title>
557 if (dev >= SNDRV_CARDS)
567 where enable[dev] is the module option.
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
575 linkend="basic-flow-constructor-set-pci"><citetitle>step
576 7</citetitle></link>).
580 <section id="basic-flow-constructor-create-card">
581 <title>2) Create a card instance</title>
588 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
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>.
601 <section id="basic-flow-constructor-create-main">
602 <title>3) Create a main component</title>
604 In this part, the PCI resources are allocated.
611 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
619 The detail will be explained in the section <link
620 linkend="pci-resource"><citetitle>PCI Resource
621 Managements</citetitle></link>.
625 <section id="basic-flow-constructor-main-component">
626 <title>4) Set the driver ID and name strings.</title>
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);
639 The driver field holds the minimal ID string of the
640 chip. This is referred by alsa-lib's configurator, so keep it
642 Even the same driver can have different driver IDs to
643 distinguish the functionality of each chip type.
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>.
653 <section id="basic-flow-constructor-create-other">
654 <title>5) Create other components, such as mixer, MIDI, etc.</title>
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.
666 <section id="basic-flow-constructor-register-card">
667 <title>6) Register the card instance.</title>
672 if ((err = snd_card_register(card)) < 0) {
682 Will be explained in the section <link
683 linkend="card-management-registration"><citetitle>Management
684 of Cards and Components</citetitle></link>, too.
688 <section id="basic-flow-constructor-set-pci">
689 <title>7) Set the PCI driver data and return zero.</title>
694 pci_set_drvdata(pci, chip);
701 In the above, the chip record is stored. This pointer is
702 referred in the remove callback and power-management
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.
713 <section id="basic-flow-destructor">
714 <title>Destructor</title>
716 The destructor, remove callback, simply releases the card
717 instance. Then the ALSA middle layer will release all the
718 attached components automatically.
722 It would be typically like the following:
727 static void __devexit snd_mychip_remove(struct pci_dev *pci)
729 mychip_t *chip = snd_magic_cast(mychip_t,
730 pci_get_drvdata(pci), return);
732 snd_card_free(chip->card);
733 pci_set_drvdata(pci, NULL);
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>).
747 <section id="basic-flow-header-files">
748 <title>Header Files</title>
750 For the above example, at least the following include files
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>
762 #include <sound/initval.h>
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.
773 In addition to them, you'll need
774 <filename><linux/interrupt.h></filename> for the interrupt
775 handling, and <filename><asm/io.h></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><linux/delay.h></filename>, too.
782 The ALSA interfaces like PCM or control API are define in other
783 header files as <filename><sound/xxx.h></filename>.
784 They have to be included after
785 <filename><sound/core.h></filename>.
792 <!-- ****************************************************** -->
793 <!-- Management of Cards and Components -->
794 <!-- ****************************************************** -->
795 <chapter id="card-management">
796 <title>Management of Cards and Components</title>
798 <section id="card-management-card-instance">
799 <title>Card Instance</title>
801 For each soundcard, a <quote>card</quote> record must be allocated.
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
816 As mentioned above, to create a card instance, call
817 <function>snd_card_new()</function>.
823 card = snd_card_new(index, id, module, extra_size);
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->private_data for the
835 chip-specific data. Note that this data
836 <emphasis>is</emphasis> allocated by
837 <function>snd_card_new()</function>.
841 <section id="card-management-component">
842 <title>Components</title>
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
853 A component can be created via
854 <function>snd_device_new()</function> function.
859 snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
866 This takes the card pointer, the device-level
867 (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
868 callback pointers (<parameter>&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>.
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
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.
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
901 <section id="card-management-chip-specific">
902 <title>Chip-Specific Data</title>
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:
913 typedef struct snd_mychip mychip_t;
923 You might have objections against such a typedef, but this
924 typedef is necessary if you use a <quote>magic-cast</quote>
926 linkend="card-management-chip-what-advantage"><citetitle>later</citetitle></link>).
930 In general, there are two ways to allocate the chip record.
933 <section id="card-management-chip-specific-snd-card-new">
934 <title>1. Allocating via <function>snd_card_new()</function>.</title>
936 As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
941 card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
946 whether <type>mychip_t</type> is the type of the chip record.
950 In return, the allocated record can be accessed as
955 mychip_t *chip = (mychip_t *)card->private_data;
960 With this method, you don't have to allocate twice. But you
961 cannot use <quote>magic-cast</quote> for this record pointer,
966 <section id="card-management-chip-specific-allocate-extra">
967 <title>2. Allocating an extra device.</title>
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>.
980 card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
982 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
987 Once when the record is allocated via snd_magic stuff, you
988 can use <quote>magic-cast</quote> for the void pointer.
992 The chip record should have the field to hold the card
1008 Then, set the card pointer in the returned chip instance.
1020 Also, you need to define a magic-value for <type>mychip_t</type>.
1025 #define mychip_t_magic 0xa15a4501
1029 (the detail will be described in the
1030 <link linkend="card-management-chip-what-advantage"><citetitle>
1031 next</citetitle></link> subsection).
1035 Next, initialize the fields, and register this chip
1036 record as a low-level device with a specified
1037 <parameter>ops</parameter>,
1042 static snd_device_ops_t ops = {
1043 .dev_free = snd_mychip_dev_free,
1046 snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1051 <function>snd_mychip_dev_free()</function> is the
1052 device-destructor function, which will call the real
1060 static int snd_mychip_dev_free(snd_device_t *device)
1062 mychip_t *chip = snd_magic_cast(mychip_t, device->device_data,
1064 return snd_mychip_free(chip);
1070 where <function>snd_mychip_free()</function> is the real destructor.
1074 <section id="card-management-chip-what-advantage">
1075 <title>Not a magic but a logic</title>
1077 <para>Now, you might have a question: What is the advantage of the
1078 second method? Obviously, it looks far more complicated.</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->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.
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>.
1100 chip = snd_magic_kmalloc(mychip_t, 0, GFP_KERNEL);
1101 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1106 The difference of these two functions is whether the area is
1107 zero-cleared (<function>kcalloc</function>) or not
1108 (<function>kmalloc</function>).
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
1121 #define mychip_t_magic 0xa15a4501
1126 The value is arbitrary but should be unique.
1127 This is usually defined in
1128 <filename><include/sndmagic.h></filename> or
1129 <filename><include/amagic.h></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.
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.
1144 For casting a pointer, use
1145 <function>snd_magic_cast()</function> macro:
1150 mychip_t *chip = snd_magic_cast(mychip_t, source_pointer, action);
1155 where <parameter>source_pointer</parameter> is the pointer to
1156 be casted (e.g. pcm->private_data), and
1157 <parameter>action</parameter> is the action to do if the cast
1158 fails (e.g. return <constant>-EINVAL</constant>).
1162 For releasing the magic-allocated data, you need to call
1163 <function>snd_magic_kfree()</function> function instead of
1164 <function>kfree()</function>.
1169 snd_magic_kfree(chip);
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
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.
1195 <section id="card-management-registration">
1196 <title>Registration and Release</title>
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>.
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.
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.
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
1233 <!-- ****************************************************** -->
1234 <!-- PCI Resource Managements -->
1235 <!-- ****************************************************** -->
1236 <chapter id="pci-resource">
1237 <title>PCI Resource Managements</title>
1239 <section id="pci-resource-example">
1240 <title>Full Code Example</title>
1242 In this section, we'll finish the chip-specific constructor,
1243 destructor and PCI entries. The example code is shown first,
1247 <title>PCI Resource Managements Example</title>
1252 struct pci_dev *pci;
1255 struct resource *res_port;
1260 static int snd_mychip_free(mychip_t *chip)
1262 // disable hardware here if any
1263 // (not implemented in this document)
1265 // release the i/o port
1266 if (chip->res_port) {
1267 release_resource(chip->res_port);
1268 kfree_nocheck(chip->res_port);
1272 free_irq(chip->irq, (void *)chip);
1274 snd_magic_kfree(chip);
1278 // chip-specific constructor
1279 static int __devinit snd_mychip_create(snd_card_t *card,
1280 struct pci_dev *pci,
1285 static snd_device_ops_t ops = {
1286 .dev_free = snd_mychip_dev_free,
1291 // check PCI availability (28bit DMA)
1292 if ((err = pci_enable_device(pci)) < 0)
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");
1300 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1304 // initialize the stuff
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");
1317 if (request_irq(pci->irq, snd_mychip_interrupt,
1318 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1320 snd_mychip_free(chip);
1321 printk(KERN_ERR "cannot grab irq\n");
1324 chip->irq = pci->irq;
1326 // (2) initialization of the chip hardware
1327 // (not implemented in this document)
1329 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1331 snd_mychip_free(chip);
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, },
1345 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
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),
1355 // initialization of the module
1356 static int __init alsa_card_mychip_init(void)
1360 if ((err = pci_module_init(&driver)) < 0) {
1362 printk(KERN_ERR "My chip soundcard not found "
1363 "or device busy\n");
1370 // clean up the module
1371 static void __exit alsa_card_mychip_exit(void)
1373 pci_unregister_driver(&driver);
1376 module_init(alsa_card_mychip_init)
1377 module_exit(alsa_card_mychip_exit)
1379 EXPORT_NO_SYMBOLS; /* for old kernels only */
1386 <section id="pci-resource-some-haftas">
1387 <title>Some Hafta's</title>
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
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,
1405 Suppose the 28bit mask, and the code to be added would be like:
1410 if ((err = pci_enable_device(pci)) < 0)
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");
1424 <section id="pci-resource-resource-allocation">
1425 <title>Resource Allocation</title>
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.
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
1446 struct resource *res_port;
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.
1467 The allocation of an i/o port is done like this:
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",
1477 snd_mychip_free(chip);
1486 It will reserve the i/o port region of 8 bytes of the given
1487 PCI device. The returned value, chip->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.
1495 The allocation of an interrupt source is done like this:
1500 if (request_irq(pci->irq, snd_mychip_interrupt,
1501 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1503 snd_mychip_free(chip);
1504 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1507 chip->irq = pci->irq;
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->irq should be defined
1516 only when <function>request_irq()</function> succeeded.
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>.
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
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:
1540 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1541 struct pt_regs *regs)
1543 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
1551 Again the magic-cast is used here to get the correct pointer
1552 from the second argument.
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.
1563 For releasing the resources, <quote>check-and-release</quote>
1564 method is a safer way. For the i/o port, do like this:
1569 if (chip->res_port) {
1570 release_resource(chip->res_port);
1571 kfree_nocheck(chip->res_port);
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
1587 <function>kfree()</function>.
1588 <function>kfree_nocheck()</function> is used for that; it calls
1589 the native <function>kfree()</function> without wrapper.
1593 For releasing the interrupt, do like this:
1599 free_irq(chip->irq, (void *)chip);
1604 And finally, release the chip-specific record.
1609 snd_magic_kfree(chip);
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.
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.
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.
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
1653 unsigned long iobase_phys;
1654 unsigned long iobase_virt;
1655 struct resource *res_iobase;
1661 and the allocation would be (assuming its size is 512 bytes):
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);
1679 and the corresponding destructor would be:
1684 static int snd_mychip_free(mychip_t *chip)
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);
1702 <section id="pci-resource-entries">
1703 <title>PCI Entries</title>
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
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, },
1724 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
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.
1742 The last entry of this list is the terminator. You must
1743 specify this all-zero entry.
1747 Then, prepare the <structname>pci_driver</structname> record:
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),
1764 The <structfield>probe</structfield> and
1765 <structfield>remove</structfield> functions are what we already
1767 the previous sections. The <structfield>remove</structfield> should
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.
1777 And at last, the module entries:
1782 static int __init alsa_card_mychip_init(void)
1786 if ((err = pci_module_init(&driver)) < 0) {
1788 printk(KERN_ERR "My chip soundcard not found"
1789 " or device busy\n");
1796 static void __exit alsa_card_mychip_exit(void)
1798 pci_unregister_driver(&driver);
1801 module_init(alsa_card_mychip_init)
1802 module_exit(alsa_card_mychip_exit)
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>.
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).
1835 <!-- ****************************************************** -->
1836 <!-- PCM Interface -->
1837 <!-- ****************************************************** -->
1838 <chapter id="pcm-interface">
1839 <title>PCM Interface</title>
1841 <section id="pcm-interface-general">
1842 <title>General</title>
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.
1850 For accessing to the PCM layer, you need to include
1851 <filename><sound/pcm.h></filename> above all. In addition,
1852 <filename><sound/pcm_params.h></filename> might be needed
1853 if you access to some functions related with hw_param.
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.
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.
1878 <section id="pcm-interface-example">
1879 <title>Full Code Example</title>
1881 The example code below does not include any hardware access
1882 routines but shows only the skeleton, how to build up the PCM
1886 <title>PCM Example Code</title>
1889 #include <sound/pcm.h>
1892 #define chip_t mychip_t
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,
1907 .buffer_bytes_max = 32768,
1908 .period_bytes_min = 4096,
1909 .period_bytes_max = 32768,
1911 .periods_max = 1024,
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,
1926 .buffer_bytes_max = 32768,
1927 .period_bytes_min = 4096,
1928 .period_bytes_max = 32768,
1930 .periods_max = 1024,
1934 static int snd_mychip_playback_open(snd_pcm_substream_t *substream)
1936 mychip_t *chip = snd_pcm_substream_chip(substream);
1937 snd_pcm_runtime_t *runtime = substream->runtime;
1939 runtime->hw = snd_mychip_playback_hw;
1940 // more hardware-initialization will be done here
1944 /* close callback */
1945 static int snd_mychip_playback_close(snd_pcm_substream_t *substream)
1947 mychip_t *chip = snd_pcm_substream_chip(substream);
1948 // the hardware-specific codes will be here
1954 static int snd_mychip_capture_open(snd_pcm_substream_t *substream)
1956 mychip_t *chip = snd_pcm_substream_chip(substream);
1957 snd_pcm_runtime_t *runtime = substream->runtime;
1959 runtime->hw = snd_mychip_capture_hw;
1960 // more hardware-initialization will be done here
1964 /* close callback */
1965 static int snd_mychip_capture_close(snd_pcm_substream_t *substream)
1967 mychip_t *chip = snd_pcm_substream_chip(substream);
1968 // the hardware-specific codes will be here
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)
1977 return snd_pcm_lib_malloc_pages(substream,
1978 params_buffer_bytes(hw_params));
1981 /* hw_free callback */
1982 static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1984 return snd_pcm_lib_free_pages(substream);
1987 /* prepare callback */
1988 static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1990 mychip_t *chip = snd_pcm_substream_chip(substream);
1991 snd_pcm_runtime_t *runtime = substream->runtime;
1993 // set up the hardware with the current configuration
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,
2004 /* trigger callback */
2005 static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
2009 case SNDRV_PCM_TRIGGER_START:
2010 // do something to start the PCM engine
2012 case SNDRV_PCM_TRIGGER_STOP:
2013 // do something to stop the PCM engine
2020 /* pointer callback */
2021 static snd_pcm_uframes_t
2022 snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
2024 mychip_t *chip = snd_pcm_substream_chip(substream);
2025 unsigned int current_ptr;
2027 // get the current hardware pointer
2028 current_ptr = mychip_get_hw_pointer(chip);
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,
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,
2057 * definitions of capture are omitted here...
2060 /* create a pcm device */
2061 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2066 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2069 pcm->private_data = chip;
2070 strcpy(pcm->name, "My Chip");
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),
2089 <section id="pcm-interface-constructor">
2090 <title>Constructor</title>
2092 A pcm instance is allocated <function>snd_pcm_new()</function>
2093 function. It would be better to create a constructor for pcm,
2099 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2104 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2107 pcm->private_data = chip;
2108 strcpy(pcm->name, "My Chip");
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.
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.
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.
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
2150 snd_pcm_substream_t *substream;
2151 int index = substream->number;
2158 After the pcm is created, you need to set operators for each
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);
2174 The operators are defined typically like this:
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,
2193 Each of callbacks is explained in the subsection
2194 <link linkend="pcm-interface-operators"><citetitle>
2195 Operators</citetitle></link>.
2199 After setting the operators, most likely you'd like to
2200 pre-allocate the buffer. For the pre-allocation, simply call
2206 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2207 snd_dma_pci_data(chip->pci),
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>.
2220 Additionally, you can set some extra information for this pcm
2221 in pcm->info_flags.
2222 The available values are defined as
2223 <constant>SNDRV_PCM_INFO_XXX</constant> in
2224 <filename><sound/asound.h></filename>, which is used for
2225 the hardware definition (described later). When your soundchip
2226 supports only half-duplex, specify like this:
2231 pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2238 <section id="pcm-interface-destructor">
2239 <title>... And the Destructor?</title>
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
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->private_free:
2254 <title>PCM Instance with a Destructor</title>
2257 static void mychip_pcm_free(snd_pcm_t *pcm)
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...
2266 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
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;
2283 <section id="pcm-interface-runtime">
2284 <title>Runtime Pointer - The Chest of PCM Information</title>
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->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.
2296 The definition of runtime instance is found in
2297 <filename><sound/pcm.h></filename>. Here is the
2302 struct _snd_pcm_runtime {
2304 snd_pcm_substream_t *trigger_master;
2305 snd_timestamp_t trigger_tstamp; /* trigger timestamp */
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*/
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 */
2323 unsigned int frame_bits;
2324 unsigned int sample_bits;
2326 unsigned int rate_num;
2327 unsigned int rate_den;
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 */
2342 snd_pcm_uframes_t silenced_start;
2343 snd_pcm_uframes_t silenced_size;
2345 snd_pcm_sync_id_t sync; /* hardware synchronization ID */
2348 volatile snd_pcm_mmap_status_t *status;
2349 volatile snd_pcm_mmap_control_t *control;
2350 atomic_t mmap_count;
2352 /* -- locking / scheduling -- */
2354 wait_queue_head_t sleep;
2355 struct timer_list tick_timer;
2356 struct fasync_struct *fasync;
2358 /* -- private section -- */
2360 void (*private_free)(snd_pcm_runtime_t *runtime);
2362 /* -- hardware description -- */
2363 snd_pcm_hardware_t hw;
2364 snd_pcm_hw_constraints_t hw_constraints;
2366 /* -- interrupt callbacks -- */
2367 void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2368 void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2371 unsigned int timer_resolution; /* timer resolution */
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 */
2379 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2380 /* -- OSS things -- */
2381 snd_pcm_oss_runtime_t oss;
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.
2401 In the sections below, important records are explained.
2404 <section id="pcm-interface-runtime-hw">
2405 <title>Hardware Description</title>
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->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
2422 snd_pcm_runtime_t *runtime = substream->runtime;
2424 runtime->hw = snd_mychip_playback_hw; // common definition
2425 if (chip->model == VERY_OLD_ONE)
2426 runtime->hw.channels_max = 1;
2433 Typically, you'll have a hardware descriptor like below:
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,
2448 .buffer_bytes_max = 32768,
2449 .period_bytes_min = 4096,
2450 .period_bytes_max = 32768,
2452 .periods_max = 1024,
2462 The <structfield>info</structfield> field contains the type and
2463 capabilities of this pcm. The bit flags are defined in
2464 <filename><sound/asound.h></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,
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
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.
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.
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.
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).
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.
2541 <structfield>channel_min</structfield> and
2542 <structfield>channel_max</structfield>
2543 define, as you might already expected, the minimal and maximal
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.
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.
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.
2587 <section id="pcm-interface-runtime-config">
2588 <title>PCM Configurations</title>
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>.
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>.
2612 period_bytes = frames_to_bytes(runtime, runtime->period_size);
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
2627 <section id="pcm-interface-runtime-dma">
2628 <title>DMA Buffer Information</title>
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.
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.
2663 <section id="pcm-interface-runtime-status">
2664 <title>Running Status</title>
2666 The running status can be referred via <constant>runtime->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->status->hw_ptr</constant>.
2673 The DMA application pointer can be referred via
2674 <constant>runtime->control</constant>, which points
2675 <type>snd_pcm_mmap_control_t</type> record.
2676 However, accessing directly to this value is not recommended.
2680 <section id="pcm-interface-runtime-private">
2681 <title>Private Data</title>
2683 You can allocate a record for the substream and store it in
2684 <constant>runtime->private_data</constant>. Usually, this
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.
2694 static int snd_xxx_open(snd_pcm_substream_t *substream)
2696 my_pcm_data_t *data;
2698 data = snd_magic_kmalloc(my_pcm_data_t, 0, GFP_KERNEL);
2699 substream->runtime->private_data = data;
2708 The allocated object must be released in
2709 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2710 the close callback</citetitle></link>.
2714 <section id="pcm-interface-runtime-intr">
2715 <title>Interrupt Callbacks</title>
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.
2726 <section id="pcm-interface-operators">
2727 <title>Operators</title>
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
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
2745 #define chip_t mychip_t
2748 mychip_t *chip = snd_pcm_substream_chip(substream);
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.
2763 <section id="pcm-interface-operators-open-callback">
2764 <title>open callback</title>
2769 static int snd_xxx_open(snd_pcm_substream_t *substream);
2774 This is called when a pcm substream is opened.
2778 At least, here you have to initialize the runtime->hw
2779 record. Typically, this is done by like this:
2784 static int snd_xxx_open(snd_pcm_substream_t *substream)
2786 mychip_t *chip = snd_pcm_substream_chip(substream);
2787 snd_pcm_runtime_t *runtime = substream->runtime;
2789 runtime->hw = snd_mychip_playback_hw;
2796 where <parameter>snd_mychip_playback_hw</parameter> is the
2797 pre-defined hardware description.
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.
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.
2814 <section id="pcm-interface-operators-close-callback">
2815 <title>close callback</title>
2820 static int snd_xxx_close(snd_pcm_substream_t *substream);
2825 Obviously, this is called when a pcm substream is closed.
2829 Any private instance for a pcm substream allocated in the
2830 open callback will be released here.
2835 static int snd_xxx_close(snd_pcm_substream_t *substream)
2838 snd_magic_kfree(substream->runtime->private_data);
2847 <section id="pcm-interface-operators-ioctl-callback">
2848 <title>ioctl callback</title>
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>.
2856 <section id="pcm-interface-operators-hw-params-callback">
2857 <title>hw_params callback</title>
2862 static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2863 snd_pcm_hw_params_t * hw_params);
2868 This and <structfield>hw_free</structfield> callbacks exist
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.
2881 Many hardware set-up should be done in this callback,
2882 including the allocation of buffers.
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,
2893 snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
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.
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.
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.
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.
2932 <section id="pcm-interface-operators-hw-free-callback">
2933 <title>hw_free callback</title>
2938 static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2945 This is called to release the resources allocated via
2946 <structfield>hw_params</structfield>. For example, releasing the
2948 <function>snd_pcm_lib_malloc_pages()</function> is done by
2949 calling the following:
2954 snd_pcm_lib_free_pages(substream);
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.
2967 <section id="pcm-interface-operators-prepare-callback">
2968 <title>prepare callback</title>
2973 static int snd_xxx_prepare(snd_pcm_substream_t * substream);
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
2986 <function>snd_pcm_prepare()</function> is called, i.e. when
2987 recovered after underruns, etc.
2991 As mentioned above, this callback is atomic.
2995 In this and the following callbacks, you can refer to the
2996 values via the runtime record,
2997 substream->runtime.
2998 For example, to get the current
2999 rate, format or channels, access to
3001 runtime->format or
3002 runtime->channels, respectively.
3003 The physical address of the allocated buffer is set to
3004 runtime->dma_area. The buffer and period sizes are
3005 in runtime->buffer_size and runtime->period_size,
3010 Be careful that this callback will be called many times at
3015 <section id="pcm-interface-operators-trigger-callback">
3016 <title>trigger callback</title>
3021 static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
3026 This is called when the pcm is started, stopped or paused.
3030 Which action is specified in the second argument,
3031 <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
3032 <filename><sound/pcm.h></filename>. At least,
3033 <constant>START</constant> and <constant>STOP</constant>
3034 commands must be defined in this callback.
3040 case SNDRV_PCM_TRIGGER_START:
3041 // do something to start the PCM engine
3043 case SNDRV_PCM_TRIGGER_STOP:
3044 // do something to stop the PCM engine
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.
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.
3076 This callback is also atomic.
3080 <section id="pcm-interface-operators-pointer-callback">
3081 <title>pointer callback</title>
3086 static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
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.
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.
3107 This callback is also atomic.
3111 <section id="pcm-interface-operators-copy-silence">
3112 <title>copy and silence callbacks</title>
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.
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>.
3133 <section id="pcm-interface-operators-ack">
3134 <title>ack callback</title>
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.
3144 <section id="pcm-interface-operators-page-callback">
3145 <title>page callback</title>
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.
3158 <section id="pcm-interface-interrupt-handler">
3159 <title>Interrupt Handler</title>
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>
3170 There are several types of sound chips to generate the interrupts.
3173 <section id="pcm-interface-interrupt-handler-boundary">
3174 <title>Interrupts at the period (fragment) boundary</title>
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
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).
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
3202 A typical coding would be like:
3205 <title>Interrupt Handler Case #1</title>
3208 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3209 struct pt_regs *regs)
3211 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3212 spin_lock(&chip->lock);
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
3222 spin_unlock(&chip->lock);
3231 <section id="pcm-interface-interrupt-handler-timer">
3232 <title>High-frequent timer interrupts</title>
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
3241 <function>snd_pcm_period_elapsed()</function> and reset the
3246 A typical coding would be like the following.
3249 <title>Interrupt Handler Case #2</title>
3252 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3253 struct pt_regs *regs)
3255 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3256 spin_lock(&chip->lock);
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
3264 if (last_ptr < chip->last_ptr)
3265 size = runtime->buffer_size + last_ptr
3268 size = last_ptr - chip->last_ptr;
3269 // remember the last updated point
3270 chip->last_ptr = last_ptr;
3271 // accumulate the size
3273 // over the period boundary?
3274 if (chip->size >= runtime->period_size) {
3275 // reset the accumulator
3276 chip->size %= runtime->period_size;
3278 spin_unlock(&chip->lock);
3279 snd_pcm_period_elapsed(substream);
3280 spin_lock(&chip->lock);
3282 // acknowledge the interrupt if necessary
3285 spin_unlock(&chip->lock);
3294 <section id="pcm-interface-interrupt-handler-both">
3295 <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3297 In both cases, even if more than one period are elapsed, you
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.
3306 <section id="pcm-interface-atomicity">
3307 <title>Atomicity</title>
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.
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.
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>.
3339 <section id="pcm-interface-constraints">
3340 <title>Constraints</title>
3342 If your chip supports unconventional sample rates, or only the
3343 limited samples, you need to set a constraint for the
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.
3354 <title>Example of Hardware Constraints</title>
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]),
3365 static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3369 err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3370 SNDRV_PCM_HW_PARAM_RATE,
3371 &constraints_rates);
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:
3391 <title>Example of Hardware Constraints for Channels</title>
3394 static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3395 snd_pcm_hw_rule_t *rule)
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);
3401 snd_mask_any(&fmt); // Init the struct
3403 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3404 return snd_mask_refine(f, &fmt);
3414 Then you need to call this function to add your rule:
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,
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:
3433 <title>Example of Hardware Constraints for Channels</title>
3436 static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3437 snd_pcm_hw_rule_t *rule)
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);
3443 snd_interval_any(&ch);
3444 if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3445 ch.min = ch.max = 1;
3447 return snd_interval_refine(c, &ch);
3457 ...and in the open callback:
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,
3470 I won't explain more details here, rather I
3471 would like to say, <quote>Luke, use the source.</quote>
3478 <!-- ****************************************************** -->
3479 <!-- Control Interface -->
3480 <!-- ****************************************************** -->
3481 <chapter id="control-interface">
3482 <title>Control Interface</title>
3484 <section id="control-interface-general">
3485 <title>General</title>
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).
3495 ALSA has a well-defined AC97 control module. If your chip
3496 supports only the AC97 and nothing else, you can skip this
3501 The control API is defined in
3502 <filename><sound/control.h></filename>.
3503 Include this file if you add your own controls.
3507 <section id="control-interface-definition">
3508 <title>Definition of Controls</title>
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:
3517 <title>Definition of a Control</title>
3520 static snd_kcontrol_new_t my_control __devinitdata = {
3521 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3522 .name = "PCM Playback Switch",
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
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.
3543 The <structfield>iface</structfield> field specifies the type of
3545 <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3546 <constant>MIXER</constant>, <constant>PCM</constant>,
3547 <constant>CARD</constant>, etc.
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
3556 <link linkend="control-interface-control-names"><citetitle>
3557 Control Names</citetitle></link>.
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.
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>.
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.
3591 <link linkend="control-interface-callbacks"><citetitle>
3592 callback functions</citetitle></link>.
3596 <section id="control-interface-control-names">
3597 <title>Control Names</title>
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>.
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.
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.
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>.
3627 The example of control names are, thus, <quote>Master Capture
3628 Switch</quote> or <quote>PCM Playback Volume</quote>.
3632 There are some exceptions:
3635 <section id="control-interface-control-names-global">
3636 <title>Global capture and playback</title>
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
3647 <section id="control-interface-control-names-tone">
3648 <title>Tone-controls</title>
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>.
3657 <section id="control-interface-control-names-3d">
3658 <title>3D controls</title>
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>.
3667 <section id="control-interface-control-names-mic">
3668 <title>Mic boost</title>
3670 Mic-boost switch is set as <quote>Mic Boost</quote> or
3671 <quote>Mic Boost (6dB)</quote>.
3675 More precise information can be found in
3676 <filename>alsa-kernel/Documentation/sound/alsa/ControlNames.txt</filename>.
3681 <section id="control-interface-access-flags">
3682 <title>Access Flags</title>
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.
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.
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.
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
3722 <section id="control-interface-callbacks">
3723 <title>Callbacks</title>
3725 <section id="control-interface-callbacks-info">
3726 <title>info callback</title>
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
3735 <title>Example of info callback</title>
3738 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3739 snd_ctl_elem_info_t *uinfo)
3741 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3743 uinfo->value.integer.min = 0;
3744 uinfo->value.integer.max = 1;
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.
3767 The enumerated type is a bit different from others. You'll
3768 need to set the string for the currently given item index.
3773 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3774 snd_ctl_elem_info_t *uinfo)
3776 static char *texts[4] = {
3777 "First", "Second", "Third", "Fourth"
3779 uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
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]);
3794 <section id="control-interface-callbacks-get">
3795 <title>get callback</title>
3798 This callback is used to read the current value of the
3799 control and to return to the user-space.
3806 <title>Example of get callback</title>
3809 static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3810 snd_ctl_elem_value_t *ucontrol)
3812 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3813 ucontrol->value.integer.value[0] = get_some_value(chip);
3822 Here, the chip instance is retrieved via
3823 <function>snd_kcontrol_chip()</function> macro. This macro
3824 converts from kcontrol->private_data to the type defined by
3825 <type>chip_t</type>. The
3826 kcontrol->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>).
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
3841 .private_value = reg | (shift << 16) | (mask << 24)
3845 and is retrieved in callbacks like
3849 static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3850 snd_ctl_elem_value_t *ucontrol)
3852 int reg = kcontrol->private_value & 0xff;
3853 int shift = (kcontrol->private_value >> 16) & 0xff;
3854 int mask = (kcontrol->private_value >> 24) & 0xff;
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> > 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.
3872 <section id="control-interface-callbacks-put">
3873 <title>put callback</title>
3876 This callback is used to write a value from the user-space.
3883 <title>Example of put callback</title>
3886 static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3887 snd_ctl_elem_value_t *ucontrol)
3889 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3891 if (chip->current_value !=
3892 ucontrol->value.integer.value[0]) {
3893 change_current_value(chip,
3894 ucontrol->value.integer.value[0]);
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
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.
3916 <section id="control-interface-callbacks-all">
3917 <title>Callbacks are not atomic</title>
3919 All these three callbacks are basically not atomic.
3924 <section id="control-interface-constructor">
3925 <title>Constructor</title>
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>.
3934 In the simplest way, you can do like this:
3939 if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
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->private_data
3949 which can be referred in callbacks.
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.
3962 <section id="control-interface-change-notification">
3963 <title>Change Notification</title>
3965 If you need to change and update a control in the interrupt
3966 routine, you can call <function>snd_ctl_notify()</function>. For
3972 snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
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>
3983 You can find some examples in <filename>es1938.c</filename> or
3984 <filename>es1968.c</filename> for hardware volume interrupts.
3991 <!-- ****************************************************** -->
3992 <!-- API for AC97 Codec -->
3993 <!-- ****************************************************** -->
3994 <chapter id="api-ac97">
3995 <title>API for AC97 Codec</title>
3998 <title>General</title>
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><sound/ac97_codec.h></filename>.
4007 <section id="api-ac97-example">
4008 <title>Full Code Example</title>
4011 <title>Example of AC97 Interface</title>
4020 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4023 mychip_t *chip = snd_magic_cast(mychip_t,
4024 ac97->private_data, return 0);
4026 // read a register value here from the codec
4027 return the_register_value;
4030 static void snd_mychip_ac97_write(ac97_t *ac97,
4031 unsigned short reg, unsigned short val)
4033 mychip_t *chip = snd_magic_cast(mychip_t,
4034 ac97->private_data, return 0);
4036 // write the given register value to the codec
4039 static int snd_mychip_ac97(mychip_t *chip)
4041 ac97_bus_t bus, *pbus;
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)
4050 memset(&ac97, 0, sizeof(ac97));
4051 ac97.private_data = chip;
4052 return snd_ac97_mixer(pbus, &ac97, &chip->ac97);
4061 <section id="api-ac97-constructor">
4062 <title>Constructor</title>
4064 For creating an ac97 instance, first call <function>snd_ac97_bus</function>
4065 with <type>ac97_bus_t</type> record including callback functions.
4070 ac97_bus_t bus, *pbus;
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);
4081 The bus record is shared among all belonging ac97 instances.
4085 And then call <function>snd_ac97_mixer()</function> with an <type>ac97_t</type>
4086 record together with the bus pointer created above.
4094 memset(&ac97, 0, sizeof(ac97));
4095 ac97.private_data = chip;
4096 snd_ac97_mixer(bus, &ac97, &chip->ac97);
4101 where chip->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.
4112 <section id="api-ac97-callbacks">
4113 <title>Callbacks</title>
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.
4122 The <structfield>read</structfield> callback returns the
4123 register value specified in the argument.
4128 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4131 mychip_t *chip = snd_magic_cast(mychip_t,
4132 ac97->private_data, return 0);
4134 return the_register_value;
4140 Here, the chip can be cast from ac97->private_data.
4144 Meanwhile, the <structfield>write</structfield> callback is
4145 used to set the register value.
4150 static void snd_mychip_ac97_write(ac97_t *ac97,
4151 unsigned short reg, unsigned short val)
4158 These callbacks are non-atomic like the callbacks of control API.
4162 There are also other callbacks:
4163 <structfield>reset</structfield>,
4164 <structfield>wait</structfield> and
4165 <structfield>init</structfield>.
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.
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.
4181 The <structfield>init</structfield> callback is used for
4182 additional initialization of the codec.
4186 <section id="api-ac97-updating-registers">
4187 <title>Updating Registers in The Driver</title>
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>.
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
4210 snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4211 snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4218 <function>snd_ac97_read()</function> is used to read the value
4219 of the given register. For example,
4224 value = snd_ac97_read(ac97, AC97_MASTER);
4231 <function>snd_ac97_update_bits()</function> is used to update
4232 some bits of the given register.
4237 snd_ac97_update_bits(ac97, reg, mask, value);
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>.
4253 snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
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
4271 <section id="api-ac97-clock-adjustment">
4272 <title>Clock Adjustment</title>
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->clock to the corresponding
4277 value. For example, intel8x0
4278 and es1968 drivers have the auto-measurement function of the
4283 <section id="api-ac97-proc-files">
4284 <title>Proc Files</title>
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.
4293 <section id="api-ac97-multiple-codecs">
4294 <title>Multiple Codecs</title>
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
4304 If you have set up multiple codecs, you need to either write
4305 different callbacks for each codec or check
4314 <!-- ****************************************************** -->
4315 <!-- MIDI (MPU401-UART) Interface -->
4316 <!-- ****************************************************** -->
4317 <chapter id="midi-interface">
4318 <title>MIDI (MPU401-UART) Interface</title>
4320 <section id="midi-interface-general">
4321 <title>General</title>
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><sound/mpu401.h></filename>.
4331 Some soundchips have similar but a little bit different
4332 implementation of mpu401 stuff. For example, emu10k1 has its own
4337 In this document, I won't explain the rawmidi interface API,
4338 which is the basis of MPU401-UART implementation.
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>.
4349 <section id="midi-interface-constructor">
4350 <title>Constructor</title>
4352 For creating a rawmidi object, call
4353 <function>snd_mpu401_uart_new()</function>.
4358 snd_rawmidi_t *rmidi;
4359 snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4360 irq, irq_flags, &rmidi);
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
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>.
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
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
4390 (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4392 the mpu401-uart layer will allocate the i/o ports by itself.
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->private_data to
4404 <type>mpu401_t</type> explicitly,
4410 mpu = snd_magic_cast(mpu401_t, rmidi->private_data, );
4415 and reset the cport as you like:
4420 mpu->cport = my_own_control_port;
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
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.
4438 <section id="midi-interface-interrupt-handler">
4439 <title>Interrupt Handler</title>
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
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>.
4459 snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4469 <!-- ****************************************************** -->
4470 <!-- Miscellaneous Devices -->
4471 <!-- ****************************************************** -->
4472 <chapter id="misc-devices">
4473 <title>Miscellaneous Devices</title>
4475 <section id="misc-devices-opl3">
4476 <title>FM OPL3</title>
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><sound/opl3.h></filename>.
4485 FM registers can be directly accessed through direct-FM API,
4486 defined in <filename><sound/asound_fm.h></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.
4494 For creating the OPL3 component, you have two functions to
4495 call. The first one is a constructor for <type>opl3_t</type>
4502 snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
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.
4516 The fourth argument is the hardware type.
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.
4527 If this function returns successfully with 0, then create a
4528 hwdep device for this opl3.
4533 snd_hwdep_t *opl3hwdep;
4534 snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4541 The first argument is the <type>opl3_t</type> instance you
4542 created, and the second is the index number, usually 0.
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).
4552 <section id="misc-devices-hardware-dependent">
4553 <title>Hardware-Dependent Devices</title>
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><sound/hwdep.h></filename>. You can
4559 find examples in opl3 driver or
4560 <filename>isa/sb/sb16_csp.c</filename>.
4564 Creation of the <type>hwdep</type> instance is done via
4565 <function>snd_hwdep_new()</function>.
4571 snd_hwdep_new(card, "My HWDEP", 0, &hw);
4576 where the third argument is the index number.
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.
4590 mydata_t *p = snd_magic_kmalloc(mydata_t, 0, GFP_KERNEL);
4591 hw->private_data = p;
4592 hw->private_free = mydata_free;
4597 and the implementation of destructor would be:
4602 static void mydata_free(snd_hwdep_t *hw)
4604 mydata_t *p = snd_magic_cast(mydata_csp_t,
4605 hw->private_data, return);
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.
4622 hw->ops.open = mydata_open;
4623 hw->ops.ioctl = mydata_ioctl;
4624 hw->ops.release = mydata_release;
4629 And implement the callback functions as you like.
4633 <section id="misc-devices-IEC958">
4634 <title>IEC958 (S/PDIF)</title>
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><include/asound.h></filename>.
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,
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>).
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.
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.
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>.
4688 <!-- ****************************************************** -->
4689 <!-- Buffer and Memory Management -->
4690 <!-- ****************************************************** -->
4691 <chapter id="buffer-and-memory">
4692 <title>Buffer and Memory Management</title>
4694 <section id="buffer-and-memory-buffer-types">
4695 <title>Buffer Types</title>
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
4701 <function>snd_malloc_xxx_pages()</function> function, where xxx
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.
4714 For releasing the space, call
4715 <function>snd_free_xxx_pages()</function> function.
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).
4729 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
4730 snd_dma_pci_data(pci), size, max);
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.
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>
4757 <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers
4758 </citetitle></link>).
4762 Once when the buffer is pre-allocated, you can use the
4763 allocator in the <structfield>hw_params</structfield> callback
4768 snd_pcm_lib_malloc_pages(substream, size);
4773 Note that you have to pre-allocate to use this function.
4777 <section id="buffer-and-memory-external-hardware">
4778 <title>External Hardware Buffers</title>
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).
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
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.
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>.
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
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);
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.
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.
4852 The last argument is the number of frames to be copied.
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:
4867 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4868 frames_to_bytes(runtime, count));
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>).
4883 my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4884 frames_to_bytes(runtime, count));
4889 Note that both of the position and the data amount are given
4894 In the case of non-interleaved samples, the implementation
4895 will be a bit more complicated.
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.
4906 The <structfield>silence</structfield> callback is also
4907 implemented in a similar way.
4912 static int silence(snd_pcm_substream_t *substream, int channel,
4913 snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
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.
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:
4940 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4941 frames_to_bytes(runtime, count));
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>.
4954 <section id="buffer-and-memory-non-contiguous">
4955 <title>Non-Contiguous Buffers</title>
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><sound/pcm_sgbuf.h></filename>.
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->dma_private. You can cast
4979 snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
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->dma_area.
4992 The physical address (runtime->dma_addr) is set to zero,
4993 because the buffer is physically non-contigous.
4994 The physical address table is set up in sgbuf->table.
4995 You can get the physical address at a certain offset via
4996 <function>snd_pcm_sgbuf_get_addr()</function>.
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>.)
5008 For releasing the data, call
5009 <function>snd_pcm_lib_free_pages()</function> in the
5010 <structfield>hw_free</structfield> callback as usual.
5014 <section id="buffer-and-memory-vmalloced">
5015 <title>Vmalloc'ed Buffers</title>
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.
5025 The implementation of <structfield>page</structfield> callback
5031 #include <linux/vmalloc.h>
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)
5037 void *pageptr = substream->runtime->dma_area + offset;
5038 return vmalloc_to_page(pageptr);
5049 <!-- ****************************************************** -->
5050 <!-- Proc Interface -->
5051 <!-- ****************************************************** -->
5052 <chapter id="proc-interface">
5053 <title>Proc Interface</title>
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><sound/info.h></filename>.
5063 For creating a proc file, call
5064 <function>snd_card_proc_new()</function>.
5069 snd_info_entry_t *entry;
5070 int err = snd_card_proc_new(card, "my-file", &entry);
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>.
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
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>.
5099 snd_info_set_text_ops(entry, chip, read_size, my_proc_read);
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
5113 static void my_proc_read(snd_info_entry_t *entry,
5114 snd_info_buffer_t *buffer);
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,
5129 static void my_proc_read(snd_info_entry_t *entry,
5130 snd_info_buffer_t *buffer)
5132 chip_t *cm = snd_magic_cast(mychip_t,
5133 entry->private_data, return);
5135 snd_iprintf(buffer, "This is my chip!\n");
5136 snd_iprintf(buffer, "Port = %ld\n", chip->port);
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:
5151 entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
5156 and set the write buffer size and the callback
5161 entry->c.text.write_size = 256;
5162 entry->c.text.write = my_proc_write;
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.
5178 entry->c.text.read_size = 65536;
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>.
5194 For a raw-data proc-file, set the attributes like the following:
5199 static struct snd_info_entry_ops my_file_io_ops = {
5200 .read = my_file_io_read,
5203 entry->content = SNDRV_INFO_CONTENT_DATA;
5204 entry->private_data = chip;
5205 entry->c.ops = &my_file_io_ops;
5207 entry->mode = S_IFREG | S_IRUGO;
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.
5222 static long my_file_io_read(snd_info_entry_t *entry,
5223 void *file_private_data,
5225 char *buf, long 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))
5232 file->f_pos += size;
5243 <!-- ****************************************************** -->
5244 <!-- Power Management -->
5245 <!-- ****************************************************** -->
5246 <chapter id="power-management">
5247 <title>Power Management</title>
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>.
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
5270 #ifndef PCI_OLD_SUSPEND
5271 static int snd_my_suspend(struct pci_dev *dev, u32 state)
5273 mychip_t *chip = snd_magic_cast(mychip_t,
5274 pci_get_drvdata(dev), return -ENXIO);
5275 mychip_suspend(chip);
5278 static int snd_my_resume(struct pci_dev *dev)
5280 mychip_t *chip = snd_magic_cast(mychip_t,
5281 pci_get_drvdata(dev), return -ENXIO);
5282 mychip_resume(chip);
5286 static void snd_my_suspend(struct pci_dev *dev)
5288 mychip_t *chip = snd_magic_cast(mychip_t,
5289 pci_get_drvdata(dev), return);
5290 mychip_suspend(chip);
5292 static void snd_mychip_resume(struct pci_dev *dev)
5294 mychip_t *chip = snd_magic_cast(mychip_t,
5295 pci_get_drvdata(dev), return);
5296 mychip_resume(chip);
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
5308 See <filename>alsa-driver/pci/ali5451.c</filename> for example.
5312 The scheme of the real suspend job is as following.
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>
5324 A typical code would be like:
5329 static void mychip_suspend(mychip_t *chip)
5331 snd_card_t *card = chip->card;
5333 if (card->power_state == SNDRV_CTL_POWER_D3hot)
5336 snd_pcm_suspend_all(chip->pcm);
5338 snd_mychip_save_registers(chip);
5340 snd_mychip_stop_hardware(chip);
5342 snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
5350 The scheme of the real resume job is as following.
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>
5368 A typical code would be like:
5373 static void mychip_resume(mychip_t *chip)
5375 snd_card_t *card = chip->card;
5377 if (card->power_state == SNDRV_CTL_POWER_D0)
5380 pci_enable_device(chip->pci);
5382 snd_mychip_reinit_chip(chip);
5384 snd_mychip_restore_registers(chip);
5386 snd_ac97_resume(chip->ac97);
5388 snd_mychip_restart_chip(chip);
5390 snd_power_change_state(card, SNDRV_CTL_POWER_D0);
5398 In addition to the callbacks above, you should define a callback
5399 for the changes via the ALSA control interface. It's defined
5405 static int snd_mychip_set_power_state(snd_card_t *card,
5406 unsigned int power_state)
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);
5416 case SNDRV_CTL_POWER_D3hot:
5417 case SNDRV_CTL_POWER_D3cold:
5418 mychip_suspend(chip);
5431 OK, we have all callbacks now. Let's set up them now. In the
5432 initialization of the card, add the following:
5437 static int __devinit snd_mychip_probe(struct pci_dev *pci,
5438 const struct pci_device_id *pci_id)
5444 card->set_power_state = snd_mychip_set_power_state;
5445 card->power_state_private_data = chip;
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
5465 And next, set suspend/resume callbacks to the pci_driver,
5470 static struct pci_driver driver = {
5474 .suspend = snd_mychip_suspend,
5475 .resume = snd_mychip_resume,
5486 <!-- ****************************************************** -->
5487 <!-- Module Parameters -->
5488 <!-- ****************************************************** -->
5489 <chapter id="module-parameters">
5490 <title>Module Parameters</title>
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>
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:
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;
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.
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>
5533 For convenience, the typical string arguments given to
5534 <function>MODULE_PARM_SYNTAX()</function> are defined in
5535 <filename><sound/initval.h></filename>, such as
5536 <constant>SNDRV_ID_DESC</constant> or
5537 <constant>SNDRV_ENABLED</constant>.
5541 The typical coding would be like below:
5546 #define CARD_NAME "My Chip"
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);
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>.
5571 MODULE_DESCRIPTION("My Chip");
5572 MODULE_CLASSES("{sound}");
5573 MODULE_LICENSE("GPL");
5574 MODULE_DEVICES("{{Vendor,My Chip Name}}");
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.
5591 /* format is: snd-mychip=enable,index,id */
5593 static int __init alsa_card_mychip_setup(char *str)
5595 static unsigned __initdata nr_dev = 0;
5597 if (nr_dev >= SNDRV_CARDS)
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);
5606 __setup("snd-mychip=", alsa_card_mychip_setup);
5608 #endif /* ifndef MODULE */
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>
5622 <title>General</title>
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.
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
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.
5649 <title>Driver with A Single Source File</title>
5654 Modify alsa-driver/pci/Makefile
5658 Suppose you have a file xyz.c. Add the following
5663 snd-xyz-objs := xyz.o
5664 extra-obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5673 Create the Kconfig entry
5677 Add the new entry of Kconfig for your xyz driver.
5682 tristate "Foobar XYX"
5686 Say 'Y' or 'M' to include support for Foobar XYZ soundcard.
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.
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.
5707 For the details of Kconfig script, refer to the kbuild
5715 Run cvscompile script to re-generate the configure script and
5716 build the whole stuff again.
5724 <title>Drivers with Several Source Files</title>
5726 Suppose that the driver snd-xyz have several source files.
5727 They are located in the new subdirectory,
5733 Add a new directory (xyz) to extra-subdir-y list in alsa-driver/pci/Makefile
5738 obj-$(CONFIG_SND) += xyz/
5747 Under the directory xyz, create a Makefile
5750 <title>Sample Makefile for a driver xyz</title>
5757 include $(TOPDIR)/toplevel.config
5758 include $(TOPDIR)/Makefile.conf
5760 snd-xyz-objs := xyz.o abc.o def.o
5762 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5764 include $(TOPDIR)/Rules.make
5773 Create the Kconfig entry
5777 This procedure is as same as in the last section.
5783 Run cvscompile script to re-generate the configure script and
5784 build the whole stuff again.
5793 <!-- ****************************************************** -->
5794 <!-- Useful Functions -->
5795 <!-- ****************************************************** -->
5796 <chapter id="useful-functions">
5797 <title>Useful Functions</title>
5799 <section id="useful-functions-snd-printk">
5800 <title><function>snd_printk()</function> and friends</title>
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.
5814 snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
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.
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.
5840 <section id="useful-functions-snd-assert">
5841 <title><function>snd_assert()</function></title>
5843 <function>snd_assert()</function> macro is similar with the
5844 normal <function>assert()</function> macro. For example,
5849 snd_assert(pointer != NULL, return -EINVAL);
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
5865 <section id="useful-functions-snd-runtime-check">
5866 <title><function>snd_runtime_check()</function></title>
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>.
5879 <section id="useful-functions-snd-bug">
5880 <title><function>snd_BUG()</function></title>
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.
5890 <!-- ****************************************************** -->
5891 <!-- Acknowledgments -->
5892 <!-- ****************************************************** -->
5893 <chapter id="acknowledments">
5894 <title>Acknowledgments</title>
5896 I would like to thank Phil Kerr for his help for improvement and
5897 corrections of this document.
5900 Kevin Conder reformatted the original plain-text to the
5904 Giuliano Pochini corrected typos and contributed the example codes
5905 in the hardware constraints section.