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, card);
519 // destructor -- see "Destructor" sub-section
520 static void __devexit snd_mychip_remove(struct pci_dev *pci)
522 snd_card_free(pci_get_drvdata(pci));
523 pci_set_drvdata(pci, NULL);
531 <section id="basic-flow-constructor">
532 <title>Constructor</title>
534 The real constructor of PCI drivers is probe callback. The
535 probe callback and other component-constructors which are called
536 from probe callback should be defined with
537 <parameter>__devinit</parameter> prefix. You
538 cannot use <parameter>__init</parameter> prefix for them,
539 because any PCI device could be a hotplug device.
543 In the probe callback, the following scheme is often used.
546 <section id="basic-flow-constructor-device-index">
547 <title>1) Check and increment the device index.</title>
554 if (dev >= SNDRV_CARDS)
564 where enable[dev] is the module option.
568 At each time probe callback is called, check the
569 availability of the device. If not available, simply increment
570 the device index and returns. dev will be incremented also
572 linkend="basic-flow-constructor-set-pci"><citetitle>step
573 7</citetitle></link>).
577 <section id="basic-flow-constructor-create-card">
578 <title>2) Create a card instance</title>
585 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
592 The detail will be explained in the section
593 <link linkend="card-management-card-instance"><citetitle>
594 Management of Cards and Components</citetitle></link>.
598 <section id="basic-flow-constructor-create-main">
599 <title>3) Create a main component</title>
601 In this part, the PCI resources are allocated.
608 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
616 The detail will be explained in the section <link
617 linkend="pci-resource"><citetitle>PCI Resource
618 Managements</citetitle></link>.
622 <section id="basic-flow-constructor-main-component">
623 <title>4) Set the driver ID and name strings.</title>
628 strcpy(card->driver, "My Chip");
629 strcpy(card->shortname, "My Own Chip 123");
630 sprintf(card->longname, "%s at 0x%lx irq %i",
631 card->shortname, chip->ioport, chip->irq);
636 The driver field holds the minimal ID string of the
637 chip. This is referred by alsa-lib's configurator, so keep it
639 Even the same driver can have different driver IDs to
640 distinguish the functionality of each chip type.
644 The shortname field is a string shown as more verbose
645 name. The longname field contains the information which is
646 shown in <filename>/proc/asound/cards</filename>.
650 <section id="basic-flow-constructor-create-other">
651 <title>5) Create other components, such as mixer, MIDI, etc.</title>
653 Here you define the basic components such as
654 <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
655 mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
656 MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
657 and other interfaces.
658 Also, if you want a <link linkend="proc-interface"><citetitle>proc
659 file</citetitle></link>, define it here, too.
663 <section id="basic-flow-constructor-register-card">
664 <title>6) Register the card instance.</title>
669 if ((err = snd_card_register(card)) < 0) {
679 Will be explained in the section <link
680 linkend="card-management-registration"><citetitle>Management
681 of Cards and Components</citetitle></link>, too.
685 <section id="basic-flow-constructor-set-pci">
686 <title>7) Set the PCI driver data and return zero.</title>
691 pci_set_drvdata(pci, card);
698 In the above, the card record is stored. This pointer is
699 referred in the remove callback and power-management
705 <section id="basic-flow-destructor">
706 <title>Destructor</title>
708 The destructor, remove callback, simply releases the card
709 instance. Then the ALSA middle layer will release all the
710 attached components automatically.
714 It would be typically like the following:
719 static void __devexit snd_mychip_remove(struct pci_dev *pci)
721 snd_card_free(pci_get_drvdata(pci));
722 pci_set_drvdata(pci, NULL);
728 The above code assumes that the card pointer is set to the PCI
733 <section id="basic-flow-header-files">
734 <title>Header Files</title>
736 For the above example, at least the following include files
742 #include <sound/driver.h>
743 #include <linux/init.h>
744 #include <linux/pci.h>
745 #include <linux/slab.h>
746 #include <sound/core.h>
748 #include <sound/initval.h>
753 where the last twos are necessary only when module options are
754 defined in the source file. If the codes are split to several
755 files, the file without module options don't need them.
759 In addition to them, you'll need
760 <filename><linux/interrupt.h></filename> for the interrupt
761 handling, and <filename><asm/io.h></filename> for the i/o
762 access. If you use <function>mdelay()</function> or
763 <function>udelay()</function> functions, you'll need to include
764 <filename><linux/delay.h></filename>, too.
768 The ALSA interfaces like PCM or control API are define in other
769 header files as <filename><sound/xxx.h></filename>.
770 They have to be included after
771 <filename><sound/core.h></filename>.
778 <!-- ****************************************************** -->
779 <!-- Management of Cards and Components -->
780 <!-- ****************************************************** -->
781 <chapter id="card-management">
782 <title>Management of Cards and Components</title>
784 <section id="card-management-card-instance">
785 <title>Card Instance</title>
787 For each soundcard, a <quote>card</quote> record must be allocated.
791 A card record is the headquarters of the soundcard. It manages
792 the list of whole devices (components) on the soundcard, such as
793 PCM, mixers, MIDI, synthesizer, and so on. Also, the card
794 record holds the ID and the name strings of the card, manages
795 the root of proc files, and controls the power-management states
796 and hotplug disconnections. The component list on the card
797 record is used to manage the proper releases of resources at
802 As mentioned above, to create a card instance, call
803 <function>snd_card_new()</function>.
809 card = snd_card_new(index, id, module, extra_size);
816 The function takes four arguments, the card-index number, the
817 id string, the module pointer (usually
818 <constant>THIS_MODULE</constant>),
819 and the size of extra-data space. The last argument is used to
820 allocate card->private_data for the
821 chip-specific data. Note that this data
822 <emphasis>is</emphasis> allocated by
823 <function>snd_card_new()</function>.
827 <section id="card-management-component">
828 <title>Components</title>
830 After the card is created, you can attach the components
831 (devices) to the card instance. On ALSA driver, a component is
832 represented as a <type>snd_device_t</type> object.
833 A component can be a PCM instance, a control interface, a raw
834 MIDI interface, etc. Each of such instances has one component
839 A component can be created via
840 <function>snd_device_new()</function> function.
845 snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
852 This takes the card pointer, the device-level
853 (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
854 callback pointers (<parameter>&ops</parameter>). The
855 device-level defines the type of components and the order of
856 registration and de-registration. For most of components, the
857 device-level is already defined. For a user-defined component,
858 you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
862 This function itself doesn't allocate the data space. The data
863 must be allocated manually beforehand, and its pointer is passed
864 as the argument. This pointer is used as the identifier
865 (<parameter>chip</parameter> in the above example) for the
870 Each ALSA pre-defined component such as ac97 or pcm calls
871 <function>snd_device_new()</function> inside its
872 constructor. The destructor for each component is defined in the
873 callback pointers. Hence, you don't need to take care of
874 calling a destructor for such a component.
878 If you would like to create your own component, you need to
879 set the destructor function to dev_free callback in
880 <parameter>ops</parameter>, so that it can be released
881 automatically via <function>snd_card_free()</function>. The
882 example will be shown later as an implementation of a
887 <section id="card-management-chip-specific">
888 <title>Chip-Specific Data</title>
890 The chip-specific information, e.g. the i/o port address, its
891 resource pointer, or the irq number, is stored in the
892 chip-specific record.
893 Usually, the chip-specific record is typedef'ed as
894 <type>xxx_t</type> like the following:
899 typedef struct snd_mychip mychip_t;
909 You might have objections against such a typedef, but this
910 typedef is necessary if you use a <quote>magic-cast</quote>
912 linkend="card-management-chip-what-advantage"><citetitle>later</citetitle></link>).
916 In general, there are two ways to allocate the chip record.
919 <section id="card-management-chip-specific-snd-card-new">
920 <title>1. Allocating via <function>snd_card_new()</function>.</title>
922 As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
927 card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
932 whether <type>mychip_t</type> is the type of the chip record.
936 In return, the allocated record can be accessed as
941 mychip_t *chip = (mychip_t *)card->private_data;
946 With this method, you don't have to allocate twice. But you
947 cannot use <quote>magic-cast</quote> for this record pointer,
952 <section id="card-management-chip-specific-allocate-extra">
953 <title>2. Allocating an extra device.</title>
956 After allocating a card instance via
957 <function>snd_card_new()</function> (with
958 <constant>NULL</constant> on the 4th arg), call
959 <function>snd_magic_kcalloc()</function>.
966 card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
968 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
973 Once when the record is allocated via snd_magic stuff, you
974 can use <quote>magic-cast</quote> for the void pointer.
978 The chip record should have the field to hold the card
994 Then, set the card pointer in the returned chip instance.
1006 Also, you need to define a magic-value for <type>mychip_t</type>.
1011 #define mychip_t_magic 0xa15a4501
1015 (the detail will be described in the
1016 <link linkend="card-management-chip-what-advantage"><citetitle>
1017 next</citetitle></link> subsection).
1021 Next, initialize the fields, and register this chip
1022 record as a low-level device with a specified
1023 <parameter>ops</parameter>,
1028 static snd_device_ops_t ops = {
1029 .dev_free = snd_mychip_dev_free,
1032 snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1037 <function>snd_mychip_dev_free()</function> is the
1038 device-destructor function, which will call the real
1046 static int snd_mychip_dev_free(snd_device_t *device)
1048 mychip_t *chip = snd_magic_cast(mychip_t, device->device_data,
1050 return snd_mychip_free(chip);
1056 where <function>snd_mychip_free()</function> is the real destructor.
1060 <section id="card-management-chip-what-advantage">
1061 <title>Not a magic but a logic</title>
1063 <para>Now, you might have a question: What is the advantage of the
1064 second method? Obviously, it looks far more complicated.</para>
1066 As I wrote many times, the second method allows a
1067 <quote>magic-cast</quote> for <type>mychip_t</type>. If you
1068 have a void pointer (such as
1069 pcm->private_data), the pointer type
1070 is unknown at the compile time, and you cannot know even if a
1071 wrong pointer type is passed. The compiler would accept
1072 it. The magic-cast checks the pointer type at the runtime (and
1073 whether it's a null pointer, too). Hence, the cast will be
1074 much safer and good for debugging.
1078 As you have already seen, allocation with a magic-header can
1079 be done via <function>snd_magic_kmalloc()</function> or
1080 <function>snd_magic_kcalloc()</function>.
1086 chip = snd_magic_kmalloc(mychip_t, 0, GFP_KERNEL);
1087 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1092 The difference of these two functions is whether the area is
1093 zero-cleared (<function>kcalloc</function>) or not
1094 (<function>kmalloc</function>).
1098 The first argument of the allocator is the type of the
1099 record. The magic-constant has to be defined for this type
1100 beforehand. In this case, we'll need to define
1101 <constant>mychip_t_magic</constant>, for example, as already
1107 #define mychip_t_magic 0xa15a4501
1112 The value is arbitrary but should be unique.
1113 This is usually defined in
1114 <filename><include/sndmagic.h></filename> or
1115 <filename><include/amagic.h></filename> for alsa-driver tree,
1116 but you may define it locally in the code at the early
1117 development stage, since changing
1118 <filename>sndmagic.h</filename> will lead to the recompilation
1119 of the whole driver codes.
1123 The second argument is the extra-data length. It is usually
1124 zero. The third argument is the flags to be passed to kernel
1125 memory allocator, <constant>GFP_XXX</constant>. Normally,
1126 <constant>GFP_KERNEL</constant> is passed.
1130 For casting a pointer, use
1131 <function>snd_magic_cast()</function> macro:
1136 mychip_t *chip = snd_magic_cast(mychip_t, source_pointer, action);
1141 where <parameter>source_pointer</parameter> is the pointer to
1142 be casted (e.g. pcm->private_data), and
1143 <parameter>action</parameter> is the action to do if the cast
1144 fails (e.g. return <constant>-EINVAL</constant>).
1148 For releasing the magic-allocated data, you need to call
1149 <function>snd_magic_kfree()</function> function instead of
1150 <function>kfree()</function>.
1155 snd_magic_kfree(chip);
1162 If you call <function>kfree()</function> for the
1163 magic-allocated value, it will lead to memory leaks.
1164 When the ALSA drivers are compiled with
1165 <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config (or
1166 configured with <option>--with-debug=full</option>), the
1167 non-matching free will be checked and you'll see warning
1172 If you are 100% sure that your code is bug-free, you can
1173 compile the driver without
1174 <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config,
1175 so that the magic-allocator and the magic-cast will be
1176 replaced to the normal kmalloc and cast.
1181 <section id="card-management-registration">
1182 <title>Registration and Release</title>
1184 After all components are assigned, register the card instance
1185 by calling <function>snd_card_register()</function>. The access
1186 to the device files are enabled at this point. That is, before
1187 <function>snd_card_register()</function> is called, the
1188 components are safely inaccessible from external side. If this
1189 call fails, exit the probe function after releasing the card via
1190 <function>snd_card_free()</function>.
1194 For releasing the card instance, you can call simply
1195 <function>snd_card_free()</function>. As already mentioned, all
1196 components are released automatically by this call.
1200 As further notes, the destructors (both
1201 <function>snd_mychip_dev_free</function> and
1202 <function>snd_mychip_free</function>) cannot be defined with
1203 <parameter>__devexit</parameter> prefix, because they may be
1204 called from the constructor, too, at the false path.
1208 For a device which allows hotplugging, you can use
1209 <function>snd_card_free_in_thread</function>. This one will
1210 postpone the destruction and wait in a kernel-thread until all
1219 <!-- ****************************************************** -->
1220 <!-- PCI Resource Managements -->
1221 <!-- ****************************************************** -->
1222 <chapter id="pci-resource">
1223 <title>PCI Resource Managements</title>
1225 <section id="pci-resource-example">
1226 <title>Full Code Example</title>
1228 In this section, we'll finish the chip-specific constructor,
1229 destructor and PCI entries. The example code is shown first,
1233 <title>PCI Resource Managements Example</title>
1238 struct pci_dev *pci;
1241 struct resource *res_port;
1246 static int snd_mychip_free(mychip_t *chip)
1248 // disable hardware here if any
1249 // (not implemented in this document)
1251 // release the i/o port
1252 if (chip->res_port) {
1253 release_resource(chip->res_port);
1254 kfree_nocheck(chip->res_port);
1258 free_irq(chip->irq, (void *)chip);
1260 snd_magic_kfree(chip);
1264 // chip-specific constructor
1265 static int __devinit snd_mychip_create(snd_card_t *card,
1266 struct pci_dev *pci,
1271 static snd_device_ops_t ops = {
1272 .dev_free = snd_mychip_dev_free,
1277 // check PCI availability (28bit DMA)
1278 if ((err = pci_enable_device(pci)) < 0)
1280 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1281 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1282 printk(KERN_ERR "error to set 28bit mask DMA\n");
1286 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1290 // initialize the stuff
1295 // (1) PCI resource allocation
1296 chip->port = pci_resource_start(pci, 0);
1297 if ((chip->res_port = request_region(chip->port, 8,
1298 "My Chip")) == NULL) {
1299 snd_mychip_free(chip);
1300 printk(KERN_ERR "cannot allocate the port\n");
1303 if (request_irq(pci->irq, snd_mychip_interrupt,
1304 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1306 snd_mychip_free(chip);
1307 printk(KERN_ERR "cannot grab irq\n");
1310 chip->irq = pci->irq;
1312 // (2) initialization of the chip hardware
1313 // (not implemented in this document)
1315 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1317 snd_mychip_free(chip);
1325 static struct pci_device_id snd_mychip_ids[] = {
1326 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1327 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1331 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1333 // pci_driver definition
1334 static struct pci_driver driver = {
1335 .name = "My Own Chip",
1336 .id_table = snd_mychip_ids,
1337 .probe = snd_mychip_probe,
1338 .remove = __devexit_p(snd_mychip_remove),
1341 // initialization of the module
1342 static int __init alsa_card_mychip_init(void)
1344 return pci_module_init(&driver);
1347 // clean up the module
1348 static void __exit alsa_card_mychip_exit(void)
1350 pci_unregister_driver(&driver);
1353 module_init(alsa_card_mychip_init)
1354 module_exit(alsa_card_mychip_exit)
1356 EXPORT_NO_SYMBOLS; /* for old kernels only */
1363 <section id="pci-resource-some-haftas">
1364 <title>Some Hafta's</title>
1366 The allocation of PCI resources is done in the
1367 <function>probe()</function> function, and usually an extra
1368 <function>xxx_create()</function> function is written for this
1373 In the case of PCI devices, you have to call at first
1374 <function>pci_enable_device()</function> function before
1375 allocating resources. Also, you need to set the proper PCI DMA
1376 mask to limit the accessed i/o range. In some cases, you might
1377 need to call <function>pci_set_master()</function> function,
1382 Suppose the 28bit mask, and the code to be added would be like:
1387 if ((err = pci_enable_device(pci)) < 0)
1389 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1390 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1391 printk(KERN_ERR "error to set 28bit mask DMA\n");
1401 <section id="pci-resource-resource-allocation">
1402 <title>Resource Allocation</title>
1404 The allocation of I/O ports and irqs are done via standard kernel
1405 functions. Unlike ALSA ver.0.5.x., there are no helpers for
1406 that. And these resources must be released in the destructor
1407 function (see below). Also, on ALSA 0.9.x, you don't need to
1408 allocate (pseudo-)DMA for PCI like ALSA 0.5.x.
1412 Now assume that this PCI device has an I/O port with 8 bytes
1413 and an interrupt. Then <type>mychip_t</type> will have the
1423 struct resource *res_port;
1433 For an i/o port (and also a memory region), you need to have
1434 the resource pointer for the standard resource management. For
1435 an irq, you have to keep only the irq number (integer). But you
1436 need to initialize this number as -1 before actual allocation,
1437 since irq 0 is valid. The port address and its resource pointer
1438 can be initialized as null by
1439 <function>snd_magic_kcalloc()</function> automatically, so you
1440 don't have to take care of resetting them.
1444 The allocation of an i/o port is done like this:
1449 chip->port = pci_resource_start(pci, 0);
1450 if ((chip->res_port = request_region(chip->port, 8,
1451 "My Chip")) == NULL) {
1452 printk(KERN_ERR "cannot allocate the port 0x%lx\n",
1454 snd_mychip_free(chip);
1463 It will reserve the i/o port region of 8 bytes of the given
1464 PCI device. The returned value, chip->res_port, is allocated
1465 via <function>kmalloc()</function> by
1466 <function>request_region()</function>. The pointer must be
1467 released via <function>kfree()</function>, but there is some
1468 problem regarding this. This issue will be explained more below.
1472 The allocation of an interrupt source is done like this:
1477 if (request_irq(pci->irq, snd_mychip_interrupt,
1478 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1480 snd_mychip_free(chip);
1481 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1484 chip->irq = pci->irq;
1489 where <function>snd_mychip_interrupt()</function> is the
1490 interrupt handler defined <link
1491 linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1492 Note that chip->irq should be defined
1493 only when <function>request_irq()</function> succeeded.
1497 On the PCI bus, the interrupts can be shared. Thus,
1498 <constant>SA_SHIRQ</constant> is given as the interrupt flag of
1499 <function>request_irq()</function>.
1503 The last argument of <function>request_irq()</function> is the
1504 data pointer passed to the interrupt handler. Usually, the
1505 chip-specific record is used for that, but you can use what you
1510 I won't define the detail of the interrupt handler at this
1511 point, but at least its appearance can be explained now. The
1512 interrupt handler looks usually like the following:
1517 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1518 struct pt_regs *regs)
1520 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
1528 Again the magic-cast is used here to get the correct pointer
1529 from the second argument.
1533 Now let's write the corresponding destructor for the resources
1534 above. The role of destructor is simple: disable the hardware
1535 (if already activated) and release the resources. So far, we
1536 have no hardware part, so the disabling is not written here.
1540 For releasing the resources, <quote>check-and-release</quote>
1541 method is a safer way. For the i/o port, do like this:
1546 if (chip->res_port) {
1547 release_resource(chip->res_port);
1548 kfree_nocheck(chip->res_port);
1556 As you can see, the i/o resource pointer is also to be freed
1557 via <function>kfree_nocheck()</function> after
1558 <function>release_resource()</function> is called. You
1559 cannot use <function>kfree()</function> here, because on ALSA,
1560 <function>kfree()</function> may be a wrapper to its own
1561 allocator with the memory debugging. Since the resource pointer
1562 is allocated externally outside the ALSA, it must be released
1564 <function>kfree()</function>.
1565 <function>kfree_nocheck()</function> is used for that; it calls
1566 the native <function>kfree()</function> without wrapper.
1570 For releasing the interrupt, do like this:
1576 free_irq(chip->irq, (void *)chip);
1581 And finally, release the chip-specific record.
1586 snd_magic_kfree(chip);
1593 The chip instance is freed via
1594 <function>snd_magic_kfree()</function>. Please use this function
1595 for the object allocated by
1596 <function>snd_magic_kmalloc()</function>. If you free it with
1597 <function>kfree()</function>, it won't work properly and will
1598 result in the memory leak. Also, again, remember that you cannot
1599 set <parameter>__devexit</parameter> prefix for this destructor.
1603 We didn't implement the hardware-disabling part in the above.
1604 If you need to do this, please note that the destructor may be
1605 called even before the initialization of the chip is completed.
1606 It would be better to have a flag to skip the hardware-disabling
1607 if the hardware was not initialized yet.
1611 When the chip-data is assigned to the card using
1612 <function>snd_device_new()</function> with
1613 <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is
1614 called at the last. that is, it is assured that all other
1615 components like PCMs and controls have been already released.
1616 You don't have to call stopping PCMs, etc. explicitly, but just
1617 stop the hardware in the low-level.
1621 The management of a memory-mapped region is almost as same as
1622 the management of an i/o port. You'll need three fields like
1630 unsigned long iobase_phys;
1631 unsigned long iobase_virt;
1632 struct resource *res_iobase;
1638 and the allocation would be (assuming its size is 512 bytes):
1643 chip->iobase_phys = pci_resource_start(pci, 0);
1644 chip->iobase_virt = (unsigned long)
1645 ioremap_nocache(chip->iobase_phys, 512);
1646 if ((chip->res_port = request_mem_region(chip->iobase_phys, 512,
1647 "My Chip")) == NULL) {
1648 printk(KERN_ERR "cannot allocate the memory region\n");
1649 snd_mychip_free(chip);
1656 and the corresponding destructor would be:
1661 static int snd_mychip_free(mychip_t *chip)
1664 if (chip->iobase_virt)
1665 iounmap((void *)chip->iobase_virt);
1666 if (chip->res_iobase) {
1667 release_resource(chip->res_iobase);
1668 kfree_nocheck(chip->res_iobase);
1679 <section id="pci-resource-entries">
1680 <title>PCI Entries</title>
1682 So far, so good. Let's finish the rest of missing PCI
1683 stuffs. At first, we need a
1684 <structname>pci_device_id</structname> table for this
1685 chipset. It's a table of PCI vendor/device ID number, and some
1695 static struct pci_device_id snd_mychip_ids[] = {
1696 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1697 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1701 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1708 The first and second fields of
1709 <structname>pci_device_id</structname> struct are the vendor and
1710 device IDs. If you have nothing special to filter the matching
1711 devices, you can use the rest of fields like above. The last
1712 field of <structname>pci_device_id</structname> struct is a
1713 private data for this entry. You can specify any value here, for
1714 example, to tell the type of different operations per each
1715 device IDs. Such an example is found in intel8x0 driver.
1719 The last entry of this list is the terminator. You must
1720 specify this all-zero entry.
1724 Then, prepare the <structname>pci_driver</structname> record:
1729 static struct pci_driver driver = {
1730 .name = "My Own Chip",
1731 .id_table = snd_mychip_ids,
1732 .probe = snd_mychip_probe,
1733 .remove = __devexit_p(snd_mychip_remove),
1741 The <structfield>probe</structfield> and
1742 <structfield>remove</structfield> functions are what we already
1744 the previous sections. The <structfield>remove</structfield> should
1746 <function>__devexit_p()</function> macro, so that it's not
1747 defined for built-in (and non-hot-pluggable) case. The
1748 <structfield>name</structfield>
1749 field is the name string of this device. Note that you must not
1750 use a slash <quote>/</quote> in this string.
1754 And at last, the module entries:
1759 static int __init alsa_card_mychip_init(void)
1761 return pci_module_init(&driver);
1764 static void __exit alsa_card_mychip_exit(void)
1766 pci_unregister_driver(&driver);
1769 module_init(alsa_card_mychip_init)
1770 module_exit(alsa_card_mychip_exit)
1777 Note that these module entries are tagged with
1778 <parameter>__init</parameter> and
1779 <parameter>__exit</parameter> prefixes, not
1780 <parameter>__devinit</parameter> nor
1781 <parameter>__devexit</parameter>.
1785 Oh, one thing was forgotten. If you have no exported symbols,
1786 you need to declare it on 2.2 or 2.4 kernels (on 2.6 kernels
1787 it's not necessary, though).
1803 <!-- ****************************************************** -->
1804 <!-- PCM Interface -->
1805 <!-- ****************************************************** -->
1806 <chapter id="pcm-interface">
1807 <title>PCM Interface</title>
1809 <section id="pcm-interface-general">
1810 <title>General</title>
1812 The PCM middle layer of ALSA is quite powerful and it is only
1813 necessary for each driver to implement the low-level functions
1814 to access its hardware.
1818 For accessing to the PCM layer, you need to include
1819 <filename><sound/pcm.h></filename> above all. In addition,
1820 <filename><sound/pcm_params.h></filename> might be needed
1821 if you access to some functions related with hw_param.
1825 Each card device can have up to four pcm instances. A pcm
1826 instance corresponds to a pcm device file. The limitation of
1827 number of instances comes only from the available bit size of
1828 the linux's device number. Once when 64bit device number is
1829 used, we'll have more available pcm instances.
1833 A pcm instance consists of pcm playback and capture streams,
1834 and each pcm stream consists of one or more pcm substreams. Some
1835 soundcard supports the multiple-playback function. For example,
1836 emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1837 each open, a free substream is (usually) automatically chosen
1838 and opened. Meanwhile, when only one substream exists and it was
1839 already opened, the succeeding open will result in the blocking
1840 or the error with <constant>EAGAIN</constant> according to the
1841 file open mode. But you don't have to know the detail in your
1842 driver. The PCM middle layer will take all such jobs.
1846 <section id="pcm-interface-example">
1847 <title>Full Code Example</title>
1849 The example code below does not include any hardware access
1850 routines but shows only the skeleton, how to build up the PCM
1854 <title>PCM Example Code</title>
1857 #include <sound/pcm.h>
1860 #define chip_t mychip_t
1863 /* hardware definition */
1864 static snd_pcm_hardware_t snd_mychip_playback_hw = {
1865 .info = (SNDRV_PCM_INFO_MMAP |
1866 SNDRV_PCM_INFO_INTERLEAVED |
1867 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1868 SNDRV_PCM_INFO_MMAP_VALID),
1869 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1870 .rates = SNDRV_PCM_RATE_8000_48000,
1875 .buffer_bytes_max = 32768,
1876 .period_bytes_min = 4096,
1877 .period_bytes_max = 32768,
1879 .periods_max = 1024,
1882 /* hardware definition */
1883 static snd_pcm_hardware_t snd_mychip_capture_hw = {
1884 .info = (SNDRV_PCM_INFO_MMAP |
1885 SNDRV_PCM_INFO_INTERLEAVED |
1886 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1887 SNDRV_PCM_INFO_MMAP_VALID),
1888 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1889 .rates = SNDRV_PCM_RATE_8000_48000,
1894 .buffer_bytes_max = 32768,
1895 .period_bytes_min = 4096,
1896 .period_bytes_max = 32768,
1898 .periods_max = 1024,
1902 static int snd_mychip_playback_open(snd_pcm_substream_t *substream)
1904 mychip_t *chip = snd_pcm_substream_chip(substream);
1905 snd_pcm_runtime_t *runtime = substream->runtime;
1907 runtime->hw = snd_mychip_playback_hw;
1908 // more hardware-initialization will be done here
1912 /* close callback */
1913 static int snd_mychip_playback_close(snd_pcm_substream_t *substream)
1915 mychip_t *chip = snd_pcm_substream_chip(substream);
1916 // the hardware-specific codes will be here
1922 static int snd_mychip_capture_open(snd_pcm_substream_t *substream)
1924 mychip_t *chip = snd_pcm_substream_chip(substream);
1925 snd_pcm_runtime_t *runtime = substream->runtime;
1927 runtime->hw = snd_mychip_capture_hw;
1928 // more hardware-initialization will be done here
1932 /* close callback */
1933 static int snd_mychip_capture_close(snd_pcm_substream_t *substream)
1935 mychip_t *chip = snd_pcm_substream_chip(substream);
1936 // the hardware-specific codes will be here
1941 /* hw_params callback */
1942 static int snd_mychip_pcm_hw_params(snd_pcm_substream_t *substream,
1943 snd_pcm_hw_params_t * hw_params)
1945 return snd_pcm_lib_malloc_pages(substream,
1946 params_buffer_bytes(hw_params));
1949 /* hw_free callback */
1950 static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1952 return snd_pcm_lib_free_pages(substream);
1955 /* prepare callback */
1956 static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1958 mychip_t *chip = snd_pcm_substream_chip(substream);
1959 snd_pcm_runtime_t *runtime = substream->runtime;
1961 // set up the hardware with the current configuration
1963 mychip_set_sample_format(chip, runtime->format);
1964 mychip_set_sample_rate(chip, runtime->rate);
1965 mychip_set_channels(chip, runtime->channels);
1966 mychip_set_dma_setup(chip, runtime->dma_area,
1972 /* trigger callback */
1973 static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
1977 case SNDRV_PCM_TRIGGER_START:
1978 // do something to start the PCM engine
1980 case SNDRV_PCM_TRIGGER_STOP:
1981 // do something to stop the PCM engine
1988 /* pointer callback */
1989 static snd_pcm_uframes_t
1990 snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
1992 mychip_t *chip = snd_pcm_substream_chip(substream);
1993 unsigned int current_ptr;
1995 // get the current hardware pointer
1996 current_ptr = mychip_get_hw_pointer(chip);
2001 static snd_pcm_ops_t snd_mychip_playback_ops = {
2002 .open = snd_mychip_playback_open,
2003 .close = snd_mychip_playback_close,
2004 .ioctl = snd_pcm_lib_ioctl,
2005 .hw_params = snd_mychip_pcm_hw_params,
2006 .hw_free = snd_mychip_pcm_hw_free,
2007 .prepare = snd_mychip_pcm_prepare,
2008 .trigger = snd_mychip_pcm_trigger,
2009 .pointer = snd_mychip_pcm_pointer,
2013 static snd_pcm_ops_t snd_mychip_capture_ops = {
2014 .open = snd_mychip_capture_open,
2015 .close = snd_mychip_capture_close,
2016 .ioctl = snd_pcm_lib_ioctl,
2017 .hw_params = snd_mychip_pcm_hw_params,
2018 .hw_free = snd_mychip_pcm_hw_free,
2019 .prepare = snd_mychip_pcm_prepare,
2020 .trigger = snd_mychip_pcm_trigger,
2021 .pointer = snd_mychip_pcm_pointer,
2025 * definitions of capture are omitted here...
2028 /* create a pcm device */
2029 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2034 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2037 pcm->private_data = chip;
2038 strcpy(pcm->name, "My Chip");
2041 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2042 &snd_mychip_playback_ops);
2043 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2044 &snd_mychip_capture_ops);
2045 /* pre-allocation of buffers */
2046 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2047 snd_dma_pci_data(chip->pci),
2057 <section id="pcm-interface-constructor">
2058 <title>Constructor</title>
2060 A pcm instance is allocated <function>snd_pcm_new()</function>
2061 function. It would be better to create a constructor for pcm,
2067 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2072 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2075 pcm->private_data = chip;
2076 strcpy(pcm->name, "My Chip");
2087 The <function>snd_pcm_new()</function> function takes the four
2088 arguments. The first argument is the card pointer to which this
2089 pcm is assigned, and the second is the ID string.
2093 The third argument (<parameter>index</parameter>, 0 in the
2094 above) is the index of this new pcm. It begins from zero. When
2095 you will create more than one pcm instances, specify the
2096 different numbers in this argument. For example,
2097 <parameter>index</parameter> = 1 for the second PCM device.
2101 The fourth and fifth arguments are the number of substreams
2102 for playback and capture, respectively. Here both 1 are given in
2103 the above example. When no playback or no capture is available,
2104 pass 0 to the corresponding argument.
2108 If a chip supports multiple playbacks or captures, you can
2109 specify more numbers, but they must be handled properly in
2110 open/close, etc. callbacks. When you need to know which
2111 substream you are referring to, then it can be obtained from
2112 <type>snd_pcm_substream_t</type> data passed to each callback
2118 snd_pcm_substream_t *substream;
2119 int index = substream->number;
2126 After the pcm is created, you need to set operators for each
2132 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2133 &snd_mychip_playback_ops);
2134 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2135 &snd_mychip_capture_ops);
2142 The operators are defined typically like this:
2147 static snd_pcm_ops_t snd_mychip_playback_ops = {
2148 .open = snd_mychip_pcm_open,
2149 .close = snd_mychip_pcm_close,
2150 .ioctl = snd_pcm_lib_ioctl,
2151 .hw_params = snd_mychip_pcm_hw_params,
2152 .hw_free = snd_mychip_pcm_hw_free,
2153 .prepare = snd_mychip_pcm_prepare,
2154 .trigger = snd_mychip_pcm_trigger,
2155 .pointer = snd_mychip_pcm_pointer,
2161 Each of callbacks is explained in the subsection
2162 <link linkend="pcm-interface-operators"><citetitle>
2163 Operators</citetitle></link>.
2167 After setting the operators, most likely you'd like to
2168 pre-allocate the buffer. For the pre-allocation, simply call
2174 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2175 snd_dma_pci_data(chip->pci),
2181 It will allocate up to 64kB buffer as default. The details of
2182 buffer management will be described in the later section <link
2183 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2184 Management</citetitle></link>.
2188 Additionally, you can set some extra information for this pcm
2189 in pcm->info_flags.
2190 The available values are defined as
2191 <constant>SNDRV_PCM_INFO_XXX</constant> in
2192 <filename><sound/asound.h></filename>, which is used for
2193 the hardware definition (described later). When your soundchip
2194 supports only half-duplex, specify like this:
2199 pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2206 <section id="pcm-interface-destructor">
2207 <title>... And the Destructor?</title>
2209 The destructor for a pcm instance is not always
2210 necessary. Since the pcm device will be released by the middle
2211 layer code automatically, you don't have to call destructor
2216 The destructor would be necessary when you created some
2217 special records internally and need to release them. In such a
2218 case, set the destructor function to
2219 pcm->private_free:
2222 <title>PCM Instance with a Destructor</title>
2225 static void mychip_pcm_free(snd_pcm_t *pcm)
2227 mychip_t *chip = snd_magic_cast(mychip_t,
2228 pcm->private_data, return);
2229 // free your own data
2230 kfree(chip->my_private_pcm_data);
2231 // do what you like else...
2234 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2238 // allocate your own data
2239 chip->my_private_pcm_data = kmalloc(...);
2240 // set the destructor
2241 pcm->private_data = chip;
2242 pcm->private_free = mychip_pcm_free;
2251 <section id="pcm-interface-runtime">
2252 <title>Runtime Pointer - The Chest of PCM Information</title>
2254 When the PCM substream is opened, a PCM runtime instance is
2255 allocated and assigned to the substream. This pointer is
2256 accessible via <constant>substream->runtime</constant>.
2257 This runtime pointer holds the various information; it holds
2258 the copy of hw_params and sw_params configurations, the buffer
2259 pointers, mmap records, spinlocks, etc. Almost everyhing you
2260 need for controlling the PCM can be found there.
2264 The definition of runtime instance is found in
2265 <filename><sound/pcm.h></filename>. Here is the
2270 struct _snd_pcm_runtime {
2272 snd_pcm_substream_t *trigger_master;
2273 snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2275 snd_pcm_uframes_t avail_max;
2276 snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */
2277 snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2279 /* -- HW params -- */
2280 snd_pcm_access_t access; /* access mode */
2281 snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */
2282 snd_pcm_subformat_t subformat; /* subformat */
2283 unsigned int rate; /* rate in Hz */
2284 unsigned int channels; /* channels */
2285 snd_pcm_uframes_t period_size; /* period size */
2286 unsigned int periods; /* periods */
2287 snd_pcm_uframes_t buffer_size; /* buffer size */
2288 unsigned int tick_time; /* tick time */
2289 snd_pcm_uframes_t min_align; /* Min alignment for the format */
2291 unsigned int frame_bits;
2292 unsigned int sample_bits;
2294 unsigned int rate_num;
2295 unsigned int rate_den;
2297 /* -- SW params -- */
2298 int tstamp_timespec; /* use timeval (0) or timespec (1) */
2299 snd_pcm_tstamp_t tstamp_mode; /* mmap timestamp is updated */
2300 unsigned int period_step;
2301 unsigned int sleep_min; /* min ticks to sleep */
2302 snd_pcm_uframes_t xfer_align; /* xfer size need to be a multiple */
2303 snd_pcm_uframes_t start_threshold;
2304 snd_pcm_uframes_t stop_threshold;
2305 snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2306 noise is nearest than this */
2307 snd_pcm_uframes_t silence_size; /* Silence filling size */
2308 snd_pcm_uframes_t boundary; /* pointers wrap point */
2310 snd_pcm_uframes_t silenced_start;
2311 snd_pcm_uframes_t silenced_size;
2313 snd_pcm_sync_id_t sync; /* hardware synchronization ID */
2316 volatile snd_pcm_mmap_status_t *status;
2317 volatile snd_pcm_mmap_control_t *control;
2318 atomic_t mmap_count;
2320 /* -- locking / scheduling -- */
2322 wait_queue_head_t sleep;
2323 struct timer_list tick_timer;
2324 struct fasync_struct *fasync;
2326 /* -- private section -- */
2328 void (*private_free)(snd_pcm_runtime_t *runtime);
2330 /* -- hardware description -- */
2331 snd_pcm_hardware_t hw;
2332 snd_pcm_hw_constraints_t hw_constraints;
2334 /* -- interrupt callbacks -- */
2335 void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2336 void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2339 unsigned int timer_resolution; /* timer resolution */
2342 unsigned char *dma_area; /* DMA area */
2343 dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */
2344 size_t dma_bytes; /* size of DMA area */
2345 void *dma_private; /* private DMA data for the memory allocator */
2347 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2348 /* -- OSS things -- */
2349 snd_pcm_oss_runtime_t oss;
2358 For the operators (callbacks) of each sound driver, most of
2359 these records are supposed to be read-only. Only the PCM
2360 middle-layer changes / updates these info. The excpetions are
2361 the hardware description (hw), interrupt callbacks
2362 (transfer_ack_xxx), DMA buffer information, and the private
2363 data. Besides, if you use the standard buffer allocation
2364 method via <function>snd_pcm_lib_malloc_pages()</function>,
2365 you don't need to set the DMA buffer information by yourself.
2369 In the sections below, important records are explained.
2372 <section id="pcm-interface-runtime-hw">
2373 <title>Hardware Description</title>
2375 The hardware descriptor (<type>snd_pcm_hardware_t</type>)
2376 contains the definitions of the fundamental hardware
2377 configuration. Above all, you'll need to define this in
2378 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2379 the open callback</citetitle></link>.
2380 Note that the runtime instance holds the copy of the
2381 descriptor, not the pointer to the existing descriptor. That
2382 is, in the open callback, you can modify the copied descriptor
2383 (<constant>runtime->hw</constant>) as you need. For example, if the maximum
2384 number of channels is 1 only on some chip models, you can
2385 still use the same hardware descriptor and change the
2390 snd_pcm_runtime_t *runtime = substream->runtime;
2392 runtime->hw = snd_mychip_playback_hw; // common definition
2393 if (chip->model == VERY_OLD_ONE)
2394 runtime->hw.channels_max = 1;
2401 Typically, you'll have a hardware descriptor like below:
2405 static snd_pcm_hardware_t snd_mychip_playback_hw = {
2406 .info = (SNDRV_PCM_INFO_MMAP |
2407 SNDRV_PCM_INFO_INTERLEAVED |
2408 SNDRV_PCM_INFO_BLOCK_TRANSFER |
2409 SNDRV_PCM_INFO_MMAP_VALID),
2410 .formats = SNDRV_PCM_FMTBIT_S16_LE,
2411 .rates = SNDRV_PCM_RATE_8000_48000,
2416 .buffer_bytes_max = 32768,
2417 .period_bytes_min = 4096,
2418 .period_bytes_max = 32768,
2420 .periods_max = 1024,
2430 The <structfield>info</structfield> field contains the type and
2431 capabilities of this pcm. The bit flags are defined in
2432 <filename><sound/asound.h></filename> as
2433 <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2434 have to specify whether the mmap is supported and which
2435 interleaved format is supported.
2436 When the mmap is supported, add
2437 <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2438 hardware supports the interleaved or the non-interleaved
2439 format, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2440 <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2441 be set, respectively. If both are supported, you can set both,
2446 In the above example, <constant>MMAP_VALID</constant> and
2447 <constant>BLOCK_TRANSFER</constant> are specified for OSS mmap
2448 mode. Usually both are set. Of course,
2449 <constant>MMAP_VALID</constant> is set only if the mmap is
2454 The other possible flags are
2455 <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2456 <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2457 <constant>PAUSE</constant> bit means that the pcm supports the
2458 <quote>pause</quote> operation, while the
2459 <constant>RESUME</constant> bit means that the pcm supports
2460 the <quote>suspend/resume</quote> operation. If these flags
2461 are set, the <structfield>trigger</structfield> callback below
2462 must handle the corresponding commands.
2466 When the PCM substreams can be synchronized (typically,
2467 synchorinized start/stop of a playback and a capture streams),
2468 you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2469 too. In this case, you'll need to check the linked-list of
2470 PCM substreams in the trigger callback. This will be
2471 described in the later section.
2477 <structfield>formats</structfield> field contains the bit-flags
2478 of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2479 If the hardware supports more than one format, give all or'ed
2480 bits. In the example above, the signed 16bit little-endian
2481 format is specified.
2487 <structfield>rates</structfield> field contains the bit-flags of
2488 supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2489 When the chip supports continuous rates, pass
2490 <constant>CONTINUOUS</constant> bit additionally.
2491 The pre-defined rate bits are provided only for typical
2492 rates. If your chip supports unconventional rates, you need to add
2493 <constant>KNOT</constant> bit and set up the hardware
2494 constraint manually (explained later).
2500 <structfield>rate_min</structfield> and
2501 <structfield>rate_max</structfield> define the minimal and
2502 maximal sample rate. This should correspond somehow to
2503 <structfield>rates</structfield> bits.
2509 <structfield>channel_min</structfield> and
2510 <structfield>channel_max</structfield>
2511 define, as you might already expected, the minimal and maximal
2518 <structfield>buffer_bytes_max</structfield> defines the
2519 maximal buffer size in bytes. There is no
2520 <structfield>buffer_bytes_min</structfield> field, since
2521 it can be calculated from the minimal period size and the
2522 minimal number of periods.
2523 Meanwhile, <structfield>period_bytes_min</structfield> and
2524 define the minimal and maximal size of the period in bytes.
2525 <structfield>periods_max</structfield> and
2526 <structfield>periods_min</structfield> define the maximal and
2527 minimal number of periods in the buffer.
2531 The <quote>period</quote> is a term, that corresponds to
2532 fragment in the OSS world. The period defines the size at
2533 which the PCM interrupt is generated. This size strongly
2534 depends on the hardware.
2535 Generally, the smaller period size will give you more
2536 interrupts, that is, more controls.
2537 In the case of capture, this size defines the input latency.
2538 On the other hand, the whole buffer size defines the
2539 output latency for the playback direction.
2545 There is also a field <structfield>fifo_size</structfield>.
2546 This specifies the size of the hardware FIFO, but it's not
2547 used currently in the driver nor in the alsa-lib. So, you
2548 can ignore this field.
2555 <section id="pcm-interface-runtime-config">
2556 <title>PCM Configurations</title>
2558 Ok, let's go back again to the PCM runtime records.
2559 The most frequently referred records in the runtime instance are
2560 the PCM configurations.
2561 The PCM configurations are stored on runtime instance
2562 after the application sends <type>hw_params</type> data via
2563 alsa-lib. There are many fields copied from hw_params and
2564 sw_params structs. For example,
2565 <structfield>format</structfield> holds the format type
2566 chosen by the application. This field contains the enum value
2567 <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2571 One thing to be noted is that the configured buffer and period
2572 sizes are stored in <quote>frames</quote> in the runtime
2573 In the ALSA world, 1 frame = channels * samples-size.
2574 For conversion between frames and bytes, you can use the
2575 helper functions, <function>frames_to_bytes()</function> and
2576 <function>bytes_to_frames()</function>.
2580 period_bytes = frames_to_bytes(runtime, runtime->period_size);
2587 Also, many software parameters (sw_params) are
2588 stored in frames, too. Please check the type of the field.
2589 <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2590 integer while <type>snd_pcm_sframes_t</type> is for the frames
2595 <section id="pcm-interface-runtime-dma">
2596 <title>DMA Buffer Information</title>
2598 The DMA buffer is defined by the following four fields,
2599 <structfield>dma_area</structfield>,
2600 <structfield>dma_addr</structfield>,
2601 <structfield>dma_bytes</structfield> and
2602 <structfield>dma_private</structfield>.
2603 The <structfield>dma_area</structfield> holds the buffer
2604 pointer (the logical address). You can call
2605 <function>memcpy</function> from/to
2606 this pointer. Meanwhile, <structfield>dma_addr</structfield>
2607 holds the physical address of the buffer. This field is
2608 specified only when the buffer is a linear buffer.
2609 <structfield>dma_bytes</structfield> holds the size of buffer
2610 in bytes. <structfield>dma_private</structfield> is used for
2611 the ALSA DMA allocator.
2615 If you use a standard ALSA function,
2616 <function>snd_pcm_lib_malloc_pages()</function>, for
2617 allocating the buffer, these fields are set by the ALSA middle
2618 layer, and you should <emphasis>not</emphasis> change them by
2619 yourself. You can read them but not write them.
2620 On the other hand, if you want to allocate the buffer by
2621 yourself, you'll need to manage it in hw_params callback.
2622 At least, <structfield>dma_bytes</structfield> is mandatory.
2623 <structfield>dma_area</structfield> is necessary when the
2624 buffer is mmapped. If your driver doesn't support mmap, this
2625 field is not necessary. <structfield>dma_addr</structfield>
2626 is also not mandatory. You can use
2627 <structfield>dma_private</structfield> as you like, too.
2631 <section id="pcm-interface-runtime-status">
2632 <title>Running Status</title>
2634 The running status can be referred via <constant>runtime->status</constant>.
2635 This is the pointer to <type>snd_pcm_mmap_status_t</type>
2636 record. For example, you can get the current DMA hardware
2637 pointer via <constant>runtime->status->hw_ptr</constant>.
2641 The DMA application pointer can be referred via
2642 <constant>runtime->control</constant>, which points
2643 <type>snd_pcm_mmap_control_t</type> record.
2644 However, accessing directly to this value is not recommended.
2648 <section id="pcm-interface-runtime-private">
2649 <title>Private Data</title>
2651 You can allocate a record for the substream and store it in
2652 <constant>runtime->private_data</constant>. Usually, this
2654 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2655 the open callback</citetitle></link>.
2656 Since it's a void pointer, you should use magic-kmalloc and
2657 magic-cast for such an object.
2662 static int snd_xxx_open(snd_pcm_substream_t *substream)
2664 my_pcm_data_t *data;
2666 data = snd_magic_kmalloc(my_pcm_data_t, 0, GFP_KERNEL);
2667 substream->runtime->private_data = data;
2676 The allocated object must be released in
2677 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2678 the close callback</citetitle></link>.
2682 <section id="pcm-interface-runtime-intr">
2683 <title>Interrupt Callbacks</title>
2685 The field <structfield>transfer_ack_begin</structfield> and
2686 <structfield>transfer_ack_end</structfield> are called at
2687 the beginning and the end of
2688 <function>snd_pcm_period_elapsed()</function>, respectively.
2694 <section id="pcm-interface-operators">
2695 <title>Operators</title>
2697 OK, now let me explain the detail of each pcm callback
2698 (<parameter>ops</parameter>). In general, every callback must
2699 return 0 if successful, or a negative number with the error
2700 number such as <constant>-EINVAL</constant> at any
2705 The callback function takes at least the argument with
2706 <type>snd_pcm_substream_t</type> pointer. For retrieving the
2707 chip record from the given substream instance, you can use the
2713 #define chip_t mychip_t
2716 mychip_t *chip = snd_pcm_substream_chip(substream);
2725 It's expanded with a magic-cast, so the cast-error is
2726 automatically checked. You should define <type>chip_t</type> at
2727 the beginning of the code, since this will be referred in many
2728 places of pcm and control interfaces.
2731 <section id="pcm-interface-operators-open-callback">
2732 <title>open callback</title>
2737 static int snd_xxx_open(snd_pcm_substream_t *substream);
2742 This is called when a pcm substream is opened.
2746 At least, here you have to initialize the runtime->hw
2747 record. Typically, this is done by like this:
2752 static int snd_xxx_open(snd_pcm_substream_t *substream)
2754 mychip_t *chip = snd_pcm_substream_chip(substream);
2755 snd_pcm_runtime_t *runtime = substream->runtime;
2757 runtime->hw = snd_mychip_playback_hw;
2764 where <parameter>snd_mychip_playback_hw</parameter> is the
2765 pre-defined hardware description.
2769 You can allocate a private data in this callback, as described
2770 in <link linkend="pcm-interface-runtime-private"><citetitle>
2771 Private Data</citetitle></link> section.
2775 If the hardware configuration needs more constraints, set the
2776 hardware constraints here, too.
2777 See <link linkend="pcm-interface-constraints"><citetitle>
2778 Constraints</citetitle></link> for more details.
2782 <section id="pcm-interface-operators-close-callback">
2783 <title>close callback</title>
2788 static int snd_xxx_close(snd_pcm_substream_t *substream);
2793 Obviously, this is called when a pcm substream is closed.
2797 Any private instance for a pcm substream allocated in the
2798 open callback will be released here.
2803 static int snd_xxx_close(snd_pcm_substream_t *substream)
2806 snd_magic_kfree(substream->runtime->private_data);
2815 <section id="pcm-interface-operators-ioctl-callback">
2816 <title>ioctl callback</title>
2818 This is used for any special action to pcm ioctls. But
2819 usually you can pass a generic ioctl callback,
2820 <function>snd_pcm_lib_ioctl</function>.
2824 <section id="pcm-interface-operators-hw-params-callback">
2825 <title>hw_params callback</title>
2830 static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2831 snd_pcm_hw_params_t * hw_params);
2836 This and <structfield>hw_free</structfield> callbacks exist
2841 This is called when the hardware parameter
2842 (<structfield>hw_params</structfield>) is set
2843 up by the application,
2844 that is, once when the buffer size, the period size, the
2845 format, etc. are defined for the pcm substream.
2849 Many hardware set-up should be done in this callback,
2850 including the allocation of buffers.
2854 Parameters to be initialized are retrieved by
2855 <function>params_xxx()</function> macros. For allocating a
2856 buffer, you can call a helper function,
2861 snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2866 <function>snd_pcm_lib_malloc_pages()</function> is available
2867 only when the DMA buffers have been pre-allocated.
2868 See the section <link
2869 linkend="buffer-and-memory-buffer-types"><citetitle>
2870 Buffer Types</citetitle></link> for more details.
2874 Note that this and <structfield>prepare</structfield> callbacks
2875 may be called multiple times per initialization.
2876 For example, the OSS emulation may
2877 call these callbacks at each change via its ioctl.
2881 Thus, you need to take care not to allocate the same buffers
2882 many times, which will lead to memory leak! Calling the
2883 helper function above many times is OK. It will release the
2884 previous buffer automatically when it was already allocated.
2888 Another note is that this callback is non-atomic
2889 (schedulable). This is important, because the
2890 <structfield>prepare</structfield> callback
2891 is atomic (non-schedulable). That is, mutex or any
2892 schedule-related functions are available only in
2893 <structfield>hw_params</structfield> callback.
2894 Please see the subsection
2895 <link linkend="pcm-interface-atomicity"><citetitle>
2896 Atomicity</citetitle></link> for details.
2900 <section id="pcm-interface-operators-hw-free-callback">
2901 <title>hw_free callback</title>
2906 static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2913 This is called to release the resources allocated via
2914 <structfield>hw_params</structfield>. For example, releasing the
2916 <function>snd_pcm_lib_malloc_pages()</function> is done by
2917 calling the following:
2922 snd_pcm_lib_free_pages(substream);
2929 This function is always called before the close callback is called.
2930 Also, the callback may be called multiple times, too.
2931 Keep track whether the resource was already released.
2935 <section id="pcm-interface-operators-prepare-callback">
2936 <title>prepare callback</title>
2941 static int snd_xxx_prepare(snd_pcm_substream_t * substream);
2948 This callback is called when the pcm is
2949 <quote>prepared</quote>. You can set the format type, sample
2950 rate, etc. here. The difference from
2951 <structfield>hw_params</structfield> is that the
2952 <structfield>prepare</structfield> callback will be called at each
2954 <function>snd_pcm_prepare()</function> is called, i.e. when
2955 recovered after underruns, etc.
2959 As mentioned above, this callback is atomic.
2963 In this and the following callbacks, you can refer to the
2964 values via the runtime record,
2965 substream->runtime.
2966 For example, to get the current
2967 rate, format or channels, access to
2969 runtime->format or
2970 runtime->channels, respectively.
2971 The physical address of the allocated buffer is set to
2972 runtime->dma_area. The buffer and period sizes are
2973 in runtime->buffer_size and runtime->period_size,
2978 Be careful that this callback will be called many times at
2983 <section id="pcm-interface-operators-trigger-callback">
2984 <title>trigger callback</title>
2989 static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
2994 This is called when the pcm is started, stopped or paused.
2998 Which action is specified in the second argument,
2999 <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
3000 <filename><sound/pcm.h></filename>. At least,
3001 <constant>START</constant> and <constant>STOP</constant>
3002 commands must be defined in this callback.
3008 case SNDRV_PCM_TRIGGER_START:
3009 // do something to start the PCM engine
3011 case SNDRV_PCM_TRIGGER_STOP:
3012 // do something to stop the PCM engine
3023 When the pcm supports the pause operation (given in info
3024 field of the hardware table), <constant>PAUSE_PUSE</constant>
3025 and <constant>PAUSE_RELEASE</constant> commands must be
3026 handled here, too. The former is the command to pause the pcm,
3027 and the latter to restart the pcm again.
3031 When the pcm supports the suspend/resume operation
3032 (i.e. <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set),
3033 <constant>SUSPEND</constant> and <constant>RESUME</constant>
3034 commands must be handled, too.
3035 These commands are issued when the power-management status is
3036 changed. Obviously, the <constant>SUSPEND</constant> and
3037 <constant>RESUME</constant>
3038 do suspend and resume of the pcm substream, and usually, they
3039 are identical with <constant>STOP</constant> and
3040 <constant>START</constant> commands, respectively.
3044 This callback is also atomic.
3048 <section id="pcm-interface-operators-pointer-callback">
3049 <title>pointer callback</title>
3054 static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
3059 This callback is called when the PCM middle layer inquires
3060 the current hardware position on the buffer. The position must
3061 be returned in frames (which was in bytes on ALSA 0.5.x),
3062 ranged from 0 to buffer_size - 1.
3066 This is called usually from the buffer-update routine in the
3067 pcm middle layer, which is invoked when
3068 <function>snd_pcm_period_elapsed()</function> is called in the
3069 interrupt routine. Then the pcm middle layer updates the
3070 position and calculates the available space, and wakes up the
3071 sleeping poll threads, etc.
3075 This callback is also atomic.
3079 <section id="pcm-interface-operators-copy-silence">
3080 <title>copy and silence callbacks</title>
3082 These callbacks are not mandatory, and can be omitted in
3083 most cases. These callbacks are used when the hardware buffer
3084 cannot be on the normal memory space. Some chips have their
3085 own buffer on the hardware which is not mappable. In such a
3086 case, you have to transfer the data manually from the memory
3087 buffer to the hardware buffer. Or, if the buffer is
3088 non-contiguous on both physical and virtual memory spaces,
3089 these callbacks must be defined, too.
3093 If these two callbacks are defined, copy and set-silence
3094 operations are done by them. The detailed will be described in
3095 the later section <link
3096 linkend="buffer-and-memory"><citetitle>Buffer and Memory
3097 Management</citetitle></link>.
3101 <section id="pcm-interface-operators-ack">
3102 <title>ack callback</title>
3104 This callback is also not mandatory. This callback is called
3105 when the appl_ptr is updated in read or write operations.
3106 Some drivers like emu10k1-fx and cs46xx need to track the
3107 current appl_ptr for the internal buffer, and this callback
3108 is useful only for such a purpose.
3112 <section id="pcm-interface-operators-page-callback">
3113 <title>page callback</title>
3116 This callback is also not mandatory. This callback is used
3117 mainly for the non-contiguous buffer. The mmap calls this
3118 callback to get the page address. Some examples will be
3119 explained in the later section <link
3120 linkend="buffer-and-memory"><citetitle>Buffer and Memory
3121 Management</citetitle></link>, too.
3126 <section id="pcm-interface-interrupt-handler">
3127 <title>Interrupt Handler</title>
3129 The rest of pcm stuff is the PCM interrupt handler. The
3130 role of PCM interrupt handler in the sound driver is to update
3131 the buffer position and to tell the PCM middle layer when the
3132 buffer position goes across the prescribed period size. To
3133 inform this, call <function>snd_pcm_period_elapsed()</function>
3138 There are several types of sound chips to generate the interrupts.
3141 <section id="pcm-interface-interrupt-handler-boundary">
3142 <title>Interrupts at the period (fragment) boundary</title>
3144 This is the most frequently found type: the hardware
3145 generates an interrupt at each period boundary.
3146 In this case, you can call
3147 <function>snd_pcm_period_elapsed()</function> at each
3152 <function>snd_pcm_period_elapsed()</function> takes the
3153 substream pointer as its argument. Thus, you need to keep the
3154 substream pointer accessible from the chip instance. For
3155 example, define substream field in the chip record to hold the
3156 current running substream pointer, and set the pointer value
3157 at open callback (and reset at close callback).
3161 If you aquire a spinlock in the interrupt handler, and the
3162 lock is used in other pcm callbacks, too, then you have to
3163 release the lock before calling
3164 <function>snd_pcm_period_elapsed()</function>, because
3165 <function>snd_pcm_period_elapsed()</function> calls other pcm
3170 A typical coding would be like:
3173 <title>Interrupt Handler Case #1</title>
3176 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3177 struct pt_regs *regs)
3179 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3180 spin_lock(&chip->lock);
3182 if (pcm_irq_invoked(chip)) {
3183 // call updater, unlock before it
3184 spin_unlock(&chip->lock);
3185 snd_pcm_period_elapsed(chip->substream);
3186 spin_lock(&chip->lock);
3187 // acknowledge the interrupt if necessary
3190 spin_unlock(&chip->lock);
3199 <section id="pcm-interface-interrupt-handler-timer">
3200 <title>High-frequent timer interrupts</title>
3202 This is the case when the hardware doesn't generate interrupts
3203 at the period boundary but do timer-interrupts at the fixed
3204 timer rate (e.g. es1968 or ymfpci drivers).
3205 In this case, you need to check the current hardware
3206 position and accumulates the processed sample length at each
3207 interrupt. When the accumulated size overcomes the period
3209 <function>snd_pcm_period_elapsed()</function> and reset the
3214 A typical coding would be like the following.
3217 <title>Interrupt Handler Case #2</title>
3220 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3221 struct pt_regs *regs)
3223 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3224 spin_lock(&chip->lock);
3226 if (pcm_irq_invoked(chip)) {
3227 unsigned int last_ptr, size;
3228 // get the current hardware pointer (in frames)
3229 last_ptr = get_hw_ptr(chip);
3230 // calculate the processed frames since the
3232 if (last_ptr < chip->last_ptr)
3233 size = runtime->buffer_size + last_ptr
3236 size = last_ptr - chip->last_ptr;
3237 // remember the last updated point
3238 chip->last_ptr = last_ptr;
3239 // accumulate the size
3241 // over the period boundary?
3242 if (chip->size >= runtime->period_size) {
3243 // reset the accumulator
3244 chip->size %= runtime->period_size;
3246 spin_unlock(&chip->lock);
3247 snd_pcm_period_elapsed(substream);
3248 spin_lock(&chip->lock);
3250 // acknowledge the interrupt if necessary
3253 spin_unlock(&chip->lock);
3262 <section id="pcm-interface-interrupt-handler-both">
3263 <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3265 In both cases, even if more than one period are elapsed, you
3267 <function>snd_pcm_period_elapsed()</function> many times. Call
3268 only once. And the pcm layer will check the current hardware
3269 pointer and update to the latest status.
3274 <section id="pcm-interface-atomicity">
3275 <title>Atomicity</title>
3277 One of the most important (and thus difficult to debug) problem
3278 on the kernel programming is the race condition.
3279 On linux kernel, usually it's solved via spin-locks or
3280 semaphores. In general, if the race condition may
3281 happen in the interrupt handler, it's handled as atomic, and you
3282 have to use spinlock for protecting the critical session. If it
3283 never happens in the interrupt and it may take relatively long
3284 time, you should use semaphore.
3288 As already seen, some pcm callbacks are atomic and some are
3289 not. For example, <parameter>hw_params</parameter> callback is
3290 non-atomic, while <parameter>prepare</parameter> callback is
3291 atomic. This means, the latter is called already in a spinlock
3292 held by the PCM middle layer. Please take this atomicity into
3293 account when you use a spinlock or a semaphore in the callbacks.
3297 In the atomic callbacks, you cannot use functions which may call
3298 <function>schedule</function> or go to
3299 <function>sleep</function>. The semaphore and mutex do sleep,
3300 and hence they cannot be used inside the atomic callbacks
3301 (e.g. <parameter>prepare</parameter> callback).
3302 For taking a certain delay in such a callback, please use
3303 <function>udelay()</function> or <function>mdelay()</function>.
3307 <section id="pcm-interface-constraints">
3308 <title>Constraints</title>
3310 If your chip supports unconventional sample rates, or only the
3311 limited samples, you need to set a constraint for the
3316 For example, in order to restrict the sample rates in the some
3317 supported values, use
3318 <function>snd_pcm_hw_constraint_list()</function>.
3319 You need to call this function in the open callback.
3322 <title>Example of Hardware Constraints</title>
3325 static unsigned int rates[] =
3326 {4000, 10000, 22050, 44100};
3327 static snd_pcm_hw_constraint_list_t constraints_rates = {
3328 .count = sizeof(rates) / sizeof(rates[0]),
3333 static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3337 err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3338 SNDRV_PCM_HW_PARAM_RATE,
3339 &constraints_rates);
3350 There are many different constraints.
3351 Look in <filename>sound/asound.h</filename> for a complete list.
3352 You can even define your own constraint rules.
3353 For example, let's suppose my_chip can manage a substream of 1 channel
3354 if and only if the format is S16_LE, otherwise it supports any format
3355 specified in the <type>snd_pcm_hardware_t</type> stucture (or in any
3356 other constraint_list). You can build a rule like this:
3359 <title>Example of Hardware Constraints for Channels</title>
3362 static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3363 snd_pcm_hw_rule_t *rule)
3365 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3366 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3369 snd_mask_any(&fmt); // Init the struct
3371 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3372 return snd_mask_refine(f, &fmt);
3382 Then you need to call this function to add your rule:
3387 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3388 hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3396 The rule function is called when an application sets the number of
3397 channels. But an application can set the format before the number of
3398 channels. Thus you also need to define the inverse rule:
3401 <title>Example of Hardware Constraints for Channels</title>
3404 static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3405 snd_pcm_hw_rule_t *rule)
3407 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3408 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3411 snd_interval_any(&ch);
3412 if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3413 ch.min = ch.max = 1;
3415 return snd_interval_refine(c, &ch);
3425 ...and in the open callback:
3429 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3430 hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3438 I won't explain more details here, rather I
3439 would like to say, <quote>Luke, use the source.</quote>
3446 <!-- ****************************************************** -->
3447 <!-- Control Interface -->
3448 <!-- ****************************************************** -->
3449 <chapter id="control-interface">
3450 <title>Control Interface</title>
3452 <section id="control-interface-general">
3453 <title>General</title>
3455 The control interface is used widely for many switches,
3456 sliders, etc. which are accessed from the user-space. Its most
3457 important use is the mixer interface. In other words, on ALSA
3458 0.9.x, all the mixer stuff is implemented on the control kernel
3459 API (while there was an independent mixer kernel API on 0.5.x).
3463 ALSA has a well-defined AC97 control module. If your chip
3464 supports only the AC97 and nothing else, you can skip this
3469 The control API is defined in
3470 <filename><sound/control.h></filename>.
3471 Include this file if you add your own controls.
3475 <section id="control-interface-definition">
3476 <title>Definition of Controls</title>
3478 For creating a new control, you need to define the three
3479 callbacks: <structfield>info</structfield>,
3480 <structfield>get</structfield> and
3481 <structfield>put</structfield>. Then, define a
3482 <type>snd_kcontrol_new_t</type> record, such as:
3485 <title>Definition of a Control</title>
3488 static snd_kcontrol_new_t my_control __devinitdata = {
3489 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3490 .name = "PCM Playback Switch",
3492 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3493 .private_values = 0xffff,
3494 .info = my_control_info,
3495 .get = my_control_get,
3496 .put = my_control_put
3504 Most likely the control is created via
3505 <function>snd_ctl_new1()</function>, and in such a case, you can
3506 add <parameter>__devinitdata</parameter> prefix to the
3507 definition like above.
3511 The <structfield>iface</structfield> field specifies the type of
3513 <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3514 <constant>MIXER</constant>, <constant>PCM</constant>,
3515 <constant>CARD</constant>, etc.
3519 The <structfield>name</structfield> is the name identifier
3520 string. On ALSA 0.9.x, the control name is very important,
3521 because its role is classified from its name. There are
3522 pre-defined standard control names. The details are described in
3524 <link linkend="control-interface-control-names"><citetitle>
3525 Control Names</citetitle></link>.
3529 The <structfield>index</structfield> field holds the index number
3530 of this control. If there are several different controls with
3531 the same name, they can be distinguished by the index
3532 number. This is the case when
3533 several codecs exist on the card. If the index is zero, you can
3534 omit the definition above.
3538 The <structfield>access</structfield> field contains the access
3539 type of this control. Give the combination of bit masks,
3540 <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.
3541 The detailed will be explained in the subsection
3542 <link linkend="control-interface-access-flags"><citetitle>
3543 Access Flags</citetitle></link>.
3547 The <structfield>private_values</structfield> field contains
3548 an arbitrary long integer value for this record. When using
3549 generic <structfield>info</structfield>,
3550 <structfield>get</structfield> and
3551 <structfield>put</structfield> callbacks, you can pass a value
3552 through this field. If several small numbers are necessary, you can
3553 combine them in bitwise. Or, it's possible to give a pointer
3554 (casted to unsigned long) of some record to this field, too.
3559 <link linkend="control-interface-callbacks"><citetitle>
3560 callback functions</citetitle></link>.
3564 <section id="control-interface-control-names">
3565 <title>Control Names</title>
3567 There are some standards for defining the control names. A
3568 control is usually defined from the three parts as
3569 <quote>SOURCE DIRECTION FUNCTION</quote>.
3573 The first, <constant>SOURCE</constant>, specifies the source
3574 of the control, and is a string such as <quote>Master</quote>,
3575 <quote>PCM</quote>, <quote>CD</quote> or
3576 <quote>Line</quote>. There are many pre-defined sources.
3580 The second, <constant>DIRECTION</constant>, is one of the
3581 following strings according to the direction of the control:
3582 <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass
3583 Playback</quote> and <quote>Bypass Capture</quote>. Or, it can
3584 be omitted, meaning both playback and capture directions.
3588 The third, <constant>FUNCTION</constant>, is one of the
3589 following strings according to the function of the control:
3590 <quote>Switch</quote>, <quote>Volume</quote> and
3591 <quote>Route</quote>.
3595 The example of control names are, thus, <quote>Master Capture
3596 Switch</quote> or <quote>PCM Playback Volume</quote>.
3600 There are some exceptions:
3603 <section id="control-interface-control-names-global">
3604 <title>Global capture and playback</title>
3606 <quote>Capture Source</quote>, <quote>Capture Switch</quote>
3607 and <quote>Capture Volume</quote> are used for the global
3608 capture (input) source, switch and volume. Similarly,
3609 <quote>Playback Switch</quote> and <quote>Playback
3610 Volume</quote> are used for the global output gain switch and
3615 <section id="control-interface-control-names-tone">
3616 <title>Tone-controls</title>
3618 tone-control switch and volumes are specified like
3619 <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -
3620 Switch</quote>, <quote>Tone Control - Bass</quote>,
3621 <quote>Tone Control - Center</quote>.
3625 <section id="control-interface-control-names-3d">
3626 <title>3D controls</title>
3628 3D-control switches and volumes are specified like <quote>3D
3629 Control - XXX</quote>, e.g. <quote>3D Control -
3630 Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D
3631 Control - Space</quote>.
3635 <section id="control-interface-control-names-mic">
3636 <title>Mic boost</title>
3638 Mic-boost switch is set as <quote>Mic Boost</quote> or
3639 <quote>Mic Boost (6dB)</quote>.
3643 More precise information can be found in
3644 <filename>Documentation/sound/alsa/ControlNames.txt</filename>.
3649 <section id="control-interface-access-flags">
3650 <title>Access Flags</title>
3653 The access flag is the bit-flags which specifies the access type
3654 of the given control. The default access type is
3655 <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>,
3656 which means both read and write are allowed to this control.
3657 When the access flag is omitted (i.e. = 0), it is
3658 regarded as <constant>READWRITE</constant> access as default.
3662 When the control is read-only, pass
3663 <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.
3664 In this case, you don't have to define
3665 <structfield>put</structfield> callback.
3666 Similarly, when the control is write-only (although it's a rare
3667 case), you can use <constant>WRITE</constant> flag instead, and
3668 you don't need <structfield>get</structfield> callback.
3672 If the control value changes frequently (e.g. the VU meter),
3673 <constant>VOLATILE</constant> flag should be given. This means
3674 that the control may be changed without
3675 <link linkend="control-interface-change-notification"><citetitle>
3676 notification</citetitle></link>. Applications should poll such
3677 a control constantly.
3681 When the control is inactive, set
3682 <constant>INACTIVE</constant> flag, too.
3683 There are <constant>LOCK</constant> and
3684 <constant>OWNER</constant> flags for changing the write
3690 <section id="control-interface-callbacks">
3691 <title>Callbacks</title>
3693 <section id="control-interface-callbacks-info">
3694 <title>info callback</title>
3696 The <structfield>info</structfield> callback is used to get
3697 the detailed information of this control. This must store the
3698 values of the given <type>snd_ctl_elem_info_t</type>
3699 object. For example, for a boolean control with a single
3703 <title>Example of info callback</title>
3706 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3707 snd_ctl_elem_info_t *uinfo)
3709 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3711 uinfo->value.integer.min = 0;
3712 uinfo->value.integer.max = 1;
3721 The <structfield>type</structfield> field specifies the type
3722 of the control. There are <constant>BOOLEAN</constant>,
3723 <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,
3724 <constant>BYTES</constant>, <constant>IEC958</constant> and
3725 <constant>INTEGER64</constant>. The
3726 <structfield>count</structfield> field specifies the
3727 number of elements in this control. For example, a stereo
3728 volume would have count = 2. The
3729 <structfield>value</structfield> field is a union, and
3730 the values stored are depending on the type. The boolean and
3731 integer are identical.
3735 The enumerated type is a bit different from others. You'll
3736 need to set the string for the currently given item index.
3741 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3742 snd_ctl_elem_info_t *uinfo)
3744 static char *texts[4] = {
3745 "First", "Second", "Third", "Fourth"
3747 uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3749 uinfo->value.enumerated.items = 4;
3750 if (uinfo->value.enumerated.item > 3)
3751 uinfo->value.enumerated.item = 3;
3752 strcpy(uinfo->value.enumerated.name,
3753 texts[uinfo->value.enumerated.item]);
3762 <section id="control-interface-callbacks-get">
3763 <title>get callback</title>
3766 This callback is used to read the current value of the
3767 control and to return to the user-space.
3774 <title>Example of get callback</title>
3777 static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3778 snd_ctl_elem_value_t *ucontrol)
3780 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3781 ucontrol->value.integer.value[0] = get_some_value(chip);
3790 Here, the chip instance is retrieved via
3791 <function>snd_kcontrol_chip()</function> macro. This macro
3792 converts from kcontrol->private_data to the type defined by
3793 <type>chip_t</type>. The
3794 kcontrol->private_data field is
3795 given as the argument of <function>snd_ctl_new()</function>
3796 (see the later subsection
3797 <link linkend="control-interface-constructor"><citetitle>Constructor</citetitle></link>).
3801 The <structfield>value</structfield> field is depending on
3802 the type of control as well as on info callback. For example,
3803 the sb driver uses this field to store the register offset,
3804 the bit-shift and the bit-mask. The
3805 <structfield>private_value</structfield> is set like
3809 .private_value = reg | (shift << 16) | (mask << 24)
3813 and is retrieved in callbacks like
3817 static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3818 snd_ctl_elem_value_t *ucontrol)
3820 int reg = kcontrol->private_value & 0xff;
3821 int shift = (kcontrol->private_value >> 16) & 0xff;
3822 int mask = (kcontrol->private_value >> 24) & 0xff;
3831 In <structfield>get</structfield> callback, you have to fill all the elements if the
3832 control has more than one elements,
3833 i.e. <structfield>count</structfield> > 1.
3834 In the example above, we filled only one element
3835 (<structfield>value.integer.value[0]</structfield>) since it's
3836 assumed as <structfield>count</structfield> = 1.
3840 <section id="control-interface-callbacks-put">
3841 <title>put callback</title>
3844 This callback is used to write a value from the user-space.
3851 <title>Example of put callback</title>
3854 static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3855 snd_ctl_elem_value_t *ucontrol)
3857 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3859 if (chip->current_value !=
3860 ucontrol->value.integer.value[0]) {
3861 change_current_value(chip,
3862 ucontrol->value.integer.value[0]);
3871 As seen above, you have to return 1 if the value is
3872 changed. If the value is not changed, return 0 instead.
3873 If any fatal error happens, return a negative error code as
3878 Like <structfield>get</structfield> callback,
3879 when the control has more than one elements,
3880 all elemehts must be evaluated in this callback, too.
3884 <section id="control-interface-callbacks-all">
3885 <title>Callbacks are not atomic</title>
3887 All these three callbacks are basically not atomic.
3892 <section id="control-interface-constructor">
3893 <title>Constructor</title>
3895 When everything is ready, finally we can create a new
3896 control. For creating a control, there are two functions to be
3897 called, <function>snd_ctl_new1()</function> and
3898 <function>snd_ctl_add()</function>.
3902 In the simplest way, you can do like this:
3907 if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
3913 where <parameter>my_control</parameter> is the
3914 <type>snd_kcontrol_new_t</type> object defined above, and chip
3915 is the object pointer to be passed to
3916 kcontrol->private_data
3917 which can be referred in callbacks.
3921 <function>snd_ctl_new1()</function> allocates a new
3922 <type>snd_kcontrol_t</type> instance (that's why the definition
3923 of <parameter>my_control</parameter> can be with
3924 <parameter>__devinitdata</parameter>
3925 prefix), and <function>snd_ctl_add</function> assigns the given
3926 control component to the card.
3930 <section id="control-interface-change-notification">
3931 <title>Change Notification</title>
3933 If you need to change and update a control in the interrupt
3934 routine, you can call <function>snd_ctl_notify()</function>. For
3940 snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
3945 This function takes the card pointer, the event-mask, and the
3946 control id pointer for the notification. The event-mask
3947 specifies the types of notification, for example, in the above
3948 example, the change of control values is notified.
3949 The id pointer is the pointer of <type>snd_ctl_elem_id_t</type>
3951 You can find some examples in <filename>es1938.c</filename> or
3952 <filename>es1968.c</filename> for hardware volume interrupts.
3959 <!-- ****************************************************** -->
3960 <!-- API for AC97 Codec -->
3961 <!-- ****************************************************** -->
3962 <chapter id="api-ac97">
3963 <title>API for AC97 Codec</title>
3966 <title>General</title>
3968 The ALSA AC97 codec layer is a well-defined one, and you don't
3969 have to write many codes to control it. Only low-level control
3970 routines are necessary. The AC97 codec API is defined in
3971 <filename><sound/ac97_codec.h></filename>.
3975 <section id="api-ac97-example">
3976 <title>Full Code Example</title>
3979 <title>Example of AC97 Interface</title>
3988 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3991 mychip_t *chip = snd_magic_cast(mychip_t,
3992 ac97->private_data, return 0);
3994 // read a register value here from the codec
3995 return the_register_value;
3998 static void snd_mychip_ac97_write(ac97_t *ac97,
3999 unsigned short reg, unsigned short val)
4001 mychip_t *chip = snd_magic_cast(mychip_t,
4002 ac97->private_data, return 0);
4004 // write the given register value to the codec
4007 static int snd_mychip_ac97(mychip_t *chip)
4009 ac97_bus_t bus, *pbus;
4013 memset(&bus, 0, sizeof(bus));
4014 bus.write = snd_mychip_ac97_write;
4015 bus.read = snd_mychip_ac97_read;
4016 if ((err = snd_ac97_bus(chip->card, &bus, &pbus)) < 0)
4018 memset(&ac97, 0, sizeof(ac97));
4019 ac97.private_data = chip;
4020 return snd_ac97_mixer(pbus, &ac97, &chip->ac97);
4029 <section id="api-ac97-constructor">
4030 <title>Constructor</title>
4032 For creating an ac97 instance, first call <function>snd_ac97_bus</function>
4033 with <type>ac97_bus_t</type> record including callback functions.
4038 ac97_bus_t bus, *pbus;
4041 memset(&bus, 0, sizeof(bus));
4042 bus.write = snd_mychip_ac97_write;
4043 bus.read = snd_mychip_ac97_read;
4044 snd_ac97_bus(card, &bus, &pbus);
4049 The bus record is shared among all belonging ac97 instances.
4053 And then call <function>snd_ac97_mixer()</function> with an <type>ac97_t</type>
4054 record together with the bus pointer created above.
4062 memset(&ac97, 0, sizeof(ac97));
4063 ac97.private_data = chip;
4064 snd_ac97_mixer(bus, &ac97, &chip->ac97);
4069 where chip->ac97 is the pointer of a newly created
4070 <type>ac97_t</type> instance.
4071 In this case, the chip pointer is set as the private data, so that
4072 the read/write callback functions can refer to this chip instance.
4073 This instance is not necessarily stored in the chip
4074 record. When you need to change the register values from the
4075 driver, or need the suspend/resume of ac97 codecs, keep this
4076 pointer to pass to the corresponding functions.
4080 <section id="api-ac97-callbacks">
4081 <title>Callbacks</title>
4083 The standard callbacks are <structfield>read</structfield> and
4084 <structfield>write</structfield>. Obviously they
4085 correspond to the functions for read and write accesses to the
4086 hardware low-level codes.
4090 The <structfield>read</structfield> callback returns the
4091 register value specified in the argument.
4096 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4099 mychip_t *chip = snd_magic_cast(mychip_t,
4100 ac97->private_data, return 0);
4102 return the_register_value;
4108 Here, the chip can be cast from ac97->private_data.
4112 Meanwhile, the <structfield>write</structfield> callback is
4113 used to set the register value.
4118 static void snd_mychip_ac97_write(ac97_t *ac97,
4119 unsigned short reg, unsigned short val)
4126 These callbacks are non-atomic like the callbacks of control API.
4130 There are also other callbacks:
4131 <structfield>reset</structfield>,
4132 <structfield>wait</structfield> and
4133 <structfield>init</structfield>.
4137 The <structfield>reset</structfield> callback is used to reset
4138 the codec. If the chip requires a special way of reset, you can
4139 define this callback.
4143 The <structfield>wait</structfield> callback is used for a
4144 certain wait at the standard initialization of the codec. If the
4145 chip requires the extra wait-time, define this callback.
4149 The <structfield>init</structfield> callback is used for
4150 additional initialization of the codec.
4154 <section id="api-ac97-updating-registers">
4155 <title>Updating Registers in The Driver</title>
4157 If you need to access to the codec from the driver, you can
4158 call the following functions:
4159 <function>snd_ac97_write()</function>,
4160 <function>snd_ac97_read()</function>,
4161 <function>snd_ac97_update()</function> and
4162 <function>snd_ac97_update_bits()</function>.
4166 Both <function>snd_ac97_write()</function> and
4167 <function>snd_ac97_update()</function> functions are used to
4168 set a value to the given register
4169 (<constant>AC97_XXX</constant>). The different between them is
4170 that <function>snd_ac97_update()</function> doesn't write a
4171 value if the given value has been already set, while
4172 <function>snd_ac97_write()</function> always rewrites the
4178 snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4179 snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4186 <function>snd_ac97_read()</function> is used to read the value
4187 of the given register. For example,
4192 value = snd_ac97_read(ac97, AC97_MASTER);
4199 <function>snd_ac97_update_bits()</function> is used to update
4200 some bits of the given register.
4205 snd_ac97_update_bits(ac97, reg, mask, value);
4212 Also, there is a function to change the sample rate (of a
4213 certain register such as
4214 <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA is
4215 supported by the codec:
4216 <function>snd_ac97_set_rate()</function>.
4221 snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
4228 The following registers are available for setting the rate:
4229 <constant>AC97_PCM_MIC_ADC_RATE</constant>,
4230 <constant>AC97_PCM_FRONT_DAC_RATE</constant>,
4231 <constant>AC97_PCM_LR_ADC_RATE</constant>,
4232 <constant>AC97_SPDIF</constant>. When the
4233 <constant>AC97_SPDIF</constant> is specified, the register is
4234 not really changed but the corresponding IEC958 status bits will
4239 <section id="api-ac97-clock-adjustment">
4240 <title>Clock Adjustment</title>
4242 On some chip, the clock of the codec isn't 48000 but using a
4243 PCI clock (to save a quartz!). In this case, change the field
4244 ac97->clock to the corresponding
4245 value. For example, intel8x0
4246 and es1968 drivers have the auto-measurement function of the
4251 <section id="api-ac97-proc-files">
4252 <title>Proc Files</title>
4254 The ALSA AC97 interface will create a proc file such as
4255 <filename>/proc/asound/card0/ac97#0</filename> and
4256 <filename>ac97#0regs</filename>. You can refer to these files to
4257 see the current status and registers of the codec.
4261 <section id="api-ac97-multiple-codecs">
4262 <title>Multiple Codecs</title>
4264 When there are several codecs on the same card, you need to
4265 call <function>snd_ac97_new()</function> multiple times with
4266 ac97.num=1 or greater. The <structfield>num</structfield> field
4272 If you have set up multiple codecs, you need to either write
4273 different callbacks for each codec or check
4282 <!-- ****************************************************** -->
4283 <!-- MIDI (MPU401-UART) Interface -->
4284 <!-- ****************************************************** -->
4285 <chapter id="midi-interface">
4286 <title>MIDI (MPU401-UART) Interface</title>
4288 <section id="midi-interface-general">
4289 <title>General</title>
4291 Many soundcards have built-in MIDI (MPU401-UART)
4292 interfaces. When the soundcard supports the standard MPU401-UART
4293 interface, most likely you can use the ALSA MPU401-UART API. The
4294 MPU401-UART API is defined in
4295 <filename><sound/mpu401.h></filename>.
4299 Some soundchips have similar but a little bit different
4300 implementation of mpu401 stuff. For example, emu10k1 has its own
4305 In this document, I won't explain the rawmidi interface API,
4306 which is the basis of MPU401-UART implementation.
4310 For details, please check the source,
4311 <filename>core/rawmidi.c</filename>, and examples such as
4312 <filename>drivers/mpu401/mpu401_uart.c</filename> or
4313 <filename>usb/usbmidi.c</filename>.
4317 <section id="midi-interface-constructor">
4318 <title>Constructor</title>
4320 For creating a rawmidi object, call
4321 <function>snd_mpu401_uart_new()</function>.
4326 snd_rawmidi_t *rmidi;
4327 snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4328 irq, irq_flags, &rmidi);
4335 The first argument is the card pointer, and the second is the
4336 index of this component. You can create up to 8 rawmidi
4341 The third argument is the type of the hardware,
4342 <constant>MPU401_HW_XXX</constant>. If it's not a special one,
4343 you can use <constant>MPU401_HW_MPU401</constant>.
4347 The 4th argument is the i/o port address. Many
4348 backward-compatible MPU401 has an i/o port such as 0x330. Or, it
4349 might be a part of its own PCI i/o region. It depends on the
4354 When the i/o port address above is a part of the PCI i/o
4355 region, the MPU401 i/o port might have been already allocated
4356 (reserved) by the driver itself. In such a case, pass non-zero
4358 (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4360 the mpu401-uart layer will allocate the i/o ports by itself.
4364 Usually, the port address corresponds to the command port and
4365 port + 1 corresponds to the data port. If not, you may change
4366 the <structfield>cport</structfield> field of
4367 <type>mpu401_t</type> manually
4368 afterward. However, <type>mpu401_t</type> pointer is not
4369 returned explicitly by
4370 <function>snd_mpu401_uart_new()</function>. You need to cast
4371 rmidi->private_data to
4372 <type>mpu401_t</type> explicitly,
4378 mpu = snd_magic_cast(mpu401_t, rmidi->private_data, );
4383 and reset the cport as you like:
4388 mpu->cport = my_own_control_port;
4395 The 6th argument specifies the irq number for UART. If the irq
4396 is already allocated, pass 0 to the 7th argument
4397 (<parameter>irq_flags</parameter>). Otherwise, pass the flags
4399 (<constant>SA_XXX</constant> bits) to it, and the irq will be
4400 reserved by the mpu401-uart layer. If the card doesn't generates
4401 UART interrupts, pass -1 as the irq number. Then a timer
4402 interrupt will be invoked for polling.
4406 <section id="midi-interface-interrupt-handler">
4407 <title>Interrupt Handler</title>
4409 When the interrupt is allocated in
4410 <function>snd_mpu401_uart_new()</function>, the private
4411 interrupt handler is used, hence you don't have to do nothing
4412 else than creating the mpu401 stuff. Otherwise, you have to call
4413 <function>snd_mpu401_uart_interrupt()</function> explicitly when
4414 a UART interrupt is invoked and checked in your own interrupt
4419 In this case, you need to pass the private_data of the
4420 returned rawmidi object from
4421 <function>snd_mpu401_uart_new()</function> as the second
4422 argument of <function>snd_mpu401_uart_interrupt()</function>.
4427 snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4437 <!-- ****************************************************** -->
4438 <!-- Miscellaneous Devices -->
4439 <!-- ****************************************************** -->
4440 <chapter id="misc-devices">
4441 <title>Miscellaneous Devices</title>
4443 <section id="misc-devices-opl3">
4444 <title>FM OPL3</title>
4446 The FM OPL3 is still used on many chips (mainly for backward
4447 compatibility). ALSA has a nice OPL3 FM control layer, too. The
4448 OPL3 API is defined in
4449 <filename><sound/opl3.h></filename>.
4453 FM registers can be directly accessed through direct-FM API,
4454 defined in <filename><sound/asound_fm.h></filename>. In
4455 ALSA native mode, FM registers are accessed through
4456 Hardware-Dependant Device direct-FM extension API, whereas in
4457 OSS compatible mode, FM registers can be accessed with OSS
4458 direct-FM compatible API on <filename>/dev/dmfmX</filename> device.
4462 For creating the OPL3 component, you have two functions to
4463 call. The first one is a constructor for <type>opl3_t</type>
4470 snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
4478 The first argument is the card pointer, the second one is the
4479 left port address, and the third is the right port address. In
4480 most cases, the right port is placed at the left port + 2.
4484 The fourth argument is the hardware type.
4488 When the left and right ports have been already allocated by
4489 the card driver, pass non-zero to the fifth argument
4490 (<parameter>integrated</parameter>). Otherwise, opl3 module will
4491 allocate the specified ports by itself.
4495 If this function returns successfully with 0, then create a
4496 hwdep device for this opl3.
4501 snd_hwdep_t *opl3hwdep;
4502 snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4509 The first argument is the <type>opl3_t</type> instance you
4510 created, and the second is the index number, usually 0.
4514 The third argument is the index-offset for the sequencer
4515 client assigned to the OPL3 port. When there is an MPU401-UART,
4516 give 1 for here (UART always takes 0).
4520 <section id="misc-devices-hardware-dependent">
4521 <title>Hardware-Dependent Devices</title>
4523 Some chips need the access from the user-space for special
4524 controls or for loading the micro code. In such a case, you can
4525 create a hwdep (hardware-dependent) device. The hwdep API is
4526 defined in <filename><sound/hwdep.h></filename>. You can
4527 find examples in opl3 driver or
4528 <filename>isa/sb/sb16_csp.c</filename>.
4532 Creation of the <type>hwdep</type> instance is done via
4533 <function>snd_hwdep_new()</function>.
4539 snd_hwdep_new(card, "My HWDEP", 0, &hw);
4544 where the third argument is the index number.
4548 You can then pass any pointer value to the
4549 <parameter>private_data</parameter>. Again, it should be a
4550 magic-allocated record, so that the cast can be checked more
4551 safely. If you assign a private data, you should define the
4552 destructor, too. The destructor function is set to
4553 <structfield>private_free</structfield> field.
4558 mydata_t *p = snd_magic_kmalloc(mydata_t, 0, GFP_KERNEL);
4559 hw->private_data = p;
4560 hw->private_free = mydata_free;
4565 and the implementation of destructor would be:
4570 static void mydata_free(snd_hwdep_t *hw)
4572 mydata_t *p = snd_magic_cast(mydata_csp_t,
4573 hw->private_data, return);
4582 The arbitrary file operations can be defined for this
4583 instance. The file operators are defined in
4584 <parameter>ops</parameter> table. For example, assume that
4585 this chip needs an ioctl.
4590 hw->ops.open = mydata_open;
4591 hw->ops.ioctl = mydata_ioctl;
4592 hw->ops.release = mydata_release;
4597 And implement the callback functions as you like.
4601 <section id="misc-devices-IEC958">
4602 <title>IEC958 (S/PDIF)</title>
4604 Usually the controls for IEC958 devices are implemented via
4605 control interface. There is a macro to compose a name string for
4606 IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>
4607 defined in <filename><include/asound.h></filename>.
4611 There are some standard controls for IEC958 status bits. These
4612 controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,
4613 and the size of element is fixed as 4 bytes array
4614 (value.iec958.status[x]). For <structfield>info</structfield>
4615 callback, you don't specify
4616 the value field for this type (the count field must be set,
4621 <quote>IEC958 Playback Con Mask</quote> is used to return the
4622 bit-mask for the IEC958 status bits of consumer mode. Similarly,
4623 <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for
4624 professional mode. They are read-only controls, and are defined
4625 as MIXER controls (iface =
4626 <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>).
4630 Meanwhile, <quote>IEC958 Playback Default</quote> control is
4631 defined for getting and setting the current default IEC958
4632 bits. Note that this one is usually defined as a PCM control
4633 (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),
4634 although in some places it's defined as a MIXER control.
4638 In addition, you can define the control switches to
4639 enable/disable or to set the raw bit mode. The implementation
4640 will depend on the chip, but the control should be named as
4641 <quote>IEC958 xxx</quote>, preferably using
4642 <function>SNDRV_CTL_NAME_IEC958()</function> macro.
4646 You can find several cases, for example,
4647 <filename>pci/emu10k1</filename>,
4648 <filename>pci/ice1712</filename>, or
4649 <filename>pci/cmipci.c</filename>.
4656 <!-- ****************************************************** -->
4657 <!-- Buffer and Memory Management -->
4658 <!-- ****************************************************** -->
4659 <chapter id="buffer-and-memory">
4660 <title>Buffer and Memory Management</title>
4662 <section id="buffer-and-memory-buffer-types">
4663 <title>Buffer Types</title>
4665 ALSA provides several different buffer allocation functions
4666 depending on the bus and the architecture. All these have a
4667 consistent API. The allocation of physically-contiguous pages is
4669 <function>snd_malloc_xxx_pages()</function> function, where xxx
4674 The allocation of pages with fallback is
4675 <function>snd_malloc_xxx_pages_fallback()</function>. This
4676 function tries to allocate the specified pages but if the pages
4677 are not available, it tries to reduce the page sizes until the
4678 enough space is found.
4682 For releasing the space, call
4683 <function>snd_free_xxx_pages()</function> function.
4687 Usually, ALSA drivers try to allocate and reserve
4688 a large contiguous physical space
4689 at the time the module is loaded for the later use.
4690 This is called <quote>pre-allocation</quote>.
4691 As already written, you can call the following function at the
4692 construction of pcm instance (in the case of PCI bus).
4697 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
4698 snd_dma_pci_data(pci), size, max);
4703 where <parameter>size</parameter> is the byte size to be
4704 pre-allocated and the <parameter>max</parameter> is the maximal
4705 size to be changed via <filename>prealloc</filename> proc file.
4706 The allocator will try to get as the large area as possible
4707 within the given size.
4711 The second argument (type) and the third argument (device pointer)
4712 are dependent on the bus.
4713 In the case of ISA bus, pass <function>snd_dma_isa_data()</function>
4714 as the third argument with <constant>SNDRV_DMA_TYPE_DEV</constant> type.
4715 For the continuous buffer unrelated to the bus can be pre-allocated
4716 with <constant>SNDRV_DMA_TYPE_CONTINUOUS</constant> type and the
4717 <function>snd_dma_continuous_data(GFP_KERNEL)</function> device pointer,
4718 whereh <constant>GFP_KERNEL</constant> is the kernel allocation flag to
4719 use. For the SBUS, <constant>SNDRV_DMA_TYPE_SBUS</constant> and
4720 <function>snd_dma_sbus_data(sbus_dev)</function> are used instead.
4721 For the PCI scatter-gather buffers, use
4722 <constant>SNDRV_DMA_TYPE_DEV_SG</constant> with
4723 <function>snd_dma_pci_data(pci)</function>
4725 <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers
4726 </citetitle></link>).
4730 Once when the buffer is pre-allocated, you can use the
4731 allocator in the <structfield>hw_params</structfield> callback
4736 snd_pcm_lib_malloc_pages(substream, size);
4741 Note that you have to pre-allocate to use this function.
4745 <section id="buffer-and-memory-external-hardware">
4746 <title>External Hardware Buffers</title>
4748 Some chips have their own hardware buffers and the DMA
4749 transfer from the host memory is not available. In such a case,
4750 you need to either 1) copy/set the audio data directly to the
4751 external hardware buffer, or 2) make an intermediate buffer and
4752 copy/set the data from it to the external hardware buffer in
4753 interrupts (or in tasklets, preferably).
4757 The first case works fine if the external hardware buffer is enough
4758 large. This method doesn't need any extra buffers and thus is
4759 more effective. You need to define the
4760 <structfield>copy</structfield> and
4761 <structfield>silence</structfield> callbacks for
4762 the data transfer. However, there is a drawback: it cannot
4763 be mmapped. The examples are GUS's GF1 PCM or emu8000's
4768 The second case allows the mmap of the buffer, although you have
4769 to handle an interrupt or a tasklet for transferring the data
4770 from the intermediate buffer to the hardware buffer. You can find an
4771 example in vxpocket driver.
4775 Another case is that the chip uses a PCI memory-map
4776 region for the buffer instead of the host memory. In this case,
4777 mmap is available only on certain architectures like intel. In
4778 non-mmap mode, the data cannot be transferred as the normal
4779 way. Thus you need to define <structfield>copy</structfield> and
4780 <structfield>silence</structfield> callbacks as well
4781 as in the cases above. The examples are found in
4782 <filename>rme32.c</filename> and <filename>rme96.c</filename>.
4786 The implementation of <structfield>copy</structfield> and
4787 <structfield>silence</structfield> callbacks depends upon
4788 whether the hardware supports interleaved or non-interleaved
4789 samples. The <structfield>copy</structfield> callback is
4790 defined like below, a bit
4791 differently depending whether the direction is playback or
4797 static int playback_copy(snd_pcm_substream_t *substream, int channel,
4798 snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);
4799 static int capture_copy(snd_pcm_substream_t *substream, int channel,
4800 snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);
4807 In the case of interleaved samples, the second argument
4808 (<parameter>channel</parameter>) is not used. The third argument
4809 (<parameter>pos</parameter>) points the
4810 current position offset in frames.
4814 The meaning of the fourth argument is different between
4815 playback and capture. For playback, it holds the source data
4816 pointer, and for capture, it's the destination data pointer.
4820 The last argument is the number of frames to be copied.
4824 What you have to do in this callback is again different
4825 between playback and capture directions. In the case of
4826 playback, you do: copy the given amount of data
4827 (<parameter>count</parameter>) at the specified pointer
4828 (<parameter>src</parameter>) to the specified offset
4829 (<parameter>pos</parameter>) on the hardware buffer. When
4830 coded like memcpy-like way, the copy would be like:
4835 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4836 frames_to_bytes(runtime, count));
4843 For the capture direction, you do: copy the given amount of
4844 data (<parameter>count</parameter>) at the specified offset
4845 (<parameter>pos</parameter>) on the hardware buffer to the
4846 specified pointer (<parameter>dst</parameter>).
4851 my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4852 frames_to_bytes(runtime, count));
4857 Note that both of the position and the data amount are given
4862 In the case of non-interleaved samples, the implementation
4863 will be a bit more complicated.
4867 You need to check the channel argument, and if it's -1, copy
4868 the whole channels. Otherwise, you have to copy only the
4869 specified channel. Please check
4870 <filename>isa/gus/gus_pcm.c</filename> as an example.
4874 The <structfield>silence</structfield> callback is also
4875 implemented in a similar way.
4880 static int silence(snd_pcm_substream_t *substream, int channel,
4881 snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
4888 The meanings of arguments are identical with the
4889 <structfield>copy</structfield>
4890 callback, although there is no <parameter>src/dst</parameter>
4891 argument. In the case of interleaved samples, the channel
4892 argument has no meaning, as well as on
4893 <structfield>copy</structfield> callback.
4897 The role of <structfield>silence</structfield> callback is to
4898 set the given amount
4899 (<parameter>count</parameter>) of silence data at the
4900 specified offset (<parameter>pos</parameter>) on the hardware
4901 buffer. Suppose that the data format is signed (that is, the
4902 silent-data is 0), and the implementation using a memset-like
4903 function would be like:
4908 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4909 frames_to_bytes(runtime, count));
4916 In the case of non-interleaved samples, again, the
4917 implementation becomes a bit more complicated. See, for example,
4918 <filename>isa/gus/gus_pcm.c</filename>.
4922 <section id="buffer-and-memory-non-contiguous">
4923 <title>Non-Contiguous Buffers</title>
4925 If your hardware supports the page table like emu10k1 or the
4926 buffer descriptors like via82xx, you can use the scatter-gather
4927 (SG) DMA. ALSA provides an interface for handling SG-buffers.
4928 The API is provided in <filename><sound/pcm_sgbuf.h></filename>.
4932 For creating the SG-buffer handler, call
4933 <function>snd_pcm_lib_preallocate_pages()</function> or
4934 <function>snd_pcm_lib_preallocate_pages_for_all()</function>
4935 with <constant>SNDRV_DMA_TYPE_DEV_SG</constant>
4936 in the PCM constructor like other PCI pre-allocator.
4937 You need to pass the <function>snd_dma_pci_data(pci)</function>,
4938 where pci is the struct <structname>pci_dev</structname> pointer
4939 of the chip as well.
4940 The <type>snd_sg_buf_t</type> instance is created as
4941 substream->dma_private. You can cast
4947 snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
4954 Then call <function>snd_pcm_lib_malloc_pages()</function>
4955 in <structfield>hw_params</structfield> callback
4956 as well as in the case of normal PCI buffer.
4957 The SG-buffer handler will allocate the non-contiguous kernel
4958 pages of the given size and map them onto the virtually contiguous
4959 memory. The virtual pointer is addressed in runtime->dma_area.
4960 The physical address (runtime->dma_addr) is set to zero,
4961 because the buffer is physically non-contigous.
4962 The physical address table is set up in sgbuf->table.
4963 You can get the physical address at a certain offset via
4964 <function>snd_pcm_sgbuf_get_addr()</function>.
4968 When a SG-handler is used, you need to set
4969 <function>snd_pcm_sgbuf_ops_page</function> as
4970 the <structfield>page</structfield> callback.
4971 (See <link linkend="pcm-interface-operators-page-callback">
4972 <citetitle>page callback section</citetitle></link>.)
4976 For releasing the data, call
4977 <function>snd_pcm_lib_free_pages()</function> in the
4978 <structfield>hw_free</structfield> callback as usual.
4982 <section id="buffer-and-memory-vmalloced">
4983 <title>Vmalloc'ed Buffers</title>
4985 It's possible to use a buffer allocated via
4986 <function>vmalloc</function>, for example, for an intermediate
4987 buffer. Since the allocated pages are not contiguous, you need
4988 to set the <structfield>page</structfield> callback to obtain
4989 the physical address at every offset.
4993 The implementation of <structfield>page</structfield> callback
4999 #include <linux/vmalloc.h>
5001 /* get the physical page pointer on the given offset */
5002 static struct page *mychip_page(snd_pcm_substream_t *substream,
5003 unsigned long offset)
5005 void *pageptr = substream->runtime->dma_area + offset;
5006 return vmalloc_to_page(pageptr);
5017 <!-- ****************************************************** -->
5018 <!-- Proc Interface -->
5019 <!-- ****************************************************** -->
5020 <chapter id="proc-interface">
5021 <title>Proc Interface</title>
5023 ALSA provides an easy interface for procfs. The proc files are
5024 very useful for debugging. I recommend you set up proc files if
5025 you write a driver and want to get a running status or register
5026 dumps. The API is found in
5027 <filename><sound/info.h></filename>.
5031 For creating a proc file, call
5032 <function>snd_card_proc_new()</function>.
5037 snd_info_entry_t *entry;
5038 int err = snd_card_proc_new(card, "my-file", &entry);
5043 where the second argument specifies the proc-file name to be
5044 created. The above example will create a file
5045 <filename>my-file</filename> under the card directory,
5046 e.g. <filename>/proc/asound/card0/my-file</filename>.
5050 Like other components, the proc entry created via
5051 <function>snd_card_proc_new()</function> will be registered and
5052 released automatically in the card registration and release
5057 When the creation is successful, the function stores a new
5058 instance at the pointer given in the third argument.
5059 It is initialized as a text proc file for read only. For using
5060 this proc file as a read-only text file as it is, set the read
5061 callback with a private data via
5062 <function>snd_info_set_text_ops()</function>.
5067 snd_info_set_text_ops(entry, chip, read_size, my_proc_read);
5072 where the second argument (<parameter>chip</parameter>) is the
5073 private data to be used in the callbacks. The third parameter
5074 specifies the read buffer size and the fourth
5075 (<parameter>my_proc_read</parameter>) is the callback function, which
5081 static void my_proc_read(snd_info_entry_t *entry,
5082 snd_info_buffer_t *buffer);
5090 In the read callback, use <function>snd_iprintf()</function> for
5091 output strings, which works just like normal
5092 <function>printf()</function>. For example,
5097 static void my_proc_read(snd_info_entry_t *entry,
5098 snd_info_buffer_t *buffer)
5100 chip_t *cm = snd_magic_cast(mychip_t,
5101 entry->private_data, return);
5103 snd_iprintf(buffer, "This is my chip!\n");
5104 snd_iprintf(buffer, "Port = %ld\n", chip->port);
5112 The file permission can be changed afterwards. As default, it's
5113 set as read only for all users. If you want to add the write
5114 permission to the user (root as default), set like below:
5119 entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
5124 and set the write buffer size and the callback
5129 entry->c.text.write_size = 256;
5130 entry->c.text.write = my_proc_write;
5137 The buffer size for read is set to 1024 implicitly by
5138 <function>snd_info_set_text_ops()</function>. It should suffice
5139 in most cases (the size will be aligned to
5140 <constant>PAGE_SIZE</constant> anyway), but if you need to handle
5141 very large text files, you can set it explicitly, too.
5146 entry->c.text.read_size = 65536;
5153 For the write callback, you can use
5154 <function>snd_info_get_line()</function> to get a text line, and
5155 <function>snd_info_get_str()</function> to retrieve a string from
5156 the line. Some examples are found in
5157 <filename>core/oss/mixer_oss.c</filename>, core/oss/and
5158 <filename>pcm_oss.c</filename>.
5162 For a raw-data proc-file, set the attributes like the following:
5167 static struct snd_info_entry_ops my_file_io_ops = {
5168 .read = my_file_io_read,
5171 entry->content = SNDRV_INFO_CONTENT_DATA;
5172 entry->private_data = chip;
5173 entry->c.ops = &my_file_io_ops;
5175 entry->mode = S_IFREG | S_IRUGO;
5182 The callback is much more complicated than the text-file
5183 version. You need to use a low-level i/o functions such as
5184 <function>copy_from/to_user()</function> to transfer the
5190 static long my_file_io_read(snd_info_entry_t *entry,
5191 void *file_private_data,
5194 unsigned long count,
5198 if (pos + size > local_max_size)
5199 size = local_max_size - pos;
5200 if (copy_to_user(buf, local_data + pos, size))
5212 <!-- ****************************************************** -->
5213 <!-- Power Management -->
5214 <!-- ****************************************************** -->
5215 <chapter id="power-management">
5216 <title>Power Management</title>
5218 If the chip is supposed to work with with suspend/resume
5219 functions, you need to add the power-management codes to the
5220 driver. The additional codes for the power-management should be
5221 <function>ifdef</function>'ed with
5222 <constant>CONFIG_PM</constant>.
5226 ALSA provides the common power-management layer. Each card driver
5227 needs to have only low-level suspend and resume callbacks.
5233 static int snd_my_suspend(snd_card_t *card, unsigned int state)
5235 .... // do things for suspsend
5238 static int snd_my_resume(snd_card_t *card, unsigned int state)
5240 .... // do things for suspsend
5250 The scheme of the real suspend job is as following.
5253 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5254 <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>
5255 <listitem><para>Save the register values if necessary.</para></listitem>
5256 <listitem><para>Stop the hardware if necessary.</para></listitem>
5257 <listitem><para>Set the power-state as D3hot by calling <function>snd_power_change_state()</function>.</para></listitem>
5262 A typical code would be like:
5267 static int mychip_suspend(snd_card_t *card, unsigned int state)
5270 mychip_t *chip = snd_magic_cast(mychip_t, card->pm_private_data,
5273 snd_pcm_suspend_all(chip->pcm);
5275 snd_mychip_save_registers(chip);
5277 snd_mychip_stop_hardware(chip);
5279 snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
5288 The scheme of the real resume job is as following.
5291 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5292 <listitem><para>Enable the pci device again by calling
5293 <function>pci_enable_device()</function>.</para></listitem>
5294 <listitem><para>Re-initialize the chip.</para></listitem>
5295 <listitem><para>Restore the saved registers if necessary.</para></listitem>
5296 <listitem><para>Resume the mixer, e.g. calling
5297 <function>snd_ac97_resume()</function>.</para></listitem>
5298 <listitem><para>Restart the hardware (if any).</para></listitem>
5299 <listitem><para>Set the power-state as D0 by calling
5300 <function>snd_power_change_state()</function>.</para></listitem>
5305 A typical code would be like:
5310 static void mychip_resume(mychip_t *chip)
5313 mychip_t *chip = snd_magic_cast(mychip_t, card->pm_private_data,
5316 pci_enable_device(chip->pci);
5318 snd_mychip_reinit_chip(chip);
5320 snd_mychip_restore_registers(chip);
5322 snd_ac97_resume(chip->ac97);
5324 snd_mychip_restart_chip(chip);
5326 snd_power_change_state(card, SNDRV_CTL_POWER_D0);
5335 OK, we have all callbacks now. Let's set up them now. In the
5336 initialization of the card, add the following:
5341 static int __devinit snd_mychip_probe(struct pci_dev *pci,
5342 const struct pci_device_id *pci_id)
5348 snd_card_set_pm_callback(card, snd_my_suspend, snd_my_resume, chip);
5355 Here you don't have to put ifdef CONFIG_PM around, since it's already
5356 checked in the header and expanded to empty if not needed.
5360 If you need a space for saving the registers, you'll need to
5361 allocate the buffer for it here, too, since it would be fatal
5362 if you cannot allocate a memory in the suspend phase.
5363 The allocated buffer should be released in the corresponding
5368 And next, set suspend/resume callbacks to the pci_driver,
5369 This can be done by passing a macro SND_PCI_PM_CALLBACKS
5370 in the pci_driver struct. This macro is expanded to the correct
5371 (global) callbacks if CONFIG_PM is set.
5376 static struct pci_driver driver = {
5378 .id_table = snd_my_ids,
5379 .probe = snd_my_probe,
5380 .remove = __devexit_p(snd_my_remove),
5381 SND_PCI_PM_CALLBACKS
5391 <!-- ****************************************************** -->
5392 <!-- Module Parameters -->
5393 <!-- ****************************************************** -->
5394 <chapter id="module-parameters">
5395 <title>Module Parameters</title>
5397 There are standard module options for ALSA. At least, each
5398 module should have <parameter>index</parameter>,
5399 <parameter>id</parameter> and <parameter>enable</parameter>
5404 If the module supports multiple cards (usually up to
5405 8 = <constant>SNDRV_CARDS</constant> cards), they should be
5406 arrays. The default initial values are defined already as
5407 constants for ease of programming:
5412 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
5413 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
5414 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
5421 If the module supports only a single card, they could be single
5422 variables, instead. <parameter>enable</parameter> option is not
5423 always necessary in this case, but it wouldn't be so bad to have a
5424 dummy option for compatibility.
5428 The module parameters must be declared with the standard
5429 <function>module_param()()</function>,
5430 <function>module_param_array()()</function> and
5431 <function>MODULE_PARM_DESC()</function> macros. The ALSA provides
5432 an additional macro, <function>MODULE_PARM_SYNTAX()</function>,
5433 for describing its syntax. The strings will be written to
5434 <filename>/lib/modules/XXX/modules.generic_string</filename>
5439 For convenience, the typical string arguments given to
5440 <function>MODULE_PARM_SYNTAX()</function> are defined in
5441 <filename><sound/initval.h></filename>, such as
5442 <constant>SNDRV_ID_DESC</constant> or
5443 <constant>SNDRV_ENABLED</constant>.
5447 The typical coding would be like below:
5452 #define CARD_NAME "My Chip"
5454 static int boot_devs;
5455 module_param_array(index, int, boot_devs, 0444);
5456 MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
5457 MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
5458 module_param_array(id, charp, boot_devs, 0444);
5459 MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
5460 MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
5461 module_param_array(enable, bool, boot_devs, 0444);
5462 MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
5463 MODULE_PARM_SYNTAX(enable, SNDRV_ENABLE_DESC);
5468 Here boot_devs is passed but simply ignored since we don't care
5469 the number of parsed parameters.
5473 Also, don't forget to define the module description, classes,
5474 license and devices. Especially, the recent modprobe requires to
5475 define the module license as GPL, etc., otherwise the system is
5476 shown as <quote>tainted</quote>.
5481 MODULE_DESCRIPTION("My Chip");
5482 MODULE_CLASSES("{sound}");
5483 MODULE_LICENSE("GPL");
5484 MODULE_DEVICES("{{Vendor,My Chip Name}}");
5493 <!-- ****************************************************** -->
5494 <!-- How To Put Your Driver -->
5495 <!-- ****************************************************** -->
5496 <chapter id="how-to-put-your-driver">
5497 <title>How To Put Your Driver Into ALSA Tree</title>
5499 <title>General</title>
5501 So far, you've learned how to write the driver codes.
5502 And you might have a question now: how to put my own
5503 driver into the ALSA driver tree?
5504 Here (finally :) the standard procedure is described briefly.
5508 Suppose that you'll create a new PCI driver for the card
5509 <quote>xyz</quote>. The card module name would be
5510 snd-xyz. The new driver is usually put into alsa-driver
5511 tree, <filename>alsa-driver/pci</filename> directory in
5512 the case of PCI cards.
5513 Then the driver is evaluated, audited and tested
5514 by developers and users. After a certain time, the driver
5515 will go to alsa-kernel tree (to the corresponding directory,
5516 such as <filename>alsa-kernel/pci</filename>) and eventually
5517 integrated into Linux 2.6 tree (the directory would be
5518 <filename>linux/sound/pci</filename>).
5522 In the following sections, the driver code is supposed
5523 to be put into alsa-driver tree. The two cases are assumed:
5524 a driver consisting of a single source file and one consisting
5525 of several source files.
5530 <title>Driver with A Single Source File</title>
5535 Modify alsa-driver/pci/Makefile
5539 Suppose you have a file xyz.c. Add the following
5544 snd-xyz-objs := xyz.o
5545 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5554 Create the Kconfig entry
5558 Add the new entry of Kconfig for your xyz driver.
5563 tristate "Foobar XYZ"
5567 Say 'Y' or 'M' to include support for Foobar XYZ soundcard.
5572 the line, select SND_PCM, specifies that the driver xyz supports
5573 PCM. In addition to SND_PCM, the following components are
5574 supported for select command:
5575 SND_RAWMIDI, SND_TIMER, SND_HWDEP, SND_MPU401_UART,
5576 SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB, SND_AC97_CODEC.
5577 Add the select command for each supported component.
5581 Note that some selections imply the lowlevel selections.
5582 For example, PCM includes TIMER, MPU401_UART includes RAWMIDI,
5583 AC97_CODEC includes PCM, and OPL3_LIB includes HWDEP.
5584 You don't need to give the lowlevel selections again.
5588 For the details of Kconfig script, refer to the kbuild
5596 Run cvscompile script to re-generate the configure script and
5597 build the whole stuff again.
5605 <title>Drivers with Several Source Files</title>
5607 Suppose that the driver snd-xyz have several source files.
5608 They are located in the new subdirectory,
5614 Add a new directory (<filename>xyz</filename>) in
5615 <filename>alsa-driver/pci/Makefile</filename> like below
5620 obj-$(CONFIG_SND) += xyz/
5629 Under the directory <filename>xyz</filename>, create a Makefile
5632 <title>Sample Makefile for a driver xyz</title>
5639 include $(TOPDIR)/toplevel.config
5640 include $(TOPDIR)/Makefile.conf
5642 snd-xyz-objs := xyz.o abc.o def.o
5644 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5646 include $(TOPDIR)/Rules.make
5655 Create the Kconfig entry
5659 This procedure is as same as in the last section.
5665 Run cvscompile script to re-generate the configure script and
5666 build the whole stuff again.
5675 <!-- ****************************************************** -->
5676 <!-- Useful Functions -->
5677 <!-- ****************************************************** -->
5678 <chapter id="useful-functions">
5679 <title>Useful Functions</title>
5681 <section id="useful-functions-snd-printk">
5682 <title><function>snd_printk()</function> and friends</title>
5684 ALSA provides a verbose version of
5685 <function>printk()</function> function. If a kernel config
5686 <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this
5687 function prints the given message together with the file name
5688 and the line of the caller. The <constant>KERN_XXX</constant>
5689 prefix is processed as
5690 well as the original <function>printk()</function> does, so it's
5691 recommended to add this prefix, e.g.
5696 snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
5703 There are also <function>printk()</function>'s for
5704 debugging. <function>snd_printd()</function> can be used for
5705 general debugging purposes. If
5706 <constant>CONFIG_SND_DEBUG</constant> is set, this function is
5707 compiled, and works just like
5708 <function>snd_printk()</function>. If the ALSA is compiled
5709 without the debugging flag, it's ignored.
5713 <function>snd_printdd()</function> is compiled in only when
5714 <constant>CONFIG_SND_DEBUG_DETECT</constant> is set. Please note
5715 that <constant>DEBUG_DETECT</constant> is not set as default
5716 even if you configure the alsa-driver with
5717 <option>--with-debug=full</option> option. You need to give
5718 explicitly <option>--with-debug=detect</option> option instead.
5722 <section id="useful-functions-snd-assert">
5723 <title><function>snd_assert()</function></title>
5725 <function>snd_assert()</function> macro is similar with the
5726 normal <function>assert()</function> macro. For example,
5731 snd_assert(pointer != NULL, return -EINVAL);
5738 The first argument is the expression to evaluate, and the
5739 second argument is the action if it fails. When
5740 <constant>CONFIG_SND_DEBUG</constant>, is set, it will show an
5741 error message such as <computeroutput>BUG? (xxx) (called from
5742 yyy)</computeroutput>. When no debug flag is set, this is
5747 <section id="useful-functions-snd-runtime-check">
5748 <title><function>snd_runtime_check()</function></title>
5750 This macro is quite similar with
5751 <function>snd_assert()</function>. Unlike
5752 <function>snd_assert()</function>, the expression is always
5753 evaluated regardless of
5754 <constant>CONFIG_SND_DEBUG</constant>. When
5755 <constant>CONFIG_SND_DEBUG</constant> is set, the macro will
5756 show a message like <computeroutput>ERROR (xx) (called from
5757 yyy)</computeroutput>.
5761 <section id="useful-functions-snd-bug">
5762 <title><function>snd_BUG()</function></title>
5764 It calls <function>snd_assert(0,)</function> -- that is, just
5765 prints the error message at the point. It's useful to show that
5766 a fatal error happens there.
5772 <!-- ****************************************************** -->
5773 <!-- Acknowledgments -->
5774 <!-- ****************************************************** -->
5775 <chapter id="acknowledments">
5776 <title>Acknowledgments</title>
5778 I would like to thank Phil Kerr for his help for improvement and
5779 corrections of this document.
5782 Kevin Conder reformatted the original plain-text to the
5786 Giuliano Pochini corrected typos and contributed the example codes
5787 in the hardware constraints section.