writing-an-alsa-driver.rst 140 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260
  1. ======================
  2. Writing an ALSA Driver
  3. ======================
  4. :Author: Takashi Iwai <tiwai@suse.de>
  5. :Date: Oct 15, 2007
  6. :Edition: 0.3.7
  7. Preface
  8. =======
  9. This document describes how to write an `ALSA (Advanced Linux Sound
  10. Architecture) <http://www.alsa-project.org/>`__ driver. The document
  11. focuses mainly on PCI soundcards. In the case of other device types, the
  12. API might be different, too. However, at least the ALSA kernel API is
  13. consistent, and therefore it would be still a bit help for writing them.
  14. This document targets people who already have enough C language skills
  15. and have basic linux kernel programming knowledge. This document doesn't
  16. explain the general topic of linux kernel coding and doesn't cover
  17. low-level driver implementation details. It only describes the standard
  18. way to write a PCI sound driver on ALSA.
  19. If you are already familiar with the older ALSA ver.0.5.x API, you can
  20. check the drivers such as ``sound/pci/es1938.c`` or
  21. ``sound/pci/maestro3.c`` which have also almost the same code-base in
  22. the ALSA 0.5.x tree, so you can compare the differences.
  23. This document is still a draft version. Any feedback and corrections,
  24. please!!
  25. File Tree Structure
  26. ===================
  27. General
  28. -------
  29. The ALSA drivers are provided in two ways.
  30. One is the trees provided as a tarball or via cvs from the ALSA's ftp
  31. site, and another is the 2.6 (or later) Linux kernel tree. To
  32. synchronize both, the ALSA driver tree is split into two different
  33. trees: alsa-kernel and alsa-driver. The former contains purely the
  34. source code for the Linux 2.6 (or later) tree. This tree is designed
  35. only for compilation on 2.6 or later environment. The latter,
  36. alsa-driver, contains many subtle files for compiling ALSA drivers
  37. outside of the Linux kernel tree, wrapper functions for older 2.2 and
  38. 2.4 kernels, to adapt the latest kernel API, and additional drivers
  39. which are still in development or in tests. The drivers in alsa-driver
  40. tree will be moved to alsa-kernel (and eventually to the 2.6 kernel
  41. tree) when they are finished and confirmed to work fine.
  42. The file tree structure of ALSA driver is depicted below. Both
  43. alsa-kernel and alsa-driver have almost the same file structure, except
  44. for “core” directory. It's named as “acore” in alsa-driver tree.
  45. ::
  46. sound
  47. /core
  48. /oss
  49. /seq
  50. /oss
  51. /instr
  52. /ioctl32
  53. /include
  54. /drivers
  55. /mpu401
  56. /opl3
  57. /i2c
  58. /l3
  59. /synth
  60. /emux
  61. /pci
  62. /(cards)
  63. /isa
  64. /(cards)
  65. /arm
  66. /ppc
  67. /sparc
  68. /usb
  69. /pcmcia /(cards)
  70. /oss
  71. core directory
  72. --------------
  73. This directory contains the middle layer which is the heart of ALSA
  74. drivers. In this directory, the native ALSA modules are stored. The
  75. sub-directories contain different modules and are dependent upon the
  76. kernel config.
  77. core/oss
  78. ~~~~~~~~
  79. The codes for PCM and mixer OSS emulation modules are stored in this
  80. directory. The rawmidi OSS emulation is included in the ALSA rawmidi
  81. code since it's quite small. The sequencer code is stored in
  82. ``core/seq/oss`` directory (see `below <#core-seq-oss>`__).
  83. core/ioctl32
  84. ~~~~~~~~~~~~
  85. This directory contains the 32bit-ioctl wrappers for 64bit architectures
  86. such like x86-64, ppc64 and sparc64. For 32bit and alpha architectures,
  87. these are not compiled.
  88. core/seq
  89. ~~~~~~~~
  90. This directory and its sub-directories are for the ALSA sequencer. This
  91. directory contains the sequencer core and primary sequencer modules such
  92. like snd-seq-midi, snd-seq-virmidi, etc. They are compiled only when
  93. ``CONFIG_SND_SEQUENCER`` is set in the kernel config.
  94. core/seq/oss
  95. ~~~~~~~~~~~~
  96. This contains the OSS sequencer emulation codes.
  97. core/seq/instr
  98. ~~~~~~~~~~~~~~
  99. This directory contains the modules for the sequencer instrument layer.
  100. include directory
  101. -----------------
  102. This is the place for the public header files of ALSA drivers, which are
  103. to be exported to user-space, or included by several files at different
  104. directories. Basically, the private header files should not be placed in
  105. this directory, but you may still find files there, due to historical
  106. reasons :)
  107. drivers directory
  108. -----------------
  109. This directory contains code shared among different drivers on different
  110. architectures. They are hence supposed not to be architecture-specific.
  111. For example, the dummy pcm driver and the serial MIDI driver are found
  112. in this directory. In the sub-directories, there is code for components
  113. which are independent from bus and cpu architectures.
  114. drivers/mpu401
  115. ~~~~~~~~~~~~~~
  116. The MPU401 and MPU401-UART modules are stored here.
  117. drivers/opl3 and opl4
  118. ~~~~~~~~~~~~~~~~~~~~~
  119. The OPL3 and OPL4 FM-synth stuff is found here.
  120. i2c directory
  121. -------------
  122. This contains the ALSA i2c components.
  123. Although there is a standard i2c layer on Linux, ALSA has its own i2c
  124. code for some cards, because the soundcard needs only a simple operation
  125. and the standard i2c API is too complicated for such a purpose.
  126. i2c/l3
  127. ~~~~~~
  128. This is a sub-directory for ARM L3 i2c.
  129. synth directory
  130. ---------------
  131. This contains the synth middle-level modules.
  132. So far, there is only Emu8000/Emu10k1 synth driver under the
  133. ``synth/emux`` sub-directory.
  134. pci directory
  135. -------------
  136. This directory and its sub-directories hold the top-level card modules
  137. for PCI soundcards and the code specific to the PCI BUS.
  138. The drivers compiled from a single file are stored directly in the pci
  139. directory, while the drivers with several source files are stored on
  140. their own sub-directory (e.g. emu10k1, ice1712).
  141. isa directory
  142. -------------
  143. This directory and its sub-directories hold the top-level card modules
  144. for ISA soundcards.
  145. arm, ppc, and sparc directories
  146. -------------------------------
  147. They are used for top-level card modules which are specific to one of
  148. these architectures.
  149. usb directory
  150. -------------
  151. This directory contains the USB-audio driver. In the latest version, the
  152. USB MIDI driver is integrated in the usb-audio driver.
  153. pcmcia directory
  154. ----------------
  155. The PCMCIA, especially PCCard drivers will go here. CardBus drivers will
  156. be in the pci directory, because their API is identical to that of
  157. standard PCI cards.
  158. oss directory
  159. -------------
  160. The OSS/Lite source files are stored here in Linux 2.6 (or later) tree.
  161. In the ALSA driver tarball, this directory is empty, of course :)
  162. Basic Flow for PCI Drivers
  163. ==========================
  164. Outline
  165. -------
  166. The minimum flow for PCI soundcards is as follows:
  167. - define the PCI ID table (see the section `PCI Entries`_).
  168. - create ``probe`` callback.
  169. - create ``remove`` callback.
  170. - create a :c:type:`struct pci_driver <pci_driver>` structure
  171. containing the three pointers above.
  172. - create an ``init`` function just calling the
  173. :c:func:`pci_register_driver()` to register the pci_driver
  174. table defined above.
  175. - create an ``exit`` function to call the
  176. :c:func:`pci_unregister_driver()` function.
  177. Full Code Example
  178. -----------------
  179. The code example is shown below. Some parts are kept unimplemented at
  180. this moment but will be filled in the next sections. The numbers in the
  181. comment lines of the :c:func:`snd_mychip_probe()` function refer
  182. to details explained in the following section.
  183. ::
  184. #include <linux/init.h>
  185. #include <linux/pci.h>
  186. #include <linux/slab.h>
  187. #include <sound/core.h>
  188. #include <sound/initval.h>
  189. /* module parameters (see "Module Parameters") */
  190. /* SNDRV_CARDS: maximum number of cards supported by this module */
  191. static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
  192. static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
  193. static bool enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
  194. /* definition of the chip-specific record */
  195. struct mychip {
  196. struct snd_card *card;
  197. /* the rest of the implementation will be in section
  198. * "PCI Resource Management"
  199. */
  200. };
  201. /* chip-specific destructor
  202. * (see "PCI Resource Management")
  203. */
  204. static int snd_mychip_free(struct mychip *chip)
  205. {
  206. .... /* will be implemented later... */
  207. }
  208. /* component-destructor
  209. * (see "Management of Cards and Components")
  210. */
  211. static int snd_mychip_dev_free(struct snd_device *device)
  212. {
  213. return snd_mychip_free(device->device_data);
  214. }
  215. /* chip-specific constructor
  216. * (see "Management of Cards and Components")
  217. */
  218. static int snd_mychip_create(struct snd_card *card,
  219. struct pci_dev *pci,
  220. struct mychip **rchip)
  221. {
  222. struct mychip *chip;
  223. int err;
  224. static struct snd_device_ops ops = {
  225. .dev_free = snd_mychip_dev_free,
  226. };
  227. *rchip = NULL;
  228. /* check PCI availability here
  229. * (see "PCI Resource Management")
  230. */
  231. ....
  232. /* allocate a chip-specific data with zero filled */
  233. chip = kzalloc(sizeof(*chip), GFP_KERNEL);
  234. if (chip == NULL)
  235. return -ENOMEM;
  236. chip->card = card;
  237. /* rest of initialization here; will be implemented
  238. * later, see "PCI Resource Management"
  239. */
  240. ....
  241. err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
  242. if (err < 0) {
  243. snd_mychip_free(chip);
  244. return err;
  245. }
  246. *rchip = chip;
  247. return 0;
  248. }
  249. /* constructor -- see "Driver Constructor" sub-section */
  250. static int snd_mychip_probe(struct pci_dev *pci,
  251. const struct pci_device_id *pci_id)
  252. {
  253. static int dev;
  254. struct snd_card *card;
  255. struct mychip *chip;
  256. int err;
  257. /* (1) */
  258. if (dev >= SNDRV_CARDS)
  259. return -ENODEV;
  260. if (!enable[dev]) {
  261. dev++;
  262. return -ENOENT;
  263. }
  264. /* (2) */
  265. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  266. 0, &card);
  267. if (err < 0)
  268. return err;
  269. /* (3) */
  270. err = snd_mychip_create(card, pci, &chip);
  271. if (err < 0) {
  272. snd_card_free(card);
  273. return err;
  274. }
  275. /* (4) */
  276. strcpy(card->driver, "My Chip");
  277. strcpy(card->shortname, "My Own Chip 123");
  278. sprintf(card->longname, "%s at 0x%lx irq %i",
  279. card->shortname, chip->ioport, chip->irq);
  280. /* (5) */
  281. .... /* implemented later */
  282. /* (6) */
  283. err = snd_card_register(card);
  284. if (err < 0) {
  285. snd_card_free(card);
  286. return err;
  287. }
  288. /* (7) */
  289. pci_set_drvdata(pci, card);
  290. dev++;
  291. return 0;
  292. }
  293. /* destructor -- see the "Destructor" sub-section */
  294. static void snd_mychip_remove(struct pci_dev *pci)
  295. {
  296. snd_card_free(pci_get_drvdata(pci));
  297. pci_set_drvdata(pci, NULL);
  298. }
  299. Driver Constructor
  300. ------------------
  301. The real constructor of PCI drivers is the ``probe`` callback. The
  302. ``probe`` callback and other component-constructors which are called
  303. from the ``probe`` callback cannot be used with the ``__init`` prefix
  304. because any PCI device could be a hotplug device.
  305. In the ``probe`` callback, the following scheme is often used.
  306. 1) Check and increment the device index.
  307. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  308. ::
  309. static int dev;
  310. ....
  311. if (dev >= SNDRV_CARDS)
  312. return -ENODEV;
  313. if (!enable[dev]) {
  314. dev++;
  315. return -ENOENT;
  316. }
  317. where ``enable[dev]`` is the module option.
  318. Each time the ``probe`` callback is called, check the availability of
  319. the device. If not available, simply increment the device index and
  320. returns. dev will be incremented also later (`step 7
  321. <#set-the-pci-driver-data-and-return-zero>`__).
  322. 2) Create a card instance
  323. ~~~~~~~~~~~~~~~~~~~~~~~~~
  324. ::
  325. struct snd_card *card;
  326. int err;
  327. ....
  328. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  329. 0, &card);
  330. The details will be explained in the section `Management of Cards and
  331. Components`_.
  332. 3) Create a main component
  333. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  334. In this part, the PCI resources are allocated.
  335. ::
  336. struct mychip *chip;
  337. ....
  338. err = snd_mychip_create(card, pci, &chip);
  339. if (err < 0) {
  340. snd_card_free(card);
  341. return err;
  342. }
  343. The details will be explained in the section `PCI Resource
  344. Management`_.
  345. 4) Set the driver ID and name strings.
  346. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  347. ::
  348. strcpy(card->driver, "My Chip");
  349. strcpy(card->shortname, "My Own Chip 123");
  350. sprintf(card->longname, "%s at 0x%lx irq %i",
  351. card->shortname, chip->ioport, chip->irq);
  352. The driver field holds the minimal ID string of the chip. This is used
  353. by alsa-lib's configurator, so keep it simple but unique. Even the
  354. same driver can have different driver IDs to distinguish the
  355. functionality of each chip type.
  356. The shortname field is a string shown as more verbose name. The longname
  357. field contains the information shown in ``/proc/asound/cards``.
  358. 5) Create other components, such as mixer, MIDI, etc.
  359. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  360. Here you define the basic components such as `PCM <#PCM-Interface>`__,
  361. mixer (e.g. `AC97 <#API-for-AC97-Codec>`__), MIDI (e.g.
  362. `MPU-401 <#MIDI-MPU401-UART-Interface>`__), and other interfaces.
  363. Also, if you want a `proc file <#Proc-Interface>`__, define it here,
  364. too.
  365. 6) Register the card instance.
  366. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  367. ::
  368. err = snd_card_register(card);
  369. if (err < 0) {
  370. snd_card_free(card);
  371. return err;
  372. }
  373. Will be explained in the section `Management of Cards and
  374. Components`_, too.
  375. 7) Set the PCI driver data and return zero.
  376. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  377. ::
  378. pci_set_drvdata(pci, card);
  379. dev++;
  380. return 0;
  381. In the above, the card record is stored. This pointer is used in the
  382. remove callback and power-management callbacks, too.
  383. Destructor
  384. ----------
  385. The destructor, remove callback, simply releases the card instance. Then
  386. the ALSA middle layer will release all the attached components
  387. automatically.
  388. It would be typically like the following:
  389. ::
  390. static void snd_mychip_remove(struct pci_dev *pci)
  391. {
  392. snd_card_free(pci_get_drvdata(pci));
  393. pci_set_drvdata(pci, NULL);
  394. }
  395. The above code assumes that the card pointer is set to the PCI driver
  396. data.
  397. Header Files
  398. ------------
  399. For the above example, at least the following include files are
  400. necessary.
  401. ::
  402. #include <linux/init.h>
  403. #include <linux/pci.h>
  404. #include <linux/slab.h>
  405. #include <sound/core.h>
  406. #include <sound/initval.h>
  407. where the last one is necessary only when module options are defined
  408. in the source file. If the code is split into several files, the files
  409. without module options don't need them.
  410. In addition to these headers, you'll need ``<linux/interrupt.h>`` for
  411. interrupt handling, and ``<asm/io.h>`` for I/O access. If you use the
  412. :c:func:`mdelay()` or :c:func:`udelay()` functions, you'll need
  413. to include ``<linux/delay.h>`` too.
  414. The ALSA interfaces like the PCM and control APIs are defined in other
  415. ``<sound/xxx.h>`` header files. They have to be included after
  416. ``<sound/core.h>``.
  417. Management of Cards and Components
  418. ==================================
  419. Card Instance
  420. -------------
  421. For each soundcard, a “card” record must be allocated.
  422. A card record is the headquarters of the soundcard. It manages the whole
  423. list of devices (components) on the soundcard, such as PCM, mixers,
  424. MIDI, synthesizer, and so on. Also, the card record holds the ID and the
  425. name strings of the card, manages the root of proc files, and controls
  426. the power-management states and hotplug disconnections. The component
  427. list on the card record is used to manage the correct release of
  428. resources at destruction.
  429. As mentioned above, to create a card instance, call
  430. :c:func:`snd_card_new()`.
  431. ::
  432. struct snd_card *card;
  433. int err;
  434. err = snd_card_new(&pci->dev, index, id, module, extra_size, &card);
  435. The function takes six arguments: the parent device pointer, the
  436. card-index number, the id string, the module pointer (usually
  437. ``THIS_MODULE``), the size of extra-data space, and the pointer to
  438. return the card instance. The extra_size argument is used to allocate
  439. card->private_data for the chip-specific data. Note that these data are
  440. allocated by :c:func:`snd_card_new()`.
  441. The first argument, the pointer of struct :c:type:`struct device
  442. <device>`, specifies the parent device. For PCI devices, typically
  443. ``&pci->`` is passed there.
  444. Components
  445. ----------
  446. After the card is created, you can attach the components (devices) to
  447. the card instance. In an ALSA driver, a component is represented as a
  448. :c:type:`struct snd_device <snd_device>` object. A component
  449. can be a PCM instance, a control interface, a raw MIDI interface, etc.
  450. Each such instance has one component entry.
  451. A component can be created via :c:func:`snd_device_new()`
  452. function.
  453. ::
  454. snd_device_new(card, SNDRV_DEV_XXX, chip, &ops);
  455. This takes the card pointer, the device-level (``SNDRV_DEV_XXX``), the
  456. data pointer, and the callback pointers (``&ops``). The device-level
  457. defines the type of components and the order of registration and
  458. de-registration. For most components, the device-level is already
  459. defined. For a user-defined component, you can use
  460. ``SNDRV_DEV_LOWLEVEL``.
  461. This function itself doesn't allocate the data space. The data must be
  462. allocated manually beforehand, and its pointer is passed as the
  463. argument. This pointer (``chip`` in the above example) is used as the
  464. identifier for the instance.
  465. Each pre-defined ALSA component such as ac97 and pcm calls
  466. :c:func:`snd_device_new()` inside its constructor. The destructor
  467. for each component is defined in the callback pointers. Hence, you don't
  468. need to take care of calling a destructor for such a component.
  469. If you wish to create your own component, you need to set the destructor
  470. function to the dev_free callback in the ``ops``, so that it can be
  471. released automatically via :c:func:`snd_card_free()`. The next
  472. example will show an implementation of chip-specific data.
  473. Chip-Specific Data
  474. ------------------
  475. Chip-specific information, e.g. the I/O port address, its resource
  476. pointer, or the irq number, is stored in the chip-specific record.
  477. ::
  478. struct mychip {
  479. ....
  480. };
  481. In general, there are two ways of allocating the chip record.
  482. 1. Allocating via :c:func:`snd_card_new()`.
  483. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  484. As mentioned above, you can pass the extra-data-length to the 5th
  485. argument of :c:func:`snd_card_new()`, i.e.
  486. ::
  487. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  488. sizeof(struct mychip), &card);
  489. :c:type:`struct mychip <mychip>` is the type of the chip record.
  490. In return, the allocated record can be accessed as
  491. ::
  492. struct mychip *chip = card->private_data;
  493. With this method, you don't have to allocate twice. The record is
  494. released together with the card instance.
  495. 2. Allocating an extra device.
  496. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  497. After allocating a card instance via :c:func:`snd_card_new()`
  498. (with ``0`` on the 4th arg), call :c:func:`kzalloc()`.
  499. ::
  500. struct snd_card *card;
  501. struct mychip *chip;
  502. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  503. 0, &card);
  504. .....
  505. chip = kzalloc(sizeof(*chip), GFP_KERNEL);
  506. The chip record should have the field to hold the card pointer at least,
  507. ::
  508. struct mychip {
  509. struct snd_card *card;
  510. ....
  511. };
  512. Then, set the card pointer in the returned chip instance.
  513. ::
  514. chip->card = card;
  515. Next, initialize the fields, and register this chip record as a
  516. low-level device with a specified ``ops``,
  517. ::
  518. static struct snd_device_ops ops = {
  519. .dev_free = snd_mychip_dev_free,
  520. };
  521. ....
  522. snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
  523. :c:func:`snd_mychip_dev_free()` is the device-destructor
  524. function, which will call the real destructor.
  525. ::
  526. static int snd_mychip_dev_free(struct snd_device *device)
  527. {
  528. return snd_mychip_free(device->device_data);
  529. }
  530. where :c:func:`snd_mychip_free()` is the real destructor.
  531. Registration and Release
  532. ------------------------
  533. After all components are assigned, register the card instance by calling
  534. :c:func:`snd_card_register()`. Access to the device files is
  535. enabled at this point. That is, before
  536. :c:func:`snd_card_register()` is called, the components are safely
  537. inaccessible from external side. If this call fails, exit the probe
  538. function after releasing the card via :c:func:`snd_card_free()`.
  539. For releasing the card instance, you can call simply
  540. :c:func:`snd_card_free()`. As mentioned earlier, all components
  541. are released automatically by this call.
  542. For a device which allows hotplugging, you can use
  543. :c:func:`snd_card_free_when_closed()`. This one will postpone
  544. the destruction until all devices are closed.
  545. PCI Resource Management
  546. =======================
  547. Full Code Example
  548. -----------------
  549. In this section, we'll complete the chip-specific constructor,
  550. destructor and PCI entries. Example code is shown first, below.
  551. ::
  552. struct mychip {
  553. struct snd_card *card;
  554. struct pci_dev *pci;
  555. unsigned long port;
  556. int irq;
  557. };
  558. static int snd_mychip_free(struct mychip *chip)
  559. {
  560. /* disable hardware here if any */
  561. .... /* (not implemented in this document) */
  562. /* release the irq */
  563. if (chip->irq >= 0)
  564. free_irq(chip->irq, chip);
  565. /* release the I/O ports & memory */
  566. pci_release_regions(chip->pci);
  567. /* disable the PCI entry */
  568. pci_disable_device(chip->pci);
  569. /* release the data */
  570. kfree(chip);
  571. return 0;
  572. }
  573. /* chip-specific constructor */
  574. static int snd_mychip_create(struct snd_card *card,
  575. struct pci_dev *pci,
  576. struct mychip **rchip)
  577. {
  578. struct mychip *chip;
  579. int err;
  580. static struct snd_device_ops ops = {
  581. .dev_free = snd_mychip_dev_free,
  582. };
  583. *rchip = NULL;
  584. /* initialize the PCI entry */
  585. err = pci_enable_device(pci);
  586. if (err < 0)
  587. return err;
  588. /* check PCI availability (28bit DMA) */
  589. if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||
  590. pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {
  591. printk(KERN_ERR "error to set 28bit mask DMA\n");
  592. pci_disable_device(pci);
  593. return -ENXIO;
  594. }
  595. chip = kzalloc(sizeof(*chip), GFP_KERNEL);
  596. if (chip == NULL) {
  597. pci_disable_device(pci);
  598. return -ENOMEM;
  599. }
  600. /* initialize the stuff */
  601. chip->card = card;
  602. chip->pci = pci;
  603. chip->irq = -1;
  604. /* (1) PCI resource allocation */
  605. err = pci_request_regions(pci, "My Chip");
  606. if (err < 0) {
  607. kfree(chip);
  608. pci_disable_device(pci);
  609. return err;
  610. }
  611. chip->port = pci_resource_start(pci, 0);
  612. if (request_irq(pci->irq, snd_mychip_interrupt,
  613. IRQF_SHARED, KBUILD_MODNAME, chip)) {
  614. printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
  615. snd_mychip_free(chip);
  616. return -EBUSY;
  617. }
  618. chip->irq = pci->irq;
  619. /* (2) initialization of the chip hardware */
  620. .... /* (not implemented in this document) */
  621. err = snd_device_new(card, SNDRV_DEV_LOWLEVEL, chip, &ops);
  622. if (err < 0) {
  623. snd_mychip_free(chip);
  624. return err;
  625. }
  626. *rchip = chip;
  627. return 0;
  628. }
  629. /* PCI IDs */
  630. static struct pci_device_id snd_mychip_ids[] = {
  631. { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
  632. PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
  633. ....
  634. { 0, }
  635. };
  636. MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
  637. /* pci_driver definition */
  638. static struct pci_driver driver = {
  639. .name = KBUILD_MODNAME,
  640. .id_table = snd_mychip_ids,
  641. .probe = snd_mychip_probe,
  642. .remove = snd_mychip_remove,
  643. };
  644. /* module initialization */
  645. static int __init alsa_card_mychip_init(void)
  646. {
  647. return pci_register_driver(&driver);
  648. }
  649. /* module clean up */
  650. static void __exit alsa_card_mychip_exit(void)
  651. {
  652. pci_unregister_driver(&driver);
  653. }
  654. module_init(alsa_card_mychip_init)
  655. module_exit(alsa_card_mychip_exit)
  656. EXPORT_NO_SYMBOLS; /* for old kernels only */
  657. Some Hafta's
  658. ------------
  659. The allocation of PCI resources is done in the ``probe`` function, and
  660. usually an extra :c:func:`xxx_create()` function is written for this
  661. purpose.
  662. In the case of PCI devices, you first have to call the
  663. :c:func:`pci_enable_device()` function before allocating
  664. resources. Also, you need to set the proper PCI DMA mask to limit the
  665. accessed I/O range. In some cases, you might need to call
  666. :c:func:`pci_set_master()` function, too.
  667. Suppose the 28bit mask, and the code to be added would be like:
  668. ::
  669. err = pci_enable_device(pci);
  670. if (err < 0)
  671. return err;
  672. if (pci_set_dma_mask(pci, DMA_BIT_MASK(28)) < 0 ||
  673. pci_set_consistent_dma_mask(pci, DMA_BIT_MASK(28)) < 0) {
  674. printk(KERN_ERR "error to set 28bit mask DMA\n");
  675. pci_disable_device(pci);
  676. return -ENXIO;
  677. }
  678. Resource Allocation
  679. -------------------
  680. The allocation of I/O ports and irqs is done via standard kernel
  681. functions. Unlike ALSA ver.0.5.x., there are no helpers for that. And
  682. these resources must be released in the destructor function (see below).
  683. Also, on ALSA 0.9.x, you don't need to allocate (pseudo-)DMA for PCI
  684. like in ALSA 0.5.x.
  685. Now assume that the PCI device has an I/O port with 8 bytes and an
  686. interrupt. Then :c:type:`struct mychip <mychip>` will have the
  687. following fields:
  688. ::
  689. struct mychip {
  690. struct snd_card *card;
  691. unsigned long port;
  692. int irq;
  693. };
  694. For an I/O port (and also a memory region), you need to have the
  695. resource pointer for the standard resource management. For an irq, you
  696. have to keep only the irq number (integer). But you need to initialize
  697. this number as -1 before actual allocation, since irq 0 is valid. The
  698. port address and its resource pointer can be initialized as null by
  699. :c:func:`kzalloc()` automatically, so you don't have to take care of
  700. resetting them.
  701. The allocation of an I/O port is done like this:
  702. ::
  703. err = pci_request_regions(pci, "My Chip");
  704. if (err < 0) {
  705. kfree(chip);
  706. pci_disable_device(pci);
  707. return err;
  708. }
  709. chip->port = pci_resource_start(pci, 0);
  710. It will reserve the I/O port region of 8 bytes of the given PCI device.
  711. The returned value, ``chip->res_port``, is allocated via
  712. :c:func:`kmalloc()` by :c:func:`request_region()`. The pointer
  713. must be released via :c:func:`kfree()`, but there is a problem with
  714. this. This issue will be explained later.
  715. The allocation of an interrupt source is done like this:
  716. ::
  717. if (request_irq(pci->irq, snd_mychip_interrupt,
  718. IRQF_SHARED, KBUILD_MODNAME, chip)) {
  719. printk(KERN_ERR "cannot grab irq %d\n", pci->irq);
  720. snd_mychip_free(chip);
  721. return -EBUSY;
  722. }
  723. chip->irq = pci->irq;
  724. where :c:func:`snd_mychip_interrupt()` is the interrupt handler
  725. defined `later <#pcm-interface-interrupt-handler>`__. Note that
  726. ``chip->irq`` should be defined only when :c:func:`request_irq()`
  727. succeeded.
  728. On the PCI bus, interrupts can be shared. Thus, ``IRQF_SHARED`` is used
  729. as the interrupt flag of :c:func:`request_irq()`.
  730. The last argument of :c:func:`request_irq()` is the data pointer
  731. passed to the interrupt handler. Usually, the chip-specific record is
  732. used for that, but you can use what you like, too.
  733. I won't give details about the interrupt handler at this point, but at
  734. least its appearance can be explained now. The interrupt handler looks
  735. usually like the following:
  736. ::
  737. static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
  738. {
  739. struct mychip *chip = dev_id;
  740. ....
  741. return IRQ_HANDLED;
  742. }
  743. Now let's write the corresponding destructor for the resources above.
  744. The role of destructor is simple: disable the hardware (if already
  745. activated) and release the resources. So far, we have no hardware part,
  746. so the disabling code is not written here.
  747. To release the resources, the “check-and-release” method is a safer way.
  748. For the interrupt, do like this:
  749. ::
  750. if (chip->irq >= 0)
  751. free_irq(chip->irq, chip);
  752. Since the irq number can start from 0, you should initialize
  753. ``chip->irq`` with a negative value (e.g. -1), so that you can check
  754. the validity of the irq number as above.
  755. When you requested I/O ports or memory regions via
  756. :c:func:`pci_request_region()` or
  757. :c:func:`pci_request_regions()` like in this example, release the
  758. resource(s) using the corresponding function,
  759. :c:func:`pci_release_region()` or
  760. :c:func:`pci_release_regions()`.
  761. ::
  762. pci_release_regions(chip->pci);
  763. When you requested manually via :c:func:`request_region()` or
  764. :c:func:`request_mem_region()`, you can release it via
  765. :c:func:`release_resource()`. Suppose that you keep the resource
  766. pointer returned from :c:func:`request_region()` in
  767. chip->res_port, the release procedure looks like:
  768. ::
  769. release_and_free_resource(chip->res_port);
  770. Don't forget to call :c:func:`pci_disable_device()` before the
  771. end.
  772. And finally, release the chip-specific record.
  773. ::
  774. kfree(chip);
  775. We didn't implement the hardware disabling part in the above. If you
  776. need to do this, please note that the destructor may be called even
  777. before the initialization of the chip is completed. It would be better
  778. to have a flag to skip hardware disabling if the hardware was not
  779. initialized yet.
  780. When the chip-data is assigned to the card using
  781. :c:func:`snd_device_new()` with ``SNDRV_DEV_LOWLELVEL`` , its
  782. destructor is called at the last. That is, it is assured that all other
  783. components like PCMs and controls have already been released. You don't
  784. have to stop PCMs, etc. explicitly, but just call low-level hardware
  785. stopping.
  786. The management of a memory-mapped region is almost as same as the
  787. management of an I/O port. You'll need three fields like the
  788. following:
  789. ::
  790. struct mychip {
  791. ....
  792. unsigned long iobase_phys;
  793. void __iomem *iobase_virt;
  794. };
  795. and the allocation would be like below:
  796. ::
  797. if ((err = pci_request_regions(pci, "My Chip")) < 0) {
  798. kfree(chip);
  799. return err;
  800. }
  801. chip->iobase_phys = pci_resource_start(pci, 0);
  802. chip->iobase_virt = ioremap_nocache(chip->iobase_phys,
  803. pci_resource_len(pci, 0));
  804. and the corresponding destructor would be:
  805. ::
  806. static int snd_mychip_free(struct mychip *chip)
  807. {
  808. ....
  809. if (chip->iobase_virt)
  810. iounmap(chip->iobase_virt);
  811. ....
  812. pci_release_regions(chip->pci);
  813. ....
  814. }
  815. PCI Entries
  816. -----------
  817. So far, so good. Let's finish the missing PCI stuff. At first, we need a
  818. :c:type:`struct pci_device_id <pci_device_id>` table for
  819. this chipset. It's a table of PCI vendor/device ID number, and some
  820. masks.
  821. For example,
  822. ::
  823. static struct pci_device_id snd_mychip_ids[] = {
  824. { PCI_VENDOR_ID_FOO, PCI_DEVICE_ID_BAR,
  825. PCI_ANY_ID, PCI_ANY_ID, 0, 0, 0, },
  826. ....
  827. { 0, }
  828. };
  829. MODULE_DEVICE_TABLE(pci, snd_mychip_ids);
  830. The first and second fields of the :c:type:`struct pci_device_id
  831. <pci_device_id>` structure are the vendor and device IDs. If you
  832. have no reason to filter the matching devices, you can leave the
  833. remaining fields as above. The last field of the :c:type:`struct
  834. pci_device_id <pci_device_id>` struct contains private data
  835. for this entry. You can specify any value here, for example, to define
  836. specific operations for supported device IDs. Such an example is found
  837. in the intel8x0 driver.
  838. The last entry of this list is the terminator. You must specify this
  839. all-zero entry.
  840. Then, prepare the :c:type:`struct pci_driver <pci_driver>`
  841. record:
  842. ::
  843. static struct pci_driver driver = {
  844. .name = KBUILD_MODNAME,
  845. .id_table = snd_mychip_ids,
  846. .probe = snd_mychip_probe,
  847. .remove = snd_mychip_remove,
  848. };
  849. The ``probe`` and ``remove`` functions have already been defined in
  850. the previous sections. The ``name`` field is the name string of this
  851. device. Note that you must not use a slash “/” in this string.
  852. And at last, the module entries:
  853. ::
  854. static int __init alsa_card_mychip_init(void)
  855. {
  856. return pci_register_driver(&driver);
  857. }
  858. static void __exit alsa_card_mychip_exit(void)
  859. {
  860. pci_unregister_driver(&driver);
  861. }
  862. module_init(alsa_card_mychip_init)
  863. module_exit(alsa_card_mychip_exit)
  864. Note that these module entries are tagged with ``__init`` and ``__exit``
  865. prefixes.
  866. Oh, one thing was forgotten. If you have no exported symbols, you need
  867. to declare it in 2.2 or 2.4 kernels (it's not necessary in 2.6 kernels).
  868. ::
  869. EXPORT_NO_SYMBOLS;
  870. That's all!
  871. PCM Interface
  872. =============
  873. General
  874. -------
  875. The PCM middle layer of ALSA is quite powerful and it is only necessary
  876. for each driver to implement the low-level functions to access its
  877. hardware.
  878. For accessing to the PCM layer, you need to include ``<sound/pcm.h>``
  879. first. In addition, ``<sound/pcm_params.h>`` might be needed if you
  880. access to some functions related with hw_param.
  881. Each card device can have up to four pcm instances. A pcm instance
  882. corresponds to a pcm device file. The limitation of number of instances
  883. comes only from the available bit size of the Linux's device numbers.
  884. Once when 64bit device number is used, we'll have more pcm instances
  885. available.
  886. A pcm instance consists of pcm playback and capture streams, and each
  887. pcm stream consists of one or more pcm substreams. Some soundcards
  888. support multiple playback functions. For example, emu10k1 has a PCM
  889. playback of 32 stereo substreams. In this case, at each open, a free
  890. substream is (usually) automatically chosen and opened. Meanwhile, when
  891. only one substream exists and it was already opened, the successful open
  892. will either block or error with ``EAGAIN`` according to the file open
  893. mode. But you don't have to care about such details in your driver. The
  894. PCM middle layer will take care of such work.
  895. Full Code Example
  896. -----------------
  897. The example code below does not include any hardware access routines but
  898. shows only the skeleton, how to build up the PCM interfaces.
  899. ::
  900. #include <sound/pcm.h>
  901. ....
  902. /* hardware definition */
  903. static struct snd_pcm_hardware snd_mychip_playback_hw = {
  904. .info = (SNDRV_PCM_INFO_MMAP |
  905. SNDRV_PCM_INFO_INTERLEAVED |
  906. SNDRV_PCM_INFO_BLOCK_TRANSFER |
  907. SNDRV_PCM_INFO_MMAP_VALID),
  908. .formats = SNDRV_PCM_FMTBIT_S16_LE,
  909. .rates = SNDRV_PCM_RATE_8000_48000,
  910. .rate_min = 8000,
  911. .rate_max = 48000,
  912. .channels_min = 2,
  913. .channels_max = 2,
  914. .buffer_bytes_max = 32768,
  915. .period_bytes_min = 4096,
  916. .period_bytes_max = 32768,
  917. .periods_min = 1,
  918. .periods_max = 1024,
  919. };
  920. /* hardware definition */
  921. static struct snd_pcm_hardware snd_mychip_capture_hw = {
  922. .info = (SNDRV_PCM_INFO_MMAP |
  923. SNDRV_PCM_INFO_INTERLEAVED |
  924. SNDRV_PCM_INFO_BLOCK_TRANSFER |
  925. SNDRV_PCM_INFO_MMAP_VALID),
  926. .formats = SNDRV_PCM_FMTBIT_S16_LE,
  927. .rates = SNDRV_PCM_RATE_8000_48000,
  928. .rate_min = 8000,
  929. .rate_max = 48000,
  930. .channels_min = 2,
  931. .channels_max = 2,
  932. .buffer_bytes_max = 32768,
  933. .period_bytes_min = 4096,
  934. .period_bytes_max = 32768,
  935. .periods_min = 1,
  936. .periods_max = 1024,
  937. };
  938. /* open callback */
  939. static int snd_mychip_playback_open(struct snd_pcm_substream *substream)
  940. {
  941. struct mychip *chip = snd_pcm_substream_chip(substream);
  942. struct snd_pcm_runtime *runtime = substream->runtime;
  943. runtime->hw = snd_mychip_playback_hw;
  944. /* more hardware-initialization will be done here */
  945. ....
  946. return 0;
  947. }
  948. /* close callback */
  949. static int snd_mychip_playback_close(struct snd_pcm_substream *substream)
  950. {
  951. struct mychip *chip = snd_pcm_substream_chip(substream);
  952. /* the hardware-specific codes will be here */
  953. ....
  954. return 0;
  955. }
  956. /* open callback */
  957. static int snd_mychip_capture_open(struct snd_pcm_substream *substream)
  958. {
  959. struct mychip *chip = snd_pcm_substream_chip(substream);
  960. struct snd_pcm_runtime *runtime = substream->runtime;
  961. runtime->hw = snd_mychip_capture_hw;
  962. /* more hardware-initialization will be done here */
  963. ....
  964. return 0;
  965. }
  966. /* close callback */
  967. static int snd_mychip_capture_close(struct snd_pcm_substream *substream)
  968. {
  969. struct mychip *chip = snd_pcm_substream_chip(substream);
  970. /* the hardware-specific codes will be here */
  971. ....
  972. return 0;
  973. }
  974. /* hw_params callback */
  975. static int snd_mychip_pcm_hw_params(struct snd_pcm_substream *substream,
  976. struct snd_pcm_hw_params *hw_params)
  977. {
  978. return snd_pcm_lib_malloc_pages(substream,
  979. params_buffer_bytes(hw_params));
  980. }
  981. /* hw_free callback */
  982. static int snd_mychip_pcm_hw_free(struct snd_pcm_substream *substream)
  983. {
  984. return snd_pcm_lib_free_pages(substream);
  985. }
  986. /* prepare callback */
  987. static int snd_mychip_pcm_prepare(struct snd_pcm_substream *substream)
  988. {
  989. struct mychip *chip = snd_pcm_substream_chip(substream);
  990. struct snd_pcm_runtime *runtime = substream->runtime;
  991. /* set up the hardware with the current configuration
  992. * for example...
  993. */
  994. mychip_set_sample_format(chip, runtime->format);
  995. mychip_set_sample_rate(chip, runtime->rate);
  996. mychip_set_channels(chip, runtime->channels);
  997. mychip_set_dma_setup(chip, runtime->dma_addr,
  998. chip->buffer_size,
  999. chip->period_size);
  1000. return 0;
  1001. }
  1002. /* trigger callback */
  1003. static int snd_mychip_pcm_trigger(struct snd_pcm_substream *substream,
  1004. int cmd)
  1005. {
  1006. switch (cmd) {
  1007. case SNDRV_PCM_TRIGGER_START:
  1008. /* do something to start the PCM engine */
  1009. ....
  1010. break;
  1011. case SNDRV_PCM_TRIGGER_STOP:
  1012. /* do something to stop the PCM engine */
  1013. ....
  1014. break;
  1015. default:
  1016. return -EINVAL;
  1017. }
  1018. }
  1019. /* pointer callback */
  1020. static snd_pcm_uframes_t
  1021. snd_mychip_pcm_pointer(struct snd_pcm_substream *substream)
  1022. {
  1023. struct mychip *chip = snd_pcm_substream_chip(substream);
  1024. unsigned int current_ptr;
  1025. /* get the current hardware pointer */
  1026. current_ptr = mychip_get_hw_pointer(chip);
  1027. return current_ptr;
  1028. }
  1029. /* operators */
  1030. static struct snd_pcm_ops snd_mychip_playback_ops = {
  1031. .open = snd_mychip_playback_open,
  1032. .close = snd_mychip_playback_close,
  1033. .ioctl = snd_pcm_lib_ioctl,
  1034. .hw_params = snd_mychip_pcm_hw_params,
  1035. .hw_free = snd_mychip_pcm_hw_free,
  1036. .prepare = snd_mychip_pcm_prepare,
  1037. .trigger = snd_mychip_pcm_trigger,
  1038. .pointer = snd_mychip_pcm_pointer,
  1039. };
  1040. /* operators */
  1041. static struct snd_pcm_ops snd_mychip_capture_ops = {
  1042. .open = snd_mychip_capture_open,
  1043. .close = snd_mychip_capture_close,
  1044. .ioctl = snd_pcm_lib_ioctl,
  1045. .hw_params = snd_mychip_pcm_hw_params,
  1046. .hw_free = snd_mychip_pcm_hw_free,
  1047. .prepare = snd_mychip_pcm_prepare,
  1048. .trigger = snd_mychip_pcm_trigger,
  1049. .pointer = snd_mychip_pcm_pointer,
  1050. };
  1051. /*
  1052. * definitions of capture are omitted here...
  1053. */
  1054. /* create a pcm device */
  1055. static int snd_mychip_new_pcm(struct mychip *chip)
  1056. {
  1057. struct snd_pcm *pcm;
  1058. int err;
  1059. err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);
  1060. if (err < 0)
  1061. return err;
  1062. pcm->private_data = chip;
  1063. strcpy(pcm->name, "My Chip");
  1064. chip->pcm = pcm;
  1065. /* set operators */
  1066. snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
  1067. &snd_mychip_playback_ops);
  1068. snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
  1069. &snd_mychip_capture_ops);
  1070. /* pre-allocation of buffers */
  1071. /* NOTE: this may fail */
  1072. snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
  1073. snd_dma_pci_data(chip->pci),
  1074. 64*1024, 64*1024);
  1075. return 0;
  1076. }
  1077. PCM Constructor
  1078. ---------------
  1079. A pcm instance is allocated by the :c:func:`snd_pcm_new()`
  1080. function. It would be better to create a constructor for pcm, namely,
  1081. ::
  1082. static int snd_mychip_new_pcm(struct mychip *chip)
  1083. {
  1084. struct snd_pcm *pcm;
  1085. int err;
  1086. err = snd_pcm_new(chip->card, "My Chip", 0, 1, 1, &pcm);
  1087. if (err < 0)
  1088. return err;
  1089. pcm->private_data = chip;
  1090. strcpy(pcm->name, "My Chip");
  1091. chip->pcm = pcm;
  1092. ....
  1093. return 0;
  1094. }
  1095. The :c:func:`snd_pcm_new()` function takes four arguments. The
  1096. first argument is the card pointer to which this pcm is assigned, and
  1097. the second is the ID string.
  1098. The third argument (``index``, 0 in the above) is the index of this new
  1099. pcm. It begins from zero. If you create more than one pcm instances,
  1100. specify the different numbers in this argument. For example, ``index =
  1101. 1`` for the second PCM device.
  1102. The fourth and fifth arguments are the number of substreams for playback
  1103. and capture, respectively. Here 1 is used for both arguments. When no
  1104. playback or capture substreams are available, pass 0 to the
  1105. corresponding argument.
  1106. If a chip supports multiple playbacks or captures, you can specify more
  1107. numbers, but they must be handled properly in open/close, etc.
  1108. callbacks. When you need to know which substream you are referring to,
  1109. then it can be obtained from :c:type:`struct snd_pcm_substream
  1110. <snd_pcm_substream>` data passed to each callback as follows:
  1111. ::
  1112. struct snd_pcm_substream *substream;
  1113. int index = substream->number;
  1114. After the pcm is created, you need to set operators for each pcm stream.
  1115. ::
  1116. snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_PLAYBACK,
  1117. &snd_mychip_playback_ops);
  1118. snd_pcm_set_ops(pcm, SNDRV_PCM_STREAM_CAPTURE,
  1119. &snd_mychip_capture_ops);
  1120. The operators are defined typically like this:
  1121. ::
  1122. static struct snd_pcm_ops snd_mychip_playback_ops = {
  1123. .open = snd_mychip_pcm_open,
  1124. .close = snd_mychip_pcm_close,
  1125. .ioctl = snd_pcm_lib_ioctl,
  1126. .hw_params = snd_mychip_pcm_hw_params,
  1127. .hw_free = snd_mychip_pcm_hw_free,
  1128. .prepare = snd_mychip_pcm_prepare,
  1129. .trigger = snd_mychip_pcm_trigger,
  1130. .pointer = snd_mychip_pcm_pointer,
  1131. };
  1132. All the callbacks are described in the Operators_ subsection.
  1133. After setting the operators, you probably will want to pre-allocate the
  1134. buffer. For the pre-allocation, simply call the following:
  1135. ::
  1136. snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
  1137. snd_dma_pci_data(chip->pci),
  1138. 64*1024, 64*1024);
  1139. It will allocate a buffer up to 64kB as default. Buffer management
  1140. details will be described in the later section `Buffer and Memory
  1141. Management`_.
  1142. Additionally, you can set some extra information for this pcm in
  1143. ``pcm->info_flags``. The available values are defined as
  1144. ``SNDRV_PCM_INFO_XXX`` in ``<sound/asound.h>``, which is used for the
  1145. hardware definition (described later). When your soundchip supports only
  1146. half-duplex, specify like this:
  1147. ::
  1148. pcm->info_flags = SNDRV_PCM_INFO_HALF_DUPLEX;
  1149. ... And the Destructor?
  1150. -----------------------
  1151. The destructor for a pcm instance is not always necessary. Since the pcm
  1152. device will be released by the middle layer code automatically, you
  1153. don't have to call the destructor explicitly.
  1154. The destructor would be necessary if you created special records
  1155. internally and needed to release them. In such a case, set the
  1156. destructor function to ``pcm->private_free``:
  1157. ::
  1158. static void mychip_pcm_free(struct snd_pcm *pcm)
  1159. {
  1160. struct mychip *chip = snd_pcm_chip(pcm);
  1161. /* free your own data */
  1162. kfree(chip->my_private_pcm_data);
  1163. /* do what you like else */
  1164. ....
  1165. }
  1166. static int snd_mychip_new_pcm(struct mychip *chip)
  1167. {
  1168. struct snd_pcm *pcm;
  1169. ....
  1170. /* allocate your own data */
  1171. chip->my_private_pcm_data = kmalloc(...);
  1172. /* set the destructor */
  1173. pcm->private_data = chip;
  1174. pcm->private_free = mychip_pcm_free;
  1175. ....
  1176. }
  1177. Runtime Pointer - The Chest of PCM Information
  1178. ----------------------------------------------
  1179. When the PCM substream is opened, a PCM runtime instance is allocated
  1180. and assigned to the substream. This pointer is accessible via
  1181. ``substream->runtime``. This runtime pointer holds most information you
  1182. need to control the PCM: the copy of hw_params and sw_params
  1183. configurations, the buffer pointers, mmap records, spinlocks, etc.
  1184. The definition of runtime instance is found in ``<sound/pcm.h>``. Here
  1185. are the contents of this file:
  1186. ::
  1187. struct _snd_pcm_runtime {
  1188. /* -- Status -- */
  1189. struct snd_pcm_substream *trigger_master;
  1190. snd_timestamp_t trigger_tstamp; /* trigger timestamp */
  1191. int overrange;
  1192. snd_pcm_uframes_t avail_max;
  1193. snd_pcm_uframes_t hw_ptr_base; /* Position at buffer restart */
  1194. snd_pcm_uframes_t hw_ptr_interrupt; /* Position at interrupt time*/
  1195. /* -- HW params -- */
  1196. snd_pcm_access_t access; /* access mode */
  1197. snd_pcm_format_t format; /* SNDRV_PCM_FORMAT_* */
  1198. snd_pcm_subformat_t subformat; /* subformat */
  1199. unsigned int rate; /* rate in Hz */
  1200. unsigned int channels; /* channels */
  1201. snd_pcm_uframes_t period_size; /* period size */
  1202. unsigned int periods; /* periods */
  1203. snd_pcm_uframes_t buffer_size; /* buffer size */
  1204. unsigned int tick_time; /* tick time */
  1205. snd_pcm_uframes_t min_align; /* Min alignment for the format */
  1206. size_t byte_align;
  1207. unsigned int frame_bits;
  1208. unsigned int sample_bits;
  1209. unsigned int info;
  1210. unsigned int rate_num;
  1211. unsigned int rate_den;
  1212. /* -- SW params -- */
  1213. struct timespec tstamp_mode; /* mmap timestamp is updated */
  1214. unsigned int period_step;
  1215. unsigned int sleep_min; /* min ticks to sleep */
  1216. snd_pcm_uframes_t start_threshold;
  1217. snd_pcm_uframes_t stop_threshold;
  1218. snd_pcm_uframes_t silence_threshold; /* Silence filling happens when
  1219. noise is nearest than this */
  1220. snd_pcm_uframes_t silence_size; /* Silence filling size */
  1221. snd_pcm_uframes_t boundary; /* pointers wrap point */
  1222. snd_pcm_uframes_t silenced_start;
  1223. snd_pcm_uframes_t silenced_size;
  1224. snd_pcm_sync_id_t sync; /* hardware synchronization ID */
  1225. /* -- mmap -- */
  1226. volatile struct snd_pcm_mmap_status *status;
  1227. volatile struct snd_pcm_mmap_control *control;
  1228. atomic_t mmap_count;
  1229. /* -- locking / scheduling -- */
  1230. spinlock_t lock;
  1231. wait_queue_head_t sleep;
  1232. struct timer_list tick_timer;
  1233. struct fasync_struct *fasync;
  1234. /* -- private section -- */
  1235. void *private_data;
  1236. void (*private_free)(struct snd_pcm_runtime *runtime);
  1237. /* -- hardware description -- */
  1238. struct snd_pcm_hardware hw;
  1239. struct snd_pcm_hw_constraints hw_constraints;
  1240. /* -- timer -- */
  1241. unsigned int timer_resolution; /* timer resolution */
  1242. /* -- DMA -- */
  1243. unsigned char *dma_area; /* DMA area */
  1244. dma_addr_t dma_addr; /* physical bus address (not accessible from main CPU) */
  1245. size_t dma_bytes; /* size of DMA area */
  1246. struct snd_dma_buffer *dma_buffer_p; /* allocated buffer */
  1247. #if defined(CONFIG_SND_PCM_OSS) || defined(CONFIG_SND_PCM_OSS_MODULE)
  1248. /* -- OSS things -- */
  1249. struct snd_pcm_oss_runtime oss;
  1250. #endif
  1251. };
  1252. For the operators (callbacks) of each sound driver, most of these
  1253. records are supposed to be read-only. Only the PCM middle-layer changes
  1254. / updates them. The exceptions are the hardware description (hw) DMA
  1255. buffer information and the private data. Besides, if you use the
  1256. standard buffer allocation method via
  1257. :c:func:`snd_pcm_lib_malloc_pages()`, you don't need to set the
  1258. DMA buffer information by yourself.
  1259. In the sections below, important records are explained.
  1260. Hardware Description
  1261. ~~~~~~~~~~~~~~~~~~~~
  1262. The hardware descriptor (:c:type:`struct snd_pcm_hardware
  1263. <snd_pcm_hardware>`) contains the definitions of the fundamental
  1264. hardware configuration. Above all, you'll need to define this in the
  1265. `PCM open callback`_. Note that the runtime instance holds the copy of
  1266. the descriptor, not the pointer to the existing descriptor. That is,
  1267. in the open callback, you can modify the copied descriptor
  1268. (``runtime->hw``) as you need. For example, if the maximum number of
  1269. channels is 1 only on some chip models, you can still use the same
  1270. hardware descriptor and change the channels_max later:
  1271. ::
  1272. struct snd_pcm_runtime *runtime = substream->runtime;
  1273. ...
  1274. runtime->hw = snd_mychip_playback_hw; /* common definition */
  1275. if (chip->model == VERY_OLD_ONE)
  1276. runtime->hw.channels_max = 1;
  1277. Typically, you'll have a hardware descriptor as below:
  1278. ::
  1279. static struct snd_pcm_hardware snd_mychip_playback_hw = {
  1280. .info = (SNDRV_PCM_INFO_MMAP |
  1281. SNDRV_PCM_INFO_INTERLEAVED |
  1282. SNDRV_PCM_INFO_BLOCK_TRANSFER |
  1283. SNDRV_PCM_INFO_MMAP_VALID),
  1284. .formats = SNDRV_PCM_FMTBIT_S16_LE,
  1285. .rates = SNDRV_PCM_RATE_8000_48000,
  1286. .rate_min = 8000,
  1287. .rate_max = 48000,
  1288. .channels_min = 2,
  1289. .channels_max = 2,
  1290. .buffer_bytes_max = 32768,
  1291. .period_bytes_min = 4096,
  1292. .period_bytes_max = 32768,
  1293. .periods_min = 1,
  1294. .periods_max = 1024,
  1295. };
  1296. - The ``info`` field contains the type and capabilities of this
  1297. pcm. The bit flags are defined in ``<sound/asound.h>`` as
  1298. ``SNDRV_PCM_INFO_XXX``. Here, at least, you have to specify whether
  1299. the mmap is supported and which interleaved format is
  1300. supported. When the hardware supports mmap, add the
  1301. ``SNDRV_PCM_INFO_MMAP`` flag here. When the hardware supports the
  1302. interleaved or the non-interleaved formats,
  1303. ``SNDRV_PCM_INFO_INTERLEAVED`` or ``SNDRV_PCM_INFO_NONINTERLEAVED``
  1304. flag must be set, respectively. If both are supported, you can set
  1305. both, too.
  1306. In the above example, ``MMAP_VALID`` and ``BLOCK_TRANSFER`` are
  1307. specified for the OSS mmap mode. Usually both are set. Of course,
  1308. ``MMAP_VALID`` is set only if the mmap is really supported.
  1309. The other possible flags are ``SNDRV_PCM_INFO_PAUSE`` and
  1310. ``SNDRV_PCM_INFO_RESUME``. The ``PAUSE`` bit means that the pcm
  1311. supports the “pause” operation, while the ``RESUME`` bit means that
  1312. the pcm supports the full “suspend/resume” operation. If the
  1313. ``PAUSE`` flag is set, the ``trigger`` callback below must handle
  1314. the corresponding (pause push/release) commands. The suspend/resume
  1315. trigger commands can be defined even without the ``RESUME``
  1316. flag. See `Power Management`_ section for details.
  1317. When the PCM substreams can be synchronized (typically,
  1318. synchronized start/stop of a playback and a capture streams), you
  1319. can give ``SNDRV_PCM_INFO_SYNC_START``, too. In this case, you'll
  1320. need to check the linked-list of PCM substreams in the trigger
  1321. callback. This will be described in the later section.
  1322. - ``formats`` field contains the bit-flags of supported formats
  1323. (``SNDRV_PCM_FMTBIT_XXX``). If the hardware supports more than one
  1324. format, give all or'ed bits. In the example above, the signed 16bit
  1325. little-endian format is specified.
  1326. - ``rates`` field contains the bit-flags of supported rates
  1327. (``SNDRV_PCM_RATE_XXX``). When the chip supports continuous rates,
  1328. pass ``CONTINUOUS`` bit additionally. The pre-defined rate bits are
  1329. provided only for typical rates. If your chip supports
  1330. unconventional rates, you need to add the ``KNOT`` bit and set up
  1331. the hardware constraint manually (explained later).
  1332. - ``rate_min`` and ``rate_max`` define the minimum and maximum sample
  1333. rate. This should correspond somehow to ``rates`` bits.
  1334. - ``channel_min`` and ``channel_max`` define, as you might already
  1335. expected, the minimum and maximum number of channels.
  1336. - ``buffer_bytes_max`` defines the maximum buffer size in
  1337. bytes. There is no ``buffer_bytes_min`` field, since it can be
  1338. calculated from the minimum period size and the minimum number of
  1339. periods. Meanwhile, ``period_bytes_min`` and define the minimum and
  1340. maximum size of the period in bytes. ``periods_max`` and
  1341. ``periods_min`` define the maximum and minimum number of periods in
  1342. the buffer.
  1343. The “period” is a term that corresponds to a fragment in the OSS
  1344. world. The period defines the size at which a PCM interrupt is
  1345. generated. This size strongly depends on the hardware. Generally,
  1346. the smaller period size will give you more interrupts, that is,
  1347. more controls. In the case of capture, this size defines the input
  1348. latency. On the other hand, the whole buffer size defines the
  1349. output latency for the playback direction.
  1350. - There is also a field ``fifo_size``. This specifies the size of the
  1351. hardware FIFO, but currently it is neither used in the driver nor
  1352. in the alsa-lib. So, you can ignore this field.
  1353. PCM Configurations
  1354. ~~~~~~~~~~~~~~~~~~
  1355. Ok, let's go back again to the PCM runtime records. The most
  1356. frequently referred records in the runtime instance are the PCM
  1357. configurations. The PCM configurations are stored in the runtime
  1358. instance after the application sends ``hw_params`` data via
  1359. alsa-lib. There are many fields copied from hw_params and sw_params
  1360. structs. For example, ``format`` holds the format type chosen by the
  1361. application. This field contains the enum value
  1362. ``SNDRV_PCM_FORMAT_XXX``.
  1363. One thing to be noted is that the configured buffer and period sizes
  1364. are stored in “frames” in the runtime. In the ALSA world, ``1 frame =
  1365. channels \* samples-size``. For conversion between frames and bytes,
  1366. you can use the :c:func:`frames_to_bytes()` and
  1367. :c:func:`bytes_to_frames()` helper functions.
  1368. ::
  1369. period_bytes = frames_to_bytes(runtime, runtime->period_size);
  1370. Also, many software parameters (sw_params) are stored in frames, too.
  1371. Please check the type of the field. ``snd_pcm_uframes_t`` is for the
  1372. frames as unsigned integer while ``snd_pcm_sframes_t`` is for the
  1373. frames as signed integer.
  1374. DMA Buffer Information
  1375. ~~~~~~~~~~~~~~~~~~~~~~
  1376. The DMA buffer is defined by the following four fields, ``dma_area``,
  1377. ``dma_addr``, ``dma_bytes`` and ``dma_private``. The ``dma_area``
  1378. holds the buffer pointer (the logical address). You can call
  1379. :c:func:`memcpy()` from/to this pointer. Meanwhile, ``dma_addr`` holds
  1380. the physical address of the buffer. This field is specified only when
  1381. the buffer is a linear buffer. ``dma_bytes`` holds the size of buffer
  1382. in bytes. ``dma_private`` is used for the ALSA DMA allocator.
  1383. If you use a standard ALSA function,
  1384. :c:func:`snd_pcm_lib_malloc_pages()`, for allocating the buffer,
  1385. these fields are set by the ALSA middle layer, and you should *not*
  1386. change them by yourself. You can read them but not write them. On the
  1387. other hand, if you want to allocate the buffer by yourself, you'll
  1388. need to manage it in hw_params callback. At least, ``dma_bytes`` is
  1389. mandatory. ``dma_area`` is necessary when the buffer is mmapped. If
  1390. your driver doesn't support mmap, this field is not
  1391. necessary. ``dma_addr`` is also optional. You can use dma_private as
  1392. you like, too.
  1393. Running Status
  1394. ~~~~~~~~~~~~~~
  1395. The running status can be referred via ``runtime->status``. This is
  1396. the pointer to the :c:type:`struct snd_pcm_mmap_status
  1397. <snd_pcm_mmap_status>` record. For example, you can get the current
  1398. DMA hardware pointer via ``runtime->status->hw_ptr``.
  1399. The DMA application pointer can be referred via ``runtime->control``,
  1400. which points to the :c:type:`struct snd_pcm_mmap_control
  1401. <snd_pcm_mmap_control>` record. However, accessing directly to
  1402. this value is not recommended.
  1403. Private Data
  1404. ~~~~~~~~~~~~
  1405. You can allocate a record for the substream and store it in
  1406. ``runtime->private_data``. Usually, this is done in the `PCM open
  1407. callback`_. Don't mix this with ``pcm->private_data``. The
  1408. ``pcm->private_data`` usually points to the chip instance assigned
  1409. statically at the creation of PCM, while the ``runtime->private_data``
  1410. points to a dynamic data structure created at the PCM open
  1411. callback.
  1412. ::
  1413. static int snd_xxx_open(struct snd_pcm_substream *substream)
  1414. {
  1415. struct my_pcm_data *data;
  1416. ....
  1417. data = kmalloc(sizeof(*data), GFP_KERNEL);
  1418. substream->runtime->private_data = data;
  1419. ....
  1420. }
  1421. The allocated object must be released in the `close callback`_.
  1422. Operators
  1423. ---------
  1424. OK, now let me give details about each pcm callback (``ops``). In
  1425. general, every callback must return 0 if successful, or a negative
  1426. error number such as ``-EINVAL``. To choose an appropriate error
  1427. number, it is advised to check what value other parts of the kernel
  1428. return when the same kind of request fails.
  1429. The callback function takes at least the argument with :c:type:`struct
  1430. snd_pcm_substream <snd_pcm_substream>` pointer. To retrieve the chip
  1431. record from the given substream instance, you can use the following
  1432. macro.
  1433. ::
  1434. int xxx() {
  1435. struct mychip *chip = snd_pcm_substream_chip(substream);
  1436. ....
  1437. }
  1438. The macro reads ``substream->private_data``, which is a copy of
  1439. ``pcm->private_data``. You can override the former if you need to
  1440. assign different data records per PCM substream. For example, the
  1441. cmi8330 driver assigns different ``private_data`` for playback and
  1442. capture directions, because it uses two different codecs (SB- and
  1443. AD-compatible) for different directions.
  1444. PCM open callback
  1445. ~~~~~~~~~~~~~~~~~
  1446. ::
  1447. static int snd_xxx_open(struct snd_pcm_substream *substream);
  1448. This is called when a pcm substream is opened.
  1449. At least, here you have to initialize the ``runtime->hw``
  1450. record. Typically, this is done by like this:
  1451. ::
  1452. static int snd_xxx_open(struct snd_pcm_substream *substream)
  1453. {
  1454. struct mychip *chip = snd_pcm_substream_chip(substream);
  1455. struct snd_pcm_runtime *runtime = substream->runtime;
  1456. runtime->hw = snd_mychip_playback_hw;
  1457. return 0;
  1458. }
  1459. where ``snd_mychip_playback_hw`` is the pre-defined hardware
  1460. description.
  1461. You can allocate a private data in this callback, as described in
  1462. `Private Data`_ section.
  1463. If the hardware configuration needs more constraints, set the hardware
  1464. constraints here, too. See Constraints_ for more details.
  1465. close callback
  1466. ~~~~~~~~~~~~~~
  1467. ::
  1468. static int snd_xxx_close(struct snd_pcm_substream *substream);
  1469. Obviously, this is called when a pcm substream is closed.
  1470. Any private instance for a pcm substream allocated in the ``open``
  1471. callback will be released here.
  1472. ::
  1473. static int snd_xxx_close(struct snd_pcm_substream *substream)
  1474. {
  1475. ....
  1476. kfree(substream->runtime->private_data);
  1477. ....
  1478. }
  1479. ioctl callback
  1480. ~~~~~~~~~~~~~~
  1481. This is used for any special call to pcm ioctls. But usually you can
  1482. pass a generic ioctl callback, :c:func:`snd_pcm_lib_ioctl()`.
  1483. hw_params callback
  1484. ~~~~~~~~~~~~~~~~~~~
  1485. ::
  1486. static int snd_xxx_hw_params(struct snd_pcm_substream *substream,
  1487. struct snd_pcm_hw_params *hw_params);
  1488. This is called when the hardware parameter (``hw_params``) is set up
  1489. by the application, that is, once when the buffer size, the period
  1490. size, the format, etc. are defined for the pcm substream.
  1491. Many hardware setups should be done in this callback, including the
  1492. allocation of buffers.
  1493. Parameters to be initialized are retrieved by
  1494. :c:func:`params_xxx()` macros. To allocate buffer, you can call a
  1495. helper function,
  1496. ::
  1497. snd_pcm_lib_malloc_pages(substream, params_buffer_bytes(hw_params));
  1498. :c:func:`snd_pcm_lib_malloc_pages()` is available only when the
  1499. DMA buffers have been pre-allocated. See the section `Buffer Types`_
  1500. for more details.
  1501. Note that this and ``prepare`` callbacks may be called multiple times
  1502. per initialization. For example, the OSS emulation may call these
  1503. callbacks at each change via its ioctl.
  1504. Thus, you need to be careful not to allocate the same buffers many
  1505. times, which will lead to memory leaks! Calling the helper function
  1506. above many times is OK. It will release the previous buffer
  1507. automatically when it was already allocated.
  1508. Another note is that this callback is non-atomic (schedulable) as
  1509. default, i.e. when no ``nonatomic`` flag set. This is important,
  1510. because the ``trigger`` callback is atomic (non-schedulable). That is,
  1511. mutexes or any schedule-related functions are not available in
  1512. ``trigger`` callback. Please see the subsection Atomicity_ for
  1513. details.
  1514. hw_free callback
  1515. ~~~~~~~~~~~~~~~~~
  1516. ::
  1517. static int snd_xxx_hw_free(struct snd_pcm_substream *substream);
  1518. This is called to release the resources allocated via
  1519. ``hw_params``. For example, releasing the buffer via
  1520. :c:func:`snd_pcm_lib_malloc_pages()` is done by calling the
  1521. following:
  1522. ::
  1523. snd_pcm_lib_free_pages(substream);
  1524. This function is always called before the close callback is called.
  1525. Also, the callback may be called multiple times, too. Keep track
  1526. whether the resource was already released.
  1527. prepare callback
  1528. ~~~~~~~~~~~~~~~~
  1529. ::
  1530. static int snd_xxx_prepare(struct snd_pcm_substream *substream);
  1531. This callback is called when the pcm is “prepared”. You can set the
  1532. format type, sample rate, etc. here. The difference from ``hw_params``
  1533. is that the ``prepare`` callback will be called each time
  1534. :c:func:`snd_pcm_prepare()` is called, i.e. when recovering after
  1535. underruns, etc.
  1536. Note that this callback is now non-atomic. You can use
  1537. schedule-related functions safely in this callback.
  1538. In this and the following callbacks, you can refer to the values via
  1539. the runtime record, ``substream->runtime``. For example, to get the
  1540. current rate, format or channels, access to ``runtime->rate``,
  1541. ``runtime->format`` or ``runtime->channels``, respectively. The
  1542. physical address of the allocated buffer is set to
  1543. ``runtime->dma_area``. The buffer and period sizes are in
  1544. ``runtime->buffer_size`` and ``runtime->period_size``, respectively.
  1545. Be careful that this callback will be called many times at each setup,
  1546. too.
  1547. trigger callback
  1548. ~~~~~~~~~~~~~~~~
  1549. ::
  1550. static int snd_xxx_trigger(struct snd_pcm_substream *substream, int cmd);
  1551. This is called when the pcm is started, stopped or paused.
  1552. Which action is specified in the second argument,
  1553. ``SNDRV_PCM_TRIGGER_XXX`` in ``<sound/pcm.h>``. At least, the ``START``
  1554. and ``STOP`` commands must be defined in this callback.
  1555. ::
  1556. switch (cmd) {
  1557. case SNDRV_PCM_TRIGGER_START:
  1558. /* do something to start the PCM engine */
  1559. break;
  1560. case SNDRV_PCM_TRIGGER_STOP:
  1561. /* do something to stop the PCM engine */
  1562. break;
  1563. default:
  1564. return -EINVAL;
  1565. }
  1566. When the pcm supports the pause operation (given in the info field of
  1567. the hardware table), the ``PAUSE_PUSH`` and ``PAUSE_RELEASE`` commands
  1568. must be handled here, too. The former is the command to pause the pcm,
  1569. and the latter to restart the pcm again.
  1570. When the pcm supports the suspend/resume operation, regardless of full
  1571. or partial suspend/resume support, the ``SUSPEND`` and ``RESUME``
  1572. commands must be handled, too. These commands are issued when the
  1573. power-management status is changed. Obviously, the ``SUSPEND`` and
  1574. ``RESUME`` commands suspend and resume the pcm substream, and usually,
  1575. they are identical to the ``STOP`` and ``START`` commands, respectively.
  1576. See the `Power Management`_ section for details.
  1577. As mentioned, this callback is atomic as default unless ``nonatomic``
  1578. flag set, and you cannot call functions which may sleep. The
  1579. ``trigger`` callback should be as minimal as possible, just really
  1580. triggering the DMA. The other stuff should be initialized
  1581. ``hw_params`` and ``prepare`` callbacks properly beforehand.
  1582. pointer callback
  1583. ~~~~~~~~~~~~~~~~
  1584. ::
  1585. static snd_pcm_uframes_t snd_xxx_pointer(struct snd_pcm_substream *substream)
  1586. This callback is called when the PCM middle layer inquires the current
  1587. hardware position on the buffer. The position must be returned in
  1588. frames, ranging from 0 to ``buffer_size - 1``.
  1589. This is called usually from the buffer-update routine in the pcm
  1590. middle layer, which is invoked when :c:func:`snd_pcm_period_elapsed()`
  1591. is called in the interrupt routine. Then the pcm middle layer updates
  1592. the position and calculates the available space, and wakes up the
  1593. sleeping poll threads, etc.
  1594. This callback is also atomic as default.
  1595. copy_user, copy_kernel and fill_silence ops
  1596. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1597. These callbacks are not mandatory, and can be omitted in most cases.
  1598. These callbacks are used when the hardware buffer cannot be in the
  1599. normal memory space. Some chips have their own buffer on the hardware
  1600. which is not mappable. In such a case, you have to transfer the data
  1601. manually from the memory buffer to the hardware buffer. Or, if the
  1602. buffer is non-contiguous on both physical and virtual memory spaces,
  1603. these callbacks must be defined, too.
  1604. If these two callbacks are defined, copy and set-silence operations
  1605. are done by them. The detailed will be described in the later section
  1606. `Buffer and Memory Management`_.
  1607. ack callback
  1608. ~~~~~~~~~~~~
  1609. This callback is also not mandatory. This callback is called when the
  1610. ``appl_ptr`` is updated in read or write operations. Some drivers like
  1611. emu10k1-fx and cs46xx need to track the current ``appl_ptr`` for the
  1612. internal buffer, and this callback is useful only for such a purpose.
  1613. This callback is atomic as default.
  1614. page callback
  1615. ~~~~~~~~~~~~~
  1616. This callback is optional too. This callback is used mainly for
  1617. non-contiguous buffers. The mmap calls this callback to get the page
  1618. address. Some examples will be explained in the later section `Buffer
  1619. and Memory Management`_, too.
  1620. PCM Interrupt Handler
  1621. ---------------------
  1622. The rest of pcm stuff is the PCM interrupt handler. The role of PCM
  1623. interrupt handler in the sound driver is to update the buffer position
  1624. and to tell the PCM middle layer when the buffer position goes across
  1625. the prescribed period size. To inform this, call the
  1626. :c:func:`snd_pcm_period_elapsed()` function.
  1627. There are several types of sound chips to generate the interrupts.
  1628. Interrupts at the period (fragment) boundary
  1629. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1630. This is the most frequently found type: the hardware generates an
  1631. interrupt at each period boundary. In this case, you can call
  1632. :c:func:`snd_pcm_period_elapsed()` at each interrupt.
  1633. :c:func:`snd_pcm_period_elapsed()` takes the substream pointer as
  1634. its argument. Thus, you need to keep the substream pointer accessible
  1635. from the chip instance. For example, define ``substream`` field in the
  1636. chip record to hold the current running substream pointer, and set the
  1637. pointer value at ``open`` callback (and reset at ``close`` callback).
  1638. If you acquire a spinlock in the interrupt handler, and the lock is used
  1639. in other pcm callbacks, too, then you have to release the lock before
  1640. calling :c:func:`snd_pcm_period_elapsed()`, because
  1641. :c:func:`snd_pcm_period_elapsed()` calls other pcm callbacks
  1642. inside.
  1643. Typical code would be like:
  1644. ::
  1645. static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
  1646. {
  1647. struct mychip *chip = dev_id;
  1648. spin_lock(&chip->lock);
  1649. ....
  1650. if (pcm_irq_invoked(chip)) {
  1651. /* call updater, unlock before it */
  1652. spin_unlock(&chip->lock);
  1653. snd_pcm_period_elapsed(chip->substream);
  1654. spin_lock(&chip->lock);
  1655. /* acknowledge the interrupt if necessary */
  1656. }
  1657. ....
  1658. spin_unlock(&chip->lock);
  1659. return IRQ_HANDLED;
  1660. }
  1661. High frequency timer interrupts
  1662. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1663. This happens when the hardware doesn't generate interrupts at the period
  1664. boundary but issues timer interrupts at a fixed timer rate (e.g. es1968
  1665. or ymfpci drivers). In this case, you need to check the current hardware
  1666. position and accumulate the processed sample length at each interrupt.
  1667. When the accumulated size exceeds the period size, call
  1668. :c:func:`snd_pcm_period_elapsed()` and reset the accumulator.
  1669. Typical code would be like the following.
  1670. ::
  1671. static irqreturn_t snd_mychip_interrupt(int irq, void *dev_id)
  1672. {
  1673. struct mychip *chip = dev_id;
  1674. spin_lock(&chip->lock);
  1675. ....
  1676. if (pcm_irq_invoked(chip)) {
  1677. unsigned int last_ptr, size;
  1678. /* get the current hardware pointer (in frames) */
  1679. last_ptr = get_hw_ptr(chip);
  1680. /* calculate the processed frames since the
  1681. * last update
  1682. */
  1683. if (last_ptr < chip->last_ptr)
  1684. size = runtime->buffer_size + last_ptr
  1685. - chip->last_ptr;
  1686. else
  1687. size = last_ptr - chip->last_ptr;
  1688. /* remember the last updated point */
  1689. chip->last_ptr = last_ptr;
  1690. /* accumulate the size */
  1691. chip->size += size;
  1692. /* over the period boundary? */
  1693. if (chip->size >= runtime->period_size) {
  1694. /* reset the accumulator */
  1695. chip->size %= runtime->period_size;
  1696. /* call updater */
  1697. spin_unlock(&chip->lock);
  1698. snd_pcm_period_elapsed(substream);
  1699. spin_lock(&chip->lock);
  1700. }
  1701. /* acknowledge the interrupt if necessary */
  1702. }
  1703. ....
  1704. spin_unlock(&chip->lock);
  1705. return IRQ_HANDLED;
  1706. }
  1707. On calling :c:func:`snd_pcm_period_elapsed()`
  1708. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1709. In both cases, even if more than one period are elapsed, you don't have
  1710. to call :c:func:`snd_pcm_period_elapsed()` many times. Call only
  1711. once. And the pcm layer will check the current hardware pointer and
  1712. update to the latest status.
  1713. Atomicity
  1714. ---------
  1715. One of the most important (and thus difficult to debug) problems in
  1716. kernel programming are race conditions. In the Linux kernel, they are
  1717. usually avoided via spin-locks, mutexes or semaphores. In general, if a
  1718. race condition can happen in an interrupt handler, it has to be managed
  1719. atomically, and you have to use a spinlock to protect the critical
  1720. session. If the critical section is not in interrupt handler code and if
  1721. taking a relatively long time to execute is acceptable, you should use
  1722. mutexes or semaphores instead.
  1723. As already seen, some pcm callbacks are atomic and some are not. For
  1724. example, the ``hw_params`` callback is non-atomic, while ``trigger``
  1725. callback is atomic. This means, the latter is called already in a
  1726. spinlock held by the PCM middle layer. Please take this atomicity into
  1727. account when you choose a locking scheme in the callbacks.
  1728. In the atomic callbacks, you cannot use functions which may call
  1729. :c:func:`schedule()` or go to :c:func:`sleep()`. Semaphores and
  1730. mutexes can sleep, and hence they cannot be used inside the atomic
  1731. callbacks (e.g. ``trigger`` callback). To implement some delay in such a
  1732. callback, please use :c:func:`udelay()` or :c:func:`mdelay()`.
  1733. All three atomic callbacks (trigger, pointer, and ack) are called with
  1734. local interrupts disabled.
  1735. The recent changes in PCM core code, however, allow all PCM operations
  1736. to be non-atomic. This assumes that the all caller sides are in
  1737. non-atomic contexts. For example, the function
  1738. :c:func:`snd_pcm_period_elapsed()` is called typically from the
  1739. interrupt handler. But, if you set up the driver to use a threaded
  1740. interrupt handler, this call can be in non-atomic context, too. In such
  1741. a case, you can set ``nonatomic`` filed of :c:type:`struct snd_pcm
  1742. <snd_pcm>` object after creating it. When this flag is set, mutex
  1743. and rwsem are used internally in the PCM core instead of spin and
  1744. rwlocks, so that you can call all PCM functions safely in a non-atomic
  1745. context.
  1746. Constraints
  1747. -----------
  1748. If your chip supports unconventional sample rates, or only the limited
  1749. samples, you need to set a constraint for the condition.
  1750. For example, in order to restrict the sample rates in the some supported
  1751. values, use :c:func:`snd_pcm_hw_constraint_list()`. You need to
  1752. call this function in the open callback.
  1753. ::
  1754. static unsigned int rates[] =
  1755. {4000, 10000, 22050, 44100};
  1756. static struct snd_pcm_hw_constraint_list constraints_rates = {
  1757. .count = ARRAY_SIZE(rates),
  1758. .list = rates,
  1759. .mask = 0,
  1760. };
  1761. static int snd_mychip_pcm_open(struct snd_pcm_substream *substream)
  1762. {
  1763. int err;
  1764. ....
  1765. err = snd_pcm_hw_constraint_list(substream->runtime, 0,
  1766. SNDRV_PCM_HW_PARAM_RATE,
  1767. &constraints_rates);
  1768. if (err < 0)
  1769. return err;
  1770. ....
  1771. }
  1772. There are many different constraints. Look at ``sound/pcm.h`` for a
  1773. complete list. You can even define your own constraint rules. For
  1774. example, let's suppose my_chip can manage a substream of 1 channel if
  1775. and only if the format is ``S16_LE``, otherwise it supports any format
  1776. specified in the :c:type:`struct snd_pcm_hardware
  1777. <snd_pcm_hardware>` structure (or in any other
  1778. constraint_list). You can build a rule like this:
  1779. ::
  1780. static int hw_rule_channels_by_format(struct snd_pcm_hw_params *params,
  1781. struct snd_pcm_hw_rule *rule)
  1782. {
  1783. struct snd_interval *c = hw_param_interval(params,
  1784. SNDRV_PCM_HW_PARAM_CHANNELS);
  1785. struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
  1786. struct snd_interval ch;
  1787. snd_interval_any(&ch);
  1788. if (f->bits[0] == SNDRV_PCM_FMTBIT_S16_LE) {
  1789. ch.min = ch.max = 1;
  1790. ch.integer = 1;
  1791. return snd_interval_refine(c, &ch);
  1792. }
  1793. return 0;
  1794. }
  1795. Then you need to call this function to add your rule:
  1796. ::
  1797. snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_CHANNELS,
  1798. hw_rule_channels_by_format, NULL,
  1799. SNDRV_PCM_HW_PARAM_FORMAT, -1);
  1800. The rule function is called when an application sets the PCM format, and
  1801. it refines the number of channels accordingly. But an application may
  1802. set the number of channels before setting the format. Thus you also need
  1803. to define the inverse rule:
  1804. ::
  1805. static int hw_rule_format_by_channels(struct snd_pcm_hw_params *params,
  1806. struct snd_pcm_hw_rule *rule)
  1807. {
  1808. struct snd_interval *c = hw_param_interval(params,
  1809. SNDRV_PCM_HW_PARAM_CHANNELS);
  1810. struct snd_mask *f = hw_param_mask(params, SNDRV_PCM_HW_PARAM_FORMAT);
  1811. struct snd_mask fmt;
  1812. snd_mask_any(&fmt); /* Init the struct */
  1813. if (c->min < 2) {
  1814. fmt.bits[0] &= SNDRV_PCM_FMTBIT_S16_LE;
  1815. return snd_mask_refine(f, &fmt);
  1816. }
  1817. return 0;
  1818. }
  1819. ... and in the open callback:
  1820. ::
  1821. snd_pcm_hw_rule_add(substream->runtime, 0, SNDRV_PCM_HW_PARAM_FORMAT,
  1822. hw_rule_format_by_channels, NULL,
  1823. SNDRV_PCM_HW_PARAM_CHANNELS, -1);
  1824. I won't give more details here, rather I would like to say, “Luke, use
  1825. the source.”
  1826. Control Interface
  1827. =================
  1828. General
  1829. -------
  1830. The control interface is used widely for many switches, sliders, etc.
  1831. which are accessed from user-space. Its most important use is the mixer
  1832. interface. In other words, since ALSA 0.9.x, all the mixer stuff is
  1833. implemented on the control kernel API.
  1834. ALSA has a well-defined AC97 control module. If your chip supports only
  1835. the AC97 and nothing else, you can skip this section.
  1836. The control API is defined in ``<sound/control.h>``. Include this file
  1837. if you want to add your own controls.
  1838. Definition of Controls
  1839. ----------------------
  1840. To create a new control, you need to define the following three
  1841. callbacks: ``info``, ``get`` and ``put``. Then, define a
  1842. :c:type:`struct snd_kcontrol_new <snd_kcontrol_new>` record, such as:
  1843. ::
  1844. static struct snd_kcontrol_new my_control = {
  1845. .iface = SNDRV_CTL_ELEM_IFACE_MIXER,
  1846. .name = "PCM Playback Switch",
  1847. .index = 0,
  1848. .access = SNDRV_CTL_ELEM_ACCESS_READWRITE,
  1849. .private_value = 0xffff,
  1850. .info = my_control_info,
  1851. .get = my_control_get,
  1852. .put = my_control_put
  1853. };
  1854. The ``iface`` field specifies the control type,
  1855. ``SNDRV_CTL_ELEM_IFACE_XXX``, which is usually ``MIXER``. Use ``CARD``
  1856. for global controls that are not logically part of the mixer. If the
  1857. control is closely associated with some specific device on the sound
  1858. card, use ``HWDEP``, ``PCM``, ``RAWMIDI``, ``TIMER``, or ``SEQUENCER``,
  1859. and specify the device number with the ``device`` and ``subdevice``
  1860. fields.
  1861. The ``name`` is the name identifier string. Since ALSA 0.9.x, the
  1862. control name is very important, because its role is classified from
  1863. its name. There are pre-defined standard control names. The details
  1864. are described in the `Control Names`_ subsection.
  1865. The ``index`` field holds the index number of this control. If there
  1866. are several different controls with the same name, they can be
  1867. distinguished by the index number. This is the case when several
  1868. codecs exist on the card. If the index is zero, you can omit the
  1869. definition above.
  1870. The ``access`` field contains the access type of this control. Give
  1871. the combination of bit masks, ``SNDRV_CTL_ELEM_ACCESS_XXX``,
  1872. there. The details will be explained in the `Access Flags`_
  1873. subsection.
  1874. The ``private_value`` field contains an arbitrary long integer value
  1875. for this record. When using the generic ``info``, ``get`` and ``put``
  1876. callbacks, you can pass a value through this field. If several small
  1877. numbers are necessary, you can combine them in bitwise. Or, it's
  1878. possible to give a pointer (casted to unsigned long) of some record to
  1879. this field, too.
  1880. The ``tlv`` field can be used to provide metadata about the control;
  1881. see the `Metadata`_ subsection.
  1882. The other three are `Control Callbacks`_.
  1883. Control Names
  1884. -------------
  1885. There are some standards to define the control names. A control is
  1886. usually defined from the three parts as “SOURCE DIRECTION FUNCTION”.
  1887. The first, ``SOURCE``, specifies the source of the control, and is a
  1888. string such as “Master”, “PCM”, “CD” and “Line”. There are many
  1889. pre-defined sources.
  1890. The second, ``DIRECTION``, is one of the following strings according to
  1891. the direction of the control: “Playback”, “Capture”, “Bypass Playback”
  1892. and “Bypass Capture”. Or, it can be omitted, meaning both playback and
  1893. capture directions.
  1894. The third, ``FUNCTION``, is one of the following strings according to
  1895. the function of the control: “Switch”, “Volume” and “Route”.
  1896. The example of control names are, thus, “Master Capture Switch” or “PCM
  1897. Playback Volume”.
  1898. There are some exceptions:
  1899. Global capture and playback
  1900. ~~~~~~~~~~~~~~~~~~~~~~~~~~~
  1901. “Capture Source”, “Capture Switch” and “Capture Volume” are used for the
  1902. global capture (input) source, switch and volume. Similarly, “Playback
  1903. Switch” and “Playback Volume” are used for the global output gain switch
  1904. and volume.
  1905. Tone-controls
  1906. ~~~~~~~~~~~~~
  1907. tone-control switch and volumes are specified like “Tone Control - XXX”,
  1908. e.g. “Tone Control - Switch”, “Tone Control - Bass”, “Tone Control -
  1909. Center”.
  1910. 3D controls
  1911. ~~~~~~~~~~~
  1912. 3D-control switches and volumes are specified like “3D Control - XXX”,
  1913. e.g. “3D Control - Switch”, “3D Control - Center”, “3D Control - Space”.
  1914. Mic boost
  1915. ~~~~~~~~~
  1916. Mic-boost switch is set as “Mic Boost” or “Mic Boost (6dB)”.
  1917. More precise information can be found in
  1918. ``Documentation/sound/designs/control-names.rst``.
  1919. Access Flags
  1920. ------------
  1921. The access flag is the bitmask which specifies the access type of the
  1922. given control. The default access type is
  1923. ``SNDRV_CTL_ELEM_ACCESS_READWRITE``, which means both read and write are
  1924. allowed to this control. When the access flag is omitted (i.e. = 0), it
  1925. is considered as ``READWRITE`` access as default.
  1926. When the control is read-only, pass ``SNDRV_CTL_ELEM_ACCESS_READ``
  1927. instead. In this case, you don't have to define the ``put`` callback.
  1928. Similarly, when the control is write-only (although it's a rare case),
  1929. you can use the ``WRITE`` flag instead, and you don't need the ``get``
  1930. callback.
  1931. If the control value changes frequently (e.g. the VU meter),
  1932. ``VOLATILE`` flag should be given. This means that the control may be
  1933. changed without `Change notification`_. Applications should poll such
  1934. a control constantly.
  1935. When the control is inactive, set the ``INACTIVE`` flag, too. There are
  1936. ``LOCK`` and ``OWNER`` flags to change the write permissions.
  1937. Control Callbacks
  1938. -----------------
  1939. info callback
  1940. ~~~~~~~~~~~~~
  1941. The ``info`` callback is used to get detailed information on this
  1942. control. This must store the values of the given :c:type:`struct
  1943. snd_ctl_elem_info <snd_ctl_elem_info>` object. For example,
  1944. for a boolean control with a single element:
  1945. ::
  1946. static int snd_myctl_mono_info(struct snd_kcontrol *kcontrol,
  1947. struct snd_ctl_elem_info *uinfo)
  1948. {
  1949. uinfo->type = SNDRV_CTL_ELEM_TYPE_BOOLEAN;
  1950. uinfo->count = 1;
  1951. uinfo->value.integer.min = 0;
  1952. uinfo->value.integer.max = 1;
  1953. return 0;
  1954. }
  1955. The ``type`` field specifies the type of the control. There are
  1956. ``BOOLEAN``, ``INTEGER``, ``ENUMERATED``, ``BYTES``, ``IEC958`` and
  1957. ``INTEGER64``. The ``count`` field specifies the number of elements in
  1958. this control. For example, a stereo volume would have count = 2. The
  1959. ``value`` field is a union, and the values stored are depending on the
  1960. type. The boolean and integer types are identical.
  1961. The enumerated type is a bit different from others. You'll need to set
  1962. the string for the currently given item index.
  1963. ::
  1964. static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,
  1965. struct snd_ctl_elem_info *uinfo)
  1966. {
  1967. static char *texts[4] = {
  1968. "First", "Second", "Third", "Fourth"
  1969. };
  1970. uinfo->type = SNDRV_CTL_ELEM_TYPE_ENUMERATED;
  1971. uinfo->count = 1;
  1972. uinfo->value.enumerated.items = 4;
  1973. if (uinfo->value.enumerated.item > 3)
  1974. uinfo->value.enumerated.item = 3;
  1975. strcpy(uinfo->value.enumerated.name,
  1976. texts[uinfo->value.enumerated.item]);
  1977. return 0;
  1978. }
  1979. The above callback can be simplified with a helper function,
  1980. :c:func:`snd_ctl_enum_info()`. The final code looks like below.
  1981. (You can pass ``ARRAY_SIZE(texts)`` instead of 4 in the third argument;
  1982. it's a matter of taste.)
  1983. ::
  1984. static int snd_myctl_enum_info(struct snd_kcontrol *kcontrol,
  1985. struct snd_ctl_elem_info *uinfo)
  1986. {
  1987. static char *texts[4] = {
  1988. "First", "Second", "Third", "Fourth"
  1989. };
  1990. return snd_ctl_enum_info(uinfo, 1, 4, texts);
  1991. }
  1992. Some common info callbacks are available for your convenience:
  1993. :c:func:`snd_ctl_boolean_mono_info()` and
  1994. :c:func:`snd_ctl_boolean_stereo_info()`. Obviously, the former
  1995. is an info callback for a mono channel boolean item, just like
  1996. :c:func:`snd_myctl_mono_info()` above, and the latter is for a
  1997. stereo channel boolean item.
  1998. get callback
  1999. ~~~~~~~~~~~~
  2000. This callback is used to read the current value of the control and to
  2001. return to user-space.
  2002. For example,
  2003. ::
  2004. static int snd_myctl_get(struct snd_kcontrol *kcontrol,
  2005. struct snd_ctl_elem_value *ucontrol)
  2006. {
  2007. struct mychip *chip = snd_kcontrol_chip(kcontrol);
  2008. ucontrol->value.integer.value[0] = get_some_value(chip);
  2009. return 0;
  2010. }
  2011. The ``value`` field depends on the type of control as well as on the
  2012. info callback. For example, the sb driver uses this field to store the
  2013. register offset, the bit-shift and the bit-mask. The ``private_value``
  2014. field is set as follows:
  2015. ::
  2016. .private_value = reg | (shift << 16) | (mask << 24)
  2017. and is retrieved in callbacks like
  2018. ::
  2019. static int snd_sbmixer_get_single(struct snd_kcontrol *kcontrol,
  2020. struct snd_ctl_elem_value *ucontrol)
  2021. {
  2022. int reg = kcontrol->private_value & 0xff;
  2023. int shift = (kcontrol->private_value >> 16) & 0xff;
  2024. int mask = (kcontrol->private_value >> 24) & 0xff;
  2025. ....
  2026. }
  2027. In the ``get`` callback, you have to fill all the elements if the
  2028. control has more than one elements, i.e. ``count > 1``. In the example
  2029. above, we filled only one element (``value.integer.value[0]``) since
  2030. it's assumed as ``count = 1``.
  2031. put callback
  2032. ~~~~~~~~~~~~
  2033. This callback is used to write a value from user-space.
  2034. For example,
  2035. ::
  2036. static int snd_myctl_put(struct snd_kcontrol *kcontrol,
  2037. struct snd_ctl_elem_value *ucontrol)
  2038. {
  2039. struct mychip *chip = snd_kcontrol_chip(kcontrol);
  2040. int changed = 0;
  2041. if (chip->current_value !=
  2042. ucontrol->value.integer.value[0]) {
  2043. change_current_value(chip,
  2044. ucontrol->value.integer.value[0]);
  2045. changed = 1;
  2046. }
  2047. return changed;
  2048. }
  2049. As seen above, you have to return 1 if the value is changed. If the
  2050. value is not changed, return 0 instead. If any fatal error happens,
  2051. return a negative error code as usual.
  2052. As in the ``get`` callback, when the control has more than one
  2053. elements, all elements must be evaluated in this callback, too.
  2054. Callbacks are not atomic
  2055. ~~~~~~~~~~~~~~~~~~~~~~~~
  2056. All these three callbacks are basically not atomic.
  2057. Control Constructor
  2058. -------------------
  2059. When everything is ready, finally we can create a new control. To create
  2060. a control, there are two functions to be called,
  2061. :c:func:`snd_ctl_new1()` and :c:func:`snd_ctl_add()`.
  2062. In the simplest way, you can do like this:
  2063. ::
  2064. err = snd_ctl_add(card, snd_ctl_new1(&my_control, chip));
  2065. if (err < 0)
  2066. return err;
  2067. where ``my_control`` is the :c:type:`struct snd_kcontrol_new
  2068. <snd_kcontrol_new>` object defined above, and chip is the object
  2069. pointer to be passed to kcontrol->private_data which can be referred
  2070. to in callbacks.
  2071. :c:func:`snd_ctl_new1()` allocates a new :c:type:`struct
  2072. snd_kcontrol <snd_kcontrol>` instance, and
  2073. :c:func:`snd_ctl_add()` assigns the given control component to the
  2074. card.
  2075. Change Notification
  2076. -------------------
  2077. If you need to change and update a control in the interrupt routine, you
  2078. can call :c:func:`snd_ctl_notify()`. For example,
  2079. ::
  2080. snd_ctl_notify(card, SNDRV_CTL_EVENT_MASK_VALUE, id_pointer);
  2081. This function takes the card pointer, the event-mask, and the control id
  2082. pointer for the notification. The event-mask specifies the types of
  2083. notification, for example, in the above example, the change of control
  2084. values is notified. The id pointer is the pointer of :c:type:`struct
  2085. snd_ctl_elem_id <snd_ctl_elem_id>` to be notified. You can
  2086. find some examples in ``es1938.c`` or ``es1968.c`` for hardware volume
  2087. interrupts.
  2088. Metadata
  2089. --------
  2090. To provide information about the dB values of a mixer control, use on of
  2091. the ``DECLARE_TLV_xxx`` macros from ``<sound/tlv.h>`` to define a
  2092. variable containing this information, set the ``tlv.p`` field to point to
  2093. this variable, and include the ``SNDRV_CTL_ELEM_ACCESS_TLV_READ`` flag
  2094. in the ``access`` field; like this:
  2095. ::
  2096. static DECLARE_TLV_DB_SCALE(db_scale_my_control, -4050, 150, 0);
  2097. static struct snd_kcontrol_new my_control = {
  2098. ...
  2099. .access = SNDRV_CTL_ELEM_ACCESS_READWRITE |
  2100. SNDRV_CTL_ELEM_ACCESS_TLV_READ,
  2101. ...
  2102. .tlv.p = db_scale_my_control,
  2103. };
  2104. The :c:func:`DECLARE_TLV_DB_SCALE()` macro defines information
  2105. about a mixer control where each step in the control's value changes the
  2106. dB value by a constant dB amount. The first parameter is the name of the
  2107. variable to be defined. The second parameter is the minimum value, in
  2108. units of 0.01 dB. The third parameter is the step size, in units of 0.01
  2109. dB. Set the fourth parameter to 1 if the minimum value actually mutes
  2110. the control.
  2111. The :c:func:`DECLARE_TLV_DB_LINEAR()` macro defines information
  2112. about a mixer control where the control's value affects the output
  2113. linearly. The first parameter is the name of the variable to be defined.
  2114. The second parameter is the minimum value, in units of 0.01 dB. The
  2115. third parameter is the maximum value, in units of 0.01 dB. If the
  2116. minimum value mutes the control, set the second parameter to
  2117. ``TLV_DB_GAIN_MUTE``.
  2118. API for AC97 Codec
  2119. ==================
  2120. General
  2121. -------
  2122. The ALSA AC97 codec layer is a well-defined one, and you don't have to
  2123. write much code to control it. Only low-level control routines are
  2124. necessary. The AC97 codec API is defined in ``<sound/ac97_codec.h>``.
  2125. Full Code Example
  2126. -----------------
  2127. ::
  2128. struct mychip {
  2129. ....
  2130. struct snd_ac97 *ac97;
  2131. ....
  2132. };
  2133. static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,
  2134. unsigned short reg)
  2135. {
  2136. struct mychip *chip = ac97->private_data;
  2137. ....
  2138. /* read a register value here from the codec */
  2139. return the_register_value;
  2140. }
  2141. static void snd_mychip_ac97_write(struct snd_ac97 *ac97,
  2142. unsigned short reg, unsigned short val)
  2143. {
  2144. struct mychip *chip = ac97->private_data;
  2145. ....
  2146. /* write the given register value to the codec */
  2147. }
  2148. static int snd_mychip_ac97(struct mychip *chip)
  2149. {
  2150. struct snd_ac97_bus *bus;
  2151. struct snd_ac97_template ac97;
  2152. int err;
  2153. static struct snd_ac97_bus_ops ops = {
  2154. .write = snd_mychip_ac97_write,
  2155. .read = snd_mychip_ac97_read,
  2156. };
  2157. err = snd_ac97_bus(chip->card, 0, &ops, NULL, &bus);
  2158. if (err < 0)
  2159. return err;
  2160. memset(&ac97, 0, sizeof(ac97));
  2161. ac97.private_data = chip;
  2162. return snd_ac97_mixer(bus, &ac97, &chip->ac97);
  2163. }
  2164. AC97 Constructor
  2165. ----------------
  2166. To create an ac97 instance, first call :c:func:`snd_ac97_bus()`
  2167. with an ``ac97_bus_ops_t`` record with callback functions.
  2168. ::
  2169. struct snd_ac97_bus *bus;
  2170. static struct snd_ac97_bus_ops ops = {
  2171. .write = snd_mychip_ac97_write,
  2172. .read = snd_mychip_ac97_read,
  2173. };
  2174. snd_ac97_bus(card, 0, &ops, NULL, &pbus);
  2175. The bus record is shared among all belonging ac97 instances.
  2176. And then call :c:func:`snd_ac97_mixer()` with an :c:type:`struct
  2177. snd_ac97_template <snd_ac97_template>` record together with
  2178. the bus pointer created above.
  2179. ::
  2180. struct snd_ac97_template ac97;
  2181. int err;
  2182. memset(&ac97, 0, sizeof(ac97));
  2183. ac97.private_data = chip;
  2184. snd_ac97_mixer(bus, &ac97, &chip->ac97);
  2185. where chip->ac97 is a pointer to a newly created ``ac97_t``
  2186. instance. In this case, the chip pointer is set as the private data,
  2187. so that the read/write callback functions can refer to this chip
  2188. instance. This instance is not necessarily stored in the chip
  2189. record. If you need to change the register values from the driver, or
  2190. need the suspend/resume of ac97 codecs, keep this pointer to pass to
  2191. the corresponding functions.
  2192. AC97 Callbacks
  2193. --------------
  2194. The standard callbacks are ``read`` and ``write``. Obviously they
  2195. correspond to the functions for read and write accesses to the
  2196. hardware low-level codes.
  2197. The ``read`` callback returns the register value specified in the
  2198. argument.
  2199. ::
  2200. static unsigned short snd_mychip_ac97_read(struct snd_ac97 *ac97,
  2201. unsigned short reg)
  2202. {
  2203. struct mychip *chip = ac97->private_data;
  2204. ....
  2205. return the_register_value;
  2206. }
  2207. Here, the chip can be cast from ``ac97->private_data``.
  2208. Meanwhile, the ``write`` callback is used to set the register
  2209. value
  2210. ::
  2211. static void snd_mychip_ac97_write(struct snd_ac97 *ac97,
  2212. unsigned short reg, unsigned short val)
  2213. These callbacks are non-atomic like the control API callbacks.
  2214. There are also other callbacks: ``reset``, ``wait`` and ``init``.
  2215. The ``reset`` callback is used to reset the codec. If the chip
  2216. requires a special kind of reset, you can define this callback.
  2217. The ``wait`` callback is used to add some waiting time in the standard
  2218. initialization of the codec. If the chip requires the extra waiting
  2219. time, define this callback.
  2220. The ``init`` callback is used for additional initialization of the
  2221. codec.
  2222. Updating Registers in The Driver
  2223. --------------------------------
  2224. If you need to access to the codec from the driver, you can call the
  2225. following functions: :c:func:`snd_ac97_write()`,
  2226. :c:func:`snd_ac97_read()`, :c:func:`snd_ac97_update()` and
  2227. :c:func:`snd_ac97_update_bits()`.
  2228. Both :c:func:`snd_ac97_write()` and
  2229. :c:func:`snd_ac97_update()` functions are used to set a value to
  2230. the given register (``AC97_XXX``). The difference between them is that
  2231. :c:func:`snd_ac97_update()` doesn't write a value if the given
  2232. value has been already set, while :c:func:`snd_ac97_write()`
  2233. always rewrites the value.
  2234. ::
  2235. snd_ac97_write(ac97, AC97_MASTER, 0x8080);
  2236. snd_ac97_update(ac97, AC97_MASTER, 0x8080);
  2237. :c:func:`snd_ac97_read()` is used to read the value of the given
  2238. register. For example,
  2239. ::
  2240. value = snd_ac97_read(ac97, AC97_MASTER);
  2241. :c:func:`snd_ac97_update_bits()` is used to update some bits in
  2242. the given register.
  2243. ::
  2244. snd_ac97_update_bits(ac97, reg, mask, value);
  2245. Also, there is a function to change the sample rate (of a given register
  2246. such as ``AC97_PCM_FRONT_DAC_RATE``) when VRA or DRA is supported by the
  2247. codec: :c:func:`snd_ac97_set_rate()`.
  2248. ::
  2249. snd_ac97_set_rate(ac97, AC97_PCM_FRONT_DAC_RATE, 44100);
  2250. The following registers are available to set the rate:
  2251. ``AC97_PCM_MIC_ADC_RATE``, ``AC97_PCM_FRONT_DAC_RATE``,
  2252. ``AC97_PCM_LR_ADC_RATE``, ``AC97_SPDIF``. When ``AC97_SPDIF`` is
  2253. specified, the register is not really changed but the corresponding
  2254. IEC958 status bits will be updated.
  2255. Clock Adjustment
  2256. ----------------
  2257. In some chips, the clock of the codec isn't 48000 but using a PCI clock
  2258. (to save a quartz!). In this case, change the field ``bus->clock`` to
  2259. the corresponding value. For example, intel8x0 and es1968 drivers have
  2260. their own function to read from the clock.
  2261. Proc Files
  2262. ----------
  2263. The ALSA AC97 interface will create a proc file such as
  2264. ``/proc/asound/card0/codec97#0/ac97#0-0`` and ``ac97#0-0+regs``. You
  2265. can refer to these files to see the current status and registers of
  2266. the codec.
  2267. Multiple Codecs
  2268. ---------------
  2269. When there are several codecs on the same card, you need to call
  2270. :c:func:`snd_ac97_mixer()` multiple times with ``ac97.num=1`` or
  2271. greater. The ``num`` field specifies the codec number.
  2272. If you set up multiple codecs, you either need to write different
  2273. callbacks for each codec or check ``ac97->num`` in the callback
  2274. routines.
  2275. MIDI (MPU401-UART) Interface
  2276. ============================
  2277. General
  2278. -------
  2279. Many soundcards have built-in MIDI (MPU401-UART) interfaces. When the
  2280. soundcard supports the standard MPU401-UART interface, most likely you
  2281. can use the ALSA MPU401-UART API. The MPU401-UART API is defined in
  2282. ``<sound/mpu401.h>``.
  2283. Some soundchips have a similar but slightly different implementation of
  2284. mpu401 stuff. For example, emu10k1 has its own mpu401 routines.
  2285. MIDI Constructor
  2286. ----------------
  2287. To create a rawmidi object, call :c:func:`snd_mpu401_uart_new()`.
  2288. ::
  2289. struct snd_rawmidi *rmidi;
  2290. snd_mpu401_uart_new(card, 0, MPU401_HW_MPU401, port, info_flags,
  2291. irq, &rmidi);
  2292. The first argument is the card pointer, and the second is the index of
  2293. this component. You can create up to 8 rawmidi devices.
  2294. The third argument is the type of the hardware, ``MPU401_HW_XXX``. If
  2295. it's not a special one, you can use ``MPU401_HW_MPU401``.
  2296. The 4th argument is the I/O port address. Many backward-compatible
  2297. MPU401 have an I/O port such as 0x330. Or, it might be a part of its own
  2298. PCI I/O region. It depends on the chip design.
  2299. The 5th argument is a bitflag for additional information. When the I/O
  2300. port address above is part of the PCI I/O region, the MPU401 I/O port
  2301. might have been already allocated (reserved) by the driver itself. In
  2302. such a case, pass a bit flag ``MPU401_INFO_INTEGRATED``, and the
  2303. mpu401-uart layer will allocate the I/O ports by itself.
  2304. When the controller supports only the input or output MIDI stream, pass
  2305. the ``MPU401_INFO_INPUT`` or ``MPU401_INFO_OUTPUT`` bitflag,
  2306. respectively. Then the rawmidi instance is created as a single stream.
  2307. ``MPU401_INFO_MMIO`` bitflag is used to change the access method to MMIO
  2308. (via readb and writeb) instead of iob and outb. In this case, you have
  2309. to pass the iomapped address to :c:func:`snd_mpu401_uart_new()`.
  2310. When ``MPU401_INFO_TX_IRQ`` is set, the output stream isn't checked in
  2311. the default interrupt handler. The driver needs to call
  2312. :c:func:`snd_mpu401_uart_interrupt_tx()` by itself to start
  2313. processing the output stream in the irq handler.
  2314. If the MPU-401 interface shares its interrupt with the other logical
  2315. devices on the card, set ``MPU401_INFO_IRQ_HOOK`` (see
  2316. `below <#MIDI-Interrupt-Handler>`__).
  2317. Usually, the port address corresponds to the command port and port + 1
  2318. corresponds to the data port. If not, you may change the ``cport``
  2319. field of :c:type:`struct snd_mpu401 <snd_mpu401>` manually afterward.
  2320. However, :c:type:`struct snd_mpu401 <snd_mpu401>` pointer is
  2321. not returned explicitly by :c:func:`snd_mpu401_uart_new()`. You
  2322. need to cast ``rmidi->private_data`` to :c:type:`struct snd_mpu401
  2323. <snd_mpu401>` explicitly,
  2324. ::
  2325. struct snd_mpu401 *mpu;
  2326. mpu = rmidi->private_data;
  2327. and reset the ``cport`` as you like:
  2328. ::
  2329. mpu->cport = my_own_control_port;
  2330. The 6th argument specifies the ISA irq number that will be allocated. If
  2331. no interrupt is to be allocated (because your code is already allocating
  2332. a shared interrupt, or because the device does not use interrupts), pass
  2333. -1 instead. For a MPU-401 device without an interrupt, a polling timer
  2334. will be used instead.
  2335. MIDI Interrupt Handler
  2336. ----------------------
  2337. When the interrupt is allocated in
  2338. :c:func:`snd_mpu401_uart_new()`, an exclusive ISA interrupt
  2339. handler is automatically used, hence you don't have anything else to do
  2340. than creating the mpu401 stuff. Otherwise, you have to set
  2341. ``MPU401_INFO_IRQ_HOOK``, and call
  2342. :c:func:`snd_mpu401_uart_interrupt()` explicitly from your own
  2343. interrupt handler when it has determined that a UART interrupt has
  2344. occurred.
  2345. In this case, you need to pass the private_data of the returned rawmidi
  2346. object from :c:func:`snd_mpu401_uart_new()` as the second
  2347. argument of :c:func:`snd_mpu401_uart_interrupt()`.
  2348. ::
  2349. snd_mpu401_uart_interrupt(irq, rmidi->private_data, regs);
  2350. RawMIDI Interface
  2351. =================
  2352. Overview
  2353. --------
  2354. The raw MIDI interface is used for hardware MIDI ports that can be
  2355. accessed as a byte stream. It is not used for synthesizer chips that do
  2356. not directly understand MIDI.
  2357. ALSA handles file and buffer management. All you have to do is to write
  2358. some code to move data between the buffer and the hardware.
  2359. The rawmidi API is defined in ``<sound/rawmidi.h>``.
  2360. RawMIDI Constructor
  2361. -------------------
  2362. To create a rawmidi device, call the :c:func:`snd_rawmidi_new()`
  2363. function:
  2364. ::
  2365. struct snd_rawmidi *rmidi;
  2366. err = snd_rawmidi_new(chip->card, "MyMIDI", 0, outs, ins, &rmidi);
  2367. if (err < 0)
  2368. return err;
  2369. rmidi->private_data = chip;
  2370. strcpy(rmidi->name, "My MIDI");
  2371. rmidi->info_flags = SNDRV_RAWMIDI_INFO_OUTPUT |
  2372. SNDRV_RAWMIDI_INFO_INPUT |
  2373. SNDRV_RAWMIDI_INFO_DUPLEX;
  2374. The first argument is the card pointer, the second argument is the ID
  2375. string.
  2376. The third argument is the index of this component. You can create up to
  2377. 8 rawmidi devices.
  2378. The fourth and fifth arguments are the number of output and input
  2379. substreams, respectively, of this device (a substream is the equivalent
  2380. of a MIDI port).
  2381. Set the ``info_flags`` field to specify the capabilities of the
  2382. device. Set ``SNDRV_RAWMIDI_INFO_OUTPUT`` if there is at least one
  2383. output port, ``SNDRV_RAWMIDI_INFO_INPUT`` if there is at least one
  2384. input port, and ``SNDRV_RAWMIDI_INFO_DUPLEX`` if the device can handle
  2385. output and input at the same time.
  2386. After the rawmidi device is created, you need to set the operators
  2387. (callbacks) for each substream. There are helper functions to set the
  2388. operators for all the substreams of a device:
  2389. ::
  2390. snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_OUTPUT, &snd_mymidi_output_ops);
  2391. snd_rawmidi_set_ops(rmidi, SNDRV_RAWMIDI_STREAM_INPUT, &snd_mymidi_input_ops);
  2392. The operators are usually defined like this:
  2393. ::
  2394. static struct snd_rawmidi_ops snd_mymidi_output_ops = {
  2395. .open = snd_mymidi_output_open,
  2396. .close = snd_mymidi_output_close,
  2397. .trigger = snd_mymidi_output_trigger,
  2398. };
  2399. These callbacks are explained in the `RawMIDI Callbacks`_ section.
  2400. If there are more than one substream, you should give a unique name to
  2401. each of them:
  2402. ::
  2403. struct snd_rawmidi_substream *substream;
  2404. list_for_each_entry(substream,
  2405. &rmidi->streams[SNDRV_RAWMIDI_STREAM_OUTPUT].substreams,
  2406. list {
  2407. sprintf(substream->name, "My MIDI Port %d", substream->number + 1);
  2408. }
  2409. /* same for SNDRV_RAWMIDI_STREAM_INPUT */
  2410. RawMIDI Callbacks
  2411. -----------------
  2412. In all the callbacks, the private data that you've set for the rawmidi
  2413. device can be accessed as ``substream->rmidi->private_data``.
  2414. If there is more than one port, your callbacks can determine the port
  2415. index from the struct snd_rawmidi_substream data passed to each
  2416. callback:
  2417. ::
  2418. struct snd_rawmidi_substream *substream;
  2419. int index = substream->number;
  2420. RawMIDI open callback
  2421. ~~~~~~~~~~~~~~~~~~~~~
  2422. ::
  2423. static int snd_xxx_open(struct snd_rawmidi_substream *substream);
  2424. This is called when a substream is opened. You can initialize the
  2425. hardware here, but you shouldn't start transmitting/receiving data yet.
  2426. RawMIDI close callback
  2427. ~~~~~~~~~~~~~~~~~~~~~~
  2428. ::
  2429. static int snd_xxx_close(struct snd_rawmidi_substream *substream);
  2430. Guess what.
  2431. The ``open`` and ``close`` callbacks of a rawmidi device are
  2432. serialized with a mutex, and can sleep.
  2433. Rawmidi trigger callback for output substreams
  2434. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2435. ::
  2436. static void snd_xxx_output_trigger(struct snd_rawmidi_substream *substream, int up);
  2437. This is called with a nonzero ``up`` parameter when there is some data
  2438. in the substream buffer that must be transmitted.
  2439. To read data from the buffer, call
  2440. :c:func:`snd_rawmidi_transmit_peek()`. It will return the number
  2441. of bytes that have been read; this will be less than the number of bytes
  2442. requested when there are no more data in the buffer. After the data have
  2443. been transmitted successfully, call
  2444. :c:func:`snd_rawmidi_transmit_ack()` to remove the data from the
  2445. substream buffer:
  2446. ::
  2447. unsigned char data;
  2448. while (snd_rawmidi_transmit_peek(substream, &data, 1) == 1) {
  2449. if (snd_mychip_try_to_transmit(data))
  2450. snd_rawmidi_transmit_ack(substream, 1);
  2451. else
  2452. break; /* hardware FIFO full */
  2453. }
  2454. If you know beforehand that the hardware will accept data, you can use
  2455. the :c:func:`snd_rawmidi_transmit()` function which reads some
  2456. data and removes them from the buffer at once:
  2457. ::
  2458. while (snd_mychip_transmit_possible()) {
  2459. unsigned char data;
  2460. if (snd_rawmidi_transmit(substream, &data, 1) != 1)
  2461. break; /* no more data */
  2462. snd_mychip_transmit(data);
  2463. }
  2464. If you know beforehand how many bytes you can accept, you can use a
  2465. buffer size greater than one with the
  2466. :c:func:`snd_rawmidi_transmit\*()` functions.
  2467. The ``trigger`` callback must not sleep. If the hardware FIFO is full
  2468. before the substream buffer has been emptied, you have to continue
  2469. transmitting data later, either in an interrupt handler, or with a
  2470. timer if the hardware doesn't have a MIDI transmit interrupt.
  2471. The ``trigger`` callback is called with a zero ``up`` parameter when
  2472. the transmission of data should be aborted.
  2473. RawMIDI trigger callback for input substreams
  2474. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  2475. ::
  2476. static void snd_xxx_input_trigger(struct snd_rawmidi_substream *substream, int up);
  2477. This is called with a nonzero ``up`` parameter to enable receiving data,
  2478. or with a zero ``up`` parameter do disable receiving data.
  2479. The ``trigger`` callback must not sleep; the actual reading of data
  2480. from the device is usually done in an interrupt handler.
  2481. When data reception is enabled, your interrupt handler should call
  2482. :c:func:`snd_rawmidi_receive()` for all received data:
  2483. ::
  2484. void snd_mychip_midi_interrupt(...)
  2485. {
  2486. while (mychip_midi_available()) {
  2487. unsigned char data;
  2488. data = mychip_midi_read();
  2489. snd_rawmidi_receive(substream, &data, 1);
  2490. }
  2491. }
  2492. drain callback
  2493. ~~~~~~~~~~~~~~
  2494. ::
  2495. static void snd_xxx_drain(struct snd_rawmidi_substream *substream);
  2496. This is only used with output substreams. This function should wait
  2497. until all data read from the substream buffer have been transmitted.
  2498. This ensures that the device can be closed and the driver unloaded
  2499. without losing data.
  2500. This callback is optional. If you do not set ``drain`` in the struct
  2501. snd_rawmidi_ops structure, ALSA will simply wait for 50 milliseconds
  2502. instead.
  2503. Miscellaneous Devices
  2504. =====================
  2505. FM OPL3
  2506. -------
  2507. The FM OPL3 is still used in many chips (mainly for backward
  2508. compatibility). ALSA has a nice OPL3 FM control layer, too. The OPL3 API
  2509. is defined in ``<sound/opl3.h>``.
  2510. FM registers can be directly accessed through the direct-FM API, defined
  2511. in ``<sound/asound_fm.h>``. In ALSA native mode, FM registers are
  2512. accessed through the Hardware-Dependent Device direct-FM extension API,
  2513. whereas in OSS compatible mode, FM registers can be accessed with the
  2514. OSS direct-FM compatible API in ``/dev/dmfmX`` device.
  2515. To create the OPL3 component, you have two functions to call. The first
  2516. one is a constructor for the ``opl3_t`` instance.
  2517. ::
  2518. struct snd_opl3 *opl3;
  2519. snd_opl3_create(card, lport, rport, OPL3_HW_OPL3_XXX,
  2520. integrated, &opl3);
  2521. The first argument is the card pointer, the second one is the left port
  2522. address, and the third is the right port address. In most cases, the
  2523. right port is placed at the left port + 2.
  2524. The fourth argument is the hardware type.
  2525. When the left and right ports have been already allocated by the card
  2526. driver, pass non-zero to the fifth argument (``integrated``). Otherwise,
  2527. the opl3 module will allocate the specified ports by itself.
  2528. When the accessing the hardware requires special method instead of the
  2529. standard I/O access, you can create opl3 instance separately with
  2530. :c:func:`snd_opl3_new()`.
  2531. ::
  2532. struct snd_opl3 *opl3;
  2533. snd_opl3_new(card, OPL3_HW_OPL3_XXX, &opl3);
  2534. Then set ``command``, ``private_data`` and ``private_free`` for the
  2535. private access function, the private data and the destructor. The
  2536. ``l_port`` and ``r_port`` are not necessarily set. Only the command
  2537. must be set properly. You can retrieve the data from the
  2538. ``opl3->private_data`` field.
  2539. After creating the opl3 instance via :c:func:`snd_opl3_new()`,
  2540. call :c:func:`snd_opl3_init()` to initialize the chip to the
  2541. proper state. Note that :c:func:`snd_opl3_create()` always calls
  2542. it internally.
  2543. If the opl3 instance is created successfully, then create a hwdep device
  2544. for this opl3.
  2545. ::
  2546. struct snd_hwdep *opl3hwdep;
  2547. snd_opl3_hwdep_new(opl3, 0, 1, &opl3hwdep);
  2548. The first argument is the ``opl3_t`` instance you created, and the
  2549. second is the index number, usually 0.
  2550. The third argument is the index-offset for the sequencer client assigned
  2551. to the OPL3 port. When there is an MPU401-UART, give 1 for here (UART
  2552. always takes 0).
  2553. Hardware-Dependent Devices
  2554. --------------------------
  2555. Some chips need user-space access for special controls or for loading
  2556. the micro code. In such a case, you can create a hwdep
  2557. (hardware-dependent) device. The hwdep API is defined in
  2558. ``<sound/hwdep.h>``. You can find examples in opl3 driver or
  2559. ``isa/sb/sb16_csp.c``.
  2560. The creation of the ``hwdep`` instance is done via
  2561. :c:func:`snd_hwdep_new()`.
  2562. ::
  2563. struct snd_hwdep *hw;
  2564. snd_hwdep_new(card, "My HWDEP", 0, &hw);
  2565. where the third argument is the index number.
  2566. You can then pass any pointer value to the ``private_data``. If you
  2567. assign a private data, you should define the destructor, too. The
  2568. destructor function is set in the ``private_free`` field.
  2569. ::
  2570. struct mydata *p = kmalloc(sizeof(*p), GFP_KERNEL);
  2571. hw->private_data = p;
  2572. hw->private_free = mydata_free;
  2573. and the implementation of the destructor would be:
  2574. ::
  2575. static void mydata_free(struct snd_hwdep *hw)
  2576. {
  2577. struct mydata *p = hw->private_data;
  2578. kfree(p);
  2579. }
  2580. The arbitrary file operations can be defined for this instance. The file
  2581. operators are defined in the ``ops`` table. For example, assume that
  2582. this chip needs an ioctl.
  2583. ::
  2584. hw->ops.open = mydata_open;
  2585. hw->ops.ioctl = mydata_ioctl;
  2586. hw->ops.release = mydata_release;
  2587. And implement the callback functions as you like.
  2588. IEC958 (S/PDIF)
  2589. ---------------
  2590. Usually the controls for IEC958 devices are implemented via the control
  2591. interface. There is a macro to compose a name string for IEC958
  2592. controls, :c:func:`SNDRV_CTL_NAME_IEC958()` defined in
  2593. ``<include/asound.h>``.
  2594. There are some standard controls for IEC958 status bits. These controls
  2595. use the type ``SNDRV_CTL_ELEM_TYPE_IEC958``, and the size of element is
  2596. fixed as 4 bytes array (value.iec958.status[x]). For the ``info``
  2597. callback, you don't specify the value field for this type (the count
  2598. field must be set, though).
  2599. “IEC958 Playback Con Mask” is used to return the bit-mask for the IEC958
  2600. status bits of consumer mode. Similarly, “IEC958 Playback Pro Mask”
  2601. returns the bitmask for professional mode. They are read-only controls,
  2602. and are defined as MIXER controls (iface =
  2603. ``SNDRV_CTL_ELEM_IFACE_MIXER``).
  2604. Meanwhile, “IEC958 Playback Default” control is defined for getting and
  2605. setting the current default IEC958 bits. Note that this one is usually
  2606. defined as a PCM control (iface = ``SNDRV_CTL_ELEM_IFACE_PCM``),
  2607. although in some places it's defined as a MIXER control.
  2608. In addition, you can define the control switches to enable/disable or to
  2609. set the raw bit mode. The implementation will depend on the chip, but
  2610. the control should be named as “IEC958 xxx”, preferably using the
  2611. :c:func:`SNDRV_CTL_NAME_IEC958()` macro.
  2612. You can find several cases, for example, ``pci/emu10k1``,
  2613. ``pci/ice1712``, or ``pci/cmipci.c``.
  2614. Buffer and Memory Management
  2615. ============================
  2616. Buffer Types
  2617. ------------
  2618. ALSA provides several different buffer allocation functions depending on
  2619. the bus and the architecture. All these have a consistent API. The
  2620. allocation of physically-contiguous pages is done via
  2621. :c:func:`snd_malloc_xxx_pages()` function, where xxx is the bus
  2622. type.
  2623. The allocation of pages with fallback is
  2624. :c:func:`snd_malloc_xxx_pages_fallback()`. This function tries
  2625. to allocate the specified pages but if the pages are not available, it
  2626. tries to reduce the page sizes until enough space is found.
  2627. The release the pages, call :c:func:`snd_free_xxx_pages()`
  2628. function.
  2629. Usually, ALSA drivers try to allocate and reserve a large contiguous
  2630. physical space at the time the module is loaded for the later use. This
  2631. is called “pre-allocation”. As already written, you can call the
  2632. following function at pcm instance construction time (in the case of PCI
  2633. bus).
  2634. ::
  2635. snd_pcm_lib_preallocate_pages_for_all(pcm, SNDRV_DMA_TYPE_DEV,
  2636. snd_dma_pci_data(pci), size, max);
  2637. where ``size`` is the byte size to be pre-allocated and the ``max`` is
  2638. the maximum size to be changed via the ``prealloc`` proc file. The
  2639. allocator will try to get an area as large as possible within the
  2640. given size.
  2641. The second argument (type) and the third argument (device pointer) are
  2642. dependent on the bus. In the case of the ISA bus, pass
  2643. :c:func:`snd_dma_isa_data()` as the third argument with
  2644. ``SNDRV_DMA_TYPE_DEV`` type. For the continuous buffer unrelated to the
  2645. bus can be pre-allocated with ``SNDRV_DMA_TYPE_CONTINUOUS`` type and the
  2646. ``snd_dma_continuous_data(GFP_KERNEL)`` device pointer, where
  2647. ``GFP_KERNEL`` is the kernel allocation flag to use. For the PCI
  2648. scatter-gather buffers, use ``SNDRV_DMA_TYPE_DEV_SG`` with
  2649. ``snd_dma_pci_data(pci)`` (see the `Non-Contiguous Buffers`_
  2650. section).
  2651. Once the buffer is pre-allocated, you can use the allocator in the
  2652. ``hw_params`` callback:
  2653. ::
  2654. snd_pcm_lib_malloc_pages(substream, size);
  2655. Note that you have to pre-allocate to use this function.
  2656. External Hardware Buffers
  2657. -------------------------
  2658. Some chips have their own hardware buffers and the DMA transfer from the
  2659. host memory is not available. In such a case, you need to either 1)
  2660. copy/set the audio data directly to the external hardware buffer, or 2)
  2661. make an intermediate buffer and copy/set the data from it to the
  2662. external hardware buffer in interrupts (or in tasklets, preferably).
  2663. The first case works fine if the external hardware buffer is large
  2664. enough. This method doesn't need any extra buffers and thus is more
  2665. effective. You need to define the ``copy_user`` and ``copy_kernel``
  2666. callbacks for the data transfer, in addition to ``fill_silence``
  2667. callback for playback. However, there is a drawback: it cannot be
  2668. mmapped. The examples are GUS's GF1 PCM or emu8000's wavetable PCM.
  2669. The second case allows for mmap on the buffer, although you have to
  2670. handle an interrupt or a tasklet to transfer the data from the
  2671. intermediate buffer to the hardware buffer. You can find an example in
  2672. the vxpocket driver.
  2673. Another case is when the chip uses a PCI memory-map region for the
  2674. buffer instead of the host memory. In this case, mmap is available only
  2675. on certain architectures like the Intel one. In non-mmap mode, the data
  2676. cannot be transferred as in the normal way. Thus you need to define the
  2677. ``copy_user``, ``copy_kernel`` and ``fill_silence`` callbacks as well,
  2678. as in the cases above. The examples are found in ``rme32.c`` and
  2679. ``rme96.c``.
  2680. The implementation of the ``copy_user``, ``copy_kernel`` and
  2681. ``silence`` callbacks depends upon whether the hardware supports
  2682. interleaved or non-interleaved samples. The ``copy_user`` callback is
  2683. defined like below, a bit differently depending whether the direction
  2684. is playback or capture:
  2685. ::
  2686. static int playback_copy_user(struct snd_pcm_substream *substream,
  2687. int channel, unsigned long pos,
  2688. void __user *src, unsigned long count);
  2689. static int capture_copy_user(struct snd_pcm_substream *substream,
  2690. int channel, unsigned long pos,
  2691. void __user *dst, unsigned long count);
  2692. In the case of interleaved samples, the second argument (``channel``) is
  2693. not used. The third argument (``pos``) points the current position
  2694. offset in bytes.
  2695. The meaning of the fourth argument is different between playback and
  2696. capture. For playback, it holds the source data pointer, and for
  2697. capture, it's the destination data pointer.
  2698. The last argument is the number of bytes to be copied.
  2699. What you have to do in this callback is again different between playback
  2700. and capture directions. In the playback case, you copy the given amount
  2701. of data (``count``) at the specified pointer (``src``) to the specified
  2702. offset (``pos``) on the hardware buffer. When coded like memcpy-like
  2703. way, the copy would be like:
  2704. ::
  2705. my_memcpy_from_user(my_buffer + pos, src, count);
  2706. For the capture direction, you copy the given amount of data (``count``)
  2707. at the specified offset (``pos``) on the hardware buffer to the
  2708. specified pointer (``dst``).
  2709. ::
  2710. my_memcpy_to_user(dst, my_buffer + pos, count);
  2711. Here the functions are named as ``from_user`` and ``to_user`` because
  2712. it's the user-space buffer that is passed to these callbacks. That
  2713. is, the callback is supposed to copy from/to the user-space data
  2714. directly to/from the hardware buffer.
  2715. Careful readers might notice that these callbacks receive the
  2716. arguments in bytes, not in frames like other callbacks. It's because
  2717. it would make coding easier like the examples above, and also it makes
  2718. easier to unify both the interleaved and non-interleaved cases, as
  2719. explained in the following.
  2720. In the case of non-interleaved samples, the implementation will be a bit
  2721. more complicated. The callback is called for each channel, passed by
  2722. the second argument, so totally it's called for N-channels times per
  2723. transfer.
  2724. The meaning of other arguments are almost same as the interleaved
  2725. case. The callback is supposed to copy the data from/to the given
  2726. user-space buffer, but only for the given channel. For the detailed
  2727. implementations, please check ``isa/gus/gus_pcm.c`` or
  2728. "pci/rme9652/rme9652.c" as examples.
  2729. The above callbacks are the copy from/to the user-space buffer. There
  2730. are some cases where we want copy from/to the kernel-space buffer
  2731. instead. In such a case, ``copy_kernel`` callback is called. It'd
  2732. look like:
  2733. ::
  2734. static int playback_copy_kernel(struct snd_pcm_substream *substream,
  2735. int channel, unsigned long pos,
  2736. void *src, unsigned long count);
  2737. static int capture_copy_kernel(struct snd_pcm_substream *substream,
  2738. int channel, unsigned long pos,
  2739. void *dst, unsigned long count);
  2740. As found easily, the only difference is that the buffer pointer is
  2741. without ``__user`` prefix; that is, a kernel-buffer pointer is passed
  2742. in the fourth argument. Correspondingly, the implementation would be
  2743. a version without the user-copy, such as:
  2744. ::
  2745. my_memcpy(my_buffer + pos, src, count);
  2746. Usually for the playback, another callback ``fill_silence`` is
  2747. defined. It's implemented in a similar way as the copy callbacks
  2748. above:
  2749. ::
  2750. static int silence(struct snd_pcm_substream *substream, int channel,
  2751. unsigned long pos, unsigned long count);
  2752. The meanings of arguments are the same as in the ``copy_user`` and
  2753. ``copy_kernel`` callbacks, although there is no buffer pointer
  2754. argument. In the case of interleaved samples, the channel argument has
  2755. no meaning, as well as on ``copy_*`` callbacks.
  2756. The role of ``fill_silence`` callback is to set the given amount
  2757. (``count``) of silence data at the specified offset (``pos``) on the
  2758. hardware buffer. Suppose that the data format is signed (that is, the
  2759. silent-data is 0), and the implementation using a memset-like function
  2760. would be like:
  2761. ::
  2762. my_memset(my_buffer + pos, 0, count);
  2763. In the case of non-interleaved samples, again, the implementation
  2764. becomes a bit more complicated, as it's called N-times per transfer
  2765. for each channel. See, for example, ``isa/gus/gus_pcm.c``.
  2766. Non-Contiguous Buffers
  2767. ----------------------
  2768. If your hardware supports the page table as in emu10k1 or the buffer
  2769. descriptors as in via82xx, you can use the scatter-gather (SG) DMA. ALSA
  2770. provides an interface for handling SG-buffers. The API is provided in
  2771. ``<sound/pcm.h>``.
  2772. For creating the SG-buffer handler, call
  2773. :c:func:`snd_pcm_lib_preallocate_pages()` or
  2774. :c:func:`snd_pcm_lib_preallocate_pages_for_all()` with
  2775. ``SNDRV_DMA_TYPE_DEV_SG`` in the PCM constructor like other PCI
  2776. pre-allocator. You need to pass ``snd_dma_pci_data(pci)``, where pci is
  2777. the :c:type:`struct pci_dev <pci_dev>` pointer of the chip as
  2778. well. The ``struct snd_sg_buf`` instance is created as
  2779. ``substream->dma_private``. You can cast the pointer like:
  2780. ::
  2781. struct snd_sg_buf *sgbuf = (struct snd_sg_buf *)substream->dma_private;
  2782. Then call :c:func:`snd_pcm_lib_malloc_pages()` in the ``hw_params``
  2783. callback as well as in the case of normal PCI buffer. The SG-buffer
  2784. handler will allocate the non-contiguous kernel pages of the given size
  2785. and map them onto the virtually contiguous memory. The virtual pointer
  2786. is addressed in runtime->dma_area. The physical address
  2787. (``runtime->dma_addr``) is set to zero, because the buffer is
  2788. physically non-contiguous. The physical address table is set up in
  2789. ``sgbuf->table``. You can get the physical address at a certain offset
  2790. via :c:func:`snd_pcm_sgbuf_get_addr()`.
  2791. When a SG-handler is used, you need to set
  2792. :c:func:`snd_pcm_sgbuf_ops_page()` as the ``page`` callback. (See
  2793. `page callback`_ section.)
  2794. To release the data, call :c:func:`snd_pcm_lib_free_pages()` in
  2795. the ``hw_free`` callback as usual.
  2796. Vmalloc'ed Buffers
  2797. ------------------
  2798. It's possible to use a buffer allocated via :c:func:`vmalloc()`, for
  2799. example, for an intermediate buffer. Since the allocated pages are not
  2800. contiguous, you need to set the ``page`` callback to obtain the physical
  2801. address at every offset.
  2802. The implementation of ``page`` callback would be like this:
  2803. ::
  2804. #include <linux/vmalloc.h>
  2805. /* get the physical page pointer on the given offset */
  2806. static struct page *mychip_page(struct snd_pcm_substream *substream,
  2807. unsigned long offset)
  2808. {
  2809. void *pageptr = substream->runtime->dma_area + offset;
  2810. return vmalloc_to_page(pageptr);
  2811. }
  2812. Proc Interface
  2813. ==============
  2814. ALSA provides an easy interface for procfs. The proc files are very
  2815. useful for debugging. I recommend you set up proc files if you write a
  2816. driver and want to get a running status or register dumps. The API is
  2817. found in ``<sound/info.h>``.
  2818. To create a proc file, call :c:func:`snd_card_proc_new()`.
  2819. ::
  2820. struct snd_info_entry *entry;
  2821. int err = snd_card_proc_new(card, "my-file", &entry);
  2822. where the second argument specifies the name of the proc file to be
  2823. created. The above example will create a file ``my-file`` under the
  2824. card directory, e.g. ``/proc/asound/card0/my-file``.
  2825. Like other components, the proc entry created via
  2826. :c:func:`snd_card_proc_new()` will be registered and released
  2827. automatically in the card registration and release functions.
  2828. When the creation is successful, the function stores a new instance in
  2829. the pointer given in the third argument. It is initialized as a text
  2830. proc file for read only. To use this proc file as a read-only text file
  2831. as it is, set the read callback with a private data via
  2832. :c:func:`snd_info_set_text_ops()`.
  2833. ::
  2834. snd_info_set_text_ops(entry, chip, my_proc_read);
  2835. where the second argument (``chip``) is the private data to be used in
  2836. the callbacks. The third parameter specifies the read buffer size and
  2837. the fourth (``my_proc_read``) is the callback function, which is
  2838. defined like
  2839. ::
  2840. static void my_proc_read(struct snd_info_entry *entry,
  2841. struct snd_info_buffer *buffer);
  2842. In the read callback, use :c:func:`snd_iprintf()` for output
  2843. strings, which works just like normal :c:func:`printf()`. For
  2844. example,
  2845. ::
  2846. static void my_proc_read(struct snd_info_entry *entry,
  2847. struct snd_info_buffer *buffer)
  2848. {
  2849. struct my_chip *chip = entry->private_data;
  2850. snd_iprintf(buffer, "This is my chip!\n");
  2851. snd_iprintf(buffer, "Port = %ld\n", chip->port);
  2852. }
  2853. The file permissions can be changed afterwards. As default, it's set as
  2854. read only for all users. If you want to add write permission for the
  2855. user (root as default), do as follows:
  2856. ::
  2857. entry->mode = S_IFREG | S_IRUGO | S_IWUSR;
  2858. and set the write buffer size and the callback
  2859. ::
  2860. entry->c.text.write = my_proc_write;
  2861. For the write callback, you can use :c:func:`snd_info_get_line()`
  2862. to get a text line, and :c:func:`snd_info_get_str()` to retrieve
  2863. a string from the line. Some examples are found in
  2864. ``core/oss/mixer_oss.c``, core/oss/and ``pcm_oss.c``.
  2865. For a raw-data proc-file, set the attributes as follows:
  2866. ::
  2867. static struct snd_info_entry_ops my_file_io_ops = {
  2868. .read = my_file_io_read,
  2869. };
  2870. entry->content = SNDRV_INFO_CONTENT_DATA;
  2871. entry->private_data = chip;
  2872. entry->c.ops = &my_file_io_ops;
  2873. entry->size = 4096;
  2874. entry->mode = S_IFREG | S_IRUGO;
  2875. For the raw data, ``size`` field must be set properly. This specifies
  2876. the maximum size of the proc file access.
  2877. The read/write callbacks of raw mode are more direct than the text mode.
  2878. You need to use a low-level I/O functions such as
  2879. :c:func:`copy_from/to_user()` to transfer the data.
  2880. ::
  2881. static ssize_t my_file_io_read(struct snd_info_entry *entry,
  2882. void *file_private_data,
  2883. struct file *file,
  2884. char *buf,
  2885. size_t count,
  2886. loff_t pos)
  2887. {
  2888. if (copy_to_user(buf, local_data + pos, count))
  2889. return -EFAULT;
  2890. return count;
  2891. }
  2892. If the size of the info entry has been set up properly, ``count`` and
  2893. ``pos`` are guaranteed to fit within 0 and the given size. You don't
  2894. have to check the range in the callbacks unless any other condition is
  2895. required.
  2896. Power Management
  2897. ================
  2898. If the chip is supposed to work with suspend/resume functions, you need
  2899. to add power-management code to the driver. The additional code for
  2900. power-management should be ifdef-ed with ``CONFIG_PM``.
  2901. If the driver *fully* supports suspend/resume that is, the device can be
  2902. properly resumed to its state when suspend was called, you can set the
  2903. ``SNDRV_PCM_INFO_RESUME`` flag in the pcm info field. Usually, this is
  2904. possible when the registers of the chip can be safely saved and restored
  2905. to RAM. If this is set, the trigger callback is called with
  2906. ``SNDRV_PCM_TRIGGER_RESUME`` after the resume callback completes.
  2907. Even if the driver doesn't support PM fully but partial suspend/resume
  2908. is still possible, it's still worthy to implement suspend/resume
  2909. callbacks. In such a case, applications would reset the status by
  2910. calling :c:func:`snd_pcm_prepare()` and restart the stream
  2911. appropriately. Hence, you can define suspend/resume callbacks below but
  2912. don't set ``SNDRV_PCM_INFO_RESUME`` info flag to the PCM.
  2913. Note that the trigger with SUSPEND can always be called when
  2914. :c:func:`snd_pcm_suspend_all()` is called, regardless of the
  2915. ``SNDRV_PCM_INFO_RESUME`` flag. The ``RESUME`` flag affects only the
  2916. behavior of :c:func:`snd_pcm_resume()`. (Thus, in theory,
  2917. ``SNDRV_PCM_TRIGGER_RESUME`` isn't needed to be handled in the trigger
  2918. callback when no ``SNDRV_PCM_INFO_RESUME`` flag is set. But, it's better
  2919. to keep it for compatibility reasons.)
  2920. In the earlier version of ALSA drivers, a common power-management layer
  2921. was provided, but it has been removed. The driver needs to define the
  2922. suspend/resume hooks according to the bus the device is connected to. In
  2923. the case of PCI drivers, the callbacks look like below:
  2924. ::
  2925. #ifdef CONFIG_PM
  2926. static int snd_my_suspend(struct pci_dev *pci, pm_message_t state)
  2927. {
  2928. .... /* do things for suspend */
  2929. return 0;
  2930. }
  2931. static int snd_my_resume(struct pci_dev *pci)
  2932. {
  2933. .... /* do things for suspend */
  2934. return 0;
  2935. }
  2936. #endif
  2937. The scheme of the real suspend job is as follows.
  2938. 1. Retrieve the card and the chip data.
  2939. 2. Call :c:func:`snd_power_change_state()` with
  2940. ``SNDRV_CTL_POWER_D3hot`` to change the power status.
  2941. 3. Call :c:func:`snd_pcm_suspend_all()` to suspend the running
  2942. PCM streams.
  2943. 4. If AC97 codecs are used, call :c:func:`snd_ac97_suspend()` for
  2944. each codec.
  2945. 5. Save the register values if necessary.
  2946. 6. Stop the hardware if necessary.
  2947. 7. Disable the PCI device by calling
  2948. :c:func:`pci_disable_device()`. Then, call
  2949. :c:func:`pci_save_state()` at last.
  2950. A typical code would be like:
  2951. ::
  2952. static int mychip_suspend(struct pci_dev *pci, pm_message_t state)
  2953. {
  2954. /* (1) */
  2955. struct snd_card *card = pci_get_drvdata(pci);
  2956. struct mychip *chip = card->private_data;
  2957. /* (2) */
  2958. snd_power_change_state(card, SNDRV_CTL_POWER_D3hot);
  2959. /* (3) */
  2960. snd_pcm_suspend_all(chip->pcm);
  2961. /* (4) */
  2962. snd_ac97_suspend(chip->ac97);
  2963. /* (5) */
  2964. snd_mychip_save_registers(chip);
  2965. /* (6) */
  2966. snd_mychip_stop_hardware(chip);
  2967. /* (7) */
  2968. pci_disable_device(pci);
  2969. pci_save_state(pci);
  2970. return 0;
  2971. }
  2972. The scheme of the real resume job is as follows.
  2973. 1. Retrieve the card and the chip data.
  2974. 2. Set up PCI. First, call :c:func:`pci_restore_state()`. Then
  2975. enable the pci device again by calling
  2976. :c:func:`pci_enable_device()`. Call
  2977. :c:func:`pci_set_master()` if necessary, too.
  2978. 3. Re-initialize the chip.
  2979. 4. Restore the saved registers if necessary.
  2980. 5. Resume the mixer, e.g. calling :c:func:`snd_ac97_resume()`.
  2981. 6. Restart the hardware (if any).
  2982. 7. Call :c:func:`snd_power_change_state()` with
  2983. ``SNDRV_CTL_POWER_D0`` to notify the processes.
  2984. A typical code would be like:
  2985. ::
  2986. static int mychip_resume(struct pci_dev *pci)
  2987. {
  2988. /* (1) */
  2989. struct snd_card *card = pci_get_drvdata(pci);
  2990. struct mychip *chip = card->private_data;
  2991. /* (2) */
  2992. pci_restore_state(pci);
  2993. pci_enable_device(pci);
  2994. pci_set_master(pci);
  2995. /* (3) */
  2996. snd_mychip_reinit_chip(chip);
  2997. /* (4) */
  2998. snd_mychip_restore_registers(chip);
  2999. /* (5) */
  3000. snd_ac97_resume(chip->ac97);
  3001. /* (6) */
  3002. snd_mychip_restart_chip(chip);
  3003. /* (7) */
  3004. snd_power_change_state(card, SNDRV_CTL_POWER_D0);
  3005. return 0;
  3006. }
  3007. As shown in the above, it's better to save registers after suspending
  3008. the PCM operations via :c:func:`snd_pcm_suspend_all()` or
  3009. :c:func:`snd_pcm_suspend()`. It means that the PCM streams are
  3010. already stopped when the register snapshot is taken. But, remember that
  3011. you don't have to restart the PCM stream in the resume callback. It'll
  3012. be restarted via trigger call with ``SNDRV_PCM_TRIGGER_RESUME`` when
  3013. necessary.
  3014. OK, we have all callbacks now. Let's set them up. In the initialization
  3015. of the card, make sure that you can get the chip data from the card
  3016. instance, typically via ``private_data`` field, in case you created the
  3017. chip data individually.
  3018. ::
  3019. static int snd_mychip_probe(struct pci_dev *pci,
  3020. const struct pci_device_id *pci_id)
  3021. {
  3022. ....
  3023. struct snd_card *card;
  3024. struct mychip *chip;
  3025. int err;
  3026. ....
  3027. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  3028. 0, &card);
  3029. ....
  3030. chip = kzalloc(sizeof(*chip), GFP_KERNEL);
  3031. ....
  3032. card->private_data = chip;
  3033. ....
  3034. }
  3035. When you created the chip data with :c:func:`snd_card_new()`, it's
  3036. anyway accessible via ``private_data`` field.
  3037. ::
  3038. static int snd_mychip_probe(struct pci_dev *pci,
  3039. const struct pci_device_id *pci_id)
  3040. {
  3041. ....
  3042. struct snd_card *card;
  3043. struct mychip *chip;
  3044. int err;
  3045. ....
  3046. err = snd_card_new(&pci->dev, index[dev], id[dev], THIS_MODULE,
  3047. sizeof(struct mychip), &card);
  3048. ....
  3049. chip = card->private_data;
  3050. ....
  3051. }
  3052. If you need a space to save the registers, allocate the buffer for it
  3053. here, too, since it would be fatal if you cannot allocate a memory in
  3054. the suspend phase. The allocated buffer should be released in the
  3055. corresponding destructor.
  3056. And next, set suspend/resume callbacks to the pci_driver.
  3057. ::
  3058. static struct pci_driver driver = {
  3059. .name = KBUILD_MODNAME,
  3060. .id_table = snd_my_ids,
  3061. .probe = snd_my_probe,
  3062. .remove = snd_my_remove,
  3063. #ifdef CONFIG_PM
  3064. .suspend = snd_my_suspend,
  3065. .resume = snd_my_resume,
  3066. #endif
  3067. };
  3068. Module Parameters
  3069. =================
  3070. There are standard module options for ALSA. At least, each module should
  3071. have the ``index``, ``id`` and ``enable`` options.
  3072. If the module supports multiple cards (usually up to 8 = ``SNDRV_CARDS``
  3073. cards), they should be arrays. The default initial values are defined
  3074. already as constants for easier programming:
  3075. ::
  3076. static int index[SNDRV_CARDS] = SNDRV_DEFAULT_IDX;
  3077. static char *id[SNDRV_CARDS] = SNDRV_DEFAULT_STR;
  3078. static int enable[SNDRV_CARDS] = SNDRV_DEFAULT_ENABLE_PNP;
  3079. If the module supports only a single card, they could be single
  3080. variables, instead. ``enable`` option is not always necessary in this
  3081. case, but it would be better to have a dummy option for compatibility.
  3082. The module parameters must be declared with the standard
  3083. ``module_param()()``, ``module_param_array()()`` and
  3084. :c:func:`MODULE_PARM_DESC()` macros.
  3085. The typical coding would be like below:
  3086. ::
  3087. #define CARD_NAME "My Chip"
  3088. module_param_array(index, int, NULL, 0444);
  3089. MODULE_PARM_DESC(index, "Index value for " CARD_NAME " soundcard.");
  3090. module_param_array(id, charp, NULL, 0444);
  3091. MODULE_PARM_DESC(id, "ID string for " CARD_NAME " soundcard.");
  3092. module_param_array(enable, bool, NULL, 0444);
  3093. MODULE_PARM_DESC(enable, "Enable " CARD_NAME " soundcard.");
  3094. Also, don't forget to define the module description, classes, license
  3095. and devices. Especially, the recent modprobe requires to define the
  3096. module license as GPL, etc., otherwise the system is shown as “tainted”.
  3097. ::
  3098. MODULE_DESCRIPTION("My Chip");
  3099. MODULE_LICENSE("GPL");
  3100. MODULE_SUPPORTED_DEVICE("{{Vendor,My Chip Name}}");
  3101. How To Put Your Driver Into ALSA Tree
  3102. =====================================
  3103. General
  3104. -------
  3105. So far, you've learned how to write the driver codes. And you might have
  3106. a question now: how to put my own driver into the ALSA driver tree? Here
  3107. (finally :) the standard procedure is described briefly.
  3108. Suppose that you create a new PCI driver for the card “xyz”. The card
  3109. module name would be snd-xyz. The new driver is usually put into the
  3110. alsa-driver tree, ``alsa-driver/pci`` directory in the case of PCI
  3111. cards. Then the driver is evaluated, audited and tested by developers
  3112. and users. After a certain time, the driver will go to the alsa-kernel
  3113. tree (to the corresponding directory, such as ``alsa-kernel/pci``) and
  3114. eventually will be integrated into the Linux 2.6 tree (the directory
  3115. would be ``linux/sound/pci``).
  3116. In the following sections, the driver code is supposed to be put into
  3117. alsa-driver tree. The two cases are covered: a driver consisting of a
  3118. single source file and one consisting of several source files.
  3119. Driver with A Single Source File
  3120. --------------------------------
  3121. 1. Modify alsa-driver/pci/Makefile
  3122. Suppose you have a file xyz.c. Add the following two lines
  3123. ::
  3124. snd-xyz-objs := xyz.o
  3125. obj-$(CONFIG_SND_XYZ) += snd-xyz.o
  3126. 2. Create the Kconfig entry
  3127. Add the new entry of Kconfig for your xyz driver. config SND_XYZ
  3128. tristate "Foobar XYZ" depends on SND select SND_PCM help Say Y here
  3129. to include support for Foobar XYZ soundcard. To compile this driver
  3130. as a module, choose M here: the module will be called snd-xyz. the
  3131. line, select SND_PCM, specifies that the driver xyz supports PCM. In
  3132. addition to SND_PCM, the following components are supported for
  3133. select command: SND_RAWMIDI, SND_TIMER, SND_HWDEP,
  3134. SND_MPU401_UART, SND_OPL3_LIB, SND_OPL4_LIB, SND_VX_LIB,
  3135. SND_AC97_CODEC. Add the select command for each supported
  3136. component.
  3137. Note that some selections imply the lowlevel selections. For example,
  3138. PCM includes TIMER, MPU401_UART includes RAWMIDI, AC97_CODEC
  3139. includes PCM, and OPL3_LIB includes HWDEP. You don't need to give
  3140. the lowlevel selections again.
  3141. For the details of Kconfig script, refer to the kbuild documentation.
  3142. 3. Run cvscompile script to re-generate the configure script and build
  3143. the whole stuff again.
  3144. Drivers with Several Source Files
  3145. ---------------------------------
  3146. Suppose that the driver snd-xyz have several source files. They are
  3147. located in the new subdirectory, pci/xyz.
  3148. 1. Add a new directory (``xyz``) in ``alsa-driver/pci/Makefile`` as
  3149. below
  3150. ::
  3151. obj-$(CONFIG_SND) += xyz/
  3152. 2. Under the directory ``xyz``, create a Makefile
  3153. ::
  3154. ifndef SND_TOPDIR
  3155. SND_TOPDIR=../..
  3156. endif
  3157. include $(SND_TOPDIR)/toplevel.config
  3158. include $(SND_TOPDIR)/Makefile.conf
  3159. snd-xyz-objs := xyz.o abc.o def.o
  3160. obj-$(CONFIG_SND_XYZ) += snd-xyz.o
  3161. include $(SND_TOPDIR)/Rules.make
  3162. 3. Create the Kconfig entry
  3163. This procedure is as same as in the last section.
  3164. 4. Run cvscompile script to re-generate the configure script and build
  3165. the whole stuff again.
  3166. Useful Functions
  3167. ================
  3168. :c:func:`snd_printk()` and friends
  3169. ---------------------------------------
  3170. ALSA provides a verbose version of the :c:func:`printk()` function.
  3171. If a kernel config ``CONFIG_SND_VERBOSE_PRINTK`` is set, this function
  3172. prints the given message together with the file name and the line of the
  3173. caller. The ``KERN_XXX`` prefix is processed as well as the original
  3174. :c:func:`printk()` does, so it's recommended to add this prefix,
  3175. e.g. snd_printk(KERN_ERR "Oh my, sorry, it's extremely bad!\\n");
  3176. There are also :c:func:`printk()`'s for debugging.
  3177. :c:func:`snd_printd()` can be used for general debugging purposes.
  3178. If ``CONFIG_SND_DEBUG`` is set, this function is compiled, and works
  3179. just like :c:func:`snd_printk()`. If the ALSA is compiled without
  3180. the debugging flag, it's ignored.
  3181. :c:func:`snd_printdd()` is compiled in only when
  3182. ``CONFIG_SND_DEBUG_VERBOSE`` is set. Please note that
  3183. ``CONFIG_SND_DEBUG_VERBOSE`` is not set as default even if you configure
  3184. the alsa-driver with ``--with-debug=full`` option. You need to give
  3185. explicitly ``--with-debug=detect`` option instead.
  3186. :c:func:`snd_BUG()`
  3187. ------------------------
  3188. It shows the ``BUG?`` message and stack trace as well as
  3189. :c:func:`snd_BUG_ON()` at the point. It's useful to show that a
  3190. fatal error happens there.
  3191. When no debug flag is set, this macro is ignored.
  3192. :c:func:`snd_BUG_ON()`
  3193. ----------------------------
  3194. :c:func:`snd_BUG_ON()` macro is similar with
  3195. :c:func:`WARN_ON()` macro. For example, snd_BUG_ON(!pointer); or
  3196. it can be used as the condition, if (snd_BUG_ON(non_zero_is_bug))
  3197. return -EINVAL;
  3198. The macro takes an conditional expression to evaluate. When
  3199. ``CONFIG_SND_DEBUG``, is set, if the expression is non-zero, it shows
  3200. the warning message such as ``BUG? (xxx)`` normally followed by stack
  3201. trace. In both cases it returns the evaluated value.
  3202. Acknowledgments
  3203. ===============
  3204. I would like to thank Phil Kerr for his help for improvement and
  3205. corrections of this document.
  3206. Kevin Conder reformatted the original plain-text to the DocBook format.
  3207. Giuliano Pochini corrected typos and contributed the example codes in
  3208. the hardware constraints section.