···11-<?xml version="1.0" encoding="UTF-8"?>22-<!DOCTYPE book PUBLIC "-//OASIS//DTD DocBook XML V4.1.2//EN"33- "http://www.oasis-open.org/docbook/xml/4.1.2/docbookx.dtd" []>44-55-<!-- ****************************************************** -->66-<!-- Header -->77-<!-- ****************************************************** -->88-<book id="Writing-an-ALSA-Driver">99- <bookinfo>1010- <title>Writing an ALSA Driver</title>1111- <author>1212- <firstname>Takashi</firstname>1313- <surname>Iwai</surname>1414- <affiliation>1515- <address>1616- <email>tiwai@suse.de</email>1717- </address>1818- </affiliation>1919- </author>2020-2121- <date>Oct 15, 2007</date>2222- <edition>0.3.7</edition>2323-2424- <abstract>2525- <para>2626- This document describes how to write an ALSA (Advanced Linux2727- Sound Architecture) driver.2828- </para>2929- </abstract>3030-3131- <legalnotice>3232- <para>3333- Copyright (c) 2002-2005 Takashi Iwai <email>tiwai@suse.de</email>3434- </para>3535-3636- <para>3737- This document is free; you can redistribute it and/or modify it3838- under the terms of the GNU General Public License as published by3939- the Free Software Foundation; either version 2 of the License, or4040- (at your option) any later version. 4141- </para>4242-4343- <para>4444- This document is distributed in the hope that it will be useful,4545- but <emphasis>WITHOUT ANY WARRANTY</emphasis>; without even the4646- implied warranty of <emphasis>MERCHANTABILITY or FITNESS FOR A4747- PARTICULAR PURPOSE</emphasis>. See the GNU General Public License4848- for more details.4949- </para>5050-5151- <para>5252- You should have received a copy of the GNU General Public5353- License along with this program; if not, write to the Free5454- Software Foundation, Inc., 59 Temple Place, Suite 330, Boston,5555- MA 02111-1307 USA5656- </para>5757- </legalnotice>5858-5959- </bookinfo>6060-6161-<!-- ****************************************************** -->6262-<!-- Preface -->6363-<!-- ****************************************************** -->6464- <preface id="preface">6565- <title>Preface</title>6666- <para>6767- This document describes how to write an6868- <ulink url="http://www.alsa-project.org/"><citetitle>6969- ALSA (Advanced Linux Sound Architecture)</citetitle></ulink>7070- driver. The document focuses mainly on PCI soundcards.7171- In the case of other device types, the API might7272- be different, too. However, at least the ALSA kernel API is7373- consistent, and therefore it would be still a bit help for7474- writing them.7575- </para>7676-7777- <para>7878- This document targets people who already have enough7979- C language skills and have basic linux kernel programming8080- knowledge. This document doesn't explain the general8181- topic of linux kernel coding and doesn't cover low-level8282- driver implementation details. It only describes8383- the standard way to write a PCI sound driver on ALSA.8484- </para>8585-8686- <para>8787- If you are already familiar with the older ALSA ver.0.5.x API, you8888- can check the drivers such as <filename>sound/pci/es1938.c</filename> or8989- <filename>sound/pci/maestro3.c</filename> which have also almost the same9090- code-base in the ALSA 0.5.x tree, so you can compare the differences.9191- </para>9292-9393- <para>9494- This document is still a draft version. Any feedback and9595- corrections, please!!9696- </para>9797- </preface>9898-9999-100100-<!-- ****************************************************** -->101101-<!-- File Tree Structure -->102102-<!-- ****************************************************** -->103103- <chapter id="file-tree">104104- <title>File Tree Structure</title>105105-106106- <section id="file-tree-general">107107- <title>General</title>108108- <para>109109- The ALSA drivers are provided in two ways.110110- </para>111111-112112- <para>113113- One is the trees provided as a tarball or via cvs from the114114- ALSA's ftp site, and another is the 2.6 (or later) Linux kernel115115- tree. To synchronize both, the ALSA driver tree is split into116116- two different trees: alsa-kernel and alsa-driver. The former117117- contains purely the source code for the Linux 2.6 (or later)118118- tree. This tree is designed only for compilation on 2.6 or119119- later environment. The latter, alsa-driver, contains many subtle120120- files for compiling ALSA drivers outside of the Linux kernel tree,121121- wrapper functions for older 2.2 and 2.4 kernels, to adapt the latest kernel API,122122- and additional drivers which are still in development or in123123- tests. The drivers in alsa-driver tree will be moved to124124- alsa-kernel (and eventually to the 2.6 kernel tree) when they are125125- finished and confirmed to work fine.126126- </para>127127-128128- <para>129129- The file tree structure of ALSA driver is depicted below. Both130130- alsa-kernel and alsa-driver have almost the same file131131- structure, except for <quote>core</quote> directory. It's132132- named as <quote>acore</quote> in alsa-driver tree. 133133-134134- <example>135135- <title>ALSA File Tree Structure</title>136136- <literallayout>137137- sound138138- /core139139- /oss140140- /seq141141- /oss142142- /instr143143- /ioctl32144144- /include145145- /drivers146146- /mpu401147147- /opl3148148- /i2c149149- /l3150150- /synth151151- /emux152152- /pci153153- /(cards)154154- /isa155155- /(cards)156156- /arm157157- /ppc158158- /sparc159159- /usb160160- /pcmcia /(cards)161161- /oss162162- </literallayout>163163- </example>164164- </para>165165- </section>166166-167167- <section id="file-tree-core-directory">168168- <title>core directory</title>169169- <para>170170- This directory contains the middle layer which is the heart171171- of ALSA drivers. In this directory, the native ALSA modules are172172- stored. The sub-directories contain different modules and are173173- dependent upon the kernel config. 174174- </para>175175-176176- <section id="file-tree-core-directory-oss">177177- <title>core/oss</title>178178-179179- <para>180180- The codes for PCM and mixer OSS emulation modules are stored181181- in this directory. The rawmidi OSS emulation is included in182182- the ALSA rawmidi code since it's quite small. The sequencer183183- code is stored in <filename>core/seq/oss</filename> directory (see184184- <link linkend="file-tree-core-directory-seq-oss"><citetitle>185185- below</citetitle></link>).186186- </para>187187- </section>188188-189189- <section id="file-tree-core-directory-ioctl32">190190- <title>core/ioctl32</title>191191-192192- <para>193193- This directory contains the 32bit-ioctl wrappers for 64bit194194- architectures such like x86-64, ppc64 and sparc64. For 32bit195195- and alpha architectures, these are not compiled. 196196- </para>197197- </section>198198-199199- <section id="file-tree-core-directory-seq">200200- <title>core/seq</title>201201- <para>202202- This directory and its sub-directories are for the ALSA203203- sequencer. This directory contains the sequencer core and204204- primary sequencer modules such like snd-seq-midi,205205- snd-seq-virmidi, etc. They are compiled only when206206- <constant>CONFIG_SND_SEQUENCER</constant> is set in the kernel207207- config. 208208- </para>209209- </section>210210-211211- <section id="file-tree-core-directory-seq-oss">212212- <title>core/seq/oss</title>213213- <para>214214- This contains the OSS sequencer emulation codes.215215- </para>216216- </section>217217-218218- <section id="file-tree-core-directory-deq-instr">219219- <title>core/seq/instr</title>220220- <para>221221- This directory contains the modules for the sequencer222222- instrument layer. 223223- </para>224224- </section>225225- </section>226226-227227- <section id="file-tree-include-directory">228228- <title>include directory</title>229229- <para>230230- This is the place for the public header files of ALSA drivers,231231- which are to be exported to user-space, or included by232232- several files at different directories. Basically, the private233233- header files should not be placed in this directory, but you may234234- still find files there, due to historical reasons :) 235235- </para>236236- </section>237237-238238- <section id="file-tree-drivers-directory">239239- <title>drivers directory</title>240240- <para>241241- This directory contains code shared among different drivers242242- on different architectures. They are hence supposed not to be243243- architecture-specific.244244- For example, the dummy pcm driver and the serial MIDI245245- driver are found in this directory. In the sub-directories,246246- there is code for components which are independent from247247- bus and cpu architectures. 248248- </para>249249-250250- <section id="file-tree-drivers-directory-mpu401">251251- <title>drivers/mpu401</title>252252- <para>253253- The MPU401 and MPU401-UART modules are stored here.254254- </para>255255- </section>256256-257257- <section id="file-tree-drivers-directory-opl3">258258- <title>drivers/opl3 and opl4</title>259259- <para>260260- The OPL3 and OPL4 FM-synth stuff is found here.261261- </para>262262- </section>263263- </section>264264-265265- <section id="file-tree-i2c-directory">266266- <title>i2c directory</title>267267- <para>268268- This contains the ALSA i2c components.269269- </para>270270-271271- <para>272272- Although there is a standard i2c layer on Linux, ALSA has its273273- own i2c code for some cards, because the soundcard needs only a274274- simple operation and the standard i2c API is too complicated for275275- such a purpose. 276276- </para>277277-278278- <section id="file-tree-i2c-directory-l3">279279- <title>i2c/l3</title>280280- <para>281281- This is a sub-directory for ARM L3 i2c.282282- </para>283283- </section>284284- </section>285285-286286- <section id="file-tree-synth-directory">287287- <title>synth directory</title>288288- <para>289289- This contains the synth middle-level modules.290290- </para>291291-292292- <para>293293- So far, there is only Emu8000/Emu10k1 synth driver under294294- the <filename>synth/emux</filename> sub-directory. 295295- </para>296296- </section>297297-298298- <section id="file-tree-pci-directory">299299- <title>pci directory</title>300300- <para>301301- This directory and its sub-directories hold the top-level card modules302302- for PCI soundcards and the code specific to the PCI BUS.303303- </para>304304-305305- <para>306306- The drivers compiled from a single file are stored directly307307- in the pci directory, while the drivers with several source files are308308- stored on their own sub-directory (e.g. emu10k1, ice1712). 309309- </para>310310- </section>311311-312312- <section id="file-tree-isa-directory">313313- <title>isa directory</title>314314- <para>315315- This directory and its sub-directories hold the top-level card modules316316- for ISA soundcards. 317317- </para>318318- </section>319319-320320- <section id="file-tree-arm-ppc-sparc-directories">321321- <title>arm, ppc, and sparc directories</title>322322- <para>323323- They are used for top-level card modules which are324324- specific to one of these architectures. 325325- </para>326326- </section>327327-328328- <section id="file-tree-usb-directory">329329- <title>usb directory</title>330330- <para>331331- This directory contains the USB-audio driver. In the latest version, the332332- USB MIDI driver is integrated in the usb-audio driver. 333333- </para>334334- </section>335335-336336- <section id="file-tree-pcmcia-directory">337337- <title>pcmcia directory</title>338338- <para>339339- The PCMCIA, especially PCCard drivers will go here. CardBus340340- drivers will be in the pci directory, because their API is identical341341- to that of standard PCI cards. 342342- </para>343343- </section>344344-345345- <section id="file-tree-oss-directory">346346- <title>oss directory</title>347347- <para>348348- The OSS/Lite source files are stored here in Linux 2.6 (or349349- later) tree. In the ALSA driver tarball, this directory is empty,350350- of course :) 351351- </para>352352- </section>353353- </chapter>354354-355355-356356-<!-- ****************************************************** -->357357-<!-- Basic Flow for PCI Drivers -->358358-<!-- ****************************************************** -->359359- <chapter id="basic-flow">360360- <title>Basic Flow for PCI Drivers</title>361361-362362- <section id="basic-flow-outline">363363- <title>Outline</title>364364- <para>365365- The minimum flow for PCI soundcards is as follows:366366-367367- <itemizedlist>368368- <listitem><para>define the PCI ID table (see the section369369- <link linkend="pci-resource-entries"><citetitle>PCI Entries370370- </citetitle></link>).</para></listitem> 371371- <listitem><para>create <function>probe()</function> callback.</para></listitem>372372- <listitem><para>create <function>remove()</function> callback.</para></listitem>373373- <listitem><para>create a <structname>pci_driver</structname> structure374374- containing the three pointers above.</para></listitem>375375- <listitem><para>create an <function>init()</function> function just calling376376- the <function>pci_register_driver()</function> to register the pci_driver table377377- defined above.</para></listitem>378378- <listitem><para>create an <function>exit()</function> function to call379379- the <function>pci_unregister_driver()</function> function.</para></listitem>380380- </itemizedlist>381381- </para>382382- </section>383383-384384- <section id="basic-flow-example">385385- <title>Full Code Example</title>386386- <para>387387- The code example is shown below. Some parts are kept388388- unimplemented at this moment but will be filled in the389389- next sections. The numbers in the comment lines of the390390- <function>snd_mychip_probe()</function> function391391- refer to details explained in the following section. 392392-393393- <example>394394- <title>Basic Flow for PCI Drivers - Example</title>395395- <programlisting>396396-<![CDATA[397397- #include <linux/init.h>398398- #include <linux/pci.h>399399- #include <linux/slab.h>400400- #include <sound/core.h>401401- #include <sound/initval.h>402402-403403- /* module parameters (see "Module Parameters") */404404- /* SNDRV_CARDS: maximum number of cards supported by this module */405405- static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;406406- static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;407407- static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;408408-409409- /* definition of the chip-specific record */410410- struct mychip {411411- struct snd_card *card;412412- /* the rest of the implementation will be in section413413- * "PCI Resource Management"414414- */415415- };416416-417417- /* chip-specific destructor418418- * (see "PCI Resource Management")419419- */420420- static int snd_mychip_free(struct mychip *chip)421421- {422422- .... /* will be implemented later... */423423- }424424-425425- /* component-destructor426426- * (see "Management of Cards and Components")427427- */428428- static int snd_mychip_dev_free(struct snd_device *device)429429- {430430- return snd_mychip_free(device->device_data);431431- }432432-433433- /* chip-specific constructor434434- * (see "Management of Cards and Components")435435- */436436- static int snd_mychip_create(struct snd_card *card,437437- struct pci_dev *pci,438438- struct mychip **rchip)439439- {440440- struct mychip *chip;441441- int err;442442- static struct snd_device_ops ops = {443443- .dev_free = snd_mychip_dev_free,444444- };445445-446446- *rchip = NULL;447447-448448- /* check PCI availability here449449- * (see "PCI Resource Management")450450- */451451- ....452452-453453- /* allocate a chip-specific data with zero filled */454454- chip = kzalloc(sizeof(*chip), GFP_KERNEL);455455- if (chip == NULL)456456- return -ENOMEM;457457-458458- chip->card = card;459459-460460- /* rest of initialization here; will be implemented461461- * later, see "PCI Resource Management"462462- */463463- ....464464-465465- err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);466466- if (err < 0) {467467- snd_mychip_free(chip);468468- return err;469469- }470470-471471- *rchip = chip;472472- return 0;473473- }474474-475475- /* constructor -- see "Constructor" sub-section */476476- static int snd_mychip_probe(struct pci_dev *pci,477477- const struct pci_device_id *pci_id)478478- {479479- static int dev;480480- struct snd_card *card;481481- struct mychip *chip;482482- int err;483483-484484- /* (1) */485485- if (dev >= SNDRV_CARDS)486486- return -ENODEV;487487- if (!enable[dev]) {488488- dev++;489489- return -ENOENT;490490- }491491-492492- /* (2) */493493- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,494494- 0, &card);495495- if (err < 0)496496- return err;497497-498498- /* (3) */499499- err = snd_mychip_create(card, pci, &chip);500500- if (err < 0) {501501- snd_card_free(card);502502- return err;503503- }504504-505505- /* (4) */506506- strcpy(card->driver, "My Chip");507507- strcpy(card->shortname, "My Own Chip 123");508508- sprintf(card->longname, "%s at 0x%lx irq %i",509509- card->shortname, chip->ioport, chip->irq);510510-511511- /* (5) */512512- .... /* implemented later */513513-514514- /* (6) */515515- err = snd_card_register(card);516516- if (err < 0) {517517- snd_card_free(card);518518- return err;519519- }520520-521521- /* (7) */522522- pci_set_drvdata(pci, card);523523- dev++;524524- return 0;525525- }526526-527527- /* destructor -- see the "Destructor" sub-section */528528- static void snd_mychip_remove(struct pci_dev *pci)529529- {530530- snd_card_free(pci_get_drvdata(pci));531531- pci_set_drvdata(pci, NULL);532532- }533533-]]>534534- </programlisting>535535- </example>536536- </para>537537- </section>538538-539539- <section id="basic-flow-constructor">540540- <title>Constructor</title>541541- <para>542542- The real constructor of PCI drivers is the <function>probe</function> callback.543543- The <function>probe</function> callback and other component-constructors which are called544544- from the <function>probe</function> callback cannot be used with545545- the <parameter>__init</parameter> prefix546546- because any PCI device could be a hotplug device. 547547- </para>548548-549549- <para>550550- In the <function>probe</function> callback, the following scheme is often used.551551- </para>552552-553553- <section id="basic-flow-constructor-device-index">554554- <title>1) Check and increment the device index.</title>555555- <para>556556- <informalexample>557557- <programlisting>558558-<![CDATA[559559- static int dev;560560- ....561561- if (dev >= SNDRV_CARDS)562562- return -ENODEV;563563- if (!enable[dev]) {564564- dev++;565565- return -ENOENT;566566- }567567-]]>568568- </programlisting>569569- </informalexample>570570-571571- where enable[dev] is the module option.572572- </para>573573-574574- <para>575575- Each time the <function>probe</function> callback is called, check the576576- availability of the device. If not available, simply increment577577- the device index and returns. dev will be incremented also578578- later (<link579579- linkend="basic-flow-constructor-set-pci"><citetitle>step580580- 7</citetitle></link>). 581581- </para>582582- </section>583583-584584- <section id="basic-flow-constructor-create-card">585585- <title>2) Create a card instance</title>586586- <para>587587- <informalexample>588588- <programlisting>589589-<![CDATA[590590- struct snd_card *card;591591- int err;592592- ....593593- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,594594- 0, &card);595595-]]>596596- </programlisting>597597- </informalexample>598598- </para>599599-600600- <para>601601- The details will be explained in the section602602- <link linkend="card-management-card-instance"><citetitle>603603- Management of Cards and Components</citetitle></link>.604604- </para>605605- </section>606606-607607- <section id="basic-flow-constructor-create-main">608608- <title>3) Create a main component</title>609609- <para>610610- In this part, the PCI resources are allocated.611611-612612- <informalexample>613613- <programlisting>614614-<![CDATA[615615- struct mychip *chip;616616- ....617617- err = snd_mychip_create(card, pci, &chip);618618- if (err < 0) {619619- snd_card_free(card);620620- return err;621621- }622622-]]>623623- </programlisting>624624- </informalexample>625625-626626- The details will be explained in the section <link627627- linkend="pci-resource"><citetitle>PCI Resource628628- Management</citetitle></link>.629629- </para>630630- </section>631631-632632- <section id="basic-flow-constructor-main-component">633633- <title>4) Set the driver ID and name strings.</title>634634- <para>635635- <informalexample>636636- <programlisting>637637-<![CDATA[638638- strcpy(card->driver, "My Chip");639639- strcpy(card->shortname, "My Own Chip 123");640640- sprintf(card->longname, "%s at 0x%lx irq %i",641641- card->shortname, chip->ioport, chip->irq);642642-]]>643643- </programlisting>644644- </informalexample>645645-646646- The driver field holds the minimal ID string of the647647- chip. This is used by alsa-lib's configurator, so keep it648648- simple but unique. 649649- Even the same driver can have different driver IDs to650650- distinguish the functionality of each chip type. 651651- </para>652652-653653- <para>654654- The shortname field is a string shown as more verbose655655- name. The longname field contains the information656656- shown in <filename>/proc/asound/cards</filename>. 657657- </para>658658- </section>659659-660660- <section id="basic-flow-constructor-create-other">661661- <title>5) Create other components, such as mixer, MIDI, etc.</title>662662- <para>663663- Here you define the basic components such as664664- <link linkend="pcm-interface"><citetitle>PCM</citetitle></link>,665665- mixer (e.g. <link linkend="api-ac97"><citetitle>AC97</citetitle></link>),666666- MIDI (e.g. <link linkend="midi-interface"><citetitle>MPU-401</citetitle></link>),667667- and other interfaces.668668- Also, if you want a <link linkend="proc-interface"><citetitle>proc669669- file</citetitle></link>, define it here, too.670670- </para>671671- </section>672672-673673- <section id="basic-flow-constructor-register-card">674674- <title>6) Register the card instance.</title>675675- <para>676676- <informalexample>677677- <programlisting>678678-<![CDATA[679679- err = snd_card_register(card);680680- if (err < 0) {681681- snd_card_free(card);682682- return err;683683- }684684-]]>685685- </programlisting>686686- </informalexample>687687- </para>688688-689689- <para>690690- Will be explained in the section <link691691- linkend="card-management-registration"><citetitle>Management692692- of Cards and Components</citetitle></link>, too. 693693- </para>694694- </section>695695-696696- <section id="basic-flow-constructor-set-pci">697697- <title>7) Set the PCI driver data and return zero.</title>698698- <para>699699- <informalexample>700700- <programlisting>701701-<![CDATA[702702- pci_set_drvdata(pci, card);703703- dev++;704704- return 0;705705-]]>706706- </programlisting>707707- </informalexample>708708-709709- In the above, the card record is stored. This pointer is710710- used in the remove callback and power-management711711- callbacks, too. 712712- </para>713713- </section>714714- </section>715715-716716- <section id="basic-flow-destructor">717717- <title>Destructor</title>718718- <para>719719- The destructor, remove callback, simply releases the card720720- instance. Then the ALSA middle layer will release all the721721- attached components automatically. 722722- </para>723723-724724- <para>725725- It would be typically like the following:726726-727727- <informalexample>728728- <programlisting>729729-<![CDATA[730730- static void snd_mychip_remove(struct pci_dev *pci)731731- {732732- snd_card_free(pci_get_drvdata(pci));733733- pci_set_drvdata(pci, NULL);734734- }735735-]]>736736- </programlisting>737737- </informalexample>738738-739739- The above code assumes that the card pointer is set to the PCI740740- driver data.741741- </para>742742- </section>743743-744744- <section id="basic-flow-header-files">745745- <title>Header Files</title>746746- <para>747747- For the above example, at least the following include files748748- are necessary. 749749-750750- <informalexample>751751- <programlisting>752752-<![CDATA[753753- #include <linux/init.h>754754- #include <linux/pci.h>755755- #include <linux/slab.h>756756- #include <sound/core.h>757757- #include <sound/initval.h>758758-]]>759759- </programlisting>760760- </informalexample>761761-762762- where the last one is necessary only when module options are763763- defined in the source file. If the code is split into several764764- files, the files without module options don't need them.765765- </para>766766-767767- <para>768768- In addition to these headers, you'll need769769- <filename><linux/interrupt.h></filename> for interrupt770770- handling, and <filename><asm/io.h></filename> for I/O771771- access. If you use the <function>mdelay()</function> or772772- <function>udelay()</function> functions, you'll need to include773773- <filename><linux/delay.h></filename> too. 774774- </para>775775-776776- <para>777777- The ALSA interfaces like the PCM and control APIs are defined in other778778- <filename><sound/xxx.h></filename> header files.779779- They have to be included after780780- <filename><sound/core.h></filename>.781781- </para>782782-783783- </section>784784- </chapter>785785-786786-787787-<!-- ****************************************************** -->788788-<!-- Management of Cards and Components -->789789-<!-- ****************************************************** -->790790- <chapter id="card-management">791791- <title>Management of Cards and Components</title>792792-793793- <section id="card-management-card-instance">794794- <title>Card Instance</title>795795- <para>796796- For each soundcard, a <quote>card</quote> record must be allocated.797797- </para>798798-799799- <para>800800- A card record is the headquarters of the soundcard. It manages801801- the whole list of devices (components) on the soundcard, such as802802- PCM, mixers, MIDI, synthesizer, and so on. Also, the card803803- record holds the ID and the name strings of the card, manages804804- the root of proc files, and controls the power-management states805805- and hotplug disconnections. The component list on the card806806- record is used to manage the correct release of resources at807807- destruction. 808808- </para>809809-810810- <para>811811- As mentioned above, to create a card instance, call812812- <function>snd_card_new()</function>.813813-814814- <informalexample>815815- <programlisting>816816-<![CDATA[817817- struct snd_card *card;818818- int err;819819- err = snd_card_new(&pci->dev, index, id, module, extra_size, &card);820820-]]>821821- </programlisting>822822- </informalexample>823823- </para>824824-825825- <para>826826- The function takes six arguments: the parent device pointer,827827- the card-index number, the id string, the module pointer (usually828828- <constant>THIS_MODULE</constant>),829829- the size of extra-data space, and the pointer to return the830830- card instance. The extra_size argument is used to831831- allocate card->private_data for the832832- chip-specific data. Note that these data833833- are allocated by <function>snd_card_new()</function>.834834- </para>835835-836836- <para>837837- The first argument, the pointer of struct838838- <structname>device</structname>, specifies the parent device.839839- For PCI devices, typically &pci-> is passed there.840840- </para>841841- </section>842842-843843- <section id="card-management-component">844844- <title>Components</title>845845- <para>846846- After the card is created, you can attach the components847847- (devices) to the card instance. In an ALSA driver, a component is848848- represented as a struct <structname>snd_device</structname> object.849849- A component can be a PCM instance, a control interface, a raw850850- MIDI interface, etc. Each such instance has one component851851- entry.852852- </para>853853-854854- <para>855855- A component can be created via856856- <function>snd_device_new()</function> function. 857857-858858- <informalexample>859859- <programlisting>860860-<![CDATA[861861- snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);862862-]]>863863- </programlisting>864864- </informalexample>865865- </para>866866-867867- <para>868868- This takes the card pointer, the device-level869869- (<constant>SNDRV_DEV_XXX</constant>), the data pointer, and the870870- callback pointers (<parameter>&ops</parameter>). The871871- device-level defines the type of components and the order of872872- registration and de-registration. For most components, the873873- device-level is already defined. For a user-defined component,874874- you can use <constant>SNDRV_DEV_LOWLEVEL</constant>.875875- </para>876876-877877- <para>878878- This function itself doesn't allocate the data space. The data879879- must be allocated manually beforehand, and its pointer is passed880880- as the argument. This pointer (<parameter>chip</parameter> in the881881- above example) is used as the identifier for the instance.882882- </para>883883-884884- <para>885885- Each pre-defined ALSA component such as ac97 and pcm calls886886- <function>snd_device_new()</function> inside its887887- constructor. The destructor for each component is defined in the888888- callback pointers. Hence, you don't need to take care of889889- calling a destructor for such a component.890890- </para>891891-892892- <para>893893- If you wish to create your own component, you need to894894- set the destructor function to the dev_free callback in895895- the <parameter>ops</parameter>, so that it can be released896896- automatically via <function>snd_card_free()</function>.897897- The next example will show an implementation of chip-specific898898- data.899899- </para>900900- </section>901901-902902- <section id="card-management-chip-specific">903903- <title>Chip-Specific Data</title>904904- <para>905905- Chip-specific information, e.g. the I/O port address, its906906- resource pointer, or the irq number, is stored in the907907- chip-specific record.908908-909909- <informalexample>910910- <programlisting>911911-<![CDATA[912912- struct mychip {913913- ....914914- };915915-]]>916916- </programlisting>917917- </informalexample>918918- </para>919919-920920- <para>921921- In general, there are two ways of allocating the chip record.922922- </para>923923-924924- <section id="card-management-chip-specific-snd-card-new">925925- <title>1. Allocating via <function>snd_card_new()</function>.</title>926926- <para>927927- As mentioned above, you can pass the extra-data-length928928- to the 5th argument of <function>snd_card_new()</function>, i.e.929929-930930- <informalexample>931931- <programlisting>932932-<![CDATA[933933- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,934934- sizeof(struct mychip), &card);935935-]]>936936- </programlisting>937937- </informalexample>938938-939939- struct <structname>mychip</structname> is the type of the chip record.940940- </para>941941-942942- <para>943943- In return, the allocated record can be accessed as944944-945945- <informalexample>946946- <programlisting>947947-<![CDATA[948948- struct mychip *chip = card->private_data;949949-]]>950950- </programlisting>951951- </informalexample>952952-953953- With this method, you don't have to allocate twice.954954- The record is released together with the card instance.955955- </para>956956- </section>957957-958958- <section id="card-management-chip-specific-allocate-extra">959959- <title>2. Allocating an extra device.</title>960960-961961- <para>962962- After allocating a card instance via963963- <function>snd_card_new()</function> (with964964- <constant>0</constant> on the 4th arg), call965965- <function>kzalloc()</function>. 966966-967967- <informalexample>968968- <programlisting>969969-<![CDATA[970970- struct snd_card *card;971971- struct mychip *chip;972972- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,973973- 0, &card);974974- .....975975- chip = kzalloc(sizeof(*chip), GFP_KERNEL);976976-]]>977977- </programlisting>978978- </informalexample>979979- </para>980980-981981- <para>982982- The chip record should have the field to hold the card983983- pointer at least, 984984-985985- <informalexample>986986- <programlisting>987987-<![CDATA[988988- struct mychip {989989- struct snd_card *card;990990- ....991991- };992992-]]>993993- </programlisting>994994- </informalexample>995995- </para>996996-997997- <para>998998- Then, set the card pointer in the returned chip instance.999999-10001000- <informalexample>10011001- <programlisting>10021002-<![CDATA[10031003- chip->card = card;10041004-]]>10051005- </programlisting>10061006- </informalexample>10071007- </para>10081008-10091009- <para>10101010- Next, initialize the fields, and register this chip10111011- record as a low-level device with a specified10121012- <parameter>ops</parameter>, 10131013-10141014- <informalexample>10151015- <programlisting>10161016-<![CDATA[10171017- static struct snd_device_ops ops = {10181018- .dev_free = snd_mychip_dev_free,10191019- };10201020- ....10211021- snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);10221022-]]>10231023- </programlisting>10241024- </informalexample>10251025-10261026- <function>snd_mychip_dev_free()</function> is the10271027- device-destructor function, which will call the real10281028- destructor. 10291029- </para>10301030-10311031- <para>10321032- <informalexample>10331033- <programlisting>10341034-<![CDATA[10351035- static int snd_mychip_dev_free(struct snd_device *device)10361036- {10371037- return snd_mychip_free(device->device_data);10381038- }10391039-]]>10401040- </programlisting>10411041- </informalexample>10421042-10431043- where <function>snd_mychip_free()</function> is the real destructor.10441044- </para>10451045- </section>10461046- </section>10471047-10481048- <section id="card-management-registration">10491049- <title>Registration and Release</title>10501050- <para>10511051- After all components are assigned, register the card instance10521052- by calling <function>snd_card_register()</function>. Access10531053- to the device files is enabled at this point. That is, before10541054- <function>snd_card_register()</function> is called, the10551055- components are safely inaccessible from external side. If this10561056- call fails, exit the probe function after releasing the card via10571057- <function>snd_card_free()</function>. 10581058- </para>10591059-10601060- <para>10611061- For releasing the card instance, you can call simply10621062- <function>snd_card_free()</function>. As mentioned earlier, all10631063- components are released automatically by this call. 10641064- </para>10651065-10661066- <para>10671067- For a device which allows hotplugging, you can use10681068- <function>snd_card_free_when_closed</function>. This one will10691069- postpone the destruction until all devices are closed.10701070- </para>10711071-10721072- </section>10731073-10741074- </chapter>10751075-10761076-10771077-<!-- ****************************************************** -->10781078-<!-- PCI Resource Management -->10791079-<!-- ****************************************************** -->10801080- <chapter id="pci-resource">10811081- <title>PCI Resource Management</title>10821082-10831083- <section id="pci-resource-example">10841084- <title>Full Code Example</title>10851085- <para>10861086- In this section, we'll complete the chip-specific constructor,10871087- destructor and PCI entries. Example code is shown first,10881088- below. 10891089-10901090- <example>10911091- <title>PCI Resource Management Example</title>10921092- <programlisting>10931093-<![CDATA[10941094- struct mychip {10951095- struct snd_card *card;10961096- struct pci_dev *pci;10971097-10981098- unsigned long port;10991099- int irq;11001100- };11011101-11021102- static int snd_mychip_free(struct mychip *chip)11031103- {11041104- /* disable hardware here if any */11051105- .... /* (not implemented in this document) */11061106-11071107- /* release the irq */11081108- if (chip->irq >= 0)11091109- free_irq(chip->irq, chip);11101110- /* release the I/O ports & memory */11111111- pci_release_regions(chip->pci);11121112- /* disable the PCI entry */11131113- pci_disable_device(chip->pci);11141114- /* release the data */11151115- kfree(chip);11161116- return 0;11171117- }11181118-11191119- /* chip-specific constructor */11201120- static int snd_mychip_create(struct snd_card *card,11211121- struct pci_dev *pci,11221122- struct mychip **rchip)11231123- {11241124- struct mychip *chip;11251125- int err;11261126- static struct snd_device_ops ops = {11271127- .dev_free = snd_mychip_dev_free,11281128- };11291129-11301130- *rchip = NULL;11311131-11321132- /* initialize the PCI entry */11331133- err = pci_enable_device(pci);11341134- if (err < 0)11351135- return err;11361136- /* check PCI availability (28bit DMA) */11371137- if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||11381138- pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {11391139- printk(KERN_ERR "error to set 28bit mask DMA\n");11401140- pci_disable_device(pci);11411141- return -ENXIO;11421142- }11431143-11441144- chip = kzalloc(sizeof(*chip), GFP_KERNEL);11451145- if (chip == NULL) {11461146- pci_disable_device(pci);11471147- return -ENOMEM;11481148- }11491149-11501150- /* initialize the stuff */11511151- chip->card = card;11521152- chip->pci = pci;11531153- chip->irq = -1;11541154-11551155- /* (1) PCI resource allocation */11561156- err = pci_request_regions(pci, "My Chip");11571157- if (err < 0) {11581158- kfree(chip);11591159- pci_disable_device(pci);11601160- return err;11611161- }11621162- chip->port = pci_resource_start(pci, 0);11631163- if (request_irq(pci->irq, snd_mychip_interrupt,11641164- IRQF_SHARED, KBUILD_MODNAME, chip)) {11651165- printk(KERN_ERR "cannot grab irq %d\n", pci->irq);11661166- snd_mychip_free(chip);11671167- return -EBUSY;11681168- }11691169- chip->irq = pci->irq;11701170-11711171- /* (2) initialization of the chip hardware */11721172- .... /* (not implemented in this document) */11731173-11741174- err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);11751175- if (err < 0) {11761176- snd_mychip_free(chip);11771177- return err;11781178- }11791179-11801180- *rchip = chip;11811181- return 0;11821182- } 11831183-11841184- /* PCI IDs */11851185- static struct pci_device_id snd_mychip_ids[] = {11861186- { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,11871187- PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },11881188- ....11891189- { 0, }11901190- };11911191- MODULE_DEVICE_TABLE(pci, snd_mychip_ids);11921192-11931193- /* pci_driver definition */11941194- static struct pci_driver driver = {11951195- .name = KBUILD_MODNAME,11961196- .id_table = snd_mychip_ids,11971197- .probe = snd_mychip_probe,11981198- .remove = snd_mychip_remove,11991199- };12001200-12011201- /* module initialization */12021202- static int __init alsa_card_mychip_init(void)12031203- {12041204- return pci_register_driver(&driver);12051205- }12061206-12071207- /* module clean up */12081208- static void __exit alsa_card_mychip_exit(void)12091209- {12101210- pci_unregister_driver(&driver);12111211- }12121212-12131213- module_init(alsa_card_mychip_init)12141214- module_exit(alsa_card_mychip_exit)12151215-12161216- EXPORT_NO_SYMBOLS; /* for old kernels only */12171217-]]>12181218- </programlisting>12191219- </example>12201220- </para>12211221- </section>12221222-12231223- <section id="pci-resource-some-haftas">12241224- <title>Some Hafta's</title>12251225- <para>12261226- The allocation of PCI resources is done in the12271227- <function>probe()</function> function, and usually an extra12281228- <function>xxx_create()</function> function is written for this12291229- purpose.12301230- </para>12311231-12321232- <para>12331233- In the case of PCI devices, you first have to call12341234- the <function>pci_enable_device()</function> function before12351235- allocating resources. Also, you need to set the proper PCI DMA12361236- mask to limit the accessed I/O range. In some cases, you might12371237- need to call <function>pci_set_master()</function> function,12381238- too.12391239- </para>12401240-12411241- <para>12421242- Suppose the 28bit mask, and the code to be added would be like:12431243-12441244- <informalexample>12451245- <programlisting>12461246-<![CDATA[12471247- err = pci_enable_device(pci);12481248- if (err < 0)12491249- return err;12501250- if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||12511251- pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {12521252- printk(KERN_ERR "error to set 28bit mask DMA\n");12531253- pci_disable_device(pci);12541254- return -ENXIO;12551255- }12561256-12571257-]]>12581258- </programlisting>12591259- </informalexample>12601260- </para>12611261- </section>12621262-12631263- <section id="pci-resource-resource-allocation">12641264- <title>Resource Allocation</title>12651265- <para>12661266- The allocation of I/O ports and irqs is done via standard kernel12671267- functions. Unlike ALSA ver.0.5.x., there are no helpers for12681268- that. And these resources must be released in the destructor12691269- function (see below). Also, on ALSA 0.9.x, you don't need to12701270- allocate (pseudo-)DMA for PCI like in ALSA 0.5.x.12711271- </para>12721272-12731273- <para>12741274- Now assume that the PCI device has an I/O port with 8 bytes12751275- and an interrupt. Then struct <structname>mychip</structname> will have the12761276- following fields:12771277-12781278- <informalexample>12791279- <programlisting>12801280-<![CDATA[12811281- struct mychip {12821282- struct snd_card *card;12831283-12841284- unsigned long port;12851285- int irq;12861286- };12871287-]]>12881288- </programlisting>12891289- </informalexample>12901290- </para>12911291-12921292- <para>12931293- For an I/O port (and also a memory region), you need to have12941294- the resource pointer for the standard resource management. For12951295- an irq, you have to keep only the irq number (integer). But you12961296- need to initialize this number as -1 before actual allocation,12971297- since irq 0 is valid. The port address and its resource pointer12981298- can be initialized as null by12991299- <function>kzalloc()</function> automatically, so you13001300- don't have to take care of resetting them. 13011301- </para>13021302-13031303- <para>13041304- The allocation of an I/O port is done like this:13051305-13061306- <informalexample>13071307- <programlisting>13081308-<![CDATA[13091309- err = pci_request_regions(pci, "My Chip");13101310- if (err < 0) { 13111311- kfree(chip);13121312- pci_disable_device(pci);13131313- return err;13141314- }13151315- chip->port = pci_resource_start(pci, 0);13161316-]]>13171317- </programlisting>13181318- </informalexample>13191319- </para>13201320-13211321- <para>13221322- <!-- obsolete -->13231323- It will reserve the I/O port region of 8 bytes of the given13241324- PCI device. The returned value, chip->res_port, is allocated13251325- via <function>kmalloc()</function> by13261326- <function>request_region()</function>. The pointer must be13271327- released via <function>kfree()</function>, but there is a13281328- problem with this. This issue will be explained later.13291329- </para>13301330-13311331- <para>13321332- The allocation of an interrupt source is done like this:13331333-13341334- <informalexample>13351335- <programlisting>13361336-<![CDATA[13371337- if (request_irq(pci->irq, snd_mychip_interrupt,13381338- IRQF_SHARED, KBUILD_MODNAME, chip)) {13391339- printk(KERN_ERR "cannot grab irq %d\n", pci->irq);13401340- snd_mychip_free(chip);13411341- return -EBUSY;13421342- }13431343- chip->irq = pci->irq;13441344-]]>13451345- </programlisting>13461346- </informalexample>13471347-13481348- where <function>snd_mychip_interrupt()</function> is the13491349- interrupt handler defined <link13501350- linkend="pcm-interface-interrupt-handler"><citetitle>later</citetitle></link>.13511351- Note that chip->irq should be defined13521352- only when <function>request_irq()</function> succeeded.13531353- </para>13541354-13551355- <para>13561356- On the PCI bus, interrupts can be shared. Thus,13571357- <constant>IRQF_SHARED</constant> is used as the interrupt flag of13581358- <function>request_irq()</function>. 13591359- </para>13601360-13611361- <para>13621362- The last argument of <function>request_irq()</function> is the13631363- data pointer passed to the interrupt handler. Usually, the13641364- chip-specific record is used for that, but you can use what you13651365- like, too. 13661366- </para>13671367-13681368- <para>13691369- I won't give details about the interrupt handler at this13701370- point, but at least its appearance can be explained now. The13711371- interrupt handler looks usually like the following: 13721372-13731373- <informalexample>13741374- <programlisting>13751375-<![CDATA[13761376- static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)13771377- {13781378- struct mychip *chip = dev_id;13791379- ....13801380- return IRQ_HANDLED;13811381- }13821382-]]>13831383- </programlisting>13841384- </informalexample>13851385- </para>13861386-13871387- <para>13881388- Now let's write the corresponding destructor for the resources13891389- above. The role of destructor is simple: disable the hardware13901390- (if already activated) and release the resources. So far, we13911391- have no hardware part, so the disabling code is not written here. 13921392- </para>13931393-13941394- <para>13951395- To release the resources, the <quote>check-and-release</quote>13961396- method is a safer way. For the interrupt, do like this: 13971397-13981398- <informalexample>13991399- <programlisting>14001400-<![CDATA[14011401- if (chip->irq >= 0)14021402- free_irq(chip->irq, chip);14031403-]]>14041404- </programlisting>14051405- </informalexample>14061406-14071407- Since the irq number can start from 0, you should initialize14081408- chip->irq with a negative value (e.g. -1), so that you can14091409- check the validity of the irq number as above.14101410- </para>14111411-14121412- <para>14131413- When you requested I/O ports or memory regions via14141414- <function>pci_request_region()</function> or14151415- <function>pci_request_regions()</function> like in this example,14161416- release the resource(s) using the corresponding function,14171417- <function>pci_release_region()</function> or14181418- <function>pci_release_regions()</function>.14191419-14201420- <informalexample>14211421- <programlisting>14221422-<![CDATA[14231423- pci_release_regions(chip->pci);14241424-]]>14251425- </programlisting>14261426- </informalexample>14271427- </para>14281428-14291429- <para>14301430- When you requested manually via <function>request_region()</function>14311431- or <function>request_mem_region</function>, you can release it via14321432- <function>release_resource()</function>. Suppose that you keep14331433- the resource pointer returned from <function>request_region()</function>14341434- in chip->res_port, the release procedure looks like:14351435-14361436- <informalexample>14371437- <programlisting>14381438-<![CDATA[14391439- release_and_free_resource(chip->res_port);14401440-]]>14411441- </programlisting>14421442- </informalexample>14431443- </para>14441444-14451445- <para>14461446- Don't forget to call <function>pci_disable_device()</function>14471447- before the end.14481448- </para>14491449-14501450- <para>14511451- And finally, release the chip-specific record.14521452-14531453- <informalexample>14541454- <programlisting>14551455-<![CDATA[14561456- kfree(chip);14571457-]]>14581458- </programlisting>14591459- </informalexample>14601460- </para>14611461-14621462- <para>14631463- We didn't implement the hardware disabling part in the above.14641464- If you need to do this, please note that the destructor may be14651465- called even before the initialization of the chip is completed.14661466- It would be better to have a flag to skip hardware disabling14671467- if the hardware was not initialized yet.14681468- </para>14691469-14701470- <para>14711471- When the chip-data is assigned to the card using14721472- <function>snd_device_new()</function> with14731473- <constant>SNDRV_DEV_LOWLELVEL</constant> , its destructor is 14741474- called at the last. That is, it is assured that all other14751475- components like PCMs and controls have already been released.14761476- You don't have to stop PCMs, etc. explicitly, but just14771477- call low-level hardware stopping.14781478- </para>14791479-14801480- <para>14811481- The management of a memory-mapped region is almost as same as14821482- the management of an I/O port. You'll need three fields like14831483- the following: 14841484-14851485- <informalexample>14861486- <programlisting>14871487-<![CDATA[14881488- struct mychip {14891489- ....14901490- unsigned long iobase_phys;14911491- void __iomem *iobase_virt;14921492- };14931493-]]>14941494- </programlisting>14951495- </informalexample>14961496-14971497- and the allocation would be like below:14981498-14991499- <informalexample>15001500- <programlisting>15011501-<![CDATA[15021502- if ((err = pci_request_regions(pci, "My Chip")) < 0) {15031503- kfree(chip);15041504- return err;15051505- }15061506- chip->iobase_phys = pci_resource_start(pci, 0);15071507- chip->iobase_virt = ioremap_nocache(chip->iobase_phys,15081508- pci_resource_len(pci, 0));15091509-]]>15101510- </programlisting>15111511- </informalexample>15121512-15131513- and the corresponding destructor would be:15141514-15151515- <informalexample>15161516- <programlisting>15171517-<![CDATA[15181518- static int snd_mychip_free(struct mychip *chip)15191519- {15201520- ....15211521- if (chip->iobase_virt)15221522- iounmap(chip->iobase_virt);15231523- ....15241524- pci_release_regions(chip->pci);15251525- ....15261526- }15271527-]]>15281528- </programlisting>15291529- </informalexample>15301530- </para>15311531-15321532- </section>15331533-15341534- <section id="pci-resource-entries">15351535- <title>PCI Entries</title>15361536- <para>15371537- So far, so good. Let's finish the missing PCI15381538- stuff. At first, we need a15391539- <structname>pci_device_id</structname> table for this15401540- chipset. It's a table of PCI vendor/device ID number, and some15411541- masks. 15421542- </para>15431543-15441544- <para>15451545- For example,15461546-15471547- <informalexample>15481548- <programlisting>15491549-<![CDATA[15501550- static struct pci_device_id snd_mychip_ids[] = {15511551- { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,15521552- PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },15531553- ....15541554- { 0, }15551555- };15561556- MODULE_DEVICE_TABLE(pci, snd_mychip_ids);15571557-]]>15581558- </programlisting>15591559- </informalexample>15601560- </para>15611561-15621562- <para>15631563- The first and second fields of15641564- the <structname>pci_device_id</structname> structure are the vendor and15651565- device IDs. If you have no reason to filter the matching15661566- devices, you can leave the remaining fields as above. The last15671567- field of the <structname>pci_device_id</structname> struct contains15681568- private data for this entry. You can specify any value here, for15691569- example, to define specific operations for supported device IDs.15701570- Such an example is found in the intel8x0 driver. 15711571- </para>15721572-15731573- <para>15741574- The last entry of this list is the terminator. You must15751575- specify this all-zero entry. 15761576- </para>15771577-15781578- <para>15791579- Then, prepare the <structname>pci_driver</structname> record:15801580-15811581- <informalexample>15821582- <programlisting>15831583-<![CDATA[15841584- static struct pci_driver driver = {15851585- .name = KBUILD_MODNAME,15861586- .id_table = snd_mychip_ids,15871587- .probe = snd_mychip_probe,15881588- .remove = snd_mychip_remove,15891589- };15901590-]]>15911591- </programlisting>15921592- </informalexample>15931593- </para>15941594-15951595- <para>15961596- The <structfield>probe</structfield> and15971597- <structfield>remove</structfield> functions have already15981598- been defined in the previous sections.15991599- The <structfield>name</structfield>16001600- field is the name string of this device. Note that you must not16011601- use a slash <quote>/</quote> in this string. 16021602- </para>16031603-16041604- <para>16051605- And at last, the module entries:16061606-16071607- <informalexample>16081608- <programlisting>16091609-<![CDATA[16101610- static int __init alsa_card_mychip_init(void)16111611- {16121612- return pci_register_driver(&driver);16131613- }16141614-16151615- static void __exit alsa_card_mychip_exit(void)16161616- {16171617- pci_unregister_driver(&driver);16181618- }16191619-16201620- module_init(alsa_card_mychip_init)16211621- module_exit(alsa_card_mychip_exit)16221622-]]>16231623- </programlisting>16241624- </informalexample>16251625- </para>16261626-16271627- <para>16281628- Note that these module entries are tagged with16291629- <parameter>__init</parameter> and 16301630- <parameter>__exit</parameter> prefixes.16311631- </para>16321632-16331633- <para>16341634- Oh, one thing was forgotten. If you have no exported symbols,16351635- you need to declare it in 2.2 or 2.4 kernels (it's not necessary in 2.6 kernels).16361636-16371637- <informalexample>16381638- <programlisting>16391639-<![CDATA[16401640- EXPORT_NO_SYMBOLS;16411641-]]>16421642- </programlisting>16431643- </informalexample>16441644-16451645- That's all!16461646- </para>16471647- </section>16481648- </chapter>16491649-16501650-16511651-<!-- ****************************************************** -->16521652-<!-- PCM Interface -->16531653-<!-- ****************************************************** -->16541654- <chapter id="pcm-interface">16551655- <title>PCM Interface</title>16561656-16571657- <section id="pcm-interface-general">16581658- <title>General</title>16591659- <para>16601660- The PCM middle layer of ALSA is quite powerful and it is only16611661- necessary for each driver to implement the low-level functions16621662- to access its hardware.16631663- </para>16641664-16651665- <para>16661666- For accessing to the PCM layer, you need to include16671667- <filename><sound/pcm.h></filename> first. In addition,16681668- <filename><sound/pcm_params.h></filename> might be needed16691669- if you access to some functions related with hw_param. 16701670- </para>16711671-16721672- <para>16731673- Each card device can have up to four pcm instances. A pcm16741674- instance corresponds to a pcm device file. The limitation of16751675- number of instances comes only from the available bit size of16761676- the Linux's device numbers. Once when 64bit device number is16771677- used, we'll have more pcm instances available. 16781678- </para>16791679-16801680- <para>16811681- A pcm instance consists of pcm playback and capture streams,16821682- and each pcm stream consists of one or more pcm substreams. Some16831683- soundcards support multiple playback functions. For example,16841684- emu10k1 has a PCM playback of 32 stereo substreams. In this case, at16851685- each open, a free substream is (usually) automatically chosen16861686- and opened. Meanwhile, when only one substream exists and it was16871687- already opened, the successful open will either block16881688- or error with <constant>EAGAIN</constant> according to the16891689- file open mode. But you don't have to care about such details in your16901690- driver. The PCM middle layer will take care of such work.16911691- </para>16921692- </section>16931693-16941694- <section id="pcm-interface-example">16951695- <title>Full Code Example</title>16961696- <para>16971697- The example code below does not include any hardware access16981698- routines but shows only the skeleton, how to build up the PCM16991699- interfaces.17001700-17011701- <example>17021702- <title>PCM Example Code</title>17031703- <programlisting>17041704-<![CDATA[17051705- #include <sound/pcm.h>17061706- ....17071707-17081708- /* hardware definition */17091709- static struct snd_pcm_hardware snd_mychip_playback_hw = {17101710- .info = (SNDRV_PCM_INFO_MMAP |17111711- SNDRV_PCM_INFO_INTERLEAVED |17121712- SNDRV_PCM_INFO_BLOCK_TRANSFER |17131713- SNDRV_PCM_INFO_MMAP_VALID),17141714- .formats = SNDRV_PCM_FMTBIT_S16_LE,17151715- .rates = SNDRV_PCM_RATE_8000_48000,17161716- .rate_min = 8000,17171717- .rate_max = 48000,17181718- .channels_min = 2,17191719- .channels_max = 2,17201720- .buffer_bytes_max = 32768,17211721- .period_bytes_min = 4096,17221722- .period_bytes_max = 32768,17231723- .periods_min = 1,17241724- .periods_max = 1024,17251725- };17261726-17271727- /* hardware definition */17281728- static struct snd_pcm_hardware snd_mychip_capture_hw = {17291729- .info = (SNDRV_PCM_INFO_MMAP |17301730- SNDRV_PCM_INFO_INTERLEAVED |17311731- SNDRV_PCM_INFO_BLOCK_TRANSFER |17321732- SNDRV_PCM_INFO_MMAP_VALID),17331733- .formats = SNDRV_PCM_FMTBIT_S16_LE,17341734- .rates = SNDRV_PCM_RATE_8000_48000,17351735- .rate_min = 8000,17361736- .rate_max = 48000,17371737- .channels_min = 2,17381738- .channels_max = 2,17391739- .buffer_bytes_max = 32768,17401740- .period_bytes_min = 4096,17411741- .period_bytes_max = 32768,17421742- .periods_min = 1,17431743- .periods_max = 1024,17441744- };17451745-17461746- /* open callback */17471747- static int snd_mychip_playback_open(struct snd_pcm_substream *substream)17481748- {17491749- struct mychip *chip = snd_pcm_substream_chip(substream);17501750- struct snd_pcm_runtime *runtime = substream->runtime;17511751-17521752- runtime->hw = snd_mychip_playback_hw;17531753- /* more hardware-initialization will be done here */17541754- ....17551755- return 0;17561756- }17571757-17581758- /* close callback */17591759- static int snd_mychip_playback_close(struct snd_pcm_substream *substream)17601760- {17611761- struct mychip *chip = snd_pcm_substream_chip(substream);17621762- /* the hardware-specific codes will be here */17631763- ....17641764- return 0;17651765-17661766- }17671767-17681768- /* open callback */17691769- static int snd_mychip_capture_open(struct snd_pcm_substream *substream)17701770- {17711771- struct mychip *chip = snd_pcm_substream_chip(substream);17721772- struct snd_pcm_runtime *runtime = substream->runtime;17731773-17741774- runtime->hw = snd_mychip_capture_hw;17751775- /* more hardware-initialization will be done here */17761776- ....17771777- return 0;17781778- }17791779-17801780- /* close callback */17811781- static int snd_mychip_capture_close(struct snd_pcm_substream *substream)17821782- {17831783- struct mychip *chip = snd_pcm_substream_chip(substream);17841784- /* the hardware-specific codes will be here */17851785- ....17861786- return 0;17871787-17881788- }17891789-17901790- /* hw_params callback */17911791- static int snd_mychip_pcm_hw_params(struct snd_pcm_substream *substream,17921792- struct snd_pcm_hw_params *hw_params)17931793- {17941794- return snd_pcm_lib_malloc_pages(substream,17951795- params_buffer_bytes(hw_params));17961796- }17971797-17981798- /* hw_free callback */17991799- static int snd_mychip_pcm_hw_free(struct snd_pcm_substream *substream)18001800- {18011801- return snd_pcm_lib_free_pages(substream);18021802- }18031803-18041804- /* prepare callback */18051805- static int snd_mychip_pcm_prepare(struct snd_pcm_substream *substream)18061806- {18071807- struct mychip *chip = snd_pcm_substream_chip(substream);18081808- struct snd_pcm_runtime *runtime = substream->runtime;18091809-18101810- /* set up the hardware with the current configuration18111811- * for example...18121812- */18131813- mychip_set_sample_format(chip, runtime->format);18141814- mychip_set_sample_rate(chip, runtime->rate);18151815- mychip_set_channels(chip, runtime->channels);18161816- mychip_set_dma_setup(chip, runtime->dma_addr,18171817- chip->buffer_size,18181818- chip->period_size);18191819- return 0;18201820- }18211821-18221822- /* trigger callback */18231823- static int snd_mychip_pcm_trigger(struct snd_pcm_substream *substream,18241824- int cmd)18251825- {18261826- switch (cmd) {18271827- case SNDRV_PCM_TRIGGER_START:18281828- /* do something to start the PCM engine */18291829- ....18301830- break;18311831- case SNDRV_PCM_TRIGGER_STOP:18321832- /* do something to stop the PCM engine */18331833- ....18341834- break;18351835- default:18361836- return -EINVAL;18371837- }18381838- }18391839-18401840- /* pointer callback */18411841- static snd_pcm_uframes_t18421842- snd_mychip_pcm_pointer(struct snd_pcm_substream *substream)18431843- {18441844- struct mychip *chip = snd_pcm_substream_chip(substream);18451845- unsigned int current_ptr;18461846-18471847- /* get the current hardware pointer */18481848- current_ptr = mychip_get_hw_pointer(chip);18491849- return current_ptr;18501850- }18511851-18521852- /* operators */18531853- static struct snd_pcm_ops snd_mychip_playback_ops = {18541854- .open = snd_mychip_playback_open,18551855- .close = snd_mychip_playback_close,18561856- .ioctl = snd_pcm_lib_ioctl,18571857- .hw_params = snd_mychip_pcm_hw_params,18581858- .hw_free = snd_mychip_pcm_hw_free,18591859- .prepare = snd_mychip_pcm_prepare,18601860- .trigger = snd_mychip_pcm_trigger,18611861- .pointer = snd_mychip_pcm_pointer,18621862- };18631863-18641864- /* operators */18651865- static struct snd_pcm_ops snd_mychip_capture_ops = {18661866- .open = snd_mychip_capture_open,18671867- .close = snd_mychip_capture_close,18681868- .ioctl = snd_pcm_lib_ioctl,18691869- .hw_params = snd_mychip_pcm_hw_params,18701870- .hw_free = snd_mychip_pcm_hw_free,18711871- .prepare = snd_mychip_pcm_prepare,18721872- .trigger = snd_mychip_pcm_trigger,18731873- .pointer = snd_mychip_pcm_pointer,18741874- };18751875-18761876- /*18771877- * definitions of capture are omitted here...18781878- */18791879-18801880- /* create a pcm device */18811881- static int snd_mychip_new_pcm(struct mychip *chip)18821882- {18831883- struct snd_pcm *pcm;18841884- int err;18851885-18861886- err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);18871887- if (err < 0) 18881888- return err;18891889- pcm->private_data = chip;18901890- strcpy(pcm->name, "My Chip");18911891- chip->pcm = pcm;18921892- /* set operators */18931893- snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,18941894- &snd_mychip_playback_ops);18951895- snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,18961896- &snd_mychip_capture_ops);18971897- /* pre-allocation of buffers */18981898- /* NOTE: this may fail */18991899- snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,19001900- snd_dma_pci_data(chip->pci),19011901- 64*1024, 64*1024);19021902- return 0;19031903- }19041904-]]>19051905- </programlisting>19061906- </example>19071907- </para>19081908- </section>19091909-19101910- <section id="pcm-interface-constructor">19111911- <title>Constructor</title>19121912- <para>19131913- A pcm instance is allocated by the <function>snd_pcm_new()</function>19141914- function. It would be better to create a constructor for pcm,19151915- namely, 19161916-19171917- <informalexample>19181918- <programlisting>19191919-<![CDATA[19201920- static int snd_mychip_new_pcm(struct mychip *chip)19211921- {19221922- struct snd_pcm *pcm;19231923- int err;19241924-19251925- err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);19261926- if (err < 0) 19271927- return err;19281928- pcm->private_data = chip;19291929- strcpy(pcm->name, "My Chip");19301930- chip->pcm = pcm;19311931- ....19321932- return 0;19331933- }19341934-]]>19351935- </programlisting>19361936- </informalexample>19371937- </para>19381938-19391939- <para>19401940- The <function>snd_pcm_new()</function> function takes four19411941- arguments. The first argument is the card pointer to which this19421942- pcm is assigned, and the second is the ID string. 19431943- </para>19441944-19451945- <para>19461946- The third argument (<parameter>index</parameter>, 0 in the19471947- above) is the index of this new pcm. It begins from zero. If19481948- you create more than one pcm instances, specify the19491949- different numbers in this argument. For example,19501950- <parameter>index</parameter> = 1 for the second PCM device. 19511951- </para>19521952-19531953- <para>19541954- The fourth and fifth arguments are the number of substreams19551955- for playback and capture, respectively. Here 1 is used for19561956- both arguments. When no playback or capture substreams are available,19571957- pass 0 to the corresponding argument.19581958- </para>19591959-19601960- <para>19611961- If a chip supports multiple playbacks or captures, you can19621962- specify more numbers, but they must be handled properly in19631963- open/close, etc. callbacks. When you need to know which19641964- substream you are referring to, then it can be obtained from19651965- struct <structname>snd_pcm_substream</structname> data passed to each callback19661966- as follows: 19671967-19681968- <informalexample>19691969- <programlisting>19701970-<![CDATA[19711971- struct snd_pcm_substream *substream;19721972- int index = substream->number;19731973-]]>19741974- </programlisting>19751975- </informalexample>19761976- </para>19771977-19781978- <para>19791979- After the pcm is created, you need to set operators for each19801980- pcm stream. 19811981-19821982- <informalexample>19831983- <programlisting>19841984-<![CDATA[19851985- snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,19861986- &snd_mychip_playback_ops);19871987- snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,19881988- &snd_mychip_capture_ops);19891989-]]>19901990- </programlisting>19911991- </informalexample>19921992- </para>19931993-19941994- <para>19951995- The operators are defined typically like this:19961996-19971997- <informalexample>19981998- <programlisting>19991999-<![CDATA[20002000- static struct snd_pcm_ops snd_mychip_playback_ops = {20012001- .open = snd_mychip_pcm_open,20022002- .close = snd_mychip_pcm_close,20032003- .ioctl = snd_pcm_lib_ioctl,20042004- .hw_params = snd_mychip_pcm_hw_params,20052005- .hw_free = snd_mychip_pcm_hw_free,20062006- .prepare = snd_mychip_pcm_prepare,20072007- .trigger = snd_mychip_pcm_trigger,20082008- .pointer = snd_mychip_pcm_pointer,20092009- };20102010-]]>20112011- </programlisting>20122012- </informalexample>20132013-20142014- All the callbacks are described in the20152015- <link linkend="pcm-interface-operators"><citetitle>20162016- Operators</citetitle></link> subsection.20172017- </para>20182018-20192019- <para>20202020- After setting the operators, you probably will want to20212021- pre-allocate the buffer. For the pre-allocation, simply call20222022- the following: 20232023-20242024- <informalexample>20252025- <programlisting>20262026-<![CDATA[20272027- snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,20282028- snd_dma_pci_data(chip->pci),20292029- 64*1024, 64*1024);20302030-]]>20312031- </programlisting>20322032- </informalexample>20332033-20342034- It will allocate a buffer up to 64kB as default.20352035- Buffer management details will be described in the later section <link20362036- linkend="buffer-and-memory"><citetitle>Buffer and Memory20372037- Management</citetitle></link>. 20382038- </para>20392039-20402040- <para>20412041- Additionally, you can set some extra information for this pcm20422042- in pcm->info_flags.20432043- The available values are defined as20442044- <constant>SNDRV_PCM_INFO_XXX</constant> in20452045- <filename><sound/asound.h></filename>, which is used for20462046- the hardware definition (described later). When your soundchip20472047- supports only half-duplex, specify like this: 20482048-20492049- <informalexample>20502050- <programlisting>20512051-<![CDATA[20522052- pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;20532053-]]>20542054- </programlisting>20552055- </informalexample>20562056- </para>20572057- </section>20582058-20592059- <section id="pcm-interface-destructor">20602060- <title>... And the Destructor?</title>20612061- <para>20622062- The destructor for a pcm instance is not always20632063- necessary. Since the pcm device will be released by the middle20642064- layer code automatically, you don't have to call the destructor20652065- explicitly.20662066- </para>20672067-20682068- <para>20692069- The destructor would be necessary if you created20702070- special records internally and needed to release them. In such a20712071- case, set the destructor function to20722072- pcm->private_free: 20732073-20742074- <example>20752075- <title>PCM Instance with a Destructor</title>20762076- <programlisting>20772077-<![CDATA[20782078- static void mychip_pcm_free(struct snd_pcm *pcm)20792079- {20802080- struct mychip *chip = snd_pcm_chip(pcm);20812081- /* free your own data */20822082- kfree(chip->my_private_pcm_data);20832083- /* do what you like else */20842084- ....20852085- }20862086-20872087- static int snd_mychip_new_pcm(struct mychip *chip)20882088- {20892089- struct snd_pcm *pcm;20902090- ....20912091- /* allocate your own data */20922092- chip->my_private_pcm_data = kmalloc(...);20932093- /* set the destructor */20942094- pcm->private_data = chip;20952095- pcm->private_free = mychip_pcm_free;20962096- ....20972097- }20982098-]]>20992099- </programlisting>21002100- </example>21012101- </para>21022102- </section>21032103-21042104- <section id="pcm-interface-runtime">21052105- <title>Runtime Pointer - The Chest of PCM Information</title>21062106- <para>21072107- When the PCM substream is opened, a PCM runtime instance is21082108- allocated and assigned to the substream. This pointer is21092109- accessible via <constant>substream->runtime</constant>.21102110- This runtime pointer holds most information you need21112111- to control the PCM: the copy of hw_params and sw_params configurations, the buffer21122112- pointers, mmap records, spinlocks, etc.21132113- </para>21142114-21152115- <para>21162116- The definition of runtime instance is found in21172117- <filename><sound/pcm.h></filename>. Here are21182118- the contents of this file:21192119- <informalexample>21202120- <programlisting>21212121-<![CDATA[21222122-struct _snd_pcm_runtime {21232123- /* -- Status -- */21242124- struct snd_pcm_substream *trigger_master;21252125- snd_timestamp_t trigger_tstamp; /* trigger timestamp */21262126- int overrange;21272127- snd_pcm_uframes_t avail_max;21282128- snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */21292129- snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/21302130-21312131- /* -- HW params -- */21322132- snd_pcm_access_t access; /* access mode */21332133- snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */21342134- snd_pcm_subformat_t subformat; /* subformat */21352135- unsigned int rate; /* rate in Hz */21362136- unsigned int channels; /* channels */21372137- snd_pcm_uframes_t period_size; /* period size */21382138- unsigned int periods; /* periods */21392139- snd_pcm_uframes_t buffer_size; /* buffer size */21402140- unsigned int tick_time; /* tick time */21412141- snd_pcm_uframes_t min_align; /* Min alignment for the format */21422142- size_t byte_align;21432143- unsigned int frame_bits;21442144- unsigned int sample_bits;21452145- unsigned int info;21462146- unsigned int rate_num;21472147- unsigned int rate_den;21482148-21492149- /* -- SW params -- */21502150- struct timespec tstamp_mode; /* mmap timestamp is updated */21512151- unsigned int period_step;21522152- unsigned int sleep_min; /* min ticks to sleep */21532153- snd_pcm_uframes_t start_threshold;21542154- snd_pcm_uframes_t stop_threshold;21552155- snd_pcm_uframes_t silence_threshold; /* Silence filling happens when21562156- noise is nearest than this */21572157- snd_pcm_uframes_t silence_size; /* Silence filling size */21582158- snd_pcm_uframes_t boundary; /* pointers wrap point */21592159-21602160- snd_pcm_uframes_t silenced_start;21612161- snd_pcm_uframes_t silenced_size;21622162-21632163- snd_pcm_sync_id_t sync; /* hardware synchronization ID */21642164-21652165- /* -- mmap -- */21662166- volatile struct snd_pcm_mmap_status *status;21672167- volatile struct snd_pcm_mmap_control *control;21682168- atomic_t mmap_count;21692169-21702170- /* -- locking / scheduling -- */21712171- spinlock_t lock;21722172- wait_queue_head_t sleep;21732173- struct timer_list tick_timer;21742174- struct fasync_struct *fasync;21752175-21762176- /* -- private section -- */21772177- void *private_data;21782178- void (*private_free)(struct snd_pcm_runtime *runtime);21792179-21802180- /* -- hardware description -- */21812181- struct snd_pcm_hardware hw;21822182- struct snd_pcm_hw_constraints hw_constraints;21832183-21842184- /* -- timer -- */21852185- unsigned int timer_resolution; /* timer resolution */21862186-21872187- /* -- DMA -- */ 21882188- unsigned char *dma_area; /* DMA area */21892189- dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */21902190- size_t dma_bytes; /* size of DMA area */21912191-21922192- struct snd_dma_buffer *dma_buffer_p; /* allocated buffer */21932193-21942194-#if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)21952195- /* -- OSS things -- */21962196- struct snd_pcm_oss_runtime oss;21972197-#endif21982198-};21992199-]]>22002200- </programlisting>22012201- </informalexample>22022202- </para>22032203-22042204- <para>22052205- For the operators (callbacks) of each sound driver, most of22062206- these records are supposed to be read-only. Only the PCM22072207- middle-layer changes / updates them. The exceptions are22082208- the hardware description (hw) DMA buffer information and the22092209- private data. Besides, if you use the standard buffer allocation22102210- method via <function>snd_pcm_lib_malloc_pages()</function>,22112211- you don't need to set the DMA buffer information by yourself.22122212- </para>22132213-22142214- <para>22152215- In the sections below, important records are explained.22162216- </para>22172217-22182218- <section id="pcm-interface-runtime-hw">22192219- <title>Hardware Description</title>22202220- <para>22212221- The hardware descriptor (struct <structname>snd_pcm_hardware</structname>)22222222- contains the definitions of the fundamental hardware22232223- configuration. Above all, you'll need to define this in22242224- <link linkend="pcm-interface-operators-open-callback"><citetitle>22252225- the open callback</citetitle></link>.22262226- Note that the runtime instance holds the copy of the22272227- descriptor, not the pointer to the existing descriptor. That22282228- is, in the open callback, you can modify the copied descriptor22292229- (<constant>runtime->hw</constant>) as you need. For example, if the maximum22302230- number of channels is 1 only on some chip models, you can22312231- still use the same hardware descriptor and change the22322232- channels_max later:22332233- <informalexample>22342234- <programlisting>22352235-<![CDATA[22362236- struct snd_pcm_runtime *runtime = substream->runtime;22372237- ...22382238- runtime->hw = snd_mychip_playback_hw; /* common definition */22392239- if (chip->model == VERY_OLD_ONE)22402240- runtime->hw.channels_max = 1;22412241-]]>22422242- </programlisting>22432243- </informalexample>22442244- </para>22452245-22462246- <para>22472247- Typically, you'll have a hardware descriptor as below:22482248- <informalexample>22492249- <programlisting>22502250-<![CDATA[22512251- static struct snd_pcm_hardware snd_mychip_playback_hw = {22522252- .info = (SNDRV_PCM_INFO_MMAP |22532253- SNDRV_PCM_INFO_INTERLEAVED |22542254- SNDRV_PCM_INFO_BLOCK_TRANSFER |22552255- SNDRV_PCM_INFO_MMAP_VALID),22562256- .formats = SNDRV_PCM_FMTBIT_S16_LE,22572257- .rates = SNDRV_PCM_RATE_8000_48000,22582258- .rate_min = 8000,22592259- .rate_max = 48000,22602260- .channels_min = 2,22612261- .channels_max = 2,22622262- .buffer_bytes_max = 32768,22632263- .period_bytes_min = 4096,22642264- .period_bytes_max = 32768,22652265- .periods_min = 1,22662266- .periods_max = 1024,22672267- };22682268-]]>22692269- </programlisting>22702270- </informalexample>22712271- </para>22722272-22732273- <para>22742274- <itemizedlist>22752275- <listitem><para>22762276- The <structfield>info</structfield> field contains the type and22772277- capabilities of this pcm. The bit flags are defined in22782278- <filename><sound/asound.h></filename> as22792279- <constant>SNDRV_PCM_INFO_XXX</constant>. Here, at least, you22802280- have to specify whether the mmap is supported and which22812281- interleaved format is supported.22822282- When the hardware supports mmap, add the22832283- <constant>SNDRV_PCM_INFO_MMAP</constant> flag here. When the22842284- hardware supports the interleaved or the non-interleaved22852285- formats, <constant>SNDRV_PCM_INFO_INTERLEAVED</constant> or22862286- <constant>SNDRV_PCM_INFO_NONINTERLEAVED</constant> flag must22872287- be set, respectively. If both are supported, you can set both,22882288- too. 22892289- </para>22902290-22912291- <para>22922292- In the above example, <constant>MMAP_VALID</constant> and22932293- <constant>BLOCK_TRANSFER</constant> are specified for the OSS mmap22942294- mode. Usually both are set. Of course,22952295- <constant>MMAP_VALID</constant> is set only if the mmap is22962296- really supported. 22972297- </para>22982298-22992299- <para>23002300- The other possible flags are23012301- <constant>SNDRV_PCM_INFO_PAUSE</constant> and23022302- <constant>SNDRV_PCM_INFO_RESUME</constant>. The23032303- <constant>PAUSE</constant> bit means that the pcm supports the23042304- <quote>pause</quote> operation, while the23052305- <constant>RESUME</constant> bit means that the pcm supports23062306- the full <quote>suspend/resume</quote> operation.23072307- If the <constant>PAUSE</constant> flag is set,23082308- the <structfield>trigger</structfield> callback below23092309- must handle the corresponding (pause push/release) commands.23102310- The suspend/resume trigger commands can be defined even without23112311- the <constant>RESUME</constant> flag. See <link23122312- linkend="power-management"><citetitle>23132313- Power Management</citetitle></link> section for details.23142314- </para>23152315-23162316- <para>23172317- When the PCM substreams can be synchronized (typically,23182318- synchronized start/stop of a playback and a capture streams),23192319- you can give <constant>SNDRV_PCM_INFO_SYNC_START</constant>,23202320- too. In this case, you'll need to check the linked-list of23212321- PCM substreams in the trigger callback. This will be23222322- described in the later section.23232323- </para>23242324- </listitem>23252325-23262326- <listitem>23272327- <para>23282328- <structfield>formats</structfield> field contains the bit-flags23292329- of supported formats (<constant>SNDRV_PCM_FMTBIT_XXX</constant>).23302330- If the hardware supports more than one format, give all or'ed23312331- bits. In the example above, the signed 16bit little-endian23322332- format is specified.23332333- </para>23342334- </listitem>23352335-23362336- <listitem>23372337- <para>23382338- <structfield>rates</structfield> field contains the bit-flags of23392339- supported rates (<constant>SNDRV_PCM_RATE_XXX</constant>).23402340- When the chip supports continuous rates, pass23412341- <constant>CONTINUOUS</constant> bit additionally.23422342- The pre-defined rate bits are provided only for typical23432343- rates. If your chip supports unconventional rates, you need to add23442344- the <constant>KNOT</constant> bit and set up the hardware23452345- constraint manually (explained later).23462346- </para>23472347- </listitem>23482348-23492349- <listitem>23502350- <para>23512351- <structfield>rate_min</structfield> and23522352- <structfield>rate_max</structfield> define the minimum and23532353- maximum sample rate. This should correspond somehow to23542354- <structfield>rates</structfield> bits.23552355- </para>23562356- </listitem>23572357-23582358- <listitem>23592359- <para>23602360- <structfield>channel_min</structfield> and23612361- <structfield>channel_max</structfield> 23622362- define, as you might already expected, the minimum and maximum23632363- number of channels.23642364- </para>23652365- </listitem>23662366-23672367- <listitem>23682368- <para>23692369- <structfield>buffer_bytes_max</structfield> defines the23702370- maximum buffer size in bytes. There is no23712371- <structfield>buffer_bytes_min</structfield> field, since23722372- it can be calculated from the minimum period size and the23732373- minimum number of periods.23742374- Meanwhile, <structfield>period_bytes_min</structfield> and23752375- define the minimum and maximum size of the period in bytes.23762376- <structfield>periods_max</structfield> and23772377- <structfield>periods_min</structfield> define the maximum and23782378- minimum number of periods in the buffer.23792379- </para>23802380-23812381- <para>23822382- The <quote>period</quote> is a term that corresponds to23832383- a fragment in the OSS world. The period defines the size at23842384- which a PCM interrupt is generated. This size strongly23852385- depends on the hardware. 23862386- Generally, the smaller period size will give you more23872387- interrupts, that is, more controls. 23882388- In the case of capture, this size defines the input latency.23892389- On the other hand, the whole buffer size defines the23902390- output latency for the playback direction.23912391- </para>23922392- </listitem>23932393-23942394- <listitem>23952395- <para>23962396- There is also a field <structfield>fifo_size</structfield>.23972397- This specifies the size of the hardware FIFO, but currently it23982398- is neither used in the driver nor in the alsa-lib. So, you23992399- can ignore this field.24002400- </para>24012401- </listitem>24022402- </itemizedlist>24032403- </para>24042404- </section>24052405-24062406- <section id="pcm-interface-runtime-config">24072407- <title>PCM Configurations</title>24082408- <para>24092409- Ok, let's go back again to the PCM runtime records.24102410- The most frequently referred records in the runtime instance are24112411- the PCM configurations.24122412- The PCM configurations are stored in the runtime instance24132413- after the application sends <type>hw_params</type> data via24142414- alsa-lib. There are many fields copied from hw_params and24152415- sw_params structs. For example,24162416- <structfield>format</structfield> holds the format type24172417- chosen by the application. This field contains the enum value24182418- <constant>SNDRV_PCM_FORMAT_XXX</constant>.24192419- </para>24202420-24212421- <para>24222422- One thing to be noted is that the configured buffer and period24232423- sizes are stored in <quote>frames</quote> in the runtime.24242424- In the ALSA world, 1 frame = channels * samples-size.24252425- For conversion between frames and bytes, you can use the24262426- <function>frames_to_bytes()</function> and24272427- <function>bytes_to_frames()</function> helper functions. 24282428- <informalexample>24292429- <programlisting>24302430-<![CDATA[24312431- period_bytes = frames_to_bytes(runtime, runtime->period_size);24322432-]]>24332433- </programlisting>24342434- </informalexample>24352435- </para>24362436-24372437- <para>24382438- Also, many software parameters (sw_params) are24392439- stored in frames, too. Please check the type of the field.24402440- <type>snd_pcm_uframes_t</type> is for the frames as unsigned24412441- integer while <type>snd_pcm_sframes_t</type> is for the frames24422442- as signed integer.24432443- </para>24442444- </section>24452445-24462446- <section id="pcm-interface-runtime-dma">24472447- <title>DMA Buffer Information</title>24482448- <para>24492449- The DMA buffer is defined by the following four fields,24502450- <structfield>dma_area</structfield>,24512451- <structfield>dma_addr</structfield>,24522452- <structfield>dma_bytes</structfield> and24532453- <structfield>dma_private</structfield>.24542454- The <structfield>dma_area</structfield> holds the buffer24552455- pointer (the logical address). You can call24562456- <function>memcpy</function> from/to 24572457- this pointer. Meanwhile, <structfield>dma_addr</structfield>24582458- holds the physical address of the buffer. This field is24592459- specified only when the buffer is a linear buffer.24602460- <structfield>dma_bytes</structfield> holds the size of buffer24612461- in bytes. <structfield>dma_private</structfield> is used for24622462- the ALSA DMA allocator.24632463- </para>24642464-24652465- <para>24662466- If you use a standard ALSA function,24672467- <function>snd_pcm_lib_malloc_pages()</function>, for24682468- allocating the buffer, these fields are set by the ALSA middle24692469- layer, and you should <emphasis>not</emphasis> change them by24702470- yourself. You can read them but not write them.24712471- On the other hand, if you want to allocate the buffer by24722472- yourself, you'll need to manage it in hw_params callback.24732473- At least, <structfield>dma_bytes</structfield> is mandatory.24742474- <structfield>dma_area</structfield> is necessary when the24752475- buffer is mmapped. If your driver doesn't support mmap, this24762476- field is not necessary. <structfield>dma_addr</structfield>24772477- is also optional. You can use24782478- <structfield>dma_private</structfield> as you like, too.24792479- </para>24802480- </section>24812481-24822482- <section id="pcm-interface-runtime-status">24832483- <title>Running Status</title>24842484- <para>24852485- The running status can be referred via <constant>runtime->status</constant>.24862486- This is the pointer to the struct <structname>snd_pcm_mmap_status</structname>24872487- record. For example, you can get the current DMA hardware24882488- pointer via <constant>runtime->status->hw_ptr</constant>.24892489- </para>24902490-24912491- <para>24922492- The DMA application pointer can be referred via24932493- <constant>runtime->control</constant>, which points to the24942494- struct <structname>snd_pcm_mmap_control</structname> record.24952495- However, accessing directly to this value is not recommended.24962496- </para>24972497- </section>24982498-24992499- <section id="pcm-interface-runtime-private">25002500- <title>Private Data</title> 25012501- <para>25022502- You can allocate a record for the substream and store it in25032503- <constant>runtime->private_data</constant>. Usually, this25042504- is done in25052505- <link linkend="pcm-interface-operators-open-callback"><citetitle>25062506- the open callback</citetitle></link>.25072507- Don't mix this with <constant>pcm->private_data</constant>.25082508- The <constant>pcm->private_data</constant> usually points to the25092509- chip instance assigned statically at the creation of PCM, while the 25102510- <constant>runtime->private_data</constant> points to a dynamic25112511- data structure created at the PCM open callback.25122512-25132513- <informalexample>25142514- <programlisting>25152515-<![CDATA[25162516- static int snd_xxx_open(struct snd_pcm_substream *substream)25172517- {25182518- struct my_pcm_data *data;25192519- ....25202520- data = kmalloc(sizeof(*data), GFP_KERNEL);25212521- substream->runtime->private_data = data;25222522- ....25232523- }25242524-]]>25252525- </programlisting>25262526- </informalexample>25272527- </para>25282528-25292529- <para>25302530- The allocated object must be released in25312531- <link linkend="pcm-interface-operators-open-callback"><citetitle>25322532- the close callback</citetitle></link>.25332533- </para>25342534- </section>25352535-25362536- </section>25372537-25382538- <section id="pcm-interface-operators">25392539- <title>Operators</title>25402540- <para>25412541- OK, now let me give details about each pcm callback25422542- (<parameter>ops</parameter>). In general, every callback must25432543- return 0 if successful, or a negative error number25442544- such as <constant>-EINVAL</constant>. To choose an appropriate25452545- error number, it is advised to check what value other parts of25462546- the kernel return when the same kind of request fails.25472547- </para>25482548-25492549- <para>25502550- The callback function takes at least the argument with25512551- <structname>snd_pcm_substream</structname> pointer. To retrieve25522552- the chip record from the given substream instance, you can use the25532553- following macro. 25542554-25552555- <informalexample>25562556- <programlisting>25572557-<![CDATA[25582558- int xxx() {25592559- struct mychip *chip = snd_pcm_substream_chip(substream);25602560- ....25612561- }25622562-]]>25632563- </programlisting>25642564- </informalexample>25652565-25662566- The macro reads <constant>substream->private_data</constant>,25672567- which is a copy of <constant>pcm->private_data</constant>.25682568- You can override the former if you need to assign different data25692569- records per PCM substream. For example, the cmi8330 driver assigns25702570- different private_data for playback and capture directions,25712571- because it uses two different codecs (SB- and AD-compatible) for25722572- different directions.25732573- </para>25742574-25752575- <section id="pcm-interface-operators-open-callback">25762576- <title>open callback</title>25772577- <para>25782578- <informalexample>25792579- <programlisting>25802580-<![CDATA[25812581- static int snd_xxx_open(struct snd_pcm_substream *substream);25822582-]]>25832583- </programlisting>25842584- </informalexample>25852585-25862586- This is called when a pcm substream is opened.25872587- </para>25882588-25892589- <para>25902590- At least, here you have to initialize the runtime->hw25912591- record. Typically, this is done by like this: 25922592-25932593- <informalexample>25942594- <programlisting>25952595-<![CDATA[25962596- static int snd_xxx_open(struct snd_pcm_substream *substream)25972597- {25982598- struct mychip *chip = snd_pcm_substream_chip(substream);25992599- struct snd_pcm_runtime *runtime = substream->runtime;26002600-26012601- runtime->hw = snd_mychip_playback_hw;26022602- return 0;26032603- }26042604-]]>26052605- </programlisting>26062606- </informalexample>26072607-26082608- where <parameter>snd_mychip_playback_hw</parameter> is the26092609- pre-defined hardware description.26102610- </para>26112611-26122612- <para>26132613- You can allocate a private data in this callback, as described26142614- in <link linkend="pcm-interface-runtime-private"><citetitle>26152615- Private Data</citetitle></link> section.26162616- </para>26172617-26182618- <para>26192619- If the hardware configuration needs more constraints, set the26202620- hardware constraints here, too.26212621- See <link linkend="pcm-interface-constraints"><citetitle>26222622- Constraints</citetitle></link> for more details.26232623- </para>26242624- </section>26252625-26262626- <section id="pcm-interface-operators-close-callback">26272627- <title>close callback</title>26282628- <para>26292629- <informalexample>26302630- <programlisting>26312631-<![CDATA[26322632- static int snd_xxx_close(struct snd_pcm_substream *substream);26332633-]]>26342634- </programlisting>26352635- </informalexample>26362636-26372637- Obviously, this is called when a pcm substream is closed.26382638- </para>26392639-26402640- <para>26412641- Any private instance for a pcm substream allocated in the26422642- open callback will be released here. 26432643-26442644- <informalexample>26452645- <programlisting>26462646-<![CDATA[26472647- static int snd_xxx_close(struct snd_pcm_substream *substream)26482648- {26492649- ....26502650- kfree(substream->runtime->private_data);26512651- ....26522652- }26532653-]]>26542654- </programlisting>26552655- </informalexample>26562656- </para>26572657- </section>26582658-26592659- <section id="pcm-interface-operators-ioctl-callback">26602660- <title>ioctl callback</title>26612661- <para>26622662- This is used for any special call to pcm ioctls. But26632663- usually you can pass a generic ioctl callback, 26642664- <function>snd_pcm_lib_ioctl</function>.26652665- </para>26662666- </section>26672667-26682668- <section id="pcm-interface-operators-hw-params-callback">26692669- <title>hw_params callback</title>26702670- <para>26712671- <informalexample>26722672- <programlisting>26732673-<![CDATA[26742674- static int snd_xxx_hw_params(struct snd_pcm_substream *substream,26752675- struct snd_pcm_hw_params *hw_params);26762676-]]>26772677- </programlisting>26782678- </informalexample>26792679- </para>26802680-26812681- <para>26822682- This is called when the hardware parameter26832683- (<structfield>hw_params</structfield>) is set26842684- up by the application, 26852685- that is, once when the buffer size, the period size, the26862686- format, etc. are defined for the pcm substream. 26872687- </para>26882688-26892689- <para>26902690- Many hardware setups should be done in this callback,26912691- including the allocation of buffers. 26922692- </para>26932693-26942694- <para>26952695- Parameters to be initialized are retrieved by26962696- <function>params_xxx()</function> macros. To allocate26972697- buffer, you can call a helper function, 26982698-26992699- <informalexample>27002700- <programlisting>27012701-<![CDATA[27022702- snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));27032703-]]>27042704- </programlisting>27052705- </informalexample>27062706-27072707- <function>snd_pcm_lib_malloc_pages()</function> is available27082708- only when the DMA buffers have been pre-allocated.27092709- See the section <link27102710- linkend="buffer-and-memory-buffer-types"><citetitle>27112711- Buffer Types</citetitle></link> for more details.27122712- </para>27132713-27142714- <para>27152715- Note that this and <structfield>prepare</structfield> callbacks27162716- may be called multiple times per initialization.27172717- For example, the OSS emulation may27182718- call these callbacks at each change via its ioctl. 27192719- </para>27202720-27212721- <para>27222722- Thus, you need to be careful not to allocate the same buffers27232723- many times, which will lead to memory leaks! Calling the27242724- helper function above many times is OK. It will release the27252725- previous buffer automatically when it was already allocated. 27262726- </para>27272727-27282728- <para>27292729- Another note is that this callback is non-atomic27302730- (schedulable) as default, i.e. when no27312731- <structfield>nonatomic</structfield> flag set.27322732- This is important, because the27332733- <structfield>trigger</structfield> callback 27342734- is atomic (non-schedulable). That is, mutexes or any27352735- schedule-related functions are not available in27362736- <structfield>trigger</structfield> callback.27372737- Please see the subsection27382738- <link linkend="pcm-interface-atomicity"><citetitle>27392739- Atomicity</citetitle></link> for details.27402740- </para>27412741- </section>27422742-27432743- <section id="pcm-interface-operators-hw-free-callback">27442744- <title>hw_free callback</title>27452745- <para>27462746- <informalexample>27472747- <programlisting>27482748-<![CDATA[27492749- static int snd_xxx_hw_free(struct snd_pcm_substream *substream);27502750-]]>27512751- </programlisting>27522752- </informalexample>27532753- </para>27542754-27552755- <para>27562756- This is called to release the resources allocated via27572757- <structfield>hw_params</structfield>. For example, releasing the27582758- buffer via 27592759- <function>snd_pcm_lib_malloc_pages()</function> is done by27602760- calling the following: 27612761-27622762- <informalexample>27632763- <programlisting>27642764-<![CDATA[27652765- snd_pcm_lib_free_pages(substream);27662766-]]>27672767- </programlisting>27682768- </informalexample>27692769- </para>27702770-27712771- <para>27722772- This function is always called before the close callback is called.27732773- Also, the callback may be called multiple times, too.27742774- Keep track whether the resource was already released. 27752775- </para>27762776- </section>27772777-27782778- <section id="pcm-interface-operators-prepare-callback">27792779- <title>prepare callback</title>27802780- <para>27812781- <informalexample>27822782- <programlisting>27832783-<![CDATA[27842784- static int snd_xxx_prepare(struct snd_pcm_substream *substream);27852785-]]>27862786- </programlisting>27872787- </informalexample>27882788- </para>27892789-27902790- <para>27912791- This callback is called when the pcm is27922792- <quote>prepared</quote>. You can set the format type, sample27932793- rate, etc. here. The difference from27942794- <structfield>hw_params</structfield> is that the 27952795- <structfield>prepare</structfield> callback will be called each27962796- time 27972797- <function>snd_pcm_prepare()</function> is called, i.e. when27982798- recovering after underruns, etc. 27992799- </para>28002800-28012801- <para>28022802- Note that this callback is now non-atomic.28032803- You can use schedule-related functions safely in this callback.28042804- </para>28052805-28062806- <para>28072807- In this and the following callbacks, you can refer to the28082808- values via the runtime record,28092809- substream->runtime.28102810- For example, to get the current28112811- rate, format or channels, access to28122812- runtime->rate,28132813- runtime->format or28142814- runtime->channels, respectively. 28152815- The physical address of the allocated buffer is set to28162816- runtime->dma_area. The buffer and period sizes are28172817- in runtime->buffer_size and runtime->period_size,28182818- respectively.28192819- </para>28202820-28212821- <para>28222822- Be careful that this callback will be called many times at28232823- each setup, too. 28242824- </para>28252825- </section>28262826-28272827- <section id="pcm-interface-operators-trigger-callback">28282828- <title>trigger callback</title>28292829- <para>28302830- <informalexample>28312831- <programlisting>28322832-<![CDATA[28332833- static int snd_xxx_trigger(struct snd_pcm_substream *substream, int cmd);28342834-]]>28352835- </programlisting>28362836- </informalexample>28372837-28382838- This is called when the pcm is started, stopped or paused.28392839- </para>28402840-28412841- <para>28422842- Which action is specified in the second argument,28432843- <constant>SNDRV_PCM_TRIGGER_XXX</constant> in28442844- <filename><sound/pcm.h></filename>. At least,28452845- the <constant>START</constant> and <constant>STOP</constant>28462846- commands must be defined in this callback. 28472847-28482848- <informalexample>28492849- <programlisting>28502850-<![CDATA[28512851- switch (cmd) {28522852- case SNDRV_PCM_TRIGGER_START:28532853- /* do something to start the PCM engine */28542854- break;28552855- case SNDRV_PCM_TRIGGER_STOP:28562856- /* do something to stop the PCM engine */28572857- break;28582858- default:28592859- return -EINVAL;28602860- }28612861-]]>28622862- </programlisting>28632863- </informalexample>28642864- </para>28652865-28662866- <para>28672867- When the pcm supports the pause operation (given in the info28682868- field of the hardware table), the <constant>PAUSE_PUSH</constant>28692869- and <constant>PAUSE_RELEASE</constant> commands must be28702870- handled here, too. The former is the command to pause the pcm,28712871- and the latter to restart the pcm again. 28722872- </para>28732873-28742874- <para>28752875- When the pcm supports the suspend/resume operation,28762876- regardless of full or partial suspend/resume support,28772877- the <constant>SUSPEND</constant> and <constant>RESUME</constant>28782878- commands must be handled, too.28792879- These commands are issued when the power-management status is28802880- changed. Obviously, the <constant>SUSPEND</constant> and28812881- <constant>RESUME</constant> commands28822882- suspend and resume the pcm substream, and usually, they28832883- are identical to the <constant>STOP</constant> and28842884- <constant>START</constant> commands, respectively.28852885- See the <link linkend="power-management"><citetitle>28862886- Power Management</citetitle></link> section for details.28872887- </para>28882888-28892889- <para>28902890- As mentioned, this callback is atomic as default unless28912891- <structfield>nonatomic</structfield> flag set, and28922892- you cannot call functions which may sleep.28932893- The trigger callback should be as minimal as possible,28942894- just really triggering the DMA. The other stuff should be28952895- initialized hw_params and prepare callbacks properly28962896- beforehand.28972897- </para>28982898- </section>28992899-29002900- <section id="pcm-interface-operators-pointer-callback">29012901- <title>pointer callback</title>29022902- <para>29032903- <informalexample>29042904- <programlisting>29052905-<![CDATA[29062906- static snd_pcm_uframes_t snd_xxx_pointer(struct snd_pcm_substream *substream)29072907-]]>29082908- </programlisting>29092909- </informalexample>29102910-29112911- This callback is called when the PCM middle layer inquires29122912- the current hardware position on the buffer. The position must29132913- be returned in frames,29142914- ranging from 0 to buffer_size - 1.29152915- </para>29162916-29172917- <para>29182918- This is called usually from the buffer-update routine in the29192919- pcm middle layer, which is invoked when29202920- <function>snd_pcm_period_elapsed()</function> is called in the29212921- interrupt routine. Then the pcm middle layer updates the29222922- position and calculates the available space, and wakes up the29232923- sleeping poll threads, etc. 29242924- </para>29252925-29262926- <para>29272927- This callback is also atomic as default.29282928- </para>29292929- </section>29302930-29312931- <section id="pcm-interface-operators-copy-silence">29322932- <title>copy and silence callbacks</title>29332933- <para>29342934- These callbacks are not mandatory, and can be omitted in29352935- most cases. These callbacks are used when the hardware buffer29362936- cannot be in the normal memory space. Some chips have their29372937- own buffer on the hardware which is not mappable. In such a29382938- case, you have to transfer the data manually from the memory29392939- buffer to the hardware buffer. Or, if the buffer is29402940- non-contiguous on both physical and virtual memory spaces,29412941- these callbacks must be defined, too. 29422942- </para>29432943-29442944- <para>29452945- If these two callbacks are defined, copy and set-silence29462946- operations are done by them. The detailed will be described in29472947- the later section <link29482948- linkend="buffer-and-memory"><citetitle>Buffer and Memory29492949- Management</citetitle></link>. 29502950- </para>29512951- </section>29522952-29532953- <section id="pcm-interface-operators-ack">29542954- <title>ack callback</title>29552955- <para>29562956- This callback is also not mandatory. This callback is called29572957- when the appl_ptr is updated in read or write operations.29582958- Some drivers like emu10k1-fx and cs46xx need to track the29592959- current appl_ptr for the internal buffer, and this callback29602960- is useful only for such a purpose.29612961- </para>29622962- <para>29632963- This callback is atomic as default.29642964- </para>29652965- </section>29662966-29672967- <section id="pcm-interface-operators-page-callback">29682968- <title>page callback</title>29692969-29702970- <para>29712971- This callback is optional too. This callback is used29722972- mainly for non-contiguous buffers. The mmap calls this29732973- callback to get the page address. Some examples will be29742974- explained in the later section <link29752975- linkend="buffer-and-memory"><citetitle>Buffer and Memory29762976- Management</citetitle></link>, too. 29772977- </para>29782978- </section>29792979- </section>29802980-29812981- <section id="pcm-interface-interrupt-handler">29822982- <title>Interrupt Handler</title>29832983- <para>29842984- The rest of pcm stuff is the PCM interrupt handler. The29852985- role of PCM interrupt handler in the sound driver is to update29862986- the buffer position and to tell the PCM middle layer when the29872987- buffer position goes across the prescribed period size. To29882988- inform this, call the <function>snd_pcm_period_elapsed()</function>29892989- function. 29902990- </para>29912991-29922992- <para>29932993- There are several types of sound chips to generate the interrupts.29942994- </para>29952995-29962996- <section id="pcm-interface-interrupt-handler-boundary">29972997- <title>Interrupts at the period (fragment) boundary</title>29982998- <para>29992999- This is the most frequently found type: the hardware30003000- generates an interrupt at each period boundary.30013001- In this case, you can call30023002- <function>snd_pcm_period_elapsed()</function> at each 30033003- interrupt. 30043004- </para>30053005-30063006- <para>30073007- <function>snd_pcm_period_elapsed()</function> takes the30083008- substream pointer as its argument. Thus, you need to keep the30093009- substream pointer accessible from the chip instance. For30103010- example, define substream field in the chip record to hold the30113011- current running substream pointer, and set the pointer value30123012- at open callback (and reset at close callback). 30133013- </para>30143014-30153015- <para>30163016- If you acquire a spinlock in the interrupt handler, and the30173017- lock is used in other pcm callbacks, too, then you have to30183018- release the lock before calling30193019- <function>snd_pcm_period_elapsed()</function>, because30203020- <function>snd_pcm_period_elapsed()</function> calls other pcm30213021- callbacks inside. 30223022- </para>30233023-30243024- <para>30253025- Typical code would be like:30263026-30273027- <example>30283028- <title>Interrupt Handler Case #1</title>30293029- <programlisting>30303030-<![CDATA[30313031- static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)30323032- {30333033- struct mychip *chip = dev_id;30343034- spin_lock(&chip->lock);30353035- ....30363036- if (pcm_irq_invoked(chip)) {30373037- /* call updater, unlock before it */30383038- spin_unlock(&chip->lock);30393039- snd_pcm_period_elapsed(chip->substream);30403040- spin_lock(&chip->lock);30413041- /* acknowledge the interrupt if necessary */30423042- }30433043- ....30443044- spin_unlock(&chip->lock);30453045- return IRQ_HANDLED;30463046- }30473047-]]>30483048- </programlisting>30493049- </example>30503050- </para>30513051- </section>30523052-30533053- <section id="pcm-interface-interrupt-handler-timer">30543054- <title>High frequency timer interrupts</title>30553055- <para>30563056- This happens when the hardware doesn't generate interrupts30573057- at the period boundary but issues timer interrupts at a fixed30583058- timer rate (e.g. es1968 or ymfpci drivers). 30593059- In this case, you need to check the current hardware30603060- position and accumulate the processed sample length at each30613061- interrupt. When the accumulated size exceeds the period30623062- size, call 30633063- <function>snd_pcm_period_elapsed()</function> and reset the30643064- accumulator. 30653065- </para>30663066-30673067- <para>30683068- Typical code would be like the following.30693069-30703070- <example>30713071- <title>Interrupt Handler Case #2</title>30723072- <programlisting>30733073-<![CDATA[30743074- static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)30753075- {30763076- struct mychip *chip = dev_id;30773077- spin_lock(&chip->lock);30783078- ....30793079- if (pcm_irq_invoked(chip)) {30803080- unsigned int last_ptr, size;30813081- /* get the current hardware pointer (in frames) */30823082- last_ptr = get_hw_ptr(chip);30833083- /* calculate the processed frames since the30843084- * last update30853085- */30863086- if (last_ptr < chip->last_ptr)30873087- size = runtime->buffer_size + last_ptr 30883088- - chip->last_ptr; 30893089- else30903090- size = last_ptr - chip->last_ptr;30913091- /* remember the last updated point */30923092- chip->last_ptr = last_ptr;30933093- /* accumulate the size */30943094- chip->size += size;30953095- /* over the period boundary? */30963096- if (chip->size >= runtime->period_size) {30973097- /* reset the accumulator */30983098- chip->size %= runtime->period_size;30993099- /* call updater */31003100- spin_unlock(&chip->lock);31013101- snd_pcm_period_elapsed(substream);31023102- spin_lock(&chip->lock);31033103- }31043104- /* acknowledge the interrupt if necessary */31053105- }31063106- ....31073107- spin_unlock(&chip->lock);31083108- return IRQ_HANDLED;31093109- }31103110-]]>31113111- </programlisting>31123112- </example>31133113- </para>31143114- </section>31153115-31163116- <section id="pcm-interface-interrupt-handler-both">31173117- <title>On calling <function>snd_pcm_period_elapsed()</function></title>31183118- <para>31193119- In both cases, even if more than one period are elapsed, you31203120- don't have to call31213121- <function>snd_pcm_period_elapsed()</function> many times. Call31223122- only once. And the pcm layer will check the current hardware31233123- pointer and update to the latest status. 31243124- </para>31253125- </section>31263126- </section>31273127-31283128- <section id="pcm-interface-atomicity">31293129- <title>Atomicity</title>31303130- <para>31313131- One of the most important (and thus difficult to debug) problems31323132- in kernel programming are race conditions.31333133- In the Linux kernel, they are usually avoided via spin-locks, mutexes31343134- or semaphores. In general, if a race condition can happen31353135- in an interrupt handler, it has to be managed atomically, and you31363136- have to use a spinlock to protect the critical session. If the31373137- critical section is not in interrupt handler code and31383138- if taking a relatively long time to execute is acceptable, you31393139- should use mutexes or semaphores instead.31403140- </para>31413141-31423142- <para>31433143- As already seen, some pcm callbacks are atomic and some are31443144- not. For example, the <parameter>hw_params</parameter> callback is31453145- non-atomic, while <parameter>trigger</parameter> callback is31463146- atomic. This means, the latter is called already in a spinlock31473147- held by the PCM middle layer. Please take this atomicity into31483148- account when you choose a locking scheme in the callbacks.31493149- </para>31503150-31513151- <para>31523152- In the atomic callbacks, you cannot use functions which may call31533153- <function>schedule</function> or go to31543154- <function>sleep</function>. Semaphores and mutexes can sleep,31553155- and hence they cannot be used inside the atomic callbacks31563156- (e.g. <parameter>trigger</parameter> callback).31573157- To implement some delay in such a callback, please use31583158- <function>udelay()</function> or <function>mdelay()</function>.31593159- </para>31603160-31613161- <para>31623162- All three atomic callbacks (trigger, pointer, and ack) are31633163- called with local interrupts disabled.31643164- </para>31653165-31663166- <para>31673167- The recent changes in PCM core code, however, allow all PCM31683168- operations to be non-atomic. This assumes that the all caller31693169- sides are in non-atomic contexts. For example, the function31703170- <function>snd_pcm_period_elapsed()</function> is called31713171- typically from the interrupt handler. But, if you set up the31723172- driver to use a threaded interrupt handler, this call can be in31733173- non-atomic context, too. In such a case, you can set31743174- <structfield>nonatomic</structfield> filed of31753175- <structname>snd_pcm</structname> object after creating it.31763176- When this flag is set, mutex and rwsem are used internally in31773177- the PCM core instead of spin and rwlocks, so that you can call31783178- all PCM functions safely in a non-atomic context.31793179- </para>31803180-31813181- </section>31823182- <section id="pcm-interface-constraints">31833183- <title>Constraints</title>31843184- <para>31853185- If your chip supports unconventional sample rates, or only the31863186- limited samples, you need to set a constraint for the31873187- condition. 31883188- </para>31893189-31903190- <para>31913191- For example, in order to restrict the sample rates in the some31923192- supported values, use31933193- <function>snd_pcm_hw_constraint_list()</function>.31943194- You need to call this function in the open callback.31953195-31963196- <example>31973197- <title>Example of Hardware Constraints</title>31983198- <programlisting>31993199-<![CDATA[32003200- static unsigned int rates[] =32013201- {4000, 10000, 22050, 44100};32023202- static struct snd_pcm_hw_constraint_list constraints_rates = {32033203- .count = ARRAY_SIZE(rates),32043204- .list = rates,32053205- .mask = 0,32063206- };32073207-32083208- static int snd_mychip_pcm_open(struct snd_pcm_substream *substream)32093209- {32103210- int err;32113211- ....32123212- err = snd_pcm_hw_constraint_list(substream->runtime, 0,32133213- SNDRV_PCM_HW_PARAM_RATE,32143214- &constraints_rates);32153215- if (err < 0)32163216- return err;32173217- ....32183218- }32193219-]]>32203220- </programlisting>32213221- </example>32223222- </para>32233223-32243224- <para>32253225- There are many different constraints.32263226- Look at <filename>sound/pcm.h</filename> for a complete list.32273227- You can even define your own constraint rules.32283228- For example, let's suppose my_chip can manage a substream of 1 channel32293229- if and only if the format is S16_LE, otherwise it supports any format32303230- specified in the <structname>snd_pcm_hardware</structname> structure (or in any32313231- other constraint_list). You can build a rule like this:32323232-32333233- <example>32343234- <title>Example of Hardware Constraints for Channels</title>32353235- <programlisting>32363236-<![CDATA[32373237- static int hw_rule_channels_by_format(struct snd_pcm_hw_params *params,32383238- struct snd_pcm_hw_rule *rule)32393239- {32403240- struct snd_interval *c = hw_param_interval(params,32413241- SNDRV_PCM_HW_PARAM_CHANNELS);32423242- struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);32433243- struct snd_interval ch;32443244-32453245- snd_interval_any(&ch);32463246- if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {32473247- ch.min = ch.max = 1;32483248- ch.integer = 1;32493249- return snd_interval_refine(c, &ch);32503250- }32513251- return 0;32523252- }32533253-]]>32543254- </programlisting>32553255- </example>32563256- </para>32573257-32583258- <para>32593259- Then you need to call this function to add your rule:32603260-32613261- <informalexample>32623262- <programlisting>32633263-<![CDATA[32643264- snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,32653265- hw_rule_channels_by_format, NULL,32663266- SNDRV_PCM_HW_PARAM_FORMAT, -1);32673267-]]>32683268- </programlisting>32693269- </informalexample>32703270- </para>32713271-32723272- <para>32733273- The rule function is called when an application sets the PCM32743274- format, and it refines the number of channels accordingly.32753275- But an application may set the number of channels before32763276- setting the format. Thus you also need to define the inverse rule:32773277-32783278- <example>32793279- <title>Example of Hardware Constraints for Formats</title>32803280- <programlisting>32813281-<![CDATA[32823282- static int hw_rule_format_by_channels(struct snd_pcm_hw_params *params,32833283- struct snd_pcm_hw_rule *rule)32843284- {32853285- struct snd_interval *c = hw_param_interval(params,32863286- SNDRV_PCM_HW_PARAM_CHANNELS);32873287- struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);32883288- struct snd_mask fmt;32893289-32903290- snd_mask_any(&fmt); /* Init the struct */32913291- if (c->min < 2) {32923292- fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;32933293- return snd_mask_refine(f, &fmt);32943294- }32953295- return 0;32963296- }32973297-]]>32983298- </programlisting>32993299- </example>33003300- </para>33013301-33023302- <para>33033303- ...and in the open callback:33043304- <informalexample>33053305- <programlisting>33063306-<![CDATA[33073307- snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,33083308- hw_rule_format_by_channels, NULL,33093309- SNDRV_PCM_HW_PARAM_CHANNELS, -1);33103310-]]>33113311- </programlisting>33123312- </informalexample>33133313- </para>33143314-33153315- <para>33163316- I won't give more details here, rather I33173317- would like to say, <quote>Luke, use the source.</quote>33183318- </para>33193319- </section>33203320-33213321- </chapter>33223322-33233323-33243324-<!-- ****************************************************** -->33253325-<!-- Control Interface -->33263326-<!-- ****************************************************** -->33273327- <chapter id="control-interface">33283328- <title>Control Interface</title>33293329-33303330- <section id="control-interface-general">33313331- <title>General</title>33323332- <para>33333333- The control interface is used widely for many switches,33343334- sliders, etc. which are accessed from user-space. Its most33353335- important use is the mixer interface. In other words, since ALSA33363336- 0.9.x, all the mixer stuff is implemented on the control kernel API.33373337- </para>33383338-33393339- <para>33403340- ALSA has a well-defined AC97 control module. If your chip33413341- supports only the AC97 and nothing else, you can skip this33423342- section. 33433343- </para>33443344-33453345- <para>33463346- The control API is defined in33473347- <filename><sound/control.h></filename>.33483348- Include this file if you want to add your own controls.33493349- </para>33503350- </section>33513351-33523352- <section id="control-interface-definition">33533353- <title>Definition of Controls</title>33543354- <para>33553355- To create a new control, you need to define the33563356- following three33573357- callbacks: <structfield>info</structfield>,33583358- <structfield>get</structfield> and33593359- <structfield>put</structfield>. Then, define a33603360- struct <structname>snd_kcontrol_new</structname> record, such as: 33613361-33623362- <example>33633363- <title>Definition of a Control</title>33643364- <programlisting>33653365-<![CDATA[33663366- static struct snd_kcontrol_new my_control = {33673367- .iface = SNDRV_CTL_ELEM_IFACE_MIXER,33683368- .name = "PCM Playback Switch",33693369- .index = 0,33703370- .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,33713371- .private_value = 0xffff,33723372- .info = my_control_info,33733373- .get = my_control_get,33743374- .put = my_control_put33753375- };33763376-]]>33773377- </programlisting>33783378- </example>33793379- </para>33803380-33813381- <para>33823382- The <structfield>iface</structfield> field specifies the control33833383- type, <constant>SNDRV_CTL_ELEM_IFACE_XXX</constant>, which33843384- is usually <constant>MIXER</constant>.33853385- Use <constant>CARD</constant> for global controls that are not33863386- logically part of the mixer.33873387- If the control is closely associated with some specific device on33883388- the sound card, use <constant>HWDEP</constant>,33893389- <constant>PCM</constant>, <constant>RAWMIDI</constant>,33903390- <constant>TIMER</constant>, or <constant>SEQUENCER</constant>, and33913391- specify the device number with the33923392- <structfield>device</structfield> and33933393- <structfield>subdevice</structfield> fields.33943394- </para>33953395-33963396- <para>33973397- The <structfield>name</structfield> is the name identifier33983398- string. Since ALSA 0.9.x, the control name is very important,33993399- because its role is classified from its name. There are34003400- pre-defined standard control names. The details are described in34013401- the <link linkend="control-interface-control-names"><citetitle>34023402- Control Names</citetitle></link> subsection.34033403- </para>34043404-34053405- <para>34063406- The <structfield>index</structfield> field holds the index number34073407- of this control. If there are several different controls with34083408- the same name, they can be distinguished by the index34093409- number. This is the case when 34103410- several codecs exist on the card. If the index is zero, you can34113411- omit the definition above. 34123412- </para>34133413-34143414- <para>34153415- The <structfield>access</structfield> field contains the access34163416- type of this control. Give the combination of bit masks,34173417- <constant>SNDRV_CTL_ELEM_ACCESS_XXX</constant>, there.34183418- The details will be explained in34193419- the <link linkend="control-interface-access-flags"><citetitle>34203420- Access Flags</citetitle></link> subsection.34213421- </para>34223422-34233423- <para>34243424- The <structfield>private_value</structfield> field contains34253425- an arbitrary long integer value for this record. When using34263426- the generic <structfield>info</structfield>,34273427- <structfield>get</structfield> and34283428- <structfield>put</structfield> callbacks, you can pass a value 34293429- through this field. If several small numbers are necessary, you can34303430- combine them in bitwise. Or, it's possible to give a pointer34313431- (casted to unsigned long) of some record to this field, too. 34323432- </para>34333433-34343434- <para>34353435- The <structfield>tlv</structfield> field can be used to provide34363436- metadata about the control; see the34373437- <link linkend="control-interface-tlv">34383438- <citetitle>Metadata</citetitle></link> subsection.34393439- </para>34403440-34413441- <para>34423442- The other three are34433443- <link linkend="control-interface-callbacks"><citetitle>34443444- callback functions</citetitle></link>.34453445- </para>34463446- </section>34473447-34483448- <section id="control-interface-control-names">34493449- <title>Control Names</title>34503450- <para>34513451- There are some standards to define the control names. A34523452- control is usually defined from the three parts as34533453- <quote>SOURCE DIRECTION FUNCTION</quote>. 34543454- </para>34553455-34563456- <para>34573457- The first, <constant>SOURCE</constant>, specifies the source34583458- of the control, and is a string such as <quote>Master</quote>,34593459- <quote>PCM</quote>, <quote>CD</quote> and34603460- <quote>Line</quote>. There are many pre-defined sources. 34613461- </para>34623462-34633463- <para>34643464- The second, <constant>DIRECTION</constant>, is one of the34653465- following strings according to the direction of the control:34663466- <quote>Playback</quote>, <quote>Capture</quote>, <quote>Bypass34673467- Playback</quote> and <quote>Bypass Capture</quote>. Or, it can34683468- be omitted, meaning both playback and capture directions. 34693469- </para>34703470-34713471- <para>34723472- The third, <constant>FUNCTION</constant>, is one of the34733473- following strings according to the function of the control:34743474- <quote>Switch</quote>, <quote>Volume</quote> and34753475- <quote>Route</quote>. 34763476- </para>34773477-34783478- <para>34793479- The example of control names are, thus, <quote>Master Capture34803480- Switch</quote> or <quote>PCM Playback Volume</quote>. 34813481- </para>34823482-34833483- <para>34843484- There are some exceptions:34853485- </para>34863486-34873487- <section id="control-interface-control-names-global">34883488- <title>Global capture and playback</title>34893489- <para>34903490- <quote>Capture Source</quote>, <quote>Capture Switch</quote>34913491- and <quote>Capture Volume</quote> are used for the global34923492- capture (input) source, switch and volume. Similarly,34933493- <quote>Playback Switch</quote> and <quote>Playback34943494- Volume</quote> are used for the global output gain switch and34953495- volume. 34963496- </para>34973497- </section>34983498-34993499- <section id="control-interface-control-names-tone">35003500- <title>Tone-controls</title>35013501- <para>35023502- tone-control switch and volumes are specified like35033503- <quote>Tone Control - XXX</quote>, e.g. <quote>Tone Control -35043504- Switch</quote>, <quote>Tone Control - Bass</quote>,35053505- <quote>Tone Control - Center</quote>. 35063506- </para>35073507- </section>35083508-35093509- <section id="control-interface-control-names-3d">35103510- <title>3D controls</title>35113511- <para>35123512- 3D-control switches and volumes are specified like <quote>3D35133513- Control - XXX</quote>, e.g. <quote>3D Control -35143514- Switch</quote>, <quote>3D Control - Center</quote>, <quote>3D35153515- Control - Space</quote>. 35163516- </para>35173517- </section>35183518-35193519- <section id="control-interface-control-names-mic">35203520- <title>Mic boost</title>35213521- <para>35223522- Mic-boost switch is set as <quote>Mic Boost</quote> or35233523- <quote>Mic Boost (6dB)</quote>. 35243524- </para>35253525-35263526- <para>35273527- More precise information can be found in35283528- <filename>Documentation/sound/alsa/ControlNames.txt</filename>.35293529- </para>35303530- </section>35313531- </section>35323532-35333533- <section id="control-interface-access-flags">35343534- <title>Access Flags</title>35353535-35363536- <para>35373537- The access flag is the bitmask which specifies the access type35383538- of the given control. The default access type is35393539- <constant>SNDRV_CTL_ELEM_ACCESS_READWRITE</constant>, 35403540- which means both read and write are allowed to this control.35413541- When the access flag is omitted (i.e. = 0), it is35423542- considered as <constant>READWRITE</constant> access as default. 35433543- </para>35443544-35453545- <para>35463546- When the control is read-only, pass35473547- <constant>SNDRV_CTL_ELEM_ACCESS_READ</constant> instead.35483548- In this case, you don't have to define35493549- the <structfield>put</structfield> callback.35503550- Similarly, when the control is write-only (although it's a rare35513551- case), you can use the <constant>WRITE</constant> flag instead, and35523552- you don't need the <structfield>get</structfield> callback.35533553- </para>35543554-35553555- <para>35563556- If the control value changes frequently (e.g. the VU meter),35573557- <constant>VOLATILE</constant> flag should be given. This means35583558- that the control may be changed without35593559- <link linkend="control-interface-change-notification"><citetitle>35603560- notification</citetitle></link>. Applications should poll such35613561- a control constantly.35623562- </para>35633563-35643564- <para>35653565- When the control is inactive, set35663566- the <constant>INACTIVE</constant> flag, too.35673567- There are <constant>LOCK</constant> and35683568- <constant>OWNER</constant> flags to change the write35693569- permissions.35703570- </para>35713571-35723572- </section>35733573-35743574- <section id="control-interface-callbacks">35753575- <title>Callbacks</title>35763576-35773577- <section id="control-interface-callbacks-info">35783578- <title>info callback</title>35793579- <para>35803580- The <structfield>info</structfield> callback is used to get35813581- detailed information on this control. This must store the35823582- values of the given struct <structname>snd_ctl_elem_info</structname>35833583- object. For example, for a boolean control with a single35843584- element: 35853585-35863586- <example>35873587- <title>Example of info callback</title>35883588- <programlisting>35893589-<![CDATA[35903590- static int snd_myctl_mono_info(struct snd_kcontrol *kcontrol,35913591- struct snd_ctl_elem_info *uinfo)35923592- {35933593- uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;35943594- uinfo->count = 1;35953595- uinfo->value.integer.min = 0;35963596- uinfo->value.integer.max = 1;35973597- return 0;35983598- }35993599-]]>36003600- </programlisting>36013601- </example>36023602- </para>36033603-36043604- <para>36053605- The <structfield>type</structfield> field specifies the type36063606- of the control. There are <constant>BOOLEAN</constant>,36073607- <constant>INTEGER</constant>, <constant>ENUMERATED</constant>,36083608- <constant>BYTES</constant>, <constant>IEC958</constant> and36093609- <constant>INTEGER64</constant>. The36103610- <structfield>count</structfield> field specifies the 36113611- number of elements in this control. For example, a stereo36123612- volume would have count = 2. The36133613- <structfield>value</structfield> field is a union, and 36143614- the values stored are depending on the type. The boolean and36153615- integer types are identical. 36163616- </para>36173617-36183618- <para>36193619- The enumerated type is a bit different from others. You'll36203620- need to set the string for the currently given item index. 36213621-36223622- <informalexample>36233623- <programlisting>36243624-<![CDATA[36253625- static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,36263626- struct snd_ctl_elem_info *uinfo)36273627- {36283628- static char *texts[4] = {36293629- "First", "Second", "Third", "Fourth"36303630- };36313631- uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;36323632- uinfo->count = 1;36333633- uinfo->value.enumerated.items = 4;36343634- if (uinfo->value.enumerated.item > 3)36353635- uinfo->value.enumerated.item = 3;36363636- strcpy(uinfo->value.enumerated.name,36373637- texts[uinfo->value.enumerated.item]);36383638- return 0;36393639- }36403640-]]>36413641- </programlisting>36423642- </informalexample>36433643- </para>36443644-36453645- <para>36463646- The above callback can be simplified with a helper function,36473647- <function>snd_ctl_enum_info</function>. The final code36483648- looks like below.36493649- (You can pass ARRAY_SIZE(texts) instead of 4 in the third36503650- argument; it's a matter of taste.)36513651-36523652- <informalexample>36533653- <programlisting>36543654-<![CDATA[36553655- static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,36563656- struct snd_ctl_elem_info *uinfo)36573657- {36583658- static char *texts[4] = {36593659- "First", "Second", "Third", "Fourth"36603660- };36613661- return snd_ctl_enum_info(uinfo, 1, 4, texts);36623662- }36633663-]]>36643664- </programlisting>36653665- </informalexample>36663666- </para>36673667-36683668- <para>36693669- Some common info callbacks are available for your convenience:36703670- <function>snd_ctl_boolean_mono_info()</function> and36713671- <function>snd_ctl_boolean_stereo_info()</function>.36723672- Obviously, the former is an info callback for a mono channel36733673- boolean item, just like <function>snd_myctl_mono_info</function>36743674- above, and the latter is for a stereo channel boolean item.36753675- </para>36763676-36773677- </section>36783678-36793679- <section id="control-interface-callbacks-get">36803680- <title>get callback</title>36813681-36823682- <para>36833683- This callback is used to read the current value of the36843684- control and to return to user-space. 36853685- </para>36863686-36873687- <para>36883688- For example,36893689-36903690- <example>36913691- <title>Example of get callback</title>36923692- <programlisting>36933693-<![CDATA[36943694- static int snd_myctl_get(struct snd_kcontrol *kcontrol,36953695- struct snd_ctl_elem_value *ucontrol)36963696- {36973697- struct mychip *chip = snd_kcontrol_chip(kcontrol);36983698- ucontrol->value.integer.value[0] = get_some_value(chip);36993699- return 0;37003700- }37013701-]]>37023702- </programlisting>37033703- </example>37043704- </para>37053705-37063706- <para>37073707- The <structfield>value</structfield> field depends on 37083708- the type of control as well as on the info callback. For example,37093709- the sb driver uses this field to store the register offset,37103710- the bit-shift and the bit-mask. The37113711- <structfield>private_value</structfield> field is set as follows:37123712- <informalexample>37133713- <programlisting>37143714-<![CDATA[37153715- .private_value = reg | (shift << 16) | (mask << 24)37163716-]]>37173717- </programlisting>37183718- </informalexample>37193719- and is retrieved in callbacks like37203720- <informalexample>37213721- <programlisting>37223722-<![CDATA[37233723- static int snd_sbmixer_get_single(struct snd_kcontrol *kcontrol,37243724- struct snd_ctl_elem_value *ucontrol)37253725- {37263726- int reg = kcontrol->private_value & 0xff;37273727- int shift = (kcontrol->private_value >> 16) & 0xff;37283728- int mask = (kcontrol->private_value >> 24) & 0xff;37293729- ....37303730- }37313731-]]>37323732- </programlisting>37333733- </informalexample>37343734- </para>37353735-37363736- <para>37373737- In the <structfield>get</structfield> callback,37383738- you have to fill all the elements if the37393739- control has more than one elements,37403740- i.e. <structfield>count</structfield> > 1.37413741- In the example above, we filled only one element37423742- (<structfield>value.integer.value[0]</structfield>) since it's37433743- assumed as <structfield>count</structfield> = 1.37443744- </para>37453745- </section>37463746-37473747- <section id="control-interface-callbacks-put">37483748- <title>put callback</title>37493749-37503750- <para>37513751- This callback is used to write a value from user-space.37523752- </para>37533753-37543754- <para>37553755- For example,37563756-37573757- <example>37583758- <title>Example of put callback</title>37593759- <programlisting>37603760-<![CDATA[37613761- static int snd_myctl_put(struct snd_kcontrol *kcontrol,37623762- struct snd_ctl_elem_value *ucontrol)37633763- {37643764- struct mychip *chip = snd_kcontrol_chip(kcontrol);37653765- int changed = 0;37663766- if (chip->current_value !=37673767- ucontrol->value.integer.value[0]) {37683768- change_current_value(chip,37693769- ucontrol->value.integer.value[0]);37703770- changed = 1;37713771- }37723772- return changed;37733773- }37743774-]]>37753775- </programlisting>37763776- </example>37773777-37783778- As seen above, you have to return 1 if the value is37793779- changed. If the value is not changed, return 0 instead. 37803780- If any fatal error happens, return a negative error code as37813781- usual.37823782- </para>37833783-37843784- <para>37853785- As in the <structfield>get</structfield> callback,37863786- when the control has more than one elements,37873787- all elements must be evaluated in this callback, too.37883788- </para>37893789- </section>37903790-37913791- <section id="control-interface-callbacks-all">37923792- <title>Callbacks are not atomic</title>37933793- <para>37943794- All these three callbacks are basically not atomic.37953795- </para>37963796- </section>37973797- </section>37983798-37993799- <section id="control-interface-constructor">38003800- <title>Constructor</title>38013801- <para>38023802- When everything is ready, finally we can create a new38033803- control. To create a control, there are two functions to be38043804- called, <function>snd_ctl_new1()</function> and38053805- <function>snd_ctl_add()</function>. 38063806- </para>38073807-38083808- <para>38093809- In the simplest way, you can do like this:38103810-38113811- <informalexample>38123812- <programlisting>38133813-<![CDATA[38143814- err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip));38153815- if (err < 0)38163816- return err;38173817-]]>38183818- </programlisting>38193819- </informalexample>38203820-38213821- where <parameter>my_control</parameter> is the38223822- struct <structname>snd_kcontrol_new</structname> object defined above, and chip38233823- is the object pointer to be passed to38243824- kcontrol->private_data 38253825- which can be referred to in callbacks. 38263826- </para>38273827-38283828- <para>38293829- <function>snd_ctl_new1()</function> allocates a new38303830- <structname>snd_kcontrol</structname> instance,38313831- and <function>snd_ctl_add</function> assigns the given38323832- control component to the card. 38333833- </para>38343834- </section>38353835-38363836- <section id="control-interface-change-notification">38373837- <title>Change Notification</title>38383838- <para>38393839- If you need to change and update a control in the interrupt38403840- routine, you can call <function>snd_ctl_notify()</function>. For38413841- example, 38423842-38433843- <informalexample>38443844- <programlisting>38453845-<![CDATA[38463846- snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);38473847-]]>38483848- </programlisting>38493849- </informalexample>38503850-38513851- This function takes the card pointer, the event-mask, and the38523852- control id pointer for the notification. The event-mask38533853- specifies the types of notification, for example, in the above38543854- example, the change of control values is notified.38553855- The id pointer is the pointer of struct <structname>snd_ctl_elem_id</structname>38563856- to be notified.38573857- You can find some examples in <filename>es1938.c</filename> or38583858- <filename>es1968.c</filename> for hardware volume interrupts. 38593859- </para>38603860- </section>38613861-38623862- <section id="control-interface-tlv">38633863- <title>Metadata</title>38643864- <para>38653865- To provide information about the dB values of a mixer control, use38663866- on of the <constant>DECLARE_TLV_xxx</constant> macros from38673867- <filename><sound/tlv.h></filename> to define a variable38683868- containing this information, set the<structfield>tlv.p38693869- </structfield> field to point to this variable, and include the38703870- <constant>SNDRV_CTL_ELEM_ACCESS_TLV_READ</constant> flag in the38713871- <structfield>access</structfield> field; like this:38723872- <informalexample>38733873- <programlisting>38743874-<![CDATA[38753875- static DECLARE_TLV_DB_SCALE(db_scale_my_control, -4050, 150, 0);38763876-38773877- static struct snd_kcontrol_new my_control = {38783878- ...38793879- .access = SNDRV_CTL_ELEM_ACCESS_READWRITE |38803880- SNDRV_CTL_ELEM_ACCESS_TLV_READ,38813881- ...38823882- .tlv.p = db_scale_my_control,38833883- };38843884-]]>38853885- </programlisting>38863886- </informalexample>38873887- </para>38883888-38893889- <para>38903890- The <function>DECLARE_TLV_DB_SCALE</function> macro defines38913891- information about a mixer control where each step in the control's38923892- value changes the dB value by a constant dB amount.38933893- The first parameter is the name of the variable to be defined.38943894- The second parameter is the minimum value, in units of 0.01 dB.38953895- The third parameter is the step size, in units of 0.01 dB.38963896- Set the fourth parameter to 1 if the minimum value actually mutes38973897- the control.38983898- </para>38993899-39003900- <para>39013901- The <function>DECLARE_TLV_DB_LINEAR</function> macro defines39023902- information about a mixer control where the control's value affects39033903- the output linearly.39043904- The first parameter is the name of the variable to be defined.39053905- The second parameter is the minimum value, in units of 0.01 dB.39063906- The third parameter is the maximum value, in units of 0.01 dB.39073907- If the minimum value mutes the control, set the second parameter to39083908- <constant>TLV_DB_GAIN_MUTE</constant>.39093909- </para>39103910- </section>39113911-39123912- </chapter>39133913-39143914-39153915-<!-- ****************************************************** -->39163916-<!-- API for AC97 Codec -->39173917-<!-- ****************************************************** -->39183918- <chapter id="api-ac97">39193919- <title>API for AC97 Codec</title>39203920-39213921- <section>39223922- <title>General</title>39233923- <para>39243924- The ALSA AC97 codec layer is a well-defined one, and you don't39253925- have to write much code to control it. Only low-level control39263926- routines are necessary. The AC97 codec API is defined in39273927- <filename><sound/ac97_codec.h></filename>. 39283928- </para>39293929- </section>39303930-39313931- <section id="api-ac97-example">39323932- <title>Full Code Example</title>39333933- <para>39343934- <example>39353935- <title>Example of AC97 Interface</title>39363936- <programlisting>39373937-<![CDATA[39383938- struct mychip {39393939- ....39403940- struct snd_ac97 *ac97;39413941- ....39423942- };39433943-39443944- static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,39453945- unsigned short reg)39463946- {39473947- struct mychip *chip = ac97->private_data;39483948- ....39493949- /* read a register value here from the codec */39503950- return the_register_value;39513951- }39523952-39533953- static void snd_mychip_ac97_write(struct snd_ac97 *ac97,39543954- unsigned short reg, unsigned short val)39553955- {39563956- struct mychip *chip = ac97->private_data;39573957- ....39583958- /* write the given register value to the codec */39593959- }39603960-39613961- static int snd_mychip_ac97(struct mychip *chip)39623962- {39633963- struct snd_ac97_bus *bus;39643964- struct snd_ac97_template ac97;39653965- int err;39663966- static struct snd_ac97_bus_ops ops = {39673967- .write = snd_mychip_ac97_write,39683968- .read = snd_mychip_ac97_read,39693969- };39703970-39713971- err = snd_ac97_bus(chip->card, 0, &ops, NULL, &bus);39723972- if (err < 0)39733973- return err;39743974- memset(&ac97, 0, sizeof(ac97));39753975- ac97.private_data = chip;39763976- return snd_ac97_mixer(bus, &ac97, &chip->ac97);39773977- }39783978-39793979-]]>39803980- </programlisting>39813981- </example>39823982- </para>39833983- </section>39843984-39853985- <section id="api-ac97-constructor">39863986- <title>Constructor</title>39873987- <para>39883988- To create an ac97 instance, first call <function>snd_ac97_bus</function>39893989- with an <type>ac97_bus_ops_t</type> record with callback functions.39903990-39913991- <informalexample>39923992- <programlisting>39933993-<![CDATA[39943994- struct snd_ac97_bus *bus;39953995- static struct snd_ac97_bus_ops ops = {39963996- .write = snd_mychip_ac97_write,39973997- .read = snd_mychip_ac97_read,39983998- };39993999-40004000- snd_ac97_bus(card, 0, &ops, NULL, &pbus);40014001-]]>40024002- </programlisting>40034003- </informalexample>40044004-40054005- The bus record is shared among all belonging ac97 instances.40064006- </para>40074007-40084008- <para>40094009- And then call <function>snd_ac97_mixer()</function> with an40104010- struct <structname>snd_ac97_template</structname>40114011- record together with the bus pointer created above.40124012-40134013- <informalexample>40144014- <programlisting>40154015-<![CDATA[40164016- struct snd_ac97_template ac97;40174017- int err;40184018-40194019- memset(&ac97, 0, sizeof(ac97));40204020- ac97.private_data = chip;40214021- snd_ac97_mixer(bus, &ac97, &chip->ac97);40224022-]]>40234023- </programlisting>40244024- </informalexample>40254025-40264026- where chip->ac97 is a pointer to a newly created40274027- <type>ac97_t</type> instance.40284028- In this case, the chip pointer is set as the private data, so that40294029- the read/write callback functions can refer to this chip instance.40304030- This instance is not necessarily stored in the chip40314031- record. If you need to change the register values from the40324032- driver, or need the suspend/resume of ac97 codecs, keep this40334033- pointer to pass to the corresponding functions.40344034- </para>40354035- </section>40364036-40374037- <section id="api-ac97-callbacks">40384038- <title>Callbacks</title>40394039- <para>40404040- The standard callbacks are <structfield>read</structfield> and40414041- <structfield>write</structfield>. Obviously they 40424042- correspond to the functions for read and write accesses to the40434043- hardware low-level codes. 40444044- </para>40454045-40464046- <para>40474047- The <structfield>read</structfield> callback returns the40484048- register value specified in the argument. 40494049-40504050- <informalexample>40514051- <programlisting>40524052-<![CDATA[40534053- static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,40544054- unsigned short reg)40554055- {40564056- struct mychip *chip = ac97->private_data;40574057- ....40584058- return the_register_value;40594059- }40604060-]]>40614061- </programlisting>40624062- </informalexample>40634063-40644064- Here, the chip can be cast from ac97->private_data.40654065- </para>40664066-40674067- <para>40684068- Meanwhile, the <structfield>write</structfield> callback is40694069- used to set the register value. 40704070-40714071- <informalexample>40724072- <programlisting>40734073-<![CDATA[40744074- static void snd_mychip_ac97_write(struct snd_ac97 *ac97,40754075- unsigned short reg, unsigned short val)40764076-]]>40774077- </programlisting>40784078- </informalexample>40794079- </para>40804080-40814081- <para>40824082- These callbacks are non-atomic like the control API callbacks.40834083- </para>40844084-40854085- <para>40864086- There are also other callbacks:40874087- <structfield>reset</structfield>,40884088- <structfield>wait</structfield> and40894089- <structfield>init</structfield>. 40904090- </para>40914091-40924092- <para>40934093- The <structfield>reset</structfield> callback is used to reset40944094- the codec. If the chip requires a special kind of reset, you can40954095- define this callback. 40964096- </para>40974097-40984098- <para>40994099- The <structfield>wait</structfield> callback is used to41004100- add some waiting time in the standard initialization of the codec. If the41014101- chip requires the extra waiting time, define this callback. 41024102- </para>41034103-41044104- <para>41054105- The <structfield>init</structfield> callback is used for41064106- additional initialization of the codec.41074107- </para>41084108- </section>41094109-41104110- <section id="api-ac97-updating-registers">41114111- <title>Updating Registers in The Driver</title>41124112- <para>41134113- If you need to access to the codec from the driver, you can41144114- call the following functions:41154115- <function>snd_ac97_write()</function>,41164116- <function>snd_ac97_read()</function>,41174117- <function>snd_ac97_update()</function> and41184118- <function>snd_ac97_update_bits()</function>. 41194119- </para>41204120-41214121- <para>41224122- Both <function>snd_ac97_write()</function> and41234123- <function>snd_ac97_update()</function> functions are used to41244124- set a value to the given register41254125- (<constant>AC97_XXX</constant>). The difference between them is41264126- that <function>snd_ac97_update()</function> doesn't write a41274127- value if the given value has been already set, while41284128- <function>snd_ac97_write()</function> always rewrites the41294129- value. 41304130-41314131- <informalexample>41324132- <programlisting>41334133-<![CDATA[41344134- snd_ac97_write(ac97, AC97_MASTER, 0x8080);41354135- snd_ac97_update(ac97, AC97_MASTER, 0x8080);41364136-]]>41374137- </programlisting>41384138- </informalexample>41394139- </para>41404140-41414141- <para>41424142- <function>snd_ac97_read()</function> is used to read the value41434143- of the given register. For example, 41444144-41454145- <informalexample>41464146- <programlisting>41474147-<![CDATA[41484148- value = snd_ac97_read(ac97, AC97_MASTER);41494149-]]>41504150- </programlisting>41514151- </informalexample>41524152- </para>41534153-41544154- <para>41554155- <function>snd_ac97_update_bits()</function> is used to update41564156- some bits in the given register. 41574157-41584158- <informalexample>41594159- <programlisting>41604160-<![CDATA[41614161- snd_ac97_update_bits(ac97, reg, mask, value);41624162-]]>41634163- </programlisting>41644164- </informalexample>41654165- </para>41664166-41674167- <para>41684168- Also, there is a function to change the sample rate (of a41694169- given register such as41704170- <constant>AC97_PCM_FRONT_DAC_RATE</constant>) when VRA or41714171- DRA is supported by the codec:41724172- <function>snd_ac97_set_rate()</function>. 41734173-41744174- <informalexample>41754175- <programlisting>41764176-<![CDATA[41774177- snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);41784178-]]>41794179- </programlisting>41804180- </informalexample>41814181- </para>41824182-41834183- <para>41844184- The following registers are available to set the rate:41854185- <constant>AC97_PCM_MIC_ADC_RATE</constant>,41864186- <constant>AC97_PCM_FRONT_DAC_RATE</constant>,41874187- <constant>AC97_PCM_LR_ADC_RATE</constant>,41884188- <constant>AC97_SPDIF</constant>. When41894189- <constant>AC97_SPDIF</constant> is specified, the register is41904190- not really changed but the corresponding IEC958 status bits will41914191- be updated. 41924192- </para>41934193- </section>41944194-41954195- <section id="api-ac97-clock-adjustment">41964196- <title>Clock Adjustment</title>41974197- <para>41984198- In some chips, the clock of the codec isn't 48000 but using a41994199- PCI clock (to save a quartz!). In this case, change the field42004200- bus->clock to the corresponding42014201- value. For example, intel8x0 42024202- and es1968 drivers have their own function to read from the clock.42034203- </para>42044204- </section>42054205-42064206- <section id="api-ac97-proc-files">42074207- <title>Proc Files</title>42084208- <para>42094209- The ALSA AC97 interface will create a proc file such as42104210- <filename>/proc/asound/card0/codec97#0/ac97#0-0</filename> and42114211- <filename>ac97#0-0+regs</filename>. You can refer to these files to42124212- see the current status and registers of the codec. 42134213- </para>42144214- </section>42154215-42164216- <section id="api-ac97-multiple-codecs">42174217- <title>Multiple Codecs</title>42184218- <para>42194219- When there are several codecs on the same card, you need to42204220- call <function>snd_ac97_mixer()</function> multiple times with42214221- ac97.num=1 or greater. The <structfield>num</structfield> field42224222- specifies the codec number. 42234223- </para>42244224-42254225- <para>42264226- If you set up multiple codecs, you either need to write42274227- different callbacks for each codec or check42284228- ac97->num in the callback routines. 42294229- </para>42304230- </section>42314231-42324232- </chapter>42334233-42344234-42354235-<!-- ****************************************************** -->42364236-<!-- MIDI (MPU401-UART) Interface -->42374237-<!-- ****************************************************** -->42384238- <chapter id="midi-interface">42394239- <title>MIDI (MPU401-UART) Interface</title>42404240-42414241- <section id="midi-interface-general">42424242- <title>General</title>42434243- <para>42444244- Many soundcards have built-in MIDI (MPU401-UART)42454245- interfaces. When the soundcard supports the standard MPU401-UART42464246- interface, most likely you can use the ALSA MPU401-UART API. The42474247- MPU401-UART API is defined in42484248- <filename><sound/mpu401.h></filename>. 42494249- </para>42504250-42514251- <para>42524252- Some soundchips have a similar but slightly different42534253- implementation of mpu401 stuff. For example, emu10k1 has its own42544254- mpu401 routines. 42554255- </para>42564256- </section>42574257-42584258- <section id="midi-interface-constructor">42594259- <title>Constructor</title>42604260- <para>42614261- To create a rawmidi object, call42624262- <function>snd_mpu401_uart_new()</function>. 42634263-42644264- <informalexample>42654265- <programlisting>42664266-<![CDATA[42674267- struct snd_rawmidi *rmidi;42684268- snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, info_flags,42694269- irq, &rmidi);42704270-]]>42714271- </programlisting>42724272- </informalexample>42734273- </para>42744274-42754275- <para>42764276- The first argument is the card pointer, and the second is the42774277- index of this component. You can create up to 8 rawmidi42784278- devices. 42794279- </para>42804280-42814281- <para>42824282- The third argument is the type of the hardware,42834283- <constant>MPU401_HW_XXX</constant>. If it's not a special one,42844284- you can use <constant>MPU401_HW_MPU401</constant>. 42854285- </para>42864286-42874287- <para>42884288- The 4th argument is the I/O port address. Many42894289- backward-compatible MPU401 have an I/O port such as 0x330. Or, it42904290- might be a part of its own PCI I/O region. It depends on the42914291- chip design. 42924292- </para>42934293-42944294- <para>42954295- The 5th argument is a bitflag for additional information.42964296- When the I/O port address above is part of the PCI I/O42974297- region, the MPU401 I/O port might have been already allocated42984298- (reserved) by the driver itself. In such a case, pass a bit flag42994299- <constant>MPU401_INFO_INTEGRATED</constant>,43004300- and the mpu401-uart layer will allocate the I/O ports by itself. 43014301- </para>43024302-43034303- <para>43044304- When the controller supports only the input or output MIDI stream,43054305- pass the <constant>MPU401_INFO_INPUT</constant> or43064306- <constant>MPU401_INFO_OUTPUT</constant> bitflag, respectively.43074307- Then the rawmidi instance is created as a single stream.43084308- </para>43094309-43104310- <para>43114311- <constant>MPU401_INFO_MMIO</constant> bitflag is used to change43124312- the access method to MMIO (via readb and writeb) instead of43134313- iob and outb. In this case, you have to pass the iomapped address43144314- to <function>snd_mpu401_uart_new()</function>.43154315- </para>43164316-43174317- <para>43184318- When <constant>MPU401_INFO_TX_IRQ</constant> is set, the output43194319- stream isn't checked in the default interrupt handler. The driver43204320- needs to call <function>snd_mpu401_uart_interrupt_tx()</function>43214321- by itself to start processing the output stream in the irq handler.43224322- </para>43234323-43244324- <para>43254325- If the MPU-401 interface shares its interrupt with the other logical43264326- devices on the card, set <constant>MPU401_INFO_IRQ_HOOK</constant>43274327- (see <link linkend="midi-interface-interrupt-handler"><citetitle>43284328- below</citetitle></link>).43294329- </para>43304330-43314331- <para>43324332- Usually, the port address corresponds to the command port and43334333- port + 1 corresponds to the data port. If not, you may change43344334- the <structfield>cport</structfield> field of43354335- struct <structname>snd_mpu401</structname> manually 43364336- afterward. However, <structname>snd_mpu401</structname> pointer is not43374337- returned explicitly by43384338- <function>snd_mpu401_uart_new()</function>. You need to cast43394339- rmidi->private_data to43404340- <structname>snd_mpu401</structname> explicitly, 43414341-43424342- <informalexample>43434343- <programlisting>43444344-<![CDATA[43454345- struct snd_mpu401 *mpu;43464346- mpu = rmidi->private_data;43474347-]]>43484348- </programlisting>43494349- </informalexample>43504350-43514351- and reset the cport as you like:43524352-43534353- <informalexample>43544354- <programlisting>43554355-<![CDATA[43564356- mpu->cport = my_own_control_port;43574357-]]>43584358- </programlisting>43594359- </informalexample>43604360- </para>43614361-43624362- <para>43634363- The 6th argument specifies the ISA irq number that will be43644364- allocated. If no interrupt is to be allocated (because your43654365- code is already allocating a shared interrupt, or because the43664366- device does not use interrupts), pass -1 instead.43674367- For a MPU-401 device without an interrupt, a polling timer43684368- will be used instead.43694369- </para>43704370- </section>43714371-43724372- <section id="midi-interface-interrupt-handler">43734373- <title>Interrupt Handler</title>43744374- <para>43754375- When the interrupt is allocated in43764376- <function>snd_mpu401_uart_new()</function>, an exclusive ISA43774377- interrupt handler is automatically used, hence you don't have43784378- anything else to do than creating the mpu401 stuff. Otherwise, you43794379- have to set <constant>MPU401_INFO_IRQ_HOOK</constant>, and call43804380- <function>snd_mpu401_uart_interrupt()</function> explicitly from your43814381- own interrupt handler when it has determined that a UART interrupt43824382- has occurred.43834383- </para>43844384-43854385- <para>43864386- In this case, you need to pass the private_data of the43874387- returned rawmidi object from43884388- <function>snd_mpu401_uart_new()</function> as the second43894389- argument of <function>snd_mpu401_uart_interrupt()</function>. 43904390-43914391- <informalexample>43924392- <programlisting>43934393-<![CDATA[43944394- snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);43954395-]]>43964396- </programlisting>43974397- </informalexample>43984398- </para>43994399- </section>44004400-44014401- </chapter>44024402-44034403-44044404-<!-- ****************************************************** -->44054405-<!-- RawMIDI Interface -->44064406-<!-- ****************************************************** -->44074407- <chapter id="rawmidi-interface">44084408- <title>RawMIDI Interface</title>44094409-44104410- <section id="rawmidi-interface-overview">44114411- <title>Overview</title>44124412-44134413- <para>44144414- The raw MIDI interface is used for hardware MIDI ports that can44154415- be accessed as a byte stream. It is not used for synthesizer44164416- chips that do not directly understand MIDI.44174417- </para>44184418-44194419- <para>44204420- ALSA handles file and buffer management. All you have to do is44214421- to write some code to move data between the buffer and the44224422- hardware.44234423- </para>44244424-44254425- <para>44264426- The rawmidi API is defined in44274427- <filename><sound/rawmidi.h></filename>.44284428- </para>44294429- </section>44304430-44314431- <section id="rawmidi-interface-constructor">44324432- <title>Constructor</title>44334433-44344434- <para>44354435- To create a rawmidi device, call the44364436- <function>snd_rawmidi_new</function> function:44374437- <informalexample>44384438- <programlisting>44394439-<![CDATA[44404440- struct snd_rawmidi *rmidi;44414441- err = snd_rawmidi_new(chip->card, "MyMIDI", 0, outs, ins, &rmidi);44424442- if (err < 0)44434443- return err;44444444- rmidi->private_data = chip;44454445- strcpy(rmidi->name, "My MIDI");44464446- rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |44474447- SNDRV_RAWMIDI_INFO_INPUT |44484448- SNDRV_RAWMIDI_INFO_DUPLEX;44494449-]]>44504450- </programlisting>44514451- </informalexample>44524452- </para>44534453-44544454- <para>44554455- The first argument is the card pointer, the second argument is44564456- the ID string.44574457- </para>44584458-44594459- <para>44604460- The third argument is the index of this component. You can44614461- create up to 8 rawmidi devices.44624462- </para>44634463-44644464- <para>44654465- The fourth and fifth arguments are the number of output and44664466- input substreams, respectively, of this device (a substream is44674467- the equivalent of a MIDI port).44684468- </para>44694469-44704470- <para>44714471- Set the <structfield>info_flags</structfield> field to specify44724472- the capabilities of the device.44734473- Set <constant>SNDRV_RAWMIDI_INFO_OUTPUT</constant> if there is44744474- at least one output port,44754475- <constant>SNDRV_RAWMIDI_INFO_INPUT</constant> if there is at44764476- least one input port,44774477- and <constant>SNDRV_RAWMIDI_INFO_DUPLEX</constant> if the device44784478- can handle output and input at the same time.44794479- </para>44804480-44814481- <para>44824482- After the rawmidi device is created, you need to set the44834483- operators (callbacks) for each substream. There are helper44844484- functions to set the operators for all the substreams of a device:44854485- <informalexample>44864486- <programlisting>44874487-<![CDATA[44884488- snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_mymidi_output_ops);44894489- snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_mymidi_input_ops);44904490-]]>44914491- </programlisting>44924492- </informalexample>44934493- </para>44944494-44954495- <para>44964496- The operators are usually defined like this:44974497- <informalexample>44984498- <programlisting>44994499-<![CDATA[45004500- static struct snd_rawmidi_ops snd_mymidi_output_ops = {45014501- .open = snd_mymidi_output_open,45024502- .close = snd_mymidi_output_close,45034503- .trigger = snd_mymidi_output_trigger,45044504- };45054505-]]>45064506- </programlisting>45074507- </informalexample>45084508- These callbacks are explained in the <link45094509- linkend="rawmidi-interface-callbacks"><citetitle>Callbacks</citetitle></link>45104510- section.45114511- </para>45124512-45134513- <para>45144514- If there are more than one substream, you should give a45154515- unique name to each of them:45164516- <informalexample>45174517- <programlisting>45184518-<![CDATA[45194519- struct snd_rawmidi_substream *substream;45204520- list_for_each_entry(substream,45214521- &rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,45224522- list {45234523- sprintf(substream->name, "My MIDI Port %d", substream->number + 1);45244524- }45254525- /* same for SNDRV_RAWMIDI_STREAM_INPUT */45264526-]]>45274527- </programlisting>45284528- </informalexample>45294529- </para>45304530- </section>45314531-45324532- <section id="rawmidi-interface-callbacks">45334533- <title>Callbacks</title>45344534-45354535- <para>45364536- In all the callbacks, the private data that you've set for the45374537- rawmidi device can be accessed as45384538- substream->rmidi->private_data.45394539- <!-- <code> isn't available before DocBook 4.3 -->45404540- </para>45414541-45424542- <para>45434543- If there is more than one port, your callbacks can determine the45444544- port index from the struct snd_rawmidi_substream data passed to each45454545- callback:45464546- <informalexample>45474547- <programlisting>45484548-<![CDATA[45494549- struct snd_rawmidi_substream *substream;45504550- int index = substream->number;45514551-]]>45524552- </programlisting>45534553- </informalexample>45544554- </para>45554555-45564556- <section id="rawmidi-interface-op-open">45574557- <title><function>open</function> callback</title>45584558-45594559- <informalexample>45604560- <programlisting>45614561-<![CDATA[45624562- static int snd_xxx_open(struct snd_rawmidi_substream *substream);45634563-]]>45644564- </programlisting>45654565- </informalexample>45664566-45674567- <para>45684568- This is called when a substream is opened.45694569- You can initialize the hardware here, but you shouldn't45704570- start transmitting/receiving data yet.45714571- </para>45724572- </section>45734573-45744574- <section id="rawmidi-interface-op-close">45754575- <title><function>close</function> callback</title>45764576-45774577- <informalexample>45784578- <programlisting>45794579-<![CDATA[45804580- static int snd_xxx_close(struct snd_rawmidi_substream *substream);45814581-]]>45824582- </programlisting>45834583- </informalexample>45844584-45854585- <para>45864586- Guess what.45874587- </para>45884588-45894589- <para>45904590- The <function>open</function> and <function>close</function>45914591- callbacks of a rawmidi device are serialized with a mutex,45924592- and can sleep.45934593- </para>45944594- </section>45954595-45964596- <section id="rawmidi-interface-op-trigger-out">45974597- <title><function>trigger</function> callback for output45984598- substreams</title>45994599-46004600- <informalexample>46014601- <programlisting>46024602-<![CDATA[46034603- static void snd_xxx_output_trigger(struct snd_rawmidi_substream *substream, int up);46044604-]]>46054605- </programlisting>46064606- </informalexample>46074607-46084608- <para>46094609- This is called with a nonzero <parameter>up</parameter>46104610- parameter when there is some data in the substream buffer that46114611- must be transmitted.46124612- </para>46134613-46144614- <para>46154615- To read data from the buffer, call46164616- <function>snd_rawmidi_transmit_peek</function>. It will46174617- return the number of bytes that have been read; this will be46184618- less than the number of bytes requested when there are no more46194619- data in the buffer.46204620- After the data have been transmitted successfully, call46214621- <function>snd_rawmidi_transmit_ack</function> to remove the46224622- data from the substream buffer:46234623- <informalexample>46244624- <programlisting>46254625-<![CDATA[46264626- unsigned char data;46274627- while (snd_rawmidi_transmit_peek(substream, &data, 1) == 1) {46284628- if (snd_mychip_try_to_transmit(data))46294629- snd_rawmidi_transmit_ack(substream, 1);46304630- else46314631- break; /* hardware FIFO full */46324632- }46334633-]]>46344634- </programlisting>46354635- </informalexample>46364636- </para>46374637-46384638- <para>46394639- If you know beforehand that the hardware will accept data, you46404640- can use the <function>snd_rawmidi_transmit</function> function46414641- which reads some data and removes them from the buffer at once:46424642- <informalexample>46434643- <programlisting>46444644-<![CDATA[46454645- while (snd_mychip_transmit_possible()) {46464646- unsigned char data;46474647- if (snd_rawmidi_transmit(substream, &data, 1) != 1)46484648- break; /* no more data */46494649- snd_mychip_transmit(data);46504650- }46514651-]]>46524652- </programlisting>46534653- </informalexample>46544654- </para>46554655-46564656- <para>46574657- If you know beforehand how many bytes you can accept, you can46584658- use a buffer size greater than one with the46594659- <function>snd_rawmidi_transmit*</function> functions.46604660- </para>46614661-46624662- <para>46634663- The <function>trigger</function> callback must not sleep. If46644664- the hardware FIFO is full before the substream buffer has been46654665- emptied, you have to continue transmitting data later, either46664666- in an interrupt handler, or with a timer if the hardware46674667- doesn't have a MIDI transmit interrupt.46684668- </para>46694669-46704670- <para>46714671- The <function>trigger</function> callback is called with a46724672- zero <parameter>up</parameter> parameter when the transmission46734673- of data should be aborted.46744674- </para>46754675- </section>46764676-46774677- <section id="rawmidi-interface-op-trigger-in">46784678- <title><function>trigger</function> callback for input46794679- substreams</title>46804680-46814681- <informalexample>46824682- <programlisting>46834683-<![CDATA[46844684- static void snd_xxx_input_trigger(struct snd_rawmidi_substream *substream, int up);46854685-]]>46864686- </programlisting>46874687- </informalexample>46884688-46894689- <para>46904690- This is called with a nonzero <parameter>up</parameter>46914691- parameter to enable receiving data, or with a zero46924692- <parameter>up</parameter> parameter do disable receiving data.46934693- </para>46944694-46954695- <para>46964696- The <function>trigger</function> callback must not sleep; the46974697- actual reading of data from the device is usually done in an46984698- interrupt handler.46994699- </para>47004700-47014701- <para>47024702- When data reception is enabled, your interrupt handler should47034703- call <function>snd_rawmidi_receive</function> for all received47044704- data:47054705- <informalexample>47064706- <programlisting>47074707-<![CDATA[47084708- void snd_mychip_midi_interrupt(...)47094709- {47104710- while (mychip_midi_available()) {47114711- unsigned char data;47124712- data = mychip_midi_read();47134713- snd_rawmidi_receive(substream, &data, 1);47144714- }47154715- }47164716-]]>47174717- </programlisting>47184718- </informalexample>47194719- </para>47204720- </section>47214721-47224722- <section id="rawmidi-interface-op-drain">47234723- <title><function>drain</function> callback</title>47244724-47254725- <informalexample>47264726- <programlisting>47274727-<![CDATA[47284728- static void snd_xxx_drain(struct snd_rawmidi_substream *substream);47294729-]]>47304730- </programlisting>47314731- </informalexample>47324732-47334733- <para>47344734- This is only used with output substreams. This function should wait47354735- until all data read from the substream buffer have been transmitted.47364736- This ensures that the device can be closed and the driver unloaded47374737- without losing data.47384738- </para>47394739-47404740- <para>47414741- This callback is optional. If you do not set47424742- <structfield>drain</structfield> in the struct snd_rawmidi_ops47434743- structure, ALSA will simply wait for 50 milliseconds47444744- instead.47454745- </para>47464746- </section>47474747- </section>47484748-47494749- </chapter>47504750-47514751-47524752-<!-- ****************************************************** -->47534753-<!-- Miscellaneous Devices -->47544754-<!-- ****************************************************** -->47554755- <chapter id="misc-devices">47564756- <title>Miscellaneous Devices</title>47574757-47584758- <section id="misc-devices-opl3">47594759- <title>FM OPL3</title>47604760- <para>47614761- The FM OPL3 is still used in many chips (mainly for backward47624762- compatibility). ALSA has a nice OPL3 FM control layer, too. The47634763- OPL3 API is defined in47644764- <filename><sound/opl3.h></filename>. 47654765- </para>47664766-47674767- <para>47684768- FM registers can be directly accessed through the direct-FM API,47694769- defined in <filename><sound/asound_fm.h></filename>. In47704770- ALSA native mode, FM registers are accessed through47714771- the Hardware-Dependent Device direct-FM extension API, whereas in47724772- OSS compatible mode, FM registers can be accessed with the OSS47734773- direct-FM compatible API in <filename>/dev/dmfmX</filename> device. 47744774- </para>47754775-47764776- <para>47774777- To create the OPL3 component, you have two functions to47784778- call. The first one is a constructor for the <type>opl3_t</type>47794779- instance. 47804780-47814781- <informalexample>47824782- <programlisting>47834783-<![CDATA[47844784- struct snd_opl3 *opl3;47854785- snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,47864786- integrated, &opl3);47874787-]]>47884788- </programlisting>47894789- </informalexample>47904790- </para>47914791-47924792- <para>47934793- The first argument is the card pointer, the second one is the47944794- left port address, and the third is the right port address. In47954795- most cases, the right port is placed at the left port + 2. 47964796- </para>47974797-47984798- <para>47994799- The fourth argument is the hardware type.48004800- </para>48014801-48024802- <para>48034803- When the left and right ports have been already allocated by48044804- the card driver, pass non-zero to the fifth argument48054805- (<parameter>integrated</parameter>). Otherwise, the opl3 module will48064806- allocate the specified ports by itself. 48074807- </para>48084808-48094809- <para>48104810- When the accessing the hardware requires special method48114811- instead of the standard I/O access, you can create opl3 instance48124812- separately with <function>snd_opl3_new()</function>.48134813-48144814- <informalexample>48154815- <programlisting>48164816-<![CDATA[48174817- struct snd_opl3 *opl3;48184818- snd_opl3_new(card, OPL3_HW_OPL3_XXX, &opl3);48194819-]]>48204820- </programlisting>48214821- </informalexample>48224822- </para>48234823-48244824- <para>48254825- Then set <structfield>command</structfield>,48264826- <structfield>private_data</structfield> and48274827- <structfield>private_free</structfield> for the private48284828- access function, the private data and the destructor.48294829- The l_port and r_port are not necessarily set. Only the48304830- command must be set properly. You can retrieve the data48314831- from the opl3->private_data field.48324832- </para>48334833-48344834- <para>48354835- After creating the opl3 instance via <function>snd_opl3_new()</function>,48364836- call <function>snd_opl3_init()</function> to initialize the chip to the48374837- proper state. Note that <function>snd_opl3_create()</function> always48384838- calls it internally.48394839- </para>48404840-48414841- <para>48424842- If the opl3 instance is created successfully, then create a48434843- hwdep device for this opl3. 48444844-48454845- <informalexample>48464846- <programlisting>48474847-<![CDATA[48484848- struct snd_hwdep *opl3hwdep;48494849- snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);48504850-]]>48514851- </programlisting>48524852- </informalexample>48534853- </para>48544854-48554855- <para>48564856- The first argument is the <type>opl3_t</type> instance you48574857- created, and the second is the index number, usually 0. 48584858- </para>48594859-48604860- <para>48614861- The third argument is the index-offset for the sequencer48624862- client assigned to the OPL3 port. When there is an MPU401-UART,48634863- give 1 for here (UART always takes 0). 48644864- </para>48654865- </section>48664866-48674867- <section id="misc-devices-hardware-dependent">48684868- <title>Hardware-Dependent Devices</title>48694869- <para>48704870- Some chips need user-space access for special48714871- controls or for loading the micro code. In such a case, you can48724872- create a hwdep (hardware-dependent) device. The hwdep API is48734873- defined in <filename><sound/hwdep.h></filename>. You can48744874- find examples in opl3 driver or48754875- <filename>isa/sb/sb16_csp.c</filename>. 48764876- </para>48774877-48784878- <para>48794879- The creation of the <type>hwdep</type> instance is done via48804880- <function>snd_hwdep_new()</function>. 48814881-48824882- <informalexample>48834883- <programlisting>48844884-<![CDATA[48854885- struct snd_hwdep *hw;48864886- snd_hwdep_new(card, "My HWDEP", 0, &hw);48874887-]]>48884888- </programlisting>48894889- </informalexample>48904890-48914891- where the third argument is the index number.48924892- </para>48934893-48944894- <para>48954895- You can then pass any pointer value to the48964896- <parameter>private_data</parameter>.48974897- If you assign a private data, you should define the48984898- destructor, too. The destructor function is set in48994899- the <structfield>private_free</structfield> field. 49004900-49014901- <informalexample>49024902- <programlisting>49034903-<![CDATA[49044904- struct mydata *p = kmalloc(sizeof(*p), GFP_KERNEL);49054905- hw->private_data = p;49064906- hw->private_free = mydata_free;49074907-]]>49084908- </programlisting>49094909- </informalexample>49104910-49114911- and the implementation of the destructor would be:49124912-49134913- <informalexample>49144914- <programlisting>49154915-<![CDATA[49164916- static void mydata_free(struct snd_hwdep *hw)49174917- {49184918- struct mydata *p = hw->private_data;49194919- kfree(p);49204920- }49214921-]]>49224922- </programlisting>49234923- </informalexample>49244924- </para>49254925-49264926- <para>49274927- The arbitrary file operations can be defined for this49284928- instance. The file operators are defined in49294929- the <parameter>ops</parameter> table. For example, assume that49304930- this chip needs an ioctl. 49314931-49324932- <informalexample>49334933- <programlisting>49344934-<![CDATA[49354935- hw->ops.open = mydata_open;49364936- hw->ops.ioctl = mydata_ioctl;49374937- hw->ops.release = mydata_release;49384938-]]>49394939- </programlisting>49404940- </informalexample>49414941-49424942- And implement the callback functions as you like.49434943- </para>49444944- </section>49454945-49464946- <section id="misc-devices-IEC958">49474947- <title>IEC958 (S/PDIF)</title>49484948- <para>49494949- Usually the controls for IEC958 devices are implemented via49504950- the control interface. There is a macro to compose a name string for49514951- IEC958 controls, <function>SNDRV_CTL_NAME_IEC958()</function>49524952- defined in <filename><include/asound.h></filename>. 49534953- </para>49544954-49554955- <para>49564956- There are some standard controls for IEC958 status bits. These49574957- controls use the type <type>SNDRV_CTL_ELEM_TYPE_IEC958</type>,49584958- and the size of element is fixed as 4 bytes array49594959- (value.iec958.status[x]). For the <structfield>info</structfield>49604960- callback, you don't specify 49614961- the value field for this type (the count field must be set,49624962- though). 49634963- </para>49644964-49654965- <para>49664966- <quote>IEC958 Playback Con Mask</quote> is used to return the49674967- bit-mask for the IEC958 status bits of consumer mode. Similarly,49684968- <quote>IEC958 Playback Pro Mask</quote> returns the bitmask for49694969- professional mode. They are read-only controls, and are defined49704970- as MIXER controls (iface =49714971- <constant>SNDRV_CTL_ELEM_IFACE_MIXER</constant>). 49724972- </para>49734973-49744974- <para>49754975- Meanwhile, <quote>IEC958 Playback Default</quote> control is49764976- defined for getting and setting the current default IEC95849774977- bits. Note that this one is usually defined as a PCM control49784978- (iface = <constant>SNDRV_CTL_ELEM_IFACE_PCM</constant>),49794979- although in some places it's defined as a MIXER control. 49804980- </para>49814981-49824982- <para>49834983- In addition, you can define the control switches to49844984- enable/disable or to set the raw bit mode. The implementation49854985- will depend on the chip, but the control should be named as49864986- <quote>IEC958 xxx</quote>, preferably using49874987- the <function>SNDRV_CTL_NAME_IEC958()</function> macro. 49884988- </para>49894989-49904990- <para>49914991- You can find several cases, for example,49924992- <filename>pci/emu10k1</filename>,49934993- <filename>pci/ice1712</filename>, or49944994- <filename>pci/cmipci.c</filename>. 49954995- </para>49964996- </section>49974997-49984998- </chapter>49994999-50005000-50015001-<!-- ****************************************************** -->50025002-<!-- Buffer and Memory Management -->50035003-<!-- ****************************************************** -->50045004- <chapter id="buffer-and-memory">50055005- <title>Buffer and Memory Management</title>50065006-50075007- <section id="buffer-and-memory-buffer-types">50085008- <title>Buffer Types</title>50095009- <para>50105010- ALSA provides several different buffer allocation functions50115011- depending on the bus and the architecture. All these have a50125012- consistent API. The allocation of physically-contiguous pages is50135013- done via 50145014- <function>snd_malloc_xxx_pages()</function> function, where xxx50155015- is the bus type. 50165016- </para>50175017-50185018- <para>50195019- The allocation of pages with fallback is50205020- <function>snd_malloc_xxx_pages_fallback()</function>. This50215021- function tries to allocate the specified pages but if the pages50225022- are not available, it tries to reduce the page sizes until50235023- enough space is found.50245024- </para>50255025-50265026- <para>50275027- The release the pages, call50285028- <function>snd_free_xxx_pages()</function> function. 50295029- </para>50305030-50315031- <para>50325032- Usually, ALSA drivers try to allocate and reserve50335033- a large contiguous physical space50345034- at the time the module is loaded for the later use.50355035- This is called <quote>pre-allocation</quote>.50365036- As already written, you can call the following function at 50375037- pcm instance construction time (in the case of PCI bus). 50385038-50395039- <informalexample>50405040- <programlisting>50415041-<![CDATA[50425042- snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,50435043- snd_dma_pci_data(pci), size, max);50445044-]]>50455045- </programlisting>50465046- </informalexample>50475047-50485048- where <parameter>size</parameter> is the byte size to be50495049- pre-allocated and the <parameter>max</parameter> is the maximum50505050- size to be changed via the <filename>prealloc</filename> proc file.50515051- The allocator will try to get an area as large as possible50525052- within the given size. 50535053- </para>50545054-50555055- <para>50565056- The second argument (type) and the third argument (device pointer)50575057- are dependent on the bus.50585058- In the case of the ISA bus, pass <function>snd_dma_isa_data()</function>50595059- as the third argument with <constant>SNDRV_DMA_TYPE_DEV</constant> type.50605060- For the continuous buffer unrelated to the bus can be pre-allocated50615061- with <constant>SNDRV_DMA_TYPE_CONTINUOUS</constant> type and the50625062- <function>snd_dma_continuous_data(GFP_KERNEL)</function> device pointer,50635063- where <constant>GFP_KERNEL</constant> is the kernel allocation flag to50645064- use.50655065- For the PCI scatter-gather buffers, use50665066- <constant>SNDRV_DMA_TYPE_DEV_SG</constant> with50675067- <function>snd_dma_pci_data(pci)</function>50685068- (see the 50695069- <link linkend="buffer-and-memory-non-contiguous"><citetitle>Non-Contiguous Buffers50705070- </citetitle></link> section).50715071- </para>50725072-50735073- <para>50745074- Once the buffer is pre-allocated, you can use the50755075- allocator in the <structfield>hw_params</structfield> callback: 50765076-50775077- <informalexample>50785078- <programlisting>50795079-<![CDATA[50805080- snd_pcm_lib_malloc_pages(substream, size);50815081-]]>50825082- </programlisting>50835083- </informalexample>50845084-50855085- Note that you have to pre-allocate to use this function.50865086- </para>50875087- </section>50885088-50895089- <section id="buffer-and-memory-external-hardware">50905090- <title>External Hardware Buffers</title>50915091- <para>50925092- Some chips have their own hardware buffers and the DMA50935093- transfer from the host memory is not available. In such a case,50945094- you need to either 1) copy/set the audio data directly to the50955095- external hardware buffer, or 2) make an intermediate buffer and50965096- copy/set the data from it to the external hardware buffer in50975097- interrupts (or in tasklets, preferably).50985098- </para>50995099-51005100- <para>51015101- The first case works fine if the external hardware buffer is large51025102- enough. This method doesn't need any extra buffers and thus is51035103- more effective. You need to define the51045104- <structfield>copy</structfield> and51055105- <structfield>silence</structfield> callbacks for 51065106- the data transfer. However, there is a drawback: it cannot51075107- be mmapped. The examples are GUS's GF1 PCM or emu8000's51085108- wavetable PCM. 51095109- </para>51105110-51115111- <para>51125112- The second case allows for mmap on the buffer, although you have51135113- to handle an interrupt or a tasklet to transfer the data51145114- from the intermediate buffer to the hardware buffer. You can find an51155115- example in the vxpocket driver. 51165116- </para>51175117-51185118- <para>51195119- Another case is when the chip uses a PCI memory-map51205120- region for the buffer instead of the host memory. In this case,51215121- mmap is available only on certain architectures like the Intel one.51225122- In non-mmap mode, the data cannot be transferred as in the normal51235123- way. Thus you need to define the <structfield>copy</structfield> and51245124- <structfield>silence</structfield> callbacks as well, 51255125- as in the cases above. The examples are found in51265126- <filename>rme32.c</filename> and <filename>rme96.c</filename>. 51275127- </para>51285128-51295129- <para>51305130- The implementation of the <structfield>copy</structfield> and51315131- <structfield>silence</structfield> callbacks depends upon 51325132- whether the hardware supports interleaved or non-interleaved51335133- samples. The <structfield>copy</structfield> callback is51345134- defined like below, a bit 51355135- differently depending whether the direction is playback or51365136- capture: 51375137-51385138- <informalexample>51395139- <programlisting>51405140-<![CDATA[51415141- static int playback_copy(struct snd_pcm_substream *substream, int channel,51425142- snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);51435143- static int capture_copy(struct snd_pcm_substream *substream, int channel,51445144- snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);51455145-]]>51465146- </programlisting>51475147- </informalexample>51485148- </para>51495149-51505150- <para>51515151- In the case of interleaved samples, the second argument51525152- (<parameter>channel</parameter>) is not used. The third argument51535153- (<parameter>pos</parameter>) points the 51545154- current position offset in frames. 51555155- </para>51565156-51575157- <para>51585158- The meaning of the fourth argument is different between51595159- playback and capture. For playback, it holds the source data51605160- pointer, and for capture, it's the destination data pointer. 51615161- </para>51625162-51635163- <para>51645164- The last argument is the number of frames to be copied.51655165- </para>51665166-51675167- <para>51685168- What you have to do in this callback is again different51695169- between playback and capture directions. In the51705170- playback case, you copy the given amount of data51715171- (<parameter>count</parameter>) at the specified pointer51725172- (<parameter>src</parameter>) to the specified offset51735173- (<parameter>pos</parameter>) on the hardware buffer. When51745174- coded like memcpy-like way, the copy would be like: 51755175-51765176- <informalexample>51775177- <programlisting>51785178-<![CDATA[51795179- my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,51805180- frames_to_bytes(runtime, count));51815181-]]>51825182- </programlisting>51835183- </informalexample>51845184- </para>51855185-51865186- <para>51875187- For the capture direction, you copy the given amount of51885188- data (<parameter>count</parameter>) at the specified offset51895189- (<parameter>pos</parameter>) on the hardware buffer to the51905190- specified pointer (<parameter>dst</parameter>). 51915191-51925192- <informalexample>51935193- <programlisting>51945194-<![CDATA[51955195- my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),51965196- frames_to_bytes(runtime, count));51975197-]]>51985198- </programlisting>51995199- </informalexample>52005200-52015201- Note that both the position and the amount of data are given52025202- in frames. 52035203- </para>52045204-52055205- <para>52065206- In the case of non-interleaved samples, the implementation52075207- will be a bit more complicated. 52085208- </para>52095209-52105210- <para>52115211- You need to check the channel argument, and if it's -1, copy52125212- the whole channels. Otherwise, you have to copy only the52135213- specified channel. Please check52145214- <filename>isa/gus/gus_pcm.c</filename> as an example. 52155215- </para>52165216-52175217- <para>52185218- The <structfield>silence</structfield> callback is also52195219- implemented in a similar way. 52205220-52215221- <informalexample>52225222- <programlisting>52235223-<![CDATA[52245224- static int silence(struct snd_pcm_substream *substream, int channel,52255225- snd_pcm_uframes_t pos, snd_pcm_uframes_t count);52265226-]]>52275227- </programlisting>52285228- </informalexample>52295229- </para>52305230-52315231- <para>52325232- The meanings of arguments are the same as in the52335233- <structfield>copy</structfield> 52345234- callback, although there is no <parameter>src/dst</parameter>52355235- argument. In the case of interleaved samples, the channel52365236- argument has no meaning, as well as on52375237- <structfield>copy</structfield> callback. 52385238- </para>52395239-52405240- <para>52415241- The role of <structfield>silence</structfield> callback is to52425242- set the given amount 52435243- (<parameter>count</parameter>) of silence data at the52445244- specified offset (<parameter>pos</parameter>) on the hardware52455245- buffer. Suppose that the data format is signed (that is, the52465246- silent-data is 0), and the implementation using a memset-like52475247- function would be like: 52485248-52495249- <informalexample>52505250- <programlisting>52515251-<![CDATA[52525252- my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,52535253- frames_to_bytes(runtime, count));52545254-]]>52555255- </programlisting>52565256- </informalexample>52575257- </para>52585258-52595259- <para>52605260- In the case of non-interleaved samples, again, the52615261- implementation becomes a bit more complicated. See, for example,52625262- <filename>isa/gus/gus_pcm.c</filename>. 52635263- </para>52645264- </section>52655265-52665266- <section id="buffer-and-memory-non-contiguous">52675267- <title>Non-Contiguous Buffers</title>52685268- <para>52695269- If your hardware supports the page table as in emu10k1 or the52705270- buffer descriptors as in via82xx, you can use the scatter-gather52715271- (SG) DMA. ALSA provides an interface for handling SG-buffers.52725272- The API is provided in <filename><sound/pcm.h></filename>. 52735273- </para>52745274-52755275- <para>52765276- For creating the SG-buffer handler, call52775277- <function>snd_pcm_lib_preallocate_pages()</function> or52785278- <function>snd_pcm_lib_preallocate_pages_for_all()</function>52795279- with <constant>SNDRV_DMA_TYPE_DEV_SG</constant>52805280- in the PCM constructor like other PCI pre-allocator.52815281- You need to pass <function>snd_dma_pci_data(pci)</function>,52825282- where pci is the struct <structname>pci_dev</structname> pointer52835283- of the chip as well.52845284- The <type>struct snd_sg_buf</type> instance is created as52855285- substream->dma_private. You can cast52865286- the pointer like: 52875287-52885288- <informalexample>52895289- <programlisting>52905290-<![CDATA[52915291- struct snd_sg_buf *sgbuf = (struct snd_sg_buf *)substream->dma_private;52925292-]]>52935293- </programlisting>52945294- </informalexample>52955295- </para>52965296-52975297- <para>52985298- Then call <function>snd_pcm_lib_malloc_pages()</function>52995299- in the <structfield>hw_params</structfield> callback53005300- as well as in the case of normal PCI buffer.53015301- The SG-buffer handler will allocate the non-contiguous kernel53025302- pages of the given size and map them onto the virtually contiguous53035303- memory. The virtual pointer is addressed in runtime->dma_area.53045304- The physical address (runtime->dma_addr) is set to zero,53055305- because the buffer is physically non-contiguous.53065306- The physical address table is set up in sgbuf->table.53075307- You can get the physical address at a certain offset via53085308- <function>snd_pcm_sgbuf_get_addr()</function>. 53095309- </para>53105310-53115311- <para>53125312- When a SG-handler is used, you need to set53135313- <function>snd_pcm_sgbuf_ops_page</function> as53145314- the <structfield>page</structfield> callback.53155315- (See <link linkend="pcm-interface-operators-page-callback">53165316- <citetitle>page callback section</citetitle></link>.)53175317- </para>53185318-53195319- <para>53205320- To release the data, call53215321- <function>snd_pcm_lib_free_pages()</function> in the53225322- <structfield>hw_free</structfield> callback as usual.53235323- </para>53245324- </section>53255325-53265326- <section id="buffer-and-memory-vmalloced">53275327- <title>Vmalloc'ed Buffers</title>53285328- <para>53295329- It's possible to use a buffer allocated via53305330- <function>vmalloc</function>, for example, for an intermediate53315331- buffer. Since the allocated pages are not contiguous, you need53325332- to set the <structfield>page</structfield> callback to obtain53335333- the physical address at every offset. 53345334- </para>53355335-53365336- <para>53375337- The implementation of <structfield>page</structfield> callback53385338- would be like this: 53395339-53405340- <informalexample>53415341- <programlisting>53425342-<![CDATA[53435343- #include <linux/vmalloc.h>53445344-53455345- /* get the physical page pointer on the given offset */53465346- static struct page *mychip_page(struct snd_pcm_substream *substream,53475347- unsigned long offset)53485348- {53495349- void *pageptr = substream->runtime->dma_area + offset;53505350- return vmalloc_to_page(pageptr);53515351- }53525352-]]>53535353- </programlisting>53545354- </informalexample>53555355- </para>53565356- </section>53575357-53585358- </chapter>53595359-53605360-53615361-<!-- ****************************************************** -->53625362-<!-- Proc Interface -->53635363-<!-- ****************************************************** -->53645364- <chapter id="proc-interface">53655365- <title>Proc Interface</title>53665366- <para>53675367- ALSA provides an easy interface for procfs. The proc files are53685368- very useful for debugging. I recommend you set up proc files if53695369- you write a driver and want to get a running status or register53705370- dumps. The API is found in53715371- <filename><sound/info.h></filename>. 53725372- </para>53735373-53745374- <para>53755375- To create a proc file, call53765376- <function>snd_card_proc_new()</function>. 53775377-53785378- <informalexample>53795379- <programlisting>53805380-<![CDATA[53815381- struct snd_info_entry *entry;53825382- int err = snd_card_proc_new(card, "my-file", &entry);53835383-]]>53845384- </programlisting>53855385- </informalexample>53865386-53875387- where the second argument specifies the name of the proc file to be53885388- created. The above example will create a file53895389- <filename>my-file</filename> under the card directory,53905390- e.g. <filename>/proc/asound/card0/my-file</filename>. 53915391- </para>53925392-53935393- <para>53945394- Like other components, the proc entry created via53955395- <function>snd_card_proc_new()</function> will be registered and53965396- released automatically in the card registration and release53975397- functions.53985398- </para>53995399-54005400- <para>54015401- When the creation is successful, the function stores a new54025402- instance in the pointer given in the third argument.54035403- It is initialized as a text proc file for read only. To use54045404- this proc file as a read-only text file as it is, set the read54055405- callback with a private data via 54065406- <function>snd_info_set_text_ops()</function>.54075407-54085408- <informalexample>54095409- <programlisting>54105410-<![CDATA[54115411- snd_info_set_text_ops(entry, chip, my_proc_read);54125412-]]>54135413- </programlisting>54145414- </informalexample>54155415-54165416- where the second argument (<parameter>chip</parameter>) is the54175417- private data to be used in the callbacks. The third parameter54185418- specifies the read buffer size and the fourth54195419- (<parameter>my_proc_read</parameter>) is the callback function, which54205420- is defined like54215421-54225422- <informalexample>54235423- <programlisting>54245424-<![CDATA[54255425- static void my_proc_read(struct snd_info_entry *entry,54265426- struct snd_info_buffer *buffer);54275427-]]>54285428- </programlisting>54295429- </informalexample>54305430-54315431- </para>54325432-54335433- <para>54345434- In the read callback, use <function>snd_iprintf()</function> for54355435- output strings, which works just like normal54365436- <function>printf()</function>. For example,54375437-54385438- <informalexample>54395439- <programlisting>54405440-<![CDATA[54415441- static void my_proc_read(struct snd_info_entry *entry,54425442- struct snd_info_buffer *buffer)54435443- {54445444- struct my_chip *chip = entry->private_data;54455445-54465446- snd_iprintf(buffer, "This is my chip!\n");54475447- snd_iprintf(buffer, "Port = %ld\n", chip->port);54485448- }54495449-]]>54505450- </programlisting>54515451- </informalexample>54525452- </para>54535453-54545454- <para>54555455- The file permissions can be changed afterwards. As default, it's54565456- set as read only for all users. If you want to add write54575457- permission for the user (root as default), do as follows:54585458-54595459- <informalexample>54605460- <programlisting>54615461-<![CDATA[54625462- entry->mode = S_IFREG | S_IRUGO | S_IWUSR;54635463-]]>54645464- </programlisting>54655465- </informalexample>54665466-54675467- and set the write buffer size and the callback54685468-54695469- <informalexample>54705470- <programlisting>54715471-<![CDATA[54725472- entry->c.text.write = my_proc_write;54735473-]]>54745474- </programlisting>54755475- </informalexample>54765476- </para>54775477-54785478- <para>54795479- For the write callback, you can use54805480- <function>snd_info_get_line()</function> to get a text line, and54815481- <function>snd_info_get_str()</function> to retrieve a string from54825482- the line. Some examples are found in54835483- <filename>core/oss/mixer_oss.c</filename>, core/oss/and54845484- <filename>pcm_oss.c</filename>. 54855485- </para>54865486-54875487- <para>54885488- For a raw-data proc-file, set the attributes as follows:54895489-54905490- <informalexample>54915491- <programlisting>54925492-<![CDATA[54935493- static struct snd_info_entry_ops my_file_io_ops = {54945494- .read = my_file_io_read,54955495- };54965496-54975497- entry->content = SNDRV_INFO_CONTENT_DATA;54985498- entry->private_data = chip;54995499- entry->c.ops = &my_file_io_ops;55005500- entry->size = 4096;55015501- entry->mode = S_IFREG | S_IRUGO;55025502-]]>55035503- </programlisting>55045504- </informalexample>55055505-55065506- For the raw data, <structfield>size</structfield> field must be55075507- set properly. This specifies the maximum size of the proc file access.55085508- </para>55095509-55105510- <para>55115511- The read/write callbacks of raw mode are more direct than the text mode.55125512- You need to use a low-level I/O functions such as55135513- <function>copy_from/to_user()</function> to transfer the55145514- data.55155515-55165516- <informalexample>55175517- <programlisting>55185518-<![CDATA[55195519- static ssize_t my_file_io_read(struct snd_info_entry *entry,55205520- void *file_private_data,55215521- struct file *file,55225522- char *buf,55235523- size_t count,55245524- loff_t pos)55255525- {55265526- if (copy_to_user(buf, local_data + pos, count))55275527- return -EFAULT;55285528- return count;55295529- }55305530-]]>55315531- </programlisting>55325532- </informalexample>55335533-55345534- If the size of the info entry has been set up properly,55355535- <structfield>count</structfield> and <structfield>pos</structfield> are55365536- guaranteed to fit within 0 and the given size.55375537- You don't have to check the range in the callbacks unless any55385538- other condition is required.55395539-55405540- </para>55415541-55425542- </chapter>55435543-55445544-55455545-<!-- ****************************************************** -->55465546-<!-- Power Management -->55475547-<!-- ****************************************************** -->55485548- <chapter id="power-management">55495549- <title>Power Management</title>55505550- <para>55515551- If the chip is supposed to work with suspend/resume55525552- functions, you need to add power-management code to the55535553- driver. The additional code for power-management should be55545554- <function>ifdef</function>'ed with55555555- <constant>CONFIG_PM</constant>. 55565556- </para>55575557-55585558- <para>55595559- If the driver <emphasis>fully</emphasis> supports suspend/resume55605560- that is, the device can be55615561- properly resumed to its state when suspend was called,55625562- you can set the <constant>SNDRV_PCM_INFO_RESUME</constant> flag55635563- in the pcm info field. Usually, this is possible when the55645564- registers of the chip can be safely saved and restored to55655565- RAM. If this is set, the trigger callback is called with55665566- <constant>SNDRV_PCM_TRIGGER_RESUME</constant> after the resume55675567- callback completes. 55685568- </para>55695569-55705570- <para>55715571- Even if the driver doesn't support PM fully but 55725572- partial suspend/resume is still possible, it's still worthy to55735573- implement suspend/resume callbacks. In such a case, applications55745574- would reset the status by calling55755575- <function>snd_pcm_prepare()</function> and restart the stream55765576- appropriately. Hence, you can define suspend/resume callbacks55775577- below but don't set <constant>SNDRV_PCM_INFO_RESUME</constant>55785578- info flag to the PCM.55795579- </para>55805580-55815581- <para>55825582- Note that the trigger with SUSPEND can always be called when55835583- <function>snd_pcm_suspend_all</function> is called,55845584- regardless of the <constant>SNDRV_PCM_INFO_RESUME</constant> flag.55855585- The <constant>RESUME</constant> flag affects only the behavior55865586- of <function>snd_pcm_resume()</function>.55875587- (Thus, in theory,55885588- <constant>SNDRV_PCM_TRIGGER_RESUME</constant> isn't needed55895589- to be handled in the trigger callback when no55905590- <constant>SNDRV_PCM_INFO_RESUME</constant> flag is set. But,55915591- it's better to keep it for compatibility reasons.)55925592- </para>55935593- <para>55945594- In the earlier version of ALSA drivers, a common55955595- power-management layer was provided, but it has been removed.55965596- The driver needs to define the suspend/resume hooks according to55975597- the bus the device is connected to. In the case of PCI drivers, the55985598- callbacks look like below:55995599-56005600- <informalexample>56015601- <programlisting>56025602-<![CDATA[56035603- #ifdef CONFIG_PM56045604- static int snd_my_suspend(struct pci_dev *pci, pm_message_t state)56055605- {56065606- .... /* do things for suspend */56075607- return 0;56085608- }56095609- static int snd_my_resume(struct pci_dev *pci)56105610- {56115611- .... /* do things for suspend */56125612- return 0;56135613- }56145614- #endif56155615-]]>56165616- </programlisting>56175617- </informalexample>56185618- </para>56195619-56205620- <para>56215621- The scheme of the real suspend job is as follows.56225622-56235623- <orderedlist>56245624- <listitem><para>Retrieve the card and the chip data.</para></listitem>56255625- <listitem><para>Call <function>snd_power_change_state()</function> with56265626- <constant>SNDRV_CTL_POWER_D3hot</constant> to change the56275627- power status.</para></listitem>56285628- <listitem><para>Call <function>snd_pcm_suspend_all()</function> to suspend the running PCM streams.</para></listitem>56295629- <listitem><para>If AC97 codecs are used, call56305630- <function>snd_ac97_suspend()</function> for each codec.</para></listitem>56315631- <listitem><para>Save the register values if necessary.</para></listitem>56325632- <listitem><para>Stop the hardware if necessary.</para></listitem>56335633- <listitem><para>Disable the PCI device by calling56345634- <function>pci_disable_device()</function>. Then, call56355635- <function>pci_save_state()</function> at last.</para></listitem>56365636- </orderedlist>56375637- </para>56385638-56395639- <para>56405640- A typical code would be like:56415641-56425642- <informalexample>56435643- <programlisting>56445644-<![CDATA[56455645- static int mychip_suspend(struct pci_dev *pci, pm_message_t state)56465646- {56475647- /* (1) */56485648- struct snd_card *card = pci_get_drvdata(pci);56495649- struct mychip *chip = card->private_data;56505650- /* (2) */56515651- snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);56525652- /* (3) */56535653- snd_pcm_suspend_all(chip->pcm);56545654- /* (4) */56555655- snd_ac97_suspend(chip->ac97);56565656- /* (5) */56575657- snd_mychip_save_registers(chip);56585658- /* (6) */56595659- snd_mychip_stop_hardware(chip);56605660- /* (7) */56615661- pci_disable_device(pci);56625662- pci_save_state(pci);56635663- return 0;56645664- }56655665-]]>56665666- </programlisting>56675667- </informalexample>56685668- </para>56695669-56705670- <para>56715671- The scheme of the real resume job is as follows.56725672-56735673- <orderedlist>56745674- <listitem><para>Retrieve the card and the chip data.</para></listitem>56755675- <listitem><para>Set up PCI. First, call <function>pci_restore_state()</function>.56765676- Then enable the pci device again by calling <function>pci_enable_device()</function>.56775677- Call <function>pci_set_master()</function> if necessary, too.</para></listitem>56785678- <listitem><para>Re-initialize the chip.</para></listitem>56795679- <listitem><para>Restore the saved registers if necessary.</para></listitem>56805680- <listitem><para>Resume the mixer, e.g. calling56815681- <function>snd_ac97_resume()</function>.</para></listitem>56825682- <listitem><para>Restart the hardware (if any).</para></listitem>56835683- <listitem><para>Call <function>snd_power_change_state()</function> with56845684- <constant>SNDRV_CTL_POWER_D0</constant> to notify the processes.</para></listitem>56855685- </orderedlist>56865686- </para>56875687-56885688- <para>56895689- A typical code would be like:56905690-56915691- <informalexample>56925692- <programlisting>56935693-<![CDATA[56945694- static int mychip_resume(struct pci_dev *pci)56955695- {56965696- /* (1) */56975697- struct snd_card *card = pci_get_drvdata(pci);56985698- struct mychip *chip = card->private_data;56995699- /* (2) */57005700- pci_restore_state(pci);57015701- pci_enable_device(pci);57025702- pci_set_master(pci);57035703- /* (3) */57045704- snd_mychip_reinit_chip(chip);57055705- /* (4) */57065706- snd_mychip_restore_registers(chip);57075707- /* (5) */57085708- snd_ac97_resume(chip->ac97);57095709- /* (6) */57105710- snd_mychip_restart_chip(chip);57115711- /* (7) */57125712- snd_power_change_state(card, SNDRV_CTL_POWER_D0);57135713- return 0;57145714- }57155715-]]>57165716- </programlisting>57175717- </informalexample>57185718- </para>57195719-57205720- <para>57215721- As shown in the above, it's better to save registers after57225722- suspending the PCM operations via57235723- <function>snd_pcm_suspend_all()</function> or57245724- <function>snd_pcm_suspend()</function>. It means that the PCM57255725- streams are already stopped when the register snapshot is57265726- taken. But, remember that you don't have to restart the PCM57275727- stream in the resume callback. It'll be restarted via 57285728- trigger call with <constant>SNDRV_PCM_TRIGGER_RESUME</constant>57295729- when necessary.57305730- </para>57315731-57325732- <para>57335733- OK, we have all callbacks now. Let's set them up. In the57345734- initialization of the card, make sure that you can get the chip57355735- data from the card instance, typically via57365736- <structfield>private_data</structfield> field, in case you57375737- created the chip data individually.57385738-57395739- <informalexample>57405740- <programlisting>57415741-<![CDATA[57425742- static int snd_mychip_probe(struct pci_dev *pci,57435743- const struct pci_device_id *pci_id)57445744- {57455745- ....57465746- struct snd_card *card;57475747- struct mychip *chip;57485748- int err;57495749- ....57505750- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,57515751- 0, &card);57525752- ....57535753- chip = kzalloc(sizeof(*chip), GFP_KERNEL);57545754- ....57555755- card->private_data = chip;57565756- ....57575757- }57585758-]]>57595759- </programlisting>57605760- </informalexample>57615761-57625762- When you created the chip data with57635763- <function>snd_card_new()</function>, it's anyway accessible57645764- via <structfield>private_data</structfield> field.57655765-57665766- <informalexample>57675767- <programlisting>57685768-<![CDATA[57695769- static int snd_mychip_probe(struct pci_dev *pci,57705770- const struct pci_device_id *pci_id)57715771- {57725772- ....57735773- struct snd_card *card;57745774- struct mychip *chip;57755775- int err;57765776- ....57775777- err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,57785778- sizeof(struct mychip), &card);57795779- ....57805780- chip = card->private_data;57815781- ....57825782- }57835783-]]>57845784- </programlisting>57855785- </informalexample>57865786-57875787- </para>57885788-57895789- <para>57905790- If you need a space to save the registers, allocate the57915791- buffer for it here, too, since it would be fatal57925792- if you cannot allocate a memory in the suspend phase.57935793- The allocated buffer should be released in the corresponding57945794- destructor.57955795- </para>57965796-57975797- <para>57985798- And next, set suspend/resume callbacks to the pci_driver.57995799-58005800- <informalexample>58015801- <programlisting>58025802-<![CDATA[58035803- static struct pci_driver driver = {58045804- .name = KBUILD_MODNAME,58055805- .id_table = snd_my_ids,58065806- .probe = snd_my_probe,58075807- .remove = snd_my_remove,58085808- #ifdef CONFIG_PM58095809- .suspend = snd_my_suspend,58105810- .resume = snd_my_resume,58115811- #endif58125812- };58135813-]]>58145814- </programlisting>58155815- </informalexample>58165816- </para>58175817-58185818- </chapter>58195819-58205820-58215821-<!-- ****************************************************** -->58225822-<!-- Module Parameters -->58235823-<!-- ****************************************************** -->58245824- <chapter id="module-parameters">58255825- <title>Module Parameters</title>58265826- <para>58275827- There are standard module options for ALSA. At least, each58285828- module should have the <parameter>index</parameter>,58295829- <parameter>id</parameter> and <parameter>enable</parameter>58305830- options. 58315831- </para>58325832-58335833- <para>58345834- If the module supports multiple cards (usually up to58355835- 8 = <constant>SNDRV_CARDS</constant> cards), they should be58365836- arrays. The default initial values are defined already as58375837- constants for easier programming:58385838-58395839- <informalexample>58405840- <programlisting>58415841-<![CDATA[58425842- static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;58435843- static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;58445844- static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;58455845-]]>58465846- </programlisting>58475847- </informalexample>58485848- </para>58495849-58505850- <para>58515851- If the module supports only a single card, they could be single58525852- variables, instead. <parameter>enable</parameter> option is not58535853- always necessary in this case, but it would be better to have a58545854- dummy option for compatibility.58555855- </para>58565856-58575857- <para>58585858- The module parameters must be declared with the standard58595859- <function>module_param()()</function>,58605860- <function>module_param_array()()</function> and58615861- <function>MODULE_PARM_DESC()</function> macros.58625862- </para>58635863-58645864- <para>58655865- The typical coding would be like below:58665866-58675867- <informalexample>58685868- <programlisting>58695869-<![CDATA[58705870- #define CARD_NAME "My Chip"58715871-58725872- module_param_array(index, int, NULL, 0444);58735873- MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");58745874- module_param_array(id, charp, NULL, 0444);58755875- MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");58765876- module_param_array(enable, bool, NULL, 0444);58775877- MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");58785878-]]>58795879- </programlisting>58805880- </informalexample>58815881- </para>58825882-58835883- <para>58845884- Also, don't forget to define the module description, classes,58855885- license and devices. Especially, the recent modprobe requires to58865886- define the module license as GPL, etc., otherwise the system is58875887- shown as <quote>tainted</quote>. 58885888-58895889- <informalexample>58905890- <programlisting>58915891-<![CDATA[58925892- MODULE_DESCRIPTION("My Chip");58935893- MODULE_LICENSE("GPL");58945894- MODULE_SUPPORTED_DEVICE("{{Vendor,My Chip Name}}");58955895-]]>58965896- </programlisting>58975897- </informalexample>58985898- </para>58995899-59005900- </chapter>59015901-59025902-59035903-<!-- ****************************************************** -->59045904-<!-- How To Put Your Driver -->59055905-<!-- ****************************************************** -->59065906- <chapter id="how-to-put-your-driver">59075907- <title>How To Put Your Driver Into ALSA Tree</title>59085908- <section>59095909- <title>General</title>59105910- <para>59115911- So far, you've learned how to write the driver codes.59125912- And you might have a question now: how to put my own59135913- driver into the ALSA driver tree?59145914- Here (finally :) the standard procedure is described briefly.59155915- </para>59165916-59175917- <para>59185918- Suppose that you create a new PCI driver for the card59195919- <quote>xyz</quote>. The card module name would be59205920- snd-xyz. The new driver is usually put into the alsa-driver59215921- tree, <filename>alsa-driver/pci</filename> directory in59225922- the case of PCI cards.59235923- Then the driver is evaluated, audited and tested59245924- by developers and users. After a certain time, the driver59255925- will go to the alsa-kernel tree (to the corresponding directory,59265926- such as <filename>alsa-kernel/pci</filename>) and eventually59275927- will be integrated into the Linux 2.6 tree (the directory would be59285928- <filename>linux/sound/pci</filename>).59295929- </para>59305930-59315931- <para>59325932- In the following sections, the driver code is supposed59335933- to be put into alsa-driver tree. The two cases are covered:59345934- a driver consisting of a single source file and one consisting59355935- of several source files.59365936- </para>59375937- </section>59385938-59395939- <section>59405940- <title>Driver with A Single Source File</title>59415941- <para>59425942- <orderedlist>59435943- <listitem>59445944- <para>59455945- Modify alsa-driver/pci/Makefile59465946- </para>59475947-59485948- <para>59495949- Suppose you have a file xyz.c. Add the following59505950- two lines59515951- <informalexample>59525952- <programlisting>59535953-<![CDATA[59545954- snd-xyz-objs := xyz.o59555955- obj-$(CONFIG_SND_XYZ) += snd-xyz.o59565956-]]>59575957- </programlisting>59585958- </informalexample>59595959- </para>59605960- </listitem>59615961-59625962- <listitem>59635963- <para>59645964- Create the Kconfig entry59655965- </para>59665966-59675967- <para>59685968- Add the new entry of Kconfig for your xyz driver.59695969- <informalexample>59705970- <programlisting>59715971-<![CDATA[59725972- config SND_XYZ59735973- tristate "Foobar XYZ"59745974- depends on SND59755975- select SND_PCM59765976- help59775977- Say Y here to include support for Foobar XYZ soundcard.59785978-59795979- To compile this driver as a module, choose M here: the module59805980- will be called snd-xyz.59815981-]]>59825982- </programlisting>59835983- </informalexample>59845984-59855985- the line, select SND_PCM, specifies that the driver xyz supports59865986- PCM. In addition to SND_PCM, the following components are59875987- supported for select command:59885988- SND_RAWMIDI, SND_TIMER, SND_HWDEP, SND_MPU401_UART,59895989- SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB, SND_AC97_CODEC.59905990- Add the select command for each supported component.59915991- </para>59925992-59935993- <para>59945994- Note that some selections imply the lowlevel selections.59955995- For example, PCM includes TIMER, MPU401_UART includes RAWMIDI,59965996- AC97_CODEC includes PCM, and OPL3_LIB includes HWDEP.59975997- You don't need to give the lowlevel selections again.59985998- </para>59995999-60006000- <para>60016001- For the details of Kconfig script, refer to the kbuild60026002- documentation.60036003- </para>60046004-60056005- </listitem>60066006-60076007- <listitem>60086008- <para>60096009- Run cvscompile script to re-generate the configure script and60106010- build the whole stuff again.60116011- </para>60126012- </listitem>60136013- </orderedlist>60146014- </para>60156015- </section>60166016-60176017- <section>60186018- <title>Drivers with Several Source Files</title>60196019- <para>60206020- Suppose that the driver snd-xyz have several source files.60216021- They are located in the new subdirectory,60226022- pci/xyz.60236023-60246024- <orderedlist>60256025- <listitem>60266026- <para>60276027- Add a new directory (<filename>xyz</filename>) in60286028- <filename>alsa-driver/pci/Makefile</filename> as below60296029-60306030- <informalexample>60316031- <programlisting>60326032-<![CDATA[60336033- obj-$(CONFIG_SND) += xyz/60346034-]]>60356035- </programlisting>60366036- </informalexample>60376037- </para>60386038- </listitem>60396039-60406040- <listitem>60416041- <para>60426042- Under the directory <filename>xyz</filename>, create a Makefile60436043-60446044- <example>60456045- <title>Sample Makefile for a driver xyz</title>60466046- <programlisting>60476047-<![CDATA[60486048- ifndef SND_TOPDIR60496049- SND_TOPDIR=../..60506050- endif60516051-60526052- include $(SND_TOPDIR)/toplevel.config60536053- include $(SND_TOPDIR)/Makefile.conf60546054-60556055- snd-xyz-objs := xyz.o abc.o def.o60566056-60576057- obj-$(CONFIG_SND_XYZ) += snd-xyz.o60586058-60596059- include $(SND_TOPDIR)/Rules.make60606060-]]>60616061- </programlisting>60626062- </example>60636063- </para>60646064- </listitem>60656065-60666066- <listitem>60676067- <para>60686068- Create the Kconfig entry60696069- </para>60706070-60716071- <para>60726072- This procedure is as same as in the last section.60736073- </para>60746074- </listitem>60756075-60766076- <listitem>60776077- <para>60786078- Run cvscompile script to re-generate the configure script and60796079- build the whole stuff again.60806080- </para>60816081- </listitem>60826082- </orderedlist>60836083- </para>60846084- </section>60856085-60866086- </chapter>60876087-60886088-<!-- ****************************************************** -->60896089-<!-- Useful Functions -->60906090-<!-- ****************************************************** -->60916091- <chapter id="useful-functions">60926092- <title>Useful Functions</title>60936093-60946094- <section id="useful-functions-snd-printk">60956095- <title><function>snd_printk()</function> and friends</title>60966096- <para>60976097- ALSA provides a verbose version of the60986098- <function>printk()</function> function. If a kernel config60996099- <constant>CONFIG_SND_VERBOSE_PRINTK</constant> is set, this61006100- function prints the given message together with the file name61016101- and the line of the caller. The <constant>KERN_XXX</constant>61026102- prefix is processed as 61036103- well as the original <function>printk()</function> does, so it's61046104- recommended to add this prefix, e.g. 61056105-61066106- <informalexample>61076107- <programlisting>61086108-<![CDATA[61096109- snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\n");61106110-]]>61116111- </programlisting>61126112- </informalexample>61136113- </para>61146114-61156115- <para>61166116- There are also <function>printk()</function>'s for61176117- debugging. <function>snd_printd()</function> can be used for61186118- general debugging purposes. If61196119- <constant>CONFIG_SND_DEBUG</constant> is set, this function is61206120- compiled, and works just like61216121- <function>snd_printk()</function>. If the ALSA is compiled61226122- without the debugging flag, it's ignored. 61236123- </para>61246124-61256125- <para>61266126- <function>snd_printdd()</function> is compiled in only when61276127- <constant>CONFIG_SND_DEBUG_VERBOSE</constant> is set. Please note61286128- that <constant>CONFIG_SND_DEBUG_VERBOSE</constant> is not set as default61296129- even if you configure the alsa-driver with61306130- <option>--with-debug=full</option> option. You need to give61316131- explicitly <option>--with-debug=detect</option> option instead. 61326132- </para>61336133- </section>61346134-61356135- <section id="useful-functions-snd-bug">61366136- <title><function>snd_BUG()</function></title>61376137- <para>61386138- It shows the <computeroutput>BUG?</computeroutput> message and61396139- stack trace as well as <function>snd_BUG_ON</function> at the point.61406140- It's useful to show that a fatal error happens there. 61416141- </para>61426142- <para>61436143- When no debug flag is set, this macro is ignored. 61446144- </para>61456145- </section>61466146-61476147- <section id="useful-functions-snd-bug-on">61486148- <title><function>snd_BUG_ON()</function></title>61496149- <para>61506150- <function>snd_BUG_ON()</function> macro is similar with61516151- <function>WARN_ON()</function> macro. For example, 61526152-61536153- <informalexample>61546154- <programlisting>61556155-<![CDATA[61566156- snd_BUG_ON(!pointer);61576157-]]>61586158- </programlisting>61596159- </informalexample>61606160-61616161- or it can be used as the condition,61626162- <informalexample>61636163- <programlisting>61646164-<![CDATA[61656165- if (snd_BUG_ON(non_zero_is_bug))61666166- return -EINVAL;61676167-]]>61686168- </programlisting>61696169- </informalexample>61706170-61716171- </para>61726172-61736173- <para>61746174- The macro takes an conditional expression to evaluate.61756175- When <constant>CONFIG_SND_DEBUG</constant>, is set, if the61766176- expression is non-zero, it shows the warning message such as61776177- <computeroutput>BUG? (xxx)</computeroutput>61786178- normally followed by stack trace.61796179-61806180- In both cases it returns the evaluated value.61816181- </para>61826182-61836183- </section>61846184-61856185- </chapter>61866186-61876187-61886188-<!-- ****************************************************** -->61896189-<!-- Acknowledgments -->61906190-<!-- ****************************************************** -->61916191- <chapter id="acknowledgments">61926192- <title>Acknowledgments</title>61936193- <para>61946194- I would like to thank Phil Kerr for his help for improvement and61956195- corrections of this document. 61966196- </para>61976197- <para>61986198- Kevin Conder reformatted the original plain-text to the61996199- DocBook format.62006200- </para>62016201- <para>62026202- Giuliano Pochini corrected typos and contributed the example codes62036203- in the hardware constraints section.62046204- </para>62056205- </chapter>62066206-</book>
···11+======================22+Writing an ALSA Driver33+======================44+55+:Author: Takashi Iwai <tiwai@suse.de>66+:Date: Oct 15, 200777+:Edition: 0.3.788+99+Preface1010+=======1111+1212+This document describes how to write an `ALSA (Advanced Linux Sound1313+Architecture) <http://www.alsa-project.org/>`__ driver. The document1414+focuses mainly on PCI soundcards. In the case of other device types, the1515+API might be different, too. However, at least the ALSA kernel API is1616+consistent, and therefore it would be still a bit help for writing them.1717+1818+This document targets people who already have enough C language skills1919+and have basic linux kernel programming knowledge. This document doesn't2020+explain the general topic of linux kernel coding and doesn't cover2121+low-level driver implementation details. It only describes the standard2222+way to write a PCI sound driver on ALSA.2323+2424+If you are already familiar with the older ALSA ver.0.5.x API, you can2525+check the drivers such as ``sound/pci/es1938.c`` or2626+``sound/pci/maestro3.c`` which have also almost the same code-base in2727+the ALSA 0.5.x tree, so you can compare the differences.2828+2929+This document is still a draft version. Any feedback and corrections,3030+please!!3131+3232+File Tree Structure3333+===================3434+3535+General3636+-------3737+3838+The ALSA drivers are provided in two ways.3939+4040+One is the trees provided as a tarball or via cvs from the ALSA's ftp4141+site, and another is the 2.6 (or later) Linux kernel tree. To4242+synchronize both, the ALSA driver tree is split into two different4343+trees: alsa-kernel and alsa-driver. The former contains purely the4444+source code for the Linux 2.6 (or later) tree. This tree is designed4545+only for compilation on 2.6 or later environment. The latter,4646+alsa-driver, contains many subtle files for compiling ALSA drivers4747+outside of the Linux kernel tree, wrapper functions for older 2.2 and4848+2.4 kernels, to adapt the latest kernel API, and additional drivers4949+which are still in development or in tests. The drivers in alsa-driver5050+tree will be moved to alsa-kernel (and eventually to the 2.6 kernel5151+tree) when they are finished and confirmed to work fine.5252+5353+The file tree structure of ALSA driver is depicted below. Both5454+alsa-kernel and alsa-driver have almost the same file structure, except5555+for “core” directory. It's named as “acore” in alsa-driver tree.5656+5757+::5858+5959+ sound6060+ /core6161+ /oss6262+ /seq6363+ /oss6464+ /instr6565+ /ioctl326666+ /include6767+ /drivers6868+ /mpu4016969+ /opl37070+ /i2c7171+ /l37272+ /synth7373+ /emux7474+ /pci7575+ /(cards)7676+ /isa7777+ /(cards)7878+ /arm7979+ /ppc8080+ /sparc8181+ /usb8282+ /pcmcia /(cards)8383+ /oss8484+8585+8686+core directory8787+--------------8888+8989+This directory contains the middle layer which is the heart of ALSA9090+drivers. In this directory, the native ALSA modules are stored. The9191+sub-directories contain different modules and are dependent upon the9292+kernel config.9393+9494+core/oss9595+~~~~~~~~9696+9797+The codes for PCM and mixer OSS emulation modules are stored in this9898+directory. The rawmidi OSS emulation is included in the ALSA rawmidi9999+code since it's quite small. The sequencer code is stored in100100+``core/seq/oss`` directory (see `below <#core-seq-oss>`__).101101+102102+core/ioctl32103103+~~~~~~~~~~~~104104+105105+This directory contains the 32bit-ioctl wrappers for 64bit architectures106106+such like x86-64, ppc64 and sparc64. For 32bit and alpha architectures,107107+these are not compiled.108108+109109+core/seq110110+~~~~~~~~111111+112112+This directory and its sub-directories are for the ALSA sequencer. This113113+directory contains the sequencer core and primary sequencer modules such114114+like snd-seq-midi, snd-seq-virmidi, etc. They are compiled only when115115+``CONFIG_SND_SEQUENCER`` is set in the kernel config.116116+117117+core/seq/oss118118+~~~~~~~~~~~~119119+120120+This contains the OSS sequencer emulation codes.121121+122122+core/seq/instr123123+~~~~~~~~~~~~~~124124+125125+This directory contains the modules for the sequencer instrument layer.126126+127127+include directory128128+-----------------129129+130130+This is the place for the public header files of ALSA drivers, which are131131+to be exported to user-space, or included by several files at different132132+directories. Basically, the private header files should not be placed in133133+this directory, but you may still find files there, due to historical134134+reasons :)135135+136136+drivers directory137137+-----------------138138+139139+This directory contains code shared among different drivers on different140140+architectures. They are hence supposed not to be architecture-specific.141141+For example, the dummy pcm driver and the serial MIDI driver are found142142+in this directory. In the sub-directories, there is code for components143143+which are independent from bus and cpu architectures.144144+145145+drivers/mpu401146146+~~~~~~~~~~~~~~147147+148148+The MPU401 and MPU401-UART modules are stored here.149149+150150+drivers/opl3 and opl4151151+~~~~~~~~~~~~~~~~~~~~~152152+153153+The OPL3 and OPL4 FM-synth stuff is found here.154154+155155+i2c directory156156+-------------157157+158158+This contains the ALSA i2c components.159159+160160+Although there is a standard i2c layer on Linux, ALSA has its own i2c161161+code for some cards, because the soundcard needs only a simple operation162162+and the standard i2c API is too complicated for such a purpose.163163+164164+i2c/l3165165+~~~~~~166166+167167+This is a sub-directory for ARM L3 i2c.168168+169169+synth directory170170+---------------171171+172172+This contains the synth middle-level modules.173173+174174+So far, there is only Emu8000/Emu10k1 synth driver under the175175+``synth/emux`` sub-directory.176176+177177+pci directory178178+-------------179179+180180+This directory and its sub-directories hold the top-level card modules181181+for PCI soundcards and the code specific to the PCI BUS.182182+183183+The drivers compiled from a single file are stored directly in the pci184184+directory, while the drivers with several source files are stored on185185+their own sub-directory (e.g. emu10k1, ice1712).186186+187187+isa directory188188+-------------189189+190190+This directory and its sub-directories hold the top-level card modules191191+for ISA soundcards.192192+193193+arm, ppc, and sparc directories194194+-------------------------------195195+196196+They are used for top-level card modules which are specific to one of197197+these architectures.198198+199199+usb directory200200+-------------201201+202202+This directory contains the USB-audio driver. In the latest version, the203203+USB MIDI driver is integrated in the usb-audio driver.204204+205205+pcmcia directory206206+----------------207207+208208+The PCMCIA, especially PCCard drivers will go here. CardBus drivers will209209+be in the pci directory, because their API is identical to that of210210+standard PCI cards.211211+212212+oss directory213213+-------------214214+215215+The OSS/Lite source files are stored here in Linux 2.6 (or later) tree.216216+In the ALSA driver tarball, this directory is empty, of course :)217217+218218+Basic Flow for PCI Drivers219219+==========================220220+221221+Outline222222+-------223223+224224+The minimum flow for PCI soundcards is as follows:225225+226226+- define the PCI ID table (see the section `PCI Entries`_).227227+228228+- create ``probe`` callback.229229+230230+- create ``remove`` callback.231231+232232+- create a :c:type:`struct pci_driver <pci_driver>` structure233233+ containing the three pointers above.234234+235235+- create an ``init`` function just calling the236236+ :c:func:`pci_register_driver()` to register the pci_driver237237+ table defined above.238238+239239+- create an ``exit`` function to call the240240+ :c:func:`pci_unregister_driver()` function.241241+242242+Full Code Example243243+-----------------244244+245245+The code example is shown below. Some parts are kept unimplemented at246246+this moment but will be filled in the next sections. The numbers in the247247+comment lines of the :c:func:`snd_mychip_probe()` function refer248248+to details explained in the following section.249249+250250+::251251+252252+ #include <linux/init.h>253253+ #include <linux/pci.h>254254+ #include <linux/slab.h>255255+ #include <sound/core.h>256256+ #include <sound/initval.h>257257+258258+ /* module parameters (see "Module Parameters") */259259+ /* SNDRV_CARDS: maximum number of cards supported by this module */260260+ static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;261261+ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;262262+ static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;263263+264264+ /* definition of the chip-specific record */265265+ struct mychip {266266+ struct snd_card *card;267267+ /* the rest of the implementation will be in section268268+ * "PCI Resource Management"269269+ */270270+ };271271+272272+ /* chip-specific destructor273273+ * (see "PCI Resource Management")274274+ */275275+ static int snd_mychip_free(struct mychip *chip)276276+ {277277+ .... /* will be implemented later... */278278+ }279279+280280+ /* component-destructor281281+ * (see "Management of Cards and Components")282282+ */283283+ static int snd_mychip_dev_free(struct snd_device *device)284284+ {285285+ return snd_mychip_free(device->device_data);286286+ }287287+288288+ /* chip-specific constructor289289+ * (see "Management of Cards and Components")290290+ */291291+ static int snd_mychip_create(struct snd_card *card,292292+ struct pci_dev *pci,293293+ struct mychip **rchip)294294+ {295295+ struct mychip *chip;296296+ int err;297297+ static struct snd_device_ops ops = {298298+ .dev_free = snd_mychip_dev_free,299299+ };300300+301301+ *rchip = NULL;302302+303303+ /* check PCI availability here304304+ * (see "PCI Resource Management")305305+ */306306+ ....307307+308308+ /* allocate a chip-specific data with zero filled */309309+ chip = kzalloc(sizeof(*chip), GFP_KERNEL);310310+ if (chip == NULL)311311+ return -ENOMEM;312312+313313+ chip->card = card;314314+315315+ /* rest of initialization here; will be implemented316316+ * later, see "PCI Resource Management"317317+ */318318+ ....319319+320320+ err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);321321+ if (err < 0) {322322+ snd_mychip_free(chip);323323+ return err;324324+ }325325+326326+ *rchip = chip;327327+ return 0;328328+ }329329+330330+ /* constructor -- see "Driver Constructor" sub-section */331331+ static int snd_mychip_probe(struct pci_dev *pci,332332+ const struct pci_device_id *pci_id)333333+ {334334+ static int dev;335335+ struct snd_card *card;336336+ struct mychip *chip;337337+ int err;338338+339339+ /* (1) */340340+ if (dev >= SNDRV_CARDS)341341+ return -ENODEV;342342+ if (!enable[dev]) {343343+ dev++;344344+ return -ENOENT;345345+ }346346+347347+ /* (2) */348348+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,349349+ 0, &card);350350+ if (err < 0)351351+ return err;352352+353353+ /* (3) */354354+ err = snd_mychip_create(card, pci, &chip);355355+ if (err < 0) {356356+ snd_card_free(card);357357+ return err;358358+ }359359+360360+ /* (4) */361361+ strcpy(card->driver, "My Chip");362362+ strcpy(card->shortname, "My Own Chip 123");363363+ sprintf(card->longname, "%s at 0x%lx irq %i",364364+ card->shortname, chip->ioport, chip->irq);365365+366366+ /* (5) */367367+ .... /* implemented later */368368+369369+ /* (6) */370370+ err = snd_card_register(card);371371+ if (err < 0) {372372+ snd_card_free(card);373373+ return err;374374+ }375375+376376+ /* (7) */377377+ pci_set_drvdata(pci, card);378378+ dev++;379379+ return 0;380380+ }381381+382382+ /* destructor -- see the "Destructor" sub-section */383383+ static void snd_mychip_remove(struct pci_dev *pci)384384+ {385385+ snd_card_free(pci_get_drvdata(pci));386386+ pci_set_drvdata(pci, NULL);387387+ }388388+389389+390390+391391+Driver Constructor392392+------------------393393+394394+The real constructor of PCI drivers is the ``probe`` callback. The395395+``probe`` callback and other component-constructors which are called396396+from the ``probe`` callback cannot be used with the ``__init`` prefix397397+because any PCI device could be a hotplug device.398398+399399+In the ``probe`` callback, the following scheme is often used.400400+401401+1) Check and increment the device index.402402+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~403403+404404+::405405+406406+ static int dev;407407+ ....408408+ if (dev >= SNDRV_CARDS)409409+ return -ENODEV;410410+ if (!enable[dev]) {411411+ dev++;412412+ return -ENOENT;413413+ }414414+415415+416416+where ``enable[dev]`` is the module option.417417+418418+Each time the ``probe`` callback is called, check the availability of419419+the device. If not available, simply increment the device index and420420+returns. dev will be incremented also later (`step 7421421+<#set-the-pci-driver-data-and-return-zero>`__).422422+423423+2) Create a card instance424424+~~~~~~~~~~~~~~~~~~~~~~~~~425425+426426+::427427+428428+ struct snd_card *card;429429+ int err;430430+ ....431431+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,432432+ 0, &card);433433+434434+435435+The details will be explained in the section `Management of Cards and436436+Components`_.437437+438438+3) Create a main component439439+~~~~~~~~~~~~~~~~~~~~~~~~~~440440+441441+In this part, the PCI resources are allocated.442442+443443+::444444+445445+ struct mychip *chip;446446+ ....447447+ err = snd_mychip_create(card, pci, &chip);448448+ if (err < 0) {449449+ snd_card_free(card);450450+ return err;451451+ }452452+453453+The details will be explained in the section `PCI Resource454454+Management`_.455455+456456+4) Set the driver ID and name strings.457457+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~458458+459459+::460460+461461+ strcpy(card->driver, "My Chip");462462+ strcpy(card->shortname, "My Own Chip 123");463463+ sprintf(card->longname, "%s at 0x%lx irq %i",464464+ card->shortname, chip->ioport, chip->irq);465465+466466+The driver field holds the minimal ID string of the chip. This is used467467+by alsa-lib's configurator, so keep it simple but unique. Even the468468+same driver can have different driver IDs to distinguish the469469+functionality of each chip type.470470+471471+The shortname field is a string shown as more verbose name. The longname472472+field contains the information shown in ``/proc/asound/cards``.473473+474474+5) Create other components, such as mixer, MIDI, etc.475475+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~476476+477477+Here you define the basic components such as `PCM <#PCM-Interface>`__,478478+mixer (e.g. `AC97 <#API-for-AC97-Codec>`__), MIDI (e.g.479479+`MPU-401 <#MIDI-MPU401-UART-Interface>`__), and other interfaces.480480+Also, if you want a `proc file <#Proc-Interface>`__, define it here,481481+too.482482+483483+6) Register the card instance.484484+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~485485+486486+::487487+488488+ err = snd_card_register(card);489489+ if (err < 0) {490490+ snd_card_free(card);491491+ return err;492492+ }493493+494494+Will be explained in the section `Management of Cards and495495+Components`_, too.496496+497497+7) Set the PCI driver data and return zero.498498+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~499499+500500+::501501+502502+ pci_set_drvdata(pci, card);503503+ dev++;504504+ return 0;505505+506506+In the above, the card record is stored. This pointer is used in the507507+remove callback and power-management callbacks, too.508508+509509+Destructor510510+----------511511+512512+The destructor, remove callback, simply releases the card instance. Then513513+the ALSA middle layer will release all the attached components514514+automatically.515515+516516+It would be typically like the following:517517+518518+::519519+520520+ static void snd_mychip_remove(struct pci_dev *pci)521521+ {522522+ snd_card_free(pci_get_drvdata(pci));523523+ pci_set_drvdata(pci, NULL);524524+ }525525+526526+527527+The above code assumes that the card pointer is set to the PCI driver528528+data.529529+530530+Header Files531531+------------532532+533533+For the above example, at least the following include files are534534+necessary.535535+536536+::537537+538538+ #include <linux/init.h>539539+ #include <linux/pci.h>540540+ #include <linux/slab.h>541541+ #include <sound/core.h>542542+ #include <sound/initval.h>543543+544544+where the last one is necessary only when module options are defined545545+in the source file. If the code is split into several files, the files546546+without module options don't need them.547547+548548+In addition to these headers, you'll need ``<linux/interrupt.h>`` for549549+interrupt handling, and ``<asm/io.h>`` for I/O access. If you use the550550+:c:func:`mdelay()` or :c:func:`udelay()` functions, you'll need551551+to include ``<linux/delay.h>`` too.552552+553553+The ALSA interfaces like the PCM and control APIs are defined in other554554+``<sound/xxx.h>`` header files. They have to be included after555555+``<sound/core.h>``.556556+557557+Management of Cards and Components558558+==================================559559+560560+Card Instance561561+-------------562562+563563+For each soundcard, a “card” record must be allocated.564564+565565+A card record is the headquarters of the soundcard. It manages the whole566566+list of devices (components) on the soundcard, such as PCM, mixers,567567+MIDI, synthesizer, and so on. Also, the card record holds the ID and the568568+name strings of the card, manages the root of proc files, and controls569569+the power-management states and hotplug disconnections. The component570570+list on the card record is used to manage the correct release of571571+resources at destruction.572572+573573+As mentioned above, to create a card instance, call574574+:c:func:`snd_card_new()`.575575+576576+::577577+578578+ struct snd_card *card;579579+ int err;580580+ err = snd_card_new(&pci->dev, index, id, module, extra_size, &card);581581+582582+583583+The function takes six arguments: the parent device pointer, the584584+card-index number, the id string, the module pointer (usually585585+``THIS_MODULE``), the size of extra-data space, and the pointer to586586+return the card instance. The extra_size argument is used to allocate587587+card->private_data for the chip-specific data. Note that these data are588588+allocated by :c:func:`snd_card_new()`.589589+590590+The first argument, the pointer of struct :c:type:`struct device591591+<device>`, specifies the parent device. For PCI devices, typically592592+``&pci->`` is passed there.593593+594594+Components595595+----------596596+597597+After the card is created, you can attach the components (devices) to598598+the card instance. In an ALSA driver, a component is represented as a599599+:c:type:`struct snd_device <snd_device>` object. A component600600+can be a PCM instance, a control interface, a raw MIDI interface, etc.601601+Each such instance has one component entry.602602+603603+A component can be created via :c:func:`snd_device_new()`604604+function.605605+606606+::607607+608608+ snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);609609+610610+This takes the card pointer, the device-level (``SNDRV_DEV_XXX``), the611611+data pointer, and the callback pointers (``&ops``). The device-level612612+defines the type of components and the order of registration and613613+de-registration. For most components, the device-level is already614614+defined. For a user-defined component, you can use615615+``SNDRV_DEV_LOWLEVEL``.616616+617617+This function itself doesn't allocate the data space. The data must be618618+allocated manually beforehand, and its pointer is passed as the619619+argument. This pointer (``chip`` in the above example) is used as the620620+identifier for the instance.621621+622622+Each pre-defined ALSA component such as ac97 and pcm calls623623+:c:func:`snd_device_new()` inside its constructor. The destructor624624+for each component is defined in the callback pointers. Hence, you don't625625+need to take care of calling a destructor for such a component.626626+627627+If you wish to create your own component, you need to set the destructor628628+function to the dev_free callback in the ``ops``, so that it can be629629+released automatically via :c:func:`snd_card_free()`. The next630630+example will show an implementation of chip-specific data.631631+632632+Chip-Specific Data633633+------------------634634+635635+Chip-specific information, e.g. the I/O port address, its resource636636+pointer, or the irq number, is stored in the chip-specific record.637637+638638+::639639+640640+ struct mychip {641641+ ....642642+ };643643+644644+645645+In general, there are two ways of allocating the chip record.646646+647647+1. Allocating via :c:func:`snd_card_new()`.648648+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~649649+650650+As mentioned above, you can pass the extra-data-length to the 5th651651+argument of :c:func:`snd_card_new()`, i.e.652652+653653+::654654+655655+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,656656+ sizeof(struct mychip), &card);657657+658658+:c:type:`struct mychip <mychip>` is the type of the chip record.659659+660660+In return, the allocated record can be accessed as661661+662662+::663663+664664+ struct mychip *chip = card->private_data;665665+666666+With this method, you don't have to allocate twice. The record is667667+released together with the card instance.668668+669669+2. Allocating an extra device.670670+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~671671+672672+After allocating a card instance via :c:func:`snd_card_new()`673673+(with ``0`` on the 4th arg), call :c:func:`kzalloc()`.674674+675675+::676676+677677+ struct snd_card *card;678678+ struct mychip *chip;679679+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,680680+ 0, &card);681681+ .....682682+ chip = kzalloc(sizeof(*chip), GFP_KERNEL);683683+684684+The chip record should have the field to hold the card pointer at least,685685+686686+::687687+688688+ struct mychip {689689+ struct snd_card *card;690690+ ....691691+ };692692+693693+694694+Then, set the card pointer in the returned chip instance.695695+696696+::697697+698698+ chip->card = card;699699+700700+Next, initialize the fields, and register this chip record as a701701+low-level device with a specified ``ops``,702702+703703+::704704+705705+ static struct snd_device_ops ops = {706706+ .dev_free = snd_mychip_dev_free,707707+ };708708+ ....709709+ snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);710710+711711+:c:func:`snd_mychip_dev_free()` is the device-destructor712712+function, which will call the real destructor.713713+714714+::715715+716716+ static int snd_mychip_dev_free(struct snd_device *device)717717+ {718718+ return snd_mychip_free(device->device_data);719719+ }720720+721721+where :c:func:`snd_mychip_free()` is the real destructor.722722+723723+Registration and Release724724+------------------------725725+726726+After all components are assigned, register the card instance by calling727727+:c:func:`snd_card_register()`. Access to the device files is728728+enabled at this point. That is, before729729+:c:func:`snd_card_register()` is called, the components are safely730730+inaccessible from external side. If this call fails, exit the probe731731+function after releasing the card via :c:func:`snd_card_free()`.732732+733733+For releasing the card instance, you can call simply734734+:c:func:`snd_card_free()`. As mentioned earlier, all components735735+are released automatically by this call.736736+737737+For a device which allows hotplugging, you can use738738+:c:func:`snd_card_free_when_closed()`. This one will postpone739739+the destruction until all devices are closed.740740+741741+PCI Resource Management742742+=======================743743+744744+Full Code Example745745+-----------------746746+747747+In this section, we'll complete the chip-specific constructor,748748+destructor and PCI entries. Example code is shown first, below.749749+750750+::751751+752752+ struct mychip {753753+ struct snd_card *card;754754+ struct pci_dev *pci;755755+756756+ unsigned long port;757757+ int irq;758758+ };759759+760760+ static int snd_mychip_free(struct mychip *chip)761761+ {762762+ /* disable hardware here if any */763763+ .... /* (not implemented in this document) */764764+765765+ /* release the irq */766766+ if (chip->irq >= 0)767767+ free_irq(chip->irq, chip);768768+ /* release the I/O ports & memory */769769+ pci_release_regions(chip->pci);770770+ /* disable the PCI entry */771771+ pci_disable_device(chip->pci);772772+ /* release the data */773773+ kfree(chip);774774+ return 0;775775+ }776776+777777+ /* chip-specific constructor */778778+ static int snd_mychip_create(struct snd_card *card,779779+ struct pci_dev *pci,780780+ struct mychip **rchip)781781+ {782782+ struct mychip *chip;783783+ int err;784784+ static struct snd_device_ops ops = {785785+ .dev_free = snd_mychip_dev_free,786786+ };787787+788788+ *rchip = NULL;789789+790790+ /* initialize the PCI entry */791791+ err = pci_enable_device(pci);792792+ if (err < 0)793793+ return err;794794+ /* check PCI availability (28bit DMA) */795795+ if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||796796+ pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {797797+ printk(KERN_ERR "error to set 28bit mask DMA\n");798798+ pci_disable_device(pci);799799+ return -ENXIO;800800+ }801801+802802+ chip = kzalloc(sizeof(*chip), GFP_KERNEL);803803+ if (chip == NULL) {804804+ pci_disable_device(pci);805805+ return -ENOMEM;806806+ }807807+808808+ /* initialize the stuff */809809+ chip->card = card;810810+ chip->pci = pci;811811+ chip->irq = -1;812812+813813+ /* (1) PCI resource allocation */814814+ err = pci_request_regions(pci, "My Chip");815815+ if (err < 0) {816816+ kfree(chip);817817+ pci_disable_device(pci);818818+ return err;819819+ }820820+ chip->port = pci_resource_start(pci, 0);821821+ if (request_irq(pci->irq, snd_mychip_interrupt,822822+ IRQF_SHARED, KBUILD_MODNAME, chip)) {823823+ printk(KERN_ERR "cannot grab irq %d\n", pci->irq);824824+ snd_mychip_free(chip);825825+ return -EBUSY;826826+ }827827+ chip->irq = pci->irq;828828+829829+ /* (2) initialization of the chip hardware */830830+ .... /* (not implemented in this document) */831831+832832+ err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);833833+ if (err < 0) {834834+ snd_mychip_free(chip);835835+ return err;836836+ }837837+838838+ *rchip = chip;839839+ return 0;840840+ }841841+842842+ /* PCI IDs */843843+ static struct pci_device_id snd_mychip_ids[] = {844844+ { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,845845+ PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },846846+ ....847847+ { 0, }848848+ };849849+ MODULE_DEVICE_TABLE(pci, snd_mychip_ids);850850+851851+ /* pci_driver definition */852852+ static struct pci_driver driver = {853853+ .name = KBUILD_MODNAME,854854+ .id_table = snd_mychip_ids,855855+ .probe = snd_mychip_probe,856856+ .remove = snd_mychip_remove,857857+ };858858+859859+ /* module initialization */860860+ static int __init alsa_card_mychip_init(void)861861+ {862862+ return pci_register_driver(&driver);863863+ }864864+865865+ /* module clean up */866866+ static void __exit alsa_card_mychip_exit(void)867867+ {868868+ pci_unregister_driver(&driver);869869+ }870870+871871+ module_init(alsa_card_mychip_init)872872+ module_exit(alsa_card_mychip_exit)873873+874874+ EXPORT_NO_SYMBOLS; /* for old kernels only */875875+876876+Some Hafta's877877+------------878878+879879+The allocation of PCI resources is done in the ``probe`` function, and880880+usually an extra :c:func:`xxx_create()` function is written for this881881+purpose.882882+883883+In the case of PCI devices, you first have to call the884884+:c:func:`pci_enable_device()` function before allocating885885+resources. Also, you need to set the proper PCI DMA mask to limit the886886+accessed I/O range. In some cases, you might need to call887887+:c:func:`pci_set_master()` function, too.888888+889889+Suppose the 28bit mask, and the code to be added would be like:890890+891891+::892892+893893+ err = pci_enable_device(pci);894894+ if (err < 0)895895+ return err;896896+ if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||897897+ pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {898898+ printk(KERN_ERR "error to set 28bit mask DMA\n");899899+ pci_disable_device(pci);900900+ return -ENXIO;901901+ }902902+903903+904904+Resource Allocation905905+-------------------906906+907907+The allocation of I/O ports and irqs is done via standard kernel908908+functions. Unlike ALSA ver.0.5.x., there are no helpers for that. And909909+these resources must be released in the destructor function (see below).910910+Also, on ALSA 0.9.x, you don't need to allocate (pseudo-)DMA for PCI911911+like in ALSA 0.5.x.912912+913913+Now assume that the PCI device has an I/O port with 8 bytes and an914914+interrupt. Then :c:type:`struct mychip <mychip>` will have the915915+following fields:916916+917917+::918918+919919+ struct mychip {920920+ struct snd_card *card;921921+922922+ unsigned long port;923923+ int irq;924924+ };925925+926926+927927+For an I/O port (and also a memory region), you need to have the928928+resource pointer for the standard resource management. For an irq, you929929+have to keep only the irq number (integer). But you need to initialize930930+this number as -1 before actual allocation, since irq 0 is valid. The931931+port address and its resource pointer can be initialized as null by932932+:c:func:`kzalloc()` automatically, so you don't have to take care of933933+resetting them.934934+935935+The allocation of an I/O port is done like this:936936+937937+::938938+939939+ err = pci_request_regions(pci, "My Chip");940940+ if (err < 0) { 941941+ kfree(chip);942942+ pci_disable_device(pci);943943+ return err;944944+ }945945+ chip->port = pci_resource_start(pci, 0);946946+947947+It will reserve the I/O port region of 8 bytes of the given PCI device.948948+The returned value, ``chip->res_port``, is allocated via949949+:c:func:`kmalloc()` by :c:func:`request_region()`. The pointer950950+must be released via :c:func:`kfree()`, but there is a problem with951951+this. This issue will be explained later.952952+953953+The allocation of an interrupt source is done like this:954954+955955+::956956+957957+ if (request_irq(pci->irq, snd_mychip_interrupt,958958+ IRQF_SHARED, KBUILD_MODNAME, chip)) {959959+ printk(KERN_ERR "cannot grab irq %d\n", pci->irq);960960+ snd_mychip_free(chip);961961+ return -EBUSY;962962+ }963963+ chip->irq = pci->irq;964964+965965+where :c:func:`snd_mychip_interrupt()` is the interrupt handler966966+defined `later <#pcm-interface-interrupt-handler>`__. Note that967967+``chip->irq`` should be defined only when :c:func:`request_irq()`968968+succeeded.969969+970970+On the PCI bus, interrupts can be shared. Thus, ``IRQF_SHARED`` is used971971+as the interrupt flag of :c:func:`request_irq()`.972972+973973+The last argument of :c:func:`request_irq()` is the data pointer974974+passed to the interrupt handler. Usually, the chip-specific record is975975+used for that, but you can use what you like, too.976976+977977+I won't give details about the interrupt handler at this point, but at978978+least its appearance can be explained now. The interrupt handler looks979979+usually like the following:980980+981981+::982982+983983+ static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)984984+ {985985+ struct mychip *chip = dev_id;986986+ ....987987+ return IRQ_HANDLED;988988+ }989989+990990+991991+Now let's write the corresponding destructor for the resources above.992992+The role of destructor is simple: disable the hardware (if already993993+activated) and release the resources. So far, we have no hardware part,994994+so the disabling code is not written here.995995+996996+To release the resources, the “check-and-release” method is a safer way.997997+For the interrupt, do like this:998998+999999+::10001000+10011001+ if (chip->irq >= 0)10021002+ free_irq(chip->irq, chip);10031003+10041004+Since the irq number can start from 0, you should initialize10051005+``chip->irq`` with a negative value (e.g. -1), so that you can check10061006+the validity of the irq number as above.10071007+10081008+When you requested I/O ports or memory regions via10091009+:c:func:`pci_request_region()` or10101010+:c:func:`pci_request_regions()` like in this example, release the10111011+resource(s) using the corresponding function,10121012+:c:func:`pci_release_region()` or10131013+:c:func:`pci_release_regions()`.10141014+10151015+::10161016+10171017+ pci_release_regions(chip->pci);10181018+10191019+When you requested manually via :c:func:`request_region()` or10201020+:c:func:`request_mem_region()`, you can release it via10211021+:c:func:`release_resource()`. Suppose that you keep the resource10221022+pointer returned from :c:func:`request_region()` in10231023+chip->res_port, the release procedure looks like:10241024+10251025+::10261026+10271027+ release_and_free_resource(chip->res_port);10281028+10291029+Don't forget to call :c:func:`pci_disable_device()` before the10301030+end.10311031+10321032+And finally, release the chip-specific record.10331033+10341034+::10351035+10361036+ kfree(chip);10371037+10381038+We didn't implement the hardware disabling part in the above. If you10391039+need to do this, please note that the destructor may be called even10401040+before the initialization of the chip is completed. It would be better10411041+to have a flag to skip hardware disabling if the hardware was not10421042+initialized yet.10431043+10441044+When the chip-data is assigned to the card using10451045+:c:func:`snd_device_new()` with ``SNDRV_DEV_LOWLELVEL`` , its10461046+destructor is called at the last. That is, it is assured that all other10471047+components like PCMs and controls have already been released. You don't10481048+have to stop PCMs, etc. explicitly, but just call low-level hardware10491049+stopping.10501050+10511051+The management of a memory-mapped region is almost as same as the10521052+management of an I/O port. You'll need three fields like the10531053+following:10541054+10551055+::10561056+10571057+ struct mychip {10581058+ ....10591059+ unsigned long iobase_phys;10601060+ void __iomem *iobase_virt;10611061+ };10621062+10631063+and the allocation would be like below:10641064+10651065+::10661066+10671067+ if ((err = pci_request_regions(pci, "My Chip")) < 0) {10681068+ kfree(chip);10691069+ return err;10701070+ }10711071+ chip->iobase_phys = pci_resource_start(pci, 0);10721072+ chip->iobase_virt = ioremap_nocache(chip->iobase_phys,10731073+ pci_resource_len(pci, 0));10741074+10751075+and the corresponding destructor would be:10761076+10771077+::10781078+10791079+ static int snd_mychip_free(struct mychip *chip)10801080+ {10811081+ ....10821082+ if (chip->iobase_virt)10831083+ iounmap(chip->iobase_virt);10841084+ ....10851085+ pci_release_regions(chip->pci);10861086+ ....10871087+ }10881088+10891089+PCI Entries10901090+-----------10911091+10921092+So far, so good. Let's finish the missing PCI stuff. At first, we need a10931093+:c:type:`struct pci_device_id <pci_device_id>` table for10941094+this chipset. It's a table of PCI vendor/device ID number, and some10951095+masks.10961096+10971097+For example,10981098+10991099+::11001100+11011101+ static struct pci_device_id snd_mychip_ids[] = {11021102+ { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,11031103+ PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },11041104+ ....11051105+ { 0, }11061106+ };11071107+ MODULE_DEVICE_TABLE(pci, snd_mychip_ids);11081108+11091109+The first and second fields of the :c:type:`struct pci_device_id11101110+<pci_device_id>` structure are the vendor and device IDs. If you11111111+have no reason to filter the matching devices, you can leave the11121112+remaining fields as above. The last field of the :c:type:`struct11131113+pci_device_id <pci_device_id>` struct contains private data11141114+for this entry. You can specify any value here, for example, to define11151115+specific operations for supported device IDs. Such an example is found11161116+in the intel8x0 driver.11171117+11181118+The last entry of this list is the terminator. You must specify this11191119+all-zero entry.11201120+11211121+Then, prepare the :c:type:`struct pci_driver <pci_driver>`11221122+record:11231123+11241124+::11251125+11261126+ static struct pci_driver driver = {11271127+ .name = KBUILD_MODNAME,11281128+ .id_table = snd_mychip_ids,11291129+ .probe = snd_mychip_probe,11301130+ .remove = snd_mychip_remove,11311131+ };11321132+11331133+The ``probe`` and ``remove`` functions have already been defined in11341134+the previous sections. The ``name`` field is the name string of this11351135+device. Note that you must not use a slash “/” in this string.11361136+11371137+And at last, the module entries:11381138+11391139+::11401140+11411141+ static int __init alsa_card_mychip_init(void)11421142+ {11431143+ return pci_register_driver(&driver);11441144+ }11451145+11461146+ static void __exit alsa_card_mychip_exit(void)11471147+ {11481148+ pci_unregister_driver(&driver);11491149+ }11501150+11511151+ module_init(alsa_card_mychip_init)11521152+ module_exit(alsa_card_mychip_exit)11531153+11541154+Note that these module entries are tagged with ``__init`` and ``__exit``11551155+prefixes.11561156+11571157+Oh, one thing was forgotten. If you have no exported symbols, you need11581158+to declare it in 2.2 or 2.4 kernels (it's not necessary in 2.6 kernels).11591159+11601160+::11611161+11621162+ EXPORT_NO_SYMBOLS;11631163+11641164+That's all!11651165+11661166+PCM Interface11671167+=============11681168+11691169+General11701170+-------11711171+11721172+The PCM middle layer of ALSA is quite powerful and it is only necessary11731173+for each driver to implement the low-level functions to access its11741174+hardware.11751175+11761176+For accessing to the PCM layer, you need to include ``<sound/pcm.h>``11771177+first. In addition, ``<sound/pcm_params.h>`` might be needed if you11781178+access to some functions related with hw_param.11791179+11801180+Each card device can have up to four pcm instances. A pcm instance11811181+corresponds to a pcm device file. The limitation of number of instances11821182+comes only from the available bit size of the Linux's device numbers.11831183+Once when 64bit device number is used, we'll have more pcm instances11841184+available.11851185+11861186+A pcm instance consists of pcm playback and capture streams, and each11871187+pcm stream consists of one or more pcm substreams. Some soundcards11881188+support multiple playback functions. For example, emu10k1 has a PCM11891189+playback of 32 stereo substreams. In this case, at each open, a free11901190+substream is (usually) automatically chosen and opened. Meanwhile, when11911191+only one substream exists and it was already opened, the successful open11921192+will either block or error with ``EAGAIN`` according to the file open11931193+mode. But you don't have to care about such details in your driver. The11941194+PCM middle layer will take care of such work.11951195+11961196+Full Code Example11971197+-----------------11981198+11991199+The example code below does not include any hardware access routines but12001200+shows only the skeleton, how to build up the PCM interfaces.12011201+12021202+::12031203+12041204+ #include <sound/pcm.h>12051205+ ....12061206+12071207+ /* hardware definition */12081208+ static struct snd_pcm_hardware snd_mychip_playback_hw = {12091209+ .info = (SNDRV_PCM_INFO_MMAP |12101210+ SNDRV_PCM_INFO_INTERLEAVED |12111211+ SNDRV_PCM_INFO_BLOCK_TRANSFER |12121212+ SNDRV_PCM_INFO_MMAP_VALID),12131213+ .formats = SNDRV_PCM_FMTBIT_S16_LE,12141214+ .rates = SNDRV_PCM_RATE_8000_48000,12151215+ .rate_min = 8000,12161216+ .rate_max = 48000,12171217+ .channels_min = 2,12181218+ .channels_max = 2,12191219+ .buffer_bytes_max = 32768,12201220+ .period_bytes_min = 4096,12211221+ .period_bytes_max = 32768,12221222+ .periods_min = 1,12231223+ .periods_max = 1024,12241224+ };12251225+12261226+ /* hardware definition */12271227+ static struct snd_pcm_hardware snd_mychip_capture_hw = {12281228+ .info = (SNDRV_PCM_INFO_MMAP |12291229+ SNDRV_PCM_INFO_INTERLEAVED |12301230+ SNDRV_PCM_INFO_BLOCK_TRANSFER |12311231+ SNDRV_PCM_INFO_MMAP_VALID),12321232+ .formats = SNDRV_PCM_FMTBIT_S16_LE,12331233+ .rates = SNDRV_PCM_RATE_8000_48000,12341234+ .rate_min = 8000,12351235+ .rate_max = 48000,12361236+ .channels_min = 2,12371237+ .channels_max = 2,12381238+ .buffer_bytes_max = 32768,12391239+ .period_bytes_min = 4096,12401240+ .period_bytes_max = 32768,12411241+ .periods_min = 1,12421242+ .periods_max = 1024,12431243+ };12441244+12451245+ /* open callback */12461246+ static int snd_mychip_playback_open(struct snd_pcm_substream *substream)12471247+ {12481248+ struct mychip *chip = snd_pcm_substream_chip(substream);12491249+ struct snd_pcm_runtime *runtime = substream->runtime;12501250+12511251+ runtime->hw = snd_mychip_playback_hw;12521252+ /* more hardware-initialization will be done here */12531253+ ....12541254+ return 0;12551255+ }12561256+12571257+ /* close callback */12581258+ static int snd_mychip_playback_close(struct snd_pcm_substream *substream)12591259+ {12601260+ struct mychip *chip = snd_pcm_substream_chip(substream);12611261+ /* the hardware-specific codes will be here */12621262+ ....12631263+ return 0;12641264+12651265+ }12661266+12671267+ /* open callback */12681268+ static int snd_mychip_capture_open(struct snd_pcm_substream *substream)12691269+ {12701270+ struct mychip *chip = snd_pcm_substream_chip(substream);12711271+ struct snd_pcm_runtime *runtime = substream->runtime;12721272+12731273+ runtime->hw = snd_mychip_capture_hw;12741274+ /* more hardware-initialization will be done here */12751275+ ....12761276+ return 0;12771277+ }12781278+12791279+ /* close callback */12801280+ static int snd_mychip_capture_close(struct snd_pcm_substream *substream)12811281+ {12821282+ struct mychip *chip = snd_pcm_substream_chip(substream);12831283+ /* the hardware-specific codes will be here */12841284+ ....12851285+ return 0;12861286+12871287+ }12881288+12891289+ /* hw_params callback */12901290+ static int snd_mychip_pcm_hw_params(struct snd_pcm_substream *substream,12911291+ struct snd_pcm_hw_params *hw_params)12921292+ {12931293+ return snd_pcm_lib_malloc_pages(substream,12941294+ params_buffer_bytes(hw_params));12951295+ }12961296+12971297+ /* hw_free callback */12981298+ static int snd_mychip_pcm_hw_free(struct snd_pcm_substream *substream)12991299+ {13001300+ return snd_pcm_lib_free_pages(substream);13011301+ }13021302+13031303+ /* prepare callback */13041304+ static int snd_mychip_pcm_prepare(struct snd_pcm_substream *substream)13051305+ {13061306+ struct mychip *chip = snd_pcm_substream_chip(substream);13071307+ struct snd_pcm_runtime *runtime = substream->runtime;13081308+13091309+ /* set up the hardware with the current configuration13101310+ * for example...13111311+ */13121312+ mychip_set_sample_format(chip, runtime->format);13131313+ mychip_set_sample_rate(chip, runtime->rate);13141314+ mychip_set_channels(chip, runtime->channels);13151315+ mychip_set_dma_setup(chip, runtime->dma_addr,13161316+ chip->buffer_size,13171317+ chip->period_size);13181318+ return 0;13191319+ }13201320+13211321+ /* trigger callback */13221322+ static int snd_mychip_pcm_trigger(struct snd_pcm_substream *substream,13231323+ int cmd)13241324+ {13251325+ switch (cmd) {13261326+ case SNDRV_PCM_TRIGGER_START:13271327+ /* do something to start the PCM engine */13281328+ ....13291329+ break;13301330+ case SNDRV_PCM_TRIGGER_STOP:13311331+ /* do something to stop the PCM engine */13321332+ ....13331333+ break;13341334+ default:13351335+ return -EINVAL;13361336+ }13371337+ }13381338+13391339+ /* pointer callback */13401340+ static snd_pcm_uframes_t13411341+ snd_mychip_pcm_pointer(struct snd_pcm_substream *substream)13421342+ {13431343+ struct mychip *chip = snd_pcm_substream_chip(substream);13441344+ unsigned int current_ptr;13451345+13461346+ /* get the current hardware pointer */13471347+ current_ptr = mychip_get_hw_pointer(chip);13481348+ return current_ptr;13491349+ }13501350+13511351+ /* operators */13521352+ static struct snd_pcm_ops snd_mychip_playback_ops = {13531353+ .open = snd_mychip_playback_open,13541354+ .close = snd_mychip_playback_close,13551355+ .ioctl = snd_pcm_lib_ioctl,13561356+ .hw_params = snd_mychip_pcm_hw_params,13571357+ .hw_free = snd_mychip_pcm_hw_free,13581358+ .prepare = snd_mychip_pcm_prepare,13591359+ .trigger = snd_mychip_pcm_trigger,13601360+ .pointer = snd_mychip_pcm_pointer,13611361+ };13621362+13631363+ /* operators */13641364+ static struct snd_pcm_ops snd_mychip_capture_ops = {13651365+ .open = snd_mychip_capture_open,13661366+ .close = snd_mychip_capture_close,13671367+ .ioctl = snd_pcm_lib_ioctl,13681368+ .hw_params = snd_mychip_pcm_hw_params,13691369+ .hw_free = snd_mychip_pcm_hw_free,13701370+ .prepare = snd_mychip_pcm_prepare,13711371+ .trigger = snd_mychip_pcm_trigger,13721372+ .pointer = snd_mychip_pcm_pointer,13731373+ };13741374+13751375+ /*13761376+ * definitions of capture are omitted here...13771377+ */13781378+13791379+ /* create a pcm device */13801380+ static int snd_mychip_new_pcm(struct mychip *chip)13811381+ {13821382+ struct snd_pcm *pcm;13831383+ int err;13841384+13851385+ err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);13861386+ if (err < 0)13871387+ return err;13881388+ pcm->private_data = chip;13891389+ strcpy(pcm->name, "My Chip");13901390+ chip->pcm = pcm;13911391+ /* set operators */13921392+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,13931393+ &snd_mychip_playback_ops);13941394+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,13951395+ &snd_mychip_capture_ops);13961396+ /* pre-allocation of buffers */13971397+ /* NOTE: this may fail */13981398+ snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,13991399+ snd_dma_pci_data(chip->pci),14001400+ 64*1024, 64*1024);14011401+ return 0;14021402+ }14031403+14041404+14051405+PCM Constructor14061406+---------------14071407+14081408+A pcm instance is allocated by the :c:func:`snd_pcm_new()`14091409+function. It would be better to create a constructor for pcm, namely,14101410+14111411+::14121412+14131413+ static int snd_mychip_new_pcm(struct mychip *chip)14141414+ {14151415+ struct snd_pcm *pcm;14161416+ int err;14171417+14181418+ err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);14191419+ if (err < 0) 14201420+ return err;14211421+ pcm->private_data = chip;14221422+ strcpy(pcm->name, "My Chip");14231423+ chip->pcm = pcm;14241424+ ....14251425+ return 0;14261426+ }14271427+14281428+The :c:func:`snd_pcm_new()` function takes four arguments. The14291429+first argument is the card pointer to which this pcm is assigned, and14301430+the second is the ID string.14311431+14321432+The third argument (``index``, 0 in the above) is the index of this new14331433+pcm. It begins from zero. If you create more than one pcm instances,14341434+specify the different numbers in this argument. For example, ``index =14351435+1`` for the second PCM device.14361436+14371437+The fourth and fifth arguments are the number of substreams for playback14381438+and capture, respectively. Here 1 is used for both arguments. When no14391439+playback or capture substreams are available, pass 0 to the14401440+corresponding argument.14411441+14421442+If a chip supports multiple playbacks or captures, you can specify more14431443+numbers, but they must be handled properly in open/close, etc.14441444+callbacks. When you need to know which substream you are referring to,14451445+then it can be obtained from :c:type:`struct snd_pcm_substream14461446+<snd_pcm_substream>` data passed to each callback as follows:14471447+14481448+::14491449+14501450+ struct snd_pcm_substream *substream;14511451+ int index = substream->number;14521452+14531453+14541454+After the pcm is created, you need to set operators for each pcm stream.14551455+14561456+::14571457+14581458+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,14591459+ &snd_mychip_playback_ops);14601460+ snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,14611461+ &snd_mychip_capture_ops);14621462+14631463+The operators are defined typically like this:14641464+14651465+::14661466+14671467+ static struct snd_pcm_ops snd_mychip_playback_ops = {14681468+ .open = snd_mychip_pcm_open,14691469+ .close = snd_mychip_pcm_close,14701470+ .ioctl = snd_pcm_lib_ioctl,14711471+ .hw_params = snd_mychip_pcm_hw_params,14721472+ .hw_free = snd_mychip_pcm_hw_free,14731473+ .prepare = snd_mychip_pcm_prepare,14741474+ .trigger = snd_mychip_pcm_trigger,14751475+ .pointer = snd_mychip_pcm_pointer,14761476+ };14771477+14781478+All the callbacks are described in the Operators_ subsection.14791479+14801480+After setting the operators, you probably will want to pre-allocate the14811481+buffer. For the pre-allocation, simply call the following:14821482+14831483+::14841484+14851485+ snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,14861486+ snd_dma_pci_data(chip->pci),14871487+ 64*1024, 64*1024);14881488+14891489+It will allocate a buffer up to 64kB as default. Buffer management14901490+details will be described in the later section `Buffer and Memory14911491+Management`_.14921492+14931493+Additionally, you can set some extra information for this pcm in14941494+``pcm->info_flags``. The available values are defined as14951495+``SNDRV_PCM_INFO_XXX`` in ``<sound/asound.h>``, which is used for the14961496+hardware definition (described later). When your soundchip supports only14971497+half-duplex, specify like this:14981498+14991499+::15001500+15011501+ pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;15021502+15031503+15041504+... And the Destructor?15051505+-----------------------15061506+15071507+The destructor for a pcm instance is not always necessary. Since the pcm15081508+device will be released by the middle layer code automatically, you15091509+don't have to call the destructor explicitly.15101510+15111511+The destructor would be necessary if you created special records15121512+internally and needed to release them. In such a case, set the15131513+destructor function to ``pcm->private_free``:15141514+15151515+::15161516+15171517+ static void mychip_pcm_free(struct snd_pcm *pcm)15181518+ {15191519+ struct mychip *chip = snd_pcm_chip(pcm);15201520+ /* free your own data */15211521+ kfree(chip->my_private_pcm_data);15221522+ /* do what you like else */15231523+ ....15241524+ }15251525+15261526+ static int snd_mychip_new_pcm(struct mychip *chip)15271527+ {15281528+ struct snd_pcm *pcm;15291529+ ....15301530+ /* allocate your own data */15311531+ chip->my_private_pcm_data = kmalloc(...);15321532+ /* set the destructor */15331533+ pcm->private_data = chip;15341534+ pcm->private_free = mychip_pcm_free;15351535+ ....15361536+ }15371537+15381538+15391539+15401540+Runtime Pointer - The Chest of PCM Information15411541+----------------------------------------------15421542+15431543+When the PCM substream is opened, a PCM runtime instance is allocated15441544+and assigned to the substream. This pointer is accessible via15451545+``substream->runtime``. This runtime pointer holds most information you15461546+need to control the PCM: the copy of hw_params and sw_params15471547+configurations, the buffer pointers, mmap records, spinlocks, etc.15481548+15491549+The definition of runtime instance is found in ``<sound/pcm.h>``. Here15501550+are the contents of this file:15511551+15521552+::15531553+15541554+ struct _snd_pcm_runtime {15551555+ /* -- Status -- */15561556+ struct snd_pcm_substream *trigger_master;15571557+ snd_timestamp_t trigger_tstamp; /* trigger timestamp */15581558+ int overrange;15591559+ snd_pcm_uframes_t avail_max;15601560+ snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */15611561+ snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/15621562+15631563+ /* -- HW params -- */15641564+ snd_pcm_access_t access; /* access mode */15651565+ snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */15661566+ snd_pcm_subformat_t subformat; /* subformat */15671567+ unsigned int rate; /* rate in Hz */15681568+ unsigned int channels; /* channels */15691569+ snd_pcm_uframes_t period_size; /* period size */15701570+ unsigned int periods; /* periods */15711571+ snd_pcm_uframes_t buffer_size; /* buffer size */15721572+ unsigned int tick_time; /* tick time */15731573+ snd_pcm_uframes_t min_align; /* Min alignment for the format */15741574+ size_t byte_align;15751575+ unsigned int frame_bits;15761576+ unsigned int sample_bits;15771577+ unsigned int info;15781578+ unsigned int rate_num;15791579+ unsigned int rate_den;15801580+15811581+ /* -- SW params -- */15821582+ struct timespec tstamp_mode; /* mmap timestamp is updated */15831583+ unsigned int period_step;15841584+ unsigned int sleep_min; /* min ticks to sleep */15851585+ snd_pcm_uframes_t start_threshold;15861586+ snd_pcm_uframes_t stop_threshold;15871587+ snd_pcm_uframes_t silence_threshold; /* Silence filling happens when15881588+ noise is nearest than this */15891589+ snd_pcm_uframes_t silence_size; /* Silence filling size */15901590+ snd_pcm_uframes_t boundary; /* pointers wrap point */15911591+15921592+ snd_pcm_uframes_t silenced_start;15931593+ snd_pcm_uframes_t silenced_size;15941594+15951595+ snd_pcm_sync_id_t sync; /* hardware synchronization ID */15961596+15971597+ /* -- mmap -- */15981598+ volatile struct snd_pcm_mmap_status *status;15991599+ volatile struct snd_pcm_mmap_control *control;16001600+ atomic_t mmap_count;16011601+16021602+ /* -- locking / scheduling -- */16031603+ spinlock_t lock;16041604+ wait_queue_head_t sleep;16051605+ struct timer_list tick_timer;16061606+ struct fasync_struct *fasync;16071607+16081608+ /* -- private section -- */16091609+ void *private_data;16101610+ void (*private_free)(struct snd_pcm_runtime *runtime);16111611+16121612+ /* -- hardware description -- */16131613+ struct snd_pcm_hardware hw;16141614+ struct snd_pcm_hw_constraints hw_constraints;16151615+16161616+ /* -- timer -- */16171617+ unsigned int timer_resolution; /* timer resolution */16181618+16191619+ /* -- DMA -- */ 16201620+ unsigned char *dma_area; /* DMA area */16211621+ dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */16221622+ size_t dma_bytes; /* size of DMA area */16231623+16241624+ struct snd_dma_buffer *dma_buffer_p; /* allocated buffer */16251625+16261626+ #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)16271627+ /* -- OSS things -- */16281628+ struct snd_pcm_oss_runtime oss;16291629+ #endif16301630+ };16311631+16321632+16331633+For the operators (callbacks) of each sound driver, most of these16341634+records are supposed to be read-only. Only the PCM middle-layer changes16351635+/ updates them. The exceptions are the hardware description (hw) DMA16361636+buffer information and the private data. Besides, if you use the16371637+standard buffer allocation method via16381638+:c:func:`snd_pcm_lib_malloc_pages()`, you don't need to set the16391639+DMA buffer information by yourself.16401640+16411641+In the sections below, important records are explained.16421642+16431643+Hardware Description16441644+~~~~~~~~~~~~~~~~~~~~16451645+16461646+The hardware descriptor (:c:type:`struct snd_pcm_hardware16471647+<snd_pcm_hardware>`) contains the definitions of the fundamental16481648+hardware configuration. Above all, you'll need to define this in the16491649+`PCM open callback`_. Note that the runtime instance holds the copy of16501650+the descriptor, not the pointer to the existing descriptor. That is,16511651+in the open callback, you can modify the copied descriptor16521652+(``runtime->hw``) as you need. For example, if the maximum number of16531653+channels is 1 only on some chip models, you can still use the same16541654+hardware descriptor and change the channels_max later:16551655+16561656+::16571657+16581658+ struct snd_pcm_runtime *runtime = substream->runtime;16591659+ ...16601660+ runtime->hw = snd_mychip_playback_hw; /* common definition */16611661+ if (chip->model == VERY_OLD_ONE)16621662+ runtime->hw.channels_max = 1;16631663+16641664+Typically, you'll have a hardware descriptor as below:16651665+16661666+::16671667+16681668+ static struct snd_pcm_hardware snd_mychip_playback_hw = {16691669+ .info = (SNDRV_PCM_INFO_MMAP |16701670+ SNDRV_PCM_INFO_INTERLEAVED |16711671+ SNDRV_PCM_INFO_BLOCK_TRANSFER |16721672+ SNDRV_PCM_INFO_MMAP_VALID),16731673+ .formats = SNDRV_PCM_FMTBIT_S16_LE,16741674+ .rates = SNDRV_PCM_RATE_8000_48000,16751675+ .rate_min = 8000,16761676+ .rate_max = 48000,16771677+ .channels_min = 2,16781678+ .channels_max = 2,16791679+ .buffer_bytes_max = 32768,16801680+ .period_bytes_min = 4096,16811681+ .period_bytes_max = 32768,16821682+ .periods_min = 1,16831683+ .periods_max = 1024,16841684+ };16851685+16861686+- The ``info`` field contains the type and capabilities of this16871687+ pcm. The bit flags are defined in ``<sound/asound.h>`` as16881688+ ``SNDRV_PCM_INFO_XXX``. Here, at least, you have to specify whether16891689+ the mmap is supported and which interleaved format is16901690+ supported. When the hardware supports mmap, add the16911691+ ``SNDRV_PCM_INFO_MMAP`` flag here. When the hardware supports the16921692+ interleaved or the non-interleaved formats,16931693+ ``SNDRV_PCM_INFO_INTERLEAVED`` or ``SNDRV_PCM_INFO_NONINTERLEAVED``16941694+ flag must be set, respectively. If both are supported, you can set16951695+ both, too.16961696+16971697+ In the above example, ``MMAP_VALID`` and ``BLOCK_TRANSFER`` are16981698+ specified for the OSS mmap mode. Usually both are set. Of course,16991699+ ``MMAP_VALID`` is set only if the mmap is really supported.17001700+17011701+ The other possible flags are ``SNDRV_PCM_INFO_PAUSE`` and17021702+ ``SNDRV_PCM_INFO_RESUME``. The ``PAUSE`` bit means that the pcm17031703+ supports the “pause” operation, while the ``RESUME`` bit means that17041704+ the pcm supports the full “suspend/resume” operation. If the17051705+ ``PAUSE`` flag is set, the ``trigger`` callback below must handle17061706+ the corresponding (pause push/release) commands. The suspend/resume17071707+ trigger commands can be defined even without the ``RESUME``17081708+ flag. See `Power Management`_ section for details.17091709+17101710+ When the PCM substreams can be synchronized (typically,17111711+ synchronized start/stop of a playback and a capture streams), you17121712+ can give ``SNDRV_PCM_INFO_SYNC_START``, too. In this case, you'll17131713+ need to check the linked-list of PCM substreams in the trigger17141714+ callback. This will be described in the later section.17151715+17161716+- ``formats`` field contains the bit-flags of supported formats17171717+ (``SNDRV_PCM_FMTBIT_XXX``). If the hardware supports more than one17181718+ format, give all or'ed bits. In the example above, the signed 16bit17191719+ little-endian format is specified.17201720+17211721+- ``rates`` field contains the bit-flags of supported rates17221722+ (``SNDRV_PCM_RATE_XXX``). When the chip supports continuous rates,17231723+ pass ``CONTINUOUS`` bit additionally. The pre-defined rate bits are17241724+ provided only for typical rates. If your chip supports17251725+ unconventional rates, you need to add the ``KNOT`` bit and set up17261726+ the hardware constraint manually (explained later).17271727+17281728+- ``rate_min`` and ``rate_max`` define the minimum and maximum sample17291729+ rate. This should correspond somehow to ``rates`` bits.17301730+17311731+- ``channel_min`` and ``channel_max`` define, as you might already17321732+ expected, the minimum and maximum number of channels.17331733+17341734+- ``buffer_bytes_max`` defines the maximum buffer size in17351735+ bytes. There is no ``buffer_bytes_min`` field, since it can be17361736+ calculated from the minimum period size and the minimum number of17371737+ periods. Meanwhile, ``period_bytes_min`` and define the minimum and17381738+ maximum size of the period in bytes. ``periods_max`` and17391739+ ``periods_min`` define the maximum and minimum number of periods in17401740+ the buffer.17411741+17421742+ The “period” is a term that corresponds to a fragment in the OSS17431743+ world. The period defines the size at which a PCM interrupt is17441744+ generated. This size strongly depends on the hardware. Generally,17451745+ the smaller period size will give you more interrupts, that is,17461746+ more controls. In the case of capture, this size defines the input17471747+ latency. On the other hand, the whole buffer size defines the17481748+ output latency for the playback direction.17491749+17501750+- There is also a field ``fifo_size``. This specifies the size of the17511751+ hardware FIFO, but currently it is neither used in the driver nor17521752+ in the alsa-lib. So, you can ignore this field.17531753+17541754+PCM Configurations17551755+~~~~~~~~~~~~~~~~~~17561756+17571757+Ok, let's go back again to the PCM runtime records. The most17581758+frequently referred records in the runtime instance are the PCM17591759+configurations. The PCM configurations are stored in the runtime17601760+instance after the application sends ``hw_params`` data via17611761+alsa-lib. There are many fields copied from hw_params and sw_params17621762+structs. For example, ``format`` holds the format type chosen by the17631763+application. This field contains the enum value17641764+``SNDRV_PCM_FORMAT_XXX``.17651765+17661766+One thing to be noted is that the configured buffer and period sizes17671767+are stored in “frames” in the runtime. In the ALSA world, ``1 frame =17681768+channels \* samples-size``. For conversion between frames and bytes,17691769+you can use the :c:func:`frames_to_bytes()` and17701770+:c:func:`bytes_to_frames()` helper functions.17711771+17721772+::17731773+17741774+ period_bytes = frames_to_bytes(runtime, runtime->period_size);17751775+17761776+Also, many software parameters (sw_params) are stored in frames, too.17771777+Please check the type of the field. ``snd_pcm_uframes_t`` is for the17781778+frames as unsigned integer while ``snd_pcm_sframes_t`` is for the17791779+frames as signed integer.17801780+17811781+DMA Buffer Information17821782+~~~~~~~~~~~~~~~~~~~~~~17831783+17841784+The DMA buffer is defined by the following four fields, ``dma_area``,17851785+``dma_addr``, ``dma_bytes`` and ``dma_private``. The ``dma_area``17861786+holds the buffer pointer (the logical address). You can call17871787+:c:func:`memcpy()` from/to this pointer. Meanwhile, ``dma_addr`` holds17881788+the physical address of the buffer. This field is specified only when17891789+the buffer is a linear buffer. ``dma_bytes`` holds the size of buffer17901790+in bytes. ``dma_private`` is used for the ALSA DMA allocator.17911791+17921792+If you use a standard ALSA function,17931793+:c:func:`snd_pcm_lib_malloc_pages()`, for allocating the buffer,17941794+these fields are set by the ALSA middle layer, and you should *not*17951795+change them by yourself. You can read them but not write them. On the17961796+other hand, if you want to allocate the buffer by yourself, you'll17971797+need to manage it in hw_params callback. At least, ``dma_bytes`` is17981798+mandatory. ``dma_area`` is necessary when the buffer is mmapped. If17991799+your driver doesn't support mmap, this field is not18001800+necessary. ``dma_addr`` is also optional. You can use dma_private as18011801+you like, too.18021802+18031803+Running Status18041804+~~~~~~~~~~~~~~18051805+18061806+The running status can be referred via ``runtime->status``. This is18071807+the pointer to the :c:type:`struct snd_pcm_mmap_status18081808+<snd_pcm_mmap_status>` record. For example, you can get the current18091809+DMA hardware pointer via ``runtime->status->hw_ptr``.18101810+18111811+The DMA application pointer can be referred via ``runtime->control``,18121812+which points to the :c:type:`struct snd_pcm_mmap_control18131813+<snd_pcm_mmap_control>` record. However, accessing directly to18141814+this value is not recommended.18151815+18161816+Private Data18171817+~~~~~~~~~~~~18181818+18191819+You can allocate a record for the substream and store it in18201820+``runtime->private_data``. Usually, this is done in the `PCM open18211821+callback`_. Don't mix this with ``pcm->private_data``. The18221822+``pcm->private_data`` usually points to the chip instance assigned18231823+statically at the creation of PCM, while the ``runtime->private_data``18241824+points to a dynamic data structure created at the PCM open18251825+callback.18261826+18271827+::18281828+18291829+ static int snd_xxx_open(struct snd_pcm_substream *substream)18301830+ {18311831+ struct my_pcm_data *data;18321832+ ....18331833+ data = kmalloc(sizeof(*data), GFP_KERNEL);18341834+ substream->runtime->private_data = data;18351835+ ....18361836+ }18371837+18381838+18391839+The allocated object must be released in the `close callback`_.18401840+18411841+Operators18421842+---------18431843+18441844+OK, now let me give details about each pcm callback (``ops``). In18451845+general, every callback must return 0 if successful, or a negative18461846+error number such as ``-EINVAL``. To choose an appropriate error18471847+number, it is advised to check what value other parts of the kernel18481848+return when the same kind of request fails.18491849+18501850+The callback function takes at least the argument with :c:type:`struct18511851+snd_pcm_substream <snd_pcm_substream>` pointer. To retrieve the chip18521852+record from the given substream instance, you can use the following18531853+macro.18541854+18551855+::18561856+18571857+ int xxx() {18581858+ struct mychip *chip = snd_pcm_substream_chip(substream);18591859+ ....18601860+ }18611861+18621862+The macro reads ``substream->private_data``, which is a copy of18631863+``pcm->private_data``. You can override the former if you need to18641864+assign different data records per PCM substream. For example, the18651865+cmi8330 driver assigns different ``private_data`` for playback and18661866+capture directions, because it uses two different codecs (SB- and18671867+AD-compatible) for different directions.18681868+18691869+PCM open callback18701870+~~~~~~~~~~~~~~~~~18711871+18721872+::18731873+18741874+ static int snd_xxx_open(struct snd_pcm_substream *substream);18751875+18761876+This is called when a pcm substream is opened.18771877+18781878+At least, here you have to initialize the ``runtime->hw``18791879+record. Typically, this is done by like this:18801880+18811881+::18821882+18831883+ static int snd_xxx_open(struct snd_pcm_substream *substream)18841884+ {18851885+ struct mychip *chip = snd_pcm_substream_chip(substream);18861886+ struct snd_pcm_runtime *runtime = substream->runtime;18871887+18881888+ runtime->hw = snd_mychip_playback_hw;18891889+ return 0;18901890+ }18911891+18921892+where ``snd_mychip_playback_hw`` is the pre-defined hardware18931893+description.18941894+18951895+You can allocate a private data in this callback, as described in18961896+`Private Data`_ section.18971897+18981898+If the hardware configuration needs more constraints, set the hardware18991899+constraints here, too. See Constraints_ for more details.19001900+19011901+close callback19021902+~~~~~~~~~~~~~~19031903+19041904+::19051905+19061906+ static int snd_xxx_close(struct snd_pcm_substream *substream);19071907+19081908+19091909+Obviously, this is called when a pcm substream is closed.19101910+19111911+Any private instance for a pcm substream allocated in the ``open``19121912+callback will be released here.19131913+19141914+::19151915+19161916+ static int snd_xxx_close(struct snd_pcm_substream *substream)19171917+ {19181918+ ....19191919+ kfree(substream->runtime->private_data);19201920+ ....19211921+ }19221922+19231923+ioctl callback19241924+~~~~~~~~~~~~~~19251925+19261926+This is used for any special call to pcm ioctls. But usually you can19271927+pass a generic ioctl callback, :c:func:`snd_pcm_lib_ioctl()`.19281928+19291929+hw_params callback19301930+~~~~~~~~~~~~~~~~~~~19311931+19321932+::19331933+19341934+ static int snd_xxx_hw_params(struct snd_pcm_substream *substream,19351935+ struct snd_pcm_hw_params *hw_params);19361936+19371937+This is called when the hardware parameter (``hw_params``) is set up19381938+by the application, that is, once when the buffer size, the period19391939+size, the format, etc. are defined for the pcm substream.19401940+19411941+Many hardware setups should be done in this callback, including the19421942+allocation of buffers.19431943+19441944+Parameters to be initialized are retrieved by19451945+:c:func:`params_xxx()` macros. To allocate buffer, you can call a19461946+helper function,19471947+19481948+::19491949+19501950+ snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));19511951+19521952+:c:func:`snd_pcm_lib_malloc_pages()` is available only when the19531953+DMA buffers have been pre-allocated. See the section `Buffer Types`_19541954+for more details.19551955+19561956+Note that this and ``prepare`` callbacks may be called multiple times19571957+per initialization. For example, the OSS emulation may call these19581958+callbacks at each change via its ioctl.19591959+19601960+Thus, you need to be careful not to allocate the same buffers many19611961+times, which will lead to memory leaks! Calling the helper function19621962+above many times is OK. It will release the previous buffer19631963+automatically when it was already allocated.19641964+19651965+Another note is that this callback is non-atomic (schedulable) as19661966+default, i.e. when no ``nonatomic`` flag set. This is important,19671967+because the ``trigger`` callback is atomic (non-schedulable). That is,19681968+mutexes or any schedule-related functions are not available in19691969+``trigger`` callback. Please see the subsection Atomicity_ for19701970+details.19711971+19721972+hw_free callback19731973+~~~~~~~~~~~~~~~~~19741974+19751975+::19761976+19771977+ static int snd_xxx_hw_free(struct snd_pcm_substream *substream);19781978+19791979+This is called to release the resources allocated via19801980+``hw_params``. For example, releasing the buffer via19811981+:c:func:`snd_pcm_lib_malloc_pages()` is done by calling the19821982+following:19831983+19841984+::19851985+19861986+ snd_pcm_lib_free_pages(substream);19871987+19881988+This function is always called before the close callback is called.19891989+Also, the callback may be called multiple times, too. Keep track19901990+whether the resource was already released.19911991+19921992+prepare callback19931993+~~~~~~~~~~~~~~~~19941994+19951995+::19961996+19971997+ static int snd_xxx_prepare(struct snd_pcm_substream *substream);19981998+19991999+This callback is called when the pcm is “prepared”. You can set the20002000+format type, sample rate, etc. here. The difference from ``hw_params``20012001+is that the ``prepare`` callback will be called each time20022002+:c:func:`snd_pcm_prepare()` is called, i.e. when recovering after20032003+underruns, etc.20042004+20052005+Note that this callback is now non-atomic. You can use20062006+schedule-related functions safely in this callback.20072007+20082008+In this and the following callbacks, you can refer to the values via20092009+the runtime record, ``substream->runtime``. For example, to get the20102010+current rate, format or channels, access to ``runtime->rate``,20112011+``runtime->format`` or ``runtime->channels``, respectively. The20122012+physical address of the allocated buffer is set to20132013+``runtime->dma_area``. The buffer and period sizes are in20142014+``runtime->buffer_size`` and ``runtime->period_size``, respectively.20152015+20162016+Be careful that this callback will be called many times at each setup,20172017+too.20182018+20192019+trigger callback20202020+~~~~~~~~~~~~~~~~20212021+20222022+::20232023+20242024+ static int snd_xxx_trigger(struct snd_pcm_substream *substream, int cmd);20252025+20262026+This is called when the pcm is started, stopped or paused.20272027+20282028+Which action is specified in the second argument,20292029+``SNDRV_PCM_TRIGGER_XXX`` in ``<sound/pcm.h>``. At least, the ``START``20302030+and ``STOP`` commands must be defined in this callback.20312031+20322032+::20332033+20342034+ switch (cmd) {20352035+ case SNDRV_PCM_TRIGGER_START:20362036+ /* do something to start the PCM engine */20372037+ break;20382038+ case SNDRV_PCM_TRIGGER_STOP:20392039+ /* do something to stop the PCM engine */20402040+ break;20412041+ default:20422042+ return -EINVAL;20432043+ }20442044+20452045+When the pcm supports the pause operation (given in the info field of20462046+the hardware table), the ``PAUSE_PUSH`` and ``PAUSE_RELEASE`` commands20472047+must be handled here, too. The former is the command to pause the pcm,20482048+and the latter to restart the pcm again.20492049+20502050+When the pcm supports the suspend/resume operation, regardless of full20512051+or partial suspend/resume support, the ``SUSPEND`` and ``RESUME``20522052+commands must be handled, too. These commands are issued when the20532053+power-management status is changed. Obviously, the ``SUSPEND`` and20542054+``RESUME`` commands suspend and resume the pcm substream, and usually,20552055+they are identical to the ``STOP`` and ``START`` commands, respectively.20562056+See the `Power Management`_ section for details.20572057+20582058+As mentioned, this callback is atomic as default unless ``nonatomic``20592059+flag set, and you cannot call functions which may sleep. The20602060+``trigger`` callback should be as minimal as possible, just really20612061+triggering the DMA. The other stuff should be initialized20622062+``hw_params`` and ``prepare`` callbacks properly beforehand.20632063+20642064+pointer callback20652065+~~~~~~~~~~~~~~~~20662066+20672067+::20682068+20692069+ static snd_pcm_uframes_t snd_xxx_pointer(struct snd_pcm_substream *substream)20702070+20712071+This callback is called when the PCM middle layer inquires the current20722072+hardware position on the buffer. The position must be returned in20732073+frames, ranging from 0 to ``buffer_size - 1``. 20742074+20752075+This is called usually from the buffer-update routine in the pcm20762076+middle layer, which is invoked when :c:func:`snd_pcm_period_elapsed()`20772077+is called in the interrupt routine. Then the pcm middle layer updates20782078+the position and calculates the available space, and wakes up the20792079+sleeping poll threads, etc.20802080+20812081+This callback is also atomic as default.20822082+20832083+copy and silence callbacks20842084+~~~~~~~~~~~~~~~~~~~~~~~~~~20852085+20862086+These callbacks are not mandatory, and can be omitted in most cases.20872087+These callbacks are used when the hardware buffer cannot be in the20882088+normal memory space. Some chips have their own buffer on the hardware20892089+which is not mappable. In such a case, you have to transfer the data20902090+manually from the memory buffer to the hardware buffer. Or, if the20912091+buffer is non-contiguous on both physical and virtual memory spaces,20922092+these callbacks must be defined, too.20932093+20942094+If these two callbacks are defined, copy and set-silence operations20952095+are done by them. The detailed will be described in the later section20962096+`Buffer and Memory Management`_.20972097+20982098+ack callback20992099+~~~~~~~~~~~~21002100+21012101+This callback is also not mandatory. This callback is called when the21022102+``appl_ptr`` is updated in read or write operations. Some drivers like21032103+emu10k1-fx and cs46xx need to track the current ``appl_ptr`` for the21042104+internal buffer, and this callback is useful only for such a purpose.21052105+21062106+This callback is atomic as default.21072107+21082108+page callback21092109+~~~~~~~~~~~~~21102110+21112111+This callback is optional too. This callback is used mainly for21122112+non-contiguous buffers. The mmap calls this callback to get the page21132113+address. Some examples will be explained in the later section `Buffer21142114+and Memory Management`_, too.21152115+21162116+PCM Interrupt Handler21172117+---------------------21182118+21192119+The rest of pcm stuff is the PCM interrupt handler. The role of PCM21202120+interrupt handler in the sound driver is to update the buffer position21212121+and to tell the PCM middle layer when the buffer position goes across21222122+the prescribed period size. To inform this, call the21232123+:c:func:`snd_pcm_period_elapsed()` function.21242124+21252125+There are several types of sound chips to generate the interrupts.21262126+21272127+Interrupts at the period (fragment) boundary21282128+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~21292129+21302130+This is the most frequently found type: the hardware generates an21312131+interrupt at each period boundary. In this case, you can call21322132+:c:func:`snd_pcm_period_elapsed()` at each interrupt.21332133+21342134+:c:func:`snd_pcm_period_elapsed()` takes the substream pointer as21352135+its argument. Thus, you need to keep the substream pointer accessible21362136+from the chip instance. For example, define ``substream`` field in the21372137+chip record to hold the current running substream pointer, and set the21382138+pointer value at ``open`` callback (and reset at ``close`` callback).21392139+21402140+If you acquire a spinlock in the interrupt handler, and the lock is used21412141+in other pcm callbacks, too, then you have to release the lock before21422142+calling :c:func:`snd_pcm_period_elapsed()`, because21432143+:c:func:`snd_pcm_period_elapsed()` calls other pcm callbacks21442144+inside.21452145+21462146+Typical code would be like:21472147+21482148+::21492149+21502150+21512151+ static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)21522152+ {21532153+ struct mychip *chip = dev_id;21542154+ spin_lock(&chip->lock);21552155+ ....21562156+ if (pcm_irq_invoked(chip)) {21572157+ /* call updater, unlock before it */21582158+ spin_unlock(&chip->lock);21592159+ snd_pcm_period_elapsed(chip->substream);21602160+ spin_lock(&chip->lock);21612161+ /* acknowledge the interrupt if necessary */21622162+ }21632163+ ....21642164+ spin_unlock(&chip->lock);21652165+ return IRQ_HANDLED;21662166+ }21672167+21682168+21692169+21702170+High frequency timer interrupts21712171+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~21722172+21732173+This happens when the hardware doesn't generate interrupts at the period21742174+boundary but issues timer interrupts at a fixed timer rate (e.g. es196821752175+or ymfpci drivers). In this case, you need to check the current hardware21762176+position and accumulate the processed sample length at each interrupt.21772177+When the accumulated size exceeds the period size, call21782178+:c:func:`snd_pcm_period_elapsed()` and reset the accumulator.21792179+21802180+Typical code would be like the following.21812181+21822182+::21832183+21842184+21852185+ static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)21862186+ {21872187+ struct mychip *chip = dev_id;21882188+ spin_lock(&chip->lock);21892189+ ....21902190+ if (pcm_irq_invoked(chip)) {21912191+ unsigned int last_ptr, size;21922192+ /* get the current hardware pointer (in frames) */21932193+ last_ptr = get_hw_ptr(chip);21942194+ /* calculate the processed frames since the21952195+ * last update21962196+ */21972197+ if (last_ptr < chip->last_ptr)21982198+ size = runtime->buffer_size + last_ptr21992199+ - chip->last_ptr;22002200+ else22012201+ size = last_ptr - chip->last_ptr;22022202+ /* remember the last updated point */22032203+ chip->last_ptr = last_ptr;22042204+ /* accumulate the size */22052205+ chip->size += size;22062206+ /* over the period boundary? */22072207+ if (chip->size >= runtime->period_size) {22082208+ /* reset the accumulator */22092209+ chip->size %= runtime->period_size;22102210+ /* call updater */22112211+ spin_unlock(&chip->lock);22122212+ snd_pcm_period_elapsed(substream);22132213+ spin_lock(&chip->lock);22142214+ }22152215+ /* acknowledge the interrupt if necessary */22162216+ }22172217+ ....22182218+ spin_unlock(&chip->lock);22192219+ return IRQ_HANDLED;22202220+ }22212221+22222222+22232223+22242224+On calling :c:func:`snd_pcm_period_elapsed()`22252225+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~22262226+22272227+In both cases, even if more than one period are elapsed, you don't have22282228+to call :c:func:`snd_pcm_period_elapsed()` many times. Call only22292229+once. And the pcm layer will check the current hardware pointer and22302230+update to the latest status.22312231+22322232+Atomicity22332233+---------22342234+22352235+One of the most important (and thus difficult to debug) problems in22362236+kernel programming are race conditions. In the Linux kernel, they are22372237+usually avoided via spin-locks, mutexes or semaphores. In general, if a22382238+race condition can happen in an interrupt handler, it has to be managed22392239+atomically, and you have to use a spinlock to protect the critical22402240+session. If the critical section is not in interrupt handler code and if22412241+taking a relatively long time to execute is acceptable, you should use22422242+mutexes or semaphores instead.22432243+22442244+As already seen, some pcm callbacks are atomic and some are not. For22452245+example, the ``hw_params`` callback is non-atomic, while ``trigger``22462246+callback is atomic. This means, the latter is called already in a22472247+spinlock held by the PCM middle layer. Please take this atomicity into22482248+account when you choose a locking scheme in the callbacks.22492249+22502250+In the atomic callbacks, you cannot use functions which may call22512251+:c:func:`schedule()` or go to :c:func:`sleep()`. Semaphores and22522252+mutexes can sleep, and hence they cannot be used inside the atomic22532253+callbacks (e.g. ``trigger`` callback). To implement some delay in such a22542254+callback, please use :c:func:`udelay()` or :c:func:`mdelay()`.22552255+22562256+All three atomic callbacks (trigger, pointer, and ack) are called with22572257+local interrupts disabled.22582258+22592259+The recent changes in PCM core code, however, allow all PCM operations22602260+to be non-atomic. This assumes that the all caller sides are in22612261+non-atomic contexts. For example, the function22622262+:c:func:`snd_pcm_period_elapsed()` is called typically from the22632263+interrupt handler. But, if you set up the driver to use a threaded22642264+interrupt handler, this call can be in non-atomic context, too. In such22652265+a case, you can set ``nonatomic`` filed of :c:type:`struct snd_pcm22662266+<snd_pcm>` object after creating it. When this flag is set, mutex22672267+and rwsem are used internally in the PCM core instead of spin and22682268+rwlocks, so that you can call all PCM functions safely in a non-atomic22692269+context.22702270+22712271+Constraints22722272+-----------22732273+22742274+If your chip supports unconventional sample rates, or only the limited22752275+samples, you need to set a constraint for the condition.22762276+22772277+For example, in order to restrict the sample rates in the some supported22782278+values, use :c:func:`snd_pcm_hw_constraint_list()`. You need to22792279+call this function in the open callback.22802280+22812281+::22822282+22832283+ static unsigned int rates[] =22842284+ {4000, 10000, 22050, 44100};22852285+ static struct snd_pcm_hw_constraint_list constraints_rates = {22862286+ .count = ARRAY_SIZE(rates),22872287+ .list = rates,22882288+ .mask = 0,22892289+ };22902290+22912291+ static int snd_mychip_pcm_open(struct snd_pcm_substream *substream)22922292+ {22932293+ int err;22942294+ ....22952295+ err = snd_pcm_hw_constraint_list(substream->runtime, 0,22962296+ SNDRV_PCM_HW_PARAM_RATE,22972297+ &constraints_rates);22982298+ if (err < 0)22992299+ return err;23002300+ ....23012301+ }23022302+23032303+23042304+23052305+There are many different constraints. Look at ``sound/pcm.h`` for a23062306+complete list. You can even define your own constraint rules. For23072307+example, let's suppose my_chip can manage a substream of 1 channel if23082308+and only if the format is ``S16_LE``, otherwise it supports any format23092309+specified in the :c:type:`struct snd_pcm_hardware23102310+<snd_pcm_hardware>` structure (or in any other23112311+constraint_list). You can build a rule like this:23122312+23132313+::23142314+23152315+ static int hw_rule_channels_by_format(struct snd_pcm_hw_params *params,23162316+ struct snd_pcm_hw_rule *rule)23172317+ {23182318+ struct snd_interval *c = hw_param_interval(params,23192319+ SNDRV_PCM_HW_PARAM_CHANNELS);23202320+ struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);23212321+ struct snd_interval ch;23222322+23232323+ snd_interval_any(&ch);23242324+ if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {23252325+ ch.min = ch.max = 1;23262326+ ch.integer = 1;23272327+ return snd_interval_refine(c, &ch);23282328+ }23292329+ return 0;23302330+ }23312331+23322332+23332333+Then you need to call this function to add your rule:23342334+23352335+::23362336+23372337+ snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,23382338+ hw_rule_channels_by_format, NULL,23392339+ SNDRV_PCM_HW_PARAM_FORMAT, -1);23402340+23412341+The rule function is called when an application sets the PCM format, and23422342+it refines the number of channels accordingly. But an application may23432343+set the number of channels before setting the format. Thus you also need23442344+to define the inverse rule:23452345+23462346+::23472347+23482348+ static int hw_rule_format_by_channels(struct snd_pcm_hw_params *params,23492349+ struct snd_pcm_hw_rule *rule)23502350+ {23512351+ struct snd_interval *c = hw_param_interval(params,23522352+ SNDRV_PCM_HW_PARAM_CHANNELS);23532353+ struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);23542354+ struct snd_mask fmt;23552355+23562356+ snd_mask_any(&fmt); /* Init the struct */23572357+ if (c->min < 2) {23582358+ fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;23592359+ return snd_mask_refine(f, &fmt);23602360+ }23612361+ return 0;23622362+ }23632363+23642364+23652365+... and in the open callback:23662366+23672367+::23682368+23692369+ snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,23702370+ hw_rule_format_by_channels, NULL,23712371+ SNDRV_PCM_HW_PARAM_CHANNELS, -1);23722372+23732373+I won't give more details here, rather I would like to say, “Luke, use23742374+the source.”23752375+23762376+Control Interface23772377+=================23782378+23792379+General23802380+-------23812381+23822382+The control interface is used widely for many switches, sliders, etc.23832383+which are accessed from user-space. Its most important use is the mixer23842384+interface. In other words, since ALSA 0.9.x, all the mixer stuff is23852385+implemented on the control kernel API.23862386+23872387+ALSA has a well-defined AC97 control module. If your chip supports only23882388+the AC97 and nothing else, you can skip this section.23892389+23902390+The control API is defined in ``<sound/control.h>``. Include this file23912391+if you want to add your own controls.23922392+23932393+Definition of Controls23942394+----------------------23952395+23962396+To create a new control, you need to define the following three23972397+callbacks: ``info``, ``get`` and ``put``. Then, define a23982398+:c:type:`struct snd_kcontrol_new <snd_kcontrol_new>` record, such as:23992399+24002400+::24012401+24022402+24032403+ static struct snd_kcontrol_new my_control = {24042404+ .iface = SNDRV_CTL_ELEM_IFACE_MIXER,24052405+ .name = "PCM Playback Switch",24062406+ .index = 0,24072407+ .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,24082408+ .private_value = 0xffff,24092409+ .info = my_control_info,24102410+ .get = my_control_get,24112411+ .put = my_control_put24122412+ };24132413+24142414+24152415+The ``iface`` field specifies the control type,24162416+``SNDRV_CTL_ELEM_IFACE_XXX``, which is usually ``MIXER``. Use ``CARD``24172417+for global controls that are not logically part of the mixer. If the24182418+control is closely associated with some specific device on the sound24192419+card, use ``HWDEP``, ``PCM``, ``RAWMIDI``, ``TIMER``, or ``SEQUENCER``,24202420+and specify the device number with the ``device`` and ``subdevice``24212421+fields.24222422+24232423+The ``name`` is the name identifier string. Since ALSA 0.9.x, the24242424+control name is very important, because its role is classified from24252425+its name. There are pre-defined standard control names. The details24262426+are described in the `Control Names`_ subsection.24272427+24282428+The ``index`` field holds the index number of this control. If there24292429+are several different controls with the same name, they can be24302430+distinguished by the index number. This is the case when several24312431+codecs exist on the card. If the index is zero, you can omit the24322432+definition above. 24332433+24342434+The ``access`` field contains the access type of this control. Give24352435+the combination of bit masks, ``SNDRV_CTL_ELEM_ACCESS_XXX``,24362436+there. The details will be explained in the `Access Flags`_24372437+subsection.24382438+24392439+The ``private_value`` field contains an arbitrary long integer value24402440+for this record. When using the generic ``info``, ``get`` and ``put``24412441+callbacks, you can pass a value through this field. If several small24422442+numbers are necessary, you can combine them in bitwise. Or, it's24432443+possible to give a pointer (casted to unsigned long) of some record to24442444+this field, too. 24452445+24462446+The ``tlv`` field can be used to provide metadata about the control;24472447+see the `Metadata`_ subsection.24482448+24492449+The other three are `Control Callbacks`_.24502450+24512451+Control Names24522452+-------------24532453+24542454+There are some standards to define the control names. A control is24552455+usually defined from the three parts as “SOURCE DIRECTION FUNCTION”.24562456+24572457+The first, ``SOURCE``, specifies the source of the control, and is a24582458+string such as “Master”, “PCM”, “CD” and “Line”. There are many24592459+pre-defined sources.24602460+24612461+The second, ``DIRECTION``, is one of the following strings according to24622462+the direction of the control: “Playback”, “Capture”, “Bypass Playback”24632463+and “Bypass Capture”. Or, it can be omitted, meaning both playback and24642464+capture directions.24652465+24662466+The third, ``FUNCTION``, is one of the following strings according to24672467+the function of the control: “Switch”, “Volume” and “Route”.24682468+24692469+The example of control names are, thus, “Master Capture Switch” or “PCM24702470+Playback Volume”.24712471+24722472+There are some exceptions:24732473+24742474+Global capture and playback24752475+~~~~~~~~~~~~~~~~~~~~~~~~~~~24762476+24772477+“Capture Source”, “Capture Switch” and “Capture Volume” are used for the24782478+global capture (input) source, switch and volume. Similarly, “Playback24792479+Switch” and “Playback Volume” are used for the global output gain switch24802480+and volume.24812481+24822482+Tone-controls24832483+~~~~~~~~~~~~~24842484+24852485+tone-control switch and volumes are specified like “Tone Control - XXX”,24862486+e.g. “Tone Control - Switch”, “Tone Control - Bass”, “Tone Control -24872487+Center”.24882488+24892489+3D controls24902490+~~~~~~~~~~~24912491+24922492+3D-control switches and volumes are specified like “3D Control - XXX”,24932493+e.g. “3D Control - Switch”, “3D Control - Center”, “3D Control - Space”.24942494+24952495+Mic boost24962496+~~~~~~~~~24972497+24982498+Mic-boost switch is set as “Mic Boost” or “Mic Boost (6dB)”.24992499+25002500+More precise information can be found in25012501+``Documentation/sound/alsa/ControlNames.txt``.25022502+25032503+Access Flags25042504+------------25052505+25062506+The access flag is the bitmask which specifies the access type of the25072507+given control. The default access type is25082508+``SNDRV_CTL_ELEM_ACCESS_READWRITE``, which means both read and write are25092509+allowed to this control. When the access flag is omitted (i.e. = 0), it25102510+is considered as ``READWRITE`` access as default.25112511+25122512+When the control is read-only, pass ``SNDRV_CTL_ELEM_ACCESS_READ``25132513+instead. In this case, you don't have to define the ``put`` callback.25142514+Similarly, when the control is write-only (although it's a rare case),25152515+you can use the ``WRITE`` flag instead, and you don't need the ``get``25162516+callback.25172517+25182518+If the control value changes frequently (e.g. the VU meter),25192519+``VOLATILE`` flag should be given. This means that the control may be25202520+changed without `Change notification`_. Applications should poll such25212521+a control constantly.25222522+25232523+When the control is inactive, set the ``INACTIVE`` flag, too. There are25242524+``LOCK`` and ``OWNER`` flags to change the write permissions.25252525+25262526+Control Callbacks25272527+-----------------25282528+25292529+info callback25302530+~~~~~~~~~~~~~25312531+25322532+The ``info`` callback is used to get detailed information on this25332533+control. This must store the values of the given :c:type:`struct25342534+snd_ctl_elem_info <snd_ctl_elem_info>` object. For example,25352535+for a boolean control with a single element:25362536+25372537+::25382538+25392539+25402540+ static int snd_myctl_mono_info(struct snd_kcontrol *kcontrol,25412541+ struct snd_ctl_elem_info *uinfo)25422542+ {25432543+ uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;25442544+ uinfo->count = 1;25452545+ uinfo->value.integer.min = 0;25462546+ uinfo->value.integer.max = 1;25472547+ return 0;25482548+ }25492549+25502550+25512551+25522552+The ``type`` field specifies the type of the control. There are25532553+``BOOLEAN``, ``INTEGER``, ``ENUMERATED``, ``BYTES``, ``IEC958`` and25542554+``INTEGER64``. The ``count`` field specifies the number of elements in25552555+this control. For example, a stereo volume would have count = 2. The25562556+``value`` field is a union, and the values stored are depending on the25572557+type. The boolean and integer types are identical.25582558+25592559+The enumerated type is a bit different from others. You'll need to set25602560+the string for the currently given item index.25612561+25622562+::25632563+25642564+ static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,25652565+ struct snd_ctl_elem_info *uinfo)25662566+ {25672567+ static char *texts[4] = {25682568+ "First", "Second", "Third", "Fourth"25692569+ };25702570+ uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;25712571+ uinfo->count = 1;25722572+ uinfo->value.enumerated.items = 4;25732573+ if (uinfo->value.enumerated.item > 3)25742574+ uinfo->value.enumerated.item = 3;25752575+ strcpy(uinfo->value.enumerated.name,25762576+ texts[uinfo->value.enumerated.item]);25772577+ return 0;25782578+ }25792579+25802580+The above callback can be simplified with a helper function,25812581+:c:func:`snd_ctl_enum_info()`. The final code looks like below.25822582+(You can pass ``ARRAY_SIZE(texts)`` instead of 4 in the third argument;25832583+it's a matter of taste.)25842584+25852585+::25862586+25872587+ static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,25882588+ struct snd_ctl_elem_info *uinfo)25892589+ {25902590+ static char *texts[4] = {25912591+ "First", "Second", "Third", "Fourth"25922592+ };25932593+ return snd_ctl_enum_info(uinfo, 1, 4, texts);25942594+ }25952595+25962596+25972597+Some common info callbacks are available for your convenience:25982598+:c:func:`snd_ctl_boolean_mono_info()` and25992599+:c:func:`snd_ctl_boolean_stereo_info()`. Obviously, the former26002600+is an info callback for a mono channel boolean item, just like26012601+:c:func:`snd_myctl_mono_info()` above, and the latter is for a26022602+stereo channel boolean item.26032603+26042604+get callback26052605+~~~~~~~~~~~~26062606+26072607+This callback is used to read the current value of the control and to26082608+return to user-space.26092609+26102610+For example,26112611+26122612+::26132613+26142614+26152615+ static int snd_myctl_get(struct snd_kcontrol *kcontrol,26162616+ struct snd_ctl_elem_value *ucontrol)26172617+ {26182618+ struct mychip *chip = snd_kcontrol_chip(kcontrol);26192619+ ucontrol->value.integer.value[0] = get_some_value(chip);26202620+ return 0;26212621+ }26222622+26232623+26242624+26252625+The ``value`` field depends on the type of control as well as on the26262626+info callback. For example, the sb driver uses this field to store the26272627+register offset, the bit-shift and the bit-mask. The ``private_value``26282628+field is set as follows:26292629+26302630+::26312631+26322632+ .private_value = reg | (shift << 16) | (mask << 24)26332633+26342634+and is retrieved in callbacks like26352635+26362636+::26372637+26382638+ static int snd_sbmixer_get_single(struct snd_kcontrol *kcontrol,26392639+ struct snd_ctl_elem_value *ucontrol)26402640+ {26412641+ int reg = kcontrol->private_value & 0xff;26422642+ int shift = (kcontrol->private_value >> 16) & 0xff;26432643+ int mask = (kcontrol->private_value >> 24) & 0xff;26442644+ ....26452645+ }26462646+26472647+In the ``get`` callback, you have to fill all the elements if the26482648+control has more than one elements, i.e. ``count > 1``. In the example26492649+above, we filled only one element (``value.integer.value[0]``) since26502650+it's assumed as ``count = 1``.26512651+26522652+put callback26532653+~~~~~~~~~~~~26542654+26552655+This callback is used to write a value from user-space.26562656+26572657+For example,26582658+26592659+::26602660+26612661+26622662+ static int snd_myctl_put(struct snd_kcontrol *kcontrol,26632663+ struct snd_ctl_elem_value *ucontrol)26642664+ {26652665+ struct mychip *chip = snd_kcontrol_chip(kcontrol);26662666+ int changed = 0;26672667+ if (chip->current_value !=26682668+ ucontrol->value.integer.value[0]) {26692669+ change_current_value(chip,26702670+ ucontrol->value.integer.value[0]);26712671+ changed = 1;26722672+ }26732673+ return changed;26742674+ }26752675+26762676+26772677+26782678+As seen above, you have to return 1 if the value is changed. If the26792679+value is not changed, return 0 instead. If any fatal error happens,26802680+return a negative error code as usual.26812681+26822682+As in the ``get`` callback, when the control has more than one26832683+elements, all elements must be evaluated in this callback, too.26842684+26852685+Callbacks are not atomic26862686+~~~~~~~~~~~~~~~~~~~~~~~~26872687+26882688+All these three callbacks are basically not atomic.26892689+26902690+Control Constructor26912691+-------------------26922692+26932693+When everything is ready, finally we can create a new control. To create26942694+a control, there are two functions to be called,26952695+:c:func:`snd_ctl_new1()` and :c:func:`snd_ctl_add()`.26962696+26972697+In the simplest way, you can do like this:26982698+26992699+::27002700+27012701+ err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip));27022702+ if (err < 0)27032703+ return err;27042704+27052705+where ``my_control`` is the :c:type:`struct snd_kcontrol_new27062706+<snd_kcontrol_new>` object defined above, and chip is the object27072707+pointer to be passed to kcontrol->private_data which can be referred27082708+to in callbacks.27092709+27102710+:c:func:`snd_ctl_new1()` allocates a new :c:type:`struct27112711+snd_kcontrol <snd_kcontrol>` instance, and27122712+:c:func:`snd_ctl_add()` assigns the given control component to the27132713+card.27142714+27152715+Change Notification27162716+-------------------27172717+27182718+If you need to change and update a control in the interrupt routine, you27192719+can call :c:func:`snd_ctl_notify()`. For example,27202720+27212721+::27222722+27232723+ snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);27242724+27252725+This function takes the card pointer, the event-mask, and the control id27262726+pointer for the notification. The event-mask specifies the types of27272727+notification, for example, in the above example, the change of control27282728+values is notified. The id pointer is the pointer of :c:type:`struct27292729+snd_ctl_elem_id <snd_ctl_elem_id>` to be notified. You can27302730+find some examples in ``es1938.c`` or ``es1968.c`` for hardware volume27312731+interrupts.27322732+27332733+Metadata27342734+--------27352735+27362736+To provide information about the dB values of a mixer control, use on of27372737+the ``DECLARE_TLV_xxx`` macros from ``<sound/tlv.h>`` to define a27382738+variable containing this information, set the ``tlv.p`` field to point to27392739+this variable, and include the ``SNDRV_CTL_ELEM_ACCESS_TLV_READ`` flag27402740+in the ``access`` field; like this:27412741+27422742+::27432743+27442744+ static DECLARE_TLV_DB_SCALE(db_scale_my_control, -4050, 150, 0);27452745+27462746+ static struct snd_kcontrol_new my_control = {27472747+ ...27482748+ .access = SNDRV_CTL_ELEM_ACCESS_READWRITE |27492749+ SNDRV_CTL_ELEM_ACCESS_TLV_READ,27502750+ ...27512751+ .tlv.p = db_scale_my_control,27522752+ };27532753+27542754+27552755+The :c:func:`DECLARE_TLV_DB_SCALE()` macro defines information27562756+about a mixer control where each step in the control's value changes the27572757+dB value by a constant dB amount. The first parameter is the name of the27582758+variable to be defined. The second parameter is the minimum value, in27592759+units of 0.01 dB. The third parameter is the step size, in units of 0.0127602760+dB. Set the fourth parameter to 1 if the minimum value actually mutes27612761+the control.27622762+27632763+The :c:func:`DECLARE_TLV_DB_LINEAR()` macro defines information27642764+about a mixer control where the control's value affects the output27652765+linearly. The first parameter is the name of the variable to be defined.27662766+The second parameter is the minimum value, in units of 0.01 dB. The27672767+third parameter is the maximum value, in units of 0.01 dB. If the27682768+minimum value mutes the control, set the second parameter to27692769+``TLV_DB_GAIN_MUTE``.27702770+27712771+API for AC97 Codec27722772+==================27732773+27742774+General27752775+-------27762776+27772777+The ALSA AC97 codec layer is a well-defined one, and you don't have to27782778+write much code to control it. Only low-level control routines are27792779+necessary. The AC97 codec API is defined in ``<sound/ac97_codec.h>``.27802780+27812781+Full Code Example27822782+-----------------27832783+27842784+::27852785+27862786+ struct mychip {27872787+ ....27882788+ struct snd_ac97 *ac97;27892789+ ....27902790+ };27912791+27922792+ static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,27932793+ unsigned short reg)27942794+ {27952795+ struct mychip *chip = ac97->private_data;27962796+ ....27972797+ /* read a register value here from the codec */27982798+ return the_register_value;27992799+ }28002800+28012801+ static void snd_mychip_ac97_write(struct snd_ac97 *ac97,28022802+ unsigned short reg, unsigned short val)28032803+ {28042804+ struct mychip *chip = ac97->private_data;28052805+ ....28062806+ /* write the given register value to the codec */28072807+ }28082808+28092809+ static int snd_mychip_ac97(struct mychip *chip)28102810+ {28112811+ struct snd_ac97_bus *bus;28122812+ struct snd_ac97_template ac97;28132813+ int err;28142814+ static struct snd_ac97_bus_ops ops = {28152815+ .write = snd_mychip_ac97_write,28162816+ .read = snd_mychip_ac97_read,28172817+ };28182818+28192819+ err = snd_ac97_bus(chip->card, 0, &ops, NULL, &bus);28202820+ if (err < 0)28212821+ return err;28222822+ memset(&ac97, 0, sizeof(ac97));28232823+ ac97.private_data = chip;28242824+ return snd_ac97_mixer(bus, &ac97, &chip->ac97);28252825+ }28262826+28272827+28282828+AC97 Constructor28292829+----------------28302830+28312831+To create an ac97 instance, first call :c:func:`snd_ac97_bus()`28322832+with an ``ac97_bus_ops_t`` record with callback functions.28332833+28342834+::28352835+28362836+ struct snd_ac97_bus *bus;28372837+ static struct snd_ac97_bus_ops ops = {28382838+ .write = snd_mychip_ac97_write,28392839+ .read = snd_mychip_ac97_read,28402840+ };28412841+28422842+ snd_ac97_bus(card, 0, &ops, NULL, &pbus);28432843+28442844+The bus record is shared among all belonging ac97 instances.28452845+28462846+And then call :c:func:`snd_ac97_mixer()` with an :c:type:`struct28472847+snd_ac97_template <snd_ac97_template>` record together with28482848+the bus pointer created above.28492849+28502850+::28512851+28522852+ struct snd_ac97_template ac97;28532853+ int err;28542854+28552855+ memset(&ac97, 0, sizeof(ac97));28562856+ ac97.private_data = chip;28572857+ snd_ac97_mixer(bus, &ac97, &chip->ac97);28582858+28592859+where chip->ac97 is a pointer to a newly created ``ac97_t``28602860+instance. In this case, the chip pointer is set as the private data,28612861+so that the read/write callback functions can refer to this chip28622862+instance. This instance is not necessarily stored in the chip28632863+record. If you need to change the register values from the driver, or28642864+need the suspend/resume of ac97 codecs, keep this pointer to pass to28652865+the corresponding functions.28662866+28672867+AC97 Callbacks28682868+--------------28692869+28702870+The standard callbacks are ``read`` and ``write``. Obviously they28712871+correspond to the functions for read and write accesses to the28722872+hardware low-level codes.28732873+28742874+The ``read`` callback returns the register value specified in the28752875+argument.28762876+28772877+::28782878+28792879+ static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,28802880+ unsigned short reg)28812881+ {28822882+ struct mychip *chip = ac97->private_data;28832883+ ....28842884+ return the_register_value;28852885+ }28862886+28872887+Here, the chip can be cast from ``ac97->private_data``.28882888+28892889+Meanwhile, the ``write`` callback is used to set the register28902890+value28912891+28922892+::28932893+28942894+ static void snd_mychip_ac97_write(struct snd_ac97 *ac97,28952895+ unsigned short reg, unsigned short val)28962896+28972897+28982898+These callbacks are non-atomic like the control API callbacks.28992899+29002900+There are also other callbacks: ``reset``, ``wait`` and ``init``.29012901+29022902+The ``reset`` callback is used to reset the codec. If the chip29032903+requires a special kind of reset, you can define this callback.29042904+29052905+The ``wait`` callback is used to add some waiting time in the standard29062906+initialization of the codec. If the chip requires the extra waiting29072907+time, define this callback.29082908+29092909+The ``init`` callback is used for additional initialization of the29102910+codec.29112911+29122912+Updating Registers in The Driver29132913+--------------------------------29142914+29152915+If you need to access to the codec from the driver, you can call the29162916+following functions: :c:func:`snd_ac97_write()`,29172917+:c:func:`snd_ac97_read()`, :c:func:`snd_ac97_update()` and29182918+:c:func:`snd_ac97_update_bits()`.29192919+29202920+Both :c:func:`snd_ac97_write()` and29212921+:c:func:`snd_ac97_update()` functions are used to set a value to29222922+the given register (``AC97_XXX``). The difference between them is that29232923+:c:func:`snd_ac97_update()` doesn't write a value if the given29242924+value has been already set, while :c:func:`snd_ac97_write()`29252925+always rewrites the value.29262926+29272927+::29282928+29292929+ snd_ac97_write(ac97, AC97_MASTER, 0x8080);29302930+ snd_ac97_update(ac97, AC97_MASTER, 0x8080);29312931+29322932+:c:func:`snd_ac97_read()` is used to read the value of the given29332933+register. For example,29342934+29352935+::29362936+29372937+ value = snd_ac97_read(ac97, AC97_MASTER);29382938+29392939+:c:func:`snd_ac97_update_bits()` is used to update some bits in29402940+the given register.29412941+29422942+::29432943+29442944+ snd_ac97_update_bits(ac97, reg, mask, value);29452945+29462946+Also, there is a function to change the sample rate (of a given register29472947+such as ``AC97_PCM_FRONT_DAC_RATE``) when VRA or DRA is supported by the29482948+codec: :c:func:`snd_ac97_set_rate()`.29492949+29502950+::29512951+29522952+ snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);29532953+29542954+29552955+The following registers are available to set the rate:29562956+``AC97_PCM_MIC_ADC_RATE``, ``AC97_PCM_FRONT_DAC_RATE``,29572957+``AC97_PCM_LR_ADC_RATE``, ``AC97_SPDIF``. When ``AC97_SPDIF`` is29582958+specified, the register is not really changed but the corresponding29592959+IEC958 status bits will be updated.29602960+29612961+Clock Adjustment29622962+----------------29632963+29642964+In some chips, the clock of the codec isn't 48000 but using a PCI clock29652965+(to save a quartz!). In this case, change the field ``bus->clock`` to29662966+the corresponding value. For example, intel8x0 and es1968 drivers have29672967+their own function to read from the clock.29682968+29692969+Proc Files29702970+----------29712971+29722972+The ALSA AC97 interface will create a proc file such as29732973+``/proc/asound/card0/codec97#0/ac97#0-0`` and ``ac97#0-0+regs``. You29742974+can refer to these files to see the current status and registers of29752975+the codec.29762976+29772977+Multiple Codecs29782978+---------------29792979+29802980+When there are several codecs on the same card, you need to call29812981+:c:func:`snd_ac97_mixer()` multiple times with ``ac97.num=1`` or29822982+greater. The ``num`` field specifies the codec number.29832983+29842984+If you set up multiple codecs, you either need to write different29852985+callbacks for each codec or check ``ac97->num`` in the callback29862986+routines.29872987+29882988+MIDI (MPU401-UART) Interface29892989+============================29902990+29912991+General29922992+-------29932993+29942994+Many soundcards have built-in MIDI (MPU401-UART) interfaces. When the29952995+soundcard supports the standard MPU401-UART interface, most likely you29962996+can use the ALSA MPU401-UART API. The MPU401-UART API is defined in29972997+``<sound/mpu401.h>``.29982998+29992999+Some soundchips have a similar but slightly different implementation of30003000+mpu401 stuff. For example, emu10k1 has its own mpu401 routines.30013001+30023002+MIDI Constructor30033003+----------------30043004+30053005+To create a rawmidi object, call :c:func:`snd_mpu401_uart_new()`.30063006+30073007+::30083008+30093009+ struct snd_rawmidi *rmidi;30103010+ snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, info_flags,30113011+ irq, &rmidi);30123012+30133013+30143014+The first argument is the card pointer, and the second is the index of30153015+this component. You can create up to 8 rawmidi devices.30163016+30173017+The third argument is the type of the hardware, ``MPU401_HW_XXX``. If30183018+it's not a special one, you can use ``MPU401_HW_MPU401``.30193019+30203020+The 4th argument is the I/O port address. Many backward-compatible30213021+MPU401 have an I/O port such as 0x330. Or, it might be a part of its own30223022+PCI I/O region. It depends on the chip design.30233023+30243024+The 5th argument is a bitflag for additional information. When the I/O30253025+port address above is part of the PCI I/O region, the MPU401 I/O port30263026+might have been already allocated (reserved) by the driver itself. In30273027+such a case, pass a bit flag ``MPU401_INFO_INTEGRATED``, and the30283028+mpu401-uart layer will allocate the I/O ports by itself.30293029+30303030+When the controller supports only the input or output MIDI stream, pass30313031+the ``MPU401_INFO_INPUT`` or ``MPU401_INFO_OUTPUT`` bitflag,30323032+respectively. Then the rawmidi instance is created as a single stream.30333033+30343034+``MPU401_INFO_MMIO`` bitflag is used to change the access method to MMIO30353035+(via readb and writeb) instead of iob and outb. In this case, you have30363036+to pass the iomapped address to :c:func:`snd_mpu401_uart_new()`.30373037+30383038+When ``MPU401_INFO_TX_IRQ`` is set, the output stream isn't checked in30393039+the default interrupt handler. The driver needs to call30403040+:c:func:`snd_mpu401_uart_interrupt_tx()` by itself to start30413041+processing the output stream in the irq handler.30423042+30433043+If the MPU-401 interface shares its interrupt with the other logical30443044+devices on the card, set ``MPU401_INFO_IRQ_HOOK`` (see30453045+`below <#MIDI-Interrupt-Handler>`__).30463046+30473047+Usually, the port address corresponds to the command port and port + 130483048+corresponds to the data port. If not, you may change the ``cport``30493049+field of :c:type:`struct snd_mpu401 <snd_mpu401>` manually afterward.30503050+However, :c:type:`struct snd_mpu401 <snd_mpu401>` pointer is30513051+not returned explicitly by :c:func:`snd_mpu401_uart_new()`. You30523052+need to cast ``rmidi->private_data`` to :c:type:`struct snd_mpu40130533053+<snd_mpu401>` explicitly,30543054+30553055+::30563056+30573057+ struct snd_mpu401 *mpu;30583058+ mpu = rmidi->private_data;30593059+30603060+and reset the ``cport`` as you like:30613061+30623062+::30633063+30643064+ mpu->cport = my_own_control_port;30653065+30663066+The 6th argument specifies the ISA irq number that will be allocated. If30673067+no interrupt is to be allocated (because your code is already allocating30683068+a shared interrupt, or because the device does not use interrupts), pass30693069+-1 instead. For a MPU-401 device without an interrupt, a polling timer30703070+will be used instead.30713071+30723072+MIDI Interrupt Handler30733073+----------------------30743074+30753075+When the interrupt is allocated in30763076+:c:func:`snd_mpu401_uart_new()`, an exclusive ISA interrupt30773077+handler is automatically used, hence you don't have anything else to do30783078+than creating the mpu401 stuff. Otherwise, you have to set30793079+``MPU401_INFO_IRQ_HOOK``, and call30803080+:c:func:`snd_mpu401_uart_interrupt()` explicitly from your own30813081+interrupt handler when it has determined that a UART interrupt has30823082+occurred.30833083+30843084+In this case, you need to pass the private_data of the returned rawmidi30853085+object from :c:func:`snd_mpu401_uart_new()` as the second30863086+argument of :c:func:`snd_mpu401_uart_interrupt()`.30873087+30883088+::30893089+30903090+ snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);30913091+30923092+30933093+RawMIDI Interface30943094+=================30953095+30963096+Overview30973097+--------30983098+30993099+The raw MIDI interface is used for hardware MIDI ports that can be31003100+accessed as a byte stream. It is not used for synthesizer chips that do31013101+not directly understand MIDI.31023102+31033103+ALSA handles file and buffer management. All you have to do is to write31043104+some code to move data between the buffer and the hardware.31053105+31063106+The rawmidi API is defined in ``<sound/rawmidi.h>``.31073107+31083108+RawMIDI Constructor31093109+-------------------31103110+31113111+To create a rawmidi device, call the :c:func:`snd_rawmidi_new()`31123112+function:31133113+31143114+::31153115+31163116+ struct snd_rawmidi *rmidi;31173117+ err = snd_rawmidi_new(chip->card, "MyMIDI", 0, outs, ins, &rmidi);31183118+ if (err < 0)31193119+ return err;31203120+ rmidi->private_data = chip;31213121+ strcpy(rmidi->name, "My MIDI");31223122+ rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |31233123+ SNDRV_RAWMIDI_INFO_INPUT |31243124+ SNDRV_RAWMIDI_INFO_DUPLEX;31253125+31263126+The first argument is the card pointer, the second argument is the ID31273127+string.31283128+31293129+The third argument is the index of this component. You can create up to31303130+8 rawmidi devices.31313131+31323132+The fourth and fifth arguments are the number of output and input31333133+substreams, respectively, of this device (a substream is the equivalent31343134+of a MIDI port).31353135+31363136+Set the ``info_flags`` field to specify the capabilities of the31373137+device. Set ``SNDRV_RAWMIDI_INFO_OUTPUT`` if there is at least one31383138+output port, ``SNDRV_RAWMIDI_INFO_INPUT`` if there is at least one31393139+input port, and ``SNDRV_RAWMIDI_INFO_DUPLEX`` if the device can handle31403140+output and input at the same time.31413141+31423142+After the rawmidi device is created, you need to set the operators31433143+(callbacks) for each substream. There are helper functions to set the31443144+operators for all the substreams of a device:31453145+31463146+::31473147+31483148+ snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_mymidi_output_ops);31493149+ snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_mymidi_input_ops);31503150+31513151+The operators are usually defined like this:31523152+31533153+::31543154+31553155+ static struct snd_rawmidi_ops snd_mymidi_output_ops = {31563156+ .open = snd_mymidi_output_open,31573157+ .close = snd_mymidi_output_close,31583158+ .trigger = snd_mymidi_output_trigger,31593159+ };31603160+31613161+These callbacks are explained in the `RawMIDI Callbacks`_ section.31623162+31633163+If there are more than one substream, you should give a unique name to31643164+each of them:31653165+31663166+::31673167+31683168+ struct snd_rawmidi_substream *substream;31693169+ list_for_each_entry(substream,31703170+ &rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,31713171+ list {31723172+ sprintf(substream->name, "My MIDI Port %d", substream->number + 1);31733173+ }31743174+ /* same for SNDRV_RAWMIDI_STREAM_INPUT */31753175+31763176+RawMIDI Callbacks31773177+-----------------31783178+31793179+In all the callbacks, the private data that you've set for the rawmidi31803180+device can be accessed as ``substream->rmidi->private_data``.31813181+31823182+If there is more than one port, your callbacks can determine the port31833183+index from the struct snd_rawmidi_substream data passed to each31843184+callback:31853185+31863186+::31873187+31883188+ struct snd_rawmidi_substream *substream;31893189+ int index = substream->number;31903190+31913191+RawMIDI open callback31923192+~~~~~~~~~~~~~~~~~~~~~31933193+31943194+::31953195+31963196+ static int snd_xxx_open(struct snd_rawmidi_substream *substream);31973197+31983198+31993199+This is called when a substream is opened. You can initialize the32003200+hardware here, but you shouldn't start transmitting/receiving data yet.32013201+32023202+RawMIDI close callback32033203+~~~~~~~~~~~~~~~~~~~~~~32043204+32053205+::32063206+32073207+ static int snd_xxx_close(struct snd_rawmidi_substream *substream);32083208+32093209+Guess what.32103210+32113211+The ``open`` and ``close`` callbacks of a rawmidi device are32123212+serialized with a mutex, and can sleep.32133213+32143214+Rawmidi trigger callback for output substreams32153215+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~32163216+32173217+::32183218+32193219+ static void snd_xxx_output_trigger(struct snd_rawmidi_substream *substream, int up);32203220+32213221+32223222+This is called with a nonzero ``up`` parameter when there is some data32233223+in the substream buffer that must be transmitted.32243224+32253225+To read data from the buffer, call32263226+:c:func:`snd_rawmidi_transmit_peek()`. It will return the number32273227+of bytes that have been read; this will be less than the number of bytes32283228+requested when there are no more data in the buffer. After the data have32293229+been transmitted successfully, call32303230+:c:func:`snd_rawmidi_transmit_ack()` to remove the data from the32313231+substream buffer:32323232+32333233+::32343234+32353235+ unsigned char data;32363236+ while (snd_rawmidi_transmit_peek(substream, &data, 1) == 1) {32373237+ if (snd_mychip_try_to_transmit(data))32383238+ snd_rawmidi_transmit_ack(substream, 1);32393239+ else32403240+ break; /* hardware FIFO full */32413241+ }32423242+32433243+If you know beforehand that the hardware will accept data, you can use32443244+the :c:func:`snd_rawmidi_transmit()` function which reads some32453245+data and removes them from the buffer at once:32463246+32473247+::32483248+32493249+ while (snd_mychip_transmit_possible()) {32503250+ unsigned char data;32513251+ if (snd_rawmidi_transmit(substream, &data, 1) != 1)32523252+ break; /* no more data */32533253+ snd_mychip_transmit(data);32543254+ }32553255+32563256+If you know beforehand how many bytes you can accept, you can use a32573257+buffer size greater than one with the32583258+:c:func:`snd_rawmidi_transmit\*()` functions.32593259+32603260+The ``trigger`` callback must not sleep. If the hardware FIFO is full32613261+before the substream buffer has been emptied, you have to continue32623262+transmitting data later, either in an interrupt handler, or with a32633263+timer if the hardware doesn't have a MIDI transmit interrupt.32643264+32653265+The ``trigger`` callback is called with a zero ``up`` parameter when32663266+the transmission of data should be aborted.32673267+32683268+RawMIDI trigger callback for input substreams32693269+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~32703270+32713271+::32723272+32733273+ static void snd_xxx_input_trigger(struct snd_rawmidi_substream *substream, int up);32743274+32753275+32763276+This is called with a nonzero ``up`` parameter to enable receiving data,32773277+or with a zero ``up`` parameter do disable receiving data.32783278+32793279+The ``trigger`` callback must not sleep; the actual reading of data32803280+from the device is usually done in an interrupt handler.32813281+32823282+When data reception is enabled, your interrupt handler should call32833283+:c:func:`snd_rawmidi_receive()` for all received data:32843284+32853285+::32863286+32873287+ void snd_mychip_midi_interrupt(...)32883288+ {32893289+ while (mychip_midi_available()) {32903290+ unsigned char data;32913291+ data = mychip_midi_read();32923292+ snd_rawmidi_receive(substream, &data, 1);32933293+ }32943294+ }32953295+32963296+32973297+drain callback32983298+~~~~~~~~~~~~~~32993299+33003300+::33013301+33023302+ static void snd_xxx_drain(struct snd_rawmidi_substream *substream);33033303+33043304+33053305+This is only used with output substreams. This function should wait33063306+until all data read from the substream buffer have been transmitted.33073307+This ensures that the device can be closed and the driver unloaded33083308+without losing data.33093309+33103310+This callback is optional. If you do not set ``drain`` in the struct33113311+snd_rawmidi_ops structure, ALSA will simply wait for 50 milliseconds33123312+instead.33133313+33143314+Miscellaneous Devices33153315+=====================33163316+33173317+FM OPL333183318+-------33193319+33203320+The FM OPL3 is still used in many chips (mainly for backward33213321+compatibility). ALSA has a nice OPL3 FM control layer, too. The OPL3 API33223322+is defined in ``<sound/opl3.h>``.33233323+33243324+FM registers can be directly accessed through the direct-FM API, defined33253325+in ``<sound/asound_fm.h>``. In ALSA native mode, FM registers are33263326+accessed through the Hardware-Dependent Device direct-FM extension API,33273327+whereas in OSS compatible mode, FM registers can be accessed with the33283328+OSS direct-FM compatible API in ``/dev/dmfmX`` device.33293329+33303330+To create the OPL3 component, you have two functions to call. The first33313331+one is a constructor for the ``opl3_t`` instance.33323332+33333333+::33343334+33353335+ struct snd_opl3 *opl3;33363336+ snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,33373337+ integrated, &opl3);33383338+33393339+The first argument is the card pointer, the second one is the left port33403340+address, and the third is the right port address. In most cases, the33413341+right port is placed at the left port + 2.33423342+33433343+The fourth argument is the hardware type.33443344+33453345+When the left and right ports have been already allocated by the card33463346+driver, pass non-zero to the fifth argument (``integrated``). Otherwise,33473347+the opl3 module will allocate the specified ports by itself.33483348+33493349+When the accessing the hardware requires special method instead of the33503350+standard I/O access, you can create opl3 instance separately with33513351+:c:func:`snd_opl3_new()`.33523352+33533353+::33543354+33553355+ struct snd_opl3 *opl3;33563356+ snd_opl3_new(card, OPL3_HW_OPL3_XXX, &opl3);33573357+33583358+Then set ``command``, ``private_data`` and ``private_free`` for the33593359+private access function, the private data and the destructor. The33603360+``l_port`` and ``r_port`` are not necessarily set. Only the command33613361+must be set properly. You can retrieve the data from the33623362+``opl3->private_data`` field. 33633363+33643364+After creating the opl3 instance via :c:func:`snd_opl3_new()`,33653365+call :c:func:`snd_opl3_init()` to initialize the chip to the33663366+proper state. Note that :c:func:`snd_opl3_create()` always calls33673367+it internally.33683368+33693369+If the opl3 instance is created successfully, then create a hwdep device33703370+for this opl3.33713371+33723372+::33733373+33743374+ struct snd_hwdep *opl3hwdep;33753375+ snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);33763376+33773377+The first argument is the ``opl3_t`` instance you created, and the33783378+second is the index number, usually 0.33793379+33803380+The third argument is the index-offset for the sequencer client assigned33813381+to the OPL3 port. When there is an MPU401-UART, give 1 for here (UART33823382+always takes 0).33833383+33843384+Hardware-Dependent Devices33853385+--------------------------33863386+33873387+Some chips need user-space access for special controls or for loading33883388+the micro code. In such a case, you can create a hwdep33893389+(hardware-dependent) device. The hwdep API is defined in33903390+``<sound/hwdep.h>``. You can find examples in opl3 driver or33913391+``isa/sb/sb16_csp.c``.33923392+33933393+The creation of the ``hwdep`` instance is done via33943394+:c:func:`snd_hwdep_new()`.33953395+33963396+::33973397+33983398+ struct snd_hwdep *hw;33993399+ snd_hwdep_new(card, "My HWDEP", 0, &hw);34003400+34013401+where the third argument is the index number.34023402+34033403+You can then pass any pointer value to the ``private_data``. If you34043404+assign a private data, you should define the destructor, too. The34053405+destructor function is set in the ``private_free`` field.34063406+34073407+::34083408+34093409+ struct mydata *p = kmalloc(sizeof(*p), GFP_KERNEL);34103410+ hw->private_data = p;34113411+ hw->private_free = mydata_free;34123412+34133413+and the implementation of the destructor would be:34143414+34153415+::34163416+34173417+ static void mydata_free(struct snd_hwdep *hw)34183418+ {34193419+ struct mydata *p = hw->private_data;34203420+ kfree(p);34213421+ }34223422+34233423+The arbitrary file operations can be defined for this instance. The file34243424+operators are defined in the ``ops`` table. For example, assume that34253425+this chip needs an ioctl.34263426+34273427+::34283428+34293429+ hw->ops.open = mydata_open;34303430+ hw->ops.ioctl = mydata_ioctl;34313431+ hw->ops.release = mydata_release;34323432+34333433+And implement the callback functions as you like.34343434+34353435+IEC958 (S/PDIF)34363436+---------------34373437+34383438+Usually the controls for IEC958 devices are implemented via the control34393439+interface. There is a macro to compose a name string for IEC95834403440+controls, :c:func:`SNDRV_CTL_NAME_IEC958()` defined in34413441+``<include/asound.h>``.34423442+34433443+There are some standard controls for IEC958 status bits. These controls34443444+use the type ``SNDRV_CTL_ELEM_TYPE_IEC958``, and the size of element is34453445+fixed as 4 bytes array (value.iec958.status[x]). For the ``info``34463446+callback, you don't specify the value field for this type (the count34473447+field must be set, though).34483448+34493449+“IEC958 Playback Con Mask” is used to return the bit-mask for the IEC95834503450+status bits of consumer mode. Similarly, “IEC958 Playback Pro Mask”34513451+returns the bitmask for professional mode. They are read-only controls,34523452+and are defined as MIXER controls (iface =34533453+``SNDRV_CTL_ELEM_IFACE_MIXER``).34543454+34553455+Meanwhile, “IEC958 Playback Default” control is defined for getting and34563456+setting the current default IEC958 bits. Note that this one is usually34573457+defined as a PCM control (iface = ``SNDRV_CTL_ELEM_IFACE_PCM``),34583458+although in some places it's defined as a MIXER control.34593459+34603460+In addition, you can define the control switches to enable/disable or to34613461+set the raw bit mode. The implementation will depend on the chip, but34623462+the control should be named as “IEC958 xxx”, preferably using the34633463+:c:func:`SNDRV_CTL_NAME_IEC958()` macro.34643464+34653465+You can find several cases, for example, ``pci/emu10k1``,34663466+``pci/ice1712``, or ``pci/cmipci.c``.34673467+34683468+Buffer and Memory Management34693469+============================34703470+34713471+Buffer Types34723472+------------34733473+34743474+ALSA provides several different buffer allocation functions depending on34753475+the bus and the architecture. All these have a consistent API. The34763476+allocation of physically-contiguous pages is done via34773477+:c:func:`snd_malloc_xxx_pages()` function, where xxx is the bus34783478+type.34793479+34803480+The allocation of pages with fallback is34813481+:c:func:`snd_malloc_xxx_pages_fallback()`. This function tries34823482+to allocate the specified pages but if the pages are not available, it34833483+tries to reduce the page sizes until enough space is found.34843484+34853485+The release the pages, call :c:func:`snd_free_xxx_pages()`34863486+function.34873487+34883488+Usually, ALSA drivers try to allocate and reserve a large contiguous34893489+physical space at the time the module is loaded for the later use. This34903490+is called “pre-allocation”. As already written, you can call the34913491+following function at pcm instance construction time (in the case of PCI34923492+bus).34933493+34943494+::34953495+34963496+ snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,34973497+ snd_dma_pci_data(pci), size, max);34983498+34993499+where ``size`` is the byte size to be pre-allocated and the ``max`` is35003500+the maximum size to be changed via the ``prealloc`` proc file. The35013501+allocator will try to get an area as large as possible within the35023502+given size.35033503+35043504+The second argument (type) and the third argument (device pointer) are35053505+dependent on the bus. In the case of the ISA bus, pass35063506+:c:func:`snd_dma_isa_data()` as the third argument with35073507+``SNDRV_DMA_TYPE_DEV`` type. For the continuous buffer unrelated to the35083508+bus can be pre-allocated with ``SNDRV_DMA_TYPE_CONTINUOUS`` type and the35093509+``snd_dma_continuous_data(GFP_KERNEL)`` device pointer, where35103510+``GFP_KERNEL`` is the kernel allocation flag to use. For the PCI35113511+scatter-gather buffers, use ``SNDRV_DMA_TYPE_DEV_SG`` with35123512+``snd_dma_pci_data(pci)`` (see the `Non-Contiguous Buffers`_35133513+section).35143514+35153515+Once the buffer is pre-allocated, you can use the allocator in the35163516+``hw_params`` callback:35173517+35183518+::35193519+35203520+ snd_pcm_lib_malloc_pages(substream, size);35213521+35223522+Note that you have to pre-allocate to use this function.35233523+35243524+External Hardware Buffers35253525+-------------------------35263526+35273527+Some chips have their own hardware buffers and the DMA transfer from the35283528+host memory is not available. In such a case, you need to either 1)35293529+copy/set the audio data directly to the external hardware buffer, or 2)35303530+make an intermediate buffer and copy/set the data from it to the35313531+external hardware buffer in interrupts (or in tasklets, preferably).35323532+35333533+The first case works fine if the external hardware buffer is large35343534+enough. This method doesn't need any extra buffers and thus is more35353535+effective. You need to define the ``copy`` and ``silence`` callbacks35363536+for the data transfer. However, there is a drawback: it cannot be35373537+mmapped. The examples are GUS's GF1 PCM or emu8000's wavetable PCM.35383538+35393539+The second case allows for mmap on the buffer, although you have to35403540+handle an interrupt or a tasklet to transfer the data from the35413541+intermediate buffer to the hardware buffer. You can find an example in35423542+the vxpocket driver.35433543+35443544+Another case is when the chip uses a PCI memory-map region for the35453545+buffer instead of the host memory. In this case, mmap is available only35463546+on certain architectures like the Intel one. In non-mmap mode, the data35473547+cannot be transferred as in the normal way. Thus you need to define the35483548+``copy`` and ``silence`` callbacks as well, as in the cases above. The35493549+examples are found in ``rme32.c`` and ``rme96.c``.35503550+35513551+The implementation of the ``copy`` and ``silence`` callbacks depends35523552+upon whether the hardware supports interleaved or non-interleaved35533553+samples. The ``copy`` callback is defined like below, a bit35543554+differently depending whether the direction is playback or capture:35553555+35563556+::35573557+35583558+ static int playback_copy(struct snd_pcm_substream *substream, int channel,35593559+ snd_pcm_uframes_t pos, void *src, snd_pcm_uframes_t count);35603560+ static int capture_copy(struct snd_pcm_substream *substream, int channel,35613561+ snd_pcm_uframes_t pos, void *dst, snd_pcm_uframes_t count);35623562+35633563+In the case of interleaved samples, the second argument (``channel``) is35643564+not used. The third argument (``pos``) points the current position35653565+offset in frames.35663566+35673567+The meaning of the fourth argument is different between playback and35683568+capture. For playback, it holds the source data pointer, and for35693569+capture, it's the destination data pointer.35703570+35713571+The last argument is the number of frames to be copied.35723572+35733573+What you have to do in this callback is again different between playback35743574+and capture directions. In the playback case, you copy the given amount35753575+of data (``count``) at the specified pointer (``src``) to the specified35763576+offset (``pos``) on the hardware buffer. When coded like memcpy-like35773577+way, the copy would be like:35783578+35793579+::35803580+35813581+ my_memcpy(my_buffer + frames_to_bytes(runtime, pos), src,35823582+ frames_to_bytes(runtime, count));35833583+35843584+For the capture direction, you copy the given amount of data (``count``)35853585+at the specified offset (``pos``) on the hardware buffer to the35863586+specified pointer (``dst``).35873587+35883588+::35893589+35903590+ my_memcpy(dst, my_buffer + frames_to_bytes(runtime, pos),35913591+ frames_to_bytes(runtime, count));35923592+35933593+Note that both the position and the amount of data are given in frames.35943594+35953595+In the case of non-interleaved samples, the implementation will be a bit35963596+more complicated.35973597+35983598+You need to check the channel argument, and if it's -1, copy the whole35993599+channels. Otherwise, you have to copy only the specified channel. Please36003600+check ``isa/gus/gus_pcm.c`` as an example.36013601+36023602+The ``silence`` callback is also implemented in a similar way36033603+36043604+::36053605+36063606+ static int silence(struct snd_pcm_substream *substream, int channel,36073607+ snd_pcm_uframes_t pos, snd_pcm_uframes_t count);36083608+36093609+The meanings of arguments are the same as in the ``copy`` callback,36103610+although there is no ``src/dst`` argument. In the case of interleaved36113611+samples, the channel argument has no meaning, as well as on ``copy``36123612+callback.36133613+36143614+The role of ``silence`` callback is to set the given amount36153615+(``count``) of silence data at the specified offset (``pos``) on the36163616+hardware buffer. Suppose that the data format is signed (that is, the36173617+silent-data is 0), and the implementation using a memset-like function36183618+would be like: 36193619+36203620+::36213621+36223622+ my_memcpy(my_buffer + frames_to_bytes(runtime, pos), 0,36233623+ frames_to_bytes(runtime, count));36243624+36253625+In the case of non-interleaved samples, again, the implementation36263626+becomes a bit more complicated. See, for example, ``isa/gus/gus_pcm.c``.36273627+36283628+Non-Contiguous Buffers36293629+----------------------36303630+36313631+If your hardware supports the page table as in emu10k1 or the buffer36323632+descriptors as in via82xx, you can use the scatter-gather (SG) DMA. ALSA36333633+provides an interface for handling SG-buffers. The API is provided in36343634+``<sound/pcm.h>``.36353635+36363636+For creating the SG-buffer handler, call36373637+:c:func:`snd_pcm_lib_preallocate_pages()` or36383638+:c:func:`snd_pcm_lib_preallocate_pages_for_all()` with36393639+``SNDRV_DMA_TYPE_DEV_SG`` in the PCM constructor like other PCI36403640+pre-allocator. You need to pass ``snd_dma_pci_data(pci)``, where pci is36413641+the :c:type:`struct pci_dev <pci_dev>` pointer of the chip as36423642+well. The ``struct snd_sg_buf`` instance is created as36433643+``substream->dma_private``. You can cast the pointer like:36443644+36453645+::36463646+36473647+ struct snd_sg_buf *sgbuf = (struct snd_sg_buf *)substream->dma_private;36483648+36493649+Then call :c:func:`snd_pcm_lib_malloc_pages()` in the ``hw_params``36503650+callback as well as in the case of normal PCI buffer. The SG-buffer36513651+handler will allocate the non-contiguous kernel pages of the given size36523652+and map them onto the virtually contiguous memory. The virtual pointer36533653+is addressed in runtime->dma_area. The physical address36543654+(``runtime->dma_addr``) is set to zero, because the buffer is36553655+physically non-contiguous. The physical address table is set up in36563656+``sgbuf->table``. You can get the physical address at a certain offset36573657+via :c:func:`snd_pcm_sgbuf_get_addr()`.36583658+36593659+When a SG-handler is used, you need to set36603660+:c:func:`snd_pcm_sgbuf_ops_page()` as the ``page`` callback. (See36613661+`page callback`_ section.)36623662+36633663+To release the data, call :c:func:`snd_pcm_lib_free_pages()` in36643664+the ``hw_free`` callback as usual.36653665+36663666+Vmalloc'ed Buffers36673667+------------------36683668+36693669+It's possible to use a buffer allocated via :c:func:`vmalloc()`, for36703670+example, for an intermediate buffer. Since the allocated pages are not36713671+contiguous, you need to set the ``page`` callback to obtain the physical36723672+address at every offset.36733673+36743674+The implementation of ``page`` callback would be like this:36753675+36763676+::36773677+36783678+ #include <linux/vmalloc.h>36793679+36803680+ /* get the physical page pointer on the given offset */36813681+ static struct page *mychip_page(struct snd_pcm_substream *substream,36823682+ unsigned long offset)36833683+ {36843684+ void *pageptr = substream->runtime->dma_area + offset;36853685+ return vmalloc_to_page(pageptr);36863686+ }36873687+36883688+Proc Interface36893689+==============36903690+36913691+ALSA provides an easy interface for procfs. The proc files are very36923692+useful for debugging. I recommend you set up proc files if you write a36933693+driver and want to get a running status or register dumps. The API is36943694+found in ``<sound/info.h>``.36953695+36963696+To create a proc file, call :c:func:`snd_card_proc_new()`.36973697+36983698+::36993699+37003700+ struct snd_info_entry *entry;37013701+ int err = snd_card_proc_new(card, "my-file", &entry);37023702+37033703+where the second argument specifies the name of the proc file to be37043704+created. The above example will create a file ``my-file`` under the37053705+card directory, e.g. ``/proc/asound/card0/my-file``.37063706+37073707+Like other components, the proc entry created via37083708+:c:func:`snd_card_proc_new()` will be registered and released37093709+automatically in the card registration and release functions.37103710+37113711+When the creation is successful, the function stores a new instance in37123712+the pointer given in the third argument. It is initialized as a text37133713+proc file for read only. To use this proc file as a read-only text file37143714+as it is, set the read callback with a private data via37153715+:c:func:`snd_info_set_text_ops()`.37163716+37173717+::37183718+37193719+ snd_info_set_text_ops(entry, chip, my_proc_read);37203720+37213721+where the second argument (``chip``) is the private data to be used in37223722+the callbacks. The third parameter specifies the read buffer size and37233723+the fourth (``my_proc_read``) is the callback function, which is37243724+defined like37253725+37263726+::37273727+37283728+ static void my_proc_read(struct snd_info_entry *entry,37293729+ struct snd_info_buffer *buffer);37303730+37313731+In the read callback, use :c:func:`snd_iprintf()` for output37323732+strings, which works just like normal :c:func:`printf()`. For37333733+example,37343734+37353735+::37363736+37373737+ static void my_proc_read(struct snd_info_entry *entry,37383738+ struct snd_info_buffer *buffer)37393739+ {37403740+ struct my_chip *chip = entry->private_data;37413741+37423742+ snd_iprintf(buffer, "This is my chip!\n");37433743+ snd_iprintf(buffer, "Port = %ld\n", chip->port);37443744+ }37453745+37463746+The file permissions can be changed afterwards. As default, it's set as37473747+read only for all users. If you want to add write permission for the37483748+user (root as default), do as follows:37493749+37503750+::37513751+37523752+ entry->mode = S_IFREG | S_IRUGO | S_IWUSR;37533753+37543754+and set the write buffer size and the callback37553755+37563756+::37573757+37583758+ entry->c.text.write = my_proc_write;37593759+37603760+For the write callback, you can use :c:func:`snd_info_get_line()`37613761+to get a text line, and :c:func:`snd_info_get_str()` to retrieve37623762+a string from the line. Some examples are found in37633763+``core/oss/mixer_oss.c``, core/oss/and ``pcm_oss.c``.37643764+37653765+For a raw-data proc-file, set the attributes as follows:37663766+37673767+::37683768+37693769+ static struct snd_info_entry_ops my_file_io_ops = {37703770+ .read = my_file_io_read,37713771+ };37723772+37733773+ entry->content = SNDRV_INFO_CONTENT_DATA;37743774+ entry->private_data = chip;37753775+ entry->c.ops = &my_file_io_ops;37763776+ entry->size = 4096;37773777+ entry->mode = S_IFREG | S_IRUGO;37783778+37793779+For the raw data, ``size`` field must be set properly. This specifies37803780+the maximum size of the proc file access.37813781+37823782+The read/write callbacks of raw mode are more direct than the text mode.37833783+You need to use a low-level I/O functions such as37843784+:c:func:`copy_from/to_user()` to transfer the data.37853785+37863786+::37873787+37883788+ static ssize_t my_file_io_read(struct snd_info_entry *entry,37893789+ void *file_private_data,37903790+ struct file *file,37913791+ char *buf,37923792+ size_t count,37933793+ loff_t pos)37943794+ {37953795+ if (copy_to_user(buf, local_data + pos, count))37963796+ return -EFAULT;37973797+ return count;37983798+ }37993799+38003800+If the size of the info entry has been set up properly, ``count`` and38013801+``pos`` are guaranteed to fit within 0 and the given size. You don't38023802+have to check the range in the callbacks unless any other condition is38033803+required.38043804+38053805+Power Management38063806+================38073807+38083808+If the chip is supposed to work with suspend/resume functions, you need38093809+to add power-management code to the driver. The additional code for38103810+power-management should be ifdef-ed with ``CONFIG_PM``.38113811+38123812+If the driver *fully* supports suspend/resume that is, the device can be38133813+properly resumed to its state when suspend was called, you can set the38143814+``SNDRV_PCM_INFO_RESUME`` flag in the pcm info field. Usually, this is38153815+possible when the registers of the chip can be safely saved and restored38163816+to RAM. If this is set, the trigger callback is called with38173817+``SNDRV_PCM_TRIGGER_RESUME`` after the resume callback completes.38183818+38193819+Even if the driver doesn't support PM fully but partial suspend/resume38203820+is still possible, it's still worthy to implement suspend/resume38213821+callbacks. In such a case, applications would reset the status by38223822+calling :c:func:`snd_pcm_prepare()` and restart the stream38233823+appropriately. Hence, you can define suspend/resume callbacks below but38243824+don't set ``SNDRV_PCM_INFO_RESUME`` info flag to the PCM.38253825+38263826+Note that the trigger with SUSPEND can always be called when38273827+:c:func:`snd_pcm_suspend_all()` is called, regardless of the38283828+``SNDRV_PCM_INFO_RESUME`` flag. The ``RESUME`` flag affects only the38293829+behavior of :c:func:`snd_pcm_resume()`. (Thus, in theory,38303830+``SNDRV_PCM_TRIGGER_RESUME`` isn't needed to be handled in the trigger38313831+callback when no ``SNDRV_PCM_INFO_RESUME`` flag is set. But, it's better38323832+to keep it for compatibility reasons.)38333833+38343834+In the earlier version of ALSA drivers, a common power-management layer38353835+was provided, but it has been removed. The driver needs to define the38363836+suspend/resume hooks according to the bus the device is connected to. In38373837+the case of PCI drivers, the callbacks look like below:38383838+38393839+::38403840+38413841+ #ifdef CONFIG_PM38423842+ static int snd_my_suspend(struct pci_dev *pci, pm_message_t state)38433843+ {38443844+ .... /* do things for suspend */38453845+ return 0;38463846+ }38473847+ static int snd_my_resume(struct pci_dev *pci)38483848+ {38493849+ .... /* do things for suspend */38503850+ return 0;38513851+ }38523852+ #endif38533853+38543854+The scheme of the real suspend job is as follows.38553855+38563856+1. Retrieve the card and the chip data.38573857+38583858+2. Call :c:func:`snd_power_change_state()` with38593859+ ``SNDRV_CTL_POWER_D3hot`` to change the power status.38603860+38613861+3. Call :c:func:`snd_pcm_suspend_all()` to suspend the running38623862+ PCM streams.38633863+38643864+4. If AC97 codecs are used, call :c:func:`snd_ac97_suspend()` for38653865+ each codec.38663866+38673867+5. Save the register values if necessary.38683868+38693869+6. Stop the hardware if necessary.38703870+38713871+7. Disable the PCI device by calling38723872+ :c:func:`pci_disable_device()`. Then, call38733873+ :c:func:`pci_save_state()` at last.38743874+38753875+A typical code would be like:38763876+38773877+::38783878+38793879+ static int mychip_suspend(struct pci_dev *pci, pm_message_t state)38803880+ {38813881+ /* (1) */38823882+ struct snd_card *card = pci_get_drvdata(pci);38833883+ struct mychip *chip = card->private_data;38843884+ /* (2) */38853885+ snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);38863886+ /* (3) */38873887+ snd_pcm_suspend_all(chip->pcm);38883888+ /* (4) */38893889+ snd_ac97_suspend(chip->ac97);38903890+ /* (5) */38913891+ snd_mychip_save_registers(chip);38923892+ /* (6) */38933893+ snd_mychip_stop_hardware(chip);38943894+ /* (7) */38953895+ pci_disable_device(pci);38963896+ pci_save_state(pci);38973897+ return 0;38983898+ }38993899+39003900+39013901+The scheme of the real resume job is as follows.39023902+39033903+1. Retrieve the card and the chip data.39043904+39053905+2. Set up PCI. First, call :c:func:`pci_restore_state()`. Then39063906+ enable the pci device again by calling39073907+ :c:func:`pci_enable_device()`. Call39083908+ :c:func:`pci_set_master()` if necessary, too.39093909+39103910+3. Re-initialize the chip.39113911+39123912+4. Restore the saved registers if necessary.39133913+39143914+5. Resume the mixer, e.g. calling :c:func:`snd_ac97_resume()`.39153915+39163916+6. Restart the hardware (if any).39173917+39183918+7. Call :c:func:`snd_power_change_state()` with39193919+ ``SNDRV_CTL_POWER_D0`` to notify the processes.39203920+39213921+A typical code would be like:39223922+39233923+::39243924+39253925+ static int mychip_resume(struct pci_dev *pci)39263926+ {39273927+ /* (1) */39283928+ struct snd_card *card = pci_get_drvdata(pci);39293929+ struct mychip *chip = card->private_data;39303930+ /* (2) */39313931+ pci_restore_state(pci);39323932+ pci_enable_device(pci);39333933+ pci_set_master(pci);39343934+ /* (3) */39353935+ snd_mychip_reinit_chip(chip);39363936+ /* (4) */39373937+ snd_mychip_restore_registers(chip);39383938+ /* (5) */39393939+ snd_ac97_resume(chip->ac97);39403940+ /* (6) */39413941+ snd_mychip_restart_chip(chip);39423942+ /* (7) */39433943+ snd_power_change_state(card, SNDRV_CTL_POWER_D0);39443944+ return 0;39453945+ }39463946+39473947+As shown in the above, it's better to save registers after suspending39483948+the PCM operations via :c:func:`snd_pcm_suspend_all()` or39493949+:c:func:`snd_pcm_suspend()`. It means that the PCM streams are39503950+already stopped when the register snapshot is taken. But, remember that39513951+you don't have to restart the PCM stream in the resume callback. It'll39523952+be restarted via trigger call with ``SNDRV_PCM_TRIGGER_RESUME`` when39533953+necessary.39543954+39553955+OK, we have all callbacks now. Let's set them up. In the initialization39563956+of the card, make sure that you can get the chip data from the card39573957+instance, typically via ``private_data`` field, in case you created the39583958+chip data individually.39593959+39603960+::39613961+39623962+ static int snd_mychip_probe(struct pci_dev *pci,39633963+ const struct pci_device_id *pci_id)39643964+ {39653965+ ....39663966+ struct snd_card *card;39673967+ struct mychip *chip;39683968+ int err;39693969+ ....39703970+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,39713971+ 0, &card);39723972+ ....39733973+ chip = kzalloc(sizeof(*chip), GFP_KERNEL);39743974+ ....39753975+ card->private_data = chip;39763976+ ....39773977+ }39783978+39793979+When you created the chip data with :c:func:`snd_card_new()`, it's39803980+anyway accessible via ``private_data`` field.39813981+39823982+::39833983+39843984+ static int snd_mychip_probe(struct pci_dev *pci,39853985+ const struct pci_device_id *pci_id)39863986+ {39873987+ ....39883988+ struct snd_card *card;39893989+ struct mychip *chip;39903990+ int err;39913991+ ....39923992+ err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,39933993+ sizeof(struct mychip), &card);39943994+ ....39953995+ chip = card->private_data;39963996+ ....39973997+ }39983998+39993999+If you need a space to save the registers, allocate the buffer for it40004000+here, too, since it would be fatal if you cannot allocate a memory in40014001+the suspend phase. The allocated buffer should be released in the40024002+corresponding destructor.40034003+40044004+And next, set suspend/resume callbacks to the pci_driver.40054005+40064006+::40074007+40084008+ static struct pci_driver driver = {40094009+ .name = KBUILD_MODNAME,40104010+ .id_table = snd_my_ids,40114011+ .probe = snd_my_probe,40124012+ .remove = snd_my_remove,40134013+ #ifdef CONFIG_PM40144014+ .suspend = snd_my_suspend,40154015+ .resume = snd_my_resume,40164016+ #endif40174017+ };40184018+40194019+Module Parameters40204020+=================40214021+40224022+There are standard module options for ALSA. At least, each module should40234023+have the ``index``, ``id`` and ``enable`` options.40244024+40254025+If the module supports multiple cards (usually up to 8 = ``SNDRV_CARDS``40264026+cards), they should be arrays. The default initial values are defined40274027+already as constants for easier programming:40284028+40294029+::40304030+40314031+ static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;40324032+ static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;40334033+ static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;40344034+40354035+If the module supports only a single card, they could be single40364036+variables, instead. ``enable`` option is not always necessary in this40374037+case, but it would be better to have a dummy option for compatibility.40384038+40394039+The module parameters must be declared with the standard40404040+``module_param()()``, ``module_param_array()()`` and40414041+:c:func:`MODULE_PARM_DESC()` macros.40424042+40434043+The typical coding would be like below:40444044+40454045+::40464046+40474047+ #define CARD_NAME "My Chip"40484048+40494049+ module_param_array(index, int, NULL, 0444);40504050+ MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");40514051+ module_param_array(id, charp, NULL, 0444);40524052+ MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");40534053+ module_param_array(enable, bool, NULL, 0444);40544054+ MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");40554055+40564056+Also, don't forget to define the module description, classes, license40574057+and devices. Especially, the recent modprobe requires to define the40584058+module license as GPL, etc., otherwise the system is shown as “tainted”.40594059+40604060+::40614061+40624062+ MODULE_DESCRIPTION("My Chip");40634063+ MODULE_LICENSE("GPL");40644064+ MODULE_SUPPORTED_DEVICE("{{Vendor,My Chip Name}}");40654065+40664066+40674067+How To Put Your Driver Into ALSA Tree40684068+=====================================40694069+40704070+General40714071+-------40724072+40734073+So far, you've learned how to write the driver codes. And you might have40744074+a question now: how to put my own driver into the ALSA driver tree? Here40754075+(finally :) the standard procedure is described briefly.40764076+40774077+Suppose that you create a new PCI driver for the card “xyz”. The card40784078+module name would be snd-xyz. The new driver is usually put into the40794079+alsa-driver tree, ``alsa-driver/pci`` directory in the case of PCI40804080+cards. Then the driver is evaluated, audited and tested by developers40814081+and users. After a certain time, the driver will go to the alsa-kernel40824082+tree (to the corresponding directory, such as ``alsa-kernel/pci``) and40834083+eventually will be integrated into the Linux 2.6 tree (the directory40844084+would be ``linux/sound/pci``).40854085+40864086+In the following sections, the driver code is supposed to be put into40874087+alsa-driver tree. The two cases are covered: a driver consisting of a40884088+single source file and one consisting of several source files.40894089+40904090+Driver with A Single Source File40914091+--------------------------------40924092+40934093+1. Modify alsa-driver/pci/Makefile40944094+40954095+ Suppose you have a file xyz.c. Add the following two lines40964096+40974097+::40984098+40994099+ snd-xyz-objs := xyz.o41004100+ obj-$(CONFIG_SND_XYZ) += snd-xyz.o41014101+41024102+2. Create the Kconfig entry41034103+41044104+ Add the new entry of Kconfig for your xyz driver. config SND_XYZ41054105+ tristate "Foobar XYZ" depends on SND select SND_PCM help Say Y here41064106+ to include support for Foobar XYZ soundcard. To compile this driver41074107+ as a module, choose M here: the module will be called snd-xyz. the41084108+ line, select SND_PCM, specifies that the driver xyz supports PCM. In41094109+ addition to SND_PCM, the following components are supported for41104110+ select command: SND_RAWMIDI, SND_TIMER, SND_HWDEP,41114111+ SND_MPU401_UART, SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB,41124112+ SND_AC97_CODEC. Add the select command for each supported41134113+ component.41144114+41154115+ Note that some selections imply the lowlevel selections. For example,41164116+ PCM includes TIMER, MPU401_UART includes RAWMIDI, AC97_CODEC41174117+ includes PCM, and OPL3_LIB includes HWDEP. You don't need to give41184118+ the lowlevel selections again.41194119+41204120+ For the details of Kconfig script, refer to the kbuild documentation.41214121+41224122+3. Run cvscompile script to re-generate the configure script and build41234123+ the whole stuff again.41244124+41254125+Drivers with Several Source Files41264126+---------------------------------41274127+41284128+Suppose that the driver snd-xyz have several source files. They are41294129+located in the new subdirectory, pci/xyz.41304130+41314131+1. Add a new directory (``xyz``) in ``alsa-driver/pci/Makefile`` as41324132+ below41334133+41344134+::41354135+41364136+ obj-$(CONFIG_SND) += xyz/41374137+41384138+41394139+2. Under the directory ``xyz``, create a Makefile41404140+41414141+::41424142+41434143+ ifndef SND_TOPDIR41444144+ SND_TOPDIR=../..41454145+ endif41464146+41474147+ include $(SND_TOPDIR)/toplevel.config41484148+ include $(SND_TOPDIR)/Makefile.conf41494149+41504150+ snd-xyz-objs := xyz.o abc.o def.o41514151+41524152+ obj-$(CONFIG_SND_XYZ) += snd-xyz.o41534153+41544154+ include $(SND_TOPDIR)/Rules.make41554155+41564156+3. Create the Kconfig entry41574157+41584158+ This procedure is as same as in the last section.41594159+41604160+4. Run cvscompile script to re-generate the configure script and build41614161+ the whole stuff again.41624162+41634163+Useful Functions41644164+================41654165+41664166+:c:func:`snd_printk()` and friends41674167+---------------------------------------41684168+41694169+ALSA provides a verbose version of the :c:func:`printk()` function.41704170+If a kernel config ``CONFIG_SND_VERBOSE_PRINTK`` is set, this function41714171+prints the given message together with the file name and the line of the41724172+caller. The ``KERN_XXX`` prefix is processed as well as the original41734173+:c:func:`printk()` does, so it's recommended to add this prefix,41744174+e.g. snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\\n");41754175+41764176+There are also :c:func:`printk()`'s for debugging.41774177+:c:func:`snd_printd()` can be used for general debugging purposes.41784178+If ``CONFIG_SND_DEBUG`` is set, this function is compiled, and works41794179+just like :c:func:`snd_printk()`. If the ALSA is compiled without41804180+the debugging flag, it's ignored.41814181+41824182+:c:func:`snd_printdd()` is compiled in only when41834183+``CONFIG_SND_DEBUG_VERBOSE`` is set. Please note that41844184+``CONFIG_SND_DEBUG_VERBOSE`` is not set as default even if you configure41854185+the alsa-driver with ``--with-debug=full`` option. You need to give41864186+explicitly ``--with-debug=detect`` option instead.41874187+41884188+:c:func:`snd_BUG()`41894189+------------------------41904190+41914191+It shows the ``BUG?`` message and stack trace as well as41924192+:c:func:`snd_BUG_ON()` at the point. It's useful to show that a41934193+fatal error happens there.41944194+41954195+When no debug flag is set, this macro is ignored.41964196+41974197+:c:func:`snd_BUG_ON()`41984198+----------------------------41994199+42004200+:c:func:`snd_BUG_ON()` macro is similar with42014201+:c:func:`WARN_ON()` macro. For example, snd_BUG_ON(!pointer); or42024202+it can be used as the condition, if (snd_BUG_ON(non_zero_is_bug))42034203+return -EINVAL;42044204+42054205+The macro takes an conditional expression to evaluate. When42064206+``CONFIG_SND_DEBUG``, is set, if the expression is non-zero, it shows42074207+the warning message such as ``BUG? (xxx)`` normally followed by stack42084208+trace. In both cases it returns the evaluated value.42094209+42104210+Acknowledgments42114211+===============42124212+42134213+I would like to thank Phil Kerr for his help for improvement and42144214+corrections of this document.42154215+42164216+Kevin Conder reformatted the original plain-text to the DocBook format.42174217+42184218+Giuliano Pochini corrected typos and contributed the example codes in42194219+the hardware constraints section.