1 <!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook V4.1//EN">
4 <?dbhtml filename="index.html">
6 <!-- ****************************************************** -->
8 <!-- ****************************************************** -->
10 <title>Writing an ALSA Driver</title>
12 <firstname>Takashi</firstname>
13 <surname>Iwai</surname>
16 <email>tiwai@suse.de</email>
21 <date>July 11, 2004</date>
22 <edition>0.3.3</edition>
26 This document describes how to write an ALSA (Advanced Linux
27 Sound Architecture) driver.
33 Copyright (c) 2002-2004 Takashi Iwai <email>tiwai@suse.de</email>
37 This document is free; you can redistribute it and/or modify it
38 under the terms of the GNU General Public License as published by
39 the Free Software Foundation; either version 2 of the License, or
40 (at your option) any later version.
44 This document is distributed in the hope that it will be useful,
45 but <emphasis>WITHOUT ANY WARRANTY</emphasis>; without even the
46 implied warranty of <emphasis>MERCHANTABILITY or FITNESS FOR A
47 PARTICULAR PURPOSE</emphasis>. See the GNU General Public License
52 You should have received a copy of the GNU General Public
53 License along with this program; if not, write to the Free
54 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,
61 <!-- ****************************************************** -->
63 <!-- ****************************************************** -->
64 <preface id="preface">
65 <title>Preface</title>
67 This document describes how to write an
68 <ulink url="http://www.alsa-project.org/"><citetitle>
69 ALSA (Advanced Linux Sound Architecture)</citetitle></ulink>
70 driver. The document focuses mainly on the PCI soundcard.
71 In the case of other device types, the API might
72 be different, too. However, at least the ALSA kernel API is
73 consistent, and therefore it would be still a bit help for
78 The target of this document is ones who already have enough
79 skill of C language and have the basic knowledge of linux
80 kernel programming. This document doesn't explain the general
81 topics of linux kernel codes and doesn't cover the detail of
82 implementation of each low-level driver. It describes only how is
83 the standard way to write a PCI sound driver on ALSA.
87 If you are already familiar with the older ALSA ver.0.5.x, you
88 can check the drivers such as <filename>es1938.c</filename> or
89 <filename>maestro3.c</filename> which have also almost the same
90 code-base in the ALSA 0.5.x tree, so you can compare the differences.
94 This document is still a draft version. Any feedbacks and
100 <!-- ****************************************************** -->
101 <!-- File Tree Structure -->
102 <!-- ****************************************************** -->
103 <chapter id="file-tree">
104 <title>File Tree Structure</title>
106 <section id="file-tree-general">
107 <title>General</title>
109 The ALSA drivers are provided in the two ways.
113 One is the the trees provided as a tarball or via cvs from the
114 ALSA's ftp site, and another is the 2.6 (or later) Linux kernel
115 tree. To synchronize both, the ALSA driver tree is split to
116 two different trees: alsa-kernel and alsa-driver. The former
117 contains purely the source codes for the Linux 2.6 (or later)
118 tree. This tree is designed only for compilation on 2.6 or
119 later environment. The latter, alsa-driver, contains many subtle
120 files for compiling the ALSA driver on the outside of Linux
121 kernel like configure script, the wrapper functions for older,
122 2.2 and 2.4 kernels, to adapt the latest kernel API,
123 and additional drivers which are still in development or in
124 tests. The drivers in alsa-driver tree will be moved to
125 alsa-kernel (eventually 2.6 kernel tree) once when they are
126 finished and confirmed to work fine.
130 The file tree structure of ALSA driver is depicted below. Both
131 alsa-kernel and alsa-driver have almost the same file
132 structure, except for <quote>core</quote> directory. It's
133 named as <quote>acore</quote> in alsa-driver tree.
136 <title>ALSA File Tree Structure</title>
168 <section id="file-tree-core-directory">
169 <title>core directory</title>
171 This directory contains the middle layer, that is, the heart
172 of ALSA drivers. In this directory, the native ALSA modules are
173 stored. The sub-directories contain different modules and are
174 dependent upon the kernel config.
177 <section id="file-tree-core-directory-oss">
178 <title>core/oss</title>
181 The codes for PCM and mixer OSS emulation modules are stored
182 in this directory. The rawmidi OSS emulation is included in
183 the ALSA rawmidi code since it's quite small. The sequencer
184 code is stored in core/seq/oss directory (see
185 <link linkend="file-tree-core-directory-seq-oss"><citetitle>
186 below</citetitle></link>).
190 <section id="file-tree-core-directory-ioctl32">
191 <title>core/ioctl32</title>
194 This directory contains the 32bit-ioctl wrappers for 64bit
195 architectures such like x86-64, ppc64 and sparc64. For 32bit
196 and alpha architectures, these are not compiled.
200 <section id="file-tree-core-directory-seq">
201 <title>core/seq</title>
203 This and its sub-directories are for the ALSA
204 sequencer. This directory contains the sequencer core and
205 primary sequencer modules such like snd-seq-midi,
206 snd-seq-virmidi, etc. They are compiled only when
207 <constant>CONFIG_SND_SEQUENCER</constant> is set in the kernel
212 <section id="file-tree-core-directory-seq-oss">
213 <title>core/seq/oss</title>
215 This contains the OSS sequencer emulation codes.
219 <section id="file-tree-core-directory-deq-instr">
220 <title>core/seq/instr</title>
222 This directory contains the modules for the sequencer
228 <section id="file-tree-include-directory">
229 <title>include directory</title>
231 This is the place for the public header files of ALSA drivers,
232 which are to be exported to the user-space, or included by
233 several files at different directories. Basically, the private
234 header files should not be placed in this directory, but you may
235 still find files there, due to historical reason :)
239 <section id="file-tree-drivers-directory">
240 <title>drivers directory</title>
242 This directory contains the codes shared among different drivers
243 on the different architectures. They are hence supposed not to be
244 architecture-specific.
245 For example, the dummy pcm driver and the serial MIDI
246 driver are found in this directory. In the sub-directories,
247 there are the codes for components which are independent from
248 bus and cpu architectures.
251 <section id="file-tree-drivers-directory-mpu401">
252 <title>drivers/mpu401</title>
254 The MPU401 and MPU401-UART modules are stored here.
258 <section id="file-tree-drivers-directory-opl3">
259 <title>drivers/opl3 and opl4</title>
261 The OPL3 and OPL4 FM-synth stuff is found here.
266 <section id="file-tree-i2c-directory">
267 <title>i2c directory</title>
269 This contains the ALSA i2c components.
273 Although there is a standard i2c layer on Linux, ALSA has its
274 own i2c codes for some cards, because the soundcard needs only a
275 simple operation and the standard i2c API is too complicated for
279 <section id="file-tree-i2c-directory-l3">
280 <title>i2c/l3</title>
282 This is a sub-directory for ARM L3 i2c.
287 <section id="file-tree-synth-directory">
288 <title>synth directory</title>
290 This contains the synth middle-level modules.
294 So far, there is only Emu8000/Emu10k1 synth driver under
295 synth/emux sub-directory.
299 <section id="file-tree-pci-directory">
300 <title>pci directory</title>
302 This and its sub-directories hold the top-level card modules
303 for PCI soundcards and the codes specific to the PCI BUS.
307 The drivers compiled from a single file is stored directly on
308 pci directory, while the drivers with several source files are
309 stored on its own sub-directory (e.g. emu10k1, ice1712).
313 <section id="file-tree-isa-directory">
314 <title>isa directory</title>
316 This and its sub-directories hold the top-level card modules
321 <section id="file-tree-arm-ppc-sparc-directories">
322 <title>arm, ppc, and sparc directories</title>
324 These are for the top-level card modules which are
325 specific to each given architecture.
329 <section id="file-tree-usb-directory">
330 <title>usb directory</title>
332 This contains the USB-audio driver. On the latest version, the
333 USB MIDI driver is integrated together with usb-audio driver.
337 <section id="file-tree-pcmcia-directory">
338 <title>pcmcia directory</title>
340 The PCMCIA, especially PCCard drivers will go here. CardBus
341 drivers will be on pci directory, because its API is identical
342 with the standard PCI cards.
346 <section id="file-tree-oss-directory">
347 <title>oss directory</title>
349 The OSS/Lite source files are stored here on Linux 2.6 (or
350 later) tree. (In the ALSA driver tarball, it's empty, of course :)
356 <!-- ****************************************************** -->
357 <!-- Basic Flow for PCI Drivers -->
358 <!-- ****************************************************** -->
359 <chapter id="basic-flow">
360 <title>Basic Flow for PCI Drivers</title>
362 <section id="basic-flow-outline">
363 <title>Outline</title>
365 The minimum flow of PCI soundcard is like the following:
368 <listitem><para>define the PCI ID table (see the section
369 <link linkend="pci-resource-entries"><citetitle>PCI Entries
370 </citetitle></link>).</para></listitem>
371 <listitem><para>create <function>probe()</function> callback.</para></listitem>
372 <listitem><para>create <function>remove()</function> callback.</para></listitem>
373 <listitem><para>create pci_driver table which contains the three pointers above.</para></listitem>
374 <listitem><para>create <function>init()</function> function just calling <function>pci_module_init()</function> to register the pci_driver table defined above.</para></listitem>
375 <listitem><para>create <function>exit()</function> function to call <function>pci_unregister_driver()</function> function.</para></listitem>
380 <section id="basic-flow-example">
381 <title>Full Code Example</title>
383 The code example is shown below. Some parts are kept
384 unimplemented at this moment but will be filled in the
385 succeeding sections. The numbers in comment lines of
386 <function>snd_mychip_probe()</function> function are the
390 <title>Basic Flow for PCI Drivers Example</title>
393 #include <sound/driver.h>
394 #include <linux/init.h>
395 #include <linux/pci.h>
396 #include <linux/slab.h>
397 #include <sound/core.h>
398 #include <sound/initval.h>
400 // module parameters (see "Module Parameters")
401 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
402 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
403 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
405 // definition of the chip-specific record
406 typedef struct snd_mychip mychip_t;
409 // rest of implementation will be in the section
410 // "PCI Resource Managements"
413 // chip-specific destructor
414 // (see "PCI Resource Managements")
415 static int snd_mychip_free(mychip_t *chip)
417 // will be implemented later...
420 // component-destructor
421 // (see "Management of Cards and Components")
422 static int snd_mychip_dev_free(snd_device_t *device)
424 mychip_t *chip = device->device_data;
425 return snd_mychip_free(chip);
428 // chip-specific constructor
429 // (see "Management of Cards and Components")
430 static int __devinit snd_mychip_create(snd_card_t *card,
436 static snd_device_ops_t ops = {
437 .dev_free = snd_mychip_dev_free,
442 // check PCI availability here
443 // (see "PCI Resource Managements")
445 // allocate a chip-specific data with zero filled
446 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
452 // rest of initialization here; will be implemented
453 // later, see "PCI Resource Managements"
455 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
457 snd_mychip_free(chip);
464 // constructor -- see "Constructor" sub-section
465 static int __devinit snd_mychip_probe(struct pci_dev *pci,
466 const struct pci_device_id *pci_id)
474 if (dev >= SNDRV_CARDS)
482 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
487 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
493 strcpy(card->driver, "My Chip");
494 strcpy(card->shortname, "My Own Chip 123");
495 sprintf(card->longname, "%s at 0x%lx irq %i",
496 card->shortname, chip->ioport, chip->irq);
502 if ((err = snd_card_register(card)) < 0) {
508 pci_set_drvdata(pci, card);
513 // destructor -- see "Destructor" sub-section
514 static void __devexit snd_mychip_remove(struct pci_dev *pci)
516 snd_card_free(pci_get_drvdata(pci));
517 pci_set_drvdata(pci, NULL);
525 <section id="basic-flow-constructor">
526 <title>Constructor</title>
528 The real constructor of PCI drivers is probe callback. The
529 probe callback and other component-constructors which are called
530 from probe callback should be defined with
531 <parameter>__devinit</parameter> prefix. You
532 cannot use <parameter>__init</parameter> prefix for them,
533 because any PCI device could be a hotplug device.
537 In the probe callback, the following scheme is often used.
540 <section id="basic-flow-constructor-device-index">
541 <title>1) Check and increment the device index.</title>
548 if (dev >= SNDRV_CARDS)
558 where enable[dev] is the module option.
562 At each time probe callback is called, check the
563 availability of the device. If not available, simply increment
564 the device index and returns. dev will be incremented also
566 linkend="basic-flow-constructor-set-pci"><citetitle>step
567 7</citetitle></link>).
571 <section id="basic-flow-constructor-create-card">
572 <title>2) Create a card instance</title>
579 card = snd_card_new(index[dev], id[dev], THIS_MODULE, 0);
586 The detail will be explained in the section
587 <link linkend="card-management-card-instance"><citetitle>
588 Management of Cards and Components</citetitle></link>.
592 <section id="basic-flow-constructor-create-main">
593 <title>3) Create a main component</title>
595 In this part, the PCI resources are allocated.
602 if ((err = snd_mychip_create(card, pci, &chip)) < 0) {
610 The detail will be explained in the section <link
611 linkend="pci-resource"><citetitle>PCI Resource
612 Managements</citetitle></link>.
616 <section id="basic-flow-constructor-main-component">
617 <title>4) Set the driver ID and name strings.</title>
622 strcpy(card->driver, "My Chip");
623 strcpy(card->shortname, "My Own Chip 123");
624 sprintf(card->longname, "%s at 0x%lx irq %i",
625 card->shortname, chip->ioport, chip->irq);
630 The driver field holds the minimal ID string of the
631 chip. This is referred by alsa-lib's configurator, so keep it
633 Even the same driver can have different driver IDs to
634 distinguish the functionality of each chip type.
638 The shortname field is a string shown as more verbose
639 name. The longname field contains the information which is
640 shown in <filename>/proc/asound/cards</filename>.
644 <section id="basic-flow-constructor-create-other">
645 <title>5) Create other components, such as mixer, MIDI, etc.</title>
647 Here you define the basic components such as
648 <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,
649 mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),
650 MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),
651 and other interfaces.
652 Also, if you want a <link linkend="proc-interface"><citetitle>proc
653 file</citetitle></link>, define it here, too.
657 <section id="basic-flow-constructor-register-card">
658 <title>6) Register the card instance.</title>
663 if ((err = snd_card_register(card)) < 0) {
673 Will be explained in the section <link
674 linkend="card-management-registration"><citetitle>Management
675 of Cards and Components</citetitle></link>, too.
679 <section id="basic-flow-constructor-set-pci">
680 <title>7) Set the PCI driver data and return zero.</title>
685 pci_set_drvdata(pci, card);
692 In the above, the card record is stored. This pointer is
693 referred in the remove callback and power-management
699 <section id="basic-flow-destructor">
700 <title>Destructor</title>
702 The destructor, remove callback, simply releases the card
703 instance. Then the ALSA middle layer will release all the
704 attached components automatically.
708 It would be typically like the following:
713 static void __devexit snd_mychip_remove(struct pci_dev *pci)
715 snd_card_free(pci_get_drvdata(pci));
716 pci_set_drvdata(pci, NULL);
722 The above code assumes that the card pointer is set to the PCI
727 <section id="basic-flow-header-files">
728 <title>Header Files</title>
730 For the above example, at least the following include files
736 #include <sound/driver.h>
737 #include <linux/init.h>
738 #include <linux/pci.h>
739 #include <linux/slab.h>
740 #include <sound/core.h>
741 #include <sound/initval.h>
746 where the last twos are necessary only when module options are
747 defined in the source file. If the codes are split to several
748 files, the file without module options don't need them.
752 In addition to them, you'll need
753 <filename><linux/interrupt.h></filename> for the interrupt
754 handling, and <filename><asm/io.h></filename> for the i/o
755 access. If you use <function>mdelay()</function> or
756 <function>udelay()</function> functions, you'll need to include
757 <filename><linux/delay.h></filename>, too.
761 The ALSA interfaces like PCM or control API are define in other
762 header files as <filename><sound/xxx.h></filename>.
763 They have to be included after
764 <filename><sound/core.h></filename>.
771 <!-- ****************************************************** -->
772 <!-- Management of Cards and Components -->
773 <!-- ****************************************************** -->
774 <chapter id="card-management">
775 <title>Management of Cards and Components</title>
777 <section id="card-management-card-instance">
778 <title>Card Instance</title>
780 For each soundcard, a <quote>card</quote> record must be allocated.
784 A card record is the headquarters of the soundcard. It manages
785 the list of whole devices (components) on the soundcard, such as
786 PCM, mixers, MIDI, synthesizer, and so on. Also, the card
787 record holds the ID and the name strings of the card, manages
788 the root of proc files, and controls the power-management states
789 and hotplug disconnections. The component list on the card
790 record is used to manage the proper releases of resources at
795 As mentioned above, to create a card instance, call
796 <function>snd_card_new()</function>.
802 card = snd_card_new(index, id, module, extra_size);
809 The function takes four arguments, the card-index number, the
810 id string, the module pointer (usually
811 <constant>THIS_MODULE</constant>),
812 and the size of extra-data space. The last argument is used to
813 allocate card->private_data for the
814 chip-specific data. Note that this data
815 <emphasis>is</emphasis> allocated by
816 <function>snd_card_new()</function>.
820 <section id="card-management-component">
821 <title>Components</title>
823 After the card is created, you can attach the components
824 (devices) to the card instance. On ALSA driver, a component is
825 represented as a <type>snd_device_t</type> object.
826 A component can be a PCM instance, a control interface, a raw
827 MIDI interface, etc. Each of such instances has one component
832 A component can be created via
833 <function>snd_device_new()</function> function.
838 snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
845 This takes the card pointer, the device-level
846 (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the
847 callback pointers (<parameter>&ops</parameter>). The
848 device-level defines the type of components and the order of
849 registration and de-registration. For most of components, the
850 device-level is already defined. For a user-defined component,
851 you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.
855 This function itself doesn't allocate the data space. The data
856 must be allocated manually beforehand, and its pointer is passed
857 as the argument. This pointer is used as the identifier
858 (<parameter>chip</parameter> in the above example) for the
863 Each ALSA pre-defined component such as ac97 or pcm calls
864 <function>snd_device_new()</function> inside its
865 constructor. The destructor for each component is defined in the
866 callback pointers. Hence, you don't need to take care of
867 calling a destructor for such a component.
871 If you would like to create your own component, you need to
872 set the destructor function to dev_free callback in
873 <parameter>ops</parameter>, so that it can be released
874 automatically via <function>snd_card_free()</function>. The
875 example will be shown later as an implementation of a
880 <section id="card-management-chip-specific">
881 <title>Chip-Specific Data</title>
883 The chip-specific information, e.g. the i/o port address, its
884 resource pointer, or the irq number, is stored in the
885 chip-specific record.
886 Usually, the chip-specific record is typedef'ed as
887 <type>xxx_t</type> like the following:
892 typedef struct snd_mychip mychip_t;
902 In general, there are two ways to allocate the chip record.
905 <section id="card-management-chip-specific-snd-card-new">
906 <title>1. Allocating via <function>snd_card_new()</function>.</title>
908 As mentioned above, you can pass the extra-data-length to the 4th argument of <function>snd_card_new()</function>, i.e.
913 card = snd_card_new(index[dev], id[dev], THIS_MODULE, sizeof(mychip_t));
918 whether <type>mychip_t</type> is the type of the chip record.
922 In return, the allocated record can be accessed as
927 mychip_t *chip = (mychip_t *)card->private_data;
932 With this method, you don't have to allocate twice.
933 The record is released together with the card instance.
937 <section id="card-management-chip-specific-allocate-extra">
938 <title>2. Allocating an extra device.</title>
941 After allocating a card instance via
942 <function>snd_card_new()</function> (with
943 <constant>NULL</constant> on the 4th arg), call
944 <function>kcalloc()</function>.
951 card = snd_card_new(index[dev], id[dev], THIS_MODULE, NULL);
953 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
960 The chip record should have the field to hold the card
976 Then, set the card pointer in the returned chip instance.
988 Next, initialize the fields, and register this chip
989 record as a low-level device with a specified
990 <parameter>ops</parameter>,
995 static snd_device_ops_t ops = {
996 .dev_free = snd_mychip_dev_free,
999 snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
1004 <function>snd_mychip_dev_free()</function> is the
1005 device-destructor function, which will call the real
1013 static int snd_mychip_dev_free(snd_device_t *device)
1015 mychip_t *chip = device->device_data;
1016 return snd_mychip_free(chip);
1022 where <function>snd_mychip_free()</function> is the real destructor.
1027 <section id="card-management-registration">
1028 <title>Registration and Release</title>
1030 After all components are assigned, register the card instance
1031 by calling <function>snd_card_register()</function>. The access
1032 to the device files are enabled at this point. That is, before
1033 <function>snd_card_register()</function> is called, the
1034 components are safely inaccessible from external side. If this
1035 call fails, exit the probe function after releasing the card via
1036 <function>snd_card_free()</function>.
1040 For releasing the card instance, you can call simply
1041 <function>snd_card_free()</function>. As already mentioned, all
1042 components are released automatically by this call.
1046 As further notes, the destructors (both
1047 <function>snd_mychip_dev_free</function> and
1048 <function>snd_mychip_free</function>) cannot be defined with
1049 <parameter>__devexit</parameter> prefix, because they may be
1050 called from the constructor, too, at the false path.
1054 For a device which allows hotplugging, you can use
1055 <function>snd_card_free_in_thread</function>. This one will
1056 postpone the destruction and wait in a kernel-thread until all
1065 <!-- ****************************************************** -->
1066 <!-- PCI Resource Managements -->
1067 <!-- ****************************************************** -->
1068 <chapter id="pci-resource">
1069 <title>PCI Resource Managements</title>
1071 <section id="pci-resource-example">
1072 <title>Full Code Example</title>
1074 In this section, we'll finish the chip-specific constructor,
1075 destructor and PCI entries. The example code is shown first,
1079 <title>PCI Resource Managements Example</title>
1084 struct pci_dev *pci;
1090 static int snd_mychip_free(mychip_t *chip)
1092 // disable hardware here if any
1093 // (not implemented in this document)
1097 free_irq(chip->irq, (void *)chip);
1098 // release the i/o ports
1099 pci_release_regions(chip->pci);
1105 // chip-specific constructor
1106 static int __devinit snd_mychip_create(snd_card_t *card,
1107 struct pci_dev *pci,
1112 static snd_device_ops_t ops = {
1113 .dev_free = snd_mychip_dev_free,
1118 // check PCI availability (28bit DMA)
1119 if ((err = pci_enable_device(pci)) < 0)
1121 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1122 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1123 printk(KERN_ERR "error to set 28bit mask DMA\n");
1127 chip = kcalloc(1, sizeof(*chip), GFP_KERNEL);
1131 // initialize the stuff
1136 // (1) PCI resource allocation
1137 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1141 chip->port = pci_resource_start(pci, 0);
1142 if (request_irq(pci->irq, snd_mychip_interrupt,
1143 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1145 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1146 snd_mychip_free(chip);
1149 chip->irq = pci->irq;
1151 // (2) initialization of the chip hardware
1152 // (not implemented in this document)
1154 if ((err = snd_device_new(card, SNDRV_DEV_LOWLEVEL,
1156 snd_mychip_free(chip);
1164 static struct pci_device_id snd_mychip_ids[] = {
1165 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1166 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1170 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1172 // pci_driver definition
1173 static struct pci_driver driver = {
1174 .name = "My Own Chip",
1175 .id_table = snd_mychip_ids,
1176 .probe = snd_mychip_probe,
1177 .remove = __devexit_p(snd_mychip_remove),
1180 // initialization of the module
1181 static int __init alsa_card_mychip_init(void)
1183 return pci_module_init(&driver);
1186 // clean up the module
1187 static void __exit alsa_card_mychip_exit(void)
1189 pci_unregister_driver(&driver);
1192 module_init(alsa_card_mychip_init)
1193 module_exit(alsa_card_mychip_exit)
1195 EXPORT_NO_SYMBOLS; /* for old kernels only */
1202 <section id="pci-resource-some-haftas">
1203 <title>Some Hafta's</title>
1205 The allocation of PCI resources is done in the
1206 <function>probe()</function> function, and usually an extra
1207 <function>xxx_create()</function> function is written for this
1212 In the case of PCI devices, you have to call at first
1213 <function>pci_enable_device()</function> function before
1214 allocating resources. Also, you need to set the proper PCI DMA
1215 mask to limit the accessed i/o range. In some cases, you might
1216 need to call <function>pci_set_master()</function> function,
1221 Suppose the 28bit mask, and the code to be added would be like:
1226 if ((err = pci_enable_device(pci)) < 0)
1228 if (pci_set_dma_mask(pci, 0x0fffffff) < 0 ||
1229 pci_set_consistent_dma_mask(pci, 0x0fffffff) < 0) {
1230 printk(KERN_ERR "error to set 28bit mask DMA\n");
1240 <section id="pci-resource-resource-allocation">
1241 <title>Resource Allocation</title>
1243 The allocation of I/O ports and irqs are done via standard kernel
1244 functions. Unlike ALSA ver.0.5.x., there are no helpers for
1245 that. And these resources must be released in the destructor
1246 function (see below). Also, on ALSA 0.9.x, you don't need to
1247 allocate (pseudo-)DMA for PCI like ALSA 0.5.x.
1251 Now assume that this PCI device has an I/O port with 8 bytes
1252 and an interrupt. Then <type>mychip_t</type> will have the
1270 For an i/o port (and also a memory region), you need to have
1271 the resource pointer for the standard resource management. For
1272 an irq, you have to keep only the irq number (integer). But you
1273 need to initialize this number as -1 before actual allocation,
1274 since irq 0 is valid. The port address and its resource pointer
1275 can be initialized as null by
1276 <function>kcalloc()</function> automatically, so you
1277 don't have to take care of resetting them.
1281 The allocation of an i/o port is done like this:
1286 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1290 chip->port = pci_resource_start(pci, 0);
1297 It will reserve the i/o port region of 8 bytes of the given
1298 PCI device. The returned value, chip->res_port, is allocated
1299 via <function>kmalloc()</function> by
1300 <function>request_region()</function>. The pointer must be
1301 released via <function>kfree()</function>, but there is some
1302 problem regarding this. This issue will be explained more below.
1306 The allocation of an interrupt source is done like this:
1311 if (request_irq(pci->irq, snd_mychip_interrupt,
1312 SA_INTERRUPT|SA_SHIRQ, "My Chip",
1314 printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
1315 snd_mychip_free(chip);
1318 chip->irq = pci->irq;
1323 where <function>snd_mychip_interrupt()</function> is the
1324 interrupt handler defined <link
1325 linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.
1326 Note that chip->irq should be defined
1327 only when <function>request_irq()</function> succeeded.
1331 On the PCI bus, the interrupts can be shared. Thus,
1332 <constant>SA_SHIRQ</constant> is given as the interrupt flag of
1333 <function>request_irq()</function>.
1337 The last argument of <function>request_irq()</function> is the
1338 data pointer passed to the interrupt handler. Usually, the
1339 chip-specific record is used for that, but you can use what you
1344 I won't define the detail of the interrupt handler at this
1345 point, but at least its appearance can be explained now. The
1346 interrupt handler looks usually like the following:
1351 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
1352 struct pt_regs *regs)
1354 mychip_t *chip = dev_id;
1364 Now let's write the corresponding destructor for the resources
1365 above. The role of destructor is simple: disable the hardware
1366 (if already activated) and release the resources. So far, we
1367 have no hardware part, so the disabling is not written here.
1371 For releasing the resources, <quote>check-and-release</quote>
1372 method is a safer way. For the interrupt, do like this:
1378 free_irq(chip->irq, (void *)chip);
1383 Since the irq number can start from 0, you should initialize
1384 chip->irq with a negative value (e.g. -1), so that you can
1385 check the validity of the irq number as above.
1389 When you requested I/O ports or memory regions via
1390 <function>pci_request_region()</function> or
1391 <function>pci_request_regions()</function> like this example,
1392 release the resource(s) using the corresponding function,
1393 <function>pci_release_region()</function> or
1394 <function>pci_release_regions()</function>.
1399 pci_release_regions(chip->pci);
1406 When you requested manually via <function>request_region()</function>
1407 or <function>request_mem_region</function>, you can release it via
1408 <function>release_resource()</function>. Suppose that you keep
1409 the resource pointer returned from <function>request_region()</function>
1410 in chip->res_port, the release procedure looks like below:
1415 if (chip->res_port) {
1416 release_resource(chip->res_port);
1417 kfree_nocheck(chip->res_port);
1423 As you can see, the resource pointer is also to be freed
1424 via <function>kfree_nocheck()</function> after
1425 <function>release_resource()</function> is called. You
1426 cannot use <function>kfree()</function> here, because on ALSA,
1427 <function>kfree()</function> may be a wrapper to its own
1428 allocator with the memory debugging. Since the resource pointer
1429 is allocated externally outside the ALSA, it must be released
1431 <function>kfree()</function>.
1432 <function>kfree_nocheck()</function> is used for that; it calls
1433 the native <function>kfree()</function> without wrapper.
1437 And finally, release the chip-specific record.
1449 Again, remember that you cannot
1450 set <parameter>__devexit</parameter> prefix for this destructor.
1454 We didn't implement the hardware-disabling part in the above.
1455 If you need to do this, please note that the destructor may be
1456 called even before the initialization of the chip is completed.
1457 It would be better to have a flag to skip the hardware-disabling
1458 if the hardware was not initialized yet.
1462 When the chip-data is assigned to the card using
1463 <function>snd_device_new()</function> with
1464 <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is
1465 called at the last. that is, it is assured that all other
1466 components like PCMs and controls have been already released.
1467 You don't have to call stopping PCMs, etc. explicitly, but just
1468 stop the hardware in the low-level.
1472 The management of a memory-mapped region is almost as same as
1473 the management of an i/o port. You'll need three fields like
1481 unsigned long iobase_phys;
1482 unsigned long iobase_virt;
1488 and the allocation would be (assuming its size is 512 bytes):
1493 if ((err = pci_request_regions(pci, "My Chip")) < 0) {
1497 chip->iobase_phys = pci_resource_start(pci, 0);
1498 chip->iobase_virt = (unsigned long)
1499 ioremap_nocache(chip->iobase_phys,
1500 pci_resource_len(pci, 0));
1505 and the corresponding destructor would be:
1510 static int snd_mychip_free(mychip_t *chip)
1513 if (chip->iobase_virt)
1514 iounmap((void *)chip->iobase_virt);
1516 pci_release_regions(chip->pci);
1526 <section id="pci-resource-entries">
1527 <title>PCI Entries</title>
1529 So far, so good. Let's finish the rest of missing PCI
1530 stuffs. At first, we need a
1531 <structname>pci_device_id</structname> table for this
1532 chipset. It's a table of PCI vendor/device ID number, and some
1542 static struct pci_device_id snd_mychip_ids[] = {
1543 { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
1544 PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
1548 MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
1555 The first and second fields of
1556 <structname>pci_device_id</structname> struct are the vendor and
1557 device IDs. If you have nothing special to filter the matching
1558 devices, you can use the rest of fields like above. The last
1559 field of <structname>pci_device_id</structname> struct is a
1560 private data for this entry. You can specify any value here, for
1561 example, to tell the type of different operations per each
1562 device IDs. Such an example is found in intel8x0 driver.
1566 The last entry of this list is the terminator. You must
1567 specify this all-zero entry.
1571 Then, prepare the <structname>pci_driver</structname> record:
1576 static struct pci_driver driver = {
1577 .name = "My Own Chip",
1578 .id_table = snd_mychip_ids,
1579 .probe = snd_mychip_probe,
1580 .remove = __devexit_p(snd_mychip_remove),
1588 The <structfield>probe</structfield> and
1589 <structfield>remove</structfield> functions are what we already
1591 the previous sections. The <structfield>remove</structfield> should
1593 <function>__devexit_p()</function> macro, so that it's not
1594 defined for built-in (and non-hot-pluggable) case. The
1595 <structfield>name</structfield>
1596 field is the name string of this device. Note that you must not
1597 use a slash <quote>/</quote> in this string.
1601 And at last, the module entries:
1606 static int __init alsa_card_mychip_init(void)
1608 return pci_module_init(&driver);
1611 static void __exit alsa_card_mychip_exit(void)
1613 pci_unregister_driver(&driver);
1616 module_init(alsa_card_mychip_init)
1617 module_exit(alsa_card_mychip_exit)
1624 Note that these module entries are tagged with
1625 <parameter>__init</parameter> and
1626 <parameter>__exit</parameter> prefixes, not
1627 <parameter>__devinit</parameter> nor
1628 <parameter>__devexit</parameter>.
1632 Oh, one thing was forgotten. If you have no exported symbols,
1633 you need to declare it on 2.2 or 2.4 kernels (on 2.6 kernels
1634 it's not necessary, though).
1650 <!-- ****************************************************** -->
1651 <!-- PCM Interface -->
1652 <!-- ****************************************************** -->
1653 <chapter id="pcm-interface">
1654 <title>PCM Interface</title>
1656 <section id="pcm-interface-general">
1657 <title>General</title>
1659 The PCM middle layer of ALSA is quite powerful and it is only
1660 necessary for each driver to implement the low-level functions
1661 to access its hardware.
1665 For accessing to the PCM layer, you need to include
1666 <filename><sound/pcm.h></filename> above all. In addition,
1667 <filename><sound/pcm_params.h></filename> might be needed
1668 if you access to some functions related with hw_param.
1672 Each card device can have up to four pcm instances. A pcm
1673 instance corresponds to a pcm device file. The limitation of
1674 number of instances comes only from the available bit size of
1675 the linux's device number. Once when 64bit device number is
1676 used, we'll have more available pcm instances.
1680 A pcm instance consists of pcm playback and capture streams,
1681 and each pcm stream consists of one or more pcm substreams. Some
1682 soundcard supports the multiple-playback function. For example,
1683 emu10k1 has a PCM playback of 32 stereo substreams. In this case, at
1684 each open, a free substream is (usually) automatically chosen
1685 and opened. Meanwhile, when only one substream exists and it was
1686 already opened, the succeeding open will result in the blocking
1687 or the error with <constant>EAGAIN</constant> according to the
1688 file open mode. But you don't have to know the detail in your
1689 driver. The PCM middle layer will take all such jobs.
1693 <section id="pcm-interface-example">
1694 <title>Full Code Example</title>
1696 The example code below does not include any hardware access
1697 routines but shows only the skeleton, how to build up the PCM
1701 <title>PCM Example Code</title>
1704 #include <sound/pcm.h>
1707 /* hardware definition */
1708 static snd_pcm_hardware_t snd_mychip_playback_hw = {
1709 .info = (SNDRV_PCM_INFO_MMAP |
1710 SNDRV_PCM_INFO_INTERLEAVED |
1711 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1712 SNDRV_PCM_INFO_MMAP_VALID),
1713 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1714 .rates = SNDRV_PCM_RATE_8000_48000,
1719 .buffer_bytes_max = 32768,
1720 .period_bytes_min = 4096,
1721 .period_bytes_max = 32768,
1723 .periods_max = 1024,
1726 /* hardware definition */
1727 static snd_pcm_hardware_t snd_mychip_capture_hw = {
1728 .info = (SNDRV_PCM_INFO_MMAP |
1729 SNDRV_PCM_INFO_INTERLEAVED |
1730 SNDRV_PCM_INFO_BLOCK_TRANSFER |
1731 SNDRV_PCM_INFO_MMAP_VALID),
1732 .formats = SNDRV_PCM_FMTBIT_S16_LE,
1733 .rates = SNDRV_PCM_RATE_8000_48000,
1738 .buffer_bytes_max = 32768,
1739 .period_bytes_min = 4096,
1740 .period_bytes_max = 32768,
1742 .periods_max = 1024,
1746 static int snd_mychip_playback_open(snd_pcm_substream_t *substream)
1748 mychip_t *chip = snd_pcm_substream_chip(substream);
1749 snd_pcm_runtime_t *runtime = substream->runtime;
1751 runtime->hw = snd_mychip_playback_hw;
1752 // more hardware-initialization will be done here
1756 /* close callback */
1757 static int snd_mychip_playback_close(snd_pcm_substream_t *substream)
1759 mychip_t *chip = snd_pcm_substream_chip(substream);
1760 // the hardware-specific codes will be here
1766 static int snd_mychip_capture_open(snd_pcm_substream_t *substream)
1768 mychip_t *chip = snd_pcm_substream_chip(substream);
1769 snd_pcm_runtime_t *runtime = substream->runtime;
1771 runtime->hw = snd_mychip_capture_hw;
1772 // more hardware-initialization will be done here
1776 /* close callback */
1777 static int snd_mychip_capture_close(snd_pcm_substream_t *substream)
1779 mychip_t *chip = snd_pcm_substream_chip(substream);
1780 // the hardware-specific codes will be here
1785 /* hw_params callback */
1786 static int snd_mychip_pcm_hw_params(snd_pcm_substream_t *substream,
1787 snd_pcm_hw_params_t * hw_params)
1789 return snd_pcm_lib_malloc_pages(substream,
1790 params_buffer_bytes(hw_params));
1793 /* hw_free callback */
1794 static int snd_mychip_pcm_hw_free(snd_pcm_substream_t *substream)
1796 return snd_pcm_lib_free_pages(substream);
1799 /* prepare callback */
1800 static int snd_mychip_pcm_prepare(snd_pcm_substream_t *substream)
1802 mychip_t *chip = snd_pcm_substream_chip(substream);
1803 snd_pcm_runtime_t *runtime = substream->runtime;
1805 // set up the hardware with the current configuration
1807 mychip_set_sample_format(chip, runtime->format);
1808 mychip_set_sample_rate(chip, runtime->rate);
1809 mychip_set_channels(chip, runtime->channels);
1810 mychip_set_dma_setup(chip, runtime->dma_area,
1816 /* trigger callback */
1817 static int snd_mychip_pcm_trigger(snd_pcm_substream_t *substream,
1821 case SNDRV_PCM_TRIGGER_START:
1822 // do something to start the PCM engine
1824 case SNDRV_PCM_TRIGGER_STOP:
1825 // do something to stop the PCM engine
1832 /* pointer callback */
1833 static snd_pcm_uframes_t
1834 snd_mychip_pcm_pointer(snd_pcm_substream_t *substream)
1836 mychip_t *chip = snd_pcm_substream_chip(substream);
1837 unsigned int current_ptr;
1839 // get the current hardware pointer
1840 current_ptr = mychip_get_hw_pointer(chip);
1845 static snd_pcm_ops_t snd_mychip_playback_ops = {
1846 .open = snd_mychip_playback_open,
1847 .close = snd_mychip_playback_close,
1848 .ioctl = snd_pcm_lib_ioctl,
1849 .hw_params = snd_mychip_pcm_hw_params,
1850 .hw_free = snd_mychip_pcm_hw_free,
1851 .prepare = snd_mychip_pcm_prepare,
1852 .trigger = snd_mychip_pcm_trigger,
1853 .pointer = snd_mychip_pcm_pointer,
1857 static snd_pcm_ops_t snd_mychip_capture_ops = {
1858 .open = snd_mychip_capture_open,
1859 .close = snd_mychip_capture_close,
1860 .ioctl = snd_pcm_lib_ioctl,
1861 .hw_params = snd_mychip_pcm_hw_params,
1862 .hw_free = snd_mychip_pcm_hw_free,
1863 .prepare = snd_mychip_pcm_prepare,
1864 .trigger = snd_mychip_pcm_trigger,
1865 .pointer = snd_mychip_pcm_pointer,
1869 * definitions of capture are omitted here...
1872 /* create a pcm device */
1873 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
1878 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
1881 pcm->private_data = chip;
1882 strcpy(pcm->name, "My Chip");
1885 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1886 &snd_mychip_playback_ops);
1887 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
1888 &snd_mychip_capture_ops);
1889 /* pre-allocation of buffers */
1890 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
1891 snd_dma_pci_data(chip->pci),
1901 <section id="pcm-interface-constructor">
1902 <title>Constructor</title>
1904 A pcm instance is allocated <function>snd_pcm_new()</function>
1905 function. It would be better to create a constructor for pcm,
1911 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
1916 if ((err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1,
1919 pcm->private_data = chip;
1920 strcpy(pcm->name, "My Chip");
1931 The <function>snd_pcm_new()</function> function takes the four
1932 arguments. The first argument is the card pointer to which this
1933 pcm is assigned, and the second is the ID string.
1937 The third argument (<parameter>index</parameter>, 0 in the
1938 above) is the index of this new pcm. It begins from zero. When
1939 you will create more than one pcm instances, specify the
1940 different numbers in this argument. For example,
1941 <parameter>index</parameter> = 1 for the second PCM device.
1945 The fourth and fifth arguments are the number of substreams
1946 for playback and capture, respectively. Here both 1 are given in
1947 the above example. When no playback or no capture is available,
1948 pass 0 to the corresponding argument.
1952 If a chip supports multiple playbacks or captures, you can
1953 specify more numbers, but they must be handled properly in
1954 open/close, etc. callbacks. When you need to know which
1955 substream you are referring to, then it can be obtained from
1956 <type>snd_pcm_substream_t</type> data passed to each callback
1962 snd_pcm_substream_t *substream;
1963 int index = substream->number;
1970 After the pcm is created, you need to set operators for each
1976 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
1977 &snd_mychip_playback_ops);
1978 snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
1979 &snd_mychip_capture_ops);
1986 The operators are defined typically like this:
1991 static snd_pcm_ops_t snd_mychip_playback_ops = {
1992 .open = snd_mychip_pcm_open,
1993 .close = snd_mychip_pcm_close,
1994 .ioctl = snd_pcm_lib_ioctl,
1995 .hw_params = snd_mychip_pcm_hw_params,
1996 .hw_free = snd_mychip_pcm_hw_free,
1997 .prepare = snd_mychip_pcm_prepare,
1998 .trigger = snd_mychip_pcm_trigger,
1999 .pointer = snd_mychip_pcm_pointer,
2005 Each of callbacks is explained in the subsection
2006 <link linkend="pcm-interface-operators"><citetitle>
2007 Operators</citetitle></link>.
2011 After setting the operators, most likely you'd like to
2012 pre-allocate the buffer. For the pre-allocation, simply call
2018 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
2019 snd_dma_pci_data(chip->pci),
2025 It will allocate up to 64kB buffer as default. The details of
2026 buffer management will be described in the later section <link
2027 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2028 Management</citetitle></link>.
2032 Additionally, you can set some extra information for this pcm
2033 in pcm->info_flags.
2034 The available values are defined as
2035 <constant>SNDRV_PCM_INFO_XXX</constant> in
2036 <filename><sound/asound.h></filename>, which is used for
2037 the hardware definition (described later). When your soundchip
2038 supports only half-duplex, specify like this:
2043 pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
2050 <section id="pcm-interface-destructor">
2051 <title>... And the Destructor?</title>
2053 The destructor for a pcm instance is not always
2054 necessary. Since the pcm device will be released by the middle
2055 layer code automatically, you don't have to call destructor
2060 The destructor would be necessary when you created some
2061 special records internally and need to release them. In such a
2062 case, set the destructor function to
2063 pcm->private_free:
2066 <title>PCM Instance with a Destructor</title>
2069 static void mychip_pcm_free(snd_pcm_t *pcm)
2071 mychip_t *chip = snd_pcm_chip(pcm);
2072 // free your own data
2073 kfree(chip->my_private_pcm_data);
2074 // do what you like else...
2077 static int __devinit snd_mychip_new_pcm(mychip_t *chip)
2081 // allocate your own data
2082 chip->my_private_pcm_data = kmalloc(...);
2083 // set the destructor
2084 pcm->private_data = chip;
2085 pcm->private_free = mychip_pcm_free;
2094 <section id="pcm-interface-runtime">
2095 <title>Runtime Pointer - The Chest of PCM Information</title>
2097 When the PCM substream is opened, a PCM runtime instance is
2098 allocated and assigned to the substream. This pointer is
2099 accessible via <constant>substream->runtime</constant>.
2100 This runtime pointer holds the various information; it holds
2101 the copy of hw_params and sw_params configurations, the buffer
2102 pointers, mmap records, spinlocks, etc. Almost everyhing you
2103 need for controlling the PCM can be found there.
2107 The definition of runtime instance is found in
2108 <filename><sound/pcm.h></filename>. Here is the
2113 struct _snd_pcm_runtime {
2115 snd_pcm_substream_t *trigger_master;
2116 snd_timestamp_t trigger_tstamp; /* trigger timestamp */
2118 snd_pcm_uframes_t avail_max;
2119 snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */
2120 snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
2122 /* -- HW params -- */
2123 snd_pcm_access_t access; /* access mode */
2124 snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */
2125 snd_pcm_subformat_t subformat; /* subformat */
2126 unsigned int rate; /* rate in Hz */
2127 unsigned int channels; /* channels */
2128 snd_pcm_uframes_t period_size; /* period size */
2129 unsigned int periods; /* periods */
2130 snd_pcm_uframes_t buffer_size; /* buffer size */
2131 unsigned int tick_time; /* tick time */
2132 snd_pcm_uframes_t min_align; /* Min alignment for the format */
2134 unsigned int frame_bits;
2135 unsigned int sample_bits;
2137 unsigned int rate_num;
2138 unsigned int rate_den;
2140 /* -- SW params -- */
2141 int tstamp_timespec; /* use timeval (0) or timespec (1) */
2142 snd_pcm_tstamp_t tstamp_mode; /* mmap timestamp is updated */
2143 unsigned int period_step;
2144 unsigned int sleep_min; /* min ticks to sleep */
2145 snd_pcm_uframes_t xfer_align; /* xfer size need to be a multiple */
2146 snd_pcm_uframes_t start_threshold;
2147 snd_pcm_uframes_t stop_threshold;
2148 snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
2149 noise is nearest than this */
2150 snd_pcm_uframes_t silence_size; /* Silence filling size */
2151 snd_pcm_uframes_t boundary; /* pointers wrap point */
2153 snd_pcm_uframes_t silenced_start;
2154 snd_pcm_uframes_t silenced_size;
2156 snd_pcm_sync_id_t sync; /* hardware synchronization ID */
2159 volatile snd_pcm_mmap_status_t *status;
2160 volatile snd_pcm_mmap_control_t *control;
2161 atomic_t mmap_count;
2163 /* -- locking / scheduling -- */
2165 wait_queue_head_t sleep;
2166 struct timer_list tick_timer;
2167 struct fasync_struct *fasync;
2169 /* -- private section -- */
2171 void (*private_free)(snd_pcm_runtime_t *runtime);
2173 /* -- hardware description -- */
2174 snd_pcm_hardware_t hw;
2175 snd_pcm_hw_constraints_t hw_constraints;
2177 /* -- interrupt callbacks -- */
2178 void (*transfer_ack_begin)(snd_pcm_substream_t *substream);
2179 void (*transfer_ack_end)(snd_pcm_substream_t *substream);
2182 unsigned int timer_resolution; /* timer resolution */
2185 unsigned char *dma_area; /* DMA area */
2186 dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */
2187 size_t dma_bytes; /* size of DMA area */
2188 void *dma_private; /* private DMA data for the memory allocator */
2190 #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
2191 /* -- OSS things -- */
2192 snd_pcm_oss_runtime_t oss;
2201 For the operators (callbacks) of each sound driver, most of
2202 these records are supposed to be read-only. Only the PCM
2203 middle-layer changes / updates these info. The excpetions are
2204 the hardware description (hw), interrupt callbacks
2205 (transfer_ack_xxx), DMA buffer information, and the private
2206 data. Besides, if you use the standard buffer allocation
2207 method via <function>snd_pcm_lib_malloc_pages()</function>,
2208 you don't need to set the DMA buffer information by yourself.
2212 In the sections below, important records are explained.
2215 <section id="pcm-interface-runtime-hw">
2216 <title>Hardware Description</title>
2218 The hardware descriptor (<type>snd_pcm_hardware_t</type>)
2219 contains the definitions of the fundamental hardware
2220 configuration. Above all, you'll need to define this in
2221 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2222 the open callback</citetitle></link>.
2223 Note that the runtime instance holds the copy of the
2224 descriptor, not the pointer to the existing descriptor. That
2225 is, in the open callback, you can modify the copied descriptor
2226 (<constant>runtime->hw</constant>) as you need. For example, if the maximum
2227 number of channels is 1 only on some chip models, you can
2228 still use the same hardware descriptor and change the
2233 snd_pcm_runtime_t *runtime = substream->runtime;
2235 runtime->hw = snd_mychip_playback_hw; // common definition
2236 if (chip->model == VERY_OLD_ONE)
2237 runtime->hw.channels_max = 1;
2244 Typically, you'll have a hardware descriptor like below:
2248 static snd_pcm_hardware_t snd_mychip_playback_hw = {
2249 .info = (SNDRV_PCM_INFO_MMAP |
2250 SNDRV_PCM_INFO_INTERLEAVED |
2251 SNDRV_PCM_INFO_BLOCK_TRANSFER |
2252 SNDRV_PCM_INFO_MMAP_VALID),
2253 .formats = SNDRV_PCM_FMTBIT_S16_LE,
2254 .rates = SNDRV_PCM_RATE_8000_48000,
2259 .buffer_bytes_max = 32768,
2260 .period_bytes_min = 4096,
2261 .period_bytes_max = 32768,
2263 .periods_max = 1024,
2273 The <structfield>info</structfield> field contains the type and
2274 capabilities of this pcm. The bit flags are defined in
2275 <filename><sound/asound.h></filename> as
2276 <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you
2277 have to specify whether the mmap is supported and which
2278 interleaved format is supported.
2279 When the mmap is supported, add
2280 <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the
2281 hardware supports the interleaved or the non-interleaved
2282 format, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or
2283 <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must
2284 be set, respectively. If both are supported, you can set both,
2289 In the above example, <constant>MMAP_VALID</constant> and
2290 <constant>BLOCK_TRANSFER</constant> are specified for OSS mmap
2291 mode. Usually both are set. Of course,
2292 <constant>MMAP_VALID</constant> is set only if the mmap is
2297 The other possible flags are
2298 <constant>SNDRV_PCM_INFO_PAUSE</constant> and
2299 <constant>SNDRV_PCM_INFO_RESUME</constant>. The
2300 <constant>PAUSE</constant> bit means that the pcm supports the
2301 <quote>pause</quote> operation, while the
2302 <constant>RESUME</constant> bit means that the pcm supports
2303 the <quote>suspend/resume</quote> operation. If these flags
2304 are set, the <structfield>trigger</structfield> callback below
2305 must handle the corresponding commands.
2309 When the PCM substreams can be synchronized (typically,
2310 synchorinized start/stop of a playback and a capture streams),
2311 you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,
2312 too. In this case, you'll need to check the linked-list of
2313 PCM substreams in the trigger callback. This will be
2314 described in the later section.
2320 <structfield>formats</structfield> field contains the bit-flags
2321 of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).
2322 If the hardware supports more than one format, give all or'ed
2323 bits. In the example above, the signed 16bit little-endian
2324 format is specified.
2330 <structfield>rates</structfield> field contains the bit-flags of
2331 supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).
2332 When the chip supports continuous rates, pass
2333 <constant>CONTINUOUS</constant> bit additionally.
2334 The pre-defined rate bits are provided only for typical
2335 rates. If your chip supports unconventional rates, you need to add
2336 <constant>KNOT</constant> bit and set up the hardware
2337 constraint manually (explained later).
2343 <structfield>rate_min</structfield> and
2344 <structfield>rate_max</structfield> define the minimal and
2345 maximal sample rate. This should correspond somehow to
2346 <structfield>rates</structfield> bits.
2352 <structfield>channel_min</structfield> and
2353 <structfield>channel_max</structfield>
2354 define, as you might already expected, the minimal and maximal
2361 <structfield>buffer_bytes_max</structfield> defines the
2362 maximal buffer size in bytes. There is no
2363 <structfield>buffer_bytes_min</structfield> field, since
2364 it can be calculated from the minimal period size and the
2365 minimal number of periods.
2366 Meanwhile, <structfield>period_bytes_min</structfield> and
2367 define the minimal and maximal size of the period in bytes.
2368 <structfield>periods_max</structfield> and
2369 <structfield>periods_min</structfield> define the maximal and
2370 minimal number of periods in the buffer.
2374 The <quote>period</quote> is a term, that corresponds to
2375 fragment in the OSS world. The period defines the size at
2376 which the PCM interrupt is generated. This size strongly
2377 depends on the hardware.
2378 Generally, the smaller period size will give you more
2379 interrupts, that is, more controls.
2380 In the case of capture, this size defines the input latency.
2381 On the other hand, the whole buffer size defines the
2382 output latency for the playback direction.
2388 There is also a field <structfield>fifo_size</structfield>.
2389 This specifies the size of the hardware FIFO, but it's not
2390 used currently in the driver nor in the alsa-lib. So, you
2391 can ignore this field.
2398 <section id="pcm-interface-runtime-config">
2399 <title>PCM Configurations</title>
2401 Ok, let's go back again to the PCM runtime records.
2402 The most frequently referred records in the runtime instance are
2403 the PCM configurations.
2404 The PCM configurations are stored on runtime instance
2405 after the application sends <type>hw_params</type> data via
2406 alsa-lib. There are many fields copied from hw_params and
2407 sw_params structs. For example,
2408 <structfield>format</structfield> holds the format type
2409 chosen by the application. This field contains the enum value
2410 <constant>SNDRV_PCM_FORMAT_XXX</constant>.
2414 One thing to be noted is that the configured buffer and period
2415 sizes are stored in <quote>frames</quote> in the runtime
2416 In the ALSA world, 1 frame = channels * samples-size.
2417 For conversion between frames and bytes, you can use the
2418 helper functions, <function>frames_to_bytes()</function> and
2419 <function>bytes_to_frames()</function>.
2423 period_bytes = frames_to_bytes(runtime, runtime->period_size);
2430 Also, many software parameters (sw_params) are
2431 stored in frames, too. Please check the type of the field.
2432 <type>snd_pcm_uframes_t</type> is for the frames as unsigned
2433 integer while <type>snd_pcm_sframes_t</type> is for the frames
2438 <section id="pcm-interface-runtime-dma">
2439 <title>DMA Buffer Information</title>
2441 The DMA buffer is defined by the following four fields,
2442 <structfield>dma_area</structfield>,
2443 <structfield>dma_addr</structfield>,
2444 <structfield>dma_bytes</structfield> and
2445 <structfield>dma_private</structfield>.
2446 The <structfield>dma_area</structfield> holds the buffer
2447 pointer (the logical address). You can call
2448 <function>memcpy</function> from/to
2449 this pointer. Meanwhile, <structfield>dma_addr</structfield>
2450 holds the physical address of the buffer. This field is
2451 specified only when the buffer is a linear buffer.
2452 <structfield>dma_bytes</structfield> holds the size of buffer
2453 in bytes. <structfield>dma_private</structfield> is used for
2454 the ALSA DMA allocator.
2458 If you use a standard ALSA function,
2459 <function>snd_pcm_lib_malloc_pages()</function>, for
2460 allocating the buffer, these fields are set by the ALSA middle
2461 layer, and you should <emphasis>not</emphasis> change them by
2462 yourself. You can read them but not write them.
2463 On the other hand, if you want to allocate the buffer by
2464 yourself, you'll need to manage it in hw_params callback.
2465 At least, <structfield>dma_bytes</structfield> is mandatory.
2466 <structfield>dma_area</structfield> is necessary when the
2467 buffer is mmapped. If your driver doesn't support mmap, this
2468 field is not necessary. <structfield>dma_addr</structfield>
2469 is also not mandatory. You can use
2470 <structfield>dma_private</structfield> as you like, too.
2474 <section id="pcm-interface-runtime-status">
2475 <title>Running Status</title>
2477 The running status can be referred via <constant>runtime->status</constant>.
2478 This is the pointer to <type>snd_pcm_mmap_status_t</type>
2479 record. For example, you can get the current DMA hardware
2480 pointer via <constant>runtime->status->hw_ptr</constant>.
2484 The DMA application pointer can be referred via
2485 <constant>runtime->control</constant>, which points
2486 <type>snd_pcm_mmap_control_t</type> record.
2487 However, accessing directly to this value is not recommended.
2491 <section id="pcm-interface-runtime-private">
2492 <title>Private Data</title>
2494 You can allocate a record for the substream and store it in
2495 <constant>runtime->private_data</constant>. Usually, this
2497 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2498 the open callback</citetitle></link>.
2499 Don't mix this with <constant>pcm->private_data</constant>.
2500 The <constant>pcm->private_data</constant> usually points the
2501 chip instance assigned statically at the creation of PCM, while the
2502 <constant>runtime->private_data</constant> points a dynamic
2503 data created at the PCM open callback.
2508 static int snd_xxx_open(snd_pcm_substream_t *substream)
2510 my_pcm_data_t *data;
2512 data = kmalloc(sizeof(*data), GFP_KERNEL);
2513 substream->runtime->private_data = data;
2522 The allocated object must be released in
2523 <link linkend="pcm-interface-operators-open-callback"><citetitle>
2524 the close callback</citetitle></link>.
2528 <section id="pcm-interface-runtime-intr">
2529 <title>Interrupt Callbacks</title>
2531 The field <structfield>transfer_ack_begin</structfield> and
2532 <structfield>transfer_ack_end</structfield> are called at
2533 the beginning and the end of
2534 <function>snd_pcm_period_elapsed()</function>, respectively.
2540 <section id="pcm-interface-operators">
2541 <title>Operators</title>
2543 OK, now let me explain the detail of each pcm callback
2544 (<parameter>ops</parameter>). In general, every callback must
2545 return 0 if successful, or a negative number with the error
2546 number such as <constant>-EINVAL</constant> at any
2551 The callback function takes at least the argument with
2552 <type>snd_pcm_substream_t</type> pointer. For retrieving the
2553 chip record from the given substream instance, you can use the
2560 mychip_t *chip = snd_pcm_substream_chip(substream);
2567 The macro reads <constant>substream->private_data</constant>,
2568 which is a copy of <constant>pcm->private_data</constant>.
2569 You can override the former if you need to assign different data
2570 records per PCM substream. For example, cmi8330 driver assigns
2571 different private_data for playback and capture directions,
2572 because it uses two different codecs (SB- and AD-compatible) for
2573 different directions.
2576 <section id="pcm-interface-operators-open-callback">
2577 <title>open callback</title>
2582 static int snd_xxx_open(snd_pcm_substream_t *substream);
2587 This is called when a pcm substream is opened.
2591 At least, here you have to initialize the runtime->hw
2592 record. Typically, this is done by like this:
2597 static int snd_xxx_open(snd_pcm_substream_t *substream)
2599 mychip_t *chip = snd_pcm_substream_chip(substream);
2600 snd_pcm_runtime_t *runtime = substream->runtime;
2602 runtime->hw = snd_mychip_playback_hw;
2609 where <parameter>snd_mychip_playback_hw</parameter> is the
2610 pre-defined hardware description.
2614 You can allocate a private data in this callback, as described
2615 in <link linkend="pcm-interface-runtime-private"><citetitle>
2616 Private Data</citetitle></link> section.
2620 If the hardware configuration needs more constraints, set the
2621 hardware constraints here, too.
2622 See <link linkend="pcm-interface-constraints"><citetitle>
2623 Constraints</citetitle></link> for more details.
2627 <section id="pcm-interface-operators-close-callback">
2628 <title>close callback</title>
2633 static int snd_xxx_close(snd_pcm_substream_t *substream);
2638 Obviously, this is called when a pcm substream is closed.
2642 Any private instance for a pcm substream allocated in the
2643 open callback will be released here.
2648 static int snd_xxx_close(snd_pcm_substream_t *substream)
2651 kfree(substream->runtime->private_data);
2660 <section id="pcm-interface-operators-ioctl-callback">
2661 <title>ioctl callback</title>
2663 This is used for any special action to pcm ioctls. But
2664 usually you can pass a generic ioctl callback,
2665 <function>snd_pcm_lib_ioctl</function>.
2669 <section id="pcm-interface-operators-hw-params-callback">
2670 <title>hw_params callback</title>
2675 static int snd_xxx_hw_params(snd_pcm_substream_t * substream,
2676 snd_pcm_hw_params_t * hw_params);
2681 This and <structfield>hw_free</structfield> callbacks exist
2686 This is called when the hardware parameter
2687 (<structfield>hw_params</structfield>) is set
2688 up by the application,
2689 that is, once when the buffer size, the period size, the
2690 format, etc. are defined for the pcm substream.
2694 Many hardware set-up should be done in this callback,
2695 including the allocation of buffers.
2699 Parameters to be initialized are retrieved by
2700 <function>params_xxx()</function> macros. For allocating a
2701 buffer, you can call a helper function,
2706 snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
2711 <function>snd_pcm_lib_malloc_pages()</function> is available
2712 only when the DMA buffers have been pre-allocated.
2713 See the section <link
2714 linkend="buffer-and-memory-buffer-types"><citetitle>
2715 Buffer Types</citetitle></link> for more details.
2719 Note that this and <structfield>prepare</structfield> callbacks
2720 may be called multiple times per initialization.
2721 For example, the OSS emulation may
2722 call these callbacks at each change via its ioctl.
2726 Thus, you need to take care not to allocate the same buffers
2727 many times, which will lead to memory leak! Calling the
2728 helper function above many times is OK. It will release the
2729 previous buffer automatically when it was already allocated.
2733 Another note is that this callback is non-atomic
2734 (schedulable). This is important, because the
2735 <structfield>trigger</structfield> callback
2736 is atomic (non-schedulable). That is, mutex or any
2737 schedule-related functions are not available in
2738 <structfield>trigger</structfield> callback.
2739 Please see the subsection
2740 <link linkend="pcm-interface-atomicity"><citetitle>
2741 Atomicity</citetitle></link> for details.
2745 <section id="pcm-interface-operators-hw-free-callback">
2746 <title>hw_free callback</title>
2751 static int snd_xxx_hw_free(snd_pcm_substream_t * substream);
2758 This is called to release the resources allocated via
2759 <structfield>hw_params</structfield>. For example, releasing the
2761 <function>snd_pcm_lib_malloc_pages()</function> is done by
2762 calling the following:
2767 snd_pcm_lib_free_pages(substream);
2774 This function is always called before the close callback is called.
2775 Also, the callback may be called multiple times, too.
2776 Keep track whether the resource was already released.
2780 <section id="pcm-interface-operators-prepare-callback">
2781 <title>prepare callback</title>
2786 static int snd_xxx_prepare(snd_pcm_substream_t * substream);
2793 This callback is called when the pcm is
2794 <quote>prepared</quote>. You can set the format type, sample
2795 rate, etc. here. The difference from
2796 <structfield>hw_params</structfield> is that the
2797 <structfield>prepare</structfield> callback will be called at each
2799 <function>snd_pcm_prepare()</function> is called, i.e. when
2800 recovered after underruns, etc.
2804 Note that this callback became non-atomic since the recent version.
2805 You can use schedule-related fucntions safely in this callback now.
2809 In this and the following callbacks, you can refer to the
2810 values via the runtime record,
2811 substream->runtime.
2812 For example, to get the current
2813 rate, format or channels, access to
2815 runtime->format or
2816 runtime->channels, respectively.
2817 The physical address of the allocated buffer is set to
2818 runtime->dma_area. The buffer and period sizes are
2819 in runtime->buffer_size and runtime->period_size,
2824 Be careful that this callback will be called many times at
2829 <section id="pcm-interface-operators-trigger-callback">
2830 <title>trigger callback</title>
2835 static int snd_xxx_trigger(snd_pcm_substream_t * substream, int cmd);
2840 This is called when the pcm is started, stopped or paused.
2844 Which action is specified in the second argument,
2845 <constant>SNDRV_PCM_TRIGGER_XXX</constant> in
2846 <filename><sound/pcm.h></filename>. At least,
2847 <constant>START</constant> and <constant>STOP</constant>
2848 commands must be defined in this callback.
2854 case SNDRV_PCM_TRIGGER_START:
2855 // do something to start the PCM engine
2857 case SNDRV_PCM_TRIGGER_STOP:
2858 // do something to stop the PCM engine
2869 When the pcm supports the pause operation (given in info
2870 field of the hardware table), <constant>PAUSE_PUSE</constant>
2871 and <constant>PAUSE_RELEASE</constant> commands must be
2872 handled here, too. The former is the command to pause the pcm,
2873 and the latter to restart the pcm again.
2877 When the pcm supports the suspend/resume operation
2878 (i.e. <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set),
2879 <constant>SUSPEND</constant> and <constant>RESUME</constant>
2880 commands must be handled, too.
2881 These commands are issued when the power-management status is
2882 changed. Obviously, the <constant>SUSPEND</constant> and
2883 <constant>RESUME</constant>
2884 do suspend and resume of the pcm substream, and usually, they
2885 are identical with <constant>STOP</constant> and
2886 <constant>START</constant> commands, respectively.
2890 As mentioned, this callback is atomic. You cannot call
2891 the function going to sleep.
2892 The trigger callback should be as minimal as possible,
2893 just really triggering the DMA. The other stuff should be
2894 initialized hw_params and prepare callbacks properly
2899 <section id="pcm-interface-operators-pointer-callback">
2900 <title>pointer callback</title>
2905 static snd_pcm_uframes_t snd_xxx_pointer(snd_pcm_substream_t * substream)
2910 This callback is called when the PCM middle layer inquires
2911 the current hardware position on the buffer. The position must
2912 be returned in frames (which was in bytes on ALSA 0.5.x),
2913 ranged from 0 to buffer_size - 1.
2917 This is called usually from the buffer-update routine in the
2918 pcm middle layer, which is invoked when
2919 <function>snd_pcm_period_elapsed()</function> is called in the
2920 interrupt routine. Then the pcm middle layer updates the
2921 position and calculates the available space, and wakes up the
2922 sleeping poll threads, etc.
2926 This callback is also atomic.
2930 <section id="pcm-interface-operators-copy-silence">
2931 <title>copy and silence callbacks</title>
2933 These callbacks are not mandatory, and can be omitted in
2934 most cases. These callbacks are used when the hardware buffer
2935 cannot be on the normal memory space. Some chips have their
2936 own buffer on the hardware which is not mappable. In such a
2937 case, you have to transfer the data manually from the memory
2938 buffer to the hardware buffer. Or, if the buffer is
2939 non-contiguous on both physical and virtual memory spaces,
2940 these callbacks must be defined, too.
2944 If these two callbacks are defined, copy and set-silence
2945 operations are done by them. The detailed will be described in
2946 the later section <link
2947 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2948 Management</citetitle></link>.
2952 <section id="pcm-interface-operators-ack">
2953 <title>ack callback</title>
2955 This callback is also not mandatory. This callback is called
2956 when the appl_ptr is updated in read or write operations.
2957 Some drivers like emu10k1-fx and cs46xx need to track the
2958 current appl_ptr for the internal buffer, and this callback
2959 is useful only for such a purpose.
2963 <section id="pcm-interface-operators-page-callback">
2964 <title>page callback</title>
2967 This callback is also not mandatory. This callback is used
2968 mainly for the non-contiguous buffer. The mmap calls this
2969 callback to get the page address. Some examples will be
2970 explained in the later section <link
2971 linkend="buffer-and-memory"><citetitle>Buffer and Memory
2972 Management</citetitle></link>, too.
2977 <section id="pcm-interface-interrupt-handler">
2978 <title>Interrupt Handler</title>
2980 The rest of pcm stuff is the PCM interrupt handler. The
2981 role of PCM interrupt handler in the sound driver is to update
2982 the buffer position and to tell the PCM middle layer when the
2983 buffer position goes across the prescribed period size. To
2984 inform this, call <function>snd_pcm_period_elapsed()</function>
2989 There are several types of sound chips to generate the interrupts.
2992 <section id="pcm-interface-interrupt-handler-boundary">
2993 <title>Interrupts at the period (fragment) boundary</title>
2995 This is the most frequently found type: the hardware
2996 generates an interrupt at each period boundary.
2997 In this case, you can call
2998 <function>snd_pcm_period_elapsed()</function> at each
3003 <function>snd_pcm_period_elapsed()</function> takes the
3004 substream pointer as its argument. Thus, you need to keep the
3005 substream pointer accessible from the chip instance. For
3006 example, define substream field in the chip record to hold the
3007 current running substream pointer, and set the pointer value
3008 at open callback (and reset at close callback).
3012 If you aquire a spinlock in the interrupt handler, and the
3013 lock is used in other pcm callbacks, too, then you have to
3014 release the lock before calling
3015 <function>snd_pcm_period_elapsed()</function>, because
3016 <function>snd_pcm_period_elapsed()</function> calls other pcm
3021 A typical coding would be like:
3024 <title>Interrupt Handler Case #1</title>
3027 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3028 struct pt_regs *regs)
3030 mychip_t *chip = dev_id;
3031 spin_lock(&chip->lock);
3033 if (pcm_irq_invoked(chip)) {
3034 // call updater, unlock before it
3035 spin_unlock(&chip->lock);
3036 snd_pcm_period_elapsed(chip->substream);
3037 spin_lock(&chip->lock);
3038 // acknowledge the interrupt if necessary
3041 spin_unlock(&chip->lock);
3050 <section id="pcm-interface-interrupt-handler-timer">
3051 <title>High-frequent timer interrupts</title>
3053 This is the case when the hardware doesn't generate interrupts
3054 at the period boundary but do timer-interrupts at the fixed
3055 timer rate (e.g. es1968 or ymfpci drivers).
3056 In this case, you need to check the current hardware
3057 position and accumulates the processed sample length at each
3058 interrupt. When the accumulated size overcomes the period
3060 <function>snd_pcm_period_elapsed()</function> and reset the
3065 A typical coding would be like the following.
3068 <title>Interrupt Handler Case #2</title>
3071 static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id,
3072 struct pt_regs *regs)
3074 mychip_t *chip = dev_id;
3075 spin_lock(&chip->lock);
3077 if (pcm_irq_invoked(chip)) {
3078 unsigned int last_ptr, size;
3079 // get the current hardware pointer (in frames)
3080 last_ptr = get_hw_ptr(chip);
3081 // calculate the processed frames since the
3083 if (last_ptr < chip->last_ptr)
3084 size = runtime->buffer_size + last_ptr
3087 size = last_ptr - chip->last_ptr;
3088 // remember the last updated point
3089 chip->last_ptr = last_ptr;
3090 // accumulate the size
3092 // over the period boundary?
3093 if (chip->size >= runtime->period_size) {
3094 // reset the accumulator
3095 chip->size %= runtime->period_size;
3097 spin_unlock(&chip->lock);
3098 snd_pcm_period_elapsed(substream);
3099 spin_lock(&chip->lock);
3101 // acknowledge the interrupt if necessary
3104 spin_unlock(&chip->lock);
3113 <section id="pcm-interface-interrupt-handler-both">
3114 <title>On calling <function>snd_pcm_period_elapsed()</function></title>
3116 In both cases, even if more than one period are elapsed, you
3118 <function>snd_pcm_period_elapsed()</function> many times. Call
3119 only once. And the pcm layer will check the current hardware
3120 pointer and update to the latest status.
3125 <section id="pcm-interface-atomicity">
3126 <title>Atomicity</title>
3128 One of the most important (and thus difficult to debug) problem
3129 on the kernel programming is the race condition.
3130 On linux kernel, usually it's solved via spin-locks or
3131 semaphores. In general, if the race condition may
3132 happen in the interrupt handler, it's handled as atomic, and you
3133 have to use spinlock for protecting the critical session. If it
3134 never happens in the interrupt and it may take relatively long
3135 time, you should use semaphore.
3139 As already seen, some pcm callbacks are atomic and some are
3140 not. For example, <parameter>hw_params</parameter> callback is
3141 non-atomic, while <parameter>trigger</parameter> callback is
3142 atomic. This means, the latter is called already in a spinlock
3143 held by the PCM middle layer. Please take this atomicity into
3144 account when you use a spinlock or a semaphore in the callbacks.
3148 In the atomic callbacks, you cannot use functions which may call
3149 <function>schedule</function> or go to
3150 <function>sleep</function>. The semaphore and mutex do sleep,
3151 and hence they cannot be used inside the atomic callbacks
3152 (e.g. <parameter>trigger</parameter> callback).
3153 For taking a certain delay in such a callback, please use
3154 <function>udelay()</function> or <function>mdelay()</function>.
3158 <section id="pcm-interface-constraints">
3159 <title>Constraints</title>
3161 If your chip supports unconventional sample rates, or only the
3162 limited samples, you need to set a constraint for the
3167 For example, in order to restrict the sample rates in the some
3168 supported values, use
3169 <function>snd_pcm_hw_constraint_list()</function>.
3170 You need to call this function in the open callback.
3173 <title>Example of Hardware Constraints</title>
3176 static unsigned int rates[] =
3177 {4000, 10000, 22050, 44100};
3178 static snd_pcm_hw_constraint_list_t constraints_rates = {
3179 .count = ARRAY_SIZE(rates),
3184 static int snd_mychip_pcm_open(snd_pcm_substream_t *substream)
3188 err = snd_pcm_hw_constraint_list(substream->runtime, 0,
3189 SNDRV_PCM_HW_PARAM_RATE,
3190 &constraints_rates);
3201 There are many different constraints.
3202 Look in <filename>sound/asound.h</filename> for a complete list.
3203 You can even define your own constraint rules.
3204 For example, let's suppose my_chip can manage a substream of 1 channel
3205 if and only if the format is S16_LE, otherwise it supports any format
3206 specified in the <type>snd_pcm_hardware_t</type> stucture (or in any
3207 other constraint_list). You can build a rule like this:
3210 <title>Example of Hardware Constraints for Channels</title>
3213 static int hw_rule_format_by_channels(snd_pcm_hw_params_t *params,
3214 snd_pcm_hw_rule_t *rule)
3216 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3217 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3220 snd_mask_any(&fmt); // Init the struct
3222 fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
3223 return snd_mask_refine(f, &fmt);
3233 Then you need to call this function to add your rule:
3238 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3239 hw_rule_channels_by_format, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3247 The rule function is called when an application sets the number of
3248 channels. But an application can set the format before the number of
3249 channels. Thus you also need to define the inverse rule:
3252 <title>Example of Hardware Constraints for Channels</title>
3255 static int hw_rule_channels_by_format(snd_pcm_hw_params_t *params,
3256 snd_pcm_hw_rule_t *rule)
3258 snd_interval_t *c = hw_param_interval(params, SNDRV_PCM_HW_PARAM_CHANNELS);
3259 snd_mask_t *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
3262 snd_interval_any(&ch);
3263 if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
3264 ch.min = ch.max = 1;
3266 return snd_interval_refine(c, &ch);
3276 ...and in the open callback:
3280 snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
3281 hw_rule_format_by_channels, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
3289 I won't explain more details here, rather I
3290 would like to say, <quote>Luke, use the source.</quote>
3297 <!-- ****************************************************** -->
3298 <!-- Control Interface -->
3299 <!-- ****************************************************** -->
3300 <chapter id="control-interface">
3301 <title>Control Interface</title>
3303 <section id="control-interface-general">
3304 <title>General</title>
3306 The control interface is used widely for many switches,
3307 sliders, etc. which are accessed from the user-space. Its most
3308 important use is the mixer interface. In other words, on ALSA
3309 0.9.x, all the mixer stuff is implemented on the control kernel
3310 API (while there was an independent mixer kernel API on 0.5.x).
3314 ALSA has a well-defined AC97 control module. If your chip
3315 supports only the AC97 and nothing else, you can skip this
3320 The control API is defined in
3321 <filename><sound/control.h></filename>.
3322 Include this file if you add your own controls.
3326 <section id="control-interface-definition">
3327 <title>Definition of Controls</title>
3329 For creating a new control, you need to define the three
3330 callbacks: <structfield>info</structfield>,
3331 <structfield>get</structfield> and
3332 <structfield>put</structfield>. Then, define a
3333 <type>snd_kcontrol_new_t</type> record, such as:
3336 <title>Definition of a Control</title>
3339 static snd_kcontrol_new_t my_control __devinitdata = {
3340 .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
3341 .name = "PCM Playback Switch",
3343 .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
3344 .private_values = 0xffff,
3345 .info = my_control_info,
3346 .get = my_control_get,
3347 .put = my_control_put
3355 Most likely the control is created via
3356 <function>snd_ctl_new1()</function>, and in such a case, you can
3357 add <parameter>__devinitdata</parameter> prefix to the
3358 definition like above.
3362 The <structfield>iface</structfield> field specifies the type of
3364 <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>. There are
3365 <constant>MIXER</constant>, <constant>PCM</constant>,
3366 <constant>CARD</constant>, etc.
3370 The <structfield>name</structfield> is the name identifier
3371 string. On ALSA 0.9.x, the control name is very important,
3372 because its role is classified from its name. There are
3373 pre-defined standard control names. The details are described in
3375 <link linkend="control-interface-control-names"><citetitle>
3376 Control Names</citetitle></link>.
3380 The <structfield>index</structfield> field holds the index number
3381 of this control. If there are several different controls with
3382 the same name, they can be distinguished by the index
3383 number. This is the case when
3384 several codecs exist on the card. If the index is zero, you can
3385 omit the definition above.
3389 The <structfield>access</structfield> field contains the access
3390 type of this control. Give the combination of bit masks,
3391 <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.
3392 The detailed will be explained in the subsection
3393 <link linkend="control-interface-access-flags"><citetitle>
3394 Access Flags</citetitle></link>.
3398 The <structfield>private_values</structfield> field contains
3399 an arbitrary long integer value for this record. When using
3400 generic <structfield>info</structfield>,
3401 <structfield>get</structfield> and
3402 <structfield>put</structfield> callbacks, you can pass a value
3403 through this field. If several small numbers are necessary, you can
3404 combine them in bitwise. Or, it's possible to give a pointer
3405 (casted to unsigned long) of some record to this field, too.
3410 <link linkend="control-interface-callbacks"><citetitle>
3411 callback functions</citetitle></link>.
3415 <section id="control-interface-control-names">
3416 <title>Control Names</title>
3418 There are some standards for defining the control names. A
3419 control is usually defined from the three parts as
3420 <quote>SOURCE DIRECTION FUNCTION</quote>.
3424 The first, <constant>SOURCE</constant>, specifies the source
3425 of the control, and is a string such as <quote>Master</quote>,
3426 <quote>PCM</quote>, <quote>CD</quote> or
3427 <quote>Line</quote>. There are many pre-defined sources.
3431 The second, <constant>DIRECTION</constant>, is one of the
3432 following strings according to the direction of the control:
3433 <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass
3434 Playback</quote> and <quote>Bypass Capture</quote>. Or, it can
3435 be omitted, meaning both playback and capture directions.
3439 The third, <constant>FUNCTION</constant>, is one of the
3440 following strings according to the function of the control:
3441 <quote>Switch</quote>, <quote>Volume</quote> and
3442 <quote>Route</quote>.
3446 The example of control names are, thus, <quote>Master Capture
3447 Switch</quote> or <quote>PCM Playback Volume</quote>.
3451 There are some exceptions:
3454 <section id="control-interface-control-names-global">
3455 <title>Global capture and playback</title>
3457 <quote>Capture Source</quote>, <quote>Capture Switch</quote>
3458 and <quote>Capture Volume</quote> are used for the global
3459 capture (input) source, switch and volume. Similarly,
3460 <quote>Playback Switch</quote> and <quote>Playback
3461 Volume</quote> are used for the global output gain switch and
3466 <section id="control-interface-control-names-tone">
3467 <title>Tone-controls</title>
3469 tone-control switch and volumes are specified like
3470 <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -
3471 Switch</quote>, <quote>Tone Control - Bass</quote>,
3472 <quote>Tone Control - Center</quote>.
3476 <section id="control-interface-control-names-3d">
3477 <title>3D controls</title>
3479 3D-control switches and volumes are specified like <quote>3D
3480 Control - XXX</quote>, e.g. <quote>3D Control -
3481 Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D
3482 Control - Space</quote>.
3486 <section id="control-interface-control-names-mic">
3487 <title>Mic boost</title>
3489 Mic-boost switch is set as <quote>Mic Boost</quote> or
3490 <quote>Mic Boost (6dB)</quote>.
3494 More precise information can be found in
3495 <filename>Documentation/sound/alsa/ControlNames.txt</filename>.
3500 <section id="control-interface-access-flags">
3501 <title>Access Flags</title>
3504 The access flag is the bit-flags which specifies the access type
3505 of the given control. The default access type is
3506 <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>,
3507 which means both read and write are allowed to this control.
3508 When the access flag is omitted (i.e. = 0), it is
3509 regarded as <constant>READWRITE</constant> access as default.
3513 When the control is read-only, pass
3514 <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.
3515 In this case, you don't have to define
3516 <structfield>put</structfield> callback.
3517 Similarly, when the control is write-only (although it's a rare
3518 case), you can use <constant>WRITE</constant> flag instead, and
3519 you don't need <structfield>get</structfield> callback.
3523 If the control value changes frequently (e.g. the VU meter),
3524 <constant>VOLATILE</constant> flag should be given. This means
3525 that the control may be changed without
3526 <link linkend="control-interface-change-notification"><citetitle>
3527 notification</citetitle></link>. Applications should poll such
3528 a control constantly.
3532 When the control is inactive, set
3533 <constant>INACTIVE</constant> flag, too.
3534 There are <constant>LOCK</constant> and
3535 <constant>OWNER</constant> flags for changing the write
3541 <section id="control-interface-callbacks">
3542 <title>Callbacks</title>
3544 <section id="control-interface-callbacks-info">
3545 <title>info callback</title>
3547 The <structfield>info</structfield> callback is used to get
3548 the detailed information of this control. This must store the
3549 values of the given <type>snd_ctl_elem_info_t</type>
3550 object. For example, for a boolean control with a single
3554 <title>Example of info callback</title>
3557 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3558 snd_ctl_elem_info_t *uinfo)
3560 uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
3562 uinfo->value.integer.min = 0;
3563 uinfo->value.integer.max = 1;
3572 The <structfield>type</structfield> field specifies the type
3573 of the control. There are <constant>BOOLEAN</constant>,
3574 <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,
3575 <constant>BYTES</constant>, <constant>IEC958</constant> and
3576 <constant>INTEGER64</constant>. The
3577 <structfield>count</structfield> field specifies the
3578 number of elements in this control. For example, a stereo
3579 volume would have count = 2. The
3580 <structfield>value</structfield> field is a union, and
3581 the values stored are depending on the type. The boolean and
3582 integer are identical.
3586 The enumerated type is a bit different from others. You'll
3587 need to set the string for the currently given item index.
3592 static int snd_myctl_info(snd_kcontrol_t *kcontrol,
3593 snd_ctl_elem_info_t *uinfo)
3595 static char *texts[4] = {
3596 "First", "Second", "Third", "Fourth"
3598 uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
3600 uinfo->value.enumerated.items = 4;
3601 if (uinfo->value.enumerated.item > 3)
3602 uinfo->value.enumerated.item = 3;
3603 strcpy(uinfo->value.enumerated.name,
3604 texts[uinfo->value.enumerated.item]);
3613 <section id="control-interface-callbacks-get">
3614 <title>get callback</title>
3617 This callback is used to read the current value of the
3618 control and to return to the user-space.
3625 <title>Example of get callback</title>
3628 static int snd_myctl_get(snd_kcontrol_t *kcontrol,
3629 snd_ctl_elem_value_t *ucontrol)
3631 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3632 ucontrol->value.integer.value[0] = get_some_value(chip);
3641 Here, the chip instance is retrieved via
3642 <function>snd_kcontrol_chip()</function> macro. This macro
3643 converts from kcontrol->private_data to the type defined by
3644 <type>chip_t</type>. The
3645 kcontrol->private_data field is
3646 given as the argument of <function>snd_ctl_new()</function>
3647 (see the later subsection
3648 <link linkend="control-interface-constructor"><citetitle>Constructor</citetitle></link>).
3652 The <structfield>value</structfield> field is depending on
3653 the type of control as well as on info callback. For example,
3654 the sb driver uses this field to store the register offset,
3655 the bit-shift and the bit-mask. The
3656 <structfield>private_value</structfield> is set like
3660 .private_value = reg | (shift << 16) | (mask << 24)
3664 and is retrieved in callbacks like
3668 static int snd_sbmixer_get_single(snd_kcontrol_t *kcontrol,
3669 snd_ctl_elem_value_t *ucontrol)
3671 int reg = kcontrol->private_value & 0xff;
3672 int shift = (kcontrol->private_value >> 16) & 0xff;
3673 int mask = (kcontrol->private_value >> 24) & 0xff;
3682 In <structfield>get</structfield> callback, you have to fill all the elements if the
3683 control has more than one elements,
3684 i.e. <structfield>count</structfield> > 1.
3685 In the example above, we filled only one element
3686 (<structfield>value.integer.value[0]</structfield>) since it's
3687 assumed as <structfield>count</structfield> = 1.
3691 <section id="control-interface-callbacks-put">
3692 <title>put callback</title>
3695 This callback is used to write a value from the user-space.
3702 <title>Example of put callback</title>
3705 static int snd_myctl_put(snd_kcontrol_t *kcontrol,
3706 snd_ctl_elem_value_t *ucontrol)
3708 mychip_t *chip = snd_kcontrol_chip(kcontrol);
3710 if (chip->current_value !=
3711 ucontrol->value.integer.value[0]) {
3712 change_current_value(chip,
3713 ucontrol->value.integer.value[0]);
3722 As seen above, you have to return 1 if the value is
3723 changed. If the value is not changed, return 0 instead.
3724 If any fatal error happens, return a negative error code as
3729 Like <structfield>get</structfield> callback,
3730 when the control has more than one elements,
3731 all elemehts must be evaluated in this callback, too.
3735 <section id="control-interface-callbacks-all">
3736 <title>Callbacks are not atomic</title>
3738 All these three callbacks are basically not atomic.
3743 <section id="control-interface-constructor">
3744 <title>Constructor</title>
3746 When everything is ready, finally we can create a new
3747 control. For creating a control, there are two functions to be
3748 called, <function>snd_ctl_new1()</function> and
3749 <function>snd_ctl_add()</function>.
3753 In the simplest way, you can do like this:
3758 if ((err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip))) < 0)
3764 where <parameter>my_control</parameter> is the
3765 <type>snd_kcontrol_new_t</type> object defined above, and chip
3766 is the object pointer to be passed to
3767 kcontrol->private_data
3768 which can be referred in callbacks.
3772 <function>snd_ctl_new1()</function> allocates a new
3773 <type>snd_kcontrol_t</type> instance (that's why the definition
3774 of <parameter>my_control</parameter> can be with
3775 <parameter>__devinitdata</parameter>
3776 prefix), and <function>snd_ctl_add</function> assigns the given
3777 control component to the card.
3781 <section id="control-interface-change-notification">
3782 <title>Change Notification</title>
3784 If you need to change and update a control in the interrupt
3785 routine, you can call <function>snd_ctl_notify()</function>. For
3791 snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
3796 This function takes the card pointer, the event-mask, and the
3797 control id pointer for the notification. The event-mask
3798 specifies the types of notification, for example, in the above
3799 example, the change of control values is notified.
3800 The id pointer is the pointer of <type>snd_ctl_elem_id_t</type>
3802 You can find some examples in <filename>es1938.c</filename> or
3803 <filename>es1968.c</filename> for hardware volume interrupts.
3810 <!-- ****************************************************** -->
3811 <!-- API for AC97 Codec -->
3812 <!-- ****************************************************** -->
3813 <chapter id="api-ac97">
3814 <title>API for AC97 Codec</title>
3817 <title>General</title>
3819 The ALSA AC97 codec layer is a well-defined one, and you don't
3820 have to write many codes to control it. Only low-level control
3821 routines are necessary. The AC97 codec API is defined in
3822 <filename><sound/ac97_codec.h></filename>.
3826 <section id="api-ac97-example">
3827 <title>Full Code Example</title>
3830 <title>Example of AC97 Interface</title>
3839 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3842 mychip_t *chip = ac97->private_data;
3844 // read a register value here from the codec
3845 return the_register_value;
3848 static void snd_mychip_ac97_write(ac97_t *ac97,
3849 unsigned short reg, unsigned short val)
3851 mychip_t *chip = ac97->private_data;
3853 // write the given register value to the codec
3856 static int snd_mychip_ac97(mychip_t *chip)
3859 ac97_template_t ac97;
3861 static ac97_bus_ops_t ops = {
3862 .write = snd_mychip_ac97_write,
3863 .read = snd_mychip_ac97_read,
3866 if ((err = snd_ac97_bus(chip->card, 0, &ops, NULL, &bus)) < 0)
3868 memset(&ac97, 0, sizeof(ac97));
3869 ac97.private_data = chip;
3870 return snd_ac97_mixer(bus, &ac97, &chip->ac97);
3879 <section id="api-ac97-constructor">
3880 <title>Constructor</title>
3882 For creating an ac97 instance, first call <function>snd_ac97_bus</function>
3883 with an <type>ac97_bus_ops_t</type> record with callback functions.
3889 static ac97_bus_ops_t ops = {
3890 .write = snd_mychip_ac97_write,
3891 .read = snd_mychip_ac97_read,
3894 snd_ac97_bus(card, 0, &ops, NULL, &pbus);
3899 The bus record is shared among all belonging ac97 instances.
3903 And then call <function>snd_ac97_mixer()</function> with an <type>ac97_template_t</type>
3904 record together with the bus pointer created above.
3909 ac97_template_t ac97;
3912 memset(&ac97, 0, sizeof(ac97));
3913 ac97.private_data = chip;
3914 snd_ac97_mixer(bus, &ac97, &chip->ac97);
3919 where chip->ac97 is the pointer of a newly created
3920 <type>ac97_t</type> instance.
3921 In this case, the chip pointer is set as the private data, so that
3922 the read/write callback functions can refer to this chip instance.
3923 This instance is not necessarily stored in the chip
3924 record. When you need to change the register values from the
3925 driver, or need the suspend/resume of ac97 codecs, keep this
3926 pointer to pass to the corresponding functions.
3930 <section id="api-ac97-callbacks">
3931 <title>Callbacks</title>
3933 The standard callbacks are <structfield>read</structfield> and
3934 <structfield>write</structfield>. Obviously they
3935 correspond to the functions for read and write accesses to the
3936 hardware low-level codes.
3940 The <structfield>read</structfield> callback returns the
3941 register value specified in the argument.
3946 static unsigned short snd_mychip_ac97_read(ac97_t *ac97,
3949 mychip_t *chip = ac97->private_data;
3951 return the_register_value;
3957 Here, the chip can be cast from ac97->private_data.
3961 Meanwhile, the <structfield>write</structfield> callback is
3962 used to set the register value.
3967 static void snd_mychip_ac97_write(ac97_t *ac97,
3968 unsigned short reg, unsigned short val)
3975 These callbacks are non-atomic like the callbacks of control API.
3979 There are also other callbacks:
3980 <structfield>reset</structfield>,
3981 <structfield>wait</structfield> and
3982 <structfield>init</structfield>.
3986 The <structfield>reset</structfield> callback is used to reset
3987 the codec. If the chip requires a special way of reset, you can
3988 define this callback.
3992 The <structfield>wait</structfield> callback is used for a
3993 certain wait at the standard initialization of the codec. If the
3994 chip requires the extra wait-time, define this callback.
3998 The <structfield>init</structfield> callback is used for
3999 additional initialization of the codec.
4003 <section id="api-ac97-updating-registers">
4004 <title>Updating Registers in The Driver</title>
4006 If you need to access to the codec from the driver, you can
4007 call the following functions:
4008 <function>snd_ac97_write()</function>,
4009 <function>snd_ac97_read()</function>,
4010 <function>snd_ac97_update()</function> and
4011 <function>snd_ac97_update_bits()</function>.
4015 Both <function>snd_ac97_write()</function> and
4016 <function>snd_ac97_update()</function> functions are used to
4017 set a value to the given register
4018 (<constant>AC97_XXX</constant>). The different between them is
4019 that <function>snd_ac97_update()</function> doesn't write a
4020 value if the given value has been already set, while
4021 <function>snd_ac97_write()</function> always rewrites the
4027 snd_ac97_write(ac97, AC97_MASTER, 0x8080);
4028 snd_ac97_update(ac97, AC97_MASTER, 0x8080);
4035 <function>snd_ac97_read()</function> is used to read the value
4036 of the given register. For example,
4041 value = snd_ac97_read(ac97, AC97_MASTER);
4048 <function>snd_ac97_update_bits()</function> is used to update
4049 some bits of the given register.
4054 snd_ac97_update_bits(ac97, reg, mask, value);
4061 Also, there is a function to change the sample rate (of a
4062 certain register such as
4063 <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA is
4064 supported by the codec:
4065 <function>snd_ac97_set_rate()</function>.
4070 snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
4077 The following registers are available for setting the rate:
4078 <constant>AC97_PCM_MIC_ADC_RATE</constant>,
4079 <constant>AC97_PCM_FRONT_DAC_RATE</constant>,
4080 <constant>AC97_PCM_LR_ADC_RATE</constant>,
4081 <constant>AC97_SPDIF</constant>. When the
4082 <constant>AC97_SPDIF</constant> is specified, the register is
4083 not really changed but the corresponding IEC958 status bits will
4088 <section id="api-ac97-clock-adjustment">
4089 <title>Clock Adjustment</title>
4091 On some chip, the clock of the codec isn't 48000 but using a
4092 PCI clock (to save a quartz!). In this case, change the field
4093 bus->clock to the corresponding
4094 value. For example, intel8x0
4095 and es1968 drivers have the auto-measurement function of the
4100 <section id="api-ac97-proc-files">
4101 <title>Proc Files</title>
4103 The ALSA AC97 interface will create a proc file such as
4104 <filename>/proc/asound/card0/ac97#0</filename> and
4105 <filename>ac97#0regs</filename>. You can refer to these files to
4106 see the current status and registers of the codec.
4110 <section id="api-ac97-multiple-codecs">
4111 <title>Multiple Codecs</title>
4113 When there are several codecs on the same card, you need to
4114 call <function>snd_ac97_new()</function> multiple times with
4115 ac97.num=1 or greater. The <structfield>num</structfield> field
4121 If you have set up multiple codecs, you need to either write
4122 different callbacks for each codec or check
4131 <!-- ****************************************************** -->
4132 <!-- MIDI (MPU401-UART) Interface -->
4133 <!-- ****************************************************** -->
4134 <chapter id="midi-interface">
4135 <title>MIDI (MPU401-UART) Interface</title>
4137 <section id="midi-interface-general">
4138 <title>General</title>
4140 Many soundcards have built-in MIDI (MPU401-UART)
4141 interfaces. When the soundcard supports the standard MPU401-UART
4142 interface, most likely you can use the ALSA MPU401-UART API. The
4143 MPU401-UART API is defined in
4144 <filename><sound/mpu401.h></filename>.
4148 Some soundchips have similar but a little bit different
4149 implementation of mpu401 stuff. For example, emu10k1 has its own
4154 In this document, I won't explain the rawmidi interface API,
4155 which is the basis of MPU401-UART implementation.
4159 For details, please check the source,
4160 <filename>core/rawmidi.c</filename>, and examples such as
4161 <filename>drivers/mpu401/mpu401_uart.c</filename> or
4162 <filename>usb/usbmidi.c</filename>.
4166 <section id="midi-interface-constructor">
4167 <title>Constructor</title>
4169 For creating a rawmidi object, call
4170 <function>snd_mpu401_uart_new()</function>.
4175 snd_rawmidi_t *rmidi;
4176 snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, integrated,
4177 irq, irq_flags, &rmidi);
4184 The first argument is the card pointer, and the second is the
4185 index of this component. You can create up to 8 rawmidi
4190 The third argument is the type of the hardware,
4191 <constant>MPU401_HW_XXX</constant>. If it's not a special one,
4192 you can use <constant>MPU401_HW_MPU401</constant>.
4196 The 4th argument is the i/o port address. Many
4197 backward-compatible MPU401 has an i/o port such as 0x330. Or, it
4198 might be a part of its own PCI i/o region. It depends on the
4203 When the i/o port address above is a part of the PCI i/o
4204 region, the MPU401 i/o port might have been already allocated
4205 (reserved) by the driver itself. In such a case, pass non-zero
4207 (<parameter>integrated</parameter>). Otherwise, pass 0 to it,
4209 the mpu401-uart layer will allocate the i/o ports by itself.
4213 Usually, the port address corresponds to the command port and
4214 port + 1 corresponds to the data port. If not, you may change
4215 the <structfield>cport</structfield> field of
4216 <type>mpu401_t</type> manually
4217 afterward. However, <type>mpu401_t</type> pointer is not
4218 returned explicitly by
4219 <function>snd_mpu401_uart_new()</function>. You need to cast
4220 rmidi->private_data to
4221 <type>mpu401_t</type> explicitly,
4227 mpu = rmidi->private_data;
4232 and reset the cport as you like:
4237 mpu->cport = my_own_control_port;
4244 The 6th argument specifies the irq number for UART. If the irq
4245 is already allocated, pass 0 to the 7th argument
4246 (<parameter>irq_flags</parameter>). Otherwise, pass the flags
4248 (<constant>SA_XXX</constant> bits) to it, and the irq will be
4249 reserved by the mpu401-uart layer. If the card doesn't generates
4250 UART interrupts, pass -1 as the irq number. Then a timer
4251 interrupt will be invoked for polling.
4255 <section id="midi-interface-interrupt-handler">
4256 <title>Interrupt Handler</title>
4258 When the interrupt is allocated in
4259 <function>snd_mpu401_uart_new()</function>, the private
4260 interrupt handler is used, hence you don't have to do nothing
4261 else than creating the mpu401 stuff. Otherwise, you have to call
4262 <function>snd_mpu401_uart_interrupt()</function> explicitly when
4263 a UART interrupt is invoked and checked in your own interrupt
4268 In this case, you need to pass the private_data of the
4269 returned rawmidi object from
4270 <function>snd_mpu401_uart_new()</function> as the second
4271 argument of <function>snd_mpu401_uart_interrupt()</function>.
4276 snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
4286 <!-- ****************************************************** -->
4287 <!-- Miscellaneous Devices -->
4288 <!-- ****************************************************** -->
4289 <chapter id="misc-devices">
4290 <title>Miscellaneous Devices</title>
4292 <section id="misc-devices-opl3">
4293 <title>FM OPL3</title>
4295 The FM OPL3 is still used on many chips (mainly for backward
4296 compatibility). ALSA has a nice OPL3 FM control layer, too. The
4297 OPL3 API is defined in
4298 <filename><sound/opl3.h></filename>.
4302 FM registers can be directly accessed through direct-FM API,
4303 defined in <filename><sound/asound_fm.h></filename>. In
4304 ALSA native mode, FM registers are accessed through
4305 Hardware-Dependant Device direct-FM extension API, whereas in
4306 OSS compatible mode, FM registers can be accessed with OSS
4307 direct-FM compatible API on <filename>/dev/dmfmX</filename> device.
4311 For creating the OPL3 component, you have two functions to
4312 call. The first one is a constructor for <type>opl3_t</type>
4319 snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
4327 The first argument is the card pointer, the second one is the
4328 left port address, and the third is the right port address. In
4329 most cases, the right port is placed at the left port + 2.
4333 The fourth argument is the hardware type.
4337 When the left and right ports have been already allocated by
4338 the card driver, pass non-zero to the fifth argument
4339 (<parameter>integrated</parameter>). Otherwise, opl3 module will
4340 allocate the specified ports by itself.
4344 If this function returns successfully with 0, then create a
4345 hwdep device for this opl3.
4350 snd_hwdep_t *opl3hwdep;
4351 snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
4358 The first argument is the <type>opl3_t</type> instance you
4359 created, and the second is the index number, usually 0.
4363 The third argument is the index-offset for the sequencer
4364 client assigned to the OPL3 port. When there is an MPU401-UART,
4365 give 1 for here (UART always takes 0).
4369 <section id="misc-devices-hardware-dependent">
4370 <title>Hardware-Dependent Devices</title>
4372 Some chips need the access from the user-space for special
4373 controls or for loading the micro code. In such a case, you can
4374 create a hwdep (hardware-dependent) device. The hwdep API is
4375 defined in <filename><sound/hwdep.h></filename>. You can
4376 find examples in opl3 driver or
4377 <filename>isa/sb/sb16_csp.c</filename>.
4381 Creation of the <type>hwdep</type> instance is done via
4382 <function>snd_hwdep_new()</function>.
4388 snd_hwdep_new(card, "My HWDEP", 0, &hw);
4393 where the third argument is the index number.
4397 You can then pass any pointer value to the
4398 <parameter>private_data</parameter>.
4399 If you assign a private data, you should define the
4400 destructor, too. The destructor function is set to
4401 <structfield>private_free</structfield> field.
4406 mydata_t *p = kmalloc(sizeof(*p), GFP_KERNEL);
4407 hw->private_data = p;
4408 hw->private_free = mydata_free;
4413 and the implementation of destructor would be:
4418 static void mydata_free(snd_hwdep_t *hw)
4420 mydata_t *p = hw->private_data;
4429 The arbitrary file operations can be defined for this
4430 instance. The file operators are defined in
4431 <parameter>ops</parameter> table. For example, assume that
4432 this chip needs an ioctl.
4437 hw->ops.open = mydata_open;
4438 hw->ops.ioctl = mydata_ioctl;
4439 hw->ops.release = mydata_release;
4444 And implement the callback functions as you like.
4448 <section id="misc-devices-IEC958">
4449 <title>IEC958 (S/PDIF)</title>
4451 Usually the controls for IEC958 devices are implemented via
4452 control interface. There is a macro to compose a name string for
4453 IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>
4454 defined in <filename><include/asound.h></filename>.
4458 There are some standard controls for IEC958 status bits. These
4459 controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,
4460 and the size of element is fixed as 4 bytes array
4461 (value.iec958.status[x]). For <structfield>info</structfield>
4462 callback, you don't specify
4463 the value field for this type (the count field must be set,
4468 <quote>IEC958 Playback Con Mask</quote> is used to return the
4469 bit-mask for the IEC958 status bits of consumer mode. Similarly,
4470 <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for
4471 professional mode. They are read-only controls, and are defined
4472 as MIXER controls (iface =
4473 <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>).
4477 Meanwhile, <quote>IEC958 Playback Default</quote> control is
4478 defined for getting and setting the current default IEC958
4479 bits. Note that this one is usually defined as a PCM control
4480 (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),
4481 although in some places it's defined as a MIXER control.
4485 In addition, you can define the control switches to
4486 enable/disable or to set the raw bit mode. The implementation
4487 will depend on the chip, but the control should be named as
4488 <quote>IEC958 xxx</quote>, preferably using
4489 <function>SNDRV_CTL_NAME_IEC958()</function> macro.
4493 You can find several cases, for example,
4494 <filename>pci/emu10k1</filename>,
4495 <filename>pci/ice1712</filename>, or
4496 <filename>pci/cmipci.c</filename>.
4503 <!-- ****************************************************** -->
4504 <!-- Buffer and Memory Management -->
4505 <!-- ****************************************************** -->
4506 <chapter id="buffer-and-memory">
4507 <title>Buffer and Memory Management</title>
4509 <section id="buffer-and-memory-buffer-types">
4510 <title>Buffer Types</title>
4512 ALSA provides several different buffer allocation functions
4513 depending on the bus and the architecture. All these have a
4514 consistent API. The allocation of physically-contiguous pages is
4516 <function>snd_malloc_xxx_pages()</function> function, where xxx
4521 The allocation of pages with fallback is
4522 <function>snd_malloc_xxx_pages_fallback()</function>. This
4523 function tries to allocate the specified pages but if the pages
4524 are not available, it tries to reduce the page sizes until the
4525 enough space is found.
4529 For releasing the space, call
4530 <function>snd_free_xxx_pages()</function> function.
4534 Usually, ALSA drivers try to allocate and reserve
4535 a large contiguous physical space
4536 at the time the module is loaded for the later use.
4537 This is called <quote>pre-allocation</quote>.
4538 As already written, you can call the following function at the
4539 construction of pcm instance (in the case of PCI bus).
4544 snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
4545 snd_dma_pci_data(pci), size, max);
4550 where <parameter>size</parameter> is the byte size to be
4551 pre-allocated and the <parameter>max</parameter> is the maximal
4552 size to be changed via <filename>prealloc</filename> proc file.
4553 The allocator will try to get as the large area as possible
4554 within the given size.
4558 The second argument (type) and the third argument (device pointer)
4559 are dependent on the bus.
4560 In the case of ISA bus, pass <function>snd_dma_isa_data()</function>
4561 as the third argument with <constant>SNDRV_DMA_TYPE_DEV</constant> type.
4562 For the continuous buffer unrelated to the bus can be pre-allocated
4563 with <constant>SNDRV_DMA_TYPE_CONTINUOUS</constant> type and the
4564 <function>snd_dma_continuous_data(GFP_KERNEL)</function> device pointer,
4565 whereh <constant>GFP_KERNEL</constant> is the kernel allocation flag to
4566 use. For the SBUS, <constant>SNDRV_DMA_TYPE_SBUS</constant> and
4567 <function>snd_dma_sbus_data(sbus_dev)</function> are used instead.
4568 For the PCI scatter-gather buffers, use
4569 <constant>SNDRV_DMA_TYPE_DEV_SG</constant> with
4570 <function>snd_dma_pci_data(pci)</function>
4572 <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers
4573 </citetitle></link>).
4577 Once when the buffer is pre-allocated, you can use the
4578 allocator in the <structfield>hw_params</structfield> callback
4583 snd_pcm_lib_malloc_pages(substream, size);
4588 Note that you have to pre-allocate to use this function.
4592 <section id="buffer-and-memory-external-hardware">
4593 <title>External Hardware Buffers</title>
4595 Some chips have their own hardware buffers and the DMA
4596 transfer from the host memory is not available. In such a case,
4597 you need to either 1) copy/set the audio data directly to the
4598 external hardware buffer, or 2) make an intermediate buffer and
4599 copy/set the data from it to the external hardware buffer in
4600 interrupts (or in tasklets, preferably).
4604 The first case works fine if the external hardware buffer is enough
4605 large. This method doesn't need any extra buffers and thus is
4606 more effective. You need to define the
4607 <structfield>copy</structfield> and
4608 <structfield>silence</structfield> callbacks for
4609 the data transfer. However, there is a drawback: it cannot
4610 be mmapped. The examples are GUS's GF1 PCM or emu8000's
4615 The second case allows the mmap of the buffer, although you have
4616 to handle an interrupt or a tasklet for transferring the data
4617 from the intermediate buffer to the hardware buffer. You can find an
4618 example in vxpocket driver.
4622 Another case is that the chip uses a PCI memory-map
4623 region for the buffer instead of the host memory. In this case,
4624 mmap is available only on certain architectures like intel. In
4625 non-mmap mode, the data cannot be transferred as the normal
4626 way. Thus you need to define <structfield>copy</structfield> and
4627 <structfield>silence</structfield> callbacks as well
4628 as in the cases above. The examples are found in
4629 <filename>rme32.c</filename> and <filename>rme96.c</filename>.
4633 The implementation of <structfield>copy</structfield> and
4634 <structfield>silence</structfield> callbacks depends upon
4635 whether the hardware supports interleaved or non-interleaved
4636 samples. The <structfield>copy</structfield> callback is
4637 defined like below, a bit
4638 differently depending whether the direction is playback or
4644 static int playback_copy(snd_pcm_substream_t *substream, int channel,
4645 snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);
4646 static int capture_copy(snd_pcm_substream_t *substream, int channel,
4647 snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);
4654 In the case of interleaved samples, the second argument
4655 (<parameter>channel</parameter>) is not used. The third argument
4656 (<parameter>pos</parameter>) points the
4657 current position offset in frames.
4661 The meaning of the fourth argument is different between
4662 playback and capture. For playback, it holds the source data
4663 pointer, and for capture, it's the destination data pointer.
4667 The last argument is the number of frames to be copied.
4671 What you have to do in this callback is again different
4672 between playback and capture directions. In the case of
4673 playback, you do: copy the given amount of data
4674 (<parameter>count</parameter>) at the specified pointer
4675 (<parameter>src</parameter>) to the specified offset
4676 (<parameter>pos</parameter>) on the hardware buffer. When
4677 coded like memcpy-like way, the copy would be like:
4682 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,
4683 frames_to_bytes(runtime, count));
4690 For the capture direction, you do: copy the given amount of
4691 data (<parameter>count</parameter>) at the specified offset
4692 (<parameter>pos</parameter>) on the hardware buffer to the
4693 specified pointer (<parameter>dst</parameter>).
4698 my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),
4699 frames_to_bytes(runtime, count));
4704 Note that both of the position and the data amount are given
4709 In the case of non-interleaved samples, the implementation
4710 will be a bit more complicated.
4714 You need to check the channel argument, and if it's -1, copy
4715 the whole channels. Otherwise, you have to copy only the
4716 specified channel. Please check
4717 <filename>isa/gus/gus_pcm.c</filename> as an example.
4721 The <structfield>silence</structfield> callback is also
4722 implemented in a similar way.
4727 static int silence(snd_pcm_substream_t *substream, int channel,
4728 snd_pcm_uframes_t pos, snd_pcm_uframes_t count);
4735 The meanings of arguments are identical with the
4736 <structfield>copy</structfield>
4737 callback, although there is no <parameter>src/dst</parameter>
4738 argument. In the case of interleaved samples, the channel
4739 argument has no meaning, as well as on
4740 <structfield>copy</structfield> callback.
4744 The role of <structfield>silence</structfield> callback is to
4745 set the given amount
4746 (<parameter>count</parameter>) of silence data at the
4747 specified offset (<parameter>pos</parameter>) on the hardware
4748 buffer. Suppose that the data format is signed (that is, the
4749 silent-data is 0), and the implementation using a memset-like
4750 function would be like:
4755 my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,
4756 frames_to_bytes(runtime, count));
4763 In the case of non-interleaved samples, again, the
4764 implementation becomes a bit more complicated. See, for example,
4765 <filename>isa/gus/gus_pcm.c</filename>.
4769 <section id="buffer-and-memory-non-contiguous">
4770 <title>Non-Contiguous Buffers</title>
4772 If your hardware supports the page table like emu10k1 or the
4773 buffer descriptors like via82xx, you can use the scatter-gather
4774 (SG) DMA. ALSA provides an interface for handling SG-buffers.
4775 The API is provided in <filename><sound/pcm_sgbuf.h></filename>.
4779 For creating the SG-buffer handler, call
4780 <function>snd_pcm_lib_preallocate_pages()</function> or
4781 <function>snd_pcm_lib_preallocate_pages_for_all()</function>
4782 with <constant>SNDRV_DMA_TYPE_DEV_SG</constant>
4783 in the PCM constructor like other PCI pre-allocator.
4784 You need to pass the <function>snd_dma_pci_data(pci)</function>,
4785 where pci is the struct <structname>pci_dev</structname> pointer
4786 of the chip as well.
4787 The <type>snd_sg_buf_t</type> instance is created as
4788 substream->dma_private. You can cast
4794 snd_pcm_sgbuf_t *sgbuf = (snd_pcm_sgbuf_t*)substream->dma_private;
4801 Then call <function>snd_pcm_lib_malloc_pages()</function>
4802 in <structfield>hw_params</structfield> callback
4803 as well as in the case of normal PCI buffer.
4804 The SG-buffer handler will allocate the non-contiguous kernel
4805 pages of the given size and map them onto the virtually contiguous
4806 memory. The virtual pointer is addressed in runtime->dma_area.
4807 The physical address (runtime->dma_addr) is set to zero,
4808 because the buffer is physically non-contigous.
4809 The physical address table is set up in sgbuf->table.
4810 You can get the physical address at a certain offset via
4811 <function>snd_pcm_sgbuf_get_addr()</function>.
4815 When a SG-handler is used, you need to set
4816 <function>snd_pcm_sgbuf_ops_page</function> as
4817 the <structfield>page</structfield> callback.
4818 (See <link linkend="pcm-interface-operators-page-callback">
4819 <citetitle>page callback section</citetitle></link>.)
4823 For releasing the data, call
4824 <function>snd_pcm_lib_free_pages()</function> in the
4825 <structfield>hw_free</structfield> callback as usual.
4829 <section id="buffer-and-memory-vmalloced">
4830 <title>Vmalloc'ed Buffers</title>
4832 It's possible to use a buffer allocated via
4833 <function>vmalloc</function>, for example, for an intermediate
4834 buffer. Since the allocated pages are not contiguous, you need
4835 to set the <structfield>page</structfield> callback to obtain
4836 the physical address at every offset.
4840 The implementation of <structfield>page</structfield> callback
4846 #include <linux/vmalloc.h>
4848 /* get the physical page pointer on the given offset */
4849 static struct page *mychip_page(snd_pcm_substream_t *substream,
4850 unsigned long offset)
4852 void *pageptr = substream->runtime->dma_area + offset;
4853 return vmalloc_to_page(pageptr);
4864 <!-- ****************************************************** -->
4865 <!-- Proc Interface -->
4866 <!-- ****************************************************** -->
4867 <chapter id="proc-interface">
4868 <title>Proc Interface</title>
4870 ALSA provides an easy interface for procfs. The proc files are
4871 very useful for debugging. I recommend you set up proc files if
4872 you write a driver and want to get a running status or register
4873 dumps. The API is found in
4874 <filename><sound/info.h></filename>.
4878 For creating a proc file, call
4879 <function>snd_card_proc_new()</function>.
4884 snd_info_entry_t *entry;
4885 int err = snd_card_proc_new(card, "my-file", &entry);
4890 where the second argument specifies the proc-file name to be
4891 created. The above example will create a file
4892 <filename>my-file</filename> under the card directory,
4893 e.g. <filename>/proc/asound/card0/my-file</filename>.
4897 Like other components, the proc entry created via
4898 <function>snd_card_proc_new()</function> will be registered and
4899 released automatically in the card registration and release
4904 When the creation is successful, the function stores a new
4905 instance at the pointer given in the third argument.
4906 It is initialized as a text proc file for read only. For using
4907 this proc file as a read-only text file as it is, set the read
4908 callback with a private data via
4909 <function>snd_info_set_text_ops()</function>.
4914 snd_info_set_text_ops(entry, chip, read_size, my_proc_read);
4919 where the second argument (<parameter>chip</parameter>) is the
4920 private data to be used in the callbacks. The third parameter
4921 specifies the read buffer size and the fourth
4922 (<parameter>my_proc_read</parameter>) is the callback function, which
4928 static void my_proc_read(snd_info_entry_t *entry,
4929 snd_info_buffer_t *buffer);
4937 In the read callback, use <function>snd_iprintf()</function> for
4938 output strings, which works just like normal
4939 <function>printf()</function>. For example,
4944 static void my_proc_read(snd_info_entry_t *entry,
4945 snd_info_buffer_t *buffer)
4947 chip_t *chip = entry->private_data;
4949 snd_iprintf(buffer, "This is my chip!\n");
4950 snd_iprintf(buffer, "Port = %ld\n", chip->port);
4958 The file permission can be changed afterwards. As default, it's
4959 set as read only for all users. If you want to add the write
4960 permission to the user (root as default), set like below:
4965 entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
4970 and set the write buffer size and the callback
4975 entry->c.text.write_size = 256;
4976 entry->c.text.write = my_proc_write;
4983 The buffer size for read is set to 1024 implicitly by
4984 <function>snd_info_set_text_ops()</function>. It should suffice
4985 in most cases (the size will be aligned to
4986 <constant>PAGE_SIZE</constant> anyway), but if you need to handle
4987 very large text files, you can set it explicitly, too.
4992 entry->c.text.read_size = 65536;
4999 For the write callback, you can use
5000 <function>snd_info_get_line()</function> to get a text line, and
5001 <function>snd_info_get_str()</function> to retrieve a string from
5002 the line. Some examples are found in
5003 <filename>core/oss/mixer_oss.c</filename>, core/oss/and
5004 <filename>pcm_oss.c</filename>.
5008 For a raw-data proc-file, set the attributes like the following:
5013 static struct snd_info_entry_ops my_file_io_ops = {
5014 .read = my_file_io_read,
5017 entry->content = SNDRV_INFO_CONTENT_DATA;
5018 entry->private_data = chip;
5019 entry->c.ops = &my_file_io_ops;
5021 entry->mode = S_IFREG | S_IRUGO;
5028 The callback is much more complicated than the text-file
5029 version. You need to use a low-level i/o functions such as
5030 <function>copy_from/to_user()</function> to transfer the
5036 static long my_file_io_read(snd_info_entry_t *entry,
5037 void *file_private_data,
5040 unsigned long count,
5044 if (pos + size > local_max_size)
5045 size = local_max_size - pos;
5046 if (copy_to_user(buf, local_data + pos, size))
5058 <!-- ****************************************************** -->
5059 <!-- Power Management -->
5060 <!-- ****************************************************** -->
5061 <chapter id="power-management">
5062 <title>Power Management</title>
5064 If the chip is supposed to work with with suspend/resume
5065 functions, you need to add the power-management codes to the
5066 driver. The additional codes for the power-management should be
5067 <function>ifdef</function>'ed with
5068 <constant>CONFIG_PM</constant>.
5072 ALSA provides the common power-management layer. Each card driver
5073 needs to have only low-level suspend and resume callbacks.
5079 static int snd_my_suspend(snd_card_t *card, unsigned int state)
5081 .... // do things for suspsend
5084 static int snd_my_resume(snd_card_t *card, unsigned int state)
5086 .... // do things for suspsend
5096 The scheme of the real suspend job is as following.
5099 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5100 <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>
5101 <listitem><para>Save the register values if necessary.</para></listitem>
5102 <listitem><para>Stop the hardware if necessary.</para></listitem>
5103 <listitem><para>Set the power-state as D3hot by calling <function>snd_power_change_state()</function>.</para></listitem>
5108 A typical code would be like:
5113 static int mychip_suspend(snd_card_t *card, unsigned int state)
5116 mychip_t *chip = card->pm_private_data;
5118 snd_pcm_suspend_all(chip->pcm);
5120 snd_mychip_save_registers(chip);
5122 snd_mychip_stop_hardware(chip);
5124 snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
5133 The scheme of the real resume job is as following.
5136 <listitem><para>Retrieve the chip data from pm_private_data field.</para></listitem>
5137 <listitem><para>Enable the pci device again by calling
5138 <function>pci_enable_device()</function>.</para></listitem>
5139 <listitem><para>Re-initialize the chip.</para></listitem>
5140 <listitem><para>Restore the saved registers if necessary.</para></listitem>
5141 <listitem><para>Resume the mixer, e.g. calling
5142 <function>snd_ac97_resume()</function>.</para></listitem>
5143 <listitem><para>Restart the hardware (if any).</para></listitem>
5144 <listitem><para>Set the power-state as D0 by calling
5145 <function>snd_power_change_state()</function>.</para></listitem>
5150 A typical code would be like:
5155 static void mychip_resume(mychip_t *chip)
5158 mychip_t *chip = card->pm_private_data;
5160 pci_enable_device(chip->pci);
5162 snd_mychip_reinit_chip(chip);
5164 snd_mychip_restore_registers(chip);
5166 snd_ac97_resume(chip->ac97);
5168 snd_mychip_restart_chip(chip);
5170 snd_power_change_state(card, SNDRV_CTL_POWER_D0);
5179 OK, we have all callbacks now. Let's set up them now. In the
5180 initialization of the card, add the following:
5185 static int __devinit snd_mychip_probe(struct pci_dev *pci,
5186 const struct pci_device_id *pci_id)
5192 snd_card_set_pm_callback(card, snd_my_suspend, snd_my_resume, chip);
5199 Here you don't have to put ifdef CONFIG_PM around, since it's already
5200 checked in the header and expanded to empty if not needed.
5204 If you need a space for saving the registers, you'll need to
5205 allocate the buffer for it here, too, since it would be fatal
5206 if you cannot allocate a memory in the suspend phase.
5207 The allocated buffer should be released in the corresponding
5212 And next, set suspend/resume callbacks to the pci_driver,
5213 This can be done by passing a macro SND_PCI_PM_CALLBACKS
5214 in the pci_driver struct. This macro is expanded to the correct
5215 (global) callbacks if CONFIG_PM is set.
5220 static struct pci_driver driver = {
5222 .id_table = snd_my_ids,
5223 .probe = snd_my_probe,
5224 .remove = __devexit_p(snd_my_remove),
5225 SND_PCI_PM_CALLBACKS
5235 <!-- ****************************************************** -->
5236 <!-- Module Parameters -->
5237 <!-- ****************************************************** -->
5238 <chapter id="module-parameters">
5239 <title>Module Parameters</title>
5241 There are standard module options for ALSA. At least, each
5242 module should have <parameter>index</parameter>,
5243 <parameter>id</parameter> and <parameter>enable</parameter>
5248 If the module supports multiple cards (usually up to
5249 8 = <constant>SNDRV_CARDS</constant> cards), they should be
5250 arrays. The default initial values are defined already as
5251 constants for ease of programming:
5256 static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
5257 static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
5258 static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
5265 If the module supports only a single card, they could be single
5266 variables, instead. <parameter>enable</parameter> option is not
5267 always necessary in this case, but it wouldn't be so bad to have a
5268 dummy option for compatibility.
5272 The module parameters must be declared with the standard
5273 <function>module_param()()</function>,
5274 <function>module_param_array()()</function> and
5275 <function>MODULE_PARM_DESC()</function> macros.
5279 The typical coding would be like below:
5284 #define CARD_NAME "My Chip"
5286 static int boot_devs;
5287 module_param_array(index, int, boot_devs, 0444);
5288 MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
5289 module_param_array(id, charp, boot_devs, 0444);
5290 MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
5291 module_param_array(enable, bool, boot_devs, 0444);
5292 MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
5297 Here boot_devs is passed but simply ignored since we don't care
5298 the number of parsed parameters.
5302 Also, don't forget to define the module description, classes,
5303 license and devices. Especially, the recent modprobe requires to
5304 define the module license as GPL, etc., otherwise the system is
5305 shown as <quote>tainted</quote>.
5310 MODULE_DESCRIPTION("My Chip");
5311 MODULE_LICENSE("GPL");
5312 MODULE_SUPPORTED_DEVICE("{{Vendor,My Chip Name}}");
5321 <!-- ****************************************************** -->
5322 <!-- How To Put Your Driver -->
5323 <!-- ****************************************************** -->
5324 <chapter id="how-to-put-your-driver">
5325 <title>How To Put Your Driver Into ALSA Tree</title>
5327 <title>General</title>
5329 So far, you've learned how to write the driver codes.
5330 And you might have a question now: how to put my own
5331 driver into the ALSA driver tree?
5332 Here (finally :) the standard procedure is described briefly.
5336 Suppose that you'll create a new PCI driver for the card
5337 <quote>xyz</quote>. The card module name would be
5338 snd-xyz. The new driver is usually put into alsa-driver
5339 tree, <filename>alsa-driver/pci</filename> directory in
5340 the case of PCI cards.
5341 Then the driver is evaluated, audited and tested
5342 by developers and users. After a certain time, the driver
5343 will go to alsa-kernel tree (to the corresponding directory,
5344 such as <filename>alsa-kernel/pci</filename>) and eventually
5345 integrated into Linux 2.6 tree (the directory would be
5346 <filename>linux/sound/pci</filename>).
5350 In the following sections, the driver code is supposed
5351 to be put into alsa-driver tree. The two cases are assumed:
5352 a driver consisting of a single source file and one consisting
5353 of several source files.
5358 <title>Driver with A Single Source File</title>
5363 Modify alsa-driver/pci/Makefile
5367 Suppose you have a file xyz.c. Add the following
5372 snd-xyz-objs := xyz.o
5373 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5382 Create the Kconfig entry
5386 Add the new entry of Kconfig for your xyz driver.
5391 tristate "Foobar XYZ"
5395 Say 'Y' or 'M' to include support for Foobar XYZ soundcard.
5400 the line, select SND_PCM, specifies that the driver xyz supports
5401 PCM. In addition to SND_PCM, the following components are
5402 supported for select command:
5403 SND_RAWMIDI, SND_TIMER, SND_HWDEP, SND_MPU401_UART,
5404 SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB, SND_AC97_CODEC.
5405 Add the select command for each supported component.
5409 Note that some selections imply the lowlevel selections.
5410 For example, PCM includes TIMER, MPU401_UART includes RAWMIDI,
5411 AC97_CODEC includes PCM, and OPL3_LIB includes HWDEP.
5412 You don't need to give the lowlevel selections again.
5416 For the details of Kconfig script, refer to the kbuild
5424 Run cvscompile script to re-generate the configure script and
5425 build the whole stuff again.
5433 <title>Drivers with Several Source Files</title>
5435 Suppose that the driver snd-xyz have several source files.
5436 They are located in the new subdirectory,
5442 Add a new directory (<filename>xyz</filename>) in
5443 <filename>alsa-driver/pci/Makefile</filename> like below
5448 obj-$(CONFIG_SND) += xyz/
5457 Under the directory <filename>xyz</filename>, create a Makefile
5460 <title>Sample Makefile for a driver xyz</title>
5467 include $(SND_TOPDIR)/toplevel.config
5468 include $(SND_TOPDIR)/Makefile.conf
5470 snd-xyz-objs := xyz.o abc.o def.o
5472 obj-$(CONFIG_SND_XYZ) += snd-xyz.o
5474 include $(SND_TOPDIR)/Rules.make
5483 Create the Kconfig entry
5487 This procedure is as same as in the last section.
5493 Run cvscompile script to re-generate the configure script and
5494 build the whole stuff again.
5503 <!-- ****************************************************** -->
5504 <!-- Useful Functions -->
5505 <!-- ****************************************************** -->
5506 <chapter id="useful-functions">
5507 <title>Useful Functions</title>
5509 <section id="useful-functions-snd-printk">
5510 <title><function>snd_printk()</function> and friends</title>
5512 ALSA provides a verbose version of
5513 <function>printk()</function> function. If a kernel config
5514 <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this
5515 function prints the given message together with the file name
5516 and the line of the caller. The <constant>KERN_XXX</constant>
5517 prefix is processed as
5518 well as the original <function>printk()</function> does, so it's
5519 recommended to add this prefix, e.g.
5524 snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");
5531 There are also <function>printk()</function>'s for
5532 debugging. <function>snd_printd()</function> can be used for
5533 general debugging purposes. If
5534 <constant>CONFIG_SND_DEBUG</constant> is set, this function is
5535 compiled, and works just like
5536 <function>snd_printk()</function>. If the ALSA is compiled
5537 without the debugging flag, it's ignored.
5541 <function>snd_printdd()</function> is compiled in only when
5542 <constant>CONFIG_SND_DEBUG_DETECT</constant> is set. Please note
5543 that <constant>DEBUG_DETECT</constant> is not set as default
5544 even if you configure the alsa-driver with
5545 <option>--with-debug=full</option> option. You need to give
5546 explicitly <option>--with-debug=detect</option> option instead.
5550 <section id="useful-functions-snd-assert">
5551 <title><function>snd_assert()</function></title>
5553 <function>snd_assert()</function> macro is similar with the
5554 normal <function>assert()</function> macro. For example,
5559 snd_assert(pointer != NULL, return -EINVAL);
5566 The first argument is the expression to evaluate, and the
5567 second argument is the action if it fails. When
5568 <constant>CONFIG_SND_DEBUG</constant>, is set, it will show an
5569 error message such as <computeroutput>BUG? (xxx) (called from
5570 yyy)</computeroutput>. When no debug flag is set, this is
5575 <section id="useful-functions-snd-runtime-check">
5576 <title><function>snd_runtime_check()</function></title>
5578 This macro is quite similar with
5579 <function>snd_assert()</function>. Unlike
5580 <function>snd_assert()</function>, the expression is always
5581 evaluated regardless of
5582 <constant>CONFIG_SND_DEBUG</constant>. When
5583 <constant>CONFIG_SND_DEBUG</constant> is set, the macro will
5584 show a message like <computeroutput>ERROR (xx) (called from
5585 yyy)</computeroutput>.
5589 <section id="useful-functions-snd-bug">
5590 <title><function>snd_BUG()</function></title>
5592 It calls <function>snd_assert(0,)</function> -- that is, just
5593 prints the error message at the point. It's useful to show that
5594 a fatal error happens there.
5600 <!-- ****************************************************** -->
5601 <!-- Acknowledgments -->
5602 <!-- ****************************************************** -->
5603 <chapter id="acknowledments">
5604 <title>Acknowledgments</title>
5606 I would like to thank Phil Kerr for his help for improvement and
5607 corrections of this document.
5610 Kevin Conder reformatted the original plain-text to the
5614 Giuliano Pochini corrected typos and contributed the example codes
5615 in the hardware constraints section.