1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">
4 <?dbhtml filename="index.html">
6 <!-- ****************************************************** -->
8 <!-- ****************************************************** -->
10 <title>Writing an ALSA Driver</title>
12 <firstname>Takashi</firstname>
13 <surname>Iwai</surname>
16 <email>tiwai@suse.de</email>
21 <date>Mar. 26, 2003</date>
22 <edition>0.3</edition>
26 This document describes how to write an ALSA (Advanced Linux
27 Sound Architecture) driver.
33 Copyright (c) 2002, 2003 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.5 (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.5 (or later)
118 tree. This tree is designed only for compilation on 2.5 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.5 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 non-architecture-specific
243 codes. For example, the dummy pcm driver and the serial MIDI
244 driver are found in this directory. In the sub-directories,
245 there are the codes for components which are independent from
246 bus and cpu architectures.
249 <section id="file-tree-drivers-directory-mpu401">
250 <title>drivers/mpu401</title>
252 The MPU401 and MPU401-UART modules are stored here.
256 <section id="file-tree-drivers-directory-opl3">
257 <title>drivers/opl3</title>
259 The OPL3 FM-synth stuff is found here.
264 <section id="file-tree-i2c-directory">
265 <title>i2c directory</title>
267 This contains the ALSA i2c components.
271 Although there is a standard i2c layer on Linux, ALSA uses its
272 own i2c codes for some cards, because the soundcard needs only a
273 simple operation and the standard API is too complicated for
277 <section id="file-tree-i2c-directory-l3">
278 <title>i2c/l3</title>
280 This is a sub-directory for ARM L3 i2c.
285 <section id="file-tree-synth-directory">
286 <title>synth directory</title>
288 This contains the synth middle-level modules.
292 So far, there is only Emu8000/Emu10k1 synth driver under
293 synth/emux sub-directory.
297 <section id="file-tree-pci-directory">
298 <title>pci directory</title>
300 This and its sub-directories hold the top-level card modules
305 The drivers compiled from a single file is stored directly on
306 pci directory, while the drivers with several source files are
307 stored on its own sub-directory (e.g. emu10k1, ice1712).
311 <section id="file-tree-isa-directory">
312 <title>isa directory</title>
314 This and its sub-directories hold the top-level card modules
319 <section id="file-tree-arm-ppc-sparc-directories">
320 <title>arm, ppc, and sparc directories</title>
322 These are for the top-level card modules which are
323 architecture specific.
327 <section id="file-tree-usb-directory">
328 <title>usb directory</title>
330 This contains the USB-audio driver. On the latest version, the
331 USB MIDI driver is integrated together with usb-audio driver.
335 <section id="file-tree-pcmcia-directory">
336 <title>pcmcia directory</title>
338 The PCMCIA, especially PCCard drivers will go here. CardBus
339 drivers will be on pci directory, because its API is identical
340 with the standard PCI cards.
344 At this moment, only VX-pocket driver exists.
348 <section id="file-tree-oss-directory">
349 <title>oss directory</title>
351 The OSS/Lite source files are stored here on Linux 2.5 (or
352 later) tree. (In the ALSA driver tarball, it's empty, of course :)
358 <!-- ****************************************************** -->
359 <!-- Basic Flow for PCI Drivers -->
360 <!-- ****************************************************** -->
361 <chapter id="basic-flow">
362 <title>Basic Flow for PCI Drivers</title>
364 <section id="basic-flow-outline">
365 <title>Outline</title>
367 The minimum flow of PCI soundcard is like the following:
370 <listitem><para>define the PCI ID table (see the section
371 <link linkend="pci-resource-entries"><citetitle>PCI Entries
372 </citetitle></link>).</para></listitem>
373 <listitem><para>create <function>probe()</function> callback.</para></listitem>
374 <listitem><para>create <function>remove()</function> callback.</para></listitem>
375 <listitem><para>create pci_driver table which contains the three pointers above.</para></listitem>
376 <listitem><para>create <function>init()</function> function just calling <function>pci_module_init()</function> to register the pci_driver table defined above.</para></listitem>
377 <listitem><para>create <function>exit()</function> function to call <function>pci_unregister_driver()</function> function.</para></listitem>
382 <section id="basic-flow-example">
383 <title>Full Code Example</title>
385 The code example is shown below. Some parts are kept
386 unimplemented at this moment but will be filled in the
387 succeeding sections. The numbers in comment lines of
388 <function>snd_mychip_probe()</function> function are the
392 <title>Basic Flow for PCI Drivers Example</title>
395 #include <sound/driver.h>
396 #include <linux/init.h>
397 #include <linux/pci.h>
398 #include <linux/slab.h>
399 #include <sound/core.h>
401 #include <sound/initval.h>
403 // module parameters (see "Module Parameters")
404 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
405 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
406 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
408 // definition of the chip-specific record
409 typedef struct snd_mychip mychip_t;
412 // rest of implementation will be in the section
413 // "PCI Resource Managements"
416 // this should be go into <sound/sndmagic.h>
417 // (see "Management of Cards and Components")
418 #define mychip_t_magic 0xa15a4501
420 // chip-specific destructor
421 // (see "PCI Resource Managements")
422 static int snd_mychip_free(mychip_t *chip)
424 // will be implemented later...
427 // component-destructor
428 // (see "Management of Cards and Components")
429 static int snd_mychip_dev_free(snd_device_t *device)
431 mychip_t *chip = snd_magic_cast(mychip_t,
432 device->device_data, return -ENXIO);
433 return snd_mychip_free(chip);
436 // chip-specific constructor
437 // (see "Management of Cards and Components")
438 static int __devinit snd_mychip_create(snd_card_t *card,
439 struct pci_device *pci,
444 static snd_device_ops_t ops = {
445 .dev_free = snd_mychip_dev_free,
450 // check PCI availability here
451 // (see "PCI Resource Managements")
453 // allocate a chip-specific data with magic-alloc
454 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
460 // rest of initialization here; will be implemented
461 // later, see "PCI Resource Managements"
463 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
465 snd_mychip_free(chip);
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) {
504 strcpy(card->driver, "My Chip");
505 strcpy(card->shortname, "My Own Chip 123");
506 sprintf(card->longname, "%s at 0x%lx irq %i",
507 card->shortname, chip->ioport, chip->irq);
510 if ((err = snd_card_register(card)) < 0) {
516 pci_set_drvdata(pci, chip);
521 // destructor -- see "Destructor" sub-section
522 static void __devexit snd_mychip_remove(struct pci_dev *pci)
524 mychip_t *chip = snd_magic_cast(mychip_t,
525 pci_get_drvdata(pci), return);
527 snd_card_free(chip->card);
528 pci_set_drvdata(pci, NULL);
536 <section id="basic-flow-constructor">
537 <title>Constructor</title>
539 The real constructor of PCI drivers is probe callback. The
540 probe callback and other component-constructors which are called
541 from probe callback should be defined with
542 <parameter>__devinit</parameter> prefix. You
543 cannot use <parameter>__init</parameter> prefix for them,
544 because any PCI device could be a hotplug device.
548 In the probe callback, the following scheme is often used.
551 <section id="basic-flow-constructor-device-index">
552 <title>1) Check and increment the device index.</title>
559 if (dev >= SNDRV_CARDS)
569 where enable[dev] is the module option.
573 At each time probe callback is called, check the
574 availability of the device. If not available, simply increment
575 the device index and returns. dev will be incremented also
577 linkend="basic-flow-constructor-set-pci"><citetitle>step
578 7</citetitle></link>).
582 <section id="basic-flow-constructor-create-card">
583 <title>2) Create a card instance</title>
590 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
597 The detail will be explained in the section
598 <link linkend="card-management-card-instance"><citetitle>
599 Management of Cards and Components</citetitle></link>.
603 <section id="basic-flow-constructor-create-main">
604 <title>3) Create a main component</title>
606 In this part, the PCI resources are allocated.
613 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
621 The detail will be explained in the section <link
622 linkend="pci-resource"><citetitle>PCI Resource
623 Managements</citetitle></link>.
627 <section id="basic-flow-constructor-create-other">
628 <title>4) Create other components, such as mixer, MIDI, etc.</title>
630 Here you define the basic components such as
631 <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
632 mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
633 MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
634 and other interfaces.
635 Also, if you want a <link linkend="proc-interface"><citetitle>proc
636 file</citetitle></link>, define it here, too.
640 <section id="basic-flow-constructor-main-component">
641 <title>5) Set the driver ID and name strings.</title>
646 strcpy(card->driver, "My Chip");
647 strcpy(card->shortname, "My Own Chip 123");
648 sprintf(card->longname, "%s at 0x%lx irq %i",
649 card->shortname, chip->ioport, chip->irq);
654 The driver field holds the minimal ID string of the
655 chip. This is referred by alsa-lib's configurator, so keep it
657 Even the same driver can have different driver IDs to
658 distinguish the functionality of each chip type.
662 The shortname field is a string shown as more verbose
663 name. The longname field contains the information which is
664 shown in <filename>/proc/asound/cards</filename>.
668 <section id="basic-flow-constructor-register-card">
669 <title>6) Register the card instance.</title>
674 if ((err = snd_card_register(card)) < 0) {
684 Will be explained in the section <link
685 linkend="card-management-registration"><citetitle>Management
686 of Cards and Components</citetitle></link>, too.
690 <section id="basic-flow-constructor-set-pci">
691 <title>7) Set the PCI driver data and return zero.</title>
696 pci_set_drvdata(pci, chip);
703 In the above, the chip record is stored. This pointer is
704 referred in the remove callback and power-management
706 If the card doesn't support the suspend/resume, you can store
707 the card pointer instead of the chip pointer, so that
708 <function>snd_card_free</function> can be called directly
709 without cast in the remove callback. But anyway, be sure
710 which pointer is used.
715 <section id="basic-flow-destructor">
716 <title>Destructor</title>
718 The destructor, remove callback, simply releases the card
719 instance. Then the ALSA middle layer will release all the
720 attached components automatically.
724 It would be typically like the following:
729 static void __devexit snd_mychip_remove(struct pci_dev *pci)
731 mychip_t *chip = snd_magic_cast(mychip_t,
732 pci_get_drvdata(pci), return);
734 snd_card_free(chip->card);
735 pci_set_drvdata(pci, NULL);
741 The above code assumes that the chip is allocated
742 with snd_magic stuff and
743 has the field to hold the card pointer (see <link
744 linkend="card-management"><citetitle>the next
745 section</citetitle></link>).
749 <section id="basic-flow-header-files">
750 <title>Header Files</title>
752 For the above example, at least the following include files
758 #include <sound/driver.h>
759 #include <linux/init.h>
760 #include <linux/pci.h>
761 #include <linux/slab.h>
762 #include <sound/core.h>
764 #include <sound/initval.h>
769 where the last twos are necessary only when module options are
770 defined in the source file. If the codes are split to several
771 files, the file without module options don't need them.
775 In addition to them, you'll need
776 <filename><linux/interrupt.h></filename> for the interrupt
777 handling, and <filename><asm/io.h></filename> for the i/o
778 access. If you use <function>mdelay()</function> or
779 <function>udelay()</function> functions, you'll need to include
780 <filename><linux/delay.h></filename>, too.
784 The ALSA interfaces like PCM or control API are define in other
785 header files as <filename><sound/xxx.h></filename>.
786 They have to be included after
787 <filename><sound/core.h></filename>.
794 <!-- ****************************************************** -->
795 <!-- Management of Cards and Components -->
796 <!-- ****************************************************** -->
797 <chapter id="card-management">
798 <title>Management of Cards and Components</title>
800 <section id="card-management-card-instance">
801 <title>Card Instance</title>
803 For each soundcard, a <quote>card</quote> record must be allocated.
807 A card record is the headquarters of the soundcard. It manages
808 the list of whole devices (components) on the soundcard, such as
809 PCM, mixers, MIDI, synthesizer, and so on. Also, the card
810 record holds the ID and the name strings of the card, manages
811 the root of proc files, and controls the power-management states
812 and hotplug disconnections. The component list on the card
813 record is used to manage the proper releases of resources at
818 As mentioned above, to create a card instance, call
819 <function>snd_card_new()</function>.
825 card = snd_card_new(index, id, module, extra_size);
832 The function takes four arguments, the card-index number, the
833 id string, the module pointer (usually
834 <constant>THIS_MODULE</constant>),
835 and the size of extra-data space. The last argument is used to
836 allocate card->private_data for the
837 chip-specific data. Note that this data
838 <emphasis>is</emphasis> allocated by
839 <function>snd_card_new()</function>.
843 <section id="card-management-component">
844 <title>Components</title>
846 After the card is created, you can attach the components
847 (devices) to the card instance. On ALSA driver, a component is
848 represented as a <type>snd_device_t</type> object.
849 A component can be a PCM instance, a control interface, a raw
850 MIDI interface, etc. Each of such instances has one component
855 A component can be created via
856 <function>snd_device_new()</function> function.
861 snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
868 This takes the card pointer, the device-level
869 (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
870 callback pointers (<parameter>&ops</parameter>). The
871 device-level defines the type of components and the order of
872 registration and de-registration. For most of components, the
873 device-level is already defined. For a user-defined component,
874 you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
878 This function itself doesn't allocate the data space. The data
879 must be allocated manually beforehand, and its pointer is passed
880 as the argument. This pointer is used as the identifier
881 (<parameter>chip</parameter> in the above example) for the
886 Each ALSA pre-defined component such as ac97 or pcm calls
887 <function>snd_device_new()</function> inside its
888 constructor. The destructor for each component is defined in the
889 callback pointers. Hence, you don't need to take care of
890 calling a destructor for such a component.
894 If you would like to create your own component, you need to
895 set the destructor function to dev_free callback in
896 <parameter>ops</parameter>, so that it can be released
897 automatically via <function>snd_card_free()</function>. The
898 example will be shown later as an implementation of a
903 <section id="card-management-chip-specific">
904 <title>Chip-Specific Data</title>
906 The chip-specific information, e.g. the i/o port address, its
907 resource pointer, or the irq number, is stored in the
908 chip-specific record.
909 Usually, the chip-specific record is typedef'ed as
910 <type>xxx_t</type> like the following:
915 typedef struct snd_mychip mychip_t;
925 You might have objections against such a typedef, but this
926 typedef is necessary if you use a <quote>magic-cast</quote>
928 linkend="card-management-chip-what-advantage"><citetitle>later</citetitle></link>).
932 In general, there are two ways to allocate the chip record.
935 <section id="card-management-chip-specific-snd-card-new">
936 <title>1. Allocating via <function>snd_card_new()</function>.</title>
938 As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
943 card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
948 whether <type>mychip_t</type> is the type of the chip record.
952 In return, the allocated record can be accessed as
957 mychip_t *chip = (mychip_t *)card->private_data;
962 With this method, you don't have to allocate twice. But you
963 cannot use <quote>magic-cast</quote> for this record pointer,
968 <section id="card-management-chip-specific-allocate-extra">
969 <title>2. Allocating an extra device.</title>
972 After allocating a card instance via
973 <function>snd_card_new()</function> (with
974 <constant>NULL</constant> on the 4th arg), call
975 <function>snd_magic_kcalloc()</function>.
982 card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
984 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
989 Once when the record is allocated via snd_magic stuff, you
990 can use <quote>magic-cast</quote> for the void pointer.
994 The chip record should have the field to hold the card
1010 Then, set the card pointer in the returned chip instance.
1022 Also, you need to define a magic-value for <type>mychip_t</type>.
1027 #define mychip_t_magic 0xa15a4501
1031 (the detail will be described in the
1032 <link linkend="card-management-chip-what-advantage"><citetitle>
1033 next</citetitle></link> subsection).
1037 Next, initialize the fields, and register this chip
1038 record as a low-level device with a specified
1039 <parameter>ops</parameter>,
1044 static snd_device_ops_t ops = {
1045 .dev_free = snd_mychip_dev_free,
1048 snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1053 <function>snd_mychip_dev_free()</function> is the
1054 device-destructor function, which will call the real
1062 static int snd_mychip_dev_free(snd_device_t *device)
1064 mychip_t *chip = snd_magic_cast(mychip_t, device->device_data,
1066 return snd_mychip_free(chip);
1072 where <function>snd_mychip_free()</function> is the real destructor.
1076 <section id="card-management-chip-what-advantage">
1077 <title>Not a magic but a logic</title>
1079 <para>Now, you might have a question: What is the advantage of the
1080 second method? Obviously, it looks far more complicated.</para>
1082 As I wrote many times, the second method allows a
1083 <quote>magic-cast</quote> for <type>mychip_t</type>. If you
1084 have a void pointer (such as
1085 pcm->private_data), the pointer type
1086 is unknown at the compile time, and you cannot know even if a
1087 wrong pointer type is passed. The compiler would accept
1088 it. The magic-cast checks the pointer type at the runtime (and
1089 whether it's a null pointer, too). Hence, the cast will be
1090 much safer and good for debugging.
1094 As you have already seen, allocation with a magic-header can
1095 be done via <function>snd_magic_kmalloc()</function> or
1096 <function>snd_magic_kcalloc()</function>.
1102 chip = snd_magic_kmalloc(mychip_t, 0, GFP_KERNEL);
1103 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1108 The difference of these two functions is whether the area is
1109 zero-cleared (<function>kcalloc</function>) or not
1110 (<function>kmalloc</function>).
1114 The first argument of the allocator is the type of the
1115 record. The magic-constant has to be defined for this type
1116 beforehand. In this case, we'll need to define
1117 <constant>mychip_t_magic</constant>, for example, as already
1123 #define mychip_t_magic 0xa15a4501
1128 The value is arbitrary but should be unique.
1129 This is usually defined in
1130 <filename><include/sndmagic.h></filename> or
1131 <filename><include/amagic.h></filename> for alsa-driver tree,
1132 but you may define it locally in the code at the early
1133 development stage, since changing
1134 <filename>sndmagic.h</filename> will lead to the recompilation
1135 of the whole driver codes.
1139 The second argument is the extra-data length. It is usually
1140 zero. The third argument is the flags to be passed to kernel
1141 memory allocator, <constant>GFP_XXX</constant>. Normally,
1142 <constant>GFP_KERNEL</constant> is passed.
1146 For casting a pointer, use
1147 <function>snd_magic_cast()</function> macro:
1152 mychip_t *chip = snd_magic_cast(mychip_t, source_pointer, action);
1157 where <parameter>source_pointer</parameter> is the pointer to
1158 be casted (e.g. pcm->private_data), and
1159 <parameter>action</parameter> is the action to do if the cast
1160 fails (e.g. return <constant>-EINVAL</constant>).
1164 For releasing the magic-allocated data, you need to call
1165 <function>snd_magic_kfree()</function> function instead of
1166 <function>kfree()</function>.
1171 snd_magic_kfree(chip);
1178 If you call <function>kfree()</function> for the
1179 magic-allocated value, it will lead to memory leaks.
1180 When the ALSA drivers are compiled with
1181 <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config (or
1182 configured with <option>--with-debug=full</option>), the
1183 non-matching free will be checked and you'll see warning
1188 If you are 100% sure that your code is bug-free, you can
1189 compile the driver without
1190 <constant>CONFIG_SND_DEBUG_MEMORY</constant> kernel config,
1191 so that the magic-allocator and the magic-cast will be
1192 replaced to the normal kmalloc and cast.
1197 <section id="card-management-registration">
1198 <title>Registration and Release</title>
1200 After all components are assigned, register the card instance
1201 by calling <function>snd_card_register()</function>. The access
1202 to the device files are enabled at this point. That is, before
1203 <function>snd_card_register()</function> is called, the
1204 components are safely inaccessible from external side. If this
1205 call fails, exit the probe function after releasing the card via
1206 <function>snd_card_free()</function>.
1210 For releasing the card instance, you can call simply
1211 <function>snd_card_free()</function>. As already mentioned, all
1212 components are released automatically by this call.
1216 As further notes, the destructors (both
1217 <function>snd_mychip_dev_free</function> and
1218 <function>snd_mychip_free</function>) cannot be defined with
1219 <parameter>__devexit</parameter> prefix, because they may be
1220 called from the constructor, too, at the false path.
1224 For a device which allows hotplugging, you can use
1225 <function>snd_card_free_in_thread</function>. This one will
1226 postpone the destruction and wait in a kernel-thread until all
1235 <!-- ****************************************************** -->
1236 <!-- PCI Resource Managements -->
1237 <!-- ****************************************************** -->
1238 <chapter id="pci-resource">
1239 <title>PCI Resource Managements</title>
1241 <section id="pci-resource-example">
1242 <title>Full Code Example</title>
1244 In this section, we'll finish the chip-specific constructor,
1245 destructor and PCI entries. The example code is shown first,
1249 <title>PCI Resource Managements Example</title>
1254 struct pci_dev *pci;
1257 struct resource *res_port;
1262 static int snd_mychip_free(mychip_t *chip)
1264 // disable hardware here if any
1265 // (not implemented in this document)
1267 // release the i/o port
1268 if (chip->res_port) {
1269 release_resource(chip->res_port);
1270 kfree_nocheck(chip->res_port);
1274 free_irq(chip->irq, (void *)chip);
1276 snd_magic_kfree(chip);
1280 // chip-specific constructor
1281 static int __devinit snd_mychip_create(snd_card_t *card,
1282 struct pci_dev *pci,
1287 static snd_device_ops_t ops = {
1288 .dev_free = snd_mychip_dev_free,
1293 // check PCI availability (28bit DMA)
1294 if ((err = pci_enable_device(pci)) < 0)
1296 if (!pci_dma_supported(pci, 0x0fffffff)) {
1297 printk(KERN_ERR "error to set 28bit mask DMA\n");
1300 pci_set_dma_mask(pci, 0x0fffffff);
1302 chip = snd_magic_kcalloc(mychip_t, 0, GFP_KERNEL);
1306 // initialize the stuff
1311 // (1) PCI resource allocation
1312 chip->port = pci_resource_start(pci, 0);
1313 if ((chip->res_port = request_region(chip->port, 8,
1314 "My Chip")) == NULL) {
1315 snd_mychip_free(chip);
1316 printk(KERN_ERR "cannot allocate the port\n");
1319 if (request_irq(pci->irq, snd_mychip_interrupt,
1320 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1322 snd_mychip_free(chip);
1323 printk(KERN_ERR "cannot grab irq\n");
1326 chip->irq = pci->irq;
1328 // (2) initialization of the chip hardware
1329 // (not implemented in this document)
1331 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1333 snd_mychip_free(chip);
1341 static struct pci_device_id snd_mychip_ids[] __devinitdata = {
1342 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1343 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1347 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1349 // pci_driver definition
1350 static struct pci_driver driver = {
1351 .name = "My Own Chip",
1352 .id_table = snd_mychip_ids,
1353 .probe = snd_mychip_probe,
1354 .remove = __devexit_p(snd_mychip_remove),
1357 // initialization of the module
1358 static int __init alsa_card_mychip_init(void)
1362 if ((err = pci_module_init(&driver)) < 0) {
1364 printk(KERN_ERR "My chip soundcard not found "
1365 "or device busy\n");
1372 // clean up the module
1373 static void __exit alsa_card_mychip_exit(void)
1375 pci_unregister_driver(&driver);
1378 module_init(alsa_card_mychip_init)
1379 module_exit(alsa_card_mychip_exit)
1381 EXPORT_NO_SYMBOLS; /* for old kernels only */
1388 <section id="pci-resource-some-haftas">
1389 <title>Some Hafta's</title>
1391 The allocation of PCI resources is done in the
1392 <function>probe()</function> function, and usually an extra
1393 <function>xxx_create()</function> function is written for this
1398 In the case of PCI devices, you have to call at first
1399 <function>pci_enable_device()</function> function before
1400 allocating resources. Also, you need to set the proper PCI DMA
1401 mask to limit the accessed i/o range. In some cases, you might
1402 need to call <function>pci_set_master()</function> function,
1407 Suppose the 28bit mask, and the code to be added would be like:
1412 if ((err = pci_enable_device(pci)) < 0)
1414 if (!pci_dma_supported(pci, 0x0fffffff)) {
1415 printk(KERN_ERR "error to set 28bit mask DMA\n");
1418 pci_set_dma_mask(pci, 0x0fffffff);
1425 <section id="pci-resource-resource-allocation">
1426 <title>Resource Allocation</title>
1428 The allocation of I/O ports and irqs are done via standard kernel
1429 functions. Unlike ALSA ver.0.5.x., there are no helpers for
1430 that. And these resources must be released in the destructor
1431 function (see below). Also, on ALSA 0.9.x, you don't need to
1432 allocate (pseudo-)DMA for PCI like ALSA 0.5.x.
1436 Now assume that this PCI device has an I/O port with 8 bytes
1437 and an interrupt. Then <type>mychip_t</type> will have the
1447 struct resource *res_port;
1457 For an i/o port (and also a memory region), you need to have
1458 the resource pointer for the standard resource management. For
1459 an irq, you have to keep only the irq number (integer). But you
1460 need to initialize this number as -1 before actual allocation,
1461 since irq 0 is valid. The port address and its resource pointer
1462 can be initialized as null by
1463 <function>snd_magic_kcalloc()</function> automatically, so you
1464 don't have to take care of resetting them.
1468 The allocation of an i/o port is done like this:
1473 chip->port = pci_resource_start(pci, 0);
1474 if ((chip->res_port = request_region(chip->port, 8,
1475 "My Chip")) == NULL) {
1476 printk(KERN_ERR "cannot allocate the port 0x%lx\n",
1478 snd_mychip_free(chip);
1487 It will reserve the i/o port region of 8 bytes of the given
1488 PCI device. The returned value, chip->res_port, is allocated
1489 via <function>kmalloc()</function> by
1490 <function>request_region()</function>. The pointer must be
1491 released via <function>kfree()</function>, but there is some
1492 problem regarding this. This issue will be explained more below.
1496 The allocation of an interrupt source is done like this:
1501 if (request_irq(pci->irq, snd_mychip_interrupt,
1502 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1504 snd_mychip_free(chip);
1505 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1508 chip->irq = pci->irq;
1513 where <function>snd_mychip_interrupt()</function> is the
1514 interrupt handler defined <link
1515 linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1516 Note that chip->irq should be defined
1517 only when <function>request_irq()</function> succeeded.
1521 On the PCI bus, the interrupts can be shared. Thus,
1522 <constant>SA_SHIRQ</constant> is given as the interrupt flag of
1523 <function>request_irq()</function>.
1527 The last argument of <function>request_irq()</function> is the
1528 data pointer passed to the interrupt handler. Usually, the
1529 chip-specific record is used for that, but you can use what you
1534 I won't define the detail of the interrupt handler at this
1535 point, but at least its appearance can be explained now. The
1536 interrupt handler looks usually like the following:
1541 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1542 struct pt_regs *regs)
1544 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
1552 Again the magic-cast is used here to get the correct pointer
1553 from the second argument.
1557 Now let's write the corresponding destructor for the resources
1558 above. The role of destructor is simple: disable the hardware
1559 (if already activated) and release the resources. So far, we
1560 have no hardware part, so the disabling is not written here.
1564 For releasing the resources, <quote>check-and-release</quote>
1565 method is a safer way. For the i/o port, do like this:
1570 if (chip->res_port) {
1571 release_resource(chip->res_port);
1572 kfree_nocheck(chip->res_port);
1580 As you can see, the i/o resource pointer is also to be freed
1581 via <function>kfree_nocheck()</function> after
1582 <function>release_resource()</function> is called. You
1583 cannot use <function>kfree()</function> here, because on ALSA,
1584 <function>kfree()</function> may be a wrapper to its own
1585 allocator with the memory debugging. Since the resource pointer
1586 is allocated externally outside the ALSA, it must be released
1588 <function>kfree()</function>.
1589 <function>kfree_nocheck()</function> is used for that; it calls
1590 the native <function>kfree()</function> without wrapper.
1594 For releasing the interrupt, do like this:
1600 free_irq(chip->irq, (void *)chip);
1605 And finally, release the chip-specific record.
1610 snd_magic_kfree(chip);
1617 The chip instance is freed via
1618 <function>snd_magic_kfree()</function>. Please use this function
1619 for the object allocated by
1620 <function>snd_magic_kmalloc()</function>. If you free it with
1621 <function>kfree()</function>, it won't work properly and will
1622 result in the memory leak. Also, again, remember that you cannot
1623 set <parameter>__devexit</parameter> prefix for this destructor.
1627 We didn't implement the hardware-disabling part in the above.
1628 If you need to do this, please note that the destructor may be
1629 called even before the initialization of the chip is completed.
1630 It would be better to have a flag to skip the hardware-disabling
1631 if the hardware was not initialized yet.
1635 When the chip-data is assigned to the card using
1636 <function>snd_device_new()</function> with
1637 <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is
1638 called at the last. that is, it is assured that all other
1639 components like PCMs and controls have been already released.
1640 You don't have to call stopping PCMs, etc. explicitly, but just
1641 stop the hardware in the low-level.
1645 The management of a memory-mapped region is almost as same as
1646 the management of an i/o port. You'll need three fields like
1654 unsigned long iobase_phys;
1655 unsigned long iobase_virt;
1656 struct resource *res_iobase;
1662 and the allocation would be (assuming its size is 512 bytes):
1667 chip->iobase_phys = pci_resource_start(pci, 0);
1668 chip->iobase_virt = (unsigned long)
1669 ioremap_nocache(chip->iobase_phys, 512);
1670 if ((chip->res_port = request_mem_region(chip->iobase_phys, 512,
1671 "My Chip")) == NULL) {
1672 printk(KERN_ERR "cannot allocate the memory region\n");
1673 snd_mychip_free(chip);
1680 and the corresponding destructor would be:
1685 static int snd_mychip_free(mychip_t *chip)
1688 if (chip->iobase_virt)
1689 iounmap((void *)chip->iobase_virt);
1690 if (chip->res_iobase) {
1691 release_resource(chip->res_iobase);
1692 kfree_nocheck(chip->res_iobase);
1703 <section id="pci-resource-entries">
1704 <title>PCI Entries</title>
1706 So far, so good. Let's finish the rest of missing PCI
1707 stuffs. At first, we need a
1708 <structname>pci_device_id</structname> table for this
1709 chipset. It's a table of PCI vendor/device ID number, and some
1719 static struct pci_device_id snd_mychip_ids[] __devinitdata = {
1720 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1721 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1725 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1732 The first and second fields of
1733 <structname>pci_device_id</structname> struct are the vendor and
1734 device IDs. If you have nothing special to filter the matching
1735 devices, you can use the rest of fields like above. The last
1736 field of <structname>pci_device_id</structname> struct is a
1737 private data for this entry. You can specify any value here, for
1738 example, to tell the type of different operations per each
1739 device IDs. Such an example is found in intel8x0 driver.
1743 The last entry of this list is the terminator. You must
1744 specify this all-zero entry.
1748 Then, prepare the <structname>pci_driver</structname> record:
1753 static struct pci_driver driver = {
1754 .name = "My Own Chip",
1755 .id_table = snd_mychip_ids,
1756 .probe = snd_mychip_probe,
1757 .remove = __devexit_p(snd_mychip_remove),
1765 The <structfield>probe</structfield> and
1766 <structfield>remove</structfield> functions are what we already
1768 the previous sections. The <structfield>remove</structfield> should
1770 <function>__devexit_p()</function> macro, so that it's not
1771 defined for built-in (and non-hot-pluggable) case. The
1772 <structfield>name</structfield>
1773 field is the name string of this device. Note that you must not
1774 use a slash <quote>/</quote> in this string.
1778 And at last, the module entries:
1783 static int __init alsa_card_mychip_init(void)
1787 if ((err = pci_module_init(&driver)) < 0) {
1789 printk(KERN_ERR "My chip soundcard not found"
1790 " or device busy\n");
1797 static void __exit alsa_card_mychip_exit(void)
1799 pci_unregister_driver(&driver);
1802 module_init(alsa_card_mychip_init)
1803 module_exit(alsa_card_mychip_exit)
1810 Note that these module entries are tagged with
1811 <parameter>__init</parameter> and
1812 <parameter>__exit</parameter> prefixes, not
1813 <parameter>__devinit</parameter> nor
1814 <parameter>__devexit</parameter>.
1818 Oh, one thing was forgotten. If you have no exported symbols,
1819 you need to declare it on 2.2 or 2.4 kernels (on 2.5 kernels
1820 it's not necessary, though).
1836 <!-- ****************************************************** -->
1837 <!-- PCM Interface -->
1838 <!-- ****************************************************** -->
1839 <chapter id="pcm-interface">
1840 <title>PCM Interface</title>
1842 <section id="pcm-interface-general">
1843 <title>General</title>
1845 The PCM middle layer of ALSA is quite powerful and it is only
1846 necessary for each driver to implement the low-level functions
1847 to access its hardware.
1851 For accessing to the PCM layer, you need to include
1852 <filename><sound/pcm.h></filename> above all. In addition,
1853 <filename><sound/pcm_params.h></filename> might be needed
1854 if you access to some functions related with hw_param.
1858 Each card device can have up to four pcm instances. A pcm
1859 instance corresponds to a pcm device file. The limitation of
1860 number of instances comes only from the available bit size of
1861 the linux's device number. Once when 64bit device number is
1862 used, we'll have more available pcm instances.
1866 A pcm instance consists of pcm playback and capture streams,
1867 and each pcm stream consists of one or more pcm substreams. Some
1868 soundcard supports the multiple-playback function. For example,
1869 emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1870 each open, a free substream is (usually) automatically chosen
1871 and opened. Meanwhile, when only one substream exists and it was
1872 already opened, the succeeding open will result in the blocking
1873 or the error with <constant>EAGAIN</constant> according to the
1874 file open mode. But you don't have to know the detail in your
1875 driver. The PCM middle layer will take all such jobs.
1879 <section id="pcm-interface-example">
1880 <title>Full Code Example</title>
1882 The example code below does not include any hardware access
1883 routines but shows only the skeleton, how to build up the PCM
1887 <title>PCM Example Code</title>
1890 #include <sound/pcm.h>
1893 #define chip_t mychip_t
1896 /* hardware definition */
1897 static snd_pcm_hardware_t snd_mychip_playback_hw = {
1898 .info = (SNDRV_PCM_INFO_MMAP |
1899 SNDRV_PCM_INFO_INTERLEAVED |
1900 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1901 SNDRV_PCM_INFO_MMAP_VALID),
1902 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1903 .rates = SNDRV_PCM_RATE_8000_48000,
1908 .buffer_bytes_max = 32768,
1909 .period_bytes_min = 4096,
1910 .period_bytes_max = 32768,
1912 .periods_max = 1024,
1916 static int snd_mychip_pcm_open(snd_pcm_substream_t *subs)
1918 mychip_t *chip = snd_pcm_substream_chip(substream);
1919 snd_pcm_runtime_t *runtime = substream->runtime;
1921 runtime->hw = snd_mychip_playback_hw;
1922 // more hardware-initialization will be done here
1926 /* close callback */
1927 static int snd_mychip_pcm_close(snd_pcm_substream_t *substream)
1929 mychip_t *chip = snd_pcm_substream_chip(substream);
1930 // the hardware-specific codes will be here
1935 /* hw_params callback */
1936 static int snd_mychip_pcm_hw_params(snd_pcm_substream_t *substream,
1937 snd_pcm_hw_params_t * hw_params)
1939 return snd_pcm_lib_malloc_pages(substream,
1940 params_buffer_bytes(hw_params));
1943 /* hw_free callback */
1944 static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1946 return snd_pcm_lib_free_pages(substream);
1949 /* prepare callback */
1950 static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1952 mychip_t *chip = snd_pcm_substream_chip(substream);
1953 snd_pcm_runtime_t *runtime = substream->runtime;
1955 // set up the hardware with the current configuration
1957 mychip_set_sample_format(chip, runtime->format);
1958 mychip_set_sample_rate(chip, runtime->rate);
1959 mychip_set_channels(chip, runtime->channels);
1960 mychip_set_dma_setup(chip, runtime->dma_area,
1966 /* trigger callback */
1967 static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
1971 case SNDRV_PCM_TRIGGER_START:
1972 // do something to start the PCM engine
1974 case SNDRV_PCM_TRIGGER_STOP:
1975 // do something to stop the PCM engine
1982 /* pointer callback */
1983 static snd_pcm_uframes_t
1984 snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
1986 mychip_t *chip = snd_pcm_substream_chip(substream);
1987 unsigned int current_ptr;
1989 // get the current hardware pointer
1990 current_ptr = mychip_get_hw_pointer(chip);
1995 static snd_pcm_ops_t snd_mychip_playback_ops = {
1996 .open = snd_mychip_playback_open,
1997 .close = snd_mychip_playback_close,
1998 .ioctl = snd_pcm_lib_ioctl,
1999 .hw_params = snd_mychip_pcm_hw_params,
2000 .hw_free = snd_mychip_pcm_hw_free,
2001 .prepare = snd_mychip_pcm_prepare,
2002 .trigger = snd_mychip_pcm_trigger,
2003 .pointer = snd_mychip_pcm_pointer,
2007 * definitions of capture are omitted here...
2010 /* create a pcm device */
2011 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2016 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2019 pcm->private_data = chip;
2020 strcpy(pcm->name, "My Chip");
2023 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2024 &snd_mychip_playback_ops);
2025 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2026 &snd_mychip_capture_ops);
2027 /* pre-allocation of buffers */
2028 snd_pcm_lib_preallocate_pci_pages_for_all(chip->pci, pcm,
2038 <section id="pcm-interface-constructor">
2039 <title>Constructor</title>
2041 A pcm instance is allocated <function>snd_pcm_new()</function>
2042 function. It would be better to create a constructor for pcm,
2048 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2053 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
2056 pcm->private_data = chip;
2057 strcpy(pcm->name, "My Chip");
2068 The <function>snd_pcm_new()</function> function takes the four
2069 arguments. The first argument is the card pointer to which this
2070 pcm is assigned, and the second is the ID string.
2074 The third argument (<parameter>index</parameter>, 0 in the
2075 above) is the index of this new pcm. It begins from zero. When
2076 you will create more than one pcm instances, specify the
2077 different numbers in this argument. For example,
2078 <parameter>index</parameter> = 1 for the second PCM device.
2082 The fourth and fifth arguments are the number of substreams
2083 for playback and capture, respectively. Here both 1 are given in
2084 the above example. When no playback or no capture is available,
2085 pass 0 to the corresponding argument.
2089 If a chip supports multiple playbacks or captures, you can
2090 specify more numbers, but they must be handled properly in
2091 open/close, etc. callbacks. When you need to know which
2092 substream you are referring to, then it can be obtained from
2093 <type>snd_pcm_substream_t</type> data passed to each callback
2099 snd_pcm_substream_t *substream;
2100 int index = substream->number;
2107 After the pcm is created, you need to set operators for each
2113 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
2114 &snd_mychip_playback_ops);
2115 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
2116 &snd_mychip_capture_ops);
2123 The operators are defined typically like this:
2128 static snd_pcm_ops_t snd_mychip_playback_ops = {
2129 .open = snd_mychip_pcm_open,
2130 .close = snd_mychip_pcm_close,
2131 .ioctl = snd_pcm_lib_ioctl,
2132 .hw_params = snd_mychip_pcm_hw_params,
2133 .hw_free = snd_mychip_pcm_hw_free,
2134 .prepare = snd_mychip_pcm_prepare,
2135 .trigger = snd_mychip_pcm_trigger,
2136 .pointer = snd_mychip_pcm_pointer,
2142 Each of callbacks is explained in the subsection
2143 <link linkend="pcm-interface-operators"><citetitle>
2144 Operators</citetitle></link>.
2148 After setting the operators, most likely you'd like to
2149 pre-allocate the buffer. For the pre-allocation, simply call
2155 snd_pcm_lib_preallocate_pci_pages_for_all(chip->pci, pcm,
2161 It will allocate up to 64kB buffer as default. The details of
2162 buffer management will be described in the later section <link
2163 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2164 Management</citetitle></link>.
2168 Additionally, you can set some extra information for this pcm
2169 in pcm->info_flags.
2170 The available values are defined as
2171 <constant>SNDRV_PCM_INFO_XXX</constant> in
2172 <filename><sound/asound.h></filename>, which is used for
2173 the hardware definition (described later). When your soundchip
2174 supports only half-duplex, specify like this:
2179 pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2186 <section id="pcm-interface-destructor">
2187 <title>... And the Destructor?</title>
2189 The destructor for a pcm instance is not always
2190 necessary. Since the pcm device will be released by the middle
2191 layer code automatically, you don't have to call destructor
2196 The destructor would be necessary when you created some
2197 special records internally and need to release them. In such a
2198 case, set the destructor function to
2199 pcm->private_free:
2202 <title>PCM Instance with a Destructor</title>
2205 static void mychip_pcm_free(snd_pcm_t *pcm)
2207 mychip_t *chip = snd_magic_cast(mychip_t,
2208 pcm->private_data, return);
2209 // free your own data
2210 kfree(chip->my_private_pcm_data);
2211 // do what you like else...
2214 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2218 // allocate your own data
2219 chip->my_private_pcm_data = kmalloc(...);
2220 // set the destructor
2221 pcm->private_data = chip;
2222 pcm->private_free = mychip_pcm_free;
2231 <section id="pcm-interface-runtime">
2232 <title>Runtime Pointer - The Chest of PCM Information</title>
2234 When the PCM substream is opened, a PCM runtime instance is
2235 allocated and assigned to the substream. This pointer is
2236 accessible via <constant>substream->runtime</constant>.
2237 This runtime pointer holds the various information; it holds
2238 the copy of hw_params and sw_params configurations, the buffer
2239 pointers, mmap records, spinlocks, etc. Almost everyhing you
2240 need for controlling the PCM can be found there.
2244 The definition of runtime instance is found in
2245 <filename><sound/pcm.h></filename>. Here is the
2250 struct _snd_pcm_runtime {
2252 snd_pcm_substream_t *trigger_master;
2253 snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2255 snd_pcm_uframes_t avail_max;
2256 snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */
2257 snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2259 /* -- HW params -- */
2260 snd_pcm_access_t access; /* access mode */
2261 snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */
2262 snd_pcm_subformat_t subformat; /* subformat */
2263 unsigned int rate; /* rate in Hz */
2264 unsigned int channels; /* channels */
2265 snd_pcm_uframes_t period_size; /* period size */
2266 unsigned int periods; /* periods */
2267 snd_pcm_uframes_t buffer_size; /* buffer size */
2268 unsigned int tick_time; /* tick time */
2269 snd_pcm_uframes_t min_align; /* Min alignment for the format */
2271 unsigned int frame_bits;
2272 unsigned int sample_bits;
2274 unsigned int rate_num;
2275 unsigned int rate_den;
2277 /* -- SW params -- */
2278 int tstamp_timespec; /* use timeval (0) or timespec (1) */
2279 snd_pcm_tstamp_t tstamp_mode; /* mmap timestamp is updated */
2280 unsigned int period_step;
2281 unsigned int sleep_min; /* min ticks to sleep */
2282 snd_pcm_uframes_t xfer_align; /* xfer size need to be a multiple */
2283 snd_pcm_uframes_t start_threshold;
2284 snd_pcm_uframes_t stop_threshold;
2285 snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2286 noise is nearest than this */
2287 snd_pcm_uframes_t silence_size; /* Silence filling size */
2288 snd_pcm_uframes_t boundary; /* pointers wrap point */
2290 snd_pcm_uframes_t silenced_start;
2291 snd_pcm_uframes_t silenced_size;
2293 snd_pcm_sync_id_t sync; /* hardware synchronization ID */
2296 volatile snd_pcm_mmap_status_t *status;
2297 volatile snd_pcm_mmap_control_t *control;
2298 atomic_t mmap_count;
2300 /* -- locking / scheduling -- */
2302 wait_queue_head_t sleep;
2303 struct timer_list tick_timer;
2304 struct fasync_struct *fasync;
2306 /* -- private section -- */
2308 void (*private_free)(snd_pcm_runtime_t *runtime);
2310 /* -- hardware description -- */
2311 snd_pcm_hardware_t hw;
2312 snd_pcm_hw_constraints_t hw_constraints;
2314 /* -- interrupt callbacks -- */
2315 void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2316 void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2319 unsigned int timer_resolution; /* timer resolution */
2322 unsigned char *dma_area; /* DMA area */
2323 dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */
2324 size_t dma_bytes; /* size of DMA area */
2325 void *dma_private; /* private DMA data for the memory allocator */
2327 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2328 /* -- OSS things -- */
2329 snd_pcm_oss_runtime_t oss;
2338 For the operators (callbacks) of each sound driver, most of
2339 these records are supposed to be read-only. Only the PCM
2340 middle-layer changes / updates these info. The excpetions are
2341 the hardware description (hw), interrupt callbacks
2342 (transfer_ack_xxx), DMA buffer information, and the private
2343 data. Besides, if you use the standard buffer allocation
2344 method via <function>snd_pcm_lib_malloc_pages()</function>,
2345 you don't need to set the DMA buffer information by yourself.
2349 In the sections below, important records are explained.
2352 <section id="pcm-interface-runtime-hw">
2353 <title>Hardware Description</title>
2355 The hardware descriptor (<type>snd_pcm_hardware_t</type>)
2356 contains the definitions of the fundamental hardware
2357 configuration. Above all, you'll need to define this in
2358 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2359 the open callback</citetitle></link>.
2360 Note that the runtime instance holds the copy of the
2361 descriptor, not the pointer to the existing descriptor. That
2362 is, in the open callback, you can modify the copied descriptor
2363 (<constant>runtime->hw</constant>) as you need. For example, if the maximum
2364 number of channels is 1 only on some chip models, you can
2365 still use the same hardware descriptor and change the
2370 snd_pcm_runtime_t *runtime = substream->runtime;
2372 runtime->hw = snd_mychip_playback_hw; // common definition
2373 if (chip->model == VERY_OLD_ONE)
2374 runtime->hw.channels_max = 1;
2381 Typically, you'll have a hardware descriptor like below:
2385 static snd_pcm_hardware_t snd_mychip_playback_hw = {
2386 .info = (SNDRV_PCM_INFO_MMAP |
2387 SNDRV_PCM_INFO_INTERLEAVED |
2388 SNDRV_PCM_INFO_BLOCK_TRANSFER |
2389 SNDRV_PCM_INFO_MMAP_VALID),
2390 .formats = SNDRV_PCM_FMTBIT_S16_LE,
2391 .rates = SNDRV_PCM_RATE_8000_48000,
2396 .buffer_bytes_max = 32768,
2397 .period_bytes_min = 4096,
2398 .period_bytes_max = 32768,
2400 .periods_max = 1024,
2410 The <structfield>info</structfield> field contains the type and
2411 capabilities of this pcm. The bit flags are defined in
2412 <filename><sound/asound.h></filename> as
2413 <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2414 have to specify whether the mmap is supported and which
2415 interleaved format is supported.
2416 When the mmap is supported, add
2417 <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2418 hardware supports the interleaved or the non-interleaved
2419 format, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2420 <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2421 be set, respectively. If both are supported, you can set both,
2426 In the above example, <constant>MMAP_VALID</constant> and
2427 <constant>BLOCK_TRANSFER</constant> are specified for OSS mmap
2428 mode. Usually both are set. Of course,
2429 <constant>MMAP_VALID</constant> is set only if the mmap is
2434 The other possible flags are
2435 <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2436 <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2437 <constant>PAUSE</constant> bit means that the pcm supports the
2438 <quote>pause</quote> operation, while the
2439 <constant>RESUME</constant> bit means that the pcm supports
2440 the <quote>suspend/resume</quote> operation. If these flags
2441 are set, the <structfield>trigger</structfield> callback below
2442 must handle the corresponding commands.
2446 When the PCM substreams can be synchronized (typically,
2447 synchorinized start/stop of a playback and a capture streams),
2448 you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2449 too. In this case, you'll need to check the linked-list of
2450 PCM substreams in the trigger callback. This will be
2451 described in the later section.
2457 <structfield>formats</structfield> field contains the bit-flags
2458 of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2459 If the hardware supports more than one format, give all or'ed
2460 bits. In the example above, the signed 16bit little-endian
2461 format is specified.
2467 <structfield>rates</structfield> field contains the bit-flags of
2468 supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2469 When the chip supports continuous rates, pass
2470 <constant>CONTINUOUS</constant> bit additionally.
2471 The pre-defined rate bits are provided only for typical
2472 rates. If your chip supports unconventional rates, you need to add
2473 <constant>KNOT</constant> bit and set up the hardware
2474 constraint manually (explained later).
2480 <structfield>rate_min</structfield> and
2481 <structfield>rate_max</structfield> define the minimal and
2482 maximal sample rate. This should correspond somehow to
2483 <structfield>rates</structfield> bits.
2489 <structfield>channel_min</structfield> and
2490 <structfield>channel_max</structfield>
2491 define, as you might already expected, the minimal and maximal
2498 <structfield>buffer_bytes_max</structfield> defines the
2499 maximal buffer size in bytes. There is no
2500 <structfield>buffer_bytes_min</structfield> field, since
2501 it can be calculated from the minimal period size and the
2502 minimal number of periods.
2503 Meanwhile, <structfield>period_bytes_min</structfield> and
2504 define the minimal and maximal size of the period in bytes.
2505 <structfield>periods_max</structfield> and
2506 <structfield>periods_min</structfield> define the maximal and
2507 minimal number of periods in the buffer.
2511 The <quote>period</quote> is a term, that corresponds to
2512 fragment in the OSS world. The period defines the size at
2513 which the PCM interrupt is generated. This size strongly
2514 depends on the hardware.
2515 Generally, the smaller period size will give you more
2516 interrupts, that is, more controls.
2517 In the case of capture, this size defines the input latency.
2518 On the other hand, the whole buffer size defines the
2519 output latency for the playback direction.
2525 There is also a field <structfield>fifo_size</structfield>.
2526 This specifies the size of the hardware FIFO, but it's not
2527 used currently in the driver nor in the alsa-lib. So, you
2528 can ignore this field.
2535 <section id="pcm-interface-runtime-config">
2536 <title>PCM Configurations</title>
2538 Ok, let's go back again to the PCM runtime records.
2539 The most frequently referred records in the runtime instance are
2540 the PCM configurations.
2541 The PCM configurations are stored on runtime instance
2542 after the application sends <type>hw_params</type> data via
2543 alsa-lib. There are many fields copied from hw_params and
2544 sw_params structs. For example,
2545 <structfield>format</structfield> holds the format type
2546 chosen by the application. This field contains the enum value
2547 <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2551 One thing to be noted is that the configured buffer and period
2552 sizes are stored in <quote>frames</quote> in the runtime
2553 In the ALSA world, 1 frame = channels * samples-size.
2554 For conversion between frames and bytes, you can use the
2555 helper functions, <function>frames_to_bytes()</function> and
2556 <function>bytes_to_frames()</function>.
2560 period_bytes = frames_to_bytes(runtime, runtime->period_size);
2567 Also, many software parameters (sw_params) are
2568 stored in frames, too. Please check the type of the field.
2569 <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2570 integer while <type>snd_pcm_sframes_t</type> is for the frames
2575 <section id="pcm-interface-runtime-dma">
2576 <title>DMA Buffer Information</title>
2578 The DMA buffer is defined by the following four fields,
2579 <structfield>dma_area</structfield>,
2580 <structfield>dma_addr</structfield>,
2581 <structfield>dma_bytes</structfield> and
2582 <structfield>dma_private</structfield>.
2583 The <structfield>dma_area</structfield> holds the buffer
2584 pointer (the logical address). You can call
2585 <function>memcpy</function> from/to
2586 this pointer. Meanwhile, <structfield>dma_addr</structfield>
2587 holds the physical address of the buffer. This field is
2588 specified only when the buffer is a linear buffer.
2589 <structfield>dma_bytes</structfield> holds the size of buffer
2590 in bytes. <structfield>dma_private</structfield> is used for
2591 the ALSA DMA allocator.
2595 If you use a standard ALSA function,
2596 <function>snd_pcm_lib_malloc_pages()</function>, for
2597 allocating the buffer, these fields are set by the ALSA middle
2598 layer, and you should <emphasis>not</emphasis> change them by
2599 yourself. You can read them but not write them.
2600 On the other hand, if you want to allocate the buffer by
2601 yourself, you'll need to manage it in hw_params callback.
2602 At least, <structfield>dma_bytes</structfield> is mandatory.
2603 <structfield>dma_area</structfield> is necessary when the
2604 buffer is mmapped. If your driver doesn't support mmap, this
2605 field is not necessary. <structfield>dma_addr</structfield>
2606 is also not mandatory. You can use
2607 <structfield>dma_private</structfield> as you like, too.
2611 <section id="pcm-interface-runtime-status">
2612 <title>Running Status</title>
2614 The running status can be referred via <constant>runtime->status</constant>.
2615 This is the pointer to <type>snd_pcm_mmap_status_t</type>
2616 record. For example, you can get the current DMA hardware
2617 pointer via <constant>runtime->status->hw_ptr</constant>.
2621 The DMA application pointer can be referred via
2622 <constant>runtime->control</constant>, which points
2623 <type>snd_pcm_mmap_control_t</type> record.
2624 However, accessing directly to this value is not recommended.
2628 <section id="pcm-interface-runtime-private">
2629 <title>Private Data</title>
2631 You can allocate a record for the substream and store it in
2632 <constant>runtime->private_data</constant>. Usually, this
2634 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2635 the open callback</citetitle></link>.
2636 Since it's a void pointer, you should use magic-kmalloc and
2637 magic-cast for such an object.
2642 static int snd_xxx_open(snd_pcm_substream_t *substream)
2644 my_pcm_data_t *data;
2646 data = snd_magic_kmalloc(my_pcm_data_t, 0, GFP_KERNEL);
2647 substream->runtime->private_data = data;
2656 The allocated object must be released in
2657 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2658 the close callback</citetitle></link>.
2662 <section id="pcm-interface-runtime-intr">
2663 <title>Interrupt Callbacks</title>
2665 The field <structfield>transfer_ack_begin</structfield> and
2666 <structfield>transfer_ack_end</structfield> are called at
2667 the beginning and the end of
2668 <function>snd_pcm_period_elapsed()</function>, respectively.
2674 <section id="pcm-interface-operators">
2675 <title>Operators</title>
2677 OK, now let me explain the detail of each pcm callback
2678 (<parameter>ops</parameter>). In general, every callback must
2679 return 0 if successful, or a negative number with the error
2680 number such as <constant>-EINVAL</constant> at any
2685 The callback function takes at least the argument with
2686 <type>snd_pcm_substream_t</type> pointer. For retrieving the
2687 chip record from the given substream instance, you can use the
2693 #define chip_t mychip_t
2696 mychip_t *chip = snd_pcm_substream_chip(substream);
2705 It's expanded with a magic-cast, so the cast-error is
2706 automatically checked. You should define <type>chip_t</type> at
2707 the beginning of the code, since this will be referred in many
2708 places of pcm and control interfaces.
2711 <section id="pcm-interface-operators-open-callback">
2712 <title>open callback</title>
2717 static int snd_xxx_open(snd_pcm_substream_t *subs);
2722 This is called when a pcm substream is opened.
2726 At least, here you have to initialize the runtime->hw
2727 record. Typically, this is done by like this:
2732 static int snd_xxx_open(snd_pcm_substream_t *substream)
2734 mychip_t *chip = snd_pcm_substream_chip(substream);
2735 snd_pcm_runtime_t *runtime = substream->runtime;
2737 runtime->hw = snd_mychip_playback_hw;
2744 where <parameter>snd_mychip_playback_hw</parameter> is the
2745 pre-defined hardware description.
2749 You can allocate a private data in this callback, as described
2750 in <link linkend="pcm-interface-runtime-private"><citetitle>
2751 Private Data</citetitle></link> section.
2755 If the hardware configuration needs more constraints, set the
2756 hardware constraints here, too.
2757 See <link linkend="pcm-interface-constraints"><citetitle>
2758 Constraints</citetitle></link> for more details.
2762 <section id="pcm-interface-operators-close-callback">
2763 <title>close callback</title>
2768 static int snd_xxx_close(snd_pcm_substream_t *subs);
2773 Obviously, this is called when a pcm substream is closed.
2777 Any private instance for a pcm substream allocated in the
2778 open callback will be released here.
2783 static int snd_xxx_close(snd_pcm_substream_t *substream)
2786 snd_magic_kfree(substream->runtime->private_data);
2795 <section id="pcm-interface-operators-ioctl-callback">
2796 <title>ioctl callback</title>
2798 This is used for any special action to pcm ioctls. But
2799 usually you can pass a generic ioctl callback,
2800 <function>snd_pcm_lib_ioctl</function>.
2804 <section id="pcm-interface-operators-hw-params-callback">
2805 <title>hw_params callback</title>
2810 static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2811 snd_pcm_hw_params_t * hw_params);
2816 This and <structfield>hw_free</structfield> callbacks exist
2821 This is called when the hardware parameter
2822 (<structfield>hw_params</structfield>) is set
2823 up by the application,
2824 that is, once when the buffer size, the period size, the
2825 format, etc. are defined for the pcm substream.
2829 Many hardware set-up should be done in this callback,
2830 including the allocation of buffers.
2834 Parameters to be initialized are retrieved by
2835 <function>params_xxx()</function> macros. For allocating a
2836 buffer, you can call a helper function,
2841 snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2846 <function>snd_pcm_lib_malloc_pages()</function> is available
2847 only when the DMA buffers have been pre-allocated.
2848 See the section <link
2849 linkend="buffer-and-memory-buffer-types"><citetitle>
2850 Buffer Types</citetitle></link> for more details.
2854 Note that this and <structfield>prepare</structfield> callbacks
2855 may be called multiple times per initialization.
2856 For example, the OSS emulation may
2857 call these callbacks at each change via its ioctl.
2861 Thus, you need to take care not to allocate the same buffers
2862 many times, which will lead to memory leak! Calling the
2863 helper function above many times is OK. It will release the
2864 previous buffer automatically when it was already allocated.
2868 Another note is that this callback is non-atomic
2869 (schedulable). This is important, because the
2870 <structfield>prepare</structfield> callback
2871 is atomic (non-schedulable). That is, mutex or any
2872 schedule-related functions are available only in
2873 <structfield>hw_params</structfield> callback.
2874 Please see the subsection
2875 <link linkend="pcm-interface-atomicity"><citetitle>
2876 Atomicity</citetitle></link> for details.
2880 <section id="pcm-interface-operators-hw-free-callback">
2881 <title>hw_free callback</title>
2886 static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2893 This is called to release the resources allocated via
2894 <structfield>hw_params</structfield>. For example, releasing the
2896 <function>snd_pcm_lib_malloc_pages()</function> is done by
2897 calling the following:
2902 snd_pcm_lib_free_pages(substream);
2909 This function is always called before the close callback is called.
2910 Also, the callback may be called multiple times, too.
2911 Keep track whether the resource was already released.
2915 <section id="pcm-interface-operators-prepare-callback">
2916 <title>prepare callback</title>
2921 static int snd_xxx_prepare(snd_pcm_substream_t * substream);
2928 This callback is called when the pcm is
2929 <quote>prepared</quote>. You can set the format type, sample
2930 rate, etc. here. The difference from
2931 <structfield>hw_params</structfield> is that the
2932 <structfield>prepare</structfield> callback will be called at each
2934 <function>snd_pcm_prepare()</function> is called, i.e. when
2935 recovered after underruns, etc.
2939 As mentioned above, this callback is atomic.
2943 In this and the following callbacks, you can refer to the
2944 values via the runtime record,
2945 substream->runtime.
2946 For example, to get the current
2947 rate, format or channels, access to
2949 runtime->format or
2950 runtime->channels, respectively.
2951 The physical address of the allocated buffer is set to
2952 runtime->dma_area. The buffer and period sizes are
2953 in runtime->buffer_size and runtime->period_size,
2958 Be careful that this callback will be called many times at
2963 <section id="pcm-interface-operators-trigger-callback">
2964 <title>trigger callback</title>
2969 static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
2974 This is called when the pcm is started, stopped or paused.
2978 Which action is specified in the second argument,
2979 <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
2980 <filename><sound/pcm.h></filename>. At least,
2981 <constant>START</constant> and <constant>STOP</constant>
2982 commands must be defined in this callback.
2988 case SNDRV_PCM_TRIGGER_START:
2989 // do something to start the PCM engine
2991 case SNDRV_PCM_TRIGGER_STOP:
2992 // do something to stop the PCM engine
3003 When the pcm supports the pause operation (given in info
3004 field of the hardware table), <constant>PAUSE_PUSE</constant>
3005 and <constant>PAUSE_RELEASE</constant> commands must be
3006 handled here, too. The former is the command to pause the pcm,
3007 and the latter to restart the pcm again.
3011 When the pcm supports the suspend/resume operation
3012 (i.e. <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set),
3013 <constant>SUSPEND</constant> and <constant>RESUME</constant>
3014 commands must be handled, too.
3015 These commands are issued when the power-management status is
3016 changed. Obviously, the <constant>SUSPEND</constant> and
3017 <constant>RESUME</constant>
3018 do suspend and resume of the pcm substream, and usually, they
3019 are identical with <constant>STOP</constant> and
3020 <constant>START</constant> commands, respectively.
3024 This callback is also atomic.
3028 <section id="pcm-interface-operators-pointer-callback">
3029 <title>pointer callback</title>
3034 static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
3039 This callback is called when the PCM middle layer inquires
3040 the current hardware position on the buffer. The position must
3041 be returned in frames (which was in bytes on ALSA 0.5.x),
3042 ranged from 0 to buffer_size - 1.
3046 This is called usually from the buffer-update routine in the
3047 pcm middle layer, which is invoked when
3048 <function>snd_pcm_period_elapsed()</function> is called in the
3049 interrupt routine. Then the pcm middle layer updates the
3050 position and calculates the available space, and wakes up the
3051 sleeping poll threads, etc.
3055 This callback is also atomic.
3059 <section id="pcm-interface-operators-copy-silence">
3060 <title>copy and silence callbacks</title>
3062 These callbacks are not mandatory, and can be omitted in
3063 most cases. These callbacks are used when the hardware buffer
3064 cannot be on the normal memory space. Some chips have their
3065 own buffer on the hardware which is not mappable. In such a
3066 case, you have to transfer the data manually from the memory
3067 buffer to the hardware buffer. Or, if the buffer is
3068 non-contiguous on both physical and virtual memory spaces,
3069 these callbacks must be defined, too.
3073 If these two callbacks are defined, copy and set-silence
3074 operations are done by them. The detailed will be described in
3075 the later section <link
3076 linkend="buffer-and-memory"><citetitle>Buffer and Memory
3077 Management</citetitle></link>.
3081 <section id="pcm-interface-operators-ack">
3082 <title>ack callback</title>
3084 This callback is also not mandatory. This callback is called
3085 when the appl_ptr is updated in read or write operations.
3086 Some drivers like emu10k1-fx and cs46xx need to track the
3087 current appl_ptr for the internal buffer, and this callback
3088 is useful only for such a purpose.
3092 <section id="pcm-interface-operators-page-callback">
3093 <title>page callback</title>
3096 This callback is also not mandatory. This callback is used
3097 mainly for the non-contiguous buffer. The mmap calls this
3098 callback to get the page address. Some examples will be
3099 explained in the later section <link
3100 linkend="buffer-and-memory"><citetitle>Buffer and Memory
3101 Management</citetitle></link>, too.
3106 <section id="pcm-interface-interrupt-handler">
3107 <title>Interrupt Handler</title>
3109 The rest of pcm stuff is the PCM interrupt handler. The
3110 role of PCM interrupt handler in the sound driver is to update
3111 the buffer position and to tell the PCM middle layer when the
3112 buffer position goes across the prescribed period size. To
3113 inform this, call <function>snd_pcm_period_elapsed()</function>
3118 There are several types of sound chips to generate the interrupts.
3121 <section id="pcm-interface-interrupt-handler-boundary">
3122 <title>Interrupts at the period (fragment) boundary</title>
3124 This is the most frequently found type: the hardware
3125 generates an interrupt at each period boundary.
3126 In this case, you can call
3127 <function>snd_pcm_period_elapsed()</function> at each
3132 <function>snd_pcm_period_elapsed()</function> takes the
3133 substream pointer as its argument. Thus, you need to keep the
3134 substream pointer accessible from the chip instance. For
3135 example, define substream field in the chip record to hold the
3136 current running substream pointer, and set the pointer value
3137 at open callback (and reset at close callback).
3141 If you aquire a spinlock in the interrupt handler, and the
3142 lock is used in other pcm callbacks, too, then you have to
3143 release the lock before calling
3144 <function>snd_pcm_period_elapsed()</function>, because
3145 <function>snd_pcm_period_elapsed()</function> calls other pcm
3150 A typical coding would be like:
3153 <title>Interrupt Handler Case #1</title>
3156 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3157 struct pt_regs *regs)
3159 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3160 spin_lock(&chip->lock);
3162 if (pcm_irq_invoked(chip)) {
3163 // call updater, unlock before it
3164 spin_unlock(&chip->lock);
3165 snd_pcm_period_elapsed(chip->substream);
3166 spin_lock(&chip->lock);
3167 // acknowledge the interrupt if necessary
3170 spin_unlock(&chip->lock);
3179 <section id="pcm-interface-interrupt-handler-timer">
3180 <title>High-frequent timer interrupts</title>
3182 This is the case when the hardware doesn't generate interrupts
3183 at the period boundary but do timer-interrupts at the fixed
3184 timer rate (e.g. es1968 or ymfpci drivers).
3185 In this case, you need to check the current hardware
3186 position and accumulates the processed sample length at each
3187 interrupt. When the accumulated size overcomes the period
3189 <function>snd_pcm_period_elapsed()</function> and reset the
3194 A typical coding would be like the following.
3197 <title>Interrupt Handler Case #2</title>
3200 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3201 struct pt_regs *regs)
3203 mychip_t *chip = snd_magic_cast(mychip_t, dev_id, return);
3204 spin_lock(&chip->lock);
3206 if (pcm_irq_invoked(chip)) {
3207 unsigned int last_ptr, size;
3208 // get the current hardware pointer (in frames)
3209 last_ptr = get_hw_ptr(chip);
3210 // calculate the processed frames since the
3212 if (last_ptr < chip->last_ptr)
3213 size = runtime->buffer_size + last_ptr
3216 size = last_ptr - chip->last_ptr;
3217 // remember the last updated point
3218 chip->last_ptr = last_ptr;
3219 // accumulate the size
3221 // over the period boundary?
3222 if (chip->size >= runtime->period_size) {
3223 // reset the accumulator
3224 chip->size %= runtime->period_size;
3226 spin_unlock(&chip->lock);
3227 snd_pcm_period_elapsed(substream);
3228 spin_lock(&chip->lock);
3230 // acknowledge the interrupt if necessary
3233 spin_unlock(&chip->lock);
3242 <section id="pcm-interface-interrupt-handler-both">
3243 <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3245 In both cases, even if more than one period are elapsed, you
3247 <function>snd_pcm_period_elapsed()</function> many times. Call
3248 only once. And the pcm layer will check the current hardware
3249 pointer and update to the latest status.
3254 <section id="pcm-interface-atomicity">
3255 <title>Atomicity</title>
3257 One of the most important (and thus difficult to debug) problem
3258 on the kernel programming is the race condition.
3259 On linux kernel, usually it's solved via spin-locks or
3260 semaphores. In general, if the race condition may
3261 happen in the interrupt handler, it's handled as atomic, and you
3262 have to use spinlock for protecting the critical session. If it
3263 never happens in the interrupt and it may take relatively long
3264 time, you should use semaphore.
3268 As already seen, some pcm callbacks are atomic and some are
3269 not. For example, <parameter>hw_params</parameter> callback is
3270 non-atomic, while <parameter>prepare</parameter> callback is
3271 atomic. This means, the latter is called already in a spinlock
3272 held by the PCM middle layer. Please take this atomicity into
3273 account when you use a spinlock or a semaphore in the callbacks.
3277 In the atomic callbacks, you cannot use functions which may call
3278 <function>schedule</function> or go to
3279 <function>sleep</function>. The semaphore and mutex do sleep,
3280 and hence they cannot be used inside the atomic callbacks
3281 (e.g. <parameter>prepare</parameter> callback).
3282 For taking a certain delay in such a callback, please use
3283 <function>udelay()</function> or <function>mdelay()</function>.
3287 This atomicity problem appears also in the initialization of the
3288 hardware when the power-management is supported. The functions
3289 for suspending and resuming the chip must be atomic, i.e. no
3290 mutex nor sleep can be used in them.
3294 <section id="pcm-interface-constraints">
3295 <title>Constraints</title>
3297 If your chip supports unconventional sample rates, or only the
3298 limited samples, you need to set a constraint for the
3303 For example, in order to restrict the sample rates in the some
3304 supported values, use
3305 <function>snd_pcm_hw_constraint_list()</function>.
3306 You need to call this function in the open callback.
3309 <title>Example of Hardware Constraints</title>
3312 static unsigned int rates[] =
3313 {4000, 10000, 22050, 44100};
3314 static snd_pcm_hw_constraint_list_t constraints_rates = {
3315 .count = sizeof(rates) / sizeof(rates[0]),
3320 static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3324 err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3325 SNDRV_PCM_HW_PARAM_RATE,
3326 &constraints_rates);
3337 There are many different constraints.
3338 Look in <filename>sound/asound.h</filename> for a complete list.
3339 You can even define your own constraint rules.
3340 For example, let's suppose my_chip can manage a substream of 1 channel
3341 if and only if the format is S16_LE, otherwise it supports any format
3342 specified in the <type>snd_pcm_hardware_t</type> stucture (or in any
3343 other constraint_list). You can build a rule like this:
3346 <title>Example of Hardware Constraints for Channels</title>
3349 static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3350 snd_pcm_hw_rule_t *rule)
3352 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3353 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3356 snd_mask_any(&fmt); // Init the struct
3358 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3359 return snd_mask_refine(f, &fmt);
3369 Then you need to call this function to add your rule:
3374 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3375 hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3383 The rule function is called when an application sets the number of
3384 channels. But an application can set the format before the number of
3385 channels. Thus you also need to define the inverse rule:
3388 <title>Example of Hardware Constraints for Channels</title>
3391 static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3392 snd_pcm_hw_rule_t *rule)
3394 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3395 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3398 snd_interval_any(&ch);
3399 if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3400 ch.min = ch.max = 1;
3402 return snd_interval_refine(c, &ch);
3412 ...and in the open callback:
3416 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3417 hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3425 I won't explain more details here, rather I
3426 would like to say, <quote>Luke, use the source.</quote>
3433 <!-- ****************************************************** -->
3434 <!-- Control Interface -->
3435 <!-- ****************************************************** -->
3436 <chapter id="control-interface">
3437 <title>Control Interface</title>
3439 <section id="control-interface-general">
3440 <title>General</title>
3442 The control interface is used widely for many switches,
3443 sliders, etc. which are accessed from the user-space. Its most
3444 important use is the mixer interface. In other words, on ALSA
3445 0.9.x, all the mixer stuff is implemented on the control kernel
3446 API (while there was an independent mixer kernel API on 0.5.x).
3450 ALSA has a well-defined AC97 control module. If your chip
3451 supports only the AC97 and nothing else, you can skip this
3456 The control API is defined in
3457 <filename><sound/control.h></filename>.
3458 Include this file if you add your own controls.
3462 <section id="control-interface-definition">
3463 <title>Definition of Controls</title>
3465 For creating a new control, you need to define the three
3466 callbacks: <structfield>info</structfield>,
3467 <structfield>get</structfield> and
3468 <structfield>put</structfield>. Then, define a
3469 <type>snd_kcontrol_new_t</type> record, such as:
3472 <title>Definition of a Control</title>
3475 static snd_kcontrol_new_t my_control __devinitdata = {
3476 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3477 .name = "PCM Playback Switch",
3479 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3480 .private_values = 0xffff,
3481 .info = my_control_info,
3482 .get = my_control_get,
3483 .put = my_control_put
3491 Most likely the control is created via
3492 <function>snd_ctl_new1()</function>, and in such a case, you can
3493 add <parameter>__devinitdata</parameter> prefix to the
3494 definition like above.
3498 The <structfield>iface</structfield> field specifies the type of
3500 <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3501 <constant>MIXER</constant>, <constant>PCM</constant>,
3502 <constant>CARD</constant>, etc.
3506 The <structfield>name</structfield> is the name identifier
3507 string. On ALSA 0.9.x, the control name is very important,
3508 because its role is classified from its name. There are
3509 pre-defined standard control names. The details are described in
3511 <link linkend="control-interface-control-names"><citetitle>
3512 Control Names</citetitle></link>.
3516 The <structfield>index</structfield> field holds the index number
3517 of this control. If there are several different controls with
3518 the same name, they can be distinguished by the index
3519 number. This is the case when
3520 several codecs exist on the card. If the index is zero, you can
3521 omit the definition above.
3525 The <structfield>access</structfield> field contains the access
3526 type of this control. Give the combination of bit masks,
3527 <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.
3528 The detailed will be explained in the subsection
3529 <link linkend="control-interface-access-flags"><citetitle>
3530 Access Flags</citetitle></link>.
3534 The <structfield>private_values</structfield> field contains
3535 an arbitrary long integer value for this record. When using
3536 generic <structfield>info</structfield>,
3537 <structfield>get</structfield> and
3538 <structfield>put</structfield> callbacks, you can pass a value
3539 through this field. If several small numbers are necessary, you can
3540 combine them in bitwise. Or, it's possible to give a pointer
3541 (casted to unsigned long) of some record to this field, too.
3546 <link linkend="control-interface-callbacks"><citetitle>
3547 callback functions</citetitle></link>.
3551 <section id="control-interface-control-names">
3552 <title>Control Names</title>
3554 There are some standards for defining the control names. A
3555 control is usually defined from the three parts as
3556 <quote>SOURCE DIRECTION FUNCTION</quote>.
3560 The first, <constant>SOURCE</constant>, specifies the source
3561 of the control, and is a string such as <quote>Master</quote>,
3562 <quote>PCM</quote>, <quote>CD</quote> or
3563 <quote>Line</quote>. There are many pre-defined sources.
3567 The second, <constant>DIRECTION</constant>, is one of the
3568 following strings according to the direction of the control:
3569 <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass
3570 Playback</quote> and <quote>Bypass Capture</quote>. Or, it can
3571 be omitted, meaning both playback and capture directions.
3575 The third, <constant>FUNCTION</constant>, is one of the
3576 following strings according to the function of the control:
3577 <quote>Switch</quote>, <quote>Volume</quote> and
3578 <quote>Route</quote>.
3582 The example of control names are, thus, <quote>Master Capture
3583 Switch</quote> or <quote>PCM Playback Volume</quote>.
3587 There are some exceptions:
3590 <section id="control-interface-control-names-global">
3591 <title>Global capture and playback</title>
3593 <quote>Capture Source</quote>, <quote>Capture Switch</quote>
3594 and <quote>Capture Volume</quote> are used for the global
3595 capture (input) source, switch and volume. Similarly,
3596 <quote>Playback Switch</quote> and <quote>Playback
3597 Volume</quote> are used for the global output gain switch and
3602 <section id="control-interface-control-names-tone">
3603 <title>Tone-controls</title>
3605 tone-control switch and volumes are specified like
3606 <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -
3607 Switch</quote>, <quote>Tone Control - Bass</quote>,
3608 <quote>Tone Control - Center</quote>.
3612 <section id="control-interface-control-names-3d">
3613 <title>3D controls</title>
3615 3D-control switches and volumes are specified like <quote>3D
3616 Control - XXX</quote>, e.g. <quote>3D Control -
3617 Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D
3618 Control - Space</quote>.
3622 <section id="control-interface-control-names-mic">
3623 <title>Mic boost</title>
3625 Mic-boost switch is set as <quote>Mic Boost</quote> or
3626 <quote>Mic Boost (6dB)</quote>.
3630 More precise information can be found in
3631 <filename>alsa-kernel/Documentation/ControlNames.txt</filename>.
3636 <section id="control-interface-access-flags">
3637 <title>Access Flags</title>
3640 The access flag is the bit-flags which specifies the access type
3641 of the given control. The default access type is
3642 <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>,
3643 which means both read and write are allowed to this control.
3644 When the access flag is omitted (i.e. = 0), it is
3645 regarded as <constant>READWRITE</constant> access as default.
3649 When the control is read-only, pass
3650 <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.
3651 In this case, you don't have to define
3652 <structfield>put</structfield> callback.
3653 Similarly, when the control is write-only (although it's a rare
3654 case), you can use <constant>WRITE</constant> flag instead, and
3655 you don't need <structfield>get</structfield> callback.
3659 If the control value changes frequently (e.g. the VU meter),
3660 <constant>VOLATILE</constant> flag should be given. This means
3661 that the control may be changed without
3662 <link linkend="control-interface-change-notification"><citetitle>
3663 notification</citetitle></link>. Applications should poll such
3664 a control constantly.
3668 When the control is inactive, set
3669 <constant>INACTIVE</constant> flag, too.
3670 There are <constant>LOCK</constant> and
3671 <constant>OWNER</constant> flags for changing the write
3677 <section id="control-interface-callbacks">
3678 <title>Callbacks</title>
3680 <section id="control-interface-callbacks-info">
3681 <title>info callback</title>
3683 The <structfield>info</structfield> callback is used to get
3684 the detailed information of this control. This must store the
3685 values of the given <type>snd_ctl_elem_info_t</type>
3686 object. For example, for a boolean control with a single
3690 <title>Example of info callback</title>
3693 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3694 snd_ctl_elem_info_t *uinfo)
3696 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3698 uinfo->value.integer.min = 0;
3699 uinfo->value.integer.max = 1;
3708 The <structfield>type</structfield> field specifies the type
3709 of the control. There are <constant>BOOLEAN</constant>,
3710 <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,
3711 <constant>BYTES</constant>, <constant>IEC958</constant> and
3712 <constant>INTEGER64</constant>. The
3713 <structfield>count</structfield> field specifies the
3714 number of elements in this control. For example, a stereo
3715 volume would have count = 2. The
3716 <structfield>value</structfield> field is a union, and
3717 the values stored are depending on the type. The boolean and
3718 integer are identical.
3722 The enumerated type is a bit different from others. You'll
3723 need to set the string for the currently given item index.
3728 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3729 static char *texts[4] = {
3730 "First", "Second", "Third", "Fourth"
3732 uinfo->value.enumerated.items = 4;
3733 if (uinfo->value.enumerated.item > 3)
3734 uinfo->value.enumerated.item = 3;
3735 strcpy(uinfo->value.enumerated.name,
3736 texts[uinfo->value.enumerated.item]);
3743 <section id="control-interface-callbacks-get">
3744 <title>get callback</title>
3747 This callback is used to read the current value of the
3748 control and to return to the user-space.
3755 <title>Example of get callback</title>
3758 static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3759 snd_ctl_elem_value_t *ucontrol)
3761 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3762 ucontrol->value.integer.value[0] = get_some_value(chip);
3771 Here, the chip instance is retrieved via
3772 <function>snd_kcontrol_chip()</function> macro. This macro
3773 converts from kcontrol->private_data to the type defined by
3774 <type>chip_t</type>. The
3775 kcontrol->private_data field is
3776 given as the argument of <function>snd_ctl_new()</function>
3777 (see the later subsection
3778 <link linkend="control-interface-constructor"><citetitle>Constructor</citetitle></link>).
3782 The <structfield>value</structfield> field is depending on
3783 the type of control as well as on info callback. For example,
3784 the sb driver uses this field to store the register offset,
3785 the bit-shift and the bit-mask. The
3786 <structfield>private_value</structfield> is set like
3790 .private_value = reg | (shift << 16) | (mask << 24)
3794 and is retrieved in callbacks like
3798 static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3799 snd_ctl_elem_value_t *ucontrol)
3801 int reg = kcontrol->private_value & 0xff;
3802 int shift = (kcontrol->private_value >> 16) & 0xff;
3803 int mask = (kcontrol->private_value >> 24) & 0xff;
3812 In <structfield>get</structfield> callback, you have to fill all the elements if the
3813 control has more than one elements,
3814 i.e. <structfield>count</structfield> > 1.
3815 In the example above, we filled only one element
3816 (<structfield>value.integer.value[0]</structfield>) since it's
3817 assumed as <structfield>count</structfield> = 1.
3821 <section id="control-interface-callbacks-put">
3822 <title>put callback</title>
3825 This callback is used to write a value from the user-space.
3832 <title>Example of put callback</title>
3835 static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3836 snd_ctl_elem_value_t *ucontrol)
3838 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3840 if (chip->current_value !=
3841 ucontrol->value.integer.value[0]) {
3842 change_current_value(chip,
3843 ucontrol->value.integer.value[0]);
3852 As seen above, you have to return 1 if the value is
3853 changed. If the value is not changed, return 0 instead.
3854 If any fatal error happens, return a negative error code as
3859 Like <structfield>get</structfield> callback,
3860 when the control has more than one elements,
3861 all elemehts must be evaluated in this callback, too.
3865 <section id="control-interface-callbacks-all">
3866 <title>Callbacks are not atomic</title>
3868 All these three callbacks are basically not atomic.
3873 <section id="control-interface-constructor">
3874 <title>Constructor</title>
3876 When everything is ready, finally we can create a new
3877 control. For creating a control, there are two functions to be
3878 called, <function>snd_ctl_new1()</function> and
3879 <function>snd_ctl_add()</function>.
3883 In the simplest way, you can do like this:
3888 if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
3894 where <parameter>my_control</parameter> is the
3895 <type>snd_kcontrol_new_t</type> object defined above, and chip
3896 is the object pointer to be passed to
3897 kcontrol->private_data
3898 which can be referred in callbacks.
3902 <function>snd_ctl_new1()</function> allocates a new
3903 <type>snd_kcontrol_t</type> instance (that's why the definition
3904 of <parameter>my_control</parameter> can be with
3905 <parameter>__devinitdata</parameter>
3906 prefix), and <function>snd_ctl_add</function> assigns the given
3907 control component to the card.
3911 <section id="control-interface-change-notification">
3912 <title>Change Notification</title>
3914 If you need to change and update a control in the interrupt
3915 routine, you can call <function>snd_ctl_notify()</function>. For
3921 snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
3926 This function takes the card pointer, the event-mask, and the
3927 control id pointer for the notification. The event-mask
3928 specifies the types of notification, for example, in the above
3929 example, the change of control values is notified.
3930 The id pointer is the pointer of <type>snd_ctl_elem_id_t</type>
3932 You can find some examples in <filename>es1938.c</filename> or
3933 <filename>es1968.c</filename> for hardware volume interrupts.
3940 <!-- ****************************************************** -->
3941 <!-- API for AC97 Codec -->
3942 <!-- ****************************************************** -->
3943 <chapter id="api-ac97">
3944 <title>API for AC97 Codec</title>
3947 <title>General</title>
3949 The ALSA AC97 codec layer is a well-defined one, and you don't
3950 have to write many codes to control it. Only low-level control
3951 routines are necessary. The AC97 codec API is defined in
3952 <filename><sound/ac97_codec.h></filename>.
3956 <section id="api-ac97-example">
3957 <title>Full Code Example</title>
3960 <title>Example of AC97 Interface</title>
3969 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3972 mychip_t *chip = snd_magic_cast(mychip_t,
3973 ac97->private_data, return 0);
3975 // read a register value here from the codec
3976 return the_register_value;
3979 static void snd_mychip_ac97_write(ac97_t *ac97,
3980 unsigned short reg, unsigned short val)
3982 mychip_t *chip = snd_magic_cast(mychip_t,
3983 ac97->private_data, return 0);
3985 // write the given register value to the codec
3988 static int snd_mychip_ac97(mychip_t *chip)
3992 memset(&ac97, 0, sizeof(ac97));
3993 ac97.write = snd_mychip_ac97_write;
3994 ac97.read = snd_mychip_ac97_read;
3995 ac97.private_data = chip;
3996 return snd_ac97_mixer(card, &ac97, &chip->ac97);
4005 <section id="api-ac97-constructor">
4006 <title>Constructor</title>
4008 For creating an ac97 instance, call
4009 <function>snd_ac97_mixer()</function> with an <type>ac97_t</type>
4010 record, in which the callbacks and the private_data is set.
4018 memset(&ac97, 0, sizeof(ac97));
4019 ac97.write = snd_mychip_ac97_write;
4020 ac97.read = snd_mychip_ac97_read;
4021 ac97.private_data = chip;
4022 snd_ac97_mixer(card, &ac97, &chip->ac97);
4027 where chip->ac97 is the pointer of a newly created
4028 <type>ac97_t</type> instance.
4029 This instance is not necessarily stored in the chip
4030 record. When you need to change the register values from the
4031 driver, or need the suspend/resume of ac97 codecs, keep this
4032 pointer to pass to the corresponding functions.
4036 <section id="api-ac97-callbacks">
4037 <title>Callbacks</title>
4039 The standard callbacks are <structfield>read</structfield> and
4040 <structfield>write</structfield>. Obviously they
4041 correspond to the functions for read and write accesses to the
4042 hardware low-level codes.
4046 The <structfield>read</structfield> callback returns the
4047 register value specified in the argument.
4052 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
4055 mychip_t *chip = snd_magic_cast(mychip_t,
4056 ac97->private_data, return 0);
4058 return the_register_value;
4064 Here, the chip can be cast from ac97->private_data.
4068 Meanwhile, the <structfield>write</structfield> callback is
4069 used to set the register value.
4074 static void snd_mychip_ac97_write(ac97_t *ac97,
4075 unsigned short reg, unsigned short val)
4082 These callbacks are non-atomic like the callbacks of control API
4083 unless they are called during suspend/resume phase.
4087 There are also other callbacks:
4088 <structfield>reset</structfield>,
4089 <structfield>wait</structfield> and
4090 <structfield>init</structfield>.
4094 The <structfield>reset</structfield> callback is used to reset
4095 the codec. If the chip requires a special way of reset, you can
4096 define this callback.
4097 This callback must be atomic when it's called in the suspend
4102 The <structfield>wait</structfield> callback is used for a
4103 certain wait at the standard initialization of the codec. If the
4104 chip requires the extra wait-time, define this callback.
4105 This callback is always non-atomic, because it's never called
4110 The <structfield>init</structfield> callback is used for
4111 additional initialization of the codec. This callback is called
4112 after the reset, and should be atomic in the resume mode.
4116 <section id="api-ac97-updating-registers">
4117 <title>Updating Registers in The Driver</title>
4119 If you need to access to the codec from the driver, you can
4120 call the following functions:
4121 <function>snd_ac97_write()</function>,
4122 <function>snd_ac97_read()</function>,
4123 <function>snd_ac97_update()</function> and
4124 <function>snd_ac97_update_bits()</function>.
4128 Both <function>snd_ac97_write()</function> and
4129 <function>snd_ac97_update()</function> functions are used to
4130 set a value to the given register
4131 (<constant>AC97_XXX</constant>). The different between them is
4132 that <function>snd_ac97_update()</function> doesn't write a
4133 value if the given value has been already set, while
4134 <function>snd_ac97_write()</function> always rewrites the
4140 snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4141 snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4148 <function>snd_ac97_read()</function> is used to read the value
4149 of the given register. For example,
4154 value = snd_ac97_read(ac97, AC97_MASTER);
4161 <function>snd_ac97_update_bits()</function> is used to update
4162 some bits of the given register.
4167 snd_ac97_update_bits(ac97, reg, mask, value);
4174 Also, there is a function to change the sample rate (of a
4175 certain register such as
4176 <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA is
4177 supported by the codec:
4178 <function>snd_ac97_set_rate()</function>.
4183 snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
4190 The following registers are available for setting the rate:
4191 <constant>AC97_PCM_MIC_ADC_RATE</constant>,
4192 <constant>AC97_PCM_FRONT_DAC_RATE</constant>,
4193 <constant>AC97_PCM_LR_ADC_RATE</constant>,
4194 <constant>AC97_SPDIF</constant>. When the
4195 <constant>AC97_SPDIF</constant> is specified, the register is
4196 not really changed but the corresponding IEC958 status bits will
4201 <section id="api-ac97-clock-adjustment">
4202 <title>Clock Adjustment</title>
4204 On some chip, the clock of the codec isn't 48000 but using a
4205 PCI clock (to save a quartz!). In this case, change the field
4206 ac97->clock to the corresponding
4207 value. For example, intel8x0
4208 and es1968 drivers have the auto-measurement function of the
4213 <section id="api-ac97-proc-files">
4214 <title>Proc Files</title>
4216 The ALSA AC97 interface will create a proc file such as
4217 <filename>/proc/asound/card0/ac97#0</filename> and
4218 <filename>ac97#0regs</filename>. You can refer to these files to
4219 see the current status and registers of the codec.
4223 <section id="api-ac97-multiple-codecs">
4224 <title>Multiple Codecs</title>
4226 When there are several codecs on the same card, you need to
4227 call <function>snd_ac97_new()</function> multiple times with
4228 ac97.num=1 or greater. The <structfield>num</structfield> field
4234 If you have set up multiple codecs, you need to either write
4235 different callbacks for each codec or check
4244 <!-- ****************************************************** -->
4245 <!-- MIDI (MPU401-UART) Interface -->
4246 <!-- ****************************************************** -->
4247 <chapter id="midi-interface">
4248 <title>MIDI (MPU401-UART) Interface</title>
4250 <section id="midi-interface-general">
4251 <title>General</title>
4253 Many soundcards have built-in MIDI (MPU401-UART)
4254 interfaces. When the soundcard supports the standard MPU401-UART
4255 interface, most likely you can use the ALSA MPU401-UART API. The
4256 MPU401-UART API is defined in
4257 <filename><sound/mpu401.h></filename>.
4261 Some soundchips have similar but a little bit different
4262 implementation of mpu401 stuff. For example, emu10k1 has its own
4267 In this document, I won't explain the rawmidi interface API,
4268 which is the basis of MPU401-UART implementation.
4272 For details, please check the source,
4273 <filename>core/rawmidi.c</filename>, and examples such as
4274 <filename>drivers/mpu401/mpu401_uart.c</filename> or
4275 <filename>usb/usbmidi.c</filename>.
4279 <section id="midi-interface-constructor">
4280 <title>Constructor</title>
4282 For creating a rawmidi object, call
4283 <function>snd_mpu401_uart_new()</function>.
4288 snd_rawmidi_t *rmidi;
4289 snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4290 irq, irq_flags, &rmidi);
4297 The first argument is the card pointer, and the second is the
4298 index of this component. You can create up to 8 rawmidi
4303 The third argument is the type of the hardware,
4304 <constant>MPU401_HW_XXX</constant>. If it's not a special one,
4305 you can use <constant>MPU401_HW_MPU401</constant>.
4309 The 4th argument is the i/o port address. Many
4310 backward-compatible MPU401 has an i/o port such as 0x330. Or, it
4311 might be a part of its own PCI i/o region. It depends on the
4316 When the i/o port address above is a part of the PCI i/o
4317 region, the MPU401 i/o port might have been already allocated
4318 (reserved) by the driver itself. In such a case, pass non-zero
4320 (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4322 the mpu401-uart layer will allocate the i/o ports by itself.
4326 Usually, the port address corresponds to the command port and
4327 port + 1 corresponds to the data port. If not, you may change
4328 the <structfield>cport</structfield> field of
4329 <type>mpu401_t</type> manually
4330 afterward. However, <type>mpu401_t</type> pointer is not
4331 returned explicitly by
4332 <function>snd_mpu401_uart_new()</function>. You need to cast
4333 rmidi->private_data to
4334 <type>mpu401_t</type> explicitly,
4340 mpu = snd_magic_cast(mpu401_t, rmidi->private_data, );
4345 and reset the cport as you like:
4350 mpu->cport = my_own_control_port;
4357 The 6th argument specifies the irq number for UART. If the irq
4358 is already allocated, pass 0 to the 7th argument
4359 (<parameter>irq_flags</parameter>). Otherwise, pass the flags
4361 (<constant>SA_XXX</constant> bits) to it, and the irq will be
4362 reserved by the mpu401-uart layer. If the card doesn't generates
4363 UART interrupts, pass -1 as the irq number. Then a timer
4364 interrupt will be invoked for polling.
4368 <section id="midi-interface-interrupt-handler">
4369 <title>Interrupt Handler</title>
4371 When the interrupt is allocated in
4372 <function>snd_mpu401_uart_new()</function>, the private
4373 interrupt handler is used, hence you don't have to do nothing
4374 else than creating the mpu401 stuff. Otherwise, you have to call
4375 <function>snd_mpu401_uart_interrupt()</function> explicitly when
4376 a UART interrupt is invoked and checked in your own interrupt
4381 In this case, you need to pass the private_data of the
4382 returned rawmidi object from
4383 <function>snd_mpu401_uart_new()</function> as the second
4384 argument of <function>snd_mpu401_uart_interrupt()</function>.
4389 snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4399 <!-- ****************************************************** -->
4400 <!-- Miscellaneous Devices -->
4401 <!-- ****************************************************** -->
4402 <chapter id="misc-devices">
4403 <title>Miscellaneous Devices</title>
4405 <section id="misc-devices-opl3">
4406 <title>FM OPL3</title>
4408 The FM OPL3 is still used on many chips (mainly for backward
4409 compatibility). ALSA has a nice OPL3 FM control layer, too. The
4410 OPL3 API is defined in
4411 <filename><sound/opl3.h></filename>.
4415 FM registers can be directly accessed through direct-FM API,
4416 defined in <filename><sound/asound_fm.h></filename>. In
4417 ALSA native mode, FM registers are accessed through
4418 Hardware-Dependant Device direct-FM extension API, whereas in
4419 OSS compatible mode, FM registers can be accessed with OSS
4420 direct-FM compatible API on <filename>/dev/dmfmX</filename> device.
4424 For creating the OPL3 component, you have two functions to
4425 call. The first one is a constructor for <type>opl3_t</type>
4432 snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
4440 The first argument is the card pointer, the second one is the
4441 left port address, and the third is the right port address. In
4442 most cases, the right port is placed at the left port + 2.
4446 The fourth argument is the hardware type.
4450 When the left and right ports have been already allocated by
4451 the card driver, pass non-zero to the fifth argument
4452 (<parameter>integrated</parameter>). Otherwise, opl3 module will
4453 allocate the specified ports by itself.
4457 If this function returns successfully with 0, then create a
4458 hwdep device for this opl3.
4463 snd_hwdep_t *opl3hwdep;
4464 snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4471 The first argument is the <type>opl3_t</type> instance you
4472 created, and the second is the index number, usually 0.
4476 The third argument is the index-offset for the sequencer
4477 client assigned to the OPL3 port. When there is an MPU401-UART,
4478 give 1 for here (UART always takes 0).
4482 <section id="misc-devices-hardware-dependent">
4483 <title>Hardware-Dependent Devices</title>
4485 Some chips need the access from the user-space for special
4486 controls or for loading the micro code. In such a case, you can
4487 create a hwdep (hardware-dependent) device. The hwdep API is
4488 defined in <filename><sound/hwdep.h></filename>. You can
4489 find examples in opl3 driver or
4490 <filename>isa/sb/sb16_csp.c</filename>.
4494 Creation of the <type>hwdep</type> instance is done via
4495 <function>snd_hwdep_new()</function>.
4501 snd_hwdep_new(card, "My HWDEP", 0, &hw);
4506 where the third argument is the index number.
4510 You can then pass any pointer value to the
4511 <parameter>private_data</parameter>. Again, it should be a
4512 magic-allocated record, so that the cast can be checked more
4513 safely. If you assign a private data, you should define the
4514 destructor, too. The destructor function is set to
4515 <structfield>private_free</structfield> field.
4520 mydata_t *p = snd_magic_kmalloc(mydata_t, 0, GFP_KERNEL);
4521 hw->private_data = p;
4522 hw->private_free = mydata_free;
4527 and the implementation of destructor would be:
4532 static void mydata_free(snd_hwdep_t *hw)
4534 mydata_t *p = snd_magic_cast(mydata_csp_t,
4535 hw->private_data, return);
4544 The arbitrary file operations can be defined for this
4545 instance. The file operators are defined in
4546 <parameter>ops</parameter> table. For example, assume that
4547 this chip needs an ioctl.
4552 hw->ops.open = mydata_open;
4553 hw->ops.ioctl = mydata_ioctl;
4554 hw->ops.release = mydata_release;
4559 And implement the callback functions as you like.
4563 <section id="misc-devices-IEC958">
4564 <title>IEC958 (S/PDIF)</title>
4566 Usually the controls for IEC958 devices are implemented via
4567 control interface. There is a macro to compose a name string for
4568 IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>
4569 defined in <filename><include/asound.h></filename>.
4573 There are some standard controls for IEC958 status bits. These
4574 controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,
4575 and the size of element is fixed as 4 bytes array
4576 (value.iec958.status[x]). For <structfield>info</structfield>
4577 callback, you don't specify
4578 the value field for this type (the count field must be set,
4583 <quote>IEC958 Playback Con Mask</quote> is used to return the
4584 bit-mask for the IEC958 status bits of consumer mode. Similarly,
4585 <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for
4586 professional mode. They are read-only controls, and are defined
4587 as MIXER controls (iface =
4588 <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>).
4592 Meanwhile, <quote>IEC958 Playback Default</quote> control is
4593 defined for getting and setting the current default IEC958
4594 bits. Note that this one is usually defined as a PCM control
4595 (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),
4596 although in some places it's defined as a MIXER control.
4600 In addition, you can define the control switches to
4601 enable/disable or to set the raw bit mode. The implementation
4602 will depend on the chip, but the control should be named as
4603 <quote>IEC958 xxx</quote>, preferably using
4604 <function>SNDRV_CTL_NAME_IEC958()</function> macro.
4608 You can find several cases, for example,
4609 <filename>pci/emu10k1</filename>,
4610 <filename>pci/ice1712</filename>, or
4611 <filename>pci/cmipci.c</filename>.
4618 <!-- ****************************************************** -->
4619 <!-- Buffer and Memory Management -->
4620 <!-- ****************************************************** -->
4621 <chapter id="buffer-and-memory">
4622 <title>Buffer and Memory Management</title>
4624 <section id="buffer-and-memory-buffer-types">
4625 <title>Buffer Types</title>
4627 ALSA provides several different buffer allocation functions
4628 depending on the bus and the architecture. All these have a
4629 consistent API. The allocation of physically-contiguous pages is
4631 <function>snd_malloc_xxx_pages()</function> function, where xxx
4636 The allocation of pages with fallback is
4637 <function>snd_malloc_xxx_pages_fallback()</function>. This
4638 function tries to allocate the specified pages but if the pages
4639 are not available, it tries to reduce the page sizes until the
4640 enough space is found.
4644 For releasing the space, call
4645 <function>snd_free_xxx_pages()</function> function.
4649 Usually, ALSA drivers try to allocate and reserve
4650 a large contiguous physical space
4651 at the time the module is loaded for the later use.
4652 This is called <quote>pre-allocation</quote>.
4653 As already written, you can call the following function at the
4654 construction of pcm instance (in the case of PCI bus).
4659 snd_pcm_lib_preallocate_pci_pages_for_all(pci, pcm, size, max);
4664 where <parameter>size</parameter> is the byte size to be
4665 pre-allocated and the <parameter>max</parameter> is the maximal
4666 size to be changed via <filename>prealloc</filename> proc file.
4667 The allocator will try to get as the large area as possible
4668 within the given size.
4669 There are different versions of pre-allocator for different
4674 Once when the buffer is pre-allocated, you can use the
4675 allocator in the <structfield>hw_params</structfield> callback
4680 snd_pcm_lib_malloc_pages(substream, size);
4685 Note that you have to pre-allocate to use this function
4686 (i.e. you cannot use this function for
4687 <link linkend="buffer-and-memory-non-contiguous"><citetitle>
4688 a scatter-gather buffer</citetitle></link>).
4692 <section id="buffer-and-memory-external-hardware">
4693 <title>External Hardware Buffers</title>
4695 Some chips have their own hardware buffers and the DMA
4696 transfer from the host memory is not available. In such a case,
4697 you need to either 1) copy/set the audio data directly to the
4698 external hardware buffer, or 2) make an intermediate buffer and
4699 copy/set the data from it to the external hardware buffer in
4700 interrupts (or in tasklets, preferably).
4704 The first case works fine if the external hardware buffer is enough
4705 large. This method doesn't need any extra buffers and thus is
4706 more effective. You need to define the
4707 <structfield>copy</structfield> and
4708 <structfield>silence</structfield> callbacks for
4709 the data transfer. However, there is a drawback: it cannot
4710 be mmapped. The examples are GUS's GF1 PCM or emu8000's
4715 The second case allows the mmap of the buffer, although you have
4716 to handle an interrupt or a tasklet for transferring the data
4717 from the intermediate buffer to the hardware buffer. You can find an
4718 example in vxpocket driver.
4722 Another case is that the chip uses a PCI memory-map
4723 region for the buffer instead of the host memory. In this case,
4724 mmap is available only on certain architectures like intel. In
4725 non-mmap mode, the data cannot be transferred as the normal
4726 way. Thus you need to define <structfield>copy</structfield> and
4727 <structfield>silence</structfield> callbacks as well
4728 as in the cases above. The examples are found in
4729 <filename>rme32.c</filename> and <filename>rme96.c</filename>.
4733 The implementation of <structfield>copy</structfield> and
4734 <structfield>silence</structfield> callbacks depends upon
4735 whether the hardware supports interleaved or non-interleaved
4736 samples. The <structfield>copy</structfield> callback is
4737 defined like below, a bit
4738 differently depending whether the direction is playback or
4744 static int playback_copy(snd_pcm_substream_t *substream, int channel,
4745 snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);
4746 static int capture_copy(snd_pcm_substream_t *substream, int channel,
4747 snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);
4754 In the case of interleaved samples, the second argument
4755 (<parameter>channel</parameter>) is not used. The third argument
4756 (<parameter>pos</parameter>) points the
4757 current position offset in frames.
4761 The meaning of the fourth argument is different between
4762 playback and capture. For playback, it holds the source data
4763 pointer, and for capture, it's the destination data pointer.
4767 The last argument is the number of frames to be copied.
4771 What you have to do in this callback is again different
4772 between playback and capture directions. In the case of
4773 playback, you do: copy the given amount of data
4774 (<parameter>count</parameter>) at the specified pointer
4775 (<parameter>src</parameter>) to the specified offset
4776 (<parameter>pos</parameter>) on the hardware buffer. When
4777 coded like memcpy-like way, the copy would be like:
4782 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4783 frames_to_bytes(runtime, count));
4790 For the capture direction, you do: copy the given amount of
4791 data (<parameter>count</parameter>) at the specified offset
4792 (<parameter>pos</parameter>) on the hardware buffer to the
4793 specified pointer (<parameter>dst</parameter>).
4798 my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4799 frames_to_bytes(runtime, count));
4804 Note that both of the position and the data amount are given
4809 In the case of non-interleaved samples, the implementation
4810 will be a bit more complicated.
4814 You need to check the channel argument, and if it's -1, copy
4815 the whole channels. Otherwise, you have to copy only the
4816 specified channel. Please check
4817 <filename>isa/gus/gus_pcm.c</filename> as an example.
4821 The <structfield>silence</structfield> callback is also
4822 implemented in a similar way.
4827 static int silence(snd_pcm_substream_t *substream, int channel,
4828 snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
4835 The meanings of arguments are identical with the
4836 <structfield>copy</structfield>
4837 callback, although there is no <parameter>src/dst</parameter>
4838 argument. In the case of interleaved samples, the channel
4839 argument has no meaning, as well as on
4840 <structfield>copy</structfield> callback.
4844 The role of <structfield>silence</structfield> callback is to
4845 set the given amount
4846 (<parameter>count</parameter>) of silence data at the
4847 specified offset (<parameter>pos</parameter>) on the hardware
4848 buffer. Suppose that the data format is signed (that is, the
4849 silent-data is 0), and the implementation using a memset-like
4850 function would be like:
4855 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4856 frames_to_bytes(runtime, count));
4863 In the case of non-interleaved samples, again, the
4864 implementation becomes a bit more complicated. See, for example,
4865 <filename>isa/gus/gus_pcm.c</filename>.
4869 <section id="buffer-and-memory-non-contiguous">
4870 <title>Non-Contiguous Buffers</title>
4872 If your hardware supports the page table like emu10k1 or the
4873 buffer descriptors like via82xx, you can use the scatter-gather
4874 (SG) DMA. ALSA provides an interface for handling SG-buffers.
4875 The API is provided in <filename><sound/pcm_sgbuf.h></filename>.
4879 For creating the SG-buffer handler, call
4880 <function>snd_pcm_lib_preallocate_sg_pages()</function> or
4881 <function>snd_pcm_lib_preallocate_sg_pages_for_all()</function>
4882 in the PCM constructor like other PCI pre-allocator.
4883 You need to pass the
4884 <structname>pci_dev</structname> struct pointer of the chip.
4885 The <type>snd_sg_buf_t</type> instance is created as
4886 substream->dma_private. You can cast
4892 snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
4899 Then call <function>snd_pcm_lib_malloc_pages()</function>
4900 in <structfield>hw_params</structfield> callback
4901 as well as in the case of normal PCI buffer.
4902 The SG-buffer handler will allocate the non-contiguous kernel
4903 pages of the given size and map them onto the virtually contiguous
4904 memory. The virtual pointer is addressed in runtime->dma_area.
4905 The physical address (runtime->dma_addr) is set to zero,
4906 because the buffer is physically non-contigous.
4907 The physical address table is set up in sgbuf->table.
4908 You can get the physical address at a certain offset via
4909 <function>snd_pcm_sgbuf_get_addr()</function>.
4913 When a SG-handler is used, you need to set
4914 <function>snd_pcm_sgbuf_ops_page</function> as
4915 the <structfield>page</structfield> callback.
4919 For releasing the data, call
4920 <function>snd_pcm_lib_free_pages()</function> in the
4921 <structfield>hw_free</structfield> callback as usual.
4925 <section id="buffer-and-memory-vmalloced">
4926 <title>Vmalloc'ed Buffers</title>
4928 It's possible to use a buffer allocated via
4929 <function>vmalloc</function>, for example, for an intermediate
4930 buffer. Since the allocated pages are not contiguous, you need
4931 to set the <structfield>page</structfield> callback to obtain
4932 the physical address at every offset.
4936 The implementation of <structfield>page</structfield> callback
4942 #include <linux/vmalloc.h>
4944 /* get the physical page pointer on the given offset */
4945 static struct page *mychip_page(snd_pcm_substream_t *substream,
4946 unsigned long offset)
4948 void *pageptr = substream->runtime->dma_area + offset;
4949 return vmalloc_to_page(pageptr);
4960 <!-- ****************************************************** -->
4961 <!-- Proc Interface -->
4962 <!-- ****************************************************** -->
4963 <chapter id="proc-interface">
4964 <title>Proc Interface</title>
4966 ALSA provides an easy interface for procfs. The proc files are
4967 very useful for debugging. I recommend you set up proc files if
4968 you write a driver and want to get a running status or register
4969 dumps. The API is found in
4970 <filename><sound/info.h></filename>.
4974 For creating a proc file, call
4975 <function>snd_card_proc_new()</function>.
4980 snd_info_entry_t *entry;
4981 int err = snd_card_proc_new(card, "my-file", &entry);
4986 where the second argument specifies the proc-file name to be
4987 created. The above example will create a file
4988 <filename>my-file</filename> under the card directory,
4989 e.g. <filename>/proc/asound/card0/my-file</filename>.
4993 Like other components, the proc entry created via
4994 <function>snd_card_proc_new()</function> will be registered and
4995 released automatically in the card registration and release
5000 When the creation is successful, the function stores a new
5001 instance at the pointer given in the third argument.
5002 It is initialized as a text proc file for read only. For using
5003 this proc file as a read-only text file as it is, set the read
5004 callback with a private data via
5005 <function>snd_info_set_text_ops()</function>.
5010 snd_info_set_text_ops(entry, chip, my_proc_read);
5015 where the second argument (<parameter>chip</parameter>) is the
5016 private data to be used in the callbacks and the third
5017 (<parameter>my_proc_read</parameter>) is the callback function, which
5023 static void my_proc_read(snd_info_entry_t *entry,
5024 snd_info_buffer_t *buffer);
5032 In the read callback, use <function>snd_iprintf()</function> for
5033 output strings, which works just like normal
5034 <function>printf()</function>. For example,
5039 static void my_proc_read(snd_info_entry_t *entry,
5040 snd_info_buffer_t *buffer)
5042 chip_t *cm = snd_magic_cast(mychip_t,
5043 entry->private_data, return);
5045 snd_iprintf(buffer, "This is my chip!\n");
5046 snd_iprintf(buffer, "Port = %ld\n", chip->port);
5054 The file permission can be changed afterwards. As default, it's
5055 set as read only for all users. If you want to add the write
5056 permission to the user (root as default), set like below:
5061 entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
5066 and set the write buffer size and the callback
5071 entry->c.text.write_size = 256;
5072 entry->c.text.write = my_proc_write;
5079 The buffer size for read is set to 1024 implicitly by
5080 <function>snd_info_set_text_ops()</function>. It should suffice
5081 in most cases (the size will be aligned to
5082 <constant>PAGE_SIZE</constant> anyway), but if you need to handle
5083 very large text files, you can set it explicitly, too.
5088 entry->c.text.read_size = 65536;
5095 For the write callback, you can use
5096 <function>snd_info_get_line()</function> to get a text line, and
5097 <function>snd_info_get_str()</function> to retrieve a string from
5098 the line. Some examples are found in
5099 <filename>core/oss/mixer_oss.c</filename>, core/oss/and
5100 <filename>pcm_oss.c</filename>.
5104 For a raw-data proc-file, set the attributes like the following:
5109 static struct snd_info_entry_ops my_file_io_ops = {
5110 .read = my_file_io_read,
5113 entry->content = SNDRV_INFO_CONTENT_DATA;
5114 entry->private_data = chip;
5115 entry->c.ops = &my_file_io_ops;
5117 entry->mode = S_IFREG | S_IRUGO;
5124 The callback is much more complicated than the text-file
5125 version. You need to use a low-level i/o functions such as
5126 <function>copy_from/to_user()</function> to transfer the
5127 data. Also, you have to keep tracking the file position, too.
5132 static long my_file_io_read(snd_info_entry_t *entry,
5133 void *file_private_data,
5135 char *buf, long count)
5138 if (file->f_pos + size > local_max_size)
5139 size = local_max_size - file->f_pos;
5140 if (copy_to_user(buf, local_data + file->f_pos, size))
5142 file->f_pos += size;
5153 <!-- ****************************************************** -->
5154 <!-- Power Management -->
5155 <!-- ****************************************************** -->
5156 <chapter id="power-management">
5157 <title>Power Management</title>
5159 If the chip is supposed to work with with suspend/resume
5160 functions, you need to add the power-management codes to the
5161 driver. The additional codes for the power-management should be
5162 <function>ifdef</function>'ed with
5163 <constant>CONFIG_PM</constant>.
5167 Basic jobs of suspend/resume are done in
5168 <structfield>suspend</structfield> and
5169 <structfield>resume</structfield> callbacks of
5170 <structname>pci_driver</structname> struct. Unfortunately, the
5171 API of these callbacks was changed at the middle time of Linux
5172 2.4.x, if you want to keep the support for older kernels, you
5173 have to write two different callbacks. The example below is the
5174 skeleton callbacks which just call the real suspend and resume
5180 #ifndef PCI_OLD_SUSPEND
5181 static int snd_my_suspend(struct pci_dev *dev, u32 state)
5183 mychip_t *chip = snd_magic_cast(mychip_t,
5184 pci_get_drvdata(dev), return -ENXIO);
5185 mychip_suspend(chip);
5188 static int snd_my_resume(struct pci_dev *dev)
5190 mychip_t *chip = snd_magic_cast(mychip_t,
5191 pci_get_drvdata(dev), return -ENXIO);
5192 mychip_resume(chip);
5196 static void snd_my_suspend(struct pci_dev *dev)
5198 mychip_t *chip = snd_magic_cast(mychip_t,
5199 pci_get_drvdata(dev), return);
5200 mychip_suspend(chip);
5202 static void snd_mychip_resume(struct pci_dev *dev)
5204 mychip_t *chip = snd_magic_cast(mychip_t,
5205 pci_get_drvdata(dev), return);
5206 mychip_resume(chip);
5215 The scheme of the real suspend job is as following.
5218 <listitem><para>Check whether the power-state is already D3hot. If yes, skip the job.</para></listitem>
5219 <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>
5220 <listitem><para>Save the register values if necessary.</para></listitem>
5221 <listitem><para>Stop the hardware if necessary.</para></listitem>
5222 <listitem><para>Set the power-state as D3hot by calling <function>snd_power_change_state()</function>.</para></listitem>
5227 A typical code would be like:
5232 static void mychip_suspend(mychip_t *chip)
5234 snd_card_t *card = chip->card;
5236 if (card->power_state == SNDRV_CTL_POWER_D3hot)
5239 snd_pcm_suspend_all(chip->pcm);
5241 snd_mychip_save_registers(chip);
5243 snd_mychip_stop_hardware(chip);
5245 snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
5253 The scheme of the real resume job is as following.
5256 <listitem><para>Check whether the power-state is already D0.
5257 If yes, skip the job.</para></listitem>
5258 <listitem><para>Enable the pci device again by calling
5259 <function>pci_enable_device()</function>.</para></listitem>
5260 <listitem><para>Re-initialize the chip.</para></listitem>
5261 <listitem><para>Restore the saved registers if necessary.</para></listitem>
5262 <listitem><para>Resume the mixer, e.g. calling
5263 <function>snd_ac97_resume()</function>.</para></listitem>
5264 <listitem><para>Restart the hardware (if any).</para></listitem>
5265 <listitem><para>Set the power-state as D0 by calling
5266 <function>snd_power_change_state()</function>.</para></listitem>
5271 A typical code would be like:
5276 static void mychip_resume(mychip_t *chip)
5278 snd_card_t *card = chip->card;
5280 if (card->power_state == SNDRV_CTL_POWER_D0)
5283 pci_enable_device(chip->pci);
5285 snd_mychip_reinit_chip(chip);
5287 snd_mychip_restore_registers(chip);
5289 snd_ac97_resume(chip->ac97);
5291 snd_mychip_restart_chip(chip);
5293 snd_power_change_state(card, SNDRV_CTL_POWER_D0);
5301 In addition to the callbacks above, you should define a callback
5302 for the changes via the ALSA control interface. It's defined
5308 static int snd_mychip_set_power_state(snd_card_t *card,
5309 unsigned int power_state)
5311 mychip_t *chip = snd_magic_cast(mychip_t,
5312 card->power_state_private_data, return -ENXIO);
5313 switch (power_state) {
5314 case SNDRV_CTL_POWER_D0:
5315 case SNDRV_CTL_POWER_D1:
5316 case SNDRV_CTL_POWER_D2:
5317 mychip_resume(chip);
5319 case SNDRV_CTL_POWER_D3hot:
5320 case SNDRV_CTL_POWER_D3cold:
5321 mychip_suspend(chip);
5334 OK, we have all callbacks now. Let's set up them now. In the
5335 initialization of the card, add the following:
5340 static int __devinit snd_mychip_probe(struct pci_dev *pci,
5341 const struct pci_device_id *pci_id)
5347 card->set_power_state = snd_mychip_set_power_state;
5348 card->power_state_private_data = chip;
5358 If you need a space for saving the registers, you'll need to
5359 allocate the buffer for it here, too, since you cannot call
5360 <function>kmalloc()</function> with
5361 <constant>GFP_KERNEL</constant> flag or
5362 <function>vmalloc()</function> in the suspend callback.
5363 The allocated buffer should be released in the corresponding
5368 And next, set suspend/resume callbacks to the pci_driver,
5373 static struct pci_driver driver = {
5377 .suspend = snd_mychip_suspend,
5378 .resume = snd_mychip_resume,
5387 Last but not least: Please keep in mind that you cannot call
5388 <function>schedule()</function> during the suspend and the resume
5389 callbacks. If any delay is necessary, you have to use
5390 <function>mdelay()</function> or <function>udelay()</function>
5391 instead of <function>schedule_timeout()</function>!
5392 Of course, semaphores cannot be used, too, which will invoke sleep
5398 <!-- ****************************************************** -->
5399 <!-- Module Parameters -->
5400 <!-- ****************************************************** -->
5401 <chapter id="module-parameters">
5402 <title>Module Parameters</title>
5404 There are standard module options for ALSA. At least, each
5405 module should have <parameter>index</parameter>,
5406 <parameter>id</parameter> and <parameter>enable</parameter>
5411 If the module supports multiple cards (usually up to
5412 8 = <constant>SNDRV_CARDS</constant> cards), they should be
5413 arrays. The default initial values are defined already as
5414 constants for ease of programming:
5419 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
5420 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
5421 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
5428 If the module supports only a single card, they could be single
5429 variables, instead. <parameter>enable</parameter> option is not
5430 always necessary in this case, but it wouldn't be so bad to have a
5431 dummy option for compatibility.
5435 The module parameters must be declared with the standard
5436 <function>MODULE_PARM()</function> and
5437 <function>MODULE_PARM_DESC()</function> macros. The ALSA provides
5438 an additional macro, <function>MODULE_PARM_SYNTAX()</function>,
5439 for describing its syntax. The strings will be written to
5440 <filename>/lib/modules/XXX/modules.generic_string</filename>
5445 For convenience, the typical string arguments given to
5446 <function>MODULE_PARM_SYNTAX()</function> are defined in
5447 <filename><sound/initval.h></filename>, such as
5448 <constant>SNDRV_ID_DESC</constant> or
5449 <constant>SNDRV_ENABLED</constant>.
5453 The typical coding would be like below:
5458 #define CARD_NAME "My Chip"
5460 MODULE_PARM(index, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
5461 MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
5462 MODULE_PARM_SYNTAX(index, SNDRV_INDEX_DESC);
5463 MODULE_PARM(id, "1-" __MODULE_STRING(SNDRV_CARDS) "s");
5464 MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
5465 MODULE_PARM_SYNTAX(id, SNDRV_ID_DESC);
5466 MODULE_PARM(enable, "1-" __MODULE_STRING(SNDRV_CARDS) "i");
5467 MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
5468 MODULE_PARM_SYNTAX(enable, SNDRV_ENABLE_DESC);
5475 Also, don't forget to define the module description, classes,
5476 license and devices. Especially, the recent modprobe requires to
5477 define the module license as GPL, etc., otherwise the system is
5478 shown as <quote>tainted</quote>.
5483 MODULE_DESCRIPTION("My Chip");
5484 MODULE_CLASSES("{sound}");
5485 MODULE_LICENSE("GPL");
5486 MODULE_DEVICES("{{Vendor,My Chip Name}}");
5493 For building the driver into kernel, you should define the
5494 <function>setup()</function> function in addition, too.
5495 ALSA provides <function>get_id()</function> function to retrieve
5496 a string argument from the kernel boot parameters.
5503 /* format is: snd-mychip=enable,index,id */
5505 static int __init alsa_card_mychip_setup(char *str)
5507 static unsigned __initdata nr_dev = 0;
5509 if (nr_dev >= SNDRV_CARDS)
5511 (void)(get_option(&str,&enable[nr_dev]) == 2 &&
5512 get_option(&str,&index[nr_dev]) == 2 &&
5513 get_id(&str,&id[nr_dev]) == 2);
5518 __setup("snd-mychip=", alsa_card_mychip_setup);
5520 #endif /* ifndef MODULE */
5528 <!-- ****************************************************** -->
5529 <!-- How To Put Your Driver -->
5530 <!-- ****************************************************** -->
5531 <chapter id="how-to-put-your-driver">
5532 <title>How To Put Your Driver Into ALSA Tree</title>
5534 <title>General</title>
5536 So far, you've learned how to write the driver codes.
5537 And you might have a question now: how to put my own
5538 driver into the ALSA driver tree?
5539 Here (finally :) the standard procedure is described briefly.
5543 Suppose that you'll create a new PCI driver for the card
5544 <quote>xyz</quote>. The card module name would be
5545 snd-xyz. The new driver is usually put into alsa-driver
5546 tree. Then the driver is evaluated, audited and tested
5547 by developers and users. After a certain time, the driver
5548 will go to alsa-kernel tree and eventually integrated into
5553 In the following sections, the driver code is supposed
5554 to be put into alsa-driver tree. The two cases are assumed:
5555 a driver consisting of a single source file and one consisting
5556 of several source files.
5561 <title>Driver with A Single Source File</title>
5566 Modify alsa-driver/pci/Makefile
5570 Suppose you have a file xyz.c. Add the following
5575 snd-xyz-objs := xyz.o
5576 extra-obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5585 Modify alsa-driver/acore/Makefile
5589 Here define the dependent modules.
5593 obj-$(CONFIG_SND_XYZ) += snd.o ...
5598 If the driver supports PCM, snd-pcm.o,
5599 snd-timer.o and snd-page-alloc.o
5603 For rawmidi, snd-rawmidi.o is needed in addition.
5604 The MIDI stuff is also related to the sequencer.
5605 You'll need to modify alsa-driver/acore/seq/Makefile.
5609 For OPL3, snd-hwdep.o is needed, too.
5610 It's involved with the sequencer, and as well as rawmidi,
5611 you'll need to modify alsa-driver/acore/seq/Makefile
5612 and acore/seq/instr/Makefile in addition.
5613 Also, a new entry is necessary in
5614 alsa-driver/drivers/opl3/Makefile.
5621 Modify alsa-driver/utils/Modules.dep
5625 Add the module definition for configure, here.
5626 The beginning of the line must be a vertical bar, following
5627 the card module name (snd-xyz) and the list of its all
5633 %dir linux/sound/pci
5634 |snd-azt3328 snd-pcm snd-mpu401-uart snd-opl3-lib snd-opl3-synth
5635 |snd-xyz snd-pcm ...
5644 Run cvscompile script to re-generate the configure script and
5645 build the whole stuff again.
5653 <title>Drivers with Several Source Files</title>
5655 Suppose that the driver snd-xyz have several source files.
5656 They are located in the new subdirectory,
5662 Add a new directory (xyz) to extra-subdir-y list in alsa-driver/pci/Makefile
5667 extra-subdir-y := pdplus vx222 xyz
5676 Under the directory xyz, create a Makefile
5679 <title>Sample Makefile for a driver xyz</title>
5684 include $(TOPDIR)/toplevel.config
5685 include $(TOPDIR)/Makefile.conf
5687 TOPDIR = $(MAINSRCDIR)
5689 snd-xyz-objs := xyz.o abc.o def.o
5691 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5693 include $(TOPDIR)/Rules.make
5702 Modify alsa-driver/acore/Makefile
5706 This procedure is as same as in the last section.
5712 Modify alsa-driver/utils/Modules.dep
5719 %dir linux/sound/pci/xyz
5720 |snd-xyz snd-pcm ...
5729 Run cvscompile script to re-generate the configure script and
5730 build the whole stuff again.
5739 <!-- ****************************************************** -->
5740 <!-- Useful Functions -->
5741 <!-- ****************************************************** -->
5742 <chapter id="useful-functions">
5743 <title>Useful Functions</title>
5745 <section id="useful-functions-snd-printk">
5746 <title><function>snd_printk()</function> and friends</title>
5748 ALSA provides a verbose version of
5749 <function>printk()</function> function. If a kernel config
5750 <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this
5751 function prints the given message together with the file name
5752 and the line of the caller. The <constant>KERN_XXX</constant>
5753 prefix is processed as
5754 well as the original <function>printk()</function> does, so it's
5755 recommended to add this prefix, e.g.
5760 snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
5767 There are also <function>printk()</function>'s for
5768 debugging. <function>snd_printd()</function> can be used for
5769 general debugging purposes. If
5770 <constant>CONFIG_SND_DEBUG</constant> is set, this function is
5771 compiled, and works just like
5772 <function>snd_printk()</function>. If the ALSA is compiled
5773 without the debugging flag, it's ignored.
5777 <function>snd_printdd()</function> is compiled in only when
5778 <constant>CONFIG_SND_DEBUG_DETECT</constant> is set. Please note
5779 that <constant>DEBUG_DETECT</constant> is not set as default
5780 even if you configure the alsa-driver with
5781 <option>--with-debug=full</option> option. You need to give
5782 explicitly <option>--with-debug=detect</option> option instead.
5786 <section id="useful-functions-snd-assert">
5787 <title><function>snd_assert()</function></title>
5789 <function>snd_assert()</function> macro is similar with the
5790 normal <function>assert()</function> macro. For example,
5795 snd_assert(pointer != NULL, return -EINVAL);
5802 The first argument is the expression to evaluate, and the
5803 second argument is the action if it fails. When
5804 <constant>CONFIG_SND_DEBUG</constant>, is set, it will show an
5805 error message such as <computeroutput>BUG? (xxx) (called from
5806 yyy)</computeroutput>. When no debug flag is set, this is
5811 <section id="useful-functions-snd-runtime-check">
5812 <title><function>snd_runtime_check()</function></title>
5814 This macro is quite similar with
5815 <function>snd_assert()</function>. Unlike
5816 <function>snd_assert()</function>, the expression is always
5817 evaluated regardless of
5818 <constant>CONFIG_SND_DEBUG</constant>. When
5819 <constant>CONFIG_SND_DEBUG</constant> is set, the macro will
5820 show a message like <computeroutput>ERROR (xx) (called from
5821 yyy)</computeroutput>.
5825 <section id="useful-functions-snd-bug">
5826 <title><function>snd_BUG()</function></title>
5828 It calls <function>snd_assert(0,)</function> -- that is, just
5829 prints the error message at the point. It's useful to show that
5830 a fatal error happens there.
5836 <!-- ****************************************************** -->
5837 <!-- Acknowledgments -->
5838 <!-- ****************************************************** -->
5839 <chapter id="acknowledments">
5840 <title>Acknowledgments</title>
5842 I would like to thank Phil Kerr for his help for improvement and
5843 corrections of this document.
5846 Kevin Conder reformatted the original plain-text to the
5850 Giuliano Pochini corrected typos and contributed the example codes
5851 in the hardware constraints section.