spi.c 97 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621
  1. /*
  2. * SPI init/core code
  3. *
  4. * Copyright (C) 2005 David Brownell
  5. * Copyright (C) 2008 Secret Lab Technologies Ltd.
  6. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 2 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. */
  17. #include <linux/kernel.h>
  18. #include <linux/device.h>
  19. #include <linux/init.h>
  20. #include <linux/cache.h>
  21. #include <linux/dma-mapping.h>
  22. #include <linux/dmaengine.h>
  23. #include <linux/mutex.h>
  24. #include <linux/of_device.h>
  25. #include <linux/of_irq.h>
  26. #include <linux/clk/clk-conf.h>
  27. #include <linux/slab.h>
  28. #include <linux/mod_devicetable.h>
  29. #include <linux/spi/spi.h>
  30. #include <linux/spi/spi-mem.h>
  31. #include <linux/of_gpio.h>
  32. #include <linux/pm_runtime.h>
  33. #include <linux/pm_domain.h>
  34. #include <linux/property.h>
  35. #include <linux/export.h>
  36. #include <linux/sched/rt.h>
  37. #include <uapi/linux/sched/types.h>
  38. #include <linux/delay.h>
  39. #include <linux/kthread.h>
  40. #include <linux/ioport.h>
  41. #include <linux/acpi.h>
  42. #include <linux/highmem.h>
  43. #include <linux/idr.h>
  44. #include <linux/platform_data/x86/apple.h>
  45. #define CREATE_TRACE_POINTS
  46. #include <trace/events/spi.h>
  47. #include "internals.h"
  48. static DEFINE_IDR(spi_master_idr);
  49. static void spidev_release(struct device *dev)
  50. {
  51. struct spi_device *spi = to_spi_device(dev);
  52. /* spi controllers may cleanup for released devices */
  53. if (spi->controller->cleanup)
  54. spi->controller->cleanup(spi);
  55. spi_controller_put(spi->controller);
  56. kfree(spi);
  57. }
  58. static ssize_t
  59. modalias_show(struct device *dev, struct device_attribute *a, char *buf)
  60. {
  61. const struct spi_device *spi = to_spi_device(dev);
  62. int len;
  63. len = acpi_device_modalias(dev, buf, PAGE_SIZE - 1);
  64. if (len != -ENODEV)
  65. return len;
  66. return sprintf(buf, "%s%s\n", SPI_MODULE_PREFIX, spi->modalias);
  67. }
  68. static DEVICE_ATTR_RO(modalias);
  69. #define SPI_STATISTICS_ATTRS(field, file) \
  70. static ssize_t spi_controller_##field##_show(struct device *dev, \
  71. struct device_attribute *attr, \
  72. char *buf) \
  73. { \
  74. struct spi_controller *ctlr = container_of(dev, \
  75. struct spi_controller, dev); \
  76. return spi_statistics_##field##_show(&ctlr->statistics, buf); \
  77. } \
  78. static struct device_attribute dev_attr_spi_controller_##field = { \
  79. .attr = { .name = file, .mode = 0444 }, \
  80. .show = spi_controller_##field##_show, \
  81. }; \
  82. static ssize_t spi_device_##field##_show(struct device *dev, \
  83. struct device_attribute *attr, \
  84. char *buf) \
  85. { \
  86. struct spi_device *spi = to_spi_device(dev); \
  87. return spi_statistics_##field##_show(&spi->statistics, buf); \
  88. } \
  89. static struct device_attribute dev_attr_spi_device_##field = { \
  90. .attr = { .name = file, .mode = 0444 }, \
  91. .show = spi_device_##field##_show, \
  92. }
  93. #define SPI_STATISTICS_SHOW_NAME(name, file, field, format_string) \
  94. static ssize_t spi_statistics_##name##_show(struct spi_statistics *stat, \
  95. char *buf) \
  96. { \
  97. unsigned long flags; \
  98. ssize_t len; \
  99. spin_lock_irqsave(&stat->lock, flags); \
  100. len = sprintf(buf, format_string, stat->field); \
  101. spin_unlock_irqrestore(&stat->lock, flags); \
  102. return len; \
  103. } \
  104. SPI_STATISTICS_ATTRS(name, file)
  105. #define SPI_STATISTICS_SHOW(field, format_string) \
  106. SPI_STATISTICS_SHOW_NAME(field, __stringify(field), \
  107. field, format_string)
  108. SPI_STATISTICS_SHOW(messages, "%lu");
  109. SPI_STATISTICS_SHOW(transfers, "%lu");
  110. SPI_STATISTICS_SHOW(errors, "%lu");
  111. SPI_STATISTICS_SHOW(timedout, "%lu");
  112. SPI_STATISTICS_SHOW(spi_sync, "%lu");
  113. SPI_STATISTICS_SHOW(spi_sync_immediate, "%lu");
  114. SPI_STATISTICS_SHOW(spi_async, "%lu");
  115. SPI_STATISTICS_SHOW(bytes, "%llu");
  116. SPI_STATISTICS_SHOW(bytes_rx, "%llu");
  117. SPI_STATISTICS_SHOW(bytes_tx, "%llu");
  118. #define SPI_STATISTICS_TRANSFER_BYTES_HISTO(index, number) \
  119. SPI_STATISTICS_SHOW_NAME(transfer_bytes_histo##index, \
  120. "transfer_bytes_histo_" number, \
  121. transfer_bytes_histo[index], "%lu")
  122. SPI_STATISTICS_TRANSFER_BYTES_HISTO(0, "0-1");
  123. SPI_STATISTICS_TRANSFER_BYTES_HISTO(1, "2-3");
  124. SPI_STATISTICS_TRANSFER_BYTES_HISTO(2, "4-7");
  125. SPI_STATISTICS_TRANSFER_BYTES_HISTO(3, "8-15");
  126. SPI_STATISTICS_TRANSFER_BYTES_HISTO(4, "16-31");
  127. SPI_STATISTICS_TRANSFER_BYTES_HISTO(5, "32-63");
  128. SPI_STATISTICS_TRANSFER_BYTES_HISTO(6, "64-127");
  129. SPI_STATISTICS_TRANSFER_BYTES_HISTO(7, "128-255");
  130. SPI_STATISTICS_TRANSFER_BYTES_HISTO(8, "256-511");
  131. SPI_STATISTICS_TRANSFER_BYTES_HISTO(9, "512-1023");
  132. SPI_STATISTICS_TRANSFER_BYTES_HISTO(10, "1024-2047");
  133. SPI_STATISTICS_TRANSFER_BYTES_HISTO(11, "2048-4095");
  134. SPI_STATISTICS_TRANSFER_BYTES_HISTO(12, "4096-8191");
  135. SPI_STATISTICS_TRANSFER_BYTES_HISTO(13, "8192-16383");
  136. SPI_STATISTICS_TRANSFER_BYTES_HISTO(14, "16384-32767");
  137. SPI_STATISTICS_TRANSFER_BYTES_HISTO(15, "32768-65535");
  138. SPI_STATISTICS_TRANSFER_BYTES_HISTO(16, "65536+");
  139. SPI_STATISTICS_SHOW(transfers_split_maxsize, "%lu");
  140. static struct attribute *spi_dev_attrs[] = {
  141. &dev_attr_modalias.attr,
  142. NULL,
  143. };
  144. static const struct attribute_group spi_dev_group = {
  145. .attrs = spi_dev_attrs,
  146. };
  147. static struct attribute *spi_device_statistics_attrs[] = {
  148. &dev_attr_spi_device_messages.attr,
  149. &dev_attr_spi_device_transfers.attr,
  150. &dev_attr_spi_device_errors.attr,
  151. &dev_attr_spi_device_timedout.attr,
  152. &dev_attr_spi_device_spi_sync.attr,
  153. &dev_attr_spi_device_spi_sync_immediate.attr,
  154. &dev_attr_spi_device_spi_async.attr,
  155. &dev_attr_spi_device_bytes.attr,
  156. &dev_attr_spi_device_bytes_rx.attr,
  157. &dev_attr_spi_device_bytes_tx.attr,
  158. &dev_attr_spi_device_transfer_bytes_histo0.attr,
  159. &dev_attr_spi_device_transfer_bytes_histo1.attr,
  160. &dev_attr_spi_device_transfer_bytes_histo2.attr,
  161. &dev_attr_spi_device_transfer_bytes_histo3.attr,
  162. &dev_attr_spi_device_transfer_bytes_histo4.attr,
  163. &dev_attr_spi_device_transfer_bytes_histo5.attr,
  164. &dev_attr_spi_device_transfer_bytes_histo6.attr,
  165. &dev_attr_spi_device_transfer_bytes_histo7.attr,
  166. &dev_attr_spi_device_transfer_bytes_histo8.attr,
  167. &dev_attr_spi_device_transfer_bytes_histo9.attr,
  168. &dev_attr_spi_device_transfer_bytes_histo10.attr,
  169. &dev_attr_spi_device_transfer_bytes_histo11.attr,
  170. &dev_attr_spi_device_transfer_bytes_histo12.attr,
  171. &dev_attr_spi_device_transfer_bytes_histo13.attr,
  172. &dev_attr_spi_device_transfer_bytes_histo14.attr,
  173. &dev_attr_spi_device_transfer_bytes_histo15.attr,
  174. &dev_attr_spi_device_transfer_bytes_histo16.attr,
  175. &dev_attr_spi_device_transfers_split_maxsize.attr,
  176. NULL,
  177. };
  178. static const struct attribute_group spi_device_statistics_group = {
  179. .name = "statistics",
  180. .attrs = spi_device_statistics_attrs,
  181. };
  182. static const struct attribute_group *spi_dev_groups[] = {
  183. &spi_dev_group,
  184. &spi_device_statistics_group,
  185. NULL,
  186. };
  187. static struct attribute *spi_controller_statistics_attrs[] = {
  188. &dev_attr_spi_controller_messages.attr,
  189. &dev_attr_spi_controller_transfers.attr,
  190. &dev_attr_spi_controller_errors.attr,
  191. &dev_attr_spi_controller_timedout.attr,
  192. &dev_attr_spi_controller_spi_sync.attr,
  193. &dev_attr_spi_controller_spi_sync_immediate.attr,
  194. &dev_attr_spi_controller_spi_async.attr,
  195. &dev_attr_spi_controller_bytes.attr,
  196. &dev_attr_spi_controller_bytes_rx.attr,
  197. &dev_attr_spi_controller_bytes_tx.attr,
  198. &dev_attr_spi_controller_transfer_bytes_histo0.attr,
  199. &dev_attr_spi_controller_transfer_bytes_histo1.attr,
  200. &dev_attr_spi_controller_transfer_bytes_histo2.attr,
  201. &dev_attr_spi_controller_transfer_bytes_histo3.attr,
  202. &dev_attr_spi_controller_transfer_bytes_histo4.attr,
  203. &dev_attr_spi_controller_transfer_bytes_histo5.attr,
  204. &dev_attr_spi_controller_transfer_bytes_histo6.attr,
  205. &dev_attr_spi_controller_transfer_bytes_histo7.attr,
  206. &dev_attr_spi_controller_transfer_bytes_histo8.attr,
  207. &dev_attr_spi_controller_transfer_bytes_histo9.attr,
  208. &dev_attr_spi_controller_transfer_bytes_histo10.attr,
  209. &dev_attr_spi_controller_transfer_bytes_histo11.attr,
  210. &dev_attr_spi_controller_transfer_bytes_histo12.attr,
  211. &dev_attr_spi_controller_transfer_bytes_histo13.attr,
  212. &dev_attr_spi_controller_transfer_bytes_histo14.attr,
  213. &dev_attr_spi_controller_transfer_bytes_histo15.attr,
  214. &dev_attr_spi_controller_transfer_bytes_histo16.attr,
  215. &dev_attr_spi_controller_transfers_split_maxsize.attr,
  216. NULL,
  217. };
  218. static const struct attribute_group spi_controller_statistics_group = {
  219. .name = "statistics",
  220. .attrs = spi_controller_statistics_attrs,
  221. };
  222. static const struct attribute_group *spi_master_groups[] = {
  223. &spi_controller_statistics_group,
  224. NULL,
  225. };
  226. void spi_statistics_add_transfer_stats(struct spi_statistics *stats,
  227. struct spi_transfer *xfer,
  228. struct spi_controller *ctlr)
  229. {
  230. unsigned long flags;
  231. int l2len = min(fls(xfer->len), SPI_STATISTICS_HISTO_SIZE) - 1;
  232. if (l2len < 0)
  233. l2len = 0;
  234. spin_lock_irqsave(&stats->lock, flags);
  235. stats->transfers++;
  236. stats->transfer_bytes_histo[l2len]++;
  237. stats->bytes += xfer->len;
  238. if ((xfer->tx_buf) &&
  239. (xfer->tx_buf != ctlr->dummy_tx))
  240. stats->bytes_tx += xfer->len;
  241. if ((xfer->rx_buf) &&
  242. (xfer->rx_buf != ctlr->dummy_rx))
  243. stats->bytes_rx += xfer->len;
  244. spin_unlock_irqrestore(&stats->lock, flags);
  245. }
  246. EXPORT_SYMBOL_GPL(spi_statistics_add_transfer_stats);
  247. /* modalias support makes "modprobe $MODALIAS" new-style hotplug work,
  248. * and the sysfs version makes coldplug work too.
  249. */
  250. static const struct spi_device_id *spi_match_id(const struct spi_device_id *id,
  251. const struct spi_device *sdev)
  252. {
  253. while (id->name[0]) {
  254. if (!strcmp(sdev->modalias, id->name))
  255. return id;
  256. id++;
  257. }
  258. return NULL;
  259. }
  260. const struct spi_device_id *spi_get_device_id(const struct spi_device *sdev)
  261. {
  262. const struct spi_driver *sdrv = to_spi_driver(sdev->dev.driver);
  263. return spi_match_id(sdrv->id_table, sdev);
  264. }
  265. EXPORT_SYMBOL_GPL(spi_get_device_id);
  266. static int spi_match_device(struct device *dev, struct device_driver *drv)
  267. {
  268. const struct spi_device *spi = to_spi_device(dev);
  269. const struct spi_driver *sdrv = to_spi_driver(drv);
  270. /* Attempt an OF style match */
  271. if (of_driver_match_device(dev, drv))
  272. return 1;
  273. /* Then try ACPI */
  274. if (acpi_driver_match_device(dev, drv))
  275. return 1;
  276. if (sdrv->id_table)
  277. return !!spi_match_id(sdrv->id_table, spi);
  278. return strcmp(spi->modalias, drv->name) == 0;
  279. }
  280. static int spi_uevent(struct device *dev, struct kobj_uevent_env *env)
  281. {
  282. const struct spi_device *spi = to_spi_device(dev);
  283. int rc;
  284. rc = acpi_device_uevent_modalias(dev, env);
  285. if (rc != -ENODEV)
  286. return rc;
  287. return add_uevent_var(env, "MODALIAS=%s%s", SPI_MODULE_PREFIX, spi->modalias);
  288. }
  289. struct bus_type spi_bus_type = {
  290. .name = "spi",
  291. .dev_groups = spi_dev_groups,
  292. .match = spi_match_device,
  293. .uevent = spi_uevent,
  294. };
  295. EXPORT_SYMBOL_GPL(spi_bus_type);
  296. static int spi_drv_probe(struct device *dev)
  297. {
  298. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  299. struct spi_device *spi = to_spi_device(dev);
  300. int ret;
  301. ret = of_clk_set_defaults(dev->of_node, false);
  302. if (ret)
  303. return ret;
  304. if (dev->of_node) {
  305. spi->irq = of_irq_get(dev->of_node, 0);
  306. if (spi->irq == -EPROBE_DEFER)
  307. return -EPROBE_DEFER;
  308. if (spi->irq < 0)
  309. spi->irq = 0;
  310. }
  311. ret = dev_pm_domain_attach(dev, true);
  312. if (ret)
  313. return ret;
  314. if (sdrv->probe) {
  315. ret = sdrv->probe(spi);
  316. if (ret)
  317. dev_pm_domain_detach(dev, true);
  318. }
  319. return ret;
  320. }
  321. static int spi_drv_remove(struct device *dev)
  322. {
  323. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  324. int ret = 0;
  325. if (sdrv->remove)
  326. ret = sdrv->remove(to_spi_device(dev));
  327. dev_pm_domain_detach(dev, true);
  328. return ret;
  329. }
  330. static void spi_drv_shutdown(struct device *dev)
  331. {
  332. const struct spi_driver *sdrv = to_spi_driver(dev->driver);
  333. sdrv->shutdown(to_spi_device(dev));
  334. }
  335. /**
  336. * __spi_register_driver - register a SPI driver
  337. * @owner: owner module of the driver to register
  338. * @sdrv: the driver to register
  339. * Context: can sleep
  340. *
  341. * Return: zero on success, else a negative error code.
  342. */
  343. int __spi_register_driver(struct module *owner, struct spi_driver *sdrv)
  344. {
  345. sdrv->driver.owner = owner;
  346. sdrv->driver.bus = &spi_bus_type;
  347. sdrv->driver.probe = spi_drv_probe;
  348. sdrv->driver.remove = spi_drv_remove;
  349. if (sdrv->shutdown)
  350. sdrv->driver.shutdown = spi_drv_shutdown;
  351. return driver_register(&sdrv->driver);
  352. }
  353. EXPORT_SYMBOL_GPL(__spi_register_driver);
  354. /*-------------------------------------------------------------------------*/
  355. /* SPI devices should normally not be created by SPI device drivers; that
  356. * would make them board-specific. Similarly with SPI controller drivers.
  357. * Device registration normally goes into like arch/.../mach.../board-YYY.c
  358. * with other readonly (flashable) information about mainboard devices.
  359. */
  360. struct boardinfo {
  361. struct list_head list;
  362. struct spi_board_info board_info;
  363. };
  364. static LIST_HEAD(board_list);
  365. static LIST_HEAD(spi_controller_list);
  366. /*
  367. * Used to protect add/del opertion for board_info list and
  368. * spi_controller list, and their matching process
  369. * also used to protect object of type struct idr
  370. */
  371. static DEFINE_MUTEX(board_lock);
  372. /*
  373. * Prevents addition of devices with same chip select and
  374. * addition of devices below an unregistering controller.
  375. */
  376. static DEFINE_MUTEX(spi_add_lock);
  377. /**
  378. * spi_alloc_device - Allocate a new SPI device
  379. * @ctlr: Controller to which device is connected
  380. * Context: can sleep
  381. *
  382. * Allows a driver to allocate and initialize a spi_device without
  383. * registering it immediately. This allows a driver to directly
  384. * fill the spi_device with device parameters before calling
  385. * spi_add_device() on it.
  386. *
  387. * Caller is responsible to call spi_add_device() on the returned
  388. * spi_device structure to add it to the SPI controller. If the caller
  389. * needs to discard the spi_device without adding it, then it should
  390. * call spi_dev_put() on it.
  391. *
  392. * Return: a pointer to the new device, or NULL.
  393. */
  394. struct spi_device *spi_alloc_device(struct spi_controller *ctlr)
  395. {
  396. struct spi_device *spi;
  397. if (!spi_controller_get(ctlr))
  398. return NULL;
  399. spi = kzalloc(sizeof(*spi), GFP_KERNEL);
  400. if (!spi) {
  401. spi_controller_put(ctlr);
  402. return NULL;
  403. }
  404. spi->master = spi->controller = ctlr;
  405. spi->dev.parent = &ctlr->dev;
  406. spi->dev.bus = &spi_bus_type;
  407. spi->dev.release = spidev_release;
  408. spi->cs_gpio = -ENOENT;
  409. spin_lock_init(&spi->statistics.lock);
  410. device_initialize(&spi->dev);
  411. return spi;
  412. }
  413. EXPORT_SYMBOL_GPL(spi_alloc_device);
  414. static void spi_dev_set_name(struct spi_device *spi)
  415. {
  416. struct acpi_device *adev = ACPI_COMPANION(&spi->dev);
  417. if (adev) {
  418. dev_set_name(&spi->dev, "spi-%s", acpi_dev_name(adev));
  419. return;
  420. }
  421. dev_set_name(&spi->dev, "%s.%u", dev_name(&spi->controller->dev),
  422. spi->chip_select);
  423. }
  424. static int spi_dev_check(struct device *dev, void *data)
  425. {
  426. struct spi_device *spi = to_spi_device(dev);
  427. struct spi_device *new_spi = data;
  428. if (spi->controller == new_spi->controller &&
  429. spi->chip_select == new_spi->chip_select)
  430. return -EBUSY;
  431. return 0;
  432. }
  433. /**
  434. * spi_add_device - Add spi_device allocated with spi_alloc_device
  435. * @spi: spi_device to register
  436. *
  437. * Companion function to spi_alloc_device. Devices allocated with
  438. * spi_alloc_device can be added onto the spi bus with this function.
  439. *
  440. * Return: 0 on success; negative errno on failure
  441. */
  442. int spi_add_device(struct spi_device *spi)
  443. {
  444. struct spi_controller *ctlr = spi->controller;
  445. struct device *dev = ctlr->dev.parent;
  446. int status;
  447. /* Chipselects are numbered 0..max; validate. */
  448. if (spi->chip_select >= ctlr->num_chipselect) {
  449. dev_err(dev, "cs%d >= max %d\n", spi->chip_select,
  450. ctlr->num_chipselect);
  451. return -EINVAL;
  452. }
  453. /* Set the bus ID string */
  454. spi_dev_set_name(spi);
  455. /* We need to make sure there's no other device with this
  456. * chipselect **BEFORE** we call setup(), else we'll trash
  457. * its configuration. Lock against concurrent add() calls.
  458. */
  459. mutex_lock(&spi_add_lock);
  460. status = bus_for_each_dev(&spi_bus_type, NULL, spi, spi_dev_check);
  461. if (status) {
  462. dev_err(dev, "chipselect %d already in use\n",
  463. spi->chip_select);
  464. goto done;
  465. }
  466. /* Controller may unregister concurrently */
  467. if (IS_ENABLED(CONFIG_SPI_DYNAMIC) &&
  468. !device_is_registered(&ctlr->dev)) {
  469. status = -ENODEV;
  470. goto done;
  471. }
  472. if (ctlr->cs_gpios)
  473. spi->cs_gpio = ctlr->cs_gpios[spi->chip_select];
  474. /* Drivers may modify this initial i/o setup, but will
  475. * normally rely on the device being setup. Devices
  476. * using SPI_CS_HIGH can't coexist well otherwise...
  477. */
  478. status = spi_setup(spi);
  479. if (status < 0) {
  480. dev_err(dev, "can't setup %s, status %d\n",
  481. dev_name(&spi->dev), status);
  482. goto done;
  483. }
  484. /* Device may be bound to an active driver when this returns */
  485. status = device_add(&spi->dev);
  486. if (status < 0)
  487. dev_err(dev, "can't add %s, status %d\n",
  488. dev_name(&spi->dev), status);
  489. else
  490. dev_dbg(dev, "registered child %s\n", dev_name(&spi->dev));
  491. done:
  492. mutex_unlock(&spi_add_lock);
  493. return status;
  494. }
  495. EXPORT_SYMBOL_GPL(spi_add_device);
  496. /**
  497. * spi_new_device - instantiate one new SPI device
  498. * @ctlr: Controller to which device is connected
  499. * @chip: Describes the SPI device
  500. * Context: can sleep
  501. *
  502. * On typical mainboards, this is purely internal; and it's not needed
  503. * after board init creates the hard-wired devices. Some development
  504. * platforms may not be able to use spi_register_board_info though, and
  505. * this is exported so that for example a USB or parport based adapter
  506. * driver could add devices (which it would learn about out-of-band).
  507. *
  508. * Return: the new device, or NULL.
  509. */
  510. struct spi_device *spi_new_device(struct spi_controller *ctlr,
  511. struct spi_board_info *chip)
  512. {
  513. struct spi_device *proxy;
  514. int status;
  515. /* NOTE: caller did any chip->bus_num checks necessary.
  516. *
  517. * Also, unless we change the return value convention to use
  518. * error-or-pointer (not NULL-or-pointer), troubleshootability
  519. * suggests syslogged diagnostics are best here (ugh).
  520. */
  521. proxy = spi_alloc_device(ctlr);
  522. if (!proxy)
  523. return NULL;
  524. WARN_ON(strlen(chip->modalias) >= sizeof(proxy->modalias));
  525. proxy->chip_select = chip->chip_select;
  526. proxy->max_speed_hz = chip->max_speed_hz;
  527. proxy->mode = chip->mode;
  528. proxy->irq = chip->irq;
  529. strlcpy(proxy->modalias, chip->modalias, sizeof(proxy->modalias));
  530. proxy->dev.platform_data = (void *) chip->platform_data;
  531. proxy->controller_data = chip->controller_data;
  532. proxy->controller_state = NULL;
  533. if (chip->properties) {
  534. status = device_add_properties(&proxy->dev, chip->properties);
  535. if (status) {
  536. dev_err(&ctlr->dev,
  537. "failed to add properties to '%s': %d\n",
  538. chip->modalias, status);
  539. goto err_dev_put;
  540. }
  541. }
  542. status = spi_add_device(proxy);
  543. if (status < 0)
  544. goto err_remove_props;
  545. return proxy;
  546. err_remove_props:
  547. if (chip->properties)
  548. device_remove_properties(&proxy->dev);
  549. err_dev_put:
  550. spi_dev_put(proxy);
  551. return NULL;
  552. }
  553. EXPORT_SYMBOL_GPL(spi_new_device);
  554. /**
  555. * spi_unregister_device - unregister a single SPI device
  556. * @spi: spi_device to unregister
  557. *
  558. * Start making the passed SPI device vanish. Normally this would be handled
  559. * by spi_unregister_controller().
  560. */
  561. void spi_unregister_device(struct spi_device *spi)
  562. {
  563. if (!spi)
  564. return;
  565. if (spi->dev.of_node) {
  566. of_node_clear_flag(spi->dev.of_node, OF_POPULATED);
  567. of_node_put(spi->dev.of_node);
  568. }
  569. if (ACPI_COMPANION(&spi->dev))
  570. acpi_device_clear_enumerated(ACPI_COMPANION(&spi->dev));
  571. device_unregister(&spi->dev);
  572. }
  573. EXPORT_SYMBOL_GPL(spi_unregister_device);
  574. static void spi_match_controller_to_boardinfo(struct spi_controller *ctlr,
  575. struct spi_board_info *bi)
  576. {
  577. struct spi_device *dev;
  578. if (ctlr->bus_num != bi->bus_num)
  579. return;
  580. dev = spi_new_device(ctlr, bi);
  581. if (!dev)
  582. dev_err(ctlr->dev.parent, "can't create new device for %s\n",
  583. bi->modalias);
  584. }
  585. /**
  586. * spi_register_board_info - register SPI devices for a given board
  587. * @info: array of chip descriptors
  588. * @n: how many descriptors are provided
  589. * Context: can sleep
  590. *
  591. * Board-specific early init code calls this (probably during arch_initcall)
  592. * with segments of the SPI device table. Any device nodes are created later,
  593. * after the relevant parent SPI controller (bus_num) is defined. We keep
  594. * this table of devices forever, so that reloading a controller driver will
  595. * not make Linux forget about these hard-wired devices.
  596. *
  597. * Other code can also call this, e.g. a particular add-on board might provide
  598. * SPI devices through its expansion connector, so code initializing that board
  599. * would naturally declare its SPI devices.
  600. *
  601. * The board info passed can safely be __initdata ... but be careful of
  602. * any embedded pointers (platform_data, etc), they're copied as-is.
  603. * Device properties are deep-copied though.
  604. *
  605. * Return: zero on success, else a negative error code.
  606. */
  607. int spi_register_board_info(struct spi_board_info const *info, unsigned n)
  608. {
  609. struct boardinfo *bi;
  610. int i;
  611. if (!n)
  612. return 0;
  613. bi = kcalloc(n, sizeof(*bi), GFP_KERNEL);
  614. if (!bi)
  615. return -ENOMEM;
  616. for (i = 0; i < n; i++, bi++, info++) {
  617. struct spi_controller *ctlr;
  618. memcpy(&bi->board_info, info, sizeof(*info));
  619. if (info->properties) {
  620. bi->board_info.properties =
  621. property_entries_dup(info->properties);
  622. if (IS_ERR(bi->board_info.properties))
  623. return PTR_ERR(bi->board_info.properties);
  624. }
  625. mutex_lock(&board_lock);
  626. list_add_tail(&bi->list, &board_list);
  627. list_for_each_entry(ctlr, &spi_controller_list, list)
  628. spi_match_controller_to_boardinfo(ctlr,
  629. &bi->board_info);
  630. mutex_unlock(&board_lock);
  631. }
  632. return 0;
  633. }
  634. /*-------------------------------------------------------------------------*/
  635. static void spi_set_cs(struct spi_device *spi, bool enable)
  636. {
  637. if (spi->mode & SPI_CS_HIGH)
  638. enable = !enable;
  639. if (gpio_is_valid(spi->cs_gpio)) {
  640. gpio_set_value(spi->cs_gpio, !enable);
  641. /* Some SPI masters need both GPIO CS & slave_select */
  642. if ((spi->controller->flags & SPI_MASTER_GPIO_SS) &&
  643. spi->controller->set_cs)
  644. spi->controller->set_cs(spi, !enable);
  645. } else if (spi->controller->set_cs) {
  646. spi->controller->set_cs(spi, !enable);
  647. }
  648. }
  649. #ifdef CONFIG_HAS_DMA
  650. int spi_map_buf(struct spi_controller *ctlr, struct device *dev,
  651. struct sg_table *sgt, void *buf, size_t len,
  652. enum dma_data_direction dir)
  653. {
  654. const bool vmalloced_buf = is_vmalloc_addr(buf);
  655. unsigned int max_seg_size = dma_get_max_seg_size(dev);
  656. #ifdef CONFIG_HIGHMEM
  657. const bool kmap_buf = ((unsigned long)buf >= PKMAP_BASE &&
  658. (unsigned long)buf < (PKMAP_BASE +
  659. (LAST_PKMAP * PAGE_SIZE)));
  660. #else
  661. const bool kmap_buf = false;
  662. #endif
  663. int desc_len;
  664. int sgs;
  665. struct page *vm_page;
  666. struct scatterlist *sg;
  667. void *sg_buf;
  668. size_t min;
  669. int i, ret;
  670. if (vmalloced_buf || kmap_buf) {
  671. desc_len = min_t(int, max_seg_size, PAGE_SIZE);
  672. sgs = DIV_ROUND_UP(len + offset_in_page(buf), desc_len);
  673. } else if (virt_addr_valid(buf)) {
  674. desc_len = min_t(int, max_seg_size, ctlr->max_dma_len);
  675. sgs = DIV_ROUND_UP(len, desc_len);
  676. } else {
  677. return -EINVAL;
  678. }
  679. ret = sg_alloc_table(sgt, sgs, GFP_KERNEL);
  680. if (ret != 0)
  681. return ret;
  682. sg = &sgt->sgl[0];
  683. for (i = 0; i < sgs; i++) {
  684. if (vmalloced_buf || kmap_buf) {
  685. /*
  686. * Next scatterlist entry size is the minimum between
  687. * the desc_len and the remaining buffer length that
  688. * fits in a page.
  689. */
  690. min = min_t(size_t, desc_len,
  691. min_t(size_t, len,
  692. PAGE_SIZE - offset_in_page(buf)));
  693. if (vmalloced_buf)
  694. vm_page = vmalloc_to_page(buf);
  695. else
  696. vm_page = kmap_to_page(buf);
  697. if (!vm_page) {
  698. sg_free_table(sgt);
  699. return -ENOMEM;
  700. }
  701. sg_set_page(sg, vm_page,
  702. min, offset_in_page(buf));
  703. } else {
  704. min = min_t(size_t, len, desc_len);
  705. sg_buf = buf;
  706. sg_set_buf(sg, sg_buf, min);
  707. }
  708. buf += min;
  709. len -= min;
  710. sg = sg_next(sg);
  711. }
  712. ret = dma_map_sg(dev, sgt->sgl, sgt->nents, dir);
  713. if (!ret)
  714. ret = -ENOMEM;
  715. if (ret < 0) {
  716. sg_free_table(sgt);
  717. return ret;
  718. }
  719. sgt->nents = ret;
  720. return 0;
  721. }
  722. void spi_unmap_buf(struct spi_controller *ctlr, struct device *dev,
  723. struct sg_table *sgt, enum dma_data_direction dir)
  724. {
  725. if (sgt->orig_nents) {
  726. dma_unmap_sg(dev, sgt->sgl, sgt->orig_nents, dir);
  727. sg_free_table(sgt);
  728. }
  729. }
  730. static int __spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
  731. {
  732. struct device *tx_dev, *rx_dev;
  733. struct spi_transfer *xfer;
  734. int ret;
  735. if (!ctlr->can_dma)
  736. return 0;
  737. if (ctlr->dma_tx)
  738. tx_dev = ctlr->dma_tx->device->dev;
  739. else
  740. tx_dev = ctlr->dev.parent;
  741. if (ctlr->dma_rx)
  742. rx_dev = ctlr->dma_rx->device->dev;
  743. else
  744. rx_dev = ctlr->dev.parent;
  745. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  746. if (!ctlr->can_dma(ctlr, msg->spi, xfer))
  747. continue;
  748. if (xfer->tx_buf != NULL) {
  749. ret = spi_map_buf(ctlr, tx_dev, &xfer->tx_sg,
  750. (void *)xfer->tx_buf, xfer->len,
  751. DMA_TO_DEVICE);
  752. if (ret != 0)
  753. return ret;
  754. }
  755. if (xfer->rx_buf != NULL) {
  756. ret = spi_map_buf(ctlr, rx_dev, &xfer->rx_sg,
  757. xfer->rx_buf, xfer->len,
  758. DMA_FROM_DEVICE);
  759. if (ret != 0) {
  760. spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg,
  761. DMA_TO_DEVICE);
  762. return ret;
  763. }
  764. }
  765. }
  766. ctlr->cur_msg_mapped = true;
  767. return 0;
  768. }
  769. static int __spi_unmap_msg(struct spi_controller *ctlr, struct spi_message *msg)
  770. {
  771. struct spi_transfer *xfer;
  772. struct device *tx_dev, *rx_dev;
  773. if (!ctlr->cur_msg_mapped || !ctlr->can_dma)
  774. return 0;
  775. if (ctlr->dma_tx)
  776. tx_dev = ctlr->dma_tx->device->dev;
  777. else
  778. tx_dev = ctlr->dev.parent;
  779. if (ctlr->dma_rx)
  780. rx_dev = ctlr->dma_rx->device->dev;
  781. else
  782. rx_dev = ctlr->dev.parent;
  783. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  784. if (!ctlr->can_dma(ctlr, msg->spi, xfer))
  785. continue;
  786. spi_unmap_buf(ctlr, rx_dev, &xfer->rx_sg, DMA_FROM_DEVICE);
  787. spi_unmap_buf(ctlr, tx_dev, &xfer->tx_sg, DMA_TO_DEVICE);
  788. }
  789. return 0;
  790. }
  791. #else /* !CONFIG_HAS_DMA */
  792. static inline int __spi_map_msg(struct spi_controller *ctlr,
  793. struct spi_message *msg)
  794. {
  795. return 0;
  796. }
  797. static inline int __spi_unmap_msg(struct spi_controller *ctlr,
  798. struct spi_message *msg)
  799. {
  800. return 0;
  801. }
  802. #endif /* !CONFIG_HAS_DMA */
  803. static inline int spi_unmap_msg(struct spi_controller *ctlr,
  804. struct spi_message *msg)
  805. {
  806. struct spi_transfer *xfer;
  807. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  808. /*
  809. * Restore the original value of tx_buf or rx_buf if they are
  810. * NULL.
  811. */
  812. if (xfer->tx_buf == ctlr->dummy_tx)
  813. xfer->tx_buf = NULL;
  814. if (xfer->rx_buf == ctlr->dummy_rx)
  815. xfer->rx_buf = NULL;
  816. }
  817. return __spi_unmap_msg(ctlr, msg);
  818. }
  819. static int spi_map_msg(struct spi_controller *ctlr, struct spi_message *msg)
  820. {
  821. struct spi_transfer *xfer;
  822. void *tmp;
  823. unsigned int max_tx, max_rx;
  824. if (ctlr->flags & (SPI_CONTROLLER_MUST_RX | SPI_CONTROLLER_MUST_TX)) {
  825. max_tx = 0;
  826. max_rx = 0;
  827. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  828. if ((ctlr->flags & SPI_CONTROLLER_MUST_TX) &&
  829. !xfer->tx_buf)
  830. max_tx = max(xfer->len, max_tx);
  831. if ((ctlr->flags & SPI_CONTROLLER_MUST_RX) &&
  832. !xfer->rx_buf)
  833. max_rx = max(xfer->len, max_rx);
  834. }
  835. if (max_tx) {
  836. tmp = krealloc(ctlr->dummy_tx, max_tx,
  837. GFP_KERNEL | GFP_DMA);
  838. if (!tmp)
  839. return -ENOMEM;
  840. ctlr->dummy_tx = tmp;
  841. memset(tmp, 0, max_tx);
  842. }
  843. if (max_rx) {
  844. tmp = krealloc(ctlr->dummy_rx, max_rx,
  845. GFP_KERNEL | GFP_DMA);
  846. if (!tmp)
  847. return -ENOMEM;
  848. ctlr->dummy_rx = tmp;
  849. }
  850. if (max_tx || max_rx) {
  851. list_for_each_entry(xfer, &msg->transfers,
  852. transfer_list) {
  853. if (!xfer->len)
  854. continue;
  855. if (!xfer->tx_buf)
  856. xfer->tx_buf = ctlr->dummy_tx;
  857. if (!xfer->rx_buf)
  858. xfer->rx_buf = ctlr->dummy_rx;
  859. }
  860. }
  861. }
  862. return __spi_map_msg(ctlr, msg);
  863. }
  864. /*
  865. * spi_transfer_one_message - Default implementation of transfer_one_message()
  866. *
  867. * This is a standard implementation of transfer_one_message() for
  868. * drivers which implement a transfer_one() operation. It provides
  869. * standard handling of delays and chip select management.
  870. */
  871. static int spi_transfer_one_message(struct spi_controller *ctlr,
  872. struct spi_message *msg)
  873. {
  874. struct spi_transfer *xfer;
  875. bool keep_cs = false;
  876. int ret = 0;
  877. unsigned long long ms = 1;
  878. struct spi_statistics *statm = &ctlr->statistics;
  879. struct spi_statistics *stats = &msg->spi->statistics;
  880. spi_set_cs(msg->spi, true);
  881. SPI_STATISTICS_INCREMENT_FIELD(statm, messages);
  882. SPI_STATISTICS_INCREMENT_FIELD(stats, messages);
  883. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  884. trace_spi_transfer_start(msg, xfer);
  885. spi_statistics_add_transfer_stats(statm, xfer, ctlr);
  886. spi_statistics_add_transfer_stats(stats, xfer, ctlr);
  887. if (xfer->tx_buf || xfer->rx_buf) {
  888. reinit_completion(&ctlr->xfer_completion);
  889. ret = ctlr->transfer_one(ctlr, msg->spi, xfer);
  890. if (ret < 0) {
  891. SPI_STATISTICS_INCREMENT_FIELD(statm,
  892. errors);
  893. SPI_STATISTICS_INCREMENT_FIELD(stats,
  894. errors);
  895. dev_err(&msg->spi->dev,
  896. "SPI transfer failed: %d\n", ret);
  897. goto out;
  898. }
  899. if (ret > 0) {
  900. ret = 0;
  901. ms = 8LL * 1000LL * xfer->len;
  902. do_div(ms, xfer->speed_hz);
  903. ms += ms + 200; /* some tolerance */
  904. if (ms > UINT_MAX)
  905. ms = UINT_MAX;
  906. ms = wait_for_completion_timeout(&ctlr->xfer_completion,
  907. msecs_to_jiffies(ms));
  908. }
  909. if (ms == 0) {
  910. SPI_STATISTICS_INCREMENT_FIELD(statm,
  911. timedout);
  912. SPI_STATISTICS_INCREMENT_FIELD(stats,
  913. timedout);
  914. dev_err(&msg->spi->dev,
  915. "SPI transfer timed out\n");
  916. msg->status = -ETIMEDOUT;
  917. }
  918. } else {
  919. if (xfer->len)
  920. dev_err(&msg->spi->dev,
  921. "Bufferless transfer has length %u\n",
  922. xfer->len);
  923. }
  924. trace_spi_transfer_stop(msg, xfer);
  925. if (msg->status != -EINPROGRESS)
  926. goto out;
  927. if (xfer->delay_usecs) {
  928. u16 us = xfer->delay_usecs;
  929. if (us <= 10)
  930. udelay(us);
  931. else
  932. usleep_range(us, us + DIV_ROUND_UP(us, 10));
  933. }
  934. if (xfer->cs_change) {
  935. if (list_is_last(&xfer->transfer_list,
  936. &msg->transfers)) {
  937. keep_cs = true;
  938. } else {
  939. spi_set_cs(msg->spi, false);
  940. udelay(10);
  941. spi_set_cs(msg->spi, true);
  942. }
  943. }
  944. msg->actual_length += xfer->len;
  945. }
  946. out:
  947. if (ret != 0 || !keep_cs)
  948. spi_set_cs(msg->spi, false);
  949. if (msg->status == -EINPROGRESS)
  950. msg->status = ret;
  951. if (msg->status && ctlr->handle_err)
  952. ctlr->handle_err(ctlr, msg);
  953. spi_finalize_current_message(ctlr);
  954. return ret;
  955. }
  956. /**
  957. * spi_finalize_current_transfer - report completion of a transfer
  958. * @ctlr: the controller reporting completion
  959. *
  960. * Called by SPI drivers using the core transfer_one_message()
  961. * implementation to notify it that the current interrupt driven
  962. * transfer has finished and the next one may be scheduled.
  963. */
  964. void spi_finalize_current_transfer(struct spi_controller *ctlr)
  965. {
  966. complete(&ctlr->xfer_completion);
  967. }
  968. EXPORT_SYMBOL_GPL(spi_finalize_current_transfer);
  969. /**
  970. * __spi_pump_messages - function which processes spi message queue
  971. * @ctlr: controller to process queue for
  972. * @in_kthread: true if we are in the context of the message pump thread
  973. *
  974. * This function checks if there is any spi message in the queue that
  975. * needs processing and if so call out to the driver to initialize hardware
  976. * and transfer each message.
  977. *
  978. * Note that it is called both from the kthread itself and also from
  979. * inside spi_sync(); the queue extraction handling at the top of the
  980. * function should deal with this safely.
  981. */
  982. static void __spi_pump_messages(struct spi_controller *ctlr, bool in_kthread)
  983. {
  984. unsigned long flags;
  985. bool was_busy = false;
  986. int ret;
  987. /* Lock queue */
  988. spin_lock_irqsave(&ctlr->queue_lock, flags);
  989. /* Make sure we are not already running a message */
  990. if (ctlr->cur_msg) {
  991. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  992. return;
  993. }
  994. /* If another context is idling the device then defer */
  995. if (ctlr->idling) {
  996. kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
  997. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  998. return;
  999. }
  1000. /* Check if the queue is idle */
  1001. if (list_empty(&ctlr->queue) || !ctlr->running) {
  1002. if (!ctlr->busy) {
  1003. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1004. return;
  1005. }
  1006. /* Only do teardown in the thread */
  1007. if (!in_kthread) {
  1008. kthread_queue_work(&ctlr->kworker,
  1009. &ctlr->pump_messages);
  1010. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1011. return;
  1012. }
  1013. ctlr->busy = false;
  1014. ctlr->idling = true;
  1015. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1016. kfree(ctlr->dummy_rx);
  1017. ctlr->dummy_rx = NULL;
  1018. kfree(ctlr->dummy_tx);
  1019. ctlr->dummy_tx = NULL;
  1020. if (ctlr->unprepare_transfer_hardware &&
  1021. ctlr->unprepare_transfer_hardware(ctlr))
  1022. dev_err(&ctlr->dev,
  1023. "failed to unprepare transfer hardware\n");
  1024. if (ctlr->auto_runtime_pm) {
  1025. pm_runtime_mark_last_busy(ctlr->dev.parent);
  1026. pm_runtime_put_autosuspend(ctlr->dev.parent);
  1027. }
  1028. trace_spi_controller_idle(ctlr);
  1029. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1030. ctlr->idling = false;
  1031. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1032. return;
  1033. }
  1034. /* Extract head of queue */
  1035. ctlr->cur_msg =
  1036. list_first_entry(&ctlr->queue, struct spi_message, queue);
  1037. list_del_init(&ctlr->cur_msg->queue);
  1038. if (ctlr->busy)
  1039. was_busy = true;
  1040. else
  1041. ctlr->busy = true;
  1042. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1043. mutex_lock(&ctlr->io_mutex);
  1044. if (!was_busy && ctlr->auto_runtime_pm) {
  1045. ret = pm_runtime_get_sync(ctlr->dev.parent);
  1046. if (ret < 0) {
  1047. pm_runtime_put_noidle(ctlr->dev.parent);
  1048. dev_err(&ctlr->dev, "Failed to power device: %d\n",
  1049. ret);
  1050. mutex_unlock(&ctlr->io_mutex);
  1051. return;
  1052. }
  1053. }
  1054. if (!was_busy)
  1055. trace_spi_controller_busy(ctlr);
  1056. if (!was_busy && ctlr->prepare_transfer_hardware) {
  1057. ret = ctlr->prepare_transfer_hardware(ctlr);
  1058. if (ret) {
  1059. dev_err(&ctlr->dev,
  1060. "failed to prepare transfer hardware\n");
  1061. if (ctlr->auto_runtime_pm)
  1062. pm_runtime_put(ctlr->dev.parent);
  1063. mutex_unlock(&ctlr->io_mutex);
  1064. return;
  1065. }
  1066. }
  1067. trace_spi_message_start(ctlr->cur_msg);
  1068. if (ctlr->prepare_message) {
  1069. ret = ctlr->prepare_message(ctlr, ctlr->cur_msg);
  1070. if (ret) {
  1071. dev_err(&ctlr->dev, "failed to prepare message: %d\n",
  1072. ret);
  1073. ctlr->cur_msg->status = ret;
  1074. spi_finalize_current_message(ctlr);
  1075. goto out;
  1076. }
  1077. ctlr->cur_msg_prepared = true;
  1078. }
  1079. ret = spi_map_msg(ctlr, ctlr->cur_msg);
  1080. if (ret) {
  1081. ctlr->cur_msg->status = ret;
  1082. spi_finalize_current_message(ctlr);
  1083. goto out;
  1084. }
  1085. ret = ctlr->transfer_one_message(ctlr, ctlr->cur_msg);
  1086. if (ret) {
  1087. dev_err(&ctlr->dev,
  1088. "failed to transfer one message from queue\n");
  1089. goto out;
  1090. }
  1091. out:
  1092. mutex_unlock(&ctlr->io_mutex);
  1093. /* Prod the scheduler in case transfer_one() was busy waiting */
  1094. if (!ret)
  1095. cond_resched();
  1096. }
  1097. /**
  1098. * spi_pump_messages - kthread work function which processes spi message queue
  1099. * @work: pointer to kthread work struct contained in the controller struct
  1100. */
  1101. static void spi_pump_messages(struct kthread_work *work)
  1102. {
  1103. struct spi_controller *ctlr =
  1104. container_of(work, struct spi_controller, pump_messages);
  1105. __spi_pump_messages(ctlr, true);
  1106. }
  1107. static int spi_init_queue(struct spi_controller *ctlr)
  1108. {
  1109. struct sched_param param = { .sched_priority = MAX_RT_PRIO - 1 };
  1110. ctlr->running = false;
  1111. ctlr->busy = false;
  1112. kthread_init_worker(&ctlr->kworker);
  1113. ctlr->kworker_task = kthread_run(kthread_worker_fn, &ctlr->kworker,
  1114. "%s", dev_name(&ctlr->dev));
  1115. if (IS_ERR(ctlr->kworker_task)) {
  1116. dev_err(&ctlr->dev, "failed to create message pump task\n");
  1117. return PTR_ERR(ctlr->kworker_task);
  1118. }
  1119. kthread_init_work(&ctlr->pump_messages, spi_pump_messages);
  1120. /*
  1121. * Controller config will indicate if this controller should run the
  1122. * message pump with high (realtime) priority to reduce the transfer
  1123. * latency on the bus by minimising the delay between a transfer
  1124. * request and the scheduling of the message pump thread. Without this
  1125. * setting the message pump thread will remain at default priority.
  1126. */
  1127. if (ctlr->rt) {
  1128. dev_info(&ctlr->dev,
  1129. "will run message pump with realtime priority\n");
  1130. sched_setscheduler(ctlr->kworker_task, SCHED_FIFO, &param);
  1131. }
  1132. return 0;
  1133. }
  1134. /**
  1135. * spi_get_next_queued_message() - called by driver to check for queued
  1136. * messages
  1137. * @ctlr: the controller to check for queued messages
  1138. *
  1139. * If there are more messages in the queue, the next message is returned from
  1140. * this call.
  1141. *
  1142. * Return: the next message in the queue, else NULL if the queue is empty.
  1143. */
  1144. struct spi_message *spi_get_next_queued_message(struct spi_controller *ctlr)
  1145. {
  1146. struct spi_message *next;
  1147. unsigned long flags;
  1148. /* get a pointer to the next message, if any */
  1149. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1150. next = list_first_entry_or_null(&ctlr->queue, struct spi_message,
  1151. queue);
  1152. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1153. return next;
  1154. }
  1155. EXPORT_SYMBOL_GPL(spi_get_next_queued_message);
  1156. /**
  1157. * spi_finalize_current_message() - the current message is complete
  1158. * @ctlr: the controller to return the message to
  1159. *
  1160. * Called by the driver to notify the core that the message in the front of the
  1161. * queue is complete and can be removed from the queue.
  1162. */
  1163. void spi_finalize_current_message(struct spi_controller *ctlr)
  1164. {
  1165. struct spi_message *mesg;
  1166. unsigned long flags;
  1167. int ret;
  1168. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1169. mesg = ctlr->cur_msg;
  1170. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1171. spi_unmap_msg(ctlr, mesg);
  1172. /* In the prepare_messages callback the spi bus has the opportunity to
  1173. * split a transfer to smaller chunks.
  1174. * Release splited transfers here since spi_map_msg is done on the
  1175. * splited transfers.
  1176. */
  1177. spi_res_release(ctlr, mesg);
  1178. if (ctlr->cur_msg_prepared && ctlr->unprepare_message) {
  1179. ret = ctlr->unprepare_message(ctlr, mesg);
  1180. if (ret) {
  1181. dev_err(&ctlr->dev, "failed to unprepare message: %d\n",
  1182. ret);
  1183. }
  1184. }
  1185. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1186. ctlr->cur_msg = NULL;
  1187. ctlr->cur_msg_prepared = false;
  1188. kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
  1189. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1190. trace_spi_message_done(mesg);
  1191. mesg->state = NULL;
  1192. if (mesg->complete)
  1193. mesg->complete(mesg->context);
  1194. }
  1195. EXPORT_SYMBOL_GPL(spi_finalize_current_message);
  1196. static int spi_start_queue(struct spi_controller *ctlr)
  1197. {
  1198. unsigned long flags;
  1199. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1200. if (ctlr->running || ctlr->busy) {
  1201. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1202. return -EBUSY;
  1203. }
  1204. ctlr->running = true;
  1205. ctlr->cur_msg = NULL;
  1206. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1207. kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
  1208. return 0;
  1209. }
  1210. static int spi_stop_queue(struct spi_controller *ctlr)
  1211. {
  1212. unsigned long flags;
  1213. unsigned limit = 500;
  1214. int ret = 0;
  1215. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1216. /*
  1217. * This is a bit lame, but is optimized for the common execution path.
  1218. * A wait_queue on the ctlr->busy could be used, but then the common
  1219. * execution path (pump_messages) would be required to call wake_up or
  1220. * friends on every SPI message. Do this instead.
  1221. */
  1222. while ((!list_empty(&ctlr->queue) || ctlr->busy) && limit--) {
  1223. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1224. usleep_range(10000, 11000);
  1225. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1226. }
  1227. if (!list_empty(&ctlr->queue) || ctlr->busy)
  1228. ret = -EBUSY;
  1229. else
  1230. ctlr->running = false;
  1231. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1232. if (ret) {
  1233. dev_warn(&ctlr->dev, "could not stop message queue\n");
  1234. return ret;
  1235. }
  1236. return ret;
  1237. }
  1238. static int spi_destroy_queue(struct spi_controller *ctlr)
  1239. {
  1240. int ret;
  1241. ret = spi_stop_queue(ctlr);
  1242. /*
  1243. * kthread_flush_worker will block until all work is done.
  1244. * If the reason that stop_queue timed out is that the work will never
  1245. * finish, then it does no good to call flush/stop thread, so
  1246. * return anyway.
  1247. */
  1248. if (ret) {
  1249. dev_err(&ctlr->dev, "problem destroying queue\n");
  1250. return ret;
  1251. }
  1252. kthread_flush_worker(&ctlr->kworker);
  1253. kthread_stop(ctlr->kworker_task);
  1254. return 0;
  1255. }
  1256. static int __spi_queued_transfer(struct spi_device *spi,
  1257. struct spi_message *msg,
  1258. bool need_pump)
  1259. {
  1260. struct spi_controller *ctlr = spi->controller;
  1261. unsigned long flags;
  1262. spin_lock_irqsave(&ctlr->queue_lock, flags);
  1263. if (!ctlr->running) {
  1264. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1265. return -ESHUTDOWN;
  1266. }
  1267. msg->actual_length = 0;
  1268. msg->status = -EINPROGRESS;
  1269. list_add_tail(&msg->queue, &ctlr->queue);
  1270. if (!ctlr->busy && need_pump)
  1271. kthread_queue_work(&ctlr->kworker, &ctlr->pump_messages);
  1272. spin_unlock_irqrestore(&ctlr->queue_lock, flags);
  1273. return 0;
  1274. }
  1275. /**
  1276. * spi_queued_transfer - transfer function for queued transfers
  1277. * @spi: spi device which is requesting transfer
  1278. * @msg: spi message which is to handled is queued to driver queue
  1279. *
  1280. * Return: zero on success, else a negative error code.
  1281. */
  1282. static int spi_queued_transfer(struct spi_device *spi, struct spi_message *msg)
  1283. {
  1284. return __spi_queued_transfer(spi, msg, true);
  1285. }
  1286. static int spi_controller_initialize_queue(struct spi_controller *ctlr)
  1287. {
  1288. int ret;
  1289. ctlr->transfer = spi_queued_transfer;
  1290. if (!ctlr->transfer_one_message)
  1291. ctlr->transfer_one_message = spi_transfer_one_message;
  1292. /* Initialize and start queue */
  1293. ret = spi_init_queue(ctlr);
  1294. if (ret) {
  1295. dev_err(&ctlr->dev, "problem initializing queue\n");
  1296. goto err_init_queue;
  1297. }
  1298. ctlr->queued = true;
  1299. ret = spi_start_queue(ctlr);
  1300. if (ret) {
  1301. dev_err(&ctlr->dev, "problem starting queue\n");
  1302. goto err_start_queue;
  1303. }
  1304. return 0;
  1305. err_start_queue:
  1306. spi_destroy_queue(ctlr);
  1307. err_init_queue:
  1308. return ret;
  1309. }
  1310. /**
  1311. * spi_flush_queue - Send all pending messages in the queue from the callers'
  1312. * context
  1313. * @ctlr: controller to process queue for
  1314. *
  1315. * This should be used when one wants to ensure all pending messages have been
  1316. * sent before doing something. Is used by the spi-mem code to make sure SPI
  1317. * memory operations do not preempt regular SPI transfers that have been queued
  1318. * before the spi-mem operation.
  1319. */
  1320. void spi_flush_queue(struct spi_controller *ctlr)
  1321. {
  1322. if (ctlr->transfer == spi_queued_transfer)
  1323. __spi_pump_messages(ctlr, false);
  1324. }
  1325. /*-------------------------------------------------------------------------*/
  1326. #if defined(CONFIG_OF)
  1327. static int of_spi_parse_dt(struct spi_controller *ctlr, struct spi_device *spi,
  1328. struct device_node *nc)
  1329. {
  1330. u32 value;
  1331. int rc;
  1332. /* Mode (clock phase/polarity/etc.) */
  1333. if (of_property_read_bool(nc, "spi-cpha"))
  1334. spi->mode |= SPI_CPHA;
  1335. if (of_property_read_bool(nc, "spi-cpol"))
  1336. spi->mode |= SPI_CPOL;
  1337. if (of_property_read_bool(nc, "spi-cs-high"))
  1338. spi->mode |= SPI_CS_HIGH;
  1339. if (of_property_read_bool(nc, "spi-3wire"))
  1340. spi->mode |= SPI_3WIRE;
  1341. if (of_property_read_bool(nc, "spi-lsb-first"))
  1342. spi->mode |= SPI_LSB_FIRST;
  1343. /* Device DUAL/QUAD mode */
  1344. if (!of_property_read_u32(nc, "spi-tx-bus-width", &value)) {
  1345. switch (value) {
  1346. case 1:
  1347. break;
  1348. case 2:
  1349. spi->mode |= SPI_TX_DUAL;
  1350. break;
  1351. case 4:
  1352. spi->mode |= SPI_TX_QUAD;
  1353. break;
  1354. default:
  1355. dev_warn(&ctlr->dev,
  1356. "spi-tx-bus-width %d not supported\n",
  1357. value);
  1358. break;
  1359. }
  1360. }
  1361. if (!of_property_read_u32(nc, "spi-rx-bus-width", &value)) {
  1362. switch (value) {
  1363. case 1:
  1364. break;
  1365. case 2:
  1366. spi->mode |= SPI_RX_DUAL;
  1367. break;
  1368. case 4:
  1369. spi->mode |= SPI_RX_QUAD;
  1370. break;
  1371. default:
  1372. dev_warn(&ctlr->dev,
  1373. "spi-rx-bus-width %d not supported\n",
  1374. value);
  1375. break;
  1376. }
  1377. }
  1378. if (spi_controller_is_slave(ctlr)) {
  1379. if (strcmp(nc->name, "slave")) {
  1380. dev_err(&ctlr->dev, "%pOF is not called 'slave'\n",
  1381. nc);
  1382. return -EINVAL;
  1383. }
  1384. return 0;
  1385. }
  1386. /* Device address */
  1387. rc = of_property_read_u32(nc, "reg", &value);
  1388. if (rc) {
  1389. dev_err(&ctlr->dev, "%pOF has no valid 'reg' property (%d)\n",
  1390. nc, rc);
  1391. return rc;
  1392. }
  1393. spi->chip_select = value;
  1394. /* Device speed */
  1395. rc = of_property_read_u32(nc, "spi-max-frequency", &value);
  1396. if (rc) {
  1397. dev_err(&ctlr->dev,
  1398. "%pOF has no valid 'spi-max-frequency' property (%d)\n", nc, rc);
  1399. return rc;
  1400. }
  1401. spi->max_speed_hz = value;
  1402. return 0;
  1403. }
  1404. static struct spi_device *
  1405. of_register_spi_device(struct spi_controller *ctlr, struct device_node *nc)
  1406. {
  1407. struct spi_device *spi;
  1408. int rc;
  1409. /* Alloc an spi_device */
  1410. spi = spi_alloc_device(ctlr);
  1411. if (!spi) {
  1412. dev_err(&ctlr->dev, "spi_device alloc error for %pOF\n", nc);
  1413. rc = -ENOMEM;
  1414. goto err_out;
  1415. }
  1416. /* Select device driver */
  1417. rc = of_modalias_node(nc, spi->modalias,
  1418. sizeof(spi->modalias));
  1419. if (rc < 0) {
  1420. dev_err(&ctlr->dev, "cannot find modalias for %pOF\n", nc);
  1421. goto err_out;
  1422. }
  1423. rc = of_spi_parse_dt(ctlr, spi, nc);
  1424. if (rc)
  1425. goto err_out;
  1426. /* Store a pointer to the node in the device structure */
  1427. of_node_get(nc);
  1428. spi->dev.of_node = nc;
  1429. /* Register the new device */
  1430. rc = spi_add_device(spi);
  1431. if (rc) {
  1432. dev_err(&ctlr->dev, "spi_device register error %pOF\n", nc);
  1433. goto err_of_node_put;
  1434. }
  1435. return spi;
  1436. err_of_node_put:
  1437. of_node_put(nc);
  1438. err_out:
  1439. spi_dev_put(spi);
  1440. return ERR_PTR(rc);
  1441. }
  1442. /**
  1443. * of_register_spi_devices() - Register child devices onto the SPI bus
  1444. * @ctlr: Pointer to spi_controller device
  1445. *
  1446. * Registers an spi_device for each child node of controller node which
  1447. * represents a valid SPI slave.
  1448. */
  1449. static void of_register_spi_devices(struct spi_controller *ctlr)
  1450. {
  1451. struct spi_device *spi;
  1452. struct device_node *nc;
  1453. if (!ctlr->dev.of_node)
  1454. return;
  1455. for_each_available_child_of_node(ctlr->dev.of_node, nc) {
  1456. if (of_node_test_and_set_flag(nc, OF_POPULATED))
  1457. continue;
  1458. spi = of_register_spi_device(ctlr, nc);
  1459. if (IS_ERR(spi)) {
  1460. dev_warn(&ctlr->dev,
  1461. "Failed to create SPI device for %pOF\n", nc);
  1462. of_node_clear_flag(nc, OF_POPULATED);
  1463. }
  1464. }
  1465. }
  1466. #else
  1467. static void of_register_spi_devices(struct spi_controller *ctlr) { }
  1468. #endif
  1469. #ifdef CONFIG_ACPI
  1470. static void acpi_spi_parse_apple_properties(struct spi_device *spi)
  1471. {
  1472. struct acpi_device *dev = ACPI_COMPANION(&spi->dev);
  1473. const union acpi_object *obj;
  1474. if (!x86_apple_machine)
  1475. return;
  1476. if (!acpi_dev_get_property(dev, "spiSclkPeriod", ACPI_TYPE_BUFFER, &obj)
  1477. && obj->buffer.length >= 4)
  1478. spi->max_speed_hz = NSEC_PER_SEC / *(u32 *)obj->buffer.pointer;
  1479. if (!acpi_dev_get_property(dev, "spiWordSize", ACPI_TYPE_BUFFER, &obj)
  1480. && obj->buffer.length == 8)
  1481. spi->bits_per_word = *(u64 *)obj->buffer.pointer;
  1482. if (!acpi_dev_get_property(dev, "spiBitOrder", ACPI_TYPE_BUFFER, &obj)
  1483. && obj->buffer.length == 8 && !*(u64 *)obj->buffer.pointer)
  1484. spi->mode |= SPI_LSB_FIRST;
  1485. if (!acpi_dev_get_property(dev, "spiSPO", ACPI_TYPE_BUFFER, &obj)
  1486. && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
  1487. spi->mode |= SPI_CPOL;
  1488. if (!acpi_dev_get_property(dev, "spiSPH", ACPI_TYPE_BUFFER, &obj)
  1489. && obj->buffer.length == 8 && *(u64 *)obj->buffer.pointer)
  1490. spi->mode |= SPI_CPHA;
  1491. }
  1492. static int acpi_spi_add_resource(struct acpi_resource *ares, void *data)
  1493. {
  1494. struct spi_device *spi = data;
  1495. struct spi_controller *ctlr = spi->controller;
  1496. if (ares->type == ACPI_RESOURCE_TYPE_SERIAL_BUS) {
  1497. struct acpi_resource_spi_serialbus *sb;
  1498. sb = &ares->data.spi_serial_bus;
  1499. if (sb->type == ACPI_RESOURCE_SERIAL_TYPE_SPI) {
  1500. /*
  1501. * ACPI DeviceSelection numbering is handled by the
  1502. * host controller driver in Windows and can vary
  1503. * from driver to driver. In Linux we always expect
  1504. * 0 .. max - 1 so we need to ask the driver to
  1505. * translate between the two schemes.
  1506. */
  1507. if (ctlr->fw_translate_cs) {
  1508. int cs = ctlr->fw_translate_cs(ctlr,
  1509. sb->device_selection);
  1510. if (cs < 0)
  1511. return cs;
  1512. spi->chip_select = cs;
  1513. } else {
  1514. spi->chip_select = sb->device_selection;
  1515. }
  1516. spi->max_speed_hz = sb->connection_speed;
  1517. if (sb->clock_phase == ACPI_SPI_SECOND_PHASE)
  1518. spi->mode |= SPI_CPHA;
  1519. if (sb->clock_polarity == ACPI_SPI_START_HIGH)
  1520. spi->mode |= SPI_CPOL;
  1521. if (sb->device_polarity == ACPI_SPI_ACTIVE_HIGH)
  1522. spi->mode |= SPI_CS_HIGH;
  1523. }
  1524. } else if (spi->irq < 0) {
  1525. struct resource r;
  1526. if (acpi_dev_resource_interrupt(ares, 0, &r))
  1527. spi->irq = r.start;
  1528. }
  1529. /* Always tell the ACPI core to skip this resource */
  1530. return 1;
  1531. }
  1532. static acpi_status acpi_register_spi_device(struct spi_controller *ctlr,
  1533. struct acpi_device *adev)
  1534. {
  1535. struct list_head resource_list;
  1536. struct spi_device *spi;
  1537. int ret;
  1538. if (acpi_bus_get_status(adev) || !adev->status.present ||
  1539. acpi_device_enumerated(adev))
  1540. return AE_OK;
  1541. spi = spi_alloc_device(ctlr);
  1542. if (!spi) {
  1543. dev_err(&ctlr->dev, "failed to allocate SPI device for %s\n",
  1544. dev_name(&adev->dev));
  1545. return AE_NO_MEMORY;
  1546. }
  1547. ACPI_COMPANION_SET(&spi->dev, adev);
  1548. spi->irq = -1;
  1549. INIT_LIST_HEAD(&resource_list);
  1550. ret = acpi_dev_get_resources(adev, &resource_list,
  1551. acpi_spi_add_resource, spi);
  1552. acpi_dev_free_resource_list(&resource_list);
  1553. acpi_spi_parse_apple_properties(spi);
  1554. if (ret < 0 || !spi->max_speed_hz) {
  1555. spi_dev_put(spi);
  1556. return AE_OK;
  1557. }
  1558. acpi_set_modalias(adev, acpi_device_hid(adev), spi->modalias,
  1559. sizeof(spi->modalias));
  1560. if (spi->irq < 0)
  1561. spi->irq = acpi_dev_gpio_irq_get(adev, 0);
  1562. acpi_device_set_enumerated(adev);
  1563. adev->power.flags.ignore_parent = true;
  1564. if (spi_add_device(spi)) {
  1565. adev->power.flags.ignore_parent = false;
  1566. dev_err(&ctlr->dev, "failed to add SPI device %s from ACPI\n",
  1567. dev_name(&adev->dev));
  1568. spi_dev_put(spi);
  1569. }
  1570. return AE_OK;
  1571. }
  1572. static acpi_status acpi_spi_add_device(acpi_handle handle, u32 level,
  1573. void *data, void **return_value)
  1574. {
  1575. struct spi_controller *ctlr = data;
  1576. struct acpi_device *adev;
  1577. if (acpi_bus_get_device(handle, &adev))
  1578. return AE_OK;
  1579. return acpi_register_spi_device(ctlr, adev);
  1580. }
  1581. static void acpi_register_spi_devices(struct spi_controller *ctlr)
  1582. {
  1583. acpi_status status;
  1584. acpi_handle handle;
  1585. handle = ACPI_HANDLE(ctlr->dev.parent);
  1586. if (!handle)
  1587. return;
  1588. status = acpi_walk_namespace(ACPI_TYPE_DEVICE, handle, 1,
  1589. acpi_spi_add_device, NULL, ctlr, NULL);
  1590. if (ACPI_FAILURE(status))
  1591. dev_warn(&ctlr->dev, "failed to enumerate SPI slaves\n");
  1592. }
  1593. #else
  1594. static inline void acpi_register_spi_devices(struct spi_controller *ctlr) {}
  1595. #endif /* CONFIG_ACPI */
  1596. static void spi_controller_release(struct device *dev)
  1597. {
  1598. struct spi_controller *ctlr;
  1599. ctlr = container_of(dev, struct spi_controller, dev);
  1600. kfree(ctlr);
  1601. }
  1602. static struct class spi_master_class = {
  1603. .name = "spi_master",
  1604. .owner = THIS_MODULE,
  1605. .dev_release = spi_controller_release,
  1606. .dev_groups = spi_master_groups,
  1607. };
  1608. #ifdef CONFIG_SPI_SLAVE
  1609. /**
  1610. * spi_slave_abort - abort the ongoing transfer request on an SPI slave
  1611. * controller
  1612. * @spi: device used for the current transfer
  1613. */
  1614. int spi_slave_abort(struct spi_device *spi)
  1615. {
  1616. struct spi_controller *ctlr = spi->controller;
  1617. if (spi_controller_is_slave(ctlr) && ctlr->slave_abort)
  1618. return ctlr->slave_abort(ctlr);
  1619. return -ENOTSUPP;
  1620. }
  1621. EXPORT_SYMBOL_GPL(spi_slave_abort);
  1622. static int match_true(struct device *dev, void *data)
  1623. {
  1624. return 1;
  1625. }
  1626. static ssize_t spi_slave_show(struct device *dev,
  1627. struct device_attribute *attr, char *buf)
  1628. {
  1629. struct spi_controller *ctlr = container_of(dev, struct spi_controller,
  1630. dev);
  1631. struct device *child;
  1632. child = device_find_child(&ctlr->dev, NULL, match_true);
  1633. return sprintf(buf, "%s\n",
  1634. child ? to_spi_device(child)->modalias : NULL);
  1635. }
  1636. static ssize_t spi_slave_store(struct device *dev,
  1637. struct device_attribute *attr, const char *buf,
  1638. size_t count)
  1639. {
  1640. struct spi_controller *ctlr = container_of(dev, struct spi_controller,
  1641. dev);
  1642. struct spi_device *spi;
  1643. struct device *child;
  1644. char name[32];
  1645. int rc;
  1646. rc = sscanf(buf, "%31s", name);
  1647. if (rc != 1 || !name[0])
  1648. return -EINVAL;
  1649. child = device_find_child(&ctlr->dev, NULL, match_true);
  1650. if (child) {
  1651. /* Remove registered slave */
  1652. device_unregister(child);
  1653. put_device(child);
  1654. }
  1655. if (strcmp(name, "(null)")) {
  1656. /* Register new slave */
  1657. spi = spi_alloc_device(ctlr);
  1658. if (!spi)
  1659. return -ENOMEM;
  1660. strlcpy(spi->modalias, name, sizeof(spi->modalias));
  1661. rc = spi_add_device(spi);
  1662. if (rc) {
  1663. spi_dev_put(spi);
  1664. return rc;
  1665. }
  1666. }
  1667. return count;
  1668. }
  1669. static DEVICE_ATTR(slave, 0644, spi_slave_show, spi_slave_store);
  1670. static struct attribute *spi_slave_attrs[] = {
  1671. &dev_attr_slave.attr,
  1672. NULL,
  1673. };
  1674. static const struct attribute_group spi_slave_group = {
  1675. .attrs = spi_slave_attrs,
  1676. };
  1677. static const struct attribute_group *spi_slave_groups[] = {
  1678. &spi_controller_statistics_group,
  1679. &spi_slave_group,
  1680. NULL,
  1681. };
  1682. static struct class spi_slave_class = {
  1683. .name = "spi_slave",
  1684. .owner = THIS_MODULE,
  1685. .dev_release = spi_controller_release,
  1686. .dev_groups = spi_slave_groups,
  1687. };
  1688. #else
  1689. extern struct class spi_slave_class; /* dummy */
  1690. #endif
  1691. /**
  1692. * __spi_alloc_controller - allocate an SPI master or slave controller
  1693. * @dev: the controller, possibly using the platform_bus
  1694. * @size: how much zeroed driver-private data to allocate; the pointer to this
  1695. * memory is in the driver_data field of the returned device,
  1696. * accessible with spi_controller_get_devdata().
  1697. * @slave: flag indicating whether to allocate an SPI master (false) or SPI
  1698. * slave (true) controller
  1699. * Context: can sleep
  1700. *
  1701. * This call is used only by SPI controller drivers, which are the
  1702. * only ones directly touching chip registers. It's how they allocate
  1703. * an spi_controller structure, prior to calling spi_register_controller().
  1704. *
  1705. * This must be called from context that can sleep.
  1706. *
  1707. * The caller is responsible for assigning the bus number and initializing the
  1708. * controller's methods before calling spi_register_controller(); and (after
  1709. * errors adding the device) calling spi_controller_put() to prevent a memory
  1710. * leak.
  1711. *
  1712. * Return: the SPI controller structure on success, else NULL.
  1713. */
  1714. struct spi_controller *__spi_alloc_controller(struct device *dev,
  1715. unsigned int size, bool slave)
  1716. {
  1717. struct spi_controller *ctlr;
  1718. if (!dev)
  1719. return NULL;
  1720. ctlr = kzalloc(size + sizeof(*ctlr), GFP_KERNEL);
  1721. if (!ctlr)
  1722. return NULL;
  1723. device_initialize(&ctlr->dev);
  1724. ctlr->bus_num = -1;
  1725. ctlr->num_chipselect = 1;
  1726. ctlr->slave = slave;
  1727. if (IS_ENABLED(CONFIG_SPI_SLAVE) && slave)
  1728. ctlr->dev.class = &spi_slave_class;
  1729. else
  1730. ctlr->dev.class = &spi_master_class;
  1731. ctlr->dev.parent = dev;
  1732. pm_suspend_ignore_children(&ctlr->dev, true);
  1733. spi_controller_set_devdata(ctlr, &ctlr[1]);
  1734. return ctlr;
  1735. }
  1736. EXPORT_SYMBOL_GPL(__spi_alloc_controller);
  1737. static void devm_spi_release_controller(struct device *dev, void *ctlr)
  1738. {
  1739. spi_controller_put(*(struct spi_controller **)ctlr);
  1740. }
  1741. /**
  1742. * __devm_spi_alloc_controller - resource-managed __spi_alloc_controller()
  1743. * @dev: physical device of SPI controller
  1744. * @size: how much zeroed driver-private data to allocate
  1745. * @slave: whether to allocate an SPI master (false) or SPI slave (true)
  1746. * Context: can sleep
  1747. *
  1748. * Allocate an SPI controller and automatically release a reference on it
  1749. * when @dev is unbound from its driver. Drivers are thus relieved from
  1750. * having to call spi_controller_put().
  1751. *
  1752. * The arguments to this function are identical to __spi_alloc_controller().
  1753. *
  1754. * Return: the SPI controller structure on success, else NULL.
  1755. */
  1756. struct spi_controller *__devm_spi_alloc_controller(struct device *dev,
  1757. unsigned int size,
  1758. bool slave)
  1759. {
  1760. struct spi_controller **ptr, *ctlr;
  1761. ptr = devres_alloc(devm_spi_release_controller, sizeof(*ptr),
  1762. GFP_KERNEL);
  1763. if (!ptr)
  1764. return NULL;
  1765. ctlr = __spi_alloc_controller(dev, size, slave);
  1766. if (ctlr) {
  1767. ctlr->devm_allocated = true;
  1768. *ptr = ctlr;
  1769. devres_add(dev, ptr);
  1770. } else {
  1771. devres_free(ptr);
  1772. }
  1773. return ctlr;
  1774. }
  1775. EXPORT_SYMBOL_GPL(__devm_spi_alloc_controller);
  1776. #ifdef CONFIG_OF
  1777. static int of_spi_register_master(struct spi_controller *ctlr)
  1778. {
  1779. int nb, i, *cs;
  1780. struct device_node *np = ctlr->dev.of_node;
  1781. if (!np)
  1782. return 0;
  1783. nb = of_gpio_named_count(np, "cs-gpios");
  1784. ctlr->num_chipselect = max_t(int, nb, ctlr->num_chipselect);
  1785. /* Return error only for an incorrectly formed cs-gpios property */
  1786. if (nb == 0 || nb == -ENOENT)
  1787. return 0;
  1788. else if (nb < 0)
  1789. return nb;
  1790. cs = devm_kcalloc(&ctlr->dev, ctlr->num_chipselect, sizeof(int),
  1791. GFP_KERNEL);
  1792. ctlr->cs_gpios = cs;
  1793. if (!ctlr->cs_gpios)
  1794. return -ENOMEM;
  1795. for (i = 0; i < ctlr->num_chipselect; i++)
  1796. cs[i] = -ENOENT;
  1797. for (i = 0; i < nb; i++)
  1798. cs[i] = of_get_named_gpio(np, "cs-gpios", i);
  1799. return 0;
  1800. }
  1801. #else
  1802. static int of_spi_register_master(struct spi_controller *ctlr)
  1803. {
  1804. return 0;
  1805. }
  1806. #endif
  1807. static int spi_controller_check_ops(struct spi_controller *ctlr)
  1808. {
  1809. /*
  1810. * The controller may implement only the high-level SPI-memory like
  1811. * operations if it does not support regular SPI transfers, and this is
  1812. * valid use case.
  1813. * If ->mem_ops is NULL, we request that at least one of the
  1814. * ->transfer_xxx() method be implemented.
  1815. */
  1816. if (ctlr->mem_ops) {
  1817. if (!ctlr->mem_ops->exec_op)
  1818. return -EINVAL;
  1819. } else if (!ctlr->transfer && !ctlr->transfer_one &&
  1820. !ctlr->transfer_one_message) {
  1821. return -EINVAL;
  1822. }
  1823. return 0;
  1824. }
  1825. /**
  1826. * spi_register_controller - register SPI master or slave controller
  1827. * @ctlr: initialized master, originally from spi_alloc_master() or
  1828. * spi_alloc_slave()
  1829. * Context: can sleep
  1830. *
  1831. * SPI controllers connect to their drivers using some non-SPI bus,
  1832. * such as the platform bus. The final stage of probe() in that code
  1833. * includes calling spi_register_controller() to hook up to this SPI bus glue.
  1834. *
  1835. * SPI controllers use board specific (often SOC specific) bus numbers,
  1836. * and board-specific addressing for SPI devices combines those numbers
  1837. * with chip select numbers. Since SPI does not directly support dynamic
  1838. * device identification, boards need configuration tables telling which
  1839. * chip is at which address.
  1840. *
  1841. * This must be called from context that can sleep. It returns zero on
  1842. * success, else a negative error code (dropping the controller's refcount).
  1843. * After a successful return, the caller is responsible for calling
  1844. * spi_unregister_controller().
  1845. *
  1846. * Return: zero on success, else a negative error code.
  1847. */
  1848. int spi_register_controller(struct spi_controller *ctlr)
  1849. {
  1850. struct device *dev = ctlr->dev.parent;
  1851. struct boardinfo *bi;
  1852. int status = -ENODEV;
  1853. int id, first_dynamic;
  1854. if (!dev)
  1855. return -ENODEV;
  1856. /*
  1857. * Make sure all necessary hooks are implemented before registering
  1858. * the SPI controller.
  1859. */
  1860. status = spi_controller_check_ops(ctlr);
  1861. if (status)
  1862. return status;
  1863. if (!spi_controller_is_slave(ctlr)) {
  1864. status = of_spi_register_master(ctlr);
  1865. if (status)
  1866. return status;
  1867. }
  1868. /* even if it's just one always-selected device, there must
  1869. * be at least one chipselect
  1870. */
  1871. if (ctlr->num_chipselect == 0)
  1872. return -EINVAL;
  1873. if (ctlr->bus_num >= 0) {
  1874. /* devices with a fixed bus num must check-in with the num */
  1875. mutex_lock(&board_lock);
  1876. id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
  1877. ctlr->bus_num + 1, GFP_KERNEL);
  1878. mutex_unlock(&board_lock);
  1879. if (WARN(id < 0, "couldn't get idr"))
  1880. return id == -ENOSPC ? -EBUSY : id;
  1881. ctlr->bus_num = id;
  1882. } else if (ctlr->dev.of_node) {
  1883. /* allocate dynamic bus number using Linux idr */
  1884. id = of_alias_get_id(ctlr->dev.of_node, "spi");
  1885. if (id >= 0) {
  1886. ctlr->bus_num = id;
  1887. mutex_lock(&board_lock);
  1888. id = idr_alloc(&spi_master_idr, ctlr, ctlr->bus_num,
  1889. ctlr->bus_num + 1, GFP_KERNEL);
  1890. mutex_unlock(&board_lock);
  1891. if (WARN(id < 0, "couldn't get idr"))
  1892. return id == -ENOSPC ? -EBUSY : id;
  1893. }
  1894. }
  1895. if (ctlr->bus_num < 0) {
  1896. first_dynamic = of_alias_get_highest_id("spi");
  1897. if (first_dynamic < 0)
  1898. first_dynamic = 0;
  1899. else
  1900. first_dynamic++;
  1901. mutex_lock(&board_lock);
  1902. id = idr_alloc(&spi_master_idr, ctlr, first_dynamic,
  1903. 0, GFP_KERNEL);
  1904. mutex_unlock(&board_lock);
  1905. if (WARN(id < 0, "couldn't get idr"))
  1906. return id;
  1907. ctlr->bus_num = id;
  1908. }
  1909. INIT_LIST_HEAD(&ctlr->queue);
  1910. spin_lock_init(&ctlr->queue_lock);
  1911. spin_lock_init(&ctlr->bus_lock_spinlock);
  1912. mutex_init(&ctlr->bus_lock_mutex);
  1913. mutex_init(&ctlr->io_mutex);
  1914. ctlr->bus_lock_flag = 0;
  1915. init_completion(&ctlr->xfer_completion);
  1916. if (!ctlr->max_dma_len)
  1917. ctlr->max_dma_len = INT_MAX;
  1918. /* register the device, then userspace will see it.
  1919. * registration fails if the bus ID is in use.
  1920. */
  1921. dev_set_name(&ctlr->dev, "spi%u", ctlr->bus_num);
  1922. status = device_add(&ctlr->dev);
  1923. if (status < 0) {
  1924. /* free bus id */
  1925. mutex_lock(&board_lock);
  1926. idr_remove(&spi_master_idr, ctlr->bus_num);
  1927. mutex_unlock(&board_lock);
  1928. goto done;
  1929. }
  1930. dev_dbg(dev, "registered %s %s\n",
  1931. spi_controller_is_slave(ctlr) ? "slave" : "master",
  1932. dev_name(&ctlr->dev));
  1933. /*
  1934. * If we're using a queued driver, start the queue. Note that we don't
  1935. * need the queueing logic if the driver is only supporting high-level
  1936. * memory operations.
  1937. */
  1938. if (ctlr->transfer) {
  1939. dev_info(dev, "controller is unqueued, this is deprecated\n");
  1940. } else if (ctlr->transfer_one || ctlr->transfer_one_message) {
  1941. status = spi_controller_initialize_queue(ctlr);
  1942. if (status) {
  1943. device_del(&ctlr->dev);
  1944. /* free bus id */
  1945. mutex_lock(&board_lock);
  1946. idr_remove(&spi_master_idr, ctlr->bus_num);
  1947. mutex_unlock(&board_lock);
  1948. goto done;
  1949. }
  1950. }
  1951. /* add statistics */
  1952. spin_lock_init(&ctlr->statistics.lock);
  1953. mutex_lock(&board_lock);
  1954. list_add_tail(&ctlr->list, &spi_controller_list);
  1955. list_for_each_entry(bi, &board_list, list)
  1956. spi_match_controller_to_boardinfo(ctlr, &bi->board_info);
  1957. mutex_unlock(&board_lock);
  1958. /* Register devices from the device tree and ACPI */
  1959. of_register_spi_devices(ctlr);
  1960. acpi_register_spi_devices(ctlr);
  1961. done:
  1962. return status;
  1963. }
  1964. EXPORT_SYMBOL_GPL(spi_register_controller);
  1965. static void devm_spi_unregister(struct device *dev, void *res)
  1966. {
  1967. spi_unregister_controller(*(struct spi_controller **)res);
  1968. }
  1969. /**
  1970. * devm_spi_register_controller - register managed SPI master or slave
  1971. * controller
  1972. * @dev: device managing SPI controller
  1973. * @ctlr: initialized controller, originally from spi_alloc_master() or
  1974. * spi_alloc_slave()
  1975. * Context: can sleep
  1976. *
  1977. * Register a SPI device as with spi_register_controller() which will
  1978. * automatically be unregistered and freed.
  1979. *
  1980. * Return: zero on success, else a negative error code.
  1981. */
  1982. int devm_spi_register_controller(struct device *dev,
  1983. struct spi_controller *ctlr)
  1984. {
  1985. struct spi_controller **ptr;
  1986. int ret;
  1987. ptr = devres_alloc(devm_spi_unregister, sizeof(*ptr), GFP_KERNEL);
  1988. if (!ptr)
  1989. return -ENOMEM;
  1990. ret = spi_register_controller(ctlr);
  1991. if (!ret) {
  1992. *ptr = ctlr;
  1993. devres_add(dev, ptr);
  1994. } else {
  1995. devres_free(ptr);
  1996. }
  1997. return ret;
  1998. }
  1999. EXPORT_SYMBOL_GPL(devm_spi_register_controller);
  2000. static int __unregister(struct device *dev, void *null)
  2001. {
  2002. spi_unregister_device(to_spi_device(dev));
  2003. return 0;
  2004. }
  2005. /**
  2006. * spi_unregister_controller - unregister SPI master or slave controller
  2007. * @ctlr: the controller being unregistered
  2008. * Context: can sleep
  2009. *
  2010. * This call is used only by SPI controller drivers, which are the
  2011. * only ones directly touching chip registers.
  2012. *
  2013. * This must be called from context that can sleep.
  2014. *
  2015. * Note that this function also drops a reference to the controller.
  2016. */
  2017. void spi_unregister_controller(struct spi_controller *ctlr)
  2018. {
  2019. struct spi_controller *found;
  2020. int id = ctlr->bus_num;
  2021. /* Prevent addition of new devices, unregister existing ones */
  2022. if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
  2023. mutex_lock(&spi_add_lock);
  2024. device_for_each_child(&ctlr->dev, NULL, __unregister);
  2025. /* First make sure that this controller was ever added */
  2026. mutex_lock(&board_lock);
  2027. found = idr_find(&spi_master_idr, id);
  2028. mutex_unlock(&board_lock);
  2029. if (ctlr->queued) {
  2030. if (spi_destroy_queue(ctlr))
  2031. dev_err(&ctlr->dev, "queue remove failed\n");
  2032. }
  2033. mutex_lock(&board_lock);
  2034. list_del(&ctlr->list);
  2035. mutex_unlock(&board_lock);
  2036. device_del(&ctlr->dev);
  2037. /* Release the last reference on the controller if its driver
  2038. * has not yet been converted to devm_spi_alloc_master/slave().
  2039. */
  2040. if (!ctlr->devm_allocated)
  2041. put_device(&ctlr->dev);
  2042. /* free bus id */
  2043. mutex_lock(&board_lock);
  2044. if (found == ctlr)
  2045. idr_remove(&spi_master_idr, id);
  2046. mutex_unlock(&board_lock);
  2047. if (IS_ENABLED(CONFIG_SPI_DYNAMIC))
  2048. mutex_unlock(&spi_add_lock);
  2049. }
  2050. EXPORT_SYMBOL_GPL(spi_unregister_controller);
  2051. int spi_controller_suspend(struct spi_controller *ctlr)
  2052. {
  2053. int ret;
  2054. /* Basically no-ops for non-queued controllers */
  2055. if (!ctlr->queued)
  2056. return 0;
  2057. ret = spi_stop_queue(ctlr);
  2058. if (ret)
  2059. dev_err(&ctlr->dev, "queue stop failed\n");
  2060. return ret;
  2061. }
  2062. EXPORT_SYMBOL_GPL(spi_controller_suspend);
  2063. int spi_controller_resume(struct spi_controller *ctlr)
  2064. {
  2065. int ret;
  2066. if (!ctlr->queued)
  2067. return 0;
  2068. ret = spi_start_queue(ctlr);
  2069. if (ret)
  2070. dev_err(&ctlr->dev, "queue restart failed\n");
  2071. return ret;
  2072. }
  2073. EXPORT_SYMBOL_GPL(spi_controller_resume);
  2074. static int __spi_controller_match(struct device *dev, const void *data)
  2075. {
  2076. struct spi_controller *ctlr;
  2077. const u16 *bus_num = data;
  2078. ctlr = container_of(dev, struct spi_controller, dev);
  2079. return ctlr->bus_num == *bus_num;
  2080. }
  2081. /**
  2082. * spi_busnum_to_master - look up master associated with bus_num
  2083. * @bus_num: the master's bus number
  2084. * Context: can sleep
  2085. *
  2086. * This call may be used with devices that are registered after
  2087. * arch init time. It returns a refcounted pointer to the relevant
  2088. * spi_controller (which the caller must release), or NULL if there is
  2089. * no such master registered.
  2090. *
  2091. * Return: the SPI master structure on success, else NULL.
  2092. */
  2093. struct spi_controller *spi_busnum_to_master(u16 bus_num)
  2094. {
  2095. struct device *dev;
  2096. struct spi_controller *ctlr = NULL;
  2097. dev = class_find_device(&spi_master_class, NULL, &bus_num,
  2098. __spi_controller_match);
  2099. if (dev)
  2100. ctlr = container_of(dev, struct spi_controller, dev);
  2101. /* reference got in class_find_device */
  2102. return ctlr;
  2103. }
  2104. EXPORT_SYMBOL_GPL(spi_busnum_to_master);
  2105. /*-------------------------------------------------------------------------*/
  2106. /* Core methods for SPI resource management */
  2107. /**
  2108. * spi_res_alloc - allocate a spi resource that is life-cycle managed
  2109. * during the processing of a spi_message while using
  2110. * spi_transfer_one
  2111. * @spi: the spi device for which we allocate memory
  2112. * @release: the release code to execute for this resource
  2113. * @size: size to alloc and return
  2114. * @gfp: GFP allocation flags
  2115. *
  2116. * Return: the pointer to the allocated data
  2117. *
  2118. * This may get enhanced in the future to allocate from a memory pool
  2119. * of the @spi_device or @spi_controller to avoid repeated allocations.
  2120. */
  2121. void *spi_res_alloc(struct spi_device *spi,
  2122. spi_res_release_t release,
  2123. size_t size, gfp_t gfp)
  2124. {
  2125. struct spi_res *sres;
  2126. sres = kzalloc(sizeof(*sres) + size, gfp);
  2127. if (!sres)
  2128. return NULL;
  2129. INIT_LIST_HEAD(&sres->entry);
  2130. sres->release = release;
  2131. return sres->data;
  2132. }
  2133. EXPORT_SYMBOL_GPL(spi_res_alloc);
  2134. /**
  2135. * spi_res_free - free an spi resource
  2136. * @res: pointer to the custom data of a resource
  2137. *
  2138. */
  2139. void spi_res_free(void *res)
  2140. {
  2141. struct spi_res *sres = container_of(res, struct spi_res, data);
  2142. if (!res)
  2143. return;
  2144. WARN_ON(!list_empty(&sres->entry));
  2145. kfree(sres);
  2146. }
  2147. EXPORT_SYMBOL_GPL(spi_res_free);
  2148. /**
  2149. * spi_res_add - add a spi_res to the spi_message
  2150. * @message: the spi message
  2151. * @res: the spi_resource
  2152. */
  2153. void spi_res_add(struct spi_message *message, void *res)
  2154. {
  2155. struct spi_res *sres = container_of(res, struct spi_res, data);
  2156. WARN_ON(!list_empty(&sres->entry));
  2157. list_add_tail(&sres->entry, &message->resources);
  2158. }
  2159. EXPORT_SYMBOL_GPL(spi_res_add);
  2160. /**
  2161. * spi_res_release - release all spi resources for this message
  2162. * @ctlr: the @spi_controller
  2163. * @message: the @spi_message
  2164. */
  2165. void spi_res_release(struct spi_controller *ctlr, struct spi_message *message)
  2166. {
  2167. struct spi_res *res;
  2168. while (!list_empty(&message->resources)) {
  2169. res = list_last_entry(&message->resources,
  2170. struct spi_res, entry);
  2171. if (res->release)
  2172. res->release(ctlr, message, res->data);
  2173. list_del(&res->entry);
  2174. kfree(res);
  2175. }
  2176. }
  2177. EXPORT_SYMBOL_GPL(spi_res_release);
  2178. /*-------------------------------------------------------------------------*/
  2179. /* Core methods for spi_message alterations */
  2180. static void __spi_replace_transfers_release(struct spi_controller *ctlr,
  2181. struct spi_message *msg,
  2182. void *res)
  2183. {
  2184. struct spi_replaced_transfers *rxfer = res;
  2185. size_t i;
  2186. /* call extra callback if requested */
  2187. if (rxfer->release)
  2188. rxfer->release(ctlr, msg, res);
  2189. /* insert replaced transfers back into the message */
  2190. list_splice(&rxfer->replaced_transfers, rxfer->replaced_after);
  2191. /* remove the formerly inserted entries */
  2192. for (i = 0; i < rxfer->inserted; i++)
  2193. list_del(&rxfer->inserted_transfers[i].transfer_list);
  2194. }
  2195. /**
  2196. * spi_replace_transfers - replace transfers with several transfers
  2197. * and register change with spi_message.resources
  2198. * @msg: the spi_message we work upon
  2199. * @xfer_first: the first spi_transfer we want to replace
  2200. * @remove: number of transfers to remove
  2201. * @insert: the number of transfers we want to insert instead
  2202. * @release: extra release code necessary in some circumstances
  2203. * @extradatasize: extra data to allocate (with alignment guarantees
  2204. * of struct @spi_transfer)
  2205. * @gfp: gfp flags
  2206. *
  2207. * Returns: pointer to @spi_replaced_transfers,
  2208. * PTR_ERR(...) in case of errors.
  2209. */
  2210. struct spi_replaced_transfers *spi_replace_transfers(
  2211. struct spi_message *msg,
  2212. struct spi_transfer *xfer_first,
  2213. size_t remove,
  2214. size_t insert,
  2215. spi_replaced_release_t release,
  2216. size_t extradatasize,
  2217. gfp_t gfp)
  2218. {
  2219. struct spi_replaced_transfers *rxfer;
  2220. struct spi_transfer *xfer;
  2221. size_t i;
  2222. /* allocate the structure using spi_res */
  2223. rxfer = spi_res_alloc(msg->spi, __spi_replace_transfers_release,
  2224. insert * sizeof(struct spi_transfer)
  2225. + sizeof(struct spi_replaced_transfers)
  2226. + extradatasize,
  2227. gfp);
  2228. if (!rxfer)
  2229. return ERR_PTR(-ENOMEM);
  2230. /* the release code to invoke before running the generic release */
  2231. rxfer->release = release;
  2232. /* assign extradata */
  2233. if (extradatasize)
  2234. rxfer->extradata =
  2235. &rxfer->inserted_transfers[insert];
  2236. /* init the replaced_transfers list */
  2237. INIT_LIST_HEAD(&rxfer->replaced_transfers);
  2238. /* assign the list_entry after which we should reinsert
  2239. * the @replaced_transfers - it may be spi_message.messages!
  2240. */
  2241. rxfer->replaced_after = xfer_first->transfer_list.prev;
  2242. /* remove the requested number of transfers */
  2243. for (i = 0; i < remove; i++) {
  2244. /* if the entry after replaced_after it is msg->transfers
  2245. * then we have been requested to remove more transfers
  2246. * than are in the list
  2247. */
  2248. if (rxfer->replaced_after->next == &msg->transfers) {
  2249. dev_err(&msg->spi->dev,
  2250. "requested to remove more spi_transfers than are available\n");
  2251. /* insert replaced transfers back into the message */
  2252. list_splice(&rxfer->replaced_transfers,
  2253. rxfer->replaced_after);
  2254. /* free the spi_replace_transfer structure */
  2255. spi_res_free(rxfer);
  2256. /* and return with an error */
  2257. return ERR_PTR(-EINVAL);
  2258. }
  2259. /* remove the entry after replaced_after from list of
  2260. * transfers and add it to list of replaced_transfers
  2261. */
  2262. list_move_tail(rxfer->replaced_after->next,
  2263. &rxfer->replaced_transfers);
  2264. }
  2265. /* create copy of the given xfer with identical settings
  2266. * based on the first transfer to get removed
  2267. */
  2268. for (i = 0; i < insert; i++) {
  2269. /* we need to run in reverse order */
  2270. xfer = &rxfer->inserted_transfers[insert - 1 - i];
  2271. /* copy all spi_transfer data */
  2272. memcpy(xfer, xfer_first, sizeof(*xfer));
  2273. /* add to list */
  2274. list_add(&xfer->transfer_list, rxfer->replaced_after);
  2275. /* clear cs_change and delay_usecs for all but the last */
  2276. if (i) {
  2277. xfer->cs_change = false;
  2278. xfer->delay_usecs = 0;
  2279. }
  2280. }
  2281. /* set up inserted */
  2282. rxfer->inserted = insert;
  2283. /* and register it with spi_res/spi_message */
  2284. spi_res_add(msg, rxfer);
  2285. return rxfer;
  2286. }
  2287. EXPORT_SYMBOL_GPL(spi_replace_transfers);
  2288. static int __spi_split_transfer_maxsize(struct spi_controller *ctlr,
  2289. struct spi_message *msg,
  2290. struct spi_transfer **xferp,
  2291. size_t maxsize,
  2292. gfp_t gfp)
  2293. {
  2294. struct spi_transfer *xfer = *xferp, *xfers;
  2295. struct spi_replaced_transfers *srt;
  2296. size_t offset;
  2297. size_t count, i;
  2298. /* warn once about this fact that we are splitting a transfer */
  2299. dev_warn_once(&msg->spi->dev,
  2300. "spi_transfer of length %i exceed max length of %zu - needed to split transfers\n",
  2301. xfer->len, maxsize);
  2302. /* calculate how many we have to replace */
  2303. count = DIV_ROUND_UP(xfer->len, maxsize);
  2304. /* create replacement */
  2305. srt = spi_replace_transfers(msg, xfer, 1, count, NULL, 0, gfp);
  2306. if (IS_ERR(srt))
  2307. return PTR_ERR(srt);
  2308. xfers = srt->inserted_transfers;
  2309. /* now handle each of those newly inserted spi_transfers
  2310. * note that the replacements spi_transfers all are preset
  2311. * to the same values as *xferp, so tx_buf, rx_buf and len
  2312. * are all identical (as well as most others)
  2313. * so we just have to fix up len and the pointers.
  2314. *
  2315. * this also includes support for the depreciated
  2316. * spi_message.is_dma_mapped interface
  2317. */
  2318. /* the first transfer just needs the length modified, so we
  2319. * run it outside the loop
  2320. */
  2321. xfers[0].len = min_t(size_t, maxsize, xfer[0].len);
  2322. /* all the others need rx_buf/tx_buf also set */
  2323. for (i = 1, offset = maxsize; i < count; offset += maxsize, i++) {
  2324. /* update rx_buf, tx_buf and dma */
  2325. if (xfers[i].rx_buf)
  2326. xfers[i].rx_buf += offset;
  2327. if (xfers[i].rx_dma)
  2328. xfers[i].rx_dma += offset;
  2329. if (xfers[i].tx_buf)
  2330. xfers[i].tx_buf += offset;
  2331. if (xfers[i].tx_dma)
  2332. xfers[i].tx_dma += offset;
  2333. /* update length */
  2334. xfers[i].len = min(maxsize, xfers[i].len - offset);
  2335. }
  2336. /* we set up xferp to the last entry we have inserted,
  2337. * so that we skip those already split transfers
  2338. */
  2339. *xferp = &xfers[count - 1];
  2340. /* increment statistics counters */
  2341. SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
  2342. transfers_split_maxsize);
  2343. SPI_STATISTICS_INCREMENT_FIELD(&msg->spi->statistics,
  2344. transfers_split_maxsize);
  2345. return 0;
  2346. }
  2347. /**
  2348. * spi_split_tranfers_maxsize - split spi transfers into multiple transfers
  2349. * when an individual transfer exceeds a
  2350. * certain size
  2351. * @ctlr: the @spi_controller for this transfer
  2352. * @msg: the @spi_message to transform
  2353. * @maxsize: the maximum when to apply this
  2354. * @gfp: GFP allocation flags
  2355. *
  2356. * Return: status of transformation
  2357. */
  2358. int spi_split_transfers_maxsize(struct spi_controller *ctlr,
  2359. struct spi_message *msg,
  2360. size_t maxsize,
  2361. gfp_t gfp)
  2362. {
  2363. struct spi_transfer *xfer;
  2364. int ret;
  2365. /* iterate over the transfer_list,
  2366. * but note that xfer is advanced to the last transfer inserted
  2367. * to avoid checking sizes again unnecessarily (also xfer does
  2368. * potentiall belong to a different list by the time the
  2369. * replacement has happened
  2370. */
  2371. list_for_each_entry(xfer, &msg->transfers, transfer_list) {
  2372. if (xfer->len > maxsize) {
  2373. ret = __spi_split_transfer_maxsize(ctlr, msg, &xfer,
  2374. maxsize, gfp);
  2375. if (ret)
  2376. return ret;
  2377. }
  2378. }
  2379. return 0;
  2380. }
  2381. EXPORT_SYMBOL_GPL(spi_split_transfers_maxsize);
  2382. /*-------------------------------------------------------------------------*/
  2383. /* Core methods for SPI controller protocol drivers. Some of the
  2384. * other core methods are currently defined as inline functions.
  2385. */
  2386. static int __spi_validate_bits_per_word(struct spi_controller *ctlr,
  2387. u8 bits_per_word)
  2388. {
  2389. if (ctlr->bits_per_word_mask) {
  2390. /* Only 32 bits fit in the mask */
  2391. if (bits_per_word > 32)
  2392. return -EINVAL;
  2393. if (!(ctlr->bits_per_word_mask & SPI_BPW_MASK(bits_per_word)))
  2394. return -EINVAL;
  2395. }
  2396. return 0;
  2397. }
  2398. /**
  2399. * spi_setup - setup SPI mode and clock rate
  2400. * @spi: the device whose settings are being modified
  2401. * Context: can sleep, and no requests are queued to the device
  2402. *
  2403. * SPI protocol drivers may need to update the transfer mode if the
  2404. * device doesn't work with its default. They may likewise need
  2405. * to update clock rates or word sizes from initial values. This function
  2406. * changes those settings, and must be called from a context that can sleep.
  2407. * Except for SPI_CS_HIGH, which takes effect immediately, the changes take
  2408. * effect the next time the device is selected and data is transferred to
  2409. * or from it. When this function returns, the spi device is deselected.
  2410. *
  2411. * Note that this call will fail if the protocol driver specifies an option
  2412. * that the underlying controller or its driver does not support. For
  2413. * example, not all hardware supports wire transfers using nine bit words,
  2414. * LSB-first wire encoding, or active-high chipselects.
  2415. *
  2416. * Return: zero on success, else a negative error code.
  2417. */
  2418. int spi_setup(struct spi_device *spi)
  2419. {
  2420. unsigned bad_bits, ugly_bits;
  2421. int status;
  2422. /* check mode to prevent that DUAL and QUAD set at the same time
  2423. */
  2424. if (((spi->mode & SPI_TX_DUAL) && (spi->mode & SPI_TX_QUAD)) ||
  2425. ((spi->mode & SPI_RX_DUAL) && (spi->mode & SPI_RX_QUAD))) {
  2426. dev_err(&spi->dev,
  2427. "setup: can not select dual and quad at the same time\n");
  2428. return -EINVAL;
  2429. }
  2430. /* if it is SPI_3WIRE mode, DUAL and QUAD should be forbidden
  2431. */
  2432. if ((spi->mode & SPI_3WIRE) && (spi->mode &
  2433. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD)))
  2434. return -EINVAL;
  2435. /* help drivers fail *cleanly* when they need options
  2436. * that aren't supported with their current controller
  2437. */
  2438. bad_bits = spi->mode & ~spi->controller->mode_bits;
  2439. ugly_bits = bad_bits &
  2440. (SPI_TX_DUAL | SPI_TX_QUAD | SPI_RX_DUAL | SPI_RX_QUAD);
  2441. if (ugly_bits) {
  2442. dev_warn(&spi->dev,
  2443. "setup: ignoring unsupported mode bits %x\n",
  2444. ugly_bits);
  2445. spi->mode &= ~ugly_bits;
  2446. bad_bits &= ~ugly_bits;
  2447. }
  2448. if (bad_bits) {
  2449. dev_err(&spi->dev, "setup: unsupported mode bits %x\n",
  2450. bad_bits);
  2451. return -EINVAL;
  2452. }
  2453. if (!spi->bits_per_word)
  2454. spi->bits_per_word = 8;
  2455. status = __spi_validate_bits_per_word(spi->controller,
  2456. spi->bits_per_word);
  2457. if (status)
  2458. return status;
  2459. if (!spi->max_speed_hz)
  2460. spi->max_speed_hz = spi->controller->max_speed_hz;
  2461. if (spi->controller->setup)
  2462. status = spi->controller->setup(spi);
  2463. spi_set_cs(spi, false);
  2464. dev_dbg(&spi->dev, "setup mode %d, %s%s%s%s%u bits/w, %u Hz max --> %d\n",
  2465. (int) (spi->mode & (SPI_CPOL | SPI_CPHA)),
  2466. (spi->mode & SPI_CS_HIGH) ? "cs_high, " : "",
  2467. (spi->mode & SPI_LSB_FIRST) ? "lsb, " : "",
  2468. (spi->mode & SPI_3WIRE) ? "3wire, " : "",
  2469. (spi->mode & SPI_LOOP) ? "loopback, " : "",
  2470. spi->bits_per_word, spi->max_speed_hz,
  2471. status);
  2472. return status;
  2473. }
  2474. EXPORT_SYMBOL_GPL(spi_setup);
  2475. static int __spi_validate(struct spi_device *spi, struct spi_message *message)
  2476. {
  2477. struct spi_controller *ctlr = spi->controller;
  2478. struct spi_transfer *xfer;
  2479. int w_size;
  2480. if (list_empty(&message->transfers))
  2481. return -EINVAL;
  2482. /* Half-duplex links include original MicroWire, and ones with
  2483. * only one data pin like SPI_3WIRE (switches direction) or where
  2484. * either MOSI or MISO is missing. They can also be caused by
  2485. * software limitations.
  2486. */
  2487. if ((ctlr->flags & SPI_CONTROLLER_HALF_DUPLEX) ||
  2488. (spi->mode & SPI_3WIRE)) {
  2489. unsigned flags = ctlr->flags;
  2490. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  2491. if (xfer->rx_buf && xfer->tx_buf)
  2492. return -EINVAL;
  2493. if ((flags & SPI_CONTROLLER_NO_TX) && xfer->tx_buf)
  2494. return -EINVAL;
  2495. if ((flags & SPI_CONTROLLER_NO_RX) && xfer->rx_buf)
  2496. return -EINVAL;
  2497. }
  2498. }
  2499. /**
  2500. * Set transfer bits_per_word and max speed as spi device default if
  2501. * it is not set for this transfer.
  2502. * Set transfer tx_nbits and rx_nbits as single transfer default
  2503. * (SPI_NBITS_SINGLE) if it is not set for this transfer.
  2504. */
  2505. message->frame_length = 0;
  2506. list_for_each_entry(xfer, &message->transfers, transfer_list) {
  2507. message->frame_length += xfer->len;
  2508. if (!xfer->bits_per_word)
  2509. xfer->bits_per_word = spi->bits_per_word;
  2510. if (!xfer->speed_hz)
  2511. xfer->speed_hz = spi->max_speed_hz;
  2512. if (!xfer->speed_hz)
  2513. xfer->speed_hz = ctlr->max_speed_hz;
  2514. if (ctlr->max_speed_hz && xfer->speed_hz > ctlr->max_speed_hz)
  2515. xfer->speed_hz = ctlr->max_speed_hz;
  2516. if (__spi_validate_bits_per_word(ctlr, xfer->bits_per_word))
  2517. return -EINVAL;
  2518. /*
  2519. * SPI transfer length should be multiple of SPI word size
  2520. * where SPI word size should be power-of-two multiple
  2521. */
  2522. if (xfer->bits_per_word <= 8)
  2523. w_size = 1;
  2524. else if (xfer->bits_per_word <= 16)
  2525. w_size = 2;
  2526. else
  2527. w_size = 4;
  2528. /* No partial transfers accepted */
  2529. if (xfer->len % w_size)
  2530. return -EINVAL;
  2531. if (xfer->speed_hz && ctlr->min_speed_hz &&
  2532. xfer->speed_hz < ctlr->min_speed_hz)
  2533. return -EINVAL;
  2534. if (xfer->tx_buf && !xfer->tx_nbits)
  2535. xfer->tx_nbits = SPI_NBITS_SINGLE;
  2536. if (xfer->rx_buf && !xfer->rx_nbits)
  2537. xfer->rx_nbits = SPI_NBITS_SINGLE;
  2538. /* check transfer tx/rx_nbits:
  2539. * 1. check the value matches one of single, dual and quad
  2540. * 2. check tx/rx_nbits match the mode in spi_device
  2541. */
  2542. if (xfer->tx_buf) {
  2543. if (xfer->tx_nbits != SPI_NBITS_SINGLE &&
  2544. xfer->tx_nbits != SPI_NBITS_DUAL &&
  2545. xfer->tx_nbits != SPI_NBITS_QUAD)
  2546. return -EINVAL;
  2547. if ((xfer->tx_nbits == SPI_NBITS_DUAL) &&
  2548. !(spi->mode & (SPI_TX_DUAL | SPI_TX_QUAD)))
  2549. return -EINVAL;
  2550. if ((xfer->tx_nbits == SPI_NBITS_QUAD) &&
  2551. !(spi->mode & SPI_TX_QUAD))
  2552. return -EINVAL;
  2553. }
  2554. /* check transfer rx_nbits */
  2555. if (xfer->rx_buf) {
  2556. if (xfer->rx_nbits != SPI_NBITS_SINGLE &&
  2557. xfer->rx_nbits != SPI_NBITS_DUAL &&
  2558. xfer->rx_nbits != SPI_NBITS_QUAD)
  2559. return -EINVAL;
  2560. if ((xfer->rx_nbits == SPI_NBITS_DUAL) &&
  2561. !(spi->mode & (SPI_RX_DUAL | SPI_RX_QUAD)))
  2562. return -EINVAL;
  2563. if ((xfer->rx_nbits == SPI_NBITS_QUAD) &&
  2564. !(spi->mode & SPI_RX_QUAD))
  2565. return -EINVAL;
  2566. }
  2567. }
  2568. message->status = -EINPROGRESS;
  2569. return 0;
  2570. }
  2571. static int __spi_async(struct spi_device *spi, struct spi_message *message)
  2572. {
  2573. struct spi_controller *ctlr = spi->controller;
  2574. /*
  2575. * Some controllers do not support doing regular SPI transfers. Return
  2576. * ENOTSUPP when this is the case.
  2577. */
  2578. if (!ctlr->transfer)
  2579. return -ENOTSUPP;
  2580. message->spi = spi;
  2581. SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_async);
  2582. SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_async);
  2583. trace_spi_message_submit(message);
  2584. return ctlr->transfer(spi, message);
  2585. }
  2586. /**
  2587. * spi_async - asynchronous SPI transfer
  2588. * @spi: device with which data will be exchanged
  2589. * @message: describes the data transfers, including completion callback
  2590. * Context: any (irqs may be blocked, etc)
  2591. *
  2592. * This call may be used in_irq and other contexts which can't sleep,
  2593. * as well as from task contexts which can sleep.
  2594. *
  2595. * The completion callback is invoked in a context which can't sleep.
  2596. * Before that invocation, the value of message->status is undefined.
  2597. * When the callback is issued, message->status holds either zero (to
  2598. * indicate complete success) or a negative error code. After that
  2599. * callback returns, the driver which issued the transfer request may
  2600. * deallocate the associated memory; it's no longer in use by any SPI
  2601. * core or controller driver code.
  2602. *
  2603. * Note that although all messages to a spi_device are handled in
  2604. * FIFO order, messages may go to different devices in other orders.
  2605. * Some device might be higher priority, or have various "hard" access
  2606. * time requirements, for example.
  2607. *
  2608. * On detection of any fault during the transfer, processing of
  2609. * the entire message is aborted, and the device is deselected.
  2610. * Until returning from the associated message completion callback,
  2611. * no other spi_message queued to that device will be processed.
  2612. * (This rule applies equally to all the synchronous transfer calls,
  2613. * which are wrappers around this core asynchronous primitive.)
  2614. *
  2615. * Return: zero on success, else a negative error code.
  2616. */
  2617. int spi_async(struct spi_device *spi, struct spi_message *message)
  2618. {
  2619. struct spi_controller *ctlr = spi->controller;
  2620. int ret;
  2621. unsigned long flags;
  2622. ret = __spi_validate(spi, message);
  2623. if (ret != 0)
  2624. return ret;
  2625. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  2626. if (ctlr->bus_lock_flag)
  2627. ret = -EBUSY;
  2628. else
  2629. ret = __spi_async(spi, message);
  2630. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  2631. return ret;
  2632. }
  2633. EXPORT_SYMBOL_GPL(spi_async);
  2634. /**
  2635. * spi_async_locked - version of spi_async with exclusive bus usage
  2636. * @spi: device with which data will be exchanged
  2637. * @message: describes the data transfers, including completion callback
  2638. * Context: any (irqs may be blocked, etc)
  2639. *
  2640. * This call may be used in_irq and other contexts which can't sleep,
  2641. * as well as from task contexts which can sleep.
  2642. *
  2643. * The completion callback is invoked in a context which can't sleep.
  2644. * Before that invocation, the value of message->status is undefined.
  2645. * When the callback is issued, message->status holds either zero (to
  2646. * indicate complete success) or a negative error code. After that
  2647. * callback returns, the driver which issued the transfer request may
  2648. * deallocate the associated memory; it's no longer in use by any SPI
  2649. * core or controller driver code.
  2650. *
  2651. * Note that although all messages to a spi_device are handled in
  2652. * FIFO order, messages may go to different devices in other orders.
  2653. * Some device might be higher priority, or have various "hard" access
  2654. * time requirements, for example.
  2655. *
  2656. * On detection of any fault during the transfer, processing of
  2657. * the entire message is aborted, and the device is deselected.
  2658. * Until returning from the associated message completion callback,
  2659. * no other spi_message queued to that device will be processed.
  2660. * (This rule applies equally to all the synchronous transfer calls,
  2661. * which are wrappers around this core asynchronous primitive.)
  2662. *
  2663. * Return: zero on success, else a negative error code.
  2664. */
  2665. int spi_async_locked(struct spi_device *spi, struct spi_message *message)
  2666. {
  2667. struct spi_controller *ctlr = spi->controller;
  2668. int ret;
  2669. unsigned long flags;
  2670. ret = __spi_validate(spi, message);
  2671. if (ret != 0)
  2672. return ret;
  2673. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  2674. ret = __spi_async(spi, message);
  2675. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  2676. return ret;
  2677. }
  2678. EXPORT_SYMBOL_GPL(spi_async_locked);
  2679. /*-------------------------------------------------------------------------*/
  2680. /* Utility methods for SPI protocol drivers, layered on
  2681. * top of the core. Some other utility methods are defined as
  2682. * inline functions.
  2683. */
  2684. static void spi_complete(void *arg)
  2685. {
  2686. complete(arg);
  2687. }
  2688. static int __spi_sync(struct spi_device *spi, struct spi_message *message)
  2689. {
  2690. DECLARE_COMPLETION_ONSTACK(done);
  2691. int status;
  2692. struct spi_controller *ctlr = spi->controller;
  2693. unsigned long flags;
  2694. status = __spi_validate(spi, message);
  2695. if (status != 0)
  2696. return status;
  2697. message->complete = spi_complete;
  2698. message->context = &done;
  2699. message->spi = spi;
  2700. SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics, spi_sync);
  2701. SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics, spi_sync);
  2702. /* If we're not using the legacy transfer method then we will
  2703. * try to transfer in the calling context so special case.
  2704. * This code would be less tricky if we could remove the
  2705. * support for driver implemented message queues.
  2706. */
  2707. if (ctlr->transfer == spi_queued_transfer) {
  2708. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  2709. trace_spi_message_submit(message);
  2710. status = __spi_queued_transfer(spi, message, false);
  2711. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  2712. } else {
  2713. status = spi_async_locked(spi, message);
  2714. }
  2715. if (status == 0) {
  2716. /* Push out the messages in the calling context if we
  2717. * can.
  2718. */
  2719. if (ctlr->transfer == spi_queued_transfer) {
  2720. SPI_STATISTICS_INCREMENT_FIELD(&ctlr->statistics,
  2721. spi_sync_immediate);
  2722. SPI_STATISTICS_INCREMENT_FIELD(&spi->statistics,
  2723. spi_sync_immediate);
  2724. __spi_pump_messages(ctlr, false);
  2725. }
  2726. wait_for_completion(&done);
  2727. status = message->status;
  2728. }
  2729. message->context = NULL;
  2730. return status;
  2731. }
  2732. /**
  2733. * spi_sync - blocking/synchronous SPI data transfers
  2734. * @spi: device with which data will be exchanged
  2735. * @message: describes the data transfers
  2736. * Context: can sleep
  2737. *
  2738. * This call may only be used from a context that may sleep. The sleep
  2739. * is non-interruptible, and has no timeout. Low-overhead controller
  2740. * drivers may DMA directly into and out of the message buffers.
  2741. *
  2742. * Note that the SPI device's chip select is active during the message,
  2743. * and then is normally disabled between messages. Drivers for some
  2744. * frequently-used devices may want to minimize costs of selecting a chip,
  2745. * by leaving it selected in anticipation that the next message will go
  2746. * to the same chip. (That may increase power usage.)
  2747. *
  2748. * Also, the caller is guaranteeing that the memory associated with the
  2749. * message will not be freed before this call returns.
  2750. *
  2751. * Return: zero on success, else a negative error code.
  2752. */
  2753. int spi_sync(struct spi_device *spi, struct spi_message *message)
  2754. {
  2755. int ret;
  2756. mutex_lock(&spi->controller->bus_lock_mutex);
  2757. ret = __spi_sync(spi, message);
  2758. mutex_unlock(&spi->controller->bus_lock_mutex);
  2759. return ret;
  2760. }
  2761. EXPORT_SYMBOL_GPL(spi_sync);
  2762. /**
  2763. * spi_sync_locked - version of spi_sync with exclusive bus usage
  2764. * @spi: device with which data will be exchanged
  2765. * @message: describes the data transfers
  2766. * Context: can sleep
  2767. *
  2768. * This call may only be used from a context that may sleep. The sleep
  2769. * is non-interruptible, and has no timeout. Low-overhead controller
  2770. * drivers may DMA directly into and out of the message buffers.
  2771. *
  2772. * This call should be used by drivers that require exclusive access to the
  2773. * SPI bus. It has to be preceded by a spi_bus_lock call. The SPI bus must
  2774. * be released by a spi_bus_unlock call when the exclusive access is over.
  2775. *
  2776. * Return: zero on success, else a negative error code.
  2777. */
  2778. int spi_sync_locked(struct spi_device *spi, struct spi_message *message)
  2779. {
  2780. return __spi_sync(spi, message);
  2781. }
  2782. EXPORT_SYMBOL_GPL(spi_sync_locked);
  2783. /**
  2784. * spi_bus_lock - obtain a lock for exclusive SPI bus usage
  2785. * @ctlr: SPI bus master that should be locked for exclusive bus access
  2786. * Context: can sleep
  2787. *
  2788. * This call may only be used from a context that may sleep. The sleep
  2789. * is non-interruptible, and has no timeout.
  2790. *
  2791. * This call should be used by drivers that require exclusive access to the
  2792. * SPI bus. The SPI bus must be released by a spi_bus_unlock call when the
  2793. * exclusive access is over. Data transfer must be done by spi_sync_locked
  2794. * and spi_async_locked calls when the SPI bus lock is held.
  2795. *
  2796. * Return: always zero.
  2797. */
  2798. int spi_bus_lock(struct spi_controller *ctlr)
  2799. {
  2800. unsigned long flags;
  2801. mutex_lock(&ctlr->bus_lock_mutex);
  2802. spin_lock_irqsave(&ctlr->bus_lock_spinlock, flags);
  2803. ctlr->bus_lock_flag = 1;
  2804. spin_unlock_irqrestore(&ctlr->bus_lock_spinlock, flags);
  2805. /* mutex remains locked until spi_bus_unlock is called */
  2806. return 0;
  2807. }
  2808. EXPORT_SYMBOL_GPL(spi_bus_lock);
  2809. /**
  2810. * spi_bus_unlock - release the lock for exclusive SPI bus usage
  2811. * @ctlr: SPI bus master that was locked for exclusive bus access
  2812. * Context: can sleep
  2813. *
  2814. * This call may only be used from a context that may sleep. The sleep
  2815. * is non-interruptible, and has no timeout.
  2816. *
  2817. * This call releases an SPI bus lock previously obtained by an spi_bus_lock
  2818. * call.
  2819. *
  2820. * Return: always zero.
  2821. */
  2822. int spi_bus_unlock(struct spi_controller *ctlr)
  2823. {
  2824. ctlr->bus_lock_flag = 0;
  2825. mutex_unlock(&ctlr->bus_lock_mutex);
  2826. return 0;
  2827. }
  2828. EXPORT_SYMBOL_GPL(spi_bus_unlock);
  2829. /* portable code must never pass more than 32 bytes */
  2830. #define SPI_BUFSIZ max(32, SMP_CACHE_BYTES)
  2831. static u8 *buf;
  2832. /**
  2833. * spi_write_then_read - SPI synchronous write followed by read
  2834. * @spi: device with which data will be exchanged
  2835. * @txbuf: data to be written (need not be dma-safe)
  2836. * @n_tx: size of txbuf, in bytes
  2837. * @rxbuf: buffer into which data will be read (need not be dma-safe)
  2838. * @n_rx: size of rxbuf, in bytes
  2839. * Context: can sleep
  2840. *
  2841. * This performs a half duplex MicroWire style transaction with the
  2842. * device, sending txbuf and then reading rxbuf. The return value
  2843. * is zero for success, else a negative errno status code.
  2844. * This call may only be used from a context that may sleep.
  2845. *
  2846. * Parameters to this routine are always copied using a small buffer;
  2847. * portable code should never use this for more than 32 bytes.
  2848. * Performance-sensitive or bulk transfer code should instead use
  2849. * spi_{async,sync}() calls with dma-safe buffers.
  2850. *
  2851. * Return: zero on success, else a negative error code.
  2852. */
  2853. int spi_write_then_read(struct spi_device *spi,
  2854. const void *txbuf, unsigned n_tx,
  2855. void *rxbuf, unsigned n_rx)
  2856. {
  2857. static DEFINE_MUTEX(lock);
  2858. int status;
  2859. struct spi_message message;
  2860. struct spi_transfer x[2];
  2861. u8 *local_buf;
  2862. /* Use preallocated DMA-safe buffer if we can. We can't avoid
  2863. * copying here, (as a pure convenience thing), but we can
  2864. * keep heap costs out of the hot path unless someone else is
  2865. * using the pre-allocated buffer or the transfer is too large.
  2866. */
  2867. if ((n_tx + n_rx) > SPI_BUFSIZ || !mutex_trylock(&lock)) {
  2868. local_buf = kmalloc(max((unsigned)SPI_BUFSIZ, n_tx + n_rx),
  2869. GFP_KERNEL | GFP_DMA);
  2870. if (!local_buf)
  2871. return -ENOMEM;
  2872. } else {
  2873. local_buf = buf;
  2874. }
  2875. spi_message_init(&message);
  2876. memset(x, 0, sizeof(x));
  2877. if (n_tx) {
  2878. x[0].len = n_tx;
  2879. spi_message_add_tail(&x[0], &message);
  2880. }
  2881. if (n_rx) {
  2882. x[1].len = n_rx;
  2883. spi_message_add_tail(&x[1], &message);
  2884. }
  2885. memcpy(local_buf, txbuf, n_tx);
  2886. x[0].tx_buf = local_buf;
  2887. x[1].rx_buf = local_buf + n_tx;
  2888. /* do the i/o */
  2889. status = spi_sync(spi, &message);
  2890. if (status == 0)
  2891. memcpy(rxbuf, x[1].rx_buf, n_rx);
  2892. if (x[0].tx_buf == buf)
  2893. mutex_unlock(&lock);
  2894. else
  2895. kfree(local_buf);
  2896. return status;
  2897. }
  2898. EXPORT_SYMBOL_GPL(spi_write_then_read);
  2899. /*-------------------------------------------------------------------------*/
  2900. #if IS_ENABLED(CONFIG_OF_DYNAMIC)
  2901. static int __spi_of_device_match(struct device *dev, void *data)
  2902. {
  2903. return dev->of_node == data;
  2904. }
  2905. /* must call put_device() when done with returned spi_device device */
  2906. static struct spi_device *of_find_spi_device_by_node(struct device_node *node)
  2907. {
  2908. struct device *dev = bus_find_device(&spi_bus_type, NULL, node,
  2909. __spi_of_device_match);
  2910. return dev ? to_spi_device(dev) : NULL;
  2911. }
  2912. static int __spi_of_controller_match(struct device *dev, const void *data)
  2913. {
  2914. return dev->of_node == data;
  2915. }
  2916. /* the spi controllers are not using spi_bus, so we find it with another way */
  2917. static struct spi_controller *of_find_spi_controller_by_node(struct device_node *node)
  2918. {
  2919. struct device *dev;
  2920. dev = class_find_device(&spi_master_class, NULL, node,
  2921. __spi_of_controller_match);
  2922. if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
  2923. dev = class_find_device(&spi_slave_class, NULL, node,
  2924. __spi_of_controller_match);
  2925. if (!dev)
  2926. return NULL;
  2927. /* reference got in class_find_device */
  2928. return container_of(dev, struct spi_controller, dev);
  2929. }
  2930. static int of_spi_notify(struct notifier_block *nb, unsigned long action,
  2931. void *arg)
  2932. {
  2933. struct of_reconfig_data *rd = arg;
  2934. struct spi_controller *ctlr;
  2935. struct spi_device *spi;
  2936. switch (of_reconfig_get_state_change(action, arg)) {
  2937. case OF_RECONFIG_CHANGE_ADD:
  2938. ctlr = of_find_spi_controller_by_node(rd->dn->parent);
  2939. if (ctlr == NULL)
  2940. return NOTIFY_OK; /* not for us */
  2941. if (of_node_test_and_set_flag(rd->dn, OF_POPULATED)) {
  2942. put_device(&ctlr->dev);
  2943. return NOTIFY_OK;
  2944. }
  2945. spi = of_register_spi_device(ctlr, rd->dn);
  2946. put_device(&ctlr->dev);
  2947. if (IS_ERR(spi)) {
  2948. pr_err("%s: failed to create for '%pOF'\n",
  2949. __func__, rd->dn);
  2950. of_node_clear_flag(rd->dn, OF_POPULATED);
  2951. return notifier_from_errno(PTR_ERR(spi));
  2952. }
  2953. break;
  2954. case OF_RECONFIG_CHANGE_REMOVE:
  2955. /* already depopulated? */
  2956. if (!of_node_check_flag(rd->dn, OF_POPULATED))
  2957. return NOTIFY_OK;
  2958. /* find our device by node */
  2959. spi = of_find_spi_device_by_node(rd->dn);
  2960. if (spi == NULL)
  2961. return NOTIFY_OK; /* no? not meant for us */
  2962. /* unregister takes one ref away */
  2963. spi_unregister_device(spi);
  2964. /* and put the reference of the find */
  2965. put_device(&spi->dev);
  2966. break;
  2967. }
  2968. return NOTIFY_OK;
  2969. }
  2970. static struct notifier_block spi_of_notifier = {
  2971. .notifier_call = of_spi_notify,
  2972. };
  2973. #else /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  2974. extern struct notifier_block spi_of_notifier;
  2975. #endif /* IS_ENABLED(CONFIG_OF_DYNAMIC) */
  2976. #if IS_ENABLED(CONFIG_ACPI)
  2977. static int spi_acpi_controller_match(struct device *dev, const void *data)
  2978. {
  2979. return ACPI_COMPANION(dev->parent) == data;
  2980. }
  2981. static int spi_acpi_device_match(struct device *dev, void *data)
  2982. {
  2983. return ACPI_COMPANION(dev) == data;
  2984. }
  2985. static struct spi_controller *acpi_spi_find_controller_by_adev(struct acpi_device *adev)
  2986. {
  2987. struct device *dev;
  2988. dev = class_find_device(&spi_master_class, NULL, adev,
  2989. spi_acpi_controller_match);
  2990. if (!dev && IS_ENABLED(CONFIG_SPI_SLAVE))
  2991. dev = class_find_device(&spi_slave_class, NULL, adev,
  2992. spi_acpi_controller_match);
  2993. if (!dev)
  2994. return NULL;
  2995. return container_of(dev, struct spi_controller, dev);
  2996. }
  2997. static struct spi_device *acpi_spi_find_device_by_adev(struct acpi_device *adev)
  2998. {
  2999. struct device *dev;
  3000. dev = bus_find_device(&spi_bus_type, NULL, adev, spi_acpi_device_match);
  3001. return dev ? to_spi_device(dev) : NULL;
  3002. }
  3003. static int acpi_spi_notify(struct notifier_block *nb, unsigned long value,
  3004. void *arg)
  3005. {
  3006. struct acpi_device *adev = arg;
  3007. struct spi_controller *ctlr;
  3008. struct spi_device *spi;
  3009. switch (value) {
  3010. case ACPI_RECONFIG_DEVICE_ADD:
  3011. ctlr = acpi_spi_find_controller_by_adev(adev->parent);
  3012. if (!ctlr)
  3013. break;
  3014. acpi_register_spi_device(ctlr, adev);
  3015. put_device(&ctlr->dev);
  3016. break;
  3017. case ACPI_RECONFIG_DEVICE_REMOVE:
  3018. if (!acpi_device_enumerated(adev))
  3019. break;
  3020. spi = acpi_spi_find_device_by_adev(adev);
  3021. if (!spi)
  3022. break;
  3023. spi_unregister_device(spi);
  3024. put_device(&spi->dev);
  3025. break;
  3026. }
  3027. return NOTIFY_OK;
  3028. }
  3029. static struct notifier_block spi_acpi_notifier = {
  3030. .notifier_call = acpi_spi_notify,
  3031. };
  3032. #else
  3033. extern struct notifier_block spi_acpi_notifier;
  3034. #endif
  3035. static int __init spi_init(void)
  3036. {
  3037. int status;
  3038. buf = kmalloc(SPI_BUFSIZ, GFP_KERNEL);
  3039. if (!buf) {
  3040. status = -ENOMEM;
  3041. goto err0;
  3042. }
  3043. status = bus_register(&spi_bus_type);
  3044. if (status < 0)
  3045. goto err1;
  3046. status = class_register(&spi_master_class);
  3047. if (status < 0)
  3048. goto err2;
  3049. if (IS_ENABLED(CONFIG_SPI_SLAVE)) {
  3050. status = class_register(&spi_slave_class);
  3051. if (status < 0)
  3052. goto err3;
  3053. }
  3054. if (IS_ENABLED(CONFIG_OF_DYNAMIC))
  3055. WARN_ON(of_reconfig_notifier_register(&spi_of_notifier));
  3056. if (IS_ENABLED(CONFIG_ACPI))
  3057. WARN_ON(acpi_reconfig_notifier_register(&spi_acpi_notifier));
  3058. return 0;
  3059. err3:
  3060. class_unregister(&spi_master_class);
  3061. err2:
  3062. bus_unregister(&spi_bus_type);
  3063. err1:
  3064. kfree(buf);
  3065. buf = NULL;
  3066. err0:
  3067. return status;
  3068. }
  3069. /* board_info is normally registered in arch_initcall(),
  3070. * but even essential drivers wait till later
  3071. *
  3072. * REVISIT only boardinfo really needs static linking. the rest (device and
  3073. * driver registration) _could_ be dynamically linked (modular) ... costs
  3074. * include needing to have boardinfo data structures be much more public.
  3075. */
  3076. postcore_initcall(spi_init);