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>July 11, 2004</date>
22 <edition>0.3.3</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>
398 #include <sound/initval.h>
400 /* module parameters (see "Module Parameters") */
401 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
402 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
403 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
405 /* definition of the chip-specific record */
406 typedef struct snd_mychip mychip_t;
409 // rest of implementation will be in the section
410 // "PCI Resource Managements"
413 /* chip-specific destructor
414 * (see "PCI Resource Managements")
416 static int snd_mychip_free(mychip_t *chip)
418 .... // will be implemented later...
421 /* component-destructor
422 * (see "Management of Cards and Components")
424 static int snd_mychip_dev_free(snd_device_t *device)
426 mychip_t *chip = device->device_data;
427 return snd_mychip_free(chip);
430 /* chip-specific constructor
431 * (see "Management of Cards and Components")
433 static int __devinit snd_mychip_create(snd_card_t *card,
439 static snd_device_ops_t ops = {
440 .dev_free = snd_mychip_dev_free,
445 // check PCI availability here
446 // (see "PCI Resource Managements")
449 /* allocate a chip-specific data with zero filled */
450 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
456 // rest of initialization here; will be implemented
457 // later, see "PCI Resource Managements"
460 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
462 snd_mychip_free(chip);
466 snd_card_set_dev(card, &pci->dev);
472 /* constructor -- see "Constructor" sub-section */
473 static int __devinit snd_mychip_probe(struct pci_dev *pci,
474 const struct pci_device_id *pci_id)
482 if (dev >= SNDRV_CARDS)
490 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
495 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
501 strcpy(card->driver, "My Chip");
502 strcpy(card->shortname, "My Own Chip 123");
503 sprintf(card->longname, "%s at 0x%lx irq %i",
504 card->shortname, chip->ioport, chip->irq);
507 .... // implemented later
510 if ((err = snd_card_register(card)) < 0) {
516 pci_set_drvdata(pci, card);
521 /* destructor -- see "Destructor" sub-section */
522 static void __devexit snd_mychip_remove(struct pci_dev *pci)
524 snd_card_free(pci_get_drvdata(pci));
525 pci_set_drvdata(pci, NULL);
533 <section id="basic-flow-constructor">
534 <title>Constructor</title>
536 The real constructor of PCI drivers is probe callback. The
537 probe callback and other component-constructors which are called
538 from probe callback should be defined with
539 <parameter>__devinit</parameter> prefix. You
540 cannot use <parameter>__init</parameter> prefix for them,
541 because any PCI device could be a hotplug device.
545 In the probe callback, the following scheme is often used.
548 <section id="basic-flow-constructor-device-index">
549 <title>1) Check and increment the device index.</title>
556 if (dev >= SNDRV_CARDS)
566 where enable[dev] is the module option.
570 At each time probe callback is called, check the
571 availability of the device. If not available, simply increment
572 the device index and returns. dev will be incremented also
574 linkend="basic-flow-constructor-set-pci"><citetitle>step
575 7</citetitle></link>).
579 <section id="basic-flow-constructor-create-card">
580 <title>2) Create a card instance</title>
587 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
594 The detail will be explained in the section
595 <link linkend="card-management-card-instance"><citetitle>
596 Management of Cards and Components</citetitle></link>.
600 <section id="basic-flow-constructor-create-main">
601 <title>3) Create a main component</title>
603 In this part, the PCI resources are allocated.
610 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
618 The detail will be explained in the section <link
619 linkend="pci-resource"><citetitle>PCI Resource
620 Managements</citetitle></link>.
624 <section id="basic-flow-constructor-main-component">
625 <title>4) Set the driver ID and name strings.</title>
630 strcpy(card->driver, "My Chip");
631 strcpy(card->shortname, "My Own Chip 123");
632 sprintf(card->longname, "%s at 0x%lx irq %i",
633 card->shortname, chip->ioport, chip->irq);
638 The driver field holds the minimal ID string of the
639 chip. This is referred by alsa-lib's configurator, so keep it
641 Even the same driver can have different driver IDs to
642 distinguish the functionality of each chip type.
646 The shortname field is a string shown as more verbose
647 name. The longname field contains the information which is
648 shown in <filename>/proc/asound/cards</filename>.
652 <section id="basic-flow-constructor-create-other">
653 <title>5) Create other components, such as mixer, MIDI, etc.</title>
655 Here you define the basic components such as
656 <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
657 mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
658 MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
659 and other interfaces.
660 Also, if you want a <link linkend="proc-interface"><citetitle>proc
661 file</citetitle></link>, define it here, too.
665 <section id="basic-flow-constructor-register-card">
666 <title>6) Register the card instance.</title>
671 if ((err = snd_card_register(card)) < 0) {
681 Will be explained in the section <link
682 linkend="card-management-registration"><citetitle>Management
683 of Cards and Components</citetitle></link>, too.
687 <section id="basic-flow-constructor-set-pci">
688 <title>7) Set the PCI driver data and return zero.</title>
693 pci_set_drvdata(pci, card);
700 In the above, the card record is stored. This pointer is
701 referred in the remove callback and power-management
707 <section id="basic-flow-destructor">
708 <title>Destructor</title>
710 The destructor, remove callback, simply releases the card
711 instance. Then the ALSA middle layer will release all the
712 attached components automatically.
716 It would be typically like the following:
721 static void __devexit snd_mychip_remove(struct pci_dev *pci)
723 snd_card_free(pci_get_drvdata(pci));
724 pci_set_drvdata(pci, NULL);
730 The above code assumes that the card pointer is set to the PCI
735 <section id="basic-flow-header-files">
736 <title>Header Files</title>
738 For the above example, at least the following include files
744 #include <sound/driver.h>
745 #include <linux/init.h>
746 #include <linux/pci.h>
747 #include <linux/slab.h>
748 #include <sound/core.h>
749 #include <sound/initval.h>
754 where the last one is necessary only when module options are
755 defined in the source file. If the codes are split to several
756 files, the file without module options don't need them.
760 In addition to them, you'll need
761 <filename><linux/interrupt.h></filename> for the interrupt
762 handling, and <filename><asm/io.h></filename> for the i/o
763 access. If you use <function>mdelay()</function> or
764 <function>udelay()</function> functions, you'll need to include
765 <filename><linux/delay.h></filename>, too.
769 The ALSA interfaces like PCM or control API are define in other
770 header files as <filename><sound/xxx.h></filename>.
771 They have to be included after
772 <filename><sound/core.h></filename>.
779 <!-- ****************************************************** -->
780 <!-- Management of Cards and Components -->
781 <!-- ****************************************************** -->
782 <chapter id="card-management">
783 <title>Management of Cards and Components</title>
785 <section id="card-management-card-instance">
786 <title>Card Instance</title>
788 For each soundcard, a <quote>card</quote> record must be allocated.
792 A card record is the headquarters of the soundcard. It manages
793 the list of whole devices (components) on the soundcard, such as
794 PCM, mixers, MIDI, synthesizer, and so on. Also, the card
795 record holds the ID and the name strings of the card, manages
796 the root of proc files, and controls the power-management states
797 and hotplug disconnections. The component list on the card
798 record is used to manage the proper releases of resources at
803 As mentioned above, to create a card instance, call
804 <function>snd_card_new()</function>.
810 card = snd_card_new(index, id, module, extra_size);
817 The function takes four arguments, the card-index number, the
818 id string, the module pointer (usually
819 <constant>THIS_MODULE</constant>),
820 and the size of extra-data space. The last argument is used to
821 allocate card->private_data for the
822 chip-specific data. Note that this data
823 <emphasis>is</emphasis> allocated by
824 <function>snd_card_new()</function>.
828 <section id="card-management-component">
829 <title>Components</title>
831 After the card is created, you can attach the components
832 (devices) to the card instance. On ALSA driver, a component is
833 represented as a <type>snd_device_t</type> object.
834 A component can be a PCM instance, a control interface, a raw
835 MIDI interface, etc. Each of such instances has one component
840 A component can be created via
841 <function>snd_device_new()</function> function.
846 snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
853 This takes the card pointer, the device-level
854 (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
855 callback pointers (<parameter>&ops</parameter>). The
856 device-level defines the type of components and the order of
857 registration and de-registration. For most of components, the
858 device-level is already defined. For a user-defined component,
859 you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
863 This function itself doesn't allocate the data space. The data
864 must be allocated manually beforehand, and its pointer is passed
865 as the argument. This pointer is used as the identifier
866 (<parameter>chip</parameter> in the above example) for the
871 Each ALSA pre-defined component such as ac97 or pcm calls
872 <function>snd_device_new()</function> inside its
873 constructor. The destructor for each component is defined in the
874 callback pointers. Hence, you don't need to take care of
875 calling a destructor for such a component.
879 If you would like to create your own component, you need to
880 set the destructor function to dev_free callback in
881 <parameter>ops</parameter>, so that it can be released
882 automatically via <function>snd_card_free()</function>. The
883 example will be shown later as an implementation of a
888 <section id="card-management-chip-specific">
889 <title>Chip-Specific Data</title>
891 The chip-specific information, e.g. the i/o port address, its
892 resource pointer, or the irq number, is stored in the
893 chip-specific record.
894 Usually, the chip-specific record is typedef'ed as
895 <type>xxx_t</type> like the following:
900 typedef struct snd_mychip mychip_t;
910 In general, there are two ways to allocate the chip record.
913 <section id="card-management-chip-specific-snd-card-new">
914 <title>1. Allocating via <function>snd_card_new()</function>.</title>
916 As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
921 card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
926 whether <type>mychip_t</type> is the type of the chip record.
930 In return, the allocated record can be accessed as
935 mychip_t *chip = (mychip_t *)card->private_data;
940 With this method, you don't have to allocate twice.
941 The record is released together with the card instance.
945 <section id="card-management-chip-specific-allocate-extra">
946 <title>2. Allocating an extra device.</title>
949 After allocating a card instance via
950 <function>snd_card_new()</function> (with
951 <constant>NULL</constant> on the 4th arg), call
952 <function>kcalloc()</function>.
959 card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
961 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
968 The chip record should have the field to hold the card
984 Then, set the card pointer in the returned chip instance.
996 Next, initialize the fields, and register this chip
997 record as a low-level device with a specified
998 <parameter>ops</parameter>,
1003 static snd_device_ops_t ops = {
1004 .dev_free = snd_mychip_dev_free,
1007 snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1012 <function>snd_mychip_dev_free()</function> is the
1013 device-destructor function, which will call the real
1021 static int snd_mychip_dev_free(snd_device_t *device)
1023 mychip_t *chip = device->device_data;
1024 return snd_mychip_free(chip);
1030 where <function>snd_mychip_free()</function> is the real destructor.
1035 <section id="card-management-registration">
1036 <title>Registration and Release</title>
1038 After all components are assigned, register the card instance
1039 by calling <function>snd_card_register()</function>. The access
1040 to the device files are enabled at this point. That is, before
1041 <function>snd_card_register()</function> is called, the
1042 components are safely inaccessible from external side. If this
1043 call fails, exit the probe function after releasing the card via
1044 <function>snd_card_free()</function>.
1048 For releasing the card instance, you can call simply
1049 <function>snd_card_free()</function>. As already mentioned, all
1050 components are released automatically by this call.
1054 As further notes, the destructors (both
1055 <function>snd_mychip_dev_free</function> and
1056 <function>snd_mychip_free</function>) cannot be defined with
1057 <parameter>__devexit</parameter> prefix, because they may be
1058 called from the constructor, too, at the false path.
1062 For a device which allows hotplugging, you can use
1063 <function>snd_card_free_in_thread</function>. This one will
1064 postpone the destruction and wait in a kernel-thread until all
1073 <!-- ****************************************************** -->
1074 <!-- PCI Resource Managements -->
1075 <!-- ****************************************************** -->
1076 <chapter id="pci-resource">
1077 <title>PCI Resource Managements</title>
1079 <section id="pci-resource-example">
1080 <title>Full Code Example</title>
1082 In this section, we'll finish the chip-specific constructor,
1083 destructor and PCI entries. The example code is shown first,
1087 <title>PCI Resource Managements Example</title>
1092 struct pci_dev *pci;
1098 static int snd_mychip_free(mychip_t *chip)
1100 /* disable hardware here if any */
1101 .... // (not implemented in this document)
1103 /* release the irq */
1105 free_irq(chip->irq, (void *)chip);
1106 /* release the i/o ports */
1107 pci_release_regions(chip->pci);
1108 /* disable the PCI entry */
1109 pci_disable_device(chip->pci);
1110 /* release the data */
1115 /* chip-specific constructor */
1116 static int __devinit snd_mychip_create(snd_card_t *card,
1117 struct pci_dev *pci,
1122 static snd_device_ops_t ops = {
1123 .dev_free = snd_mychip_dev_free,
1128 /* initialize the PCI entry */
1129 if ((err = pci_enable_device(pci)) < 0)
1131 /* check PCI availability (28bit DMA) */
1132 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1133 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1134 printk(KERN_ERR "error to set 28bit mask DMA\n");
1135 pci_disable_device(pci);
1139 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
1141 pci_disable_device(pci);
1145 /* initialize the stuff */
1150 /* (1) PCI resource allocation */
1151 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1153 pci_disable_device(pci);
1156 chip->port = pci_resource_start(pci, 0);
1157 if (request_irq(pci->irq, snd_mychip_interrupt,
1158 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1160 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1161 snd_mychip_free(chip);
1164 chip->irq = pci->irq;
1166 /* (2) initialization of the chip hardware */
1167 .... // (not implemented in this document)
1169 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1171 snd_mychip_free(chip);
1175 snd_card_set_dev(card, &pci->dev);
1182 static struct pci_device_id snd_mychip_ids[] = {
1183 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1184 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1188 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1190 /* pci_driver definition */
1191 static struct pci_driver driver = {
1192 .name = "My Own Chip",
1193 .id_table = snd_mychip_ids,
1194 .probe = snd_mychip_probe,
1195 .remove = __devexit_p(snd_mychip_remove),
1198 /* initialization of the module */
1199 static int __init alsa_card_mychip_init(void)
1201 return pci_module_init(&driver);
1204 /* clean up the module */
1205 static void __exit alsa_card_mychip_exit(void)
1207 pci_unregister_driver(&driver);
1210 module_init(alsa_card_mychip_init)
1211 module_exit(alsa_card_mychip_exit)
1213 EXPORT_NO_SYMBOLS; /* for old kernels only */
1220 <section id="pci-resource-some-haftas">
1221 <title>Some Hafta's</title>
1223 The allocation of PCI resources is done in the
1224 <function>probe()</function> function, and usually an extra
1225 <function>xxx_create()</function> function is written for this
1230 In the case of PCI devices, you have to call at first
1231 <function>pci_enable_device()</function> function before
1232 allocating resources. Also, you need to set the proper PCI DMA
1233 mask to limit the accessed i/o range. In some cases, you might
1234 need to call <function>pci_set_master()</function> function,
1239 Suppose the 28bit mask, and the code to be added would be like:
1244 if ((err = pci_enable_device(pci)) < 0)
1246 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1247 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1248 printk(KERN_ERR "error to set 28bit mask DMA\n");
1249 pci_disable_device(pci);
1259 <section id="pci-resource-resource-allocation">
1260 <title>Resource Allocation</title>
1262 The allocation of I/O ports and irqs are done via standard kernel
1263 functions. Unlike ALSA ver.0.5.x., there are no helpers for
1264 that. And these resources must be released in the destructor
1265 function (see below). Also, on ALSA 0.9.x, you don't need to
1266 allocate (pseudo-)DMA for PCI like ALSA 0.5.x.
1270 Now assume that this PCI device has an I/O port with 8 bytes
1271 and an interrupt. Then <type>mychip_t</type> will have the
1289 For an i/o port (and also a memory region), you need to have
1290 the resource pointer for the standard resource management. For
1291 an irq, you have to keep only the irq number (integer). But you
1292 need to initialize this number as -1 before actual allocation,
1293 since irq 0 is valid. The port address and its resource pointer
1294 can be initialized as null by
1295 <function>kcalloc()</function> automatically, so you
1296 don't have to take care of resetting them.
1300 The allocation of an i/o port is done like this:
1305 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1307 pci_disable_device(pci);
1310 chip->port = pci_resource_start(pci, 0);
1317 It will reserve the i/o port region of 8 bytes of the given
1318 PCI device. The returned value, chip->res_port, is allocated
1319 via <function>kmalloc()</function> by
1320 <function>request_region()</function>. The pointer must be
1321 released via <function>kfree()</function>, but there is some
1322 problem regarding this. This issue will be explained more below.
1326 The allocation of an interrupt source is done like this:
1331 if (request_irq(pci->irq, snd_mychip_interrupt,
1332 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1334 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1335 snd_mychip_free(chip);
1338 chip->irq = pci->irq;
1343 where <function>snd_mychip_interrupt()</function> is the
1344 interrupt handler defined <link
1345 linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1346 Note that chip->irq should be defined
1347 only when <function>request_irq()</function> succeeded.
1351 On the PCI bus, the interrupts can be shared. Thus,
1352 <constant>SA_SHIRQ</constant> is given as the interrupt flag of
1353 <function>request_irq()</function>.
1357 The last argument of <function>request_irq()</function> is the
1358 data pointer passed to the interrupt handler. Usually, the
1359 chip-specific record is used for that, but you can use what you
1364 I won't define the detail of the interrupt handler at this
1365 point, but at least its appearance can be explained now. The
1366 interrupt handler looks usually like the following:
1371 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1372 struct pt_regs *regs)
1374 mychip_t *chip = dev_id;
1384 Now let's write the corresponding destructor for the resources
1385 above. The role of destructor is simple: disable the hardware
1386 (if already activated) and release the resources. So far, we
1387 have no hardware part, so the disabling is not written here.
1391 For releasing the resources, <quote>check-and-release</quote>
1392 method is a safer way. For the interrupt, do like this:
1398 free_irq(chip->irq, (void *)chip);
1403 Since the irq number can start from 0, you should initialize
1404 chip->irq with a negative value (e.g. -1), so that you can
1405 check the validity of the irq number as above.
1409 When you requested I/O ports or memory regions via
1410 <function>pci_request_region()</function> or
1411 <function>pci_request_regions()</function> like this example,
1412 release the resource(s) using the corresponding function,
1413 <function>pci_release_region()</function> or
1414 <function>pci_release_regions()</function>.
1419 pci_release_regions(chip->pci);
1426 When you requested manually via <function>request_region()</function>
1427 or <function>request_mem_region</function>, you can release it via
1428 <function>release_resource()</function>. Suppose that you keep
1429 the resource pointer returned from <function>request_region()</function>
1430 in chip->res_port, the release procedure looks like below:
1435 if (chip->res_port) {
1436 release_resource(chip->res_port);
1437 kfree_nocheck(chip->res_port);
1443 As you can see, the resource pointer is also to be freed
1444 via <function>kfree_nocheck()</function> after
1445 <function>release_resource()</function> is called. You
1446 cannot use <function>kfree()</function> here, because on ALSA,
1447 <function>kfree()</function> may be a wrapper to its own
1448 allocator with the memory debugging. Since the resource pointer
1449 is allocated externally outside the ALSA, it must be released
1451 <function>kfree()</function>.
1452 <function>kfree_nocheck()</function> is used for that; it calls
1453 the native <function>kfree()</function> without wrapper.
1457 Don't forget to call <function>pci_disable_device()</function>
1458 before all finished.
1462 And finally, release the chip-specific record.
1474 Again, remember that you cannot
1475 set <parameter>__devexit</parameter> prefix for this destructor.
1479 We didn't implement the hardware-disabling part in the above.
1480 If you need to do this, please note that the destructor may be
1481 called even before the initialization of the chip is completed.
1482 It would be better to have a flag to skip the hardware-disabling
1483 if the hardware was not initialized yet.
1487 When the chip-data is assigned to the card using
1488 <function>snd_device_new()</function> with
1489 <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is
1490 called at the last. That is, it is assured that all other
1491 components like PCMs and controls have been already released.
1492 You don't have to call stopping PCMs, etc. explicitly, but just
1493 stop the hardware in the low-level.
1497 The management of a memory-mapped region is almost as same as
1498 the management of an i/o port. You'll need three fields like
1506 unsigned long iobase_phys;
1507 void __iomem *iobase_virt;
1513 and the allocation would be like below:
1518 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1522 chip->iobase_phys = pci_resource_start(pci, 0);
1523 chip->iobase_virt = ioremap_nocache(chip->iobase_phys,
1524 pci_resource_len(pci, 0));
1529 and the corresponding destructor would be:
1534 static int snd_mychip_free(mychip_t *chip)
1537 if (chip->iobase_virt)
1538 iounmap(chip->iobase_virt);
1540 pci_release_regions(chip->pci);
1550 <section id="pci-resource-device-struct">
1551 <title>Registration of Device Struct</title>
1553 At some point, typically after calling <function>snd_device_new()</function>,
1554 you need to register the <structname>struct device</structname> of the chip
1555 you're handling for udev and co. ALSA provides a macro for compatibility with
1556 older kernels. Simply call like the following:
1560 snd_card_set_dev(card, &pci->dev);
1564 so that it stores the PCI's device pointer to the card. This will be
1565 referred by ALSA core functions later when the devices are registered.
1568 In the case of non-PCI, pass the proper device struct pointer of the BUS
1569 instead. (In the case of legacy ISA without PnP, you don't have to do
1574 <section id="pci-resource-entries">
1575 <title>PCI Entries</title>
1577 So far, so good. Let's finish the rest of missing PCI
1578 stuffs. At first, we need a
1579 <structname>pci_device_id</structname> table for this
1580 chipset. It's a table of PCI vendor/device ID number, and some
1590 static struct pci_device_id snd_mychip_ids[] = {
1591 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1592 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1596 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1603 The first and second fields of
1604 <structname>pci_device_id</structname> struct are the vendor and
1605 device IDs. If you have nothing special to filter the matching
1606 devices, you can use the rest of fields like above. The last
1607 field of <structname>pci_device_id</structname> struct is a
1608 private data for this entry. You can specify any value here, for
1609 example, to tell the type of different operations per each
1610 device IDs. Such an example is found in intel8x0 driver.
1614 The last entry of this list is the terminator. You must
1615 specify this all-zero entry.
1619 Then, prepare the <structname>pci_driver</structname> record:
1624 static struct pci_driver driver = {
1625 .name = "My Own Chip",
1626 .id_table = snd_mychip_ids,
1627 .probe = snd_mychip_probe,
1628 .remove = __devexit_p(snd_mychip_remove),
1636 The <structfield>probe</structfield> and
1637 <structfield>remove</structfield> functions are what we already
1639 the previous sections. The <structfield>remove</structfield> should
1641 <function>__devexit_p()</function> macro, so that it's not
1642 defined for built-in (and non-hot-pluggable) case. The
1643 <structfield>name</structfield>
1644 field is the name string of this device. Note that you must not
1645 use a slash <quote>/</quote> in this string.
1649 And at last, the module entries:
1654 static int __init alsa_card_mychip_init(void)
1656 return pci_module_init(&driver);
1659 static void __exit alsa_card_mychip_exit(void)
1661 pci_unregister_driver(&driver);
1664 module_init(alsa_card_mychip_init)
1665 module_exit(alsa_card_mychip_exit)
1672 Note that these module entries are tagged with
1673 <parameter>__init</parameter> and
1674 <parameter>__exit</parameter> prefixes, not
1675 <parameter>__devinit</parameter> nor
1676 <parameter>__devexit</parameter>.
1680 Oh, one thing was forgotten. If you have no exported symbols,
1681 you need to declare it on 2.2 or 2.4 kernels (on 2.6 kernels
1682 it's not necessary, though).
1698 <!-- ****************************************************** -->
1699 <!-- PCM Interface -->
1700 <!-- ****************************************************** -->
1701 <chapter id="pcm-interface">
1702 <title>PCM Interface</title>
1704 <section id="pcm-interface-general">
1705 <title>General</title>
1707 The PCM middle layer of ALSA is quite powerful and it is only
1708 necessary for each driver to implement the low-level functions
1709 to access its hardware.
1713 For accessing to the PCM layer, you need to include
1714 <filename><sound/pcm.h></filename> above all. In addition,
1715 <filename><sound/pcm_params.h></filename> might be needed
1716 if you access to some functions related with hw_param.
1720 Each card device can have up to four pcm instances. A pcm
1721 instance corresponds to a pcm device file. The limitation of
1722 number of instances comes only from the available bit size of
1723 the linux's device number. Once when 64bit device number is
1724 used, we'll have more available pcm instances.
1728 A pcm instance consists of pcm playback and capture streams,
1729 and each pcm stream consists of one or more pcm substreams. Some
1730 soundcard supports the multiple-playback function. For example,
1731 emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1732 each open, a free substream is (usually) automatically chosen
1733 and opened. Meanwhile, when only one substream exists and it was
1734 already opened, the succeeding open will result in the blocking
1735 or the error with <constant>EAGAIN</constant> according to the
1736 file open mode. But you don't have to know the detail in your
1737 driver. The PCM middle layer will take all such jobs.
1741 <section id="pcm-interface-example">
1742 <title>Full Code Example</title>
1744 The example code below does not include any hardware access
1745 routines but shows only the skeleton, how to build up the PCM
1749 <title>PCM Example Code</title>
1752 #include <sound/pcm.h>
1755 /* hardware definition */
1756 static snd_pcm_hardware_t snd_mychip_playback_hw = {
1757 .info = (SNDRV_PCM_INFO_MMAP |
1758 SNDRV_PCM_INFO_INTERLEAVED |
1759 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1760 SNDRV_PCM_INFO_MMAP_VALID),
1761 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1762 .rates = SNDRV_PCM_RATE_8000_48000,
1767 .buffer_bytes_max = 32768,
1768 .period_bytes_min = 4096,
1769 .period_bytes_max = 32768,
1771 .periods_max = 1024,
1774 /* hardware definition */
1775 static snd_pcm_hardware_t snd_mychip_capture_hw = {
1776 .info = (SNDRV_PCM_INFO_MMAP |
1777 SNDRV_PCM_INFO_INTERLEAVED |
1778 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1779 SNDRV_PCM_INFO_MMAP_VALID),
1780 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1781 .rates = SNDRV_PCM_RATE_8000_48000,
1786 .buffer_bytes_max = 32768,
1787 .period_bytes_min = 4096,
1788 .period_bytes_max = 32768,
1790 .periods_max = 1024,
1794 static int snd_mychip_playback_open(snd_pcm_substream_t *substream)
1796 mychip_t *chip = snd_pcm_substream_chip(substream);
1797 snd_pcm_runtime_t *runtime = substream->runtime;
1799 runtime->hw = snd_mychip_playback_hw;
1800 // more hardware-initialization will be done here
1804 /* close callback */
1805 static int snd_mychip_playback_close(snd_pcm_substream_t *substream)
1807 mychip_t *chip = snd_pcm_substream_chip(substream);
1808 // the hardware-specific codes will be here
1814 static int snd_mychip_capture_open(snd_pcm_substream_t *substream)
1816 mychip_t *chip = snd_pcm_substream_chip(substream);
1817 snd_pcm_runtime_t *runtime = substream->runtime;
1819 runtime->hw = snd_mychip_capture_hw;
1820 // more hardware-initialization will be done here
1824 /* close callback */
1825 static int snd_mychip_capture_close(snd_pcm_substream_t *substream)
1827 mychip_t *chip = snd_pcm_substream_chip(substream);
1828 // the hardware-specific codes will be here
1833 /* hw_params callback */
1834 static int snd_mychip_pcm_hw_params(snd_pcm_substream_t *substream,
1835 snd_pcm_hw_params_t * hw_params)
1837 return snd_pcm_lib_malloc_pages(substream,
1838 params_buffer_bytes(hw_params));
1841 /* hw_free callback */
1842 static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1844 return snd_pcm_lib_free_pages(substream);
1847 /* prepare callback */
1848 static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1850 mychip_t *chip = snd_pcm_substream_chip(substream);
1851 snd_pcm_runtime_t *runtime = substream->runtime;
1853 /* set up the hardware with the current configuration
1856 mychip_set_sample_format(chip, runtime->format);
1857 mychip_set_sample_rate(chip, runtime->rate);
1858 mychip_set_channels(chip, runtime->channels);
1859 mychip_set_dma_setup(chip, runtime->dma_area,
1865 /* trigger callback */
1866 static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
1870 case SNDRV_PCM_TRIGGER_START:
1871 // do something to start the PCM engine
1873 case SNDRV_PCM_TRIGGER_STOP:
1874 // do something to stop the PCM engine
1881 /* pointer callback */
1882 static snd_pcm_uframes_t
1883 snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
1885 mychip_t *chip = snd_pcm_substream_chip(substream);
1886 unsigned int current_ptr;
1888 /* get the current hardware pointer */
1889 current_ptr = mychip_get_hw_pointer(chip);
1894 static snd_pcm_ops_t snd_mychip_playback_ops = {
1895 .open = snd_mychip_playback_open,
1896 .close = snd_mychip_playback_close,
1897 .ioctl = snd_pcm_lib_ioctl,
1898 .hw_params = snd_mychip_pcm_hw_params,
1899 .hw_free = snd_mychip_pcm_hw_free,
1900 .prepare = snd_mychip_pcm_prepare,
1901 .trigger = snd_mychip_pcm_trigger,
1902 .pointer = snd_mychip_pcm_pointer,
1906 static snd_pcm_ops_t snd_mychip_capture_ops = {
1907 .open = snd_mychip_capture_open,
1908 .close = snd_mychip_capture_close,
1909 .ioctl = snd_pcm_lib_ioctl,
1910 .hw_params = snd_mychip_pcm_hw_params,
1911 .hw_free = snd_mychip_pcm_hw_free,
1912 .prepare = snd_mychip_pcm_prepare,
1913 .trigger = snd_mychip_pcm_trigger,
1914 .pointer = snd_mychip_pcm_pointer,
1918 * definitions of capture are omitted here...
1921 /* create a pcm device */
1922 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
1927 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
1930 pcm->private_data = chip;
1931 strcpy(pcm->name, "My Chip");
1934 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1935 &snd_mychip_playback_ops);
1936 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
1937 &snd_mychip_capture_ops);
1938 /* pre-allocation of buffers */
1939 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
1940 snd_dma_pci_data(chip->pci),
1950 <section id="pcm-interface-constructor">
1951 <title>Constructor</title>
1953 A pcm instance is allocated <function>snd_pcm_new()</function>
1954 function. It would be better to create a constructor for pcm,
1960 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
1965 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
1968 pcm->private_data = chip;
1969 strcpy(pcm->name, "My Chip");
1980 The <function>snd_pcm_new()</function> function takes the four
1981 arguments. The first argument is the card pointer to which this
1982 pcm is assigned, and the second is the ID string.
1986 The third argument (<parameter>index</parameter>, 0 in the
1987 above) is the index of this new pcm. It begins from zero. When
1988 you will create more than one pcm instances, specify the
1989 different numbers in this argument. For example,
1990 <parameter>index</parameter> = 1 for the second PCM device.
1994 The fourth and fifth arguments are the number of substreams
1995 for playback and capture, respectively. Here both 1 are given in
1996 the above example. When no playback or no capture is available,
1997 pass 0 to the corresponding argument.
2001 If a chip supports multiple playbacks or captures, you can
2002 specify more numbers, but they must be handled properly in
2003 open/close, etc. callbacks. When you need to know which
2004 substream you are referring to, then it can be obtained from
2005 <type>snd_pcm_substream_t</type> data passed to each callback
2011 snd_pcm_substream_t *substream;
2012 int index = substream->number;
2019 After the pcm is created, you need to set operators for each
2025 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2026 &snd_mychip_playback_ops);
2027 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2028 &snd_mychip_capture_ops);
2035 The operators are defined typically like this:
2040 static snd_pcm_ops_t snd_mychip_playback_ops = {
2041 .open = snd_mychip_pcm_open,
2042 .close = snd_mychip_pcm_close,
2043 .ioctl = snd_pcm_lib_ioctl,
2044 .hw_params = snd_mychip_pcm_hw_params,
2045 .hw_free = snd_mychip_pcm_hw_free,
2046 .prepare = snd_mychip_pcm_prepare,
2047 .trigger = snd_mychip_pcm_trigger,
2048 .pointer = snd_mychip_pcm_pointer,
2054 Each of callbacks is explained in the subsection
2055 <link linkend="pcm-interface-operators"><citetitle>
2056 Operators</citetitle></link>.
2060 After setting the operators, most likely you'd like to
2061 pre-allocate the buffer. For the pre-allocation, simply call
2067 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2068 snd_dma_pci_data(chip->pci),
2074 It will allocate up to 64kB buffer as default. The details of
2075 buffer management will be described in the later section <link
2076 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2077 Management</citetitle></link>.
2081 Additionally, you can set some extra information for this pcm
2082 in pcm->info_flags.
2083 The available values are defined as
2084 <constant>SNDRV_PCM_INFO_XXX</constant> in
2085 <filename><sound/asound.h></filename>, which is used for
2086 the hardware definition (described later). When your soundchip
2087 supports only half-duplex, specify like this:
2092 pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2099 <section id="pcm-interface-destructor">
2100 <title>... And the Destructor?</title>
2102 The destructor for a pcm instance is not always
2103 necessary. Since the pcm device will be released by the middle
2104 layer code automatically, you don't have to call destructor
2109 The destructor would be necessary when you created some
2110 special records internally and need to release them. In such a
2111 case, set the destructor function to
2112 pcm->private_free:
2115 <title>PCM Instance with a Destructor</title>
2118 static void mychip_pcm_free(snd_pcm_t *pcm)
2120 mychip_t *chip = snd_pcm_chip(pcm);
2121 /* free your own data */
2122 kfree(chip->my_private_pcm_data);
2123 // do what you like else
2127 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2131 /* allocate your own data */
2132 chip->my_private_pcm_data = kmalloc(...);
2133 /* set the destructor */
2134 pcm->private_data = chip;
2135 pcm->private_free = mychip_pcm_free;
2144 <section id="pcm-interface-runtime">
2145 <title>Runtime Pointer - The Chest of PCM Information</title>
2147 When the PCM substream is opened, a PCM runtime instance is
2148 allocated and assigned to the substream. This pointer is
2149 accessible via <constant>substream->runtime</constant>.
2150 This runtime pointer holds the various information; it holds
2151 the copy of hw_params and sw_params configurations, the buffer
2152 pointers, mmap records, spinlocks, etc. Almost everyhing you
2153 need for controlling the PCM can be found there.
2157 The definition of runtime instance is found in
2158 <filename><sound/pcm.h></filename>. Here is the
2163 struct _snd_pcm_runtime {
2165 snd_pcm_substream_t *trigger_master;
2166 snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2168 snd_pcm_uframes_t avail_max;
2169 snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */
2170 snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2172 /* -- HW params -- */
2173 snd_pcm_access_t access; /* access mode */
2174 snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */
2175 snd_pcm_subformat_t subformat; /* subformat */
2176 unsigned int rate; /* rate in Hz */
2177 unsigned int channels; /* channels */
2178 snd_pcm_uframes_t period_size; /* period size */
2179 unsigned int periods; /* periods */
2180 snd_pcm_uframes_t buffer_size; /* buffer size */
2181 unsigned int tick_time; /* tick time */
2182 snd_pcm_uframes_t min_align; /* Min alignment for the format */
2184 unsigned int frame_bits;
2185 unsigned int sample_bits;
2187 unsigned int rate_num;
2188 unsigned int rate_den;
2190 /* -- SW params -- */
2191 int tstamp_timespec; /* use timeval (0) or timespec (1) */
2192 snd_pcm_tstamp_t tstamp_mode; /* mmap timestamp is updated */
2193 unsigned int period_step;
2194 unsigned int sleep_min; /* min ticks to sleep */
2195 snd_pcm_uframes_t xfer_align; /* xfer size need to be a multiple */
2196 snd_pcm_uframes_t start_threshold;
2197 snd_pcm_uframes_t stop_threshold;
2198 snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2199 noise is nearest than this */
2200 snd_pcm_uframes_t silence_size; /* Silence filling size */
2201 snd_pcm_uframes_t boundary; /* pointers wrap point */
2203 snd_pcm_uframes_t silenced_start;
2204 snd_pcm_uframes_t silenced_size;
2206 snd_pcm_sync_id_t sync; /* hardware synchronization ID */
2209 volatile snd_pcm_mmap_status_t *status;
2210 volatile snd_pcm_mmap_control_t *control;
2211 atomic_t mmap_count;
2213 /* -- locking / scheduling -- */
2215 wait_queue_head_t sleep;
2216 struct timer_list tick_timer;
2217 struct fasync_struct *fasync;
2219 /* -- private section -- */
2221 void (*private_free)(snd_pcm_runtime_t *runtime);
2223 /* -- hardware description -- */
2224 snd_pcm_hardware_t hw;
2225 snd_pcm_hw_constraints_t hw_constraints;
2227 /* -- interrupt callbacks -- */
2228 void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2229 void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2232 unsigned int timer_resolution; /* timer resolution */
2235 unsigned char *dma_area; /* DMA area */
2236 dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */
2237 size_t dma_bytes; /* size of DMA area */
2238 void *dma_private; /* private DMA data for the memory allocator */
2240 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2241 /* -- OSS things -- */
2242 snd_pcm_oss_runtime_t oss;
2251 For the operators (callbacks) of each sound driver, most of
2252 these records are supposed to be read-only. Only the PCM
2253 middle-layer changes / updates these info. The excpetions are
2254 the hardware description (hw), interrupt callbacks
2255 (transfer_ack_xxx), DMA buffer information, and the private
2256 data. Besides, if you use the standard buffer allocation
2257 method via <function>snd_pcm_lib_malloc_pages()</function>,
2258 you don't need to set the DMA buffer information by yourself.
2262 In the sections below, important records are explained.
2265 <section id="pcm-interface-runtime-hw">
2266 <title>Hardware Description</title>
2268 The hardware descriptor (<type>snd_pcm_hardware_t</type>)
2269 contains the definitions of the fundamental hardware
2270 configuration. Above all, you'll need to define this in
2271 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2272 the open callback</citetitle></link>.
2273 Note that the runtime instance holds the copy of the
2274 descriptor, not the pointer to the existing descriptor. That
2275 is, in the open callback, you can modify the copied descriptor
2276 (<constant>runtime->hw</constant>) as you need. For example, if the maximum
2277 number of channels is 1 only on some chip models, you can
2278 still use the same hardware descriptor and change the
2283 snd_pcm_runtime_t *runtime = substream->runtime;
2285 runtime->hw = snd_mychip_playback_hw; /* common definition */
2286 if (chip->model == VERY_OLD_ONE)
2287 runtime->hw.channels_max = 1;
2294 Typically, you'll have a hardware descriptor like below:
2298 static snd_pcm_hardware_t snd_mychip_playback_hw = {
2299 .info = (SNDRV_PCM_INFO_MMAP |
2300 SNDRV_PCM_INFO_INTERLEAVED |
2301 SNDRV_PCM_INFO_BLOCK_TRANSFER |
2302 SNDRV_PCM_INFO_MMAP_VALID),
2303 .formats = SNDRV_PCM_FMTBIT_S16_LE,
2304 .rates = SNDRV_PCM_RATE_8000_48000,
2309 .buffer_bytes_max = 32768,
2310 .period_bytes_min = 4096,
2311 .period_bytes_max = 32768,
2313 .periods_max = 1024,
2323 The <structfield>info</structfield> field contains the type and
2324 capabilities of this pcm. The bit flags are defined in
2325 <filename><sound/asound.h></filename> as
2326 <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2327 have to specify whether the mmap is supported and which
2328 interleaved format is supported.
2329 When the mmap is supported, add
2330 <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2331 hardware supports the interleaved or the non-interleaved
2332 format, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2333 <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2334 be set, respectively. If both are supported, you can set both,
2339 In the above example, <constant>MMAP_VALID</constant> and
2340 <constant>BLOCK_TRANSFER</constant> are specified for OSS mmap
2341 mode. Usually both are set. Of course,
2342 <constant>MMAP_VALID</constant> is set only if the mmap is
2347 The other possible flags are
2348 <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2349 <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2350 <constant>PAUSE</constant> bit means that the pcm supports the
2351 <quote>pause</quote> operation, while the
2352 <constant>RESUME</constant> bit means that the pcm supports
2353 the <quote>suspend/resume</quote> operation. If these flags
2354 are set, the <structfield>trigger</structfield> callback below
2355 must handle the corresponding commands.
2359 When the PCM substreams can be synchronized (typically,
2360 synchorinized start/stop of a playback and a capture streams),
2361 you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2362 too. In this case, you'll need to check the linked-list of
2363 PCM substreams in the trigger callback. This will be
2364 described in the later section.
2370 <structfield>formats</structfield> field contains the bit-flags
2371 of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2372 If the hardware supports more than one format, give all or'ed
2373 bits. In the example above, the signed 16bit little-endian
2374 format is specified.
2380 <structfield>rates</structfield> field contains the bit-flags of
2381 supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2382 When the chip supports continuous rates, pass
2383 <constant>CONTINUOUS</constant> bit additionally.
2384 The pre-defined rate bits are provided only for typical
2385 rates. If your chip supports unconventional rates, you need to add
2386 <constant>KNOT</constant> bit and set up the hardware
2387 constraint manually (explained later).
2393 <structfield>rate_min</structfield> and
2394 <structfield>rate_max</structfield> define the minimal and
2395 maximal sample rate. This should correspond somehow to
2396 <structfield>rates</structfield> bits.
2402 <structfield>channel_min</structfield> and
2403 <structfield>channel_max</structfield>
2404 define, as you might already expected, the minimal and maximal
2411 <structfield>buffer_bytes_max</structfield> defines the
2412 maximal buffer size in bytes. There is no
2413 <structfield>buffer_bytes_min</structfield> field, since
2414 it can be calculated from the minimal period size and the
2415 minimal number of periods.
2416 Meanwhile, <structfield>period_bytes_min</structfield> and
2417 define the minimal and maximal size of the period in bytes.
2418 <structfield>periods_max</structfield> and
2419 <structfield>periods_min</structfield> define the maximal and
2420 minimal number of periods in the buffer.
2424 The <quote>period</quote> is a term, that corresponds to
2425 fragment in the OSS world. The period defines the size at
2426 which the PCM interrupt is generated. This size strongly
2427 depends on the hardware.
2428 Generally, the smaller period size will give you more
2429 interrupts, that is, more controls.
2430 In the case of capture, this size defines the input latency.
2431 On the other hand, the whole buffer size defines the
2432 output latency for the playback direction.
2438 There is also a field <structfield>fifo_size</structfield>.
2439 This specifies the size of the hardware FIFO, but it's not
2440 used currently in the driver nor in the alsa-lib. So, you
2441 can ignore this field.
2448 <section id="pcm-interface-runtime-config">
2449 <title>PCM Configurations</title>
2451 Ok, let's go back again to the PCM runtime records.
2452 The most frequently referred records in the runtime instance are
2453 the PCM configurations.
2454 The PCM configurations are stored on runtime instance
2455 after the application sends <type>hw_params</type> data via
2456 alsa-lib. There are many fields copied from hw_params and
2457 sw_params structs. For example,
2458 <structfield>format</structfield> holds the format type
2459 chosen by the application. This field contains the enum value
2460 <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2464 One thing to be noted is that the configured buffer and period
2465 sizes are stored in <quote>frames</quote> in the runtime
2466 In the ALSA world, 1 frame = channels * samples-size.
2467 For conversion between frames and bytes, you can use the
2468 helper functions, <function>frames_to_bytes()</function> and
2469 <function>bytes_to_frames()</function>.
2473 period_bytes = frames_to_bytes(runtime, runtime->period_size);
2480 Also, many software parameters (sw_params) are
2481 stored in frames, too. Please check the type of the field.
2482 <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2483 integer while <type>snd_pcm_sframes_t</type> is for the frames
2488 <section id="pcm-interface-runtime-dma">
2489 <title>DMA Buffer Information</title>
2491 The DMA buffer is defined by the following four fields,
2492 <structfield>dma_area</structfield>,
2493 <structfield>dma_addr</structfield>,
2494 <structfield>dma_bytes</structfield> and
2495 <structfield>dma_private</structfield>.
2496 The <structfield>dma_area</structfield> holds the buffer
2497 pointer (the logical address). You can call
2498 <function>memcpy</function> from/to
2499 this pointer. Meanwhile, <structfield>dma_addr</structfield>
2500 holds the physical address of the buffer. This field is
2501 specified only when the buffer is a linear buffer.
2502 <structfield>dma_bytes</structfield> holds the size of buffer
2503 in bytes. <structfield>dma_private</structfield> is used for
2504 the ALSA DMA allocator.
2508 If you use a standard ALSA function,
2509 <function>snd_pcm_lib_malloc_pages()</function>, for
2510 allocating the buffer, these fields are set by the ALSA middle
2511 layer, and you should <emphasis>not</emphasis> change them by
2512 yourself. You can read them but not write them.
2513 On the other hand, if you want to allocate the buffer by
2514 yourself, you'll need to manage it in hw_params callback.
2515 At least, <structfield>dma_bytes</structfield> is mandatory.
2516 <structfield>dma_area</structfield> is necessary when the
2517 buffer is mmapped. If your driver doesn't support mmap, this
2518 field is not necessary. <structfield>dma_addr</structfield>
2519 is also not mandatory. You can use
2520 <structfield>dma_private</structfield> as you like, too.
2524 <section id="pcm-interface-runtime-status">
2525 <title>Running Status</title>
2527 The running status can be referred via <constant>runtime->status</constant>.
2528 This is the pointer to <type>snd_pcm_mmap_status_t</type>
2529 record. For example, you can get the current DMA hardware
2530 pointer via <constant>runtime->status->hw_ptr</constant>.
2534 The DMA application pointer can be referred via
2535 <constant>runtime->control</constant>, which points
2536 <type>snd_pcm_mmap_control_t</type> record.
2537 However, accessing directly to this value is not recommended.
2541 <section id="pcm-interface-runtime-private">
2542 <title>Private Data</title>
2544 You can allocate a record for the substream and store it in
2545 <constant>runtime->private_data</constant>. Usually, this
2547 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2548 the open callback</citetitle></link>.
2549 Don't mix this with <constant>pcm->private_data</constant>.
2550 The <constant>pcm->private_data</constant> usually points the
2551 chip instance assigned statically at the creation of PCM, while the
2552 <constant>runtime->private_data</constant> points a dynamic
2553 data created at the PCM open callback.
2558 static int snd_xxx_open(snd_pcm_substream_t *substream)
2560 my_pcm_data_t *data;
2562 data = kmalloc(sizeof(*data), GFP_KERNEL);
2563 substream->runtime->private_data = data;
2572 The allocated object must be released in
2573 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2574 the close callback</citetitle></link>.
2578 <section id="pcm-interface-runtime-intr">
2579 <title>Interrupt Callbacks</title>
2581 The field <structfield>transfer_ack_begin</structfield> and
2582 <structfield>transfer_ack_end</structfield> are called at
2583 the beginning and the end of
2584 <function>snd_pcm_period_elapsed()</function>, respectively.
2590 <section id="pcm-interface-operators">
2591 <title>Operators</title>
2593 OK, now let me explain the detail of each pcm callback
2594 (<parameter>ops</parameter>). In general, every callback must
2595 return 0 if successful, or a negative number with the error
2596 number such as <constant>-EINVAL</constant> at any
2601 The callback function takes at least the argument with
2602 <type>snd_pcm_substream_t</type> pointer. For retrieving the
2603 chip record from the given substream instance, you can use the
2610 mychip_t *chip = snd_pcm_substream_chip(substream);
2617 The macro reads <constant>substream->private_data</constant>,
2618 which is a copy of <constant>pcm->private_data</constant>.
2619 You can override the former if you need to assign different data
2620 records per PCM substream. For example, cmi8330 driver assigns
2621 different private_data for playback and capture directions,
2622 because it uses two different codecs (SB- and AD-compatible) for
2623 different directions.
2626 <section id="pcm-interface-operators-open-callback">
2627 <title>open callback</title>
2632 static int snd_xxx_open(snd_pcm_substream_t *substream);
2637 This is called when a pcm substream is opened.
2641 At least, here you have to initialize the runtime->hw
2642 record. Typically, this is done by like this:
2647 static int snd_xxx_open(snd_pcm_substream_t *substream)
2649 mychip_t *chip = snd_pcm_substream_chip(substream);
2650 snd_pcm_runtime_t *runtime = substream->runtime;
2652 runtime->hw = snd_mychip_playback_hw;
2659 where <parameter>snd_mychip_playback_hw</parameter> is the
2660 pre-defined hardware description.
2664 You can allocate a private data in this callback, as described
2665 in <link linkend="pcm-interface-runtime-private"><citetitle>
2666 Private Data</citetitle></link> section.
2670 If the hardware configuration needs more constraints, set the
2671 hardware constraints here, too.
2672 See <link linkend="pcm-interface-constraints"><citetitle>
2673 Constraints</citetitle></link> for more details.
2677 <section id="pcm-interface-operators-close-callback">
2678 <title>close callback</title>
2683 static int snd_xxx_close(snd_pcm_substream_t *substream);
2688 Obviously, this is called when a pcm substream is closed.
2692 Any private instance for a pcm substream allocated in the
2693 open callback will be released here.
2698 static int snd_xxx_close(snd_pcm_substream_t *substream)
2701 kfree(substream->runtime->private_data);
2710 <section id="pcm-interface-operators-ioctl-callback">
2711 <title>ioctl callback</title>
2713 This is used for any special action to pcm ioctls. But
2714 usually you can pass a generic ioctl callback,
2715 <function>snd_pcm_lib_ioctl</function>.
2719 <section id="pcm-interface-operators-hw-params-callback">
2720 <title>hw_params callback</title>
2725 static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2726 snd_pcm_hw_params_t * hw_params);
2731 This and <structfield>hw_free</structfield> callbacks exist
2736 This is called when the hardware parameter
2737 (<structfield>hw_params</structfield>) is set
2738 up by the application,
2739 that is, once when the buffer size, the period size, the
2740 format, etc. are defined for the pcm substream.
2744 Many hardware set-up should be done in this callback,
2745 including the allocation of buffers.
2749 Parameters to be initialized are retrieved by
2750 <function>params_xxx()</function> macros. For allocating a
2751 buffer, you can call a helper function,
2756 snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2761 <function>snd_pcm_lib_malloc_pages()</function> is available
2762 only when the DMA buffers have been pre-allocated.
2763 See the section <link
2764 linkend="buffer-and-memory-buffer-types"><citetitle>
2765 Buffer Types</citetitle></link> for more details.
2769 Note that this and <structfield>prepare</structfield> callbacks
2770 may be called multiple times per initialization.
2771 For example, the OSS emulation may
2772 call these callbacks at each change via its ioctl.
2776 Thus, you need to take care not to allocate the same buffers
2777 many times, which will lead to memory leak! Calling the
2778 helper function above many times is OK. It will release the
2779 previous buffer automatically when it was already allocated.
2783 Another note is that this callback is non-atomic
2784 (schedulable). This is important, because the
2785 <structfield>trigger</structfield> callback
2786 is atomic (non-schedulable). That is, mutex or any
2787 schedule-related functions are not available in
2788 <structfield>trigger</structfield> callback.
2789 Please see the subsection
2790 <link linkend="pcm-interface-atomicity"><citetitle>
2791 Atomicity</citetitle></link> for details.
2795 <section id="pcm-interface-operators-hw-free-callback">
2796 <title>hw_free callback</title>
2801 static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2808 This is called to release the resources allocated via
2809 <structfield>hw_params</structfield>. For example, releasing the
2811 <function>snd_pcm_lib_malloc_pages()</function> is done by
2812 calling the following:
2817 snd_pcm_lib_free_pages(substream);
2824 This function is always called before the close callback is called.
2825 Also, the callback may be called multiple times, too.
2826 Keep track whether the resource was already released.
2830 <section id="pcm-interface-operators-prepare-callback">
2831 <title>prepare callback</title>
2836 static int snd_xxx_prepare(snd_pcm_substream_t * substream);
2843 This callback is called when the pcm is
2844 <quote>prepared</quote>. You can set the format type, sample
2845 rate, etc. here. The difference from
2846 <structfield>hw_params</structfield> is that the
2847 <structfield>prepare</structfield> callback will be called at each
2849 <function>snd_pcm_prepare()</function> is called, i.e. when
2850 recovered after underruns, etc.
2854 Note that this callback became non-atomic since the recent version.
2855 You can use schedule-related fucntions safely in this callback now.
2859 In this and the following callbacks, you can refer to the
2860 values via the runtime record,
2861 substream->runtime.
2862 For example, to get the current
2863 rate, format or channels, access to
2865 runtime->format or
2866 runtime->channels, respectively.
2867 The physical address of the allocated buffer is set to
2868 runtime->dma_area. The buffer and period sizes are
2869 in runtime->buffer_size and runtime->period_size,
2874 Be careful that this callback will be called many times at
2879 <section id="pcm-interface-operators-trigger-callback">
2880 <title>trigger callback</title>
2885 static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
2890 This is called when the pcm is started, stopped or paused.
2894 Which action is specified in the second argument,
2895 <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
2896 <filename><sound/pcm.h></filename>. At least,
2897 <constant>START</constant> and <constant>STOP</constant>
2898 commands must be defined in this callback.
2904 case SNDRV_PCM_TRIGGER_START:
2905 // do something to start the PCM engine
2907 case SNDRV_PCM_TRIGGER_STOP:
2908 // do something to stop the PCM engine
2919 When the pcm supports the pause operation (given in info
2920 field of the hardware table), <constant>PAUSE_PUSE</constant>
2921 and <constant>PAUSE_RELEASE</constant> commands must be
2922 handled here, too. The former is the command to pause the pcm,
2923 and the latter to restart the pcm again.
2927 When the pcm supports the suspend/resume operation
2928 (i.e. <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set),
2929 <constant>SUSPEND</constant> and <constant>RESUME</constant>
2930 commands must be handled, too.
2931 These commands are issued when the power-management status is
2932 changed. Obviously, the <constant>SUSPEND</constant> and
2933 <constant>RESUME</constant>
2934 do suspend and resume of the pcm substream, and usually, they
2935 are identical with <constant>STOP</constant> and
2936 <constant>START</constant> commands, respectively.
2940 As mentioned, this callback is atomic. You cannot call
2941 the function going to sleep.
2942 The trigger callback should be as minimal as possible,
2943 just really triggering the DMA. The other stuff should be
2944 initialized hw_params and prepare callbacks properly
2949 <section id="pcm-interface-operators-pointer-callback">
2950 <title>pointer callback</title>
2955 static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
2960 This callback is called when the PCM middle layer inquires
2961 the current hardware position on the buffer. The position must
2962 be returned in frames (which was in bytes on ALSA 0.5.x),
2963 ranged from 0 to buffer_size - 1.
2967 This is called usually from the buffer-update routine in the
2968 pcm middle layer, which is invoked when
2969 <function>snd_pcm_period_elapsed()</function> is called in the
2970 interrupt routine. Then the pcm middle layer updates the
2971 position and calculates the available space, and wakes up the
2972 sleeping poll threads, etc.
2976 This callback is also atomic.
2980 <section id="pcm-interface-operators-copy-silence">
2981 <title>copy and silence callbacks</title>
2983 These callbacks are not mandatory, and can be omitted in
2984 most cases. These callbacks are used when the hardware buffer
2985 cannot be on the normal memory space. Some chips have their
2986 own buffer on the hardware which is not mappable. In such a
2987 case, you have to transfer the data manually from the memory
2988 buffer to the hardware buffer. Or, if the buffer is
2989 non-contiguous on both physical and virtual memory spaces,
2990 these callbacks must be defined, too.
2994 If these two callbacks are defined, copy and set-silence
2995 operations are done by them. The detailed will be described in
2996 the later section <link
2997 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2998 Management</citetitle></link>.
3002 <section id="pcm-interface-operators-ack">
3003 <title>ack callback</title>
3005 This callback is also not mandatory. This callback is called
3006 when the appl_ptr is updated in read or write operations.
3007 Some drivers like emu10k1-fx and cs46xx need to track the
3008 current appl_ptr for the internal buffer, and this callback
3009 is useful only for such a purpose.
3013 <section id="pcm-interface-operators-page-callback">
3014 <title>page callback</title>
3017 This callback is also not mandatory. This callback is used
3018 mainly for the non-contiguous buffer. The mmap calls this
3019 callback to get the page address. Some examples will be
3020 explained in the later section <link
3021 linkend="buffer-and-memory"><citetitle>Buffer and Memory
3022 Management</citetitle></link>, too.
3027 <section id="pcm-interface-interrupt-handler">
3028 <title>Interrupt Handler</title>
3030 The rest of pcm stuff is the PCM interrupt handler. The
3031 role of PCM interrupt handler in the sound driver is to update
3032 the buffer position and to tell the PCM middle layer when the
3033 buffer position goes across the prescribed period size. To
3034 inform this, call <function>snd_pcm_period_elapsed()</function>
3039 There are several types of sound chips to generate the interrupts.
3042 <section id="pcm-interface-interrupt-handler-boundary">
3043 <title>Interrupts at the period (fragment) boundary</title>
3045 This is the most frequently found type: the hardware
3046 generates an interrupt at each period boundary.
3047 In this case, you can call
3048 <function>snd_pcm_period_elapsed()</function> at each
3053 <function>snd_pcm_period_elapsed()</function> takes the
3054 substream pointer as its argument. Thus, you need to keep the
3055 substream pointer accessible from the chip instance. For
3056 example, define substream field in the chip record to hold the
3057 current running substream pointer, and set the pointer value
3058 at open callback (and reset at close callback).
3062 If you aquire a spinlock in the interrupt handler, and the
3063 lock is used in other pcm callbacks, too, then you have to
3064 release the lock before calling
3065 <function>snd_pcm_period_elapsed()</function>, because
3066 <function>snd_pcm_period_elapsed()</function> calls other pcm
3071 A typical coding would be like:
3074 <title>Interrupt Handler Case #1</title>
3077 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3078 struct pt_regs *regs)
3080 mychip_t *chip = dev_id;
3081 spin_lock(&chip->lock);
3083 if (pcm_irq_invoked(chip)) {
3084 /* call updater, unlock before it */
3085 spin_unlock(&chip->lock);
3086 snd_pcm_period_elapsed(chip->substream);
3087 spin_lock(&chip->lock);
3088 // acknowledge the interrupt if necessary
3091 spin_unlock(&chip->lock);
3100 <section id="pcm-interface-interrupt-handler-timer">
3101 <title>High-frequent timer interrupts</title>
3103 This is the case when the hardware doesn't generate interrupts
3104 at the period boundary but do timer-interrupts at the fixed
3105 timer rate (e.g. es1968 or ymfpci drivers).
3106 In this case, you need to check the current hardware
3107 position and accumulates the processed sample length at each
3108 interrupt. When the accumulated size overcomes the period
3110 <function>snd_pcm_period_elapsed()</function> and reset the
3115 A typical coding would be like the following.
3118 <title>Interrupt Handler Case #2</title>
3121 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3122 struct pt_regs *regs)
3124 mychip_t *chip = dev_id;
3125 spin_lock(&chip->lock);
3127 if (pcm_irq_invoked(chip)) {
3128 unsigned int last_ptr, size;
3129 /* get the current hardware pointer (in frames) */
3130 last_ptr = get_hw_ptr(chip);
3131 /* calculate the processed frames since the
3134 if (last_ptr < chip->last_ptr)
3135 size = runtime->buffer_size + last_ptr
3138 size = last_ptr - chip->last_ptr;
3139 /* remember the last updated point */
3140 chip->last_ptr = last_ptr;
3141 /* accumulate the size */
3143 /* over the period boundary? */
3144 if (chip->size >= runtime->period_size) {
3145 /* reset the accumulator */
3146 chip->size %= runtime->period_size;
3148 spin_unlock(&chip->lock);
3149 snd_pcm_period_elapsed(substream);
3150 spin_lock(&chip->lock);
3152 // acknowledge the interrupt if necessary
3155 spin_unlock(&chip->lock);
3164 <section id="pcm-interface-interrupt-handler-both">
3165 <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3167 In both cases, even if more than one period are elapsed, you
3169 <function>snd_pcm_period_elapsed()</function> many times. Call
3170 only once. And the pcm layer will check the current hardware
3171 pointer and update to the latest status.
3176 <section id="pcm-interface-atomicity">
3177 <title>Atomicity</title>
3179 One of the most important (and thus difficult to debug) problem
3180 on the kernel programming is the race condition.
3181 On linux kernel, usually it's solved via spin-locks or
3182 semaphores. In general, if the race condition may
3183 happen in the interrupt handler, it's handled as atomic, and you
3184 have to use spinlock for protecting the critical session. If it
3185 never happens in the interrupt and it may take relatively long
3186 time, you should use semaphore.
3190 As already seen, some pcm callbacks are atomic and some are
3191 not. For example, <parameter>hw_params</parameter> callback is
3192 non-atomic, while <parameter>trigger</parameter> callback is
3193 atomic. This means, the latter is called already in a spinlock
3194 held by the PCM middle layer. Please take this atomicity into
3195 account when you use a spinlock or a semaphore in the callbacks.
3199 In the atomic callbacks, you cannot use functions which may call
3200 <function>schedule</function> or go to
3201 <function>sleep</function>. The semaphore and mutex do sleep,
3202 and hence they cannot be used inside the atomic callbacks
3203 (e.g. <parameter>trigger</parameter> callback).
3204 For taking a certain delay in such a callback, please use
3205 <function>udelay()</function> or <function>mdelay()</function>.
3209 <section id="pcm-interface-constraints">
3210 <title>Constraints</title>
3212 If your chip supports unconventional sample rates, or only the
3213 limited samples, you need to set a constraint for the
3218 For example, in order to restrict the sample rates in the some
3219 supported values, use
3220 <function>snd_pcm_hw_constraint_list()</function>.
3221 You need to call this function in the open callback.
3224 <title>Example of Hardware Constraints</title>
3227 static unsigned int rates[] =
3228 {4000, 10000, 22050, 44100};
3229 static snd_pcm_hw_constraint_list_t constraints_rates = {
3230 .count = ARRAY_SIZE(rates),
3235 static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3239 err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3240 SNDRV_PCM_HW_PARAM_RATE,
3241 &constraints_rates);
3252 There are many different constraints.
3253 Look in <filename>sound/asound.h</filename> for a complete list.
3254 You can even define your own constraint rules.
3255 For example, let's suppose my_chip can manage a substream of 1 channel
3256 if and only if the format is S16_LE, otherwise it supports any format
3257 specified in the <type>snd_pcm_hardware_t</type> stucture (or in any
3258 other constraint_list). You can build a rule like this:
3261 <title>Example of Hardware Constraints for Channels</title>
3264 static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3265 snd_pcm_hw_rule_t *rule)
3267 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3268 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3271 snd_mask_any(&fmt); /* Init the struct */
3273 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3274 return snd_mask_refine(f, &fmt);
3284 Then you need to call this function to add your rule:
3289 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3290 hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3298 The rule function is called when an application sets the number of
3299 channels. But an application can set the format before the number of
3300 channels. Thus you also need to define the inverse rule:
3303 <title>Example of Hardware Constraints for Channels</title>
3306 static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3307 snd_pcm_hw_rule_t *rule)
3309 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3310 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3313 snd_interval_any(&ch);
3314 if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3315 ch.min = ch.max = 1;
3317 return snd_interval_refine(c, &ch);
3327 ...and in the open callback:
3331 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3332 hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3340 I won't explain more details here, rather I
3341 would like to say, <quote>Luke, use the source.</quote>
3348 <!-- ****************************************************** -->
3349 <!-- Control Interface -->
3350 <!-- ****************************************************** -->
3351 <chapter id="control-interface">
3352 <title>Control Interface</title>
3354 <section id="control-interface-general">
3355 <title>General</title>
3357 The control interface is used widely for many switches,
3358 sliders, etc. which are accessed from the user-space. Its most
3359 important use is the mixer interface. In other words, on ALSA
3360 0.9.x, all the mixer stuff is implemented on the control kernel
3361 API (while there was an independent mixer kernel API on 0.5.x).
3365 ALSA has a well-defined AC97 control module. If your chip
3366 supports only the AC97 and nothing else, you can skip this
3371 The control API is defined in
3372 <filename><sound/control.h></filename>.
3373 Include this file if you add your own controls.
3377 <section id="control-interface-definition">
3378 <title>Definition of Controls</title>
3380 For creating a new control, you need to define the three
3381 callbacks: <structfield>info</structfield>,
3382 <structfield>get</structfield> and
3383 <structfield>put</structfield>. Then, define a
3384 <type>snd_kcontrol_new_t</type> record, such as:
3387 <title>Definition of a Control</title>
3390 static snd_kcontrol_new_t my_control __devinitdata = {
3391 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3392 .name = "PCM Playback Switch",
3394 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3395 .private_values = 0xffff,
3396 .info = my_control_info,
3397 .get = my_control_get,
3398 .put = my_control_put
3406 Most likely the control is created via
3407 <function>snd_ctl_new1()</function>, and in such a case, you can
3408 add <parameter>__devinitdata</parameter> prefix to the
3409 definition like above.
3413 The <structfield>iface</structfield> field specifies the type of
3415 <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3416 <constant>MIXER</constant>, <constant>PCM</constant>,
3417 <constant>CARD</constant>, etc.
3421 The <structfield>name</structfield> is the name identifier
3422 string. On ALSA 0.9.x, the control name is very important,
3423 because its role is classified from its name. There are
3424 pre-defined standard control names. The details are described in
3426 <link linkend="control-interface-control-names"><citetitle>
3427 Control Names</citetitle></link>.
3431 The <structfield>index</structfield> field holds the index number
3432 of this control. If there are several different controls with
3433 the same name, they can be distinguished by the index
3434 number. This is the case when
3435 several codecs exist on the card. If the index is zero, you can
3436 omit the definition above.
3440 The <structfield>access</structfield> field contains the access
3441 type of this control. Give the combination of bit masks,
3442 <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.
3443 The detailed will be explained in the subsection
3444 <link linkend="control-interface-access-flags"><citetitle>
3445 Access Flags</citetitle></link>.
3449 The <structfield>private_values</structfield> field contains
3450 an arbitrary long integer value for this record. When using
3451 generic <structfield>info</structfield>,
3452 <structfield>get</structfield> and
3453 <structfield>put</structfield> callbacks, you can pass a value
3454 through this field. If several small numbers are necessary, you can
3455 combine them in bitwise. Or, it's possible to give a pointer
3456 (casted to unsigned long) of some record to this field, too.
3461 <link linkend="control-interface-callbacks"><citetitle>
3462 callback functions</citetitle></link>.
3466 <section id="control-interface-control-names">
3467 <title>Control Names</title>
3469 There are some standards for defining the control names. A
3470 control is usually defined from the three parts as
3471 <quote>SOURCE DIRECTION FUNCTION</quote>.
3475 The first, <constant>SOURCE</constant>, specifies the source
3476 of the control, and is a string such as <quote>Master</quote>,
3477 <quote>PCM</quote>, <quote>CD</quote> or
3478 <quote>Line</quote>. There are many pre-defined sources.
3482 The second, <constant>DIRECTION</constant>, is one of the
3483 following strings according to the direction of the control:
3484 <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass
3485 Playback</quote> and <quote>Bypass Capture</quote>. Or, it can
3486 be omitted, meaning both playback and capture directions.
3490 The third, <constant>FUNCTION</constant>, is one of the
3491 following strings according to the function of the control:
3492 <quote>Switch</quote>, <quote>Volume</quote> and
3493 <quote>Route</quote>.
3497 The example of control names are, thus, <quote>Master Capture
3498 Switch</quote> or <quote>PCM Playback Volume</quote>.
3502 There are some exceptions:
3505 <section id="control-interface-control-names-global">
3506 <title>Global capture and playback</title>
3508 <quote>Capture Source</quote>, <quote>Capture Switch</quote>
3509 and <quote>Capture Volume</quote> are used for the global
3510 capture (input) source, switch and volume. Similarly,
3511 <quote>Playback Switch</quote> and <quote>Playback
3512 Volume</quote> are used for the global output gain switch and
3517 <section id="control-interface-control-names-tone">
3518 <title>Tone-controls</title>
3520 tone-control switch and volumes are specified like
3521 <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -
3522 Switch</quote>, <quote>Tone Control - Bass</quote>,
3523 <quote>Tone Control - Center</quote>.
3527 <section id="control-interface-control-names-3d">
3528 <title>3D controls</title>
3530 3D-control switches and volumes are specified like <quote>3D
3531 Control - XXX</quote>, e.g. <quote>3D Control -
3532 Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D
3533 Control - Space</quote>.
3537 <section id="control-interface-control-names-mic">
3538 <title>Mic boost</title>
3540 Mic-boost switch is set as <quote>Mic Boost</quote> or
3541 <quote>Mic Boost (6dB)</quote>.
3545 More precise information can be found in
3546 <filename>Documentation/sound/alsa/ControlNames.txt</filename>.
3551 <section id="control-interface-access-flags">
3552 <title>Access Flags</title>
3555 The access flag is the bit-flags which specifies the access type
3556 of the given control. The default access type is
3557 <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>,
3558 which means both read and write are allowed to this control.
3559 When the access flag is omitted (i.e. = 0), it is
3560 regarded as <constant>READWRITE</constant> access as default.
3564 When the control is read-only, pass
3565 <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.
3566 In this case, you don't have to define
3567 <structfield>put</structfield> callback.
3568 Similarly, when the control is write-only (although it's a rare
3569 case), you can use <constant>WRITE</constant> flag instead, and
3570 you don't need <structfield>get</structfield> callback.
3574 If the control value changes frequently (e.g. the VU meter),
3575 <constant>VOLATILE</constant> flag should be given. This means
3576 that the control may be changed without
3577 <link linkend="control-interface-change-notification"><citetitle>
3578 notification</citetitle></link>. Applications should poll such
3579 a control constantly.
3583 When the control is inactive, set
3584 <constant>INACTIVE</constant> flag, too.
3585 There are <constant>LOCK</constant> and
3586 <constant>OWNER</constant> flags for changing the write
3592 <section id="control-interface-callbacks">
3593 <title>Callbacks</title>
3595 <section id="control-interface-callbacks-info">
3596 <title>info callback</title>
3598 The <structfield>info</structfield> callback is used to get
3599 the detailed information of this control. This must store the
3600 values of the given <type>snd_ctl_elem_info_t</type>
3601 object. For example, for a boolean control with a single
3605 <title>Example of info callback</title>
3608 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3609 snd_ctl_elem_info_t *uinfo)
3611 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3613 uinfo->value.integer.min = 0;
3614 uinfo->value.integer.max = 1;
3623 The <structfield>type</structfield> field specifies the type
3624 of the control. There are <constant>BOOLEAN</constant>,
3625 <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,
3626 <constant>BYTES</constant>, <constant>IEC958</constant> and
3627 <constant>INTEGER64</constant>. The
3628 <structfield>count</structfield> field specifies the
3629 number of elements in this control. For example, a stereo
3630 volume would have count = 2. The
3631 <structfield>value</structfield> field is a union, and
3632 the values stored are depending on the type. The boolean and
3633 integer are identical.
3637 The enumerated type is a bit different from others. You'll
3638 need to set the string for the currently given item index.
3643 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3644 snd_ctl_elem_info_t *uinfo)
3646 static char *texts[4] = {
3647 "First", "Second", "Third", "Fourth"
3649 uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3651 uinfo->value.enumerated.items = 4;
3652 if (uinfo->value.enumerated.item > 3)
3653 uinfo->value.enumerated.item = 3;
3654 strcpy(uinfo->value.enumerated.name,
3655 texts[uinfo->value.enumerated.item]);
3664 <section id="control-interface-callbacks-get">
3665 <title>get callback</title>
3668 This callback is used to read the current value of the
3669 control and to return to the user-space.
3676 <title>Example of get callback</title>
3679 static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3680 snd_ctl_elem_value_t *ucontrol)
3682 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3683 ucontrol->value.integer.value[0] = get_some_value(chip);
3692 Here, the chip instance is retrieved via
3693 <function>snd_kcontrol_chip()</function> macro. This macro
3694 converts from kcontrol->private_data to the type defined by
3695 <type>chip_t</type>. The
3696 kcontrol->private_data field is
3697 given as the argument of <function>snd_ctl_new()</function>
3698 (see the later subsection
3699 <link linkend="control-interface-constructor"><citetitle>Constructor</citetitle></link>).
3703 The <structfield>value</structfield> field is depending on
3704 the type of control as well as on info callback. For example,
3705 the sb driver uses this field to store the register offset,
3706 the bit-shift and the bit-mask. The
3707 <structfield>private_value</structfield> is set like
3711 .private_value = reg | (shift << 16) | (mask << 24)
3715 and is retrieved in callbacks like
3719 static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3720 snd_ctl_elem_value_t *ucontrol)
3722 int reg = kcontrol->private_value & 0xff;
3723 int shift = (kcontrol->private_value >> 16) & 0xff;
3724 int mask = (kcontrol->private_value >> 24) & 0xff;
3733 In <structfield>get</structfield> callback, you have to fill all the elements if the
3734 control has more than one elements,
3735 i.e. <structfield>count</structfield> > 1.
3736 In the example above, we filled only one element
3737 (<structfield>value.integer.value[0]</structfield>) since it's
3738 assumed as <structfield>count</structfield> = 1.
3742 <section id="control-interface-callbacks-put">
3743 <title>put callback</title>
3746 This callback is used to write a value from the user-space.
3753 <title>Example of put callback</title>
3756 static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3757 snd_ctl_elem_value_t *ucontrol)
3759 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3761 if (chip->current_value !=
3762 ucontrol->value.integer.value[0]) {
3763 change_current_value(chip,
3764 ucontrol->value.integer.value[0]);
3773 As seen above, you have to return 1 if the value is
3774 changed. If the value is not changed, return 0 instead.
3775 If any fatal error happens, return a negative error code as
3780 Like <structfield>get</structfield> callback,
3781 when the control has more than one elements,
3782 all elemehts must be evaluated in this callback, too.
3786 <section id="control-interface-callbacks-all">
3787 <title>Callbacks are not atomic</title>
3789 All these three callbacks are basically not atomic.
3794 <section id="control-interface-constructor">
3795 <title>Constructor</title>
3797 When everything is ready, finally we can create a new
3798 control. For creating a control, there are two functions to be
3799 called, <function>snd_ctl_new1()</function> and
3800 <function>snd_ctl_add()</function>.
3804 In the simplest way, you can do like this:
3809 if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
3815 where <parameter>my_control</parameter> is the
3816 <type>snd_kcontrol_new_t</type> object defined above, and chip
3817 is the object pointer to be passed to
3818 kcontrol->private_data
3819 which can be referred in callbacks.
3823 <function>snd_ctl_new1()</function> allocates a new
3824 <type>snd_kcontrol_t</type> instance (that's why the definition
3825 of <parameter>my_control</parameter> can be with
3826 <parameter>__devinitdata</parameter>
3827 prefix), and <function>snd_ctl_add</function> assigns the given
3828 control component to the card.
3832 <section id="control-interface-change-notification">
3833 <title>Change Notification</title>
3835 If you need to change and update a control in the interrupt
3836 routine, you can call <function>snd_ctl_notify()</function>. For
3842 snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
3847 This function takes the card pointer, the event-mask, and the
3848 control id pointer for the notification. The event-mask
3849 specifies the types of notification, for example, in the above
3850 example, the change of control values is notified.
3851 The id pointer is the pointer of <type>snd_ctl_elem_id_t</type>
3853 You can find some examples in <filename>es1938.c</filename> or
3854 <filename>es1968.c</filename> for hardware volume interrupts.
3861 <!-- ****************************************************** -->
3862 <!-- API for AC97 Codec -->
3863 <!-- ****************************************************** -->
3864 <chapter id="api-ac97">
3865 <title>API for AC97 Codec</title>
3868 <title>General</title>
3870 The ALSA AC97 codec layer is a well-defined one, and you don't
3871 have to write many codes to control it. Only low-level control
3872 routines are necessary. The AC97 codec API is defined in
3873 <filename><sound/ac97_codec.h></filename>.
3877 <section id="api-ac97-example">
3878 <title>Full Code Example</title>
3881 <title>Example of AC97 Interface</title>
3890 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3893 mychip_t *chip = ac97->private_data;
3895 // read a register value here from the codec
3896 return the_register_value;
3899 static void snd_mychip_ac97_write(ac97_t *ac97,
3900 unsigned short reg, unsigned short val)
3902 mychip_t *chip = ac97->private_data;
3904 // write the given register value to the codec
3907 static int snd_mychip_ac97(mychip_t *chip)
3910 ac97_template_t ac97;
3912 static ac97_bus_ops_t ops = {
3913 .write = snd_mychip_ac97_write,
3914 .read = snd_mychip_ac97_read,
3917 if ((err = snd_ac97_bus(chip->card, 0, &ops, NULL, &bus)) < 0)
3919 memset(&ac97, 0, sizeof(ac97));
3920 ac97.private_data = chip;
3921 return snd_ac97_mixer(bus, &ac97, &chip->ac97);
3930 <section id="api-ac97-constructor">
3931 <title>Constructor</title>
3933 For creating an ac97 instance, first call <function>snd_ac97_bus</function>
3934 with an <type>ac97_bus_ops_t</type> record with callback functions.
3940 static ac97_bus_ops_t ops = {
3941 .write = snd_mychip_ac97_write,
3942 .read = snd_mychip_ac97_read,
3945 snd_ac97_bus(card, 0, &ops, NULL, &pbus);
3950 The bus record is shared among all belonging ac97 instances.
3954 And then call <function>snd_ac97_mixer()</function> with an <type>ac97_template_t</type>
3955 record together with the bus pointer created above.
3960 ac97_template_t ac97;
3963 memset(&ac97, 0, sizeof(ac97));
3964 ac97.private_data = chip;
3965 snd_ac97_mixer(bus, &ac97, &chip->ac97);
3970 where chip->ac97 is the pointer of a newly created
3971 <type>ac97_t</type> instance.
3972 In this case, the chip pointer is set as the private data, so that
3973 the read/write callback functions can refer to this chip instance.
3974 This instance is not necessarily stored in the chip
3975 record. When you need to change the register values from the
3976 driver, or need the suspend/resume of ac97 codecs, keep this
3977 pointer to pass to the corresponding functions.
3981 <section id="api-ac97-callbacks">
3982 <title>Callbacks</title>
3984 The standard callbacks are <structfield>read</structfield> and
3985 <structfield>write</structfield>. Obviously they
3986 correspond to the functions for read and write accesses to the
3987 hardware low-level codes.
3991 The <structfield>read</structfield> callback returns the
3992 register value specified in the argument.
3997 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4000 mychip_t *chip = ac97->private_data;
4002 return the_register_value;
4008 Here, the chip can be cast from ac97->private_data.
4012 Meanwhile, the <structfield>write</structfield> callback is
4013 used to set the register value.
4018 static void snd_mychip_ac97_write(ac97_t *ac97,
4019 unsigned short reg, unsigned short val)
4026 These callbacks are non-atomic like the callbacks of control API.
4030 There are also other callbacks:
4031 <structfield>reset</structfield>,
4032 <structfield>wait</structfield> and
4033 <structfield>init</structfield>.
4037 The <structfield>reset</structfield> callback is used to reset
4038 the codec. If the chip requires a special way of reset, you can
4039 define this callback.
4043 The <structfield>wait</structfield> callback is used for a
4044 certain wait at the standard initialization of the codec. If the
4045 chip requires the extra wait-time, define this callback.
4049 The <structfield>init</structfield> callback is used for
4050 additional initialization of the codec.
4054 <section id="api-ac97-updating-registers">
4055 <title>Updating Registers in The Driver</title>
4057 If you need to access to the codec from the driver, you can
4058 call the following functions:
4059 <function>snd_ac97_write()</function>,
4060 <function>snd_ac97_read()</function>,
4061 <function>snd_ac97_update()</function> and
4062 <function>snd_ac97_update_bits()</function>.
4066 Both <function>snd_ac97_write()</function> and
4067 <function>snd_ac97_update()</function> functions are used to
4068 set a value to the given register
4069 (<constant>AC97_XXX</constant>). The different between them is
4070 that <function>snd_ac97_update()</function> doesn't write a
4071 value if the given value has been already set, while
4072 <function>snd_ac97_write()</function> always rewrites the
4078 snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4079 snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4086 <function>snd_ac97_read()</function> is used to read the value
4087 of the given register. For example,
4092 value = snd_ac97_read(ac97, AC97_MASTER);
4099 <function>snd_ac97_update_bits()</function> is used to update
4100 some bits of the given register.
4105 snd_ac97_update_bits(ac97, reg, mask, value);
4112 Also, there is a function to change the sample rate (of a
4113 certain register such as
4114 <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA or
4115 DRA is supported by the codec:
4116 <function>snd_ac97_set_rate()</function>.
4121 snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
4128 The following registers are available for setting the rate:
4129 <constant>AC97_PCM_MIC_ADC_RATE</constant>,
4130 <constant>AC97_PCM_FRONT_DAC_RATE</constant>,
4131 <constant>AC97_PCM_LR_ADC_RATE</constant>,
4132 <constant>AC97_SPDIF</constant>. When the
4133 <constant>AC97_SPDIF</constant> is specified, the register is
4134 not really changed but the corresponding IEC958 status bits will
4139 <section id="api-ac97-clock-adjustment">
4140 <title>Clock Adjustment</title>
4142 On some chip, the clock of the codec isn't 48000 but using a
4143 PCI clock (to save a quartz!). In this case, change the field
4144 bus->clock to the corresponding
4145 value. For example, intel8x0
4146 and es1968 drivers have the auto-measurement function of the
4151 <section id="api-ac97-proc-files">
4152 <title>Proc Files</title>
4154 The ALSA AC97 interface will create a proc file such as
4155 <filename>/proc/asound/card0/ac97#0</filename> and
4156 <filename>ac97#0regs</filename>. You can refer to these files to
4157 see the current status and registers of the codec.
4161 <section id="api-ac97-multiple-codecs">
4162 <title>Multiple Codecs</title>
4164 When there are several codecs on the same card, you need to
4165 call <function>snd_ac97_new()</function> multiple times with
4166 ac97.num=1 or greater. The <structfield>num</structfield> field
4172 If you have set up multiple codecs, you need to either write
4173 different callbacks for each codec or check
4182 <!-- ****************************************************** -->
4183 <!-- MIDI (MPU401-UART) Interface -->
4184 <!-- ****************************************************** -->
4185 <chapter id="midi-interface">
4186 <title>MIDI (MPU401-UART) Interface</title>
4188 <section id="midi-interface-general">
4189 <title>General</title>
4191 Many soundcards have built-in MIDI (MPU401-UART)
4192 interfaces. When the soundcard supports the standard MPU401-UART
4193 interface, most likely you can use the ALSA MPU401-UART API. The
4194 MPU401-UART API is defined in
4195 <filename><sound/mpu401.h></filename>.
4199 Some soundchips have similar but a little bit different
4200 implementation of mpu401 stuff. For example, emu10k1 has its own
4205 In this document, I won't explain the rawmidi interface API,
4206 which is the basis of MPU401-UART implementation.
4210 For details, please check the source,
4211 <filename>core/rawmidi.c</filename>, and examples such as
4212 <filename>drivers/mpu401/mpu401_uart.c</filename> or
4213 <filename>usb/usbmidi.c</filename>.
4217 <section id="midi-interface-constructor">
4218 <title>Constructor</title>
4220 For creating a rawmidi object, call
4221 <function>snd_mpu401_uart_new()</function>.
4226 snd_rawmidi_t *rmidi;
4227 snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4228 irq, irq_flags, &rmidi);
4235 The first argument is the card pointer, and the second is the
4236 index of this component. You can create up to 8 rawmidi
4241 The third argument is the type of the hardware,
4242 <constant>MPU401_HW_XXX</constant>. If it's not a special one,
4243 you can use <constant>MPU401_HW_MPU401</constant>.
4247 The 4th argument is the i/o port address. Many
4248 backward-compatible MPU401 has an i/o port such as 0x330. Or, it
4249 might be a part of its own PCI i/o region. It depends on the
4254 When the i/o port address above is a part of the PCI i/o
4255 region, the MPU401 i/o port might have been already allocated
4256 (reserved) by the driver itself. In such a case, pass non-zero
4258 (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4260 the mpu401-uart layer will allocate the i/o ports by itself.
4264 Usually, the port address corresponds to the command port and
4265 port + 1 corresponds to the data port. If not, you may change
4266 the <structfield>cport</structfield> field of
4267 <type>mpu401_t</type> manually
4268 afterward. However, <type>mpu401_t</type> pointer is not
4269 returned explicitly by
4270 <function>snd_mpu401_uart_new()</function>. You need to cast
4271 rmidi->private_data to
4272 <type>mpu401_t</type> explicitly,
4278 mpu = rmidi->private_data;
4283 and reset the cport as you like:
4288 mpu->cport = my_own_control_port;
4295 The 6th argument specifies the irq number for UART. If the irq
4296 is already allocated, pass 0 to the 7th argument
4297 (<parameter>irq_flags</parameter>). Otherwise, pass the flags
4299 (<constant>SA_XXX</constant> bits) to it, and the irq will be
4300 reserved by the mpu401-uart layer. If the card doesn't generates
4301 UART interrupts, pass -1 as the irq number. Then a timer
4302 interrupt will be invoked for polling.
4306 <section id="midi-interface-interrupt-handler">
4307 <title>Interrupt Handler</title>
4309 When the interrupt is allocated in
4310 <function>snd_mpu401_uart_new()</function>, the private
4311 interrupt handler is used, hence you don't have to do nothing
4312 else than creating the mpu401 stuff. Otherwise, you have to call
4313 <function>snd_mpu401_uart_interrupt()</function> explicitly when
4314 a UART interrupt is invoked and checked in your own interrupt
4319 In this case, you need to pass the private_data of the
4320 returned rawmidi object from
4321 <function>snd_mpu401_uart_new()</function> as the second
4322 argument of <function>snd_mpu401_uart_interrupt()</function>.
4327 snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4337 <!-- ****************************************************** -->
4338 <!-- Miscellaneous Devices -->
4339 <!-- ****************************************************** -->
4340 <chapter id="misc-devices">
4341 <title>Miscellaneous Devices</title>
4343 <section id="misc-devices-opl3">
4344 <title>FM OPL3</title>
4346 The FM OPL3 is still used on many chips (mainly for backward
4347 compatibility). ALSA has a nice OPL3 FM control layer, too. The
4348 OPL3 API is defined in
4349 <filename><sound/opl3.h></filename>.
4353 FM registers can be directly accessed through direct-FM API,
4354 defined in <filename><sound/asound_fm.h></filename>. In
4355 ALSA native mode, FM registers are accessed through
4356 Hardware-Dependant Device direct-FM extension API, whereas in
4357 OSS compatible mode, FM registers can be accessed with OSS
4358 direct-FM compatible API on <filename>/dev/dmfmX</filename> device.
4362 For creating the OPL3 component, you have two functions to
4363 call. The first one is a constructor for <type>opl3_t</type>
4370 snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
4378 The first argument is the card pointer, the second one is the
4379 left port address, and the third is the right port address. In
4380 most cases, the right port is placed at the left port + 2.
4384 The fourth argument is the hardware type.
4388 When the left and right ports have been already allocated by
4389 the card driver, pass non-zero to the fifth argument
4390 (<parameter>integrated</parameter>). Otherwise, opl3 module will
4391 allocate the specified ports by itself.
4395 When the accessing to the hardware requires special method
4396 instead of the standard I/O access, you can create opl3 instance
4397 separately with <function>snd_opl3_new()</function>.
4403 snd_opl3_new(card, OPL3_HW_OPL3_XXX, &opl3);
4410 Then set <structfield>command</structfield>,
4411 <structfield>private_data</structfield> and
4412 <structfield>private_free</structfield> for the private
4413 access function, the private data and the destructor.
4414 The l_port and r_port are not necessarily set. Only the
4415 command must be set properly. You can retrieve the data
4416 from opl3->private_data field.
4420 After creating the opl3 instance via <function>snd_opl3_new()</function>,
4421 call <function>snd_opl3_init()</function> to initialize the chip to the
4422 proper state. Note that <function>snd_opl3_create()</function> always
4423 calls it internally.
4427 If the opl3 instance is created successfully, then create a
4428 hwdep device for this opl3.
4433 snd_hwdep_t *opl3hwdep;
4434 snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4441 The first argument is the <type>opl3_t</type> instance you
4442 created, and the second is the index number, usually 0.
4446 The third argument is the index-offset for the sequencer
4447 client assigned to the OPL3 port. When there is an MPU401-UART,
4448 give 1 for here (UART always takes 0).
4452 <section id="misc-devices-hardware-dependent">
4453 <title>Hardware-Dependent Devices</title>
4455 Some chips need the access from the user-space for special
4456 controls or for loading the micro code. In such a case, you can
4457 create a hwdep (hardware-dependent) device. The hwdep API is
4458 defined in <filename><sound/hwdep.h></filename>. You can
4459 find examples in opl3 driver or
4460 <filename>isa/sb/sb16_csp.c</filename>.
4464 Creation of the <type>hwdep</type> instance is done via
4465 <function>snd_hwdep_new()</function>.
4471 snd_hwdep_new(card, "My HWDEP", 0, &hw);
4476 where the third argument is the index number.
4480 You can then pass any pointer value to the
4481 <parameter>private_data</parameter>.
4482 If you assign a private data, you should define the
4483 destructor, too. The destructor function is set to
4484 <structfield>private_free</structfield> field.
4489 mydata_t *p = kmalloc(sizeof(*p), GFP_KERNEL);
4490 hw->private_data = p;
4491 hw->private_free = mydata_free;
4496 and the implementation of destructor would be:
4501 static void mydata_free(snd_hwdep_t *hw)
4503 mydata_t *p = hw->private_data;
4512 The arbitrary file operations can be defined for this
4513 instance. The file operators are defined in
4514 <parameter>ops</parameter> table. For example, assume that
4515 this chip needs an ioctl.
4520 hw->ops.open = mydata_open;
4521 hw->ops.ioctl = mydata_ioctl;
4522 hw->ops.release = mydata_release;
4527 And implement the callback functions as you like.
4531 <section id="misc-devices-IEC958">
4532 <title>IEC958 (S/PDIF)</title>
4534 Usually the controls for IEC958 devices are implemented via
4535 control interface. There is a macro to compose a name string for
4536 IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>
4537 defined in <filename><include/asound.h></filename>.
4541 There are some standard controls for IEC958 status bits. These
4542 controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,
4543 and the size of element is fixed as 4 bytes array
4544 (value.iec958.status[x]). For <structfield>info</structfield>
4545 callback, you don't specify
4546 the value field for this type (the count field must be set,
4551 <quote>IEC958 Playback Con Mask</quote> is used to return the
4552 bit-mask for the IEC958 status bits of consumer mode. Similarly,
4553 <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for
4554 professional mode. They are read-only controls, and are defined
4555 as MIXER controls (iface =
4556 <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>).
4560 Meanwhile, <quote>IEC958 Playback Default</quote> control is
4561 defined for getting and setting the current default IEC958
4562 bits. Note that this one is usually defined as a PCM control
4563 (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),
4564 although in some places it's defined as a MIXER control.
4568 In addition, you can define the control switches to
4569 enable/disable or to set the raw bit mode. The implementation
4570 will depend on the chip, but the control should be named as
4571 <quote>IEC958 xxx</quote>, preferably using
4572 <function>SNDRV_CTL_NAME_IEC958()</function> macro.
4576 You can find several cases, for example,
4577 <filename>pci/emu10k1</filename>,
4578 <filename>pci/ice1712</filename>, or
4579 <filename>pci/cmipci.c</filename>.
4586 <!-- ****************************************************** -->
4587 <!-- Buffer and Memory Management -->
4588 <!-- ****************************************************** -->
4589 <chapter id="buffer-and-memory">
4590 <title>Buffer and Memory Management</title>
4592 <section id="buffer-and-memory-buffer-types">
4593 <title>Buffer Types</title>
4595 ALSA provides several different buffer allocation functions
4596 depending on the bus and the architecture. All these have a
4597 consistent API. The allocation of physically-contiguous pages is
4599 <function>snd_malloc_xxx_pages()</function> function, where xxx
4604 The allocation of pages with fallback is
4605 <function>snd_malloc_xxx_pages_fallback()</function>. This
4606 function tries to allocate the specified pages but if the pages
4607 are not available, it tries to reduce the page sizes until the
4608 enough space is found.
4612 For releasing the space, call
4613 <function>snd_free_xxx_pages()</function> function.
4617 Usually, ALSA drivers try to allocate and reserve
4618 a large contiguous physical space
4619 at the time the module is loaded for the later use.
4620 This is called <quote>pre-allocation</quote>.
4621 As already written, you can call the following function at the
4622 construction of pcm instance (in the case of PCI bus).
4627 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
4628 snd_dma_pci_data(pci), size, max);
4633 where <parameter>size</parameter> is the byte size to be
4634 pre-allocated and the <parameter>max</parameter> is the maximal
4635 size to be changed via <filename>prealloc</filename> proc file.
4636 The allocator will try to get as the large area as possible
4637 within the given size.
4641 The second argument (type) and the third argument (device pointer)
4642 are dependent on the bus.
4643 In the case of ISA bus, pass <function>snd_dma_isa_data()</function>
4644 as the third argument with <constant>SNDRV_DMA_TYPE_DEV</constant> type.
4645 For the continuous buffer unrelated to the bus can be pre-allocated
4646 with <constant>SNDRV_DMA_TYPE_CONTINUOUS</constant> type and the
4647 <function>snd_dma_continuous_data(GFP_KERNEL)</function> device pointer,
4648 whereh <constant>GFP_KERNEL</constant> is the kernel allocation flag to
4649 use. For the SBUS, <constant>SNDRV_DMA_TYPE_SBUS</constant> and
4650 <function>snd_dma_sbus_data(sbus_dev)</function> are used instead.
4651 For the PCI scatter-gather buffers, use
4652 <constant>SNDRV_DMA_TYPE_DEV_SG</constant> with
4653 <function>snd_dma_pci_data(pci)</function>
4655 <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers
4656 </citetitle></link>).
4660 Once when the buffer is pre-allocated, you can use the
4661 allocator in the <structfield>hw_params</structfield> callback
4666 snd_pcm_lib_malloc_pages(substream, size);
4671 Note that you have to pre-allocate to use this function.
4675 <section id="buffer-and-memory-external-hardware">
4676 <title>External Hardware Buffers</title>
4678 Some chips have their own hardware buffers and the DMA
4679 transfer from the host memory is not available. In such a case,
4680 you need to either 1) copy/set the audio data directly to the
4681 external hardware buffer, or 2) make an intermediate buffer and
4682 copy/set the data from it to the external hardware buffer in
4683 interrupts (or in tasklets, preferably).
4687 The first case works fine if the external hardware buffer is enough
4688 large. This method doesn't need any extra buffers and thus is
4689 more effective. You need to define the
4690 <structfield>copy</structfield> and
4691 <structfield>silence</structfield> callbacks for
4692 the data transfer. However, there is a drawback: it cannot
4693 be mmapped. The examples are GUS's GF1 PCM or emu8000's
4698 The second case allows the mmap of the buffer, although you have
4699 to handle an interrupt or a tasklet for transferring the data
4700 from the intermediate buffer to the hardware buffer. You can find an
4701 example in vxpocket driver.
4705 Another case is that the chip uses a PCI memory-map
4706 region for the buffer instead of the host memory. In this case,
4707 mmap is available only on certain architectures like intel. In
4708 non-mmap mode, the data cannot be transferred as the normal
4709 way. Thus you need to define <structfield>copy</structfield> and
4710 <structfield>silence</structfield> callbacks as well
4711 as in the cases above. The examples are found in
4712 <filename>rme32.c</filename> and <filename>rme96.c</filename>.
4716 The implementation of <structfield>copy</structfield> and
4717 <structfield>silence</structfield> callbacks depends upon
4718 whether the hardware supports interleaved or non-interleaved
4719 samples. The <structfield>copy</structfield> callback is
4720 defined like below, a bit
4721 differently depending whether the direction is playback or
4727 static int playback_copy(snd_pcm_substream_t *substream, int channel,
4728 snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);
4729 static int capture_copy(snd_pcm_substream_t *substream, int channel,
4730 snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);
4737 In the case of interleaved samples, the second argument
4738 (<parameter>channel</parameter>) is not used. The third argument
4739 (<parameter>pos</parameter>) points the
4740 current position offset in frames.
4744 The meaning of the fourth argument is different between
4745 playback and capture. For playback, it holds the source data
4746 pointer, and for capture, it's the destination data pointer.
4750 The last argument is the number of frames to be copied.
4754 What you have to do in this callback is again different
4755 between playback and capture directions. In the case of
4756 playback, you do: copy the given amount of data
4757 (<parameter>count</parameter>) at the specified pointer
4758 (<parameter>src</parameter>) to the specified offset
4759 (<parameter>pos</parameter>) on the hardware buffer. When
4760 coded like memcpy-like way, the copy would be like:
4765 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4766 frames_to_bytes(runtime, count));
4773 For the capture direction, you do: copy the given amount of
4774 data (<parameter>count</parameter>) at the specified offset
4775 (<parameter>pos</parameter>) on the hardware buffer to the
4776 specified pointer (<parameter>dst</parameter>).
4781 my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4782 frames_to_bytes(runtime, count));
4787 Note that both of the position and the data amount are given
4792 In the case of non-interleaved samples, the implementation
4793 will be a bit more complicated.
4797 You need to check the channel argument, and if it's -1, copy
4798 the whole channels. Otherwise, you have to copy only the
4799 specified channel. Please check
4800 <filename>isa/gus/gus_pcm.c</filename> as an example.
4804 The <structfield>silence</structfield> callback is also
4805 implemented in a similar way.
4810 static int silence(snd_pcm_substream_t *substream, int channel,
4811 snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
4818 The meanings of arguments are identical with the
4819 <structfield>copy</structfield>
4820 callback, although there is no <parameter>src/dst</parameter>
4821 argument. In the case of interleaved samples, the channel
4822 argument has no meaning, as well as on
4823 <structfield>copy</structfield> callback.
4827 The role of <structfield>silence</structfield> callback is to
4828 set the given amount
4829 (<parameter>count</parameter>) of silence data at the
4830 specified offset (<parameter>pos</parameter>) on the hardware
4831 buffer. Suppose that the data format is signed (that is, the
4832 silent-data is 0), and the implementation using a memset-like
4833 function would be like:
4838 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4839 frames_to_bytes(runtime, count));
4846 In the case of non-interleaved samples, again, the
4847 implementation becomes a bit more complicated. See, for example,
4848 <filename>isa/gus/gus_pcm.c</filename>.
4852 <section id="buffer-and-memory-non-contiguous">
4853 <title>Non-Contiguous Buffers</title>
4855 If your hardware supports the page table like emu10k1 or the
4856 buffer descriptors like via82xx, you can use the scatter-gather
4857 (SG) DMA. ALSA provides an interface for handling SG-buffers.
4858 The API is provided in <filename><sound/pcm_sgbuf.h></filename>.
4862 For creating the SG-buffer handler, call
4863 <function>snd_pcm_lib_preallocate_pages()</function> or
4864 <function>snd_pcm_lib_preallocate_pages_for_all()</function>
4865 with <constant>SNDRV_DMA_TYPE_DEV_SG</constant>
4866 in the PCM constructor like other PCI pre-allocator.
4867 You need to pass the <function>snd_dma_pci_data(pci)</function>,
4868 where pci is the struct <structname>pci_dev</structname> pointer
4869 of the chip as well.
4870 The <type>snd_sg_buf_t</type> instance is created as
4871 substream->dma_private. You can cast
4877 snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
4884 Then call <function>snd_pcm_lib_malloc_pages()</function>
4885 in <structfield>hw_params</structfield> callback
4886 as well as in the case of normal PCI buffer.
4887 The SG-buffer handler will allocate the non-contiguous kernel
4888 pages of the given size and map them onto the virtually contiguous
4889 memory. The virtual pointer is addressed in runtime->dma_area.
4890 The physical address (runtime->dma_addr) is set to zero,
4891 because the buffer is physically non-contigous.
4892 The physical address table is set up in sgbuf->table.
4893 You can get the physical address at a certain offset via
4894 <function>snd_pcm_sgbuf_get_addr()</function>.
4898 When a SG-handler is used, you need to set
4899 <function>snd_pcm_sgbuf_ops_page</function> as
4900 the <structfield>page</structfield> callback.
4901 (See <link linkend="pcm-interface-operators-page-callback">
4902 <citetitle>page callback section</citetitle></link>.)
4906 For releasing the data, call
4907 <function>snd_pcm_lib_free_pages()</function> in the
4908 <structfield>hw_free</structfield> callback as usual.
4912 <section id="buffer-and-memory-vmalloced">
4913 <title>Vmalloc'ed Buffers</title>
4915 It's possible to use a buffer allocated via
4916 <function>vmalloc</function>, for example, for an intermediate
4917 buffer. Since the allocated pages are not contiguous, you need
4918 to set the <structfield>page</structfield> callback to obtain
4919 the physical address at every offset.
4923 The implementation of <structfield>page</structfield> callback
4929 #include <linux/vmalloc.h>
4931 /* get the physical page pointer on the given offset */
4932 static struct page *mychip_page(snd_pcm_substream_t *substream,
4933 unsigned long offset)
4935 void *pageptr = substream->runtime->dma_area + offset;
4936 return vmalloc_to_page(pageptr);
4947 <!-- ****************************************************** -->
4948 <!-- Proc Interface -->
4949 <!-- ****************************************************** -->
4950 <chapter id="proc-interface">
4951 <title>Proc Interface</title>
4953 ALSA provides an easy interface for procfs. The proc files are
4954 very useful for debugging. I recommend you set up proc files if
4955 you write a driver and want to get a running status or register
4956 dumps. The API is found in
4957 <filename><sound/info.h></filename>.
4961 For creating a proc file, call
4962 <function>snd_card_proc_new()</function>.
4967 snd_info_entry_t *entry;
4968 int err = snd_card_proc_new(card, "my-file", &entry);
4973 where the second argument specifies the proc-file name to be
4974 created. The above example will create a file
4975 <filename>my-file</filename> under the card directory,
4976 e.g. <filename>/proc/asound/card0/my-file</filename>.
4980 Like other components, the proc entry created via
4981 <function>snd_card_proc_new()</function> will be registered and
4982 released automatically in the card registration and release
4987 When the creation is successful, the function stores a new
4988 instance at the pointer given in the third argument.
4989 It is initialized as a text proc file for read only. For using
4990 this proc file as a read-only text file as it is, set the read
4991 callback with a private data via
4992 <function>snd_info_set_text_ops()</function>.
4997 snd_info_set_text_ops(entry, chip, read_size, my_proc_read);
5002 where the second argument (<parameter>chip</parameter>) is the
5003 private data to be used in the callbacks. The third parameter
5004 specifies the read buffer size and the fourth
5005 (<parameter>my_proc_read</parameter>) is the callback function, which
5011 static void my_proc_read(snd_info_entry_t *entry,
5012 snd_info_buffer_t *buffer);
5020 In the read callback, use <function>snd_iprintf()</function> for
5021 output strings, which works just like normal
5022 <function>printf()</function>. For example,
5027 static void my_proc_read(snd_info_entry_t *entry,
5028 snd_info_buffer_t *buffer)
5030 chip_t *chip = entry->private_data;
5032 snd_iprintf(buffer, "This is my chip!\n");
5033 snd_iprintf(buffer, "Port = %ld\n", chip->port);
5041 The file permission can be changed afterwards. As default, it's
5042 set as read only for all users. If you want to add the write
5043 permission to the user (root as default), set like below:
5048 entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
5053 and set the write buffer size and the callback
5058 entry->c.text.write_size = 256;
5059 entry->c.text.write = my_proc_write;
5066 The buffer size for read is set to 1024 implicitly by
5067 <function>snd_info_set_text_ops()</function>. It should suffice
5068 in most cases (the size will be aligned to
5069 <constant>PAGE_SIZE</constant> anyway), but if you need to handle
5070 very large text files, you can set it explicitly, too.
5075 entry->c.text.read_size = 65536;
5082 For the write callback, you can use
5083 <function>snd_info_get_line()</function> to get a text line, and
5084 <function>snd_info_get_str()</function> to retrieve a string from
5085 the line. Some examples are found in
5086 <filename>core/oss/mixer_oss.c</filename>, core/oss/and
5087 <filename>pcm_oss.c</filename>.
5091 For a raw-data proc-file, set the attributes like the following:
5096 static struct snd_info_entry_ops my_file_io_ops = {
5097 .read = my_file_io_read,
5100 entry->content = SNDRV_INFO_CONTENT_DATA;
5101 entry->private_data = chip;
5102 entry->c.ops = &my_file_io_ops;
5104 entry->mode = S_IFREG | S_IRUGO;
5111 The callback is much more complicated than the text-file
5112 version. You need to use a low-level i/o functions such as
5113 <function>copy_from/to_user()</function> to transfer the
5119 static long my_file_io_read(snd_info_entry_t *entry,
5120 void *file_private_data,
5123 unsigned long count,
5127 if (pos + size > local_max_size)
5128 size = local_max_size - pos;
5129 if (copy_to_user(buf, local_data + pos, size))
5141 <!-- ****************************************************** -->
5142 <!-- Power Management -->
5143 <!-- ****************************************************** -->
5144 <chapter id="power-management">
5145 <title>Power Management</title>
5147 If the chip is supposed to work with with suspend/resume
5148 functions, you need to add the power-management codes to the
5149 driver. The additional codes for the power-management should be
5150 <function>ifdef</function>'ed with
5151 <constant>CONFIG_PM</constant>.
5155 ALSA provides the common power-management layer. Each card driver
5156 needs to have only low-level suspend and resume callbacks.
5162 static int snd_my_suspend(snd_card_t *card, unsigned int state)
5164 .... // do things for suspsend
5167 static int snd_my_resume(snd_card_t *card, unsigned int state)
5169 .... // do things for suspsend
5179 The scheme of the real suspend job is as following.
5182 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5183 <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>
5184 <listitem><para>Save the register values if necessary.</para></listitem>
5185 <listitem><para>Stop the hardware if necessary.</para></listitem>
5186 <listitem><para>Disable the PCI device by calling <function>pci_disable_device()</function>.</para></listitem>
5191 A typical code would be like:
5196 static int mychip_suspend(snd_card_t *card, unsigned int state)
5199 mychip_t *chip = card->pm_private_data;
5201 snd_pcm_suspend_all(chip->pcm);
5203 snd_mychip_save_registers(chip);
5205 snd_mychip_stop_hardware(chip);
5207 pci_disable_device(chip->pci);
5216 The scheme of the real resume job is as following.
5219 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5220 <listitem><para>Enable the pci device again by calling
5221 <function>pci_enable_device()</function>.</para></listitem>
5222 <listitem><para>Re-initialize the chip.</para></listitem>
5223 <listitem><para>Restore the saved registers if necessary.</para></listitem>
5224 <listitem><para>Resume the mixer, e.g. calling
5225 <function>snd_ac97_resume()</function>.</para></listitem>
5226 <listitem><para>Restart the hardware (if any).</para></listitem>
5231 A typical code would be like:
5236 static void mychip_resume(mychip_t *chip)
5239 mychip_t *chip = card->pm_private_data;
5241 pci_enable_device(chip->pci);
5243 snd_mychip_reinit_chip(chip);
5245 snd_mychip_restore_registers(chip);
5247 snd_ac97_resume(chip->ac97);
5249 snd_mychip_restart_chip(chip);
5258 OK, we have all callbacks now. Let's set up them now. In the
5259 initialization of the card, add the following:
5264 static int __devinit snd_mychip_probe(struct pci_dev *pci,
5265 const struct pci_device_id *pci_id)
5271 snd_card_set_pm_callback(card, snd_my_suspend, snd_my_resume, chip);
5278 Here you don't have to put ifdef CONFIG_PM around, since it's already
5279 checked in the header and expanded to empty if not needed.
5283 If you need a space for saving the registers, you'll need to
5284 allocate the buffer for it here, too, since it would be fatal
5285 if you cannot allocate a memory in the suspend phase.
5286 The allocated buffer should be released in the corresponding
5291 And next, set suspend/resume callbacks to the pci_driver,
5292 This can be done by passing a macro SND_PCI_PM_CALLBACKS
5293 in the pci_driver struct. This macro is expanded to the correct
5294 (global) callbacks if CONFIG_PM is set.
5299 static struct pci_driver driver = {
5301 .id_table = snd_my_ids,
5302 .probe = snd_my_probe,
5303 .remove = __devexit_p(snd_my_remove),
5304 SND_PCI_PM_CALLBACKS
5314 <!-- ****************************************************** -->
5315 <!-- Module Parameters -->
5316 <!-- ****************************************************** -->
5317 <chapter id="module-parameters">
5318 <title>Module Parameters</title>
5320 There are standard module options for ALSA. At least, each
5321 module should have <parameter>index</parameter>,
5322 <parameter>id</parameter> and <parameter>enable</parameter>
5327 If the module supports multiple cards (usually up to
5328 8 = <constant>SNDRV_CARDS</constant> cards), they should be
5329 arrays. The default initial values are defined already as
5330 constants for ease of programming:
5335 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
5336 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
5337 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
5344 If the module supports only a single card, they could be single
5345 variables, instead. <parameter>enable</parameter> option is not
5346 always necessary in this case, but it wouldn't be so bad to have a
5347 dummy option for compatibility.
5351 The module parameters must be declared with the standard
5352 <function>module_param()()</function>,
5353 <function>module_param_array()()</function> and
5354 <function>MODULE_PARM_DESC()</function> macros.
5358 The typical coding would be like below:
5363 #define CARD_NAME "My Chip"
5365 module_param_array(index, int, NULL, 0444);
5366 MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
5367 module_param_array(id, charp, NULL, 0444);
5368 MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
5369 module_param_array(enable, bool, NULL, 0444);
5370 MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
5377 Also, don't forget to define the module description, classes,
5378 license and devices. Especially, the recent modprobe requires to
5379 define the module license as GPL, etc., otherwise the system is
5380 shown as <quote>tainted</quote>.
5385 MODULE_DESCRIPTION("My Chip");
5386 MODULE_LICENSE("GPL");
5387 MODULE_SUPPORTED_DEVICE("{{Vendor,My Chip Name}}");
5396 <!-- ****************************************************** -->
5397 <!-- How To Put Your Driver -->
5398 <!-- ****************************************************** -->
5399 <chapter id="how-to-put-your-driver">
5400 <title>How To Put Your Driver Into ALSA Tree</title>
5402 <title>General</title>
5404 So far, you've learned how to write the driver codes.
5405 And you might have a question now: how to put my own
5406 driver into the ALSA driver tree?
5407 Here (finally :) the standard procedure is described briefly.
5411 Suppose that you'll create a new PCI driver for the card
5412 <quote>xyz</quote>. The card module name would be
5413 snd-xyz. The new driver is usually put into alsa-driver
5414 tree, <filename>alsa-driver/pci</filename> directory in
5415 the case of PCI cards.
5416 Then the driver is evaluated, audited and tested
5417 by developers and users. After a certain time, the driver
5418 will go to alsa-kernel tree (to the corresponding directory,
5419 such as <filename>alsa-kernel/pci</filename>) and eventually
5420 integrated into Linux 2.6 tree (the directory would be
5421 <filename>linux/sound/pci</filename>).
5425 In the following sections, the driver code is supposed
5426 to be put into alsa-driver tree. The two cases are assumed:
5427 a driver consisting of a single source file and one consisting
5428 of several source files.
5433 <title>Driver with A Single Source File</title>
5438 Modify alsa-driver/pci/Makefile
5442 Suppose you have a file xyz.c. Add the following
5447 snd-xyz-objs := xyz.o
5448 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5457 Create the Kconfig entry
5461 Add the new entry of Kconfig for your xyz driver.
5466 tristate "Foobar XYZ"
5470 Say Y here to include support for Foobar XYZ soundcard.
5472 To compile this driver as a module, choose M here: the module
5473 will be called snd-xyz.
5478 the line, select SND_PCM, specifies that the driver xyz supports
5479 PCM. In addition to SND_PCM, the following components are
5480 supported for select command:
5481 SND_RAWMIDI, SND_TIMER, SND_HWDEP, SND_MPU401_UART,
5482 SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB, SND_AC97_CODEC.
5483 Add the select command for each supported component.
5487 Note that some selections imply the lowlevel selections.
5488 For example, PCM includes TIMER, MPU401_UART includes RAWMIDI,
5489 AC97_CODEC includes PCM, and OPL3_LIB includes HWDEP.
5490 You don't need to give the lowlevel selections again.
5494 For the details of Kconfig script, refer to the kbuild
5502 Run cvscompile script to re-generate the configure script and
5503 build the whole stuff again.
5511 <title>Drivers with Several Source Files</title>
5513 Suppose that the driver snd-xyz have several source files.
5514 They are located in the new subdirectory,
5520 Add a new directory (<filename>xyz</filename>) in
5521 <filename>alsa-driver/pci/Makefile</filename> like below
5526 obj-$(CONFIG_SND) += xyz/
5535 Under the directory <filename>xyz</filename>, create a Makefile
5538 <title>Sample Makefile for a driver xyz</title>
5545 include $(SND_TOPDIR)/toplevel.config
5546 include $(SND_TOPDIR)/Makefile.conf
5548 snd-xyz-objs := xyz.o abc.o def.o
5550 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5552 include $(SND_TOPDIR)/Rules.make
5561 Create the Kconfig entry
5565 This procedure is as same as in the last section.
5571 Run cvscompile script to re-generate the configure script and
5572 build the whole stuff again.
5581 <!-- ****************************************************** -->
5582 <!-- Useful Functions -->
5583 <!-- ****************************************************** -->
5584 <chapter id="useful-functions">
5585 <title>Useful Functions</title>
5587 <section id="useful-functions-snd-printk">
5588 <title><function>snd_printk()</function> and friends</title>
5590 ALSA provides a verbose version of
5591 <function>printk()</function> function. If a kernel config
5592 <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this
5593 function prints the given message together with the file name
5594 and the line of the caller. The <constant>KERN_XXX</constant>
5595 prefix is processed as
5596 well as the original <function>printk()</function> does, so it's
5597 recommended to add this prefix, e.g.
5602 snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
5609 There are also <function>printk()</function>'s for
5610 debugging. <function>snd_printd()</function> can be used for
5611 general debugging purposes. If
5612 <constant>CONFIG_SND_DEBUG</constant> is set, this function is
5613 compiled, and works just like
5614 <function>snd_printk()</function>. If the ALSA is compiled
5615 without the debugging flag, it's ignored.
5619 <function>snd_printdd()</function> is compiled in only when
5620 <constant>CONFIG_SND_DEBUG_DETECT</constant> is set. Please note
5621 that <constant>DEBUG_DETECT</constant> is not set as default
5622 even if you configure the alsa-driver with
5623 <option>--with-debug=full</option> option. You need to give
5624 explicitly <option>--with-debug=detect</option> option instead.
5628 <section id="useful-functions-snd-assert">
5629 <title><function>snd_assert()</function></title>
5631 <function>snd_assert()</function> macro is similar with the
5632 normal <function>assert()</function> macro. For example,
5637 snd_assert(pointer != NULL, return -EINVAL);
5644 The first argument is the expression to evaluate, and the
5645 second argument is the action if it fails. When
5646 <constant>CONFIG_SND_DEBUG</constant>, is set, it will show an
5647 error message such as <computeroutput>BUG? (xxx) (called from
5648 yyy)</computeroutput>. When no debug flag is set, this is
5653 <section id="useful-functions-snd-runtime-check">
5654 <title><function>snd_runtime_check()</function></title>
5656 This macro is quite similar with
5657 <function>snd_assert()</function>. Unlike
5658 <function>snd_assert()</function>, the expression is always
5659 evaluated regardless of
5660 <constant>CONFIG_SND_DEBUG</constant>. When
5661 <constant>CONFIG_SND_DEBUG</constant> is set, the macro will
5662 show a message like <computeroutput>ERROR (xx) (called from
5663 yyy)</computeroutput>.
5667 <section id="useful-functions-snd-bug">
5668 <title><function>snd_BUG()</function></title>
5670 It calls <function>snd_assert(0,)</function> -- that is, just
5671 prints the error message at the point. It's useful to show that
5672 a fatal error happens there.
5678 <!-- ****************************************************** -->
5679 <!-- Acknowledgments -->
5680 <!-- ****************************************************** -->
5681 <chapter id="acknowledments">
5682 <title>Acknowledgments</title>
5684 I would like to thank Phil Kerr for his help for improvement and
5685 corrections of this document.
5688 Kevin Conder reformatted the original plain-text to the
5692 Giuliano Pochini corrected typos and contributed the example codes
5693 in the hardware constraints section.