writing-an-alsa-driver.rst 143 KB

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